Example #1
0
void  writenodetable(Pfloat *x)
/*
**---------------------------------------------------------------
**   Input:   x = pointer to node results for current time
**   Output:  none                                  
**   Purpose: writes node results for current time to report file            
**---------------------------------------------------------------
*/
{
   int i,j;
   char s[MAXLINE+1],s1[16];
   float y[MAXVAR];

   /* Write table header */
   writeheader(NODEHDR,0);

   /* For each node: */
   for (i=1; i<=Nnodes; i++)
   {

      /* Place results for each node variable in y */
      y[ELEV] = Node[i].El*Ucf[ELEV];
      for (j=DEMAND; j<=QUALITY; j++) y[j] = *((x[j-DEMAND])+i);

      /* Check if node gets reported on */
      if ((Nodeflag == 1 || Node[i].Rpt) && checklimits(y,ELEV,QUALITY))
      {

         /* Check if new page needed */
         if (LineNum == (long)PageSize) writeheader(NODEHDR,1);

         /* Add node ID and each reported field to string s */
         sprintf(s,"%-15s",Node[i].ID);
         for (j=ELEV; j<=QUALITY; j++)
         {
            if (Field[j].Enabled == TRUE)
            {

/*** Updated 6/24/02 ***/
               if (fabs(y[j]) > 1.e6) sprintf(s1, "%10.2e", y[j]);
               else                   sprintf(s1, "%10.*f", Field[j].Precision, y[j]);
/*** End of update ***/

               strcat(s, s1);
            }
         }

         /* Note if node is a reservoir/tank */
         if (i > Njuncs)
         {
            strcat(s, "  ");
            strcat(s, NodeTxt[getnodetype(i)]);
         }

         /* Write results for node */
         writeline(s);
      }
   }
   writeline(" ");
}
static void archivefile(const char *path)
{
	struct fileblock *start, *cur;
	struct fileblock **prev = &start;
	int fd, r;
	unsigned size = 0;
	struct stat s;

	/* buffer the file */
	fd = xopen(path, O_RDONLY);
	do {
		cur = xzalloc(sizeof(*cur));
		*prev = cur;
		prev = &cur->next;
		r = full_read(fd, cur->data, TAR_BLOCK_SIZE);
		if (r > 0)
			size += r;
	} while (r == TAR_BLOCK_SIZE);

	/* write archive header */
	fstat(fd, &s);
	close(fd);
	s.st_size = size;
	writeheader(path, &s, '0');

	/* dump file contents */
	for (cur = start; (int)size > 0; size -= TAR_BLOCK_SIZE) {
		xwrite(STDOUT_FILENO, cur->data, TAR_BLOCK_SIZE);
		start = cur;
		cur = cur->next;
		free(start);
	}
}
Example #3
0
static
void
docreate(const char *file, const char *sizespec, int doforce)
{
    int fd;
    off_t size;

    if (!doforce) {
        fd = open(file, O_RDONLY);
        if (fd >= 0) {
            fprintf(stderr, "disk161: %s: %s\n", file,
                    strerror(EEXIST));
            exit(1);
        }
    }

    fd = doopen(file, O_RDWR|O_CREAT|O_TRUNC, 0664);
    doflock(file, fd, LOCK_EX);
    size = getsize(sizespec);
    checksize(size);
    dotruncate(file, fd, HEADERSIZE + size);
    writeheader(file, fd);
    doflock(file, fd, LOCK_UN);
    close(fd);
}
Example #4
0
File: tabdump.c Project: PADL/krb5
/* Set up state structure for the iterator. */
static krb5_error_code
setup_args(struct rec_args *args, struct tdtype *tdtype,
             struct tdopts *opts)
{
    FILE *f = NULL;
    const char *rectype = NULL;
    struct rechandle *rh;

    args->tdtype = tdtype;
    args->opts = opts;
    if (opts->fname != NULL && strcmp(opts->fname, "-") != 0) {
        f = fopen(opts->fname, "w");
        if (f == NULL) {
            com_err(progname, errno, _("opening %s for writing"),
                    opts->fname);
            return errno;
        }
        args->f = f;
    } else {
        f = stdout;
        args->f = NULL;
    }
    if (opts->writerectype)
        rectype = tdtype->rectype;
    if (opts->csv)
        rh = rechandle_csv(f, rectype);
    else
        rh = rechandle_tabsep(f, rectype);
    if (rh == NULL)
        return ENOMEM;
    args->rh = rh;
    if (!opts->omitheader && writeheader(rh, tdtype->fieldnames) < 0)
        return errno;
    return 0;
}
Example #5
0
/*
 * Collect up the data into tape record sized buffers and output them.
 */
void
ufs2_blksout(daddr_t *blkp, int frags, ino_t ino)
{
	daddr_t *bp;
	int i, j, count, blks, tbperdb;

	blks = howmany(frags * sblock->fs_fsize, TP_BSIZE);
	tbperdb = sblock->fs_bsize >> tp_bshift;
	for (i = 0; i < blks; i += TP_NINDIR) {
		if (i + TP_NINDIR > blks)
			count = blks;
		else
			count = i + TP_NINDIR;
		for (j = i; j < count; j++)
			if (blkp[j / tbperdb] != 0)
				spcl.c_addr[j - i] = 1;
			else
				spcl.c_addr[j - i] = 0;
		spcl.c_count = count - i;
		writeheader(ino);
		bp = &blkp[i / tbperdb];
		for (j = i; j < count; j += tbperdb, bp++)
			if (*bp != 0) {
				if (j + tbperdb <= count)
					dumpblock(*bp, (int)sblock->fs_bsize);
				else
					dumpblock(*bp, (count - j) * TP_BSIZE);
			}
		spcl.c_type = TS_ADDR;
	}
}
Example #6
0
void
Write_Displ(  int* pid,
              int* stepno,
              int* nshg,
              int* numVars,
              double* array1 ) { //TO BE UPDATED FOR SYNCIO


    char fname[255];
    char rfile[60];
    int irstou;
    int magic_number = 362436;
    int* mptr = &magic_number;
    time_t timenow = time ( &timenow);
    double version=0.0;
    int isize, nitems;
    int iarray[10];

    sprintf(rfile,"restart.%d.%d",*stepno,*pid+1);
    openfile(rfile,"append", &irstou);

    isize = (*nshg)*(*numVars);
    nitems = 3;
    iarray[ 0 ] = (*nshg);
    iarray[ 1 ] = (*numVars);
    iarray[ 2 ] = (*stepno);
    writeheader( &irstou, "displacement", (void*)iarray, &nitems, &isize, "double", phasta_iotype );
    writedatablock( &irstou, "displacement", (void*)(array1), &isize, "double", phasta_iotype );

    closefile( &irstou, "append" );
}
Example #7
0
int archivefile(const char *path, int destfd)
{
	struct fileblock *start, *cur;
	struct fileblock **prev = &start;
	int fd, r, size = 0;
	struct stat s;

	/* buffer and stat the file */
	fd = open(path, O_RDONLY);
	fstat(fd, &s);

	do {
		cur = calloc(1, sizeof(struct fileblock));
		*prev = cur;
		prev = &cur->next;
		r = read(fd, cur->data, 512);
		if (r > 0)
			size += r;
	} while (r == 512);

	close(fd);

	/* write archive header */
	writeheader(destfd, path, s.st_mode, s.st_uid,
		    s.st_gid, size, s.st_mtime, 0);

	/* dump file contents */
	for (cur = start; size > 0; size -= 512) {
		write(destfd, cur->data, 512);
		start = cur;
		cur = cur->next;
		free(start);
	}
}
Example #8
0
/*
 * Dump a map to the tape.
 */
void
dumpmap(const char *map, int type, ufs1_ino_t ino)
{
	int i;
	const char *cp;

	spcl.c_type = type;
	spcl.c_count = howmany(mapsize * sizeof(char), TP_BSIZE);
	writeheader(ino);
	for (i = 0, cp = map; i < spcl.c_count; i++, cp += TP_BSIZE)
		writerec(cp, 0);
}
Example #9
0
void rjMcMC1DSampler::writeresults(FILE* fp)
{
	writeheader(fp);
	writemodel(fp, mHighestLikelihood);
	writemodel(fp, mLowestMisfit);
	pmap.writedata(fp);
	nmap.writedata(fp);
	for (size_t ci = 0; ci < nchains; ci++){
		mChainInfo[ci].writeconvergencedata(ci,fp);
		mChainInfo[ci].writemodelchain_binary(ci,fp);
	}
}
Example #10
0
/*
 * Collect up the data into tape record sized buffers and output them.
 */
