Пример #1
0
/**************************************
* XmlRpcServer
*	Constructor
**************************************/
XmlRpcServer::XmlRpcServer(int port)
{
	char name[65];

	//Iniciamos la fecha
	DateInit();

	//Los mime tipes
	MIMETypeInit();

	//Le pasamos como nombre un puntero a nosotros mismos
	sprintf(name,"%p",this);	

	//Creamos el servidor
	ServerCreate(&srv,name, port, DEFAULT_DOCS, "http.log");

	//Iniciamos el servidor
	ServerInit(&srv);

	//Set the handler
	abyss_bool ret;

	//Create abyss handler
	ServerReqHandler3 abbysHndlr;

	//Set
	abbysHndlr.userdata	= (void*)this;
	abbysHndlr.handleReq	= RequestHandler;
	abbysHndlr.term		= NULL;
	abbysHndlr.handleReqStackSize = 0;

	//Add handler
	ServerAddHandler3(&srv,&abbysHndlr,&ret);
}
Пример #2
0
int main(int argc, char *argv[])
{
	int port;
	
	if(argc != 2)
	{
		fprintf(stderr, "Unknow port.\n\tUsage: server xxxx\n\n");
		return -1;
	}

	gtk_init(&argc, &argv);

	DisplayLowLevelInit();

	sscanf(argv[1], "%d", &port);
	ServerInit(port);

	if(0 == pthread_create(&server_id, NULL, (void*)ServerMainLoop, NULL))
	  printf("Create thread for server..\n");

	gtk_main();
	/* Will not return */

	return 0;
}
Пример #3
0
int 
main(int           const argc, 
     const char ** const argv) {

    struct xmlrpc_method_info3 const methodInfo = {
        .methodName     = "sample.add",
        .methodFunction = &sample_add,
        .serverInfo = NULL
    };
    TServer abyssServer;
    xmlrpc_registry * registryP;
    xmlrpc_env env;
    int terminationRequested;  /* A boolean value */
    const char * error;

    if (argc-1 != 1) {
        fprintf(stderr, "You must specify 1 argument:  The TCP port number "
                "on which to listen for XML-RPC calls.  "
                "You specified %d.\n",  argc-1);
        exit(1);
    }

    AbyssInit(&error);
    
    xmlrpc_env_init(&env);

    registryP = xmlrpc_registry_new(&env);

    xmlrpc_registry_add_method3(&env, registryP, &methodInfo);

    xmlrpc_registry_set_shutdown(registryP,
                                 &requestShutdown, &terminationRequested);

    ServerCreate(&abyssServer, "XmlRpcServer", atoi(argv[1]), NULL, NULL);
    
    xmlrpc_server_abyss_set_handlers2(&abyssServer, "/RPC2", registryP);

    ServerInit(&abyssServer);

    setupSignalHandlers();

    terminationRequested = 0;

    while (!terminationRequested) {
        printf("Waiting for next RPC...\n");

        ServerRunOnce(&abyssServer);
            /* This waits for the next connection, accepts it, reads the
               HTTP POST request, executes the indicated RPC, and closes
               the connection.
            */
    }

    ServerFree(&abyssServer);

    AbyssTerm();

    return 0;
}
Пример #4
0
/*
====================
HandleMessage
====================
*/
static void HandleMessage( const void *const arg ) {
	const server_message_t message = *( server_message_t * )arg;

	ServerInit( message.ip_socket, message.ip6_socket );

	mtx_lock( &server_mutex );
	mtx_unlock( &server_mutex );
	cnd_signal( &server_condition );
}
Пример #5
0
void ICACHE_FLASH_ATTR network_check_ip(void) {
  struct ip_info ipconfig;
  os_timer_disarm(&network_timer);
  wifi_get_ip_info(STATION_IF, &ipconfig);
  if (wifi_station_get_connect_status() == STATION_GOT_IP && ipconfig.ip.addr != 0) {
    char page_buffer[20];
    os_sprintf(page_buffer,"IP: %d.%d.%d.%d",IP2STR(&ipconfig.ip));
    os_sprintf(ipstation, "%d.%d.%d.%d",IP2STR(&ipconfig.ip));
    os_printf(page_buffer);

    ServerInit(flashData->ServerPort);


    //GetNetworkTime();
    os_printf("SNTP-----%d", flashData->SNTP);
    sntp_init(flashData->SNTP);

  } else {
    counter++;
    os_printf("No ip found\n\r");
    if (counter < 12)
    {
        os_timer_setfn(&network_timer, (os_timer_func_t *)network_check_ip, NULL);
        os_printf("try %d\n", counter);
        os_timer_arm(&network_timer, 1000, 0);
    }
    else
    {
        os_printf("could not connect to server\n", counter);
        wifi_station_disconnect();
        ServerInit(flashData->ServerPort);

        counter = 0;
    }
  }
}
Пример #6
0
int CGateServer::AppStart() {
    ServerInit();
    ServerAddr addr = CGateConfig::Instance()->GetClientAddr();
    int ret = netlib_listen(addr.ip.c_str(), addr.port, client_conn_callback, NULL);
    if (ret == NETLIB_ERROR) {
        return ret;
    }
    
    init_client_conn();
    
    ConnectRouteServer();
    
    netlib_eventloop();
    
    return 0;
}
Пример #7
0
void *server_thread(void *vptr_args){         
    int server_sock,client_sock;
    struct sockaddr_storage their_addr;
    socklen_t addr_size;
    
    ServerInfo serv_info=*(ServerInfo *)vptr_args;    
    server_sock=ServerInit(&serv_info);
    addr_size = sizeof their_addr;
    while(1){
        client_sock = accept(server_sock, (struct sockaddr *)&their_addr, &addr_size);
        if(client_sock==-1){
            DEBUG_PRINTERR("accept: %i\n",errno);
            continue;
        }
        ServiceClient(client_sock);
    }
        
    pthread_exit(NULL);
}
Пример #8
0
ShooterGame::ShooterGame()
{
	SetName("ShooterGame");
	MartEngine::GameClassRegistry::Get().Register("Player", Player::Construct());
	MartEngine::GameClassRegistry::Get().Register("Floor", Floor::Construct());
	MartEngine::GameClassRegistry::Get().Register("Bullet", Bullet::Construct());
	MartEngine::GameClassRegistry::Get().Register("Wall", Wall::Construct());

	REGISTER_NETWORK_FUNCTION(OnConnect)
	REGISTER_NETWORK_FUNCTION(Ack)
	REGISTER_NETWORK_FUNCTION(Server_SpawnPlayer)
	REGISTER_NETWORK_FUNCTION(SpawnPlayer)
	REGISTER_NETWORK_FUNCTION(Server_UpdatePlayerStats)
	REGISTER_NETWORK_FUNCTION(UpdatePlayerStats)
	REGISTER_NETWORK_FUNCTION(Server_SpawnBullet)
	REGISTER_NETWORK_FUNCTION(SpawnBullet)

	mSendTime = 0.0f;
	if (MartEngine::Args::Get()[1] == "Server") ServerInit();
	else ClientInit();
}
Пример #9
0
int main(int argc, char *argv[]) {

    if (argc != 2) {

        printf("Wrong input!\n");
        return -1;
    }

    int j;
    int epfd, maxi, nfds, i, clilen, connfd, sockfd;
    int count, recvNUm, isReadComplete;
    char recvbuf[MAXLINE];

    int client_socks[MAXEVENTS], socket_count = 0;
    memset(client_socks, -1, sizeof(client_socks));
    memset(recvbuf, 0, sizeof(recvbuf));
    struct sockaddr_in cliaddr;
    clilen = sizeof(cliaddr);
    bzero(&cliaddr, sizeof(cliaddr));
    int servsock;
    servsock = ServerInit(atoi(argv[1]));

    struct epoll_event ev, events[MAXEVENTS];
    epfd = epoll_create(256);
    ev.data.fd = servsock;
    ev.events = EPOLLIN | EPOLLET;
    epoll_ctl(epfd, EPOLL_CTL_ADD, servsock, &ev);

    maxi = 0;
    int bOut = 0;
    for (; ;) {
        
        if (bOut == 1) 
            break;
        nfds = epoll_wait(epfd, events, MAXEVENTS, -1);

        for (i = 0; i < nfds; i++) {
            if (events[i].data.fd == servsock) {
                connfd = accept(servsock, (SA*)&cliaddr, &clilen);
                if (connfd < 0) {
                    perror("Accept error!\n");
                    return -1;
                }

                printf("Recv a connection....!\n");
                make_socket_noblocking(connfd);
                ev.data.fd = connfd;
                ev.events = EPOLLIN | EPOLLET;
                epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev);
                client_socks[socket_count++] = connfd;
            } else if (events[i].events & EPOLLIN) {
                
                if ((sockfd = events[i].data.fd) < 0) 
                    continue;
                
                recvNUm = 0;
                count = 0;
                isReadComplete = 0;
                while (1) {
                    
                    recvNUm = recv(sockfd, recvbuf + count, MAXLINE, 0);
                    if (recvNUm < 0) {
                        if (errno == EAGAIN) {
                            isReadComplete = 1;
                            break;
                        } else if (errno == ECONNRESET) {
                            close_and_disable(sockfd, events[i]);
                            printf("Counterpart send out RST\n");
                            break;
                        } else if (errno == EINTR) {
                            continue;
                        } else {

                            close_and_disable(sockfd, events[i]);
                            printf("Unknown Error!\n");
                            break;
                        }
                    } else if (recvNUm == 0) {
                        close_and_disable(sockfd, events[i]);
                        printf("Counterpart had shuted off!\n");
                        break;
                    }

                    count += recvNUm;
                    if (recvNUm == MAXLINE)
                        continue;
                    else {
                        isReadComplete = 1;
                        break;
                    }
                }
                if (isReadComplete) {
                    recvbuf[count] = '\0';
                    printf("recv: %s\n", recvbuf);

                    for (j = 0; j < socket_count; j++){
                        write(client_socks[j], recvbuf, strlen(recvbuf));
                    } 
            
                    }

            }
        }

    }
    close(servsock);
}
Пример #10
0
/**
**  The main program: initialize, parse options and arguments.
*/
int main(int argc, char **argv)
{
	int status;
	int i;

	Server.Port = DEFAULT_PORT;
	Server.MaxConnections = DEFAULT_MAX_CONN;
	Server.IdleTimeout = DEFAULT_SESSION_TIMEOUT;
	Server.PollingDelay = DEFAULT_POLLING_DELAY;

	//
	// Standard SDL Init.
	//
	if (SDL_Init(0) == -1) {
		printf("SDL_Init: %s\n", SDL_GetError());
		exit(1);
	}
	atexit(SDL_Quit);

	//
	// Parse the command line.
	//
	while ((i = getopt(argc, argv, ":p:m:i:d:")) != -1) {
		switch (i) {
			case 'p':
				Server.Port = atoi(optarg);
				if (Server.Port <= 0) {
					Server.Port = DEFAULT_PORT;
				}
				break;
			case 'm':
				Server.MaxConnections = atoi(optarg);
				break;
			case 'i':
				Server.IdleTimeout = atoi(optarg);
				break;
			case 'd':
				Server.PollingDelay = atoi(optarg);
				break;
			case ':':
				printf("Missing argument for %c\n", optopt);
				exit(0);
				break;
			case '?':
				printf("Unrecognized option: -%c\n", optopt);
				break;
		}
    }

	// Initialize the database
	if (DBInit()) {
		fprintf(stderr, "DBInit failed\n");
		exit(1);
	}
	atexit(DBQuit);

	//
	// Initialize server.
	//
	// Open the server to connections.
	//
	if ((status = ServerInit(Server.Port)) != 0) {
		if (status > 0) {
			fprintf(stderr, "ERROR %d: %s\n", errno, strerror(errno));		// > 0
		} else {
			fprintf(stderr, "ERROR: %s\n", SDL_GetError());				// < 0
		}
		exit(status);
	}
	atexit(ServerQuit);

	printf("Stratagus Metaserver Initialized on port %d.\n", Server.Port);

	//
	// Uncomment this line for MSVC (or other default)
	// debugging of segmentation violations.
	//
	// signal(SIGSEGV, SIG_DFL);

	MainLoop();

	//
	// Server tasks done.
	//
	// "atexit" will take over from here for cleanup.
	//
	printf("Stratagus Metaserver Done.\n");

	return 0;
}
Пример #11
0
int main( int argc, char *argv[] )
{
    const char *fn = "main()";
    char f_randfile[ PATH_MAX ];
    int listensd;                      /* socket descriptor we'll bind to */
    int clientsd;                      /* incoming socket descriptor */
    int sockaddrlen;                       
    struct sockaddr_storage srvaddr;
    struct sockaddr_storage cliaddr;
    pthread_t ThreadId;                /* thread id of each incoming conn */
    pthread_t RecycleThread;           /* used just for the recycle thread */
    pthread_attr_t attr;               /* generic thread attribute struct */
    int rc, i, fd;
    unsigned int ui;
    struct linger lingerstruct;        /* for the socket reuse stuff */
    int flag;                          /* for the socket reuse stuff */
    ICC_Struct *ICC_tptr;             
    extern char *optarg;
    extern int optind;
    char ConfigFile[ MAXPATHLEN ];     /* path to our config file */
    char PidFile[ MAXPATHLEN ];		/* path to our pidfile */
#ifdef HAVE_LIBWRAP
    struct request_info r;             /* request struct for libwrap */
#endif
    struct addrinfo aihints, *ai;
    int gaierrnum;

    flag = 1;
    ConfigFile[0] = '\0';
    strncpy( PidFile, DEFAULT_PID_FILE, sizeof PidFile -1 );

    /*
     * Ignore signals we don't want to die from but we don't care enough
     * about to catch.
     */
    signal( SIGPIPE, SIG_IGN );
    signal( SIGHUP, SIG_IGN );
    

    while (( i = getopt( argc, argv, "f:p:h" ) ) != EOF )
    {
	switch( i )
	{
	case 'f':
	    /* user specified a config filename */
	    strncpy( ConfigFile, optarg, sizeof ConfigFile -1 );
	    ConfigFile[ sizeof ConfigFile - 1 ] = '\0';
	    syslog( LOG_INFO, "%s: Using configuration file '%s'",
		    fn, ConfigFile );
	    break;
        
        case 'p':
            /* user specified a pidfile */
            strncpy( PidFile, optarg, sizeof PidFile -1 );
            PidFile[ sizeof PidFile - 1 ] = '\0';
            syslog( LOG_INFO, "%s: Using pidfile '%s'",
            fn, PidFile );
            break;
        
	case 'h':
	    Usage();
	    exit( 0 );

	case '?':
	    Usage();
	    exit( 1 );
	}
    }


    /* 
     * Make sure we know which config file to use and then set our config
     * options.
     */
    if ( ! ConfigFile[0] )
    {
	strncpy( ConfigFile, DEFAULT_CONFIG_FILE, sizeof ConfigFile -1 );
	ConfigFile[ sizeof ConfigFile - 1 ] = '\0';
	syslog( LOG_INFO, "%s: Using default configuration file '%s'.",
		fn, ConfigFile );
    }

    SetDefaultConfigValues(&PC_Struct);
    SetConfigOptions( ConfigFile );
    SetLogOptions();

    /*
     * Just for logging purposes, are we doing SELECT caching or not?
     */
    if ( PC_Struct.enable_select_cache )
	syslog( LOG_INFO, "%s: SELECT caching is enabled", fn );
    else
	syslog( LOG_INFO, "%s: SELECT caching is disabled", fn );
	
    /*
     * Just for logging purposes, are the admin commands enabled or not?
     */
     if ( PC_Struct.enable_admin_commands )
	 syslog( LOG_INFO, "%s: Internal admin commands are enabled", fn );
     else
	 syslog( LOG_INFO, "%s: Internal admin commands are disabled", fn );
     

#ifdef HAVE_LIBWRAP
    /*
     * Set our tcpd service name
     */
    if (service = strrchr(argv[0], '/'))
	    service++;
    else
	    service = argv[0];
#endif

    /*
     * Initialize some stuff.
     */
    rc = pthread_mutex_init(&mp, NULL);
    if ( rc )
    {
	syslog(LOG_ERR, "%s: pthread_mutex_init() returned error [%d] initializing main mutex.  Exiting.", fn, rc );
	exit( 1 );
    }

    rc = pthread_mutex_init(&trace, NULL);
    if ( rc )
    {
	syslog(LOG_ERR, "%s: pthread_mutex_init() returned error [%d] initializing trace mutex.  Exiting.", fn, rc );
	exit( 1 );
    }

    TraceUser[0] = '\0';
    
    syslog( LOG_INFO, "%s: Allocating %d IMAP connection structures.", 
	    fn, PC_Struct.cache_size );

    ICC_free = (ICC_Struct *)malloc( ( sizeof ( ICC_Struct ) ) 
		       * PC_Struct.cache_size );
    
    if ( ! ICC_free )
    {
	syslog(LOG_ERR, "%s: malloc() failed to allocate [%d] IMAPConnectionContext structures: %s", fn, PC_Struct.cache_size, strerror( errno ) );
	exit( 1 );
    }
    
    memset( ICC_free, 0, sizeof ( ICC_Struct ) * PC_Struct.cache_size );
    
    ICC_tptr = ICC_free;

    /*
     * Bug fixed by Gary Mills <*****@*****.**>.  I was pre-incrementing
     * ICC_tptr and then assigning.  I guess gcc evaluates the expression
     * incorrectly, since I never had a problem with this.  Gary had the
     * problem with cc, so it's fixed here.
     */
    for ( ui = 0; ui < PC_Struct.cache_size - 1; ui++ )
    {
	ICC_tptr->next = ICC_tptr + 1;
	ICC_tptr++;
    }
    
    memset( ICC_HashTable, 0, sizeof ICC_HashTable );


#if HAVE_LIBSSL
    /* Initialize SSL_CTX */
    syslog( LOG_INFO, "%s: Enabling openssl library.", fn );
    SSL_library_init();

    /* Set up OpenSSL thread protection */
    ssl_thread_setup(fn);

    /* Need to seed PRNG, too! */
    if ( RAND_egd( ( RAND_file_name( f_randfile, sizeof( f_randfile ) ) == f_randfile ) ? f_randfile : "/.rnd" ) )
    {
	/* Not an EGD, so read and write it. */
	if ( RAND_load_file( f_randfile, -1 ) )
	RAND_write_file( f_randfile );
    }

    SSL_load_error_strings();
    tls_ctx = SSL_CTX_new( TLSv1_client_method() );
    if ( tls_ctx == NULL )
    { 
	syslog(LOG_ERR, "%s: Failed to create new SSL_CTX.  Exiting.", fn);
	exit( 1 );
    }
 
    /* Work around all known bugs */
    SSL_CTX_set_options( tls_ctx, SSL_OP_ALL );
 
    if ( PC_Struct.tls_ca_file != NULL || PC_Struct.tls_ca_path != NULL )
    {
	rc = SSL_CTX_load_verify_locations( tls_ctx,
					    PC_Struct.tls_ca_file,
					    PC_Struct.tls_ca_path );
    }
    else
    {
	rc = SSL_CTX_set_default_verify_paths( tls_ctx );
    }
    if ( rc == 0 )
    { 
	syslog(LOG_ERR, "%s: Failed to load CA data.  Exiting.", fn);
	exit( 1 );
    }
 
    if ( ! set_cert_stuff( tls_ctx,
			    PC_Struct.tls_cert_file,
			    PC_Struct.tls_key_file ) )
    { 
	syslog(LOG_ERR, "%s: Failed to load cert/key data.  Exiting.", fn);
	exit( 1 );
    }

    SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_NONE, verify_callback);
