Example #1
0
/*
 *                           u_openudp
 * Return a file descriptor.
 *  It is bound to the given port if the port is positive.
 *
 * parameter:
 *        port = number of port to bind to
 * returns:  file descriptor if successful
 *           -1 on error and sets errno
 */
int u_openudp(u_port_t port) {
   int error;
   int one = 1;
   struct sockaddr_in server;
   int sock;

   if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
      return -1;

   if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
      error = errno;
      r_close(sock);
      errno = error;
      return -1;
   }
       
   if (port > 0) {
      server.sin_family = AF_INET;
      server.sin_addr.s_addr = htonl(INADDR_ANY);
      server.sin_port = htons((short)port);
 
      if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == -1) {
         error = errno;
         r_close(sock);
         errno = error;
         return -1;
      }
   }
   return sock;
}
Example #2
0
void *copyfilepass(void *arg)  {
   int *argint;

   argint = (int *)arg;
   argint[2] = copyfile(argint[0], argint[1]);
   r_close(argint[0]);
   r_close(argint[1]);
   return argint + 2;
}
Example #3
0
/* usp Program 12.7 */
static void *copyfilepass(void *arg)
{
	copyinfo_t *cip;

	cip = (copyinfo_t *)arg;
	cip->bytescopied = copyfile(cip->sourcefd, cip->destinationfd);
	r_close(cip->sourcefd);
	r_close(cip->destinationfd);
	return (void *)(&cip->bytescopied);
}
Example #4
0
int32_t file_manager::remote_file::unbuffered_tell()   // ask server where the offset of the file pointer is
{
  if (sock)
  {
    uint8_t cmd=NFCMD_TELL;
    if (sock->write(&cmd,sizeof(cmd))!=sizeof(cmd)) { r_close("tell : could not send command"); return 0; }

    int32_t offset;
    if (sock->read(&offset,sizeof(offset))!=sizeof(offset)) { r_close("tell : could not read offset"); return 0; }
    return lltl(offset);
  }
  return 0;
}
Example #5
0
int32_t file_manager::remote_file::unbuffered_seek(int32_t offset)  // tell server to seek to a spot in a file
{
  if (sock)
  {
    uint8_t cmd=NFCMD_SEEK;
    if (sock->write(&cmd,sizeof(cmd))!=sizeof(cmd)) { r_close("seek : could not send command"); return 0; }

    int32_t off=lltl(offset);
    if (sock->write(&off,sizeof(off))!=sizeof(off)) { r_close("seek : could not send offset"); return 0; }

    if (sock->read(&offset,sizeof(offset))!=sizeof(offset)) { r_close("seek : could not read offset"); return 0; }
    return lltl(offset);
  }
  return 0;
}
Example #6
0
int main (int argc, char *argv[]) {
   time_t curtime;
   int len;
   char requestbuf[PIPE_BUF];
   int requestfd;

   if (argc != 2) {  /* name of server fifo is passed on the command line */
      fprintf(stderr, "Usage: %s fifoname\n", argv[0]);
      return 1;
   }

   if ((requestfd = open(argv[FIFOARG], O_WRONLY)) == -1) {
       perror("Client failed to open log fifo for writing");
       return 1;
   }

   curtime = time(NULL);
   snprintf(requestbuf, PIPE_BUF, "%d: %s", (int)getpid(), ctime(&curtime));
   len = strlen(requestbuf);
   if (r_write(requestfd, requestbuf, len) != len) {
      perror("Client failed to write");
      return 1;
   }
   r_close(requestfd);
   return 0;
}
/*Function to Handle the file close Call
 * INPUT:
 *      int conn :      Socket connection identifier
 *      char *recvBuff :Buffer containing request
 *
 * OUTPUT:
 *      int :   Success/Failure indicator.
 */
