TextEncoder *TextEncoder_New(int max_mbchars, int (*fn_encode)(wchar_t, unsigned char *, int)) {
  TextEncoder *ter;
  ter = (TextEncoder *)MALLOC(sizeof(TextEncoder));
  if( ter == NULL ) {
    print_perror("malloc");
    return NULL;
  }
  ter->mbchars = NULL;
  ter->mb_buff = NULL;
  ter->fn_encode = NULL;

  ter->mb_buff = DataList_New(4096, sizeof(unsigned char));
  if( ter->mb_buff == NULL ) {
    TextEncoder_Free(ter);
    return NULL;
  }

  ter->max_mbchars = max_mbchars;
  ter->mbchars = (unsigned char *)MALLOC(sizeof(unsigned char) * (max_mbchars + 1));
  if( ter->mbchars == NULL ) {
    print_perror("malloc");
    TextEncoder_Free(ter);
    return NULL;
  }
  ter->fn_encode = fn_encode;
  return ter;
}
Exemple #2
0
int state_key_generate(state *s)
{
	unsigned char entropy_pool[1024]; /* 160 + 8032 bits */

	const int real_random = 20;
	const int pseudo_random = sizeof(entropy_pool) - real_random;

	const int salt = s->flags & FLAG_SALTED;

	/* TODO: It's almost certain that it's better To read whole
	 * key from dev/random instead of this weird splitting.
	 */

	/* Gather entropy from random + urandom to speed things up... */
	if (crypto_file_rng("/dev/random", NULL,
		    entropy_pool, real_random) != 0)
	{
		print_perror(PRINT_ERROR, "Unable to open /dev/random");
		return 1;
	}

	if (crypto_file_rng("/dev/urandom", NULL,
		    entropy_pool+real_random, pseudo_random) != 0)
	{
		print_perror(PRINT_ERROR, "Unable to open /dev/random");
		return 1;
	}

	if (salt == 0) {
		crypto_sha256(entropy_pool, sizeof(entropy_pool), s->sequence_key);
		memset(entropy_pool, 0, sizeof(entropy_pool));

		s->counter = num_i(0);
		s->latest_card = num_i(0);

		s->flags &= ~(FLAG_SALTED); 
	} else {
		unsigned char cnt_bin[32] = {'\0'};

		/* Use half of entropy to generate key */
		crypto_sha256(entropy_pool, sizeof(entropy_pool)/2, s->sequence_key);

		/* And half to initialize counter */
		crypto_sha256(entropy_pool + sizeof(entropy_pool)/2, sizeof(entropy_pool)/2, cnt_bin);
		num_import(&s->counter, (char *)cnt_bin, NUM_FORMAT_BIN);
		s->counter = num_and(s->counter, s->salt_mask);
		s->latest_card = num_i(0);

		memset(entropy_pool, 0, sizeof(entropy_pool));
		memset(cnt_bin, 0, sizeof(cnt_bin));

		s->flags |= FLAG_SALTED;
	}

	s->new_key = 1;
	return 0;
}
static bool    	get_logfile(char ** logfile)
{
  char *	home;

  if (!(home = getenv("HOME")))
    return (print_perror(false, "getenv"));
  if (!(*logfile = strdupcat(home, LOGFILE)))
    return (print_perror(false, "malloc"));
  return (true);
}
JsonParser *JsonParser_New(TextEncoding *te) {
  JsonParser *jpsr;

  jpsr = (JsonParser *)MALLOC(sizeof(JsonParser));
  if( jpsr == NULL ) {
    print_perror("malloc");
    return NULL;
  }

  jpsr->jsonpull = NULL;
  jpsr->node = NULL;
  jpsr->stack = NULL;

  if( te == NULL ) {
    te = TextEncoding_New_UTF8();
    jpsr->jsonpull = JsonPull_New(te);
    TextEncoding_Free(te);
  }
  else {
    jpsr->jsonpull = JsonPull_New(te);
  }

  if( jpsr->jsonpull == NULL ) {
    JsonParser_Free(jpsr);
    return NULL;
  }

  jpsr->stack = DataList_New(16, sizeof(JsonNode **));
  if( jpsr->stack == NULL ) {
    JsonParser_Free(jpsr);
    return NULL;
  }

  return jpsr;
}
t_sock		tcp_sock_create(void)
{
  t_sock	sock;

  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
      print_perror("failed to create socket");
      return (-1);
    }
  return (sock);
}
t_list		*list_create()
{
  t_list	*tmp;

  if (!(tmp = malloc(sizeof(t_list))))
    print_perror("failed to allocate new list");
  tmp->size = 0;
  tmp->nodes = NULL;
  tmp->last = NULL;
  return (tmp);
}
DataListCell *DataListCell_New(int bytes) {
  DataListCell *datalistcell;
  datalistcell = (DataListCell *)MALLOC(sizeof(DataListCell)+bytes);
  if( datalistcell == NULL ) {
    print_perror("malloc");
    return NULL;
  }
  datalistcell->body = (char *)datalistcell + sizeof(DataListCell);
  datalistcell->prev = NULL;
  datalistcell->next = NULL;
  return datalistcell;
}
bool		init_db0chrono(t_db0chrono * c)
{
  int		fd;
  int		r;

  c_global = c;
  if (!get_logfile(&(c->logfile)))
    return (false);
  if (!access(c->logfile, F_OK))
    {
      if ((fd = open(c->logfile, O_RDONLY)) == ERR_OPEN)
	return (print_perror(false, "open"));
      if ((r = read(fd, c->time.buf, sizeof(int))) == ERR_READ)
	return (print_perror(false, "read"));
      close(fd);
    }
  if ((signal(SIGINT, update_signal) == SIG_ERR)
      || (signal(SIGQUIT, update_signal) == SIG_ERR))
    return (print_perror(false, "signal"));
  return (true);
}
int	injectbuf_write(t_injectbuf *buf, int fd)
{
  int	len;

  if ((len = write(fd, &buf->data[buf->head], buf->len)) == -1)
    {
      print_perror("failed to write buffer");
      return (-1);
    }
  buf->head += len;
  buf->len -= len;
  return (len);
}
static bool	tcp_sock_set_reusable(t_sock *sock, bool reusable)
{
  int		optVal;

  optVal = (reusable ? 1 : 0);
  if (setsockopt(*sock, SOL_SOCKET, SO_REUSEADDR,
		 (void *)&optVal, sizeof(optVal)) == -1)
    {
      close(*sock);
      print_perror("failed to set socket reusability");
      return (false);
    }
  return (true);
}
/*
** These functions are callable in two different ways
** depending on what the first argument is :
**   - a pointer to t_sock returned by tcp_sock_create()
**   - a pointer to a t_sock set to -1
**
** If the socket received as argument was not a
** pre-created socket then these functions will create one
** before initializing it and storing it in the pointer.
**
** Also, if either of theses functions fail, the socket will
** be closed and no longer valid.
*/
bool			tcp_sock_passive_init(t_sock *sock, int port,
					      int nbClients)
{
  struct sockaddr_in	sock_addr;

  if ((*sock == -1 && (*sock = tcp_sock_create()) == -1)
      || tcp_sock_get_addr(&sock_addr, INADDR_ANY, port) == NULL)
    return (false);
  if (bind(*sock, (const struct sockaddr *)&sock_addr,
	   sizeof(sock_addr)) == -1)
    {
      close(*sock);
      return (print_perror("failed to bind socket to address"));
    }
  if (tcp_sock_set_reusable(sock, true) == false)
    return (false);
  if (nbClients == 0 || listen(*sock, nbClients) == -1)
    {
      close(*sock);
      return (print_perror("failed to set socket as passive"));
    }
  return (true);
}
t_egg	*egg_create(int id, t_team *team)
{
  t_egg	*egg;

  if (!(egg = malloc(sizeof(t_egg))))
    {
      print_perror("failed to allocate new egg");
      return (NULL);
    }
  egg->is_hatches = false;
  egg->event_handler = &egg_event_handler;
  egg->id = id;
  egg->team = team;
  return (egg);
}
t_graphic	*graphic_create(t_client *client)
{
  t_graphic	*new_graph;

  if ((new_graph = malloc(sizeof(*new_graph))) == NULL)
    {
      print_perror("failed to create new graphic handle");
      return (NULL);
    }
  new_graph->receive = &graphic_receive;
  new_graph->destroy = &graphic_destroy;
  new_graph->client = client;
  list_push_back(&g_server.graphic_manager.graphic_handlers, new_graph);
  graphic_connexion(new_graph);
  return (new_graph);
}
Exemple #14
0
t_event		*event_create(t_event_handler *data, t_pl_func func,
			      long double timestamp, void *arg)
{
  t_event	*event;

  if ((event = malloc(sizeof(*event))) == NULL)
    {
      print_perror("failed to allocate new event");
      return (NULL);
    }
  event->data = data;
  event->func = func;
  event->timestamp = timestamp;
  event->arg = (arg ? strdup(arg) : NULL);
  return (event);
}
bool			tcp_sock_active_init(t_sock *sock, char *host,
					     int port)
{
  struct sockaddr_in	sock_addr;

  if ((*sock == -1 && (*sock = tcp_sock_create()) == -1)
      || tcp_sock_get_addr(&sock_addr, inet_addr(host), port) == NULL)
    return (false);
  if (connect(*sock, (const struct sockaddr *)&sock_addr,
	      sizeof(sock_addr)) == -1)
    {
      close(*sock);
      return (print_perror("socket connection failed"));
    }
  return (true);
}
static bool	check_fd_set(t_sockpool *pool, t_sockpool_node *node,
			     fd_set *fds, int (*action)(t_sockpool_node *))
{
  int		rc;

  if (FD_ISSET(node->socket, fds))
    {
      --pool->nbset;
      if ((rc = action(node)) <= 0)
	{
	  if (rc == -1)
	    print_perror("network I/O error");
	  client_shutdown(node);
	  return (false);
	}
    }
  return (true);
}
/**
 * Constructs New DataList
 * @param cell_elements Element count in one cell.
 * @param element_bytes Bytes in one element.
 * @return New DataList instance. If malloc error occurres, returns NULL.
 */