static void
ufs2_blksout(union dinode *dp, ufs2_daddr_t *blkp, int frags, ino_t ino,
	int last)
{
	ufs2_daddr_t *bp;
	int i, j, count, resid, blks, tbperdb, added;
	static int writingextdata = 0;

	/*
	 * Calculate the number of TP_BSIZE blocks to be dumped.
	 * For filesystems with a fragment size bigger than TP_BSIZE,
	 * only part of the final fragment may need to be dumped.
	 */
	blks = howmany(frags * sblock->fs_fsize, TP_BSIZE);
	if (last) {
		resid = howmany(fragoff(sblock, dp->dp2.di_size), TP_BSIZE);
		if (resid > 0)
			blks -= howmany(sblock->fs_fsize, TP_BSIZE) - resid;
	}
	tbperdb = sblock->fs_bsize >> tp_bshift;
	for (i = 0; i < blks; i += TP_NINDIR) {
		if (i + TP_NINDIR > blks)
			count = blks;
		else
			count = i + TP_NINDIR;
		for (j = i; j < count; j++)
			if (blkp[j / tbperdb] != 0)
				spcl.c_addr[j - i] = 1;
			else
				spcl.c_addr[j - i] = 0;
		spcl.c_count = count - i;
		if (last && count == blks && !writingextdata)
			added = appendextdata(dp);
		writeheader(ino);
		bp = &blkp[i / tbperdb];
		for (j = i; j < count; j += tbperdb, bp++)
			if (*bp != 0) {
				if (j + tbperdb <= count)
					dumpblock(*bp, (int)sblock->fs_bsize);
				else
					dumpblock(*bp, (count - j) * TP_BSIZE);
			}
		spcl.c_type = TS_ADDR;
		spcl.c_count = 0;
		if (last && count == blks && !writingextdata) {
			writingextdata = 1;
			writeextdata(dp, ino, added);
			writingextdata = 0;
		}
	}
}
Example #11
0
void  writeenergy()
/*
**-------------------------------------------------------------
**   Input:   none                                               
**   Output:  none                                               
**   Purpose: writes energy usage report to report file          
**-------------------------------------------------------------
*/
{
    int   j;
    float csum;
    char  s[MAXLINE+1];
    if (Npumps == 0) return;
    writeline(" ");
    writeheader(ENERHDR,0);
    csum = 0.0;
    for (j=1; j<=Npumps; j++)
    {
        csum += Pump[j].Energy[5];
        if (LineNum == (long)PageSize) writeheader(ENERHDR,1);
        sprintf(s,"%-8s  %6.2f %6.2f %9.2f %9.2f %9.2f %9.2f",
          Link[Pump[j].Link].ID,Pump[j].Energy[0],Pump[j].Energy[1],
          Pump[j].Energy[2],Pump[j].Energy[3],Pump[j].Energy[4],
          Pump[j].Energy[5]);
        writeline(s);
    }
    fillstr(s,'-',63);
    writeline(s);

/*** Updated 6/24/02 ***/
    sprintf(s,FMT74,"",Emax*Dcost);
    writeline(s);
    sprintf(s,FMT75,"",csum+Emax*Dcost);
/*** End of update ***/

    writeline(s);
    writeline(" ");
}                       /* End of writeenergy */
Example #12
0
static int
writedump(FILE *f)
{
	int rc;

	rc = writedata(f);
	if (rc != 0)
		return rc;

	rc = writeheader(f);
	if (rc != 0)
		return rc;

	return 0;
}
Example #13
0
static
void
disk_open(struct disk_data *dd, const char *filename, uint32_t configsectors)
{
    int create = 0;
    struct stat st;

    dd->dd_fd = open(filename, O_RDWR);
    if (dd->dd_fd<0 && errno==ENOENT) {
        create = 1;
        dd->dd_fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0664);
    }
    if (dd->dd_fd<0) {
        msg("disk: slot %d: %s: %s",
            dd->dd_slot, filename, strerror(errno));
        die();
    }
    disk_lock(dd, filename);
    if (create) {
        writeheader(dd, filename, configsectors);
    }
    else {
        readheader(dd, filename);
    }

    if (fstat(dd->dd_fd, &st) == -1) {
        msg("disk: slot %d: %s: fstat: %s",
            dd->dd_slot, filename, strerror(errno));
        die();
    }
    if (st.st_size < HEADERSIZE) {
        msg("disk: slot %d: %s: No header block",
            dd->dd_slot, filename);
        die();
    }
    st.st_size -= HEADERSIZE;
    if (st.st_size > 0xffffffff) {
        msg("disk: slot %d: %s: Image too large; using first 4G",
            dd->dd_slot, filename);
        dd->dd_totsectors = 0x100000000ULL / SECTSIZE;
    }
    else {
        dd->dd_totsectors = st.st_size / SECTSIZE;
    }
}
Example #14
0
int
main()
{
	copyright = ecalloc(1, BUFSIZ);
	strbuf = ecalloc(1, BUFSIZ);
	firstglyph = ecalloc(1, sizeof(Glyph)); /* TODO dummies use memory */
	lastglyph = firstglyph;

	while (!feof(stdin)) {
		fgets(strbuf, BUFSIZ, stdin);
		parse(strbuf);
	}

	writeheader();
	writemap();
	writeglyphs();

	/* TODO does one free buffers before return? */
	return 0;
}
Example #15
0
int main(int argc, char *argv[])
{
	DIR *d;
	struct dirent *de;
	struct stat s;

	chdir("/proc");
	archivefile("meminfo", 1);
	archivefile("version", 1);

	d = opendir(".");
	while ((de = readdir(d)))
		if (de->d_name[0] >= '0' && de->d_name[0] <= '9') {
			stat (de->d_name, &s);
			writeheader(1, de->d_name, 0555, s.st_uid,
				    s.st_gid, 0, s.st_mtime, 5);
			archivejoin(de->d_name, "smaps", 1);
			archivejoin(de->d_name, "cmdline", 1);
			archivejoin(de->d_name, "stat", 1);
		}

	return 0;
}
Example #16
0
void
Write_PhAvg(  int* pid,
              char* filemode,
              char* fieldtag,
              int* tagsize,
              int* iphase,
              void* array,
              char* arraytype,
              int* nshg,
              int* numvars,
              int* stepno) {

    char rfile[32];
    // assuming restart_phase_avg_<sn>.<iphase>.<pid+1>
    sprintf(rfile,"restart_phase_avg_%d.%d.%d",*stepno,*iphase,*pid+1);

    char *fieldlabel = (char *)malloc((*tagsize+1)*sizeof(char));
    strncpy(fieldlabel, fieldtag, *tagsize);
    fieldlabel[*tagsize] = '\0';

    int irstou;
    int isize, nitems;
    int iarray[10];

    char fmode[10];
    if(!strncmp(filemode,"w",1))
      strcpy(fmode,"write");
    else // default is append
      strcpy(fmode,"append");

    char datatype[10];
    if(!strncmp(arraytype,"i",1))
      strcpy(datatype,"int");
    else // default is double
      strcpy(datatype,"double");

    openfile(rfile, fmode, &irstou);

    if(!strcmp(fmode,"write")) {
      // may be create a routine for 'top' portion under write mode
      int magic_number = 362436;
      int* mptr = &magic_number;
      time_t timenow = time ( &timenow);
      double version=0.0;

      /* writing the top ascii header for the restart file */

      writestring( &irstou,"# PHASTA Input File Version 2.0\n");
      writestring( &irstou,
                    "# format \"keyphrase : sizeofnextblock usual headers\"\n");

      char fname[255];
      bzero( (void*)fname, 255 );
      sprintf(fname,"# Output generated by phasta version (NOT YET CURRENT): %lf \n", version);
      writestring( &irstou, fname );

      bzero( (void*)fname, 255 );
      gethostname(fname,255);
      writestring( &irstou,"# This result was produced on: ");
      writestring( &irstou, fname );
      writestring( &irstou,"\n");

      bzero( (void*)fname, 255 );
      sprintf(fname,"# %s\n", ctime( &timenow ));
      writestring( &irstou, fname );

      isize = 1;
      nitems = 1;
      iarray[ 0 ] = 1;
      writeheader( &irstou, "byteorder magic number ",
                    (void*)iarray, &nitems, &isize, "integer", phasta_iotype );
      writedatablock( &irstou, "byteorder magic number ",
                       (void*)mptr, &isize, "integer", phasta_iotype );
    }

    isize = (*nshg)*(*numvars);
    nitems = 3; // assuming field will write 3 items in iarray
    iarray[ 0 ] = (*nshg);
    iarray[ 1 ] = (*numvars);
    iarray[ 2 ] = (*stepno);
    writeheader( &irstou, fieldlabel, (void*)iarray, &nitems, &isize, datatype, phasta_iotype );
    writedatablock( &irstou, fieldlabel, array, &isize, datatype, phasta_iotype );

    closefile( &irstou, fmode);

    free(fieldlabel);
}
Example #17
0
void  writelinktable(Pfloat *x)
/*
**---------------------------------------------------------------
**   Input:   x = pointer to link results for current time
**   Output:  none                                  
**   Purpose: writes link results for current time to report file            
**---------------------------------------------------------------
*/
{
   int i,j,k;
   char s[MAXLINE+1],s1[16];
   float y[MAXVAR];

   /* Write table header */
   writeheader(LINKHDR,0);

   /* For each link: */
   for (i=1; i<=Nlinks; i++)
   {

      /* Place results for each link variable in y */
      y[LENGTH] = Link[i].Len*Ucf[LENGTH];
      y[DIAM] = Link[i].Diam*Ucf[DIAM];
      for (j=FLOW; j<=FRICTION; j++) y[j] = *((x[j-FLOW])+i);

      /* Check if link gets reported on */
      if ((Linkflag == 1 || Link[i].Rpt) && checklimits(y,DIAM,FRICTION))
      {

         /* Check if new page needed */
         if (LineNum == (long)PageSize) writeheader(LINKHDR,1);

         /* Add link ID and each reported field to string s */
         sprintf(s,"%-15s",Link[i].ID);
         for (j=LENGTH; j<=FRICTION; j++)
         {
            if (Field[j].Enabled == TRUE)
            {
               if (j == STATUS)
               {
                  if      (y[j] <= CLOSED) k = CLOSED;
                  else if (y[j] == ACTIVE) k = ACTIVE;
                  else                     k = OPEN;
                  sprintf(s1, "%10s", StatTxt[k]);
               }

/*** Updated 6/24/02 ***/
               else
               {
                  if (fabs(y[j]) > 1.e6) sprintf(s1, "%10.2e", y[j]);
                  else                   sprintf(s1, "%10.*f", Field[j].Precision, y[j]);
               }
/*** End of update ***/

               strcat(s, s1);
            }
         }

         /* Note if link is a pump or valve */
         if ( (j = Link[i].Type) > PIPE)
         {
            strcat(s, "  ");
            strcat(s, LinkTxt[j]);
         }

         /* Write results for link */
         writeline(s);
      }
   }
   writeline(" ");
}
Example #18
0
int
main(int argc, char *argv[])
{
	struct stat sb;
	ino_t ino;
	int dirty;
	union dinode *dp;
	struct fstab *dt;
	char *map, *mntpt;
	int ch, mode, mntflags;
	int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
	int just_estimate = 0;
	ino_t maxino;
	char *tmsg;

	spcl.c_date = _time_to_time64(time(NULL));

	tsize = 0;	/* Default later, based on 'c' option for cart tapes */
	dumpdates = _PATH_DUMPDATES;
	popenout = NULL;
	tape = NULL;
	temp = _PATH_DTMP;
	if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
		quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
	level = 0;
	rsync_friendly = 0;

	if (argc < 2)
		usage();

	obsolete(&argc, &argv);
	while ((ch = getopt(argc, argv,
	    "0123456789aB:b:C:cD:d:f:h:LnP:RrSs:T:uWw")) != -1)
		switch (ch) {
		/* dump level */
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			level = 10 * level + ch - '0';
			break;

		case 'a':		/* `auto-size', Write to EOM. */
			unlimited = 1;
			break;

		case 'B':		/* blocks per output file */
			blocksperfile = numarg("number of blocks per file",
			    1L, 0L);
			break;

		case 'b':		/* blocks per tape write */
			ntrec = numarg("number of blocks per write",
			    1L, 1000L);
			break;

		case 'C':
			cachesize = numarg("cachesize", 0, 0) * 1024 * 1024;
			break;

		case 'c':		/* Tape is cart. not 9-track */
			cartridge = 1;
			break;

		case 'D':
			dumpdates = optarg;
			break;

		case 'd':		/* density, in bits per inch */
			density = numarg("density", 10L, 327670L) / 10;
			if (density >= 625 && !bflag)
				ntrec = HIGHDENSITYTREC;
			break;

		case 'f':		/* output file */
			if (popenout != NULL)
				errx(X_STARTUP, "You cannot use the P and f "
				    "flags together.\n");
			tape = optarg;
			break;

		case 'h':
			honorlevel = numarg("honor level", 0L, 10L);
			break;

		case 'L':
			snapdump = 1;
			break;

		case 'n':		/* notify operators */
			notify = 1;
			break;

		case 'P':
			if (tape != NULL)
				errx(X_STARTUP, "You cannot use the P and f "
				    "flags together.\n");
			popenout = optarg;
			break;

		case 'r': /* store slightly less data to be friendly to rsync */
			if (rsync_friendly < 1)
				rsync_friendly = 1;
			break;

		case 'R': /* store even less data to be friendlier to rsync */
			if (rsync_friendly < 2)
				rsync_friendly = 2;
			break;

		case 'S':               /* exit after estimating # of tapes */
			just_estimate = 1;
			break;

		case 's':		/* tape size, feet */
			tsize = numarg("tape size", 1L, 0L) * 12 * 10;
			break;

		case 'T':		/* time of last dump */
			spcl.c_ddate = unctime(optarg);
			if (spcl.c_ddate < 0) {
				(void)fprintf(stderr, "bad time \"%s\"\n",
				    optarg);
				exit(X_STARTUP);
			}
			Tflag = 1;
			lastlevel = -1;
			break;

		case 'u':		/* update /etc/dumpdates */
			uflag = 1;
			break;

		case 'W':		/* what to do */
		case 'w':
			lastdump(ch);
			exit(X_FINOK);	/* do nothing else */

		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc < 1) {
		(void)fprintf(stderr, "Must specify disk or file system\n");
		exit(X_STARTUP);
	}
	disk = *argv++;
	argc--;
	if (argc >= 1) {
		(void)fprintf(stderr, "Unknown arguments to dump:");
		while (argc--)
			(void)fprintf(stderr, " %s", *argv++);
		(void)fprintf(stderr, "\n");
		exit(X_STARTUP);
	}
	if (rsync_friendly && (level > 0)) {
		(void)fprintf(stderr, "%s %s\n", "rsync friendly options",
		    "can be used only with level 0 dumps.");
		exit(X_STARTUP);
	}
	if (Tflag && uflag) {
	        (void)fprintf(stderr,
		    "You cannot use the T and u flags together.\n");
		exit(X_STARTUP);
	}
	if (popenout) {
		tape = "child pipeline process";
	} else if (tape == NULL && (tape = getenv("TAPE")) == NULL)
		tape = _PATH_DEFTAPE;
	if (strcmp(tape, "-") == 0) {
		pipeout++;
		tape = "standard output";
	}

	if (blocksperfile)
		blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
	else if (!unlimited) {
		/*
		 * Determine how to default tape size and density
		 *
		 *         	density				tape size
		 * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
		 * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
		 * cartridge	8000 bpi (100 bytes/.1")	1700 ft.
		 *						(450*4 - slop)
		 * hilit19 hits again: "
		 */
		if (density == 0)
			density = cartridge ? 100 : 160;
		if (tsize == 0)
			tsize = cartridge ? 1700L*120L : 2300L*120L;
	}

	if (strchr(tape, ':')) {
		host = tape;
		tape = strchr(host, ':');
		*tape++ = '\0';
#ifdef RDUMP
		if (strchr(tape, '\n')) {
		    (void)fprintf(stderr, "invalid characters in tape\n");
		    exit(X_STARTUP);
		}
		if (rmthost(host) == 0)
			exit(X_STARTUP);
#else
		(void)fprintf(stderr, "remote dump not enabled\n");
		exit(X_STARTUP);
#endif
	}
	(void)setuid(getuid()); /* rmthost() is the only reason to be setuid */

	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, sig);
	if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
		signal(SIGTRAP, sig);
	if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
		signal(SIGFPE, sig);
	if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
		signal(SIGBUS, sig);
	if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
		signal(SIGSEGV, sig);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, sig);
	if (signal(SIGINT, interrupt) == SIG_IGN)
		signal(SIGINT, SIG_IGN);

	dump_getfstab();	/* /etc/fstab snarfed */
	/*
	 *	disk can be either the full special file name,
	 *	the suffix of the special file name,
	 *	the special name missing the leading '/',
	 *	the file system name with or without the leading '/'.
	 */
	dt = fstabsearch(disk);
	if (dt != NULL) {
		disk = rawname(dt->fs_spec);
 		if (disk == NULL)
 			errx(X_STARTUP, "%s: unknown file system", dt->fs_spec);
		(void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
		(void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
	} else {
		(void)strncpy(spcl.c_dev, disk, NAMELEN);
		(void)strncpy(spcl.c_filesys, "an unlisted file system",
		    NAMELEN);
	}
	spcl.c_dev[NAMELEN-1]='\0';
	spcl.c_filesys[NAMELEN-1]='\0';

	if ((mntpt = getmntpt(disk, &mntflags)) != 0) {
		if (mntflags & MNT_RDONLY) {
			if (snapdump != 0) {
				msg("WARNING: %s\n",
				    "-L ignored for read-only filesystem.");
				snapdump = 0;
			}
		} else if (snapdump == 0) {
			msg("WARNING: %s\n",
			    "should use -L when dumping live read-write "
			    "filesystems!");
		} else {
			char snapname[BUFSIZ], snapcmd[BUFSIZ];

			snprintf(snapname, sizeof snapname, "%s/.snap", mntpt);
			if ((stat(snapname, &sb) < 0) || !S_ISDIR(sb.st_mode)) {
				msg("WARNING: %s %s\n",
				    "-L requested but snapshot location",
				    snapname);
				msg("         %s: %s\n",
				    "is not a directory",
				    "dump downgraded, -L ignored");
				snapdump = 0;
			} else {
				snprintf(snapname, sizeof snapname,
				    "%s/.snap/dump_snapshot", mntpt);
				snprintf(snapcmd, sizeof snapcmd, "%s %s %s",
				    _PATH_MKSNAP_FFS, mntpt, snapname);
				unlink(snapname);
				if (system(snapcmd) != 0)
					errx(X_STARTUP, "Cannot create %s: %s\n",
					    snapname, strerror(errno));
				if ((diskfd = open(snapname, O_RDONLY)) < 0) {
					unlink(snapname);
					errx(X_STARTUP, "Cannot open %s: %s\n",
					    snapname, strerror(errno));
				}
				unlink(snapname);
				if (fstat(diskfd, &sb) != 0)
					err(X_STARTUP, "%s: stat", snapname);
				spcl.c_date = _time_to_time64(sb.st_mtime);
			}
		}
	} else if (snapdump != 0) {
		msg("WARNING: Cannot use -L on an unmounted filesystem.\n");
		snapdump = 0;
	}
	if (snapdump == 0) {
		if ((diskfd = open(disk, O_RDONLY)) < 0)
			err(X_STARTUP, "Cannot open %s", disk);
		if (fstat(diskfd, &sb) != 0)
			err(X_STARTUP, "%s: stat", disk);
		if (S_ISDIR(sb.st_mode))
			errx(X_STARTUP, "%s: unknown file system", disk);
	}

	(void)strcpy(spcl.c_label, "none");
	(void)gethostname(spcl.c_host, NAMELEN);
	spcl.c_level = level;
	spcl.c_type = TS_TAPE;
	if (rsync_friendly) {
		/* don't store real dump times */
		spcl.c_date = 0;
		spcl.c_ddate = 0;
	}
	if (spcl.c_date == 0) {
		tmsg = "the epoch\n";
	} else {
		time_t t = _time64_to_time(spcl.c_date);
		tmsg = ctime(&t);
	}
	msg("Date of this level %d dump: %s", level, tmsg);

	if (!Tflag && (!rsync_friendly))
	        getdumptime();		/* /etc/dumpdates snarfed */
	if (spcl.c_ddate == 0) {
		tmsg = "the epoch\n";
	} else {
		time_t t = _time64_to_time(spcl.c_ddate);
		tmsg = ctime(&t);
	}
	if (lastlevel < 0)
		msg("Date of last (level unknown) dump: %s", tmsg);
	else
		msg("Date of last level %d dump: %s", lastlevel, tmsg);

	msg("Dumping %s%s ", snapdump ? "snapshot of ": "", disk);
	if (dt != NULL)
		msgtail("(%s) ", dt->fs_file);
	if (host)
		msgtail("to %s on host %s\n", tape, host);
	else
		msgtail("to %s\n", tape);

	sync();
	sblock = (struct fs *)sblock_buf;
	for (i = 0; sblock_try[i] != -1; i++) {
		sblock->fs_fsize = SBLOCKSIZE; /* needed in bread */
		bread(sblock_try[i] >> dev_bshift, (char *) sblock, SBLOCKSIZE);
		if ((sblock->fs_magic == FS_UFS1_MAGIC ||
		     (sblock->fs_magic == FS_UFS2_MAGIC &&
		      sblock->fs_sblockloc == sblock_try[i])) &&
		    sblock->fs_bsize <= MAXBSIZE &&
		    sblock->fs_bsize >= sizeof(struct fs))
			break;
	}
	if (sblock_try[i] == -1)
		quit("Cannot find file system superblock\n");
	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
	dev_bshift = ffs(dev_bsize) - 1;
	if (dev_bsize != (1 << dev_bshift))
		quit("dev_bsize (%ld) is not a power of 2", dev_bsize);
	tp_bshift = ffs(TP_BSIZE) - 1;
	if (TP_BSIZE != (1 << tp_bshift))
		quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
	maxino = sblock->fs_ipg * sblock->fs_ncg;
	mapsize = roundup(howmany(maxino, CHAR_BIT), TP_BSIZE);
	usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
	dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
	dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
	tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);

	nonodump = spcl.c_level < honorlevel;

	passno = 1;
	setproctitle("%s: pass 1: regular files", disk);
	msg("mapping (Pass I) [regular files]\n");
	anydirskipped = mapfiles(maxino, &tapesize);

	passno = 2;
	setproctitle("%s: pass 2: directories", disk);
	msg("mapping (Pass II) [directories]\n");
	while (anydirskipped) {
		anydirskipped = mapdirs(maxino, &tapesize);
	}

	if (pipeout || unlimited) {
		tapesize += 10;	/* 10 trailer blocks */
		msg("estimated %ld tape blocks.\n", tapesize);
	} else {
		double fetapes;

		if (blocksperfile)
			fetapes = (double) tapesize / blocksperfile;
		else if (cartridge) {
			/* Estimate number of tapes, assuming streaming stops at
			   the end of each block written, and not in mid-block.
			   Assume no erroneous blocks; this can be compensated
			   for with an artificially low tape size. */
			fetapes =
			(	  (double) tapesize	/* blocks */
				* TP_BSIZE	/* bytes/block */
				* (1.0/density)	/* 0.1" / byte " */
			  +
				  (double) tapesize	/* blocks */
				* (1.0/ntrec)	/* streaming-stops per block */
				* 15.48		/* 0.1" / streaming-stop " */
			) * (1.0 / tsize );	/* tape / 0.1" " */
		} else {
			/* Estimate number of tapes, for old fashioned 9-track
			   tape */
			int tenthsperirg = (density == 625) ? 3 : 7;
			fetapes =
			(	  (double) tapesize	/* blocks */
				* TP_BSIZE	/* bytes / block */
				* (1.0/density)	/* 0.1" / byte " */
			  +
				  (double) tapesize	/* blocks */
				* (1.0/ntrec)	/* IRG's / block */
				* tenthsperirg	/* 0.1" / IRG " */
			) * (1.0 / tsize );	/* tape / 0.1" " */
		}
		etapes = fetapes;		/* truncating assignment */
		etapes++;
		/* count the dumped inodes map on each additional tape */
		tapesize += (etapes - 1) *
			(howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
		tapesize += etapes + 10;	/* headers + 10 trailer blks */
		msg("estimated %ld tape blocks on %3.2f tape(s).\n",
		    tapesize, fetapes);
	}

        /*
         * If the user only wants an estimate of the number of
         * tapes, exit now.
         */
        if (just_estimate)
                exit(0);

	/*
	 * Allocate tape buffer.
	 */
	if (!alloctape())
		quit(
	"can't allocate tape buffers - try a smaller blocking factor.\n");

	startnewtape(1);
	(void)time((time_t *)&(tstart_writing));
	dumpmap(usedinomap, TS_CLRI, maxino - 1);

	passno = 3;
	setproctitle("%s: pass 3: directories", disk);
	msg("dumping (Pass III) [directories]\n");
	dirty = 0;		/* XXX just to get gcc to shut up */
	for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
		if (((ino - 1) % CHAR_BIT) == 0)	/* map is offset by 1 */
			dirty = *map++;
		else
			dirty >>= 1;
		if ((dirty & 1) == 0)
			continue;
		/*
		 * Skip directory inodes deleted and maybe reallocated
		 */
		dp = getino(ino, &mode);
		if (mode != IFDIR)
			continue;
		(void)dumpino(dp, ino);
	}

	passno = 4;
	setproctitle("%s: pass 4: regular files", disk);
	msg("dumping (Pass IV) [regular files]\n");
	for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
		if (((ino - 1) % CHAR_BIT) == 0)	/* map is offset by 1 */
			dirty = *map++;
		else
			dirty >>= 1;
		if ((dirty & 1) == 0)
			continue;
		/*
		 * Skip inodes deleted and reallocated as directories.
		 */
		dp = getino(ino, &mode);
		if (mode == IFDIR)
			continue;
		(void)dumpino(dp, ino);
	}

	(void)time((time_t *)&(tend_writing));
	spcl.c_type = TS_END;
	for (i = 0; i < ntrec; i++)
		writeheader(maxino - 1);
	if (pipeout)
		msg("DUMP: %jd tape blocks\n", (intmax_t)spcl.c_tapea);
	else
		msg("DUMP: %jd tape blocks on %d volume%s\n",
		    (intmax_t)spcl.c_tapea, spcl.c_volume,
		    (spcl.c_volume == 1) ? "" : "s");

	/* report dump performance, avoid division through zero */
	if (tend_writing - tstart_writing == 0)
		msg("finished in less than a second\n");
	else
		msg("finished in %jd seconds, throughput %jd KBytes/sec\n",
		    (intmax_t)tend_writing - tstart_writing, 
		    (intmax_t)(spcl.c_tapea / 
		    (tend_writing - tstart_writing)));

	putdumptime();
	trewind();
	broadcast("DUMP IS DONE!\a\a\n");
	msg("DUMP IS DONE\n");
	Exit(X_FINOK);
	/* NOTREACHED */
}
Example #19
0
void
Write_PhAvg2( int* pid,
              char* filemode,
              char* fieldtag,
              int* tagsize,
              int* iphase,
              int* nphasesincycle,
              void* array,
              char* arraytype,
              int* nshg,
              int* numvars,
              int* stepno) {

    int addtagsize=0; // phase number is added to the name of the field
    if(*iphase<10)
      addtagsize=1;
    else if(*iphase<100)
      addtagsize=2;
    else if(*iphase<1000)
      addtagsize=3;

    int tagsize2;
    tagsize2=*tagsize+addtagsize;

    char *fieldlabel = (char *)malloc((tagsize2+1)*sizeof(char));
    strncpy(fieldlabel, fieldtag, *tagsize);
    fieldlabel[tagsize2] = '\0';

    char straddtagsize[10];
    sprintf(straddtagsize,"%d",*iphase);

    if(*iphase<10) {
      fieldlabel[tagsize2-1]=straddtagsize[0];
    }
    else if(*iphase<100) {
      fieldlabel[tagsize2-2]=straddtagsize[0];
      fieldlabel[tagsize2-1]=straddtagsize[1];
    }
    else if(*iphase<1000) {
      fieldlabel[tagsize2-3]=straddtagsize[0];
      fieldlabel[tagsize2-2]=straddtagsize[1];
      fieldlabel[tagsize2-1]=straddtagsize[2];
    }

    int irstou;
    int magic_number = 362436;
    int* mptr = &magic_number;
    double version=0.0;
    int isize, nitems;
    int iarray[10];

    char fmode[10];
    if(!strncmp(filemode,"w",1))
      strcpy(fmode,"write");
    else // default is append
      strcpy(fmode,"append");

    char datatype[10];
    if(!strncmp(arraytype,"i",1))
      strcpy(datatype,"int");
    else // default is double
      strcpy(datatype,"double");

    /////////////////////////////// Start of writing using new-lib ////////////////////////////

    int nfiles;
    int nfields;
    int numparts;
    int irank;
    int nprocs;

    nfiles = outpar.nsynciofiles;
    nfields = outpar.nsynciofieldswriterestart;
    numparts = workfc.numpe;
    irank = *pid; //workfc.myrank;
    nprocs = workfc.numpe;

    int nppf = numparts/nfiles;
    int GPID;

    // Calculate number of parts each  proc deal with and where it start and end ...
    int nppp = numparts/nprocs;// nppp : Number of parts per proc ...
    int startpart = irank * nppp +1;// Part id from which I (myrank) start ...
    int endpart = startpart + nppp - 1;// Part id to which I (myrank) end ...

    char fieldtag_s[255];
    bzero((void*)fieldtag_s,255);

    field_flag++;
    if(*pid==0) {
      printf("\n");
      printf("The %d/%d th field to be written is '%s'\n",field_flag,nfields,fieldlabel);
    }

    int i;
    for ( i = 0; i < nppp; i++  ) {
        GPID = startpart + i;

        // Write solution field ...
        sprintf(fieldtag_s,"%s@%d",fieldlabel,GPID);

        isize = (*nshg)*(*numvars);
        nitems = 3;
        iarray[ 0 ] = (*nshg);
        iarray[ 1 ] = (*numvars);
        iarray[ 2 ] = (*stepno);
        writeheader( &f_descriptor, fieldtag_s, (void*)iarray, &nitems, &isize, "double", phasta_iotype);
        writedatablock( &f_descriptor, fieldtag_s, array, &isize, "double", phasta_iotype );
    }

    if (field_flag==nfields){
      closefile(&f_descriptor, "write");
      finalizephmpiio(&f_descriptor);
      if (*pid==0) {
        printf("\n");
      }
    }

    free(fieldlabel);
}
Example #20
0
int
main(int argc, char *argv[])
{
    ino_t ino;
    int dirty;
    union dinode *dp;
    struct fstab *dt;
    struct statvfs *mntinfo, fsbuf;
    char *map, *cp;
    int ch;
    int i, anydirskipped, bflag = 0, Tflag = 0, Fflag = 0, honorlevel = 1;
    int snap_internal = 0;
    ino_t maxino;
    time_t tnow, date;
    int dirc;
    char *mountpoint;
    int just_estimate = 0;
    char labelstr[LBLSIZE];
    char buf[MAXPATHLEN], rbuf[MAXPATHLEN];
    char *new_time_format;
    char *snap_backup = NULL;

    spcl.c_date = 0;
    (void)time(&tnow);
    spcl.c_date = tnow;
    tzset(); /* set up timezone for strftime */
    if ((new_time_format = getenv("TIMEFORMAT")) != NULL)
        time_string = new_time_format;

    tsize = 0;	/* Default later, based on 'c' option for cart tapes */
    if ((tape = getenv("TAPE")) == NULL)
        tape = _PATH_DEFTAPE;
    dumpdates = _PATH_DUMPDATES;
    temp = _PATH_DTMP;
    strcpy(labelstr, "none");	/* XXX safe strcpy. */
    if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
        quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
    level = '0';
    timestamp = 0;

    if (argc < 2)
        usage();

    obsolete(&argc, &argv);
    while ((ch = getopt(argc, argv,
                        "0123456789aB:b:cd:eFf:h:ik:l:L:nr:s:StT:uWwx:X")) != -1)
        switch (ch) {
        /* dump level */
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            level = ch;
            break;

        case 'a':		/* `auto-size', Write to EOM. */
            unlimited = 1;
            break;

        case 'B':		/* blocks per output file */
            blocksperfile = numarg("blocks per file", 1L, 0L);
            break;

        case 'b':		/* blocks per tape write */
            ntrec = numarg("blocks per write", 1L, 1000L);
            bflag = 1;
            break;

        case 'c':		/* Tape is cart. not 9-track */
            cartridge = 1;
            break;

        case 'd':		/* density, in bits per inch */
            density = numarg("density", 10L, 327670L) / 10;
            if (density >= 625 && !bflag)
                ntrec = HIGHDENSITYTREC;
            break;

        case 'e':		/* eject full tapes */
            eflag = 1;
            break;

        case 'F':		/* files-to-dump is an fs image */
            Fflag = 1;
            break;

        case 'f':		/* output file */
            tape = optarg;
            break;

        case 'h':
            honorlevel = numarg("honor level", 0L, 10L);
            break;

        case 'i':	/* "true incremental" regardless level */
            level = 'i';
            trueinc = 1;
            break;

        case 'k':
            readblksize = numarg("read block size", 0, 64) * 1024;
            break;

        case 'l':		/* autoload after eject full tapes */
            eflag = 1;
            lflag = numarg("timeout (in seconds)", 1, 0);
            break;

        case 'L':
            /*
             * Note that although there are LBLSIZE characters,
             * the last must be '\0', so the limit on strlen()
             * is really LBLSIZE-1.
             */
            if (strlcpy(labelstr, optarg, sizeof(labelstr))
                    >= sizeof(labelstr)) {
                msg(
                    "WARNING Label `%s' is larger than limit of %lu characters.\n",
                    optarg,
                    (unsigned long)sizeof(labelstr) - 1);
                msg("WARNING: Using truncated label `%s'.\n",
                    labelstr);
            }
            break;
        case 'n':		/* notify operators */
            notify = 1;
            break;

        case 'r':		/* read cache size */
            readcache = numarg("read cache size", 0, 512);
            break;

        case 's':		/* tape size, feet */
            tsize = numarg("tape size", 1L, 0L) * 12 * 10;
            break;

        case 'S':		/* exit after estimating # of tapes */
            just_estimate = 1;
            break;

        case 't':
            timestamp = 1;
            break;

        case 'T':		/* time of last dump */
            spcl.c_ddate = unctime(optarg);
            if (spcl.c_ddate < 0) {
                (void)fprintf(stderr, "bad time \"%s\"\n",
                              optarg);
                exit(X_STARTUP);
            }
            Tflag = 1;
            lastlevel = '?';
            break;

        case 'u':		/* update /etc/dumpdates */
            uflag = 1;
            break;

        case 'W':		/* what to do */
        case 'w':
            lastdump(ch);
            exit(X_FINOK);	/* do nothing else */

        case 'x':
            snap_backup = optarg;
            break;

        case 'X':
            snap_internal = 1;
            break;

        default:
            usage();
        }
    argc -= optind;
    argv += optind;

    if (argc < 1) {
        (void)fprintf(stderr,
                      "Must specify disk or image, or file list\n");
        exit(X_STARTUP);
    }


    /*
     *	determine if disk is a subdirectory, and setup appropriately
     */
    getfstab();		/* /etc/fstab snarfed */
    disk = NULL;
    disk_dev = NULL;
    mountpoint = NULL;
    dirc = 0;
    for (i = 0; i < argc; i++) {
        struct stat sb;
        int error;

        error = lstat(argv[i], &sb);
        if (Fflag || (!error && (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)))) {
            if (error)
                quit("Cannot stat %s: %s\n", argv[i], strerror(errno));
            disk = argv[i];
multicheck:
            if (dirc != 0)
                quit("Can't dump a disk or image at the same time as a file list\n");
            break;
        }
        if ((dt = fstabsearch(argv[i])) != NULL) {
            disk = argv[i];
            mountpoint = xstrdup(dt->fs_file);
            goto multicheck;
        }
        if (statvfs(argv[i], &fsbuf) == -1)
            quit("Cannot statvfs %s: %s\n", argv[i],
                 strerror(errno));
        disk = fsbuf.f_mntfromname;
        if (strcmp(argv[i], fsbuf.f_mntonname) == 0)
            goto multicheck;
        if (mountpoint == NULL) {
            mountpoint = xstrdup(fsbuf.f_mntonname);
            if (uflag) {
                msg("Ignoring u flag for subdir dump\n");
                uflag = 0;
            }
            if (level > '0') {
                msg("Subdir dump is done at level 0\n");
                level = '0';
            }
            msg("Dumping sub files/directories from %s\n",
                mountpoint);
        } else {
            if (strcmp(mountpoint, fsbuf.f_mntonname) != 0)
                quit("%s is not on %s\n", argv[i], mountpoint);
        }
        msg("Dumping file/directory %s\n", argv[i]);
        dirc++;
    }
    if (mountpoint)
        free(mountpoint);

    if (dirc == 0) {
        argv++;
        if (argc != 1) {
            (void)fprintf(stderr, "Excess arguments to dump:");
            while (--argc)
                (void)fprintf(stderr, " %s", *argv++);
            (void)fprintf(stderr, "\n");
            exit(X_STARTUP);
        }
    }
    if (Tflag && uflag) {
        (void)fprintf(stderr,
                      "You cannot use the T and u flags together.\n");
        exit(X_STARTUP);
    }
    if (strcmp(tape, "-") == 0) {
        pipeout++;
        tape = "standard output";
    }

    if (blocksperfile)
        blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
    else if (!unlimited) {
        /*
         * Determine how to default tape size and density
         *
         *		density				tape size
         * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
         * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
         * cartridge	8000 bpi (100 bytes/.1")	1700 ft.
         *						(450*4 - slop)
         */
        if (density == 0)
            density = cartridge ? 100 : 160;
        if (tsize == 0)
            tsize = cartridge ? 1700L*120L : 2300L*120L;
    }

    if ((cp = strchr(tape, ':')) != NULL) {
        host = tape;
        /* This is fine, because all the const strings don't have : */
        *cp++ = '\0';
        tape = cp;
#ifdef RDUMP
        if (rmthost(host) == 0)
            exit(X_STARTUP);
#else
        (void)fprintf(stderr, "remote dump not enabled\n");
        exit(X_STARTUP);
#endif
    }

    if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
        signal(SIGHUP, sig);
    if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
        signal(SIGTRAP, sig);
    if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
        signal(SIGFPE, sig);
    if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
        signal(SIGBUS, sig);
