Exemplo n.º 1
0
void TCSoapThread(const std::string& host, uint16 port)
{
    struct soap soap;
    soap_init(&soap);
    soap_set_imode(&soap, SOAP_C_UTFSTRING);
    soap_set_omode(&soap, SOAP_C_UTFSTRING);

    // check every 3 seconds if world ended
    soap.accept_timeout = 3;
    soap.recv_timeout = 5;
    soap.send_timeout = 5;
    if (!soap_valid_socket(soap_bind(&soap, host.c_str(), port, 100)))
    {
        TC_LOG_ERROR("network.soap", "Couldn't bind to %s:%d", host.c_str(), port);
        exit(-1);
    }

    TC_LOG_INFO("network.soap", "Bound to http://%s:%d", host.c_str(), port);

    while (!World::IsStopped())
    {
        if (!soap_valid_socket(soap_accept(&soap)))
            continue;   // ran into an accept timeout

        TC_LOG_DEBUG("network.soap", "Accepted connection from IP=%d.%d.%d.%d", (int)(soap.ip>>24)&0xFF, (int)(soap.ip>>16)&0xFF, (int)(soap.ip>>8)&0xFF, (int)soap.ip&0xFF);
        struct soap* thread_soap = soap_copy(&soap);// make a safe copy
        process_message(thread_soap);
    }

    soap_done(&soap);
}
Exemplo n.º 2
0
void TCSoapRunnable::run()
{
    struct soap soap;
    soap_init(&soap);
    soap_set_imode(&soap, SOAP_C_UTFSTRING);
    soap_set_omode(&soap, SOAP_C_UTFSTRING);

    // check every 3 seconds if world ended
    soap.accept_timeout = 3;
    soap.recv_timeout = 5;
    soap.send_timeout = 5;
    if (!soap_valid_socket(soap_bind(&soap, _host.c_str(), _port, 100)))
    {
        TC_LOG_ERROR("network.soap", "Couldn't bind to %s:%d", _host.c_str(), _port);
        exit(-1);
    }

    TC_LOG_INFO("network.soap", "Bound to http://%s:%d", _host.c_str(), _port);

    while (!World::IsStopped())
    {
        if (!soap_valid_socket(soap_accept(&soap)))
            continue;   // ran into an accept timeout

        TC_LOG_DEBUG("network.soap", "Accepted connection from IP=%d.%d.%d.%d", (int)(soap.ip>>24)&0xFF, (int)(soap.ip>>16)&0xFF, (int)(soap.ip>>8)&0xFF, (int)soap.ip&0xFF);
        struct soap* thread_soap = soap_copy(&soap);// make a safe copy

        ACE_Message_Block* mb = new ACE_Message_Block(sizeof(struct soap*));
        ACE_OS::memcpy(mb->wr_ptr(), &thread_soap, sizeof(struct soap*));
        process_message(mb);
    }

    soap_done(&soap);
}
Exemplo n.º 3
0
int run_server(int port)
{ struct soap soap;
  int i, ret;
  /* Enable MTOM */
#ifdef WITH_GZIP
  soap_init1(&soap, SOAP_ENC_MTOM | SOAP_ENC_ZLIB); /* Enable MTOM */
#else
  soap_init1(&soap, SOAP_ENC_MTOM); 
#endif
  /* Set the MIME callbacks */
  soap.fmimereadopen = mime_read_open;
  soap.fmimereadclose = mime_read_close;
  soap.fmimeread = mime_read;
  soap.fmimewriteopen = mime_server_write_open;
  soap.fmimewriteclose = mime_server_write_close;
  soap.fmimewrite = mime_server_write;
  /* Bind socket */
  if (!soap_valid_socket(soap_bind(&soap, NULL, port, 100)))
    soap_print_fault(&soap, stderr);
  else
  { fprintf(stderr, "Bind to port %d successful\n", port);
    /* Optional: let server time out after one hour */
    soap.accept_timeout = 3600;
    /* Unix/Linux SIGPIPE, this is OS dependent:
    soap.accept_flags = SO_NOSIGPIPE;	// some systems like this
    soap.socket_flags = MSG_NOSIGNAL;	// others need this
    signal(SIGPIPE, sigpipe_handle);	// or a sigpipe handler (more portable)
    */
    /* Main thread spawns server threads */
    for (i = 1; ; i++)
    { struct soap *tsoap;
      pthread_t tid;
      int sock = soap_accept(&soap);
      if (!soap_valid_socket(sock))
      { if (soap.errnum)
          soap_print_fault(&soap, stderr);
        else
        { fprintf(stderr, "Server timed out (see code how to change this)\n");
          break;
        }
      }
      fprintf(stderr, "Thread %d accepts socket %d connection from IP %d.%d.%d.%d\n", i, sock, (int)(soap.ip>>24)&0xFF, (int)(soap.ip>>16)&0xFF, (int)(soap.ip>>8)&0xFF, (int)soap.ip&0xFF);
      /* Copy soap environment and spawn thread */
      tsoap = soap_copy(&soap);
      pthread_create(&tid, NULL, (void*(*)(void*))process_request, (void*)tsoap);
    } 
  }
  ret = soap.error;
  soap_done(&soap);
  return ret;
}
Exemplo n.º 4
0
void MaNGOSsoapRunnable::run()
{
    // Create pool
    SOAPWorkingThread pool;
    pool.activate(THR_NEW_LWP | THR_JOINABLE, POOL_SIZE);

    struct soap soap;
    int m, s;
    soap_init(&soap);
    soap_set_imode(&soap, SOAP_C_UTFSTRING);
    soap_set_omode(&soap, SOAP_C_UTFSTRING);
    m = soap_bind(&soap, m_host.c_str(), m_port, 100);

    // Check every 3 seconds if world ended
    soap.accept_timeout = 3;

    soap.recv_timeout = 5;
    soap.send_timeout = 5;
    if (m < 0)
    {
        sLog.outError("MaNGOSsoap: couldn't bind to %s:%d", m_host.c_str(), m_port);
        exit(-1);
    }

    sLog.outString("MaNGOSsoap: bound to http://%s:%d", m_host.c_str(), m_port);

    while (!World::IsStopped())
    {
        s = soap_accept(&soap);

        if (s < 0)
        {
            // Ran into an accept timeout
            continue;
        }

        DEBUG_LOG("MaNGOSsoap: accepted connection from IP=%d.%d.%d.%d", (int)(soap.ip >> 24) & 0xFF, (int)(soap.ip >> 16) & 0xFF, (int)(soap.ip >> 8) & 0xFF, (int)soap.ip & 0xFF);
        // Make a safe copy
        struct soap* thread_soap = soap_copy(&soap);

        ACE_Message_Block* mb = new ACE_Message_Block(sizeof(struct soap*));
        ACE_OS::memcpy(mb->wr_ptr(), &thread_soap, sizeof(struct soap*));
        pool.putq(mb);
    }

    pool.msg_queue()->deactivate();
    pool.wait();

    soap_done(&soap);
}
Exemplo n.º 5
0
Arquivo: xmas.c Projeto: 119-org/TND
int __ns1__dtx(struct soap *soap, _XML x, struct _ns2__commingtotown *response)
{
  struct soap *csoap = soap_copy(soap);
  struct tm tm;
  time_t now, xmas;
  double sec, days;

  soap_set_namespaces(csoap, gmt_namespaces);
  if (soap_call_t__gmt(csoap, "http://www.cs.fsu.edu/~engelen/gmtlitserver.cgi", NULL, &now))
  {
    soap_end(csoap);
    soap_free(csoap);
    return soap_receiver_fault(soap, "Cannot connect to GMT server", NULL);
  }

  tm.tm_sec = 0;
  tm.tm_min = 0;
  tm.tm_hour = 0;
  tm.tm_mday = 25;
  tm.tm_mon = 11;
  tm.tm_year = gmtime(&now)->tm_year; /* this year */
  tm.tm_isdst = 0;
  tm.tm_zone = NULL;

  xmas = soap_timegm(&tm);

  if (xmas < now)
  {
    tm.tm_year++; /* xmas just passed, go to next year */
    xmas = soap_timegm(&tm);
  }

  sec = difftime(xmas, now);
  
  soap_set_namespaces(csoap, calc_namespaces);
  if (soap_call_ns__add(csoap, NULL, NULL, sec, 86400, &days))
  {
    soap_end(csoap);
    soap_free(csoap);
    return soap_receiver_fault(soap, "Cannot connect to calc server", NULL);
  }

  soap_end(csoap);
  soap_free(csoap);

  response->days = (int)days;

  return SOAP_OK;
}
Exemplo n.º 6
0
/**
 * Just a wrapper around soap_serve() created by gSOAP
 * called by DataGatewaySOAPServerThread for a new SOAP request
 * return true if request can be processed
 * This method sets m_hReceiveSoapEvent to signaled state
 * Run method waits this event object and then handles the soap request when the event switches to signaled state
 */
