void
ServerInit(TServer * const serverP) {
/*----------------------------------------------------------------------------
   Initialize a server to accept connections.

   Do not confuse this with creating the server -- ServerCreate().

   Not necessary or valid with a server that doesn't accept connections (i.e.
   user supplies the TCP connections).
-----------------------------------------------------------------------------*/
    struct _TServer * const srvP = serverP->srvP;
    abyss_bool success;
    
    if (!srvP->serverAcceptsConnections) {
        TraceMsg("ServerInit() is not valid on a server that doesn't "
                 "accept connections "
                 "(i.e. created with ServerCreateNoAccept)");
        success = FALSE;
    } else {
        if (!srvP->socketBound)
            createAndBindSocket(srvP);

        if (srvP->socketBound) {
            success = SocketListen(srvP->listenSocketP, MAX_CONN);

            if (!success)
                TraceMsg("Failed to listen on bound socket.");
        } else
            success = FALSE;
    }
    if (!success)
        exit(1);
}
示例#2
0
bool GDBStubListen(struct GDBStub* stub, int port, const struct Address* bindAddress) {
	if (!SOCKET_FAILED(stub->socket)) {
		GDBStubShutdown(stub);
	}
	stub->socket = SocketOpenTCP(port, bindAddress);
	if (SOCKET_FAILED(stub->socket)) {
		mLOG(DEBUGGER, ERROR, "Couldn't open socket");
		return false;
	}
	if (!SocketSetBlocking(stub->socket, false)) {
		goto cleanup;
	}
	int err = SocketListen(stub->socket, 1);
	if (err) {
		goto cleanup;
	}

	return true;

cleanup:
	mLOG(DEBUGGER, ERROR, "Couldn't listen on port");
	SocketClose(stub->socket);
	stub->socket = INVALID_SOCKET;
	return false;
}
示例#3
0
文件: server.c 项目: cmjonze/anacapa
void ServerNetInit(TServer *srv)
{
	/* sanity */
	if (!srv) {
		return;
	}

	if( srv->port == 0 ) {
		srv->listensock.fd = -1;
		return;
	}

	/********* Must check errors from these functions *************/
	if (!SocketInit())
		TraceExit("Can't initialize TCP sockets\n");;

	if (!SocketCreate(&srv->listensock))
		TraceExit("Can't create a socket\n");;

	if (!SocketBind(&srv->listensock,NULL,srv->port))
		TraceExit("Can't bind\n");

	if (!SocketListen(&srv->listensock,srv->max_conn))
		TraceExit("Can't listen\n");
}
示例#4
0
static bool _mPerfRunServer(const char* listen, const struct mArguments* args, const struct PerfOpts* perfOpts) {
	SocketSubsystemInit();
	Socket server = SocketOpenTCP(7216, NULL);
	if (SOCKET_FAILED(server)) {
		SocketSubsystemDeinit();
		return false;
	}
	if (SOCKET_FAILED(SocketListen(server, 0))) {
		SocketClose(server);
		SocketSubsystemDeinit();
		return false;
	}
	_socket = SocketAccept(server, NULL);
	if (perfOpts->csv) {
		const char* header = "game_code,frames,duration,renderer\n";
		SocketSend(_socket, header, strlen(header));
	}
	char path[PATH_MAX];
	while (SocketRecv(_socket, path, sizeof(path)) > 0) {
		char* nl = strchr(path, '\n');
		if (nl == path) {
			break;
		}
		if (nl) {
			nl[0] = '\0';
		}
		if (!_mPerfRunCore(path, args, perfOpts)) {
			break;
		}
	}
	SocketClose(_socket);
	SocketClose(server);
	SocketSubsystemDeinit();
	return true;
}
static void
tests(void)
{
    pthread_t server_thread;
    int socket;

    socket = SocketListen(4443);

    ok(socket>=0, "SocketListen failed");
    if(socket<0) {
        return;
    }
    //fprintf(stderr, "session_id: %d\n", session_id);

    pthread_create(&server_thread, NULL, securetransport_ssl_thread, socket);

    system("/usr/bin/openssl s_client -msg -debug -connect localhost:4443");

    int server_err;
    pthread_join(server_thread, (void*)&server_err);

    ok(!server_err, "Server thread failed err=%d", server_err);
}
示例#6
0
int main( int argc,char * argv[] )
{
	crypt_buffer_ctx ctx ;

	crypt_buffer_result r ;
	ssize_t n ;

	char * encryption_key ;
	size_t encryption_key_length ;

	int network_port             = PORT_NUMBER ;
	const char * network_address = NETWORK_ADDRESS ;
	socket_t c ;

	char * e ;

	#define buffer_size sizeof( zuluKey_t ) * 2
	char buffer[ buffer_size ] ;

	socket_t s ;

	struct sigaction sa ;

	if( argc < 2 ){

		puts( "error: invalid number of arguments" ) ;
		return 1 ;
	}else if( argc >= 4 ){

		network_address = *( argv + 2 ) ;
		network_port    = atoi( *( argv + 3 ) ) ;
	}

	memset( &sa,'\0',sizeof( struct sigaction ) ) ;
	sa.sa_handler = _closeServer ;
	sigaction( SIGTERM,&sa,NULL ) ;

	e = *( argv + 1 ) ;

	encryption_key_length = strlen( e ) ;

	encryption_key = malloc( sizeof( char ) * encryption_key_length ) ;
	memcpy( encryption_key,e,encryption_key_length ) ;

	memset( e,'\0',encryption_key_length ) ;

	s = SocketNet( network_address,network_port ) ;

	_clean_on_exit.s             = s ;
	_clean_on_exit.buffer        = encryption_key ;
	_clean_on_exit.buffer_length = encryption_key_length ;

	_debug( "server started" ) ;

	if( !SocketBind( s ) ){

		return _exitServer( "socket bind failed" ) ;
	}

	if( !SocketListen( s ) ){

		return _exitServer( "socket listen failed" ) ;
	}

	if( crypt_buffer_init( &ctx,encryption_key,encryption_key_length ) ){

		_clean_on_exit.ctx = ctx ;

		while( 1 ){

			c = SocketAccept( s ) ;

			n = SocketGetData_3( c,buffer,buffer_size,4 ) ;

			if( n != -1 ){

				if( crypt_buffer_decrypt( ctx,buffer,n,&r ) ){

					_process_request( c,ctx,&r ) ;
				}else{
					_debug( "failed to decrypt data" ) ;
				}
			}else{
				_debug( "network timed out" ) ;
			}

			SocketClose( &c ) ;
		}

	}else{
		_debug( "failed to initialize encryption routine" ) ;
	}

	return 0 ;
}
示例#7
0
文件: files.c 项目: mingpen/OpenNT
/* ss_sendfiles:
   Send a response naming the data pipe, collect further names
   from further client messages, all according to the protocol above.
   Start the data pipe and arrange that all the files are sent
   by getting them all enqueued on the first queue.
   Destroy PackQueue at the end.  Arrange for the other queues
   to be destroyed by the usual Queue mechanism, or destroy them
   explicitly if they never get started.
*/
BOOL
ss_sendfiles(HANDLE hPipe, long lVersion)
{       /* Create the queues and set about filling the first one */

        QUEUE PackQueue, ReadQueue, SendQueue;

#ifdef SOCKETS
        SOCKET hpSend;
        static BOOL SocketsInitialized = FALSE;
#else
        HANDLE hpSend;          /* the data pipe */
#endif /* SOCKETS */

        char PipeName[80];      /* The name of the new data pipe */
        BOOL Started = FALSE;   /* TRUE if something enqueued */


#ifdef SOCKETS
        if( !SocketsInitialized )
        {
                WSADATA WSAData;

                if( ( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) ) == 0 )
                {
                        SocketsInitialized = TRUE;
                }
                else
                {
                        printf("WSAStartup failed");
                }
        }
