Ejemplo n.º 1
0
void setup_for_childproc(int fd, char close_fd_0, char *term)
{
	int term_len = strlen(term) + 5;
	char *dummy = (char *)mymalloc(term_len + 1);

	if (close_fd_0) if (-1 == myclose(0)) error_exit(TRUE, FALSE, "close() failed\n");
	if (-1 == myclose(1)) error_exit(TRUE, FALSE, "close() failed\n");
	if (-1 == myclose(2)) error_exit(TRUE, FALSE, "close() failed\n");
	if (close_fd_0) if (-1 == mydup(fd)) error_exit(TRUE, FALSE, "dup() failed\n");
	if (-1 == mydup(fd)) error_exit(TRUE, FALSE, "dup() failed\n");
	if (-1 == mydup(fd)) error_exit(TRUE, FALSE, "dup() failed\n");

	/*
	 * not doing this: it also clears the 'PATH'
	 * I could make first do a getenv for PATH and then put it
	 * back after the clearenv, but what would be the point of
	 * doing the clearenv in the first place?
	 *
	 *	if (clearenv() == -1)
	 *	{
	 *		fprintf(stderr, "WARNING: could not clear environment variables: %s (%d)\n", strerror(errno), errno);
	 *		exit(1);
	 *	}
	 */

	/* set terminal */
	assert(term != NULL);
	snprintf(dummy, term_len, "TERM=%s", term);
	if (putenv(dummy) == -1)
		fprintf(stderr, "setup_for_childproc: Could not set TERM environment-variable (%s): %s (%d)\n", dummy, strerror(errno), errno);

	(void)umask(007);
}
Ejemplo n.º 2
0
Archivo: miscfuncs.c Proyecto: aosm/X11
int ftruncate_emu(
    int fd,
    off_t length,
    char *name)
{
    char            tmp_file[15];
    int             new_fid, bytes_left, i;
    unsigned char   buffer[CHUNKSIZE];
    struct stat     stat_val;

    /* Open a temp file. */
    sprintf(tmp_file, ".xmhtmp%d~", getpid());
    (void) unlink(tmp_file);
    new_fid = open(tmp_file, O_RDWR | O_CREAT);
    lseek(fd, (off_t)0, 0);
	
    /* Copy original file to temp file. */
    for (i = 0; i < length / CHUNKSIZE; i++) {
	if (read(fd, buffer, CHUNKSIZE) != CHUNKSIZE) {
	    (void)fprintf(stderr, "xmh: read error in ftruncate emulation\n");
	    return -1;
	}
	else if (write(new_fid, buffer, CHUNKSIZE) != CHUNKSIZE) {
	    (void)fprintf(stderr, "xmh: write error in ftruncate emulation\n");
	    return -1;
	}
    }
    bytes_left = length % CHUNKSIZE;
    if (read(fd, buffer, bytes_left) != bytes_left) {
	(void)fprintf(stderr, "xmh: read error in ftruncate() emulation\n");
	return -1;
    }
    else if (write(new_fid, buffer, bytes_left) != bytes_left) {
	(void)fprintf(stderr, "xmh: write error in ftruncate() emulation\n");
	return -1;
    }

    /* Set mode of temp file to that of original file. */
    (void) fstat(fd, &stat_val);
    (void) chmod(tmp_file, stat_val.st_mode);

    /* Close files, delete original, rename temp file to original. */
    myclose(new_fid);
    myclose(fd);
    (void) unlink(name);	/* remove original */
    (void) rename(tmp_file, name); /* rename temp file */

    /* If we weren't going to close the file right away in the one
       place this is called from, we'd have to do something like this:
    new_fid = myopen(name, O_RDWR, 0666);
    if (new_fid != fd) {
	dup2(new_fid, fd);
	close(new_fid);
    }
       but the file does get closed, so we don't bother. */

    return 0;
}
Ejemplo n.º 3
0
/* process a single client connection */
static void do_connection(mysocket_t sd)
{
    char line[256];
    int rc;


    /* loop over: 
       - get a request from the client
       - process the request
     */

    for (;;)
    {
        rc = get_nvt_line(sd, line);
        if (rc < 0 || !*line)
            goto done;
        fprintf(stderr, "client: %s\n", line);

        if (process_line(sd, line) < 0)
        {
            perror("process_line");
            goto done;
        }
    }   /* for (;;) */

done:
    if (myclose(sd) < 0)
    {
        perror("myclose (sd)");
    }
}
Ejemplo n.º 4
0
// --------------------------------------------------------------------
// main
// --------------------------------------------------------------------
int main(int argc, char**argv){
    
    if (!myopen()) {
        printf("Cannot open port %s\n", DEV);
        return -1;
    }
    Byte buf[10];
    unsigned int l=0;

    // write
    l=1;
    buf[0]=0xAA;
    if (!mywrite(buf, l)) {
        printf("Cannot write on port\n");
    }

    // read
    l=1;
    if (!myread(buf, l, 10)) {
        printf("Cannot read on port\n");
    } else {
        printf("read:0x%02x\n", buf[0]);
    }

    myclose();
    return 0;
}
Ejemplo n.º 5
0
int
main(int argc, char *argv[]) {
  char *me, *fileS;
  FILE *file;
  unsigned int llen;
  NrrdIoState *io;

  me = argv[0];
  if (2 != argc) {
    /*                       0   1   (2) */
    fprintf(stderr, "usage: %s <file>\n", me);
    exit(1);
  }
  fileS = argv[1];
  if (!( file = myopen(fileS) )) {
    fprintf(stderr, "%s: couldn't open \"%s\" for reading\n", me, fileS);
    exit(1);
  }
  io = nrrdIoStateNew();
  do {
    if (_nrrdOneLine(&llen, io, file)) {
      fprintf(stderr, "%s: trouble:\n%s", me, biffGet(NRRD));
      exit(1);
    }
    if (llen) {
      printf("%2u   |%s|\n", llen, io->line);
    }
  } while(llen > 0);
  nrrdIoStateNix(io);
  myclose(file);

  exit(0);
}
Ejemplo n.º 6
0
Archivo: util.c Proyecto: aosm/X11
void CopyFileAndCheck(char *from, char *to)
{
    int fromfid, tofid, n;
    char buf[512];
    fromfid = myopen(from, O_RDONLY, 0666);
    tofid = myopen(to, O_WRONLY | O_TRUNC | O_CREAT, 0666);
    if (fromfid < 0 || tofid < 0) {
	perror(progName);
	(void)sprintf(buf, "CopyFileAndCheck(%s->%s) failed!", from, to);
	Punt(buf);
    }
    do {
	n = read(fromfid, buf, 512);
	if (n) (void) write(tofid, buf, n);
    } while (n);
    myclose(fromfid);
    myclose(tofid);
}
Ejemplo n.º 7
0
int bb_release(const char *path, struct fuse_file_info *fi)
{
    int retstat = 0;

    log_msg("\nbb_release(path=\"%s\", fi=0x%08x)\n", path, fi);
    log_fi(fi);

    // We need to close the file.  Had we allocated any resources
    // (buffers etc) we'd need to free them here as well.
    myclose(fi->fh);

    return retstat;
}
Ejemplo n.º 8
0
static char *OpenRequest( void )
{
    trap_elen  bytes;

    BindHdl = PipeOpen( BINDERY );
    if( BindHdl == -1 ) return( TRP_ERR_NMPBIND_not_found );
    NameBuff[0] = OPEN_REQUEST;
    bytes = mywrite( BindHdl, NameBuff, strlen( NameBuff ) + 1 );
    if( bytes == 0 ) return( TRP_ERR_NMPBIND_not_found );
    bytes = myread( BindHdl, NameBuff, 1 );
    if( bytes == 0 ) return( TRP_ERR_NMPBIND_not_found );
    myclose( BindHdl );
    return( NULL );
}
Ejemplo n.º 9
0
static unsigned null_CAN_TRANSMIT(const char *devicename)
{
#if WIN32
	struct DeviceCapabilities {
		unsigned AdapterId;		/* An Id that identifies the adapter model.*/
		char AdapterModelName;	/* String containing a printable adapter model.*/
		unsigned AdapterBus;	/* The type of bus the adapter is plugged to. */
		unsigned CanTransmit;	/* TRUE if the adapter is able to perform frame injection.*/
		unsigned CanSetTransmitPower; /* TRUE if the adapter's transmit power is can be specified by the user application.*/
		unsigned ExternalAntennaPlug; /* TRUE if the adapter supports plugging one or more external antennas.*/
		unsigned SupportedMedia;
		unsigned SupportedBands;
	} caps;
	void * (*myopen)(const char *devicename, char *errbuf);
	void (*myclose)(void *h);
	unsigned (*mycapabilities)(void *h, struct DeviceCapabilities *caps);

	unsigned result = 0;
	void *hAirpcap;
	
	
	hAirpcap = LoadLibraryA("airpcap.dll");
	if (hAirpcap == NULL)
		return 0;

	
	myopen = (void * (*)(const char *, char*))GetProcAddress(hAirpcap, "AirpcapOpen");
	myclose = (void (*)(void*))GetProcAddress(hAirpcap, "AirpcapClose");
	mycapabilities = (unsigned (*)(void*, struct DeviceCapabilities *))GetProcAddress(hAirpcap, "AirpcapGetDeviceCapabilities");
	if (myopen && mycapabilities && myclose ) {
		void *h = myopen(devicename, NULL);
		if (h) {
			if (mycapabilities(h, &caps)) {
				result = caps.CanTransmit;
			}
			myclose(h);
		}
	}

	FreeLibrary(hAirpcap);
	return result;
#elif defined(__linux__)
	return 1;
#elif defined(__APPLE__) || defined(__FreeBSD__)
    return 1;
#else
#error unknown os
#endif
}
Ejemplo n.º 10
0
int mygetchar2 ()
{
int c;

debut:
	if (file_level <= 0)
		c = mygetchar1 ();
	else
	{
		c = myfgetc (files+file_level);
		if (c == EOF)
		{
			myclose (files+file_level);
			file_level--;
			goto debut;
		}
	}
	return c;
}
Ejemplo n.º 11
0
int bb_mknod(const char *path, mode_t mode, dev_t dev)
{
    int retstat = 0;
    char * mode_str;

    log_msg("\nbb_mknod(path=\"%s\", mode=0%3o, dev=%lld)\n",
            path, mode, dev);

    if (mode & O_RDONLY) {
        mode_str = "r";
    }
    else {
        mode_str = "w";
    }

    int fd = myopen(path, mode_str);
    myclose(fd);

    return retstat;
}
Ejemplo n.º 12
0
int main (int argc, char** argv) {                                            

  int arq;                                                                    
  char buf[TAM];                                                              
  ssize_t lidos;                                                              

  if (argc != 2) {                                                            
    fprintf(stderr,"forma correta: %s <nomearquivo>\n", argv[0]);       
    return 1;                                                                 
  }                                                                           

  arq = myopen (argv[1], O_RDONLY, TAM);                                           
  if (arq<0) { perror("abertura de arquivo"); return 1;}                      

  while ((lidos = myread (arq, buf)) > 0)                                
    if ((mywrite (STDOUT_FILENO, buf, lidos) != lidos))                       
      { perror("escrita:"); return 1;}                                        

  myclose (arq);                                                              
  return 0;                                                                   

}  
Ejemplo n.º 13
0
/* called by myclose() on a passive socket */
void _mysock_close_passive_socket(mysock_context_t *ctx)
{
    listen_queue_t *q;

    assert(ctx && ctx->listening && ctx->bound);

    PTHREAD_CALL(pthread_rwlock_wrlock(&listen_lock));
    if ((q = _get_connection_queue(ctx)) != NULL)
    {
        /* close any queued connections that haven't been passed up to the
         * user via myaccept()...
         */
        unsigned int k;
        completed_connect_t *connect_iter;

        for (k = 0; k < q->max_len; ++k)
        {
            if (q->connection_queue[k].sd != -1)
                myclose(q->connection_queue[k].sd);
        }
        free(q->connection_queue);

        for (connect_iter = q->completed_queue; connect_iter; )
        {
            /* note: socket was closed by the preceding loop */
            completed_connect_t *next = connect_iter->next;
            free(connect_iter);
            connect_iter = next;
        }

        PTHREAD_CALL(pthread_cond_destroy(&q->connection_cond));
        PTHREAD_CALL(pthread_mutex_destroy(&q->connection_lock));

        HASH_DELETE(listen_table, ctx->my_sd);
        memset(q, 0, sizeof(*q));
        free(q);
    }
    PTHREAD_CALL(pthread_rwlock_unlock(&listen_lock));
}
Ejemplo n.º 14
0
int main(void)
{
	MYFILE *fp;	
	char path[1024];
	char input[1024];
	char output[1024];
	size_t ret;
	int len;

	printf("bufsize: %d\n", BUFSIZ);

	printf("pls input a path: ");
	my_fgets(path, 1024);

	printf("pls input a str: ");
	my_fgets(input, 1024);

	len = strlen(input);
	printf("len: %d\n", len);

	fp = myopen(path, "w+");

	ret = mywrite(input, 1, len, fp);
	printf("write ret: %d\n", ret);

	myrewind(fp);

	myread(output, 1, len, fp);
	output[len] = '\0';
	printf("read ret: %d\n", ret);

	printf("%s\n", output);

	myclose(fp);

	return 0;
}
Ejemplo n.º 15
0
void RemoteUnLink( void )
{
    myclose( ConnHdl );
}
Ejemplo n.º 16
0
void RemoteDisco( void )
{
    ConnRequest( DISCO_REQUEST );
    myclose( ReadHdl );
    myclose( WriteHdl );
}
Ejemplo n.º 17
0
int main (int argc, char *argv[]) {

  int i,j,nb_files,nb_files_orig;
  myFH *log_file[argc-1];
  char *log_buffer[argc-1];
  char *log_scan[argc-1];
  char *log_month[argc-1];
  char ref_date_buf[DATE_SIZE+1];
  char *tmp_date_buf[argc-1];
  char *log_date;
  int year,day,hour,minut,second;
  char month[3];
  struct tm *date;
  time_t start=0;
  time_t start_new;
  char *trans_digits[60];
  char *trans_year[200];
  char months[24]="anebarprayunulugepctovec";

  /*
    print usage if necessary
   */
  if (argc == 1) {
    fprintf(stderr,"usage: %s logfile1 logfile2 ...\nmergelog %s Copyright (C) 2000-2001 Bertrand Demiddelaer\n",argv[0],VERSION);
    exit(1);
  }

#ifdef USE_ZLIB
  /*
    check if there are enough gunzip buffers
   */
  if(argc>MAX_FILES) {
    fputs("too many gzipped log files, aborting\n",stderr);
    exit(1);
  }
#endif

  /*
    open log files
  */
  for (i=1;i<argc;i++) {
    log_file[i-1]=myopen(argv[i],"r");
    if (log_file[i-1] == NULL) {
      fprintf(stderr,"can't open %s, aborting\n",argv[i]);
      exit(1);
    }
  }

  /*
    feed arrays which will be used to translate dates
   */
  for(i=0;i<60;i++) {
    trans_digits[i]=malloc(3);
    if (trans_digits[i] == NULL) {
      perror("malloc");
      exit(1);
    }
    sprintf(trans_digits[i],"%.2d",i);
  }
  for (i=70;i<200;i++) {
    trans_year[i]=malloc(5);
    if (trans_year[i] == NULL) {
      perror("malloc");
      exit(1);
    }
    sprintf(trans_year[i],"%.4d",1900+i);
  }

  /*
    malloc for the 'tm' structure
   */
  date=malloc(sizeof(struct tm));
  if (date == NULL) {
    perror("malloc");
    exit(1);
  }

  /*
    init things for each log file and get the older date to start with
   */
  nb_files=argc-1;
  for (i=0;i<argc-1;i++) {

#ifdef USE_ZLIB
    /*
      init the gzip buffer
     */
    f_buf[i]=malloc(GZBUFFER_SIZE);
    if (f_buf[i] == NULL) {
      perror("malloc");
      exit(1);
    }
    f_cp[i]=f_buf[i]+GZBUFFER_SIZE;
#endif

    /*
      init log_month buffers
      the first 2 digits will be used for the number of the month
      the last 2 digits will be used for the two letters of the month
     */
    log_month[i]=calloc(4,1);
    if (log_month[i] == NULL) {
      perror("calloc");
      exit(1);
    }

    /*
      get the first line of the log file and init log_scan
     */
    log_buffer[i]=malloc(BUFFER_SIZE);
    log_scan[i]=log_buffer[i]+SCAN_OFFSET;
    if (log_buffer[i] == NULL) {
      perror("malloc");
      exit(1);
    }

    /*
      init the tmp_date_buf
     */
    tmp_date_buf[i]=malloc(DATE_SIZE+1);
    if (tmp_date_buf[i] == NULL) {
      perror("malloc");
      exit(1);
    }
    memset(tmp_date_buf[i]+DATE_SIZE,'0',1);

    /*
      is it an empty file ?
     */
    if (mygets(log_buffer[i],BUFFER_SIZE,log_file[i],i) != NULL ) {

      /*
	get the date pointers
      */
      log_date=memchr(log_scan[i],'[',SCAN_SIZE);
      if (log_date == NULL) {
	fprintf(stderr,"abort due to a problem with %s:\n%s\n",argv[i+1],log_buffer[i]);
	exit(1);
      }
      
      /*
	put the date in the tmp_date_buf
       */
       for (j=0;((j == 12)&&(memcmp(months+2*j,log_date+5,2) != 0));j++);
       if (j == 12) {
	 fprintf(stderr,"abort due to a problem with %s:\n%s\n",argv[i+1],log_buffer[i]);
	 exit(1);
       }
       memcpy(log_month[i],trans_digits[j],2);
       memcpy(log_month[i]+2,months+2*j,2);
       memcpy(tmp_date_buf[i],log_date+8,4);
       memcpy(tmp_date_buf[i]+4,trans_digits[j],2);
       memcpy(tmp_date_buf[i]+6,log_date+1,2);
       memcpy(tmp_date_buf[i]+8,log_date+13,2);
       memcpy(tmp_date_buf[i]+10,log_date+16,2);
       memcpy(tmp_date_buf[i]+12,log_date+19,2);

      /*
	extract the date of this first line
      */
       if (sscanf(log_date+1,"%d/%3c/%d:%d:%d:%d",&day,month,&year,&hour,&minut,&second) < 6) {
	 fprintf(stderr,"abort due to a problem with %s:\n%s\n",argv[i+1],log_buffer[i]);
	 exit(1);
       }
      
      /*
	put this date in a 'tm' structure
      */
      date->tm_sec=second;
      date->tm_min=minut;
      date->tm_hour=hour;
      date->tm_mday=day;
      date->tm_year=year-1900;
      date->tm_isdst=-1;
      for (j=0;((j<12)&&(memcmp(months+2*j,month+1,2) != 0));j++);
      if (j == 12) {
	fprintf(stderr,"abort due to a problem with %s:\n%s\n",argv[i+1],log_buffer[i]);
	exit(1);
      }
      date->tm_mon=j;
      memcpy(log_month[i],trans_digits[j],2);
      memcpy(log_month[i]+2,months+2*j,2);
      memcpy(tmp_date_buf[i]+4,trans_digits[j],2);

      /*
	convert it in the 'seconds since 00:00:00, Jan 1, 1970' format
      */
      start_new=mktime(date);
      
      /*
	keep the older date
      */
      if ((start_new < start)||(start == 0)) {
	start=start_new;
      }
    } else {

      /*
	this is an empty file
       */
      nb_files--;
      *(tmp_date_buf[i])='9';
    }
  }

  /*
    exit if we have only empty files
   */
  if (nb_files == 0) {
    exit(0);
  }

  /*
    init 'start', 'date' and 'ref_date_buf'
  */
  free(date);
  start--;
  date=localtime(&start);
  memcpy(ref_date_buf,trans_year[date->tm_year],4);
  memcpy(ref_date_buf+4,trans_digits[date->tm_mon],2);
  memcpy(ref_date_buf+6,trans_digits[date->tm_mday],2);
  memcpy(ref_date_buf+8,trans_digits[date->tm_hour],2);
  memcpy(ref_date_buf+10,trans_digits[date->tm_min],2);
  memcpy(ref_date_buf+12,trans_digits[date->tm_sec],2);
  memset(ref_date_buf+DATE_SIZE,'0',1);

  /*
    start to compute since this date
  */
  nb_files_orig=argc-1;
  for(;;) {

    /*
      update 'start' 'date' and 'ref_date_buf'
    */
    start++;
    if (date->tm_sec < 59) {
      date->tm_sec++;
      memcpy(ref_date_buf+12,trans_digits[date->tm_sec],2);
    } else {
      date->tm_sec=0;
      memset(ref_date_buf+12,'0',2);
      if (date->tm_min < 59) {
	date->tm_min++;
	memcpy(ref_date_buf+10,trans_digits[date->tm_min],2);
      } else {
	date->tm_min=0;
	memset(ref_date_buf+10,'0',2);
	if (date->tm_hour < 23) {
	  date->tm_hour++;
	  memcpy(ref_date_buf+8,trans_digits[date->tm_hour],2);
	} else {
	  memset(ref_date_buf+8,'0',2);
	  date=localtime(&start);
	  memcpy(ref_date_buf,trans_year[date->tm_year],4);
	  memcpy(ref_date_buf+4,trans_digits[date->tm_mon],2);
	  memcpy(ref_date_buf+6,trans_digits[date->tm_mday],2);
	}
      }
    }

    /*
      scan this date for each log file
     */
    for(i=0;i<nb_files_orig;i++) {

      /*
	write the log lines until the reference date is older than the log line
      */
      for(;;) {

	/*
	  if the reference date is older than the log line then go to next file
          we use here a faster implementation than something like:
          if (memcmp(ref_date_buf,tmp_date_buf[i],DATE_SIZE)<0) break;
	 */
	for(j=0;(j<DATE_SIZE)&&(*(ref_date_buf+j)==*(tmp_date_buf[i]+j));j++);
	if (*(ref_date_buf+j)<*(tmp_date_buf[i]+j)) break;

	/*
	  write the log line
	  faster than a puts and we are sure to find a '\0' in log_buffer[i]
	 */
	write(1,log_buffer[i],(size_t)((char *)memchr(log_buffer[i],0,BUFFER_SIZE)-log_buffer[i]));

	/*
	  is it an end of file ?
	 */
	if (mygets(log_buffer[i],BUFFER_SIZE,log_file[i],i) == NULL) {

	  /*
	    close all log files and exit if all end of files are reached
	   */
	  if (--nb_files == 0) {
	    for (j=0;j<argc-1;j++) {
	      myclose(log_file[j]);
	    }
	    exit(0);
	  }

	  /*
	    we don't want anymore output from this file
	    we put a '9' at the beginning  of the year, to fail the date test
	    it's dirty, but it's fast, and doesn't need an extra test
	   */
	  *(tmp_date_buf[i])='9';
          break;
	} else {

	  /*
	    prepare the new pointer for the date test
	   */
	  log_date=memchr(log_scan[i],'[',SCAN_SIZE);
	  if (log_date != NULL) {

	    /*
	      convert the log line month if necessary
	      copy the new date in the buffer
	    */
	    if ((*(log_month[i]+2)==*(log_date+5))&&(*(log_month[i]+3)==*(log_date+6))) {	
	      memcpy(tmp_date_buf[i]+4,log_month[i],2);

	      memcpy(tmp_date_buf[i],log_date+8,4);
	      memcpy(tmp_date_buf[i]+6,log_date+1,2);
	      memcpy(tmp_date_buf[i]+8,log_date+13,2);
	      memcpy(tmp_date_buf[i]+10,log_date+16,2);
	      memcpy(tmp_date_buf[i]+12,log_date+19,2);

	    } else {
	      for (j=0;((j<12)&&(memcmp(months+2*j,log_date+5,2) != 0));j++);
	      if (j == 12) {
		fprintf(stderr,"problem with %s:\n%s\ncontinuing...\n",argv[i+1],log_buffer[i]);
	      } else {
		memcpy(log_month[i],trans_digits[j],2);
		memcpy(log_month[i]+2,months+2*j,2);
		memcpy(tmp_date_buf[i]+4,trans_digits[j],2);
		
		memcpy(tmp_date_buf[i],log_date+8,4);
		memcpy(tmp_date_buf[i]+6,log_date+1,2);
		memcpy(tmp_date_buf[i]+8,log_date+13,2);
		memcpy(tmp_date_buf[i]+10,log_date+16,2);
		memcpy(tmp_date_buf[i]+12,log_date+19,2);
	      }
	    }
	  } else {
	    fprintf(stderr,"problem with %s:\n%s\ncontinuing...\n",argv[i+1],log_buffer[i]);
	  }
	}
      }
    }
  }

  /*
    never reached
   */
  exit(1);
}
Ejemplo n.º 18
0
Archivo: client.c Proyecto: zx5337/STCP
int
main(int argc, char *argv[])
{
    struct sockaddr_in sin;
    char opt;
    char *pline;
    int errflg = 0;
    int sd;



    filename = NULL;
    /* Parse command line options */
    while ((opt = getopt(argc, argv, "f:q")) != EOF)
    {
        switch (opt)
        {
        case 'f':
            filename = optarg;
            break;
        case 'q':
            ++quiet_opt;
            break;
        case '?':
            ++errflg;
            break;
        }
    }
    
    if (errflg || optind != argc - 1)
    {
        fputs(usage, stderr);
        exit(1);
    }
    
    pline = argv[optind];

    if (parse_address(pline, &sin) < 0)
    {
        perror("parse_address");
        exit(1);
    }

    if (!sin.sin_port)
    {
        fprintf(stderr, "Format is %s server:port\n", argv[0]);
        exit(1);
    }
    
    if ((sd = mysocket()) < 0)
    {
        perror("mysocket");
        exit(1);
    }

    sd = myconnect(sd, (struct sockaddr *) &sin, sizeof(struct sockaddr_in));
    if (sd < 0)
    {
        perror("myconnect");
        exit(1);
    }

    loop_until_end(sd);

    if (myclose(sd) < 0)
    {
        perror("myclose");
    }

    return 0;
}                               /* end main() */
Ejemplo n.º 19
0
int getblock(FILE **TEST_FILE, char **varname, char **vartitle, int *qualid
	     ,char ***grouplist)
