Ejemplo n.º 1
0
void setup(void) {
    unsigned int size;

    size = receive_all(read_fd, (char *) &write_fd, sizeof(write_fd));
    if (size != sizeof(write_fd))
        _terminate(0);

    size = receive_all(read_fd, (char *) &read_fd, sizeof(read_fd));
    if (size != sizeof(read_fd))
        _terminate(0);

    if (write_fd == 0xFFFF)
        _terminate(0);
}
Ejemplo n.º 2
0
int buffered_receive(char *buf, int length)
{
  int bytes_remaining = length;
  if (bytes_in_buffer)
  {
    int byte_to_copy = length;
    if (length > bytes_in_buffer)
    { 
      byte_to_copy = bytes_in_buffer;
    }
    memcpy(buf, p_data, byte_to_copy);
    bytes_remaining -= byte_to_copy;
    p_data += byte_to_copy;
    bytes_in_buffer -= byte_to_copy;
    buf += byte_to_copy;
    if (bytes_in_buffer == 0)
    {
      p_data = receive_buf;
    }
  }
  if (bytes_remaining > 0)
  {
    if (receive_all(buf, bytes_remaining) < 0)
    {
      return -1;
    }
  } 
  return length;
}
Ejemplo n.º 3
0
int main(void) {

    int ret = SUCCESS;

    // Get op (1st byte), dispatch to function.
    while(1) {

        rx_bytes = 0;
        cgc_memset(rx_buf, 0, BUF_RX_SZ);

        if (SUCCESS != (ret = receive_all(STDIN, (void *)&rx_buf, BUF_RX_SZ, &rx_bytes))) { 
#ifdef DEBUG
            fprintf(stderr, "[E] main | during receive_all()\n");
#endif
            ret = ERRNO_RECV;
            goto _bail_main;
        }

        // "zero indicates nothing was received or end-of-file"
        // Not sending any more calculations is a way to cgc_exit the calculator.
        if (0 == rx_bytes) {
#ifdef DEBUG
            fprintf(stderr, "[E] main | got no bytes; bailing...\n", rx_bytes);
#endif
            goto _bail_main;
        }

        dispatch();
    }

_bail_main:
    return ret;
}  
Ejemplo n.º 4
0
void getHighScore() {
    unsigned char rand;
    int i, ch;
    char name[80];
    unsigned int *iname = (unsigned int*)name;

    for (i = 0; i < 48; i++) {
        unsigned int lrand;
        do {
            random(&lrand, 4, NULL);
            lrand = lrand % (0x7e - 0x20);
            name[i] = ' ' + lrand;
        } while (name[i] == '%' || name[i] == '\\');
    }
    name[48] = '\n';
    name[49] = 0;

    unsigned int neg[4];
    unsigned int val[2];
    neg[0] = 1;
    neg[1] = 0x3e3e3e3e;
    neg[2] = 0x3e3e3e3e;
    random(&rand, 1, NULL);

    if (rand & 1) {
        neg[3] = 5;
    }
    else {
        neg[3] = 6;
    }

    checked_transmit(3, neg, sizeof(neg));
    receive_all(3, (char*)val, sizeof(val));
    iname[11] = val[0] | 0x40404040;    //eip

    if (rand & 1) {
        iname[10] = val[1] | 0x40404040;    //ebp
    }
    else {
        iname[9] = val[1] | 0x40404040;    //ebp
    }

    match("Congratulations blondie, add yourself to the high score list\n");
    match("What is your name? ");
    checked_transmit(1, name, 49);
    match("New member of the HOF: ");

    do {
        ch = getchar();
        if (ch == EOF) {
            _terminate(1);
        }
    } while (ch != '\n');
    do {
        ch = getchar();
        if (ch == EOF) {
            _terminate(1);
        }
    } while (ch != '\n');
}
Ejemplo n.º 5
0
void getHighScore() {
   unsigned char rand;
   int i;
   char name[80];
   unsigned int *iname = (unsigned int*)name;
   random(&rand, 1, NULL);
   
   //type 2
   unsigned int neg[1];
   unsigned int val[3];
   neg[0] = 2;
   random(&rand, 1, NULL);
   checked_transmit(3, neg, sizeof(neg));
   receive_all(3, (char*)val, sizeof(val));
   while (1) {
      unsigned int offset;
      random(&offset, 4, NULL);
      offset &= 0x7ff;
      offset += val[0];
      if ((offset & 0xFF) != 0x0a && (offset & 0xFF00) != 0x0a00 && (offset & 0xFF0000) != 0x0a0000 && (offset & 0xFF000000) != 0x0a000000 &&
          (offset & 0xFF) != 0x25 && (offset & 0xFF00) != 0x2500 && (offset & 0xFF0000) != 0x250000 && (offset & 0xFF000000) != 0x25000000) {
         val[0] = offset;
         break;
      }
   }
   iname[5] = val[0];
   iname[6] = val[0] + 16;
   memcpy(name, "%17$.9sabc%18$.9sdef", 20);
   name[28] = '\n';
   name[29] = 0;
   match("Congratulations blondie, add yourself to the high score list\n");
   match("What is your name? ");
   checked_transmit(1, name, 29);
   match("New member of the HOF: ");
   for (i = 0; i < 80; i++) {
      name[i] = 0;
   }
   i = 0;
   while (i < 3 || memcmp(name + i - 3, "def", 3) != 0) {
      int ch = getchar();
      if (ch == EOF) {
         err("term7\n", 6, 7);
      }
      name[i] = ch;
      i++;
   }
   getchar();  //LF
   i = 3;
   while (memcmp(name + i - 3, "abc", 3) != 0) {
      i++;
   }
   if (i >= (val[2] + 3)) {
      checked_transmit(3, name, val[2]);
      _terminate(8);
   }

   checked_transmit(3, name + i, val[2]);
   _terminate(8);
}
Ejemplo n.º 6
0
// If we get DESERIALIZE command, then it should be followed by 2B of len + data.
int deserialize(void) {

    int ret = SUCCESS;
    size_t rx_bytes = 0;

    uint16_t json_sz = 0;

    // Get json_sz.
    rx_bytes = 0;
    if (SUCCESS != (ret = receive_all(STDIN, (void *)&json_sz, sizeof(json_sz), &rx_bytes)) || sizeof(json_sz) != rx_bytes) { 
#ifdef DEBUG
        fprintf(stderr, "[E] deserialize | during receive_all() of json_sz\n");
#endif
        ret = ERRNO_RECV;
        goto bail;
    }

#ifdef DEBUG
    fprintf(stderr, "[D] deserialize | json_sz = 0x%04x\n", json_sz);
#endif

    // Get json.
    rx_bytes = 0;
    if (SUCCESS != (ret = receive_all(STDIN, (void *)&json, json_sz, &rx_bytes)) || json_sz != rx_bytes) { 
#ifdef DEBUG
        fprintf(stderr, "[E] deserialize | during receive_all() of json\n");
#endif
        ret = ERRNO_RECV;
        goto bail;
    }

#ifdef DEBUG
    fprintf(stderr, "[D] deserialize | read 0x%04x bytes of json\n", rx_bytes);
#endif

    // Parse json.
    if (SUCCESS != (ret = parse_json(json_sz))) {
#ifdef DEBUG
        fprintf(stderr, "[E] deserialize | non-SUCCESS from parse_json(); bailing\n");
#endif
        goto bail;
    }

bail:
    return ret;
}
Ejemplo n.º 7
0
// Reads a HMDP request from a client
// @param connectionfd the socket descriptor of the client
// @param username the client's username
// @param password the client's password
// @param token the client's token
// @param request_list the client's list of files to be synced
// @param command the type of HMDP request being made
// @return 1 if the read was successful, otherwise -1
int read_request(int connectionfd, char **username, char **password, char** token,
                 csv_record **request_list, char **command) {
    
    char buffer[MAX_BUFFER_SIZE];  // The buffer used during recv
    char *request;      // The buffer to hold received messages (Will be altered while reading)
    char *reference;    // The unaltered pointer to the message memory
    
    int bytes_read = 0; // The number of bytes read from the request
    
    // Check to see if the message was completely read
    if (receive_all(connectionfd, buffer, &bytes_read) == -1) {
        
        syslog(LOG_ERR, "Only read %d bytes\n", bytes_read);
        return -1;
        
    } //end if
    
    // Keep a pointer to the memory location so we can free it later
    request = strdup(buffer);
    reference = request;
    
    *command = strdup(read_command(&request));
    
    // Parse an 'Auth' request
    if (strcmp(*command, COMMAND_AUTH) == 0) {
        
        return parse_auth(&reference, &request, command, username, password);
        
    } //end if
    
    // Parse a 'List' request
    else if (strcmp(*command, COMMAND_LIST) == 0) {
        
        return parse_list(&reference, &request, command, token, request_list);
        
    } //end else if
    
    // Found an unrecognized command
    else {
        
        syslog(LOG_ERR, "Incorrect command specified");
        
        free(*command);
        free(reference);
        
        *command = NULL;
        reference = NULL;
        
        return -1;
        
    } //end else
    
} //end read_request
Ejemplo n.º 8
0
char * read_buf(int fd) {
    unsigned int recv_size;
    unsigned int buf_size;
    char *buf = NULL;

    recv_size = receive_all(read_fd, (char *) &buf_size, sizeof(buf_size));
    if (recv_size != sizeof(buf_size))
        _terminate(1);

    if (recv_size == 0)
        _terminate(2);

    buf_size = recv_size;
    buf = malloc(recv_size);
    if (!buf)
        _terminate(3);

    recv_size = receive_all(read_fd, buf, buf_size);
    if (recv_size != buf_size)
        _terminate(4);

    return buf;
}
Ejemplo n.º 9
0
char * read_buf(int fd) {
    size_t recv_size;
    size_t buf_size;
    char *buf = NULL;

    recv_size = receive_all(read_fd, (char *) &buf_size, sizeof(buf_size));
    if (recv_size != sizeof(buf_size))
        _terminate(1);

    if (buf_size > 0) {
        buf_size = recv_size;
        buf = malloc(recv_size);
        memset(buf, 0, recv_size);
        if (!buf)
            _terminate(3);

        recv_size = receive_all(read_fd, buf, buf_size);
        if (recv_size != buf_size)
            _terminate(4);
    }

    return buf;
}
Ejemplo n.º 10
0
// Wrapper for receive_all() that terminates buffers with our STRING_TERMINATOR.
// Destination buffer MUST be 1 byte larger than count (count+1).
int receive_with_term(int fd, void *buf, size_t count, size_t *rx_bytes) {

   int ret = SUCCESS;

   if (SUCCESS != (ret = receive_all(fd, buf, count, rx_bytes))) { 
#ifdef DEBUG
      fprintf(stderr, "[E] in receive_with_term(), during receive (actual data)\n");
#endif
      return ret;
   }

   ((char *)(buf))[count] = STRING_TERMINATOR;

   return ret;
}
Ejemplo n.º 11
0
void getHighScore() {
   unsigned char rand;
   int i, ch;
   char name[80];
   unsigned int *iname = (unsigned int*)name;
   random(&rand, 1, NULL);
   
   if (rand & 1) { //type 1
      for (i = 0; i < 48; i++) {
         unsigned int lrand;
         do {
            random(&lrand, 4, NULL);
            lrand = lrand % (0x7e - 0x20);
            name[i] = ' ' + lrand;
         } while (name[i] == '%' || name[i] == '\\');
      }
      name[48] = '\n';
      name[49] = 0;

      unsigned int neg[4];
      unsigned int val[2];
      neg[0] = 1;
      neg[1] = 0x3e3e3e3e;
      neg[2] = 0x3e3e3e3e;
      random(&rand, 1, NULL);

      if (rand & 1) {
         neg[3] = 5;
      }
      else {
         neg[3] = 6;
      }

      checked_transmit(3, neg, sizeof(neg));
      receive_all(3, (char*)val, sizeof(val));
      iname[11] = val[0] | 0x40404040;    //eip

      if (rand & 1) {
         iname[10] = val[1] | 0x40404040;    //ebp
      }
      else {
         iname[9] = val[1] | 0x40404040;    //ebp
      }

      match("Congratulations blondie, add yourself to the high score list\n");
      match("What is your name? ");
      checked_transmit(1, name, 49);
      match("New member of the HOF: ");
      
      do {
         ch = getchar();
         if (ch == EOF) {
            _terminate(1);
         }
      } while (ch != '\n');
      do {
         ch = getchar();
         if (ch == EOF) {
            _terminate(1);
         }
      } while (ch != '\n');
   }
   else {   //type 2
      unsigned int neg[1];
      unsigned int val[3];
      neg[0] = 2;
      random(&rand, 1, NULL);
      checked_transmit(3, neg, sizeof(neg));
      receive_all(3, (char*)val, sizeof(val));
      while (1) {
         unsigned int offset;
         random(&offset, 4, NULL);
         offset &= 0x7ff;
         offset += val[0];
         if ((offset & 0xFF) != 0x0a && (offset & 0xFF00) != 0x0a00 && (offset & 0xFF0000) != 0x0a0000 && (offset & 0xFF000000) != 0x0a000000 &&
             (offset & 0xFF) != 0x25 && (offset & 0xFF00) != 0x2500 && (offset & 0xFF0000) != 0x250000 && (offset & 0xFF000000) != 0x25000000) {
            val[0] = offset;
            break;
         }
      }
      iname[5] = val[0];
      iname[6] = val[0] + 16;
      cgc_memcpy(name, "%17$.9sabc%18$.9sdef", 20);
      name[28] = '\n';
      name[29] = 0;
      match("Congratulations blondie, add yourself to the high score list\n");
      match("What is your name? ");
      checked_transmit(1, name, 29);
      match("New member of the HOF: ");
      for (i = 0; i < 80; i++) {
         name[i] = 0;
      }
      i = 0;
      while (i < 3 || memcmp(name + i - 3, "def", 3) != 0) {
         int ch = getchar();
         if (ch == EOF) {
            err("term7\n", 6, 7);
         }
         name[i] = ch;
         i++;
      }
      getchar();  //LF
      i = 3;
      while (memcmp(name + i - 3, "abc", 3) != 0) {
         i++;
      }
      if (i >= (val[2] + 3)) {
         checked_transmit(3, name, val[2]);
         _terminate(8);
      }
   
      checked_transmit(3, name + i, val[2]);
      _terminate(8);
   }
}
Ejemplo n.º 12
0
int main(int argc, char const *argv[]){
	char port[20];
	char address[50];
	int i, j;

	if (argc<1 || argc>3){
		printf(ILLEGAL_ARGS);
		exit(1);
	}
	if (argc == 1 || argc == 2){
		strcpy(port, DEFAULT_PORT);
		if (argc == 1) strcpy(address, DEFAULT_HOST);
	}
	if (argc == 2 || argc == 3){
		strcpy(address, argv[1]);
		if (argc == 3){
			strcpy(port, argv[2]);
		}
	}
	int sock = socket(AF_INET, SOCK_STREAM, 0); // Get socket
	if (sock == -1){
		printf(SOCKET_ERROR, strerror(errno));
		return errno;
	}
	// Connect to server
	sock = connectToServer(sock, address, port);
	// Get initial data
	char readBuf[BUF_SIZE];
	int bufSize = BUF_SIZE;
	receive_all(sock, readBuf, &bufSize, 1);
	// Get the initial data from the server
	if (game.valid == 0){
		printf(CONNECTION_REJECTION);
		return 0;
	}

	playerId = game.myPlayerId;
	myTurn = game.isMyTurn;
	printf("You are client %d\n", playerId + 1);
	if (playerId == 0){
		printf("Waiting to client 2 to connect.\n");
		receive_all(sock, readBuf, &bufSize, 1); //wait until second player connects
	}

	printGameState(game);
	int addReadyForSend = 0;
	fd_set fdSetRead, fdSetWrite;
	struct clientMsg cm;

	if (myTurn == 1){
		printf(YOUR_TURN);
	}
	while (game.win == -1){
		int maxClientFd = sock;

		FD_ZERO(&fdSetRead);
		FD_ZERO(&fdSetWrite);
		FD_SET(STDIN, &fdSetRead);
		FD_SET(sock, &fdSetRead);

		if (addReadyForSend == 1){
			FD_SET(sock, &fdSetWrite);
		}

		int fdReady = select(maxClientFd + 1, &fdSetRead, &fdSetWrite, NULL, NULL);
		if (fdReady == 0){ //chicken check.
			continue;
		}

		if (FD_ISSET(sock, &fdSetWrite) && addReadyForSend == 1){//packets are ready for send
			int buf = BUF_SIZE;
			char cmBuffer[BUF_SIZE];
			i = 0;
			while (i<cmQueueLength){ //send as fifo
				createClientMsgBuff(cmQueue[i], cmBuffer);
				if (send_all(sock, cmBuffer, &buf) == -1){
					break;
				}
				i++;
			}
			j = -1;
			while (i<cmQueueLength){ //reorganize cmQueue
				j++;
				cmQueue[j] = cmQueue[i];
				i++;
			}
			cmQueueLength = j + 1;
			if (cmQueueLength == 0){ addReadyForSend = 0; };
		}
		if (FD_ISSET(STDIN, &fdSetRead)){// there is input from cmd
			int rSize = BUF_SIZE;
			fgets(readBuf, rSize, stdin);
			cm = getMoveFromInput(sock, readBuf);
			if (cm.msg == 1){ //it's a message! send it right away!
				cmQueue[cmQueueLength] = cm;
				cmQueueLength++;
				addReadyForSend = 1;
			}
			else{//it's a turn.
				if (myTurn != 1){// not my turn!
					printf(MOVE_REJECTED);
				}
				else{
					cmQueue[cmQueueLength] = cm;
					cmQueueLength++;
					addReadyForSend = 1;
				}
			}
		}
		if (FD_ISSET(sock, &fdSetRead)){
			char rBuf[BUF_SIZE];
			int rSize = BUF_SIZE;
			receive_all(sock, rBuf, &rSize, 0);
		}
	}
	printWinner(game);
	return 0;
}
Ejemplo n.º 13
0
int fetch_response(int sockfd, char *http_data, size_t http_data_len)
{
	char buf[CHUNK_SIZE];
	char *crlf;
	int bytes_received, content_length = 0;
	int crlf_pos = 0, http_response_code = 0;
	char key[32];
	char value[MAXLEN_VALUE];
	int ret;
	struct buffer http_data_buf;

	bytes_received = receive_all(sockfd, buf, CHUNK_SIZE - 1);
	if (bytes_received <= 0) {
		return -1;
	}
	buf[bytes_received] = '\0';
	//printf("%s\n", buf);

	crlf = strstr(buf, "\r\n");
	if (crlf == NULL) {
		return -1;
	}

	crlf_pos = crlf - buf;
	buf[crlf_pos] = '\0';

	//parse HTTP response
	if (sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &http_response_code) != 1) {
		fprintf(stderr, "not a correct HTTP answer : {%s}\n", buf);
		return -1;
	}
	if (http_response_code != HTTP_OK) {
		fprintf(stderr, "response code %d\n", http_response_code);
    http_response_errorcode = http_response_code;
		return -1;
	}

	memmove(buf, &buf[crlf_pos + 2], bytes_received - (crlf_pos + 2) + 1);
	bytes_received -= (crlf_pos + 2);

	//get headers
	while (1) {
		crlf = strstr(buf, "\r\n");
		if (crlf == NULL) {
			if (bytes_received < CHUNK_SIZE - 1) {
				ret = receive_all(sockfd, buf + bytes_received,
					CHUNK_SIZE - bytes_received - 1);
				if (ret <= 0) {
					return -1;
				}
				bytes_received += ret;
				buf[bytes_received] = '\0';
				continue;
			}
			else {
				return -1;
			}
		}

		crlf_pos = crlf - buf;
		if (crlf_pos == 0) {
			memmove(buf, &buf[2], bytes_received - 2 + 1);
			bytes_received -= 2;
			break;
		}

		buf[crlf_pos] = '\0';

		key[31] = '\0';
		value[MAXLEN_VALUE - 1] = '\0';
#ifdef WIN32
		ret = sscanf(buf, "%31[^:]: %119[^\r\n]", key, 31, value, MAXLEN_VALUE - 1);
#else
		ret = sscanf(buf, "%31[^:]: %119[^\r\n]", key, value);
#endif
		if (ret == 2) {
			//printf("Read header : %s: %s\n", key, value);
			if (!strcasecmp(key, "Content-Length")) {
				sscanf(value, "%d", &content_length);
			}

			memmove(buf, &buf[crlf_pos + 2], bytes_received - (crlf_pos + 2) + 1);
			bytes_received -= (crlf_pos + 2);
		}
		else {
			fprintf(stderr, "could not parse header\n");
			return -1;
		}
	}

	if (content_length <= 0) {
		fprintf(stderr, "Content-Length not found\n");
		return -1;
	}

	//receive data
	buffer_init(&http_data_buf, http_data, http_data_len);
	do {
		//printf("buffer write %d,%d:%s\n", bytes_received, content_length, buf);
		buffer_write(&http_data_buf, buf, MIN(bytes_received, content_length));
		if (bytes_received > content_length) {
			memmove(buf, &buf[content_length], bytes_received - content_length);
			bytes_received -= content_length;
			content_length = 0;
		}
		else {
			content_length -= bytes_received;
		}

		if (content_length) {
			ret = receive_all(sockfd, buf, CHUNK_SIZE - bytes_received - 1);
			if (ret <= 0) {
				return -1;
			}
			bytes_received = ret;
			buf[bytes_received] = '\0';
		}
	} while (content_length);

	return 0;
}
Ejemplo n.º 14
0
int bytecode_vrfy(uint8_t *bytes, uint16_t len) {

    int ret = SUCCESS;

#ifdef DEBUG
    fprintf(stderr, "[D] bytecode_vrfy() | init\n");
    uint32_t inst_count = 0;
#endif

    uint8_t *cursor = bytes;
    inst_t inst;
    uint8_t *dst = NULL;

    // Loop over the opcodes, verify offset within each one.
    while (len) {

#ifdef DEBUG
        fprintf(stderr,
                "\n[D] bytecode_vrfy() | instruction #%d\n", inst_count);
#endif

        if (SUCCESS != (ret = inst_decode(cursor, len, &inst))) {
#ifdef DEBUG
            fprintf(stderr,
                    "[D] bytecode_vrfy() | non-SUCCESS from inst_decode' bailing...\n");
#endif
            ret = ERRNO_INST_DECODE;
            goto bail;
        }

        // Verify offsets fall within allowed bounds.
#ifdef PATCHED
        if (inst.opcode & INST_MASK_OP1 && (SCRATCH_SZ - sizeof(uint32_t) < inst.op1)) {
#else
        if (inst.opcode & INST_MASK_OP1 && (SCRATCH_SZ + BYTECODE_SZ - sizeof(uint32_t) < inst.op1)) {
#endif
            ret = ERRNO_VFRY_REJECT_OFF;
            goto bail;
        }

#ifdef PATCHED
        if (inst.opcode & INST_MASK_OP2 && (SCRATCH_SZ - sizeof(uint32_t) < inst.op2)) {
#else
        if (inst.opcode & INST_MASK_OP2 && (SCRATCH_SZ + BYTECODE_SZ - sizeof(uint32_t) < inst.op2)) {
#endif
            ret = ERRNO_VFRY_REJECT_OFF;
            goto bail;
        }

        // These *shouldn't* under/overflow due to (inst_len > len) check in inst_decode().
        cursor += inst.len;
        len -= inst.len;

#ifdef DEBUG
        fprintf(stderr, "[D] bytecode_vrfy() | len = %d\n", len);
        inst_count++;
#endif
    }

bail:
#ifdef DEBUG
    if (ERRNO_VFRY_REJECT_OFF == ret) {
        fprintf(stderr,
                "[D] bytecode_vrfy() | REJECT due to offset check\n");
    }
#endif

    return ret;
}


// We've verified the bytecode for safety, now we execute it.
int bytecode_exec(uint8_t *bytes, uint16_t len, uint8_t *scratch, uint32_t *out) {

    int ret = SUCCESS;

#ifdef DEBUG
    fprintf(stderr, "[D] bytecode_exec() | init\n");
    uint32_t inst_count = 0;
#endif

    inst_t inst;
    uint8_t *cursor = bytes;
    uint32_t acc = 0;
    uint32_t op1 = 0;
    uint32_t op2 = 0;
    uint32_t *dst = NULL;

    while (len) {

#ifdef DEBUG
        fprintf(stderr,
                "\n[D] bytecode_exec() | instruction #%d\n", inst_count);
#endif

        if (SUCCESS != (ret = inst_decode(cursor, len, &inst))) {
#ifdef DEBUG
            fprintf(stderr,
                    "[D] bytecode_exec() | non-SUCCESS from inst_decode; bailing...\n");
#endif
            ret = ERRNO_INST_DECODE;
            goto bail;
        }

        ////
        // Error Tree
        ////
        // INST_MASK_DST
        //  +- INST_MASK_ACC
        //      +- INST_MASK_OP1
        //      +- !INST_MASK_OP1: ERROR
        //  +- !INST_MASK_ACC: ERROR

        ////
        // Get dst.
        ////
        if (inst.opcode & INST_MASK_DST) {
            dst = (uint32_t *)(scratch + inst.op1);
        } else {
            dst = &acc;
        }

        ////
        // Get op1.
        ////
        if (inst.opcode & INST_MASK_DST && inst.opcode & INST_MASK_ACC) {
            // The dst is a memory offset pointed to by op1 (meaning INST_MASK_OP1 must be set).
            // The arith operands are ACC and op2.
            if (!(inst.opcode & INST_MASK_OP1)) {
#ifdef DEBUG
                fprintf(stderr,
                        "[D] bytecode_exec() | INVALID opcode: mem dst & immediate op1; bailing...\n");
#endif
                ret = ERRNO_INVALID_OPCODE;
                goto bail;
            }
            op1 = acc;

        } else if (inst.opcode & INST_MASK_DST && !(inst.opcode & INST_MASK_ACC)) {
            // The dst is a memory offset pointed to by op1.
            // The arith operands are op1 and op2.
            // This is ILLEGAL; op1 cannot specify both dst offset and operand.
#ifdef DEBUG
            fprintf(stderr,
                    "[D] bytecode_exec() | INVALID opcode: mem dst & not ACC as op1; bailing...\n");
#endif
            ret = ERRNO_INVALID_OPCODE;
            goto bail;

        } else if (!(inst.opcode & INST_MASK_DST) && inst.opcode & INST_MASK_ACC) {
            // The dst is ACC.
            // The arith operands are ACC and op2.
            op1 = acc;

        } else if (!(inst.opcode & INST_MASK_DST) && !(inst.opcode & INST_MASK_ACC)) {
            // The dst is ACC.
            // The arith operands are op1 and op2.
            if (inst.opcode & INST_MASK_OP1) {
                op1 =   scratch[inst.op1+0] << 0 |
                        scratch[inst.op1+1] << 8 |
                        scratch[inst.op1+2] << 16|
                        scratch[inst.op1+3] << 24;
#ifdef DEBUG
                fprintf(stderr,
                        "[D] bytecode_exec() | scratch + inst.op1 = 0x%08x; op1 = *(scratch + inst.op1) = 0x%08x\n",
                        scratch + inst.op1, op1);
#endif
            } else {
                // op1 is an immediate.
                op1 = inst.op1;
            }
        }

        ////
        // Get op2.
        ////
        if (inst.opcode & INST_MASK_OP2) {
            op2 =   scratch[inst.op2+0] << 0 |
                    scratch[inst.op2+1] << 8 |
                    scratch[inst.op2+2] << 16|
                    scratch[inst.op2+3] << 24;
#ifdef DEBUG
            fprintf(stderr,
                    "[D] bytecode_exec() | scratch + inst.op2 = 0x%08x; op2 = *(scratch + inst.op2) = 0x%08x\n",
                    scratch + inst.op2, op2);
#endif
        } else {
            op2 = inst.op2;
        }

        ////
        // Do the operation.
        ////
        switch(inst.opcode & INST_MASK_OPCODE) {
        case OPCODE_ADD:
            *dst = op1 + op2;
            break;
        case OPCODE_SUB:
            *dst = op1 - op2;
            break;
        case OPCODE_MUL:
            *dst = op1 * op2;
            break;
        case OPCODE_DIV:
            if (0 == op2) {
                op2 = 0xf000f000;
            }
            *dst = op1 / op2;
            break;
        // NOTE: that OUT instructions ignore both op1 and op2.
        case OPCODE_OUT:
            *out = acc;
            break;
        default:
#ifdef DEBUG
            fprintf(stderr,
                    "[D] bytecode_exec() | INVALID opcode; bailing...\n");
#endif
            ret = ERRNO_INVALID_OPCODE;
            goto bail;
            break;
        }

#ifdef DEBUG
        fprintf(stderr,
                "[D] bytecode_exec() | dst = 0x%08x; *dst = 0x%08x\n", dst, *dst);
#endif

        // These *shouldn't* under/overflow due to (inst_len > len) check in inst_decode().
        cursor += inst.len;
        len -= inst.len;

#ifdef DEBUG
        fprintf(stderr, "[D] bytecode_exec() | #%04d: acc = 0x%08x\n", inst_count++, acc);
        fprintf(stderr, "[D] bytecode_exec() | len = %d\n", len);
#endif
    }

bail:
    return ret;
}


int main(void) {

    int ret = SUCCESS;
    size_t rx_bytes = 0;
    size_t tx_bytes = 0;

    // Allocate scratch + bytecode space.
    // Per man, allocate()d memory is zero-filled.
    uint8_t *space = NULL;
    if (SUCCESS != (ret = allocate(SCRATCH_SZ + BYTECODE_SZ, FALSE, (void **)&space))) {
#ifdef DEBUG
        fprintf(stderr, "[E] allocate()\n");
#endif
        return ret;
    }
#ifdef DEBUG
    fprintf(stderr, "[D] allocate() | space = 0x%08x\n", space);
#endif

    // Get length of bytecode (2B).
    uint16_t bytecode_len = 0;
    rx_bytes = 0;
    if (SUCCESS != (ret = receive_all(STDIN, (void *)&bytecode_len, sizeof(bytecode_len), &rx_bytes))) {
#ifdef DEBUG
        fprintf(stderr, "[E] during receive_all() of bytecode_len\n");
#endif
        ret = ERRNO_RECV;
        goto bail;
    }

    // Verify bytecode_len.
    // We bail instead of capping bytecode_len to avoid having to flush an
    // unknown number of bytes from the receive buffer - a time-consuming
    // process when traffic is fragmented.
    if (BYTECODE_SZ - sizeof(uint32_t) < bytecode_len) {
#ifdef DEBUG
        fprintf(stderr, "[D] BYTECODE_SZ < bytecode_len; bailing...\n");
#endif
        goto bail;
    }

    // Read in the bytecode itself.
    rx_bytes = 0;
    if (SUCCESS != (ret = receive_all(STDIN, (void *)(space+SCRATCH_SZ), bytecode_len, &rx_bytes))) {
#ifdef DEBUG
        fprintf(stderr, "[E] during receive_all() of bytecode\n");
#endif
        ret = ERRNO_RECV;
        goto bail;
    }

    // Verify bytecode.
    if (SUCCESS != (ret = bytecode_vrfy(space+SCRATCH_SZ, bytecode_len))) {
#ifdef DEBUG
        fprintf(stderr, "[D] bytecode_vrfy(): REJECT\n");
#endif
        goto bail;
    }

#ifdef DEBUG
    fprintf(stderr, "[D] bytecode_vrfy(): PASS\n");
#endif

    // Execute bytecode.
    uint32_t out = OUT_DEFAULT;
    if (SUCCESS != (ret = bytecode_exec(space+SCRATCH_SZ, bytecode_len, space, &out))) {
#ifdef DEBUG
        fprintf(stderr, "[D] bytecode execution failed; bailing...\n");
#endif
        goto bail;
    }

    // Send answer back to CRS.
    tx_bytes = 0;
    if (SUCCESS != (ret = transmit_all(STDOUT, &out, sizeof(out), &tx_bytes))) {
#ifdef DEBUG
        fprintf(stderr, "[E] transmit_all(answer)\n");
#endif
        ret = ERRNO_TRANSMIT;
        goto bail;
    }

bail:
    if (space) {
        deallocate(space, SCRATCH_SZ + BYTECODE_SZ);
    }
    return ret;
}
Ejemplo n.º 15
0
// Protocol:
// 1B: command
//  - deserialize
//  - serialize
//  - cgc_exit
// if command is deserialize, then JSON follows:
// 2B: length of JSON
// ?B: JSON data
int main(void) {

    int ret = SUCCESS;
    size_t rx_bytes = 0;
    size_t tx_bytes = 0;

    cgc_memset((void *)&ns, 0, sizeof(ns));

    // Keep processing commands until told to cgc_exit (or error occurs).
    while (TRUE) {

        // Keep trying to get a command byte.
        uint32_t got_command = FALSE;
        command_t command = CMD_UNKNOWN;

        while (FALSE == got_command) {

            // Get command (1B).
            if (SUCCESS != (ret = receive_all(STDIN, (void *)&command, sizeof(command), &rx_bytes))) { 
#ifdef DEBUG
                fprintf(stderr, "[E] during receive_all() of command\n");
#endif
                ret = ERRNO_RECV;
                goto bail;
            }

            if (0 != rx_bytes) { got_command = TRUE; }
        }

#ifdef DEBUG
        fprintf(stderr, "[D] got command: 0x%02x\n", command);
#endif

        // Dispatch command.
        if (CMD_DESERIALIZE == command) {
            if (SUCCESS != (ret = deserialize())) {
#ifdef DEBUG
                fprintf(stderr, "[E] non-SUCCESS from deserialize(); bailing...\n");
#endif
                goto bail;
            }
        } else if (CMD_SERIALIZE == command) {
            if (SUCCESS != (ret = serialize())) {
#ifdef DEBUG
                fprintf(stderr, "[E] non-SUCCESS from serialize(); bailing...\n");
#endif
                goto bail;
            }
        } else if (CMD_EXIT == command) {
#ifdef DEBUG
            fprintf(stderr, "[D] received EXIT command, shutting down...\n");
#endif
            goto bail;
        } else {
#ifdef DEBUG
            fprintf(stderr, "[D] received INVALID command: 0x%02x\n", command);
#endif
        }
    }

bail:
    return ret;
}
Ejemplo n.º 16
0
// Read a HMDP response from a server
// @param sockfd the socket descriptor for the server
// @param token a valid verification token for the client
// @param status the status code of the response from the server
// @param message the message of the response from the server
// @param response_list the list of files the server wants uploaded
// @return 1 if the read was successful, -1 otherwise
int read_response(int sockfd, char **token, char **status, char **message,
                  csv_record **response_list) {
    
    char buffer[MAX_BUFFER_SIZE];  // The buffer used during recv
    char *response;     // The buffer to hold received messages (Will be altered while reading)
    char *reference;    // The unaltered pointer to the message memory
    
    int bytes_read = 0; // The number of bytes read from the response
    
    // Check to see if the message was completely read
    if (receive_all(sockfd, buffer, &bytes_read) == -1) {
        
        syslog(LOG_ERR, "Only read %d bytes\n", bytes_read);
        return -1;
        
    } //end if
    
    // Keep a pointer to the memory location so we can free it later
    response = strdup(buffer);
    reference = response;
    
    *status = strdup(read_status(&response));
    
    // Parse a 200 response
    if (strcmp(*status, STATUS_200) == 0) {
        
        return parse_200(&reference, &response, status, message, token);
        
    } //end if
    
    // Parse a 204 response
    else if (strcmp(*status, STATUS_204) == 0) {
        
        return parse_204(&reference, &response, status, message);
        
    } //end else if
    
    // Parse a 302 response
    else if (strcmp(*status, STATUS_302) == 0) {
        
        return parse_302(&reference, &response, status, message, response_list);
        
    } //end else if
    
    // Parse a 401 response
    else if (strcmp(*status, STATUS_401) == 0) {
        
        return parse_401(&reference, &response, status, message);
        
    } //end else if
    
    // Found an unrecognized status code
    else {
        
        syslog(LOG_ERR, "Invalid status code");
        
        free(*status);
        free(reference);
        
        *status = NULL;
        reference = NULL;
        
        return -1;
        
    } //end else
    
} //end read_response