Esempio n. 1
0
/* s is the file descriptor of a client that has
 * pending data. Turn it back into a struct client
 * using the lookup table.
 * Read data up to 256 characters from the socket.
 * Returns the status of the client, true for alive
 * or false for dead.
 */
int client_handle(int s)
{
	client *c;
	char buf[256];
	int r;

	c = clients[s];
	
	/* Read up to 256 bytes from the client */
	r = socket_read(s, buf, 256);
	if(r == 0)
	{
		/* 0 bytes read means the client has disconnected */
		client_destroy(s);
		return 0;
	}

	/* Returns whether the buffer has something useful in it */
	r = buffer_add(c->buffer, buf, r); 
	if(r)
	{
	//	printf("Client %d said '%s'\n", s, buffer_get(c->buffer));
		parse(s, c);

	}
	return 1;
}
Esempio n. 2
0
int socket_main(int hsocket)
{
        struct sockaddr_in sock;
        int asocket;            /* Active socket */
        socklen_t sock_len;
        char buffer[200];
        int got;

        sock_len = sizeof(struct sockaddr_in);
        asocket = accept( hsocket, (struct sockaddr *)&sock, &sock_len );
        if (asocket == -1) {
                return -1;
        }
        socket_write( asocket, "Hi there\n", 9 );
        while (1) {
                while (socket_poll(asocket)==0) {}
                if ((got=socket_read(asocket, buffer, 200))>0) {
                        socket_write( asocket, buffer, got );
                }
                else
                        break;
        }
        close(asocket);
        return 0;
}
Esempio n. 3
0
size_t nw_readline( nw_socket fd, void *buf, size_t maxlen )
{
	size_t n, rc;
	char   ch;

	for (n = 1; n < maxlen; n++)
	{
		rc = socket_read( fd, &ch, 1 );
		if (rc == 1)
		{
			*((char *) buf)++ = ch;
			if (ch == '\n')
				break;
		}
		else if (rc == 0)
		{
			if (n == 1)
				return 0;							/* EOF, no data read   */
			else
				break;								/* EOF, some data read */
		}
		else
			return -1;								/* error               */
	}

	*((char *) buf) = '\0';
	return n;
}
Esempio n. 4
0
static int read_initial_request_line(struct socket_t *socket_p,
                                     char *buf_p,
                                     struct http_server_request_t *request_p)
{
    char *action_p = NULL;
    char *path_p = NULL;
    char *proto_p = NULL;

    *buf_p++ = '\0';
    action_p = buf_p;

    while (1) {
        if (socket_read(socket_p,
                        buf_p,
                        sizeof(*buf_p)) != sizeof(*buf_p)) {
            return (-EIO);
        }

        buf_p++;

        /* The line ending is "\r\n". */
        if ((buf_p[-2] == '\r') && (buf_p[-1] == '\n')) {
            buf_p[-2] = '\0';
            break;
        }

        /* Action and path has ' ' as terminator. */
        if (buf_p[-1] == ' ') {
            buf_p[-1] = '\0';

            if (path_p == NULL) {
                path_p = buf_p;
            } else if (proto_p == NULL) {
                proto_p = buf_p;
            }
        }
    }

    /* A path is required. */
    if (path_p == NULL) {
        return (-1);
    }

    log_object_print(NULL,
                     LOG_DEBUG,
                     FSTR("%s %s %s\r\n"), action_p, path_p, proto_p);

    /* Save the action and path in the request struct. */
    strcpy(request_p->path, path_p);

    if (strcmp(action_p, "GET") == 0) {
        request_p->action = http_server_request_action_get_t;
    } else if (strcmp(action_p, "POST") == 0) {
        request_p->action = http_server_request_action_post_t;
    } else {
        return (-1);
    }

