本文整理汇总了C++中close_connection函数的典型用法代码示例。如果您正苦于以下问题:C++ close_connection函数的具体用法?C++ close_connection怎么用?C++ close_connection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了close_connection函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: send
void CControldClient::shutdown()
{
send(CControldMsg::CMD_SHUTDOWN);
close_connection();
}
示例2: DEBUG_LOG
/// Logon Proof command handler
bool AuthSocket::_HandleLogonProof()
{
DEBUG_LOG("Entering _HandleLogonProof");
///- Read the packet
sAuthLogonProof_C lp;
if (!recv((char *)&lp, sizeof(sAuthLogonProof_C)))
return false;
///- Check if the client has one of the expected version numbers
bool valid_version = FindBuildInfo(_build) != NULL;
/// <ul><li> If the client has no valid version
if (!valid_version)
{
if (this->patch_ != ACE_INVALID_HANDLE)
return false;
///- Check if we have the apropriate patch on the disk
// file looks like: 65535enGB.mpq
char tmp[64];
snprintf(tmp, 24, "./patches/%d%s.mpq", _build, _localizationName.c_str());
char filename[PATH_MAX];
if (ACE_OS::realpath(tmp, filename) != NULL)
{
patch_ = ACE_OS::open(filename, GENERIC_READ | FILE_FLAG_SEQUENTIAL_SCAN);
}
if (patch_ == ACE_INVALID_HANDLE)
{
// no patch found
ByteBuffer pkt;
pkt << (uint8) CMD_AUTH_LOGON_CHALLENGE;
pkt << (uint8) 0x00;
pkt << (uint8) WOW_FAIL_VERSION_INVALID;
DEBUG_LOG("[AuthChallenge] %u is not a valid client version!", _build);
DEBUG_LOG("[AuthChallenge] Patch %s not found", tmp);
send((char const*)pkt.contents(), pkt.size());
return true;
}
XFER_INIT xferh;
ACE_OFF_T file_size = ACE_OS::filesize(this->patch_);
if (file_size == -1)
{
close_connection();
return false;
}
if (!PatchCache::instance()->GetHash(tmp, (uint8*)&xferh.md5))
{
// calculate patch md5, happens if patch was added while realmd was running
PatchCache::instance()->LoadPatchMD5(tmp);
PatchCache::instance()->GetHash(tmp, (uint8*)&xferh.md5);
}
uint8 data[2] = { CMD_AUTH_LOGON_PROOF, WOW_FAIL_VERSION_UPDATE};
send((const char*)data, sizeof(data));
memcpy(&xferh, "0\x05Patch", 7);
xferh.cmd = CMD_XFER_INITIATE;
xferh.file_size = file_size;
send((const char*)&xferh, sizeof(xferh));
return true;
}
/// </ul>
///- Continue the SRP6 calculation based on data received from the client
BigNumber A;
A.SetBinary(lp.A, 32);
// SRP safeguard: abort if A==0
if (A.isZero())
return false;
Sha1Hash sha;
sha.UpdateBigNumbers(&A, &B, NULL);
sha.Finalize();
BigNumber u;
u.SetBinary(sha.GetDigest(), 20);
BigNumber S = (A * (v.ModExp(u, N))).ModExp(b, N);
uint8 t[32];
uint8 t1[16];
uint8 vK[40];
memcpy(t, S.AsByteArray(32), 32);
for (int i = 0; i < 16; ++i)
{
t1[i] = t[i * 2];
}
sha.Initialize();
sha.UpdateData(t1, 16);
sha.Finalize();
for (int i = 0; i < 20; ++i)
//.........这里部分代码省略.........
示例3: socket_read
/*
* Read data from socket.
*/
ssize_t
socket_read(session *ssn, char *buf, size_t len, long timeout, int timeoutfail)
{
int s;
ssize_t r;
fd_set fds;
struct timeval tv;
struct timeval *tvp;
r = 0;
s = 1;
tvp = NULL;
memset(buf, 0, len + 1);
if (timeout > 0) {
tv.tv_sec = timeout;
tv.tv_usec = 0;
tvp = &tv;
}
FD_ZERO(&fds);
FD_SET(ssn->socket, &fds);
if (ssn->sslconn) {
if (SSL_pending(ssn->sslconn) > 0 ||
((s = select(ssn->socket + 1, &fds, NULL, NULL, tvp)) > 0 &&
FD_ISSET(ssn->socket, &fds))) {
r = socket_secure_read(ssn, buf, len);
if (r <= 0)
goto fail;
}
} else {
if ((s = select(ssn->socket + 1, &fds, NULL, NULL, tvp)) > 0 &&
FD_ISSET(ssn->socket, &fds)) {
r = read(ssn->socket, buf, len);
if (r == -1) {
error("reading data; %s\n", strerror(errno));
goto fail;
} else if (r == 0) {
goto fail;
}
}
}
if (s == -1) {
error("waiting to read from socket; %s\n", strerror(errno));
goto fail;
} else if (s == 0 && timeoutfail) {
error("timeout period expired while waiting to read data\n");
goto fail;
}
return r;
fail:
close_connection(ssn);
return -1;
}
示例4: send
void CZapitClient::unlockPlayBack()
{
send(CZapitMessages::CMD_SB_UNLOCK_PLAYBACK);
close_connection();
}
示例5: handle_connect
static void
handle_connect( int cnum, struct timeval* nowP, int double_check )
{
int url_num;
char buf[600];
int bytes, r;
url_num = connections[cnum].url_num;
if ( double_check )
{
/* Check to make sure the non-blocking connect succeeded. */
int err, errlen;
if ( connect(
connections[cnum].conn_fd,
(struct sockaddr*) &connections[cnum].sa,
connections[cnum].sa_len ) < 0 )
{
switch ( errno )
{
case EISCONN:
/* Ok! */
break;
case EINVAL:
errlen = sizeof(err);
if ( getsockopt( connections[cnum].conn_fd, SOL_SOCKET, SO_ERROR, (void*) &err, &errlen ) < 0 )
(void) fprintf(
stderr, "%s: unknown connect error\n",
urls[url_num].url_str );
else
(void) fprintf(
stderr, "%s: %s\n", urls[url_num].url_str,
strerror( err ) );
close_connection( cnum );
return;
default:
perror( urls[url_num].url_str );
close_connection( cnum );
return;
}
}
}
#ifdef USE_SSL
if ( urls[url_num].protocol == PROTO_HTTPS )
{
int flags;
/* Make SSL connection. */
if ( ssl_ctx == (SSL_CTX*) 0 )
{
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
ssl_ctx = SSL_CTX_new( SSLv23_client_method() );
if ( cipher != (char*) 0 )
{
if ( ! SSL_CTX_set_cipher_list( ssl_ctx, cipher ) )
{
(void) fprintf(
stderr, "%s: cannot set cipher list\n", argv0 );
ERR_print_errors_fp( stderr );
close_connection( cnum );
return;
}
}
}
if ( ! RAND_status() )
{
unsigned char bytes[1024];
int i;
for ( i = 0; i < sizeof(bytes); ++i )
bytes[i] = random() % 0xff;
RAND_seed( bytes, sizeof(bytes) );
}
flags = fcntl( connections[cnum].conn_fd, F_GETFL, 0 );
if ( flags != -1 )
(void) fcntl(
connections[cnum].conn_fd, F_SETFL, flags & ~ (int) O_NDELAY );
connections[cnum].ssl = SSL_new( ssl_ctx );
SSL_set_fd( connections[cnum].ssl, connections[cnum].conn_fd );
r = SSL_connect( connections[cnum].ssl );
if ( r <= 0 )
{
(void) fprintf(
stderr, "%s: SSL connection failed - %d\n", argv0, r );
ERR_print_errors_fp( stderr );
close_connection( cnum );
return;
}
}
#endif
connections[cnum].did_connect = 1;
/* Format the request. */
if ( do_proxy )
{
#ifdef USE_SSL
bytes = snprintf(
buf, sizeof(buf), "GET %s://%.500s:%d%.500s HTTP/1.0\r\n",
urls[url_num].protocol == PROTO_HTTPS ? "https" : "http",
urls[url_num].hostname, (int) urls[url_num].port,
//.........这里部分代码省略.........
示例6: getOverlappingTimers
//-------------------------------------------------------------------------
int CTimerdClient::addTimerEvent( CTimerd::CTimerEventTypes evType, void* data, time_t announcetime, time_t alarmtime,time_t stoptime,
CTimerd::CTimerEventRepeat evrepeat, uint32_t repeatcount,bool forceadd)
{
if(checkDouble(evType, data, announcetime, alarmtime, stoptime, evrepeat, repeatcount))//check if timer is add double
return -1;
if (!forceadd)
{
//printf("[CTimerdClient] checking for overlapping timers\n");
CTimerd::TimerList overlappingTimer;
overlappingTimer = getOverlappingTimers(alarmtime, stoptime);
if (!overlappingTimer.empty())
{
// timerd starts eventID at 0 so we can return -1
return -1;
}
}
bool adzaptimer = false;
if(evType == CTimerd::TIMER_ADZAP){
evType = CTimerd::TIMER_ZAPTO;
adzaptimer = true;
}
CTimerd::TransferEventInfo tei;
CTimerd::TransferRecordingInfo tri;
CTimerdMsg::commandAddTimer msgAddTimer;
VALGRIND_PARANOIA(tei);
VALGRIND_PARANOIA(tri);
VALGRIND_PARANOIA(msgAddTimer);
msgAddTimer.alarmTime = alarmtime;
msgAddTimer.announceTime = announcetime;
msgAddTimer.stopTime = stoptime;
msgAddTimer.eventType = evType;
msgAddTimer.eventRepeat = evrepeat;
msgAddTimer.repeatCount = repeatcount;
int length;
if( evType == CTimerd::TIMER_SHUTDOWN || evType == CTimerd::TIMER_SLEEPTIMER )
{
length = 0;
}
/* else if(evType == CTimerd::TIMER_NEXTPROGRAM || evType == CTimerd::TIMER_ZAPTO || */
else if (evType == CTimerd::TIMER_ZAPTO ||
evType == CTimerd::TIMER_IMMEDIATE_RECORD ||
evType == CTimerd::TIMER_ADZAP)
{
CTimerd::EventInfo *ei=static_cast<CTimerd::EventInfo*>(data);
tei.apids = ei->apids;
tei.channel_id = ei->channel_id;
tei.epg_starttime = ei->epg_starttime;
tei.epgID = ei->epgID;
tei.recordingSafety = ei->recordingSafety;
length = sizeof( CTimerd::TransferEventInfo);
data = &tei;
}
else if(evType == CTimerd::TIMER_RECORD)
{
CTimerd::RecordingInfo *ri=static_cast<CTimerd::RecordingInfo*>(data);
tri.apids = ri->apids;
tri.channel_id = ri->channel_id;
tri.epg_starttime = ri->epg_starttime;
tri.epgID = ri->epgID;
tri.recordingSafety = ri->recordingSafety;
strncpy(tri.recordingDir, ri->recordingDir, RECORD_DIR_MAXLEN-1);
length = sizeof( CTimerd::TransferRecordingInfo);
data = &tri;
}
else if(evType == CTimerd::TIMER_STANDBY)
{
length = sizeof(CTimerdMsg::commandSetStandby);
}
else if(evType == CTimerd::TIMER_REMIND)
{
length = sizeof(CTimerdMsg::commandRemind);
}
else if(evType == CTimerd::TIMER_EXEC_PLUGIN)
{
length = sizeof(CTimerdMsg::commandExecPlugin);
}
else
{
length = 0;
}
send(CTimerdMsg::CMD_ADDTIMER, (char*)&msgAddTimer, sizeof(msgAddTimer));
if((data != NULL) && (length > 0))
send_data((char*)data, length);
CTimerdMsg::responseAddTimer response;
receive_data((char*)&response, sizeof(response));
close_connection();
if(adzaptimer){
adzap_eventID = response.eventID;//set adzap flag
}
return( response.eventID);
}
示例7: VERIFY_CORRECT_THREAD
void peer_connection::destroy()
{
VERIFY_CORRECT_THREAD();
#if 0 // this gets too verbose
#ifndef NDEBUG
struct scope_logger {
fc::optional<fc::ip::endpoint> endpoint;
scope_logger(const fc::optional<fc::ip::endpoint>& endpoint) : endpoint(endpoint) { dlog("entering peer_connection::destroy() for peer ${endpoint}", ("endpoint", endpoint)); }
~scope_logger() { dlog("leaving peer_connection::destroy() for peer ${endpoint}", ("endpoint", endpoint)); }
} send_message_scope_logger(get_remote_endpoint());
#endif
#endif
try
{
dlog("calling close_connection()");
close_connection();
dlog("close_connection completed normally");
}
catch ( const fc::canceled_exception& )
{
assert(false && "the task that deletes peers should not be canceled because it will prevent us from cleaning up correctly");
}
catch ( ... )
{
dlog("close_connection threw");
}
try
{
dlog("canceling _send_queued_messages task");
_send_queued_messages_done.cancel_and_wait(__FUNCTION__);
dlog("cancel_and_wait completed normally");
}
catch( const fc::exception& e )
{
wlog("Unexpected exception from peer_connection's send_queued_messages_task : ${e}", ("e", e));
}
catch( ... )
{
wlog("Unexpected exception from peer_connection's send_queued_messages_task");
}
try
{
dlog("canceling accept_or_connect_task");
accept_or_connect_task_done.cancel_and_wait(__FUNCTION__);
dlog("accept_or_connect_task completed normally");
}
catch( const fc::exception& e )
{
wlog("Unexpected exception from peer_connection's accept_or_connect_task : ${e}", ("e", e));
}
catch( ... )
{
wlog("Unexpected exception from peer_connection's accept_or_connect_task");
}
_message_connection.destroy_connection(); // shut down the read loop
}
示例8: sub_main
//.........这里部分代码省略.........
svn_cache_config_set(&settings);
}
#if APR_HAS_THREADS
SVN_ERR(svn_root_pools__create(&connection_pools));
if (handling_mode == connection_mode_thread)
{
/* create the thread pool with a valid range of threads */
if (max_thread_count < 1)
max_thread_count = 1;
if (min_thread_count > max_thread_count)
min_thread_count = max_thread_count;
status = apr_thread_pool_create(&threads,
min_thread_count,
max_thread_count,
pool);
if (status)
{
return svn_error_wrap_apr(status, _("Can't create thread pool"));
}
/* let idle threads linger for a while in case more requests are
coming in */
apr_thread_pool_idle_wait_set(threads, THREADPOOL_THREAD_IDLE_LIMIT);
/* don't queue requests unless we reached the worker thread limit */
apr_thread_pool_threshold_set(threads, 0);
}
else
{
threads = NULL;
}
#endif
while (1)
{
connection_t *connection = NULL;
SVN_ERR(accept_connection(&connection, sock, ¶ms, handling_mode,
pool));
if (run_mode == run_mode_listen_once)
{
err = serve_socket(connection, connection->pool);
close_connection(connection);
return err;
}
switch (handling_mode)
{
case connection_mode_fork:
#if APR_HAS_FORK
status = apr_proc_fork(&proc, connection->pool);
if (status == APR_INCHILD)
{
/* the child would't listen to the main server's socket */
apr_socket_close(sock);
/* serve_socket() logs any error it returns, so ignore it. */
svn_error_clear(serve_socket(connection, connection->pool));
close_connection(connection);
return SVN_NO_ERROR;
}
else if (status != APR_INPARENT)
{
err = svn_error_wrap_apr(status, "apr_proc_fork");
logger__log_error(params.logger, err, NULL, NULL);
svn_error_clear(err);
}
#endif
break;
case connection_mode_thread:
/* Create a detached thread for each connection. That's not a
particularly sophisticated strategy for a threaded server, it's
little different from forking one process per connection. */
#if APR_HAS_THREADS
attach_connection(connection);
status = apr_thread_pool_push(threads, serve_thread, connection,
0, NULL);
if (status)
{
return svn_error_wrap_apr(status, _("Can't push task"));
}
#endif
break;
case connection_mode_single:
/* Serve one connection at a time. */
/* serve_socket() logs any error it returns, so ignore it. */
svn_error_clear(serve_socket(connection, connection->pool));
}
close_connection(connection);
}
/* NOTREACHED */
}
示例9: perform_transactions
//.........这里部分代码省略.........
/* JW commented out to dup rawhoisd
if (!abort_trans)
*/
offset = ftell (fin);
/* fprintf (dfile, "HDR_START offset (%ld)\n", offset);*/
/* illegal hdr field found or EOF or no object after hdr */
if (parse_header (tr, fin, &offset, &ti)) {
abort_trans = 1;
/* fprintf (dfile, "calling update_trans_outcome_list (internal error)...\n"); */
update_trans_outcome_list (tr, start, &ti, offset, INTERNAL_ERROR_RESULT,
"\" Internal error: malformed header!\"\n");
free_ti_mem (&ti);
continue;
}
else if (update_has_errors (&ti))
abort_trans = 1;
else if (null_submission == 0) {
update_trans_outcome_list (tr, start, &ti, offset, NULL_SUBMISSION, NULL);
continue;
}
update_trans_outcome_list (tr, start, &ti, offset, 0, NULL);
free_ti_mem (&ti);
}
/* JW commented out to dup rawhoisd
* want to bring back for transaction semantic support
if (abort_trans)
reinit_return_list (dfile, start, SKIP_RESULT);
else {
*/
for (p = start->first; p != NULL; p = p->next) {
/* JW want to bring back in later, dup rawhoisd
if (p->svr_res & NOOP_RESULT)
continue;
*/
/* JW take next 3 sections out to reverse rawhoisd behavior */
if (p->svr_res & INTERNAL_ERROR_RESULT ||
p->svr_res & NULL_SUBMISSION) {
trace (ERROR, tr,
"Internal error or NULL submission. Object not added to IRRd.\n");
continue;
}
if (p->svr_res & USER_ERROR) {
trace (NORM, tr,
"Syntax or authorization error. Object not added to IRRd.\n");
continue;
}
if (p->svr_res & NOOP_RESULT) {
trace (NORM, tr, "NOOP object. Object not added to IRRd.\n");
continue;
}
/* what the eff is this segment doing? */
if (EOF == fseek (fin, p->offset, SEEK_SET))
fprintf (stderr, "ERROR: fseek (%ld)\n", p->offset);
else {
fgets (buf, MAXLINE, fin);
/*fprintf (dfile, "irrd_trans () line: %s", buf);*/
fseek (fin, p->offset, SEEK_SET);
}
/* fprintf (dfile, "perform_trans () calling irrd_transaction ()...\n");*/
ret_code = irrd_transaction (tr, (char *) WARN_TAG, &fd, fin, p->op,
p->source, ++num_trans, &open_conn,
IRRd_HOST, IRRd_PORT);
/* check for no IRRd errors and we have a key-cert object */
if (!put_transaction_code (tr, p, ret_code) &&
is_keycert_obj (p) &&
p->op != NULL) {
update_pgp_ring_new (tr, p, pgpdir);
/*
if (strcmp (p->op, DEL_OP)) {
pgp_add (tr, pgpdir, p->keycertfn, &pdat);
pgp_free (&pdat);
}
else
pgp_del (tr, pgpdir, p->obj_key + 7);
*/
}
}
if (open_conn) {
end_irrd_session (tr, fd); /* send '!q' */
fflush (fin); /* JW only needed when irrd commands are sent to terminal */
close_connection (fd);
}
/* Remove any key certificate files from our temp directory area */
for (p = start->first; p != NULL; p = p->next)
if (p->keycertfn != NULL)
remove (p->keycertfn);
/* JW want to bring back in later, dup rawhoisd
}
*/
/* fprintf (dfile, "Exit perform_transactions()\n----\n");*/
}
示例10: thread_main
int thread_main(server_decl_t * srv)
{
ci_connection_t con;
char clientname[CI_MAXHOSTNAMELEN + 1];
int ret, request_status = CI_NO_STATUS;
int keepalive_reqs;
//***********************
thread_signals(0);
//*************************
srv->srv_id = getpid(); //Setting my pid ...
for (;;) {
/*
If we must shutdown IMEDIATELLY it is time to leave the server
else if we are going to shutdown GRACEFULLY we are going to die
only if there are not any accepted connections
*/
if (child_data->to_be_killed == IMMEDIATELY) {
srv->running = 0;
return 1;
}
if ((ret = get_from_queue(con_queue, &con)) == 0) {
if (child_data->to_be_killed) {
srv->running = 0;
return 1;
}
ret = wait_for_queue(con_queue);
continue;
}
if (ret < 0) { //An error has occured
ci_debug_printf(1,
"Fatal Error!!! Error getting a connection from connections queue!!!\n");
break;
}
ci_thread_mutex_lock(&counters_mtx); /*Update counters as soon as possible */
(child_data->freeservers)--;
(child_data->usedservers)++;
ci_thread_mutex_unlock(&counters_mtx);
ci_netio_init(con.fd);
ret = 1;
if (srv->current_req == NULL)
srv->current_req = newrequest(&con);
else
ret = recycle_request(srv->current_req, &con);
if (srv->current_req == NULL || ret == 0) {
ci_sockaddr_t_to_host(&(con.claddr), clientname,
CI_MAXHOSTNAMELEN);
ci_debug_printf(1, "Request from %s denied...\n", clientname);
hard_close_connection((&con));
goto end_of_main_loop_thread; /*The request rejected. Log an error and continue ... */
}
keepalive_reqs = 0;
do {
if (MAX_KEEPALIVE_REQUESTS > 0
&& keepalive_reqs >= MAX_KEEPALIVE_REQUESTS)
srv->current_req->keepalive = 0; /*do not keep alive connection */
if (child_data->to_be_killed) /*We are going to die do not keep-alive */
srv->current_req->keepalive = 0;
if ((request_status = process_request(srv->current_req)) == CI_NO_STATUS) {
ci_debug_printf(5,
"Process request timeout or interrupted....\n");
ci_request_reset(srv->current_req);
break;
}
srv->served_requests++;
srv->served_requests_no_reallocation++;
keepalive_reqs++;
/*Increase served requests. I dont like this. The delay is small but I don't like... */
ci_thread_mutex_lock(&counters_mtx);
(child_data->requests)++;
ci_thread_mutex_unlock(&counters_mtx);
log_access(srv->current_req, request_status);
// break; //No keep-alive ......
if (child_data->to_be_killed == IMMEDIATELY)
break; //Just exiting the keep-alive loop
/*if we are going to term gracefully we will try to keep our promice for
keepalived request....
*/
if (child_data->to_be_killed == GRACEFULLY &&
srv->current_req->keepalive == 0)
break;
ci_debug_printf(8, "Keep-alive:%d\n",
srv->current_req->keepalive);
if (srv->current_req->keepalive && keepalive_request(srv->current_req)) {
ci_debug_printf(8,
"Server %d going to serve new request from client (keep-alive) \n",
srv->srv_id);
}
//.........这里部分代码省略.........
示例11: main
int main(int argc, const char **argv)
{
amqp_connection_state_t conn;
char *exchange = NULL;
char *routing_key = NULL;
char *content_type = NULL;
char *content_encoding = NULL;
char *body = NULL;
amqp_basic_properties_t props;
amqp_bytes_t body_bytes;
int delivery = 1; /* non-persistent by default */
struct poptOption options[] = {
INCLUDE_OPTIONS(connect_options),
{"exchange", 'e', POPT_ARG_STRING, &exchange, 0,
"the exchange to publish to", "exchange"},
{"routing-key", 'r', POPT_ARG_STRING, &routing_key, 0,
"the routing key to publish with", "routing key"},
{"persistent", 'p', POPT_ARG_VAL, &delivery, 2,
"use the persistent delivery mode", NULL},
{"content-type", 'C', POPT_ARG_STRING, &content_type, 0,
"the content-type for the message", "content type"},
{"content-encoding", 'E', POPT_ARG_STRING,
&content_encoding, 0,
"the content-encoding for the message", "content encoding"},
{"body", 'b', POPT_ARG_STRING, &body, 0,
"specify the message body", "body"},
POPT_AUTOHELP
{ NULL, 0, 0, NULL, 0 }
};
process_all_options(argc, argv, options);
if (!exchange && !routing_key) {
fprintf(stderr,
"neither exchange nor routing key specified\n");
return 1;
}
memset(&props, 0, sizeof props);
props._flags = AMQP_BASIC_DELIVERY_MODE_FLAG;
props.delivery_mode = 2; /* persistent delivery mode */
if (content_type) {
props._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG;
props.content_type = amqp_cstring_bytes(content_type);
}
if (content_encoding) {
props._flags |= AMQP_BASIC_CONTENT_ENCODING_FLAG;
props.content_encoding = amqp_cstring_bytes(content_encoding);
}
conn = make_connection();
if (body)
body_bytes = amqp_cstring_bytes(body);
else
body_bytes = read_all(0);
do_publish(conn, exchange, routing_key, &props, body_bytes);
if (!body)
free(body_bytes.bytes);
close_connection(conn);
return 0;
}
示例12: main
//.........这里部分代码省略.........
printf("Alter: FAILED!\n");
}
flag = check_drop(4,mysql,"test");
printf("Audit the drop operation table\n");
if(flag)
{
success++;
printf("Drop: SUCCESS!\n");
}
else{
failed++;
printf("Drop: FAILED!\n");
}
opt_audit_class = 2;
opt_audit_ops &=~AUDIT_DDL;
flag = check_create(2,mysql,table);
printf("Don't audit the create operation into file\n");
if(!flag)
{
success++;
printf("Create: SUCCESS!\n");
}
else{
failed++;
printf("Create: FAILED!\n");
}
flag = check_alter(2,mysql,table);
printf("Don't audit the alter operation into file\n");
if(!flag)
{
success++;
printf("Alter: SUCCESS!\n");
}
else{
failed++;
printf("Alter: FAILED!\n");
}
flag = check_drop(2,mysql,"test");
printf("Don't audit the drop operation file\n");
if(!flag)
{
success++;
printf("Drop: SUCCESS!\n");
}
else{
failed++;
printf("Drop: FAILED!\n");
}
opt_audit_class = 4;
flag = check_create(4,mysql,"test");
printf("Don't audit the create operation into table\n");
if(!flag)
{
success++;
printf("Create: SUCCESS!\n");
}
else{
failed++;
printf("Create: FAILED!\n");
}
flag = check_alter(4,mysql,"test");
printf("Don't audit the alter operation into table\n");
if(!flag)
{
success++;
printf("Alter: SUCCESS!\n");
}
else{
failed++;
printf("Alter: FAILED!\n");
}
flag = check_drop(4,mysql,"test");
printf("Don't audit the drop operation table\n");
if(!flag)
{
success++;
printf("Drop: SUCCESS!\n");
}
else{
failed++;
printf("Drop: FAILED!\n");
}
opt_audit_ops = origin_audit_ops;
opt_audit_class = origin_audit_class;
close_connection(mysql);
printf("=============================\n");
printf("total: %d, success: %d, failed: %d\n",success+failed,success,failed);
return 0;
}
示例13: connection_cb
static void connection_cb(struct ev_loop *loop, ev_io *w, int revents) {
struct jrpc_connection *conn;
struct jrpc_server *server = (struct jrpc_server *) w->data;
size_t bytes_read = 0;
//get our 'subclassed' event watcher
conn = (struct jrpc_connection *) w;
int fd = conn->fd;
if (conn->pos == (conn->buffer_size - 1)) {
char * new_buffer = realloc(conn->buffer, conn->buffer_size *= 2);
if (new_buffer == NULL) {
perror("Memory error");
return close_connection(loop, w);
}
conn->buffer = new_buffer;
memset(conn->buffer + conn->pos, 0, conn->buffer_size - conn->pos);
}
// can not fill the entire buffer, string must be NULL terminated
int max_read_size = conn->buffer_size - conn->pos - 1;
if ((bytes_read = read(fd, conn->buffer + conn->pos, max_read_size))
== -1) {
perror("read");
return close_connection(loop, w);
}
if (!bytes_read) {
// client closed the sending half of the connection
if (server->debug_level)
printf("Client closed connection.\n");
return close_connection(loop, w);
} else {
cJSON *root;
char *end_ptr = NULL;
conn->pos += bytes_read;
if ((root = cJSON_Parse_Stream(conn->buffer, &end_ptr)) != NULL) {
if (server->debug_level > 1) {
char * str_result = cJSON_Print(root);
printf("Valid JSON Received:\n%s\n", str_result);
free(str_result);
}
if (root->type == cJSON_Object) {
eval_request(server, conn, root);
}
//shift processed request, discarding it
memmove(conn->buffer, end_ptr, strlen(end_ptr) + 2);
conn->pos = strlen(end_ptr);
memset(conn->buffer + conn->pos, 0,
conn->buffer_size - conn->pos - 1);
cJSON_Delete(root);
} else {
// did we parse the all buffer? If so, just wait for more.
// else there was an error before the buffer's end
if (end_ptr != (conn->buffer + conn->pos)) {
if (server->debug_level) {
printf("INVALID JSON Received:\n---\n%s\n---\n",
conn->buffer);
}
send_error(conn, JRPC_PARSE_ERROR,
strdup(
"Parse error. Invalid JSON was received by the server."),
NULL);
return close_connection(loop, w);
}
}
}
}
示例14: main
int main(int argc, char** argv) {
int port = atoi(argv[1]);
Server* server = create_server(port);
listen_port(server);
Connection* con = accept_connection(server);
char client_addr[50];
get_connection_address(con, client_addr);
printf("CLIENT %s CONNECTED\n", client_addr);
receive_greet(con);
send_greet_ack(con);
//Receive folder anem
char buffer[MAX_MSG];
receive_msg(con, buffer);
send_ack(con);
char filename[100];
strcpy(filename, client_addr);
strcat(filename, buffer);
int i;
for(i = 0; filename[i] != '\0'; i++){
filename[i] = filename[i] == '/'? '.': filename[i];
}
char* filebuffer = calloc(sizeof(char), MAX_MSG);
int filebuffer_size = MAX_MSG;
filebuffer[0] = '\0';
int usedbuffer = 0;
//receive filenames
while(receive_msg(con, buffer)){
usedbuffer += strlen(buffer)+1;
if(usedbuffer > filebuffer_size){
filebuffer_size *= 2;
filebuffer = (char*) realloc(filebuffer, sizeof(char)*filebuffer_size*2);
}
printf("%s\n", buffer);
sprintf(filebuffer, "%s%s\n", filebuffer, buffer);
send_ack(con);
}
shutdown_server(server);
close_connection(con);
FILE* f = fopen(filename, "w");
fprintf(f, "%s", filebuffer);
fclose(f);
free(filebuffer);
return 0;
}
示例15: handle_read
static void
handle_read( int cnum, struct timeval* nowP )
{
char buf[30000]; /* must be larger than throttle / 2 */
int bytes_to_read, bytes_read, bytes_handled;
float elapsed;
ClientData client_data;
register long checksum;
tmr_reset( nowP, connections[cnum].idle_timer );
if ( do_throttle )
bytes_to_read = throttle / 2.0;
else
bytes_to_read = sizeof(buf);
if ( ! connections[cnum].did_response )
{
connections[cnum].did_response = 1;
connections[cnum].response_at = *nowP;
}
#ifdef USE_SSL
if ( urls[connections[cnum].url_num].protocol == PROTO_HTTPS )
bytes_read = SSL_read( connections[cnum].ssl, buf, bytes_to_read );
else
bytes_read = read( connections[cnum].conn_fd, buf, bytes_to_read );
#else
bytes_read = read( connections[cnum].conn_fd, buf, bytes_to_read );
#endif
if ( bytes_read <= 0 )
{
close_connection( cnum );
return;
}
for ( bytes_handled = 0; bytes_handled < bytes_read; )
{
switch ( connections[cnum].conn_state )
{
case CNST_HEADERS:
/* State machine to read until we reach the file part. Looks for
** Content-Length header too.
*/
for ( ; bytes_handled < bytes_read && connections[cnum].conn_state == CNST_HEADERS; ++bytes_handled )
{
switch ( connections[cnum].header_state )
{
case HDST_LINE1_PROTOCOL:
switch ( buf[bytes_handled] )
{
case ' ': case '\t':
connections[cnum].header_state = HDST_LINE1_WHITESPACE;
break;
case '\n':
connections[cnum].header_state = HDST_LF;
break;
case '\r':
connections[cnum].header_state = HDST_CR;
break;
}
break;
case HDST_LINE1_WHITESPACE:
switch ( buf[bytes_handled] )
{
case ' ': case '\t':
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
connections[cnum].http_status =
buf[bytes_handled] - '0';
connections[cnum].header_state = HDST_LINE1_STATUS;
break;
case '\n':
connections[cnum].header_state = HDST_LF;
break;
case '\r':
connections[cnum].header_state = HDST_CR;
break;
default:
connections[cnum].header_state = HDST_TEXT;
break;
}
break;
case HDST_LINE1_STATUS:
switch ( buf[bytes_handled] )
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
connections[cnum].http_status =
connections[cnum].http_status * 10 +
buf[bytes_handled] - '0';
break;
case '\n':
connections[cnum].header_state = HDST_LF;
break;
case '\r':
connections[cnum].header_state = HDST_CR;
break;
//.........这里部分代码省略.........