Ejemplo n.º 1
0
int yDecode(FILE * fOut, FILE * fIn, long y_line, long y_size,int y_part)
	{
	unsigned char srcbuf[4100];
	unsigned char desbuf[4100];
	unsigned char * srcp;
	unsigned char * desp;
	int deslen;
	int srclen;
	unsigned char c;
	int id;
	char * cp;
	long decolen;
//	long sumlen;
//	int partnr;
	unsigned long crc32;
	char name[260];
	int esize;
	unsigned char * partbuf;
	unsigned char * partptr;
	long partsize;
	long partfree;
	long wlen;
	long flen;

	if (aDsp) print("yDecoder started...\r\n");

	// sumlen=0; partnr=1;

//part_start:
	CrcInit();  // Analyse only CRC per part
	decolen=0;
	deslen=0; desp=desbuf;

	if (y_part)  // This is a multipart message !
		{
		cp=ad_fgetscr((char*) srcbuf,4097,fIn);  // fgets especially with ad_length
		if (cp==NULL)
			{
			eprint("Unexpected eof in yEncoded file\r\n");
			errors++;
			return(1);
			}

		if (aDsp) print("=ypart-line:  %s\r\n",srcbuf);

		if (strncmp((char*) srcbuf,"=ypart ",7))
			{
			eprint("Missing =ypart line in yEncoded multipart message\r\n");
			errors++;
			return(2);
			}
		cp=strstr((char*)srcbuf,"end=");
		if (cp==NULL)
			{
			eprint("Missing end= in yEncoded multipart message\r\n");
			errors++;
			return(2);
			}
		y_end=atol(cp+4);

		cp=strstr((char*)srcbuf,"begin=");
		if (cp==NULL)
			{
			eprint("Missing begin= in yEncoded multipart message\r\n");
			errors++;
			return(2);
			}
		y_begin=atol(cp+6);

		if (aDsp) print("part-begin: %ld\r\n",y_begin);
		if (aDsp) print("part-end  : %ld\r\n",y_end);

		partbuf=malloc(y_end-y_begin+10);  // Allocate a buffer for the part
		partptr=partbuf;
		partsize=y_end-y_begin+1;
		partfree=partsize;
		}

loop:

	cp=ad_fgetscr((char*) srcbuf,4097,fIn);  // fgets especially with ad_length
	if (cp==NULL)
		{
		eprint("Unexpected eof in yEncoded file\r\n");
		errors++;
		return(1);
		}
	if (strncmp((char*) srcbuf,"=yend ",6)==0)
		{
		if (aDsp) print("Endline (%d bytes): %s\r\n",decolen,srcbuf);
		goto end_of_file;
		}
	if (strncmp((char*) srcbuf,"=ybegin ",8)==0)
		{
		eprint("Unexpected =ybegin in yEncoded file\r\n");
		errors++;
		return(1);
		}
	srclen=strlen((char*)srcbuf);
	if (srclen<y_line)
		{
		if (aDsp) print("Last line.\r\n");
		}
	srcp=srcbuf;

loop2:
	c=*srcp; srcp++;
	if (c==0)
		{
		goto loop;  // End of line reached
		}
	if (c == '=')  // The escape character comes in
		{
		c=*srcp; srcp++;
		if (c==0) return(2); // Last char cannot be escape char !
		c=(unsigned char)(c-64);
		}
	c=(unsigned char)(c-42);  // Subtract the secret number
	*desp=c; desp++; deslen++;	decolen++;

	CrcAdd(c);

	if (deslen>=4096)
		{

		if (y_part)  // MultiPart --> to the partbuffer !
			{
			if (deslen>partfree)
				{
				eprint("Partial message corrupt: longer than (end-begin)!\r\n");
				errors++;
				return(11);
				}
			memcpy(partptr,desbuf,deslen);
			partptr=partptr+deslen;
			partfree=partfree-deslen;
			}
		else    // Single part --> directly to target file
			{
			id=fwrite(desbuf,deslen,1,fOut);
			if (id != 1)
				{
				eprint("Error in writing decoded file (code=%d)\r\n",errno);
				errors++;
				return(3);
				}
			}
		deslen=0; desp=desbuf;
		}
	goto loop2;

end_of_file:


	if (deslen>0)  // Empty the last buffer
		{
		if (y_part)
      	{
			if (deslen>partfree)
				{
				eprint("Partial message corrupt: longer than (end-begin)!\r\n");
				errors++;
				return(11);
				}
			memcpy(partptr,desbuf,deslen);
			//partptr=partptr+deslen;
			//partfree=partfree-deslen;
			}
		else    // Single part --> directly to target file
			{
			id=fwrite(desbuf,deslen,1,fOut);
			if (id != 1)
				{
				eprint("Error in writing decoded file (code=%d)\r\n",errno);
				errors++;
				return(3);
				}
			}



//		id=fwrite(desbuf,deslen,1,fOut);
//		if (id != 1)
//			{
//			eprint("Error in writing decoded file (code=%d)\r\n",errno);
//			return(4);
//			}
		}

	cp=strstr((char*) srcbuf,"size=");  // Compare the decoded size to the =yend size
	if (cp)
		{
		esize=atoi(cp+5);
		if (esize != decolen)
			{
			sprintf(name,"%s(size=%ld)",attname,decolen);
			strcpy(attname,name);
			eprint("Corrupt yEnc binary - endsize mismatch (%s%s)\r\n",attname,attext);
			errors++; errfiles++;
			return(0);
			}
		}


	// Check the srcbuf for the CRC
	if (y_part==0)
		{
		cp=strstr((char*)srcbuf,"crc32=");
		if (cp)
			{
			crc32=hex_to_ulong((char*)(cp+6));
			ad_rescrc=crc_val ^ 0xFFFFFFFFl;
			if (aDsp) print("Included CRC: $%08lx - calculated CRC: $%08lx\r\n",crc32,ad_rescrc);
			}
		}
	else
		{
		cp=strstr((char*)srcbuf,"pcrc32=");
		if (cp)
			{
			crc32=hex_to_ulong((char*)(cp+7));
			ad_rescrc=crc_val ^ 0xFFFFFFFFl;
			if (aDsp) print("Included CRC: $%08lx - calculated CRC: $%08lx\r\n",crc32,ad_rescrc);
			}
		}

	if (cp!=NULL)
		{
		if (crc32 != ad_rescrc)
			{
			sprintf(name,"%s(crc=%08lx)",attname,ad_rescrc);
			strcpy(attname,name);
			eprint("Corrupt yEnc binary - CRC mismatch (%s%s)\r\n",attname,attext);
			errors++; errfiles++;
			return(0);
			}
		}

	if (y_part==0)  // Single message
		{
		if ((y_part==0) & (decolen != y_size))
			{
			// eprint("Y-Decoder: Size mismatch - file corrupt.\r\n");

			sprintf(name,"%s(len=%ld)",attname,decolen);
			strcpy(attname,name);
			eprint("Corrupt yEnc binary - size mismatch (%s%s)\r\n",attname,attext);
			errors++; errfiles++;
			return(0);
			}

		ad_reslen=decolen;
		ad_rescrc=crc_val ^ 0xFFFFFFFFl;

		if (aDsp) print("yDecoder: Job done. %ld bytes written. CRC: $%08lx \r\n",decolen,ad_rescrc);
		return(0);
		}

	// Multipart message

	if ((y_part>0) & (decolen != (y_end-y_begin+1)))
		{
		eprint("yDecoder: Part size mismatch - file corrupt.\r\n");
		errors++; errparts++;
		return(6);
		}

	// ----- Special handling for external decoder

	// Now write the decoded part to the target file !

	id=fseek(fOut,y_begin-1,0);
	if (id)
		{
		eprint("Cannot write a part (fseek failed) [reason:%d]\r\n",errno);
		errors++;
		return(12);
		}
	flen=decolen;
	partptr=partbuf;

	if (aDsp) print("Write part to target file (start: %ld, size: %ld)\r\n",y_begin-1,flen);

	while (flen>0)
		{
		wlen=flen;
		if (wlen>8192) wlen=8192;
		id=fwrite(partptr,wlen,1,fOut);

		if (id != 1)
			{
			eprint("Cannot write a part (fwrite failed) [reason:%d]\r\n",errno);
			errors++;
			return(12);
			}
		partptr=partptr+wlen;
		flen=flen-wlen;
		}

	free(partbuf);  // Give the part-buffer back !

	return(0);
	}
