static err_t echo_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { os_printf("Echo recv!\n"); HTTPServer* self = (HTTPServer*) arg; int i; int len; char *pc; if (err == ERR_OK && p != NULL) { // Inform TCP that we have taken the data. tcp_recved(pcb, p->tot_len); os_printf("TCP recv no error!\n"); //pointer to the pay load pc = (char *)p->payload; //size of the pay load len = p->tot_len; uint16_t bufferLength = 1500; char buffer[bufferLength]; self->onReceive(pc); self->receiveCallback(pc, buffer); pbuf_free(p); err = tcp_write(pcb, buffer, bufferLength, 0); tcp_sent(pcb, data_sent); } if (err == ERR_OK && p == NULL) { close_conn(pcb); } return ERR_OK; }
HTTPServerRequestDespatcher::HTTPServerRequestDespatcher(HTTPServer& httpServer, SQLiteDB* pMonitoringDB, SQLiteDB* pLoadTestingDB) : m_server(httpServer), m_pMonitoringDB(pMonitoringDB), m_pLoadTestingDB(pLoadTestingDB), m_pResultsSaver(NULL) { m_webContentPath = httpServer.getWebContentPath(); m_authenticationType = httpServer.getAuthenticationType(); }
void run() { #ifndef CINATRA_SINGLE_THREAD HTTPServer s(num_threads_); #else HTTPServer s; #endif aop_.set_func(std::bind(&HTTPRouter::dispatch, router_, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); s.set_request_handler([this](Request& req, Response& res) { ContextContainer ctx(app_container_); return aop_.invoke(req, res, ctx); }) .set_error_handler(error_handler_) .static_dir(static_dir_); for (auto const & info : http_listen_infos_) { s.listen(info.address, info.port); } #ifdef CINATRA_ENABLE_HTTPS for (auto const & info : https_listen_infos_) { s.listen(info.address, info.port, info.cfg); } #endif // CINATRA_ENABLE_HTTPS s.run(); }
void read_cb(evutil_socket_t evs, short events, void *ptr) { #ifdef _DEBUG_MODE_ printf("client %d: read_cb\n", evs); //syslog(LOG_DEBUG, "client %d: read_cb\n", evs); #endif /* Last parameter is http server object */ HTTPServer *srv = (HTTPServer *)ptr; /* Read from socket */ char buf[BUF_SIZE]; ssize_t len = recv(evs, buf, BUF_SIZE, 0); if (len == 0) { /* Close connection */ srv->finishReading(evs); } else if (len != -1) { /* Add string from inBuf */ std::string header(buf, len); std::string inBuf = srv->getInBuf(evs); if (!inBuf.empty()) header = inBuf + header; /* Set response to client */ srv->setResponse(evs, header); } }
//|//////////////////// TestClient ////////////////////////////////////////// void TestClient() { threadlib::ThreadControl tc; HTTPServer server; server.sigRespond.attach([&](HTTPServer::socket_t socket, HTTPRequest const &request) { cout << " ServerReceive: " << request.method() << " " << request.location() << endl; server.send(socket, HTTPResponse("<HTML>OK</HTML>")); }); server.start(1202); HTTPResponse response; HTTPClient::execute(HTTPRequest("GET", "http://127.0.0.1:1202/objects"), &response); // HTTPClient::execute(HTTPRequest("GET", "http://www.websocket.org/echo.html"), &response); if (response.status() == 200) { cout << " ClientReceive: " << string(response.payload().begin(), response.payload().end()) << "\n"; } else cout << " ** No Data\n"; tc.join_threads(); cout << endl; }
void worker_cb(evutil_socket_t evs, short events, void *ptr) { int client_fd; ssize_t size; int BUF_LEN = 32; char buf[BUF_LEN]; struct msghdr msg; struct iovec iov; union { struct cmsghdr cmsghdr; char control[CMSG_SPACE(sizeof(int))]; } cmsgu; struct cmsghdr *cmsg; iov.iov_base = (void *)buf; iov.iov_len = BUF_LEN; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = cmsgu.control; msg.msg_controllen = sizeof(cmsgu.control); size = recvmsg(evs, &msg, 0); if (size < 0) { perror("recvmsg"); exit(1); } cmsg = CMSG_FIRSTHDR(&msg); if (cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) { if (cmsg->cmsg_level != SOL_SOCKET) { fprintf(stderr, "invalid cmsg_level %d\n", cmsg->cmsg_level); exit(1); } if (cmsg->cmsg_type != SCM_RIGHTS) { fprintf(stderr, "invalid cmsg_type %d\n", cmsg->cmsg_type); exit(1); } client_fd = *((int *)CMSG_DATA(cmsg)); printf("worker: received fd = %d\n", client_fd); } else { client_fd = -1; } if (client_fd != -1) { /* Last parameter is http server object */ HTTPServer *srv = (HTTPServer *)ptr; /* Add client to worker process */ srv->addWorkerClient(client_fd); } }
static err_t echo_accept(void *arg, struct tcp_pcb *pcb, err_t err) { HTTPServer* self = (HTTPServer*) arg; self->onAccept(); tcp_setprio(pcb, TCP_PRIO_MIN); tcp_recv(pcb, echo_recv); tcp_err(pcb, NULL); //Don't care about error here tcp_poll(pcb, NULL, 4); //No polling here return ERR_OK; }
int main() { signal(SIGINT, sghandler); signal(SIGPIPE, SIG_IGN); SocketAddress a("127.0.0.1", 8000); HTTPServer Server; Server.Bind(a); Server.Listen(); Server.Run(); return 0; }
void accept_cb(evutil_socket_t evs, short events, void *ptr) { #ifdef _DEBUG_MODE_ printf("server: accept_cb\n"); #endif /* Last parameter is http server object */ HTTPServer *srv = (HTTPServer *)ptr; /* Accept incoming connection */ int fd = accept(evs, 0, 0); srv->addClient(fd); }
//----------------------------------------------------------------------------- void HTTPHandler::admin_handle(struct evhttp_request *req, void *arg) { //TODO(binfei): need ssl and sepecial command to do admin privilege LOG(INFO) << "Request for server admin."; // TODO(binfei): need memory pool struct evbuffer *databuf = evbuffer_new(); evbuffer_add_printf(databuf, "Server will be stoped."); evhttp_send_reply_start(req, 200, "OK"); evhttp_send_reply_chunk(req, databuf); evhttp_send_reply_end(req); evbuffer_free(databuf); HTTPServer *server = static_cast<HTTPServer*>(arg); server->Stop(); }
int main(int argc, char *argv[]) { std::cout << "Initializing HTTP server" << std::endl; HTTPServer httpServer; std::string featureServerAddr(argv[2]); // = "0.0.0.0:50051"; if (!httpServer.init(featureServerAddr)) { qCritical() << "Starting HTTP Server failed"; return 1; } std::string httpServerAddr(argv[1]); // = "0.0.0.0:50056"; httpServer.run(httpServerAddr); return 0; }
int main(int argc, char** argv) { printf("Running CSL Version: %s\n", CSL::GetVersionString()); string configFile; struct option longopts[] = { { "config", required_argument, NULL, 'f' }, { 0, 0, 0, 0 } }; int opt; while ((opt = getopt_long(argc, argv, "f:", longopts, NULL)) != -1) { switch (opt) { case 'f': configFile = string(optarg); break; } } if (configFile.empty()) { fprintf(stderr, "Error: Please specify a config file\n"); usage(); return 1; } Config config; if (!config.Load(configFile)) { fprintf(stderr, "Error: Failed to load config file %s\n", configFile.c_str()); return 1; } std::thread httpThread([&](){ HTTPServer* pServer = new HTTPServer(config); pServer->Run(); delete pServer; }); httpThread.join(); return 0; }
void write_cb(evutil_socket_t evs, short events, void *ptr) { #ifdef _DEBUG_MODE_ printf("client %d: write_cb\n", evs); #endif /* Last parameter is http server object */ HTTPServer *srv = (HTTPServer *)ptr; bool err_flag = false; /* Answer with a string from outBuf */ std::string resp = srv->getResponse(evs); assert(resp.size() > 0); while (!resp.empty() && !err_flag) { /* Send response */ ssize_t sent = send(evs, resp.c_str(), resp.size(), 0); #ifdef _DEBUG_MODE_ printf("server: %zd/%zd bytes sent to client %d\n", sent, resp.size(), evs); #endif if (sent > 0) { /* Decrease string size */ resp = resp.substr(sent); } else { err_flag = true; } } if (err_flag) { if (errno != EAGAIN) { /* Remove write event for client */ srv->finishWriting(evs); } else { srv->pushToOutBuf(evs, resp); } } else { std::string str = srv->getInBuf(evs); if (str.empty()) { /* Remove write event for client */ srv->finishWriting(evs); } else { srv->setResponse(evs, str); } } }
bool start() { bool throws = false; t_ = std::thread([&]() { server_->start([&]() { barrier_.wait(); }, [&](std::exception_ptr /*ex*/) { throws = true; server_ = nullptr; barrier_.wait(); }); }); barrier_.wait(); return !throws; }
void DCServer::startServer ( ) { HTTPServer *server = new HTTPServer(); server->start(); //Request * r = new Request("net_address_type"); //QJsonDocument data = r->get(); //parse("net_address_type", data); /*r->setTablename("net_address"); data = r->get(); parse("net_address", data);*/ /*r->setTablename("device"); data = r->get(); parse("device", data);*/ //QObject::connect(taskMan, SIGNAL(sig_callTask(QString)), this, SLOT(slt_callDevice(QString))); //taskMan->run(); }
// Our main test program int main(int argc,TCHAR* argv[], TCHAR* /*envp[]*/) { int nRetCode = 0; HMODULE hModule = ::GetModuleHandle(NULL); InitializeCriticalSection(&std_stream); if(hModule == NULL) { _tprintf(_T("Fatal Error: GetModuleHandle failed\n")); nRetCode = 1; } else { // initialize MFC and print and error on failure if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) { _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { printf("TESTPROGAM: MARLIN SERVER\n"); printf("=========================\n"); printf("\n"); printf("Version string: %s\n",MARLIN_SERVER_VERSION); printf("----------------------------------\n"); printf("\n"); // See if we must do the standalone WebServiceServer test // Or that we should do the flat HTTPServer tests if(argc >= 2) { if(_stricmp(argv[1],"/ws") == 0) { CString contract = "http://interface.marlin.org/testing/"; printf("WebServiceServer test for \"%s\"\n",contract.GetString()); printf("----------------------------------------------------------------\n"); printf("\n"); // Test the Interface nRetCode = TestWebServiceServer(NULL,contract,logLevel); } } else { HTTPServer* server = nullptr; LogAnalysis* logfile = nullptr; if(StartServer(server,logfile)) { // Fire up all of our test sites int errors = 0; // Individual tests errors += Test_CrackURL(); errors += Test_HTTPTime(); errors += TestThreadPool(server->GetThreadPool()); // HTTP tests errors += TestBaseSite(server); errors += TestSecureSite(server); errors += TestClientCertificate(server,true); errors += TestCookies(server); errors += TestFormData(server); errors += TestJsonData(server); errors += TestInsecure(server); errors += TestPushEvents(server); errors += TestBodySigning(server); errors += TestBodyEncryption(server); errors += TestMessageEncryption(server); errors += TestReliable(server); errors += TestReliableBA(server); errors += TestToken(server); errors += TestSubSites(server); errors += TestFilter(server); errors += TestPatch(server); errors += TestCompression(server); errors += TestAsynchrone(server); errors += TestWebSocket(server); // Test the WebServiceServer program generation CString contract = "http://interface.marlin.org/testing/"; errors += TestJsonServer(server,contract,logLevel); errors += TestWebServiceServer(server,contract,logLevel); // See if we should wait for testing to occur if(errors) { printf("\n" "SERVER (OR PROGRAMMING) IN ERROR STATE!!\n" "%d sites not correctly started\n" "\n",errors); } else { printf("\n" "Server running....\n" "Waiting to be called by test clients...\n" "\n"); // Wait for key to occur WaitForKey(); } // Try to stop the WebSocket // errors += StopWebSocket(); // // Try to stop the subsites errors += StopSubsites(server); // Testing the errorlog function server->ErrorLog(__FUNCTION__,5,"Not a real error message, but a test to see if it works :-)"); printf("Stopping the server\n"); server->StopServer(); // See if the server is indeed in stopped state printf("The server is %s\n",server->GetIsRunning() ? "still running!\n" : "stopped.\n"); // Remember for a cmd shell nRetCode = errors; } else { totalErrors = 1; printf("HTTPServer in error state in : Error %lu: %s\n" ,server->GetLastError() ,(LPCTSTR)GetLastErrorAsString(GetLastError())); } CleanupServer(server,logfile); } } printf("\n"); printf("SUMMARY OF ALL SERVER TESTS\n"); printf("===========================\n"); if(totalErrors) { printf("ERRORS: %d\n",nRetCode += totalErrors); } else { printf("ALL OK !!!! YIPEEEE!!!!\n"); } WaitForKey(); WaitForKey(); } DeleteCriticalSection(&std_stream); return nRetCode; }
// Parse the first nessages when starting a new message handler, // which is used to determine the name of the resource to // initialize, or load from the cache. cygnal::Buffer * Handler::parseFirstRequest(int fd, gnash::Network::protocols_supported_e proto) { GNASH_REPORT_FUNCTION; string key; Network net; cygnal::Buffer *buf = 0; boost::mutex::scoped_lock lock(_mutex); switch (proto) { case Network::NONE: break; case Network::HTTP: { #if 0 int ret = _http[fd]->readNet(fd, buf); if (ret) { _http[fd]->processHeaderFields(buf); string hostname, path; string::size_type pos = _http[fd]->getField("host").find(":", 0); if (pos != string::npos) { hostname += _http[fd]->getField("host").substr(0, pos); } else { hostname += "localhost"; } path = _http[fd]->getFilespec(); key = hostname + path; log_debug("HTTP key is: %s", key); _keys[fd] = key; } else { log_error("HTTP key couldn't be read!"); } #else HTTPServer http; size_t bytes = http.sniffBytesReady(fd); if (bytes) { buf = new cygnal::Buffer(bytes); } else { return 0; } int ret = http.readNet(fd, buf); if (ret) { http.processHeaderFields(buf); string hostname, path; string::size_type pos = http.getField("host").find(":", 0); if (pos != string::npos) { hostname += http.getField("host").substr(0, pos); } else { hostname += "localhost"; } path = http.getFilespec(); key = hostname + path; log_debug("HTTP key is: %s", key); _keys[fd] = key; } else { log_error("HTTP key couldn't be read!"); } #endif break; } case Network::HTTPS: break; case Network::RTMP: { // _rtmp[fd]->recvMsg(fd); break; } case Network::RTMPT: case Network::RTMPTS: case Network::RTMPE: case Network::RTMPS: case Network::DTN: default: log_error("FD #%d has no protocol handler registered", fd); break; }; return buf; }
static err_t data_sent(void *arg, struct tcp_pcb *pcb, u16_t len) { HTTPServer* self = (HTTPServer*) arg; self->onSendAcknowledged(); }
MMISessionManager::~MMISessionManager() { HTTPServer* httpServer = HTTPServer::getInstance(); httpServer->unregisterServlet(this); }
ProtocolHTTP(const std::string &modname) : Module(modname) { for (int i = 0, j = Sinkhole::Config->CountBlock("http"); i < j; ++i) { Sinkhole::ConfigurationBlock &b = Sinkhole::Config->GetBlock("http", i); try { std::string name = b.GetValue("name"); int timeout = atoi(b.GetValue("timeout").c_str()); if (timeout < 0) timeout = 60; HTTPServer *s = HTTPServer::Find(name); if (s == NULL) { s = new HTTPServer(name); Sinkhole::Log(Sinkhole::LOG_INFORMATIONAL) << "HTTP server " << name << " starting up"; } s->timeout = timeout; for (int k = 0, l = b.CountBlock("listen"); k < l; ++k) { Sinkhole::ConfigurationBlock &lb = b.GetBlock("listen", k); try { std::string listen_address = lb.GetValue("addr"); int listen_port = atoi(lb.GetValue("port").c_str()); if (listen_port <= 0 || listen_port > 65535) listen_port = 80; bool ipv6 = lb.GetBool("ipv6"); Sinkhole::sockaddrs addr; addr.pton(ipv6 ? AF_INET6 : AF_INET, listen_address, listen_port); s->listeners.push_back(new HTTPListener(s, addr.addr(), listen_port, ipv6 ? AF_INET6 : AF_INET)); } catch (const Sinkhole::SocketException &ex) { Sinkhole::Log(Sinkhole::LOG_ERROR) << "Error binding to address " << lb.GetValue("addr") << ":" << lb.GetValue("port") << ": " << ex.GetReason(); } catch (const Sinkhole::ConfigException &ex) { Sinkhole::Log(Sinkhole::LOG_ERROR) << "Error loading listen block number " << k << " for HTTP: " << ex.GetReason(); } } for (int k = 0, l = b.CountBlock("action"); k < l; ++k) { Sinkhole::ConfigurationBlock &ab = b.GetBlock("action", k); try { std::string aname = ab.GetValue("name"); std::string sname = ab.GetValue("server-name"); std::vector<HTTPVhost> vhosts; for (int m = 0, n = ab.CountBlock("vhost"); m < n; ++m) { Sinkhole::ConfigurationBlock &vb = ab.GetBlock("vhost", m); std::string vname = vb.GetValue("name"); HTTPVhost::Type t = HTTPVhost::TYPE_SERVE; std::string data; try { data = vb.GetValue("serve"); } catch (const Sinkhole::ConfigException &) { t = HTTPVhost::TYPE_ROOT; try { data = vb.GetValue("root"); } catch (const Sinkhole::ConfigException &) { throw Sinkhole::ConfigException("You must define either serve or root"); } } HTTPVhost vhost; vhost.name = vname; vhost.data = data; vhost.type = t; vhosts.push_back(vhost); } HTTPVhost::Type t = HTTPVhost::TYPE_SERVE; std::string data; try { data = ab.GetValue("serve"); } catch (const Sinkhole::ConfigException &) { t = HTTPVhost::TYPE_ROOT; try { data = ab.GetValue("root"); } catch (const Sinkhole::ConfigException &) { throw Sinkhole::ConfigException("You must define either serve or root"); } } HTTPAction *a = new HTTPAction(); a->vhosts = vhosts; a->name = aname; a->server_name = sname; a->data = data; a->type = t; s->actions.insert(std::make_pair(a->name, a)); } catch (const Sinkhole::ConfigException &ex) { Sinkhole::Log(Sinkhole::LOG_ERROR) << "Error loading http:action for " << name << ": " << ex.GetReason(); } } for (int k = 0, l = b.CountBlock("class"); k < l; ++k) { Sinkhole::ConfigurationBlock &cb = b.GetBlock("class", k); try { std::vector<Sinkhole::cidr> sources; for (int m = 0, n = cb.CountBlock("source"); m < n; ++m) { Sinkhole::ConfigurationBlock &cbs = cb.GetBlock("source", m); Sinkhole::cidr range(cbs.GetValue("addr")); sources.push_back(range); } std::string action = cb.GetValue("action"); HTTPAction *a = s->FindAction(action); if (a == NULL) throw Sinkhole::ConfigException("Unknown action \"" + action + "\""); HTTPClass *c = new HTTPClass(a); c->sources = sources; s->classes.push_back(c); } catch (const Sinkhole::SocketException &ex) { Sinkhole::Log(Sinkhole::LOG_ERROR) << "Error loading http:class:source for " << name << ": " << ex.GetReason(); } catch (const Sinkhole::ConfigException &ex) { Sinkhole::Log(Sinkhole::LOG_ERROR) << "Error loading http:class:source for " << name << ": " << ex.GetReason(); } } } catch (const Sinkhole::ConfigException &ex) { Sinkhole::Log(Sinkhole::LOG_ERROR) << "Error loading http block " << i << ": " << ex.GetReason(); } } }
~ServerThread() { if (server_) { server_->stop(); } t_.join(); }
void SiteHandlerStream::HandleStream(EventStream* p_stream) { bool result = false; // Use the event stream testStream = p_stream; HTTPServer* server = p_stream->m_site->GetHTTPServer(); // Report it xprintf("NEW EVENT STREAM : %p\n", (void*)testStream); for(int x = 1; x <= EventTests; ++x) { ServerEvent* eventx = new ServerEvent("message"); eventx->m_id = x; eventx->m_data.Format("This is message number: %u\n",x); result = server->SendEvent(p_stream,eventx); // --- "---------------------------------------------- - ------ qprintf("Event stream OnMessage %d sent : %s\n", x, result ? "OK" : "ERROR"); if(result) { --totalChecks; } else { xerror(); } // Waiting long time to see if the flush works and testing event streams // with immediately reaction on the client // Sleep(20000); // Wait 1/10 of a second Sleep(100); } xprintf("Sending other messages\n"); ServerEvent* ander = new ServerEvent("other"); ander->m_id = 1; ander->m_data = "This is a complete different message in another set of stories."; result = server->SendEvent(p_stream,ander); // --- "---------------------------------------------- - ------ qprintf("Event stream 'other' message sent : %s\n", result ? "OK" : "ERROR"); if(result) { --totalChecks; } else { xerror(); } xprintf("Sending an error message\n"); ServerEvent* err = new ServerEvent("error"); err->m_id = 0; err->m_data = "This is a very serious bug report from your server! Heed attention to it!"; result = server->SendEvent(p_stream,err); // --- "---------------------------------------------- - ------ qprintf("Event stream 'OnError' message sent : %s\n", result ? "OK" : "ERROR"); if(result) { --totalChecks; } else { xerror(); } // Implicitly sending an OnClose xprintf("Closing event stream\n"); server->CloseEventStream(p_stream); // Check for closed stream result = !server->HasEventStream(p_stream); // --- "---------------------------------------------- - ------ qprintf("Event stream closed by server (OnClose sent) : %s\n", result ? "OK" : "ERROR"); if(result) { --totalChecks; } else { xerror(); } }