void* SC_TcpConnectionPort::Run()
{
	OSC_Packet *packet = 0;
	// wait for login message
	int32 size;
	int32 msglen;

	while (true) {
		if (!packet) {
			packet = (OSC_Packet*)malloc(sizeof(OSC_Packet));
		}
		size = recvall(mSocket, &msglen, sizeof(int32));
		if (size < 0) goto leave;

		// sk: msglen is in network byte order
		msglen = ntohl(msglen);

		char *data = (char*)malloc(msglen);
		size = recvall(mSocket, data, msglen);
		if (size < msglen) goto leave;

		packet->mReplyAddr.mReplyFunc = tcp_reply_func;
		packet->mSize = msglen;
		packet->mData = data;
		packet->mReplyAddr.mSocket = mSocket;
		ProcessOSCPacket(packet);
		packet = 0;
	}
leave:
    delete this; // ohh this could cause a crash if a reply tries to access it..
    return 0;
}
Beispiel #2
0
static ssize_t recvFromVICC(struct vicc_ctx *ctx, unsigned char **buffer)
{
    ssize_t r;
    uint16_t size;
    unsigned char *p = NULL;

    if (!buffer || !ctx) {
        errno = EINVAL;
        return -1;
    }

    /* receive size of message on 2 bytes */
    r = recvall(ctx->client_sock, &size, sizeof size);
    if (r < sizeof size)
        return r;

    size = ntohs(size);

    p = realloc(*buffer, size);
    if (p == NULL) {
        errno = ENOMEM;
        return -1;
    }
    *buffer = p;

    /* receive message */
    return recvall(ctx->client_sock, *buffer, size);
}
char* recibirString(int socket){
	int tamanioString;
	if(recvall(socket,&tamanioString,sizeof(int))<1) return NULL;
	char* string;
	string =malloc(sizeof(char)*tamanioString);
	if(recvall(socket,string,tamanioString)<1) return NULL;
	return string;
}
Beispiel #4
0
int
IMA_tcp_recv (int s, char *cmd)
{
  int len;
  int lenbuf;
  char buf[bufsize];
  FILE *fp;
  int i;

  fp = fopen (cmd, "w");
  lenbuf = bufsize;
  while (lenbuf == bufsize)
    {
      /* Receive the length of buffer. */
      len = sizeof (int);
      if (recvall (s, (char *) &lenbuf, &len) == -1)
        {
          perror ("recv");
          exit (1);
        }
      if (lenbuf == 999)
        {
          break;
        }
      /* printf ("Received: %d\n", lenbuf); */
      if (recvall (s, buf, &lenbuf) == -1)
        {
          perror ("recv");
          exit (1);
        }
      for (i = 0; i < lenbuf; i++)
        {
          fputc (buf[i], fp);
        }
    }
  if (lenbuf < bufsize)
    {
      len = sizeof (int);
      if (recvall (s, (char *) &lenbuf, &len) == -1)
        {
          perror ("recv");
          exit (1);
        }
      assert (lenbuf == 999);
    }

  fclose (fp);
  fp = NULL;
  printf ("Received: %s\n", cmd);
  return 0;

}
Beispiel #5
0
struct nlmsghdr * netlink_recv(
    struct proxy_dev *pdev)
{
    struct nlmsghdr *nlh = NULL;
    struct msghdr msgh = {0};
    struct iovec iov = {0};
    size_t bufflen = sizeof(*nlh);
    void *buffer = malloc(bufflen);

    /* netlink header is our payload */
    iov.iov_base = buffer;
    iov.iov_len = bufflen;
    msgh.msg_iov = &iov; /* this normally is an array of */
    msgh.msg_iovlen = 1;
    msgh.msg_flags = MSG_PEEK; /* first we need the full msg size */

    /* the minimum is the size of the nlmsghdr alone */
    bufflen = recvall(pdev->nl_fd, &msgh, bufflen);
    if (bufflen == -1) {
        printf("netlink_recv: failed to read message\n");
        goto err;
    }

    nlh = buffer;
    /*
    debug("type: %d, pid: %d, size: %d",
            nlh->nlmsg_type, nlh->nlmsg_pid, nlh->nlmsg_len);
    */