int
close_handler (int conn , char *recvBuff) {
        int ind = 3 , res = 0 , ret = -1;
        char sendBuff[1024] , len[5] , data[1000];
        r_file *file = (r_file *) malloc (sizeof (r_file));

        /*File Structure containing details of file to be Closed */
        memcpy (file , &recvBuff[ind] , sizeof (r_file));
        res = r_close (file);
        memset (sendBuff , 0 , sizeof (sendBuff));
        memset (data , 0 , sizeof (data));
        /*Marshal based on success or failure */
        if (res == 0) {
                sprintf (data , "%d" , res);
                strcat (sendBuff , data);
                ret = -1;
        } else {
                sprintf (data , "%d" , 1);
                strcat (sendBuff , data);
                memset (data , 0 , sizeof (data));
                /*Error code*/
                sprintf (data , "%d" , res);
                strcat (sendBuff , data);
                ret = 0;
        }
        /*Sending data to the Client */
        write (conn , sendBuff , sizeof (sendBuff) - 1);
out:
        return ret;
}
Example #8
0
int file_manager::remote_file::unbuffered_read(void *buffer, size_t count) {
	if (sock && count) {
		uint8_t cmd = NFCMD_READ;
		if (sock->write(&cmd, sizeof(cmd)) != sizeof(cmd)) {
			r_close("read : could not send command");
			return 0;
		}

		int32_t rsize = lltl(count);
		if (sock->write(&rsize, sizeof(rsize)) != sizeof(rsize)) {
			r_close("read : could not send size");
			return 0;
		}

		int32_t total_read = 0;
		char buf[READ_PACKET_SIZE];

		ushort packet_size;
		do {
			if (sock->read(&packet_size, sizeof(packet_size))
					!= sizeof(packet_size)) {
				fprintf(stderr, "could not read packet size\n");
				return 0;
			}

			packet_size = lstl(packet_size);

			ushort size_read = sock->read(buf, packet_size);

			if (size_read != packet_size) {
				if (sock->read(buf + 2 + size_read, packet_size - size_read)
						!= packet_size - size_read) {
					fprintf(stderr, "incomplete packet\n");
					return 0;
				}
			}

			memcpy(buffer, buf, packet_size);
			buffer = (void *) (((char *) buffer) + packet_size);

			total_read += packet_size;
			count -= packet_size;
		} while (packet_size == READ_PACKET_SIZE - 2 && count);
		return total_read;
	}
	return 0;
}
Example #9
0
/*
 *                       UICI Server
 *  Open a UICI port specified as a command-line argument
 *  and wait for requests.  When a request arrives,
 *  fork a child to handle the communication and resume
 *  waiting for another request.
 */
