Example #1
0
File: bus.c Project: uselessd/bus
/**
 * Open an existing bus
 * 
 * @param   bus    Bus information to fill
 * @param   file   The filename of the bus
 * @param   flags  `BUS_RDONLY`, `BUS_WRONLY` or `BUS_RDWR`
 *                 any negative value is used internally
 *                 for telling the function to not actually
 *                 opening the bus, but just to parse the file
 * @return         0 on success, -1 on error
 */
int
bus_open(bus_t *bus, const char *file, int flags)
{
	int saved_errno;
	char *line = NULL;
	size_t len = 0;
	FILE *f;

	bus->sem_id = -1;
	bus->key_sem = -1;
	bus->key_shm = -1;
	bus->message = NULL;

	f = fopen(file, "r");

	t(getline(&line, &len, f));
	t(bus->key_sem = (key_t)atoll(line));
	free(line), line = NULL, len = 0;

	t(getline(&line, &len, f));
	t(bus->key_shm = (key_t)atoll(line));
	free(line), line = NULL;

	fclose(f);

	if (flags >= 0) {
		t(open_semaphores(bus));
		t(open_shared_memory(bus, flags));
	}
	return 0;
fail:
	saved_errno = errno;
	free(line);
	errno = saved_errno;
	return -1;
}
Example #2
0
int main(int argc, char** argv)
{
	if (argc < 2) {
		fprintf(stderr, "Too few arguments given to server.\n./server N\n");
		exit(EXIT_FAILURE);
	}
	
	int server_id = atoi(argv[1]);
	pdecryptf_t decrypt = choose_decryption(server_id);
	
	char mq_name[13];
	sprintf(mq_name, "/mq_server_%d", server_id);
	mqd_t mq = open_msg_queue(mq_name);
	
	Command cmd;
    int ret = receive_command(mq, &cmd);
    if (ret == -1)
    	exit(EXIT_FAILURE);
    Command *command = &cmd;
	
	mqd_t ret_mq;
	while(strcmp(command->name, "exit") != 0) {
		
		//open shared memory
		char* shm_name = command->name;
		int shm_size = command->dim;
		int shm_fd;
		void* mem = open_shared_memory(shm_name, shm_size, &shm_fd);
		if (mem == NULL) {
			exit(EXIT_FAILURE);
		}
		
		// get size of the message from the first 
		// integer in the shared memory
		int dim_message;
		memcpy(&dim_message, mem, sizeof(int));
		
		// decrypt message
		void* out = malloc(1000);
		int decrypt_size = decrypt(mem+sizeof(int), dim_message, out);
		
		// copy result back in shared memory
		memcpy(mem, &decrypt_size, sizeof(int));
		memcpy(mem + sizeof(int), out, decrypt_size);
		
		// Close shared memory
		close_shared_memory(mem, shm_size, shm_fd, shm_name);
		
		// Send message back to gateway with self removed
		int i;
		for (i = 1; i < 17; i++)
			command->crypt[i-1] = command->crypt[i]; 
		ret_mq = open_msg_queue(MQ_GATEWAY);
		ret = send_command(ret_mq, command);
		if (ret == -1)
    		exit(EXIT_FAILURE);
		mq_close(ret_mq);
		
		// Get another message from the mq
		ret = receive_command(mq, command);
		if (ret == -1)
    		exit(EXIT_FAILURE);
	}
	mq_close(mq);
	mq_close(ret_mq);
    return 0;
}