    /* increase the buffer size if needbe */
    bufflen = nlh->nlmsg_len;
    buffer = realloc(buffer, bufflen);
    iov.iov_base = buffer;
    iov.iov_len = bufflen;
    msgh.msg_flags = 0; /* get rid of MSG_PEEK */

    /* get the rest of message */
    bufflen = recvall(pdev->nl_fd, &msgh, bufflen);
    if (bufflen == -1) {
        printf("netlink_recv: failed to read message\n");
        goto err;
    }

    nlh = buffer;
    return nlh;
err:
    free(buffer);
    return NULL;
}
int recv_command_packet(int sockfd, struct command_packet
		*command_packet, int flags){

	/* Awkward buf size, but it is correct */
	unsigned char recv_buf[SEND_BUF_SIZE];
	int n = 0, bytes_recv;

	if((n = recvall(sockfd, recv_buf, COMMAND_PACKET_SIZE, flags)) <
			0){
		fprintf(stderr, "%s: ", __FUNCTION__);
		perror("recv error");
		return ERROR;
	}

	bytes_recv = n;

	/* Server closed connection */
	if(n == 0){
		close(sockfd);
		return bytes_recv;
	}

	/* Unpack response packet header and read the payload */
	if((n = prepare_to_read_command(recv_buf, bytes_recv, command_packet)) < 0){
		fprintf(stderr, "%s: prepare_to_read_comand error\n",
				__FUNCTION__);
		return ERROR;
	}

	return bytes_recv;
}
Beispiel #7
0
//---------------------------------------------------------------------------------
int progressRead(int socket, char *buffer, int size) {
//---------------------------------------------------------------------------------

	int row,column;
	getCursor(&row,&column);
	
	int sizeleft = size, len;
	int chunksize = size/100;
	int target = size - chunksize;

	int percent = 0;

	while(sizeleft) {
		len = recvall(socket,buffer,chunksize,0);
		if (len == 0) break;
		sizeleft -= len;
		buffer += len;
		if (sizeleft <= target) {
			percent++;
			target -= chunksize;
			if (target<0) target = 0;
		}
		setCursor(row,column);
		kprintf("%%%d  ",percent);
		if ( sizeleft < chunksize) chunksize = sizeleft;
	}
	
	setCursor(row,column);
	if (sizeleft) {
		kprintf("\nReceive Error\n");
	} else {
		kprintf("%%100\n");
	}
	return sizeleft;
}
Beispiel #8
0
void *newconnection(void *arg)
{
  int sockethandle=(uintptr_t)arg;
  unsigned char command;
  int r;
  //printf("Hello!\n");

  //wait for a command and dispatch it

  r=1;
  while (r>=0)
  {
    r=recvall(sockethandle, &command, 1, MSG_WAITALL);
    if (r==1)
      DispatchCommand(sockethandle, command);
    else
    {
      //printf("Peer has disconnected");
      //if (r==-1)
      //  printf(" due to an error");

      //printf("\n");

      //fflush(stdout);
      close(sockethandle);
    }
  }

  printf("Bye\n");
  return NULL;
}
Beispiel #9
0
/* reads initialization packet (containing IV and timestamp) from server */
int read_init_packet(int sock) {
	int rc;
	init_packet receive_packet;
	int bytes_to_recv;

	/* clear the IV and timestamp */
	bzero(&received_iv, TRANSMITTED_IV_SIZE);
	packet_timestamp = (time_t)0;

	/* get the init packet from the server */
	bytes_to_recv = sizeof(receive_packet);
	rc = recvall(sock, (char *)&receive_packet, &bytes_to_recv, socket_timeout);

	/* recv() error or server disconnect */
	if (rc <= 0) {
		printf("Error: Server closed connection before init packet was received\n");
		return ERROR;
	}

	/* we couldn't read the correct amount of data, so bail out */
	else if (bytes_to_recv != sizeof(receive_packet)) {
		printf("Error: Init packet from server was too short (%d bytes received, %d expected)\n", bytes_to_recv, sizeof(receive_packet));
		return ERROR;
	}

	/* transfer the IV and timestamp */
	memcpy(&received_iv, &receive_packet.iv[0], TRANSMITTED_IV_SIZE);
	packet_timestamp = (time_t)ntohl(receive_packet.timestamp);

	return OK;
}
Beispiel #10
0
static int process_add_port(int client) {
    ctl_msg_add_port_t msg;
    msg.code = CTL_MSG_ADD_PORT_CODE;
    int n = recvall(client, ((char *) &msg) + 1, sizeof(ctl_msg_add_port_t) - 1);
    assert(n == sizeof(ctl_msg_add_port_t) - 1);
//int status = bmi_port_interface_add(port_mgr, msg.iface, msg.port_num); //send_status_reply(client, msg.request_id, status);
    return 0;
}
int boithoad_sidToGroup(char sid_in[], char username_in[]) {

	int socketha;
	int intresponse;
	char username[64];
	char sid[512];
     	int forreturn = 0;

	//ToDo: strscpy
	strncpy(sid,sid_in,sizeof(sid));

        if ((socketha = cconnect("localhost", BADPORT)) == 0) {
		return 0;
	}

        sendpacked(socketha,bad_sidToGroup,BADPROTOCOLVERSION, 0, NULL,"");

	sendall(socketha, sid, sizeof(sid));
	
	//read respons
        if (!recvall(socketha,&intresponse,sizeof(intresponse))) {
                return 0;
        }

	if (intresponse == 1) {
		if (!recvall(socketha,username,sizeof(username))) {
                	return 0;
        	}
		strcpy(username_in, username);
		forreturn = 1;
	}
	else {
		#ifdef DEBUG
			printf("didn't have a group at %s:%d\n",__FILE__,__LINE__);
		#endif
		strcpy(username_in,"");
		forreturn = 0;
	}

	close(socketha);

	return forreturn;

}
Beispiel #12
0
int rover_server_recv_and_print(int fd, FILE* my_log_file)
{
  int retval;
  int num_messages;
  const char* format_string;
  if (fd == log_imu_new_fd1)  //receiving a buffer of messages
    {
      format_string = "%s";
      //num_messages = k_msg_buf_size;
      //receive size of message buffer
      retval = recv(fd, &num_messages, sizeof(num_messages), 0);
      if (retval < 0)
	{
	  printf("rover_server_recv_and_print(): error receiving number of messages\n");
	  return FALSE;
	}
      else if ((retval == 0) || (num_messages == 0)) //use sent 0 for escape char
	//sender stopped sending, so just return
	return FALSE;
      //else we have a good num_messages
    }
  else //receiving single message
    {
      num_messages = 1;
      format_string = "%s\n";
    }
  int msg_buf_bytes = num_messages * k_LogBufSize;
  unsigned char logbuf[msg_buf_bytes];
  memset(logbuf, 0, msg_buf_bytes);  //clear buffer
  if (recvall(fd, logbuf, &msg_buf_bytes) != 0)
    {//recvall did not complete, so check msg_buf_bytes
      if (msg_buf_bytes == 0) //sender shut down
	return FALSE;
      else
	{
	  printf("******RECVALL ERROR, msg_buf_bytes = %d, fd = %d\n", msg_buf_bytes, fd);
	  perror("rover_server_recv_and_print:recvall:");
	  return FALSE;
	}
    }
  else //recvall completed, so process the buffer
    {
      //printf("received %d bytes\n", msg_buf_bytes);
      for (int i = 0; i < num_messages; i++)
  	{
  	  if ((logbuf[i * k_LogBufSize] != '\0') &&
  	      (logbuf[i * k_LogBufSize] != '\n'))
  	    fprintf(my_log_file, format_string, logbuf+(i*k_LogBufSize));
  	  else
	    fprintf(my_log_file, "%s\n", logbuf+(i*k_LogBufSize) );
	    //fprintf(my_log_file, "**BAD LINE: %s\n", logbuf+(i*k_LogBufSize) );
  	}
    }
  //if we get here, we handled the message properly, so return true
  return TRUE;
}
/**
 * Receives a header and a payload on the TCP connection. Blocks until a
 * complete packet is received, the end-of-file is encountered, or an error
 * occurs.
 *
 * @param[in] header   Header.
 * @param[in] headLen  Length of the header in bytes.
 * @param[in] payload  Payload.
 * @param[in] payLen   Length of the payload in bytes.
 * @retval    0        EOF encountered.
 * @return             Number of bytes read. Will be `headLen + payLen`.
 * @throws std::system_error  if an error is encountered reading from the
 *                            socket.
 */