int main(int argc, char *argv[])
{
   u_port_t portnumber;
   int listenfd;
   int communfd;
   char client[MAX_CANON];
   int bytes_copied;
   pid_t child;

   if (argc != 2) {
      fprintf(stderr, "Usage: %s port\n", argv[0]);
      return 1;
   }

   portnumber = (u_port_t) atoi(argv[1]);
   if ((listenfd = u_open(portnumber)) < 0) {
      perror("Listen endpoint creation failed");
      return 1;
   }

   fprintf(stderr, "[%ld]: Waiting for the first connection on port %d\n",
                    (long)getpid(), (int)portnumber);
   for ( ; ; ) {
      if ((communfd = u_accept(listenfd, client, MAX_CANON)) != -1) {
         fprintf(stderr, "[%ld]: A connection has been received from %s\n",
                 (long) getpid(), client);
         if ((child = fork()) == -1)
            perror("Could not fork a child");

         if (child == 0) {                            /* child code */
            r_close(listenfd);
            bytes_copied =
               copy2files(communfd, STDOUT_FILENO, STDIN_FILENO, communfd);
            r_close(communfd);
            fprintf(stderr, "[%ld]:Bytes transferred = %d\n",
                           (long) getpid(), bytes_copied);
            return 0;
         } else {                                    /* parent code */
            r_close(communfd);
            while (r_waitpid(-1, NULL, WNOHANG) > 0) ;  /* clean up zombies */
         }
      }
      else
         perror("Accept failed");
   }
}
Example #10
0
void monitorselect(int fd[], int numfds) {
   char buf[BUFSIZE];
   int bytesread;
   int i;
   int maxfd;
   int numnow, numready;
   fd_set readset;

   maxfd = 0;                  /* set up the range of descriptors to monitor */
   for (i = 0; i < numfds; i++) {
       if ((fd[i] < 0) || (fd[i] >= FD_SETSIZE))
          return;
       if (fd[i] >= maxfd)
          maxfd = fd[i] + 1;
   }
   numnow = numfds;
   while (numnow > 0) {            /* continue monitoring until all are done */
      FD_ZERO(&readset);                  /* set up the file descriptor mask */
      for (i = 0; i < numfds; i++)
         if (fd[i] >= 0)
            FD_SET(fd[i], &readset);
      numready = select(maxfd, &readset, NULL, NULL, NULL);  /* which ready? */
      if ((numready == -1) && (errno == EINTR))     /* interrupted by signal */
         continue;
      else if (numready == -1)                          /* real select error */
         break;
      for (i = 0; (i < numfds) && (numready > 0); i++) { /* read and process */
         if (fd[i] == -1)                         /* this descriptor is done */
            continue;
         if (FD_ISSET(fd[i], &readset)) {        /* this descriptor is ready */
            bytesread = r_read(fd[i], buf, BUFSIZE);
            numready--;
            if (bytesread > 0)
               docommand(buf, bytesread);
            else  {           /* error occurred on this descriptor, close it */
               r_close(fd[i]);
               fd[i] = -1;
               numnow--;
            }
         }
      }
   }
   for (i = 0; i < numfds; i++)
       if (fd[i] >= 0)
           r_close(fd[i]);
}
Example #11
0
void proxy_context_uninit(ProxyContext * proxy_context)
{
    if (proxy_context->client_fd != -1 )
        r_close(proxy_context->client_fd);
    //if (proxy_context->mailhdr_fd != -1 )
    //  r_close(proxy_context->mailhdr_fd);
    if (proxy_context->server_fd != -1 )
    {
        if (proxy_context->ssl_enable)
            SSL_destroy_conn(proxy_context->server_fd, proxy_context->ssl, proxy_context->ctx, proxy_context->sbio);
        else
            r_close(proxy_context->server_fd);
    }
    if (!loop)
        paramlist_uninit(&proxy_context->params);
    linebuf_uninit(proxy_context->client_buf);
    linebuf_uninit(proxy_context->server_buf);
//  if (config->broken)
//      linebuf_uninit(proxy_context->hdrbuf);
    free(proxy_context);
}
Example #12
0
static int
real_close(int fd)
{
	static int (*r_close)(int fd) = NULL;

	if (!r_close)	{
		if ((r_close = dlsym(libc_handle, "close")) == NULL)	{
			__set_errno(ENOSYS);
			return -1;
		}
	}
	return r_close(fd);
}
Example #13
0
int putblock(char *fname, int blknum, char *data) {
  int error = 0;
  int file;

  if ((file = open(fname, O_WRONLY|O_CREAT, PUTBLOCK_PERMS)) == -1)
     return -1;
  if (lseek(file, blknum*BLKSIZE, SEEK_SET) == -1)
     error = errno;
  else if (r_write(file, data, BLKSIZE) == -1)
     error = errno;
  if ((r_close(file) == -1) && !error)
     error = errno;
  if (!error)
     return 0;
  errno = error;
  return -1;
}
Example #14
0
int main()
{
	char *cmdline, *prompt, **arglist, **cmdlist;
	char rfileName[32];
	int result, fd_out, i, fno, cmdNum, rioFlag;
	int sfd = dup(STDOUT_FILENO);
	void setup();

	prompt = DFL_PROMPT;
	setup();

	cmdlist = emalloc(BUFSIZ);
	while ((cmdline = next_cmd(prompt, stdin)) != NULL)
	{
		/* io redirection */
		rioFlag = getRFileName(cmdline, rfileName);
		if (rioFlag > 0)
			fd_out = r_open(rfileName);
		
		/* pipe test*/
		cmdNum = pipeTest(cmdline, cmdlist);
		if (cmdNum == 1)
		{
			if ((arglist = splitline(cmdline)) != NULL)
			{
				if (buildIn(arglist))
				{
					;
				} else {
					result = execute(arglist);
					freelist(arglist);
				}
			}
		} 
		else if (cmdNum == 2) 
		{
			pipeCommand(cmdlist);
		}
		//freelist(cmdlist);
		free(cmdline);
		if (rioFlag > 0)
			r_close(sfd);
	}
	return 0;
}
Example #15
0
int gettermios(struct termios *termp) { 
   int fd;
   int firsterrno = 0;
   char termbuf[L_ctermid];
             
   if (ctermid(termbuf) == NULL) {                /* find the terminal name */
      errno = ENODEV;
      return -1;
   }
   if ((fd = r_open2(termbuf, O_RDONLY)) == -1)        /* open the terminal */
      return -1;
   if (tcgetattr(fd, termp) == -1)                       /* get its termios */
      firsterrno = errno;
   if ((r_close(fd) == -1) && !firsterrno)
      firsterrno = errno;
   if (firsterrno) {
      errno = firsterrno;
      return -1;
   }
   return 0;
}
Example #16
0
int main() {
    /* my.file's file descriptor */
    int fd;

    /* Open or create my.file */
    fd = open("my.file", CREATE_FLAGS, CREATE_MODE);
    /* If there was an error opening my.file */
    if (fd == -1) {
        /* Print an error */
        perror("Failed to open my.file");
        /* Return 1 to indicate the error to the shell */
        return 1;
    }
    /* Make a duplicate of my.file's file descriptor using STDOUT_FILENO
     * (if STDOUT_FILENO is open, close it first).
     */
    if (dup2(fd, STDOUT_FILENO) == -1) {
        /* If dup2 returns -1, print an error message */
        perror("Failed to redirect standard output");
        /* And return 1 to the shell to indicate an error occurred */
        return 1;
    }
    /* Close the old file descriptor. */
    if (r_close(fd) == -1) {
        /* If r_close() returned an error, print an error message */
        perror("Failed to close the file");
        /* Return 1 to the shell to indicate the error condition */
        return 1;
    }
    /* Write "OK" to STDOUT_FILENO (my.file) */
    if (write(STDOUT_FILENO, "OK", 2) == -1) {
        /* If an write() returns an error, print an error message */
        perror("Failed in writing to file");
        /* Return 1 to the shell to indicate the error condition */
        return 1;
    }
    /* If we made it here, everything went well. So return 0
     * to the shell to indicate success. */
    return 0;
}
Example #17
0
/**
 * @brief Handle client disconnection and free resources
 *
 * @param loop The event loop where the event was issued
 * @param w The async event object
 * @param revents Unused
 *
 * This event is triggered when a client disconnects or is forcefully
 * disconnected. It stops the other events from running, and frees all
 * the remaining resources for the client itself.
 */
