int riack_connect(struct RIACK_CLIENT *client, const char* host, int port, struct RIACK_CONNECTION_OPTIONS* options) { client->sockfd = sock_open(host, port); if (client->sockfd > 0) { if (client->host && host != client->host) { RFREE(client, client->host); } if (host != client->host) { client->host = (char*)RMALLOC(client, strlen(host)+1); strcpy(client->host, host); } client->port = port; if (options) { client->options = *options; if (!sock_set_timeouts(client->sockfd, options->recv_timeout_ms, options->send_timeout_ms)) { sock_close(client->sockfd); client->sockfd = -1; // TODO set last error } } return RIACK_SUCCESS; } return RIACK_ERROR_COMMUNICATION; }
void *mon_run() { static struct timespec starttime, endtime; char buffer[BUFSIZE]; struct sockaddr saddr; if (sock_open()) return 0; if (sock_bind(monifname)) return 0; state = 1; while(state == 1) { socklen_t saddr_size = sizeof saddr; int size = recvfrom(sock, buffer, BUFSIZE, 0, &saddr, &saddr_size); struct wframe * frame = buffertowframe(buffer, size); if (frame == NULL) continue; if(frame->stype == IEEE80211_STYPE_PROBE_REQ) clock_gettime(CLOCK_MONOTONIC, &starttime); if(frame->stype == IEEE80211_STYPE_PROBE_RESP) { clock_gettime(CLOCK_MONOTONIC, &endtime); struct timespec ts = tsdiff(starttime, endtime); printf("Probe Reponse Time: %ld usec\n", ts.tv_sec * 1000 * 1000 + ts.tv_nsec / 1000); state = 2; } free(frame); } state = 2; }
int lwip_socket(int domain, int type, int protocol) { int s, fd; // We only support basic internet protocols if (domain != AF_INET || protocol != 0 || (type != SOCK_STREAM && type != SOCK_DGRAM)) { errno = EPROTONOSUPPORT; return -1; } // Allocate a new socket for it s = sock_open(); if (s < 0) { errno = ENFILE; return -1; } fds[s].type = type; // Make a VFS socket for it fd = fs_open_handle(&socketvfs, (void *)(s+1)); if (fd < 0) { sock_close(s); } return fd; }
static ERL_NIF_TERM getsockfd(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { int fd; fd = sock_open(AF_INET, SOCK_STREAM, 0); return enif_make_int(env, fd); }
int try_connect_HELO(const char *hostname) { char dbg_hostname[BIG_BUF]; char dbg_version[BIG_BUF]; char buf[BIG_BUF]; char testme[BIG_BUF]; /* Try the HELO protocal */ if(my_socket != -1) sock_close(my_socket); if (sock_open(get_string("mailserver"), get_number("smtp-socket", 25), &my_socket)) return 0; if (sock_readline(my_socket, buf, sizeof(buf)) == 0) return 0; if(!sscanf(buf,"220 %s %s", &dbg_hostname[0], &dbg_version[0])) return 0; log_printf(9, "Connected: %s (%s)\n", dbg_hostname, dbg_version); sock_printf(my_socket, "HELO %s\r\n", hostname); if(sock_readline(my_socket, buf, sizeof(buf)) == 0) return 0; if(!sscanf(buf, "250 %s", testme)) return 0; return 1; }
void Client(char *Address, char *Port, int AddressFamily, int TransportProtocol) { char ErrBuf[1024]; char DataBuffer[1024]; int ClientSocket; // keeps the socket ID for this connection struct addrinfo Hints; // temporary struct to keep settings needed to open the new socket struct addrinfo *AddrInfo; // keeps the addrinfo chain; required to open a new socket int WrittenBytes; // Number of bytes written on the socket // Prepare to open a new server socket memset(&Hints, 0, sizeof(struct addrinfo)); Hints.ai_family= AddressFamily; Hints.ai_socktype= TransportProtocol; // Open a TCP or UDP connection if (sock_initaddress (Address, Port, &Hints, &AddrInfo, ErrBuf, sizeof(ErrBuf)) == sockFAILURE) { printf("Error resolving given address/port: %s\n\n", ErrBuf); return; } printf("Trying to connect to server on address %s, port %s, using protocol %s\n", Address ? Address : "all local addresses", Port, (AddrInfo->ai_family == AF_INET) ? "IPv4" : "IPv6"); if ( (ClientSocket= sock_open(AddrInfo, 0, 0, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); printf("Cannot opening the socket: %s\n\n", ErrBuf); return; } // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); printf("Connection established.\n"); printf("Type the string you want to send to the server: "); // Warning: possible buffer overflow here fgets(DataBuffer, sizeof(DataBuffer), stdin); // fgets reads also the newline character, so we have to reset it DataBuffer[strlen(DataBuffer) - 1]= 0; printf("\n\n"); WrittenBytes= sock_send(ClientSocket, DataBuffer, strlen(DataBuffer), ErrBuf, sizeof(ErrBuf)); if (WrittenBytes == sockFAILURE) { printf("Error sending data: %s\n\n", ErrBuf); return; } printf("String '%s' sent. Press ENTER to terminate the program\n", DataBuffer); fgets(DataBuffer, sizeof(DataBuffer), stdin); }
void main(int argc, char **argv) { int sock, i, ctr, k; int on = 1; struct sockaddr_in addrs; if (argc < 3) { printf("Usage: %s <ip_addr> <port>\n", argv[0]); exit(-1); } for (i = 0; i < 1002; i++) { icmph.text[i] = random() % 255; } sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char *)&on, sizeof(on)) == -1) { perror("Can't set IP_HDRINCL option on socket"); } if (sock < 0) { exit(-1); } fflush(stdout); for (ctr = 0;ctr < 1001;ctr++) { ctr = ctr % 1000; addrs = sock_open(argv[1], sock, atoi(argv[2])); icmph.iph.version = 4; icmph.iph.ihl = 6; icmph.iph.tot_len = 1024; icmph.iph.id = htons(0x001); icmph.iph.ttl = 255; icmph.iph.protocol = IPPROTO_ICMP; icmph.iph.saddr = ((random() % 255) * 255 * 255 * 255) + ((random() % 255) * 65535) + ((random() % 255) * 255) + (random() % 255); icmph.iph.daddr = addrs.sin_addr.s_addr; icmph.iph.frag_off = htons(0); icmph.icp.icmp_type = random() % 14; icmph.icp.icmp_code = random() % 10; icmph.icp.icmp_cksum = 0; icmph.icp.icmp_id = 2650; icmph.icp.icmp_seq = random() % 255; icmph.icp.icmp_cksum = in_cksum((int *)&icmph.icp, 1024); if (sendto(sock, &icmph, 1024, 0, (struct sockaddr *)&addrs,sizeof(struct sockaddr)) == -1) { if (errno != ENOBUFS) printf("X"); } if (ctr == 0) printf("b00m "); fflush(stdout); } close(sock); }
sock_t sock_connect_non_blocking (const char *hostname, unsigned port) { sock_t sock; sock = sock_open (AF_INET, SOCK_STREAM, 0); if (sock == SOCK_ERROR) return SOCK_ERROR; sock_set_blocking (sock, 0); sock_try_connection (sock, hostname, port); return sock; }
sock_t sock_get_server_socket (int port, const char *sinterface) { struct sockaddr_storage sa; struct addrinfo hints, *res, *ai; char service [10]; int sock; if (port < 0) return SOCK_ERROR; memset (&sa, 0, sizeof(sa)); memset (&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG | AI_NUMERICSERV | AI_NUMERICHOST; hints.ai_socktype = SOCK_STREAM; snprintf (service, sizeof (service), "%d", port); if (getaddrinfo (sinterface, service, &hints, &res)) return SOCK_ERROR; ai = res; do { int on = 1; int type = ai->ai_socktype; sock = sock_open (ai->ai_family, type, ai->ai_protocol); if (sock < 0) continue; setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)); on = 0; #ifdef IPV6_V6ONLY setsockopt (sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&on, sizeof on); #endif if (bind (sock, ai->ai_addr, ai->ai_addrlen) < 0) { sock_close (sock); continue; } freeaddrinfo (res); return sock; } while ((ai = ai->ai_next)); freeaddrinfo (res); return SOCK_ERROR; }
/* sock_get_server_socket ** ** create a socket for incoming requests on a specified port and ** interface. if interface is null, listen on all interfaces. ** returns the socket, or SOCK_ERROR on failure */ sock_t sock_get_server_socket(int port, const char *sinterface) { struct sockaddr_in sa; int error, opt; sock_t sock; char ip[MAX_ADDR_LEN]; if (port < 0) return SOCK_ERROR; /* defaults */ memset(&sa, 0, sizeof(sa)); /* set the interface to bind to if specified */ if (sinterface != NULL) { if (!resolver_getip(sinterface, ip, sizeof (ip))) return SOCK_ERROR; if (!inet_aton(ip, &sa.sin_addr)) { return SOCK_ERROR; } else { sa.sin_family = AF_INET; sa.sin_port = htons((short)port); } } else { sa.sin_addr.s_addr = INADDR_ANY; sa.sin_family = AF_INET; sa.sin_port = htons((short)port); } /* get a socket */ sock = sock_open (AF_INET, SOCK_STREAM, 0); if (sock == -1) return SOCK_ERROR; sock_set_cloexec (sock); /* reuse it if we can */ opt = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(int)); /* bind socket to port */ error = bind(sock, (struct sockaddr *)&sa, sizeof (struct sockaddr_in)); if (error == -1) return SOCK_ERROR; return sock; }
sock_t sock_connect_wto_bind (const char *hostname, int port, const char *bnd, int timeout) { sock_t sock; sock = sock_open (AF_INET, SOCK_STREAM, 0); if (sock == SOCK_ERROR) return SOCK_ERROR; if (bnd) { struct sockaddr_in sa; memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; if (inet_aton (bnd, &sa.sin_addr) == 0 || bind (sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) { sock_close (sock); return SOCK_ERROR; } } if (timeout) { sock_set_blocking (sock, 0); if (sock_try_connection (sock, hostname, port) < 0) { int ret = sock_connected (sock, timeout); if (ret <= 0) { sock_close (sock); return SOCK_ERROR; } } sock_set_blocking(sock, 1); } else { if (sock_try_connection (sock, hostname, port) < 0) { sock_close (sock); sock = SOCK_ERROR; } } return sock; }
void dstate_init(const char *prog, const char *devname) { char sockname[SMALLBUF]; /* do this here for now */ signal(SIGPIPE, SIG_IGN); if (devname) { snprintf(sockname, sizeof(sockname), "%s/%s-%s", dflt_statepath(), prog, devname); } else { snprintf(sockname, sizeof(sockname), "%s/%s", dflt_statepath(), prog); } sockfd = sock_open(sockname); upsdebugx(2, "dstate_init: sock %s open on fd %d", sockname, sockfd); }
void main(int argc, char **argv) { int sock, i,k; int on = 1; struct sockaddr_in addrs; printf("\t\tTCPDumper Ver 0.2 \n\t\t\tBy Bladi\n"); if (argc < 3) { printf("Uso: %s <ip_spoof> <dest_ip> \n", argv[0]); exit(-1); } encaps.text[0]=66; encaps.text[1]=76; encaps.text[2]=65; encaps.text[3]=68; encaps.text[4]=73; encaps.text[5]=32; encaps.text[6]=84; encaps.text[7]=90; encaps.text[8]=32; encaps.text[9]=84; encaps.text[10]=79;encaps.text[11]=32; encaps.text[12]=84;encaps.text[13]=79;encaps.text[14]=80;encaps.text[15]=79; sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char *)&on, sizeof(on)) == -1) { perror("Can't set IP_HDRINCL option on socket"); } if (sock < 0) { exit(-1); } fflush(stdout); addrs = sock_open(sock, argv[2], random() % 255); encaps.iph.version = 0; encaps.iph.ihl = 0; encaps.iph.frag_off = htons(0); encaps.iph.id = htons(0x001); encaps.iph.protocol = 4; encaps.iph.ttl = 146; encaps.iph.tot_len = 6574; encaps.iph.daddr = addrs.sin_addr.s_addr; encaps.iph.saddr = inet_addr(argv[1]); printf ("\t DuMpInG %s ---> %s \n",argv[1],argv[2]); if (sendto(sock, &encaps, 1204, 0, (struct sockaddr *)&addrs, sizeof(struct sockaddr)) == -1) { if (errno != ENOBUFS) printf("Error :(\n"); } fflush(stdout); close(sock); }
sock_t sock_connect_non_blocking (const char *hostname, unsigned port) { int sock = SOCK_ERROR; struct addrinfo *ai, *head, hints; char service[8]; memset (&hints, 0, sizeof (hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; snprintf (service, sizeof (service), "%u", port); if (getaddrinfo (hostname, service, &hints, &head)) return SOCK_ERROR; ai = head; while (ai) { int type = ai->ai_socktype; if ((sock = sock_open (ai->ai_family, type, ai->ai_protocol)) > -1) { sock_set_cloexec(sock); sock_set_blocking (sock, 0); if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 && !sock_connect_pending(sock_error())) { sock_close (sock); sock = SOCK_ERROR; } else break; } ai = ai->ai_next; } if (head) freeaddrinfo (head); return sock; }
/* \param plen: the length of the current message (needed in order to be able to discard excess data in the message, if present) */ pcap_t *daemon_startcapture(SOCKET sockctrl, pthread_t *threaddata, char *source, int active, struct rpcap_sampling *samp_param, uint32 plen, char *errbuf) { char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer pcap_t *fp= NULL; // pcap_t main variable unsigned int nread; // number of bytes of the payload read from the socket char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx= 0; // index which keeps the number of bytes currently buffered // socket-related variables SOCKET sockdata= 0; // socket descriptor of the data connection struct addrinfo hints; // temp, needed to open a socket connection struct addrinfo *addrinfo; // temp, needed to open a socket connection struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine pthread_attr_t detachedAttribute; // temp, needed to set the created thread as detached // RPCAP-related variables struct rpcap_startcapreq startcapreq; // start capture request message struct rpcap_startcapreply *startcapreply; // start capture reply message int serveropen_dp; // keeps who is going to open the data connection addrinfo= NULL; if ( (nread= sock_recv(sockctrl, (char *) &startcapreq, sizeof(struct rpcap_startcapreq), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) return NULL; startcapreq.flags= ntohs(startcapreq.flags); // Open the selected device if ( (fp= pcap_open(source, ntohl(startcapreq.snaplen), (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? PCAP_OPENFLAG_PROMISCUOUS : 0 /* local device, other flags not needed */, ntohl(startcapreq.read_timeout), NULL /* local device, so no auth */, errbuf)) == NULL) { rpcap_senderror(sockctrl, errbuf, PCAP_ERR_OPEN, NULL); return NULL; } // Apply sampling parameters fp->rmt_samp.method= samp_param->method; fp->rmt_samp.value= samp_param->value; /* We're in active mode if: - we're using TCP, and the user wants us to be in active mode - we're using UDP */ serveropen_dp= (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || active; /* Gets the sockaddr structure referred to the other peer in the ctrl connection We need that because: - if we're in passive mode, we need to know the address family we want to use (the same used for the ctrl socket) - if we're in active mode, we need to know the network address of the other host we want to connect to */ saddrlen = sizeof(struct sockaddr_storage); if (getpeername(sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getpeername(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } memset(&hints, 0, sizeof(struct addrinfo) ); hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; hints.ai_family = saddr.ss_family; // Now we have to create a new socket to send packets if (serveropen_dp) // Data connection is opened by the server toward the client { sprintf(portdata, "%d", ntohs(startcapreq.portdata) ); // Get the name of the other peer (needed to connect to that specific network address) if (getnameinfo( (struct sockaddr *) &saddr, saddrlen, peerhost, sizeof(peerhost), NULL, 0, NI_NUMERICHOST) ) { sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ( (sockdata= sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == -1) goto error; } else // Data connection is opened by the client toward the server { hints.ai_flags = AI_PASSIVE; // Let's the server socket pick up a free network port for us if (sock_initaddress(NULL, "0", &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ( (sockdata= sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errbuf, PCAP_ERRBUF_SIZE)) == -1) goto error; // get the complete sockaddr structure used in the data connection saddrlen = sizeof(struct sockaddr_storage); if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getsockname(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } // Get the local port the system picked up if (getnameinfo( (struct sockaddr *) &saddr, saddrlen, NULL, 0, portdata, sizeof(portdata), NI_NUMERICSERV) ) { sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } } // addrinfo is no longer used freeaddrinfo(addrinfo); addrinfo= NULL; // save the socket ID for the next calls fp->rmt_sockctrl= sockctrl; // Needed to send an error on the ctrl connection // Now I can set the filter if ( daemon_unpackapplyfilter(fp, &nread, &plen, errbuf) ) goto error; // Now, I can send a RPCAP start capture reply message if ( sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr( (struct rpcap_header *) sendbuf, RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply) ); startcapreply= (struct rpcap_startcapreply *) &sendbuf[sendbufidx]; if ( sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(startcapreply, 0, sizeof(struct rpcap_startcapreply) ); startcapreply->bufsize= htonl(fp->bufsize); if (!serveropen_dp) { unsigned short port = (unsigned short)strtoul(portdata,NULL,10); startcapreply->portdata= htons(port); } if ( sock_send(sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if (!serveropen_dp) { SOCKET socktemp; // We need another socket, since we're going to accept() a connection // Connection creation saddrlen = sizeof(struct sockaddr_storage); socktemp= accept(sockdata, (struct sockaddr *) &saddr, &saddrlen); if (socktemp == -1) { sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } // Now that I accepted the connection, the server socket is no longer needed sock_close(sockdata, errbuf, PCAP_ERRBUF_SIZE); sockdata= socktemp; } fp->rmt_sockdata= sockdata; /* GV we need this to create the thread as detached. */ /* GV otherwise, the thread handle is not destroyed */ pthread_attr_init(&detachedAttribute); pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED); // Now we have to create a new thread to receive packets if ( pthread_create(threaddata, &detachedAttribute, (void *) daemon_thrdatamain, (void *) fp) ) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread"); pthread_attr_destroy(&detachedAttribute); goto error; } pthread_attr_destroy(&detachedAttribute); // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); return fp; error: rpcap_senderror(sockctrl, errbuf, PCAP_ERR_STARTCAPTURE, NULL); if (addrinfo) freeaddrinfo(addrinfo); if (threaddata) pthread_cancel(*threaddata); if (sockdata) sock_close(sockdata, NULL, 0); // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); if (fp) { pcap_close(fp); fp= NULL; } return NULL; }
int main(int argc, char *argv[]) { int tmp; /* set progname */ progname = (const char *)strrchr(argv[0], '/'); progname = progname ? (progname + 1) : argv[0]; /* read command line */ cmdline(&argc, &argv); /* set default cfgfile */ if (*cfgfile == '\0') strncpy(cfgfile , DAEMON_CFGFILE, strlen(DAEMON_CFGFILE)); /* read config file */ if (cfg_file_read(cfgfile, cfg, cfglen) == -1) fprintf(stderr, "can't open cfgfile: %s ==> " \ "build in settings will be used\n", cfgfile); /* set unset configuration */ set_unset(); /* print configuration */ if (settings == YES) cfg_print(cfg, cfglen); /* set ebus configuration */ eb_set_nodevicecheck(nodevicecheck); eb_set_rawdump(rawdump); eb_set_showraw(showraw); tmp = (eb_htoi(&address[0])) * 16 + (eb_htoi(&address[1])); eb_set_qq((unsigned char) tmp); eb_set_get_retry(get_retry); eb_set_skip_ack(skip_ack); eb_set_max_wait(max_wait); eb_set_send_retry(send_retry); eb_set_print_size(print_size); /* open log */ log_level(loglevel); log_open(logfile, foreground); /* to be daemon */ if (foreground == NO) { log_print(L_ALL, DAEMON_NAME " " DAEMON_VERSION " started"); syslog(LOG_INFO, DAEMON_NAME " " DAEMON_VERSION " started"); daemonize(); } /* read ebus command configuration files */ if (eb_cmd_dir_read(cfgdir, extension) == -1) log_print(L_WAR, "error during read command file"); /* open raw file */ if (rawdump == YES) { if (eb_raw_file_open(rawfile) == -1) { log_print(L_ALL, "can't open rawfile: %s", rawfile); cleanup(EXIT_FAILURE); } else { log_print(L_INF, "%s opened", rawfile); } } /* open serial device */ if (eb_serial_open(device, &serialfd) == -1) { log_print(L_ALL, "can't open device: %s", device); cleanup(EXIT_FAILURE); } else { log_print(L_INF, "%s opened", device); } /* open listing tcp socket */ if (sock_open(&socketfd, port, localhost) == -1) { log_print(L_ALL, "can't open port: %d", port); cleanup(EXIT_FAILURE); } else { log_print(L_INF, "port %d opened", port); } /* init msg queue */ if (msg_queue_init() == -1) { log_print(L_ALL, "can't initialize msg queue"); cleanup(EXIT_FAILURE); } else { msg_queue_on = YES; log_print(L_INF, "msg queue initialized"); } /* enter main loop */ main_loop(); cleanup(EXIT_SUCCESS); return 0; }
void main_loop(void) { int maxfd, sfd_closed, timeout_reached; fd_set listenfds; struct timeval timeout; sfd_closed = NO; timeout_reached = NO; FD_ZERO(&listenfds); FD_SET(serialfd, &listenfds); FD_SET(socketfd, &listenfds); maxfd = socketfd; /* serialfd should be always lower then socketfd */ if (serialfd > socketfd) { log_print(L_ERR, "serialfd %d > %d socketfd", serialfd, socketfd); cleanup(EXIT_FAILURE); } for (;;) { fd_set readfds; int readfd; int ret; /* set select timeout 10 secs */ timeout.tv_sec = 10; timeout.tv_usec = 0; /* set readfds to inital listenfds */ readfds = listenfds; /* check if the usb device is working */ if (eb_serial_valid() < 0 || timeout_reached == YES) { timeout_reached = NO; if (serialfd > 0 && sfd_closed == NO) { log_print(L_ERR, "serial device is invalid"); sfd_closed = YES; /* close listing tcp socket */ if (socketfd > 0) { if (sock_close(socketfd) == -1) log_print(L_ERR, "can't close port: %d", port); else log_print(L_INF, "port %d closed", port); } /* close serial device */ if (eb_serial_close() == -1) log_print(L_ERR, "can't close device: %s", device); else log_print(L_INF, "%s closed", device); } /* need sleep to prevent high cpu consumption */ sleep(1); /* open serial device */ if (eb_serial_open(device, &serialfd) == 0) { log_print(L_INF, "%s opened", device); sfd_closed = NO; } /* open listing tcp socket */ if (sfd_closed == NO && sock_open(&socketfd, port, localhost) == 0) log_print(L_INF, "port %d opened", port); continue; } ret = select(maxfd + 1, &readfds, NULL, NULL, &timeout); /* timeout after 10 secs means that ebus is probably disconnected or USB device is dead */ if (ret == 0) { log_print(L_WAR, "select timeout (%d) reached", timeout.tv_sec); timeout_reached = YES; continue; /* ignore signals */ } else if ((ret < 0) && (errno == EINTR)) { /* log_print(L_NOT, "get signal at select: %s", strerror(errno)); */ continue; /* on other errors */ } else if (ret < 0) { err_if(1); cleanup(EXIT_FAILURE); } /* new data from serial port? */ if (FD_ISSET(serialfd, &readfds)) { /* get cycle message from bus */ ret = eb_cyc_data_recv(); /* send msg to bus - only when cyc buf is empty */ if (ret == 0 && msg_queue_entries() > 0) { char tcpbuf[SOCKET_BUFSIZE]; char data[MSG_QUEUE_MSG_SIZE]; int tcpbuflen, id, clientfd; memset(tcpbuf, '\0', sizeof(tcpbuf)); tcpbuflen = sizeof(tcpbuf); memset(data, '\0', sizeof(data)); /* get next entry from msg queue */ msg_queue_msg_del(&id, data, &clientfd); /* just do it */ eb_execute(id, data, tcpbuf, &tcpbuflen); /* send answer */ sock_client_write(clientfd, tcpbuf, tcpbuflen); } } /* new incoming connection at TCP port arrived? */ if (FD_ISSET(socketfd, &readfds)) { /* get new TCP client fd*/ ret = sock_client_accept(socketfd, &readfd); if (readfd >= 0) { /* add new TCP client fd to listenfds */ FD_SET(readfd, &listenfds); (readfd > maxfd) ? (maxfd = readfd) : (1); } } /* run through connected sockets for new data */ for (readfd = socketfd + 1; readfd <= maxfd; ++readfd) { /* check all connected clients */ if (FD_ISSET(readfd, &readfds)) { char tcpbuf[SOCKET_BUFSIZE]; char data[MSG_QUEUE_MSG_SIZE]; int tcpbuflen; memset(tcpbuf, '\0', sizeof(tcpbuf)); tcpbuflen = sizeof(tcpbuf); memset(data, '\0', sizeof(data)); /* get message from client */ ret = sock_client_read(readfd, tcpbuf, &tcpbuflen); /* remove dead TCP client */ if (ret < 0) { FD_CLR(readfd, &listenfds); continue; } /* handle different commands */ if (strncasecmp("shutdown", tcpbuf, 8) == 0) cleanup(EXIT_SUCCESS); if (strncasecmp("loglevel", tcpbuf, 8) == 0) { strncpy(loglevel, tcpbuf, strlen(tcpbuf)); log_level(loglevel); continue; } /* search ebus command */ if (tcpbuflen > 0) ret = eb_cmd_search_com(tcpbuf, data); else ret = -1; /* command not found */ if (ret < 0) { memset(tcpbuf, '\0', sizeof(tcpbuf)); strcpy(tcpbuf, "command not found\n"); tcpbuflen = strlen(tcpbuf); /* send answer */ sock_client_write(readfd, tcpbuf, tcpbuflen); } else { msg_queue_msg_add(ret, data, readfd); } } } } }
/* issue a connect, but return after the timeout (seconds) is reached. If * timeout is 0 or less then we will wait until the OS gives up on the connect * The socket is returned */ sock_t sock_connect_wto_bind (const char *hostname, int port, const char *bnd, int timeout) { sock_t sock = SOCK_ERROR; struct addrinfo *ai, *head, *b_head=NULL, hints; char service[8]; memset (&hints, 0, sizeof (hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; snprintf (service, sizeof (service), "%u", port); if (getaddrinfo (hostname, service, &hints, &head)) return SOCK_ERROR; ai = head; while (ai) { int type = ai->ai_socktype; if ((sock = sock_open (ai->ai_family, type, ai->ai_protocol)) >= 0) { sock_set_cloexec (sock); if (timeout > 0) sock_set_blocking (sock, 0); if (bnd) { struct addrinfo b_hints; memset (&b_hints, 0, sizeof(b_hints)); b_hints.ai_family = ai->ai_family; b_hints.ai_socktype = ai->ai_socktype; b_hints.ai_protocol = ai->ai_protocol; if (getaddrinfo (bnd, NULL, &b_hints, &b_head) || bind (sock, b_head->ai_addr, b_head->ai_addrlen) < 0) { sock_close (sock); sock = SOCK_ERROR; break; } } if (connect (sock, ai->ai_addr, ai->ai_addrlen) == 0) break; /* loop as the connect maybe async */ while (sock != SOCK_ERROR) { if (sock_recoverable (sock_error())) { int connected = sock_connected (sock, timeout); if (connected == 0) /* try again, interrupted */ continue; if (connected == 1) /* connected */ { if (timeout >= 0) sock_set_blocking(sock, 1); break; } } sock_close (sock); sock = SOCK_ERROR; } if (sock != SOCK_ERROR) break; } ai = ai->ai_next; } if (b_head) freeaddrinfo (b_head); freeaddrinfo (head); return sock; }
static err_t accept_tcp(void *arg, struct tcp_pcb *pcb, err_t err) { int s, i, ns; sockfd_t * fd, * nsd; err_t rv = ERR_OK; // printf("kti: accept_tcp for %d called (err %d)\n", (int)arg, err); // Dunno what to do here if not... assert( err == ERR_OK ); // Get the socket struct and lock s = (int)arg; if (sock_verify(s) < 0) return ERR_CONN; fd = fds + s; // Get access. mutex_lock(fd->mutex); // Do we have enough space? if (fd->conncnt >= fd->connmax) { rv = ERR_MEM; goto out; } // Add the connection for (i=0; i<fd->connmax; i++) if (fd->conns[i] < 0) break; if (i >= fd->connmax) { assert( 0 ); rv = ERR_MEM; goto out; } // Create a new socket FD for the connection. ns = sock_open(); if (ns < 0) { rv = ERR_MEM; goto out; } // Assign stuff. We've already got our sync objects, we just // need to get things into it. To make sure nothing weird happens // here, we'll lock first. nsd = fds + ns; mutex_lock(nsd->mutex); nsd->tcppcb = pcb; // Init our counters nsd->recv = 0; nsd->send = tcp_sndbuf(nsd->tcppcb); // Setup callbacks tcp_arg(nsd->tcppcb, (void *)ns); tcp_recv(nsd->tcppcb, recv_tcp); tcp_sent(nsd->tcppcb, sent_tcp); tcp_poll(nsd->tcppcb, poll_tcp, 4); // 4 == 4 TCP timer intervals tcp_err(nsd->tcppcb, err_tcp); // Copy over the peer address nsd->name.sin_len = sizeof(struct sockaddr_in); nsd->name.sin_family = AF_INET; nsd->name.sin_port = htons(nsd->tcppcb->remote_port); nsd->name.sin_addr.s_addr = nsd->tcppcb->remote_ip.addr; mutex_unlock(nsd->mutex); fd->conns[i] = ns; fd->conncnt++; // Signal any thread waiting on accept() cond_signal(fd->connect); out: mutex_unlock(fd->mutex); if (rv == ERR_OK) genwait_wake_all(&select_wait); return rv; }
void* pt_download(void* args) { struct pt_dwdata* pdp = (struct pt_dwdata*)args; //printf("thread: %d, offset: %d, length:%d\n", pdp->number, pdp->offset, pdp->length); int64 total = 0; int trying = 0; char buf[1024]; char localname[256]; sprintf(localname, ".tmp/%s_%d", g_pDM->getBaseName(), pdp->number); int64 dataLeft = pdp->length - total; FILE* fp = fopen(localname, "wb"); char tmp[1024]; int sock = -1; while (total < pdp->length) { sock = sock_open(g_pDM->getHost(), g_pDM->getPort()); if (sock <= 0) { printf(RED"Error: "WHITE"connect server failed, retry: %d times\n", trying++); sleep(5); continue; } //welcome message FILE* fpSock = fdopen(sock, "r"); setbuf(fpSock, (char *)0); fgets(buf, sizeof(buf), fpSock); printf("thread: "YELLOW"%d"WHITE", connect server "GREEN"OK\n"WHITE, pdp->number); dataLeft = pdp->length - total; sprintf(tmp, "get %s %llu %llu", g_pDM->getFileName(), pdp->offset + total, dataLeft); printf("%s\n", tmp); sock_cmd(sock, tmp); //printf("get %s %d %d\n", g_pDM->getFileName(), pdp->offset + total, dataLeft); int64 len; while (dataLeft)// < pdp->length) { len = sizeof(buf) > dataLeft ? dataLeft : sizeof(buf); //printf("%d\n", len); int n = sock_read(sock, buf, (int)len); if (n <= 0) { printf("sock read return %d bytes\n", n); break; } fwrite(buf, n, 1, fp); dataLeft -= n; total += n; g_pDM->setDwSize(pdp->number, total); } close(sock); //printf("%d/%d\n", total, g_data.final_size); } fclose(fp); printf("thread: "YELLOW"%d"WHITE", my task is "GREEN"OK\n"WHITE, pdp->number); return NULL; }
int main(int argc, char *argv[]) { char buffer[BUFSIZE]; struct sockaddr saddr; int opt; struct timespec starttime, endtime; clock_gettime(CLOCK_MONOTONIC, &starttime); unsigned char bcast[] = "\xFF\xFF\xFF\xFF\xFF\xFF"; sta_add(&sta_head, ccolor++, bcast); signal(SIGINT, intHandler); while ((opt = getopt(argc, argv, PARAMS)) != -1) { switch (opt) { case 'h': fprintf(stdout, HELP, argv[0]); exit(EXIT_SUCCESS); case 'b': opt_nobeacon = true; break; case 'c': opt_color = true; break; case 'd': opt_diffstamp = true; break; case 'm': opt_nomgmt = true; break; case 's': opt_simpleaddr = true; break; case 't': opt_timestamp = true; break; default: fprintf(stderr, USAGE, argv[0]); exit(EXIT_FAILURE); } } if (optind >= argc) { fprintf(stderr, USAGE, argv[0]); exit(EXIT_FAILURE); } char * iface = argv[optind]; int macs = argc - optind - 1; if(macs > 0) { maclist = (unsigned char*)malloc(6*macs); unsigned char * pos = maclist; for(int i = optind + 1; i < argc; i++) { unsigned int iMac[6]; unsigned char mac[6]; sscanf(argv[i], "%x:%x:%x:%x:%x:%x", &iMac[0], &iMac[1], &iMac[2], &iMac[3], &iMac[4], &iMac[5]); for(int j=0;j<6;j++) mac[j] = (unsigned char)iMac[j]; memcpy(pos, mac, 6); pos += 6; } } maclist_count = macs; if (sock_open()) return 0; if (sock_bind(argv[optind])) return 0; while(keepRunning) { socklen_t saddr_size = sizeof saddr; int size = recvfrom(sock, buffer, BUFSIZE, 0, &saddr, &saddr_size); analyze(buffer, size); } clock_gettime(CLOCK_MONOTONIC, &endtime); printf(CNORMAL); sock_close(); printf("Station List: \n"); print_stalist(sta_head->next); struct timespec ts = tsdiff(starttime, endtime); printf("Total Running Time: %ld.%lds\n", ts.tv_sec, ts.tv_nsec / 1000); return 0; }
/*! \brief 'true' main of the program in case the active mode is turned on. It does not have any return value nor parameters. This function loops forever trying to connect to the remote host, until the daemon is turned down. \param ptr: it keeps the 'activepars' parameters. It is a 'void *' just because pthreads want this format. */ void main_active(void *ptr) { char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed SOCKET sockctrl; // keeps the socket ID for this control connection struct addrinfo hints; // temporary struct to keep settings needed to open the new socket struct addrinfo *addrinfo; // keeps the addrinfo chain; required to open a new socket struct active_pars *activepars; struct daemon_slpars *pars; // parameters needed by the daemon_serviceloop() activepars= (struct active_pars *) ptr; // Prepare to open a new server socket memset(&hints, 0, sizeof(struct addrinfo)); // WARNING Currently it supports only ONE socket family among IPv4 and IPv6 hints.ai_family = AF_INET; // PF_UNSPEC to have both IPv4 and IPv6 server hints.ai_socktype = SOCK_STREAM; hints.ai_family= activepars->ai_family; log_info("Connecting to host %s, port %s, using protocol %s", activepars->address, activepars->port, (hints.ai_family == AF_INET) ? "IPv4": (hints.ai_family == AF_INET6) ? "IPv6" : "Unspecified"); // Initialize errbuf memset(errbuf, 0, sizeof(errbuf) ); // Do the work if (sock_initaddress(activepars->address, activepars->port, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) { log_warn("%s", errbuf); return; } while (1) { int activeclose; if ( (sockctrl= sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == -1) { log_warn("%s", errbuf); snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error connecting to host %s, port %s, using protocol %s", activepars->address, activepars->port, (hints.ai_family == AF_INET) ? "IPv4": (hints.ai_family == AF_INET6) ? "IPv6" : "Unspecified" ); log_warn("%s", errbuf); pthread_suspend(RPCAP_ACTIVE_WAIT * 1000); continue; } pars= (struct daemon_slpars *) malloc ( sizeof(struct daemon_slpars) ); if (pars == NULL) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno)); continue; } pars->sockctrl= sockctrl; pars->activeclose= 0; pars->isactive= 1; pars->nullAuthAllowed= nullAuthAllowed; pars->preselected_ifname = (activepars->ifname[0] != '\0') ? activepars->ifname : NULL; daemon_serviceloop( (void *) pars); activeclose= pars->activeclose; free(pars); // If the connection is closed by the user explicitely, don't try to connect to it again // just exit the program if (activeclose == 1) break; } }
void main_startup(void) { char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed struct addrinfo *addrinfo; // keeps the addrinfo chain; required to open a new socket int i; #ifdef WIN32 pthread_t threadId; // Pthread variable that keeps the thread structures pthread_attr_t detachedAttribute; // PThread attribute needed to create the thread as detached #else pid_t pid; #endif i= 0; addrinfo= NULL; memset(errbuf, 0, sizeof(errbuf) ); // Starts all the active threads while ( (activelist[i].address[0] != 0) && (i < MAX_ACTIVE_LIST) ) { activelist[i].ai_family= mainhints.ai_family; // use global preselected interface if not set in config file if ((activelist[i].ifname[0] == '\0') && (rpcapd_opt.preselected_ifname[0] != '\0')) { snprintf(activelist[i].ifname, sizeof(activelist[i].ifname), "%s", rpcapd_opt.preselected_ifname); } #ifdef WIN32 /* GV we need this to create the thread as detached. */ /* GV otherwise, the thread handle is not destroyed */ pthread_attr_init(&detachedAttribute); pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED); if ( pthread_create( &threadId, &detachedAttribute, (void *) &main_active, (void *) &activelist[i]) ) { log_warn("Error creating the active child thread"); pthread_attr_destroy(&detachedAttribute); continue; } pthread_attr_destroy(&detachedAttribute); #else if ( (pid= fork() ) == 0) // I am the child { main_active( (void *) &activelist[i]); exit(0); } #endif i++; } /* The code that manages the active connections is not blocking; vice versa, the code that manages the passive connection is blocking. So, if the user do not want to run in passive mode, we have to block the main thread here, otherwise the program ends and all threads are stopped. WARNING: this means that in case we have only active mode, the program does not terminate even if all the child thread terminates. The user has always to press Ctrl+C (or send a SIGTERM) to terminate the program. */ if (passivemode) { struct addrinfo *tempaddrinfo; // Do the work if (sock_initaddress((address[0]) ? address : NULL, port, &mainhints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) { log_warn("%s", errbuf); return; } tempaddrinfo= addrinfo; while (tempaddrinfo) { SOCKET *socktemp; if ( (sockmain= sock_open(tempaddrinfo, SOCKOPEN_SERVER, SOCKET_MAXCONN, errbuf, PCAP_ERRBUF_SIZE)) == -1) { log_warn("%s", errbuf); tempaddrinfo= tempaddrinfo->ai_next; continue; } // This trick is needed in order to allow the child thread to save the 'sockmain' variable // withouth getting it overwritten by the sock_open, in case we want to open more than one waiting sockets // For instance, the pthread_create() will accept the socktemp variable, and it will deallocate immediately that variable socktemp= (SOCKET *) malloc (sizeof (SOCKET)); if (socktemp == NULL) exit(0); *socktemp= sockmain; #ifdef WIN32 /* GV we need this to create the thread as detached. */ /* GV otherwise, the thread handle is not destroyed */ pthread_attr_init(&detachedAttribute); pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED); if ( pthread_create( &threadId, &detachedAttribute, (void *) &main_passive, (void *) socktemp ) ) { log_warn("Error creating the passive child thread"); pthread_attr_destroy(&detachedAttribute); continue; } pthread_attr_destroy(&detachedAttribute); #else if ( (pid= fork() ) == 0) // I am the child { main_passive( (void *) socktemp); return; } #endif tempaddrinfo= tempaddrinfo->ai_next; } freeaddrinfo(addrinfo); } // All the previous calls are no blocking, so the main line of execution goes here // and I have to avoid that the program terminates while (1) pthread_suspend(10*60*1000); // it wakes up every 10 minutes; it seems to me reasonable }
void Server(char *Address, char *Port, int AddressFamily, int TransportProtocol) { char ErrBuf[1024]; char DataBuffer[1024]; int ServerSocket, ChildSocket; // keeps the socket ID for this connection struct addrinfo Hints; // temporary struct to keep settings needed to open the new socket struct addrinfo *AddrInfo; // keeps the addrinfo chain; required to open a new socket struct sockaddr_storage From; // temp variable that keeps the parameters of the incoming connection int ReadBytes; // Number of bytes read from the socket char RemoteAddress[1024]; // temp variable to store the address of the connecting host char RemotePort[1024]; // temp variable to store the port used by the connecting host // Prepare to open a new server socket memset(&Hints, 0, sizeof(struct addrinfo)); Hints.ai_family= AddressFamily; Hints.ai_socktype= TransportProtocol; // Open a TCP/UDP connection Hints.ai_flags = AI_PASSIVE; // This is a server: ready to bind() a socket if (sock_initaddress (Address, Port, &Hints, &AddrInfo, ErrBuf, sizeof(ErrBuf)) == sockFAILURE) { printf("Error resolving given address/port: %s\n\n", ErrBuf); return; } printf("Server waiting on address %s, port %s, using protocol %s\n", Address ? Address : "all local addresses", Port, (AddrInfo->ai_family == AF_INET) ? "IPv4" : "IPv6"); if ( (ServerSocket= sock_open(AddrInfo, 1, 10, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); printf("Cannot opening the socket: %s\n\n", ErrBuf); return; } // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); if (TransportProtocol == SOCK_STREAM) { if ( (ChildSocket= sock_accept(ServerSocket, &From, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { printf("Error when accepting a new connection: %s\n\n", ErrBuf); return; } if (sock_getascii_addrport(&From, RemoteAddress, sizeof(RemoteAddress), RemotePort, sizeof(RemotePort), NI_NUMERICHOST | NI_NUMERICSERV, ErrBuf, sizeof(ErrBuf)) == sockFAILURE) { printf("Error getting information related to the connecting host: %s\n\n", ErrBuf); return; } printf("Accepting a new connection from host %s, using remote port %s.\n\n", RemoteAddress, RemotePort); ReadBytes= sock_recv(ChildSocket, DataBuffer, sizeof(DataBuffer), SOCK_RECEIVEALL_NO, 30, ErrBuf, sizeof(ErrBuf)); if (ReadBytes == sockFAILURE) { printf("Error reading data: %s\n\n", ErrBuf); return; } } else { ReadBytes= sock_recvdgram(ServerSocket, DataBuffer, sizeof(DataBuffer), SOCK_RECEIVEALL_NO, 30, ErrBuf, sizeof(ErrBuf)); if (ReadBytes == sockFAILURE) { printf("Error reading data: %s\n\n", ErrBuf); return; } } if (ReadBytes == sockWARNING) { printf("We waited for enough time and no data has been received so far.\nAborting the connection.\n\n"); return; } // Terminate buffer, just for printing purposes // Warning: this can originate a buffer overflow DataBuffer[ReadBytes]= 0; printf("Received the following string: '%s'\n\n", DataBuffer); }
int try_connect_EHLO(const char *hostname) { char dbg_hostname[BIG_BUF]; char dbg_version[BIG_BUF]; char buf[BIG_BUF]; char testme[BIG_BUF]; int read_data = 0; if(my_socket != -1) sock_close(my_socket); log_printf(9, "Attempting to connect to %s\n", get_string("mailserver")); if (sock_open(get_string("mailserver"), get_number("smtp-socket", 25), &my_socket)) return 0; while(sock_readline(my_socket, buf, sizeof(buf)) != 0) { int val; char ch; read_data = 1; log_printf(9,"Server sent: %s\n", buf); sscanf(buf, "%d%c%s %s", &val, &ch, &dbg_hostname[0], &dbg_version[0]); if(val != 220) { return 0; } if(ch != '-') { log_printf(9, "Connected: %s (%s)\n", dbg_hostname, dbg_version); break; } } if(!read_data) return 0; sock_printf(my_socket, "EHLO %s\r\n", hostname); if(sock_readline(my_socket, buf, sizeof(buf)) == 0) return 0; /* Check for valid response */ if(!sscanf(buf, "250-%s", testme)) return 0; /* Okay, we have a valid ESMTP server. Read the server caps */ while(sock_readline(my_socket, buf, sizeof(buf)) != 0) { int val; char ch; log_printf(9,"Server sent: %s\n", buf); sscanf(buf, "%d%c%s", &val, &ch, testme); if(val != 250) { return 0; } if(ch != '-') break; else { if (!strcmp(testme,"DSN")) { servercaps &= CAPS_DSN; log_printf(9, "Server caps: server supports DSN\n"); } else if (!strcmp(testme,"8BITMIME")) { servercaps &= CAPS_MIME; log_printf(9, "Server caps: server supports MIME\n"); } } } return 1; }
void *doControlConnection(void *parameters) { int AddressFamily = AF_INET; //use IPv4 int TransportProtocol = SOCK_STREAM; //use TCP char ErrBuf[1024]; char DataBuffer[1024]; int ChildSocket; // keeps the socket ID for connections from clients struct addrinfo Hints; // temporary struct to keep settings needed to open the new socket struct addrinfo *AddrInfo; // keeps the addrinfo chain; required to open a new socket struct sockaddr_storage From; // temp variable that keeps the parameters of the incoming connection int ReadBytes, WrittenBytes; int ServerSocket; // Prepare to open a new server socket memset(&Hints, 0, sizeof(struct addrinfo)); Hints.ai_family= AddressFamily; Hints.ai_socktype= TransportProtocol; // Open a TCP/UDP connection Hints.ai_flags = AI_PASSIVE; // This is a server: ready to bind() a socket if (sock_initaddress (NULL, nf_params.tcp_port, &Hints, &AddrInfo, ErrBuf, sizeof(ErrBuf)) == sockFAILURE) { fprintf(logFile,"%s Error resolving given port (%s): %s\n",module_name, nf_params.tcp_port,ErrBuf); exit(EXIT_FAILURE); } if ( (ServerSocket= sock_open(AddrInfo, 1, 10, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); fprintf(logFile,"%s Cannot opening the socket: %s\n",module_name, ErrBuf); exit(EXIT_FAILURE); } // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); while(1) { if ( (ChildSocket= sock_accept(ServerSocket, &From, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { fprintf(logFile,"%s Error when accepting a new connection: %s\n",module_name, ErrBuf); exit(EXIT_FAILURE); } ReadBytes= sock_recv(ChildSocket, DataBuffer, sizeof(DataBuffer), SOCK_RECEIVEALL_NO, 0/*no timeout*/, ErrBuf, sizeof(ErrBuf)); if (ReadBytes == sockFAILURE) { fprintf(logFile,"%s Error reading data: %s\n",module_name, ErrBuf); exit(EXIT_FAILURE); } // Terminate buffer, just for printing purposes // Warning: this can originate a buffer overflow DataBuffer[ReadBytes]= 0; fprintf(logFile,"%sData received (%d bytes):\n",module_name, ReadBytes); fprintf(logFile,"%s %s\n",module_name,DataBuffer); char answer[1024]; sprintf(answer,"Greeting from network function\"%s\"",nf_params.nf_name); fprintf(logFile,"%s Answer to be sent: %s\n",module_name,answer); WrittenBytes= sock_send(ChildSocket, answer, strlen(answer), ErrBuf, sizeof(ErrBuf)); if (WrittenBytes == sockFAILURE) { fprintf(logFile,"%s Error sending data: %s",module_name, ErrBuf); exit(EXIT_FAILURE); } sock_close(ChildSocket,ErrBuf,sizeof(ErrBuf)); } }
int64 DwManager::getSizeFromServer() { if (m_fd != -1) { close(m_fd); m_fd = -1; } int sock = sock_open(m_host, m_port); if (sock <= 0) { printf("connect server failed\n"); exit (1); } FILE* fpSock = fdopen(sock, "r"); if (fpSock == NULL) { close(sock); return -2; } setbuf(fpSock, (char *)0); char buf[1024]; if (fgets(buf, sizeof(buf), fpSock) == NULL) { close(sock); return -3; } printf("<=%s", buf); printf(GREEN"get %s\n"WHITE, m_filename); sock_cmd(sock, "size %s", m_filename); if (fgets(buf, sizeof(buf), fpSock) == NULL) { close(sock); return -4; } //if (strncmp(buf, "OK", 2) != 0) if (strncmp(buf, "+OK", 3) != 0) // simon { printf(RED"Error: %s", buf); close(sock); return -5; } // printf(YELLOW"file size: "WHITE"%s", buf + 3); printf(YELLOW"file size: "WHITE"%s", buf + 4); // simon // int64 total = atoll(buf + 3); int64 total = atoll(buf + 4); // simon if (total <= 0) { printf(RED"Error: "YELLOW"Wrong size:"WHITE"%d\n", total); close(sock); return -6; } //printf("file size: %llu\n", total); //close(sock); m_fd = sock; m_filesize = total; return m_filesize; }