static retval_t tcp_server_open(
        const channel_t * const link)
{
    int fd, ret;
    const tcp_channel_config_t * const l_config = (const tcp_channel_config_t * const) link->config;
    struct sockaddr_in addr;
    struct hostent *he;

    he = gethostbyname(l_config->address);
    if (NULL == he) return RV_ERROR;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == fd) return RV_ERROR;

    ret = 1;
    ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&ret, sizeof(ret));
    (void)(ret == 0);	/* we just keep going if this fails, what can we do? */

    memset(&addr, 0, sizeof addr);
    addr.sin_family = he->h_addrtype;
    addr.sin_port   = htons(l_config->port);
    memcpy(&addr.sin_addr, he->h_addr_list[0], he->h_length);

    ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    if (-1 == ret) {
    	close(fd);
    	return RV_ERROR;
    }

    return wait_connection(link, fd, CONNECT_TIMEOUT_SEC);
}
static retval_t unix_socket_server_open(
        const channel_t * const link)
{
    int fd, ret;
    const unix_socket_channel_config_t * const l_config =
        (const unix_socket_channel_config_t * const) link->config;
    struct sockaddr_un addr;

    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (-1 == fd) return RV_ERROR;

    memset(&addr, 0, sizeof addr);
    addr.sun_family = AF_UNIX;
    memcpy(&addr.sun_path, l_config->name, sizeof(addr.sun_path));

    (void)unlink(l_config->name);
    log_report_fmt(LOG_SOCKET, "Connect to unix socket %s\n", l_config->name);

    ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    if (-1 == ret) {
    	close(fd);
    	return RV_ERROR;
    }

    return wait_connection(link, fd, CONNECT_TIMEOUT_SEC);
}
Exemple #3
0
int server_create(prelude_client_profile_t *cp, const char *addr, unsigned int port,
                  prelude_bool_t keepalive, const char *pass, gnutls_x509_privkey_t key, gnutls_x509_crt_t cacrt, gnutls_x509_crt_t crt)
{
        int sock;
        size_t size;
        struct pollfd pfd[128];
        gnutls_dh_params_t dh_params;

#ifdef GNUTLS_SRP_ENABLED
        int ret;

        ret = gnutls_srp_allocate_server_credentials(&srpcred);
        if ( ret < 0 ) {
                fprintf(stderr, "error creating SRP credentials: %s.\n", gnutls_strerror(ret));
                return -1;
        }

        gnutls_srp_set_server_credentials_function(srpcred, srp_callback);
#endif

        one_shot_passwd = pass;
        gnutls_anon_allocate_server_credentials(&anoncred);

        fprintf(stderr, "Generating %d bits Diffie-Hellman key for anonymous authentication...", ANON_DH_BITS);
        gnutls_dh_params_init(&dh_params);
        gnutls_dh_params_generate2(dh_params, ANON_DH_BITS);
        gnutls_anon_set_server_dh_params(anoncred, dh_params);
        fprintf(stderr, "\n");

        size = sizeof(pfd) / sizeof(*pfd);
        sock = setup_server(addr, port, pfd, &size);
        if ( sock < 0 )
                return -1;

        wait_connection(cp, sock, pfd, size, keepalive, key, cacrt, crt);

#ifdef GNUTLS_SRP_ENABLED
        gnutls_srp_free_server_credentials(srpcred);
#endif

        gnutls_anon_free_server_credentials(anoncred);

        return 0;
}
static retval_t _read_or_recv(
        const channel_t * const link,
        frame_t * const recv_frame,
        const size_t count,
        read_t *_read)
{
    fd_channel_state_t *l_state = (fd_channel_state_t *)link->state;

	retval_t rv;
	void *buf;
	ssize_t actual_count;

    if (l_state->fd == NO_INCOMING_CONNETION_YET) {
    	 rv = wait_connection(link, USE_MASTER_FD_FROM_STATE, 0);
    	 if (rv != RV_SUCCESS) return rv;
    }

    if (0 == count) return RV_SUCCESS;

    rv = frame_get_data_pointer(recv_frame, &buf, count);
    if (rv != RV_SUCCESS) return rv;

    /* when running under FreeRTOS POSIX simulator, read(3) might be interrupted by a signal,
       returning -1 and errno == EINTR. We want this recv() function to be blocking, thus this loop here */
    while (1) {
    	actual_count = _read(l_state->fd, buf, count, 0);
        if (actual_count == -1 && EINTR == errno) {
            vTaskDelay(EINTR_DELAY);
        } else {
        	break;
        }
    };

    if (-1 == actual_count) {
    	if (EPIPE == errno) l_state->common.is_open = false;
    	return RV_ERROR;
    }

    frame_advance(recv_frame, actual_count);
    if (actual_count < count) return RV_PARTIAL;
    return RV_SUCCESS;
}
Exemple #5
0
/*
 * Simple httpd server for use in PicoBSD or other embedded application. 
 * Should satisfy simple httpd needs.  For more demanding situations
 * apache is probably a better (but much larger) choice.
 */