    return (0);
}
static int client_socket_receive( comm_channel_t *channel, char *buf, int len )
{
    tcp_connection_t *tc = tcp_get_connection( channel );
    int res;

    if( !tc )
    {
        return( -1 );
    }

    if( !tc->connected )
    {
        res = client_socket_connect( tc );
    }

    if( tc->connected )
    {
        res = socket_read( tc->fd, buf, len );

        if( res == -1 )
        {
            close_connection( tc );
        }
    }

    return( res );
}
Esempio n. 6
0
void *DoWork(void *test)
{
   int new_socket = *((int *) test);
   unsigned char buffer[1024];
   int len = 0;
   logger(LOG_SOCKET, NORMAL, "coming off accept\n");
   printf("Sending dat at socket %d\n", new_socket);
   const char *data = "Hello World";
   socket_send(new_socket, (const unsigned char *) data, 12);
   printf("waiting on socket read\n");
#if 0
   socket_read(new_socket, buffer, 10);
   printf("received from socket %s\n", buffer);
#endif
   len = 0;
   while(len < 22) {
      len += socket_read_nonblock(new_socket, buffer);
      if(len < 0) {
         printf("socket closed\n");
         break;
      }
      if(len==0) {
         printf("nothing to show\n");
      }
      else {
         printf("received from socket %s length %d\n", buffer, len);
      }
   }
   //printf("received from socket %s\n", buffer);
   printf("closing socket\n");
   socket_close(new_socket);
   free(test);
   return NULL;
}
Esempio n. 7
0
bool NameResolution::getIPsFromName(ims::name::IPSet &ips, const std::string &name, ims::name::NameResolutionSourceType sourceType) {
	if (name.length() > 0xff) {
		// error...
		return false;
	}

	// prepare the command
	cmdLen = name.length() + 4;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 0; // function, getIPsFromName
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	buf[5] = (unsigned char) name.length();
	memcpy(buf + 6, name.c_str(), name.length());

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the # of ips
	if (socket_read(conn_fd, (char *) &cmdLen, sizeof(uint16_t), sockTimeout) != sizeof(uint16_t)) {
		// error
		return false;
	}
	cmdLen = ntohs(cmdLen);
	// FIXME fill a buffer instead of reading one at a time
	for (uint16_t i = 0; i < cmdLen; ++i) {
		if (socket_read(conn_fd, (char *) &ip, sizeof(uint32_t), sockTimeout) != sizeof(uint32_t)) {
			return false;
		}
		ips.insert(ntohl(ip));
	}
	return true;
}
Esempio n. 8
0
bool NameResolution::getNamesFromIP(ims::name::NameSet &names, const uint32_t &ip, ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 7;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 1; // function, getNamesFromIP
	this -> ip = htonl(ip);
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	memcpy(buf + 5, &(this -> ip), sizeof(uint32_t)); // arg (ip)

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the # of names
	if (socket_read(conn_fd, (char *) &cmdLen, sizeof(uint16_t), sockTimeout) != sizeof(uint16_t)) {
		// error
		return false;
	}
	cmdLen = ntohs(cmdLen);
	// FIXME fill a buffer instead of reading one at a time
	for (uint16_t i = 0; i < cmdLen; ++i) {
		if (socket_read(conn_fd, (char *) &nameLen, 1, sockTimeout) != 1) {
			return false;
		}
		if (socket_read(conn_fd, buf, nameLen, sockTimeout) != nameLen) {
			return false;
		}
		tmpName.assign(buf, nameLen);
		names.insert(tmpName);
	}
	return true;
}
Esempio n. 9
0
int32_t execute_segment_stat_handle(struct data_buffer* dbuf,int socket_fd,MEM_POOL* mem_pool)
{
	struct data_buffer rbuf;
	
	//发数据包
	if(socket_write(socket_fd,dbuf->data,dbuf->data_len) <= 0)
		return -1;

	//接受命名
	memset(&rbuf,0,sizeof(struct data_buffer));
	rbuf.data_len = sizeof(uint32_t);
	rbuf.size = rbuf.data_len;
	rbuf.data = (uint8_t *)mem_pool_malloc(mem_pool,sizeof(uint32_t));
	if(socket_read(socket_fd,rbuf.data,rbuf.data_len) <= 0)
		return -1;

	rbuf.data_len = read_int32(&rbuf);
	rbuf.data = (uint8_t *)mem_pool_malloc(mem_pool,rbuf.data_len);
	rbuf.rpos = 0;
	rbuf.size = rbuf.data_len;

	if(socket_read(socket_fd,rbuf.data,rbuf.data_len) <= 0)
		return -1;
	
	rbuf.rpos += MESSAGE_HEAD_LEN;
	uint16_t type = message_type(&rbuf);
	if (type != MT_DC_STAT_RS)
		return -1;

	uint16_t segment_count = read_int16(&rbuf);

	uint16_t i;
	fprintf(stderr,"%-20s%-20s%-20s%-20s%-20s%-20s%-20s\n","SEGMENT_ID","CREATE_TIME","MODIFY_TIME","CHECKPOINT_TIME","FLAG","ROW_COUNT","DEL_COUNT");
	for(i=0; i<segment_count; i++)
	{
		fprintf(stderr,"%-20u",read_int16(&rbuf));
		fprintf(stderr,"%-20llu",read_int64(&rbuf));
		fprintf(stderr,"%-20llu",read_int64(&rbuf));
		fprintf(stderr,"%-20llu",read_int64(&rbuf));
		fprintf(stderr,"%-20u",read_int8(&rbuf));
		fprintf(stderr,"%-20u",read_int32(&rbuf));
		fprintf(stderr,"%-20u\n",read_int32(&rbuf));
	}
	
	return 0;
}
Esempio n. 10
0
/*
 * Private function name:   vnc_send_pointer_event
 * Since version:           0.4.2
 * Description:             Function to send the mouse pointer event/click to VNC window
 * Arguments:               @server [string]: server string to specify VNC server
 *                          @port [string]: string version of port value to connect to
 *                          @pos_x [int]: position on x-axis of the VNC window
 *                          @pos_y [int]: position on y-axis of the VNC window
 *                          @clicked [int]: mask of what buttons were clicked
 *                          @release [boolean]: release the buttons once clicked
 * Returns:                 0 on success, -errno otherwise
 */