static void client_ev_disconnect_handler(struct ev_loop *loop,
                                         ev_async *w,
                                         int revents)
{
    RTSP_Client *rtsp = (RTSP_Client*)w->data;
    GString *outbuf = NULL;
    feng *srv = rtsp->srv;

    ev_io_stop(srv->loop, &rtsp->ev_io_read);
    ev_io_stop(srv->loop, &rtsp->ev_io_write);
    ev_async_stop(srv->loop, &rtsp->ev_sig_disconnect);
    ev_timer_stop(srv->loop, &rtsp->ev_timeout);

    Sock_close(rtsp->sock);
    srv->connection_count--;

    rtsp_session_free(rtsp->session);
    
    r_close(rtsp->cached_resource);

    interleaved_free_list(rtsp);

    /* Remove the output queue */
    while( (outbuf = g_queue_pop_tail(rtsp->out_queue)) )
        g_string_free(outbuf, TRUE);

    g_queue_free(rtsp->out_queue);

    g_byte_array_free(rtsp->input, true);

    g_slice_free(RTSP_Client, rtsp);

    fnc_log(FNC_LOG_INFO, "[client] Client removed");

    demuxer_stsw_global_uninit();
    
	sleep(1);
	exit(0);

}
Example #18
0
int main(int argc, char *argv[])
{
	
	time_t curtime;
	int len;
	char buf[PIPE_BUF];
	int fd;

	if (argc != 2)
		err_quit("Usage: %s filename", argv[0]);

	if ((fd = open(argv[1], O_WRONLY)) == -1)
		err_sys("client: open logfile failed: %s", argv[1]);

	curtime = time(NULL);
	snprintf(buf, PIPE_BUF, "%d: %s", (int)getpid(), ctime(&curtime));
	len = strlen(buf);
	if (r_write(fd, buf, len) != len)
		err_sys("client: failed to write");
	r_close(fd);
	return 0;
} 
int main(int argc, char *argv[]) {
   ssize_t bytesread, byteswritten;
   char request[BUFSIZE]; 
   int requestfd;
   char reply[BUFSIZE];  
   u_port_t serverport;
   double timeout;
   int retries;
  
   if (argc != 5) {
      fprintf(stderr, "Usage: %s servername serverport timeout retries\n",
              argv[0]);
      return 1;  
   }
   serverport = (u_port_t) atoi(argv[2]);
   timeout = atof(argv[3]);
   retries = atof(argv[4]);
   if ((requestfd = u_openudp(0)) == -1) {  /* create an unbound UDP endpoint */
      perror("UDP endpoint creation failed");
      return 1;
   }
   sprintf(request, "[%ld]\n", (long)getpid());      /* create request string */
                 /* use request-reply protocol with timeout to send a message */
   bytesread = request_reply_timeout_retry(requestfd, request,
                        strlen(request) + 1, argv[1],
                        serverport, reply, BUFSIZE, timeout, retries);
   if (bytesread < 0)
      perror("Failed to complete request_reply_timeout_retry");
   else {
      byteswritten = r_write(STDOUT_FILENO, reply, bytesread);
      if (byteswritten < 0)
         perror("Failed to echo server reply");
   }
   if (r_close(requestfd) == -1 || bytesread < 0 || byteswritten < 0)
      return 1;
   return 0;
}
/*Client API function to Close the Remote File
 *
 * INPUT:
 *      struct r_file **file1 : File to be closed
 *
 * OUTPUT:
 *      int : Success/Failure indicator
 */
int
rClose (struct r_file **file1) {
        r_file *file = *file1;
        int ret = -1;

        if (file != NULL && file->inode_number != 0) {
                printf ("\nINODE : %lu - FD : %d\n" ,
                        file->inode_number , file->fd);
        } else {
                printf ("Invalid Request\n\n");
                ret = 1;
                goto out;
        }
        ret = r_close (file);
        if (ret == 0) {
                printf ("Requested file is closed\n");
                printf ("Operation Successful\n\n");
                ret = 0;
                goto out;
        } else if (ret == file_not_open) {
                printf ("ERROR: Requested file is not Open\n");
        } else {
                printf ("ERROR: Error in Closing the file\n");
        }
        printf ("Operation Failed\n\n");
        ret = 1;
out:
        if (ret == 0) {
                free (file);
                *file1 = NULL;
                close (sockfd);
                sockfd = -1;
                ret = 1;
        }
        return ret;
}
Example #21
0
int settermios(struct termios *termp) { 
   int error;
   int fd;
   int firsterrno = 0;
   char termbuf[L_ctermid];
   
   if (ctermid(termbuf) == NULL) {                /* find the terminal name */
      errno = ENODEV;
      return -1;
   }
   if ((fd = r_open2(termbuf, O_RDONLY)) == -1)        /* open the terminal */
      return -1;
   while (((error = tcsetattr(fd, TCSAFLUSH, termp)) == -1) && 
           (errno == EINTR)) ;
   if (error)
      firsterrno = errno;
   if ((r_close(fd) == -1) && !firsterrno)
      firsterrno = errno;
   if (firsterrno) {
      errno = firsterrno;
      return -1;
   }
   return 0;
}
Example #22
0
file_manager::remote_file::remote_file(net_socket *sock, char const *filename, char const *mode, remote_file *Next) : sock(sock)
{
  next=Next;
  open_local=0;

  uint8_t sizes[3]={ CLIENT_NFS,strlen(filename)+1,strlen(mode)+1};
  if (sock->write(sizes,3)!=3) { r_close("could not send open info"); return ; }
  if (sock->write(filename,sizes[1])!=sizes[1]) { r_close("could not send filename"); return ; }
  if (sock->write(mode,sizes[2])!=sizes[2]) { r_close("could not send mode"); return ; }

  int32_t remote_file_fd;
  if (sock->read(&remote_file_fd,sizeof(remote_file_fd))!=sizeof(remote_file_fd))
  { r_close("could not read remote fd"); return ; }
  remote_file_fd=lltl(remote_file_fd);
  if (remote_file_fd<0) { r_close("remote fd is bad"); return ; }

  if (sock->read(&size,sizeof(size))!=sizeof(size)) { r_close("could not read remote filesize"); return ; }

  size=lltl(size);
}
Example #23
0
file_manager::remote_file::~remote_file() {
	r_close(NULL);
}
Example #24
0
/*
 * Run as a daemon. Based on Section 13.3 in _Advanced Programming in the
 * UNIX Environment_ by Stevens.
 *
 * Returns 0 on success and -1 on error.
 */