#endif

        {
                /****************************************
                We need security attributes for the pipe to let anyone other than the
                current user log on to it.
                ***************************************/

                /* Allocate DWORDs for the ACL to get them aligned.  Round up to next DWORD above */
                DWORD Acl[(sizeof(ACL)+sizeof(ACCESS_ALLOWED_ACE)+3)/4+4];    // + 4 by experiment!!
                SECURITY_DESCRIPTOR sd;
                PSECURITY_DESCRIPTOR psd = &sd;
                PSID psid;
                SID_IDENTIFIER_AUTHORITY SidWorld = SECURITY_WORLD_SID_AUTHORITY;
                PACL pacl = (PACL)(&(Acl[0]));
                SECURITY_ATTRIBUTES sa;
                BOOL brc;
                DWORD lasterr;

                if (!AllocateAndInitializeSid( &SidWorld, 1, SECURITY_WORLD_RID
                                              , 1, 2, 3, 4, 5, 6, 7
                                              , &psid
                                              )
                   ) {
                        Error("AllocateAndInitializeSid");
                        return FALSE;
                   }

                if (!InitializeAcl(pacl, sizeof(Acl), ACL_REVISION)){
                        Error("InitializeAcl");
                        return FALSE;
                }
                if (!AddAccessAllowedAce(pacl, ACL_REVISION, GENERIC_WRITE|GENERIC_READ, psid)){
                        Error("AddAccessAllowedAce");
                        return FALSE;
                }
                if (!InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION)){
                        Error("InitializeSecurityDescriptor");
                        return FALSE;
                }
                if (!SetSecurityDescriptorDacl(psd, TRUE, pacl, FALSE)){
                        Error("SetSecurityDescriptorDacl");
                        return FALSE;
                }
                sa.nLength = sizeof(sa);
                sa.lpSecurityDescriptor = psd;
                sa.bInheritHandle = TRUE;

                /* We now have a good security descriptor!  */

                /* Create the (new, unique) name of the pipe and then create the pipe */

                /* I am finding it hard to decide whether the following line (++PpipeCount)
                   actually needs a critical section or not.  The worst that could happen
                   would be that we got an attempt to create a pipe with an existing name.
                */
                ++PipeCount;
                sprintf(PipeName, "\\\\.\\pipe\\%s%d", PIPEPREFIX, PipeCount);