/*
  Scan the file until a begin line is found.  When "begin xxx" is found, read
  all the lines up until end xxx is found, stuffing them into a line pointed
  to by vartitle.

  This code is really ugly.  Can't I make it better?
*/
{

  static char *start=0;
  static char *last=0;
  static char *next=0;
  char oline[MAXLINELENGTH];
  char line[MAXLINELENGTH];
  static char *blockname=0;
  static char **groups=0;
  char *toks[MAXTOKS];
  int toklens[3], ntoks, itok, qualifier;
  char *stat;
  char *s;
  static char *thistype=0;
  int endflag, len;
  static int maxgroups=0;

  
  int i;
  
  static int EOF_PENDING=0;	/* For cases where EOF happened in a file */

  /* Scan for a begin line */

  if(EOF_PENDING){
    EOF_PENDING = 0;
    if(start) free(start);
    start = last = 0;
    return(S_FAILURE);		/* Should be another code for EOF */
  }
  toks[0] = line;		/* Protect against blank lines */
  /* Scan for "begin" statement or #include */
 keep_looking_for_begin:
  while((stat=fgets(oline,MAXLINELENGTH,*TEST_FILE))){
    strcpy(line,oline);
    s = line;
    while(*s && *s != '\n' && *s != COMCHAR) s++;
    *s = 0;
    {				/* Break into tokens */
      s = line;
      while(*s && isspace(*s)) s++; /* Skip white space to first character */
      ntoks = 0;
      while(*s){
/*	printf("|%s|\n",s);*/
	toks[ntoks++] = s;
	while(*s && !isspace(*s)) s++; /* Skip over token */
	if(*s){
	  *s++ = 0;
	  while(*s && isspace(*s)) s++;	/* Skip white space to next */
	}
      }
    }
    itok = 0;
    if(strcasecmp(toks[itok++],BEGINSTR) == 0) break;
    if(strcasecmp(toks[0],INCLUDESTR) == 0) *TEST_FILE = do_include(toks[1]);
  }

  if(stat == NULL) {
    *TEST_FILE = myclose(*TEST_FILE);
    if(*TEST_FILE) {		/* Not the true end of file */
      goto keep_looking_for_begin;
    } else {
      if(start) free(start);
      start = last = 0;
      return(S_FAILURE);		/* Should be another code for EOF */
    }
  }

  /* Begin found at this point */


  for(i=0;qualifiers[i];i++){
    if(strncasecmp(toks[itok],
		      qualifiers[i],
		      strlen(qualifiers[i])) == 0){
      itok++;
      break;
    }
  }
  *qualid = i;

  if(thistype)
    thistype = (char *) realloc(thistype,strlen(toks[itok])+1);
  else
    thistype = (char *) malloc(strlen(toks[itok])+1);


  for(i=0;types[i];i++){
    if(strncasecmp(toks[itok],types[i],strlen(types[i])) == 0){
      break;
    }
  }
  if(types[i] == 0) {
    fprintf(STDERR,"Unknown block type %s\n",toks[itok]);
    strcpy(thistype,toks[itok]);
    /* Need provision for user defined block types? */
  } else {
    strcpy(thistype,types[i]);
  }
  itok++;
  {
    int len;
    len = strlen(BLOCKSTR) + strlen(thistype) + strlen(toks[itok]) + 3;
    if(blockname)
      blockname = (char *) realloc(blockname,len);
    else
      blockname = (char *) malloc(len);
  }
  strcpy(blockname,BLOCKSTR);
  strcat(blockname,".");
  strcat(blockname,thistype);
  strcat(blockname,".");
  strcat(blockname,toks[itok]);

/*  printf("|%s|\n",blockname);*/
  /* Look for the group id */
  itok++;
  if(!groups) {			/* Initialize groups array */
    groups = (char **) malloc(3*(sizeof(char *)));
    groups[0] = 0;
    groups[1] = 0;
    groups[2] = 0;
    maxgroups = 2;
  }
  /* Put it in the all group */
  if(groups[0]) free(groups[0]);
  groups[0] = (char *) malloc(strlen(GROUPSTR)+strlen(thistype)
			      +strlen(ALLGRPSTR)+3);
  strcpy(groups[0],GROUPSTR);
  strcat(groups[0],".");
  strcat(groups[0],thistype);
  strcat(groups[0],".");
  strcat(groups[0],ALLGRPSTR);

  if(ntoks-itok+1 > maxgroups) {
    int ig;
    groups = (char **) realloc(groups,(ntoks-itok+2)*(sizeof(char *)));
    for(ig=maxgroups+1;ig<ntoks-itok+2;ig++) {
      groups[ig] = 0;		/* Zero new elements, */
    }	/* Makeing sure realloc will work */ 
    maxgroups = ntoks-itok+1;
  }
  if(ntoks > itok) {
    int ig=1;			/* Skip over all group */
    for(;itok < ntoks;itok++) {		/* Scan for the group keyword */
      if(strncasecmp(toks[itok],GROUPSTR,strlen(GROUPSTR))==0) {
	char *grpnam;
	if(grpnam = strchr(toks[itok],'=')) {
	  grpnam++;
	  if(groups[ig]) free(groups[ig]);
#if 0
	  /* For now, groups can only contain a single block type */
	  if(strchr(grpnam,'.')) { /* Class assigned already */
	    groups[ig] =  (char *) malloc(strlen(GROUPSTR)+
					  strlen(toks[itok])+2);
	    strcpy(groups[ig],GROUPSTR);
	    strcat(groups[ig],".");
	    strcat(groups[ig],grpnam);
	  } else { /* Prepend block type */
#endif
	    
	    groups[ig] =  (char *) malloc(strlen(GROUPSTR)+
					  strlen(grpnam)+strlen(thistype)+3);
	    strcpy(groups[ig],GROUPSTR);
	    strcat(groups[ig],".");
	    strcat(groups[ig],thistype);
	    strcat(groups[ig],".");
	    strcat(groups[ig],grpnam);
#if 0
	  }
#endif
	}	/* else { ignore if = is missing } */
	ig++;
      }
    }
    if(groups[ig]) {		/* Null terminate list */
      free(groups[ig]);
      groups[ig] = 0;
    }
  } else {			/* No groups specified, use default group */
    if(groups[1]) free(groups[1]);
    groups[1] = (char *) malloc(strlen(GROUPSTR)+strlen(thistype)
				+strlen(DEFAULTGRPSTR)+3);
    strcpy(groups[1],GROUPSTR);
    strcat(groups[1],".");
    strcat(groups[1],thistype);
    strcat(groups[1],".");
    strcat(groups[1],DEFAULTGRPSTR);
    if(groups[2]) {		/* Null terminate list */
      free(groups[2]);
      groups[2] = 0;
    }
  }

  strcpy(line,oline);		/* Save the line */
  endflag = 0;
    
  next = start;			/* Initialize */
  while(1){
    len = strlen(line);
    if(next+len >= last){
      int newsize;
/*      char *src,*dst,*newstart;*/
      
/*      src = start;*/
      newsize = max((last-start) + MAXLINELENGTH,(next-start) + len + 1);
/*      newstart = dst = (char *) malloc(newsize);
      while(src < next) *dst++ = *src++;
      if(start) free(start);
      last = newstart + newsize;
      start = newstart;*/
      if(start) {
	char *newstart;
	newstart = (char *) realloc(start,newsize);
	next = next + (newstart-start);
	start = newstart;
      }  else {
	start = (char *) malloc(newsize);
	next = start;
      }
/*      next = next + (dst-src);*/
    }
    strcpy(next,line);
    next += len;

    if(endflag) break;
  reread:
    if((stat=fgets(line,MAXLINELENGTH,*TEST_FILE))){
      s = line;
      while(*s && isspace(*s)) s++;
      if(strncasecmp(s,INCLUDESTR,strlen(INCLUDESTR)) == 0) {
	*TEST_FILE = do_include(s + strlen(INCLUDESTR));
	goto reread;		/* Get another line */
      }
      if(strncasecmp(s,ENDSTR,strlen(ENDSTR))!=0) continue;
      s += strlen(ENDSTR)+1;
      while(*s && isspace(*s)) s++;
      if(strncasecmp(s,thistype,strlen(thistype))!=0) continue;
/* Don't require block name to be restated
      s += strlen(thistype)+1;
      while(*s && isspace(*s)) s++;
      if(strncasecmp(s,BLOCKSTR,strlen(BLOCKSTR))!=0) continue;
*/
      endflag = 1;
    } else {			/* EOF */
      *TEST_FILE = myclose(*TEST_FILE);
      if(!*TEST_FILE) {		/* Test for true end of file */
	strcpy(line,"end ");
	strcat(line,s);
	strcat(line," block\n");
	endflag = 1;			/* Terminate after writing end block */
      } else {
	goto reread;		/* Get another line */
      }
    }
  }

  *varname = blockname;
  *vartitle = start;
  *grouplist = groups;

  return(S_SUCCESS);
}
Ejemplo n.º 20
0
Archivo: client.c Proyecto: zx5337/STCP
/* loop_until_end
 * 
 * Loop until the connection has closed
 */