int vnc_send_pointer_event(char *server, char *port, int pos_x, int pos_y, int clicked, int release)
{
    int sfd;
    tServerFBParams params;

    DPRINTF("%s: Server is %s, port is %s, x is %d, y is %d, clicked is %d, release is %d\n", VNCFUNC,
            server, port, pos_x, pos_y, clicked, release);

    sfd = vnc_connect(server, port, 0);
    if (sfd < 0) {
        int err = errno;
        DPRINTF("%s: VNC Connection failed with error code %d (%s)\n", VNCFUNC, err, strerror(err));
        close(sfd);
        return -err;
    }

    params = vnc_read_server_init(sfd);

    if (((pos_x > params.width) || (pos_y < 0))
        || ((pos_y > params.height) || (pos_y < 0))) {
        DPRINTF("%s: Required positions out of range (width = %d, height = %d, x = %d, y = %d) for '%s'\n",
                VNCFUNC, params.width, params.height, pos_x, pos_y, params.desktopName);
        return -EINVAL;
    }

    socket_read(sfd, -1);
    vnc_set_pixel_format(sfd, params);
    vnc_set_encoding(sfd);
    socket_read(sfd, -1);
    usleep(50000);

    /* Following paragraph moves mouse pointer to [0, 0] (left upper corner) */
    vnc_send_client_pointer(sfd, 0, 0x7FFF, 0x7FFF);
    socket_read(sfd, -1);
    vnc_send_client_pointer(sfd, 0, 0, 0);
    socket_read(sfd, -1);

    vnc_send_client_pointer(sfd, clicked, (pos_x / 2), (params.height - pos_y) / 2);
    socket_read(sfd, -1);
    vnc_send_client_pointer(sfd, 0, (pos_x / 2), ((params.height - pos_y) / 2));
    socket_read(sfd, -1);

    if (release) {
        vnc_send_client_pointer(sfd, clicked, (pos_x / 2), (params.height - pos_y) / 2);
        socket_read(sfd, -1);
        vnc_send_client_pointer(sfd, 0, (pos_x / 2), (params.height - pos_y) / 2);
        socket_read(sfd, -1);
    }

    shutdown(sfd, SHUT_RDWR);
    close(sfd);

    DPRINTF("%s: Closed descriptor #%d\n", VNCFUNC, sfd);

    return 0;
}
Esempio n. 11
0
int socket_get( int asocket )
{
        char buffer[2];
        if (socket_read( asocket, buffer, 1)!=-1) {
                return buffer[0];
        }
        return -1;
}
Esempio n. 12
0
int main(void) {
	// initializing first three investors for program to start with
	// initializing_END

	int PORT = 5000;
	lib_init();
	winSock = socket_new();
    db_t * db = db_new("teacher.db");
	// Checking if socket is not busy, closing app if it is
	if (socket_bind(winSock, PORT) == SOCKET_ERROR) {
		printf("Cannot bind %i port\n", PORT);
		socket_close(winSock);
		socket_free(winSock);
		return 0;
	}

	socket_listen(winSock);
	char buf[10000];
	socket_t * client = NULL;
	// main cycle of the program
	while (1) {
		printf("Awaiting for connections...\n");
		client = socket_accept(winSock);

		// Checking if client is not null, closing app if he is
		if (client == NULL) {
			printf("NULL client, closing app...\n");
			break;
		}

		int readStatus = socket_read(client, buf, sizeof(buf));

		// Skipping empty request (may appear from time to time)
		if (readStatus <= 0) {
			printf("Empty request, skipping...\n");
			socket_close(client);
			socket_free(client);
			continue;
		}

		// Printing info about the received request to console
		printf(">> Got request (readStatus: %i):\n'%s'\n", readStatus, buf);
		http_request_t request = http_request_parse(buf);

		// check the type/path of request (API/HTML) & analyze the method (GET/POST/DELETE)
		// and provide the client with proper answer
		server_analyzeRequest(&request, client, db);

		socket_free(client);
	}

	// end of program
	socket_close(winSock);
	socket_free(winSock);
	db_free(db);
	lib_free();
	return 0;
}
Esempio n. 13
0
int hanclient_send_command_return_res(Client_Command *client_command)
{
	int sock,i;

	/* Attempt to connect to the han daemon */
  
	if(sockFilePath != NULL)
		sock = socket_connect(sockFilePath);
	else
		sock = socket_connect_ip(inetHost, inetService, PF_UNSPEC, SOCK_STREAM );

	if(sock == -1){
		debug(DEBUG_ACTION, "Could not open socket to host: %s", inetHost);
		return 1;
	}

	/* Set the socket file mode to non-blocking */

	if(fcntl(sock, F_SETFL, O_NONBLOCK) == -1){
		debug(DEBUG_ACTION, "Could not set socket to nonblocking");
		socket_close(sock);
		return 1;
	}

	/* Write the client command block */

	i = socket_write(sock,
		(void *) client_command,
		sizeof(Client_Command),
		USER_WRITE_TIMEOUT);	

	if(i == 0){
		debug(DEBUG_ACTION, "Socket time out error, writing client command");
		socket_close(sock);
		return 1;
	}
  

	debug(DEBUG_ACTION,"packet sent, waiting for response");

	/* Wait for, and read back the response */

	i = socket_read(sock,
		(void *) client_command,
		sizeof(Client_Command),
		USER_READ_TIMEOUT);

	if(i == 0){
		debug(DEBUG_ACTION,"Socket time out error, waiting for response");
		socket_close(sock);
		return 1;
	}
	/* Close the socket */

	socket_close(sock);

	return 0;
}
Esempio n. 14
0
static bool8 NPClientGetROMInfoFromServer (void)
{
	if (!npclient.online)
		return (false);

	NPNotification("Client: Receiving ROM information from server...", -1);

	if (NPClientGetMesFromServer() != kNPServerROMInfoWillSend)
	{
		NPError("Client: Failed to receive messsage from server.", 5201);
		return (false);
	}

	if (NPClientSendMesToServer(kNPClientROMInfoWaiting) == false)
	{
		NPError("Client: Failed to send messsage to server.", 5202);
		return (false);
	}

	uint8	mes[16];
	uint32	l;

	if (socket_read(npclient.socket, mes, 16) != 16)
	{
		NPError("Client: Failed to receive ROM information from server.", 5203);
		return (false);
	}

	nprominfo.crc32      = READ_LONG(mes + 0);
	nprominfo.input      = READ_LONG(mes + 4);

	l = READ_LONG(mes + 12);

	if (socket_read(npclient.socket, (uint8 *) nprominfo.fname, l) != (int) l)
	{
		NPError("Client: Failed to receive ROM name from server.", 5204);
		return (false);
	}

	nprominfo.fname[l] = 0;
	nprominfo.length   = l;

	NPNotification("Client: Received ROM information from server.", -1);
	return (true);
}
Esempio n. 15
0
size_t nw_readbyte( nw_socket fd,  nw_byte  *d )
{
    size_t rc;

    rc = socket_read( fd, d, 1 );
    if (rc == 1)
        return 1;
    return rc;
}
Esempio n. 16
0
/*
 * Private function name:   vnc_send_keys
 * Since version:           0.4.2
 * Description:             Function to send the key to VNC window
 * Arguments:               @server [string]: server string to specify VNC server
 *                          @port [string]: string version of port value to connect to
 *                          @keys [string]: string to be send to the guest's VNC window
 * Returns:                 0 on success, -errno otherwise
 */
