void TcpClient::ReadHandler(const system::error_code& ec,size_t bytes_transferred) { if(ec) { PrintError(ec); if(ConnectionDisable(ec)) { SockClose(); utility::wait_time(1000); Connect(); } return ; } else { size_t len = bytes_transferred; len = m_InData.Append(m_rev_data,len); while( m_InData.GetPacket(m_packet_buffer)) { if (!m_bIsClosed&&m_PacketProcessor) { m_PacketProcessor->PacketProcess(m_packet_buffer); } } } read(m_rev_data,max_data_buffer); }
short SockHandler (UINT socket, LPARAM lEvent) { switch (WSAGETSELECTEVENT (lEvent)) { case FD_READ: break; case FD_WRITE: break; case FD_OOB: break; case FD_ACCEPT: if (ssd.socket != socket) return -1; return SockAccept (); break; case FD_CONNECT: break; case FD_CLOSE: if (ssd.socket != socket) return -1; return SockClose (); break; } return 0; }
short SockEnd () { SockClose (); if (!--sockInstC) TerminateWinsock (); return 0; }
static int get_ifinfo(const char *ifname, ifinfo_t *ifinfo) { int socket_fd = socket(AF_INET, SOCK_DGRAM, 0); FILE *stats_file = fopen("/proc/net/dev", "r"); int result; if (socket_fd < 0 || !stats_file) result = FALSE; else { char *tmp = xstrdup(ifname); char *sp = strchr(tmp, '/'); /* hide slash and trailing info from ifname */ if (sp) *sp = '\0'; result = _get_ifinfoGT_(socket_fd, stats_file, tmp, ifinfo); free(tmp); } if (socket_fd >= 0) SockClose(socket_fd); if (stats_file) fclose(stats_file); /* not checking should be safe, mode was "r" */ return(result); }
// // thread which handles a single http request // static int proxy_handlereq(SOCKET sock_client) { SOCKET sock_server; char buf[65536]; char header_line[1024]; char host[256]; int serverPort = 80; struct sockaddr serverSockAddr; int gotHeader = 0; int count; int Status; unsigned long nbParm = 0L; char newline = '\n'; fd_set rfds; int n, maxfd; int one = 1; buf[0] = '\0'; host[0] = '\0'; // set client socket non-blocking if ((Status = SockBlock(sock_client, 0)) < 0) { SockError("proxy_handlereq(): Failed to clear non-block mode on socket"); return 1; } // now get headers from client while ((count = proxy_sockgets(sock_client, header_line, 1024)) > 0) { gotHeader = 1; // look for 'Host:' header if (!Strnicmp(header_line, "host: ", 6)) { char *pPort; strcpy(host, header_line + 6); if ((pPort = strchr(host, ':')) != NULL) { *pPort++ = '\0'; serverPort = atoi(pPort); } } //MessageBox(0, header_line, "Req header", MB_SYSTEMMODAL); strcat(buf, header_line); strcat(buf, "\n"); } // add second line terminator to mark end of header strcat(buf, "\n"); // bail if nothing came through if (!gotHeader) { SockClose(sock_client); return 1; } // did we get a host address? if (host[0] == '\0') { char err400[] = "HTTP/1.0 400 Invalid header received from browser\n\n"; SockSend(sock_client, err400, strlen(err400)); SockClose(sock_client); SockError("proxy_handlereq(): host missing from http header"); return 1; } // allow callback function to intercept if (proxy_callback_fn != NULL) if ((*proxy_callback_fn)(host, buf, sock_client) != 0) { // callback took over SockClose(sock_client); return 0; } //MessageBox(0, buf, "Header", MB_SYSTEMMODAL); // change host and portnum if using downstream proxy if (proxy_extproxyaddr != NULL) { strcpy(host, proxy_extproxyaddr); serverPort = proxy_extproxyport; } // try to find server if (proxy_getaddr(host, serverPort, &serverSockAddr) == 0) { SockSend(sock_client, "404 Host Not Found\n\n", 20); SockClose(sock_client); return 1; } sock_server = socket(AF_INET, SOCK_STREAM, 0); #ifdef WINDOWS setsockopt(sock_server, IPPROTO_TCP, TCP_NODELAY, (char * ) &one, sizeof (int)); #endif // try to connect to server if ((Status = connect(sock_server, &serverSockAddr, sizeof(serverSockAddr))) < 0) { SockSend(sock_client, "404 Host Not Found\n\n", 20); SockClose(sock_client); return 1; } // send client's req to server SockSend(sock_server, buf, strlen(buf)); // // now loop around relaying stuff between server and client // maxfd = (sock_client > sock_server ) ? sock_client : sock_server; for(;;) { FD_ZERO(&rfds); FD_SET(sock_client, &rfds); FD_SET(sock_server, &rfds); if ((n = select(maxfd+1, &rfds, NULL, NULL, NULL)) < 0) { SockError("proxy_handlereq(): select() failed while handling http req"); //fprintf(logfp, "%s: select() failed!: ", prog); //fperror(logfp, ""); return 1; } // got data from client - relay to server if(FD_ISSET(sock_client, &rfds)) { if ((n = SockReceive(sock_client, buf, sizeof(buf))) <= 0) break; // end of request if (SockSend(sock_server, buf, n) != n) { //fprintf(logfp, "%s: write to: %s failed: ", prog, http->host); //fperror(logfp, ""); return 1; } continue; } // got data from server - relay to client if (FD_ISSET(sock_server, &rfds)) { if ((n = SockReceive(sock_server, buf, sizeof(buf))) < 0) { //fprintf(logfp, "%s: read from: %s failed: ", prog, http->host); //fperror(logfp, ""); // eno = safe_strerror(errno); // sprintf(buf, CFAIL, http->hostport, eno); // freez(eno); //write_socket(m_SockClient, buf, strlen(buf), 0); return 1; } if (n == 0) break; // got all from server /* just write */ if (SockSend(sock_client, buf, n) != n) { //fprintf(logfp, "%s: write to client failed: ", prog); //fperror(logfp, ""); return 1; } continue; } // 'if (got something from server)' } // 'for (;;)' - relaying data between client and server // all done - close sockets and terminate this thread SockClose(sock_client); SockClose(sock_server); // see you later return 0; } // 'proxy_handlereq()'
// // main thread which listens for incoming http connections, and launches a thread pair // when a connection comes in // static int proxy_server(void *dummy) { int Status; SOCKET sock_listen, sock_client; int oldListenPort; char *oldextproxyaddr; int lastError; unsigned long nbParm = 1000; int one = 1; SockAddrType sockAddr; // loop around waiting for client connection or change of listen port while (1) { // create the socket oldListenPort = proxy_listenport; oldextproxyaddr = proxy_extproxyaddr; if (proxy_getaddr("127.0.0.1", proxy_listenport, &sockAddr) == 0) { SockError("proxy_server(): failed to get socket address"); return 1; } // bind the socket sock_listen = socket(AF_INET, SOCK_STREAM, 0); //Status = setsockopt (sock_listen, IPPROTO_TCP, TCP_NODELAY, (char * ) &one, sizeof (int)); Status = bind(sock_listen, &sockAddr, sizeof(sockAddr)); if(Status < 0) { SockError("proxy_server(): Failed to connect socket for receiving connections"); return 1; } // set socket to non-blocking mode if ((Status = SockBlock(sock_listen, 1)) < 0) { SockError("proxy_server(): Failed to set non-block mode on socket"); return 1; } // set socket to listen if (listen(sock_listen, SOMAXCONN) != 0) { SockError("proxy_server(): Failed to listening mode on socket"); return 1; } //printf("about to start awaiting connections\n"); // loop accepting connections with timeout while (1) { // if external proxy addr has changed, ditch the strdup()'ed string if (oldextproxyaddr != proxy_extproxyaddr) { if (oldextproxyaddr != NULL) free(oldextproxyaddr); oldextproxyaddr = proxy_extproxyaddr; } // has someone changed the listening port? if (oldListenPort != proxy_listenport) { SockClose(sock_listen); break; // fall out to top of outer loop, set up another socket on new port } // check for incoming connections if ((sock_client = accept(sock_listen, NULL, NULL)) == INVALID_SOCKET) { if (SockLastError() != SockErrWouldBlock) { SockError("proxy_server(): accept() call failed"); return 1; } else { // no connections SockSleep(); continue; } } // there's a new connection //printf("got connection\n"); if (proxy_singlethread) proxy_handlereq(sock_client); // single-thread mode else { // spawn a thread to handle request // p_thrdsecattr initstacksize threadfn threadarg creationflags p_retthreadid LaunchThread(proxy_handlereq, sock_client); } //MessageBox(0, "Got incoming connection", "FreeWeb Proxy", MB_SYSTEMMODAL); } // don't add any statements after this inner loop! } // 'while (1)' return 0; // how on earth did we get here??? } // 'proxyServer()'
int tkNetMain(int pa_argn,char **in_args) { struct KeyInfoCache KeyInfoCache; struct ProcessingList ProcList; struct BackGroundArgs BkgdArgs; struct PeerData PeerDataRoot; struct Iterator ISeedPeer; struct Sock MainSock; struct BridgeProc BdgServerProc; struct BridgeProc BdgClientProc; char BdgPeerAddrStr[32]; char *pTargetName = NULL; BOOL ifClientSkipRegister = 1; int TestPurposeNatType; struct BridgeClientProcPa *pBCPPa = NULL; printf("tknet \n build: " TKNET_VER "\n"); tkNetInit(); MutexInit(&g_BkgdMutex); ISeedPeer = GetIterator(NULL); PeerDataCons(&PeerDataRoot); PeerDataRoot.tpnd.RanPriority = 0; PeerDataRoot.addr.port = 0; PeerDataRoot.addr.IPv4 = 0; ProcessingListCons( &ProcList ); RelayModuleInit(); KeyInfoCacheCons(&KeyInfoCache); if(!KeyInfoReadFile(&KeyInfoCache,"tknet.info")) { printf("config file lost.\n"); goto exit; } if(!KeyInfoTry(&KeyInfoCache,KEY_INFO_TYPE_CONFIG,&MainSock)) { printf("bad config format.\n"); goto exit; } if( g_TargetName[0] != '\0' ) { printf("target name: %s \n", g_TargetName); tkNetConnect(NULL); } else { printf("target name unset. \n"); } if(g_ifConfigAsFullCone) { g_NATtype = NAT_T_FULL_CONE; printf("config NAT type as fullcone.\n"); } else { while(!KeyInfoTry(&KeyInfoCache,KEY_INFO_TYPE_STUNSERVER,&MainSock)) { if(!KeyInfoTry(&KeyInfoCache,KEY_INFO_TYPE_MAILSERVER,&MainSock)) { printf("No way to get NAT type.\n"); goto exit; } } printf("NAT type got from STUN: %d\n",g_NATtype); } if(pa_argn == 2) { sscanf(in_args[1],"%d",&TestPurposeNatType); g_NATtype = (uchar)TestPurposeNatType; } printf("final NAT type: %d\n",g_NATtype); while(!KeyInfoTry(&KeyInfoCache,KEY_INFO_TYPE_BRIDGEPEER,&MainSock)) { if(!KeyInfoTry(&KeyInfoCache,KEY_INFO_TYPE_MAILSERVER,&MainSock)) { printf("no avalible Bridge peer.\n"); goto no_bdg_peer; } } GetAddrText(&g_BdgPeerAddr,BdgPeerAddrStr); printf("using Bridge peer: %s\n",BdgPeerAddrStr); ifClientSkipRegister = 0; no_bdg_peer: pBCPPa = BridgeMakeClientProc(&BdgClientProc,&MainSock,&ProcList,&g_BdgPeerAddr, g_MyName,g_NATtype,pTargetName,ifClientSkipRegister); ProcessStart(&BdgClientProc.proc,&ProcList); if(g_ifBkgdEnable) printf("back ground enabled.\n"); else printf("back ground disabled.\n"); BkgdArgs.pPeerDataRoot = &PeerDataRoot; BkgdArgs.pInfoCache = &KeyInfoCache; BkgdArgs.pProcList = &ProcList; BkgdArgs.pBdgClientProc = &BdgClientProc; BkgdArgs.pMainSock = &MainSock; tkBeginThread( &BackGround , &BkgdArgs ); ConsAndStartBridgeServer(&BdgServerProc,&PeerDataRoot,&ProcList,&MainSock,&ISeedPeer); while( g_MainLoopFlag ) { MutexLock(&g_BkgdMutex); if(!ifBkgdStunProc()) SockRead(&MainSock); DoProcessing( &ProcList ); if(!ifBkgdStunProc()) MainSock.RecvLen = 0; MutexUnlock(&g_BkgdMutex); if(sta_ifBeginNewConnection && pBCPPa) { pBCPPa->pTargetNameID = g_TargetName; sta_ifBeginNewConnection = 0; } tkMsSleep(100); } SockClose(&MainSock); FreeBdgClientProc(&BdgClientProc); FreeBridgeServer(&BdgServerProc); exit: PeerDataDestroy(&PeerDataRoot,&ISeedPeer); KeyInfoUpdate( &KeyInfoCache ); KeyInfoWriteFile(&KeyInfoCache,"tknet.updateinfo"); KeyInfoFree(&KeyInfoCache); RelayMuduleDestruction(); MutexDelete(&g_BkgdMutex); tkNetUninit(); return 0; }
static int odmr_getrange(int sock, struct query *ctl, const char *id, int *countp, int *newp, int *bytes) /* send ODMR and then run a reverse SMTP session */ { int ok, opts, smtp_sock; int doing_smtp_data = 0; /* Are we in SMTP DATA state? */ char buf [MSGBUFSIZE+1]; struct idlist *qnp; /* pointer to Q names */ (void)id; if ((ok = SMTP_ehlo(sock, SMTP_MODE, fetchmailhost, ctl->server.esmtp_name, ctl->server.esmtp_password, &opts))) { report(stderr, GT_("%s's SMTP listener does not support ESMTP\n"), ctl->server.pollname); return(ok); } else if (!(opts & ESMTP_ATRN)) { report(stderr, GT_("%s's SMTP listener does not support ATRN\n"), ctl->server.pollname); return(PS_PROTOCOL); } /* make sure we don't enter the fetch loop */ *bytes = *countp = *newp = -1; /* authenticate via CRAM-MD5 */ ok = do_cram_md5(sock, "AUTH", ctl, "334 "); if (ok) return(ok); /* * By default, the hostlist has a single entry, the fetchmail host's * canonical DNS name. */ buf[0] = '\0'; for (qnp = ctl->domainlist; qnp; qnp = qnp->next) if (strlen(buf) + strlen(qnp->id) + 1 >= sizeof(buf)) break; else { strcat(buf, qnp->id); strcat(buf, ","); } buf[strlen(buf) - 1] = '\0'; /* nuke final comma */ /* ship the domain list and get turnaround */ gen_send(sock, "ATRN %s", buf); if ((ok = gen_recv(sock, buf, sizeof(buf)))) return(ok); /* this switch includes all response codes described in RFC2645 */ switch(atoi(buf)) { case 250: /* OK, turnaround is about to happe */ if (outlevel > O_SILENT) report(stdout, GT_("Turnaround now...\n")); break; case 450: /* ATRN request refused */ if (outlevel > O_SILENT) report(stdout, GT_("ATRN request refused.\n")); return(PS_PROTOCOL); case 451: /* Unable to process ATRN request now */ report(stderr, GT_("Unable to process ATRN request now\n")); return(PS_EXCLUDE); case 453: /* You have no mail */ if (outlevel > O_SILENT) report(stderr, GT_("You have no mail.\n")); return(PS_NOMAIL); case 502: /* Command not implemented */ report(stderr, GT_("Command not implemented\n")); return(PS_PROTOCOL); case 530: /* Authentication required */ report(stderr, GT_("Authentication required.\n")); return(PS_AUTHFAIL); default: { char *t = sdump(buf, strlen(buf)); report(stderr, GT_("Unknown ODMR error \"%s\"\n"), t); xfree(t); return(PS_PROTOCOL); } } /* * OK, if we got here it's time to become a pipe between the ODMR * remote server (sending) and the SMTP listener we've designated * (receiving). We're not going to try to be a protocol machine; * instead, we'll use select(2) to watch the read sides of both * sockets and just throw their data at each other. */ if ((smtp_sock = smtp_setup(ctl)) == -1) return(PS_SOCKET); else { int maxfd = (sock > smtp_sock) ? sock : smtp_sock; for (;;) { fd_set readfds; struct timeval timeout; FD_ZERO(&readfds); FD_SET(sock, &readfds); FD_SET(smtp_sock, &readfds); timeout.tv_sec = ctl->server.timeout; timeout.tv_usec = 0; if (select(maxfd+1, &readfds, NULL, NULL, &timeout) == -1) return(PS_PROTOCOL); /* timeout */ if (FD_ISSET(sock, &readfds)) { int n = SockRead(sock, buf, sizeof(buf)); if (n <= 0) break; SockWrite(smtp_sock, buf, n); if (outlevel >= O_MONITOR && !doing_smtp_data) report(stdout, "ODMR< %s", buf); } if (FD_ISSET(smtp_sock, &readfds)) { int n = SockRead(smtp_sock, buf, sizeof(buf)); if (n <= 0) break; SockWrite(sock, buf, n); if (outlevel >= O_MONITOR) report(stdout, "ODMR> %s", buf); /* We are about to receive message data if the local MTA * sends 354 (after receiving DATA) */ if (!doing_smtp_data && !strncmp(buf, "354", 3)) { doing_smtp_data = 1; if (outlevel > O_SILENT) report(stdout, GT_("receiving message data\n")); } else if (doing_smtp_data) doing_smtp_data = 0; } } SockClose(smtp_sock); } return(0); }