void
loop_until_end(int sd)
{
    int errcnd;
    char line[1000];
    int length, to_read;
    char *pline, *lenstr, *resp;
    int got;
    FILE *file;

    for (;;)
    {

        errcnd = 0;
        if (filename == NULL)
        {
            /* Prompt for a request to the server (a filename) */
            printf("\nclient> ");
            fflush(stdout);
            if (!fgets(line, sizeof(line), stdin))
                break;

            /* Remove trailing spaces and add CRLF at the end */
            pline = line + strlen(line) - 1;
            while ((pline > line - 1) && isspace((int) (*pline)))
                --pline;

            if (pline <= line)
                continue;
        }
        else
        {
            strcpy(line, filename);	
            pline = line + strlen(line) - 1;
        }
        *++pline = '\r';
        *++pline = '\n';
        *++pline = '\0';

        if (mywrite(sd, line, pline - line) < 0)
        {
            perror("mywrite");
            errcnd = 1;
            break;
        }

        if (get_nvt_line(sd, line) < 0)
        {
            perror("get_nvt_line");
            errcnd = 1;
            break;
        }

        printf("server: %s\n", line);
        fflush(stdout);

        /* Parse the response from the server */
        if (NULL == (resp = strrchr(line, ',')))
        {
            fprintf(stderr, "Malformed response from server.\n");
            errcnd = 1;
            break;
        }
        *resp++ = '\0';

        if (NULL == (lenstr = strrchr(line, ',')))
        {
            fprintf(stderr, "Malformed response from server.\n");
            errcnd = 1;
            break;
        }
        *lenstr++ = '\0';


        sscanf(lenstr, "%d", &length);
        if (length == -1)
        {
            /* Error reported from server */
            if (filename == NULL)
                continue;
            else
            {
                errcnd = 1;
                break;
            }

        }
        if ((file = fopen(RCVD_FILENAME, "w")) == NULL)
        {
            perror("file_to_write error");
            errcnd = 1;
            break;
        }
        /* Retrieve the remote file and write it to a local file */
        while (length)
        {
            to_read = MIN(length, (int) sizeof(line));

            if ((got = myread(sd, line, to_read)) < 0)
            {
                perror("myread");
                errcnd = 1;
                break;
            }

            if (!got)
            {
                break;
            }

            if (got < to_read)
            {
                to_read = got;
            }

            if (!quiet_opt)
            {
                while (0 == fwrite(line, 1, to_read, file))
                {
                    if (errno != EINTR)
                    {
                        perror("fwrite");
                        errcnd = 1;
                        break;
                    }
                }
            }
            length -= to_read;
        }

        if (length)
        {
            fprintf(stderr,
                    "Exiting: read bad number of bytes (%d less than expected)...\n",
                    length);
            fclose(file);
            myclose(sd);
            exit(-1);
        }

        fclose(file);
        if (filename != NULL)
            break;

    }                           /* end for(;;) */

    if (errcnd) fprintf(stderr, "An error occurred\n");
}
Ejemplo n.º 21
0
int
main(int argc, char *argv[])
{
    struct sockaddr_in sin;
    mysocket_t bindsd;
    int len, opt, errflg = 0;
    char localname[256];


    /* Parse the command line */
    while ((opt = getopt(argc, argv, "")) != EOF)
    {
        switch (opt)
        {
        case '?':
            ++errflg;
            break;
        }
    }

    if (errflg || optind != argc)
    {
        fprintf(stderr, usage, argv[0]);
        exit(EXIT_FAILURE);
    }

    /* open connection on any available port */
    if ((bindsd = mysocket()) < 0)
    {
        perror("mysocket");
        exit(EXIT_FAILURE);
    }

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = htonl(INADDR_ANY);
    sin.sin_port = htons(0);
    len = sizeof(struct sockaddr_in);

    if (mybind(bindsd, (struct sockaddr *) &sin, len) < 0)
    {
        perror("mybind");
        exit(EXIT_FAILURE);
    }

    if (mylisten(bindsd, 5) < 0)
    {
        perror("mylisten");
        exit(EXIT_FAILURE);
    }
    if (local_name(bindsd, localname) < 0)
    {
        perror("local_name");
        exit(EXIT_FAILURE);
    }
    fprintf(stderr, "Server's address is %s\n", localname);
    fflush(stderr);

    for (;;)
    {
        mysocket_t sd;

        /* just keep accepting connections forever */
        if ((sd = myaccept(bindsd, (struct sockaddr *) &sin, &len)) < 0)
        {
            perror("myaccept");
            exit(EXIT_FAILURE);
        }

        assert(sin.sin_family == AF_INET);
        fprintf(stderr, "connected to %s at port %u\n",
                inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));

        do_connection(sd);
    }                           /* end for(;;) */

    if (myclose(bindsd) < 0)
        perror("myclose (bindsd)");
    return 0;
}