Example #1
0
int			new_client(t_server *server, int *actual, char *buff)
{
	int				csock;
	t_sockaddr_in	csin;
	socklen_t		sinsize;

	sinsize = sizeof(csin);
	csock = accept(server->sock, (t_sockaddr *)&csin, &sinsize);
	if (csock == SOCKET_ERROR)
	{
		error("accept");
		return (-1);
	}
	if (read_client(csock, buff) == -1)
		return (-1);
	while (check_pseudo(buff, server) == -1)
	{
		write_client(csock, "Pseudo already used");
		if (read_client(csock, buff) == -1)
			return (-1);
	}
	FD_SET(csock, &(server->rdfs));
	server->max = csock > server->max ? csock : server->max;
	init_client(server, *actual, buff, csock);
	(*actual)++;
	return (csock);
}
Example #2
0
void		client_talking(t_server *server, int *actual, char *buff)
{
	int			i;
	t_client	client;
	char		*tmp;

	i = 0;
	while (i < *actual)
	{
		if (FD_ISSET(server->clients[i].sock, &(server->rdfs)))
		{
			client = server->clients[i];
			if (read_client(server->clients[i].sock, buff) == 0)
			{
				if_read(server, actual, buff, i);
			}
			else if (buff[0] == '/')
			{
				if ((tmp = cmd(buff, &(server->clients[i]), server)))
					write_client(server->clients[i].sock, tmp);
			}
			else
				send_to_all(server->clients, client, *actual, buff);
			break ;
		}
		i++;
	}
}
Example #3
0
int			run_serveur(t_serv *serv)
{
  t_user		*user_list;
  fd_set		readfd;
  int			max;
  int			socks;
  char			*buff;

  max = serv->s;
  user_list = NULL;
  if ((buff = malloc(4096 * sizeof(char))) == NULL)
    return (EXIT_FAILURE);
  while (1)
    {
      reset_list(&readfd, user_list, serv, max);
      if (FD_ISSET(serv->s, &readfd))
	{
	  accept_connect(&socks, serv);
	  if (read_client(socks, buff) != 0)
	    {
	      client_connexion(&max, socks, &readfd);
	      add_user(&user_list, DEFAULT_USER, socks, NULL);
	    }
	}
      else
	send_rcv(&user_list, &readfd);
    }
}
Example #4
0
/**
 * Poll relay server
 * Return:
 *      0  success
 *      -1 failed
 */