size_t TcpRecv::recvData(void* header, size_t headLen, char* payload,
                         size_t payLen)
{
    size_t nread;

    if (header && headLen) {
        nread = recvall(header, headLen);
        if (nread < headLen)
            return 0; // EOF
    }

    if (payload && payLen) {
        nread = recvall(payload, payLen);
        if (nread < payLen)
            return 0; // EOF
    }

    return (headLen + payLen);
}
int boithoad_getPassword(const char username_in[], char password_in[]) {

	int socketha;
	int intresponse;
	char username[64];
	char password[64];
     	int forreturn = 0;

	//ToDo: strscpy
	strncpy(username,username_in,sizeof(username));

        if ((socketha = cconnect("localhost", BADPORT)) == 0) {
		return 0;
	}

        sendpacked(socketha,bad_getPassword,BADPROTOCOLVERSION, 0, NULL,"");

	sendall(socketha,username, sizeof(username));
	
	//read respons
        if (!recvall(socketha,&intresponse,sizeof(intresponse))) {
                return 0;
        }

	if (intresponse == 1) {
		if (!recvall(socketha,password,sizeof(password))) {
                	return 0;
        	}
		//printf("got \"%s\"\n",password);
		strcpy(password_in,password);
		forreturn = 1;
	}
	else {
		printf("dident have a passord at %s:%d\n",__FILE__,__LINE__);
		strcpy(password_in,"");
		forreturn = 0;
	}

	close(socketha);

	return forreturn;

}
//motar en enkel respons liste. Den begynner med en int som sier hov lang den er
int boithoa_getLdapResponsList(int socketha,char **respons_list[],int *nrofresponses) {

	char ldaprecord[MAX_LDAP_ATTR_LEN];
	int intresponse,i,len;

	if (!recvall(socketha,&intresponse,sizeof(intresponse))) {
		return 0;
	}

	#ifdef DEBUG
	printf("nr %i\n",intresponse);
	#endif

	if (((*respons_list) = malloc((sizeof(char *) * (intresponse+1)))) == NULL) {
		perror("boithoa_getLdapResponsList: can't malloc respons array");
		return 0;
	}
        *nrofresponses = 0;

	for (i=0;i<intresponse;i++) {
		if (!recvall(socketha,ldaprecord,sizeof(ldaprecord))) {
			fprintf(stderr,"can't recvall() ldaprecord\n");
			return 0;
		}

		#ifdef DEBUG
		printf("record \"%s\", len %i\n",ldaprecord,strlen(ldaprecord));
		#endif

		len = strnlen(ldaprecord,MAX_LDAP_ATTR_LEN);
                (*respons_list)[*nrofresponses] = malloc(len+1); 

		//ToDO: strscpy
                strncpy((*respons_list)[*nrofresponses], ldaprecord, len+1);

		(*nrofresponses)++;
	}

	(*respons_list)[*nrofresponses] = NULL;

	return 1;
}
void recibirStringEn(int socket, char** stringReceptor){

	int tamanioString;

	tamanioString=recibirInt(socket);

	*stringReceptor = malloc(tamanioString);

	recvall(socket,*stringReceptor,tamanioString);

}
Beispiel #17
0
Uint16
getshort(TCPsocket sock)
{
   Uint16 cmd;
   Uint16 recvdata = recvall(sock, (unsigned char *) &cmd, sizeof(cmd));

   if (recvdata != sizeof(cmd))
   {
      return 0;
   }
   return SDLNet_Read16(&cmd);
}
Beispiel #18
0
Uint32
getint(TCPsocket sock)
{
   Uint32 cmd;
   int recvdata = recvall(sock, (unsigned char *) &cmd, sizeof(cmd));

   if (recvdata != sizeof(cmd))
   {
      return 0;
   }
   return SDLNet_Read32(&cmd);
}
Beispiel #19
0
static int process_del_port(int client) {
    ctl_msg_del_port_t msg;
    msg.code = CTL_MSG_DEL_PORT_CODE;
    int n = recvall(client, ((char *) &msg) + 1, sizeof(ctl_msg_del_port_t) - 1);
    assert(n == sizeof(ctl_msg_del_port_t) - 1);
    errno = 0;
    int port_num = strtol(msg.iface, NULL, 10);
    // FIXME: Not sure how to convert interface string to int.
    assert(errno == 0);
    int status = del_port(port_num);
    send_status_reply(client, msg.request_id, status);
    return 0;
}
Beispiel #20
0
int
sc_aggregator_connection_receive_message(sc_aggregator_connection* conn, sc_log_message** pmsg)
{
    char buf[offsetof(sc_log_message, content)];
    sc_log_message *m0 = (sc_log_message*)buf, *m = NULL;
    int32_t len;
    int n;

    n = recvall(conn->socket, buf, sizeof(buf), 0);
    if (n < 0) {
        close(conn->socket);
	conn->socket = -1;
        perror("recvall");
        return -1;
    } else if (n == 0) {
        az_log(LOG_DEBUG, "closed");
	return -4;
    }

    len = ntohl(m0->content_length);

    m = sc_log_message_new(len);
    if (!m) {
        return -2;
    }

    m->code    = ntohs(m0->code);
    m->channel = ntohs(m0->channel);

    if (m->content_length > 0) {
        if (recvall(conn->socket, m->content, m->content_length, 0) <= 0) {
            return -3;
        }
    }

    *pmsg = m;
    return 0;
}
bool Server::GetString(int ID, std::string & _string)
{
	int bufferlength; //Holds length of the message
	if (!GetInt(ID, bufferlength)) //Get length of buffer and store it in variable: bufferlength
		return false; //If get int fails, return false
	char * buffer = new char[bufferlength + 1]; //Allocate buffer
	buffer[bufferlength] = '\0'; //Set last character of buffer to be a null terminator so we aren't printing memory that we shouldn't be looking at
	if (!recvall(ID, buffer, bufferlength)) //receive message and store the message in buffer array. If buffer fails to be received...
	{
		delete[] buffer; //delete buffer to prevent memory leak
		return false; //return false: Fails to receive string buffer
	}
	_string = buffer; //set string to received buffer message
	delete[] buffer; //Deallocate buffer memory (cleanup to prevent memory leak)
	return true;//Return true if we were successful in retrieving the string
}
Beispiel #22
0
static int process_request(int client) {
    char msg_code;
    int n = recvall(client, &msg_code, 1);
    if (n <= 0) return n;
    switch(msg_code) {
    case CTL_MSG_ADD_PORT_CODE:
        process_add_port(client);
        return CTL_MSG_ADD_PORT_CODE;
    case CTL_MSG_DEL_PORT_CODE:
        process_del_port(client);
        return CTL_MSG_DEL_PORT_CODE;
    default:
        printf("Unknown message format\n");
    }
    return -1;
}
/*-------------------------------------------------------------------------*\
* object:receive() interface
\*-------------------------------------------------------------------------*/
int buffer_meth_receive(lua_State *L, p_buffer buf) {
    int err = IO_DONE, top = lua_gettop(L);
    luaL_Buffer b;
    size_t size;
    const char *part = luaL_optlstring(L, 3, "", &size);
#ifdef LUASOCKET_DEBUG
    p_timeout tm = timeout_markstart(buf->tm);
#endif
    /* initialize buffer with optional extra prefix 
     * (useful for concatenating previous partial results) */
    luaL_buffinit(L, &b);
    luaL_addlstring(&b, part, size);
    /* receive new patterns */
    if (!lua_isnumber(L, 2)) {
        const char *p= luaL_optstring(L, 2, "*l");
        if (p[0] == '*' && p[1] == 'l') err = recvline(buf, &b);
        else if (p[0] == '*' && p[1] == 'a') err = recvall(buf, &b); 
        else luaL_argcheck(L, 0, 2, "invalid receive pattern");
    /* get a fixed number of bytes (minus what was already partially 
     * received) */
    } else {
        double n = lua_tonumber(L, 2); 
        size_t wanted = (size_t) n;
        luaL_argcheck(L, n >= 0, 2, "invalid receive pattern");
        if (size == 0 || wanted > size)
            err = recvraw(buf, wanted-size, &b);
    }
    /* check if there was an error */
    if (err != IO_DONE) {
        /* we can't push anyting in the stack before pushing the
         * contents of the buffer. this is the reason for the complication */
        luaL_pushresult(&b);
        lua_pushstring(L, buf->io->error(buf->io->ctx, err)); 
        lua_pushvalue(L, -2); 
        lua_pushnil(L);
        lua_replace(L, -4);
    } else {
        luaL_pushresult(&b);
        lua_pushnil(L);
        lua_pushnil(L);
    }
#ifdef LUASOCKET_DEBUG
    /* push time elapsed during operation as the last return value */
    lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm));