bool SoapHandler::ServeSoap(struct soap* soapEnv)
{
	Util::Debug("SoapHandler::ServeSoap");
	//check can this handler process request in soapEnv
	if ( !IsBusyForSoapRequest() )
	{
		CleanSoapEnv();
		m_SoapEnv = soap_copy(soapEnv);
		//soap_free( soapEnv );
		m_SoapEnv->user = dynamic_cast<HtiSoapHandlerInterface*>( this );
		SetEvent(m_hReceiveSoapEvent);
		Util::Debug("SoapHandler::ServeSoap OK");
		return true;
	}
	else
	{
		Util::Debug("SoapHandler::ServeSoap NOK");
		return false;
	}
}
Exemplo n.º 7
0
void SOAPThread::Work()
{
    soap soap;

    soap_init(&soap);
    soap_set_imode(&soap, SOAP_C_UTFSTRING);
    soap_set_omode(&soap, SOAP_C_UTFSTRING);

    soap.accept_timeout = AcceptTimeout;
    soap.recv_timeout = DataTimeout;
    soap.send_timeout = DataTimeout;

    if (soap_bind(&soap, m_host.c_str(), m_port, BackLogSize) < 0)
    {
        sLog.outError("MaNGOSsoap: couldn't bind to %s:%d", m_host.c_str(), m_port);
        exit(-1);
    }

    sLog.outString("MaNGOSsoap: bound to http://%s:%d", m_host.c_str(), m_port);

    while (!World::IsStopped())
    {
        auto s = soap_accept(&soap);

        // timeout?
        if (s == SOAP_INVALID_SOCKET)
            continue;

        DEBUG_LOG("MaNGOSsoap: accepted connection from IP=%d.%d.%d.%d", (int)(soap.ip >> 24) & 0xFF, (int)(soap.ip >> 16) & 0xFF, (int)(soap.ip >> 8) & 0xFF, (int)soap.ip & 0xFF);

        auto copy = soap_copy(&soap);
        soap_serve(copy);
        soap_destroy(copy);
    }

    soap_end(&soap);
    soap_done(&soap);
}
Exemplo n.º 8
0
int main(int argc, char **argv) 
{ 
   /*
   rapidjson::Document document;
   document.SetObject();
   rapidjson::Value key1("key1");
   rapidjson::Value value1("value1");
   document.AddMember(key1, value1,
		      document.GetAllocator());
   rapidjson::StringBuffer buffer;
   rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
   document.Accept(writer);
  
   std::cout << buffer.GetString() << std::endl;
   std::cout << buffer.GetSize() << std::endl;
   */

   struct soap soap, *tsoap;
   pthread_t tid;
   int m, s;
   //soap_init2(&soap, SOAP_IO_KEEPALIVE, SOAP_IO_KEEPALIVE);
   //soap.max_keep_alive = 10;
   //soap.accept_timeout = 15;
   soap.cookie_domain = ".."; 
   soap.cookie_path = "/"; // the path which is used to filter/set cookies with this destination 
   int count = 0; 
   if (argc < 2)
   { 

      std::cout << "It should contain config file. Please checkout the config examples in config_template" << std::endl;
      exit(1);

      soap_getenv_cookies(&soap); // CGI app: grab cookies from 'HTTP_COOKIE' env var 
      soap_serve(&soap);

   }
   else
   {  
      std::string path_config = argv[1];
      if(!config.LoadFromFile(path_config))
      {
	exit(1);
      }


      m = soap_bind(&soap, NULL, config.GSOAP_SERVER_PORT, 100); 
      if (m < 0)
         exit(1);

      for (count = 0; count >= 0; count++) 
      { 
         soap.socket_flags = MSG_NOSIGNAL; // use this 
         //soap.accept_flags = SO_NOSIGPIPE; // or this to prevent sigpipe 
         s = soap_accept(&soap); 
         if (s < 0) 
         { 
            if (soap.errnum) 
               soap_print_fault(&soap, stderr); 
            else
               fprintf(stderr, "Server timed out\n"); // Assume timeout is long enough for threads to complete serving requests 
            break; 
         } 
         fprintf(stderr, "Accepts socket %d connection from IP %d.%d.%d.%d\n", s, (int)(soap.ip >> 24)&0xFF, (int)(soap.ip >> 16)&0xFF, (int)(soap.ip >> 8)&0xFF, (int)soap.ip&0xFF); 
         tsoap = soap_copy(&soap); 
         pthread_create(&tid, NULL, (void*(*)(void*))process_request, (void*)tsoap); 
      } 

   }
   return 0; 
} 
Exemplo n.º 9
0
OPENSPLICE_SERVICE_ENTRYPOINT (ospl_cmsoap, cmsoap)
{
    cms_service cms;
    cms_client client;
    c_bool success;
    char* name = NULL;
    char* config;
    c_long slave;
    struct soap* soap;
    slave = -1;
    soap = NULL;

       if(argc == 3)
       {
          name = argv[1];
          config = argv[2];
          cms = cms_serviceNew(name,config);

          if(cms != NULL){
             os_signalHandlerExitRequestHandle erh = os_signalHandlerExitRequestHandleNil;

             if(!os_serviceGetSingleProcess()){
                  erh = os_signalHandlerRegisterExitRequestCallback(exitRequestHandler, NULL, NULL, NULL, cms);
             }

             while(cms->terminate == FALSE){
                while( (slave < 0) && (cms->terminate == FALSE)){
                   slave = soap_accept(cms->soap);
                }
                if (slave < 0) {
                   if(cms->configuration->verbosity > 0){
                      /* soap_accept is likely to return -1 when the soap service is shutdown
                       * so should be an INFO message here rather than a WARNING
                       */
                      OS_REPORT(OS_INFO, CMS_CONTEXT, 0,
                                "not accepting requests.");
                   }
                   cms->terminate = TRUE;
                } else {
                   if(cms->configuration->verbosity > 6){
                      OS_REPORT(OS_INFO, CMS_CONTEXT, 0,
                                  "Thread %d accepts connection from IP %d.%d.%d.%d\n",
                                  slave,
                                  (int)(cms->soap->ip>>24)&0xFF,
                                  (int)(cms->soap->ip>>16)&0xFF,
                                  (int)(cms->soap->ip>>8)&0xFF,
                                  (int)(cms->soap->ip&0xFF));
                   }
                   client = cms_serviceLookupClient(cms);

                   if(client != NULL){
                      soap = soap_copy(cms->soap);

                      if (soap == NULL) {
                         if(cms->configuration->verbosity > 0){
                            OS_REPORT(OS_ERROR, CMS_CONTEXT, 0,
                                      "Could not allocate SOAP environment.");
                         }
                         cms->terminate = TRUE;
                      } else {
                         soap->socket = slave;
                         slave = -1;
                         success = cms_clientHandleRequest(client, soap);

                         if(success == FALSE){
                            soap->error = soap_receiver_fault(soap,
                                                              "Could not handle request.", NULL);
                            soap_send_fault(soap);
                            soap_destroy(soap);
                            soap_end(soap);
                            soap_done(soap);
                            os_free(soap);
                            soap = NULL;
                         }
                      }
                   } else {
                      if(cms->configuration->verbosity > 3){
                         OS_REPORT(OS_INFO, CMS_CONTEXT, 0,
                                   "Maximum number of clients reached.");
                      }

                      if (soap == NULL) {
                         if(cms->configuration->verbosity > 0){
                            OS_REPORT(OS_ERROR, CMS_CONTEXT, 0,
                                      "Could not allocate SOAP environment.");
                         }
                         cms->terminate = TRUE;
                      } else {
                         soap->socket = slave;
                         slave = -1;
                         soap->error = soap_receiver_fault(soap,
                                                           "Maximum number of clients reached.",
                                                           NULL);
                         soap_send_fault(soap);
                         soap_destroy(soap);
                         soap_end(soap);
                         soap_done(soap);
                         soap = NULL;
                      }
                   }
                }
             }
Exemplo n.º 10
0
static GMI_RESULT ServerLoop(struct soap *soap)
{
    long_t Request;
    long_t Ret;
    SOAP_SOCKET SoapSock;
    struct linger TcpLinger;

    DEBUG_LOG(g_DefaultLogClient, e_DebugLogLevel_Info, "%s In.........\n", __func__);

    ONVIF_INFO("%s In.........\n", __func__);
    //onvif probe service start
    OnvifDevProbeServiceStart();

    ONVIF_INFO("DaemonStart start\n");
    //daemon start
    DaemonStart();
    ONVIF_INFO("DaemonStart end\n");

    //accept
    for (Request = 1; l_ServerStopFlag != true; Request++)
    {
        soap->accept_flags  |= SO_LINGER;
        soap->connect_flags |= SO_LINGER;
        soap->linger_time    = 1;

        SoapSock = soap_accept(soap);
        if (!soap_valid_socket(SoapSock))
        {
            continue;
        }

        TcpLinger.l_onoff  = 1;
        TcpLinger.l_linger = 1;
        Ret = setsockopt(SoapSock, SOL_SOCKET, SO_LINGER, (char*)&TcpLinger, sizeof(struct linger));
        if (Ret == -1)
        {
            ONVIF_ERROR("set socket LINGER failed !! errno = %d\n", errno);
            DEBUG_LOG(g_DefaultLogClient, e_DebugLogLevel_Exception, "set socket LINGER failed !! errno = %d\n", errno);
            close(SoapSock);
            SoapSock = -1;
            continue;
        }

        struct soap *tsoap = NULL;
        //THREAD_TYPE TidSoap;
        //void *ThreadRet;

        ONVIF_INFO("=======>Thread count %d\n", l_ThreadCnt);
        tsoap = soap_copy(soap);
        if (tsoap)
        {
            tsoap->user = (void*)(SOAP_SOCKET)SoapSock;
            ProcessRequest((void*)tsoap);
            //mask by guoqiang.lu,2014/1/8
            //pthread_create(&TidSoap, NULL, ProcessRequest, (void*)tsoap);
            //pthread_join(TidSoap, &ThreadRet);
        }
        else
        {
            continue;
        }
    }

    //daemon stop
    DaemonStop();

    //probe service stop
    OnvifDevProbeServiceStop();
    ONVIF_INFO("%s out.........\n", __func__);
    DEBUG_LOG(g_DefaultLogClient, e_DebugLogLevel_Info, "%s out.........\n", __func__);
    return GMI_SUCCESS;
}
Exemplo n.º 11
0
////////////////////////////////////////////////////////////////////////////////
//
//	Main
//
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{

	(void) signal(SIGINT, signalhandler_func);

#if 1
	struct soap soap;
	char *s = getenv("TMPDIR");
	if (s)
		TMPDIR = s;
	// use HTTP chunking when possible
	// chunking allows streaming of DIME content without requiring DIME attachment size to be set
	// DIME attachments can be streamed without chunking only if the attachment size is set
	soap_init1(&soap, SOAP_IO_KEEPALIVE | SOAP_IO_CHUNK);
	// set DIME callbacks
	soap.fdimereadopen = dime_read_open;
	soap.fdimereadclose = dime_read_close;
	soap.fdimeread = dime_read;
	soap.fdimewriteopen = dime_write_open;
	soap.fdimewriteclose = dime_write_close;
	soap.fdimewrite = dime_write;


#ifdef _POSIX_THREADS
	pthread_t tid;
#endif
	struct soap *tsoap;
	int port = 8085;
	int m, sk, i;


	if (soap_ssl_server_context(&soap,
								SOAP_SSL_DEFAULT | SOAP_SSL_SKIP_HOST_CHECK,	/* use SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION to verify clients: client must provide a key file e.g. "client.pem" and "password" */
								"server.pem",	/* keyfile (cert+key): see README.txt to create this file */
								"password",		/* password to read the private key in the key file */
								"cacert.pem",	/* cacert file to store trusted certificates (to authenticate clients), see README.txt */
								NULL,		/* capath */
								"dh2048.pem",	/* DH file name or DH param key len bits in string (e.g. "2048"), if NULL then RSA with 2048 bits is used instead (bits defined by SOAP_SSL_RSA_BITS) */
								NULL,		/* if randfile!=NULL: use a file with random data to seed randomness */
								"sslserver"		/* server identification for SSL session cache (unique server name, e.g. use argv[0]) */
								))
	{
		soap_print_fault(&soap, stderr);
		exit(1);
	}



	// Unix SIGPIPE, this is OS dependent:
	// soap.accept_flags = SO_NOSIGPIPE;	// some systems like this
	// soap.socket_flags = MSG_NOSIGNAL;	// others need this
	// signal(SIGPIPE, sigpipe_handle);		// or a sigpipe handler (portable)

	// port is first command line argument
	//port = atoi(argv[1]);
	// bind to current host and specified port
	m = soap_bind(&soap, NULL, port, BACKLOG);
	// if we could not bind, exit
	if (m < 0)
	{ soap_print_fault(&soap, stderr);
		exit(1);
	}

	fprintf(stderr, "Socket connection successful %d, port %d \n", m, port);
	// die after 24 hrs waiting for activity on port
	soap.accept_timeout = 24*60*60;
	// IO timeouts
	soap.send_timeout = 30;
	soap.recv_timeout = 30;
	// loop through requests
	//for (i = 1; ; i++)
	while(is_main_running)
	{ // accept request
		sk = soap_accept(&soap);
		// if timeout or error, report
		if (sk < 0)
		{ if (soap.errnum)
				soap_print_fault(&soap, stderr);
			else
				fprintf(stderr, "Server timed out\n");
			break;
		}

		fprintf(stderr, "Thread %d accepts socket %d connection from IP %d.%d.%d.%d\n", i, s, (int)(soap.ip>>24)&0xFF, (int)(soap.ip>>16)&0xFF, (int)(soap.ip>>8)&0xFF, (int)soap.ip&0xFF);
		// copy soap environment and spawn thread (if Pthreads is installed)
		tsoap = soap_copy(&soap);
#ifdef _POSIX_THREADS
		pthread_create(&tid, NULL, (void*(*)(void*))process_request, (void*)tsoap);
#else
		process_request((void*)tsoap);
#endif
	}

	// detach
	soap_done(&soap);

#endif

	return 0;
}
Exemplo n.º 12
0
int main(int argc, char **argv)
{
    // program initialize
    // log4cplus configuration
    PropertyConfigurator::doConfigure(LOG4CPLUS_TEXT("./conf/Log4Cplus.inp"));

    // program configuration
    if(configure.LoadFile("conf/config.xml")) {
        fprintf(stderr,"fail to read configure file\n");
        return(-1);
    }

    // get ladp current max uid
    LdapModule* ld = new LdapModule;
    ld->conn();
    ld->initMaxUid(MAXUID);
    ld->disconn();
    delete ld;

    // Web Service
    struct soap soap;
    soap_init(&soap);
    soap.fget = http_get;
    if (argc < 2) // no args: assume this is a CGI application
    {
        soap_serve(&soap); // serve request, one thread, CGI style
        soap_destroy(&soap); // dealloc C++ data
        soap_end(&soap); // dealloc data and clean up
    }
    else
    {
        struct soap *soap_thr[MAX_THR]; // each thread needs a runtime context
        pthread_t tid[MAX_THR];
        int port = atoi(argv[1]); // first command-line arg is port
        SOAP_SOCKET m, s;
        int i;
        m = soap_bind(&soap, NULL, port, BACKLOG);
        if (!soap_valid_socket(m))
            exit(1);
        fprintf(stderr, "Socket connection successful %d\n", m);
        pthread_mutex_init(&queue_cs, NULL);
        pthread_cond_init(&queue_cv, NULL);
        for (i = 0; i < MAX_THR; i++)
        {
            soap_thr[i] = soap_copy(&soap);
            fprintf(stderr, "Starting thread %d\n", i);
            pthread_create(&tid[i], NULL, (void*(*)(void*))process_queue, (void*)soap_thr[i]);
        }
        for (;;)
        {
            s = soap_accept(&soap);
            if (!soap_valid_socket(s))
            {
                if (soap.errnum)
                {
                    soap_print_fault(&soap, stderr);
                    continue; // retry
                }
                else
                {
                    fprintf(stderr, "Server timed out\n");
                    break;
                }
            }
            fprintf(stderr, "Thread %d accepts socket %d connection from IP %d.%d.%d.%d\n", i, s, (soap.ip >> 24)&0xFF, (soap.ip >> 16)&0xFF, (soap.ip >> 8)&0xFF, soap.ip&0xFF);
            while (enqueue(s) == SOAP_EOM)
                sleep(1);
        }
        for (i = 0; i < MAX_THR; i++)
        {
            while (enqueue(SOAP_INVALID_SOCKET) == SOAP_EOM)
                sleep(1);
        }
        for (i = 0; i < MAX_THR; i++)
        {
            fprintf(stderr, "Waiting for thread %d to terminate... ", i);
            pthread_join(tid[i], NULL);
            fprintf(stderr, "terminated\n");
            soap_done(soap_thr[i]);
            free(soap_thr[i]);
        }
        pthread_mutex_destroy(&queue_cs);
        pthread_cond_destroy(&queue_cv);
    }
    soap_done(&soap);
    return 0;
}
Exemplo n.º 13
0
//Main Funtion
int main(int argc,char *argv[])
{
    int status=0;
    status=nInit();
    sprintf(sLogfile,"%s",argv[0]);
    SOAP_SOCKET m,s;
    int i=0;
    struct soap Onlsoap; 
    soap_init(&Onlsoap);
    Onlsoap.fget = http_get;
    Onlsoap.fpost = http_post;
    struct soap * soap_thr[MAX_THR];
    pthread_t tid[MAX_THR];

    sigset(SIGUSR1, signalHandle);
    sigset(SIGTERM, signalHandle);
    sigset(SIGSEGV, signalHandle);

    // 设置UTF-8编码方式
    //soap_set_mode(&Onlsoap, SOAP_C_UTFSTRING);
    
    soap_set_mode(&Onlsoap, SOAP_C_MBSTRING);
    soap_set_namespaces(&Onlsoap, namespaces);
    // ----------
    m = soap_bind(&Onlsoap,NULL,lPort,BACKLOG);
    //循环直至服务套接字合法
    while (!soap_valid_socket(m))
    {
        dzlog_error("Bind port error!");
        m = soap_bind(&Onlsoap,NULL,lPort,BACKLOG);
        sleep(2);
    }
    //锁和条件变量初始化
    pthread_mutex_init(&queue_cs,NULL);
    pthread_cond_init(&queue_cv,NULL);
    //生成服务线程
    for(i = 0; i <MAX_THR; i++)
    {
      soap_thr[i] = soap_copy(&Onlsoap);
      dzlog_info("Starting thread %d ",i);
      pthread_create(&tid[i],NULL,(void*(*)(void*))process_queue,(void*)soap_thr[i]);
      
    }
   
   for(;;)
   {

       s=soap_accept(&Onlsoap);
       if(!soap_valid_socket(s))
       {
            if (Onlsoap.errnum) 
            { 
                 soap_print_fault(&Onlsoap,stderr);
                 continue;
            } 
            else
            {
                dzlog_error("Server timed out.");
                break;
            }
       }
     
       dzlog_info("Main Process[%d] accepted connection from IP=%d.%d.%d.%d", getpid(),
              (Onlsoap.ip >> 24)&0xFF, (Onlsoap.ip >> 16)&0xFF, (Onlsoap.ip >> 8)&0xFF, Onlsoap.ip&0xFF);

        while(enqueue(s) == SOAP_EOM)
         sleep(1);
   }
   
    //服务结束后的清理工作
    for(i = 0; i < MAX_THR; i++)
    {
       while (enqueue(SOAP_INVALID_SOCKET) == SOAP_EOM) 
       {
           sleep(1);
       }
    }
    for(i=0; i< MAX_THR; i++)
    {
        pthread_join(tid[i],NULL);
        dzlog_debug("terminated[%d] ",i);
        soap_done(soap_thr[i]);
        free(soap_thr[i]);
    }
   
    pthread_mutex_destroy(&queue_cs);
    pthread_cond_destroy(&queue_cv);
    soap_done(&Onlsoap);
    DbPoolFree(&conn_pool);
	zlog_fini();
    return 0;
}
Exemplo n.º 14
0
int main(int argc, const char * argv[])
{
    struct soap soap;

	// sqlite3 设置为工作在 Serialized 模式下,因为“心跳线程”会周期操作 token table

    // 启动 webservice
    soap_init(&soap);
    
    soap_set_mode(&soap, SOAP_C_UTFSTRING); // 如果没有这个,无法正确显示 utf-8 编码的汉字
    
    if (!soap_valid_socket(soap_bind(&soap, 0, 8899, 100))) {
        fprintf(stderr, "ERR: soap_bind 8899 err\n");
        exit(-1);
    }
    
    fprintf(stdout, "start %d\n", 8899);
    
    // 启动心跳线程
    // FIXME: 在每次 webservice 的请求时,检查 token table 是不是更好些呢?. 
    // 已经修改为,在每次查询时,首先删除超时对象,这样不需要启动独立的工作线程;. 
#if 0
#ifdef WIN32
	CloseHandle(CreateThread(0, 0, heartBeatCheck_run, 0, 0, 0));
#else
    pthread_t th;
    pthread_create(&th, 0, heartBeatCheck_run, 0);
#endif // os
#endif // 0;
    
    // 开始处理所有 webservice 请求...
    while (1) {
        int n = soap_accept(&soap);
        if (n < 0) {
            fprintf(stderr, "ERR: soap_accept err\n");
            soap_print_fault(&soap, stderr);
            if (soap.errnum) {
                soap_print_fault(&soap, stderr);
                exit(1);
            }
            exit(-1);
        }
#ifdef MULTITHREAD_SERVER
		{
        struct soap *ts = soap_copy(&soap);
        if (ts) {
#ifdef WIN32
			HANDLE th;
			CloseHandle(CreateThread(0, 0, _working_proc, ts, 0, 0));
#else
            pthread_t th;
            pthread_create(&th, 0, _working_proc, ts);
#endif // 
        }
		}
#else
        soap_serve(&soap);
        soap_destroy(&soap);
        soap_end(&soap);
#endif // multi thread server
    }
    
    soap_done(&soap);
    
    return 0;
}
Exemplo n.º 15
0
int main(int argc, char **argv){ 
   
   // Asigno el handler para el Ctrl + C
   signal(SIGINT,salir);

   // Declaro estructura soap
   struct soap soap; 

   // Inicializo la estructura soap
   soap_init(&soap); 


   // Compruebo que me han pasado bien los argumentos al ejecutar el servidor
   if (argc < 2) 
   { 
      printf("Usage: ./server xxxx (port)\n"); 
      soap_serve(&soap); 
      soap_destroy(&soap);
      soap_end(&soap); 
   } 
   else{ 
      soap.send_timeout = 60; 
      soap.recv_timeout = 60; 
      soap.accept_timeout = 3600; // server stops after 1 hour of inactivity
      soap.max_keep_alive = 100;  // max keep-alive sequence
      void *process_request(void*); 
      struct soap *tsoap; 
      pthread_t tid; 
      int port = atoi(argv[1]); // first command-line arg is port
      SOAP_SOCKET m, s; 
      m = soap_bind(&soap, NULL, port, BACKLOG); 
      if (!soap_valid_socket(m)){
		soap_print_fault(&soap, stderr);
        exit(1); 
	
      }
      fprintf(stderr, "Socket connection successful %d\n", m); 
 
 	// Cargamos lus usuarios guardados en disco
      cargarListaUsuarios();
 
      for (;;) 
      { 
         s = soap_accept(&soap); 
         if (!soap_valid_socket(s)) 
         { 
            if (soap.errnum) 
            { 
               soap_print_fault(&soap, stderr); 
               exit(1); 
            } 
            fprintf(stderr, "server timed out\n"); 
            break; 
         }

         // gestiono la funcion que me pide el Cliente
		 soap_serve(&soap);
		 soap_end(&soap);


         tsoap = soap_copy(&soap); 
         if (!tsoap) 
            break; 
         pthread_create(&tid, NULL, (void*(*)(void*))process_request, (void*)tsoap); 
      } 
   } 
   soap_done(&soap); 
   return 0; 
} 
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
	SOAP_SOCKET m;
#if defined(_POSIX_THREADS) || defined(_SC_THREADS)
	pthread_t tid;
	pthread_mutex_init(&global_flag, NULL);
	pthread_mutex_init(&libssh2_flag, NULL);
	pthread_cond_init(&termination_flag, NULL);
#endif
	struct soap soap, *tsoap = NULL;
	psoap = &soap;

	int ch, msglevel = LOG_INFO;
	static char *USAGE = "\nUSAGE:\noph_server [-d] [-l <log_file>] [-p <port>] [-v] [-w]\n";

	fprintf(stdout, "%s", OPH_VERSION);
	fprintf(stdout, "%s", OPH_DISCLAIMER);

	set_debug_level(msglevel + 10);

	while ((ch = getopt(argc, argv, "dhl:p:vwxz")) != -1) {
		switch (ch) {
			case 'd':
				msglevel = LOG_DEBUG;
				break;
			case 'h':
				fprintf(stdout, "%s", USAGE);
				return 0;
			case 'l':
				oph_log_file_name = optarg;
				break;
			case 'p':
				oph_server_port = optarg;
				break;
			case 'v':
				return 0;
				break;
			case 'w':
				if (msglevel < LOG_WARNING)
					msglevel = LOG_WARNING;
				break;
			case 'x':
				fprintf(stdout, "%s", OPH_WARRANTY);
				return 0;
			case 'z':
				fprintf(stdout, "%s", OPH_CONDITIONS);
				return 0;
			default:
				fprintf(stdout, "%s", USAGE);
				return 0;
		}
	}

	set_debug_level(msglevel + 10);
	pmesg(LOG_INFO, __FILE__, __LINE__, "Selected log level %d\n", msglevel);

#ifdef OPH_SERVER_LOCATION
	oph_server_location = strdup(OPH_SERVER_LOCATION);
#else
	oph_server_location = getenv(OPH_SERVER_LOCATION_STR);
	if (!oph_server_location) {
		fprintf(stderr, "OPH_SERVER_LOCATION has to be set\n");
		return 1;
	}
#endif
	pmesg(LOG_DEBUG, __FILE__, __LINE__, "Server location '%s'\n", oph_server_location);

	char configuration_file[OPH_MAX_STRING_SIZE];
	snprintf(configuration_file, OPH_MAX_STRING_SIZE, OPH_CONFIGURATION_FILE, oph_server_location);
	set_global_values(configuration_file);

	if (oph_log_file_name) {
		if (logfile)
			fclose(logfile);
		if (!(logfile = fopen(oph_log_file_name, "a"))) {
			fprintf(stderr, "Wrong log file name '%s'\n", oph_log_file_name);
			return 1;
		}
		pmesg(LOG_INFO, __FILE__, __LINE__, "Selected log file '%s'\n", oph_log_file_name);
		if (logfile)
			set_log_file(logfile);
	} else
		oph_log_file_name = hashtbl_get(oph_server_params, OPH_SERVER_CONF_LOGFILE);

	int int_port = strtol(oph_server_port, NULL, 10);

	if (oph_handle_signals()) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "A problem occurred while setting up signal dispositions\n");
		exit(1);
	}

	if (mysql_library_init(0, 0, 0)) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Cannot setup MySQL\n");
		exit(1);
	}

	oph_tp_start_xml_parser();
	if (CRYPTO_thread_setup()) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Cannot setup thread mutex for OpenSSL\n");
		exit(1);
	}
	soap_init(&soap);
	soap.fget = oph_http_get;
	if (soap_register_plugin(&soap, oph_plugin)) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Cannot register %s plugin\n", OPH_PLUGIN_ID);
		soap_print_fault(&soap, stderr);
		cleanup();
		exit(-1);
	}
	// Register serverid
	struct oph_plugin_data *state = NULL;
	if (!(state = (struct oph_plugin_data *) soap_lookup_plugin(&soap, OPH_PLUGIN_ID))) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Error on lookup plugin struct\n");
		soap_print_fault(&soap, stderr);
		cleanup();
		exit(-1);
	}
	state->serverid = strdup(oph_web_server);