#if 0
    if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
        signal(SIGSEGV, sig);
#endif
    if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
        signal(SIGTERM, sig);
    if (signal(SIGINT, interrupt) == SIG_IGN)
        signal(SIGINT, SIG_IGN);

    /*
     *	disk can be either the full special file name, or
     *	the file system name.
     */
    mountpoint = NULL;
    mntinfo = mntinfosearch(disk);
    if ((dt = fstabsearch(disk)) != NULL) {
        if (getfsspecname(buf, sizeof(buf), dt->fs_spec) == NULL)
            quit("%s (%s)", buf, strerror(errno));
        if (getdiskrawname(rbuf, sizeof(rbuf), buf) == NULL)
            quit("Can't get disk raw name for `%s' (%s)",
                 buf, strerror(errno));
        disk = rbuf;
        mountpoint = dt->fs_file;
        msg("Found %s on %s in %s\n", disk, mountpoint, _PATH_FSTAB);
    } else if (mntinfo != NULL) {
        if (getdiskrawname(rbuf, sizeof(rbuf), mntinfo->f_mntfromname)
                == NULL)
            quit("Can't get disk raw name for `%s' (%s)",
                 mntinfo->f_mntfromname, strerror(errno));
        disk = rbuf;
        mountpoint = mntinfo->f_mntonname;
        msg("Found %s on %s in mount table\n", disk, mountpoint);
    }
    if (mountpoint != NULL) {
        if (dirc != 0)
            (void)snprintf(spcl.c_filesys, sizeof(spcl.c_filesys),
                           "a subset of %s", mountpoint);
        else
            (void)strlcpy(spcl.c_filesys, mountpoint,
                          sizeof(spcl.c_filesys));
    } else if (Fflag) {
        (void)strlcpy(spcl.c_filesys, "a file system image",
                      sizeof(spcl.c_filesys));
    } else {
        (void)strlcpy(spcl.c_filesys, "an unlisted file system",
                      sizeof(spcl.c_filesys));
    }
    (void)strlcpy(spcl.c_dev, disk, sizeof(spcl.c_dev));
    (void)strlcpy(spcl.c_label, labelstr, sizeof(spcl.c_label));
    (void)gethostname(spcl.c_host, sizeof(spcl.c_host));
    spcl.c_host[sizeof(spcl.c_host) - 1] = '\0';

    if ((snap_backup != NULL || snap_internal) && mntinfo == NULL) {
        msg("WARNING: Cannot use -x or -X on unmounted file system.\n");
        snap_backup = NULL;
        snap_internal = 0;
    }