#endif
    return lua_gettop(L) - top;
}
Beispiel #24
0
int cmc_rewrite_url(int socketha, char *collection_in, const char *url_in, enum platform_type ptype, 
		enum browser_type btype, char *url_out, size_t url_out_len, char *uri_out, size_t uri_out_len, 
		char *fulluri_out, size_t fulluri_out_len)
{
	struct rewriteFormat rewrite;

	#ifdef DEBUG_TIME
		struct timeval start_time, end_time;
		printf("cmc_rewrite_url(collection_in=\"%s\", url_in=\"%s\")\n",collection_in,url_in);
		gettimeofday(&start_time, NULL);
	#endif



	memset(&rewrite, '\0', sizeof(rewrite));
	
				
	strscpy(rewrite.collection, collection_in, sizeof(rewrite.collection));
	strscpy(rewrite.url, url_in, sizeof(rewrite.url));
	rewrite.ptype = ptype;
	rewrite.btype = btype;

	sendpacked(socketha, cm_rewriteurl, BLDPROTOCOLVERSION, sizeof(rewrite), &rewrite, "");


	if (recvall(socketha, &rewrite, sizeof(rewrite)) == 0) {
		perror("recvall(url)");
		return 0;
	}

	strscpy(url_out, rewrite.url, url_out_len);
	strscpy(uri_out, rewrite.uri, uri_out_len);
	strscpy(fulluri_out, rewrite.fulluri, fulluri_out_len);

	#ifdef DEBUG
		printf("~cmc_rewrite_url [uri_out=\"%s\", fulluri=\"%s\"]\n",uri_out,fulluri_out);
	#endif

	#ifdef DEBUG_TIME
		gettimeofday(&end_time, NULL);
		printf("~cmc_rewrite_url(2) time %f\n",getTimeDifference(&start_time,&end_time));
	#endif

	return 1;
}
int boitho_authenticat(const char username_in[],char password_in[]) {
        int socketha;
        int response;

        char username[64];
        char password[64];

        strncpy(username,username_in,sizeof(username));
        strncpy(password,password_in,sizeof(password));

        if ((socketha = cconnect("localhost", BADPORT)) == 0) {
		perror("localhost");
		return 0;
	}

	#ifdef DEBUG
		printf("boitho_authenticat: dic cconnect\n");
	#endif

        sendpacked(socketha,bad_askToAuthenticate,BADPROTOCOLVERSION, 0, NULL,"");

	sendall(socketha,username, sizeof(username));
	sendall(socketha,password, sizeof(password));

	recvall(socketha,&response,sizeof(response));

	close(socketha);


	if (response == ad_userauthenticated_OK) {
		return 1;
	}
	else if (response == ad_userauthenticated_ERROR) {
		return 0;
	}
	else if (response == ad_userauthenticated_NOACCESS) {
		return 2;
	}
	else {
		fprintf(stderr,"dident get ad_userauthenticated_ERROR or ad_userauthenticated_OK\n");
		return 0;
	}

}
Beispiel #26
0
int cdr_OpenCV_ReceiveFrame(PointGrey_t2* PG)
{
  //first receive image size
  int retval = recv(PG->new_fd, &PG->img_size, sizeof(PG->img_size), 0);
  if (retval < 0)
    {
      printf("cdr_OpenCV_ReceiveFrame: Error receiving image size\n");
      return -1;
    }
  if ((retval == 0) || (PG->img_size == 0)) //use sent 0 as escape char
    {
      printf("cdr_OpenCV_ReceiveFrame: Sender stopped sending\n");
      return -1;
    }
  //if we get here, we got valid size data
  //printf("Received image size: %d\n", PG->img_size);

  //then receive image data
  unsigned char* buf = (unsigned char*) malloc(PG->img_size);
  if (recvall(PG->new_fd, buf, &PG->img_size) != 0)
    {
      printf("cdr_OpenCV_ReceiveFrame: Error in recvall\n");
      return -1;
    }
  //copy buf into vector
  cv::vector<uchar> compressed(buf, buf+PG->img_size);
  //clean up memory allocations
  free(buf); 
  //now use data to build image and save it
    
  // if (strcmp(PORT, k_FrontCamPort) == 0)
  PG->uncompressedImage = cv::imdecode(cv::Mat(compressed), CV_LOAD_IMAGE_COLOR);
  // else
  // 	PG->uncompressedImage = imdecode(cv::Mat(compressed), CV_LOAD_IMAGE_GRAYSCALE);
  /* ***Don't seem to need to differentiate between color and */
  /* grayscale here -- gray images save gray even when loaded */
  /* as color.*** */
  return 0;
}
Beispiel #27
0
void
getmaze(TCPsocket sock)
{
   Uint16 n;
   int recv;

   switch (n = getshort(sock))
   {
      case MAZE_MAGIC:
         break;
      case SRV_BUSY:
         fprintf(stderr, "Game is already going on :(\n");
         exit(EXIT_FAILURE);
      default:
         fprintf(stderr, "Bad magic number from server: %x\n", n);
         exit(EXIT_FAILURE);
   }

   MAZE.w = getint(sock);
   MAZE.size = getint(sock);
   MAZE.h = MAZE.size / MAZE.w;

#ifdef _DEBUG
   printf("[DEBUG] maze w size h = %ld %ld %ld\n", MAZE.w, MAZE.size, MAZE.h);
#endif

   MAZE.data = malloc(MAZE.size);

   // uh no
   if ((recv = recvall(sock, MAZE.data, MAZE.size)) != MAZE.size)
   {
      fprintf(stderr, "Failed to get maze. Got %d bytes, expected %ld. %s\n",
            recv, MAZE.size, SDLNet_GetError());
      exit(EXIT_FAILURE);
   }

   sendshort(sock, MAZE_MAGIC);     /* Confirmation reply */

}
int loadCEServerExtension(HANDLE hProcess)
{
  printf("loadCEServerExtension\n");
  if (GetHandleType(hProcess) == htProcesHandle )
  {
    PProcessData p=(PProcessData)GetPointerFromHandle(hProcess);


    if (p->isDebugged)
    {
      printf("this process id being debugged\n");
      //make sure this is executed by the debugger thread
      if (p->debuggerThreadID!=pthread_self())
      {
        printf("Not the debugger thread. Switching...\n");
        //tell the debugger thread to do this
        int result=0;
#pragma pack(1)
        struct
        {
          uint8_t command;
          uint32_t pHandle;
        } lx;
#pragma pack()

        lx.command=CMD_LOADEXTENSION;
        lx.pHandle=hProcess;
        if (pthread_mutex_lock(&debugsocketmutex) == 0)
        {
          sendall(p->debuggerClient, &lx, sizeof(lx), 0);
          WakeDebuggerThread();

          recvall(p->debuggerClient, &result, sizeof(result), MSG_WAITALL);
          printf("Returned from debugger thread. Result:%d\n", result);

          pthread_mutex_unlock(&debugsocketmutex);
        }

        return result;
      }
      else
        printf("This is the debugger thread\n");
    }



    if (p->hasLoadedExtension==0)
    {
      char modulepath[256], modulepath2[256];
      int l;

      memset(modulepath, 0, 256);
      memset(modulepath2, 0, 256);

      char *mp;


      l=readlink("/proc/self/exe", modulepath2, 256);

      if (l!=-1)
      {
        modulepath2[l]=0;
        printf("modulepath2=%s\n", modulepath2);
        sscanf(modulepath2,"%s", modulepath); //sometimes it has a (deleted) text after it

        printf("modulepath=%s\n", modulepath);
        mp=dirname(modulepath);

        printf("after dirname: %s\n", mp);
        strcpy(modulepath, mp);
        strcat(modulepath, "/libceserver-extension.so");

        printf("modulepath = %s\n", modulepath);

      }
      else
      {
        strcpy(modulepath, "libceserver-extension.so");
      }




      if (p->isDebugged)
      {
        printf("This process is being debugged. Checking if it's already loaded\n");

        pthread_mutex_lock(&p->extensionMutex);
        p->hasLoadedExtension=openExtension(p->pid, &p->extensionFD);
        pthread_mutex_unlock(&p->extensionMutex);
      }
     // else

      if (p->hasLoadedExtension)
        printf("The extension is already loaded\n");


      {
        pthread_mutex_lock(&p->extensionMutex);
        if (p->hasLoadedExtension==0) //still 0
        {

          if (p->neverForceLoadExtension==0)
          {
            printf("Calling loadExtension\n");
            p->hasLoadedExtension=loadExtension(p->pid, modulepath, p->isDebugged);
          }

          if (p->hasLoadedExtension)
            p->hasLoadedExtension=openExtension(p->pid, &p->extensionFD);
        }

        pthread_mutex_unlock(&p->extensionMutex);
      }


    }
    else
      printf("Already loaded\n");

    return p->hasLoadedExtension;
  }
  else
  {
    printf("Invalid handle type");
    return 0;
  }
}
int recibirInt(int socket){
	int entero;
	if(recvall(socket,&entero,sizeof(int))<1) return -1;
	return entero;
}
Beispiel #30
0
void peer2peer(uint32_t peerIP, int peerPort, char * filen)
{
	int sockfd, portno, n, size, tempfd;
	char *filename;
	struct hostent* server;
	struct sockaddr_in serv_addr;
	char buffer[256];
	char peerAddr[INET_ADDRSTRLEN];
	
	//Convert clientIP to standard dot notation
	inet_ntop(AF_INET, &peerIP, peerAddr, INET_ADDRSTRLEN);
	
	server = gethostbyname(peerAddr);
	if(!server) {
		fprintf(stderr, "ERROR: no such host: %s\n", peerAddr);
		return;
	}
	portno = peerPort;
	filename = filen;

	sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // check man page
	if(sockfd < 0) syserr("can't open socket");
	printf("create socket...\n");

	// set all to zero, then update the sturct with info
	memset(&serv_addr, 0, sizeof(serv_addr)); 
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr = *((struct in_addr*)server->h_addr);
	serv_addr.sin_port = portno; 	

	// connect with filde descriptor, server address and size of addr
	if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
	syserr("can't connect to server");
	printf("connect...\n");
	printf("Connection established. Getting files...\n");
	
	//Get the file
	memset(buffer, 0, sizeof(buffer));
	strcpy(buffer, filename);
	n = send(sockfd, buffer, BUFFSIZE, 0);
	if(n < 0) syserr("can't send filename to peer");
	n = recv(sockfd, &size, sizeof(int), 0); 
   if(n < 0) syserr("can't receive size of file from peer");
   size = ntohl(size);        
	if(size ==0) // check if file exists
	{
		printf("File not found at peer\n");
		return;
	}
	printf("The size of the file to recieve is: %d\n", size);
	tempfd = open(filename, O_CREAT | O_WRONLY, 0666);
	if(tempfd < 0) syserr("failed to get file");
	recvall(tempfd, sockfd, size, buffer);
	printf("Download of '%s' was successful\n", filename);  
	close(tempfd);
	
	//Close connection
	n = recv(sockfd, &size, sizeof(int), 0);
   size = ntohl(size);  
   if(n < 0) syserr("can't receive exit signal from server");
    
	//Check for exit
	if(size)
	{
		printf("Connection to server terminated\n");
	}
	else
	{
		printf("Server didn't exit");
	}	
}