#ifdef SOCKETS
                if (!ss_sendnewresp( hPipe, SS_VERSION, SSRESP_PIPENAME
                                   , 0, 0, 0, TCPPORT, "")) {
                        dprintf1(( "Failed to send response on pipe %x naming new pipe.\n"
                              , hPipe));
                        return FALSE;           /* Caller will close hPipe */
                }

                if( !SocketListen( TCPPORT, &hpSend ) )
                {
                    dprintf1(("Could not create socket\n"));
                    return FALSE;
                }

                FreeSid(psid);
#else
                hpSend = CreateNamedPipe(PipeName,              /* pipe name */
                                PIPE_ACCESS_DUPLEX,     /* both read and write */
                                PIPE_WAIT|PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE,
                                1,              /* at most one instance */
                                10000,          /* sizeof(SSNEWPACK) + some for luck */
                                0,              /* dynamic inbound buffer allocation */
                                5000,           /* def. timeout 5 seconds */
                                &sa             /* security descriptor */
                                );
                FreeSid(psid);

                if (hpSend == INVALID_HANDLE_VALUE) {
                        dprintf1(("Could not create named data pipe\n"));
                        return FALSE;
                }
                dprintf1(("Data pipe %x called '%s' created for main pipe %x.\n", hpSend, PipeName, hPipe));

#endif /* SOCKETS */

        }




        /* Send the response which names the data pipe */

#ifndef SOCKETS
        if (!ss_sendnewresp( hPipe, SS_VERSION, SSRESP_PIPENAME
                           , 0, 0, 0, 0, PipeName)) {
                dprintf1(( "Failed to send response on pipe %x naming new pipe.\n"
                      , hPipe));
                CLOSEHANDLE(hpSend);
                return FALSE;           /* Caller will close hPipe */
        }

        if (!ConnectNamedPipe(hpSend, NULL)) {
                CLOSEHANDLE(hpSend);
                return FALSE;
        }