#ifdef DUMP_LFS
    sync();
    if (snap_backup != NULL || snap_internal) {
        if (lfs_wrap_stop(mountpoint) < 0) {
            msg("Cannot stop writing on %s\n", mountpoint);
            exit(X_STARTUP);
        }
    }
    if ((diskfd = open(disk, O_RDONLY)) < 0) {
        msg("Cannot open %s\n", disk);
        exit(X_STARTUP);
    }
    disk_dev = disk;
#else /* ! DUMP_LFS */
    if (snap_backup != NULL || snap_internal) {
        diskfd = snap_open(mntinfo->f_mntonname, snap_backup,
                           &tnow, &disk_dev);
        if (diskfd < 0) {
            msg("Cannot open snapshot of %s\n",
                mntinfo->f_mntonname);
            exit(X_STARTUP);
        }
        spcl.c_date = tnow;
    } else {
        if ((diskfd = open(disk, O_RDONLY)) < 0) {
            msg("Cannot open %s\n", disk);
            exit(X_STARTUP);
        }
        disk_dev = disk;
    }
    sync();
#endif /* ! DUMP_LFS */

    needswap = fs_read_sblock(sblock_buf);

    /* true incremental is always a level 10 dump */
    spcl.c_level = trueinc? iswap32(10): iswap32(level - '0');
    spcl.c_type = iswap32(TS_TAPE);
    spcl.c_date = iswap32(spcl.c_date);
    spcl.c_ddate = iswap32(spcl.c_ddate);
    if (!Tflag)
        getdumptime();		/* /etc/dumpdates snarfed */

    date = iswap32(spcl.c_date);
    msg("Date of this level %c dump: %s", level,
        spcl.c_date == 0 ? "the epoch\n" : ctime(&date));
    date = iswap32(spcl.c_ddate);
    msg("Date of last level %c dump: %s", lastlevel,
        spcl.c_ddate == 0 ? "the epoch\n" : ctime(&date));
    msg("Dumping ");
    if (snap_backup != NULL || snap_internal)
        msgtail("a snapshot of ");
    if (dirc != 0)
        msgtail("a subset of ");
    msgtail("%s (%s) ", disk, spcl.c_filesys);
    if (host)
        msgtail("to %s on host %s\n", tape, host);
    else
        msgtail("to %s\n", tape);
    msg("Label: %s\n", labelstr);

    ufsib = fs_parametrize();

    dev_bshift = ffs(dev_bsize) - 1;
    if (dev_bsize != (1 << dev_bshift))
        quit("dev_bsize (%ld) is not a power of 2", dev_bsize);
    tp_bshift = ffs(TP_BSIZE) - 1;
    if (TP_BSIZE != (1 << tp_bshift))
        quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
    maxino = fs_maxino();
    mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
    usedinomap = (char *)xcalloc((unsigned) mapsize, sizeof(char));
    dumpdirmap = (char *)xcalloc((unsigned) mapsize, sizeof(char));
    dumpinomap = (char *)xcalloc((unsigned) mapsize, sizeof(char));
    tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);

    nonodump = iswap32(spcl.c_level) < honorlevel;

    initcache(readcache, readblksize);

    (void)signal(SIGINFO, statussig);

    msg("mapping (Pass I) [regular files]\n");
    anydirskipped = mapfiles(maxino, &tapesize, mountpoint,
                             (dirc ? argv : NULL));

    msg("mapping (Pass II) [directories]\n");
    while (anydirskipped) {
        anydirskipped = mapdirs(maxino, &tapesize);
    }

    if (pipeout || unlimited) {
        tapesize += 10;	/* 10 trailer blocks */
        msg("estimated %llu tape blocks.\n",
            (unsigned long long)tapesize);
    } else {
        double fetapes;

        if (blocksperfile)
            fetapes = (double) tapesize / blocksperfile;
        else if (cartridge) {
            /* Estimate number of tapes, assuming streaming stops at
               the end of each block written, and not in mid-block.
               Assume no erroneous blocks; this can be compensated
               for with an artificially low tape size. */
            fetapes =
                (	  (double) tapesize	/* blocks */
                      * TP_BSIZE	/* bytes/block */
                      * (1.0/density)	/* 0.1" / byte */
                      +
                      (double) tapesize	/* blocks */
                      * (1.0/ntrec)	/* streaming-stops per block */
                      * 15.48		/* 0.1" / streaming-stop */
                ) * (1.0 / tsize );	/* tape / 0.1" */
        } else {
            /* Estimate number of tapes, for old fashioned 9-track
               tape */
            int tenthsperirg = (density == 625) ? 3 : 7;
            fetapes =
                (	  tapesize	/* blocks */
                      * TP_BSIZE	/* bytes / block */
                      * (1.0/density)	/* 0.1" / byte */
                      +
                      tapesize	/* blocks */
                      * (1.0/ntrec)	/* IRG's / block */
                      * tenthsperirg	/* 0.1" / IRG */
                ) * (1.0 / tsize );	/* tape / 0.1" */
        }
        etapes = fetapes;		/* truncating assignment */
        etapes++;
        /* count the dumped inodes map on each additional tape */
        tapesize += (etapes - 1) *
                    (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
        tapesize += etapes + 10;	/* headers + 10 trailer blks */
        msg("estimated %llu tape blocks on %3.2f tape(s).\n",
            (unsigned long long)tapesize, fetapes);
    }
    /*
     * If the user only wants an estimate of the number of
     * tapes, exit now.
     */
    if (just_estimate)
        exit(X_FINOK);

    /*
     * Allocate tape buffer.
     */
    if (!alloctape())
        quit("can't allocate tape buffers - try a smaller blocking factor.\n");

    startnewtape(1);
    (void)time((time_t *)&(tstart_writing));
    xferrate = 0;
    dumpmap(usedinomap, TS_CLRI, maxino - 1);

    msg("dumping (Pass III) [directories]\n");
    dirty = 0;		/* XXX just to get gcc to shut up */
    for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
        if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
            dirty = *map++;
        else
            dirty >>= 1;
        if ((dirty & 1) == 0)
            continue;
        /*
         * Skip directory inodes deleted and maybe reallocated
         */
        dp = getino(ino);
        if ((DIP(dp, mode) & IFMT) != IFDIR)
            continue;
        (void)dumpino(dp, ino);
    }

    msg("dumping (Pass IV) [regular files]\n");
    for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
        int mode;

        if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
            dirty = *map++;
        else
            dirty >>= 1;
        if ((dirty & 1) == 0)
            continue;
        /*
         * Skip inodes deleted and reallocated as directories.
         */
        dp = getino(ino);
        mode = DIP(dp, mode) & IFMT;
        if (mode == IFDIR)
            continue;
        (void)dumpino(dp, ino);
    }

    spcl.c_type = iswap32(TS_END);
    for (i = 0; i < ntrec; i++)
        writeheader(maxino - 1);
    if (pipeout)
        msg("%lld tape blocks\n",(long long)iswap64(spcl.c_tapea));
    else
        msg("%lld tape blocks on %d volume%s\n",
            (long long)iswap64(spcl.c_tapea), iswap32(spcl.c_volume),
            (iswap32(spcl.c_volume) == 1) ? "" : "s");
    tnow = do_stats();
    date = iswap32(spcl.c_date);
    msg("Date of this level %c dump: %s", level,
        spcl.c_date == 0 ? "the epoch\n" : ctime(&date));
    msg("Date this dump completed:  %s", ctime(&tnow));
    msg("Average transfer rate: %d KB/s\n", xferrate / tapeno);
    putdumptime();
    trewind(0);
    broadcast("DUMP IS DONE!\a\a\n");