int
main(int argc, char *argv[])
{
        int ch, ld;
	int             httpd_group = 65534;
        pid_t server_pid;
  
	/* Default for html directory */
	strcpy (homedir,getenv("HOME"));
        if (!geteuid()) strcpy (homedir,"/httphome");
           else         strcat (homedir,"/httphome");

	/* Defaults for log file */
	if (geteuid()) {
	    strcpy(logfile,getenv("HOME"));
	    strcat(logfile,"/");
	    strcat(logfile,"jhttp.log");
	} else 
	  strcpy(logfile,"/var/log/jhttpd.log");

	/* Parse command line arguments */
	while ((ch = getopt(argc, argv, "d:f:g:l:p:vDh")) != -1)
	  switch (ch) {
	  case 'd':
	    strcpy(homedir,optarg);
	    break;	  
	  case 'f':
	    daemonize = 0;
	    verbose = 1;
	    fetch_mode = optarg;
	    break;
	  case 'g':
	    httpd_group = atoi(optarg);
	    break;
	  case 'l':
	    strcpy(logfile,optarg);
	    break;
	  case 'p':
	    http_port = atoi(optarg);
	    break;
	  case 'v':
	    verbose = 1;
	    break;
	  case 'D':
	    daemonize = 0;
	    break;
	  case '?':
	  case 'h':
	  default:
	    printf("usage: simple_httpd [[-d directory][-g grpid][-l logfile][-p port][-vD]]\n");
	    exit(1);
	    /* NOTREACHED */
	  }                           

	/* Not running as root and no port supplied, assume 1080 */
        if ((http_port == 80) && geteuid()) {
	  http_port = 1080;
	}

	/* Do we really have rights in the html directory? */
	if (fetch_mode == NULL) {
	  if (chdir(homedir)) {
	    perror("chdir");
	    puts(homedir);
	    exit(1);
	  }
	}

	/* Create log file if it doesn't exit */
	if ((access(logfile,W_OK)) && daemonize) { 
	  ld = open (logfile,O_WRONLY);         
	  chmod (logfile,00600);
	  close(ld);
	}

        init_servconnection();                  

        if (verbose) {
	  printf("Server started with options \n"); 
	  printf("port: %d\n",http_port);
	  if (fetch_mode == NULL) printf("html home: %s\n",homedir);
	  if (daemonize) printf("logfile: %s\n",logfile);
	}

	/* httpd is spawned */
        if (daemonize) {
	  if ((server_pid = fork()) != 0) {
	    wait3(0,WNOHANG,0);
	    if (verbose) printf("pid: %d\n",server_pid);
	    exit(0);
	  }
	  wait3(0,WNOHANG,0);
	}

	if (fetch_mode == NULL) setpgrp(0,httpd_group);

	/* How many connections do you want? 
	 * Keep this lower than the available number of processes
	 */
        if (listen(http_sock,15) < 0) exit(1);

        label:	
	wait_connection();
    
	if (fork()) {
	  wait3(0,WNOHANG,0);
	  close(con_sock);
	  goto label;
	}

	http_request();

	wait3(0,WNOHANG,0);
	exit(0);
}
static port_addr open_serial(const char *dev)
{
    // Decide on the type of the file
#ifdef UNIX_SOCKETS
    struct stat stat_buf;
    int stat_ret = stat(dev, &stat_buf);

    int is_socket = 0;

    if((stat_ret == -1) && (errno == ENOENT))
        is_socket = 1;
    else if((stat_ret == 0) && S_ISSOCK(stat_buf.st_mode))
        is_socket = 1;

    if(is_socket)
    {
        // Open a unix domain socket
        unlink(dev);
        int fd = socket(AF_UNIX, SOCK_STREAM, 0);
        if(fd == -1)
        {
            fprintf(stderr, "Error creating unix domain socket, errno = %i\n",
                    errno);
            return -1;
        }

        // Prepare the address structure
        struct sockaddr_un *address;
        address = (struct sockaddr_un *)malloc(sizeof(struct sockaddr_un));
        sock_addr = (struct sockaddr *)address;

        memset(address, 0, sizeof(struct sockaddr_un));
        address->sun_family = AF_UNIX;
        strncpy(address->sun_path, dev, sizeof(address->sun_path));

        addrlen = sizeof(struct sockaddr_un);

         // Bind to the socket
        int bind_ret = bind(fd, sock_addr, sizeof(struct sockaddr_un));
        if(bind_ret == -1)
        {
            fprintf(stderr, "Error binding to unix domain socket, errno = %i\n",
                    errno);
            return -1;
        }

        // Wait for a new connection
        return wait_connection(fd);
    }
    else
#endif
    {
#ifdef _WIN32
        port_addr fd = CreateFile(dev, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL);
        if(fd == INVALID_HANDLE_VALUE)
        {
            fprintf(stderr, "Error opening %s, error: %08x\n", dev, GetLastError());
            return fd;
        }

        DCB config;
        if(GetCommState(fd, &config) == 0)
        {
            fprintf(stderr, "Error calling GetCommState, error %08x\n", GetLastError());
            return INVALID_HANDLE_VALUE;
        }

        // Set the port settings
        config.BaudRate = 115200;
        config.ByteSize = 8;
        config.Parity = NOPARITY;
        config.StopBits = ONESTOPBIT;

        if(SetCommState(fd, &config) == 0)
        {
            fprintf(stderr, "Error calling SetCommState, error %08x\n", GetLastError());
            return INVALID_HANDLE_VALUE;
        }

        // Set the timeouts
        COMMTIMEOUTS timeouts;
        timeouts.ReadIntervalTimeout = 1;
        timeouts.ReadTotalTimeoutMultiplier = 1;
        timeouts.ReadTotalTimeoutConstant = 1;
        timeouts.WriteTotalTimeoutMultiplier = 1;
        timeouts.WriteTotalTimeoutConstant = 1;
        if(SetCommTimeouts(fd, &timeouts) == 0)
        {
            fprintf(stderr, "Error calling SetCommTimeouts, error %08x\n",
                    GetLastError());
            return INVALID_HANDLE_VALUE;
        }

        return fd;
#else
        // The termios structure, to be configured for serial interface
        struct termios termios;

        // Open the device, read only
        int fd = open(dev, O_RDWR | O_NOCTTY);
        if(fd == -1)
        {
            // failed to open
            return -1;
        }

        // Must be a tty to continue set-up, otherwise assume pipe
        if(!isatty(fd))
            return fd;

        // Get the attributes
        if(tcgetattr(fd, &termios) == -1)
        {
            fprintf(stderr, "Failed to get attributes of device %s\n", dev);
            return -1;
        }

        // Poll only
        termios.c_cc[VTIME] = 0;
        termios.c_cc[VMIN] = 0;

        // 8N1 mode
        termios.c_iflag = 0;
        termios.c_oflag = 0;
        termios.c_cflag = CS8 | CREAD | CLOCAL;
        termios.c_lflag = 0;

        // Set 115200 baud
        if((cfsetispeed(&termios, B115200) < 0) ||
        (cfsetospeed(&termios, B115200) < 0))
        {
            fprintf(stderr, "Failed to set baud rate\n");
            return -1;
        }

        // Write the attributes
        if(tcsetattr(fd, TCSAFLUSH, &termios) == -1)
        {
            fprintf(stderr, "Failed to write attributes\n");
            return -1;
        }

        return fd;
#endif
    }
}
void server_generic_start(server_generic_t **server, size_t nserver)
{
        wait_connection(server, nserver);
}
Exemple #8
0
int
main (int argc, char **argv)
{
  gpg_error_t err;
  struct sock_ctx_s fd;
  gsti_ctx_t ctx;

  if (argc)
    {
      argc--;
      argv++;
    }

  /* Initialize our local context object. */
  memset (&fd, 0, sizeof fd);

  /* Make sure we get secure memory. */
  gsti_control (GSTI_SECMEM_INIT);

  /* Initialize a GSTI context. */
  err = gsti_init (&ctx);
  log_rc (err, "init");

  /* This context should be logged at debug level. */
  gsti_set_log_level (ctx, GSTI_LOG_DEBUG);

  /* Register our host key. */
  err = gsti_set_hostkey (ctx, SECKEY);
  log_rc (err, "set_hostkey");

  /* Register our read/write functions. */
  gsti_set_packet_handler_cb (ctx, mypkt_handler, 0);
  gsti_set_writefnc (ctx, mywrite, &fd);

  /* Register our auth callback function */
  gsti_set_auth_callback (ctx, my_auth_cb, NULL);

  /* Set simple banner message */
  gsti_set_auth_banner (ctx, "Eddie lives somewhere in time...", 0);

#if 0
  err = gsti_set_service (ctx, "[email protected],[email protected]");
  log_err (err, "set-service");
#endif

  /* Wait for a client to connect. */
  wait_connection (&fd.listen_fd, &fd.conn_fd);

  /* Fire up the engine.  */
  err = gsti_start (ctx);
  log_rc (err, "start");

  /* Process incoming data.  */
  err = reader_loop (&fd, ctx);
  log_rc (err, "reader_loop");

  /* Release the context. */
  gsti_deinit (ctx);

  /* And the secure memory. */
  gsti_control (GSTI_SECMEM_RELEASE);

  return 0;
}
Exemple #9
0
int main(int argc, char *argv[])
{
    SOCKET sockfd = create_socket();

    if (sockfd != INVALID_SOCKET)
    {
        if (bind_socket(&sockfd, PORT_NO, 10))
        {
            SOCKET sockets[MAX_SOCKETS] = {INVALID_SOCKET};
            int opened_sockets = 0;

            while (1)
            {
                int idx, max;
				
                if (opened_sockets < MAX_SOCKETS)
                {
                    SOCKET new_sockfd = wait_connection(&sockfd);

                    if (new_sockfd != INVALID_SOCKET)
                    {
                        sockets[opened_sockets++] = new_sockfd;
                    }
                    else if (WSAGetLastError() != WSAETIMEDOUT)
                    {
                        //printf("ERROR waiting\n");
                    }
                }

                for (idx = 0, max = opened_sockets; idx < max; idx++)
                {
                    if (sockets[idx] != INVALID_SOCKET)
                    {
                        if (do_processing(&sockets[idx]) < 0)
                        {
							printf("Disconnecting...\n");
							disconnect_socket(&sockets[idx]);
							sockets[idx] = sockets[opened_sockets-1];
							sockets[opened_sockets-1] = INVALID_SOCKET;
							opened_sockets--;
                        }
                    }
                }
            }
        }
        else
        {
            perror("ERROR binding");
        }

        disconnect_socket(&sockfd);
    }
    else
    {
        perror("ERROR opening socket");
    }

    destroy_socket(&sockfd);

    return 0;
}
Exemple #10
0
int main(int argc, char ** argv) {
  int ec_fifo, ce_fifo, es_fifo, se_fifo;
  FILE* fp;
  ssize_t msg_size;
  uint8_t *buff;
  char client_nm[NM_LENGTH], client_nm_tmp[NM_LENGTH];
  uint8_t rsa_tmp[RSA_LENGTH], rsa_tmp2[RSA_LENGTH];
  BIGNUM /**bn_n, *bn_d,*/ *bn_client_e, *bn_client_n, *bn_r;
  char client_cipher_suite;
  uint8_t sym_id, hash_id, public_id;
  uint8_t k[K_SIZE] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
  int i, done;
  int k_len, c_hex_len, c_len;
  uint8_t g[HASH_LENGTH], g1[HASH_LENGTH];
  uint8_t c[MSG_SIZE_MAX];
  unsigned int tmp;

  assert(K_SIZE == 8);

  bn_client_e = BN_new();
  bn_client_n = BN_new();
  bn_r = BN_new();


  /* Mandatory arguments */
  if (!argv[1] || !argv[2] || !argv[3] || !argv[4] ||
      !argv[1] || !argv[2] || !argv[3] || !argv[4]) {
    fprintf(stderr, "%s [server->eve fifo] [eve->server fifo] [eve->client fifo] [client->eve fifo]\n", argv[0]);
    exit(1);
  }

  se_fifo = open_channel(argv[1]);
  es_fifo = open_channel(argv[2]);
  ec_fifo = open_fifo(argv[3]);
  ce_fifo = open_fifo(argv[4]);

  /* wait real client to connect */
  fprintf(stderr,"(E) Waiting connection...\n");
  if (wait_connection(ce_fifo) < 0) {
    fprintf(stderr,"(E) Communication error...\n");
    goto next;
  }
  /* connect to server */
  write_msg(es_fifo, (const u_int8_t *)CONNECTION_STRING, strlen(CONNECTION_STRING));

  forward_string(se_fifo, ec_fifo, OK_STRING);

  /* Server authentication */
  /* client challange */
  forward_msg(ce_fifo, es_fifo);
  /* server response to challange */
  forward_msg(se_fifo, ec_fifo);

  /* Client authentication */
  /* Client name */
  msg_size = forward_msg_read(ce_fifo, es_fifo, &buff);

  /*  vvvv  copy-paste from server  vvvv  */
  buff[msg_size] = '\0';
  strncpy((char *)client_nm, (const char *) buff, NM_LENGTH);
  /* EXTRACT from (names[],c_puk[],n[]) the pair (c_puk[i],n[i]) where names[i] = nm */
  if ((fp = fopen("server_folder/clients_rsa64_public_keys.txt", "r")) == NULL) {
    fprintf(stderr, "Error while getting clients RSA public keys...\n");
    goto next;
  }
  done = 0;
  while (!feof(fp)) {
    fscanf(fp, "%129s %129s %129s", client_nm_tmp, rsa_tmp, rsa_tmp2);
    if (strcmp(client_nm_tmp, client_nm) == 0) {
      done = 1;
      break;
    }
  }
  if (done == 0) {
    fprintf(stderr, "Error: unrecognized client\n");
    goto next;
  }
  fclose(fp);

  BN_hex2bn(&bn_client_n, (const char *) rsa_tmp);
  BN_hex2bn(&bn_client_e, (const char *) rsa_tmp2);

  /*  ^^^^  copy-paste from server  ^^^^  */
  /* now I know client name and pub key */

  /* server challange */
  forward_msg(se_fifo, ec_fifo);
  /* client response */
  forward_msg(ce_fifo, es_fifo);


  /* Negotiation of the cipher suite */
  /* cipher suite c -> s */
  forward_msg_read(ce_fifo, es_fifo, &buff);

  /*  vvvv  copy-paste from server  vvvv  */
  client_cipher_suite = buff[0];
  cipher_suite_table(client_cipher_suite, &sym_id, &hash_id, &public_id);
  /*  ^^^^  copy-paste from server  ^^^^  */


  /* Negotiation of the private key */
  /* k already set as an arbitrary key */

  /*  vvvv  copy-paste from server  vvvv  */

  if (sym_id == 1) {
    k_len = 3;
  }
  else {
    k_len = K_SIZE;
  }
  BN_bin2bn(k, k_len, bn_r);

  /* If we're using RSA512 read the correct key (we have the 64bit one) */
  if (public_id == 6) {
    if ((fp = fopen("server_folder/clients_rsa512_public_keys.txt", "r")) == NULL) {
      fprintf(stderr, "Error while getting clients RSA public keys...\n");
      goto next;
    }
    done = 0;
    while (!feof(fp)) {
      fscanf(fp, "%129s %129s %129s", client_nm_tmp, rsa_tmp, rsa_tmp2);
      if (strcmp(client_nm_tmp, client_nm) == 0) {
        done = 1;
        break;
      }
    }
    if (done == 0) {
      fprintf(stderr, "Error: unrecognized client\n");
      goto next;
    }
    fclose(fp);

    BN_hex2bn(&bn_client_n, (const char *) rsa_tmp);
    BN_hex2bn(&bn_client_e, (const char *) rsa_tmp2);
  }

  /* ENCRYPT key */
  rsa_encrypt(bn_r, bn_client_e, bn_client_n);

  /* WRITE encrypted k to C */
  buff = (uint8_t *) BN_bn2hex(bn_r);
  if ((write_msg(ec_fifo, buff, strlen((char *) buff))) < 0) {
    fprintf(stderr, "Error while sending C to the client...\n");
    goto next;
  }
  OPENSSL_free(buff);

  /* Encrypted communication */
  if ((msg_size = read_msg(ce_fifo,&buff)) < 0) {
    fprintf(stderr, "Error while reading message from the client...\n");
    goto next;
  }

  c_hex_len = msg_size - HASH_LENGTH * 2;
  if (c_hex_len <= 0) {
    fprintf(stderr, "Error, malformed message...\n");
    goto next;
  }

  c_len = c_hex_len / 2;
  for (i=0; i<msg_size; i+=2) {
    if (i < c_hex_len) {
      sscanf((char *) (buff+i), "%02x", &tmp);
      c[i/2] = (uint8_t) tmp;
    }
    else {
      sscanf((char *) (buff+i), "%02x", &tmp);
      g[(i - c_hex_len) / 2] = (uint8_t) tmp;
    }
  }

  /* Decrypt C */
  decrypt(sym_id, c, c_len, k);

  /* COMPUTE G' = H(M) */
  sponge_hash(c, c_len, g1);

  c[c_len] = '\0';

  /* CHECK G' = G */
  done = 1;
  for (i=0; i<HASH_LENGTH; i++) {
    if (g[i] != g1[i]) {
      done = 0;
    }
  }

  /* If the check fails print error message */
  if (done == 0) {
    if ((write_msg(ec_fifo, (uint8_t *) CORRUPTED_STRING, strlen(CORRUPTED_STRING))) < 0) {
      fprintf(stderr, "Error while writing to the client...\n");
      goto next;
    }
  }

  /* PUT M' on a file */
  if ((fp = fopen("eve_folder/received_messages.txt", "a+")) == NULL) {
    fprintf(stderr, "Error while saving message...\n");
    fclose(fp);
    goto next;
  }
  fprintf(fp, "%s", c);
  fflush(stdout);
  fprintf(stdout, "MESSAGGIO SEGRETO >>>%s<<< FINE MESSAGGIO SEGRETO\n", c);
  fflush(stdout);
  fclose(fp);

  /* WRITE ok message to C */
  if ((write_msg(ec_fifo, (uint8_t *) DECRYPTED_STRING, strlen(DECRYPTED_STRING))) < 0) {
    fprintf(stderr, "Error while writing C to the client...\n");
    goto next;
  }

  /*  ^^^^  copy-paste from server  ^^^^  */



 next:

  /*close_channels ...!*/

  BN_free(bn_client_n);
  BN_free(bn_client_e);
  BN_free(bn_r);

  exit(0);
}
Exemple #11
0
int main(int argc, char *argv[])
{
	WSADATA wsaData;
	  // Initialize Winsock
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
    SOCKET sockfd = create_socket();

    if (sockfd != INVALID_SOCKET)
    {
        if (bind_socket(&sockfd, PORT_NO, 10))
        {
            SOCKET sockets[MAX_SOCKETS] = {INVALID_SOCKET};
            int opened_sockets = 0;

            while (1)
            {
                int idx, max;
                if (opened_sockets < MAX_SOCKETS)
                {
                    SOCKET new_sockfd = wait_connection(&sockfd);

                    if (new_sockfd != INVALID_SOCKET)
                    {
                        sockets[opened_sockets++] = new_sockfd;
                    }
                    //else if (errno != WSAETIMEDOUT)
                    {
                        //puts("ERROR waiting");
                    }
                }

                for (idx = 0, max = opened_sockets; idx < max; idx++)
                {
                    if (sockets[idx] != INVALID_SOCKET)
                    {
                        if (do_processing(&sockets[idx])==-1)
                        {
                            if (errno != WSAETIMEDOUT)
                            {
                                printf("Disconnecting...\n");
                                disconnect_socket(&sockets[idx]);
                                sockets[idx] = sockets[opened_sockets-1];
                                sockets[opened_sockets-1] = INVALID_SOCKET;
                                opened_sockets--;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            printf("ERROR binding\n");
        }

        disconnect_socket(&sockfd);
    }
    else
    {
        printf("ERROR opening socket\n");
    }

    destroy_socket(&sockfd);

    return 0;
}
Exemple #12
0
int main(int argc, char *argv[])
{
    SOCKET sock = create_socket(), sockets[MAX_CLIENT] = {INVALID_SOCKET};
	int num_clients = 0;
	
	//cria e conecta o socket
	if(sock != INVALID_SOCKET)
    {
        if(bind_socket(&sock, PORT_NO) == SOCKET_ERROR)
		{
			printf("ERROR binding\n");
			exit(1);
		}
            
		else
		{
			listen(sock, MAX_CLIENT);
			printf("Servidor iniciado.\n");
		}
    }
    else
	{
		printf("ERROR opening socket");
		exit(1);
	}
	
	//aceita conexões
	
	puts("Esperando por conexoes...");
	
	while (1)
	{
		int i, max;
		if (num_clients < MAX_CLIENT)
		{
			SOCKET new_sockfd = wait_connection(&sock);

			if(new_sockfd != INVALID_SOCKET)
			{
				sockets[num_clients++] = new_sockfd;
			}
			else if (WSAGetLastError() != WSAETIMEDOUT)
			{
				printf("ERROR waiting\n");
			}
		}

		for (i = 0, max = num_clients; i < max; i++)
		{
			if (sockets[i] != INVALID_SOCKET)
			{
				if (!do_processing(&sockets[i]))
				{
					if (WSAGetLastError() != WSAETIMEDOUT)
					{
						printf("Disconnecting...\n");
						disconnect_socket(&sockets[i]);
						sockets[i] = sockets[num_clients-1];
						sockets[num_clients-1] = INVALID_SOCKET;
						num_clients--;
					}
				}
			}
		}
	}
	
	disconnect_socket(&sock);
    destroy_socket(&sock);

    return 0;
}