string Socket<T, typename std::enable_if<Convertible<T*, base_addr*>()>::type>::readBytes() { string data; char recBuffer[BUFFERLENGTH] = {0}; int bytesAv = 0; int bytesRead = 0; int flags = 0; if ( ioctl (this->_sockfd,FIONREAD,&bytesAv) < 0 ) { throw SockError("Error in Reading from Socket."); } if ( bytesAv < 0 ) { // No Data Available throw SockError("Error In Reading"); } if ( bytesAv == 0) { // No Data Available //sockState = socket_state::TIME_WAIT; throw SockError("No Data available for read"); } bytesRead = recv(this->_sockfd,recBuffer,BUFFERLENGTH,flags); (data) += recBuffer; return data; }
string SockWrapperPlain::Read() { static char buf[1024]; string sbuf; ssize_t r; if (!sock_ok) return ""; if ((r = read(recv_fd, buf, sizeof buf - 1)) <= 0) { if (r == 0) throw SockError("Connection reset by peer..."); else if(!sockerr_again()) throw SockError(string("Read error: ") + strerror(errno)); else sbuf = ""; } else { buf[r] = 0; sbuf = buf; } return sbuf; }
IrcSocket::IrcSocket (QObject *parent) :QTcpSocket (parent), needPing (true), numBytesIn (0), numBytesOut (0) { sockCount++; setObjectName (QString("IrcSocket-%1").arg(sockCount)); hostName = objectName (); pingTimer = new QTimer (this); scriptTimer = new QTimer (this); connect (pingTimer, SIGNAL (timeout()), this, SLOT (SendPing())); connect (scriptTimer, SIGNAL (timeout()), this, SLOT (SendScriptHead())); connect (this, SIGNAL (error (QAbstractSocket::SocketError)), this, SLOT (SockError (QAbstractSocket::SocketError))); connect (this, SIGNAL (connected()), this, SLOT (DidConnect ())); connect (this, SIGNAL (disconnected ()), this, SLOT (DidDisconnect ())); connect (this, SIGNAL (readyRead ()), this, SLOT (Receive ())); connect (this, SIGNAL (bytesWritten (qint64)), this, SLOT (CountBytesOut (qint64))); qDebug () << " IrcSocket " << objectName(); }
CNetSock::CNetSock(IBridgeNet* pBridge, QObject *parent) : QTcpSocket(parent),m_pMsgOut(NULL),m_pMsgIn(NULL), m_pBridge(pBridge) { connect(this, SIGNAL(bytesWritten(qint64)), this, SLOT(SockBytesSend(qint64))); connect(this, SIGNAL(readyRead()), this, SLOT(SockReadyRead())); connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(SockError(QAbstractSocket::SocketError))); }
void Socket<T, typename std::enable_if<Convertible<T*, base_addr*>()>::type>::setReuseAddress(bool flag) { int value = flag ? 1 : 0; int rc; rc = setsockopt(this->_sockfd, SOL_SOCKET,SO_REUSEADDR,reinterpret_cast<const char*>(value),sizeof(value)); if (rc == -1) throw SockError("Error in setting Socket Options"); }
void Socket<T, typename std::enable_if<Convertible<T*, base_addr*>()>::type>::getKeepAlive() { int value = 0; int rc; rc = setsockopt(this->_sockfd, SOL_SOCKET,SO_KEEPALIVE, reinterpret_cast<const char*>(value),sizeof(value)); if (rc == -1) { throw SockError("Error in setting Socket Options"); } }
void Socket<T, typename std::enable_if<Convertible<T*, base_addr*>()>::type>::setNonBlocking(bool flag) { int iResult; iResult = ioctl(_sockfd, FIONBIO, &flag); if (iResult == -1) { throw SockError("ioctl failed with error in setting socket to non-blocking"); } }
void Socket<T, typename std::enable_if<Convertible<T*, base_addr*>()>::type>::setNoDelay(bool flag) { //Returns the value of the TCP_NODELAY socket option. int value = flag ? 1 : 0; int rc; rc = setsockopt(this->_sockfd, IPPROTO_TCP,TCP_NODELAY,reinterpret_cast<const char*>(value),sizeof(value)); if (rc == -1) { throw SockError("Error in setting Socket Options"); } }
void SockWrapperPlain::Write(string s) { ssize_t r; if (!sock_ok) return; if ((r = write(send_fd, s.c_str(), s.size())) <= 0) { if (r == 0) { sock_ok = false; throw SockError("Connection reset by peer..."); } else if(!sockerr_again()) { sock_ok = false; throw SockError(string("Read error: ") + strerror(errno)); } } }
int Socket<T, typename std::enable_if<Convertible<T*, base_addr*>()>::type>::writeBytes(const string& data) { const char* message = data.c_str(); // is this being lost ?? int sent = 0, length = data.length(); for(int i=length; i!=0 ; i-=sent ) { sent = send(_sockfd, message + length - i, i, 0); if( sent < 1 ) throw SockError("Message could not be sent."); } }
static void setupSockets(void) { static int initialised = 0; if ( !initialised ) { #ifdef HAVE_WINSOCK WSADATA data; #ifdef USE_WINSOCK2 WORD wversion = MAKEWORD(2, 0); #else WORD wversion = MAKEWORD(1, 1); #endif if ( WSAStartup(wversion, &data) != 0 ) errorPce(NIL, NAME_socket, NAME_initialise, SockError()); DEBUG(NAME_socket, Cprintf("WSAStartup(): wVersion = %d.%d, wHighVersion = %d.%d\n", data.wVersion >> 8, data.wVersion & 0xff, data.wHighVersion >> 8, data.wHighVersion & 0xff); Cprintf("Description: %s\n", data.szDescription); Cprintf("Status: %s\n", data.szSystemStatus); );
// // 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()'