/****************************************************************************** ** controlConnection() ** Description: A function that runs the connection to the client. The program ** prints to the client screen what actions are taking place, and changes the ** userCommand, dataPort and filename. Used in startServer. ** Parameters: current socket endpoint to receive data, user command (from tag), ** data port number, and the filename ** Output: 0 success, -1 error ******************************************************************************/ int controlConnection(int controlSocket, char *userCommand, int *dataPort, char* filename){ // set up variables, buffer for input and output char dataIn[PAYLOAD_LENGTH + 1]; char tagIn[TAG_LENGTH + 1]; char dataOut[PAYLOAD_LENGTH + 1]; char tagOut[TAG_LENGTH + 1]; // get the command(tag) and data // call receivePacket() to get the data port printf(" Receiving data port...\n"); receivePacket(controlSocket, tagIn, dataIn); if (strcmp(tagIn, "DPORT") == 0) { *dataPort = atoi(dataIn); } // call receivePacket to get client user command and filename printf(" Receiving user command ...\n"); receivePacket(controlSocket, tagIn, dataIn); strcpy(userCommand, tagIn); strcpy(filename, dataIn); // check if user entered the command (either -l or -g) correctly if (strcmp(tagIn, "LIST") != 0 && strcmp(tagIn, "GET") != 0) { printf(" Sending command error ...\n"); strcpy(tagOut, "ERROR"); strcpy(dataOut, "Command must be either -l or -g"); handleRequest(controlSocket, tagOut, dataOut); return -1; } // after the above collects the: port, client user command and checks for errors, // send the socket and client user command to handle the request (which sends data/file) else { printf(" Sending okay for data connection...\n"); strcpy(tagOut, "OKAY"); handleRequest(controlSocket, tagOut, ""); return 0; } }
int main(int argc, char *argv[]) { int lfd, cfd; /* Listening and connected sockets */ struct sigaction sa; /* The "-i" option means we were invoked from inetd(8), so that all we need to do is handle the connection on STDIN_FILENO */ if (argc > 1 && strcmp(argv[1], "-i") == 0) { handleRequest(STDIN_FILENO); exit(EXIT_SUCCESS); } if (becomeDaemon(0) == -1) errExit("becomeDaemon"); sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sa.sa_handler = grimReaper; if (sigaction(SIGCHLD, &sa, NULL) == -1) { syslog(LOG_ERR, "Error from sigaction(): %s", strerror(errno)); exit(EXIT_FAILURE); } lfd = inetListen(SERVICE, 10, NULL); if (lfd == -1) { syslog(LOG_ERR, "Could not create server socket (%s)", strerror(errno)); exit(EXIT_FAILURE); } for (;;) { cfd = accept(lfd, NULL, 0); /* Wait for connection */ if (cfd == -1) { syslog(LOG_ERR, "Failure in accept(): %s", strerror(errno)); continue; /* Try next */ } switch (fork()) { /* Create child for each client */ case -1: syslog(LOG_ERR, "Can't create child (%s)", strerror(errno)); close(cfd); /* Give up on this client */ break; /* May be temporary; try next client */ case 0: /* Child */ close(lfd); /* Don't need copy of listening socket */ handleRequest(cfd); _exit(EXIT_SUCCESS); default: /* Parent */ close(cfd); /* Don't need copy of connected socket */ break; /* Loop to accept next connection */ } } }
void ProxyScout::downloadResult(bool success) { KNotifyClient::Instance notifyInstance(m_instance); if(success) try { m_script = new Script(m_downloader->script()); } catch(const Script::Error &e) { KNotifyClient::event("script-error", i18n("The proxy configuration script is invalid:\n%1").arg(e.message())); success = false; } else KNotifyClient::event("download-error", m_downloader->error()); for(RequestQueue::ConstIterator it = m_requestQueue.begin(); it != m_requestQueue.end(); ++it) { QCString type = "QString"; QByteArray data; QDataStream ds(data, IO_WriteOnly); if(success) ds << handleRequest((*it).url); else ds << QString("DIRECT"); kapp->dcopClient()->endTransaction((*it).transaction, type, data); } m_requestQueue.clear(); m_downloader->deleteLater(); m_downloader = 0; // Suppress further attempts for 5 minutes if(!success) m_suspendTime = std::time(0); }
int main(int argc, char **argv) { // Basic init FILE * hittite = fopen("/dev/hittite", "w+"); // Resetting GPIB bus fprintf(hittite, "*IDN?\n"); char id[1024]; efgets(id, 1023, hittite); printf("*IDN? : %s", id); char socketBuffer[1024]; int sockfd = initServer(atoi(argv[1])); while(1) { int clientfd = eaccept(sockfd); int ret = myRead( clientfd, socketBuffer, 1024 ); while( ret > 0 ) { printf("Received: %s\n", socketBuffer); handleRequest(socketBuffer, &clientfd, hittite); ret = myRead(clientfd, socketBuffer, 1024); } close(clientfd); } return EXIT_SUCCESS; }
int main(int argc, char **argv) { int maxsock,sockfd,sock_auth; unsigned int myport,listnum; fd_set fdsr; struct timeval tv; char *url = "OK OK"; int ret; myport = DEF_LISTEN_PORT; // listnum = 10; listnum = SOMAXCONN; if(argc > 1) { myport = atoi(argv[1]); } if(myport <= 0 ) { printf("%s invalid paramters!\n",argv[0]); return 0; } sockfd = create_server_socket(myport,listnum); if(sockfd == -1) { return 0; } maxsock = sockfd; LDEBUG("%s start to listen\n",argv[0]); while(1) { //init file desc set FD_ZERO(&fdsr); FD_SET(sockfd, &fdsr); // timeout setting tv.tv_sec = 30; tv.tv_usec = 0; ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv); if(ret < 0) { printf("select error"); break; } else if(ret == 0) { LDEBUG("timeout\n"); continue; } if(FD_ISSET(sockfd, &fdsr)) { handleRequest(sockfd,url); } } return 0; }
void Worker::RequestHandler::runArg(const boost::any &arg) { ReqRspQueuePair* queuePair = boost::any_cast<ReqRspQueuePair*>(arg); while(1) { base::Block<SplitInfo>* requestBlock; queuePair->requestQueue.getReadSlot(&requestBlock); SplitInfo request = requestBlock->data; //make sure copy is OK queuePair->requestQueue.slotRead(requestBlock); int32_t responseCode = handleRequest(request, &queuePair->responseQueue); /** * create response */ base::Block<SplitInfo>* responseBlock; queuePair->responseQueue.getWriteSlot(&responseBlock); SplitInfo s; s.type = SplitInfo::FETCH_SPLIT_RESPONSE; s.filename = request.id; //TODO filename is a confusing name s.responseCode = responseCode; LOG(INFO) << "response for " << s.filename << " : " << s.responseCode; responseBlock->data = s; queuePair->responseQueue.slotWritten(responseBlock); } }
void physicsThreadMain(u32 arg) { physicsThread_s* p=(physicsThread_s*)arg; while(!p->exit) { svcWaitSynchronization(p->requestMutex, U64_MAX); appendRequestQueue(&p->privateList, &p->requestList); svcReleaseMutex(p->requestMutex); // bool debug=false; // u64 val=svcGetSystemTick(); request_s* r=NULL; while((r=unqueueRequest(&p->privateList)) && !p->exit) { handleRequest(p, r); svcSleepThread(1000); } // if(debug)print("%d ticks\n",(int)(svcGetSystemTick()-val)); updateOBBs(); svcSleepThread(1000000); } svcExitThread(); }
int server(struct dnsServer *srv) { int recvlen; int slen = sizeof(srv->client); //initialize the server if ((srv->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) return die("SOCKET", -1); memset(&srv->server, 0, sizeof(srv->server)); srv->server.sin_family = AF_INET; srv->server.sin_port = htons(srv->port); srv->server.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(srv->sock, (struct sockaddr*)&srv->server, sizeof(srv->server)) == -1) return die("BIND", -1); for (;;) { if ((recvlen = recvfrom(srv->sock, srv->buffer, BUFFER_LEN, 0, (struct sockaddr *)&srv->client, &slen)) == -1) { close(srv->sock); return die("RECV", -1); } handleRequest(srv, recvlen); } close(srv->sock); return 0; }
int main(int argc, char *argv[]) { if(argc!=3) { //fprintf(stderr,"Usage: server [portnum] [file-system-image]\n"); exit(0); } int portNum=atoi(argv[1]); sprintf(imgName,argv[2]); //Open the port sd=UDP_Open(portNum); assert(sd != -1); initImage(imgName); char buffer[sizeof(msg_t)]; //Server listening in loop while(1) { //read incoming message from port int rc=UDP_Read(sd, &addr, buffer, sizeof(msg_t)); if(rc>0) { handleRequest(buffer); rc = UDP_Write(sd, &addr, buffer, sizeof(msg_t));//Send back the response to the client } } return 0; }
int main(int argc, char **argv) { QueryParameters parameters(argc == 2 ? argv[1] : getenv("QUERY_STRING")); handleRequest(parameters); return 0; }
void WiFlyDevice::waitForRequest() { int timeout = 8000; unsigned long start = millis(); static char expected[] = "*OPEN*"; int index = 0; Serial.println("Waiting for open"); while (true) { while (!uart.available()) { if (millis() > start + timeout) { enterCommandMode(); uart.println("close"); uart.println("exit"); return; } } char c = uart.read(); Serial.print(c); if (c == expected[index]) { index++; if (index == strlen(expected)) { handleRequest(); return; } } else if (c == '*') { index = 1; // lol } else { index = 0; } } }
OCEntityHandlerResult RCSResourceObject::entityHandler( std::shared_ptr< OC::OCResourceRequest > request) { OC_LOG(WARNING, LOG_TAG, "entityHandler"); if (!request) { return OC_EH_ERROR; } try { if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag) { return handleRequest(request); } if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag) { return handleObserve(request); } } catch (const std::exception& e) { OC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what()); throw; } catch (...) { OC_LOG(WARNING, LOG_TAG, "Failed to handle request."); throw; } return OC_EH_ERROR; }
void* Server::handleClient(void *d) { Socket* aux_sock=(Socket*)d; Socket sock=*aux_sock; while(!closeServer) { char header[HEADER_SIZE]; //Blocking reception (last param=-1) int ret=sock.Receive(header,HEADER_SIZE,-1); if(-1==ret) { LOG_ERROR("Receive error");//sock.Receive outputs LOG break; } if(ret==0) { LOG_ERROR("Should never be here"); continue; } Message message;//buffering if(!message.addHeader(header,ret)) { LOG_ERROR("Incorrect header "<<ret<<" "<<string(header,ret)); break; } const int contentSize=message.getContentSize(); char* buffer=new char[contentSize]; int timeout=100+contentSize/10; if(!sock.ReceiveBytes(buffer,contentSize,timeout)) { LOG_ERROR("Unable to get full message"); break; } message.addContents(buffer,contentSize); delete buffer; string response=handleRequest(message.getContent());//call to virtual method Message responseMsg(response); sock.Send(responseMsg.getBuffer(),responseMsg.bufferSize()); //send response message } sock.close(); mutex.Lock(); for(int i=sockClients.size()-1;i>=0;i--) { if(sockClients[i]==aux_sock) { sockClients.erase(sockClients.begin()+i); clients.erase(clients.begin()+i); LOG_INFO("Closing thread and socket"); break; } } mutex.Unlock(); LOG_INFO("Server: Finishing client. NumClients: "<<sockClients.size()); return NULL; }
void Worker::wait() { fd_set master_set, working_set; FD_ZERO(&master_set); FD_SET(localSocketFd, &master_set); FD_SET(coordSocketFd, &master_set); queue<double> inData; bool computationDone = false; while (!computationDone) { // while (true) { memcpy(&working_set, &master_set, sizeof(master_set)); int selectResult = select(coordSocketFd + 1, &working_set, NULL, NULL, NULL); if (selectResult < 0) { cerr << "WORKER - SELECT FAILED" << endl; return; } if (FD_ISSET(coordSocketFd, &working_set)) { int handleResult = handleRequest(inData); if (handleResult == 1) { computationDone = true; } if (handleResult < 0) { FD_CLR(coordSocketFd, &master_set); close(coordSocketFd); } } } }
static void onSocketDataReceived(SocketClientRef client, size_t available) { if( ! listener ) return; dispatch_suspend(client->source); CRESTRequestRef request = NULL; size_t maxRead = sizeof(client->buffer) - 1; if( available > maxRead ) available = maxRead; if( available > 14 ) { int i = 0; char c; while( i < available && recv(client->fd, &c, 1, 0) > 0 && c > 0 ) { client->buffer[i] = c; i++; } request = CRESTRequestCreateWithBytes((UInt8 const *)&client->buffer, i); } CFDataRef responseData = handleRequest(request); ssize_t wd = send(client->fd, (void const *)CFDataGetBytePtr(responseData), (size_t)CFDataGetLength(responseData), 0); // todo #pragma unused(wd) CFRelease(responseData); CRESTRequestDealloc(request); closeSocketClient(client); }
/* Worker Thread. */ static void * processRequest (void *data) { int sock = *((int *)(data)); LOGD(0, "Inside new thread", sock); int curVal = handleRequest(sock, handleConn, maxConn); if(curVal >= 0) maxConn = curVal; LOGD(0, "Thread has ended", maxConn); pthread_exit(NULL); }
HTTPBigDealRequestHandler::HTTPBigDealRequestHandler(const char* rootPath, const char* localPath, HTTPConnection::HTTPMessage& Msg, TCPSocketConnection& Tcp) : HTTPRequestHandler(Msg, Tcp) { m_rootPath = rootPath; m_localPath = localPath; requestArgs = Msg.args; handleRequest(); }
void WResource::write(WT_BOSTREAM& out, const Http::ParameterMap& parameters, const Http::UploadedFileMap& files) { Http::Request request(parameters, files); Http::Response response(this, out); handleRequest(request, response); // While the resource indicates more data to be sent, get it too. while (response.continuation_ && response.continuation_->resource_) { response.continuation_->resource_ = 0; request.continuation_ = response.continuation_.get(); handleRequest(request, response); } }
TinySqlApiStorage::TinySqlApiStorage(QObject *parent, TinySqlApiServer &server) : QObject(parent), mServer(server) { mSqlHandler = new TinySqlApiSql(this); Q_CHECK_PTR(mSqlHandler); connect(&mServer, SIGNAL(newRequest()), this, SLOT(handleRequest())); }
static void *server_routine(void *arg) { static int status = 0; static int started = 0; if (started) { output_error("server routine is already running"); return NULL; } started = 1; sockfd = (SOCKET)arg; // repeat forever.. while (!shutdown_server) { struct sockaddr_in cli_addr; SOCKET newsockfd; int clilen = sizeof(cli_addr); /* accept client request and get client address */ newsockfd = accept(sockfd,(struct sockaddr *)&cli_addr,&clilen); if ((int)newsockfd<0 && errno!=EINTR) { status = GetLastError(); output_error("server accept error on fd=%d: code %d", sockfd, status); goto Done; } else if ((int)newsockfd > 0) { #ifdef WIN32 output_verbose("accepting incoming connection from %d.%d.%d.%d on port %d", cli_addr.sin_addr.S_un.S_un_b.s_b1,cli_addr.sin_addr.S_un.S_un_b.s_b2,cli_addr.sin_addr.S_un.S_un_b.s_b3,cli_addr.sin_addr.S_un.S_un_b.s_b4,cli_addr.sin_port); #else output_verbose("accepting incoming connection from on port %d",cli_addr.sin_port); #endif if ( pthread_create(&thread_id,NULL, http_response,(void*)newsockfd)!=0 ) output_error("unable to start http response thread"); if (global_server_quit_on_close) shutdown_now(); else gui_wait_status(0); } #ifdef NEVER { handleRequest(newsockfd); #ifdef WIN32 closesocket(newsockfd); #else close(newsockfd); #endif } #endif } output_verbose("server shutdown"); Done: started = 0; return (void*)&status; }
TinySqlApiStorage::~TinySqlApiStorage() { DPRINT << "SQLITEAPISRV:~TinySqlApiStorage.."; disconnect(&mServer, SIGNAL(newRequest()), this, SLOT(handleRequest())); delete mSqlHandler; mSqlHandler = NULL; }
void handleConnection( int sockfd ) { ssize_t bytesRead; char buffer[1024+1]; std::string request; while( 1 ) { bytesRead = read( sockfd, (void *) buffer, 1024 ); if( bytesRead == -1 ) { if( errno == EINTR ) { // fprintf( stdout, "read() interrupted, retrying.\n" ); continue; } fprintf( stderr, "read() failed (%d): '%s'\n", errno, strerror( errno ) ); return; } if( bytesRead == 0 ) { close( sockfd ); return; } buffer[bytesRead] = '\0'; request += buffer; // fprintf( stderr, "DEBUG: request is now '%s'.\n", request.c_str() ); // A given HTTP header is terminated by a blank line. std::string::size_type index = request.find( "\r\n\r\n" ); while( index != std::string::npos ) { std::string header = request.substr( 0, index + 4 ); request = request.substr( index + 4 ); // if( ! request.empty() ) { fprintf( stderr, "DEBUG: request remainder '%s'\n", request.c_str() ); } // fprintf( stderr, "DEBUG: handling request '%s'\n", firstRequest.c_str() ); std::string reply = handleRequest( header, request ); if( ! reply.empty() ) { // fprintf( stderr, "DEBUG: writing reply '%s'\n", reply.c_str() ); ssize_t totalBytesWritten = 0; ssize_t bytesToWrite = reply.size(); const char * outBuf = reply.c_str(); while( totalBytesWritten != bytesToWrite ) { ssize_t bytesWritten = write( sockfd, outBuf + totalBytesWritten, bytesToWrite - totalBytesWritten ); if( bytesWritten == -1 ) { fprintf( stderr, "write() failed (%d), '%s'; aborting reply.\n", errno, strerror( errno ) ); close( sockfd ); return; } totalBytesWritten += bytesWritten; } } index = request.find( "\r\n\r\n" ); } } }
void kul::https::Server::loop() throw(kul::tcp::Exception){ KUL_DBG_FUNC_ENTER int32_t newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if(newsockfd < 0) KEXCEPTION("HTTPS Server error on accept"); ssl = SSL_new(ctx); SSL_set_fd(ssl, newsockfd); //Here is the SSL Accept portion. Now all reads and writes must use SSL int16_t ssl_err = SSL_accept(ssl); if(ssl_err <= 0){ short se = 0; SSL_get_error(ssl, se); KERR << "HTTPS Server SSL ERROR on SSL_ACCEPT error: " << se; close(newsockfd); return; } KLOG(DBG) << "SSL_get_cipher: " << SSL_get_cipher(ssl); cc = SSL_get_peer_certificate (ssl); if(cc != NULL) { KLOG(DBG) << "Client certificate:"; KLOG(DBG) << "\t subject: " << X509_NAME_oneline (X509_get_subject_name (cc), 0, 0); KLOG(DBG) << "\t issuer: %s\n" << X509_NAME_oneline (X509_get_issuer_name (cc), 0, 0); X509_free(cc); }else KLOG(ERR) << "Client does not have certificate."; KOUT(DBG) << "New connection , socket fd is " << newsockfd << ", is : " << inet_ntoa(cli_addr.sin_addr) << ", port : "<< ntohs(cli_addr.sin_port); onConnect(inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port)); int16_t e; char buffer[_KUL_HTTPS_READ_BUFFER_]; std::stringstream cnt; do{ bzero(buffer,_KUL_HTTPS_READ_BUFFER_); e = SSL_read(ssl, buffer, _KUL_HTTPS_READ_BUFFER_ - 1); if(e) cnt << buffer; }while(e == (_KUL_HTTPS_READ_BUFFER_ - 1)); if (e < 0){ short se = 0; SSL_get_error(ssl, se); if(se) KLOG(ERR) << "SSL_get_error: " << se; e = -1; }else try{ std::string res; std::shared_ptr<kul::http::ARequest> req = handleRequest(cnt.str(), res); const kul::http::AResponse& rs(respond(*req.get())); std::string ret(rs.toString()); e = SSL_write(ssl, ret.c_str(), ret.length()); }catch(const kul::http::Exception& e1){ KERR << e1.what(); e = -1; } close(newsockfd); KOUT(DBG) << "Disconnect , socket fd is " << newsockfd << ", is : " << inet_ntoa(cli_addr.sin_addr) << ", port : "<< ntohs(cli_addr.sin_port); onDisconnect(inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port)); }
void WindowSystem::handleConnection() { qDebug() << "SERVER: client connected"; if (QTcpSocket *connection = m_server->nextPendingConnection()) { connect(connection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(handleConnectionError())); connect(connection, SIGNAL(readyRead()), this, SLOT(handleRequest())); connect(connection, SIGNAL(disconnected()), this, SLOT(removeConnection())); } }
FileTransferManager::FileTransferManager (ToxAccount *acc) : QObject { acc } , Acc_ { acc } { connect (this, SIGNAL (requested (int32_t, QByteArray, uint8_t, uint64_t, QString)), this, SLOT (handleRequest (int32_t, QByteArray, uint8_t, uint64_t, QString))); }
/** Starts the server. The server listens on a socket in a separate thread * for connection requests. The socket will send the connection information * back to the client (e.g. MPI port string), and inform the main thread * to accept a new incomming connection. This is a work around for MPI's * blocking MPI_Accept call :( * * \param if_name Name of the interface on which to listen. * \param communication A communication object to communicate with a client. */ Server::Server(const std::string &if_name, ICommunication *communication ) { m_config_dir = ALIO::OS::getConfigDir(); m_file = NULL; m_filedes = 0; m_communication = communication; m_if_name = if_name; m_new_connection_available.setAtomic(0); // Spawn of a thread that will handle incoming connection requests. // This is necessary e.g. in the case of MPI since the MPI_Comm_accept // blocks (and then this process can not do anything else, and trying // to use multi-threading with (esp Open)MPI is a bad idea. pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); // Should be the default, but just in case: pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_t *thread_id = new pthread_t(); int error = pthread_create(thread_id, &attr, &Server::handleConnectionRequests, this); sleep(5000); m_communication->openPort(); FILE *port_file = ALIO::OS::fopen("alio_config.dat", "w"); char *port_name = m_communication->getPortName(); ALIO::OS::fwrite(port_name, 1, strlen(port_name), port_file); ALIO::OS::fclose(port_file); while(1) { if(m_new_connection_available.getAtomic()==1) { m_communication->waitForConnection(); m_new_connection_available.setAtomic(2); } else if (m_new_connection_available.getAtomic()==2) { if(m_communication->waitForMessage()) { printf("Error waiting for message.\n"); return; } char *buffer = m_communication->receive(); handleRequest(buffer); } // new_connection_available==2 } // while } // Server
void DocsumAdapter::Run(FastOS_ThreadInterface *, void *) { setupRequest(); handleRequest(); createReply(); writeLog(); cleanup(); delete this; }
void CMediaSourceClientProfile::senderLoop() { while (mBe) { if (hasRequests()) { handleRequest(); } } }
void CMediaStreamingServerProfile::senderLoop() { LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__); while (mBe) { if (hasRequests()) { handleRequest(); } else { mpReqSemaphore->wait(); } } }
/* UART interrupt function, enters characters into the buffer */ void uart_interrupt() { unsigned char receivedChar; embsys_uart_receive(&receivedChar); enqueue(&requestBuffer, receivedChar); if(receivedChar == '.') handleRequest(); else if(requestBuffer.size == BUFFER_SIZE) requestBuffer.size = 0; /* clear queue if full, to avoid critical problems */ }