#endif /* NOT SOCKETS */
        //dprintf1(("Client connected to data pipe -- here we go...\n"));

        /* Create all the queues: Allow up to 10K file names to be queued
           up to 10 files to be packed in advance and 6 buffers of data to be
           read into main storage in advance:
                                  proc  MxMT MnQS MxQ Event   InstData   Name*/
        SendQueue = Queue_Create(SendData, 1, 0,  6, NULL, (DWORD)hpSend, "SendQueue");
        ReadQueue = Queue_Create(ReadInFile, 1, 0, 10, NULL, (DWORD)SendQueue, "ReadQueue");
        PackQueue = Queue_Create(PackFile, 3, 0, 99999, NULL, (DWORD)ReadQueue, "PackQueue");

        /* Abort unless it all worked */
        if (PackQueue==NULL || ReadQueue==NULL || SendQueue==NULL) {
                dprintf1(("Queues for pipe %x failed to Create.  Aborting...\n", hPipe));
                if (PackQueue) Queue_Destroy(PackQueue);
                if (ReadQueue) Queue_Destroy(ReadQueue);
                if (SendQueue) Queue_Destroy(SendQueue);
                CLOSEHANDLE(hpSend);
                return FALSE;           /* Caller will close hPipe */
        }


        /* Collect names from client and enqueue each one */
        for (; ; )
        {       SSNEWREQ Request;       /* message from client */
                DWORD    ActSize;       /* bytes read from (main) pipe */

                if (ReadFile(hPipe, &Request, sizeof(Request), &ActSize, NULL)){
                        if (Request.lVersion>SS_VERSION) {
                                dprintf1(("Bad version %d in file list request on pipe %x\n"
                                , Request.lVersion, hPipe));

                                break;

                        }
                        if (Request.lRequest!=LREQUEST) {
                                dprintf1(("Bad LREQUEST from pipe %x\n", hPipe));

                                break;
                        }
                        if (Request.lCode == -SSREQ_ENDFILES) {
                                dprintf1(("End of client's files list on pipe %x\n", hPipe));

                                /* This is the clean way to end */
                                Queue_Destroy(PackQueue);
                                if (!Started) {
                                        /* OK - so the clever clogs requested zero files */
                                        Queue_Destroy(ReadQueue);
                                        Queue_Destroy(SendQueue);
                                        /* Send a No More Files response */
#ifdef SOCKETS
                                        {
                                            SSNEWRESP resp;

                                            resp.lVersion = SS_VERSION;
                                            resp.lResponse = LRESPONSE;
                                            resp.lCode = SSRESP_END;
                                            resp.ulSize = 0;
                                            resp.ulSum = 0;
                                            resp.ft_lastwrite.dwLowDateTime = 0;
                                            resp.ft_lastwrite.dwHighDateTime = 0;

                                            send(hpSend, (PSTR) &resp, sizeof(resp), 0);
                                        }
#else
                                        ss_sendnewresp( hpSend, SS_VERSION, SSRESP_END
                                                , 0,0, 0,0, NULL);
#endif /* SOCKETS */
                                        CLOSEHANDLE(hpSend);
                                }
                                return TRUE;
                        }
                        if (Request.lCode != -SSREQ_NEXTFILE) {

                                dprintf1(( "Bad code (%d) in files list from pipe %x\n"
                                      , Request.lCode, hPipe));

                                break;
                        }
                }
                else {  DWORD errorcode = GetLastError();
                        switch(errorcode) {

                                case ERROR_NO_DATA:
                                case ERROR_BROKEN_PIPE:
                                        /* pipe connection lost - forget it */
                                        dprintf1(("main pipe %x broken on read\n", hPipe));
                                        break;
                                default:
                                        dprintf1(("read error %d on main pipe %x\n", errorcode, hPipe));
                                        break;
                        }
                        break;
                }
                if (!EnqueueName( PackQueue, Request.szPath
                                , (UINT)((LPBYTE)(&Request) + ActSize - (LPBYTE)(&Request.szPath))
                                )
                   ){
                        break;
                }
                Started = TRUE;
        } /* loop */

        /* only exit this way on error */
        /* Close the queues down.  Allow what's in them to run through */
        Queue_Destroy(PackQueue);
        if (!Started) {
                Queue_Destroy(ReadQueue);
                Queue_Destroy(SendQueue);

        }
        return FALSE;
} /* ss_sendfiles */
示例#8
0
int createServer(Nest *nest, int dimension)
{
	int listen_fd, conn_fd;
	struct sockaddr_in cli_addr;
	int cli_len;
	char *recvline, str[INET_ADDRSTRLEN];
	int dev_tag = -1, n;
	int ret; 

	listen_fd = SocketListen(PORT);
	if(listen_fd == -1)
	{
		fprintf(stderr, "SocketListen create failed\n");
		return -1;
	}
	

	for(;;)
	{
		printf("\n\n\nServer is listening ... \n\n\n\n\n");
		fprintf(stderr, "\n\n\nServer is listening ... \n\n\n\n\n");

		cli_len = sizeof(cli_addr);
		conn_fd = Accept(listen_fd, (struct sockaddr *)&cli_addr, &cli_len);

		inet_ntop(AF_INET, &cli_addr.sin_addr, str, sizeof(str));
		
	
		while(1)
		{
#ifdef 	_DEBUG
			printf("\n\n\nsocket from %s at PORT %d is connecting... \n", str, ntohs(cli_addr.sin_port));
#endif
			recvline = (char *)malloc(sizeof(int));
			memset(recvline, '\0', sizeof(int));		
			n = Readn(conn_fd, recvline, sizeof(int));
			dev_tag = *(int *)recvline;
#ifdef _DEBUG
			printf("createServer | dev_tag: %d\n", dev_tag);
#endif
			switch(dev_tag)
			{
				case DEV_PC:
				case DEV_PHONE:
					ret = reponseWithDevice(nest, dimension, conn_fd, dev_tag);
					if(ret == -1)
					{
						fprintf(stderr, "reponseWithDevice failed\n");
						close(conn_fd);
					}
					else if(ret == -2)
					{
						fprintf(stderr, "reponseWithDevice ask to close the socket\n");
						close(conn_fd);
					}
					fflush(stdout);
#ifdef _DEBUG
					if(ret == 0)
					{ 
						printf("createServer | reponseWithDevice success\n");
						fprintf(stderr, "createServer | reponseWithDevice success\n");
					}
#endif
					break;

				case DEV_CLOSE:
					close(conn_fd); 
					break;				
				default:
					close(conn_fd);
					printf("dev_tag  default \n");
			}
			if(  ((dev_tag != DEV_PC) && (dev_tag != DEV_PHONE)) || (ret == -1) || (ret == -2) )
			{
				printf("close current socket\n");
				break;
			}
		}
	}
	
	free(recvline);
	return 0;
}