Example #1
0
int main(int argc,char **argv)
{
	int next;

	do_socket();
#ifdef _WIN32
	atexit(sig_proc);
#else
	signal(SIGPIPE,SIG_IGN);
	signal(SIGTERM,sig_proc);
	signal(SIGINT,sig_proc);
#endif
	do_init(argc,argv);
	if (packet_parse_time > 0) {
		add_timer_func_list(parsepacket_timer,"parsepacket_timer");
		add_timer_interval(gettick()+packet_parse_time,parsepacket_timer,0,0,packet_parse_time);

		while(1){
			next=do_timer(gettick_nocache());
			do_sendrecv(next);
		}
	} else {
		while(1){
			next=do_timer(gettick_nocache());
			do_sendrecv(next);
			do_parsepacket();
		}
	}
	return 0;
}
Example #2
0
// Thread which handle the sending of a file
void* handle_send_file(void* pdata)
{
	int sock;
	struct sockaddr_in serv_info;
	char ip[16];
	char port[6];
	char filepath[MSG_BUFFER];
	int c, i;
	FILE* file;
	char bufout[RW_BUFFER];
	struct info* pinfo = pdata;
	ssize_t r,n,t;

	regex_get_filere(pinfo->inbuf, ip, port, filepath);

	// todo erno
	file = fopen(filepath, "rb");

	if(file == NULL)
	{
		printf("\n> Error : file does not exist\n> ");
		fflush(stdout);
		return NULL;
	}
	get_addr_info(&serv_info, ip, port);
	sock = do_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	for(i = 0; i < 5; i++) {
		c = connect(sock, (struct sockaddr*)&serv_info, sizeof(serv_info));
		if(c == 0)
			break;
		sleep(1);
	}

	if(c != 0)
	{
		printf("\n> Cannot connect to client\n> ");
		fflush(stdout);
		fclose(file);
		close(sock);
		return NULL;
	}

	// Send the file
	do {
		t = fread(bufout, 1, RW_BUFFER, file);
		r = t;
		do {
			n = write(sock, bufout, r);
			if (n < 0 )	error("ERROR with write() in do_write()");
			r -= n;
		} while (r > 0);
	} while(t == RW_BUFFER);

	printf("\n> File transfered.\n> ");
	fflush(stdout);

	fclose(file);
	close(sock);
}
Example #3
0
int main(int argc, char** argv) {
	int quit = 0;

	if (argc != 3) {
		fprintf(stderr, "usage: RE216_CLIENT hostname port\n");
		return 1;
	}

//get address info from the server
//get_addr_info()
	struct addrinfo addr;
	struct addrinfo * add = &addr;
	struct addrinfo ** ad = &add;

	ad = get_addr_info(argv[1], argv[2], ad);

	add = *ad;
	addr = *add;

//get the socket
	int s;
	s = do_socket();

//connect to remote socket
	do_connect(s, addr.ai_addr, addr.ai_addrlen);

	char * buffer = malloc(MAXLEN);
	memset(buffer, 0, MAXLEN);

	for(;;) {
		//get user input
		readline(0, buffer, MAXLEN);

		//send message to the server
		handle_client_message(s, buffer);

		// Test if log off signal was sent
		if (strcmp(buffer, "/quit\n") == 0) {
			fprintf(stderr, "Quit signal sent\n");
			break;
		}
		// Receive an echo and display it
		memset(buffer, 0, MAXLEN);
		read(s, buffer, 256);
		fprintf(stderr, "--> %s", buffer);
	}

	//Clean buffer
	free(buffer);
	//clean up socket
	shutdown(s, SHUT_RDWR);
	close(s);

	return 0;
}
Example #4
0
int main(int argc,char** argv)
{


    if (argc != 3)
    {
        fprintf(stderr,"usage: RE216_CLIENT hostname port\n");
        return 1;
    }

//get address info from the server
    struct addrinfo addr;
    struct addrinfo * add = &addr;
    struct addrinfo ** res = &add;
    int sockfd;

	get_addr_info(argv[1], argv[2], res);
	add = *res;
	addr= *add;

	//get the socket
	sockfd = do_socket();

	//connect to remote socket
	do_connect(sockfd,addr.ai_addr, addr.ai_addrlen);

    for(;;){
    	char buffer[256];
    	memset(&buffer, 0, 256);

        fprintf (stdout,"Tapez le message à envoyer (moins de 256 caractères) : \n");
        fgets((char *) buffer, 256, stdin);
        int ecrit = write(sockfd, buffer, strlen((char *) buffer));
    	
    	//handle_client_message(sockfd, &buffer, (int) 256);

        memset(&buffer, 0, (int) 256);
        read(sockfd, buffer, (int) 256);
        fprintf(stderr, "SERVER --> %s", buffer);
        if(strcmp(buffer, "Connexion terminée\n") == 0)
            break;
    }

    close(sockfd);


    return 0;


}
Example #5
0
void* handle_file_receive(void* pdata)
{
	struct info* pinfo = pdata;
	int sock, client, addrlen, r;
	struct sockaddr_in server_info;
	struct sockaddr_in client_addr;
	char port[6];
	char bufin[RW_BUFFER];
	FILE* file;

	system("mkdir inbox 2>/dev/null");

	memset(bufin, 0, RW_BUFFER);
	pthread_mutex_lock( &(pinfo->mutex) );
	sprintf(bufin, "./inbox/%s", pinfo->filename);
	file = fopen(bufin, "wb+");
	memset(bufin, 0, RW_BUFFER);

	memset(port, 0, 6);
	sprintf(port, "%d", pinfo->port);
	pthread_mutex_unlock( &(pinfo->mutex) );

	if(file == NULL)
	{
		printf("Error with fopen in handle_file_receive - directory inbox does not exist\n");
		file = fopen("./RE216_pwd", "wb+");
		if(file != NULL) fclose(file);
		return NULL;
	}

	// Create a server
	sock = do_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	init_serv_addr(port, &server_info);
	do_bind(sock, &server_info);
	listen(sock, 1);
	client = accept(sock, (struct sockaddr*)&client_addr, &addrlen);
	int a = 0;
	do {
		r = read(client, bufin, 1024);
		a = fwrite(bufin, 1, r, file);
	} while(r != 0);

	fclose(file);
	printf("\n> File received\n> ");
	fflush(stdout);
	close(client);
	close(sock);
}
Example #6
0
int main(int argc,char **argv)
{
	int next;

	do_socket();
	signal(SIGPIPE,SIG_IGN);
	signal(SIGTERM,sig_proc);
	signal(SIGINT,sig_proc);
	do_init(argc,argv);
	while(1){
		next=do_timer(gettick_nocache());
		do_sendrecv(next);
		do_parsepacket();
	}
	return 0;
}
Example #7
0
int create_tcp_client(char *host, int portno)
{
  int sockfd, n;
  //struct sockaddr_in serv_addr;
  //struct hostent *server;

  char buffer[256];

  //sockfd = socket(AF_INET, SOCK_STREAM, 0);
  sockfd = do_socket();
  if (sockfd < 0)
    error("ERROR opening socket");
//  server = gethostbyname(host);
//  if (server == NULL) {
//    fprintf(stderr,"ERROR, no such host\n");
//    exit(0);
//  }
//  bzero((char *) &serv_addr, sizeof(serv_addr));
//  serv_addr.sin_family = AF_INET;
//  bcopy((char *)server->h_addr,
//        (char *)&serv_addr.sin_addr.s_addr,
//        server->h_length);
//  serv_addr.sin_port = htons(portno);
//  if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
//    error("ERROR connecting");

  if (do_connect(sockfd, host, portno) < 0) {
    error("ERROR connecting");
  }
  //while(1) {
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n = write(sockfd,buffer,strlen(buffer));
    if (n < 0)
      error("ERROR writing to socket");
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0)
      error("ERROR reading from socket");
    printf("%s\n",buffer);
    //}
  close(sockfd);
  return 0;
}
Example #8
0
int create_tcp_server(int portno)
{
  int sockfd, newsockfd;
  socklen_t clilen;
  char buffer[256];
  struct sockaddr_in serv_addr, cli_addr;
  int n;

  //sockfd = socket(AF_INET, SOCK_STREAM, 0);
  sockfd = do_socket();
  if (sockfd < 0)
    error("ERROR opening socket");
//  bzero((char *) &serv_addr, sizeof(serv_addr));
//  //portno = atoi(argv[1]);
//  serv_addr.sin_family = AF_INET;
//  serv_addr.sin_addr.s_addr = INADDR_ANY;
//  serv_addr.sin_port = htons(portno);
//  if (bind(sockfd, (struct sockaddr *) &serv_addr,
//           sizeof(serv_addr)) < 0)
//    error("ERROR on binding");

  if(do_bind(sockfd, portno) < 0) {
    error("ERROR on binding");
  }

  listen(sockfd,5);
//  clilen = sizeof(cli_addr);
//  newsockfd = accept(sockfd,
//                     (struct sockaddr *) &cli_addr,
//                     &clilen);
  newsockfd = do_accept(sockfd);
  while(1) {
    if (newsockfd < 0)
      error("ERROR on accept");
    bzero(buffer,256);
    n = read(newsockfd,buffer,255);
    if (n < 0) error("ERROR reading from socket");
    printf("Here is the message: %s\n",buffer);
    n = write(newsockfd,"I got your message",18);
    if (n < 0) error("ERROR writing to socket");
  }
  close(newsockfd);
  close(sockfd);
  return 0;
}
Example #9
0
int main(int argc,char** argv) {

    if (argc != 3) {
        fprintf(stderr,"usage: RE216_CLIENT hostname port\n");
        return 1;
    }
    
	// -----------------------------------------------------------------
	// ------------------------ Variables ------------------------------
	
	// Buffer
	char *input = NULL;		// Taille d'entrée dynamique
	char output[TAILLE_MSG];// Taille de réception fixée
    
	// Liste chaînée pour l'envoi de fichiers
	struct file fichiers;
		memset(&fichiers, 0, sizeof(struct file));

	// Récupération de la structure sockaddr_in6 pour l'adresse du serveur
	struct sockaddr_in6* server_add = get_addr_info(atoi(argv[2]), argv[1]);

	// Création de la socket
	int sckt = do_socket();  

	// Connexion de la socket à l'adresse server_add
	int conn = do_connect(sckt, *server_add);

	// Initialisation des tableaux pour utliser select ------------------
    
    fd_set fd_set_read; // Ici seront stockés les descripteurs de fichier
    
    int i, select_ret_val;
    
    // Socket du serveur quand elle existe
    int socket_fichier = -1;
    
    // Eventuellement : timeout du select
	//~ struct timeval tv;
	//~ tv.tv_sec = 5;
	//~ tv.tv_usec = 0;
	
	init_reg();
	// -----------------------------------------------------------------
	// -----------------------------------------------------------------
	
	start_line();

	// Boucle jusqu'à recevoir le "/quit" final
	do {
		
		// ------------------------ R.A.Z ------------------------------
		// clean the set before adding file descriptors
		FD_ZERO(&fd_set_read);
		
		// add the fd for server connection
		FD_SET(sckt, &fd_set_read);

		// add the fd for user-input
		FD_SET(fileno(stdin), &fd_set_read);
		// -------------------------------------------------------------
		 
		// we now wait for any file descriptor to be available for reading
        select_ret_val = select(sckt + 1, &fd_set_read, NULL, NULL, NULL);//&tv);
        
        if (select_ret_val == -1) {
			error("Erreur concernant le select ");
		}
        
        //printf("Le retour de la fonction select est : %i", select_ret_val);
		
		for (i = 0; i < (sckt+1) && select_ret_val > 0; i++) {
	
            // Le buffer est nettoyé avec memset directement dans les fonctions
            
            //printf("Bonjour je suis le i n°%i. Retour => %i\n", i, select_ret_val);

            // Si le file descripteur i est dans le set mis en écoute, c'est qu'il y a une activité
            if (FD_ISSET(i, &fd_set_read)) {
				
				// printf("Descripteur trouvé : %i\n", i);

                if (i == fileno(stdin)) // C'est une entrée utilisateur
					client_write(&input, sckt, &fichiers);
				
				else // Les données viennent du serveur
					if (!client_read(sckt, output, &fichiers, &socket_fichier))
						break;

                // Select_ret_val est le nombre de descripteurs où il y 
                // a eu une activité, on diminue donc sa valeur au fur
                // et à mesure.
                select_ret_val--;

            }
        }

	} while(notquit(input) && notquit(output));

	//printf("Extinction.\n");

	free(input);
	
	free_file(&fichiers);

	free_reg();

	// Fermeture de la socket
    close_socket(sckt);
    
	printf("Fin du tchat\n");
	
    return 0;
}
Example #10
0
void do_file_entry(const u8* base,
		   const char* dir,
	           const char* path,
		   const char* name, int namelen, 
		   const struct cramfs_inode* inode)
{
   int dirlen=strlen(dir);
   int pathlen=strlen(path);
   char pname[dirlen+pathlen+namelen+3];
   const char* basename;
   
   if (dirlen) {
      strncpy(pname, dir, dirlen);
   }
   
   if (pathlen) {
      if (dirlen) {
	 pname[dirlen]='/';
	 ++dirlen;
      }
      strncpy(pname+dirlen, path, pathlen);
   }
   
   if (namelen) {
      if (pathlen+dirlen) {
	 pname[dirlen+pathlen]='/';
	 ++pathlen;
      }
      strncpy(pname+dirlen+pathlen, name, namelen);
   }

   pname[pathlen+dirlen+namelen]=0;
   basename=namelen ? pname+dirlen+pathlen : "/";
   
   // Create things here
   printmode(inode);
   printuidgid(inode);
   
   if (S_ISREG(inode->mode)) {
      do_file(base, inode->offset<<2, inode->size, pname, basename, inode->mode);
   } else  if (S_ISDIR(inode->mode)) {
      do_directory(base, inode->offset<<2, inode->size, pname, basename, inode->mode);
   } else  if (S_ISLNK(inode->mode)) {
      do_symlink(base, inode->offset<<2, inode->size, pname, basename, inode->mode);
   } else  if (S_ISFIFO(inode->mode)) {
      do_fifo(base, inode->offset<<2, inode->size, pname, basename, inode->mode, inode->uid, inode->gid);
   } else  if (S_ISSOCK(inode->mode)) {
      do_socket(base, inode->offset<<2, inode->size, pname, basename, inode->mode);
   } else  if (S_ISCHR(inode->mode)) {
      do_chrdev(base, inode->offset<<2, inode->size, pname, basename, inode->mode, inode->uid, inode->gid);
   } else  if (S_ISBLK(inode->mode)) {
      do_blkdev(base, inode->offset<<2, inode->size, pname, basename, inode->mode, inode->uid, inode->gid);
   } else {
      do_unknown(base, inode->offset<<2, inode->size, pname, basename, inode->mode);
   }
   
   if (geteuid() == 0) {
      if (lchown(pname, inode->uid, inode->gid) == -1)
         perror("cannot change owner or group");
   } else if(opt_idsfile && path && path[0]) {
      char dfp[1024];
      char *p;
      FILE *f;

      strcpy(dfp,pname);
      p = strrchr(dfp,'/');
      if (!p) {
         fprintf(stderr,"could not find path in '%s'\n",pname);
         return;
      }
      strcpy(p+1,opt_idsfile);
      f = fopen(dfp,"at");
      if (!f) {
   	    perror(dfp);
   	    return;
      }
	  fprintf(f,"%s,%u,%u,%08x\n",basename,inode->uid,inode->gid,inode->mode);
      fclose(f);
   }

   if (geteuid() == 0 || !opt_idsfile) {
      if (inode->mode & (S_ISGID|S_ISUID|S_ISVTX)) {
        if (0 != chmod(pname, inode->mode)){
          perror("chmod");
          return;
        }
      }
   }


   
   printf("\n");
}
Example #11
0
void main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "please specify local port to bind to\n");
        exit(-1);
    }

    int server_sock;
    int max_fd;
    struct sockaddr_in * serv_addr = malloc(sizeof(*serv_addr));
    struct sockaddr_in * addr = malloc(sizeof(*addr));

    char buffer[256];
    

    int users[15];
    int most_recent_user = 0;

    fd_set rdfs;
    fd_set rdfs_utd;

    //init a fresh socket
    server_sock = do_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    max_fd = server_sock;
        
    //init server address structure
    init_serv_addr(argv[1],serv_addr);

    //perform the binding
    do_bind(server_sock, serv_addr, sizeof(*serv_addr));

    //specify the socket to be a server socket and listen for at most 20 concurrent client
    if(listen(server_sock, 20) == -1)
        error("ERROR Listen");
    

    //init the fdset
    FD_ZERO(&rdfs);
    FD_SET(server_sock, &rdfs);
    rdfs_utd = rdfs;

    //in an infinite loop, listen to the stored sockets
    for (;;) {
        //use select to listen to sockets
        if(select(max_fd+1, &rdfs, NULL, NULL, NULL) == -1){
            error("ERROR Server Select");
        }

        int current_fd;
        for(current_fd = 3; current_fd <=max_fd; current_fd++){
            // Implement the listening for incoming sockets
            if(current_fd == server_sock){ // Activité sur socket Serveur = Nouveau client
                if(FD_ISSET(server_sock, &rdfs)){
                    int new_sock = do_accept(server_sock, (struct sockaddr *) addr, (socklen_t) sizeof(addr));
                    if (++most_recent_user > 2){
                        do_write(new_sock, "SATURATION : we can't accept further communication. Try later\n");
                        fprintf(stdout, "Attempt of connection but saturation\n");
                        close(new_sock);
                        //on ferme tout et on envoie un message de saturation du serveur
                    }
                    // on rajoute une nouvelle socket pour un nouvel utilisateurs
                    FD_SET(new_sock, &rdfs_utd);
                    users[most_recent_user] = new_sock;
                    //Mettre à jour le plus grand descripteur à considérer
                    max_fd = new_sock > max_fd ? new_sock : max_fd;
                    // Nettoyer le buffer
                    memset(buffer, 0, 256);
                    // Read what the client has to say
                    int lu = read(new_sock, buffer, (int) 256);
                    //Test the value of the message
                    if (strcmp(buffer,"/quit\n") == 0){
                        fprintf(stdout, "[CLIENT] : %s", buffer);
                        do_write(new_sock, "You will be terminated\n");
                        FD_CLR(new_sock, &rdfs);
                        close(new_sock);
                        printf("The client n°%i is now disconnected\n", (current_fd-3));
                        max_fd -= 1;
                    }else{
                        // Display on the server monitor who is saying what
                        fprintf(stdout, "[CLIENT n° %i] : %s", new_sock-3, buffer);
                        // we write back to the client
                        do_write(new_sock, buffer);
                    }
                }
            }
            // then implement the listening for already connected socket that write data to the server
            else{
                if(FD_ISSET(current_fd, &rdfs)){
                     // Nettoyer le buffer
                    memset(buffer, 0, 256);
                    // Read what the client have to say
                    int lu = read(current_fd, buffer, (int) 256);
                    //Test the value of the message
                    if (strcmp(buffer,"/quit\n") == 0){
                        fprintf(stdout, "[CLIENT] : %s", buffer);
                        do_write(current_fd, "You will be terminated\n");
                        FD_CLR(current_fd, &rdfs);
                        close(current_fd);
                        printf("The client n°%i is now disconnected\n", (current_fd-3));
                        max_fd -= 1;
                    }else{
                        // Display on the server monitor who is saying what
                        fprintf(stdout, "[CLIENT n° %i] : %s",(current_fd-3), buffer);
                        // we write back to the client
                        do_write(current_fd, buffer);
                    }
                }
            }
        }
        // Mettre à jour le fd d'activité
        rdfs = rdfs_utd;
    }
}
Example #12
0
int rsem_wait(struct rsem_client *rcli, const char *name)
{
	char err[512] = { 0 };
	size_t err_len = sizeof(err);
	int ret, res, port, zfd = -1, zsock = -1;
	struct rsem_request req;
	struct json_object *jo;
	uint32_t ty, resp;
	struct sockaddr_in addr;

	port = wait_for_next_free_port(rcli);
	zsock = do_bind_and_listen(port, err, err_len);
	if (err[0]) {
		glitch_log("rsem_wait: do_bind_and_listen failed with "
			   "error '%s'\n", err);
		ret = -EIO;
		zsock = -1;
		goto done;
	}
	zfd = do_socket(AF_INET, SOCK_STREAM, 0, WANT_O_CLOEXEC);
	if (zfd < 0) {
		glitch_log("rsem_wait: socket error: %d\n", zfd);
		ret = EIO;
		goto done;
	}
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(get_first_ipv4_addr(rcli->srv_host,
						err, err_len));
	if (err[0]) {
		/* couldn't resolve hostname */
		ret = EIO;
		goto done;
	}
	addr.sin_port = htons(rcli->srv_port);
	if (connect(zfd, &addr, sizeof(addr)) < 0) {
		ret = errno;
		glitch_log("rsem_wait: failed to connect to %s: error %d\n",
			   rcli->srv_host, ret);
		goto done;
	}
	ty = htonl(RSEM_CLIENT_REQ_SEM);
	if (safe_write(zfd, &ty, sizeof(uint32_t))) {
		glitch_log("rsem_wait: short write of message type\n");
		ret = -EIO;
		goto done;
	}
	memset(&req, 0, sizeof(req));
	req.name = (char*)name;
	req.port = port;
	jo = JORM_TOJSON_rsem_request(&req);
	if (!jo) {
		ret = -ENOMEM;
		glitch_log("rsem_wait: out of memory\n");
		goto done;
	}
	if (blocking_write_json_req("rsem_wait", zfd, jo)) {
		ret = -EIO;
		json_object_put(jo);
		goto done;
	}
	json_object_put(jo);
	if (safe_read(zfd, &resp, sizeof(uint32_t)) != sizeof(uint32_t)) {
		glitch_log("rsem_wait: short read of response\n");
		ret = -EIO;
		goto done;
	}
	resp = ntohl(resp);
	RETRY_ON_EINTR(res, close(zfd));
	zfd = -1;
	if (resp == RSEM_SERVER_GIVE_SEM) {
		ret = 0;
	}
	else if (resp == RSEM_SERVER_DELAY_SEM) {
		ret = rsem_wait_for_callback(name, zsock);
	}
	else {
		glitch_log("rsem_wait: unexpected server reply %d\n",
				resp);
		ret = -EIO;
	}

done:
	if (zsock >= 0)
		RETRY_ON_EINTR(res, close(zsock));
	if (zfd >= 0)
		RETRY_ON_EINTR(res, close(zfd));
	release_port(rcli, port);
	return ret;
}
Example #13
0
static int rsem_post_impl(struct rsem_client *rcli, const char *name)
{
	char err[512] = { 0 };
	size_t err_len = sizeof(err);
	int res, ret, zfd = -1;
	struct json_object *jo = NULL;
	struct sockaddr_in addr;
	uint32_t ty, resp;
	struct rsem_release rel;

	rel.name = (char*)name;
	jo = JORM_TOJSON_rsem_release(&rel);
	if (!jo) {
		ret = -ENOMEM;
		glitch_log("rsem_post_impl: out of memory\n");
		goto done;
	}
	zfd = do_socket(AF_INET, SOCK_STREAM, 0, WANT_O_CLOEXEC);
	if (zfd < 0) {
		ret = zfd;
		glitch_log("rsem_post_impl: socket error: %d\n", ret);
		goto done;
	}
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(get_first_ipv4_addr(rcli->srv_host,
				err, err_len));
	if (err[0]) {
		/* couldn't resolve hostname */
		ret = -EIO;
		goto done;
	}
	addr.sin_port = htons(rcli->srv_port);
	if (connect(zfd, &addr, sizeof(addr)) < 0) {
		ret = errno;
		glitch_log("rsem_post_impl: failed to connect to %s: "
			   "error %d\n", rcli->srv_host, ret);
		ret = -EIO;
		goto done;
	}
	ty = htonl(RSEM_CLIENT_REL_SEM);
	if (safe_write(zfd, &ty, sizeof(uint32_t))) {
		glitch_log("rsem_post_impl: short write of message type %d\n",
			   RSEM_CLIENT_REL_SEM);
		ret = -EIO;
		goto done;
	}
	if (blocking_write_json_req("rsem_post_impl", zfd, jo)) {
		ret = -EIO;
		goto done;
	}
	if (safe_read(zfd, &resp, sizeof(uint32_t)) != sizeof(uint32_t)) {
		glitch_log("rsem_post_impl: short read of response\n");
		ret = -EIO;
		goto done;
	}
	resp = ntohl(resp);
	if (resp == RSEM_SERVER_ACK) {
		ret = 0;
	}
	else {
		glitch_log("rsem_post_impl: got unexpected server "
			   "response %d\n", resp);
		ret = -EIO;
	}

done:
	if (jo)
		json_object_put(jo);
	if (zfd >= 0)
		RETRY_ON_EINTR(res, close(zfd));
	return ret;
}
int main(int argc, char** argv)
{

    if (argc != 2)
    {
        fprintf(stderr, "usage: RE216_SERVER port\n");
        return 1;
    }


  // Initialization of the server address
    struct sockaddr_in serv_addr;
    int port = atoi(argv[1]);
    serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(port);


    //Creation of the socket
    int socket;
    socket=do_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    //  Binding
    do_bind(socket,serv_addr,sizeof(serv_addr));

    // Specify the socket to be a server socket and listen for at most 20 concurrent client
    listen(socket,20);

    
    // Initialization of the select() parameters
    fd_set my_fd_set;
    fd_set fd_temp;
    FD_ZERO(&my_fd_set);
    FD_SET(socket,&my_fd_set); // adding the server socket to my_fd_set
    int max_fd = socket+1;

    //Initialization of the user list storing user profiles created after the accept() function.
    puser user_list = NULL;
    char* name_by_default;
    

    // Initialization of all the buffers and variables used in all the following options
    int size_buffer = 300;
    char* who_is_nick;
     
    //Variable used in for loop for browsing through the user list
    int k;

    /* Infinite loop */
    for (;;) 
    {
        fd_temp=my_fd_set;

        // select() is used to get the active sockets : Client or Server
        int select_temp;
        select_temp = select(max_fd,&fd_temp,NULL,NULL,NULL);

	int i;
   	    
        for(i=3;i<max_fd;i++) {
            if(FD_ISSET(i, &fd_temp)) {

                // New connections management
                if(i==socket) {

                    // Accepting connections from the differents clients
                    int new_sock_client;
                    new_sock_client = do_accept(socket,serv_addr,sizeof(serv_addr));
                    printf("CLIENT  %d IS NOW CONNECTED ON THE CHAT ! \n",new_sock_client-socket);

                    if (max_fd <= new_sock_client)
                        max_fd = new_sock_client +1;

                    FD_SET(new_sock_client,&my_fd_set); // Adding the new socket to my_fd_set

                    // Creating a new user profile 
                    struct user new_user;
                    strcpy(new_user.name,"Client");
                    new_user.socket_client = new_sock_client;
                    new_user.next_user = user_list;

                    // Connection Data Management 
                    char buffer[512];
                    char date_hour[40]; 

		    /* Date and hour management */
                    time_t timer_seconds = time(NULL);
                    struct tm * timeinfo = localtime(&timer_seconds);
                   
  
		    // /whois <nickname> displaying management
                    strftime(date_hour, sizeof(date_hour), "%d/%m/%Y@%H:%M", timeinfo); 
		    sprintf(buffer,"%s WITH IP ADDRESS 127.0.0.1 AND PORT %d \n",date_hour,port); 
                    strcpy(new_user.connect_data,buffer);

                    // Add a new user to the user_list
                    user_list = add_user(user_list,new_user);
                }

                // Client management
                else {

                    // Initialization of the buffer for incomming and outcomming information about any client 
                    char buffer_client[size_buffer];
                    bzero(buffer_client,size_buffer);
                    
                    // Get user information for the profile by the socket
                    puser user = get_user_by_socket(user_list,i);

                    // Read the sending message of the client

		    /*Receive the message from the socket by using recv */
		    int tempo_recvs=recv(i,buffer_client,size_buffer,0);


		    if (tempo_recvs != -1 && strncmp(buffer_client,"/quit\n",6) && strcmp(user->name,"Client") && strncmp(buffer_client,"/nick ",6) && strncmp(buffer_client,"/who\n",5) && strncmp(buffer_client,"/whois ",7)) {

        printf("[%s]: %s",user->name, buffer_client);

		    } else if(tempo_recvs==-1){
        printf("ERROR : AN ERROR OCCURED  WHILE RECEIVING MESSAGE \n");
        perror("recv"); exit(EXIT_FAILURE);
		    }
                    


                
                    // /nick management
                    if(strncmp(buffer_client,"/nick ",6)==0) {

                        // Get the client input and remove the segmentation fault 
                        name_by_default = strchr(buffer_client,' ') +sizeof(char);
                        strcpy(name_by_default+(strlen(name_by_default)-1)*sizeof(char),"\0");

                        int already_used=0;
			
                        
                        
                        // We browse through the user list in order to check if the nickname chosen by the Client is already used
                        for(k=4;k<max_fd;k++) {
                            if (k != i) {
                                puser nickuser = get_user_by_socket(user_list,k);
                                if(strcmp(nickuser->name,name_by_default)==0){
                                    strcpy(buffer_client,"ERROR : NICKNAME ALREADY USED ! \n");
                                    already_used=1;
                                    break;
                                }
                            }
                        }

                        // If the nickname chosen by the Client isn't already used
                        if(already_used!=1 && strcmp(user->name,name_by_default)) {

			  // When a Client visit the chat for the first time
                            if (!strcmp(user->name,"Client")) {
                                strcpy(user->name,name_by_default);

                                sprintf(buffer_client,"WELCOME ON THE CHAT %s \n",user->name);
                                printf("[SERVER]: %s",buffer_client);
                            } 

                            // If a Client is already connected on the chat with a nickname but he used /nick again, he can change his nickname
                            else {
                                printf("[SERVER]: %s IS NOW KNOWN AS %s \n",user->name,name_by_default);
                                strcpy(user->name,name_by_default);
                                sprintf(buffer_client,"YOUR NEW NICKNAME IS  %s \n",user->name);
                            }
                        }
                        do_send_server(i, buffer_client, size_buffer);                      
                    }


                    // If a Client doesn't have a nickname yet, he can't talk on the chat 
                    else if(strcmp(user->name,"Client")==0) {
                        strcpy(buffer_client,"ERROR : YOU MUST CHOOSE A NICKNAME BY USING /nick BEFORE CHATTING ! \n");
                        do_send_server(i, buffer_client, size_buffer);
                    }


                    // /who management
                    else if(strncmp(buffer_client,"/who\n",5)==0) {
                        strcpy(buffer_client,"MORE INFORMATION ABOUT ONLINE USERS -> THESE CLIENTS ARE CURRENTLY ONLINE  :\n");
                        for(k=4;k<max_fd;k++){
                            puser whouser = get_user_by_socket(user_list,k);
                            if (strcmp(whouser->name,"Client")){
                                char who_name[60];
                                sprintf(who_name," %s \n",whouser->name);
                                strcat(buffer_client,who_name);
                            }
                        }
                        do_send_server(i, buffer_client, size_buffer);
                    }

                    // /whois management
                    else if(strncmp(buffer_client,"/whois ",7)==0) {
                        who_is_nick = strchr(buffer_client,' ') +sizeof(char);
                        strcpy(who_is_nick+(strlen(who_is_nick)-1)*sizeof(char),"\0");
                        puser whois_user;
                        whois_user = get_user_by_name(user_list,who_is_nick);
                        if (whois_user != NULL) {
                            sprintf(buffer_client,"MORE INFORMATION ABOUT CLIENT  %s : HE IS CONNECTED SINCE   %s \n", whois_user->name, whois_user->connect_data);
                        }
                        else{
                            strcpy(buffer_client,"ERROR : THERE IS NO ANY CLIENTS CONNECTED  \n");
                        }
                        do_send_server(i, buffer_client, size_buffer);
                    }


                    // /quit management
                    else if(strncmp(buffer_client,"/quit\n",6)==0) {
                        close(i);
                        FD_CLR(i,&my_fd_set);
                        printf("[SERVER]: %s JUST LEFT THE CHAT -> THE CLIENT %d IS DISCONNECTED !   \n",user->name,user->socket_client-socket);                        
                        break;
                    }


                    //Sending back message to client
                    else {
                    strcpy(buffer_client,"\0");
                    do_send_server(i, buffer_client, size_buffer);
                    }

                }
            }
        }
    }

    // Closing socket
    close(socket);

    return 0;
}
Example #15
0
PUBLIC int uds_ioctl(message *dev_m_in, message *dev_m_out)
{
	int minor;

#if DEBUG == 1
	static int call_count = 0;
	printf("(uds) [%d] uds_ioctl() call_count=%d\n", uds_minor(dev_m_in),
							++call_count);
 	printf("Endpoint: 0x%x | Position 0x%x\n", dev_m_in->IO_ENDPT, 
							dev_m_in->POSITION);
#endif

	minor = uds_minor(dev_m_in);

	if (uds_fd_table[minor].state != UDS_INUSE) {

		/* attempted to close a socket that hasn't been opened --
		 * something is very wrong :(
		 */
		uds_set_reply(dev_m_out, TASK_REPLY, dev_m_in->IO_ENDPT,
				(cp_grant_id_t) dev_m_in->IO_GRANT, EINVAL);

		return EINVAL;
	}

	/* track the system call we are performing in case it gets cancelled */
	uds_fd_table[minor].call_nr = dev_m_in->m_type;
	uds_fd_table[minor].ioctl = dev_m_in->COUNT;
	uds_fd_table[minor].syscall_done = 0;

	/* setup select(2) framework */
	uds_fd_table[minor].selecting = 0;

	/* update the owner endpoint - yes it's really stored in POSITION */
	uds_fd_table[minor].owner = dev_m_in->POSITION;

	switch (dev_m_in->COUNT) {	/* Handle the ioctl(2) command */

		case NWIOSUDSCONN:

			/* connect to a listening socket -- connect() */
			return do_connect(dev_m_in, dev_m_out);

		case NWIOSUDSACCEPT:

			/* accept an incoming connection -- accept() */
			return do_accept(dev_m_in, dev_m_out);

		case NWIOSUDSBLOG:

			/* set the backlog_size and put the socket into the
			 * listening state -- listen()
			 */
			return do_listen(dev_m_in, dev_m_out);

		case NWIOSUDSTYPE:

			/* set the type for this socket (i.e. 
			 * SOCK_STREAM, SOCK_DGRAM, etc) -- socket()
			 */
			return do_socket(dev_m_in, dev_m_out);

		case NWIOSUDSADDR:

			/* set the address for this socket -- bind() */
			return do_bind(dev_m_in, dev_m_out);

		case NWIOGUDSADDR:

			/* get the address for this socket -- getsockname() */
			return do_getsockname(dev_m_in, dev_m_out);

		case NWIOGUDSPADDR:

			/* get the address for the peer -- getpeername() */
			return do_getpeername(dev_m_in, dev_m_out);

		case NWIOSUDSSHUT:

			/* shutdown a socket for reading, writing, or 
			 * both -- shutdown()
			 */
			return do_shutdown(dev_m_in, dev_m_out);

		case NWIOSUDSPAIR:

			/* connect two sockets -- socketpair() */
			return do_socketpair(dev_m_in, dev_m_out);

		case NWIOGUDSSOTYPE:

			/* get socket type -- getsockopt(SO_TYPE) */
			return do_getsockopt_sotype(dev_m_in, dev_m_out);

		case NWIOGUDSPEERCRED:

			/* get peer endpoint -- getsockopt(SO_PEERCRED) */
			return do_getsockopt_peercred(dev_m_in, dev_m_out);

		case NWIOSUDSTADDR:

			/* set target address -- sendto() */
			return do_sendto(dev_m_in, dev_m_out);

		case NWIOGUDSFADDR:

			/* get from address -- recvfrom() */
			return do_recvfrom(dev_m_in, dev_m_out);

		case NWIOGUDSSNDBUF:

			/* get the send buffer size -- getsockopt(SO_SNDBUF) */
			return do_getsockopt_sndbuf(dev_m_in, dev_m_out);

		case NWIOSUDSSNDBUF:

			/* set the send buffer size -- setsockopt(SO_SNDBUF) */
			return do_setsockopt_sndbuf(dev_m_in, dev_m_out);

		case NWIOGUDSRCVBUF:

			/* get the send buffer size -- getsockopt(SO_SNDBUF) */
			return do_getsockopt_rcvbuf(dev_m_in, dev_m_out);

		case NWIOSUDSRCVBUF:

			/* set the send buffer size -- setsockopt(SO_SNDBUF) */
			return do_setsockopt_rcvbuf(dev_m_in, dev_m_out);

		case NWIOSUDSCTRL:

			/* set the control data -- sendmsg() */
			return do_sendmsg(dev_m_in, dev_m_out);

		case NWIOGUDSCTRL:

			/* set the control data -- recvmsg() */
			return do_recvmsg(dev_m_in, dev_m_out);

		default:

			/* the IOCTL command is not valid for /dev/uds --
			 * this happens a lot and is normal. a lot of 
			 * libc functions determine the socket type with 
			 * IOCTLs. Any not for us simply get a EBADIOCTL
			 * response.
			 */
			uds_fd_table[minor].syscall_done = 1;
			uds_set_reply(dev_m_out, TASK_REPLY,
					dev_m_in->IO_ENDPT, 
					(cp_grant_id_t) dev_m_in->IO_GRANT,
					EBADIOCTL);

			return EBADIOCTL;
	}
}
Example #16
0
void do_file_entry(const u8 * base, const char *dir, const char *path, const char *name, int namelen, const struct cramfs_inode *inode) {
	int dirlen = strlen(dir);
	int pathlen = strlen(path);
	char pname[dirlen + pathlen + namelen + 3];
	const char *basename;
	u32 gid = inode->gid;

	if (dirlen) {
		strncpy(pname, dir, dirlen);
	}

	if (pathlen) {
		if (dirlen) {
			pname[dirlen] = '/';
			++dirlen;
		}
		strncpy(pname + dirlen, path, pathlen);
	}

	if (namelen) {
		if (pathlen + dirlen) {
			pname[dirlen + pathlen] = '/';
			++pathlen;
		}
		strncpy(pname + dirlen + pathlen, name, namelen);
	}

	pname[pathlen + dirlen + namelen] = 0;
	basename = namelen ? pname + dirlen + pathlen : "/";

	// Create things here
	//printmode(inode);
	//printuidgid(inode);

	if (S_ISREG(inode->mode)) {

		u32 size = inode->size;

		if (gid > DIR_GID) {
			// sirius: this is a special LG encoding of the size.
			// misusing gid field to encode the most significant byte of the size
			int lg = gid - DIR_GID;
			gid -= lg;
			lg = lg * 0x1000000;
			size += (lg);
		}

		do_file(base, inode->offset << 2, size, pname, basename, inode->mode);
	} else if (S_ISDIR(inode->mode)) {
		if (DIR_GID == 0) {
			DIR_GID = gid;
		}
		do_directory(base, inode->offset << 2, inode->size, pname, basename, inode->mode);
	} else if (S_ISLNK(inode->mode)) {
		do_symlink(base, inode->offset << 2, inode->size, pname, basename, inode->mode);
	} else if (S_ISFIFO(inode->mode)) {
		do_fifo(base, inode->offset << 2, inode->size, pname, basename, inode->mode, inode->uid, inode->gid);
	} else if (S_ISSOCK(inode->mode)) {
		do_socket(base, inode->offset << 2, inode->size, pname, basename, inode->mode);
	} else if (S_ISCHR(inode->mode)) {
		do_chrdev(base, inode->offset << 2, inode->size, pname, basename, inode->mode, inode->uid, inode->gid);
	} else if (S_ISBLK(inode->mode)) {
		do_blkdev(base, inode->offset << 2, inode->size, pname, basename, inode->mode, inode->uid, inode->gid);
	} else {
		do_unknown(base, inode->offset << 2, inode->size, pname, basename, inode->mode);
	}

	if (geteuid() == 0) {
		if (lchown(pname, inode->uid, gid) == -1)
			perror("cannot change owner or group");
	} else if (opt_idsfile && path && path[0]) {
		char dfp[1024];
		char *p;
		FILE *f;

		strcpy(dfp, pname);
		p = strrchr(dfp, '/');
		if (!p) {
			fprintf(stderr, "could not find path in '%s'\n", pname);
			return;
		}
		strcpy(p + 1, opt_idsfile);
		f = fopen(dfp, "at");
		if (!f) {
			perror(dfp);
			return;
		}
		fprintf(f, "%s,%u,%u,%08x\n", basename, inode->uid, inode->gid, inode->mode);
		fclose(f);
	}

	if (geteuid() == 0 || !opt_idsfile) {
		if (inode->mode & (S_ISGID | S_ISUID | S_ISVTX)) {
			if (0 != chmod(pname, inode->mode)) {
				perror("chmod");
				return;
			}
		}
	}
	//printf("\n");
}