static int daemonize() {
  char *pid_str = NULL;
  int ret = 0, i, open_max, pid_fd = -1;

  /* Fork once to make sure we're not a process group leader. */
  switch (fork()) {
  case -1:
    log_perror(NULL, "Couldn't fork process when daemonizing");
    ret = -1;
    goto cleanup;

  case 0:
    break;

  default:
    _exit(0);
  }

  /* Become the leader of a new session and process group, and change to the
   * root directory. */
  if (setsid() == -1) {
    log_perror(NULL, "Couldn't become a session leader");
    ret = -1;
    goto cleanup;
  }

  if (chdir("/")) {
    log_perror(NULL, "Couldn't change to root directory");
    ret = -1;
    goto cleanup;
  }

  /* Fork again so that we aren't a process group leader anymore, preventing
   * us from acquiring a controlling terminal. */
  switch (fork()) {
  case -1:
    log_perror(NULL, "Couldn't fork process when daemonizing");
    ret = -1;
    goto cleanup;

  case 0:
    break;

  default:
    _exit(0);
  }

  /* Record our new server PID. */
  g_server_pid = getpid();

  /* Set a permissive file mode mask. */
  umask(0);

  /* Create a PID file, and prepare to delete it on exit. */
  if ((pid_fd = r_open(g_config.pid_file, O_WRONLY | O_CREAT | O_EXCL,
          PID_FILE_MODE)) == -1) {
    log_perror(NULL, "Couldn't create PID file for writing");
    ret = -1;
    goto cleanup;
  }

  if (asprintf(&pid_str, "%ld\n", (long) g_server_pid) < 0) {
    log_perror(NULL, "Couldn't allocate PID string");
    ret = -1;
    goto cleanup;
  }

  if (r_write(pid_fd, pid_str, strlen(pid_str)) == -1) {
    log_perror(NULL, "Couldn't write to PID file");
    ret = -1;
    goto cleanup;
  }

  atexit(delete_pid_file);

  /* Close all (possibly) open files. */
  errno = 0;
  if ((open_max = (int) sysconf(_SC_OPEN_MAX)) == -1 && errno) {
    log_perror(NULL, "Couldn't determine maximum file descriptor");
    ret = -1;
    goto cleanup;
  }

  for (i = 0; i < ((open_max != -1) ? open_max : OPEN_MAX); ++i) {
    if (r_close(i) == -1 && errno != EBADF) {
      log_perror(NULL, "Couldn't close file descriptor when daemonizing");
      ret = -1;
      goto cleanup;
    }
  }

  /* Reopen stdin, stdout, and stderr, redirecting them to /dev/null. */
  if (r_open("/dev/null", O_RDONLY) != STDIN_FILENO
      || r_open("/dev/null", O_WRONLY) != STDOUT_FILENO
      || dup(STDOUT_FILENO) != STDERR_FILENO) {
    log_perror(NULL, "Couldn't redirect standard streams to /dev/null");
    ret = -1;
    goto cleanup;
  }

cleanup:
  r_close(pid_fd);
  free(pid_str);

  if (ret == -1 && pid_fd != -1) {
    unlink(g_config.pid_file);
  }

  return ret;
}
int main (int argc, char * argv[]){
	
	int fd, i, j;
	char *req, *rel; 
	char buf[256];
	int n;
	long name_max;
	ssize_t amount_read;
	
	// Check for the proper number of arguments
	
	if (argc != 3){
		fprintf(stderr, "Usage: %s [barrier name] [barrier size]\n", argv[0]);
		return 1;
	}
	
	// The atoi() function has been deprecated by strtol().
	// strtol is mulithread safe on the lab's target machine.
	n = (int)strtol(argv[2], NULL, 10);  
	
	
	if ((name_max = allocate_filename_strings(&req, &rel)) < 2){
		return 1;
	}
	// Decrease name_max to allow room for ".request" and ".release" extensions
	name_max = name_max-9;
	// Make sure the filesystem can support the argument.
	if (strlen(argv[1]) > name_max){
		fprintf(stderr, "File name too long.");
		return 1;
	}
	
	strncpy(req, argv[1], name_max);
	strncpy(rel, argv[1], name_max);
	
	if (mkfifo(strcat(req,".request"), FIFO_PERMS) == -1){
		fprintf(stderr, "%s cannot be created.  May already exist!\n", req);
		//exit(0);
	}
	
	if (mkfifo(strcat(rel,".release"), FIFO_PERMS) == -1){
		fprintf(stderr, "%s cannot be created.  May already exist!\n", rel);
		//exit(0);
	}
	
	for (j = 0; j < 2; j++){
		// READING FROM NAME.REQUEST
		printf("Attempting to open request FIFO.\n");	
		// Open name.request
		if ((fd = r_open2(req, O_RDONLY)) == -1){ 
			fprintf(stderr, "Cannot open %s for reading\n", req);
			return 1;
		}else{
			printf("Opened %s for reading.\n", req);
		}
		for (i = 0; i < n; i++){
			// Read from name.request - put into buf, read n chars/bytes
			
			if ((amount_read = r_read(fd, buf, 1)) != 1){
				printf("Failed to read a byte from request FIFO.\n");
				//exit(0);
			}else{
				printf("Read %d byte from %s.\n", amount_read, req);
				sleep(1); //give the client process a chance to close the FIFO.
			}
		}
		
		
		// Close name.request
		if (r_close(fd) == -1){
			fprintf(stderr, "Cannot close %s!\n", req);
			exit(0);
		}else{
			printf("Closed %s.\n", req);
		}
		
		
		printf("Attempting to open %s.\n",rel);
		if ((fd = r_open2(rel, O_WRONLY)) == -1){
			fprintf(stderr, "Cannot open %s for writing\n", rel);
			return 1;
		}else{
			printf("Opened %s for writing.\n", rel);
		}
		
		printf("Attempting to write to %s.\n",rel);
		// Write to name.release from buf, write n chars/bytes
		for (i = 0; i < n; i++){
			if (r_write(fd, rel, 1) != 1){
				fprintf(stderr, "Cannot write to %s\n", rel);
				exit(0);
			}else{
				printf("Writing to %s...\n", rel);
				sleep(1); //give another client proces a chance to open the FIFO
			}
		}
		// Close name.release
		if (r_close(fd) == -1){
			fprintf(stderr, "Cannot close %s!\n", rel);
			exit(0);
		}else{
			printf("Closed %s.\n", rel);
		}
		
	}
	
	sleep(2); // Allow clients a chance to finish with FIFOs.
	if (unlink(req) == -1)
		perror("Server failed to unlink request FIFO");
	if (unlink(rel) == -1)
		perror("Server failed to unlink release FIFO");	
	return 1;
}
/**
 * @brief Create description for an SDP session
 *
 * @param uri URI of the resource to describe
 *
 * @return A new GString containing the complete description of the
 *         session or NULL if the resource was not found or no demuxer
 *         was found to handle it.
 */