Ejemplo n.º 2
0
void printstatus() { eprint(P_STAT, "%d / %d", numchildren, limit); }
Ejemplo n.º 3
0
/* thread the typical function */
static void *threadtypical(void *targ){
  TCFDB *fdb = ((TARGTYPICAL *)targ)->fdb;
  int rnum = ((TARGTYPICAL *)targ)->rnum;
  bool nc = ((TARGTYPICAL *)targ)->nc;
  int rratio = ((TARGTYPICAL *)targ)->rratio;
  int id = ((TARGTYPICAL *)targ)->id;
  bool err = false;
  TCMAP *map = (!nc && id == 0) ? tcmapnew2(rnum + 1) : NULL;
  int base = id * rnum;
  int mrange = tclmax(50 + rratio, 100);
  int width = tcfdbwidth(fdb);
  for(int i = 1; !err && i <= rnum; i++){
    char buf[RECBUFSIZ];
    int len = sprintf(buf, "%08d", base + myrandnd(i) + 1);
    int rnd = myrand(mrange);
    if(rnd < 10){
      if(!tcfdbput2(fdb, buf, len, buf, len)){
        eprint(fdb, __LINE__, "tcfdbput2");
        err = true;
      }
      if(map) tcmapput(map, buf, len, buf, len);
    } else if(rnd < 15){
      if(!tcfdbputkeep2(fdb, buf, len, buf, len) && tcfdbecode(fdb) != TCEKEEP){
        eprint(fdb, __LINE__, "tcfdbputkeep2");
        err = true;
      }
      if(map) tcmapputkeep(map, buf, len, buf, len);
    } else if(rnd < 20){
      if(!tcfdbputcat2(fdb, buf, len, buf, len)){
        eprint(fdb, __LINE__, "tcfdbputcat2");
        err = true;
      }
      if(map) tcmapputcat(map, buf, len, buf, len);
    } else if(rnd < 25){
      if(!tcfdbout2(fdb, buf, len) && tcfdbecode(fdb) && tcfdbecode(fdb) != TCENOREC){
        eprint(fdb, __LINE__, "tcfdbout");
        err = true;
      }
      if(map) tcmapout(map, buf, len);
    } else if(rnd < 26){
      if(myrand(10) == 0 && !tcfdbiterinit(fdb) && tcfdbecode(fdb) != TCENOREC){
        eprint(fdb, __LINE__, "tcfdbiterinit");
        err = true;
      }
      for(int j = 0; !err && j < 10; j++){
        if(tcfdbiternext(fdb) < 1 &&
           tcfdbecode(fdb) != TCEINVALID && tcfdbecode(fdb) != TCENOREC){
          eprint(fdb, __LINE__, "tcfdbiternext");
          err = true;
        }
      }
    } else {
      int vsiz;
      char *vbuf = tcfdbget2(fdb, buf, len, &vsiz);
      if(vbuf){
        if(map){
          int msiz = 0;
          const char *mbuf = tcmapget(map, buf, len, &msiz);
          if(msiz > width) msiz = width;
          if(!mbuf || msiz != vsiz || memcmp(mbuf, vbuf, vsiz)){
            eprint(fdb, __LINE__, "(validation)");
            err = true;
          }
        }
        tcfree(vbuf);
      } else {
        if(tcfdbecode(fdb) != TCENOREC){
          eprint(fdb, __LINE__, "tcfdbget");
          err = true;
        }
        if(map && tcmapget(map, buf, len, &vsiz)){
          eprint(fdb, __LINE__, "(validation)");
          err = true;
        }
      }
    }
    if(id == 0 && rnum > 250 && i % (rnum / 250) == 0){
      iputchar('.');
      if(i == rnum || i % (rnum / 10) == 0) iprintf(" (%08d)\n", i);
    }
  }
  if(map){
    tcmapiterinit(map);
    int ksiz;
    const char *kbuf;
    while(!err && (kbuf = tcmapiternext(map, &ksiz)) != NULL){
      int vsiz;
      char *vbuf = tcfdbget2(fdb, kbuf, ksiz, &vsiz);
      if(vbuf){
        int msiz = 0;
        const char *mbuf = tcmapget(map, kbuf, ksiz, &msiz);
        if(msiz > width) msiz = width;
        if(!mbuf || msiz != vsiz || memcmp(mbuf, vbuf, vsiz)){
          eprint(fdb, __LINE__, "(validation)");
          err = true;
        }
        tcfree(vbuf);
      } else {
        eprint(fdb, __LINE__, "(validation)");
        err = true;
      }
    }
    tcmapdel(map);
  }
  return err ? "error" : NULL;
}
Ejemplo n.º 4
0
/* perform read command */
static int procread(const char *path, int tnum, int omode, bool wb, bool rnd){
  iprintf("<Reading Test>\n  seed=%u  path=%s  tnum=%d  omode=%d  wb=%d  rnd=%d\n\n",
          g_randseed, path, tnum, omode, wb, rnd);
  bool err = false;
  double stime = tctime();
  TCFDB *fdb = tcfdbnew();
  if(g_dbgfd >= 0) tcfdbsetdbgfd(fdb, g_dbgfd);
  if(!tcfdbsetmutex(fdb)){
    eprint(fdb, __LINE__, "tcfdbsetmutex");
    err = true;
  }
  if(!tcfdbopen(fdb, path, FDBOREADER | omode)){
    eprint(fdb, __LINE__, "tcfdbopen");
    err = true;
  }
  int rnum = tcfdbrnum(fdb) / tnum;
  TARGREAD targs[tnum];
  pthread_t threads[tnum];
  if(tnum == 1){
    targs[0].fdb = fdb;
    targs[0].rnum = rnum;
    targs[0].wb = wb;
    targs[0].rnd = rnd;
    targs[0].id = 0;
    if(threadread(targs) != NULL) err = true;
  } else {
    for(int i = 0; i < tnum; i++){
      targs[i].fdb = fdb;
      targs[i].rnum = rnum;
      targs[i].wb = wb;
      targs[i].rnd = rnd;
      targs[i].id = i;
      if(pthread_create(threads + i, NULL, threadread, targs + i) != 0){
        eprint(fdb, __LINE__, "pthread_create");
        targs[i].id = -1;
        err = true;
      }
    }
    for(int i = 0; i < tnum; i++){
      if(targs[i].id == -1) continue;
      void *rv;
      if(pthread_join(threads[i], &rv) != 0){
        eprint(fdb, __LINE__, "pthread_join");
        err = true;
      } else if(rv){
        err = true;
      }
    }
  }
  iprintf("record number: %llu\n", (unsigned long long)tcfdbrnum(fdb));
  iprintf("size: %llu\n", (unsigned long long)tcfdbfsiz(fdb));
  mprint(fdb);
  sysprint();
  if(!tcfdbclose(fdb)){
    eprint(fdb, __LINE__, "tcfdbclose");
    err = true;
  }
  tcfdbdel(fdb);
  iprintf("time: %.3f\n", tctime() - stime);
  iprintf("%s\n\n", err ? "error" : "ok");
  return err ? 1 : 0;
}
Ejemplo n.º 5
0
/* thread the typical function */
static void *threadtypical(void *targ){
  TCMDB *mdb = ((TARGTYPICAL *)targ)->mdb;
  TCNDB *ndb = ((TARGCOMBO *)targ)->ndb;
  int rnum = ((TARGTYPICAL *)targ)->rnum;
  bool nc = ((TARGTYPICAL *)targ)->nc;
  int rratio = ((TARGTYPICAL *)targ)->rratio;
  int id = ((TARGTYPICAL *)targ)->id;
  bool err = false;
  TCMAP *map = (!nc && id == 0) ? tcmapnew2(rnum + 1) : NULL;
  int base = id * rnum;
  int mrange = tclmax(50 + rratio, 100);
  for(int i = 1; !err && i <= rnum; i++){
    char buf[RECBUFSIZ];
    int len = sprintf(buf, "%08d", base + myrandnd(i));
    int rnd = myrand(mrange);
    if(rnd < 10){
      if(ndb){
        tcndbput(ndb, buf, len, buf, len);
      } else {
        tcmdbput(mdb, buf, len, buf, len);
      }
      if(map) tcmapput(map, buf, len, buf, len);
    } else if(rnd < 15){
      if(ndb){
        tcndbputkeep(ndb, buf, len, buf, len);
      } else {
        tcmdbputkeep(mdb, buf, len, buf, len);
      }
      if(map) tcmapputkeep(map, buf, len, buf, len);
    } else if(rnd < 20){
      if(ndb){
        tcndbputcat(ndb, buf, len, buf, len);
      } else {
        tcmdbputcat(mdb, buf, len, buf, len);
      }
      if(map) tcmapputcat(map, buf, len, buf, len);
    } else if(rnd < 30){
      if(ndb){
        tcndbout(ndb, buf, len);
      } else {
        tcmdbout(mdb, buf, len);
      }
      if(map) tcmapout(map, buf, len);
    } else if(rnd < 31){
      if(myrand(10) == 0) tcmdbiterinit(mdb);
      for(int j = 0; !err && j < 10; j++){
        int ksiz;
        char *kbuf = ndb ? tcndbiternext(ndb, &ksiz) : tcmdbiternext(mdb, &ksiz);
        if(kbuf) tcfree(kbuf);
      }
    } else {
      int vsiz;
      char *vbuf = ndb ? tcndbget(ndb, buf, len, &vsiz) : tcmdbget(mdb, buf, len, &vsiz);
      if(vbuf){
        if(map){
          int msiz;
          const char *mbuf = tcmapget(map, buf, len, &msiz);
          if(msiz != vsiz || memcmp(mbuf, vbuf, vsiz)){
            eprint(__LINE__, "(validation)");
            err = true;
          }
        }
        tcfree(vbuf);
      } else {
        if(map && tcmapget(map, buf, len, &vsiz)){
          eprint(__LINE__, "(validation)");
          err = true;
        }
      }
    }
    if(id == 0 && rnum > 250 && i % (rnum / 250) == 0){
      iputchar('.');
      if(i == rnum || i % (rnum / 10) == 0) iprintf(" (%08d)\n", i);
    }
  }
  if(map){
    tcmapiterinit(map);
    int ksiz;
    const char *kbuf;
    while(!err && (kbuf = tcmapiternext(map, &ksiz)) != NULL){
      int vsiz;
      char *vbuf = ndb ? tcndbget(ndb, kbuf, ksiz, &vsiz) : tcmdbget(mdb, kbuf, ksiz, &vsiz);
      if(vbuf){
        int msiz;
        const char *mbuf = tcmapget(map, kbuf, ksiz, &msiz);
        if(!mbuf || msiz != vsiz || memcmp(mbuf, vbuf, vsiz)){
          eprint(__LINE__, "(validation)");
          err = true;
        }
        tcfree(vbuf);
      } else {
        eprint(__LINE__, "(validation)");
        err = true;
      }
    }
    tcmapdel(map);
  }
  return err ? "error" : NULL;
}
Ejemplo n.º 6
0
static Inode 
f_icreate(struct DiskPartition *dp, u_long volume, u_long vnode, u_long unique,
	  u_long dataversion)
{
    struct part_ftree_opts *opts=&(dp->d->ftree);
    int	fd, rc, pos, i;
    Inode ino;
    char filename[FNAMESIZE];
    struct i_header header={1, volume, vnode, unique, dataversion, VICEMAGIC};

    /*  Find an available inode. */
    i = Bitv_getfree(opts->freebm);
    if ( i == -1 ) {
	eprint("No more free entries in freebitmap of %s\n", dp->name);
	CODA_ASSERT(0);
    }
	
    ino = (Inode)i+1; /*inode numbers start at 1 */
    
    f_inotostr(dp, ino, filename);
    if (mkpath(filename, 0700) < 0) {
        eprint("f_icreate: could not make ftree path!\n");
	CODA_ASSERT(0);
    }
    if ((fd = open(filename, O_CREAT | O_EXCL, mode)) < 0) {
	if ( errno == EEXIST ) {
	    eprint("f_icreate: bitmap free at %d, inode %ld exists!\n", 
		   i, ino);
	    CODA_ASSERT(0);
	} else {  /* other error, just fail */
	    eprint("f_icreate: error %d in creating inode %ld!\n", 
		   errno, ino);

	    /* make sure the file doesn't exist on disk, that way we keep the
	     * free bitmap in sync with reality --JH */
	    (void)unlink(filename);

	    CODA_ASSERT(0);
	}
    } else {
	close(fd);
    }

    /* write header in resouce db */
    pos = lseek(opts->resource, i * sizeof(struct i_header), SEEK_SET);

    if ( pos != i * sizeof(struct i_header) ) {
	eprint("Cannot seek in resource db for file %s\n", filename);
	unlink(filename);
	return 0;
    }

    rc = write(opts->resource, (char *)&header, sizeof(struct i_header)); 
    if ( rc != sizeof(struct i_header)) {
	printf("Error writing header for inode file %u\n",i);
	unlink(filename);
	return 0;
    }

    rc = fsync(opts->resource);
    if ( rc != 0 ) {
	printf("Error syncing header for inode file %u\n",i);
	unlink(filename);
	return 0;
    }

    return ino;
}
Ejemplo n.º 7
0
Archivo: main.c Proyecto: cobrajs/dzen
int
main(int argc, char *argv[]) {
	int i, use_ewmh_dock=0;
	char *action_string = NULL;
	char *endptr, *fnpre = NULL;

	/* default values */
	dzen.title_win.name = "dzen title";
	dzen.slave_win.name = "dzen slave";
	dzen.cur_line  = 0;
	dzen.ret_val   = 0;
	dzen.title_win.x = dzen.slave_win.x = 0;
	dzen.title_win.y = 0;
	dzen.title_win.width = dzen.slave_win.width = 0;
	dzen.title_win.alignment = ALIGNCENTER;
	dzen.slave_win.alignment = ALIGNLEFT;
	dzen.fnt = FONT;
	dzen.bg  = BGCOLOR;
	dzen.fg  = FGCOLOR;
	dzen.slave_win.max_lines  = 0;
	dzen.running = True;
	dzen.xinescreen = 0;
	dzen.tsupdate = 0;
	dzen.line_height = 0;
	dzen.title_win.expand = noexpand;

	/* Connect to X server */
	x_connect();
	x_read_resources();

	/* cmdline args */
	for(i = 1; i < argc; i++)
		if(!strncmp(argv[i], "-l", 3)){
			if(++i < argc) {
				dzen.slave_win.max_lines = atoi(argv[i]);
				if(dzen.slave_win.max_lines)
					init_input_buffer();
			}
		}
		else if(!strncmp(argv[i], "-geometry", 10)) {
			if(++i < argc) {
				int t;
				int tx, ty;
				unsigned int tw, th;

				t = XParseGeometry(argv[i], &tx, &ty, &tw, &th);

				if(t & XValue)
					dzen.title_win.x = tx;
				if(t & YValue) {
					dzen.title_win.y = ty;
					if(!ty && (t & YNegative))
						/* -0 != +0 */
						dzen.title_win.y = -1;
				}
				if(t & WidthValue)
					dzen.title_win.width = (signed int) tw;
				if(t & HeightValue)
					dzen.line_height = (signed int) th;
			}
		}
		else if(!strncmp(argv[i], "-u", 3)){
			dzen.tsupdate = True;
		}
		else if(!strncmp(argv[i], "-expand", 8)){
			if(++i < argc) {
				switch(argv[i][0]){
					case 'l':
						dzen.title_win.expand = left;
						break;
					case 'c':
						dzen.title_win.expand = both;
						break;
					case 'r':
						dzen.title_win.expand = right;
						break;
					default:
						dzen.title_win.expand = noexpand;
				}
			}
		}
		else if(!strncmp(argv[i], "-p", 3)) {
			dzen.ispersistent = True;
			if (i+1 < argc) {
				dzen.timeout = strtoul(argv[i+1], &endptr, 10);
				if(*endptr)
					dzen.timeout = 0;
				else
					i++;
			}
		}
		else if(!strncmp(argv[i], "-ta", 4)) {
			if(++i < argc) dzen.title_win.alignment = alignment_from_char(argv[i][0]);
		}
		else if(!strncmp(argv[i], "-sa", 4)) {
			if(++i < argc) dzen.slave_win.alignment = alignment_from_char(argv[i][0]);
		}
		else if(!strncmp(argv[i], "-m", 3)) {
			dzen.slave_win.ismenu = True;
			if(i+1 < argc) {
				if( argv[i+1][0] == 'v') {
					++i;
					break;
				}
				dzen.slave_win.ishmenu = (argv[i+1][0] == 'h') ? ++i, True : False;
			}
		}
		else if(!strncmp(argv[i], "-fn", 4)) {
			if(++i < argc) dzen.fnt = argv[i];
		}
		else if(!strncmp(argv[i], "-e", 3)) {
			if(++i < argc) action_string = argv[i];
		}
		else if(!strncmp(argv[i], "-title-name", 12)) {
			if(++i < argc) dzen.title_win.name = argv[i];
		}
		else if(!strncmp(argv[i], "-slave-name", 12)) {
			if(++i < argc) dzen.slave_win.name = argv[i];
		}
		else if(!strncmp(argv[i], "-bg", 4)) {
			if(++i < argc) dzen.bg = argv[i];
		}
		else if(!strncmp(argv[i], "-fg", 4)) {
			if(++i < argc) dzen.fg = argv[i];
		}
		else if(!strncmp(argv[i], "-x", 3)) {
			if(++i < argc) dzen.title_win.x = dzen.slave_win.x = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-y", 3)) {
			if(++i < argc) dzen.title_win.y = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-w", 3)) {
			if(++i < argc) dzen.slave_win.width = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-h", 3)) {
			if(++i < argc) dzen.line_height= atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-tw", 4)) {
			if(++i < argc) dzen.title_win.width = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-fn-preload", 12)) {
			if(++i < argc) {
				fnpre = estrdup(argv[i]);
			}
		}
#ifdef DZEN_XINERAMA
		else if(!strncmp(argv[i], "-xs", 4)) {
			if(++i < argc) dzen.xinescreen = atoi(argv[i]);
		}
#endif
		else if(!strncmp(argv[i], "-dock", 6))
			use_ewmh_dock = 1;
		else if(!strncmp(argv[i], "-v", 3)) {
			printf("dzen-\"VERSION\", (C)opyright 2007-2009 Robert Manea\n");
			printf(
			"Enabled optional features: "
#ifdef DZEN_XMP
			" XPM "
#endif
#ifdef DZEN_XFT
			" XFT"
#endif
#ifdef DZEN_XINERAMA
			" XINERAMA "
#endif
			"\n"
			);
			return EXIT_SUCCESS;
		}
		else
			eprint("usage: dzen2 [-v] [-p [seconds]] [-m [v|h]] [-ta <l|c|r>] [-sa <l|c|r>]\n"
                   "             [-x <pixel>] [-y <pixel>] [-w <pixel>] [-h <pixel>] [-tw <pixel>] [-u]\n"
				   "             [-e <string>] [-l <lines>]  [-fn <font>] [-bg <color>] [-fg <color>]\n"
				   "             [-geometry <geometry string>] [-expand <left|right>] [-dock]\n"
				   "             [-title-name <string>] [-slave-name <string>]\n"
#ifdef DZEN_XINERAMA
				   "             [-xs <screen>]\n"
#endif
				  );

	if(dzen.tsupdate && !dzen.slave_win.max_lines)
		dzen.tsupdate = False;

	if(!dzen.title_win.width)
		dzen.title_win.width = dzen.slave_win.width;

	if(!setlocale(LC_ALL, "") || !XSupportsLocale())
		puts("dzen: locale not available, expect problems with fonts.\n");

	if(action_string)
		fill_ev_table(action_string);
	else {
		if(!dzen.slave_win.max_lines) {
			char edef[] = "button3=exit:13";
			fill_ev_table(edef);
		}
		else if(dzen.slave_win.ishmenu) {
			char edef[] = "enterslave=grabkeys;leaveslave=ungrabkeys;"
				"button4=scrollup;button5=scrolldown;"
				"key_Left=scrollup;key_Right=scrolldown;"
				"button1=menuexec;button3=exit:13;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
		else {
			char edef[]  = "entertitle=uncollapse,grabkeys;"
				"enterslave=grabkeys;leaveslave=collapse,ungrabkeys;"
				"button1=menuexec;button2=togglestick;button3=exit:13;"
				"button4=scrollup;button5=scrolldown;"
				"key_Up=scrollup;key_Down=scrolldown;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
	}

	if((find_event(onexit) != -1)
			&& (setup_signal(SIGTERM, catch_sigterm) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGTERM\n");

	if((find_event(sigusr1) != -1)
			&& (setup_signal(SIGUSR1, catch_sigusr1) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR1\n");

	if((find_event(sigusr2) != -1)
		&& (setup_signal(SIGUSR2, catch_sigusr2) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR2\n");

	if(setup_signal(SIGALRM, catch_alrm) == SIG_ERR)
		fprintf(stderr, "dzen: error hooking SIGALARM\n");

	if(dzen.slave_win.ishmenu &&
			!dzen.slave_win.max_lines)
		dzen.slave_win.max_lines = 1;


	x_create_windows(use_ewmh_dock);

	if(!dzen.slave_win.ishmenu)
		x_map_window(dzen.title_win.win);
	else {
		XMapRaised(dzen.dpy, dzen.slave_win.win);
		for(i=0; i < dzen.slave_win.max_lines; i++)
			XMapWindow(dzen.dpy, dzen.slave_win.line[i]);
	}

	if( fnpre != NULL )
		font_preload(fnpre);

	do_action(onstart);

	/* main loop */
	event_loop();

	do_action(onexit);
	clean_up();

	if(dzen.ret_val)
		return dzen.ret_val;

	return EXIT_SUCCESS;
}
Ejemplo n.º 8
0
    int NextPBin(int *penv)
    {
        double nChanged, nDied, nMitosed, nRemaining, nGone,
				nMigrationTo, MigrationPool,
     	    	nMutated, nMutatedTo, MutationPool, nConverted, nConvertedTo, ConversionPool,temp;
        int    iindex, jindex, AlteringEvent = false, anychanges;
        int    envnowl;
		unsigned int icelltype, getcelltype();
       	extern int get_dest_gap();
		extern void sort_lookuptable();
		void Gomp_UpdateTime();
       
		if (!ContinDrugRuleActive) /* Only check for an enviroment change if a BB rule isn't in effect */
			envnowl = getenvir( t );
		else
			envnowl = *penv;
		
		if (PendingEnvChange)
			CheckEnv( t, &envnowl );


		if ((KineticsModel == IsGompertz) && (t > UpdateTime)) {
			Gomp_UpdateTime(envnowl);
    		UpdateTime += UPDATEGAP*delta_t;
    	}

	   	anychanges = false;
    	pre_ntypes = active_ntypes;
   
	 for ( iindex= 1; iindex < MaxLookUp; iindex++ )
    	      nDescOfItype(iindex) = 0.0; /* set  matrix zero */
	 for ( iindex = 1; iindex <= pre_ntypes; iindex++ )
       {
          nChanged = nMutated = nDied = nMitosed = 0.0;
          if ( CN[iindex]>= 1.0 )
          {
             /* the number of cells that are mutated, died or devided */

            temp = EventProb(SomeEventProb,iindex,envnowl);
			nChanged= grand_b_n( CN[iindex],temp);
   

     		nRemaining = nChanged;
     		if ( nRemaining <= 0.0) goto NEXTCELLTYPE;
     
            anychanges = true;
            /* number of "itype" cells which died */
			temp = EventProb(GoneProb,iindex,envnowl);


            nGone = grand_b_n( nChanged,temp);

     		nDied = grand_b_n( nGone, CondProbDeath(iindex,envnowl));
     		
			nConverted = nGone - nDied;
     		ConversionPool = nConverted; 
			
			for ( jindex = 0; jindex < LookUp[iindex].ParaPr->NumOfCo; jindex++ )
     		{ 
    		   if ( ConversionPool <= 0.0)
     			 break;
    			 icelltype=getcelltype(iindex,jindex,envnowl,G0T);
    		   	 AlteringEvent = TRUE;
                 temp=CondCoTo(iindex,jindex,envnowl);
     			 nConvertedTo = grand_b_n( ConversionPool,temp);
     			 if ( nConvertedTo > 0.0 )
     			 {
					if ( (Class[0].class_type==1 ) && (labs((long) (LookUp[iindex].LookUpId-icelltype)))>= Tblength ) {
						/* A cell has converted from the ith to jth type */                        
     					if ((*OrganFunc)(iindex,icelltype,nConvertedTo,envnowl) ==False)
							return False;
					} 
					else { /* if not "organ" */
						if ( create_para_struct(icelltype,SIM) == False )
    						return False;
    					nDescOfItype(change_index) += nConvertedTo;
					}
    			
			   		if ( ConversionPool > nConvertedTo )
     					   ConversionPool = ConversionPool - nConvertedTo;
     				else
     					   ConversionPool = 0.0;
				}/* if nConverted > 0 */
     		} /* end of for loop */

			MigrationPool = ConversionPool;
			
			if ( MigrationPool > 0.0) {
				for ( jindex = 0; jindex < LookUp[iindex].ParaPr->NumOfMig; jindex++ )
     			{ 
    			  	 AlteringEvent = TRUE;
					 temp = CondMigTo(iindex,jindex,envnowl);
					 nMigrationTo = grand_b_n(	MigrationPool,temp);
					 if (nMigrationTo > 0.0 )
     				 {
						icelltype=getcelltype(iindex,jindex,envnowl,MIG);
    					if ( create_para_struct(icelltype,SIM)== False )
    						return False;
						nDescOfItype(change_index) += nMigrationTo;
     					
    					if ( MigrationPool > nMigrationTo )
     					   MigrationPool = MigrationPool - nMigrationTo;
     					else
     					   MigrationPool = 0.0;
						if ( MigrationPool  <= 0.0)
     						 break;
     			  }
     			}
			}
    		
    		nDescOfItype(iindex) -= nGone; 
     		nRemaining =  nChanged - nGone;
     		if ( nRemaining <= 0.0) goto NEXTCELLTYPE;
     
			temp = EventProb(MuProb,iindex,envnowl);
     		nMutated = grand_b_n( nRemaining, temp);
     		MutationPool = nMutated;                  /* number of cells mutated */
     		for ( jindex = 0; jindex < LookUp[iindex].ParaPr->NumOfMu; jindex++ )
     		{ 
    		   if ( MutationPool <= 0.0)
     			 break;
    			 icelltype=getcelltype(iindex,jindex,envnowl,MUTATION);
    			 AlteringEvent = TRUE;
    			 temp=CondMuTo(iindex,jindex,envnowl);
     			 nMutatedTo = grand_b_n( MutationPool,temp);
     			 if ( nMutatedTo > 0.0 )
     			 { /* A cell has mutated from the ith to jth type */   
					 if ( create_para_struct(icelltype,SIM) == False)
    						return False ;

    				 nDescOfItype(change_index) += nMutatedTo;
     								 
					 if ( MutationPool > nMutatedTo )
     					   MutationPool = MutationPool - nMutatedTo;
     				 else
     					   MutationPool = 0.0;
					 } /* if ( nMutatedTo > 0.0 ) */
     		}    /* end of for loop */     

     		nRemaining =  nChanged - nGone - nMutated;
     		if ( nRemaining <= 0.0) goto NEXTCELLTYPE;
    		
    		nDescOfItype(iindex) += nRemaining;  /* number of cells which divided */
    
     	  }
    	  NEXTCELLTYPE:  ; /* Skip to the next cell type.*/
      }
      if ( anychanges ){
     	  /* A change occurred in at least one cell (any type) */
     	  for ( iindex = 1 ; iindex <= active_ntypes; iindex++ ){
			if (Update_CN_NGomp(iindex,envnowl)== false )
				return false;
		}

		if ( (AlteringEvent == TRUE) && (verbos > 3) )
     		  eprint( "Note: at least one cell was altered (mutated or converted)\n" );
      }
  
#ifdef SORT   
	if ( pre_ntypes < active_ntypes)
		sort_lookuptable(pre_ntypes+1,active_ntypes,SIM);
#endif
   
      *penv=envnowl;
	  nowenv = envnowl;
      return True;
     }
Ejemplo n.º 9
0
int
main(int argc, char **argv)
{
    extern char *optarg;
    extern int optind, opterr, optopt;
    int option_index;
    int err_count;
    int optc;
    int rv;

    set_eprint_fh();
    program_path = *argv;
    program_name = sname(program_path);
    option_index = 0;
    err_count = 0;
    opterr = 0;

    while (true) {
        int this_option_optind;

        if (err_count > 10) {
            eprintf("%s: Too many option errors.\n", program_name);
            break;
        }

        this_option_optind = optind ? optind : 1;
        optc = getopt_long(argc, argv, "+hVdvEHw:", long_options, &option_index);
        if (optc == -1) {
            break;
        }

        rv = 0;
        if (optc == '?' && optopt == '?') {
            optc = 'h';
        }

        switch (optc) {
        case 'V':
            show_program_version();
            exit(0);
            break;
        case 'h':
            fputs(usage_text, stdout);
            exit(0);
            break;
        case 'd':
            debug = true;
            set_debug_fh(NULL);
            break;
        case 'v':
            verbose = true;
            break;
        case 'H':
            devolve_options |= (unsigned int)OPT_SOFT_HYPHENS;
            break;
        case 'c':
            devolve_options |= (unsigned int)OPT_SHOW_COUNTS;
            break;
        case '8':
            devolve_options |= (unsigned int)OPT_SHOW_8BIT;
            break;
        case 'C':
            if (variant_strcmp(optarg, "latin-1", VARIANT_WORDS) == 0) {
                charset = CHARSET_LATIN1;
            }
            else if (variant_strcmp(optarg, "iso-8859-1", VARIANT_WORDS) == 0) {
                charset = CHARSET_LATIN1;
            }
            else if (variant_strcmp(optarg, "utf-8", VARIANT_ACRONYM) == 0) {
                charset = CHARSET_UTF8;
            }
            else {
                eprintf("Unknown character set, '%s'\n", optarg);
                ++err_count;
            }
            break;
        case 't':
            devolve_options |= (unsigned int)OPT_TRACE_CONV;
            break;
        case 'e':
            devolve_options |= (unsigned int)OPT_TRACE_ERRORS;
            break;
        case 'u':
            devolve_options |= (unsigned int)OPT_TRACE_UNTRANS;
            break;
        case '?':
            eprint(program_name);
            eprint(": ");
            if (is_long_option(argv[this_option_optind])) {
                eprintf("unknown long option, '%s'\n",
                    argv[this_option_optind]);
            }
            else {
                char chrbuf[10];
                eprintf("unknown short option, '%s'\n",
                    vischar_r(chrbuf, sizeof (chrbuf), optopt));
            }
            ++err_count;
            break;
        default:
            eprintf("%s: INTERNAL ERROR: unknown option, '%c'\n",
                program_name, optopt);
            exit(64);
            break;
        }
    }

    if (debug) {
        verbose = true;
    }
    if (verbose) {
        devolve_options |= (unsigned int)OPT_SHOW_COUNTS;
    }

    if (optind < argc) {
        filec = (size_t) (argc - optind);
        filev = argv + optind;
    }
    else {
        filec = 0;
        filev = NULL;
    }

    if (verbose) {
        fshow_str_array(errprint_fh, filec, filev);
    }

    if (verbose && optind < argc) {
        eprintf("non-option ARGV-elements:\n");
        while (optind < argc) {
            eprintf("    %s\n", argv[optind]);
            ++optind;
        }
    }

    if (err_count != 0) {
        usage();
        exit(2);
    }

    if (filec) {
        rv = filev_probe(filec, filev);
        if (rv != 0) {
            exit(rv);
        }

        rv = devolve_filev(int_to_size(filec), filev, stdout);
    }
    else {
        char *fv_stdin = { "-" };
        rv = devolve_filev(1, &fv_stdin, stdout);
    }

    if (rv != 0) {
        exit(rv);
    }

    exit(0);
}
Ejemplo n.º 10
0
Archivo: main.c Proyecto: cobrajs/dzen
static void
x_create_windows(int use_ewmh_dock) {
	XSetWindowAttributes wa;
	Window root;
	int i;
	XRectangle si;
	XClassHint *class_hint;

	root = RootWindow(dzen.dpy, dzen.screen);

	/* style */
	if((dzen.norm[ColBG] = getcolor(dzen.bg)) == ~0lu)
		eprint("dzen: error, cannot allocate color '%s'\n", dzen.bg);
	if((dzen.norm[ColFG] = getcolor(dzen.fg)) == ~0lu)
		eprint("dzen: error, cannot allocate color '%s'\n", dzen.fg);
	setfont(dzen.fnt);

	x_create_gcs();

	/* window attributes */
	wa.override_redirect = (use_ewmh_dock ? 0 : 1);
	wa.background_pixmap = ParentRelative;
	wa.event_mask = ExposureMask | ButtonReleaseMask | ButtonPressMask | ButtonMotionMask | EnterWindowMask | LeaveWindowMask | KeyPressMask;

#ifdef DZEN_XINERAMA
	queryscreeninfo(dzen.dpy, &si, dzen.xinescreen);
#else
	qsi_no_xinerama(dzen.dpy, &si);
#endif
	x_check_geometry(si);

	/* title window */
	dzen.title_win.win = XCreateWindow(dzen.dpy, root,
			dzen.title_win.x, dzen.title_win.y, dzen.title_win.width, dzen.line_height, 0,
			DefaultDepth(dzen.dpy, dzen.screen), CopyFromParent,
			DefaultVisual(dzen.dpy, dzen.screen),
			CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
	/* set class property */
	class_hint = XAllocClassHint();
	class_hint->res_name  = "dzen2";
	class_hint->res_class = "dzen";
	XSetClassHint(dzen.dpy, dzen.title_win.win, class_hint);
	XFree(class_hint);

	/* title */
	XStoreName(dzen.dpy, dzen.title_win.win, dzen.title_win.name);

	dzen.title_win.drawable = XCreatePixmap(dzen.dpy, root, dzen.title_win.width,
			dzen.line_height, DefaultDepth(dzen.dpy, dzen.screen));
	XFillRectangle(dzen.dpy, dzen.title_win.drawable, dzen.rgc, 0, 0, dzen.title_win.width, dzen.line_height);

	/* set some hints for windowmanagers*/
	set_docking_ewmh_info(dzen.dpy, dzen.title_win.win, use_ewmh_dock);

	/* TODO: Smarter approach to window creation so we can reduce the
	 *       size of this function.
	 */

	if(dzen.slave_win.max_lines) {
		dzen.slave_win.first_line_vis = 0;
		dzen.slave_win.last_line_vis  = 0;
		dzen.slave_win.line     = emalloc(sizeof(Window) * dzen.slave_win.max_lines);
		dzen.slave_win.drawable =  emalloc(sizeof(Drawable) * dzen.slave_win.max_lines);

		/* horizontal menu mode */
		if(dzen.slave_win.ishmenu) {
			/* calculate width of menuentries - this is a very simple
			 * approach but works well for general cases.
			 */
			int ew = dzen.slave_win.width / dzen.slave_win.max_lines;
			int r = dzen.slave_win.width - ew * dzen.slave_win.max_lines;
			dzen.slave_win.issticky = True;
			dzen.slave_win.y = dzen.title_win.y;

			dzen.slave_win.win = XCreateWindow(dzen.dpy, root,
					dzen.slave_win.x, dzen.slave_win.y, dzen.slave_win.width, dzen.line_height, 0,
					DefaultDepth(dzen.dpy, dzen.screen), CopyFromParent,
					DefaultVisual(dzen.dpy, dzen.screen),
					CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
			XStoreName(dzen.dpy, dzen.slave_win.win, dzen.slave_win.name);

			for(i=0; i < dzen.slave_win.max_lines; i++) {
				dzen.slave_win.drawable[i] = XCreatePixmap(dzen.dpy, root, ew+r,
						dzen.line_height, DefaultDepth(dzen.dpy, dzen.screen));
			XFillRectangle(dzen.dpy, dzen.slave_win.drawable[i], dzen.rgc, 0, 0,
					ew+r, dzen.line_height);
			}


			/* windows holding the lines */
			for(i=0; i < dzen.slave_win.max_lines; i++)
				dzen.slave_win.line[i] = XCreateWindow(dzen.dpy, dzen.slave_win.win,
						i*ew, 0, (i == dzen.slave_win.max_lines-1) ? ew+r : ew, dzen.line_height, 0,
						DefaultDepth(dzen.dpy, dzen.screen), CopyFromParent,
						DefaultVisual(dzen.dpy, dzen.screen),
						CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);

			/* As we don't use the title window in this mode,
			 * we reuse its width value
			 */
			dzen.title_win.width = dzen.slave_win.width;
			dzen.slave_win.width = ew+r;
		}

		/* vertical slave window */
		else {
			dzen.slave_win.issticky = False;
			dzen.slave_win.y = dzen.title_win.y + dzen.line_height;

			if(dzen.title_win.y + dzen.line_height*dzen.slave_win.max_lines > si.y + si.height)
				dzen.slave_win.y = (dzen.title_win.y - dzen.line_height) - dzen.line_height*(dzen.slave_win.max_lines) + dzen.line_height;

			dzen.slave_win.win = XCreateWindow(dzen.dpy, root,
					dzen.slave_win.x, dzen.slave_win.y, dzen.slave_win.width, dzen.slave_win.max_lines * dzen.line_height, 0,
					DefaultDepth(dzen.dpy, dzen.screen), CopyFromParent,
					DefaultVisual(dzen.dpy, dzen.screen),
					CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
			XStoreName(dzen.dpy, dzen.slave_win.win, dzen.slave_win.name);

			for(i=0; i < dzen.slave_win.max_lines; i++) {
				dzen.slave_win.drawable[i] = XCreatePixmap(dzen.dpy, root, dzen.slave_win.width,
						dzen.line_height, DefaultDepth(dzen.dpy, dzen.screen));
				XFillRectangle(dzen.dpy, dzen.slave_win.drawable[i], dzen.rgc, 0, 0,
						dzen.slave_win.width, dzen.line_height);
			}

			/* windows holding the lines */
			for(i=0; i < dzen.slave_win.max_lines; i++)
				dzen.slave_win.line[i] = XCreateWindow(dzen.dpy, dzen.slave_win.win,
						0, i*dzen.line_height, dzen.slave_win.width, dzen.line_height, 0,
						DefaultDepth(dzen.dpy, dzen.screen), CopyFromParent,
						DefaultVisual(dzen.dpy, dzen.screen),
						CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
		}
	}

}
Ejemplo n.º 11
0
static void
usage(void)
{
    eprintf("usage: %s [ <options> ]\n", program_name);
    eprint(usage_text);
}
Ejemplo n.º 12
0
int DecodeFile(char * fname)
	{
	FILE * fIn;
	char line[8200];
	char * cp;
	char filename[260];
	FILE * fOut;
	int id;
	long flen,wlen;
	char filename2[260];

	fIn=fopen(fname,"rb");
	if (fIn==NULL)
		{
		eprint("Cannot open sourcefile (%s) [reason:%d]\r\n",fname,errno);
		errors++;
		return(1);
		}
loop:
	cp=fgets(line,8192,fIn);    // Read source line
	if (cp==NULL) goto eof1;

	cp=strrchr(line,'\n');     // Eliminate CRLF
	if (cp) *cp=0;
	cp=strrchr(line,'\r');
	if (cp) *cp=0;

	if (strncmp(line,"=ybegin ",8)) goto loop;


	if (aDsp) print("\r\nTrigger: %s\r\n",line);

	// Start of a section found

		cp=strstr(line,"name=");
		if (cp==NULL)
			{
			eprint("'name=' not found in =ybegin line. (%s)\r\n",line);
			errors++;
			goto loop;  // Error - filename not found
			}
		strcpy(attname,cp+5);  // Store the filename
		*cp=0; // throw away the filename

		cp=strstr(line,"size=");
		if (cp==NULL)
			{
			eprint("'size=' not found in =ybegin line. (%s)\r\n",line);
			errors++;
			goto loop;  // Error - size not found
			}
		y_size=atol(cp+5);

		cp=strstr(line,"line=");
		if (cp==NULL)
			{
			eprint("'line=' not found in =ybegin line. (%s)\r\n",line);
			errors++;
			goto loop;  // Error - linelength not found
			}
		y_line=atol(cp+5);

		y_part=0;
		cp=strstr(line,"part=");   // Check if this is a multipart message
		if (cp)
			{
			y_part=atol(cp+5);
//			if (y_part != 1) goto loop;   // MUST start with the first part for proper decoding
			}

		// Now we can decode the file -- let's assume that this is a valid file

		attext[0]=0;
		cp=strrchr(attname,'.');
		if (cp)
			{
			strcpy(attext,cp); *cp=0;
			}

		// sprintf(filename,"%s\\decode.tmp",datadir);
		sprintf(filename,"%sdecode.tmp",ad_despath);

	// ----- Special Handling for offline decoder (missing parts or mixed sequence)
	if (y_part)
		{
		sprintf(filename ,"%s%s%s(%ld).tmp",ad_despath,attname,attext,y_size);
		sprintf(filename2,"%s%s%s(%ld).dec",ad_despath,attname,attext,y_size);
		}
	// ----------------------------------------------------------------------


		if (aDsp) print("DesFileName = (%s%s)\r\n",attname,attext);

		// 27-03-2001: Set the filename just in case we cannot decode it
		sprintf(ad_desname,"%s\\%s%s",ad_despath,attname,attext);
		// sprintf(ad_desname,"%s%s",attname,attext);

		// filelen=0;

/*    Not used in standalone decoder

		if (ad_crcmode) CrcInit();
		if (ad_cleanmode)
			{
			ad_cleanmode=2;  // This will prevent us from writing more to the clean buffer
			if (aDsp) print("Begin cleaning...\r\n");
			CrcInit();
			}
*/

		// Check if the target file exists already
		if (y_part)
			{

			fOut=fopen(filename2,"rb");
			if (fOut)
				{
				flen=filelength(fileno(fOut));
				fclose(fOut);
				if (flen==0)
					{
					print("Part#%3d duplicate for finished %s \r\n",y_part,ad_desname);
					goto loop;
					}
				}

			fOut=fopen(filename,"r+b");
			if (fOut)
				{
				flen=filelength(fileno(fOut));
				if (flen==y_size)
					{
					goto already_open;
					}
				else
					{
					fclose(fOut);
					eprint("Size mismatch on target multipart file !(act:%ld, new:%ld) (%s)\r\n",flen,y_size,filename);
					errors++;
					goto abortus;
					}
				}
			else // First time: Create this file & the missing index
				{
				fOut=fopen(filename2,"wb");
				if (fOut==NULL)
					{
					eprint("Cannot create part-info-file (%s)\r\n",filename2);
					errors++;
					goto abortus;
					}
				fprintf(fOut,"%ld,%ld\r\n",1,y_size);  // Everything is missing !
				fclose(fOut);
				}
			}

		fOut=fopen(filename,"w+b");
		if (fOut==NULL)  // Possibly already exists
			{
			eprint("AutoDecode: Cannot create DesFile (%s)\r\n",filename);
			errors++;
			fclose(fIn);
			return(-1);
			// goto loop;
			}

		if (y_part)  // Now create the entire file !
			{
			flen=y_size;
			memset(line,255,8192);
			while (flen>0)
				{
				wlen=flen;
				if (wlen>8192) wlen=8192;
				id=fwrite(line,wlen,1,fOut);
				if (id!=1)
					{
					eprint("Could not create the target file (disk full?)\r\n");
					fclose(fOut);
					fclose(fIn);
					errors++;
					return(-2);
					}
				flen=flen-wlen;
				}
			}
	already_open:

		// Now decode that file !

		id=yDecode(fOut,fIn,y_line,y_size,y_part);
		if (id)
			{
			eprint("yDecode failed (reason: %d)\r\n",id);
			goto abortus;
			}
		sprintf(ad_desname,"%s%s%s",ad_despath,attname,attext); // Create new target name
		if (aDsp) print("yDecode successful\r\n");
		fclose(fOut);

		// ----- Special handling for offline multipart

		if (y_part)  // Now update the 'missing part file'
			{
			id=AddPart(filename2,y_begin,y_end);
			if (id==0)  // All parts done
				{
				print("Complete multipart --> %s\r\n",ad_desname);
				goto rename_it;
				}
			if (id>0)
				{
				print("Part#%3d: %s --> %s\r\n",y_part,fname,ad_desname);
				}
			if (id==(-9))
				{
				print("Part#%3d of finished %s \r\n",y_part,ad_desname);
				}
			}
		if (y_part) goto loop;
		// --------------------------------------------

	rename_it:
		// Now check if the target file exists already
		id=rename(filename,ad_desname);
		if (id)
			{
			if (errno==35)
				{
				eprint("File exists already: (%s)\r\n",ad_desname);
				errors++;
				}
			else
				{
				eprint("Cannot create target file (%s) [reason: %d]\r\n",ad_desname,errno);
				errors++;
				}
			}
		else
			{
			if (y_part==0) print("Decoded:  %s --> %s\r\n",fname,ad_desname);
			if (y_part)    print("Decoded multipart --> %s\r\n",ad_desname);
			}
abortus:
	goto loop;


eof1:
	fclose(fIn);
	return(0);
	}
Ejemplo n.º 13
0
int AddPart(char * srcname,long y_begin, long y_end)
	{
	FILE * fSrc;
	FILE * fDes;
	char desname[260];
	char line[1024];
	long a,e;
	int copyrest;
	char * cp;
	int resparts;
	long flen;

	if (aDsp) print("AddPart (%s) [%ld - %ld]\r\n",srcname,y_begin,y_end);


	copyrest=0;
	resparts=0;

	sprintf(desname,"%s.des",srcname);

	fSrc=fopen(srcname,"rb");
	if (fSrc==NULL)
		{
		eprint("AddPart:  Part Info File not found (%s)\r\n",srcname);
		errors++;
		return(-1);
		}
	flen=filelength(fileno(fSrc));
	if (flen==0)  // Already complete
		{
		return(-9);
		}
	fDes=fopen(desname,"wb");
	if (fDes==NULL)
		{
		eprint("AddPart: Cannot create temporary part file (%s) [reason: %d]\r\n",desname,errno);
		fclose(fSrc);
		errors++;
		return(-2);
		}
loop:
	cp=fgets(line,1000,fSrc);
	if (cp==NULL) goto eof1;
	cp=strrchr(line,'\n');
	if (cp) *cp=0;
	cp=strrchr(line,'\r');
	if (cp) *cp=0;

	// print("%s\r\n",line);

	if (copyrest)  // Analysis done - copy rest & done.
		{
		fprintf(fDes,"%s\r\n",line);
		resparts++;
		goto loop;
		}

	a=atol(line);
	if (a==0)
		{
		eprint("Corrupt part-info file (%s)\r\n",line);
		errors++;
		fclose(fSrc); fclose(fDes); return(-3);
		}
	cp=strchr(line,',');
	if (cp==NULL)
		{
		eprint("Corrupt part-info file (%s)\r\n",line);
		errors++;
		fclose(fSrc); fclose(fDes); return(-4);
		}
	e=atol(cp+1);
	//	print("a:%6d, e:%6d\r\n",a,e);

// ----- Case Analysis -----
//	.............[yb--------ye]      (The new, incoming block)
//	1...a****e                       (The old, missing block)
//	2...a********-----e              (***) Newly written missing block
//	3...a********--------------****e
//	.............[yb--------ye]
//	4............a-----e
// 5............a------------e
//	6............a-------------****e
//	.............[yb--------ye]
//	7............................a***e
//	.............[yb--------ye]
//	8................a----e
//	9................a---------****e




	if (a<y_begin)  // A previous section was missed
		{
		if (e<y_begin) // A previous section was missed entirely
			{
			// Case-1
			fprintf(fDes,"%ld,%ld\r\n",a,e);  // --> Keep that entry
			resparts++;
			goto loop;
			}
		if (e<=y_end)  // Rduce the old section
			{
			// Case-2
			fprintf(fDes,"%ld,%ld\r\n",a,y_begin-1);  // --> Reduce that entry
			resparts++;
			goto loop;
			}
		// The new section is splitting the old missing section
			// Case-3
			fprintf(fDes,"%ld,%ld\r\n",a,y_begin-1);  // --> First part
			fprintf(fDes,"%ld,%ld\r\n",y_end+1,e);  // --> First part
			resparts++; resparts++;
			goto loop;
		}

	if (a==y_begin)  // New part matches this segment
		{
		if (e<y_end)   // Just a smaller section was missed
			{
			// case 4
			goto loop;  // Skip this and analyse next
			}
		if (e==y_end)  // This missing section was exactly -> remove it & done.
			{
			// case 5
			copyrest=1; goto loop;
			}
		if (e>y_end)  // The first part was found
			{
			// case-6
			fprintf(fDes,"%ld,%ld\r\n",y_end+1,e);  // Write the rest
			resparts++;
			copyrest=1; goto loop;
			}
		}

	if (a>y_begin)
		{
		if (a>y_end)  // the found section completely in front of this one.
			{
			// Case-7
			fprintf(fDes,"%ld,%ld\r\n",a,e);  // Rewrite it & copy the rest
			resparts++;
			copyrest=1; goto loop;
			}
		if (e<=y_end) // The section was completely found
			{
			// Case-8
			goto loop;  // Analyse the rest
			}
		// The first part of the missing section was found
			// case-9
			fprintf(fDes,"%ld,%ld\r\n",y_end+1,e);  // Reduce it & copy the rest
			resparts++;
			copyrest=1; goto loop;
		}

eof1:
	fclose(fSrc); fclose(fDes);
	remove(srcname);

	rename(desname,srcname);

	return(resparts);
	}
Ejemplo n.º 14
0
void die(int code, char *str) {
 eprint(P_FATAL, str);
 exit(code);
}
Ejemplo n.º 15
0
/**
 * This function should initialise the server,
 * and it not invoked after a re-exec.
 * 
 * @return  Non-zero on error
 */
int initialise_server(void)
{
  struct vt_mode mode;
  char* display_env;
  int primary_socket_fd;
  int stage = 0;
  const char* const message =
    "Command: intercept\n"
    "Message ID: 0\n"
    "Length: 38\n"
    "\n"
    "Command: get-vt\n"
    "Command: configure-vt\n";
  const char* const secondary_message =
    "Command: intercept\n"
    "Message ID: 0\n"
    "Priority: -4611686018427387904\n" /* −2⁶² */
    "Length: 22\n"
    "\n"
    "Command: switching-vt\n";
  
  primary_socket_fd = socket_fd;
  fail_if (connect_to_display());
  secondary_socket_fd = socket_fd;
  socket_fd = primary_socket_fd;
  
  display_env = getenv("MDS_DISPLAY");
  display_env = display_env ? strchr(display_env, ':') : NULL;
  if ((display_env == NULL) || (strlen(display_env) < 2))
    goto no_display;
  
  memset(vtfile_path, 0, sizeof(vtfile_path));
  xsnprintf(vtfile_path, "%s/%s.vt", MDS_RUNTIME_ROOT_DIRECTORY, display_env + 1);
  stage = 1;
  
  if (is_respawn == 0)
    {
      display_vt = select_vt();
      fail_if (display_vt < 0);
      display_tty_fd = vt_open(display_vt, &old_vt_stat);
      fail_if (write_vt_file() < 0);
      fail_if (vt_set_active(display_vt) < 0);
    }
  else
    {
      fail_if (read_vt_file() < 0);
      vt_is_active = (display_vt == vt_get_active());
      fail_if (vt_is_active < 0);
    }
  
  fail_if (full_send(secondary_socket_fd, secondary_message, strlen(secondary_message)));
  fail_if (full_send(socket_fd, message, strlen(message)));
  fail_if (server_initialised() < 0);
  fail_if (mds_message_initialise(&received)); stage = 2;
  
  fail_if (xsigaction(SIGRTMIN + 2, received_switch_vt) < 0);
  fail_if (xsigaction(SIGRTMIN + 3, received_switch_vt) < 0);
  vt_construct_mode(1, SIGRTMIN + 2, SIGRTMIN + 3, &mode);
  fail_if (vt_get_set_mode(display_tty_fd, 1, &mode) < 0);
  if (vt_set_exclusive(display_tty_fd, 1) < 0)
    xperror(*argv);
  
  return 0;
 no_display:
  eprint("no display has been set, how did this happen.");
  return 1;
 fail:
  xperror(*argv);
  if (stage >= 1)
    unlink(vtfile_path);
  if (display_tty_fd >= 0)
    vt_close(display_tty_fd, &old_vt_stat);
  if (stage >= 2)
    mds_message_destroy(&received);
  return 1;
}
Ejemplo n.º 16
0
/* thread the wicked function */
static void *threadwicked(void *targ){
  TCFDB *fdb = ((TARGWICKED *)targ)->fdb;
  int rnum = ((TARGWICKED *)targ)->rnum;
  bool nc = ((TARGWICKED *)targ)->nc;
  int id = ((TARGWICKED *)targ)->id;
  TCMAP *map = ((TARGWICKED *)targ)->map;
  bool err = false;
  for(int i = 1; i <= rnum && !err; i++){
    uint64_t kid = myrand(rnum * (id + 1)) + 1;
    char kbuf[RECBUFSIZ];
    int ksiz = sprintf(kbuf, "%llu", (unsigned long long)kid);
    char vbuf[RECBUFSIZ];
    int vsiz = myrand(RECBUFSIZ);
    memset(vbuf, '*', vsiz);
    vbuf[vsiz] = '\0';
    char *rbuf;
    if(!nc) tcglobalmutexlock();
    switch(myrand(16)){
      case 0:
        if(id == 0) iputchar('0');
        if(!tcfdbput2(fdb, kbuf, ksiz, vbuf, vsiz)){
          eprint(fdb, __LINE__, "tcfdbput2");
          err = true;
        }
        if(!nc) tcmapput(map, kbuf, ksiz, vbuf, vsiz);
        break;
      case 1:
        if(id == 0) iputchar('1');
        if(!tcfdbput3(fdb, kbuf, vbuf)){
          eprint(fdb, __LINE__, "tcfdbput3");
          err = true;
        }
        if(!nc) tcmapput2(map, kbuf, vbuf);
        break;
      case 2:
        if(id == 0) iputchar('2');
        if(!tcfdbputkeep2(fdb, kbuf, ksiz, vbuf, vsiz) && tcfdbecode(fdb) != TCEKEEP){
          eprint(fdb, __LINE__, "tcfdbputkeep2");
          err = true;
        }
        if(!nc) tcmapputkeep(map, kbuf, ksiz, vbuf, vsiz);
        break;
      case 3:
        if(id == 0) iputchar('3');
        if(!tcfdbputkeep3(fdb, kbuf, vbuf) && tcfdbecode(fdb) != TCEKEEP){
          eprint(fdb, __LINE__, "tcfdbputkeep3");
          err = true;
        }
        if(!nc) tcmapputkeep2(map, kbuf, vbuf);
        break;
      case 4:
        if(id == 0) iputchar('4');
        if(!tcfdbputcat2(fdb, kbuf, ksiz, vbuf, vsiz)){
          eprint(fdb, __LINE__, "tcfdbputcat2");
          err = true;
        }
        if(!nc) tcmapputcat(map, kbuf, ksiz, vbuf, vsiz);
        break;
      case 5:
        if(id == 0) iputchar('5');
        if(!tcfdbputcat3(fdb, kbuf, vbuf)){
          eprint(fdb, __LINE__, "tcfdbputcat3");
          err = true;
        }
        if(!nc) tcmapputcat2(map, kbuf, vbuf);
        break;
      case 6:
        if(id == 0) iputchar('6');
        if(myrand(2) == 0){
          if(!tcfdbout2(fdb, kbuf, ksiz) && tcfdbecode(fdb) != TCENOREC){
            eprint(fdb, __LINE__, "tcfdbout2");
            err = true;
          }
          if(!nc) tcmapout(map, kbuf, ksiz);
        }
        break;
      case 7:
        if(id == 0) iputchar('7');
        if(myrand(2) == 0){
          if(!tcfdbout3(fdb, kbuf) && tcfdbecode(fdb) != TCENOREC){
            eprint(fdb, __LINE__, "tcfdbout3");
            err = true;
          }
          if(!nc) tcmapout2(map, kbuf);
        }
        break;
      case 8:
        if(id == 0) iputchar('8');
        if(!(rbuf = tcfdbget2(fdb, kbuf, ksiz, &vsiz))){
          if(tcfdbecode(fdb) != TCENOREC){
            eprint(fdb, __LINE__, "tcfdbget2");
            err = true;
          }
          rbuf = tcsprintf("[%d]", myrand(i + 1));
          vsiz = strlen(rbuf);
        }
        vsiz += myrand(vsiz);
        if(myrand(3) == 0) vsiz += PATH_MAX;
        rbuf = tcrealloc(rbuf, vsiz + 1);
        for(int j = 0; j < vsiz; j++){
          rbuf[j] = myrand(0x100);
        }
        if(!tcfdbput2(fdb, kbuf, ksiz, rbuf, vsiz)){
          eprint(fdb, __LINE__, "tcfdbput2");
          err = true;
        }
        if(!nc) tcmapput(map, kbuf, ksiz, rbuf, vsiz);
        tcfree(rbuf);
        break;
      case 9:
        if(id == 0) iputchar('9');
        if(!(rbuf = tcfdbget2(fdb, kbuf, ksiz, &vsiz)) && tcfdbecode(fdb) != TCENOREC){
          eprint(fdb, __LINE__, "tcfdbget2");
          err = true;
        }
        tcfree(rbuf);
        break;
      case 10:
        if(id == 0) iputchar('A');
        if(!(rbuf = tcfdbget3(fdb, kbuf)) && tcfdbecode(fdb) != TCENOREC){
          eprint(fdb, __LINE__, "tcfdbge3");
          err = true;
        }
        tcfree(rbuf);
        break;
      case 11:
        if(id == 0) iputchar('B');
        if(myrand(1) == 0) vsiz = 1;
        if((vsiz = tcfdbget4(fdb, kid, vbuf, vsiz)) < 0 && tcfdbecode(fdb) != TCENOREC){
          eprint(fdb, __LINE__, "tcfdbget4");
          err = true;
        }
        break;
      case 14:
        if(id == 0) iputchar('E');
        if(myrand(rnum / 50) == 0){
          if(!tcfdbiterinit(fdb)){
            eprint(fdb, __LINE__, "tcfdbiterinit");
            err = true;
          }
        }
        for(int j = myrand(rnum) / 1000 + 1; j >= 0; j--){
          if(tcfdbiternext(fdb) < 1){
            int ecode = tcfdbecode(fdb);
            if(ecode != TCEINVALID && ecode != TCENOREC){
              eprint(fdb, __LINE__, "tcfdbiternext");
              err = true;
            }
          }
        }
        break;
      default:
        if(id == 0) iputchar('@');
        if(tcfdbtranbegin(fdb)){
          if(myrand(2) == 0){
            if(!tcfdbput2(fdb, kbuf, ksiz, vbuf, vsiz)){
              eprint(fdb, __LINE__, "tcfdbput");
              err = true;
            }
            if(!nc) tcmapput(map, kbuf, ksiz, vbuf, vsiz);
          } else {
            if(!tcfdbout2(fdb, kbuf, ksiz) && tcfdbecode(fdb) != TCENOREC){
              eprint(fdb, __LINE__, "tcfdbout");
              err = true;
            }
            if(!nc) tcmapout(map, kbuf, ksiz);
          }
          if(nc && myrand(2) == 0){
            if(!tcfdbtranabort(fdb)){
              eprint(fdb, __LINE__, "tcfdbtranabort");
              err = true;
            }
          } else {
            if(!tcfdbtrancommit(fdb)){
              eprint(fdb, __LINE__, "tcfdbtrancommit");
              err = true;
            }
          }
        } else {
          eprint(fdb, __LINE__, "tcfdbtranbegin");
          err = true;
        }
        if(myrand(1000) == 0){
          if(!tcfdbforeach(fdb, iterfunc, NULL)){
            eprint(fdb, __LINE__, "tcfdbforeach");
            err = true;
          }
        }
        if(myrand(10000) == 0) srand((unsigned int)(tctime() * 1000) % UINT_MAX);
        break;
    }
    if(!nc) tcglobalmutexunlock();
    if(id == 0){
      if(i % 50 == 0) iprintf(" (%08d)\n", i);
      if(id == 0 && i == rnum / 4){
        if(!tcfdboptimize(fdb, RECBUFSIZ, -1) && tcfdbecode(fdb) != TCEINVALID){
          eprint(fdb, __LINE__, "tcfdboptimize");
          err = true;
        }
        if(!tcfdbiterinit(fdb)){
          eprint(fdb, __LINE__, "tcfdbiterinit");
          err = true;
        }
      }
    }
  }
  return err ? "error" : NULL;
}
Ejemplo n.º 17
0
Archivo: main.c Proyecto: csimons/cswm
int
main(int argc, char *argv[]) {
    int i, j;
    unsigned int mask;
    Window w;
    XEvent ev;
    XModifierKeymap *modmap;
    XSetWindowAttributes wa;

    if(argc == 2 && !strncmp("-v", argv[1], 3))
        eprint("cswm-"VERSION", Copyright 2006 Anselm R. Garbe, 2012 Christopher L. Simons\n");
    else if(argc != 1)
        eprint("usage: cswm [-v]\n");
    setlocale(LC_CTYPE, "");
    dpy = XOpenDisplay(0);
    if(!dpy)
        eprint("cswm: cannot open display\n");
    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);
    otherwm = False;
    XSetErrorHandler(xerrorstart);
    /* this causes an error if some other window manager is running */
    XSelectInput(dpy, root, SubstructureRedirectMask);
    XSync(dpy, False);
    if(otherwm)
        eprint("cswm: another window manager is already running\n");

    XSync(dpy, False);
    XSetErrorHandler(NULL);
    xerrorxlib = XSetErrorHandler(xerror);
    XSync(dpy, False);

    /* init atoms */
    wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
    wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
    wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
    netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
    netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
    XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
            PropModeReplace, (unsigned char *) netatom, NetLast);
    /* init cursors */
    cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
    cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
    cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
    /* init modifier map */
    numlockmask = 0;
    modmap = XGetModifierMapping(dpy);
    for (i = 0; i < 8; i++) {
        for (j = 0; j < modmap->max_keypermod; j++) {
            if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
                numlockmask = (1 << i);
        }
    }
    XFreeModifiermap(modmap);
    /* select for events */
    wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
        | EnterWindowMask | LeaveWindowMask;
    wa.cursor = cursor[CurNormal];
    XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
    grabkeys();
    /* style */
    normcol = getcolor(NORMCOLOR);
    selcol = getcolor(SELCOLOR);
    /* geometry */
    sx = 0;
    sy = SY;
    sw = DisplayWidth(dpy, screen);
    sh = SH;
    master = MASTER;
    nmaster = NMASTER;
    /* multihead support */
    selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
    scan();
    runAutostart();

    /* main event loop, also reads status text from stdin */
    XSync(dpy, False);

    while(running) {
         XNextEvent(dpy, &ev);
        if(handler[ev.type])
            (handler[ev.type])(&ev); /* call handler */
    }
    cleanup();
    XCloseDisplay(dpy);
    return 0;
}
Ejemplo n.º 18
0
/* perform combo command */
static int proccombo(int tnum, int rnum, int bnum, bool tr, bool rnd){
  iprintf("<Combination Test>\n  seed=%u  tnum=%d  rnum=%d  bnum=%d  tr=%d  rnd=%d\n\n",
          g_randseed, tnum, rnum, bnum, tr, rnd);
  bool err = false;
  double stime = tctime();
  TCMDB *mdb = (bnum > 0) ? tcmdbnew2(bnum) : tcmdbnew();
  TCNDB *ndb = tcndbnew();
  TARGCOMBO targs[tnum];
  pthread_t threads[tnum];
  if(tnum == 1){
    targs[0].mdb = mdb;
    targs[0].ndb = tr ? ndb : NULL;
    targs[0].rnum = rnum;
    targs[0].rnd = rnd;
    targs[0].id = 0;
    if(threadwrite(targs) != NULL) err = true;
  } else {
    for(int i = 0; i < tnum; i++){
      targs[i].mdb = mdb;
      targs[i].ndb = tr ? ndb : NULL;
      targs[i].rnum = rnum;
      targs[i].rnd = rnd;
      targs[i].id = i;
      if(pthread_create(threads + i, NULL, threadwrite, targs + i) != 0){
        eprint(__LINE__, "pthread_create");
        targs[i].id = -1;
        err = true;
      }
    }
    for(int i = 0; i < tnum; i++){
      if(targs[i].id == -1) continue;
      void *rv;
      if(pthread_join(threads[i], &rv) != 0){
        eprint(__LINE__, "pthread_join");
        err = true;
      } else if(rv){
        err = true;
      }
    }
  }
  if(tnum == 1){
    targs[0].mdb = mdb;
    targs[0].ndb = tr ? ndb : NULL;
    targs[0].rnum = rnum;
    targs[0].rnd = rnd;
    targs[0].id = 0;
    if(threadread(targs) != NULL) err = true;
  } else {
    for(int i = 0; i < tnum; i++){
      targs[i].mdb = mdb;
      targs[i].ndb = tr ? ndb : NULL;
      targs[i].rnum = rnum;
      targs[i].rnd = rnd;
      targs[i].id = i;
      if(pthread_create(threads + i, NULL, threadread, targs + i) != 0){
        eprint(__LINE__, "pthread_create");
        targs[i].id = -1;
        err = true;
      }
    }
    for(int i = 0; i < tnum; i++){
      if(targs[i].id == -1) continue;
      void *rv;
      if(pthread_join(threads[i], &rv) != 0){
        eprint(__LINE__, "pthread_join");
        err = true;
      } else if(rv){
        err = true;
      }
    }
  }
  if(tnum == 1){
    targs[0].mdb = mdb;
    targs[0].ndb = tr ? ndb : NULL;
    targs[0].rnum = rnum;
    targs[0].rnd = rnd;
    targs[0].id = 0;
    if(threadremove(targs) != NULL) err = true;
  } else {
    for(int i = 0; i < tnum; i++){
      targs[i].mdb = mdb;
      targs[i].ndb = tr ? ndb : NULL;
      targs[i].rnum = rnum;
      targs[i].rnd = rnd;
      targs[i].id = i;
      if(pthread_create(threads + i, NULL, threadremove, targs + i) != 0){
        eprint(__LINE__, "pthread_create");
        targs[i].id = -1;
        err = true;
      }
    }
    for(int i = 0; i < tnum; i++){
      if(targs[i].id == -1) continue;
      void *rv;
      if(pthread_join(threads[i], &rv) != 0){
        eprint(__LINE__, "pthread_join");
        err = true;
      } else if(rv){
        err = true;
      }
    }
  }
  if(tr){
    iprintf("record number: %llu\n", (unsigned long long)tcndbrnum(ndb));
    iprintf("size: %llu\n", (unsigned long long)tcndbmsiz(ndb));
  } else {
    iprintf("record number: %llu\n", (unsigned long long)tcmdbrnum(mdb));
    iprintf("size: %llu\n", (unsigned long long)tcmdbmsiz(mdb));
  }
  tcndbdel(ndb);
  tcmdbdel(mdb);
  iprintf("time: %.3f\n", tctime() - stime);
  iprintf("%s\n\n", err ? "error" : "ok");
  return err ? 1 : 0;
}
Ejemplo n.º 19
0
int config_load (char *filename, config_t *cfg, ircclient_t **clients)
{
	int i;
	lua_State *L = lua_open ();

	iprint ("Loading configuration file: %s", filename);

	if (!L)
	{
		eprint (1, "Could not initialize Lua", filename);
	}

	luaL_openlibs (L);

	if (luaL_loadfile (L, filename) || lua_pcall (L, 0, 0, 0))
	{
		eprint (1, "Could not open config file %s.", filename);
	}

	// Load defaults
	lua_getglobal (L, "nick");
	lua_getglobal (L, "username");
	lua_getglobal (L, "realname");
	lua_getglobal (L, "prefix");

	if (!lua_isstring (L, -1) || !lua_isstring (L, -2) || !lua_isstring (L, -3) ||
	    !lua_isstring (L, -4))
	{
		eprint (1, "Could not load defaults. Make sure that \"nick\", \"username\", \"realname\", and \"prefix\" are set in %s.", filename);
	}

	cfg->nick = (char*) malloc (strlen (lua_tostring (L, -4)) + 1);
	cfg->username = (char*) malloc (strlen (lua_tostring (L, -3)) + 1);
	cfg->realname = (char*) malloc (strlen (lua_tostring (L, -2)) + 1);
	cfg->prefix = lua_tostring (L, -1) [0];

	strncpy (cfg->nick, lua_tostring (L, -4), strlen (lua_tostring (L, -4)) + 1);
	strncpy (cfg->username, lua_tostring (L, -3), strlen (lua_tostring (L, -3)) + 1);
	strncpy (cfg->realname, lua_tostring (L, -2), strlen (lua_tostring (L, -2)) + 1);

	lua_pop (L, 4);

	lua_getglobal (L, "servers");

	if (!lua_istable (L, -1))
	{
		eprint (1, "Server table not set in %s.", filename);
	}

	// Load up the server tables
	for (i = 1; i <= MAXCLIENTS; i++)
	{
		ircclient_t *cl;
		int j;

		lua_pushnumber (L, i);
		lua_gettable (L, -2);

		if (!lua_istable (L, -1))
		{
			lua_pop (L, 1);
			continue;
		}

		lua_pushstring (L, "host");
		lua_gettable (L, -2);
		lua_pushstring (L, "port");
		lua_gettable (L, -3);
		lua_pushstring (L, "nick");
		lua_gettable (L, -4);
		lua_pushstring (L, "owner");
		lua_gettable (L, -5);

		if (!lua_isstring (L, -4))
		{
			eprint (0, "\"host\" for servers[%i] unset. Skipping.", i);
			lua_pop (L, 5);
			continue;
		}

		if (!lua_isstring (L, -1))
		{
			eprint (0, "\"owner\" not set for servers[%i]. Skipping.", i);
			lua_pop (L, 5);
			continue;
		}

		clients [i - 1] = (ircclient_t*) malloc (sizeof (ircclient_t));
		cl = clients [i - 1];

		cl->host = (char*) malloc (strlen (lua_tostring (L, -4)) + 1);
		cl->port = (char*) malloc (6); // port number only goes from 0 to 65535
		cl->nick = (char*) malloc (lua_isstring (L, -2) ? strlen (lua_tostring (L, -2)) + 1 : strlen (cfg->nick) + 1);
		cl->owner = (char*) malloc (strlen (lua_tostring (L, -1)));

		strcpy (clients [i - 1]->host, lua_tostring (L, -4));

		if (lua_isnumber (L, -3))
			sprintf (cl->port, "%i", (int) lua_tonumber (L, -3));
		else
			sprintf (cl->port, "%i", 6667);

		strncpy (cl->nick, lua_isstring (L, -2) ? lua_tostring (L, -2) : cfg->nick,
		         lua_isstring (L, -2) ? strlen (lua_tostring (L, -2)) + 1 : strlen (cfg->nick) + 1);
		strncpy (cl->owner, lua_tostring (L, -1), strlen (lua_tostring (L, -1)) + 1);

		lua_pop (L, 4);

		lua_pushstring (L, "ns_nick");
		lua_gettable (L, -2);
		lua_pushstring (L, "ns_command");
		lua_gettable (L, -3);

		if (lua_isstring (L, -1) && lua_isstring (L, -2))
		{
			cl->ns_nick = (char*) malloc (strlen (lua_tostring (L, -2)) + 1);
			cl->ns_command = (char*) malloc (strlen (lua_tostring (L, -1)) + 1);

			strncpy (cl->ns_nick, lua_tostring (L, -2), strlen (lua_tostring (L, -2)) + 1);
			strncpy (cl->ns_command, lua_tostring (L, -1), strlen (lua_tostring (L, -1)) + 1);
		}
		else
		{
			cl->ns_nick = NULL;
			cl->ns_command = NULL;
		}

		lua_pop (L, 2);

		// Load up channels
		lua_pushstring (L, "channels");
		lua_gettable (L, -2);

		if (!lua_istable (L, -1))
		{
			lua_pop (L, 2);
			eprint (0, "Channel array for %s wasn't found. Continuing without joining any channels", cl->host);
			cl->channels = NULL;
			continue;
		}

		cl->channels = (chanlist_t*) malloc (sizeof (chanlist_t));
		chanlist_t *it = cl->channels;

		j = 1;
		while (1)
		{
			lua_pushnumber (L, j);
			lua_gettable (L, -2);

			if (lua_isstring (L, -1)) // no password
			{
				strncpy ((char*) it->name, lua_tostring (L, -1), MAXCHANLEN);
				lua_pop (L, 1);
			}
			else if (lua_istable (L, -1)) // Passworded
			{
				lua_pushnumber (L, 1);
				lua_gettable (L, -2);
				lua_pushnumber (L, 2);
				lua_gettable (L, -3);

				if (lua_isstring (L, -1) && lua_isstring (L, -2))
				{
					strncpy ((char*) it->name, lua_tostring (L, -2), MAXCHANLEN);
					strncpy ((char*) it->pass, lua_tostring (L, -1), MAXCHANLEN);
				}

				lua_pop (L, 3);
			}
			else if (lua_isnil (L, -1))
				break;

			it->next = (chanlist_t*) malloc (sizeof (chanlist_t));
			it = it->next;
			it->name [0] = '\0';
			it->pass [0] = '\0';
			it->next = NULL;
			j++;
		}

		lua_pop (L, 3);
	}

	// Load modules
	lua_getglobal (L, "modpath");

	if (lua_isstring (L, -1))
	{
		cfg->modpath = (char*) malloc (strlen (lua_tostring (L, -1)) + 1);
		strncpy (cfg->modpath, lua_tostring (L, -1), strlen (lua_tostring (L, -1)) + 1);
	}
	else
		cfg->modpath = "./modules/";

	lua_pop (L, 1);
	lua_getglobal (L, "modules");

	if (!lua_istable (L, -1))
	{
		eprint (0, "Module list not found.");
		lua_close (L);
		return 0;
	}

	i = 1;
	while (1)
	{
		lua_pushnumber (L, i);
		lua_gettable (L, -2);

		if (lua_isstring (L, -1))
		{
			cfg->modlist [i - 1] = (char*) malloc (strlen (cfg->modpath) + strlen (lua_tostring (L, -1)) + 1);
			sprintf (cfg->modlist [i - 1], "%s%s", cfg->modpath, lua_tostring (L, -1));
		}
		else
			cfg->modlist [i - 1] = NULL;

		lua_pop (L, 1);

		if (i++ < MAXMODULES)
			continue;
		else
			break;
	}

	lua_close (L);

	return 0;
}
Ejemplo n.º 20
0
/*
 * init: do some sanity checks
 * open resource database 
 * set up bitmap 
 */
static int f_init (union PartitionData **data, 
		   Partent partent, Device *dev)
{
    struct part_ftree_opts *options = NULL;
    struct stat buf;
    int rc, val, size, i;
    char resfilename[MAXPATHLEN];
    long filecount;
    Bitv freemap;
    struct i_header header, nullheader;

    options = (struct part_ftree_opts *)malloc(sizeof(union PartitionData));
    if ( options == NULL ) {
	eprint("Out of memory\n");
	CODA_ASSERT(0);
    } else {
	*data = (union PartitionData *)options;
    }
    
    rc = stat(Partent_dir(partent), &buf);
    if ( rc == 0 ) {
	*dev = buf.st_dev;
    } else {
	eprint("Error in init of partition %s:%s", 
	       Partent_host(partent), Partent_dir(partent));
	perror("");
	CODA_ASSERT(0);
    }
    
    if ( access(Partent_dir(partent), R_OK | W_OK) != 0 ) {
	eprint("Cannot access %s\n", Partent_dir(partent));
	perror("");
	CODA_ASSERT(0);
    }

    rc = Partent_intopt(partent, "depth", &val);
    if (rc != 0) {
	eprint("Invalid depth option in %s:%s\n",
	       Partent_host(partent), Partent_dir(partent));
	CODA_ASSERT(0);
    }
    options->depth = val;

    rc = Partent_intopt(partent, "width", &val);
    if (rc != 0) {
	eprint("Invalid width option in %s:%s\n",
	       Partent_host(partent), Partent_dir(partent));
	CODA_ASSERT(0);
    }
    options->width = val;

    i=0;
    do {
	i++;
    } while ( (1<<i) != options->width &&  i<20 );

    if ( i != 10) {
	options->logwidth = i;
    } else {
	eprint("Width should be a power of 2 smaller than 2^20");
	CODA_ASSERT(0);
    }

    options->next = 0;
    
    strcpy(resfilename, Partent_dir(partent));
    strcat(resfilename, "/");
    strcat(resfilename, RESOURCEDB);

    rc = stat(resfilename, &buf);
    if ( rc != 0 || !(buf.st_mode & S_IFREG) ) {
	dev = NULL;
	eprint("Error in init of partition %s:%s: no resource database.", 
	       Partent_host(partent), Partent_dir(partent));
	perror("");
	CODA_ASSERT(0);
    }
    
    /* open the resource data file */
    options->resource = open(resfilename, O_RDWR);
    if ( options->resource == -1 ) {
	dev = NULL;
	eprint("Error opening resource file!\n");
	perror("");
	CODA_ASSERT(0);
    }

    /* set up a bitmap */
    for (filecount = 1, i = 0; i < options->depth; i++)
	filecount *= options->width;

    freemap = Bitv_new(filecount);
    /*    Bitv_print(freemap, stdout); */
    options->freebm = freemap;
    if ( !options->freebm ) {
	eprint("Cannot setup free bitmap for %s.\n", Partent_dir(partent));
	CODA_ASSERT(0);
    }

    /* mark bits with resource records */
    size = sizeof(struct i_header);
    memset(&nullheader, 0, size);
    i = 0; 
    while ( read(options->resource, &header, size) == size) {
	if ( memcmp(&header, &nullheader, size) != 0 ) {
	    Bitv_set(options->freebm, i);
	}
	i++;
    }
    options->freebm = freemap;
    /* Bitv_print(freemap, stdout); */

    /* done: leave message in the log */
    printf("Partition %s: inodes in use: %d, total: %ld.\n",
	    Partent_dir(partent), Bitv_count(options->freebm), filecount); 

    return 0;
}
Ejemplo n.º 21
0
/*
 - main - do the simple case, hand off to regress() for regression
 */
int
main(int argc, char *argv[])

{
	regex_t re;
#	define	NS	10
	regmatch_t subs[NS];
	char erbuf[100];
	int err;
	size_t len;
	int c;
	int errflg = 0;
	register int i;
	extern int optind;
	extern char *optarg;

	progname = argv[0];

	while ((c = getopt(argc, argv, "c:E:e:S:x")) != -1)
		switch (c) {
		case 'c':	/* compile options */
			copts = options('c', optarg);
			break;
		case 'E':	/* end offset */
			endoff = (regoff_t)atoi(optarg);
			break;
		case 'e':	/* execute options */
			eopts = options('e', optarg);
			break;
		case 'S':	/* start offset */
			startoff = (regoff_t)atoi(optarg);
			break;
		case 'x':	/* Debugging. */
			debug++;
			break;
		case '?':
		default:
			errflg++;
			break;
		}
	if (errflg) {
		fprintf(stderr, "usage: %s ", progname);
		fprintf(stderr, "[-x] [-c copt] [-E endoff] [-e eopt] [-S startoff] [re]\n");
		exit(2);
	}

	if (optind >= argc) {
		regress(stdin);
		exit(status);
	}

	err = regcomp(&re, argv[optind++], copts);
	if (err) {
		len = regerror(err, &re, erbuf, sizeof(erbuf));
		fprintf(stderr, "error %s, %zu/%zu `%s'\n",
			eprint(err), len, sizeof(erbuf), erbuf);
		exit(status);
	}
	regprint(&re, stdout);	

	if (optind >= argc) {
		regfree(&re);
		exit(status);
	}

	if (eopts&REG_STARTEND) {
		subs[0].rm_so = startoff;
		subs[0].rm_eo = strlen(argv[optind]) - endoff;
	}
	err = regexec(&re, argv[optind], (size_t)NS, subs, eopts);
	if (err) {
		len = regerror(err, &re, erbuf, sizeof(erbuf));
		fprintf(stderr, "error %s, %zu/%zu `%s'\n",
			eprint(err), len, sizeof(erbuf), erbuf);
		exit(status);
	}
	if (!(copts&REG_NOSUB)) {
		len = (size_t)(subs[0].rm_eo - subs[0].rm_so);
		if (subs[0].rm_so != -1) {
			if (len != 0)
				printf("match `%.*s'\n", (int)len,
					argv[optind] + subs[0].rm_so);
			else
				printf("match `'@%.1s\n",
					argv[optind] + subs[0].rm_so);
		}
		for (i = 1; i < NS; i++)
			if (subs[i].rm_so != -1)
				printf("(%d) `%.*s'\n", i,
					(int)(subs[i].rm_eo - subs[i].rm_so),
					argv[optind] + subs[i].rm_so);
	}
	exit(status);
}
Ejemplo n.º 22
0
int main(int argc, char **argv)
{
#define nsrc (argc - 2)
	char *dest;

	progname = strrchr(*argv, '/');
	if(progname)
		progname++;
	else
		progname = *argv;

	setvbuf(stdout, NULL, _IONBF, 0);

	if(!strcmp(progname, "pcp"))
		i_am_cp = 1;
	else if(!strcmp(progname, "pmv"))
		i_am_cp = 0;
	else{
		eprint("must be invoked as ``pcp'' or ``pmv''");
		return 1;
	}

	if(argc == 1)
		usage();

	if(setvbuf(stdout, NULL, _IONBF, 0)){
		perrorf("unbuffer stdout");
		return 1;
	}
	dest = argv[argc-1];

	if(nsrc == 1)
		return copy(dest, argv[1]);
	else{
		/* either way, dest must be a dir */
		struct stat st;

		if(stat(dest, &st)){
			perrorf("stat: `%s'", dest);
			return 1;
		}else if(!S_ISDIR(st.st_mode)){
			eprintf("`%s': not a dir", dest);
			return 1;
		}

		if(nsrc)
			return dircopy(dest, argv + 1, nsrc);
		else{
			char fname[PATH_MAX];

			while(fgets(fname, PATH_MAX, stdin)){
				char *nl = strchr(fname, '\n');
				if(nl)
					*nl = '\0';
				else
					eprintf("warning: full line not read for `%s'\n", fname);

				if(copy(dest, fname))
					return 1;
			}
			return 0;
		}
	}
}
Ejemplo n.º 23
0
/* uerror -- print a unix error, our version of perror */
extern void uerror(char *s) {
	if (s != NULL)
		eprint("%s: %s\n", s, strerror(errno));
	else
		eprint("%s\n", strerror(errno));
}
Ejemplo n.º 24
0
/* perform write command */
static int procwrite(const char *path, int tnum, int rnum, int width, int64_t limsiz,
                     int omode, bool rnd){
  iprintf("<Writing Test>\n  seed=%u  path=%s  tnum=%d  rnum=%d  width=%d  limsiz=%lld"
          "  omode=%d  rnd=%d\n\n",
          g_randseed, path, tnum, rnum, width, (long long)limsiz, omode, rnd);
  bool err = false;
  double stime = tctime();
  TCFDB *fdb = tcfdbnew();
  if(g_dbgfd >= 0) tcfdbsetdbgfd(fdb, g_dbgfd);
  if(!tcfdbsetmutex(fdb)){
    eprint(fdb, __LINE__, "tcfdbsetmutex");
    err = true;
  }
  if(!tcfdbtune(fdb, width, limsiz)){
    eprint(fdb, __LINE__, "tcfdbtune");
    err = true;
  }
  if(!tcfdbopen(fdb, path, FDBOWRITER | FDBOCREAT | FDBOTRUNC | omode)){
    eprint(fdb, __LINE__, "tcfdbopen");
    err = true;
  }
  TARGWRITE targs[tnum];
  pthread_t threads[tnum];
  if(tnum == 1){
    targs[0].fdb = fdb;
    targs[0].rnum = rnum;
    targs[0].rnd = rnd;
    targs[0].id = 0;
    if(threadwrite(targs) != NULL) err = true;
  } else {
    for(int i = 0; i < tnum; i++){
      targs[i].fdb = fdb;
      targs[i].rnum = rnum;
      targs[i].rnd = rnd;
      targs[i].id = i;
      if(pthread_create(threads + i, NULL, threadwrite, targs + i) != 0){
        eprint(fdb, __LINE__, "pthread_create");
        targs[i].id = -1;
        err = true;
      }
    }
    for(int i = 0; i < tnum; i++){
      if(targs[i].id == -1) continue;
      void *rv;
      if(pthread_join(threads[i], &rv) != 0){
        eprint(fdb, __LINE__, "pthread_join");
        err = true;
      } else if(rv){
        err = true;
      }
    }
  }
  iprintf("record number: %llu\n", (unsigned long long)tcfdbrnum(fdb));
  iprintf("size: %llu\n", (unsigned long long)tcfdbfsiz(fdb));
  mprint(fdb);
  sysprint();
  if(!tcfdbclose(fdb)){
    eprint(fdb, __LINE__, "tcfdbclose");
    err = true;
  }
  tcfdbdel(fdb);
  iprintf("time: %.3f\n", tctime() - stime);
  iprintf("%s\n\n", err ? "error" : "ok");
  return err ? 1 : 0;
}
Ejemplo n.º 25
0
int main(int argc,char **argv)
{
 char *hostname, *x;
 int c, s, t;
 unsigned int u;
 unsigned int cpid = 0;

 opterr = 0;

 while ((c = getopt(argc, argv, "dDoOC:k:c:")) != -1)
  switch (c) {
	case 'c':
	 limit = atoi(optarg);
	 if (limit == 0) usage();
	 break;
	case 'd': flagdelay = 1; break;
	case 'D': flagdelay = 0; break;
	case 'O': flagkillopts = 1; break;
	case 'o': flagkillopts = 0; break;
	case 'C': cacheprogram = 1; break;
	case 'k':
	 autokill = atoi(optarg);
	 if (autokill == 0) usage();
	 break;
	default: abort();
  }
 argc -= optind;
 argv += optind;

 hostname = *argv++;
 if (!hostname) usage();

 x = *argv++;
 if (!x) usage();
 u = 0;
 u = atoi(x);
 if (u != 0) localport = u;
 else usage();

 if (!*argv) usage();

 sig_block(sig_child);
 sig_catch(sig_child,sigchld);
 sig_catch(sig_term,sigterm);
 sig_catch(sig_int,sigint);
 sig_ignore(sig_pipe);

 inet_aton(hostname, (struct in_addr *) &localip);

 if (autokill != 0) pt = ptable_init(limit);

 s = socket_tcp();
 if (s == -1) die(111, "unable to create socket");
 if (socket_bind4_reuse(s,localip,localport) == -1) die(111, "unable to bind");
 if (socket_local4(s,localip,&localport) == -1) die(111, "unable to get local address");
 if (socket_listen(s,20) == -1) die(111, "unable to listen");
 ndelay_off(s);

 fprintf(stderr, "bind: %s:%d\n", hostname, localport);

 close(0);
 close(1);
 printstatus();

 if (cacheprogram) {

   FILE *fp1;
   int fp2;
   char path[1024];
   ssize_t n;

   fp1 = popen(*argv, "r");
   if (fp1 == NULL) {
     fprintf(stderr, "Failed to run command\n");
     exit(1);
   }

   fp2 = open("/var/tmp/tcpd.cache", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
   if (fp2 == -1) {
     fprintf(stderr, "Can't open cache file\n");
     exit(1);
   }

   while ((n = fgets(path, sizeof(path)-1, fp1)) != NULL) {
     if (write(fp2, path, n) == n) {
       fprintf(stderr, "Error occured while creating cache\n");
       exit(1);
     }
   }

   /* close */
   pclose(fp1);
   close(fp2);

   // read cache file into memory
   FILE *f = fopen("/var/tmp/tcpd.cache", "rb");
   fseek(f, 0, SEEK_END);
   cachesize = ftell(f);
   fseek(f, 0, SEEK_SET);  //same as rewind(f);
   cache = malloc(cachesize + 1);
   n = fread(cache, cachesize, 1, f);
   fclose(f);
   cache[cachesize] = 0;
 }

 for (;;) {
   while (numchildren >= limit) {
    if (autokill != 0) ptable_autokill(pt, limit, autokill);
    sig_pause();
   }

   sig_unblock(sig_child);
   t = socket_accept4(s,remoteip,&remoteport);
   sig_block(sig_child);

   if (t == -1) continue;
   ++numchildren; printstatus();
   fprintf(stderr, "inbound connection from %d.%d.%d.%d:%d\n", (unsigned char) remoteip[0], (unsigned char) remoteip[1], (unsigned char) remoteip[2], (unsigned char) remoteip[3], remoteport);

   if (autokill != 0) ptable_autokill(pt,limit,autokill);

   cpid = fork();
   switch(cpid) {
	case 0:
	 close(s);
	 if(flagkillopts) socket_ipoptionskill(t);
	 if(!flagdelay) socket_tcpnodelay(t);
	 if((fd_move(0,t) == -1) || (fd_copy(1,0) == -1)) die(111,"unable to setup descriptors");
	 sig_uncatch(sig_child);
	 sig_unblock(sig_child);
	 sig_uncatch(sig_term);
	 sig_uncatch(sig_int);
	 sig_uncatch(sig_pipe);

	 if (cacheprogram) {
	   printf("%s", cache);
	   close(t);
	   exit(0);
	 } else {
	   if(execve(*argv,argv,NULL) == 0) {
	     close(t);
	     exit(0);
	   } else {
	     die(111, "unable to run argv");
	   }
	 }
	 break;
	case -1:
	 // unable to fork
	 eprint(P_WARN,"unable to fork");
	 --numchildren; printstatus();
	 break;
	default:
	 fprintf(stderr, "fork: child pid %d\n", cpid);
	 if (autokill != 0) ptable_set(pt, limit, cpid, time(NULL));
	 break;
   }
   close(t);
 }
}
Ejemplo n.º 26
0
/* perform wicked command */
static int procwicked(const char *path, int tnum, int rnum, int omode, bool nc){
  iprintf("<Writing Test>\n  seed=%u  path=%s  tnum=%d  rnum=%d  omode=%d  nc=%d\n\n",
          g_randseed, path, tnum, rnum, omode, nc);
  bool err = false;
  double stime = tctime();
  TCFDB *fdb = tcfdbnew();
  if(g_dbgfd >= 0) tcfdbsetdbgfd(fdb, g_dbgfd);
  if(!tcfdbsetmutex(fdb)){
    eprint(fdb, __LINE__, "tcfdbsetmutex");
    err = true;
  }
  if(!tcfdbtune(fdb, RECBUFSIZ * 2, EXHEADSIZ + (RECBUFSIZ * 2 + sizeof(int)) * rnum * tnum)){
    eprint(fdb, __LINE__, "tcfdbtune");
    err = true;
  }
  if(!tcfdbopen(fdb, path, FDBOWRITER | FDBOCREAT | FDBOTRUNC | omode)){
    eprint(fdb, __LINE__, "tcfdbopen");
    err = true;
  }
  if(!tcfdbiterinit(fdb)){
    eprint(fdb, __LINE__, "tcfdbiterinit");
    err = true;
  }
  TARGWICKED targs[tnum];
  pthread_t threads[tnum];
  TCMAP *map = tcmapnew();
  if(tnum == 1){
    targs[0].fdb = fdb;
    targs[0].rnum = rnum;
    targs[0].nc = nc;
    targs[0].id = 0;
    targs[0].map = map;
    if(threadwicked(targs) != NULL) err = true;
  } else {
    for(int i = 0; i < tnum; i++){
      targs[i].fdb = fdb;
      targs[i].rnum = rnum;
      targs[i].nc = nc;
      targs[i].id = i;
      targs[i].map = map;
      if(pthread_create(threads + i, NULL, threadwicked, targs + i) != 0){
        eprint(fdb, __LINE__, "pthread_create");
        targs[i].id = -1;
        err = true;
      }
    }
    for(int i = 0; i < tnum; i++){
      if(targs[i].id == -1) continue;
      void *rv;
      if(pthread_join(threads[i], &rv) != 0){
        eprint(fdb, __LINE__, "pthread_join");
        err = true;
      } else if(rv){
        err = true;
      }
    }
  }
  if(!nc){
    if(!tcfdbsync(fdb)){
      eprint(fdb, __LINE__, "tcfdbsync");
      err = true;
    }
    if(tcfdbrnum(fdb) != tcmaprnum(map)){
      eprint(fdb, __LINE__, "(validation)");
      err = true;
    }
    int end = rnum * tnum;
    for(int i = 1; i <= end && !err; i++){
      char kbuf[RECBUFSIZ];
      int ksiz = sprintf(kbuf, "%d", i);
      int vsiz;
      const char *vbuf = tcmapget(map, kbuf, ksiz, &vsiz);
      int rsiz;
      char *rbuf = tcfdbget2(fdb, kbuf, ksiz, &rsiz);
      if(vbuf){
        iputchar('.');
        if(vsiz > tcfdbwidth(fdb)) vsiz = tcfdbwidth(fdb);
        if(!rbuf){
          eprint(fdb, __LINE__, "tcfdbget");
          err = true;
        } else if(rsiz != vsiz || memcmp(rbuf, vbuf, rsiz)){
          eprint(fdb, __LINE__, "(validation)");
          err = true;
        }
      } else {
        iputchar('*');
        if(rbuf || tcfdbecode(fdb) != TCENOREC){
          eprint(fdb, __LINE__, "(validation)");
          err = true;
        }
      }
      tcfree(rbuf);
      if(i % 50 == 0) iprintf(" (%08d)\n", i);
    }
    if(rnum % 50 > 0) iprintf(" (%08d)\n", rnum);
  }
  tcmapdel(map);
  iprintf("record number: %llu\n", (unsigned long long)tcfdbrnum(fdb));
  iprintf("size: %llu\n", (unsigned long long)tcfdbfsiz(fdb));
  mprint(fdb);
  sysprint();
  if(!tcfdbclose(fdb)){
    eprint(fdb, __LINE__, "tcfdbclose");
    err = true;
  }
  tcfdbdel(fdb);
  iprintf("time: %.3f\n", tctime() - stime);
  iprintf("%s\n\n", err ? "error" : "ok");
  return err ? 1 : 0;
}
Ejemplo n.º 27
0
// -----------------------------------------------------------------------
struct cchar_unit_proto_t * cchar_term_create(struct cfg_arg_t *args)
{
	char *type = NULL;
	int port;
	int res;

	struct cchar_unit_term_t *unit = calloc(1, sizeof(struct cchar_unit_term_t));
	if (!unit) {
		goto fail;
	}

	res = cfg_args_decode(args, "s", &type);
	if (res != E_OK) {
		gerr = res;
		goto fail;
	}

	if (!strcasecmp(type, "tcp")) {
		res = cfg_args_decode(args, "si", &type, &port);
		if (res != E_OK) {
			gerr = res;
			goto fail;
		}
		unit->term = term_open_tcp(port, 100);
		if (!unit->term) {
			gerr = E_TERM;
			goto fail;
		}
	} else if (!strcasecmp(type, "console")) {
		if (em400_console == CONSOLE_DEBUGGER) {
			gerr = E_TERM_CONSOLE_DEBUG;
			goto fail;
		} else if (em400_console == CONSOLE_TERMINAL) {
			gerr = E_TERM_CONSOLE_TERM;
			goto fail;
		} else {
			em400_console = CONSOLE_TERMINAL;
			unit->term = term_open_console();
			if (!unit->term) {
				gerr = E_TERM;
				goto fail;
			}
		}
		printf("Console connected as system terminal.\n");
	} else {
		gerr = E_TERM_UNKNOWN;
		goto fail;
	}

	unit->buf = malloc(TERM_BUF_LEN);
	if (!unit->buf) {
		goto fail;
	}

	eprint("      Terminal (%s), port: %i\n", type, port);

	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	pthread_mutex_init(&unit->buf_mutex, &attr);

	res = pthread_create(&unit->worker, NULL, cchar_term_worker, (void *)unit);
	if (res != 0) {
		goto fail;
	}

	return (struct cchar_unit_proto_t *) unit;

fail:
	cchar_term_shutdown((struct cchar_unit_proto_t*) unit);
	return NULL;
}