/**
 * @NAME: temporal_get_string_time
 * @DESC: Retorna un string con la hora actual,
 * con el siguiente formato: hh:mm:ss:mmmm
 */
char *temporal_get_string_time() {
	time_t log_time;
	struct tm *log_tm;
	struct timeb tmili;
	char *str_time = strdup("hh:mm:ss:mmmm");

	if ((log_time = time(NULL)) == -1) {
		error_show("Error getting date!");
		return 0;
	}

	log_tm = localtime(&log_time);

	if (ftime(&tmili)) {
		error_show("Error getting time!");
		return 0;
	}

	char *partial_time = strdup("hh:mm:ss");
	strftime(partial_time, 127, "%H:%M:%S", log_tm);
	sprintf(str_time, "%s:%hu", partial_time, tmili.millitm);
	free(partial_time);

	//Adjust memory allocation
	str_time = realloc(str_time, strlen(str_time) + 1);
	return str_time;
}
Esempio n. 2
0
/**	@NAME: connect_to
 * 	@DESC: Intenta establecer conexion con el servidor que deberia estar escuchando. Controla errores, vuelve cuando conecta
 * 	@RETURN: Devuelve EXIT_FAILURE (1) si fallo la conexion, en otro caso devuelve el socket.
 *
 */
int connect_to(char *IP, char* Port)
{
	struct addrinfo* serverInfo = common_setup(IP, Port);
	if (serverInfo == NULL )
	{
		return -1;
	}
	int serverSocket = socket(serverInfo->ai_family, serverInfo->ai_socktype,
			serverInfo->ai_protocol);
	if (serverSocket == -1)
	{
		error_show(
				"\n No se pudo disponer de un socket al llamar connect_to, error: %d, man errno o internet!",
				errno);
		return -1;
	}
	if (connect(serverSocket, serverInfo->ai_addr, serverInfo->ai_addrlen)
			== -1)
	{
		puts("\n");
		error_show(
				"No se pudo conectar con el proceso que hace de servidor, error: %d",
				errno);
		close(serverSocket);
		return -1;
	}
	//char s[INET6_ADDRSTRLEN];
	//inet_ntop(serverInfo->ai_family, get_in_addr((struct sockaddr *)serverInfo->ai_addr),s, sizeof s);
	//printf("Conectando con %s\n", s);
	freeaddrinfo(serverInfo);
	return serverSocket;
}
Esempio n. 3
0
void		cli_prend(t_request_data *rqd, t_server *t, t_world *w)
{
  int		index_item;
  char		out[ANSWER_SIZE];

  index_item = match_index(rqd->argv[0]);
  if (index_item < RES_TYPES_COUNT && index_item >= 0
      && (w->surface[rqd->user->posy][rqd->user->posx])
      .resources[index_item] > 0)
    {
      --((w->surface[rqd->user->posy][rqd->user->posx])
	 .resources[index_item]);
      ++(rqd->user->inventory[index_item]);
      sprintf(out, "pgt %d %d\n", rqd->user->number, index_item);
      cli_answer_to_all_graph(t, out);
      cli_pin(out, rqd->user);
      cli_answer_to_all_graph(t, out);
      cli_command_bct(out, rqd->user->posx, rqd->user->posy, w);
      cli_answer_to_all_graph(t, out);
      cli_answer(rqd->user, t, "ok\n");
      free(rqd->argv[0]);
      free(rqd->argv);
      return ;
    }
  error_show("cli_prend", "", "Invalid mineral requested from player %d",
	     rqd->user->number);
  cli_answer(rqd->user, t, "ko\n");
}
Esempio n. 4
0
/**
 * @NAME: common_send
 * @DESC: Intenta mandar un paquete por el socket.
 * Devuelve EXIT_SUCCESS.
 */
void common_send(int socket, t_datosEnviar* paquete, void (*executeIfError)())
{
	char* buffer;
	int totalLength;
	t_dataSize quantitySend;
	int enviando = 1;
	int offset = 0;
	buffer = common_serializer(paquete);
	totalLength = paquete->data_size + packet_header;
	while (enviando)
	{
		quantitySend = send(socket, buffer + offset, totalLength - offset, 0);
		if (quantitySend == -1)
		{
			error_show("Error al enviar, error: %d", errno);
			executeIfError();
		}
		if (quantitySend < totalLength)
		{
			totalLength = totalLength - quantitySend;
			offset = quantitySend;
			//keep sending!!
		}
		else
			enviando = 0;
	}
	free(buffer);
}
unsigned leerUnsigned(t_config *config, char* key) {
	unsigned datoInt = 0;
	if (config_has_property(config, key)) {
		datoInt = config_get_int_value(config, key);
	} else {
		error_show("No se leyó el %s de la config \n", key);
	}
	return datoInt;
}
char* leerString(t_config *config, char* key) {
	char * datoString = malloc(sizeof(config_get_string_value(config, key)));
	if (config_has_property(config, key)) {
		datoString = config_get_string_value(config, key);
	} else {
		error_show("No se leyó el %s de la config \n", key);
	}
	return datoString;
}
Esempio n. 7
0
/** @NAME common_receive
 *  @DESC: Recibe paquetes a traves de fd, no implementa select ni poll. Si hay error ejecuta executeIfError
 *  @RETURN: Retorna el paquete recibido
 */