int vnc_send_keys(char *server, char *port, char *keys)
{
    int sfd;
    int i, skip_next;
    tServerFBParams params;

    DPRINTF("%s: server is %s, port is %s, keys are '%s'\n", VNCFUNC, server, port, keys);

    sfd = vnc_connect(server, port, 1);
    if (sfd < 0) {
        int err = errno;
        DPRINTF("%s: VNC Connection failed with error code %d (%s)\n", VNCFUNC, err, strerror(err));
        close(sfd);
        return -err;
    }

    params = vnc_read_server_init(sfd);

    skip_next = 0;
    DPRINTF("%s: About to process key sequence '%s' (%d keys)\n", VNCFUNC, keys, (int)strlen(keys));
    for (i = 0; i < strlen(keys); i++) {
        DPRINTF("%s: Processing key %d: %d [0x%02x]\n", VNCFUNC, i, keys[i], keys[i]);
        if (skip_next) {
            skip_next = 0;
            continue;
        }
        /* Handling for escape characters */
        if ((keys[i] == '\\') && (strlen(keys) > i + 1)) {
            if (keys[i + 1] == 'n')
                keys[i] = 13;
            if (keys[i + 1] == 'r')
                keys[i] = 10;

            skip_next = 1;
        }

        DPRINTF("%s: Sending key press emulation for key %d\n", VNCFUNC, keys[i]);
        vnc_send_key(sfd, keys[i], skip_next, 0);
        DPRINTF("%s: Requesting framebuffer update\n", VNCFUNC);
        vnc_send_framebuffer_update_request(sfd, 1, params);
        DPRINTF("%s: Sending key release emulation for key %d\n", VNCFUNC, keys[i]);
        vnc_send_key(sfd, keys[i], skip_next, 1);

        /* Sleep for 50 ms, required to make VNC server accept the keystroke emulation */
        usleep(50000);
    }

    DPRINTF("%s: All %d keys sent\n", VNCFUNC, (int)strlen(keys));

    while (socket_has_data(sfd, 500000, 0) == 1)
        socket_read(sfd, -1);

    shutdown(sfd, SHUT_RDWR);
    close(sfd);
    DPRINTF("%s: Closed descriptor #%d\n", VNCFUNC, sfd);
    return 0;
}
Esempio n. 17
0
// physical layer function to send data.
int phy_receive(COMMCTX* ctx, char* buffer, int size)
{
	SOCK_CTX* mctx;
  
	mctx=(SOCK_CTX*)ctx->sock_ctx;
	return socket_read(mctx->sock, buffer, size);
  //  dprintf(stderr, "in phy_receive() received %i.\n",ret);

}
Esempio n. 18
0
static inline oc::result<T> read_copyable_type(int fd)
{
    T buf;
    OUTCOME_TRY(size, socket_read(fd, &buf, sizeof(T)));
    if (size != sizeof(T)) {
        return std::errc::io_error;
    }
    return oc::success(buf);
}
Esempio n. 19
0
static ssize_t socket_dev_read(dev_cookie cookie, void *buf, off_t pos, ssize_t len)
{
	socket_dev *s = (socket_dev *)cookie;

	if(s->id >= 0)
		return socket_read(s->id, buf, len);
	else
		return ERR_NET_NOT_CONNECTED;
}
Esempio n. 20
0
static inline bool read_copyable_type(int fd, TYPE *result)
{
    TYPE buf;
    if (socket_read(fd, &buf, sizeof(TYPE)) == sizeof(TYPE)) {
        *result = buf;
        return true;
    }
    return false;
}
Esempio n. 21
0
/**
 *  Check the server for greeting code 220 and then send QUIT and
 *  check for code 221. If alive return TRUE, else, return FALSE.
 *
 *  @author Jan-Henrik Haukeland, <*****@*****.**>
 *  @author Michael Amster, <*****@*****.**>
 *
 *  @version \$Id: smtp.c,v 1.14 2004/02/18 22:31:42 chopp Exp $
 *
 *  @file
 */
