void KCrash::startDrKonqi(const char *argv[], int argc) { int socket = openSocket(); if(socket < -1) { startDirectly(argv, argc); return; } klauncher_header header; header.cmd = LAUNCHER_EXEC_NEW; const int BUFSIZE = 8192; // make sure this is big enough char buffer[BUFSIZE + 10]; int pos = 0; long argcl = argc; memcpy(buffer + pos, &argcl, sizeof(argcl)); pos += sizeof(argcl); for(int i = 0; i < argc; ++i) { int len = strlen(argv[i]) + 1; // include terminating \0 if(pos + len > BUFSIZE) { fprintf(stderr, "BUFSIZE in KCrash not big enough!\n"); startDirectly(argv, argc); return; } memcpy(buffer + pos, argv[i], len); pos += len; } long env = 0; memcpy(buffer + pos, &env, sizeof(env)); pos += sizeof(env); long avoid_loops = 0; memcpy(buffer + pos, &avoid_loops, sizeof(avoid_loops)); pos += sizeof(avoid_loops); header.arg_length = pos; write_socket(socket, (char *)&header, sizeof(header)); write_socket(socket, buffer, pos); if(read_socket(socket, (char *)&header, sizeof(header)) < 0 || header.cmd != LAUNCHER_OK) { startDirectly(argv, argc); return; } long pid; read_socket(socket, buffer, header.arg_length); pid = *((long *)buffer); alarm(0); // Seems we made it.... for(;;) { if(kill(pid, 0) < 0) _exit(253); sleep(1); // the debugger should stop this process anyway } }
int connection_read(struct connection *connection, void *data, int len) { if (connection->service->type == CONNECTION_TCP) return read_socket(connection->fd, data, len); else return read(connection->fd, data, len); }
int Cmd_operater(int sockd) { char cmd[7],message[256]; int i; int flag=0; char buffer[512]; char send_buffer[512]; while(1) { if(timeout(sockd,200)>0) { memset(buffer,'\0',512); memset(send_buffer,'\0',512); read_socket(sockd,buffer,512); printf("recv:%s\n",buffer); sprintf(send_buffer,"server recv:%s\n",buffer); write_socket(sockd,send_buffer,512); } else { close(sockd); break; } } }
/********************************************************************* * * Function : drain_and_close_socket * * Description : Closes a TCP/IP socket after draining unread data * * Parameters : * 1 : fd = file descriptor of the socket to be closed * * Returns : void * *********************************************************************/ void drain_and_close_socket(jb_socket fd) { #ifdef FEATURE_CONNECTION_KEEP_ALIVE if (socket_is_still_alive(fd)) #endif { int bytes_drained_total = 0; int bytes_drained; #ifdef HAVE_SHUTDOWN /* Apparently Windows has shutdown() but not SHUT_WR. */ #ifndef SHUT_WR #define SHUT_WR 1 #endif if (0 != shutdown(fd, SHUT_WR)) { log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd); } #endif #define ARBITRARY_DRAIN_LIMIT 10000 do { char drainage[500]; if (!data_is_available(fd, 0)) { /* * If there is no data available right now, don't try * to drain the socket as read_socket() could block. */ break; } bytes_drained = read_socket(fd, drainage, sizeof(drainage)); if (bytes_drained < 0) { log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd); } else if (bytes_drained > 0) { bytes_drained_total += bytes_drained; if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT) { log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd); break; } } } while (bytes_drained > 0); if (bytes_drained_total != 0) { log_error(LOG_LEVEL_CONNECT, "Drained %d bytes before closing socket %d", bytes_drained_total, fd); } } close_socket(fd); }
static pid_t startFromKdeinit(int argc, const char *argv[]) { int socket = openSocket(); if( socket < -1 ) return 0; klauncher_header header; header.cmd = LAUNCHER_EXEC_NEW; const int BUFSIZE = 8192; // make sure this is big enough char buffer[ BUFSIZE + 10 ]; int pos = 0; long argcl = argc; memcpy( buffer + pos, &argcl, sizeof( argcl )); pos += sizeof( argcl ); for( int i = 0; i < argc; ++i ) { int len = strlen( argv[ i ] ) + 1; // include terminating \0 if( pos + len >= BUFSIZE ) { fprintf( stderr, "BUFSIZE in KCrash not big enough!\n" ); return 0; } memcpy( buffer + pos, argv[ i ], len ); pos += len; } long env = 0; memcpy( buffer + pos, &env, sizeof( env )); pos += sizeof( env ); long avoid_loops = 0; memcpy( buffer + pos, &avoid_loops, sizeof( avoid_loops )); pos += sizeof( avoid_loops ); header.arg_length = pos; write_socket(socket, (char *) &header, sizeof(header)); write_socket(socket, buffer, pos); if( read_socket( socket, (char *) &header, sizeof(header)) < 0 || header.cmd != LAUNCHER_OK ) { return 0; } long pid; read_socket(socket, buffer, header.arg_length); pid = *((long *) buffer); return static_cast<pid_t>(pid); }
int process_request() { client.request->contents = read_socket(client.request->socket); if (!client.request->contents) return request_retry(); if (!client.request->body && process_request_contents()) return -1; if (request_done()) dechunk_request(); return 0; }
int get_input(char *buf, int n) { switch (input_type) { case FILE_INPUT: return read_file(buf, n); case SOCKET_INPUT: return read_socket(buf, n); } return 0; }
int check_fds(fd_set *fd_read, int *fd, void (*fptr[7])(char buf[515], int *), char *tab[7]) { if (FD_ISSET(0, fd_read)) if (read_stdin(fd, fptr, tab) == -1) return (-1); if (*fd != -1 && FD_ISSET(*fd, fd_read)) if (read_socket(fd) == -1) return (-1); return (0); }
static void listen_sensor_app(short port) { SOCKET guest_sock; SOCKET sock; char *data; printf("opening server on port 22470\n"); while ((guest_sock = open_server("22470")) == INVALID_SOCKET) { printf("unable to listen on port 22470... retyring in few seconds\n"); our_sleep(5); } while (1) { printf("Waiting for connection from VM\n"); SOCKET client_sock = connect_client(guest_sock); if (client_sock == INVALID_SOCKET) { perror("accept()"); continue; } printf("Got sensors connection from VM\n"); while (1) { printf("Connecting to hardware device on port %d...\n", port); sock = open_socket("127.0.0.1", port); if (sock != INVALID_SOCKET) { printf("Connected to hardware device, socket=%d :-)\n", sock); while ((data = read_socket(sock, PACKET_LEN))) { if (write_socket(client_sock, data, PACKET_LEN)<0) { printf("Connection closed with VM - closing connection with hardware device\n"); free(data); } } printf("Closing connection to hardware device\n"); closesocket(sock); our_sleep(2); } else { printf("Unable to connect to hardware device\n"); closesocket(client_sock); closesocket(guest_sock); return; } } } closesocket(guest_sock); }
int32_t select_loop(int32_t sockfd, shared_threads_t *shared) { int32_t rc; nt_frame_t oframe; memset(&oframe, 0, sizeof(oframe)); uint8_t buff[BUFF_SIZE]; while (shared->running) { /* Set up a 5 second select timeout */ struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; fd_set read_fd; FD_ZERO(&read_fd); /* Just monitor our client socket */ FD_SET(sockfd, &read_fd); /* Let's call select */ rc = select(sockfd + 1, &read_fd, NULL, NULL, &timeout); /* An error occured */ if (rc < 0) { fprintf(stderr, "[Error] select failed\n"); shared->running = false; } /* Select timeout */ else if (rc == 0) { fprintf(stdout, "[Debug] select timeout\n"); } else { /* The socket is readable */ if (FD_ISSET(sockfd, &read_fd)) { uint32_t read_bytes; /* Leave the select loop if an error occured */ if ((read_bytes = read_socket(sockfd, buff)) <= 0) { shared->running = false; } else { on_data_received(shared->input_fifo, &oframe, buff, read_bytes); } } } } fprintf(stdout, "[Debug] leaving select loop\n"); return (rc); }
void start_server(int port, void (*post_cb) (post_content_t*)) { int listen_fd; listen_fd = get_tcp_socket(); set_enable_port_reuse(listen_fd); bind_socket(listen_fd, port); prepare_listen(listen_fd, 5); intlist_t* socklist = intlist_add(NULL, listen_fd); fd_set readfds; int r; int max; while(true){ FD_ZERO(&readfds); intlist_t* cursor = socklist; while(cursor != NULL){ FD_SET(cursor->value, &readfds); cursor = cursor->next; } max = intlist_max(socklist); r = select(max + 1, &readfds, NULL, NULL, NULL); if(r == -1){ perror("select error"); exit(EXIT_FAILURE); } else{ intlist_t* cursor = socklist; while(cursor != NULL){ if(FD_ISSET(cursor->value, &readfds)){ if(cursor->value == listen_fd){ int client_fd = accept_socket(cursor->value); intlist_add(socklist, client_fd); } else{ read_socket(cursor->value, post_cb); // TODO: write HTTP/1.1 200 OK if read success close(cursor->value); intlist_del(socklist, cursor->value); } } cursor = cursor->next; } } } }
/* Handles anything a user sends to this server while they are in a chat group */ void handle_in_group_requests(void *arg){ //Socket of the particular user in question int socket = (int) arg; while(1){ char message[1000] = {'\0'}; int message_size = 0; //printf("Waiting for a message on socket %d\n",socket); //Get the size of the message from the user read_socket(socket,&message_size,sizeof(int)); message_size = ntohl(message_size); printf("Received in handle_in_group_requests an int: %d\n",message_size); //Get the message from the user read_socket(socket,message,message_size); printf("Received message: %s\n",message); //Handle that message handle_in_group_message(message); } }
void tcp_server_fd_isset(tcp_server_ctx_t* ctx, fd_set *readfds) { /* 1. check client sockets */ socketlist_t* cursor = ctx->client_sockets; while(cursor != NULL){ if(FD_ISSET(cursor->socket, readfds)){ read_socket(ctx, cursor); } cursor = cursor->next; } /* 2. check listen socket */ if(FD_ISSET(ctx->listen_socket, readfds)){ accept_socket(ctx); } }
int main (int argc, char **argv) { if (wiringPiSetup () == -1) { fprintf (stdout, "oops: %s\n", strerror (errno)) ; return 1; } if (argc < 1) { fprintf(stdout, "Usage: picolord /path/to/socket"); } softPwmCreate (PIN_RED, RED_MIN, RED_MAX); softPwmCreate (PIN_GREEN, GREEN_MIN, GREEN_MAX); softPwmCreate (PIN_BLUE, BLUE_MIN, BLUE_MAX); struct sockaddr_un server; sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock < 0) { perror("picolord: Error opening stream socket"); exit(1); } fcntl(sock, F_SETFL, O_NONBLOCK); server.sun_family = AF_UNIX; strcpy(server.sun_path, argv[1]); if (bind(sock, (struct sockaddr *) &server, sizeof(struct sockaddr_un))) { perror("picolord: Error binding stream socket"); exit(1); } listen(sock, 5); // Catch kill signals and ctrl+c signal(SIGINT, intHandler); signal(SIGKILL, intHandler); signal(SIGHUP, intHandler); while (keeprunning) { read_socket(); update_color(); delay(delay_time); } set_color(0,0,0); delay(100); if (sock) close(sock); unlink(argv[1]); return 0; }
static char *_btc_io(__maybe_unused const char *cmd, char *json, WHERE_FFL_ARGS) { char *ip, *port; char *data, *ans, *res, *ptr; int fd, ret, red; size_t len; data = btc_data(json, &len); if (!extract_sockaddr(btc_server, &ip, &port)) { LOGERR("%s() invalid btc server '%s'", __func__, btc_server); return NULL; } fd = connect_socket(ip, port); if (fd < 0) { LOGERR("%s() failed to connect to btc server %s", __func__, btc_server); return NULL; } ret = write_socket(fd, data, len); if (ret != (int)len) { LOGERR("%s() failed to write to btc server %s", __func__, btc_server); return NULL; } red = read_socket(fd, &ans, btc_timeout); ans[red] = '\0'; if (strncasecmp(ans, "HTTP/1.1 200 OK", 15)) { char *text = safe_text(ans); LOGERR("%s() btc server response not ok: %s", __func__, text); free(text); free(ans); res = strdup(EMPTY); } else { ptr = strstr(ans, "\n{"); if (ptr) res = strdup(ptr+1); else res = strdup(EMPTY); free(ans); } return res; }
int main(int argc, char *argv[]) { optiondata opt; motparm mp; port_list * plist = &g_ports; int rv; if ( (rv = get_options(&opt, &mp, plist, argc, argv)) != 0 ) return rv; /* register interrupt trap */ signal( SIGHUP, clean_n_exit ); signal( SIGINT, clean_n_exit ); signal( SIGQUIT, clean_n_exit ); signal( SIGKILL, clean_n_exit ); signal( SIGTERM, clean_n_exit ); if ( (rv = open_incoming_socket(&opt, plist)) < 0 ) return rv; while (1) /* run until interrupt or error (consider restart?) */ { mp.nread = 0; /* reset our counter */ /* wait for AFNI to talk to us */ if ( (rv = wait_for_socket(&opt, plist, &mp)) < 0 ) { clean_n_exit(0); return rv; } if ( ! opt.no_serial ) if ( (rv = open_serial(&opt, plist)) != 0 ) return rv; /* read data while it is there */ while ( (rv = read_socket(&opt, plist, &mp)) == 0) if ( ! opt.no_serial ) send_serial(&opt, plist, &mp); close_data_ports(plist); } return 0; /* should not be reached, of course */ }
int process_response() { client.response->contents = read_socket(client.response->socket); if (! client.response->contents) { error("No response contents on Response <%p>\n",client.response); return -1; } if (! client.response->body) { client.response->headers = parse_headers(client.response->contents,&client.response->body); if (! client.response->headers) { error("No response headers on Response <%p>\n",client.response); return -1; } } client.response->done = client.response->body && (len(client.response->contents) - client.response->body) >= inbound_content_length(client.response->contents,client.response->headers); if (client.response->done) dechunk_response(); return 0; }
/** * Runs the server socket loop, which uses the \c select() function * to copy received data into the socket's buffer only when the * operating system detects that the socket received some data. * * Some people would use a socket timeout in this situation. * However, we don't need that since each socket needs to have its * own thread (because FRC networking is relatively intensive). * Since each socket has its own dedicated thread, we can affort to * use a blocking \c select() call, which also reduces the overall * CPU usage of the application. * * \param ptr a pointer to a \c DS_Socket structure */ static void server_loop (DS_Socket* ptr) { if (ptr) { /* Set a 5-ms timeout on Windows */ #if defined _WIN32 struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 5000; #endif /* Make the socket non-blocking on Windows */ #if defined _WIN32 set_socket_block (ptr->info.sock_in, 0); #endif /* Periodicaly check if there is data available on the socket */ while (ptr->info.server_init == 1) { int rc; /* Set the file descriptor */ fd_set set; FD_ZERO (&set); FD_SET (ptr->info.sock_in, &set); /* Run select */ #if defined _WIN32 rc = select (0, &set, NULL, NULL, &tv); #else rc = select (ptr->info.sock_in + 1, &set, NULL, NULL, NULL); #endif /* Data is available, read it */ if (rc > 0) { if (FD_ISSET (ptr->info.sock_in, &set)) read_socket (ptr); } } } }
bool SocketInputStream2::gets(BaseString& str) { if (get_buffered_line(str)) return true; char buf[16]; do { ssize_t read_res = read_socket(buf, sizeof(buf)); if (read_res == -1) return false; if (!add_buffer(buf, read_res)) return false; if (get_buffered_line(str)) return true; } while(true); abort(); // Should never come here return false; };
void check_sockets() { int num; struct socket_node *p, *next; struct packet_disconnect packet; if (online) { num = SDLNet_CheckSockets(sockset, 0); if (num < 0) do_error("Failed checking socket set for activity"); else if (num) { for (p = socket_list; p != NULL; p = next) { next = p->next; if (SDLNet_SocketReady(p->sock)) { if (p->type == SOCKET_SERVER && server) new_connection(p->sock); else { if (read_socket(p->sock, p->recv_buf, &p->recv_buf_size) <= 0) { if (p->type == SOCKET_SERVER) { server_disconnect(); telegram("\nThe server disconnected.\n"); } else { telegram("\n%s has\ndisconnected from the\nserver.\n", GET_NAME(p->player)); init_player(p->player, INIT_PLAYER_INACTIVE); /* tell other clients */ packet.player =swap_int(p->player); packet.error =swap_int(ERROR_CONNECTION); send_all_sockets(PACKET_DISCONNECT, &packet, sizeof(struct packet_disconnect)); remove_socket(p); } } } } } } } }
void Engine::transfer_data(DataInputStream & network_in, DataOutputStream & network_out) { read_socket(network_in); read_app(); write_socket(network_out); }
static void http_exit(WEBBLK *webblk) { CGIVAR *cgivar; int rc; if(webblk) { /* MS SDK docs state: "To assure that all data is sent and received on a connected socket before it is closed, an application should use shutdown to close connection before calling closesocket. For example, to initiate a graceful disconnect: 1, Call WSAAsyncSelect to register for FD_CLOSE notification. 2. Call shutdown with how=SD_SEND. 3. When FD_CLOSE received, call recv until zero returned, or SOCKET_ERROR. 4. Call closesocket. Note: The shutdown function does not block regardless of the SO_LINGER setting on the socket." */ // Notify other end of connection to not expect any more data from us. // They should detect this via their own 'recv' returning zero bytes // (thus letting them know they've thus received all the data from us // they're ever going to receive). They should then do their own // 'shutdown(s,SHUT_WR)' at their end letting US know we're also not // going to be receiving any more data from THEM. This is called a // "graceful close" of the connection... shutdown( webblk->sock, SHUT_WR ); // Now wait for them to shudown THEIR end of the connection (i.e. wait // for them to do their own 'shutdown(s,SHUT_WR)') by "hanging" on a // 'recv' call until we either eventually detect they've shutdown their // end of the connection (0 bytes received) or else an error occurs... do { BYTE c; rc = read_socket( webblk->sock, &c, 1 ); } while ( rc > 0 ); // NOW we can SAFELY close the socket since we now KNOW for CERTAIN // that they've received ALL of the data we previously sent to them... // (otherwise they wouldn't have close their connection on us!) close_socket( webblk->sock ); if(webblk->user) free(webblk->user); if(webblk->request) free(webblk->request); cgivar = webblk->cgivar; while(cgivar) { CGIVAR *tmpvar = cgivar->next; free(cgivar->name); free(cgivar->value); free(cgivar); cgivar = tmpvar; } free(webblk); } exit_thread(NULL); }
static void CTCT_Read( DEVBLK* pDEVBLK, U32 sCount, BYTE* pIOBuf, BYTE* pUnitStat, U32* pResidual, BYTE* pMore ) { PCTCIHDR pFrame = NULL; // -> Frame header PCTCISEG pSegment = NULL; // -> Segment in buffer fd_set rfds; // Read FD_SET int iRetVal; // Return code from 'select' int iLength = 0; static struct timeval tv; // Timeout time for 'select' // Limit how long we should wait for data to come in FD_ZERO( &rfds ); FD_SET( pDEVBLK->fd, &rfds ); tv.tv_sec = CTC_READ_TIMEOUT_SECS; tv.tv_usec = 0; iRetVal = select( pDEVBLK->fd + 1, &rfds, NULL, NULL, &tv ); switch( iRetVal ) { case 0: *pUnitStat = CSW_CE | CSW_DE | CSW_UC | CSW_SM; pDEVBLK->sense[0] = 0; return; case -1: if( HSO_errno == HSO_EINTR ) return; WRMSG(HHC00973, "E", SSID_TO_LCSS(pDEVBLK->ssid), pDEVBLK->devnum, pDEVBLK->filename, strerror( HSO_errno ) ); pDEVBLK->sense[0] = SENSE_EC; *pUnitStat = CSW_CE | CSW_DE | CSW_UC; return; default: break; } // Read an IP packet from the TUN device iLength = read_socket( pDEVBLK->fd, pDEVBLK->buf, pDEVBLK->bufsize ); // Check for other error condition if( iLength < 0 ) { WRMSG(HHC00973, "E", SSID_TO_LCSS(pDEVBLK->ssid), pDEVBLK->devnum, pDEVBLK->filename, strerror( HSO_errno ) ); pDEVBLK->sense[0] = SENSE_EC; *pUnitStat = CSW_CE | CSW_DE | CSW_UC; return; } // Trace the packet received from the TUN device if( pDEVBLK->ccwtrace || pDEVBLK->ccwstep ) { WRMSG(HHC00913, "I", SSID_TO_LCSS(pDEVBLK->ssid), pDEVBLK->devnum, iLength, "TUN" ); packet_trace( pDEVBLK->buf, iLength, '<' ); } // Fix-up Frame pointer pFrame = (PCTCIHDR)pIOBuf; // Fix-up Segment pointer pSegment = (PCTCISEG)( pIOBuf + sizeof( CTCIHDR ) ); // Initialize segment memset( pSegment, 0, iLength + sizeof( CTCISEG ) ); // Update next frame offset STORE_HW( pFrame->hwOffset, (U16)(iLength + sizeof( CTCIHDR ) + sizeof( CTCISEG )) ); // Store segment length STORE_HW( pSegment->hwLength, (U16)(iLength + sizeof( CTCISEG )) ); // Store Frame type STORE_HW( pSegment->hwType, ETH_TYPE_IP ); // Copy data memcpy( pSegment->bData, pDEVBLK->buf, iLength ); // Fix-up frame pointer and terminate block pFrame = (PCTCIHDR)( pIOBuf + sizeof( CTCIHDR ) + sizeof( CTCISEG ) + iLength ); STORE_HW( pFrame->hwOffset, 0x0000 ); // Calculate #of bytes returned including two slack bytes iLength += sizeof( CTCIHDR ) + sizeof( CTCISEG ) + 2; if( sCount < (U32)iLength ) { *pMore = 1; *pResidual = 0; iLength = sCount; } else { *pMore = 0; *pResidual -= iLength; } // Set unit status *pUnitStat = CSW_CE | CSW_DE; }
static int ncat_listen_stream(int proto) { int rc, i, fds_ready; fd_set listen_fds; struct timeval tv; struct timeval *tvp = NULL; unsigned int num_sockets; /* clear out structs */ FD_ZERO(&master_readfds); FD_ZERO(&master_writefds); FD_ZERO(&master_broadcastfds); FD_ZERO(&listen_fds); #ifdef HAVE_OPENSSL FD_ZERO(&sslpending_fds); #endif zmem(&client_fdlist, sizeof(client_fdlist)); zmem(&broadcast_fdlist, sizeof(broadcast_fdlist)); #ifdef WIN32 set_pseudo_sigchld_handler(decrease_conn_count); #else /* Reap on SIGCHLD */ Signal(SIGCHLD, sigchld_handler); /* Ignore the SIGPIPE that occurs when a client disconnects suddenly and we send data to it before noticing. */ Signal(SIGPIPE, SIG_IGN); #endif #ifdef HAVE_OPENSSL if (o.ssl) setup_ssl_listen(); #endif /* Not sure if this problem exists on Windows, but fcntl and /dev/null don't */ #ifndef WIN32 /* Check whether stdin is closed. Because we treat this fd specially, we * can't risk it being reopened for an incoming connection, so we'll hold * it open instead. */ if (fcntl(STDIN_FILENO, F_GETFD) == -1 && errno == EBADF) { logdebug("stdin is closed, attempting to reserve STDIN_FILENO\n"); rc = open("/dev/null", O_RDONLY); if (rc >= 0 && rc != STDIN_FILENO) { /* Oh well, we tried */ logdebug("Couldn't reserve STDIN_FILENO\n"); close(rc); } } #endif /* We need a list of fds to keep current fdmax. The second parameter is a number added to the supplied connection limit, that will compensate maxfds for the added by default listen and stdin sockets. */ init_fdlist(&client_fdlist, sadd(o.conn_limit, num_listenaddrs + 1)); for (i = 0; i < NUM_LISTEN_ADDRS; i++) listen_socket[i] = -1; num_sockets = 0; for (i = 0; i < num_listenaddrs; i++) { /* setup the main listening socket */ listen_socket[num_sockets] = do_listen(SOCK_STREAM, proto, &listenaddrs[i]); if (listen_socket[num_sockets] == -1) { if (o.debug > 0) logdebug("do_listen(\"%s\"): %s\n", inet_ntop_ez(&listenaddrs[i].storage, sizeof(listenaddrs[i].storage)), socket_strerror(socket_errno())); continue; } /* Make our listening socket non-blocking because there are timing issues * which could cause us to block on accept() even though select() says it's * readable. See UNPv1 2nd ed, p422 for more. */ unblock_socket(listen_socket[num_sockets]); /* setup select sets and max fd */ FD_SET(listen_socket[num_sockets], &master_readfds); add_fd(&client_fdlist, listen_socket[num_sockets]); FD_SET(listen_socket[num_sockets], &listen_fds); num_sockets++; } if (num_sockets == 0) { if (num_listenaddrs == 1) bye("Unable to open listening socket on %s: %s", inet_ntop_ez(&listenaddrs[0].storage, sizeof(listenaddrs[0].storage)), socket_strerror(socket_errno())); else bye("Unable to open any listening sockets."); } add_fd(&client_fdlist, STDIN_FILENO); init_fdlist(&broadcast_fdlist, o.conn_limit); if (o.idletimeout > 0) tvp = &tv; while (1) { /* We pass these temporary descriptor sets to fselect, since fselect modifies the sets it receives. */ fd_set readfds = master_readfds, writefds = master_writefds; struct fdinfo *fdi = NULL; if (o.debug > 1) logdebug("selecting, fdmax %d\n", client_fdlist.fdmax); if (o.debug > 1 && o.broker) logdebug("Broker connection count is %d\n", get_conn_count()); if (o.idletimeout > 0) ms_to_timeval(tvp, o.idletimeout); fds_ready = fselect(client_fdlist.fdmax + 1, &readfds, &writefds, NULL, tvp); if (o.debug > 1) logdebug("select returned %d fds ready\n", fds_ready); if (fds_ready == 0) bye("Idle timeout expired (%d ms).", o.idletimeout); /* * FIXME: optimize this loop to look only at the fds in the fd list, * doing it this way means that if you have one descriptor that is very * large, say 500, and none close to it, that you'll loop many times for * nothing. */ for (i = 0; i <= client_fdlist.fdmax && fds_ready > 0; i++) { /* Loop through descriptors until there's something to read */ if (!FD_ISSET(i, &readfds) && !FD_ISSET(i, &writefds)) continue; if (o.debug > 1) logdebug("fd %d is ready\n", i); #ifdef HAVE_OPENSSL /* Is this an ssl socket pending a handshake? If so handle it. */ if (o.ssl && FD_ISSET(i, &sslpending_fds)) { FD_CLR(i, &master_readfds); FD_CLR(i, &master_writefds); fdi = get_fdinfo(&client_fdlist, i); ncat_assert(fdi != NULL); switch (ssl_handshake(fdi)) { case NCAT_SSL_HANDSHAKE_COMPLETED: /* Clear from sslpending_fds once ssl is established */ FD_CLR(i, &sslpending_fds); post_handle_connection(*fdi); break; case NCAT_SSL_HANDSHAKE_PENDING_WRITE: FD_SET(i, &master_writefds); break; case NCAT_SSL_HANDSHAKE_PENDING_READ: FD_SET(i, &master_readfds); break; case NCAT_SSL_HANDSHAKE_FAILED: default: SSL_free(fdi->ssl); Close(fdi->fd); FD_CLR(i, &sslpending_fds); FD_CLR(i, &master_readfds); rm_fd(&client_fdlist, i); /* Are we in single listening mode(without -k)? If so then we should quit also. */ if (!o.keepopen && !o.broker) return 1; --conn_inc; break; } } else #endif if (FD_ISSET(i, &listen_fds)) { /* we have a new connection request */ handle_connection(i); } else if (i == STDIN_FILENO) { if (o.broker) { read_and_broadcast(i); } else { /* Read from stdin and write to all clients. */ rc = read_stdin(); if (rc == 0) { if (o.proto != IPPROTO_TCP || (o.proto == IPPROTO_TCP && o.sendonly)) { /* There will be nothing more to send. If we're not receiving anything, we can quit here. */ return 0; } if (!o.noshutdown) shutdown_sockets(SHUT_WR); } if (rc < 0) return 1; } } else if (!o.sendonly) { if (o.broker) { read_and_broadcast(i); } else { /* Read from a client and write to stdout. */ rc = read_socket(i); if (rc <= 0 && !o.keepopen) return rc == 0 ? 0 : 1; } } fds_ready--; } } return 0; }
/* Fonction exécutée par un thread. */ void *treat_sockets(void* ptr) { int thread_id = *(int*)ptr; int sockfd, message_length, file_hash, peer_id ; int i,tmp; char message_id ; u_int s_name, file_name ; /* Buffer d'entrées sortie alloué une seule fois. */ char *io_buff = (char*) malloc(max_piecelength*sizeof(char)) ; while(1) { sockfd = pop(request) ; if(quit_program) break ; s_name = get_name(socket_map,(u_int)sockfd) ; file_hash = (int)socket_to_file[s_name] ; peer_id = (int)socket_to_peer[s_name] ; file_name = get_name(file_map,(u_int)file_hash) ; if(-1==read_socket(sockfd,(char*)&message_length,sizeof(int))) { /* pair déconnecté, on le supprime */ pthread_mutex_lock(&torrent_list[file_name]->peerlist->lock); for(i = 0 ; i < torrent_list[file_name]->peerlist->nbPeers ; i++) if(torrent_list[file_name]->peerlist->pentry[i].peerId == (u_int)peer_id) break ; assert(i < torrent_list[file_name]->peerlist->nbPeers); tmp=i; deletepeer(&torrent_list[file_name]->peerlist->pentry[i]); printf("Peer %d does not respond anymore. Deleted from list.\n",peer_id); for(i=tmp;i< torrent_list[file_name]->peerlist->nbPeers-1 ; i++) { torrent_list[file_name]->peerlist->pentry[i] = torrent_list[file_name]->peerlist->pentry[i+1] ; } torrent_list[file_name]->peerlist->nbPeers--; pthread_mutex_unlock(&torrent_list[file_name]->peerlist->lock); continue ; } assert_read_socket(sockfd,&message_id,sizeof(char)) ; switch(message_id) { case KEEP_ALIVE : pthread_mutex_lock(&print_lock) ; blue(); printf("Received KEEP_ALIVE from peer %d (file %s)\n",peer_id,torrent_list[file_name]->torrent->filename); normal() ; printf("\t\t\t\t\t\tNOT YET IMPLEMENTED.\n"); pthread_mutex_unlock(&print_lock) ; break ; case HAVE: read_have(peers[s_name],torrent_list[file_name]->torrent,thread_id); break ; case BIT_FIELD: read_bitfield(peers[s_name],torrent_list[file_name]->torrent,message_length,thread_id); break ; case REQUEST: read_request(peers[s_name],torrent_list[file_name]->torrent,io_buff,thread_id); break ; case PIECE: read_piece(peers[s_name],torrent_list[file_name]->torrent,torrent_list[file_name]->peerlist,message_length,io_buff,thread_id) ; break ; case CANCEL: pthread_mutex_lock(&print_lock) ; blue(); printf("Received CANCEL from peer %d (file %s)\n",peer_id,torrent_list[file_name]->torrent->filename); normal() ; printf("\t\t\t\t\t\tNOT YET IMPLEMENTED.\n"); assert_read_socket(sockfd,&tmp,sizeof(u_int)) ; assert_read_socket(sockfd,&tmp,sizeof(u_int)) ; assert_read_socket(sockfd,&tmp,sizeof(u_int)) ; pthread_mutex_unlock(&print_lock) ; break ; default : blue(); printf("Error, unknown message (id %d).\n",(int)message_id) ; normal() ; printf("\n"); exit(EXIT_FAILURE) ; break; } pthread_mutex_lock(&handled_request->lock) ; handled_request->queue[handled_request->last] = sockfd ; handled_request->last = (handled_request->last+1)%N_SOCK ; pthread_mutex_unlock(&handled_request->lock) ; } free(io_buff); pthread_mutex_lock(&print_lock) ; green(); printf("[#%d thread]\t\t",thread_id); normal(); printf("will quit.\n") ; pthread_mutex_unlock(&print_lock) ; pthread_exit(ptr); }
int socket2uart( Socket2Uart *socket_to_uart ) { char buffer[BUF_SIZE]; socket_to_uart->relay_thread_handle = -1; socket_to_uart->listen_fd = -1; socket_to_uart->connect_fd = -1; pthread_cond_init( &socket_to_uart->condSocket2Uart , 0 ); pthread_mutex_init( &socket_to_uart->mutexSocket2Uart , 0); while(1) { socket_to_uart->connect_fd = start_tcp_server( &socket_to_uart->listen_fd , socket_to_uart->port ); if ( socket_to_uart->relay_thread_handle == -1 ) pthread_create( &socket_to_uart->relay_thread_handle , 0 , relay_uart_to_socket , socket_to_uart ); if ( DisconnectIfNoPermit( socket_to_uart ) == 0 ) { printf_debug( "no permit, maybe ExecuteSeriesCommand take long time\n" ); continue; } if ( socket_to_uart->connect_fd < 0 ) { printf_error( "the listen socket error\n" ); continue; } socket2uart_SetReconnected( socket_to_uart ); do{ if ( DisconnectIfNoPermit( socket_to_uart ) == 0 ) { printf_debug( "socket2uart too long\n" ); break; } int read_size; read_size = read_socket( socket_to_uart->connect_fd , buffer ); if ( read_size < 0 ) break; else if ( read_size == 0 ) { printf_debug( "read socket[%d] time out\n" , socket_to_uart->connect_fd ); break; } if ( debug ) { printf_debug( "socket[%d] >>>\n" , socket_to_uart->connect_fd ); printData( buffer , read_size , "" , 1 ); } if ( CPAP_send( 0 , buffer , read_size ) >= 0 ) { //note the uart-to-socket thread to read uart pthread_mutex_lock( &socket_to_uart->mutexSocket2Uart ); pthread_cond_signal( &socket_to_uart->condSocket2Uart ); pthread_mutex_unlock( &socket_to_uart->mutexSocket2Uart ); } else { char *uart_open_failed="FAILED\nCPAP open error\n"; write( socket_to_uart->connect_fd , uart_open_failed , strlen(uart_open_failed) ); } }while(1); socket2uart_CloseClient( socket_to_uart ); } }
int shell(void) { fd_set readset; FD_ZERO(&g_context.readsave); if(g_verbose) { fprintf(stderr, "Opening connection to %s port %d\n", g_context.args.ip, g_context.args.port); } if((g_context.sock = connect_to(g_context.args.ip, g_context.args.port)) < 0) { return 1; } if(g_context.args.notty == 0) { if((g_context.outsock = connect_to(g_context.args.ip, g_context.args.port+2)) < 0) { fprintf(stderr, "Could not connect to stdout channel\n"); } if((g_context.errsock = connect_to(g_context.args.ip, g_context.args.port+3)) < 0) { fprintf(stderr, "Could not connect to stderr channel\n"); } } /* if((g_context.fssock == connect_to(g_context.args.ip, g_context.args.port+8)) < 0) { fprintf(stderr, "Could not connect to fs admin channel\n"); } */ if(!g_context.args.script) { init_readline(); read_history(g_context.history_file); history_set_pos(history_length); FD_SET(STDIN_FILENO, &g_context.readsave); } /* Change to the current directory, should return our path */ execute_line("cd ."); while(!g_context.exit) { int ret; readset = g_context.readsave; ret = select(FD_SETSIZE, &readset, NULL, NULL, NULL); if(ret < 0) { if(errno == EINTR) { continue; } perror("select"); break; } else if(ret == 0) { continue; } else { if(!g_context.args.script) { if(FD_ISSET(STDIN_FILENO, &readset)) { rl_callback_read_char(); } } if(FD_ISSET(g_context.sock, &readset)) { /* Do read */ if(read_socket(g_context.sock) < 0) { close(g_context.sock); g_context.sock = -1; break; } } if((g_context.outsock >= 0) && FD_ISSET(g_context.outsock, &readset)) { if(read_outsocket(g_context.outsock) < 0) { FD_CLR(g_context.outsock, &g_context.readsave); close(g_context.outsock); g_context.outsock = -1; } } if((g_context.errsock >= 0) && FD_ISSET(g_context.errsock, &readset)) { if(read_errsocket(g_context.errsock) < 0) { FD_CLR(g_context.errsock, &g_context.readsave); close(g_context.errsock); g_context.errsock = -1; } } if((g_context.fssock >= 0) && FD_ISSET(g_context.fssock, &readset)) { if(read_fssocket(g_context.fssock) < 0) { FD_CLR(g_context.fssock, &g_context.readsave); close(g_context.fssock); g_context.fssock = -1; } } } } if(!g_context.args.script) { write_history(g_context.history_file); rl_callback_handler_remove(); } return 0; }
int main(int argc, char **argv) { int i; int wrapper = 0; int ext_wrapper = 0; int kwrapper = 0; long arg_count; long env_count; klauncher_header header; char *start, *p, *buffer; char cwd[8192]; const char *tty = NULL; long avoid_loops = 0; const char* startup_id = NULL; int sock; long size = 0; start = argv[0]; p = start + strlen(argv[0]); while (--p > start) { if (*p == '/') break; } if ( p > start) p++; start = p; if (strcmp(start, "kdeinit_wrapper") == 0) wrapper = 1; else if (strcmp(start, "kshell") == 0) ext_wrapper = 1; else if (strcmp(start, "kwrapper") == 0) kwrapper = 1; else if (strcmp(start, "kdeinit_shutdown") == 0) { if( argc > 1) { fprintf(stderr, "Usage: %s\n\n", start); fprintf(stderr, "Shuts down kdeinit master process and terminates all processes spawned from it.\n"); exit( 255 ); } sock = openSocket(); if( sock < 0 ) { fprintf( stderr, "Error: Can't contact kdeinit!\n" ); exit( 255 ); } header.cmd = LAUNCHER_TERMINATE_KDE; header.arg_length = 0; write_socket(sock, (char *) &header, sizeof(header)); read_socket(sock, (char *) &header, 1); /* wait for the socket to close */ return 0; } if (wrapper || ext_wrapper || kwrapper) { argv++; argc--; if (argc < 1) { fprintf(stderr, "Usage: %s <application> [<args>]\n", start); exit(255); /* usage should be documented somewhere ... */ } start = argv[0]; } sock = openSocket(); if( sock < 0 ) /* couldn't contact kdeinit, start argv[ 0 ] directly */ { execvp( argv[ 0 ], argv ); fprintf( stderr, "Error: Can't run %s !\n", argv[ 0 ] ); exit( 255 ); } if( !wrapper && !ext_wrapper && !kwrapper ) { /* was called as a symlink */ avoid_loops = 1; #if defined(WE_ARE_KWRAPPER) kwrapper = 1; #elif defined(WE_ARE_KSHELL) ext_wrapper = 1; #else wrapper = 1; #endif } arg_count = argc; size += sizeof(long); /* Number of arguments*/ size += strlen(start)+1; /* Size of first argument. */ for(i = 1; i < argc; i++) { size += strlen(argv[i])+1; } if( wrapper ) { size += sizeof(long); /* empty envs */ } if (ext_wrapper || kwrapper) { if (!getcwd(cwd, 8192)) cwd[0] = '\0'; size += strlen(cwd)+1; env_count = 0; size += sizeof(long); /* Number of env.vars. */ for(; environ[env_count] ; env_count++) { int l = strlen(environ[env_count])+1; size += l; } if( kwrapper ) { tty = ttyname(1); if (!tty || !isatty(2)) tty = ""; size += strlen(tty)+1; } } size += sizeof( avoid_loops ); if( !wrapper ) { startup_id = getenv( "DESKTOP_STARTUP_ID" ); if( startup_id == NULL ) startup_id = ""; size += strlen( startup_id ) + 1; } if (wrapper) header.cmd = LAUNCHER_EXEC_NEW; else if (kwrapper) header.cmd = LAUNCHER_KWRAPPER; else header.cmd = LAUNCHER_SHELL; header.arg_length = size; write_socket(sock, (char *) &header, sizeof(header)); buffer = (char *) malloc(size); if (buffer == NULL) { fprintf(stderr, "Error: malloc() failed."); exit(255); } p = buffer; memcpy(p, &arg_count, sizeof(arg_count)); p += sizeof(arg_count); memcpy(p, start, strlen(start)+1); p += strlen(start)+1; for(i = 1; i < argc; i++) { memcpy(p, argv[i], strlen(argv[i])+1); p += strlen(argv[i])+1; } if( wrapper ) { long dummy = 0; memcpy(p, &dummy, sizeof(dummy)); /* empty envc */ p+= sizeof( dummy ); } if (ext_wrapper || kwrapper) { memcpy(p, cwd, strlen(cwd)+1); p+= strlen(cwd)+1; memcpy(p, &env_count, sizeof(env_count)); p+= sizeof(env_count); for(i = 0; i < env_count; i++) { int l = strlen(environ[i])+1; memcpy(p, environ[i], l); p += l; } if( kwrapper ) { memcpy(p, tty, strlen(tty)+1); p+=strlen(tty)+1; } } memcpy( p, &avoid_loops, sizeof( avoid_loops )); p += sizeof( avoid_loops ); if( !wrapper ) { memcpy(p, startup_id, strlen(startup_id)+1); p+= strlen(startup_id)+1; } if( p - buffer != size ) /* should fail only if you change this source and do */ /* a stupid mistake, it should be assert() actually */ { fprintf(stderr, "Oops. Invalid format.\n"); exit(255); } write_socket(sock, buffer, size); free( buffer ); if (read_socket(sock, (char *) &header, sizeof(header))==-1) { fprintf(stderr, "Communication error with KInit.\n"); exit(255); } if (header.cmd == LAUNCHER_OK) { long pid; buffer = (char *) malloc(header.arg_length); if (buffer == NULL) { fprintf(stderr, "Error: malloc() failed\n"); exit(255); } read_socket(sock, buffer, header.arg_length); pid = *((long *) buffer); if( !kwrapper ) /* kwrapper shouldn't print any output */ printf("Launched ok, pid = %ld\n", pid); else kwrapper_run( pid ); } else if (header.cmd == LAUNCHER_ERROR) { fprintf(stderr, "KInit could not launch '%s'.\n", start); exit(255); } else { fprintf(stderr, "Unexpected response from KInit (response = %ld).\n", header.cmd); exit(255); } exit(0); }
void *functionGetStatus( void *param ) { Socket2Uart *socket_to_uart=( Socket2Uart *)param; int listen_fd=-1; int connect_fd; char buffer[1024]; while(1) { connect_fd = start_tcp_server( &listen_fd , PORT_OF_GETSTATUS ); if ( connect_fd < 0 ) { printf_error( "GetStatus:the listen socket error\n" ); continue; } int read_size; read_size = read_socket( connect_fd , buffer ); if ( read_size < 0 ) { printf_error( "GetStatus:read socket error\n" ); continue; } else if ( read_size == 0 ) { printf_debug( "GetStatus:read socket[%d] time out\n" , connect_fd ); continue; } if ( debug ) { printf_debug( "GetStatus:socket[%d] >>>\n" , connect_fd ); if ( read_size > 0 ) printData( buffer , read_size , "" , 1 ); } char status_string[128]; if ( strstr( buffer , "status" ) ) { socket2uart_GetStatusString( socket_to_uart , status_string , sizeof( status_string )); if ( debug ) { printf_debug( "socket[%d] <<<\n" , connect_fd ); printData( status_string , strlen( status_string ) , "" , 0 ); } char output_status[256]; if ( strlen( status_string ) > 0 ) { snprintf( output_status , sizeof(output_status) , "STATUS\n%s" , status_string ); } else { snprintf( output_status , sizeof(output_status) , "FAILED\nPAP is not connected\n" ); } write( connect_fd , output_status , strlen( output_status )); } close( connect_fd ); } return 0; }
int handle_client_connection() { char buffer[8096]; int buffer_len; // Length of buffer char method[256]; char url[256]; char version[256]; int i = 0, // Used to iterate over the first line to get method, url, version j = 0; // Read first line buffer_len = read_line(client_sockfd, buffer, sizeof(buffer)); // Unable to read from socket, not sure what to do in this case if (buffer_len <= 0) { return -1; } fprintf(stderr, "==== Read Next Request ====\n"); // Get Method (e.g. GET, POST, etc) while ((i < (sizeof(method) - 1)) && (!isspace(buffer[i]))) { method[i] = buffer[i]; i++; } method[i] = '\0'; // fprintf(stderr, "method: %s\n", method); // Skip over spaces while (i < buffer_len && isspace(buffer[i])) { i++; } // Get URL j = 0; while (i < buffer_len && (j < (sizeof(url) - 1)) && !isspace(buffer[i])) { url[j] = buffer[i]; i++; j++; } url[j] = '\0'; // fprintf(stderr, "url: %s\n", url); // Skip over spaces while (i < buffer_len && isspace(buffer[i])) { i++; } j = 0; while (j < sizeof(version) - 1 && !isspace(buffer[i])) { version[j] = buffer[i]; i++; j++; } version[j] = '\0'; // fprintf(stderr, "version: %s\n", version); read_headers(); if (header_err_flag) { keep_alive = FALSE; bad_request(); return -1; } if (content_length > 0) { content = (char*) malloc(content_length + 1); read_socket(client_sockfd, content, content_length); } // fprintf(stderr, "Content-Length: %d\n", content_length); // fprintf(stderr, "Connection (keep_alive): %d\n", keep_alive); // fprintf(stderr, "Cookie: %d\n", cookie); // fprintf(stderr, "If-Modified-Since Valid Time: %d\n", time_is_valid); // fprintf(stderr, "If-Modified-Since Time: %p\n", if_modified_since); if (content != NULL) { // fprintf(stderr, "Content: %s\n", content); } /***********************************************************/ /* Full message has been read, respond to client */ /***********************************************************/ if (strcmp(method, "GET") != 0) { // Inform client we don't support method fprintf(stderr, "Method Not Allowed: %s\n", method); method_not_allowed(); return 0; } if (cookie) { // Inform client we don't support cookies not_implemented(); return 0; } if (not_eng) { // Inform client we only support English not_implemented(); return 0; } if (!acceptable_text) { // Inform client we only support plain text not_implemented(); return 0; } if (!acceptable_charset) { // Inform client we only support ASCII not_implemented(); return 0; } // Fix filename char file_path[512]; sprintf(file_path, "htdocs%s", url); if (file_path[strlen(file_path)-1] == '/') { file_path[strlen(file_path)-1] = '\0'; } // fprintf(stderr, "%s\n", file_path); int fname_valid = is_valid_fname(file_path); struct stat file_info; if (!fname_valid) { // invalid filename fprintf(stderr, "403 Forbidden: Invalid file name\n"); forbidden(); return 0; } if (stat(file_path, &file_info)) { fprintf(stderr, "404 Not Found: Stat failed\n"); // Stat failed not_found(); return 1; } if (!S_ISREG(file_info.st_mode)) { // Not a file forbidden(); fprintf(stderr, "403 Forbidden: Not a regular file\n"); return 0; } if (!(file_info.st_mode & S_IRUSR)) { // No read permissions forbidden(); fprintf(stderr, "403 Forbidden: No read permissions\n"); return 0; } FILE *f = fopen(file_path, "r"); if (f == NULL) { // No file not_found(); fprintf(stderr, "404 Not Found: Unable to open file\n"); return 0; } if (if_modified_since != NULL) { struct tm *last_modified = gmtime(&file_info.st_mtime); time_t last = mktime(last_modified); time_t since = mktime(if_modified_since); double diff = difftime(last, since); if (diff <= 0) { fprintf(stderr, "304 Not Modified\n"); not_modified(); return 0; } } fprintf(stderr, "All looks good, serving up content in %s\n", file_path); char *file_contents = NULL; int contents_length = 0; char line[512]; while (fgets(line, sizeof(line), f) != NULL) { if (file_contents != NULL) { char *new_contents = (char*) malloc(contents_length + strlen(line) + 1); strcpy(new_contents, file_contents); strcpy(new_contents + strlen(new_contents), line); contents_length += strlen(line); free(file_contents); file_contents = new_contents; } else { file_contents = (char*) malloc(strlen(line) + 1); strcpy(file_contents, line); contents_length += strlen(line); } } fclose(f); // fprintf(stderr, "File Contents:\n"); // fprintf(stderr, "%s\n", file_contents); ok(file_contents); return 0; }