#ifdef DUMP_LFS
    lfs_wrap_go();
#endif /* DUMP_LFS */
    msg("DUMP IS DONE\n");
    Exit(X_FINOK);
    /* NOTREACHED */
    exit(X_FINOK);		/* XXX: to satisfy gcc */
}
Example #21
0
void Banlist_writebans()
/*
 * Prefix codes are:
 *    'n' - <nick>
 *    'b' - <ban>
 *    't' - <time_set>
 *    'e' - <expires>
 *    'u' - <used>
 */
{
	FILE	*f;
	banlrec	*b;
	int	x;
	char	banlist[256], tmpfile[256];

	/* bail if banlist is inactive (pending read) */
	if(!(Banlist->flags & BANLIST_ACTIVE))
	{
		Log_write(LOG_MAIN,"*","Banlist list is not active.  Ignoring write request.");
		return;
	}

	/* Open for writing */
	sprintf(banlist,"%s/%s",Grufti->botdir,Grufti->banlist);
	sprintf(tmpfile,"%s.tmp",banlist);
	f = fopen(tmpfile,"w");
	if(f == NULL)
	{
		Log_write(LOG_MAIN|LOG_ERROR,"*","Couldn't write banlist.");
		return;
	}

	/* write header */
	writeheader(f,"Banlist->banlist - The shitlist",banlist);

	/* write each record */
	for(b=Banlist->banlist; b!=NULL; b=b->next)
	{
		/* Write nick */
		if(fprintf(f,"n %s\n",b->nick) == EOF)
			return;

		/* Write ban */
		if(fprintf(f,"b %s\n",b->ban) == EOF)
			return;

		/* Write time */
		if(fprintf(f,"t %lu\n",(u_long)b->time_set) == EOF)
			return;

		/* Write expires */
		if(fprintf(f,"e %lu\n",(u_long)b->expires) == EOF)
			return;

		/* Write used */
		if(fprintf(f,"u %d\n",b->used) == EOF)
			return;
	}

	fclose(f);

	/* Move tmpfile over to main response */
	if(Grufti->keep_tmpfiles)
		x = copyfile(tmpfile,banlist);
	else
		x = movefile(tmpfile,banlist);

	verify_write(x,tmpfile,banlist);
	if(x == 0)
	{
		Log_write(LOG_MAIN,"*","Wrote banlist.");
		Banlist->flags &= ~BANLIST_NEEDS_WRITE;
	}
}
Example #22
0
void
Write_d2wall(   int* pid,
                int* numnp,
                double* array1 ) {

    int isize, nitems;
    int iarray[10];

    /////////////////////////////// Start of writing using new-lib ////////////////////////////

    int nfiles;
    int nfields;
    int numparts;
    int irank;
    int nprocs;

    //  First, count the number of fields to write and store the result in
    //countfieldstowriterestart();

    //  Retrieve and compute the parameters required for SyncIO
    nfiles = outpar.nsynciofiles;
    nfields = 1; //outpar.nsynciofieldswriterestart;  // Only the distance to the walls in d2wall
    numparts = workfc.numpe;
    irank = *pid; //workfc.myrank;
    nprocs = workfc.numpe;
    int nppf = numparts/nfiles;
    int GPID;

    // Calculate number of parts each proc deal with and where it start and end ...
    int nppp = numparts/nprocs;// nppp : Number of parts per proc ...
    int startpart = irank * nppp +1;// Part id from which I (myrank) start ...
    int endpart = startpart + nppp - 1;// Part id to which I (myrank) end ...

    int descriptor;
    char filename[255],fieldtag_s[255];
    bzero((void*)filename,255);
    bzero((void*)fieldtag_s,255);

    sprintf(filename,"d2wall.%d",((int)(irank/(nprocs/nfiles))+1));

    if (irank==0) {
      printf("Filename is %s \n",filename);
    }

    initphmpiio(&nfields, &nppf, &nfiles, &f_descriptor, "write");

    openfile(filename, "write", &f_descriptor);

    field_flag=0;

     int i;
     for ( i = 0; i < nppp; i++) { //This loop is useful only if several parts per processor
     // GPID : global part id, corresponds to rank ...
        // e.g : (in this example)
        // proc 0 : 1--4
        // proc 1 : 5--8 ...
        GPID = startpart + i;

        // Write solution field ...
        sprintf(fieldtag_s,"d2wall@%d",GPID);

        isize = (*numnp);
        nitems = 2;
        iarray[ 0 ] = (*numnp);
        iarray[ 1 ] = 1; //numVars = 1
        writeheader( &f_descriptor, fieldtag_s, (void*)iarray, &nitems, &isize, "double", phasta_iotype);
        writedatablock( &f_descriptor, fieldtag_s, (void*)(array1), &isize, "double", phasta_iotype );
    }
    field_flag++;

    if (field_flag==nfields){
      closefile(&f_descriptor, "write");
      finalizephmpiio(&f_descriptor);
      if (irank==0) {
        printf("\n");
      }
    }
}
Example #23
0
int mbtransfer (char *ziel)
//*************************************************************************
//
//  TRANSFER-Prozedur
//  (wird fuer jedes transferierte File einzeln aufgerufen)
//
//*************************************************************************
{
  char name[20];
  strcpy(name, "mbtransfer");
  lastfunc(name);
  char *line = b->line;
  int findex;
  FILE *oldf, *newf;
  char usermail = 0;
  int retwert = NO;
  int nocp; //no-copy flag
  char oldsubject[101];
  unsigned long int oldfpos;
  char oldmsgty;
  char oldmailfname[10];
  time_t oldmsgtime;
  char old_ziel[DIRLEN+1];
  int old_usermail;
  char oldboardname[10];
  char oldmailpath[FNAMELEN+1];
  char zielcall[CALLEN+1];
  char newcall[CALLEN+1];
  int gleichesboard = NO;
  unsigned long nummer;
#ifdef USERLT
  short int old_lt;
#endif

#ifdef DEBUG_FWD
  trace(report, "mbtransfer", "ziel: %s", ziel);
#endif
  strupr(ziel);

  nexttoken(ziel, zielcall, CALLEN);
  strcpy(oldmailpath, b->mailpath);
  if (sema_test("sendlock") || m.disable)
  {
    putf(ms(m_sendnotpossible));
    return NO;
  }
  if (mbcallok(zielcall))
  { // Use newcall
    if (get_newcall(zielcall, newcall))
    {
      strcpy(zielcall, newcall);
      putf(ms(m_usingnewcall), newcall);
    }
  }
  char *bbuf = (char *) t_malloc(sizeof(tvar_t) - sizeof(task_t), "tran");
  char *oldfname;
  oldfname = (char *) t_malloc(sizeof(char) * (FNAMELEN+1), "tra2");
  if (! bbuf || ! oldfname)
    return NO;
  memcpy(bbuf, (char *) b + sizeof(task_t), sizeof(tvar_t) - sizeof(task_t));
  strlwr(b->mailpath);
  strcpy(oldfname, b->mailpath);
  strcpy(oldmailfname, b->mailfname);
  oldmsgtime = filename2time(b->mailfname);
  if ((oldf = s_fopen(oldfname, "srt")) != NULL)
  {
    fgets(b->line, BUFLEN - 1, oldf);    // Befehlszeile einlesen
    mbsend_parse(line, 0);
    if (b->mailtype == 'A'
        || (b->mailtype == 'B' && b->eraseinfo == 'T'))
    {
      retwert = NIL;
      s_fclose(oldf);
      goto error_exit;
    }
    oldmsgty = b->conttype;              // save mailflags ...(conttype)
    fgets(b->line, BUFLEN - 1, oldf);    // Forwardzeile vernichten
    fgets(b->line, BUFLEN - 1, oldf);    // Read-Zeile
    fgets(oldsubject, BETREFFLEN, oldf); // Betreff
    cut_blank(oldsubject);               // Newline entfernen
    if (mbcallok(zielcall)) *b->at = 0;  // Verteiler loeschen -> Neubestimmen
    strcpy(old_ziel, b->ziel);
#ifdef USERLT
    old_lt = b->lifetime;
    b->lifetime = 0;
#endif
    old_usermail = b->usermail;
    mbsend_parse(ziel, 2);
    if (! stricmp(b->ziel, b->mailpath+strlen(b->mailpath)-strlen(b->ziel)-8))
    {
      retwert = NIL;
      s_fclose(oldf);
      goto error_exit;
    }
    b->conttype = oldmsgty;              // set mailflags again.. (conttype)
    if (b->mailtype == 'B' && ! old_usermail)
      strcpy(b->ziel, old_ziel);
    weiterleiten(1, b->zielboard);
    waitfor(e_ticsfull);
    findex = finddir(b->zielboard, b->sysop);
    if (findex && !(strlen(b->zielboard)==1 && !b->sysop))
    {
      if (xmkdir(b->boardpath))
      {
        trace(serious, name, "mkdir %s error", b->boardpath);
        s_fclose(oldf);
        goto error_exit;
      }
      nocp = ! strcmp(b->herkunft, b->logincall) || b->sysop;
             //kein "CP " wenn Sysop!
      if (nocp || b->mailtype == 'B')
        strcpy(b->betreff, oldsubject);
      else
        sprintf(b->betreff, "CP %s: %.67s", b->logincall, oldsubject);
      //Bei Nicht-Bulletin BID neu generieren bzw. wenn BID fehlt
      if (b->mailtype != 'B'|| ! *b->bid) strcpy(b->bid, newbid());
      make_mask(b->mailpath, b->boardfullname);
      strcpy(b->mask, b->mailpath);
      // Ursprungsboardnamen aus b->mailpath holen und mit ziel vergleichen
      strcpy(oldboardname, b->boardname);
      oldmailpath[strlen(oldmailpath)-8] = 0;
      if (finddir(oldmailpath,0) > 0)
      {
        if (! strcmp(ziel, b->boardname))
          gleichesboard = YES;
      }
      else
        gleichesboard = NO;
      strcpy(b->boardname,oldboardname); // b->boardname wieder herstellen
      // bei Usermail oder gleichem Board zum Sortieren
      // Filezeit/-namen neu setzen
      if (mbcallok(zielcall) || gleichesboard)
      {
        strcpy(b->mailfname, time2filename(0));
      }
      else
        strcpy(b->mailfname, oldmailfname);
      if (! strstr(b->mailpath, "*.*"))
        trace(fatal, name, "mask %s", b->mailpath);
      strcpy(strstr(b->mailpath, "*.*"), b->mailfname);
      strlwr(b->mailpath);
      if ((newf = s_fopen(b->mailpath, "sw+t")) != NULL)
      {
        s_fsetopt(newf, 1);
#ifdef USERLT
        set_boardlife_max(old_lt);
        b->lifetime = old_lt;
#endif
        writeheader(newf, 1);
        if (b->mailtype != 'B')
        {
          if (fgets(b->line, BUFLEN - 1, oldf))
          {
            do
            { // fputs(line,f); skip old R-lines
              waitfor(e_ticsfull);
              fgets(b->line, BUFLEN - 1, oldf);
            }
            while (! feof(oldf) && *line == 'R' && line[1] == ':');
          }
          fprintf(newf, "%s\n", makeheader(1));
          fprintf(newf, "X-Transfer: %s by %s @ %s\n",
                  datestr(ad_time(), 12), b->logincall, m.boxadress);
          fprintf(newf, "X-Original-Date: %s\n", datestr(oldmsgtime, 10));
          do
          {
            if((   ! strncasecmp(line, "from", 4)
                || ! strncmp(line, "de: ", 4)
                || ! strncmp(line, "de ", 3)
                || ! strncmp(line, "fm ", 3)) && ! nocp)
              fprintf(newf, "X-Originally %s", line);
            else if ((   ! strncasecmp(line, "to: ", 4)
                      || ! strncasecmp(line, "to ", 3)) && ! nocp)
              fprintf(newf, "X-Originally %s", line);
            else if (! strncmp(line, "X-MID: ", 7))
              fprintf(newf, "X-Old-MID: %s", line + 7);
            else if (! strncmp(line, "X-BID: ", 7))
              fprintf(newf, "X-Old-BID: %s", line + 7);
            else fputs(line, newf);
            waitfor(e_ticsfull);
            fgets(b->line, BUFLEN - 1, oldf);
          }
          while (! feof(oldf) && *line != LF);
          fputc(LF, newf);
        }
        //Files binaer behandeln
        oldfpos = ftell(oldf);
        s_fclose(oldf);
        s_fclose(newf);
        writemailflags();
        if ((oldf = s_fopen(oldfname, "srb")) != NULL)
        {
          if ((newf = s_fopen(b->mailpath, "sab")) != NULL) //append to file
          {
            fseek(oldf, oldfpos, SEEK_SET);
            do
            { //oe3dzw: Transferroutine transparent
              int len;
              len = fread(line, 1, 255, oldf);
              if (len) fwrite(line, 1, len, newf);
              waitfor(e_ticsfull);
            }
            while (! feof(oldf));
            if (b->binstart)  //bei binaeren Mails offset neu berechnen
            {
              b->binstart += ftell(newf) - ftell(oldf);
              if (b->binstart < 0)
                trace(serious, name, "offset %ld in %s", b->binstart, b->mailpath);
            }
            s_fclose(newf);
            if (b->binstart) writelines(); //Neuen Binstart speichern
            if (b->bytes)
            {
              if (old_usermail || gleichesboard)
                nummer = appenddirlist(1);
              else
                nummer = appenddirlist(0); //change old CHECKLINE
              if (b->usermail)
              {
                add_fwdfile("", get_fdelay(b->herkunft), 0);
                sprintf(b->line, "%s %lu", b->herkunft, nummer);
                mbtalk("\001", b->zielboard, b->line);
                trigger_ufwd(b->zielboard);
              }
              else
              {
                handle fh;
                char found;
                if (old_usermail)
                  add_fwdfile("", get_fdelay(b->herkunft), 0);
                else
                  add_fwdfile("", get_fdelay(b->herkunft), 1);
                if (findex > 0)
                  tree[findex - 1].newestmail = oldmsgtime;
                if ((fh = s_open(CHECKNAME, "sr+b")) != EOF)
                {
                  seek_fname(fh, b->mailfname, &found, 1);
                  long pos = ltell(fh);
                  if (found)
                  {
                    _read(fh, b->line, BLEN);
                    sprintf(b->line + 15, "%-8s", b->boardname);
                    b->line[23] = '~';
#ifdef USERLT
                    char nlt[4];
                    sprintf(nlt, "%3.3d", b->boardlife_max);
                    memcpy(b->line + 51, nlt, 3);
#endif
                    lseek(fh, -(LBLEN), SEEK_CUR);
                    _write(fh, b->line, BLEN);
                  }
                  s_close(fh);
                  if (found && (fh = s_open(CHECKNUMNAME, "sr+b")) != EOF)
                  {
                    lseek(fh, 2*(pos >> 6), SEEK_SET); //2* da 32bit!
                    _write(fh, &nummer, 4); // 4Byte=32 bit
                    s_close(fh);
                  }
                }
                else
                  trace(serious, name, "check");
              }
              inc_mailgot(b->boardname);
              writemailflags();
              retwert = OK;
Example #24
0
/*
 * Dump passes 3 and 4.
 *
 * Dump the contents of an inode to tape.
 */
void
dumpino(union dinode *dp, ino_t ino)
{
	int ind_level, cnt;
	off_t size;
	char buf[TP_BSIZE];

	if (newtape) {
		newtape = 0;
		dumpmap(dumpinomap, TS_BITS, ino);
	}
	CLRINO(ino, dumpinomap);
	if (sblock->fs_magic == FS_UFS1_MAGIC) {
		spcl.c_mode = dp->dp1.di_mode;
		spcl.c_size = dp->dp1.di_size;
		spcl.c_old_atime = (time_t)dp->dp1.di_atime;
		spcl.c_atime = dp->dp1.di_atime;
		spcl.c_atimensec = dp->dp1.di_atimensec;
		spcl.c_old_mtime = (time_t)dp->dp1.di_mtime;
		spcl.c_mtime = dp->dp1.di_mtime;
		spcl.c_mtimensec = dp->dp1.di_mtimensec;
		spcl.c_birthtime = 0;
		spcl.c_birthtimensec = 0;
		spcl.c_rdev = dp->dp1.di_rdev;
		spcl.c_file_flags = dp->dp1.di_flags;
		spcl.c_uid = dp->dp1.di_uid;
		spcl.c_gid = dp->dp1.di_gid;
	} else {
		spcl.c_mode = dp->dp2.di_mode;
		spcl.c_size = dp->dp2.di_size;
		spcl.c_atime = dp->dp2.di_atime;
		spcl.c_atimensec = dp->dp2.di_atimensec;
		spcl.c_mtime = dp->dp2.di_mtime;
		spcl.c_mtimensec = dp->dp2.di_mtimensec;
		spcl.c_birthtime = dp->dp2.di_birthtime;
		spcl.c_birthtimensec = dp->dp2.di_birthnsec;
		spcl.c_rdev = dp->dp2.di_rdev;
		spcl.c_file_flags = dp->dp2.di_flags;
		spcl.c_uid = dp->dp2.di_uid;
		spcl.c_gid = dp->dp2.di_gid;
	}
	spcl.c_type = TS_INODE;
	spcl.c_count = 0;
	switch (DIP(dp, di_mode) & S_IFMT) {

	case 0:
		/*
		 * Freed inode.
		 */
		return;

	case IFLNK:
		/*
		 * Check for short symbolic link.
		 */
		if (DIP(dp, di_size) > 0 &&
#ifdef FS_44INODEFMT
		    (DIP(dp, di_size) < sblock->fs_maxsymlinklen ||
		     (sblock->fs_maxsymlinklen == 0 &&
			 DIP(dp, di_blocks) == 0))) {
#else
		    DIP(dp, di_blocks) == 0) {
#endif
			void *shortlink;

			spcl.c_addr[0] = 1;
			spcl.c_count = 1;
			writeheader(ino);
			if (sblock->fs_magic == FS_UFS1_MAGIC)
				shortlink = dp->dp1.di_shortlink;
			else
				shortlink = dp->dp2.di_shortlink;
			memcpy(buf, shortlink, DIP(dp, di_size));
			buf[DIP(dp, di_size)] = '\0';
			writerec(buf, 0);
			return;
		}
		/* FALLTHROUGH */

	case IFDIR:
	case IFREG:
		if (DIP(dp, di_size) > 0)
			break;
		/* FALLTHROUGH */

	case IFIFO:
	case IFSOCK:
	case IFCHR:
	case IFBLK:
		writeheader(ino);
		return;

	default:
		msg("Warning: undefined file type 0%o\n",
		    DIP(dp, di_mode) & IFMT);
		return;
	}
	if (DIP(dp, di_size) > NDADDR * sblock->fs_bsize)
		cnt = NDADDR * sblock->fs_frag;
	else
		cnt = howmany(DIP(dp, di_size), sblock->fs_fsize);
	if (sblock->fs_magic == FS_UFS1_MAGIC)
		ufs1_blksout(&dp->dp1.di_db[0], cnt, ino);
	else
		ufs2_blksout(&dp->dp2.di_db[0], cnt, ino);
	if ((size = DIP(dp, di_size) - NDADDR * sblock->fs_bsize) <= 0)
		return;
	for (ind_level = 0; ind_level < NIADDR; ind_level++) {
		dmpindir(ino, DIP(dp, di_ib[ind_level]), ind_level, &size);
		if (size <= 0)
			return;
	}
}
Example #25
0
/*
 * Dump passes 3 and 4.
 *
 * Dump the contents of an inode to tape.
 */
void
dumpino(struct ufs1_dinode *dp, ufs1_ino_t ino)
{
	int ind_level, cnt;
	fsizeT size;
	char buf[TP_BSIZE];

	if (newtape) {
		newtape = 0;
		dumpmap(dumpinomap, TS_BITS, ino);
	}
	CLRINO(ino, dumpinomap);
	spcl.c_dinode = *dp;
	spcl.c_type = TS_INODE;
	spcl.c_count = 0;
	switch (dp->di_mode & S_IFMT) {

	case 0:
		/*
		 * Freed inode.
		 */
		return;

	case S_IFLNK:
		/*
		 * Check for short symbolic link.
		 */
#ifdef FS_44INODEFMT
		if (dp->di_size > 0 &&
		    dp->di_size < (unsigned)sblock->fs_maxsymlinklen) {
			spcl.c_addr[0] = 1;
			spcl.c_count = 1;
			writeheader(ino);
			memmove(buf, dp->di_shortlink, (u_long)dp->di_size);
			buf[dp->di_size] = '\0';
			writerec(buf, 0);
			return;
		}
#endif
		/* fall through */

	case S_IFDIR:
	case S_IFREG:
		if (dp->di_size > 0)
			break;
		/* fall through */

	case S_IFIFO:
	case S_IFSOCK:
	case S_IFCHR:
	case S_IFBLK:
		writeheader(ino);
		return;

	default:
		msg("Warning: undefined file type 0%o\n", dp->di_mode & IFMT);
		return;
	}
	if (dp->di_size > NDADDR * (unsigned)sblock->fs_bsize)
		cnt = NDADDR * sblock->fs_frag;
	else
		cnt = howmany(dp->di_size, sblock->fs_fsize);
	blksout(&dp->di_db[0], cnt, ino);
	if ((size = dp->di_size - NDADDR * sblock->fs_bsize) <= 0)
		return;
	for (ind_level = 0; ind_level < NIADDR; ind_level++) {
		dmpindir(ino, dp->di_ib[ind_level], ind_level, &size);
		if (size <= 0)
			return;
	}
}
Example #26
0
int
main(int argc, char **argv)
{
	struct stat sb;
	ufs1_ino_t ino;
	int dirty;
	struct ufs1_dinode *dp;
	struct	fstab *dt;
	char *map;
	int ch;
	int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
	int just_estimate = 0;
	ufs1_ino_t maxino;

	spcl.c_date = 0;
	time((time_t *)&spcl.c_date);

	tsize = 0;	/* Default later, based on 'c' option for cart tapes */
	if ((tape = getenv("TAPE")) == NULL)
		tape = _PATH_DEFTAPE;
	dumpdates = _PATH_DUMPDATES;
	temp = _PATH_DTMP;
	if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
		quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
	level = '0';

	if (argc < 2)
		usage();

	obsolete(&argc, &argv);
#ifdef KERBEROS
#define optstring "0123456789aB:b:cd:f:h:kns:ST:uWwD:C:"
#else
#define optstring "0123456789aB:b:cd:f:h:ns:ST:uWwD:C:"
#endif
	while ((ch = getopt(argc, argv, optstring)) != -1)
#undef optstring
		switch (ch) {
		/* dump level */
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			level = ch;
			break;

		case 'a':		/* `auto-size', Write to EOM. */
			unlimited = 1;
			break;

		case 'B':		/* blocks per output file */
			blocksperfile = numarg("number of blocks per file",
			    1L, 0L);
			break;

		case 'b':		/* blocks per tape write */
			ntrec = numarg("number of blocks per write",
			    1L, 1000L);
			break;

		case 'c':		/* Tape is cart. not 9-track */
			cartridge = 1;
			break;

		case 'd':		/* density, in bits per inch */
			density = numarg("density", 10L, 327670L) / 10;
			if (density >= 625 && !bflag)
				ntrec = HIGHDENSITYTREC;
			break;

		case 'f':		/* output file */
			tape = optarg;
			break;

		case 'D':
			dumpdates = optarg;
			break;

		case 'C':
			cachesize = numarg("cachesize", 0, 0) * 1024 * 1024;
			break;

		case 'h':
			honorlevel = numarg("honor level", 0L, 10L);
			break;

#ifdef KERBEROS
		case 'k':
			dokerberos = 1;
			break;
#endif

		case 'n':		/* notify operators */
			notify = 1;
			break;

		case 's':		/* tape size, feet */
			tsize = numarg("tape size", 1L, 0L) * 12 * 10;
			break;

		case 'S':               /* exit after estimating # of tapes */
			just_estimate = 1;
			break;

		case 'T':		/* time of last dump */
			spcl.c_ddate = unctime(optarg);
			if (spcl.c_ddate < 0) {
				fprintf(stderr, "bad time \"%s\"\n", optarg);
				exit(X_STARTUP);
			}
			Tflag = 1;
			lastlevel = '?';
			break;

		case 'u':		/* update /etc/dumpdates */
			uflag = 1;
			break;

		case 'W':		/* what to do */
		case 'w':
			lastdump(ch);
			exit(X_FINOK);	/* do nothing else */

		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc < 1) {
		fprintf(stderr, "Must specify disk or filesystem\n");
		exit(X_STARTUP);
	}
	disk = *argv++;
	argc--;
	if (argc >= 1) {
		fprintf(stderr, "Unknown arguments to dump:");
		while (argc--)
			fprintf(stderr, " %s", *argv++);
		fprintf(stderr, "\n");
		exit(X_STARTUP);
	}
	if (Tflag && uflag) {
	        fprintf(stderr, "You cannot use the T and u flags together.\n");
		exit(X_STARTUP);
	}
	if (strcmp(tape, "-") == 0) {
		pipeout++;
		tape = "standard output";
	}

	if (blocksperfile)
		blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
	else if (!unlimited) {
		/*
		 * Determine how to default tape size and density
		 *
		 *         	density				tape size
		 * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
		 * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
		 * cartridge	8000 bpi (100 bytes/.1")	1700 ft.
		 *						(450*4 - slop)
		 * hilit19 hits again: "
		 */
		if (density == 0)
			density = cartridge ? 100 : 160;
		if (tsize == 0)
			tsize = cartridge ? 1700L*120L : 2300L*120L;
	}

	if (strchr(tape, ':')) {
		char *ehost;
		if ((host = strdup(tape)) == NULL)
			err(1, "strdup failed");
		ehost = strchr(host, ':');
		*ehost++ = '\0';
		tape = ehost;
#ifdef RDUMP
		if (strchr(tape, '\n')) {
		    fprintf(stderr, "invalid characters in tape\n");
		    exit(X_STARTUP);
		}
		if (rmthost(host) == 0)
			exit(X_STARTUP);
#else
		fprintf(stderr, "remote dump not enabled\n");
		exit(X_STARTUP);
#endif
	}
	setuid(getuid()); /* rmthost() is the only reason to be setuid */

	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, sig);
	if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
		signal(SIGTRAP, sig);
	if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
		signal(SIGFPE, sig);
	if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
		signal(SIGBUS, sig);
	if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
		signal(SIGSEGV, sig);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, sig);
	if (signal(SIGINT, interrupt) == SIG_IGN)
		signal(SIGINT, SIG_IGN);

	dump_getfstab();		/* /etc/fstab snarfed */
	/*
	 *	disk can be either the full special file name,
	 *	the suffix of the special file name,
	 *	the special name missing the leading '/',
	 *	the file system name with or without the leading '/'.
	 */
	dt = fstabsearch(disk);
	if (dt != NULL) {
		disk = rawname(dt->fs_spec);
		strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
		strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
	} else {
		strncpy(spcl.c_dev, disk, NAMELEN);
		strncpy(spcl.c_filesys, "an unlisted file system", NAMELEN);
	}
	spcl.c_dev[NAMELEN-1]='\0';
	spcl.c_filesys[NAMELEN-1]='\0';
	strcpy(spcl.c_label, "none");
	gethostname(spcl.c_host, NAMELEN);
	spcl.c_level = level - '0';
	spcl.c_type = TS_TAPE;
	if (!Tflag)
	        getdumptime();		/* /etc/dumpdates snarfed */

	msg("Date of this level %c dump: %s", level,
		spcl.c_date == 0 ? "the epoch\n" : ctime((const time_t *)&spcl.c_date));
 	msg("Date of last level %c dump: %s", lastlevel,
		spcl.c_ddate == 0 ? "the epoch\n" : ctime((const time_t *)&spcl.c_ddate));
	msg("Dumping %s ", disk);
	if (dt != NULL)
		msgtail("(%s) ", dt->fs_file);
	if (host)
		msgtail("to %s on host %s\n", tape, host);
	else
		msgtail("to %s\n", tape);

	if ((diskfd = open(disk, O_RDONLY)) < 0)
		err(X_STARTUP, "Cannot open %s", disk);
	if (fstat(diskfd, &sb) != 0)
		err(X_STARTUP, "%s: stat", disk);
	if (S_ISDIR(sb.st_mode))
		errx(X_STARTUP, "%s: unknown file system", disk);
	sync();
	sblock = (struct fs *)sblock_buf;
	bread(SBOFF, (char *) sblock, SBSIZE);
	if (sblock->fs_magic != FS_MAGIC)
		quit("bad sblock magic number\n");
	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
	dev_bshift = ffs(dev_bsize) - 1;
	if (dev_bsize != (1 << dev_bshift))
		quit("dev_bsize (%ld) is not a power of 2", dev_bsize);
	tp_bshift = ffs(TP_BSIZE) - 1;
	if (TP_BSIZE != (1 << tp_bshift))
		quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
#ifdef FS_44INODEFMT
	if (sblock->fs_inodefmt >= FS_44INODEFMT)
		spcl.c_flags |= DR_NEWINODEFMT;
#endif
	maxino = sblock->fs_ipg * sblock->fs_ncg;
	mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
	usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
	dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
	dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
	tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);

	nonodump = spcl.c_level < honorlevel;

	passno = 1;
	setproctitle("%s: pass 1: regular files", disk);
	msg("mapping (Pass I) [regular files]\n");
	anydirskipped = mapfiles(maxino, &tapesize);

	passno = 2;
	setproctitle("%s: pass 2: directories", disk);
	msg("mapping (Pass II) [directories]\n");
	while (anydirskipped) {
		anydirskipped = mapdirs(maxino, &tapesize);
	}

	if (pipeout || unlimited) {
		tapesize += 10;	/* 10 trailer blocks */
		msg("estimated %ld tape blocks.\n", tapesize);
	} else {
		double fetapes;

		if (blocksperfile)
			fetapes = (double) tapesize / blocksperfile;
		else if (cartridge) {
			/* Estimate number of tapes, assuming streaming stops at
			   the end of each block written, and not in mid-block.
			   Assume no erroneous blocks; this can be compensated
			   for with an artificially low tape size. */
			fetapes =
			(	  (double) tapesize	/* blocks */
				* TP_BSIZE	/* bytes/block */
				* (1.0/density)	/* 0.1" / byte " */
			  +
				  (double) tapesize	/* blocks */
				* (1.0/ntrec)	/* streaming-stops per block */
				* 15.48		/* 0.1" / streaming-stop " */
			) * (1.0 / tsize );	/* tape / 0.1" " */
		} else {
			/* Estimate number of tapes, for old fashioned 9-track
			   tape */
			int tenthsperirg = (density == 625) ? 3 : 7;
			fetapes =
			(	  (double) tapesize	/* blocks */
				* TP_BSIZE	/* bytes / block */
				* (1.0/density)	/* 0.1" / byte " */
			  +
				  (double) tapesize	/* blocks */
				* (1.0/ntrec)	/* IRG's / block */
				* tenthsperirg	/* 0.1" / IRG " */
			) * (1.0 / tsize );	/* tape / 0.1" " */
		}
		etapes = fetapes;		/* truncating assignment */
		etapes++;
		/* count the dumped inodes map on each additional tape */
		tapesize += (etapes - 1) *
			(howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
		tapesize += etapes + 10;	/* headers + 10 trailer blks */
		msg("estimated %ld tape blocks on %3.2f tape(s).\n",
		    tapesize, fetapes);
	}

        /*
         * If the user only wants an estimate of the number of
         * tapes, exit now.
         */
        if (just_estimate)
                exit(0);

	/*
	 * Allocate tape buffer.
	 */
	if (!alloctape())
		quit(
	"can't allocate tape buffers - try a smaller blocking factor.\n");

	startnewtape(1);
	time((time_t *)&(tstart_writing));
	dumpmap(usedinomap, TS_CLRI, maxino - 1);

	passno = 3;
	setproctitle("%s: pass 3: directories", disk);
	msg("dumping (Pass III) [directories]\n");
	dirty = 0;		/* XXX just to get gcc to shut up */
	for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
			dirty = *map++;
		else
			dirty >>= 1;
		if ((dirty & 1) == 0)
			continue;
		/*
		 * Skip directory inodes deleted and maybe reallocated
		 */
		dp = getino(ino);
		if ((dp->di_mode & IFMT) != IFDIR)
			continue;
		dumpino(dp, ino);
	}

	passno = 4;
	setproctitle("%s: pass 4: regular files", disk);
	msg("dumping (Pass IV) [regular files]\n");
	for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
		int mode;

		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
			dirty = *map++;
		else
			dirty >>= 1;
		if ((dirty & 1) == 0)
			continue;
		/*
		 * Skip inodes deleted and reallocated as directories.
		 */
		dp = getino(ino);
		mode = dp->di_mode & IFMT;
		if (mode == IFDIR)
			continue;
		dumpino(dp, ino);
	}

	time(&tend_writing);
	spcl.c_type = TS_END;
	for (i = 0; i < ntrec; i++)
		writeheader(maxino - 1);
	if (pipeout)
		msg("DUMP: %ld tape blocks\n", (long)spcl.c_tapea);
	else
		msg("DUMP: %ld tape blocks on %d volume%s\n",
		    (long)spcl.c_tapea, spcl.c_volume,
		    (spcl.c_volume == 1) ? "" : "s");

	/* report dump performance, avoid division through zero */
	if (tend_writing - tstart_writing == 0)
		msg("finished in less than a second\n");
	else
		msg("finished in %ld seconds, throughput %ld KBytes/sec\n",
		    (long)(tend_writing - tstart_writing),
		    spcl.c_tapea / (tend_writing - tstart_writing));

	putdumptime();
	trewind();
	broadcast("DUMP IS DONE!\a\a\n");
	msg("DUMP IS DONE\n");
	Exit(X_FINOK);
	/* NOTREACHED */
}
Example #27
0
int Crecompilateur::re(const char *outname, Cprogramlisting *plisting,
		       Copcodes *popcode_list, Crom_file *prom)
{
  FILE *fp;
  Instruction6502 *pinstr;
  bool            irqbrkvector = false;
  bool            nmivector = false;

  try
    {
      fp = fopen(outname, "w");
      if (fp == NULL)
	{
	  snprintf(m_error_str, sizeof(m_error_str),
		   "opening file %s failed", outname);
	  throw int(1);
	}
      //      fp = stdout;
      create_label_list(plisting, popcode_list);
      writeheader(fp);
      pinstr = plisting->get_next(true);
      while (pinstr != NULL)
	{
	  switch (pinstr->isvectorstart)
	    {
	    case resetstart:
	      // Label of the first instruction executed on start/reset
	      fprintf(fp, "NESReset:\n");
	      break;
	    case nmistart:
	      // Label of the non maskable interrupt routine
	      fprintf(fp, "NESNonMaskableInterrupt:\n");
	      nmivector = true;
	      break;
	    case irqbrkstart:
	      //
	      fprintf(fp, "NESIRQBRK:\n");
	      irqbrkvector = true;
	      break;
	    default:
	      break;
	    }
	  printlabel(fp, pinstr);
	  switch (isreplaced(pinstr, popcode_list))
	    {
	    case noreplace:
	      outinstr(fp, pinstr, popcode_list);
	      break;
	    case replaceIOPort:
	      outReplaceIOport(fp, pinstr, popcode_list);
	      break;
	    case replaceBackupRam:
	      //outReplaceBackupRam(fp, pinstr, popcode_list);
	      break;
	    case replaceJumpIndirect:
	      outReplaceJumpIndirect(fp, pinstr, popcode_list);
	      break;
	    default:
	      break;
	    };
	  pinstr = plisting->get_next(false);
	}
      fprintf(fp, "\n");
      if (!nmivector)
	{
	  fprintf(fp, "NESNonMaskableInterrupt:\n");
	  fprintf(fp, "\tjmp DebugHandler\n");
	}
      if (!irqbrkvector)
	{
	  fprintf(fp, "NESIRQBRK:\n");
	  fprintf(fp, "\tjmp DebugHandler\n");
	}
      fprintf(fp, "\n");
      // io port accesses are replaced by a jsr to a routine,
      // the routines are written here.
      writeiop_routines(fp, plisting, popcode_list);
      fprintf(fp, "\n.ENDS\n");
      fclose(fp);
    }
  catch (int e)
    {
      return 1;
    }
  return 0;
}
Example #28
0
int main(void) {
   FILE *tga;               // Pointer to a FILE
   targa_header header;     // Variable of targa_header type
   int x, y;
   int pix[3][900][900];

/* First, set all the fields in the header to appropriate values */
   header.id_len = 0;          /* no ID field */
   header.map_type = 0;        /* no colormap */
   header.img_type = 2;        /* trust me */
   header.map_first = 0;       /* not used */
   header.map_len = 0;         /* not used */
   header.map_entry_size = 0;  /* not used */
   header.x = 0;               /* image starts at (0,0) */
   header.y = 0;
   header.width = 900;         /* image is 200 x 100 */
   header.height = 900;
   header.bpp = 24;            /* 24 bits per pixel */
   header.misc = 0x20;         /* scan from upper left corner */

/* Open a file for writing targa data.  Call the file "test.tga" and
      write in binary mode (wb) so that nothing is lost as characters
      are written to the file */

int i;
   tga = fopen("test.tga", "wb"); /* Write the header information  */

   writeheader(header, tga);  

   /* Write the data for a graphic that measures 100 by 200 pixels. */

     for(y = 0; y < 100; y++)      // Create 100 Rows of Pixels 
      for(x = 0; x < 200; x++)   // Create 200 Pixels in each Row

       { /* For each pixel, write a character representing the RGB color.
            Notice that the order that is written to the file is B-G-R.
            This sequence just cycles through the colors in some pattern
            but all char values must be integers between 0 and 255. */
	for(i=0;i<3;i++){
		pix[i][x][y]=255;
       
	} 			  
       }



   for(y = 0; y < 900; y++)      // Create 100 Rows of Pixels 
      for(x = 0; x <900; x++)   // Create 200 Pixels in each Row

       { /* For each pixel, write a character representing the RGB color.
            Notice that the order that is written to the file is B-G-R.
            This sequence just cycles through the colors in some pattern
            but all char values must be integers between 0 and 255. */
	
        fputc((pix[0][x][y]) % 256, tga);               // Write char for BLUE            
        fputc(pix[0][x][y] %256, tga);   // Write char for GREEN
        fputc(pix[0][x][y] %256, tga);               // Write char for RED
       }

/* close the file */
   fclose(tga);

/* that was easy, right? */
   return 0;
}
Example #29
0
/* chop_write() writes chunks of data not larger than CURL_MAX_WRITE_SIZE via
 * client write callback(s) and takes care of pause requests from the
 * callbacks.
 */
static CURLcode chop_write(struct connectdata *conn,
                           int type,
                           char *optr,
                           size_t olen)
{
  struct Curl_easy *data = conn->data;
  curl_write_callback writeheader = NULL;
  curl_write_callback writebody = NULL;
  char *ptr = optr;
  size_t len = olen;

  if(!len)
    return CURLE_OK;

  /* If reading is paused, append this data to the already held data for this
     type. */
  if(data->req.keepon & KEEP_RECV_PAUSE)
    return pausewrite(data, type, ptr, len);

  /* Determine the callback(s) to use. */
  if(type & CLIENTWRITE_BODY)
    writebody = data->set.fwrite_func;
  if((type & CLIENTWRITE_HEADER) &&
     (data->set.fwrite_header || data->set.writeheader)) {
    /*
     * Write headers to the same callback or to the especially setup
     * header callback function (added after version 7.7.1).
     */
    writeheader =
      data->set.fwrite_header? data->set.fwrite_header: data->set.fwrite_func;
  }

  /* Chop data, write chunks. */
  while(len) {
    size_t chunklen = len <= CURL_MAX_WRITE_SIZE? len: CURL_MAX_WRITE_SIZE;

    if(writebody) {
      size_t wrote = writebody(ptr, 1, chunklen, data->set.out);

      if(CURL_WRITEFUNC_PAUSE == wrote) {
        if(conn->handler->flags & PROTOPT_NONETWORK) {
          /* Protocols that work without network cannot be paused. This is
             actually only FILE:// just now, and it can't pause since the
             transfer isn't done using the "normal" procedure. */
          failf(data, "Write callback asked for PAUSE when not supported!");
          return CURLE_WRITE_ERROR;
        }
        return pausewrite(data, type, ptr, len);
      }
      if(wrote != chunklen) {
        failf(data, "Failed writing body (%zu != %zu)", wrote, chunklen);
        return CURLE_WRITE_ERROR;
      }
    }

    ptr += chunklen;
    len -= chunklen;
  }

  if(writeheader) {
    size_t wrote;
    ptr = optr;
    len = olen;
    Curl_set_in_callback(data, true);
    wrote = writeheader(ptr, 1, len, data->set.writeheader);
    Curl_set_in_callback(data, false);

    if(CURL_WRITEFUNC_PAUSE == wrote)
      /* here we pass in the HEADER bit only since if this was body as well
         then it was passed already and clearly that didn't trigger the
         pause, so this is saved for later with the HEADER bit only */
      return pausewrite(data, CLIENTWRITE_HEADER, ptr, len);

    if(wrote != len) {
      failf(data, "Failed writing header");
      return CURLE_WRITE_ERROR;
    }
  }

  return CURLE_OK;
}
Example #30
0
int
main(int argc, char *argv[])
{
	ino_t ino;
	int dirty;
	union dinode *dp;
	struct	fstab *dt;
	char *map;
	int ch, mode;
	struct tm then;
	struct statfs fsbuf;
	int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
	ino_t maxino;
	time_t t;
	int dirlist;
	char *toplevel, *str, *mount_point = NULL;

	spcl.c_date = (int64_t)time(NULL);

	tsize = 0;	/* Default later, based on 'c' option for cart tapes */
	if ((tape = getenv("TAPE")) == NULL)
		tape = _PATH_DEFTAPE;
	dumpdates = _PATH_DUMPDATES;
	temp = _PATH_DTMP;
	if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
		quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
	level = '0';

	if (argc < 2)
		usage();

	obsolete(&argc, &argv);
	while ((ch = getopt(argc, argv, "0123456789aB:b:cd:f:h:ns:T:uWw")) != -1)
		switch (ch) {
		/* dump level */
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			level = ch;
			break;

		case 'B':		/* blocks per output file */
			blocksperfile = numarg("blocks per file", 1L, 0L);
			break;

		case 'b':		/* blocks per tape write */
			ntrec = numarg("blocks per write", 1L, 1000L);
			if (ntrec > maxbsize/1024) {
				msg("Please choose a blocksize <= %dKB\n",
				    maxbsize/1024);
				exit(X_STARTUP);
			}
			bflag = 1;
			break;

		case 'c':		/* Tape is cart. not 9-track */
			cartridge = 1;
			break;

		case 'd':		/* density, in bits per inch */
			density = numarg("density", 10L, 327670L) / 10;
			if (density >= 625 && !bflag)
				ntrec = HIGHDENSITYTREC;
			break;

		case 'f':		/* output file */
			tape = optarg;
			break;

		case 'h':
			honorlevel = numarg("honor level", 0L, 10L);
			break;

		case 'n':		/* notify operators */
			notify = 1;
			break;

		case 's':		/* tape size, feet */
			tsize = numarg("tape size", 1L, 0L) * 12 * 10;
			break;

		case 'T':		/* time of last dump */
			str = strptime(optarg, "%a %b %e %H:%M:%S %Y", &then);
			then.tm_isdst = -1;
			if (str == NULL || (*str != '\n' && *str != '\0'))
				spcl.c_ddate = -1;
			else
				spcl.c_ddate = (int64_t)mktime(&then);
			if (spcl.c_ddate < 0) {
				(void)fprintf(stderr, "bad time \"%s\"\n",
				    optarg);
				exit(X_STARTUP);
			}
			Tflag = 1;
			lastlevel = '?';
			break;

		case 'u':		/* update /etc/dumpdates */
			uflag = 1;
			break;

		case 'W':		/* what to do */
		case 'w':
			lastdump(ch);
			exit(X_FINOK);	/* do nothing else */
			break;

		case 'a':		/* `auto-size', Write to EOM. */
			unlimited = 1;
			break;

		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc < 1) {
		(void)fprintf(stderr, "Must specify disk or filesystem\n");
		exit(X_STARTUP);
	}

	/*
	 *	determine if disk is a subdirectory, and setup appropriately
	 */
	dirlist = 0;
	toplevel = NULL;
	for (i = 0; i < argc; i++) {
		struct stat sb;

		if (lstat(argv[i], &sb) == -1) {
			msg("Cannot lstat %s: %s\n", argv[i], strerror(errno));
			exit(X_STARTUP);
		}
		if (!S_ISDIR(sb.st_mode) && !S_ISREG(sb.st_mode))
			break;
		if (statfs(argv[i], &fsbuf) == -1) {
			msg("Cannot statfs %s: %s\n", argv[i], strerror(errno));
			exit(X_STARTUP);
		}
		if (strcmp(argv[i], fsbuf.f_mntonname) == 0) {
			if (dirlist != 0) {
				msg("Can't dump a mountpoint and a filelist\n");
				exit(X_STARTUP);
			}
			break;		/* exit if sole mountpoint */
		}
		if (!disk) {
			if ((toplevel = strdup(fsbuf.f_mntonname)) == NULL) {
				msg("Cannot malloc diskname\n");
				exit(X_STARTUP);
			}
			disk = toplevel;
			if (uflag) {
				msg("Ignoring u flag for subdir dump\n");
				uflag = 0;
			}
			if (level > '0') {
				msg("Subdir dump is done at level 0\n");
				level = '0';
			}
			msg("Dumping sub files/directories from %s\n", disk);
		} else {
			if (strcmp(disk, fsbuf.f_mntonname) != 0) {
				msg("%s is not on %s\n", argv[i], disk);
				exit(X_STARTUP);
			}
		}
		msg("Dumping file/directory %s\n", argv[i]);
		dirlist++;
	}
	if (dirlist == 0) {
		disk = *argv++;
		if (argc != 1) {
			(void)fputs("Excess arguments to dump:", stderr);
			while (--argc) {
				(void)putc(' ', stderr);
				(void)fputs(*argv++, stderr);
			}
			(void)putc('\n', stderr);
			exit(X_STARTUP);
		}
	}
	if (Tflag && uflag) {
	        (void)fprintf(stderr,
		    "You cannot use the T and u flags together.\n");
		exit(X_STARTUP);
	}
	if (strcmp(tape, "-") == 0) {
		pipeout++;
		tape = "standard output";
	}

	if (blocksperfile)
		blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
	else if (!unlimited) {
		/*
		 * Determine how to default tape size and density
		 *
		 *         	density				tape size
		 * 9-track	1600 bpi (160 bytes/.1")	2300 ft.
		 * 9-track	6250 bpi (625 bytes/.1")	2300 ft.
		 * cartridge	8000 bpi (100 bytes/.1")	1700 ft.
		 *						(450*4 - slop)
		 */
		if (density == 0)
			density = cartridge ? 100 : 160;
		if (tsize == 0)
			tsize = cartridge ? 1700L*120L : 2300L*120L;
	}

	if (strchr(tape, ':')) {
		host = tape;
		tape = strchr(host, ':');
		*tape++ = '\0';
#ifdef RDUMP
		if (rmthost(host) == 0)
			exit(X_STARTUP);
#else
		(void)fprintf(stderr, "remote dump not enabled\n");
		exit(X_STARTUP);
#endif
	}

	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, sig);
	if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
		signal(SIGTRAP, sig);
	if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
		signal(SIGFPE, sig);
	if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
		signal(SIGBUS, sig);
	if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
		signal(SIGSEGV, sig);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, sig);
	if (signal(SIGINT, interrupt) == SIG_IGN)
		signal(SIGINT, SIG_IGN);

	getfstab();		/* /etc/fstab snarfed */

	/*
	 *	disk can be either the full special file name,
	 *	the suffix of the special file name,
	 *	the special name missing the leading '/',
	 *	the file system name with or without the leading '/'.
	 */
	if (!statfs(disk, &fsbuf) && !strcmp(fsbuf.f_mntonname, disk)) {
		/* mounted disk? */
		disk = rawname(fsbuf.f_mntfromname);
		if (!disk) {
			(void)fprintf(stderr, "cannot get raw name for %s\n",
			    fsbuf.f_mntfromname);
			exit(X_STARTUP);
		}
		mount_point = fsbuf.f_mntonname;
		(void)strlcpy(spcl.c_dev, fsbuf.f_mntfromname,
		    sizeof(spcl.c_dev));
		if (dirlist != 0) {
			(void)snprintf(spcl.c_filesys, sizeof(spcl.c_filesys),
			    "a subset of %s", mount_point);
		} else {
			(void)strlcpy(spcl.c_filesys, mount_point,
			    sizeof(spcl.c_filesys));
		}
	} else if ((dt = fstabsearch(disk)) != NULL) {
		/* in fstab? */
		disk = rawname(dt->fs_spec);
		mount_point = dt->fs_file;
		(void)strlcpy(spcl.c_dev, dt->fs_spec, sizeof(spcl.c_dev));
		if (dirlist != 0) {
			(void)snprintf(spcl.c_filesys, sizeof(spcl.c_filesys),
			    "a subset of %s", mount_point);
		} else {
			(void)strlcpy(spcl.c_filesys, mount_point,
			    sizeof(spcl.c_filesys));
		}
	} else {
		/* must be a device */
		(void)strlcpy(spcl.c_dev, disk, sizeof(spcl.c_dev));
		(void)strlcpy(spcl.c_filesys, "an unlisted file system",
		    sizeof(spcl.c_filesys));
	}
	(void)strlcpy(spcl.c_label, "none", sizeof(spcl.c_label));
	(void)gethostname(spcl.c_host, sizeof(spcl.c_host));
	spcl.c_level = level - '0';
	spcl.c_type = TS_TAPE;
	if (!Tflag)
	        getdumptime();		/* /etc/dumpdates snarfed */

	t = (time_t)spcl.c_date;
	msg("Date of this level %c dump: %s", level,
		t == 0 ? "the epoch\n" : ctime(&t));
	t = (time_t)spcl.c_ddate;
 	msg("Date of last level %c dump: %s", lastlevel,
		t == 0 ? "the epoch\n" : ctime(&t));
	msg("Dumping %s ", disk);
	if (mount_point != NULL)
		msgtail("(%s) ", mount_point);
	if (host)
		msgtail("to %s on host %s\n", tape, host);
	else
		msgtail("to %s\n", tape);

	if ((diskfd = open(disk, O_RDONLY)) < 0) {
		msg("Cannot open %s\n", disk);
		exit(X_STARTUP);
	}
	sync();
	sblock = (struct fs *)sblock_buf;
	for (i = 0; sblock_try[i] != -1; i++) {
		ssize_t n = pread(diskfd, sblock, SBLOCKSIZE,
		    (off_t)sblock_try[i]);
		if (n == SBLOCKSIZE && (sblock->fs_magic == FS_UFS1_MAGIC ||
		     (sblock->fs_magic == FS_UFS2_MAGIC &&
		      sblock->fs_sblockloc == sblock_try[i])) &&
		    sblock->fs_bsize <= MAXBSIZE &&
		    sblock->fs_bsize >= sizeof(struct fs))
			break;
	}
	if (sblock_try[i] == -1)
		quit("Cannot find filesystem superblock\n");
	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
	dev_bshift = ffs(dev_bsize) - 1;
	if (dev_bsize != (1 << dev_bshift))
		quit("dev_bsize (%d) is not a power of 2\n", dev_bsize);
	tp_bshift = ffs(TP_BSIZE) - 1;
	if (TP_BSIZE != (1 << tp_bshift))
		quit("TP_BSIZE (%d) is not a power of 2\n", TP_BSIZE);
#ifdef FS_44INODEFMT
	if (sblock->fs_magic == FS_UFS2_MAGIC ||
	    sblock->fs_inodefmt >= FS_44INODEFMT)
		spcl.c_flags |= DR_NEWINODEFMT;
#endif
	maxino = sblock->fs_ipg * sblock->fs_ncg;
	mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
	usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
	dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
	dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
	tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);

	nonodump = spcl.c_level < honorlevel;

	(void)signal(SIGINFO, statussig);

	msg("mapping (Pass I) [regular files]\n");
	anydirskipped = mapfiles(maxino, &tapesize, toplevel,
	    (dirlist ? argv : NULL));

	msg("mapping (Pass II) [directories]\n");
	while (anydirskipped) {
		anydirskipped = mapdirs(maxino, &tapesize);
	}

	if (pipeout || unlimited) {
		tapesize += 10;	/* 10 trailer blocks */
		msg("estimated %lld tape blocks.\n", tapesize);
	} else {
		double fetapes;

		if (blocksperfile)
			fetapes = (double) tapesize / blocksperfile;
		else if (cartridge) {
			/* Estimate number of tapes, assuming streaming stops at
			   the end of each block written, and not in mid-block.
			   Assume no erroneous blocks; this can be compensated
			   for with an artificially low tape size. */
			fetapes =
			(	  tapesize	/* blocks */
				* TP_BSIZE	/* bytes/block */
				* (1.0/density)	/* 0.1" / byte */
			  +
				  tapesize	/* blocks */
				* (1.0/ntrec)	/* streaming-stops per block */
				* 15.48		/* 0.1" / streaming-stop */
			) * (1.0 / tsize );	/* tape / 0.1" */
		} else {
			/* Estimate number of tapes, for old fashioned 9-track
			   tape */
			int tenthsperirg = (density == 625) ? 3 : 7;
			fetapes =
			(	  tapesize	/* blocks */
				* TP_BSIZE	/* bytes / block */
				* (1.0/density)	/* 0.1" / byte */
			  +
				  tapesize	/* blocks */
				* (1.0/ntrec)	/* IRG's / block */
				* tenthsperirg	/* 0.1" / IRG */
			) * (1.0 / tsize );	/* tape / 0.1" */
		}
		etapes = fetapes;		/* truncating assignment */
		etapes++;
		/* count the dumped inodes map on each additional tape */
		tapesize += (etapes - 1) *
			(howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
		tapesize += etapes + 10;	/* headers + 10 trailer blks */
		msg("estimated %lld tape blocks on %3.2f tape(s).\n",
		    tapesize, fetapes);
	}

	/*
	 * Allocate tape buffer.
	 */
	if (!alloctape())
		quit("can't allocate tape buffers - try a smaller blocking factor.\n");

	startnewtape(1);
	(void)time((time_t *)&(tstart_writing));
	xferrate = 0;
	dumpmap(usedinomap, TS_CLRI, maxino - 1);

	msg("dumping (Pass III) [directories]\n");
	dirty = 0;		/* XXX just to get gcc to shut up */
	for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
			dirty = *map++;
		else
			dirty >>= 1;
		if ((dirty & 1) == 0)
			continue;
		/*
		 * Skip directory inodes deleted and maybe reallocated
		 */
		dp = getino(ino, &mode);
		if (mode != IFDIR)
			continue;
		(void)dumpino(dp, ino);
	}

	msg("dumping (Pass IV) [regular files]\n");
	for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
		if (((ino - 1) % NBBY) == 0)	/* map is offset by 1 */
			dirty = *map++;
		else
			dirty >>= 1;
		if ((dirty & 1) == 0)
			continue;
		/*
		 * Skip inodes deleted and reallocated as directories.
		 */
		dp = getino(ino, &mode);
		if (mode == IFDIR)
			continue;
		(void)dumpino(dp, ino);
	}

	spcl.c_type = TS_END;
	for (i = 0; i < ntrec; i++)
		writeheader(maxino - 1);
	if (pipeout)
		msg("%lld tape blocks\n", spcl.c_tapea);
	else
		msg("%lld tape blocks on %d volume%s\n",
		    spcl.c_tapea, spcl.c_volume,
		    (spcl.c_volume == 1) ? "" : "s");
	t = (time_t)spcl.c_date;
	msg("Date of this level %c dump: %s", level,
	    t == 0 ? "the epoch\n" : ctime(&t));
	t = do_stats();
	msg("Date this dump completed:  %s", ctime(&t));
	msg("Average transfer rate: %ld KB/s\n", xferrate / tapeno);
	putdumptime();
	trewind();
	broadcast("DUMP IS DONE!\7\7\n");
	msg("DUMP IS DONE\n");
	Exit(X_FINOK);
	/* NOTREACHED */
}