#endif /* HAVE_LIBSSL */


    ServerInit();
    
    /* Daemonize() would go here */

    SetBannerAndCapability();
    

    /*
     * We don't need to check PC_Struct.support_starttls since we
     * probably have refetched the capability list after a STARTTLS
     * if we did one; it won't ever be supported at this point.
     *
     * It also makes no difference to check PC_Struct.force_tls now
     * because we've either done a STARTTLS or we haven't - all that
     * matters is if we got LOGINDISABLED or not.
     *
     * Note that all these things *ARE* tested when checking the
     * server capabilities (in fact, the following check is probably
     * a duplicate).
     */
    if ( PC_Struct.login_disabled )
    {
	/* We're screwed!  We can't login */
	syslog(LOG_ERR,
		"%s: IMAP server has LOGINDISABLED.  Exiting.",
		fn);
	exit( 1 );
    }


    memset( &aihints, 0, sizeof aihints );
    aihints.ai_family = AF_UNSPEC;
    aihints.ai_socktype = SOCK_STREAM;
    aihints.ai_flags = AI_PASSIVE;

    if ( ( gaierrnum = getaddrinfo( PC_Struct.listen_addr,
				    PC_Struct.listen_port,
				    &aihints, &ai ) ) )
	{
	    syslog( LOG_ERR, "%s: bad bind address: '%s' specified in config file.  Exiting.", fn, PC_Struct.listen_addr );
	    exit( 1 );
	}

    syslog( LOG_INFO, "%s: Binding to tcp %s:%s", fn,
	    PC_Struct.listen_addr ? PC_Struct.listen_addr : "*",
	    PC_Struct.listen_port );

    for ( ; ai != NULL; ai = ai->ai_next )
    {
	listensd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol );
    if ( listensd == -1 )
    {
	    syslog(LOG_WARNING, "%s: socket() failed: %s", fn, strerror(errno));
	    continue;
    }

    setsockopt(listensd, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, 
	       sizeof(flag));
    lingerstruct.l_onoff = 1;
    lingerstruct.l_linger = 5;
    setsockopt(listensd, SOL_SOCKET, SO_LINGER, (void *)&lingerstruct, 
	       sizeof(lingerstruct));

    if ( PC_Struct.send_tcp_keepalives )
    {
	lingerstruct.l_onoff = 1;
	syslog( LOG_INFO, "%s: Enabling SO_KEEPALIVE.", fn );
	setsockopt( listensd, SOL_SOCKET, SO_KEEPALIVE, (void *)&lingerstruct.l_onoff, sizeof lingerstruct.l_onoff );
    }

	memcpy( &srvaddr, ai->ai_addr, ai->ai_addrlen );
	if ( bind( listensd, (struct sockaddr *)&srvaddr, ai->ai_addrlen ) < 0 )
    {
	    syslog(LOG_WARNING, "%s: bind() failed: %s", fn, strerror(errno) );
	    continue;
	}
	else break;
    }
    if ( ai == NULL )
    {
	syslog( LOG_ERR, "%s: no useable addresses to bind to", fn );
	exit( EXIT_FAILURE);
    }

    /*
     * Create and mmap() our stat file while we're still root.  Since it's
     * configurable, we want to make sure we do this as root so there's the
     * greatest possibility that we'll have permission to write where we
     * need to.
     */
    syslog( LOG_INFO, "%s: Using global statistics file '%s'", fn,
	    PC_Struct.stat_filename );
    
    fd = open( PC_Struct.stat_filename, O_RDWR | O_CREAT, S_IREAD | S_IWRITE );
    if ( fd == -1 )
    {
	syslog(LOG_ERR, "%s: open() failed for '%s': %s -- Exiting.", fn, 
	       PC_Struct.stat_filename, strerror( errno ) );
	exit( 1 );
    }
    
    if ( ( ftruncate( fd, sizeof( IMAPCounter_Struct ) ) ) == -1 )
    {
	syslog(LOG_ERR, "%s: ftruncate() failed: %s -- Exiting.", 
	       fn, strerror( errno ) );
	exit( 1 );
    }
    
    IMAPCount = ( IMAPCounter_Struct *)mmap( 0, sizeof( IMAPCounter_Struct ), 
		    PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
    
    if ( IMAPCount == MAP_FAILED )
    {
	syslog(LOG_ERR, "%s: mmap() failed: %s -- Exiting.", 
	       fn, strerror( errno ) );
	exit( 1 );
    }
    
    memset( IMAPCount, 0, sizeof( IMAPCounter_Struct ) );
    IMAPCount->StartTime = time( 0 );
    IMAPCount->CountTime = time( 0 );

    /*
     * Daemonize as late as possible, so that connection failures can be caught
     * and startup aborted before dettaching from parent
     */
    Daemonize( PidFile );

    if ( BecomeNonRoot() )
	exit( 1 );

    /* some misc thread setup */
    rc = pthread_attr_init( &attr );
    if ( rc )
    {
	syslog(LOG_ERR, "%s: pthread_attr_init() failed: [%d]\n", fn, rc);
	exit( 1 );
    }
    
    rc = pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED );
    if ( rc )
    {
	syslog(LOG_ERR, "%s: pthread_attr_setdetachstate() failed: [%d]\n", 
	       fn, rc);
	exit( 1 );
    }

    /* launch a recycle thread before we loop */
    pthread_create( &RecycleThread, &attr, (void *)ICC_Recycle_Loop, NULL );

    syslog(LOG_INFO, "%s: Launched ICC recycle thread with id %d", 
	   fn, (int)RecycleThread );

    /*
     * Now start listening and accepting connections.
     */
    if ( listen(listensd, MAX_CONN_BACKLOG) < 0)
    {
	syslog( LOG_ERR, "%s: listen() failed: %s -- Exiting", 
	       fn, strerror(errno));
	exit( 1 );
    }

    syslog( LOG_INFO, "%s: squirrelmail-imap_proxy version %s normal server startup.", fn, IMAP_PROXY_VERSION );

    /*
     * Main server loop
     */
    for ( ;; )
    {
	/*
	 * Bug fixed by Gary Mills <*****@*****.**>.  I forgot
	 * to initialize sockaddrlen.
	 */
	sockaddrlen = sizeof cliaddr;
	clientsd = accept( listensd, (struct sockaddr *)&cliaddr,
			   &sockaddrlen );
	if ( clientsd == -1 )
	{
	    syslog(LOG_WARNING, "%s: accept() failed: %s -- retrying", 
		   fn, strerror(errno));
	    sleep( 1 );
	    continue;
	}

#ifdef HAVE_LIBWRAP
	request_init(&r, RQ_DAEMON, service, 0);
	request_set(&r, RQ_FILE, clientsd, 0);
	sock_host(&r);
	if (!hosts_access(&r))
	{
	    shutdown(clientsd, SHUT_RDWR);
	    close(clientsd);
	    syslog(deny_severity, "refused connection from %s", eval_client(&r));
	    continue;
	}
#endif

	IMAPCount->TotalClientConnectionsAccepted++;
	IMAPCount->CurrentClientConnections++;
	
	if ( IMAPCount->CurrentClientConnections > 
	     IMAPCount->PeakClientConnections )
	    IMAPCount->PeakClientConnections = IMAPCount->CurrentClientConnections;
	
	rc = pthread_create( &ThreadId, &attr, (void *)HandleRequest, (void *)clientsd );
	if (rc != 0) {
	    syslog(LOG_ERR, "%s: pthread_create() returned error [%d] for HandleRequest.", fn, rc );
	    close(clientsd);
	}
	
    }
}
Пример #12
0
BOOL CALLBACK Dialog_Main(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam)
{
    switch(Message)
    {
    case WM_INITDIALOG:
    {
        g_Window.WindowID = Window;
        g_Window.SetTitle(Window, "%s [%s] :: Main", APP_NAME, APP_VERSION_T);
        g_Window.PrintLine(1);
        g_Window.PrintText("\t\t\t\tWelcome to %s [%s]", APP_NAME, APP_VERSION_T);
        g_Window.PrintLine(1);
        gSettings.ReadData(".\\Settings.ini");
        LoadConnectServerList(".\\ServerList.txt");
        g_WhiteList.Load();
        g_BlackList.Load();
        ServerInit();
        SetTimer(Window, WM_UPDATER, 1000, NULL);
    }
    break;
    // --
    case WM_COMMAND:
    {
        switch(WParam)
        {
        case IDC_CLEARCONSOLE:
        {
            SetWindowText(GetDlgItem(Window, IDC_LOGWINDOW), "");
        }
        break;
        // --
        case IDM_EXIT:
        {
            EndDialog(Window, false);
        }
        break;
        // --
        case IDM_ABOUT:
        {
            DialogBoxParam(g_Window.Instance, MAKEINTRESOURCE(IDD_ABOUTBOX), NULL, Dialog_About, NULL);
        }
        break;
        // --
        case ID_RELOAD_SETTINGS:
        {
            gSettings.ReadData(".\\Settings.ini");
        }
        break;
        // --
        case ID_RELOAD_SERVERLIST:
        {
            LoadConnectServerList(".\\ServerList.txt");
        }
        break;
        // --
        case ID_WHITELIST_RELOADWHITELIST:
        {
            g_WhiteList.Load();
        }
        break;
        // --
        case ID_WHITELIST_ADDIP32781:
        {
            DialogBoxParam(g_Window.Instance, MAKEINTRESOURCE(IDD_SQLExec), NULL, Dialog_AddWhiteIP, NULL);
        }
        break;
        // --
        case ID_WHITELIST_ENABLE:
        {
            if( gSettings.WhiteList )
            {
                g_Window.PrintLog("[WhiteList] Status changed: Off");
                gSettings.WhiteList = false;
            }
            else
            {
                g_Window.PrintLog("[WhiteList] Status changed: On");
                gSettings.WhiteList = true;
            }
        }
        break;
        // --
        case ID_BLACKLIST_RELOADBLACKLIST:
        {
            g_BlackList.Load();
        }
        break;
        // --
        case ID_BLACKLIST_ADDIP:
        {
            DialogBoxParam(g_Window.Instance, MAKEINTRESOURCE(IDD_SQLExec), NULL, Dialog_AddBlackIP, NULL);
        }
        break;
        }
    }
    break;
    // --
    case WM_CLOSE:
    {
        EndDialog(Window, false);
    }
    break;
    // --
    case WM_TIMER:
    {
        switch(WParam)
        {
        case WM_UPDATER:
        {
            CheckServerState();
            g_Window.UpdateInfo();
        }
        break;
        }
    }
    break;
    }
    // ----
    return 0;
}
Пример #13
0
static void xmlrpc_process(int rank)
{
	/* install handler to catch termination of child processes */
	if (signal(SIGCHLD, xmlrpc_sigchld)==SIG_ERR) {
		LM_ERR("failed to install signal handler for SIGCHLD\n");
		goto error;
	}

	/* Server Abyss init */

	xmlrpc_env_init(&env);

	#ifdef XMLRPC_OLD_VERSION
	xmlrpc_server_abyss_init_registry();
	registryP= xmlrpc_server_abyss_registry();
	#else
	registryP = xmlrpc_registry_new(&env);    
	#endif

	DateInit();
	MIMETypeInit();

	if (!ServerCreate(&srv, "XmlRpcServer", port, "", log_file)) {
		LM_ERR("failed to create XMLRPC server\n");
		goto error;
	}

	#ifdef XMLRPC_OLD_VERSION
	if (!ServerAddHandler(&srv, xmlrpc_server_abyss_rpc2_handler)) {
		LM_ERR("failed to add handler to server\n");
		goto error;
	}

	ServerDefaultHandler(&srv, xmlrpc_server_abyss_default_handler);

	#else

	xmlrpc_server_abyss_set_handlers2(&srv, "/RPC2", registryP);

	#endif

	ServerInit(&srv);

	if( init_mi_child() != 0 ) {
		LM_CRIT("failed to init the mi process\n");
		goto error;
	}

	if ( xr_writer_init(read_buf_size) != 0 ) {
		LM_ERR("failed to init the reply writer\n");
		goto error;
	}
	#ifdef XMLRPC_OLD_VERSION
	xmlrpc_env_init(&env);
	#endif

	if ( rpl_opt == 1 ) {
		xr_response = xmlrpc_build_value(&env, "()");
		if ( env.fault_occurred ){
			LM_ERR("failed to create an empty array: %s\n", env.fault_string);
			goto cleanup;
		}
	}

	if ( set_default_method(&env,registryP) != 0 ) {
		LM_ERR("failed to set up the default method!\n");
		goto cleanup;
	}

	/* Run server abyss */
	LM_INFO("starting xmlrpc server\n");

	ServerRun(&srv);

	LM_CRIT("Server terminated!!!\n");

cleanup:
	xmlrpc_env_clean(&env);
	if ( xr_response ) xmlrpc_DECREF(xr_response);
error:
	exit(-1);
}
Пример #14
0
int SslSocketCpServer::Start()
{
	SOCKADDR_IN InternetAddr;
	SOCKET Listen;
	HANDLE ThreadHandle;
	SOCKET Accept;

	SYSTEM_INFO SystemInfo;
	LPPER_HANDLE_DATA PerHandleData;
	LPPER_IO_OPERATION_DATA PerIoData;
	int i;
	DWORD RecvBytes;
	DWORD Flags;
	DWORD ThreadID;
	WSADATA wsaData;
	DWORD Ret;
	DWORD dwThreadId = GetCurrentThreadId();

	if ((Ret = WSAStartup((2, 2), &wsaData)) != 0)
	{
		fprintf(stderr, "%d::WSAStartup() failed with error %d\n", dwThreadId, Ret);
		return 1;
	}
	else
		fprintf(stderr, "%d::WSAStartup() is OK!\n", dwThreadId);


	if ((CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0)) == NULL)
	{
		fprintf(stderr, "%d::CreateIoCompletionPort() failed with error %d\n", dwThreadId, GetLastError());
		return 1;
	}
	else
		fprintf(stderr, "%d::CreateIoCompletionPort() is damn OK!\n", dwThreadId);


	GetSystemInfo(&SystemInfo);

	int nThreads = (int)SystemInfo.dwNumberOfProcessors * 2;

	nThreads = 2;

	//nThreads = (nThreads / 2);


	for (i = 0; i < nThreads; i++)
	{

		if ((ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, this, 0, &ThreadID)) == NULL)
		{
			fprintf(stderr, "%d::CreateThread() failed with error %d\n", dwThreadId, GetLastError());
			return 1;
		}
		else
			fprintf(stderr, "%d::CreateThread() is OK!\n", dwThreadId);

		CloseHandle(ThreadHandle);
	}


	if ((Listen = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
	{
		fprintf(stderr, "%d::WSASocket() failed with error %d\n", dwThreadId, WSAGetLastError());
		return 1;
	}
	else
		fprintf(stderr, "%d::WSASocket() is OK!\n", dwThreadId);

	InternetAddr.sin_family = AF_INET;
	InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	InternetAddr.sin_port = htons(m_PortNum);

	int bRes = bind(Listen, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr));
	while (bRes == SOCKET_ERROR)
	{
		fprintf(stderr, "%d::bind() failed with error %d\nLooking for next port...\n", dwThreadId, WSAGetLastError());
		InternetAddr.sin_port = htons(++m_PortNum);
		bRes = bind(Listen, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr));
	}
	fprintf(stderr, "%d::bind() is fine! Port number at  %d\n", dwThreadId, m_PortNum);

	// Prepare socket for listening
	if (listen(Listen, 5) == SOCKET_ERROR)
	{
		fprintf(stderr, "%d::listen() failed with error %d\n", dwThreadId, WSAGetLastError());
		return 1;
	}
	else
		fprintf(stderr, "%d::listen() is working...\n", dwThreadId);

	if (ServerInit(true) == -1)
	{
		printf("Server Init fail \n");
		exit(1);
	}


	BOOL isOK = true;
	while (isOK)
	{
		if ((Accept = WSAAccept(Listen, NULL, NULL, NULL, 0)) == SOCKET_ERROR)
		{
			fprintf(stderr, "%d::WSAAccept() failed with error %d\n", dwThreadId, WSAGetLastError());
			isOK = false;

			exit(1);
			continue;
		}
		else
			fprintf(stderr, "%d::WSAAccept() looks fine!\n", dwThreadId);


		if ((PerHandleData = (LPPER_HANDLE_DATA)GlobalAlloc(GPTR, sizeof(PER_HANDLE_DATA))) == NULL)
			fprintf(stderr, "%d::GlobalAlloc() failed with error %d\n", dwThreadId, GetLastError());
		else
			fprintf(stderr, "%d::GlobalAlloc() for LPPER_HANDLE_DATA is OK!\n", dwThreadId);


		fprintf(stderr, "%d::Socket number %d got connected...\n", dwThreadId, Accept);
		PerHandleData->Socket = Accept;

		if (CreateIoCompletionPort((HANDLE)Accept, CompletionPort, (DWORD)PerHandleData, 0) == NULL)
		{
			fprintf(stderr, "%d::CreateIoCompletionPort() failed with error %d\n", dwThreadId, GetLastError());

			exit(1);
			isOK = false;
			continue;
		}
		else
			fprintf(stderr, "%d::CreateIoCompletionPort() is OK!\n", dwThreadId);


		if ((PerIoData = (LPPER_IO_OPERATION_DATA)GlobalAlloc(GPTR, sizeof(PER_IO_OPERATION_DATA))) == NULL)
		{
			fprintf(stderr, "%d::GlobalAlloc() failed with error %d\n", dwThreadId, GetLastError());

			exit(1);
			isOK = false;
			continue;
		}
		else
			fprintf(stderr, "%d::GlobalAlloc() for LPPER_IO_OPERATION_DATA is OK!\n", dwThreadId);

		ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));
		PerIoData->BytesSEND = 0;
		PerIoData->BytesRECV = 0;
		PerIoData->DataBuf.len = DATA_BUFSIZE;
		PerIoData->DataBuf.buf = PerIoData->Buffer;
		PerIoData->LPBuffer = NULL;

		Flags = 0;
		DWORD dwRes = WSARecv(Accept, &(PerIoData->DataBuf), 1, &PerIoData->BytesRECV, &Flags, &(PerIoData->Overlapped), NULL);
		RecvBytes = PerIoData->BytesRECV;

		printf("\n\n%d::WSARECV1 Socket=%d, PerIoData->BytesRECV=%d; PerIoData->BytesSEND=%d\n\n", dwThreadId, PerHandleData->Socket, PerIoData->BytesRECV, PerIoData->BytesSEND);

		if (dwRes == SOCKET_ERROR)
		{
			if (WSAGetLastError() != ERROR_IO_PENDING)
			{
				fprintf(stderr, "%d::WSARecv() failed with error %d\n", dwThreadId, WSAGetLastError());

				isOK = true;
				continue;
			}
		}
		else
			fprintf(stderr, "%d::WSARecv() is OK!\n", dwThreadId);

	}
	return 0;
}
Пример #15
0
int main( int argc, char *argv[] )
{
    char *fn = "main()";
    char f_randfile[ PATH_MAX ];
    int listensd;                      /* socket descriptor we'll bind to */
    int clientsd;                      /* incoming socket descriptor */
    int addrlen;
    struct sockaddr_in srvaddr;
    struct sockaddr_in cliaddr;
    pthread_t ThreadId;                /* thread id of each incoming conn */
    pthread_t RecycleThread;           /* used just for the recycle thread */
    pthread_attr_t attr;               /* generic thread attribute struct */
    int rc, i, fd;
    unsigned int ui;
    pid_t pid;                         /* used just for a fork call */
    struct linger lingerstruct;        /* for the socket reuse stuff */
    int flag;                          /* for the socket reuse stuff */
    ICC_Struct *ICC_tptr;
    extern char *optarg;
    extern int optind;
    char ConfigFile[ MAXPATHLEN ];     /* path to our config file */
#ifdef HAVE_LIBWRAP
    struct request_info r;             /* request struct for libwrap */
#endif

    flag = 1;
    ConfigFile[0] = '\0';

    /*
     * Ignore signals we don't want to die from but we don't care enough
     * about to catch.
     */
    signal( SIGPIPE, SIG_IGN );
    signal( SIGHUP, SIG_IGN );


    while (( i = getopt( argc, argv, "f:h" ) ) != EOF )
    {
        switch( i )
        {
        case 'f':
            /* user specified a config filename */
            strncpy( ConfigFile, optarg, sizeof ConfigFile -1 );
            ConfigFile[ sizeof ConfigFile - 1 ] = '\0';
            syslog( LOG_INFO, "%s: Using configuration file '%s'",
                    fn, ConfigFile );
            break;

        case 'h':
            Usage();
            exit( 0 );

        case '?':
            Usage();
            exit( 1 );
        }
    }


    /*
     * Make sure we know which config file to use and then set our config
     * options.
     */
    if ( ! ConfigFile[0] )
    {
        strncpy( ConfigFile, DEFAULT_CONFIG_FILE, sizeof ConfigFile -1 );
        ConfigFile[ sizeof ConfigFile - 1 ] = '\0';
        syslog( LOG_INFO, "%s: Using default configuration file '%s'.",
                fn, ConfigFile );
    }

    SetConfigOptions( ConfigFile );
    SetLogOptions();

    /*
     * Just for logging purposes, are we doing SELECT caching or not?
     */
    if ( PC_Struct.enable_select_cache )
        syslog( LOG_INFO, "%s: SELECT caching is enabled", fn );
    else
        syslog( LOG_INFO, "%s: SELECT caching is disabled", fn );

#ifdef HAVE_LIBWRAP
    /*
     * Set our tcpd service name
     */
    if (service = strrchr(argv[0], '/'))
        service++;
    else
        service = argv[0];
#endif

    /*
     * Initialize some stuff.
     */
    rc = pthread_mutex_init(&mp, NULL);
    if ( rc )
    {
        syslog(LOG_ERR, "%s: pthread_mutex_init() returned error [%d] initializing main mutex.  Exiting.", fn, rc );
        exit( 1 );
    }

    rc = pthread_mutex_init(&trace, NULL);
    if ( rc )
    {
        syslog(LOG_ERR, "%s: pthread_mutex_init() returned error [%d] initializing trace mutex.  Exiting.", fn, rc );
        exit( 1 );
    }

    TraceUser[0] = '\0';

    syslog( LOG_INFO, "%s: Allocating %d IMAP connection structures.",
            fn, PC_Struct.cache_size );

    ICC_free = (ICC_Struct *)malloc( ( sizeof ( ICC_Struct ) )
                                     * PC_Struct.cache_size );

    if ( ! ICC_free )
    {
        syslog(LOG_ERR, "%s: malloc() failed to allocate [%d] IMAPConnectionContext structures: %s", fn, PC_Struct.cache_size, strerror( errno ) );
        exit( 1 );
    }

    memset( ICC_free, 0, sizeof ( ICC_Struct ) * PC_Struct.cache_size );

    ICC_tptr = ICC_free;

    /*
     * Bug fixed by Gary Mills <*****@*****.**>.  I was pre-incrementing
     * ICC_tptr and then assigning.  I guess gcc evaluates the expression
     * incorrectly, since I never had a problem with this.  Gary had the
     * problem with cc, so it's fixed here.
     */
    for ( ui = 0; ui < PC_Struct.cache_size - 1; ui++ )
    {
        ICC_tptr->next = ICC_tptr + 1;
        ICC_tptr++;
    }

    memset( ICC_HashTable, 0, sizeof ICC_HashTable );

    ServerInit();

    /* detach from our parent if necessary */
    if (! (getppid() == 1) && ( ! PC_Struct.foreground_mode ) )
    {
        syslog( LOG_INFO, "%s: Configured to run in background mode.", fn );

        if ( (pid = fork()) < 0)
        {
            syslog(LOG_ERR, "%s: initial call to fork() failed: %s", fn, strerror(errno));
            exit( 1 );
        }
        else if ( pid > 0)
        {
            exit( 0 );
        }

        if (setsid() == -1)
        {
            syslog(LOG_WARNING, "%s: setsid() failed: %s",
                   fn, strerror(errno));
        }
        if ( (pid = fork()) < 0)
        {
            syslog(LOG_ERR, "%s: secondary call to fork() failed: %s", fn,
                   strerror(errno));
            exit( 1 );
        }
        else if ( pid > 0)
        {
            exit( 0 );
        }
    }
    else
    {
        syslog( LOG_INFO, "%s: Configured to run in foreground mode.", fn );
    }


    SetBannerAndCapability();

    if ( PC_Struct.login_disabled || PC_Struct.force_tls )
    {
        syslog( LOG_INFO, "%s: Enabling STARTTLS.", fn );
#if HAVE_LIBSSL
        if ( PC_Struct.support_starttls )
        {
            /* Initialize SSL_CTX */
            SSL_library_init();

            /* Need to seed PRNG, too! */
            if ( RAND_egd( ( RAND_file_name( f_randfile, sizeof( f_randfile ) ) == f_randfile ) ? f_randfile : "/.rnd" ) )
            {
                /* Not an EGD, so read and write it. */
                if ( RAND_load_file( f_randfile, -1 ) )
                    RAND_write_file( f_randfile );
            }

            SSL_load_error_strings();
            tls_ctx = SSL_CTX_new( TLSv1_client_method() );
            if ( tls_ctx == NULL )
            {
                syslog(LOG_ERR, "%s: Failed to create new SSL_CTX.  Exiting.", fn);
                exit( 1 );
            }

            /* Work around all known bugs */
            SSL_CTX_set_options( tls_ctx, SSL_OP_ALL );

            if ( ! SSL_CTX_load_verify_locations( tls_ctx,
                                                  PC_Struct.tls_ca_file,
                                                  PC_Struct.tls_ca_path ) ||
                    ! SSL_CTX_set_default_verify_paths( tls_ctx ) )
            {
                syslog(LOG_ERR, "%s: Failed to load CA data.  Exiting.", fn);
                exit( 1 );
            }

            if ( ! set_cert_stuff( tls_ctx,
                                   PC_Struct.tls_cert_file,
                                   PC_Struct.tls_key_file ) )
            {
                syslog(LOG_ERR, "%s: Failed to load cert/key data.  Exiting.", fn);
                exit( 1 );
            }

            SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_NONE, verify_callback);
        }
        else
#endif /* HAVE_LIBSSL */
        {
            /* We're screwed!  We won't be able to login without SASL */
            syslog(LOG_ERR, "%s: IMAP server has LOGINDISABLED and we can't do STARTTLS.  Exiting.", fn);
            exit( 1 );
        }
    }

    memset( (char *) &srvaddr, 0, sizeof srvaddr );
    srvaddr.sin_family = PF_INET;
    if ( !PC_Struct.listen_addr )
    {
        srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    }
    else
    {
        srvaddr.sin_addr.s_addr = inet_addr( PC_Struct.listen_addr );
        if ( srvaddr.sin_addr.s_addr  == -1 )
        {
            syslog( LOG_ERR, "%s: bad bind address: '%s' specified in config file.  Exiting.", fn, PC_Struct.listen_addr );
            exit( 1 );
        }
    }


    syslog(LOG_INFO, "%s: Binding to tcp %s:%d", fn, PC_Struct.listen_addr ?
           PC_Struct.listen_addr : "*", PC_Struct.listen_port );
    srvaddr.sin_port = htons(PC_Struct.listen_port);

    listensd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if ( listensd == -1 )
    {
        syslog(LOG_ERR, "%s: socket() failed: %s", fn, strerror(errno));
        exit( 1 );
    }

    setsockopt(listensd, SOL_SOCKET, SO_REUSEADDR, (void *)&flag,
               sizeof(flag));
    lingerstruct.l_onoff = 1;
    lingerstruct.l_linger = 5;
    setsockopt(listensd, SOL_SOCKET, SO_LINGER, (void *)&lingerstruct,
               sizeof(lingerstruct));

    if ( PC_Struct.send_tcp_keepalives )
    {
        lingerstruct.l_onoff = 1;
        syslog( LOG_INFO, "%s: Enabling SO_KEEPALIVE.", fn );
        setsockopt( listensd, SOL_SOCKET, SO_KEEPALIVE, (void *)&lingerstruct.l_onoff, sizeof lingerstruct.l_onoff );
    }


    if ( bind(listensd, (struct sockaddr *)&srvaddr, sizeof( srvaddr ) ) < 0 )
    {
        syslog(LOG_ERR, "%s: bind() failed: %s", fn, strerror(errno) );
        exit( 1 );
    }

    /*
     * Create and mmap() our stat file while we're still root.  Since it's
     * configurable, we want to make sure we do this as root so there's the
     * greatest possibility that we'll have permission to write where we
     * need to.
     */
    syslog( LOG_INFO, "%s: Using global statistics file '%s'", fn,
            PC_Struct.stat_filename );

    fd = open( PC_Struct.stat_filename, O_RDWR | O_CREAT, S_IREAD | S_IWRITE );
    if ( fd == -1 )
    {
        syslog(LOG_ERR, "%s: open() failed for '%s': %s -- Exiting.", fn,
               PC_Struct.stat_filename, strerror( errno ) );
        exit( 1 );
    }

    if ( ( ftruncate( fd, sizeof( IMAPCounter_Struct ) ) ) == -1 )
    {
        syslog(LOG_ERR, "%s: ftruncate() failed: %s -- Exiting.",
               fn, strerror( errno ) );
        exit( 1 );
    }

    IMAPCount = ( IMAPCounter_Struct *)mmap( 0, sizeof( IMAPCounter_Struct ),
                PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );

    if ( IMAPCount == MAP_FAILED )
    {
        syslog(LOG_ERR, "%s: mmap() failed: %s -- Exiting.",
               fn, strerror( errno ) );
        exit( 1 );
    }

    memset( IMAPCount, 0, sizeof( IMAPCounter_Struct ) );
    IMAPCount->StartTime = time( 0 );
    IMAPCount->CountTime = time( 0 );

    if ( BecomeNonRoot() )
        exit( 1 );

    /* some misc thread setup */
    rc = pthread_attr_init( &attr );
    if ( rc )
    {
        syslog(LOG_ERR, "%s: pthread_attr_init() failed: [%d]\n", fn, rc);
        exit( 1 );
    }

    rc = pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED );
    if ( rc )
    {
        syslog(LOG_ERR, "%s: pthread_attr_setdetachstate() failed: [%d]\n",
               fn, rc);
        exit( 1 );
    }

    /* launch a recycle thread before we loop */
    pthread_create( &RecycleThread, &attr, (void *)ICC_Recycle_Loop, NULL );

    syslog(LOG_INFO, "%s: Launched ICC recycle thread with id %d",
           fn, RecycleThread );

    /*
     * Now start listening and accepting connections.
     */
    if ( listen(listensd, MAX_CONN_BACKLOG) < 0)
    {
        syslog( LOG_ERR, "%s: listen() failed: %s -- Exiting",
                fn, strerror(errno));
        exit( 1 );
    }

    syslog( LOG_INFO, "%s: Normal server startup.", fn );

    /*
     * Main server loop
     */
    for ( ;; )
    {
        /*
         * Bug fixed by Gary Mills <*****@*****.**>.  I forgot
         * to initialize addrlen.
         */
        addrlen = sizeof cliaddr;
        clientsd = accept( listensd, (struct sockaddr *)&cliaddr, &addrlen );
        if ( clientsd == -1 )
        {
            syslog(LOG_WARNING, "%s: accept() failed: %s -- retrying",
                   fn, strerror(errno));
            sleep( 1 );
            continue;
        }

#ifdef HAVE_LIBWRAP
        request_init(&r, RQ_DAEMON, service, 0);
        request_set(&r, RQ_FILE, clientsd, 0);
        sock_host(&r);
        if (!hosts_access(&r))
        {
            shutdown(clientsd, SHUT_RDWR);
            close(clientsd);
            syslog(deny_severity, "refused connection from %s", eval_client(&r));
            continue;
        }
#endif

        IMAPCount->TotalClientConnectionsAccepted++;
        IMAPCount->CurrentClientConnections++;

        if ( IMAPCount->CurrentClientConnections >
                IMAPCount->PeakClientConnections )
            IMAPCount->PeakClientConnections = IMAPCount->CurrentClientConnections;

        pthread_create( &ThreadId, &attr, (void *)HandleRequest, (void *)clientsd );

    }
}
Пример #16
0
int main(int argc,char **argv)
{
    const char * const name = argv[0];
    TServer srv;
    char * p;
    const char * conffile;
    bool err;

    conffile = DEFAULT_CONF_FILE;  /* initial value */
    err = FALSE;  /* initial value */

    while (p=*(++argv))
    {
        if ((*p=='-') && (*(p+1)))
            if (*(p+2)=='\0')
                switch (*(p+1))
                {
                case 'c':
                    argv++;
                    if (*argv)
                        conffile=*argv;
                    else
                        err=TRUE;
                    break;
                default:
                    err=TRUE;
                }
            else
                err=TRUE;
        else
            err=TRUE;
    };

    if (err)
    {
        help(name);
        exit(1);
    };

    DateInit();

    MIMETypeInit();

    ServerCreate(&srv,"HTTPServer",80,DEFAULT_DOCS,NULL);

    ConfReadServerFile(conffile,&srv);

    ServerAddHandler(&srv,HandleTime);
    ServerAddHandler(&srv,HandleDump);
    ServerAddHandler(&srv,HandleStatus);
    ServerAddHandler(&srv,HandleMIMEType);

    ServerInit(&srv);

#ifdef _UNIX
    /* Catch various termination signals. */
    signal(SIGTERM,sigterm);
    signal(SIGINT,sigterm);
    signal(SIGHUP,sigterm);
    signal(SIGUSR1,sigterm);

    /* Catch defunct children. */
    signal(SIGCHLD,sigchld);
#endif

    ServerDaemonize(srv);

    ServerRun(&srv);

    return 0;
}
Пример #17
0
static void *
xr_rpcListener (Server *svr)
{
    struct xmlrpc_method_info3 const methodInfo[] = {
       /* .methodName   	.methodFunction  	*/ 
	{ "svrping", 		&test_ping,		},
	/*
	{ "sys.abort", 		&xr_requestAbort,	},
	{ "sys.shutdown", 	&xr_requestShutdown,	}
	*/
    };
    register int i = 0;
    TServer abyssServer;
    xmlrpc_registry * registryP;
    xmlrpc_env env;
    const char * error;

    extern void xr_serverRunOnce ();
    extern int  xr_requestAbort ();


    AbyssInit (&error);				/* initialize		*/
    xmlrpc_env_init (&env);
    registryP = xmlrpc_registry_new (&env);


    if (SRVR_DEBUG)
	fprintf (stderr, "single_run_server rpcListener ....\n");

    /*  Setup a test ping method and install the special shutdown handlers.
     */
    for (i=0; i < 1; i++)
    	xmlrpc_registry_add_method3 (&env, registryP, &methodInfo[i]);

    /*  Set default shutdown method.
     */
    xmlrpc_registry_set_shutdown (registryP, &xr_requestShutdown, &svr_done);
    xr_addServerMethod ("sys.abort", xr_requestAbort, NULL);


    /*  Set the default method we'll use to dispatch calls.
     */
    svr->serverparm.enable_shutdown = (xmlrpc_bool) 1;
    xmlrpc_registry_set_default_method (&svr->env, 
        (svr->serverparm.registryP = svr->registry = registryP), 
        (xmlrpc_default_method) &xr_defaultMethod, svr);


    /*  Create the server instance.
     */
    ServerCreate (&abyssServer, "XmlRpcServer", 
	svr->serverparm.port_number, NULL, NULL);

    xmlrpc_server_abyss_set_handlers2 (&abyssServer, "/RPC2",
	svr->serverparm.registryP);

    ServerInit (&abyssServer);

#ifdef XR_SIGPIPE_IGN
    xr_setupSigpipeHandlers ();
#endif


    while (! svr_done ) {
        /*  This waits for the next connection, accepts it, reads the
         *  HTTP POST request, executes the indicated RPC, and closes
         *  the connection.
        ServerRunOnce (&abyssServer);
         */
 	//	ServerRunOnce(&abyssServer);
       (void) xr_serverRunOnce (&abyssServer);
    }

    ServerFree (&abyssServer);			/* shut down		*/
    AbyssTerm ();

    return ((void *) ERR);
}