DataList *DataList_New(int cell_elements, int element_bytes) {
  DataList *datalist;
  datalist = (DataList *)MALLOC(sizeof(DataList));
  if( datalist == NULL ) {
    print_perror("malloc");
    return NULL;
  }
  datalist->cell_elements = cell_elements;
  datalist->element_bytes = element_bytes;
  datalist->length = 0;
  datalist->head = DataListCell_New(datalist->cell_elements * datalist->element_bytes);
  if( datalist->head == NULL ) {
    FREE(datalist);
    return NULL;
  }
  datalist->tail = datalist->head;
  datalist->hix = 0;
  datalist->tix = 0;
  return datalist;
}
bool	graphic_bct2(t_graphic *graphic, void *arg1, void *arg2)
{
  char	*answer;
  bool	success;
  uint	x;
  uint	y;
  uint	*res;

  x = *((uint *)arg1);
  y = *((uint *)arg2);
  res = g_server.world.cell[(x + (y * gs_get_map_width()))].res;
  if (asprintf(&answer, "bct %u %u %u %u %u %u %u %u %u", x, y, res[0],
	       res[1], res[2], res[3], res[4], res[5], res[6]) == -1)
    {
      graphic_smg_KO(graphic);
      return (print_perror("fail to allocate new graphic message"));
    }
  success = client_write_to(graphic->client, answer);
  free(answer);
  return (success);
}
Exemple #19
0
bool	graphic_bct(t_graphic *graphic, char *cmd)
{
  uint	x;
  uint	y;
  bool	success;
  char	*answer;
  uint	*res;

  if (!get_position(cmd, &x, &y))
    return (error_type_sbp(graphic, cmd));
  if (x >= gs_get_map_width() || y >= gs_get_map_height())
    return (error_type_sbp(graphic, cmd));
  res = g_server.world.cell[(x + (y * gs_get_map_width()))].res;
  if (asprintf(&answer, "bct %u %u %u %u %u %u %u %u %u", x, y, res[0],
	       res[1], res[2], res[3], res[4], res[5], res[6]) == -1)
    {
      graphic_smg_KO(graphic);
      return (print_perror("fail to allocate new graphic message"));
    }
  success = client_write_to(graphic->client, answer);
  free(answer);
  return (success);
}
Exemple #20
0
void *memory_set(void *info)
{
	DEBUG_PRINT("notice: memory_set\n");
	int val_len = 0;
	int val_differs = 1; // if the values are the same
	store_entry *entry = NULL;
	store_db *db = NULL;

	// extract information from our info variable
	char *key = ((struct entry_inf *) info)->key;
	char *value = ((struct entry_inf *) info)->value;
	char *db_name = ((struct entry_inf *) info)->db_name;
	store_db **dbs = ((struct entry_inf *) info)->dbs;
	int *error = &(((struct entry_inf *) info)->error);

	// we shouldn't write while reading/writing
	write_lock();
	
	// locate our db and find our entry
	db = locate_db(db_name, *dbs);

	// create our db if it doesn't exist
	if(db == NULL)
	{
		DEBUG_PRINT("notice: db \"%s\" %p not found, creating...\n", db_name, dbs);
		db = create_db(db_name, dbs);
	}

	// error allocating data while creating the db?
	if(db == NULL)
	{
		perror("create_db");
		*error = ERR_ALLOC;
	}
	// are we unsetting an entry?
	else if(value[0] == '\0')
	{
		// we don't wan't to give any error if entry was not found
		delete_entry(key, db);
	}
	else
	{
		entry = locate_entry(key, db);

		// no value size limit?
		if(MAX_VAL_SIZE <= 0)
		{
			val_len = strlen(value) + 1;
		}
		// if we have set a value limit, apply it
		else
		{
			val_len = (size_t) min((int) strlen(value) + 1, MAX_VAL_SIZE);
		}

		// did we find an entry?
		if(entry != NULL)
		{
			if(0 == strncmp(value, entry->val, val_len))
			{
				DEBUG_PRINT("notice: %s: values are equal\n", db_name);
				val_differs = 0;
			}
			else
			{
				// if the value has changed, free the previous one
				free(entry->val);
				entry->val = NULL;
			}
		}
		// if we didn't, create a new one
		else
		{
			entry = create_entry(key, db);

			if(entry == NULL)
			{
				print_perror("create_entry");
				*error = ERR_ALLOC;
			}
		}

		if(*error == ERR_NONE)
		{
			// reserve space for our value as long as it was not the same
			if(val_differs)
			{
				entry->val = (char *) malloc(val_len * sizeof(char));
				
				if(entry->val == NULL)
				{
					print_perror("malloc");
					*error = ERR_ALLOC;
				}
				else
				{
					strncpy(entry->val, value, val_len);
					entry->val[val_len - 1] = '\0';
				}
			}

			DEBUG_PRINT("notice: \"%s\": setting \"%s\"=\"%s\" (\"%d\"B) DONE\n",
			            db_name, entry->key, entry->val, val_len);

			// save the entry to our info variable (as output)
			((struct entry_inf *) info)->entry = entry;

			#ifdef __DEBUG__
			print_store_tree(dbs);
			#endif
		}
	}

	// done!
	write_unlock();
	
	DEBUG_PRINT("notice: memory_set returning thread error %d\n", *error);
	pthread_exit(NULL);
}
Exemple #21
0
void *memory_get(void *info)
{
	DEBUG_PRINT("notice: memory_get\n");
	store_entry *ent = NULL;

	// extract information from our info variable
	char *key = ((struct entry_inf *) info)->key;
	char *value = NULL;
	char *db_name = ((struct entry_inf *) info)->db_name;
	store_db *dbs = *(((struct entry_inf *) info)->dbs);
	store_db *db = NULL;
	int *error = &(((struct entry_inf *) info)->error);

	// we have a limit of max readers at once
	read_lock();

	DEBUG_PRINT("notice: locating db %s in dbs %p\n", db_name, dbs);

	// locate our db and find our entry
	if(NULL == (db = locate_db(db_name, dbs)))
	{
		*error = ERR_DB;
	}
	else if(NULL == (ent = locate_entry(key, db)))
	{
		*error = ERR_ENTRY;
	}
	else if(NULL == (value = (char *) malloc((strlen(ent->val) + 1)
	                                         * sizeof(char))))
	{
		print_perror("malloc");
		*error = ERR_ALLOC;
	}
	else
	{
		DEBUG_PRINT("notice: getting from db \"%s\" key \"%s\"\n",
		            db->name, ((store_entry *) ent)->key);

		// get the value from the db
		// write semaphore not needed because the entry_info is not shared
		strcpy(value, ent->val);

		DEBUG_PRINT("notice: %s: got \"%s\"=\"%s\"\n", db_name, key, value);
		
		// save the entry and value to our info variable (as output)
		((struct entry_inf *) info)->entry = ent;
		((struct entry_inf *) info)->value = value;

		#ifdef __DEBUG__
		print_store_tree(&dbs);

		if(ent != NULL)
		{
			DEBUG_PRINT("\nnotice: %s: got entry %p \"%s\"=\"%s\"\n\n",
			            db_name, ent, ent->key, ent->val);
		}
		else
		{
			DEBUG_PRINT("\nnotice: %s: entry \"%s\" *NOT FOUND* \n\n",
			            db_name, key);
		}
		#endif
	}

	// reading done!
	read_unlock();
	
	DEBUG_PRINT("notice: memory_get returning thread error %d\n", *error);
	pthread_exit(NULL);
}