#ifdef WITH_OPENSSL
	/* init gsoap context and SSL */
	if (soap_ssl_server_context(&soap, SOAP_TLSv1_2, oph_server_cert, oph_server_password, oph_server_ca, NULL, NULL, NULL, NULL)) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "SSL Server Context Error\n");
		soap_print_fault(&soap, stderr);
		cleanup();
		exit(1);
	}
#endif

	soap.accept_timeout = oph_server_inactivity_timeout;
	soap.send_timeout = soap.recv_timeout = oph_server_timeout;
	soap.bind_flags |= SO_REUSEADDR;
	m = soap_bind(&soap, NULL, int_port, 100);
	if (!soap_valid_socket(m)) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Soap invalid socket\n");
		soap_print_fault(&soap, stderr);
		cleanup();
		exit(1);
	}
	pmesg(LOG_DEBUG, __FILE__, __LINE__, "Bind successful: socket = %d\n", m);

	for (;;) {
		SOAP_SOCKET s = soap_accept(&soap);
		if (!soap_valid_socket(s)) {
			if (soap.errnum) {
				pmesg(LOG_ERROR, __FILE__, __LINE__, "Soap invalid socket\n");
				soap_print_fault(&soap, stderr);
			} else
				pmesg(LOG_ERROR, __FILE__, __LINE__, "Server timed out (timeout set to %d seconds)\n", soap.accept_timeout);
			break;
		}
		tsoap = soap_copy(&soap);
		if (!tsoap) {
			soap_closesock(&soap);
			continue;
		}
#if defined(_POSIX_THREADS) || defined(_SC_THREADS)
		pthread_create(&tid, NULL, (void *(*)(void *)) &process_request, tsoap);
#else
		process_request(tsoap);
#endif
	}
	cleanup();
	return 0;
}