static GString *sdp_session_descr(RTSP_Client *rtsp, RFC822_Request *req)
{
    URI *uri = req->uri;
    GString *descr = NULL;
    double duration;

    float currtime_float, restime_float;

    Resource *resource;

    char *path;

    const char *inet_family;

    if ( rtsp->peer_sa == NULL ) {
        xlog(LOG_ERR, "unable to identify address family for connection");
        return NULL;
    }

    inet_family = rtsp->peer_sa->sa_family == AF_INET6 ? "IP6" : "IP4";
    path = g_uri_unescape_string(uri->path, "/");

    xlog(LOG_DBG, "[SDP] opening %s", path);
    if ( !(resource = r_open(path)) ) {
        xlog(LOG_ERR, "[SDP] %s not found", path);
        g_free(path);
        return NULL;
    }
    g_free(path);

    descr = g_string_new("v=0"SDP_EL);

    /* Near enough approximation to run it now */
    currtime_float = NTP_time(time(NULL));
    restime_float = resource->mtime ? NTP_time(resource->mtime) : currtime_float;

    /* Network type: Internet; Address type: IP4. */
    g_string_append_printf(descr, "o=- %.0f %.0f IN %s %s"SDP_EL,
                           currtime_float, restime_float,
                           inet_family,
                           uri->host);

    /* We might want to provide a better name */
    g_string_append(descr, "s=RTSP Session\r\n");

    g_string_append_printf(descr,
                           "c=IN %s %s"SDP_EL,
                           inet_family,
                           rtsp->local_host);

    g_string_append(descr, "t=0 0"SDP_EL);

    // type attribute. We offer only broadcast
    g_string_append(descr, "a=type:broadcast"SDP_EL);

    /* Server signature; the same as the Server: header */
    g_string_append_printf(descr, "a=tool:%s"SDP_EL,
                           feng_signature);

    // control attribute. We should look if aggregate metod is supported?
    g_string_append(descr, "a=control:*"SDP_EL);

    if ((duration = resource->duration) > 0 &&
        duration != HUGE_VAL)
        g_string_append_printf(descr, "a=range:npt=0-%f"SDP_EL, duration);

    g_list_foreach(resource->tracks,
                   sdp_track_descr,
                   descr);

    r_close(resource);

    xlog(LOG_INF, "[SDP] description:\n%s", descr->str);

    return descr;
}
Example #27
0
int main(int argc, const char* argv[]) {

	struct sockaddr_in user1Addr, user2Addr;
	int sock, i, slen = sizeof(user2Addr);
	char* server = "127.0.0.1"; /* change this to use a different server */
	int bufSize = BRP_MTU;
	char* buf;
	int retVal;

	/*
	 *  get the optional arguments according to the number of arguments
	 * */
	if(argc >= 2){
		server = argv[1];
	}

	/* create a socket */

	if ((sock = r_socket(AF_INET, SOCK_BRP, 0)) == -1)
		printf("socket created\n");

	/* to bind the socket to all local addresses and described protocol */
	memset((char *) &user1Addr, 0, sizeof(user1Addr));
	user1Addr.sin_family = AF_INET;
	user1Addr.sin_addr.s_addr = htonl(INADDR_ANY);
	user1Addr.sin_port = user1portNum;

	/* bind the socket with given port and address */
	if (r_bind(sock, (struct sockaddr *) &user1Addr, sizeof(user1Addr)) < 0) {
		perror("bind failed");
		return 0;
	}

	/* now define user2Addr, the address to whom we want to send messages */
	/* For convenience, the host address is expressed as a numeric IP address */
	/* that we will convert to a binary format via inet_aton */
	memset((char *) &user2Addr, 0, sizeof(user2Addr));
	user2Addr.sin_family = AF_INET;
	user2Addr.sin_port = htons(user2portNum);
	if (inet_aton(server, &user2Addr.sin_addr) == 0) {
		fprintf(stderr, "inet_aton() failed\n");
		exit(1);
	}

	/* set the buf*/
	buf = (char*) malloc(bufSize);
	memset(buf, 0, bufSize);

	/* go into infinite loop to and get the bytes to send */
	while (1) {
		printf("enter the message you wish to send:\n");
		fgets(buf, bufSize - 1, stdin);
		/*fragment each byte in the message and send it using BRP socket*/
		for (i = 0; i < strlen(buf); i++) {
			if (r_sendto(sock, &buf[i], 1, 0, (struct sockaddr *) &user2Addr,
					slen) == -1)
				perror("sendto");
		}
		memset(buf, 0, bufSize);
	}
	r_close(sock);
	return 0;
}
Example #28
0
void _fl_close (int *w)					{ r_close ((int)(w[0]), (int *)(w[1])); }
Example #29
0
ArchivoRegVars::~ArchivoRegVars(){ //dtor
    r_close();
}
Example #30
0
unsigned long send_mailfile(char * mailfile,  ProxyContext *p)
{

    struct LineBuffer *filebuf, *footbuf;
    int mailfd, footfd;
    int res = 0, sendret = 0, gotprd = 0, gottxt = 0, nogo = 0;
    unsigned long len = 0;
    char svrout[1];

    if ((mailfd = r_open2(mailfile, O_RDONLY )) < 0)
    {
        proxy_context_uninit(p);
        // Emergency: send_mailfile: Can't open client mail file.
        g_gateway_config->emergency = make_message("Can't open mailfile (%s)!", mailfile);
        do_log(LOG_EMERG, "ERR: Can't open mailfile (%s)!", mailfile);
        return 0;
    }
    filebuf = linebuf_init(16384);
    footbuf = linebuf_init(512);
    if (!filebuf)
    {
        r_close(mailfd);

        if (p->ssl_enable)
        {
            SSL_shutdown(p->ssl);
            /* 释放SSL */
            SSL_free(p->ssl);
        }

        r_close(p->server_fd);
        proxy_context_uninit(p);
        // Emergency: send_mailfile: Unable to get memory.
        g_gateway_config->emergency = "Could not allocate memory for sending mail!";
        do_log(LOG_EMERG, "ERR: Could not allocate memory for sending mail!");
    }

    gotprd = 0;
    /*  // advance to mailfd pointer to past data already sent:
        if (config->broken)
        {
            if (p->hdroffset && !p->gobogus)
            {
                while (p->hdroffset)
                {
                    res = getlinep3(mailfd, filebuf, NULL);
                    p->hdroffset--;
                }
            }
        }
        else
        {
            if (p->hdroffset)
            {
                lseek(mailfd, p->hdroffset, SEEK_SET);
            }
            // See if bogus headerline sent
            if (p->gobogus)
            {
                if (p->boguspos < 91)
                {
                    svrout[0] = BOGUSX[p->boguspos];
                    secure_write(p->client_fd, svrout, 1, p->ssl_server);
                    p->boguspos++;
                }
                //now close it
                writeline(p->client_fd, WRITELINE_LEADING_RN, PERIOD, p->ssl_server);
                p->gobogus = 0;
            }
        }*/
    while (1)
    {
        /*
        sendret = checktimeout(p);
        if (sendret == GETLINE_PIPE)
        {
            do_log(LOG_CRIT, "ERR: Client disappeared during mail send!");
            linebuf_uninit(filebuf);
            return EPIPE;
        }
        else if (sendret)
        {
            context_uninit(p);
            linebuf_uninit(filebuf);
        // Emergency: send_mailfile: Sending mail to client
            g_gateway_config->emergency = "Sending mail to client";
            do_log(LOG_EMERG, "ERR: Sending mail to client");
            // we are dead now. Should not reach here. But allow it to fall through in case LOG_EMERG is changed in the future.
            return 1;
        }*/


        //to do check timeout

        if ((res = get_line(mailfd, filebuf)) < 0)
        {
            if (res == GETLINE_TOO_LONG)
            {
                // Buffer contains part of line,
                //take care of later
            }
            else
            {
                // Other error, take care of later
                break;
            }
        }
        if (filebuf->linelen >= 0 )
        {
            len += filebuf->linelen;
            //if (config->debug_message)
            do_log(LOG_DEBUG, ">%s", filebuf->line);

            if ((strncmp(filebuf->line, ".", 1 ) == 0 && strlen(filebuf->line) == 1))
                gotprd = 1;
            if ((strncmp(filebuf->line, ".\r", 2) == 0 && strlen(filebuf->line) == 2))
                gotprd = 1;

            /*
            //if ((strncmp(filebuf->line,"Content-Type: application/pgp-signature",39)==0 && strlen(filebuf->line)==39)) gotpgp=1;
            //if (gotpgp) nogo=1;
            if (strncmp(filebuf->line, "Content-Type: ", 14) == 0)
            {
                if ((strncmp(filebuf->line, "Content-Type: text/plain;", 25) == 0 && strlen(filebuf->line) == 25)) gottxt = 1;
                else nogo = 1;
            }
            */

            /*
            if ( gotprd && !nogo)
            {
                if ((footfd = r_open2(FOOTER, O_RDONLY)) >= 0)
                {
                    sendret = writeline(fd, WRITELINE_LEADING_RN, "**********", p->ssl_server);
                    while (1)
                    {
                        if ((sendret = getlinep3(footfd, footbuf, NULL)) < 0) break;
                        if (footbuf->linelen >= 0 ) sendret = writeline(fd, WRITELINE_LEADING_RN, footbuf->line, p->ssl_server);
                    }
                    r_close(footfd);
                    writeline_format(fd, NULL, WRITELINE_LEADING_RN, PROGRAM" "VERSION" running on %s.%s", paramlist_get(p->params, "%HOSTNAME%"), paramlist_get(p->params, "%DOMAINNAME%"));
                    sendret = writeline_format(fd, NULL, WRITELINE_LEADING_RN, "%s", paramlist_get(p->params, "%VDINFO%"));
                    sendret = writeline(fd, WRITELINE_LEADING_RN, "**********", p->ssl_server);
                }
            }*/

            // Take care of buffer here
            if (res == GETLINE_TOO_LONG)
            {

                if (p->ssl_enable)
                    sendret = write_line_ssl(p->ssl, WRITELINE_LEADING_NONE, filebuf->line);
                else
                    sendret = write_line(p->server_fd, WRITELINE_LEADING_NONE, filebuf->line);
            }
            else
            {
                if (!gotprd)
                {

                    if (p->ssl_enable)
                        sendret = write_line_ssl(p->ssl, WRITELINE_LEADING_RN, filebuf->line);
                    else
                        sendret = write_line(p->server_fd, WRITELINE_LEADING_RN, filebuf->line);
                }

            }


            if (sendret == GETLINE_PIPE)
            {
                do_log(LOG_CRIT, "ERR: Client disappeared during mail send!");
                linebuf_uninit(filebuf);
                return EPIPE;
            }
            else if (sendret)
            {
                proxy_context_uninit(p);
                linebuf_uninit(filebuf);
                // Emergency: send_mailfile: Sending mail to client
                g_gateway_config->emergency = "Sending mail to client";
                do_log(LOG_EMERG, "ERR: Sending mail to client");
                // we are dead now. Should not reach here. But allow it
                //to fall through in case LOG_EMERG is changed in the future.
                return 1;
            }
        }


    }

    if (res != GETLINE_EOF)
    {
        do_log(LOG_CRIT, "ERR: reading from mailfile %s, error code: %d", mailfile, res);
        linebuf_uninit(filebuf);
        return 1;
    }

    if (!gotprd)
    {
        do_log(LOG_DEBUG, "Wrote new EOM.");

        if (p->ssl_enable)
            write_line_ssl(p->ssl, WRITELINE_LEADING_RN, ".");
        else
            write_line(p->server_fd, WRITELINE_LEADING_RN, ".");
    }
    linebuf_uninit(filebuf);
    r_close(mailfd);
    return len;

}