t_datosEnviar* common_receive(int fd, void (*executeIfError)())
{
	char *buffer = conitos_malloc(packet_header);
	int buffer_size = recv(fd, buffer, packet_header, MSG_WAITALL);
	if (buffer_size < 0)
	{
		error_show("Error at receiving packets! error: %d", errno);
		executeIfError();
		return NULL ;
	}
	if (buffer_size == 0)
	{
		error_show("Connection closed! at socket %d", fd);
		executeIfError();
		return NULL ;
	}
	t_datosEnviar* dataToReceive = common_unserializeHeader(buffer);
	free(buffer);

	buffer = conitos_malloc(dataToReceive->data_size);
	buffer_size = recv(fd, buffer, dataToReceive->data_size, MSG_WAITALL);
	if (buffer_size < 0)
	{
		error_show("Error at receiving packets! error: %d", errno);
		executeIfError();
		return NULL ;
	}
	if (buffer_size == 0)
	{
		error_show("Connection closed! at socket %d", fd);
		executeIfError();
		return NULL ;
	}
	common_unserializeData(buffer, dataToReceive);
	free(buffer);
	return dataToReceive;
}
Esempio n. 8
0
un_socket conectar_a(char *IP, char* Port) {
	struct addrinfo* serverInfo = _configurar_addrinfo(IP, Port);
	if (serverInfo == NULL) {
		exit(EXIT_FAILURE);
	}
	int serverSocket = socket(serverInfo->ai_family, serverInfo->ai_socktype,
			serverInfo->ai_protocol);
	if (serverSocket == -1) {
		error_show("\n No se pudo conectar\n",
		errno);
		exit(EXIT_FAILURE);
	}
	if (connect(serverSocket, serverInfo->ai_addr, serverInfo->ai_addrlen)
			== -1) {
		puts("\n");
		error_show(
				"No se pudo conectar con el proceso que hace de servidor, error: %d\n",
				errno);
		close(serverSocket);
		exit(EXIT_FAILURE);
	}
	freeaddrinfo(serverInfo);
	return serverSocket;
}
Esempio n. 9
0
t_item		*item_create(void *src_content, int content_size)
{
  t_item	*item;

  if ((item = (t_item*)malloc(sizeof(t_item))) != NULL)
    {
      item->cont = NULL;
      item->prev = NULL;
      item->next = NULL;
      item->cont = src_content;
      item->size = content_size;
      return (item);
    }
  error_show("item_init", "malloc", "Unable to allocate memory for item");
  return (NULL);
}
Esempio n. 10
0
void detectaCambiosEnConfigFile() {
		char buffer[BUF_LEN];
		// Al inicializar inotify este nos devuelve un descriptor de archivo
		int file_descriptor = inotify_init();
		if (file_descriptor < 0) {
			perror("inotify_init");
		}
		// Creamos un monitor sobre un path indicando que eventos queremos escuchar
		int watch_descriptor = inotify_add_watch(file_descriptor,
				"/home/utnso/workspace/SwapConfigFile/Debug", IN_MODIFY);

		// El file descriptor creado por inotify, es el que recibe la información sobre los eventos ocurridos
		// para leer esta información el descriptor se lee como si fuera un archivo comun y corriente pero
		// la diferencia esta en que lo que leemos no es el contenido de un archivo sino la información
		// referente a los eventos ocurridos
		int length = read(file_descriptor, buffer, BUF_LEN);
		if (length < 0) {
			error_show("Error al leer el descriptor de archivo");
		}
		int offset = 0;

		// Luego del read buffer es un array de n posiciones donde cada posición contiene
		// un eventos ( inotify_event ) junto con el nombre de este.
		while (offset < length) {
			huboUnCambio = 0;
			// El buffer es de tipo array de char, o array de bytes. Esto es porque como los
			// nombres pueden tener nombres mas cortos que 24 caracteres el tamaño va a ser menor
			// a sizeof( struct inotify_event ) + 24.
			struct inotify_event *event = (struct inotify_event *) &buffer[offset];
			// El campo "len" nos indica la longitud del tamaño del nombre
			if (event->len) {
				// Dentro de "mask" tenemos el evento que ocurrio y sobre donde ocurrio
				// sea un archivo o un directorio
				if (event->mask & IN_MODIFY) {
					if (event->mask) {
						printf("The file %s was modified.\n\n", event->name);
						huboUnCambio = 1;
					}
					}
				}
			offset += sizeof(struct inotify_event) + event->len;
			}

		inotify_rm_watch(file_descriptor, watch_descriptor);
		close(file_descriptor);
}
Esempio n. 11
0
struct addrinfo* _configurar_addrinfo(char *IP, char* Port) {
	struct addrinfo hints;
	struct addrinfo* serverInfo;
	int16_t error;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	if (!strcmp(IP, "localhost")) {
		hints.ai_flags = AI_PASSIVE;
		error = getaddrinfo(NULL, Port, &hints, &serverInfo);
	} else
		error = getaddrinfo(IP, Port, &hints, &serverInfo);
	if (error) {
		error_show("Problema con el getaddrinfo()!: %s\n", gai_strerror(error));
		exit(EXIT_FAILURE);
	}
	return serverInfo;
}
Esempio n. 12
0
int		graph_command_exec(t_user_graph *u, t_server *s,
				   t_world *w, char *message)
{
  int		i;
  t_graph_data	rqd;

  i = 0;
  while (g_graph_cmd[i].cmd)
    {
      if (strncmp(message, g_graph_cmd[i].cmd, 3) == 0)
        {
	  rqd.message = message;
	  rqd.user = u;
	  g_graph_cmd[i].func(&rqd, s, w);
	  return (0);
        }
      ++i;
    }
  cli_answer_to_graph(u, "suc\n");
  error_show("graph_command_exec", "", "GFX Command not found");
  return (-1);
}