int rs_loop(rscntxt_t *cntxt)
{
	if (NULL == cntxt) {
		LogE("NULL Pointer");
		return -1;
	}

#define MAX_EVENTS 16
#define WAIT_TIMEOUT 10
	struct epoll_event ev[MAX_EVENTS];
	int ret = epoll_wait(cntxt->fd_epoll, ev, MAX_EVENTS, WAIT_TIMEOUT); 
	int i;
	for (i = 0; i < ret; ++i) {
		if (ev[i].data.fd == cntxt->fd_srvr) {
			accept_connection(cntxt);
			continue;
		}

		int nread = read_client(ev[i].data.fd, cntxt);
		if (nread < 0) {
			LogE("Failed read client");
		}
	}

	return 0;
}
Example #5
0
int main(void)
{
  if(FAILED(init_com_client()))
  {
    PRINT("Failed to init\n");
    return -1;
  }

  if(FAILED(run_com_client(COM_BNEP)))
  {
    PRINT("Failed to run\n");
  }
  else
  {
    int size = 17;
    char msg[16];

    PRINT("Connected to server\n");

    memset(msg,0,size);
    while(FAILED(read_client(msg,&size)))
      size = 16;

    PRINT("received: %s\n",msg);
  }

  if(FAILED(shutdown_com_client()))
  {
    PRINT("Failed to shutdown\n");
    return -1;
  }

  return 0;
}
Example #6
0
std::auto_ptr<image_list> TIFFFormat::do_read(byte_source* src, ImageFactory* factory, bool is_multi) {
    tiff_warn_error twe;
    tif_holder t = read_client(src);
    std::auto_ptr<image_list> images(new image_list);
    do {
        const uint32 h = tiff_get<uint32>(t, TIFFTAG_IMAGELENGTH);
        const uint32 w = tiff_get<uint32>(t, TIFFTAG_IMAGEWIDTH);
        const uint16 nr_samples = tiff_get<uint16>(t, TIFFTAG_SAMPLESPERPIXEL);
        const uint16 bits_per_sample = tiff_get<uint16>(t, TIFFTAG_BITSPERSAMPLE);
        const int depth = nr_samples > 1 ? nr_samples : -1;

        std::auto_ptr<Image> output = factory->create(bits_per_sample, h, w, depth);
        if (ImageWithMetadata* metaout = dynamic_cast<ImageWithMetadata*>(output.get())) {
            std::string description = tiff_get<std::string>(t, TIFFTAG_IMAGEDESCRIPTION, "");
            metaout->set_meta(description);
        }
        for (uint32 r = 0; r != h; ++r) {
            if(TIFFReadScanline(t.tif, output->rowp_as<byte>(r), r) == -1) {
                throw CannotReadError("imread.imread._tiff: Error reading scanline");
            }
        }
        images->push_back(output);
    } while (is_multi && TIFFReadDirectory(t.tif));
    return images;
}
Example #7
0
void TcpServer::update(uint32_t diff)
{
    int res;
    while((res = accept(m_sock_fd, NULL, 0)) >= 0)
    {
        const int optval = 1;
        ioctl(res, FIONBIO, &optval);
        LOGD("Client connected: %d", res);
        m_clients.push_back(tcp_client(res));
        onClientAdded();
    }

    // disconnected clients must be removed from m_clients in this method and nowhere else
    int av;
    for(std::vector<tcp_client>::iterator itr = m_clients.begin(); itr != m_clients.end(); )
    {
        av = available((*itr).fd);
        if(av > 0)
        {
            read_client(*itr);
            ++itr;
        }
        else if(av < 0 || (av == 0 && recv((*itr).fd, NULL, 0, 0) == 0))
        {
            LOGD("Client disconnected: %d", (*itr).fd);
            ::close((*itr).fd);
            itr = m_clients.erase(itr);
            onClientRm();
        }
        else
            ++itr;
    }
}
Example #8
0
void	client_read(t_env *e, int fd, void (*tabptrfn[])())
{
  int	r;
  char	buf[BUFFER];

  bzero(buf, BUFFER);
  if ((r = (int)read(fd, buf, BUFFER - 1)) > 0)
    buf[r - 1] = '\0';
  else
    read_client(fd, e);
  printf("Received from client %d : %s\n", fd, buf);
  client_choose_func(e, fd, buf, tabptrfn);
}
Example #9
0
client::client(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::client)
{
    ui->setupUi(this);

    tcpclient = new QTcpSocket(this);

    tcpclient->connectToHost(QHostAddress("192.168.1.80"), 5000);
    //tcpclient->connectToHost(QHostAddress::LocalHost, 5000);
    //qDebug() <<QHostAddress(QHostAddress::LocalHost).toString();

    connect(tcpclient, SIGNAL (readyRead()), this, SLOT(read_client()));

    connect(ui->lineEdit, SIGNAL(returnPressed()), ui->sendButton, SLOT(click()));
}
Example #10
0
int			manage_client(t_server *server,
				      fd_set *rfds,
				      fd_set *wfds)
{
  t_client		*client;

  client = find_client(server->root_clients, rfds, wfds);
  if (client)
  {
    if (FD_ISSET(client->fd, rfds))
      read_client(server, client);
    else
      write_client(server, client);
  }
  return (0);
}
Example #11
0
int			run_serveur(t_serv *serv)
{
  while (1)
    {
      if ((serv->cs = accept(serv->s, (struct sockaddr *)&(serv->sin_client),
			     (socklen_t *)&(serv->client_len))) == -1)
	  perror("");
      else
	{
	    if (user_identificate(serv) == EXIT_SUCCESS)
	      {
		user_information(serv);
		read_client(serv, serv->cs);
	      }
	}
    }
}
Example #12
0
t_client	*manage_select(t_client *client, t_time *time, int const sfd)
{
  fd_set	fd_read;
  fd_set	fd_write;
  int		fd_max;

  fd_max = fd_set_client(&fd_read, &fd_write, client, sfd);
  if (pselect(fd_max + 1, &fd_read, &fd_write, NULL, time, NULL) == -1)
    {
      perror("select()");
      g_keep_running = false;
      return (client);
    }
  if (FD_ISSET(sfd, &fd_read) && (client = add_client(client, sfd)) == NULL)
    {
      g_keep_running = false;
      return (client);
    }
  return (write_client(&fd_write, read_client(&fd_read, client)));
}
Example #13
0
std::auto_ptr<image_list> STKFormat::read_multi(byte_source* src, ImageFactory* factory) {
    shift_source moved(src);
    stk_extend ext;
    tiff_warn_error twe;

    tif_holder t = read_client(&moved);
    std::auto_ptr<image_list> images(new image_list);
    const uint32 h = tiff_get<uint32>(t, TIFFTAG_IMAGELENGTH);
    const uint32 w = tiff_get<uint32>(t, TIFFTAG_IMAGEWIDTH);

    const uint16 nr_samples = tiff_get<uint16>(t, TIFFTAG_SAMPLESPERPIXEL, 1);
    const uint16 bits_per_sample = tiff_get<uint16>(t, TIFFTAG_BITSPERSAMPLE, 8);
    const int depth = nr_samples > 1 ? nr_samples : -1;

    const int strip_size = TIFFStripSize(t.tif);
    const int n_strips = TIFFNumberOfStrips(t.tif);
    int32_t n_planes;
    void* data;
    TIFFGetField(t.tif, UIC3Tag, &n_planes, &data);
    int raw_strip_size = 0;
    for (int st = 0; st != n_strips; ++st) {
        raw_strip_size += TIFFRawStripSize(t.tif, st);
    }
    for (int z = 0; z < n_planes; ++z) {
        // Monkey patch strip offsets. This is very hacky, but it seems to work!
        moved.shift(z * raw_strip_size);

        std::auto_ptr<Image> output(factory->create(bits_per_sample, h, w, depth));
        uint8_t* start = output->rowp_as<uint8_t>(0);
        for (int st = 0; st != n_strips; ++st) {
            const int offset = TIFFReadEncodedStrip(t.tif, st, start, strip_size);
            if (offset == -1) {
                throw CannotReadError("imread.imread._tiff.stk: Error reading strip");
            }
            start += offset;
        }
        images->push_back(output);
    }
    return images;
}
Example #14
0
void server(void)
{
   SOCKET sock = init_connection();
   char buffer[BUF_SIZE];
   int max = sock;
   fd_set rdfs;
   while(1)
   {
      FD_ZERO(&rdfs);
      FD_SET(STDIN_FILENO, &rdfs);
      FD_SET(sock, &rdfs);
      if(connected)
      {
         FD_SET(client.sock, &rdfs);
      }
      if(select(max + 1, &rdfs,NULL, NULL, NULL) == -1)
      {
         perror("select()");
         exit(errno);
      }
    if(FD_ISSET(STDIN_FILENO, &rdfs))
      {
         fgets(buffer, BUF_SIZE - 1, stdin);
         {
            char *p = NULL;
            p = strstr(buffer, "\n");
            if(p != NULL)
           {
               *p = 0;
            }
            else
            {
               buffer[BUF_SIZE - 1] = 0;
            }
         }
         if(connected && send(client.sock, buffer, strlen(buffer), 0) < 0)
	{
	  perror("send()");
	  exit(errno);
	  }
      }
      else if(FD_ISSET(sock, &rdfs))
      {
         SOCKADDR_IN csin = { 0 };
         socklen_t sinsize = sizeof csin;
         int csock = accept(sock, (SOCKADDR *)&csin, &sinsize);
         if(csock == SOCKET_ERROR)
         {
            perror("accept()");
            continue;
         }
         if(read_client(csock, buffer) == -1)
         {
              continue;
         }
         max = csock > max ? csock : max;
         FD_SET(csock, &rdfs);
         Client c = { csock };
         strncpy(c.name, buffer, BUF_SIZE - 1);
	 client=c;
         connected=1;
	}
      else
      {
         if(connected)
         {
           if(FD_ISSET(client.sock, &rdfs))
            {
               int c = read_client(client.sock, buffer);
               if(c == 0)
               {
                  closesocket(client.sock);
                  remove_client(&client);
		  puts("Client déconnecté");
               }
               else
               {
		  printf("%s : ",client.name);
                  puts(buffer);
               }
            }
         }
      }
   }

   clear_client(&client);
   end_connection(sock);
}
Example #15
0
static void app(void)
{
    SOCKET sock = init_connection();
    char buffer[BUF_SIZE];
    int max = sock;
    /* tableau des clients */
    Client clients[MAX_CLIENTS];

    fd_set rdfs;

    /* Topologie */
    struct graph * graph = initialiser_Graph();

    while(1)
    {
	int i = 0;
	FD_ZERO(&rdfs);

	/* ajouter STDIN_FILENO */
	FD_SET(STDIN_FILENO, &rdfs);

	/* ajouter le socket de connexion */
	FD_SET(sock, &rdfs);

	/* ajouter un socket pour chaque client */
	for(i = 0; i < actual; i++)
	{
	    FD_SET(clients[i].sock, &rdfs);
	}

	if(select(max + 1, &rdfs, NULL, NULL, NULL) == -1)
	{
	    perror("select()");
	    exit(errno);
	}

	/* quelque chose qui rentre depuis le clavier */
	if(FD_ISSET(STDIN_FILENO, &rdfs))
	{
	    /* char message[BUF_SIZE]; */
	    fgets(buffer, BUF_SIZE - 1, stdin);
	    {
		char *p = NULL;
		p = strstr(buffer, "\n");
		if(p != NULL)
		{
		    *p = 0;
		}
		else
		{
		    /* fclean */
		    buffer[BUF_SIZE - 1] = 0;
		}
	    }
	    /* ===Pour écrire à tous les clients===
	       message[0] = 0;
	       strncpy(message, "serveur : ", 0);
	       strncat(message, buffer, 10);
	       for(i = 0; i < actual; i++)
	       {
	       write_client(clients[i].sock, message);
	       } */

	    /* On analyse ce que l'utilisateur tape et on agit en conséquence */
	    if(analyse_cmd(graph, buffer) == 0)
		break; /* L'utilisateur veut quitter */
	}
	else if(FD_ISSET(sock, &rdfs))
	{
	    /* nouveau client */
	    SOCKADDR_IN csin = { 0 };
	    socklen_t sinsize = sizeof(csin);
	    int csock = accept(sock, (SOCKADDR *)&csin, &sinsize);
	    if(csock == SOCKET_ERROR)
	    {
		perror("accept()");
		continue;
	    }

	    /* après s'être connecté le client envoie son nom */
	    if(read_client(csock, buffer) == -1)
	    {
		/* déconnecté */
		continue;
	    }

	    /* quel est le nouveau fd maximum ? */
	    max = csock > max ? csock : max;

	    FD_SET(csock, &rdfs); /* On ajoute le socket à la liste d'écoute */

	    int nbTokens;
	    char **tokens = malloc(MAX_NB_TOKENS*sizeof(char*));
	    nbTokens = strsplit(buffer, tokens, MAX_LEN_LINE, " ");
	    printf("ENVOYE : %s, NB TOKENS : %d\n", buffer, nbTokens);
	    if (nbTokens == 6 && strcmp(tokens[0], "log") == 0 && strcmp(tokens[1], "in") == 0 && strcmp(tokens[2], "as") == 0 && strcmp(tokens[4], "port") == 0)
	    {
		printf("nbTokens == 6\n");
		int port;
		tokens[5][strlen(tokens[5])-1] = '\0';
		port = secure_atoi(tokens[5]);
		/* On cherche si un client utilise déjà le nom demandé
		 * si le nom existe
		 * et si le port est bon*/
		if (port <= 65535 && port >= 0) {
		    printf("port OK\n");
		    int indice_noeud, indice_noeud_gen;
		    Client c;
		    c.sock = csock;
		    c.port_number = port;
		    c.address = inet_ntoa(csin.sin_addr);
		    indice_noeud = exist_Noeud(graph, tokens[3]);
		    indice_noeud_gen = obtenir_Indice_Noeud_Non_Actif(graph);
		    if (indice_noeud < actual  && indice_noeud >= 0 && est_actif_noeud(graph, indice_noeud)== 0) {
			printf("indice noeud OK, %s\n", tokens[3]);
			strcpy(c.name, tokens[3]);
			activer_Noeud(graph, indice_noeud);
			clients[actual] = c;
			actual = actual + 1;
			char bufG[BUF_SIZE] = "";
			sprintf(bufG, "greeting %s*\n", c.name);
			write_client(c.sock, bufG, clients);
		    }
		    else if(indice_noeud_gen != -1) {
			printf("indice noeud gen OK\n");
			strcpy(c.name, obtenir_Nom_Noeud(graph, indice_noeud_gen));
			activer_Noeud(graph, indice_noeud_gen);
			clients[actual] = c;
			actual = actual + 1;
			char bufG[BUF_SIZE] = "";
			sprintf(bufG, "greeting %s*\n", c.name);
			printf("bufG : %s\n", bufG);
			write_client(c.sock, bufG, clients);
			printf("écrit\n");
		    }
		    else {
			printf("Tous les noeuds sont déjà occupés !\n");
		    }

		}
		else
		    printf("Erreur de port : %s\n", tokens[5]);
	    }
	    else if (nbTokens == 4 && strcmp(tokens[0], "log") == 0 && strcmp(tokens[1], "in") == 0 && strcmp(tokens[2], "port") == 0)
	    {
		int port;
		tokens[5][strlen(tokens[5])-1] = '\0';
		port = secure_atoi(tokens[5]);
		/* On cherche si un client utilise déjà le nom demandé
		 * si le nom existe
		 * et si le port est bon*/
		if (port <= 65535 && port >= 0) {
		    int indice_noeud_gen;
		    Client c;
		    c.sock = csock;
		    c.port_number = port;
		    c.address = inet_ntoa(csin.sin_addr);
		    indice_noeud_gen = obtenir_Indice_Noeud_Non_Actif(graph);
		    if(indice_noeud_gen != -1) {
			strcpy(c.name, obtenir_Nom_Noeud(graph, indice_noeud_gen));
			activer_Noeud(graph, indice_noeud_gen);
			clients[actual] = c;
			actual = actual + 1;
			char bufG[BUF_SIZE] = "";
			sprintf(bufG, "greeting %s*\n", c.name);
			/* printf("bufG : %s\n", bufG); */
			write_client(c.sock, bufG, clients);
			/* printf("écrit\n"); */
		    }
		    else {
			printf("Tous les noeuds sont déjà occupés !\n");
		    }
		}
		else
		    printf("Erreur de port : %s\n", tokens[5]);
	    }
	   
	    /*
	    for(i=0; i < nbTokens; i++) {
		free(tokens[i]);
	    }
	    free(tokens);
	    */
	}
	else
	{
	    int i;
	    for(i = 0; i < actual; i++)
	    {
		/* un client parle */
		if(FD_ISSET(clients[i].sock, &rdfs))
		{
		    Client client = clients[i];
		    int c = read_client(clients[i].sock, buffer);
		    /* client déconnecté */
		    if(c == 0)
		    {
			closesocket(clients[i].sock);
			remove_client(clients, i, &actual);
			strncpy(buffer, client.name, BUF_SIZE - 1);
			strncat(buffer, " déconnecté !", BUF_SIZE - strlen(buffer) - 1);
			send_message_to_all_clients(clients, client, actual, buffer, 1);
		    }
		    else
		    {
			/* On analyse la requête du client stockée dans buffer et on lui répond */
			printf("router_poll : %s\n", buffer);
			if(router_poll(graph, &clients[i], buffer, clients) == 0) {
			    /* Si le routeur veut être déconnecté */
			    closesocket(clients[i].sock);
			    remove_client(clients, i, &actual);
			}
			/* ====Pour envoyer un message à tous les routeurs====
			   send_message_to_all_clients(clients, client, actual, buffer, 0); */
		    }
		    break;
		}
	    }
	}
    }

    /* libération des données */
    free_graph(graph);
    clear_clients(clients, actual);
    end_connection(sock);
}
Example #16
0
/*
int main()
{
  return 0;
}
*/
int communicate(struct donnees* donnees)
{
  printf("communicate\n");
  struct client* client=donnees->client;
  ulong ip = client->sockaddr->sin_addr.s_addr;
  struct peer* peer = find_peer(donnees->peer_list, ip);
  struct file_list* file_list = donnees->file_list;
  struct peer_list* peer_list = donnees->peer_list;
  int refresh_time=get_refresh_time();
  printf("refresh time:%d\n",refresh_time);
  char* recv_buffer= malloc(sizeof(char)*RECV_BUF_SIZE);
  char* send_buffer= malloc(sizeof(char)*SEND_BUF_SIZE);  
  char* s1 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s2 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s3 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s4 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s5 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s6 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* s0 = malloc(RECV_BUF_SIZE*sizeof(char));
  char* saux = malloc(RECV_BUF_SIZE*sizeof(char));
  char** tab = malloc(7*sizeof(char *));
  tab[0]=s0;
  tab[1]=s1;
  tab[2]=s2;
  tab[3]=s3;
  tab[4]=s4;
  tab[5]=s5;
  tab[6]=s6;
  int port;
  int read;
  int decalage;
  int length;
  int piece_size;
  struct timeval *t = malloc(sizeof(struct timeval));
  struct timeval *t2 = malloc(sizeof(struct timeval));
  struct timezone *tz = malloc(sizeof(struct timezone));
  struct timezone *tz2 = malloc(sizeof(struct timezone));
  gettimeofday(t,tz);
  while(1)
    { 
      recv_buffer[0]='\0';
      send_buffer[0]='\0';
      gettimeofday(t2,tz2);
      if(( (int)(t2->tv_sec - t->tv_sec))>3*refresh_time)
	{
	  if(peer!=NULL)
	    {
	      peer->time--;
	      if(!peer->time)
		{
		  peer_list_peer_delete(peer_list,file_list,peer->ip_address);
		}
	    }
	  //free  
	  free(s0);
	  free(s1);
	  free(s2);
	  free(s3);
	  free(s4);
	  free(s5);
	  free(s6);
	  free(saux);
	  free(recv_buffer);
	  free(send_buffer);
	  free(tab);
	  free(t);
	  free(t2);
	  free(tz);
	  free(tz2);
	  end(client,donnees->ct);
	  return 0;
	}
      read=read_client(client->sock, recv_buffer);
      if(read > 0)
	{
	  gettimeofday(t,tz);
	  if(peer!=NULL)
	    peer->time ++;
	  //print_data(file_list, peer_list);	  
	  printf("received:\n");
	  switch(recv_buffer[0])
	    {
	     pthread_mutex_lock(& mutex);
	    case'a':
	      decalage=0;
	      while(compte_crochet_fermant(recv_buffer)<2)
		{
		  decalage+=read;
		  read=read_client(client->sock, recv_buffer + decalage);
		}	  
	      recv_buffer[decalage+read]='\0';
	      printf("%s\n", recv_buffer);
	      parse(recv_buffer, tab);
	      port = atoi(s2);
	      if(strcmp(s0,"announce")==0 && strcmp(s1,"listen")==0 && strcmp(s3,"seed")==0 && strcmp(s5,"leech")==0)
		{
		  
		  if(peer == NULL)
		    {
		      peer = peer_init(ip, port);
		      peer_list_add(peer_list, peer);
		      peer->time=1;
		    }
		  int i=0;
		  while(strlen(s4+i) > 0)
		    {
		      if(compte_espace(s4+i)>3)
			{		 
			  
			  sscanf(s4+i, "%s %d %d %s", s1, &length, &piece_size, s2);
			  sprintf(saux, "%s %d %d %s", s1, length, piece_size, s2);
			  struct file* file = find_file(file_list, s1);
			  if(NULL == file)
			    {
			      file = remplit_file(s1, length, piece_size, s2);
			      file_list_add(file_list, file);
			    }
			  add_link(file, peer); 
			  i+=strlen(saux)+1;
			  
			}
		      else
			{
			  
			  sscanf(s4+i, "%s %d %d %s", s1, &length, &piece_size, s2); 
			  struct file* file = find_file(file_list, s1);
			  if(NULL == file)
			    {
			      file = remplit_file(s1, length, piece_size, s2);
			      file_list_add(file_list, file);
			    }
			  add_link(file, peer); 
			  s4[i]='\0';			
			}
		    }
		  struct file_list* f_add = keys_string_to_file_list(s6);
		  
		  update_add(file_list, peer, f_add);
		  file_list_delete(f_add);
		  write_client(client->sock, "ok");
		  printf("replied:ok\n");
		  
		}
	      break;
	      
	    case'u':
	      decalage=0;
	      while(compte_crochet_fermant(recv_buffer)<2)
		{
		  decalage+=read;
		  read=read_client(client->sock, recv_buffer + decalage);
		}	  
	      recv_buffer[decalage+read]='\0'; 
	      printf("%s\n", recv_buffer);	      
	      parse(recv_buffer, tab);
	      if(strcmp(s0,"update")==0 && strcmp(s1,"seed")==0 && strcmp(s3,"leech")==0)
		{
		  if(peer==NULL){
		    //free  
		    free(s0);
		    free(s1);
		    free(s2);
		    free(s3);
		    free(s4);
		    free(s5);
		    free(s6);
		    free(saux);
		    free(recv_buffer);
		    free(send_buffer);
		    free(tab);
		    free(t);
		    free(t2);
		    free(tz);
		    free(tz2);
		    end(client, donnees->ct);
		    
		    return 0;}//ferme la socket
		  else
		    { 
		    
		      char* res=fusion_keys_string(s2, s4);
		      struct file_list* f = keys_string_to_file_list(res);
		      update_diff(f, peer->file_list, file_list, peer);
		      file_list_delete(f);
		      free(res);
		      write_client(client->sock, "ok");
		      printf("replied:ok\n");
		  
		    }	    
		}
	      break;
	      
	    case'l':
	      decalage=0;
	      while(compte_crochet_fermant(recv_buffer)<1)
		{
		  decalage+=read;
		  read=read_client(client->sock, recv_buffer + decalage);
		}	  
	      recv_buffer[decalage+read]='\0'; 
	      printf("%s\n", recv_buffer);	      
	      parse(recv_buffer, tab);
	      if(strcmp(s0,"look")==0)
		{
		  char* filename="filename";
		  int egal=1;
		  int i;
		  s2[0]='\n';
		  for(i=0;i<8;i++)
		    {
		      if(s1[i]!=filename[i]) egal --;
		    }
		  if(egal==1)
		    {
		      for(i=10;i<((int) strlen(s1))-1;i++)
			{
			  s2[i-10]=s1[i];
			}
		      s2[strlen(s1)-11]='\0';
		      
		      printf("recherche:\nfilename=%s\n",s2);
		      struct file* file=find_file_name(file_list, s2);
		      if(file==NULL) write_client(client->sock, "list []");
		      else
			{
			  sprintf(send_buffer, "list [%s %d %d %s]", s2, file->length, file->p_size, file->key);
			  write_client(client->sock, send_buffer);
			  printf("replied:%s\n", send_buffer);
			}
		    }
		}
	      break;

	    case'g':
	      recv_buffer[read]='\0'; 
	      printf("%s\n", recv_buffer);	      
	      parse(recv_buffer, tab);
	      if(strcmp(s0,"getfile")==0)
		{
		  struct file* f=find_file(file_list, s1);
		  if(f==NULL||f->peer_list->first==NULL)
		    {
		      sprintf(send_buffer, "peers %s []", s1);
		      write_client(client->sock, send_buffer);
		    }
		  else
		    {
		      struct elt_peer* aux=f->peer_list->first;
		      struct in_addr* in_addr1=malloc(sizeof(struct in_addr));
		      in_addr1->s_addr=aux->peer->ip_address;
		      char* d= inet_ntoa(*in_addr1);
		      sprintf(send_buffer, "peers %s [%s:%d", s1, d, aux->peer->port);
		      aux=aux->next;
		      while(aux!=NULL)
			{
			  struct in_addr* in_addr=malloc(sizeof(struct in_addr));
			  in_addr->s_addr=aux->peer->ip_address;
			  char* c= inet_ntoa(*in_addr);
			  sprintf(send_buffer+strlen(send_buffer), " %s:%d", c, aux->peer->port);
			  aux=aux->next;
			}
		      sprintf(send_buffer+strlen(send_buffer), "]");
		      write_client(client->sock, send_buffer);
		      printf("replied:%s\n", send_buffer);
		    }
		}
	      break;

	    default:
	      printf("entree non valide");
	      //free  
	      free(s0);
	      free(s1);
	      free(s2);
	      free(s3);
	      free(s4);
	      free(s5);
	      free(s6);
	      free(saux);
	      free(recv_buffer);
	      free(send_buffer);
	      free(tab);
	      free(t);
	      free(t2);
	      free(tz);
	      free(tz2);
	      end(client,donnees->ct);
	      return 0;
	      
	     
	    }
	  pthread_mutex_unlock( &mutex);
	}
      
    }
  return EXIT_SUCCESS;
}
Example #17
0
/**
* Methode principale
**/
static void app(void)
{

   /* Initialisation du socket */
   SOCKET sock = init_connection();
   char buffer[BUF_SIZE];
   char message[BUF_SIZE];
   /* Index de l'array */
   int actual = 0;
   int max = sock;
   int sizeread;
   /* Le tableau qui va stocker les clients */
   Client clients[MAX_CLIENTS];

   /* Lot de descripteurs */
   fd_set rdfs;

   char *commande;
   char *nomFichier;
   char *contenuFichier;

   while(1)
   {
      int i = 0;
      /* Remise à zéro des descripteurs */
      FD_ZERO(&rdfs);

      /* ajout STDIN_FILENO (console)*/
      FD_SET(STDIN_FILENO, &rdfs);

      /* ajout du socket comme descripteur */
      FD_SET(sock, &rdfs);

      /* Ajout d'un socket pour chaque clients */
      for(i = 0; i < actual; i++)
      {
         FD_SET(clients[i].sock, &rdfs);
      }

      /* Son sélectionne tous les descripteurs prêts */
      if(select(max + 1, &rdfs, NULL, NULL, NULL) == -1)
      {
         perror("select()");
         exit(errno);
      }

      /* SI c'est une entrée clavier */
      if(FD_ISSET(STDIN_FILENO, &rdfs))
      {
         /* Si on a tapé quelque chose au clavier on arrête l'application pour permettre à l'utilisateur d'écrire*/
         break;
      } /* Sinon si c'est une entrée socket  ( nouveau )*/
      else if(FD_ISSET(sock, &rdfs))
      {
         /* Nouveau client */
         SOCKADDR_IN csin = { 0 };
         size_t sinsize = sizeof csin;
         int csock = accept(sock, (SOCKADDR *)&csin, &sinsize);

         if(csock == SOCKET_ERROR)
         {
            perror("accept()");
            continue;
         }

         /* Après s'être connecté le client envoi son pseudo */
        if(read_client(csock, buffer) == -1)
         {
            /* déconnecté */
            continue;
         }

         /* Quel est le nouveau numéro de descripteur max (pour le select) ? */
         max = csock > max ? csock : max;

         /* On ajoute le client à la liste des descripteurs */
         FD_SET(csock, &rdfs);

         /* On ajoute le client à la liste des clients avec son numéro de socket */
         Client c = { csock };
         strncpy(c.name, buffer, BUF_SIZE - 1);
         clients[actual] = c;
         actual++;
      }
      else /* Sinon on vérifie si un client a parlé */
      {
         int i = 0;
         for(i = 0; i < actual; i++) /* Pour chaque client */
         {
            /* On vérifie que le socket du client contient quelque chose */
            if(FD_ISSET(clients[i].sock, &rdfs))
            {
               /* Si c'est le cas on traite le message */
               Client client = clients[i];
               /* On lie le message envoyé par le client */
               int c = read_client(clients[i].sock, buffer);
               /* Client deconnecté */
               if(c == 0)
               {
                  /* Dans ce cas on ferme le socket */
                  closesocket(clients[i].sock);
                  remove_client(clients, i, &actual);
                  strncpy(buffer, client.name, BUF_SIZE - 1);
                  strncat(buffer, " disconnected !", BUF_SIZE - strlen(buffer) - 1);
                  send_message_to_all_clients(clients, client, actual, buffer, 1); /* On notifie tout les clients que ce dernier s'est déconnecté */
               }
               else
               {
                   strcpy(message, buffer);
                   commande = strtok(buffer, " ");
                    if( commande != NULL ) {
                       if(!strncasecmp(commande,"/getfile", strlen(commande))){
                            printf("%s\n", "Début envoi fichier");
                            nomFichier = strtok(NULL, " ");
                            FILE* fp = fopen(nomFichier, "r");
                            sizeread = fread(buffer,sizeof(char),1000,fp);
                            buffer[sizeread] = 0;
                            write(clients[i].sock,buffer,strlen(buffer));
                            printf("%s\n", "Fin envoi fichier");
                       } else if(!strncasecmp(commande,"/sendfile", strlen(commande))){
                            printf("%s\n", "Début réception fichier");
                            nomFichier = strtok(NULL, " ");
                            FILE* fp = fopen(nomFichier, "w");
                            contenuFichier = strtok(NULL, "\0");
                            fprintf(fp,"%s\n",contenuFichier);
                            fclose(fp);
                            printf("%s\n", "Fin réception fichier");
                        } else {

                          /* Sinon on se chargfe juste de relayer le message */
                          send_message_to_all_clients(clients, client, actual, message, 0);
                        }
                     }

               }
               break;
            }
         }
      }
   }

    /* On supprime les clients */
   clear_clients(clients, actual);

   /* On ferme les connexions */
   end_connection(sock);
}
Example #18
0
int main(int argc, char *argv[]) {

	int fd_socket;
	fd_set active_fd, read_fd;
	struct sockaddr_in csa;
	int i = 0;
	uint16_t port;
	int dsize; /* size of file descriptors table     */
	struct logserver_t logbuff = { 0, "" };
        FILE *logfile;
	/* Check params */
	if (3 == argc) {
		logbuff.message_buffsize = atoi(argv[2]);
		logbuff.message_buffer = (char *) mem_zalloc(logbuff.message_buffsize);
		port = atoi(argv[1]);
		if (NULL == logbuff.message_buffer) {
			fprintf(stdout, "Can't allocate %d buffer size\n",
					logbuff.message_buffsize);
			return EXIT_FAILURE;
		}
	} else {
		print_usage();
		return EXIT_FAILURE;
	}

	/*create a socket to listen to*/

	fd_socket = create_socket(port);
	/* Initialise file descriptors sockets. */

	if (listen(fd_socket, 5) < 0) {
		perror("listen");
		exit(EXIT_FAILURE);
	}
	/* remember size for later usage */

	/* calculate size of file descriptors table */
	dsize = getdtablesize();

	FD_ZERO(&active_fd);
	FD_SET(fd_socket, &active_fd);

	while (1) {
		/*blocking socket block until input arrives*/
		read_fd = active_fd;
		if (select(dsize, &read_fd, NULL, NULL, (struct timeval *) NULL) < 0) {
			perror("select");
			exit(EXIT_FAILURE);
		}
		if (FD_ISSET(fd_socket,&read_fd)) {
			printf("fd socket is set \n");
			int size_csa = sizeof(csa);
			int connectd_socket = accept(fd_socket, (struct sockaddr *) &csa,
					(socklen_t *) &size_csa);
			/*are we connected*/
			if (connectd_socket < 0) {
				perror("socket accept error");
				continue;
			}
			fprintf(stdout, "Server: connected from host %s, port %d.\n",
					(char *) inet_ntoa(csa.sin_addr),
					ntohs(csa.sin_port));
			FD_SET(connectd_socket, &active_fd);
                        logfile = open_logfile();
		}
                
		for (i = 0; i < dsize; ++i) {

			if ((i != fd_socket ) && FD_ISSET(i,&read_fd)) {
                         
				if (read_client(i, &logbuff,logfile) < 0) {
					close(i);
                                    	FD_CLR(i, &active_fd);
                                        goto EXIT_SOCKFD;
				}
                            }
			
		}

	}
EXIT_SOCKFD:        
	free_zalloc(logbuff.message_buffer);
        close_logfile(logfile);
	return 0;
}