/************************************************************************** write wrapper function -vasc **************************************************************************/ static int write_socket_data(struct connection *pc, struct socket_packet_buffer *buf, int limit) { int start, nput, nblock; if (is_server() && pc->server.is_closing) { return 0; } for (start=0; buf->ndata-start>limit;) { fd_set writefs, exceptfs; struct timeval tv; FC_FD_ZERO(&writefs); FC_FD_ZERO(&exceptfs); FD_SET(pc->sock, &writefs); FD_SET(pc->sock, &exceptfs); tv.tv_sec = 0; tv.tv_usec = 0; if (fc_select(pc->sock+1, NULL, &writefs, &exceptfs, &tv) <= 0) { if (errno != EINTR) { break; } else { /* EINTR can happen sometimes, especially when compiling with -pg. * Generally we just want to run select again. */ continue; } } if (FD_ISSET(pc->sock, &exceptfs)) { connection_close(pc, _("network exception")); return -1; } if (FD_ISSET(pc->sock, &writefs)) { nblock=MIN(buf->ndata-start, MAX_LEN_PACKET); log_debug("trying to write %d limit=%d", nblock, limit); if((nput=fc_writesocket(pc->sock, (const char *)buf->data+start, nblock)) == -1) { #ifdef NONBLOCKING_SOCKETS if (errno == EWOULDBLOCK || errno == EAGAIN) { break; } #endif connection_close(pc, _("lagging connection")); return -1; } start += nput; } } if (start > 0) { buf->ndata -= start; memmove(buf->data, buf->data+start, buf->ndata); pc->last_write = timer_renew(pc->last_write, TIMER_USER, TIMER_ACTIVE); timer_start(pc->last_write); } return 0; }
static void end_session_with_error(SESSION_INSTANCE* session_instance, const char* condition_value, const char* description) { ERROR_HANDLE error_handle = error_create(condition_value); if (error_handle == NULL) { /* fatal error */ session_set_state(session_instance, SESSION_STATE_DISCARDING); (void)connection_close(session_instance->connection, "amqp:internal-error", "Cannot allocate error handle to end session"); } else { if ((error_set_description(error_handle, description) != 0) || (send_end_frame(session_instance, error_handle) != 0)) { /* fatal error */ session_set_state(session_instance, SESSION_STATE_DISCARDING); (void)connection_close(session_instance->connection, "amqp:internal-error", "Cannot allocate error handle to end session"); } else { session_set_state(session_instance, SESSION_STATE_DISCARDING); } error_destroy(error_handle); } }
// The tcpServerTask handles new incomming connections and creates new // tcpConnectionTasks void tcpServer_task_proc(void *arg) { connection_t newCon; connection_t *freeCon; int i; int ret; ret = listen(tcpServerSocket, 1); if (ret) { tims_print("ERROR: Can't listen to tcpServerSocket\n"); return; } tims_dbg("server task started, waiting for connections ... \n"); while (!terminate) { newCon.addrLen = sizeof(newCon.addr); newCon.socket = accept(tcpServerSocket, (struct sockaddr *)&newCon.addr, &newCon.addrLen); if (newCon.socket < 0) { tims_print("error: Can't accept new connection\n"); return; } freeCon = connection_getFree(&newCon); if (!freeCon) { tims_print("ERROR: Can't accept more than %i connections " "(ip %s connection refused)\n", MAX_CONNECTIONS, inet_ntoa(newCon.addr.sin_addr)); connection_close(&newCon); } else { i = freeCon->index; tims_print("con[%02d]: %s: login\n", i, inet_ntoa(conList[i].addr.sin_addr)); // create connection thread ret = pthread_create(&conList[i].conThread, NULL, (void *)tcpConnection_task_proc, &conList[i]); if (ret) { tims_print("error: Can't create thread for TCP/IP connection\n"); connection_close(&conList[i]); } } } tims_dbg("server task: exit\n"); }
connection *connection_accepted(server *srv, server_socket *srv_socket, sock_addr *cnt_addr, int cnt) { connection *con; srv->cur_fds++; /* ok, we have the connection, register it */ #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "appected()", cnt); #endif srv->con_opened++; con = connections_get_new_connection(srv); con->fd = cnt; con->fde_ndx = -1; fdevent_register(srv->ev, con->fd, connection_handle_fdevent, con); connection_set_state(srv, con, CON_STATE_REQUEST_START); con->connection_start = srv->cur_ts; con->dst_addr = *cnt_addr; buffer_copy_string(con->dst_addr_buf, inet_ntop_cache_get_ip(srv, &(con->dst_addr))); con->srv_socket = srv_socket; if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv->ev, con->fd)) { log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno)); connection_close(srv, con); return NULL; } #ifdef USE_OPENSSL /* connect FD to SSL */ if (srv_socket->is_ssl) { if (NULL == (con->ssl = SSL_new(srv_socket->ssl_ctx))) { log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", ERR_error_string(ERR_get_error(), NULL)); connection_close(srv, con); return NULL; } con->renegotiations = 0; SSL_set_app_data(con->ssl, con); SSL_set_accept_state(con->ssl); if (1 != (SSL_set_fd(con->ssl, cnt))) { log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", ERR_error_string(ERR_get_error(), NULL)); connection_close(srv, con); return NULL; } } #endif return con; }
int telnet_run(tcp_connection_t *conn) { size_t bytes = 0; while(1) { /* Receive from socket */ bytes = recv(conn->tcp_sock, buffer, 2048, 0); if(0 == bytes) { printf("Remote host closed connection.\n"); return connection_close(conn); } if(0 > bytes) { fprintf(stderr, "error while receiving from remote host!\n"); return -1; } /******************************************** * Very sophisticated business logic * ********************************************/ if(0 == strncmp(buffer, "quit", 4)) { return connection_close(conn); } else if(0 == strncmp(buffer, "halt", 4)) { return connection_terminate(conn); } else { memcpy(buffer, "Unknown command!\n", 17); bytes = 17; } /********************************************/ /* Answer on socket */ bytes = send(conn->tcp_sock, buffer, bytes, 0); if(0 >= bytes) { fprintf(stderr, "error while sending to remote host!\n"); return -1; } memset(buffer, 0, 2048); } return 0; }
// Puts the connection in error status and queues an ERROR frame for output. // The causalframe should contain the client frame that casued the error, // or NULL if there is none. Takes ownership of the error message bytestring. void connection_send_error_message(connection *c, frame *causalframe, bytestring *msg) { // Set error connection status c->status = CONNECTION_STATUS_STOMP_ERROR; // Create an error frame containing the message frame *errorframe = frame_new(); frame_set_command(errorframe, CMD_ERROR); // Set error message header headerbundle *errorheaders = frame_get_headerbundle(errorframe); headerbundle_append_header(errorheaders, bytestring_new_from_string("message"), msg); // If there was a causal frame, add details from it if (causalframe) { // Original 'receipt' header is included as the error's 'receipt-id' header const bytestring *receipt = headerbundle_get_header_value_by_str(frame_get_headerbundle(causalframe), "receipt"); if (receipt) { headerbundle_append_header(errorheaders, bytestring_new_from_string("receipt-id"), bytestring_dup(receipt));; } } // Enqueue frame if (!frameserializer_enqueue_frame(c->frameserializer, errorframe)) { log_printf(LOG_LEVEL_ERROR, "Outgoing queue is full, dropping error frame.\n"); connection_close(c); return; } return; }
/* * Timeout idle connections. */ int connections_timeout_idle(time_t now) { int i = 0; int connindex; Connection* c; for( c = connection_first( &connindex ); c != NULL; c = connection_next( c, &connindex ) ) { /* Don't timeout a slow-running request or a persistent * outbound connection */ if( c->c_n_ops_executing || c->c_conn_state == SLAP_C_CLIENT ) { continue; } if( difftime( c->c_activitytime+global_idletimeout, now) < 0 ) { /* close it */ connection_closing( c, "idletimeout" ); connection_close( c ); i++; } } connection_done( c ); return i; }
/* * shutdown all connections */ int connections_shutdown(void) { ber_socket_t i; for ( i = 0; i < dtblsize; i++ ) { if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) { ldap_pvt_thread_mutex_lock( &connections[i].c_mutex ); if( connections[i].c_struct_state == SLAP_C_USED ) { /* give persistent clients a chance to cleanup */ if( connections[i].c_conn_state == SLAP_C_CLIENT ) { ldap_pvt_thread_pool_submit( &connection_pool, connections[i].c_clientfunc, connections[i].c_clientarg ); } else { /* c_mutex is locked */ connection_closing( &connections[i], "slapd shutdown" ); connection_close( &connections[i] ); } } ldap_pvt_thread_mutex_unlock( &connections[i].c_mutex ); } } return 0; }
void* serviceConnection(void* psa) { int success; connection conn; http_server srv; http_request request; http_response response; meta_error e = meta_error_new(); conn = (connection)psa; srv = connection_arg2(conn); request = http_server_get_request(srv); response = http_server_get_response(srv); success = serviceConnection2(srv, conn, request, response, e); if(!success && is_tcpip_error(e)) { connection_discard(conn); } else { connection_close(conn); } http_server_recycle_request(srv, request); http_server_recycle_response(srv, response); meta_error_free(e); return (void*)success; }
static void ping_uplink(void *arg) { unsigned int diff; if (me.connected) { ping_sts(); diff = CURRTIME - me.uplinkpong; if (diff >= 600) { slog(LG_INFO, "ping_uplink(): uplink appears to be dead, disconnecting"); sts("ERROR :Closing Link: 127.0.0.1 (Ping timeout: %d seconds)", diff); sendq_flush(curr_uplink->conn); if (me.connected) { errno = 0; connection_close(curr_uplink->conn); } } } if (!me.connected) ping_uplink_timer = NULL; }
static void connection_handle_close_state(server *srv, connection *con) { connection_read_for_eos(srv, con); if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) { connection_close(srv, con); } }
void connection_delete(connection_t* con) { mailbox_delete_all(con->index); shutdown(con->socket, SHUT_RDWR); connection_close(con); tims_dbgdetail("connection[%i] closed\n", con->index); }
int lib2ch_thread_init(Board *board) { char url[MAX_BUF + 1]; sprintf(url, "http://%s.%s/%s/subject.txt", board->server, board->ch->host, board->name); connection(url, thread_buf); connection_close(); lib2ch_strstr(thread_list, thread_buf, "\n"); return 0; }
static void my_rhandler(connection_t * cptr) { char buf[BUFSIZE * 2]; if (my_read(cptr, buf) <= 0) connection_close(cptr); else do_packet(cptr, buf); }
static void my_rhandler(connection_t * cptr) { char buf[BUFSIZE * 2]; if (!my_read(cptr, buf)) connection_close(cptr); do_packet(buf); }
void client_free(Client* client) { connection_close(client->connection); g_io_channel_unref(client->shell_out_channel); g_io_channel_unref(client->shell_err_channel); g_io_channel_unref(client->shell_in_channel); free(client->connection); //TODO mb g_free() free(client); }
int lib2ch_response_init(Thread *thread) { char url[MAX_BUF + 1]; sprintf(url, "http://%s.%s/%s/dat/%s.dat", thread->board->server, thread->board->ch->host, thread->board->name, thread->no); connection(url, response_buf); connection_close(); lib2ch_strstr(response_list, response_buf, "\n"); return 0; }
void irc_cleanup(irc_t* irc) { free(irc->server); free(irc->port); connection_close(irc->sockfd); list_destroy(notice_list); list_destroy(privmsg_list); }
void connection_proc(io_atom *ioa, int flags) { connection *conn = (connection*)ioa; int fd = conn->io.fd; int len; if(flags & IO_READ) { do { len = read(fd, g_readbuf, sizeof(g_readbuf)); } while (errno == EINTR); // stupid posix if(len > 0) { write(fd, g_readbuf, len); conn->chars_processed += len; } else if(len == 0) { // A 0-length read means remote has closed normally connection_close(conn); return; } else { // handle an error on the socket if(errno == EAGAIN) { // nothing to read? weird. } else if(errno == EWOULDBLOCK) { // with glibc EAGAIN==EWOULDBLOCK so this is probably dead code } else { // there's some sort of read error on this stream. connection_close(conn); return; } } } if(flags & IO_WRITE) { // there's more space in the write buffer // so continue writing. } if(flags & IO_EXCEPT) { // I think this is also used for OOB. // recv (fd1, &c, 1, MSG_OOB); connection_close(conn); return; } }
void client_destroy(client_t *client) { if (client == NULL) return; if (client->worker) { WARN0 ("client still on worker thread"); return; } /* release the buffer now, as the buffer could be on the source queue * and may of disappeared after auth completes */ if (client->refbuf) { refbuf_release (client->refbuf); client->refbuf = NULL; } if (client->flags & CLIENT_AUTHENTICATED) DEBUG1 ("client still in auth \"%s\"", httpp_getvar (client->parser, HTTPP_VAR_URI)); /* write log entry if ip is set (some things don't set it, like outgoing * slave requests */ if (client->respcode > 0 && client->parser) logging_access(client); if (client->flags & CLIENT_IP_BAN_LIFT) { INFO1 ("lifting IP ban on client at %s", client->connection.ip); connection_release_banned_ip (client->connection.ip); client->flags &= ~CLIENT_IP_BAN_LIFT; } connection_close (&client->connection); if (client->parser) httpp_destroy (client->parser); global_lock (); global.clients--; stats_event_args (NULL, "clients", "%d", global.clients); config_clear_listener (client->server_conn); global_unlock (); /* we need to free client specific format data (if any) */ if (client->free_client_data) client->free_client_data (client); free(client->username); free(client->password); free(client); }
static void on_packet(connection *c,packet *p,int32_t error){ if(p){ //rpacket *rpk = (rpacket*)p; //uint64_t id = rpacket_peek_uint64(rpk); //printf("%lld\n",id); //if(id == (uint64_t)c){ // packet_count++; // connection_send(c,make_writepacket(p),NULL); //} }else{ //error or peer close unregister_timer((timer*)c->ud_ptr); connection_close(c); } }
uint32_t proto_nc_io_in_http(struct connection *con, void *context, unsigned char *data, uint32_t size) { static const char *header = "200 HTTP/1.0\r\nContent-Length: 1048576\r\n\r\n"; if( f == NULL ) { f = malloc(1024*1024 + strlen(header)); memcpy(f, header, strlen(header)); } // connection_send(con, header, strlen(header)); connection_send(con, f, 1024*1024 + strlen(header)); connection_close(con); // free(f); return size; }
static void _connection_node_destroy (connection_queue_t *node) { INFO("destroying node"); if (node->client) { client_destroy(node->client); /* destroys con, parser, refbuf */ } else { if (node->parser) { httpp_destroy(node->parser); } if (node->refbuf) { refbuf_release(node->refbuf); } if (node->con) { connection_close(node->con); } } free(node); }
static int luasocket_close(lua_State *L){ luasocket_t luasock = lua_touserdata(L,1); if(luasock->type == _SOCKET){ if(luasock->listening){ listener_close_listen(luasock); }else{ kn_close_sock(luasock->sock); destroy_luasocket(luasock); } }else if(luasock->type == _STREAM_CONN){ connection_close(luasock->streamconn); refobj_dec((refobj*)luasock->streamconn); }else{ datagram_close(luasock->datagram); refobj_dec((refobj*)luasock->datagram); } return 0; }
static VALUE response_run(connection_t *c) { /* Call the app to process the request */ VALUE response = rb_funcall_rescue(c->backend->app, sInternedCall, 1, c->env); unsigned sent = 0; if (response == Qundef) { /* log any error */ rb_funcall(c->backend->obj, rb_intern("log_last_exception"), 0); sent = 1; } else { /* store response info and prepare for writing */ int status = FIX2INT(rb_ary_entry(response, 0)); VALUE headers = rb_ary_entry(response, 1); VALUE body = rb_ary_entry(response, 2); /* read buffer no longer needed, free up now so we * can reuse some of it for write buffer */ buffer_reset(&c->read_buffer); connection_watch_writable(c); response_send_status(c, status); response_send_headers(c, headers); response_send_body(c, body); c->finished = 1; if (buffer_eof(&c->write_buffer)) sent = 1; } c->backend->thread_count--; c->thread.active = 0; if (sent) connection_close(c); return Qnil; }
void client_destroy(client_t *client) { if (client == NULL) return; /* release the buffer now, as the buffer could be on the source queue * and may of disappeared after auth completes */ if (client->refbuf) { refbuf_release (client->refbuf); client->refbuf = NULL; } if (auth_release_listener (client)) return; /* write log entry if ip is set (some things don't set it, like outgoing * slave requests */ if (client->respcode && client->parser) logging_access(client); if (client->con) connection_close(client->con); if (client->parser) httpp_destroy(client->parser); global_lock (); global.clients--; stats_event_args (NULL, "clients", "%d", global.clients); global_unlock (); /* we need to free client specific format data (if any) */ if (client->free_client_data) client->free_client_data (client); free(client->username); free(client->password); free(client); }
// Pull waiting input in to the connection's buffer. void connection_pump_input(connection *c) { int readcount = 0; // Try to read some data readcount = buffer_input_fd(c->inbuffer, c->fd, NETWORK_READ_SIZE); if (readcount == 0) { connection_close(c); } else if (readcount < 0) { int error = errno; if ((error != EAGAIN) && (error != EWOULDBLOCK)) connection_abort(c, error); // Unexpected error } // Update read timestamp, if needed if (readcount > 0) gettimeofday(&c->readtime, NULL); }
static void connection_proclist_handle(struct connection_s* self) { struct rwlist_s* proc_list = self->proc_list; struct msg_data_s** pmsg = NULL; while((pmsg = (struct msg_data_s**)ox_rwlist_pop(proc_list, 0)) != NULL) { struct msg_data_s* msg = *pmsg; if(msg->type == send_msg_connect) { connection_connect_help(self, (struct connect_msg*)msg->data); } else if(msg->type == send_msg_close) { connection_close(self); } free(msg); } }
/**************************************************************************** Add data to send to the connection. ****************************************************************************/ static bool add_connection_data(struct connection *pconn, const unsigned char *data, int len) { struct socket_packet_buffer *buf; if (NULL == pconn || !pconn->used || (is_server() && pconn->server.is_closing)) { return TRUE; } buf = pconn->send_buffer; log_debug("add %d bytes to %d (space =%d)", len, buf->ndata, buf->nsize); if (!buffer_ensure_free_extra_space(buf, len)) { connection_close(pconn, _("buffer overflow")); return FALSE; } memcpy(buf->data + buf->ndata, data, len); buf->ndata += len; return TRUE; }
gpointer connectionHandler(gpointer connection) { if (!isAthorized(connection)) { connection_close(connection); free(connection); return NULL; } gint shell_stdin; gint shell_stdout; gint shell_stderr; #ifdef __WIN32__ gchar* argv[] = {"cmd.exe", NULL}; #elif __UNIX__ gchar* argv[] = {"zsh", NULL}; #endif GError* error = NULL; gboolean success = g_spawn_async_with_pipes(".", argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &shell_stdin, &shell_stdout, &shell_stderr, &error); if (!success) { g_error(error->message); return NULL; } Client* client = client_new(shell_stdin, shell_stdout, shell_stderr, connection); client->isShellActive = TRUE; GThread* readingThread = g_thread_new(NULL, (GThreadFunc) client_reading_loop, client); GThread* writingOutThread = g_thread_new(NULL, (GThreadFunc) client_writing_shell_out_loop, client); GThread* writingErrThread = g_thread_new(NULL, (GThreadFunc) client_writing_shell_err_loop, client); g_print("threads started\n"); g_thread_join(readingThread); g_thread_join(writingOutThread); g_thread_join(writingErrThread); g_thread_unref(readingThread); g_thread_unref(writingOutThread); g_thread_unref(writingErrThread); g_print("Client disconnected\n"); client_free(client); return NULL; }