int check_smtp(Socket_T s) {

  int status;
  char buf[STRLEN];
  char msg[STRLEN];

  ASSERT(s);

  if(socket_read(s, buf, sizeof(buf)) <= 0) {
    log("SMTP: error receiving data -- %s\n", STRERROR);
    return FALSE;
  }

  chomp(buf, STRLEN);
  
  /* RATS: ignore */ /* chomp does zero termination */
  sscanf(buf, "%d %s", &status, msg);
  if(status != 220) {
    log("SMTP error: %s\n", buf);
    return FALSE;
  }

  if(socket_print(s, "QUIT\r\n") < 0) {
    log("SMTP: error sending data -- %s\n", STRERROR);
    return FALSE;
  }

  if(socket_read(s, buf, sizeof(buf)) <= 0) {
    log("SMTP: error receiving data -- %s\n", STRERROR);
    return FALSE;
  }

  chomp(buf, STRLEN);
  
  /* RATS: ignore */ /* chomp does zero termination */
  sscanf(buf, "%d %s", &status, msg);
  if(status != 221) {
    log("SMTP error: %s\n", buf);
    return FALSE;
  }

  return TRUE;
  
}
Esempio n. 22
0
static pid_t read_pid(int fd)
{
    pid_t result = 0;
    if (-1 == socket_read(fd, (void *)&result, sizeof(pid_t)))
    {
        perror("bear: read pid");
        exit(EXIT_FAILURE);
    }
    return result;
}
Esempio n. 23
0
int conn_read(struct connection *conn, struct mbuf *buf)
{
    int n = socket_read(conn->fd, buf);
    if (n == 0) return CORVUS_EOF;
    if (n == CORVUS_ERR) return CORVUS_ERR;
    if (n == CORVUS_AGAIN) return CORVUS_AGAIN;
    ATOMIC_INC(conn->ctx->stats.recv_bytes, n);
    ATOMIC_INC(conn->info->recv_bytes, n);
    return CORVUS_OK;
}
Esempio n. 24
0
int	disconnect_error(int fd)
{
  char	*tmp;

  socket_send(fd, "ByeBye");
  tmp = socket_read(fd);
  close(fd);
  free(tmp);
  return (1);
}
Esempio n. 25
0
static bool8 NPServerGetNameFromClient (int c)
{
	if (!npplayer[c].online)
		return (false);

	NPNotification("Server: Receiving player name from client %d...", c);

	if (NPServerSendMesToClient(c, kNPServerNameRequest) == false)
	{
		NPError("Server: Failed to send messsage to client.", 1201);
		return (false);
	}

	uint8	mes[4];
	uint32	l;

	if (socket_read(npplayer[c].socket, mes, 4) != 4)
	{
		NPError("Server: Failed to receive name size from client.", 1202);
		return (false);
	}

	l = READ_LONG(mes + 0);

	if (socket_read(npplayer[c].socket, (uint8 *) npplayer[c].name, l) != (int) l)
	{
		NPError("Server: Failed to receive name from client.", 1203);
		return (false);
	}

	npplayer[c].name[l] = 0;

	if (NPServerSendMesToClient(c, kNPServerNameReceived) == false)
	{
		NPError("Server: Failed to send messsage to client.", 1204);
		return (false);
	}

	NPNotification("Server: Received player name from client %d.", c);
	return (true);

	// next: kNPClientNameSent
}
Esempio n. 26
0
ssize_t ssl_socket_read(struct ssl_socket_t *self_p,
                        void *buf_p,
                        size_t size)
{
    BTASSERT(self_p != NULL);

    ssl_read_counter++;

    return (socket_read(NULL, buf_p, size));
}
Esempio n. 27
0
int 
socket_read_exact(SOCKET s, char * buff, socklen_t bufflen)
{
	int bytes;
	socklen_t currlen = bufflen;
	fd_set read_fds;
	struct timeval tm;
	int count;

	while (currlen > 0) {
		// Wait until some data can be read
		do {
			FD_ZERO( &read_fds );
			FD_SET( s, &read_fds );
			
			tm.tv_sec = 0;
			tm.tv_usec = 50;
			count = select( s + 1, &read_fds, NULL, NULL, &tm);
		} while (count == 0);

		if( count < 0 ) {
#ifdef WIN32
			errno = WSAGetLastError();
#endif
			return -1;
		} else if( count > 2 ) {
			error("socket error in select()\n");
			return -1;
		}
		
		if( FD_ISSET( s, &read_fds ) ) {
			// Try to read some data in
			bytes = socket_read(s, buff, currlen);
			if (bytes > 0) {
				// Adjust the buffer position and size
				buff += bytes;
				currlen -= bytes;
			} else if ( bytes < 0 ) {
#ifdef WIN32
				errno = WSAGetLastError();
#endif
				if( errno != EWOULDBLOCK) {
					//error("socket error.\n");
					return -1;
				}
			} else if (bytes == 0) {
				//error("zero bytes read\n");
				errno = ENOTCONN;
				return -1;
			}
		}
    }

	return 0;
}
Esempio n. 28
0
bool NameResolution::getResolvedIPs(ims::name::IPSet &resolvedIPs, ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 3;
	uint16_t tmpCmdLen = htons(cmdLen);
	uint32_t count32;
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 5; // function, getResolvedIPs
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the # of ips
	if (socket_read(conn_fd, (char *) &count32, sizeof(count32), sockTimeout) != sizeof(count32)) {
		// error
		return false;
	}
	count32 = ntohl(count32);
	// FIXME fill a buffer instead of reading one at a time
	for (uint32_t i = 0; i < count32; ++i) {
		if (socket_read(conn_fd, (char *) &ip, sizeof(uint32_t), sockTimeout) != sizeof(uint32_t)) {
			return false;
		}
		resolvedIPs.insert(ntohl(ip));
	}
	return true;
}
Esempio n. 29
0
static int NPServerGetMesFromClient (int c)
{
	uint8	mes[2];

	if (socket_read(npplayer[c].socket, mes, 2) != 2)
		return (-1);

	if (mes[0] != NP_CLIENT_MAGIC)
		return (-1);

	return ((int) mes[1]);
}
Esempio n. 30
0
static int NPClientGetMesFromServer (void)
{
	uint8	mes[2];

	if (socket_read(npclient.socket, mes, 2) != 2)
		return (-1);

	if (mes[0] != NP_SERVER_MAGIC)
		return (-1);

	return ((int) mes[1]);
}