Exemple #1
0
/*
 * This routine will turn the sftmp() file into a real /tmp file or pipe
 */
void	sh_subtmpfile(int pflag)
{
	Shell_t *shp = &sh;
	int fds[2];
	Sfoff_t off;
	register struct checkpt	*pp = (struct checkpt*)shp->jmplist;
	register struct subshell *sp = subshell_data->pipe;
	if(sfset(sfstdout,0,0)&SF_STRING)
	{
		register int fd;
		/* save file descriptor 1 if open */
		if((sp->tmpfd = fd = fcntl(1,F_DUPFD,10)) >= 0)
		{
			fcntl(fd,F_SETFD,FD_CLOEXEC);
			shp->fdstatus[fd] = shp->fdstatus[1]|IOCLEX;
			close(1);
			shp->fdstatus[1] = IOCLOSE;
		}
		else if(errno!=EBADF)
		{
			((struct checkpt*)shp->jmplist)->mode = SH_JMPERREXIT;
			shp->toomany = 1;
			errormsg(SH_DICT,ERROR_system(1),e_toomany);
		}
		if(shp->subshare || !pflag)
		{
			sfdisc(sfstdout,SF_POPDISC);
			if((fd=sffileno(sfstdout))>=0)
			{
				shp->fdstatus[fd] = IOREAD|IOWRITE;
				sfsync(sfstdout);
				if(fd==1)
					fcntl(1,F_SETFD,0);
				else
				{
					sfsetfd(sfstdout,1);
					shp->fdstatus[1] = shp->fdstatus[fd];
					shp->fdstatus[fd] = IOCLOSE;
				}
				goto skip;
			}
		}
	}
	if(sp && (shp->fdstatus[1]==IOCLOSE || (!shp->subshare && !(shp->fdstatus[1]&IONOSEEK))))
	{
		struct stat statb,statx;
		int fd;
		sh_pipe(fds);
		sp->pipefd = fds[0];
		sh_fcntl(sp->pipefd,F_SETFD,FD_CLOEXEC);
		/* write the data to the pipe */
		if(off = sftell(sfstdout))
		{
			write(fds[1],sfsetbuf(sfstdout,(Void_t*)sfstdout,0),(size_t)off);
			sfpurge(sfstdout);
		}
		if((sfset(sfstdout,0,0)&SF_STRING) || fstat(1,&statb)<0)
			statb.st_ino = 0;
		sfclose(sfstdout);
		if((sh_fcntl(fds[1],F_DUPFD, 1)) != 1)
			errormsg(SH_DICT,ERROR_system(1),e_redirect);
		sh_close(fds[1]);
		if(statb.st_ino) for(fd=0; fd < 10; fd++)
		{
			if(fd==1 || ((shp->fdstatus[fd]&(IONOSEEK|IOSEEK|IOWRITE))!=(IOSEEK|IOWRITE)) || fstat(fd,&statx)<0)
				continue;
			if(statb.st_ino==statx.st_ino && statb.st_dev==statx.st_dev)
			{
				sh_close(fd);
				fcntl(1,F_DUPFD, fd);
			}
		}
	skip:
		sh_iostream(shp,1);
		sfset(sfstdout,SF_SHARE|SF_PUBLIC,1);
		sfpool(sfstdout,shp->outpool,SF_WRITE);
		if(pp && pp->olist  && pp->olist->strm == sfstdout)
			pp->olist->strm = 0;
	}
}
Exemple #2
0
static int
spliceline(Sfio_t* s, int op, void* val, Sfdisc_t* ad)
{
	Splice_t*	d = (Splice_t*)ad;
	register char*	b;
	register int	c;
	register int	n;
	register int	q;
	register int	j;
	register char*	e;
	char*		buf;

	NoP(val);
	switch (op)
	{
	case SF_CLOSING:
		sfclose(d->sp);
		return 0;
	case SF_DPOP:
		free(d);
		return 0;
	case SF_READ:
		do
		{
			if (!(buf = sfgetr(d->sp, '\n', 0)) && !(buf = sfgetr(d->sp, '\n', -1)))
				return 0;
			n = sfvalue(d->sp);
			q = d->quote;
			j = 0;
			(*d->line)++;
			if (n > 1 && buf[n - 2] == '\\')
			{
				j = 1;
				n -= 2;
				if (q == '#')
				{
					n = 0;
					continue;
				}
			}
			else if (q == '#')
			{
				q = 0;
				n = 0;
				continue;
			}
			if (n > 0)
			{
				e = (b = buf) + n;
				while (b < e)
				{
					if ((c = *b++) == '\\')
						b++;
					else if (c == q)
						q = 0;
					else if (!q)
					{
						if (c == '\'' || c == '"')
							q = c;
						else if (c == '#' && (b == (buf + 1) || (c = *(b - 2)) == ' ' || c == '\t'))
						{
							if (buf[n - 1] != '\n')
							{
								q = '#';
								n = b - buf - 2;
							}
							else if (n = b - buf - 1)
								buf[n - 1] = '\n';
							break;
						}
					}
				}
				if (n > 0)
				{
					if (!j && buf[n - 1] != '\n' && (s->_flags & SF_STRING))
						buf[n++] = '\n';
					if (q && buf[n - 1] == '\n')
						buf[n - 1] = '\r';
				}
			}
		} while (n <= 0);
		sfsetbuf(s, buf, n);
		d->quote = q;
		return 1;
	default:
		return 0;
	}
}
Exemple #3
0
int	b_hist(int argc,char *argv[], void *extra)
{
	register History_t *hp;
	register char *arg;
	register int flag,fdo;
	register Shell_t *shp = ((Shbltin_t*)extra)->shp;
	Sfio_t *outfile;
	char *fname;
	int range[2], incr, index2, indx= -1;
	char *edit = 0;		/* name of editor */
	char *replace = 0;		/* replace old=new */
	int lflag = 0, nflag = 0, rflag = 0;
#if SHOPT_HISTEXPAND
	int pflag = 0;
#endif
	Histloc_t location;
	NOT_USED(argc);
	if(!sh_histinit((void*)shp))
		errormsg(SH_DICT,ERROR_system(1),e_histopen);
	hp = shp->gd->hist_ptr;
	while((flag = optget(argv,sh_opthist))) switch(flag)
	{
	    case 'e':
		edit = opt_info.arg;
		break;
	    case 'n':
		nflag++;
		break;
	    case 'l':
		lflag++;
		break;
	    case 'r':
		rflag++;
		break;
	    case 's':
		edit = "-";
		break;
#if SHOPT_HISTEXPAND
	    case 'p':
		pflag++;
		break;
#endif
	    case 'N':
		if(indx<=0)
		{
			if((flag = hist_max(hp) - opt_info.num-1) < 0)
				flag = 1;
			range[++indx] = flag;
			break;
		}
	    case ':':
		errormsg(SH_DICT,2, "%s", opt_info.arg);
		break;
	    case '?':
		errormsg(SH_DICT,ERROR_usage(2), "%s", opt_info.arg);
		break;
	}
	if(error_info.errors)
		errormsg(SH_DICT,ERROR_usage(2),"%s",optusage((char*)0));
	argv += (opt_info.index-1);
#if SHOPT_HISTEXPAND
	if(pflag)
	{
		hist_cancel(hp);
		pflag = 0;
		while(arg=argv[1])
		{
			flag = hist_expand(arg,&replace);
			if(!(flag & HIST_ERROR))
				sfputr(sfstdout, replace, '\n');
			else
				pflag = 1;
			if(replace)
				free(replace);
			argv++;
		}
		return pflag;
	}
#endif
	flag = indx;
	while(flag<1 && (arg=argv[1]))
	{
		/* look for old=new argument */
		if(!replace && strchr(arg+1,'='))
		{
			replace = arg;
			argv++;
			continue;
		}
		else if(isdigit(*arg) || *arg == '-')
		{
			/* see if completely numeric */
			do	arg++;
			while(isdigit(*arg));
			if(*arg==0)
			{
				arg = argv[1];
				range[++flag] = (int)strtol(arg, (char**)0, 10);
				if(*arg == '-')
					range[flag] += (hist_max(hp)-1);
				argv++;
				continue;
			}
		}
		/* search for last line starting with string */
		location = hist_find(hp,argv[1],hist_max(hp)-1,0,-1);
		if((range[++flag] = location.hist_command) < 0)
			errormsg(SH_DICT,ERROR_exit(1),e_found,argv[1]);
		argv++;
	}
	if(flag <0)
	{
		/* set default starting range */
		if(lflag)
		{
			flag = hist_max(hp)-16;
			if(flag<1)
				flag = 1;
		}
		else
			flag = hist_max(hp)-2;
		range[0] = flag;
		flag = 0;
	}
	index2 = hist_min(hp);
	if(range[0]<index2)
		range[0] = index2;
	if(flag==0)
		/* set default termination range */
		range[1] = ((lflag && !edit)?hist_max(hp)-1:range[0]);
	if(range[1]>=(flag=(hist_max(hp) - !lflag)))
		range[1] = flag;
	/* check for valid ranges */
	if(range[1]<index2 || range[0]>=flag)
		errormsg(SH_DICT,ERROR_exit(1),e_badrange,range[0],range[1]);
	if(edit && *edit=='-' && range[0]!=range[1])
		errormsg(SH_DICT,ERROR_exit(1),e_eneedsarg);
	/* now list commands from range[rflag] to range[1-rflag] */
	incr = 1;
	flag = rflag>0;
	if(range[1-flag] < range[flag])
		incr = -1;
	if(lflag)
	{
		outfile = sfstdout;
		arg = "\n\t";
	}
	else
	{
		if(!(fname=pathtmp(NIL(char*),0,0,NIL(int*))))
			errormsg(SH_DICT,ERROR_exit(1),e_create,"");
		if((fdo=open(fname,O_CREAT|O_RDWR,S_IRUSR|S_IWUSR)) < 0)
			errormsg(SH_DICT,ERROR_system(1),e_create,fname);
		outfile= sfnew(NIL(Sfio_t*),shp->outbuff,IOBSIZE,fdo,SF_WRITE);
		arg = "\n";
		nflag++;
	}
	while(1)
	{
		if(nflag==0)
			sfprintf(outfile,"%d\t",range[flag]);
		else if(lflag)
			sfputc(outfile,'\t');
		hist_list(shp->gd->hist_ptr,outfile,hist_tell(shp->gd->hist_ptr,range[flag]),0,arg);
		if(lflag)
			sh_sigcheck(shp);
		if(range[flag] == range[1-flag])
			break;
		range[flag] += incr;
	}
	if(lflag)
		return(0);
	sfclose(outfile);
	hist_eof(hp);
	arg = edit;
	if(!arg && !(arg=nv_getval(sh_scoped(shp,HISTEDIT))) && !(arg=nv_getval(sh_scoped(shp,FCEDNOD))))
		arg = (char*)e_defedit;
#ifdef apollo
	/*
	 * Code to support the FC using the pad editor.
	 * Exampled of how to use: HISTEDIT=pad
	 */
	if (strcmp (arg, "pad") == 0)
	{
		extern int pad_create(char*);
		sh_close(fdo);
		fdo = pad_create(fname);
		pad_wait(fdo);
		unlink(fname);
		strcat(fname, ".bak");
		unlink(fname);
		lseek(fdo,(off_t)0,SEEK_SET);
	}
	else
	{
#endif /* apollo */
	if(*arg != '-')
	{
		char *com[3];
		com[0] =  arg;
		com[1] =  fname;
		com[2] = 0;
		error_info.errors = sh_eval(sh_sfeval(com),0);
	}
	fdo = sh_chkopen(fname);
	unlink(fname);
	free((void*)fname);
#ifdef apollo
	}
#endif /* apollo */
	/* don't history fc itself unless forked */
	error_info.flags |= ERROR_SILENT;
	if(!sh_isstate(SH_FORKED))
		hist_cancel(hp);
	sh_onstate(SH_HISTORY);
	sh_onstate(SH_VERBOSE);	/* echo lines as read */
	if(replace)
		hist_subst(error_info.id,fdo,replace);
	else if(error_info.errors == 0)
	{
		char buff[IOBSIZE+1];
		Sfio_t *iop = sfnew(NIL(Sfio_t*),buff,IOBSIZE,fdo,SF_READ);
		/* read in and run the command */
		if(shp->hist_depth++ > HIST_RECURSE)
			errormsg(SH_DICT,ERROR_exit(1),e_toodeep,"history");
		sh_eval(iop,1);
		shp->hist_depth--;
	}
Exemple #4
0
int main(int argc, char** argv) {
  P_t              *pads;
  Pdisc_t           my_disc = Pdefault_disc;
  Pio_disc_t       *io_disc = 0;
  Ppos_t            bpos, epos;
  PADS_TY( )        rep;
  PADS_TY(_pd)      pd;
  PADS_TY(_m)       m;
#ifdef PADS_HDR_TY
  PADS_HDR_TY( )    hdr_rep;
  PADS_HDR_TY(_pd)  hdr_pd;
  PADS_HDR_TY(_m)   hdr_m;
#endif /* PADS_HDR_TY */
  Sfio_t           *io;
  char             *inName  = 0;
  char             *outName = 0;
  
#ifdef E_REP_LEV
  my_disc.e_rep = E_REP_LEV;
#endif
#ifdef PRE_LIT_LWS
  my_disc.pre_lit_lws = PRE_LIT_LWS;
#endif
#ifdef WSPACE_OK
  my_disc.flags |= (Pflags_t)P_WSPACE_OK;
#endif
#ifdef COPY_STRINGS
  my_disc.copy_strings = 1;
#endif
#ifdef IN_TIME_ZONE
  my_disc.in_time_zone = IN_TIME_ZONE;
  error(0, "Note: set my_disc.in_time_zone to \"%s\"\n", IN_TIME_ZONE);
#endif
#ifdef OUT_TIME_ZONE
  my_disc.out_time_zone = OUT_TIME_ZONE;
  error(0, "Note: set my_disc.out_time_zone to \"%s\"\n", OUT_TIME_ZONE);
#endif

#ifdef TIMESTAMP_IN_FMT
  my_disc.in_formats.timestamp = TIMESTAMP_IN_FMT;
#endif
#ifdef DATE_IN_FMT
  my_disc.in_formats.date = DATE_IN_FMT;
#endif
#ifdef TIME_IN_FMT
  my_disc.in_formats.time = TIME_IN_FMT;
#endif

#ifdef TIMESTAMP_EXPLICIT_OUT_FMT
  my_disc.out_formats.timestamp_explicit = TIMESTAMP_EXPLICIT_OUT_FMT;
#endif
#ifdef TIMESTAMP_OUT_FMT
  my_disc.out_formats.timestamp = TIMESTAMP_OUT_FMT;
#endif
#ifdef DATE_EXPLICIT_OUT_FMT
  my_disc.out_formats.date_explicit = DATE_EXPLICIT_OUT_FMT;
#endif
#ifdef DATE_OUT_FMT
  my_disc.out_formats.date = DATE_OUT_FMT;
#endif
#ifdef TIME_EXPLICIT_OUT_FMT
  my_disc.out_formats.time_explicit = TIME_EXPLICIT_OUT_FMT;
#endif
#ifdef TIME_OUT_FMT
  my_disc.out_formats.time = TIME_OUT_FMT;
#endif

#ifdef IO_DISC_MK
  if (!(io_disc = IO_DISC_MK)) {
    error(ERROR_FATAL, "IO discipline make call [ " PDCI_MacroArg2String(IO_DISC_MK) " ] failed");
  }
#ifdef IO_DISC_DESCR
  else { 
    error(0, "Installed " IO_DISC_DESCR);
  }
#endif
#endif

  if (argc >= 2) {
    inName = argv[1];
  } else {
    inName = DEF_INPUT_FILE;
  }
  error(0, "Input file = %s\n", inName);
  if (argc == 3) {
    outName = argv[2];
  } else {
    outName = DEF_OUTPUT_FILE;
  }
  error(0, "Output file = %s\n", outName);
  
  if (P_ERR == P_open(&pads, &my_disc, io_disc)) {
    error(ERROR_FATAL, "*** P_open failed ***");
  }
  if (P_ERR == P_io_fopen(pads, inName)) {
    error(ERROR_FATAL, "*** P_io_fopen failed ***");
  }
  if (!(io = P_fopen(outName, "w"))) {
    P_SYSERR1(pads->disc, "Failed to open output file \"%s\" for writing", outName);
  }
  if (P_ERR == PADS_TY(_init)(pads, &rep)) {
    error(ERROR_FATAL, "*** representation initialization failed ***");
  }
  if (P_ERR == PADS_TY(_pd_init)(pads, &pd)) {
    error(ERROR_FATAL, "*** parse description initialization failed ***");
  }

/*   /\*** New rec. code ***\/ */
  if (P_ERR == PADS_TY(_m_rec_init)(pads, &m, READ_MASK)) {
    error(ERROR_FATAL, "*** recursive mask initialization failed ***");
  }
  if (m != m->branches.element.interior) {
    error(ERROR_FATAL, "*** recursive mask initialization did not operate correctly. ***");
  }
/*   /\*** End new rec. code ***\/ */

#ifdef PADS_HDR_TY
  if (P_ERR == PADS_HDR_TY(_init)(pads, &hdr_rep)) {
    error(ERROR_FATAL, "*** header representation initialization failed ***");
  }
  if (P_ERR == PADS_HDR_TY(_pd_init)(pads, &hdr_pd)) {
    error(ERROR_FATAL, "*** header parse description initialization failed ***");
  }
  /* init mask -- must do this! */
  PADS_HDR_TY(_m_init)(pads, &hdr_m, P_CheckAndSet);
#endif /* PADS_HDR_TY */

#ifdef PADS_HDR_TY
  /*
   * Try to read header
   */
  if (!P_io_at_eof(pads)) {
    if (P_OK != PADS_HDR_TY(_read)(pads, &hdr_m, &hdr_pd, &hdr_rep EXTRA_HDR_READ_ARGS )) {
      error(ERROR_FATAL, "header read returned error");
    } else {
      error(2, "Note: header read returned OK");
      if (P_ERR == PADS_HDR_TY(_write2io)(pads, io, &hdr_pd, &hdr_rep EXTRA_HDR_READ_ARGS )) {
	error(ERROR_FATAL, "*** IO error during header write");
      }
    }
  }
#endif /* PADS_HDR_TY */

  /*
   * Try to read each line of data
   */
  while (!P_io_at_eof(pads) && (MAX_RECS == 0 || num_recs++ < MAX_RECS)) {
    P_io_getPos(pads, &bpos, 0);
    if (P_OK != PADS_TY(_read)(pads, &m, &pd, &rep EXTRA_READ_ARGS )) {
#ifdef EXTRA_BAD_READ_CODE
      EXTRA_BAD_READ_CODE;
#else
      if (my_disc.e_rep > PerrorRep_Min) {
        error(2, "read returned error");
      }
#endif
    }
    else {
      if (PADS_TY(_verify)(&(rep))) {  
	error(2, "read reported no errors and passed predicate test.");  
      } else {  error(2, "read reported no errors but failed predicate test.");  } 
#ifdef EXTRA_GOOD_READ_CODE
      EXTRA_GOOD_READ_CODE;
#endif
    }
    P_io_getPos(pads, &epos, 0);
    if (P_POS_EQ(bpos, epos)) {
      error(ERROR_FATAL, "*** read loop stuck: read call did not advance IO cursor");
    }
    tree_write2io(pads,io,&pd,&rep);
  }
  if (P_ERR == P_io_close(pads)) {
    error(ERROR_FATAL, "*** P_io_close failed ***");
  }

  if (P_ERR == PADS_TY(_cleanup)(pads, &rep)) {
    error(ERROR_FATAL, "** representation cleanup failed **");
  }
  if (P_ERR == PADS_TY(_pd_cleanup)(pads, &pd)) {
    error(ERROR_FATAL, "** parse descriptor cleanup failed **");
  }
  if (P_ERR == P_close(pads)) {
    error(ERROR_FATAL, "*** P_close failed ***");
  }
  sfclose(io);
  return 0;
  }
Exemple #5
0
int
main(int argc, register char *argv[])
{
	static char command[] = "pack";
	register Huff_t	*hp;
	register char	*infile,*outfile;
	Sfio_t		*fpin,*fpout;
	int		nfile=0, npack=0, force=0, verbose=0;
	int		out, deleted, dsize, n;
	struct stat	statb;

	NOT_USED(argc);
	error_info.id = command;
	while(n = optget(argv,usage)) switch(n)
	{
	case 'f':
		force++;
		break;
	case 'v':
		verbose = !verbose;
		break;
	case ':':
		error(2, opt_info.arg);
		break;
	case '?':
		error(ERROR_usage(2), "%s", opt_info.arg);
		break;
	}
	argv += opt_info.index;
	if(error_info.errors || !*argv)
		error(ERROR_usage(2), "%s", optusage((char*)0));

	while (infile = *argv++)
	{
		if(*infile == '-')
		{
			/* awful way to handle options, but preserves SVID */
			switch(infile[1])
			{
				case 'f':
					force++;
					continue;
				case 0:
					verbose = !verbose;
					continue;
			}
		}
		nfile++;
		fpin = fpout = (Sfio_t*)0;
		hp = (Huff_t*)0;
		deleted = 0;
		if(!(outfile = outname(infile)))
			continue;
		if (!(fpin=sfopen((Sfio_t*)0,infile,"r")))
			error(ERROR_system(0), "%s: cannot open", infile);
		else if(fstat(sffileno(fpin),&statb) < 0)
			error(ERROR_system(0), "%s: cannot stat", infile);
		else if(S_ISDIR(statb.st_mode))
			error(2, "%s: cannot pack a directory", infile);
		else if(statb.st_nlink > 1)
			error(2, "%s: has links", infile);
		else if(statb.st_size ==0)
			error(2, "%s: cannot pack a zero length file", infile);
		else if(access(outfile,F_OK) ==0)
			error(ERROR_system(0), "%s: already exists", outfile);
		else if(((out=open(outfile,O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,PERM(statb.st_mode))) < 0) ||
			!(fpout = sfnew((Sfio_t*)0,(char*)0,SF_UNBOUND,out,SF_WRITE)))
			error(ERROR_system(0), "%s: cannot create", outfile);
		else if((deleted++,chmod(outfile,statb.st_mode)) < 0)
			error(ERROR_system(0), "%s: cannot change mode to %o",outfile,statb.st_mode);
		else
		{
			chown(outfile,statb.st_uid,statb.st_gid);
			if(!(hp = huffinit(fpin,(Sfoff_t)-1)))
				error(2, "%s: read error", infile);
			else if(sfseek(fpin,(Sfoff_t)0,0) < 0)
				error(ERROR_system(0),"%s: seek error", infile);
			else if((dsize = huffputhdr(hp,fpout)) < 0)
				error(2, "%s: write error", infile);
			else if(!force && block(huffisize(hp)) <= block(huffosize(hp)+dsize))
				error(2, "%s:no savings - file unchanged", infile);
			else if(huffencode(hp,fpin,fpout,SF_UNBOUND)<0)
				error(2, "%s: read error", infile);
			else
			{
				double diff;
				if(remove(infile) < 0)
					error(ERROR_system(0), "%s: cannot remove", infile);
				diff = huffisize(hp) - (dsize+huffosize(hp));
				sfprintf(sfstdout,"%s: %s : %.1f%% Compression\n",command,
					infile,(100*diff)/((double)huffisize(hp)));
				if(verbose)
					vprint(hp,dsize);
				npack++;
				deleted = 0;
			}
		}
		if(hp)
			huffend(hp);
		if(fpin)
			sfclose(fpin);
		if(fpout)
			sfclose(fpout);
		if(deleted)
			remove(outfile);
		if(outfile)
			free(outfile);
	}
	nfile -= npack;
	if(nfile > 125)
		nfile = 125;
	exit(nfile);
}
Exemple #6
0
MAIN()
{
  Sfio_t  *f;

  if(argc > 1)
  { if(sfopen(sfstdin,argv[1],"r") != sfstdin)
      terror("Can't reopen stdin");
    sfmove(sfstdin,sfstdout,(Sfoff_t)(-1),-1);
    return 0;
  }

  if(!(f = sfopen((Sfio_t*)0,tstfile(0),"w")))
    terror("Opening to write\n");
  if(sfputc(f,'a') != 'a')
    terror("sfputc\n");
  if(sfgetc(f) >= 0)
    terror("sfgetc\n");
  
  if(!(f = sfopen(f,tstfile(0),"r")))
    terror("Opening to read\n");
  if(sfgetc(f) != 'a')
    terror("sfgetc2\n");
  if(sfputc(f,'b') >= 0)
    terror("sfputc2\n");

  if(!(f = sfopen(f,tstfile(0),"r+")))
    terror("Opening to read/write\n");

  if(sfgetc(f) != 'a')
    terror("sfgetc3\n");
  if(sfputc(f,'b') != 'b')
    terror("sfputc3\n");
  if(sfclose(f) < 0)
    terror("sfclose\n");

  if(!(f = sfpopen(NIL(Sfio_t*),sfprints("%s %s", argv[0], tstfile(0)),"r")))
    terror("sfpopen\n");
  if(sfgetc(f) != 'a')
    terror("sfgetc4\n");
  if(sfgetc(f) != 'b')
    terror("sfgetc5\n");
  if(sfgetc(f) >= 0)
    terror("sfgetc6\n");

  if(!(f = sfopen(f,tstfile(0),"w")) )
    terror("sfopen\n");
  if(sfputc(f,'a') != 'a')
    terror("sfputc1\n");
  sfsetfd(f,-1);
  if(sfputc(f,'b') >= 0)
    terror("sfputc2\n");
  if(sfclose(f) < 0)
    terror("sfclose\n");

  if(!(f = sfopen(NIL(Sfio_t*),tstfile(0),"a+")) )
    terror("sfopen2\n");
  sfset(f,SF_READ,0);
  if(!sfreserve(f,0,-1) )
    terror("Failed on buffer getting\n");
  if(sfvalue(f) <= 0)
    terror("There is no buffer?\n");

  TSTEXIT(0);
}
Exemple #7
0
char*
translate(const char* loc, const char* cmd, const char* cat, const char* msg)
{
	register char*	r;
	char*		t;
	int		p;
	int		oerrno;
	Catalog_t*	cp;
	Message_t*	mp;

	oerrno = errno;
	r = (char*)msg;

	/*
	 * quick out
	 */

	if (!cmd && !cat)
		goto done;
	if (cmd && (t = strrchr(cmd, '/')))
		cmd = (const char*)(t + 1);

	/*
	 * initialize the catalogs dictionary
	 */

	if (!state.catalogs)
	{
		if (state.error)
			goto done;
		if (!(state.tmp = sfstropen()))
		{
			state.error = 1;
			goto done;
		}
		if (!(state.catalogs = dtopen(&state.catalog_disc, Dtset)))
		{
			sfclose(state.tmp);
			state.error = 1;
			goto done;
		}
		if (streq(loc, "debug"))
			state.debug = loc;
	}

	/*
	 * get the message
	 * or do we have to spell it out for you
	 */

	if ((!cmd || !(mp = match(cmd, msg))) &&
	    (!cat || !(mp = match(cat, msg))) &&
	    (!error_info.catalog || !(mp = match(error_info.catalog, msg))) &&
	    (!ast.id || !(mp = match(ast.id, msg))) ||
	     !(cp = mp->cat))
	{
#if DEBUG_trace > 1
sfprintf(sfstderr, "AHA#%d:%s cmd %s cat %s:%s id %s msg `%s'\n", __LINE__, __FILE__, cmd, cat, error_info.catalog, ast.id, msg);
#endif
		goto done;
	}

	/*
	 * adjust for the current locale
	 */

#if DEBUG_trace
sfprintf(sfstderr, "AHA#%d:%s cp->locale `%s' %p loc `%s' %p\n", __LINE__, __FILE__, cp->locale, cp->locale, loc, loc);
#endif
	if (cp->locale != loc)
	{
		cp->locale = loc;
		if (cp->cat != NOCAT)
			catclose(cp->cat);
		if ((cp->cat = find(cp->locale, cp->name)) == NOCAT)
			cp->debug = streq(cp->locale, "debug");
		else
			cp->debug = 0;
#if DEBUG_trace
sfprintf(sfstderr, "AHA#%d:%s cp->cat %p cp->debug %d NOCAT %p\n", __LINE__, __FILE__, cp->cat, cp->debug, NOCAT);
#endif
	}
	if (cp->cat == NOCAT)
	{
		if (cp->debug)
		{
			p = tempget(state.tmp);
			sfprintf(state.tmp, "(%s,%d,%d)", cp->name, mp->set, mp->seq);
			r = tempuse(state.tmp, p);
		}
		else if (ast.locale.set & AST_LC_debug)
		{
			p = tempget(state.tmp);
			sfprintf(state.tmp, "(%s,%d,%d)%s", cp->name, mp->set, mp->seq, r);
			r = tempuse(state.tmp, p);
		}
		goto done;
	}

	/*
	 * get the translated message
	 */

	r = catgets(cp->cat, mp->set, mp->seq, msg);
	if (ast.locale.set & AST_LC_translate)
		sfprintf(sfstderr, "translate locale=%s catalog=%s set=%d seq=%d \"%s\" => \"%s\"\n", cp->locale, cp->name, mp->set, mp->seq, msg, r == (char*)msg ? "NOPE" : r);
	if (r != (char*)msg)
	{
		if (streq(r, (char*)msg))
			r = (char*)msg;
		else if (strcmp(fmtfmt(r), fmtfmt(msg)))
		{
			sfprintf(sfstderr, "locale %s catalog %s message %d.%d \"%s\" does not match \"%s\"\n", cp->locale, cp->name, mp->set, mp->seq, r, msg);
			r = (char*)msg;
		}
	}
	if (ast.locale.set & AST_LC_debug)
	{
		p = tempget(state.tmp);
		sfprintf(state.tmp, "(%s,%d,%d)%s", cp->name, mp->set, mp->seq, r);
		r = tempuse(state.tmp, p);
	}
 done:
	if (r == (char*)msg && loc == state.debug)
	{
		p = tempget(state.tmp);
		sfprintf(state.tmp, "(%s,%s,%s,\"%s\")", loc, cmd, cat, r);
		r = tempuse(state.tmp, p);
	}
	errno = oerrno;
	return r;
}
Exemple #8
0
int
sfdcpzip(Sfio_t* sp, const char* path, unsigned long flags, Pzdisc_t* disc)
{
	Sfio_t*		io;
	Sfpzip_t*	pz;
	Pz_t*		oz;

	if (flags & PZ_HANDLE)
	{
		oz = (Pz_t*)sp;
		sp = oz->io;
	}
	else
		oz = 0;
	if (sfset(sp, 0, 0) & SF_WRITE)
	{
		if (flags & PZ_STAT)
			return -1;
	}
	else if (!(flags & PZ_FORCE))
	{
		unsigned char*	s;
		int		r;
		int		m1;
		int		m2;

		if (!(r = sfset(sp, 0, 0) & SF_SHARE))
			sfset(sp, SF_SHARE, 1);
		s = (unsigned char*)sfreserve(sp, PZ_GZ_MAGOFF + 2, 1);
		if (!r)
			sfset(sp, SF_SHARE, 0);
		if (!s)
			return -1;
		m1 = s[0];
		m2 = s[1];
		r = m1 == PZ_MAGIC_1 && m2 == PZ_MAGIC_2 && s[2] > 0 && s[3] < 10 ||
		    m1 == GZ_MAGIC_1 && m2 == GZ_MAGIC_2 &&
		    s[PZ_GZ_MAGOFF] == PZ_GZ_MAGIC_1 && s[PZ_GZ_MAGOFF+1] == PZ_GZ_MAGIC_2;
		sfread(sp, s, 0);
		if (flags & PZ_STAT)
			return r;
		if (!r)
		{
			if (!(flags & PZ_NOGZIP))
			{
				if (m1 == GZ_MAGIC_1)
				{
					if (m2 == GZ_MAGIC_2)
						r = sfdcgzip(sp, (flags & PZ_CRC) ? 0 : SFGZ_NOCRC);
					else if (m2 == LZ_MAGIC_2)
						r = sfdclzw(sp, 0);
				}
				else if (m1 == 'B' && m2 == 'Z' && s[2] == 'h' && s[3] >= '1' && s[3] <= '9')
					r = sfdcbzip(sp, 0);
			}
			return r;
		}
		sfsync(sp);
	}
	if (!(io = sfnew(NiL, NiL, SF_UNBOUND, sffileno(sp), (sfset(sp, 0, 0) & (SF_READ|SF_WRITE)))))
		return -1;
	if (!(pz = newof(0, Sfpzip_t, 1, 0)))
	{
		io->_file = -1;
		sfclose(io);
		return -1;
	}
	pz->disc.version = PZ_VERSION;
	flags &= ~(PZ_READ|PZ_WRITE|PZ_STAT|PZ_STREAM|PZ_INTERNAL);
	flags |= PZ_PUSHED|PZ_STREAM|((sfset(sp, 0, 0) & SF_READ) ? PZ_READ : PZ_WRITE);
	if (oz && (oz->flags & PZ_WRITE))
		flags |= PZ_DELAY;
	if (disc)
	{
		pz->disc.errorf = disc->errorf;
		pz->disc.window = disc->window;
		pz->disc.options = disc->options;
		pz->disc.partition = disc->partition;
		if (disc->splitf)
			flags |= PZ_ACCEPT;
	}
	if (!(pz->pz = pzopen(&pz->disc, (char*)io, flags)) || (sp->_file = open("/dev/null", 0)) < 0)
	{
		io->_file = -1;
		sfclose(io);
		free(pz);
		return -1;
	}
	if (path)
		pz->pz->path = path;
	pz->sfdisc.exceptf = sfpzexcept;
	if (flags & PZ_WRITE)
	{
		pz->sfdisc.writef = sfpzwrite;
		pz->io = io;
	}
	else
		pz->sfdisc.readf = sfpzread;
	sfset(sp, SF_SHARE|SF_PUBLIC, 0);
	if (sfdisc(sp, &pz->sfdisc) != &pz->sfdisc)
	{
		close(sp->_file);
		sp->_file = io->_file;
		sfseek(sp, sftell(io), SEEK_SET);
		io->_file = -1;
		pzclose(pz->pz);
		free(pz);
		return -1;
	}
	if (oz)
		oz->flags |= pz->pz->flags & PZ_INTERNAL;
	return 1;
}
Exemple #9
0
tmain() {
    UNUSED(argc);
    UNUSED(argv);
    Sfio_t *f, *f2;
    char buf[1024];
    char rbuf[4 * 1024];
    off_t o;
    int i;

    if (!(f = sfopen(NULL, tstfile("sf", 0), "w"))) terror("Can't open file");
    sfset(f, SF_IOCHECK, 1);

    Disc.exceptf = except;
    if (!sfdisc(f, &Disc)) terror("Pushing discipline failed");

    sfdisc(f, &Disc);
    if (Type != SF_DPUSH) terror("Did not get push event");

    /* this is to test sfraise(NULL,...) */
    if (!(f2 = sfopen(NULL, tstfile("sf", 0), "w"))) terror("Can't open file");
    sfdisc(f2, &Disc);

    Sfn = 0;
    if (sfraise(0, SF_WRITE, 0) < 0) terror("sfraise failed");
    if (Sfn != 2) terror("Didn't get right event count");

    sfdisc(f, NULL);
    if (Type != SF_DPOP) terror("Did not get pop event");

    sfwrite(f, "123", 3);
    sfsync(f);
    if (Type != SF_SYNC) terror("Did not get sync event");

    sfwrite(f, "123", 3);
    sfpurge(f);
    if (Type != SF_PURGE) terror("Did not get purge event");

    sfclose(f);
    if (Type != SF_CLOSING) terror("Did not get close event");

    sfclose(f);
    if (Type != SF_FINAL) terror("Did not get final event");

    if (!(f = sfopen(NULL, tstfile("sf", 0), "r"))) terror("Can't open file");
    Disc2.readf = readfunc;
    Disc2.exceptf = except3;
    sfdisc(f, &Disc2);
    if (sfgetc(f) >= 0) terror("There should be no data here");
    if (Type != SF_LOCKED) terror("Did not get lock event");

    /* test to see if sfclose() preserves seek location */
    if (!(f = sftmp(0))) terror("Can't create temp file");
    sfsetbuf(f, buf, sizeof(buf));
    for (i = 0; i < sizeof(rbuf); ++i) rbuf[i] = i;
    sfwrite(f, rbuf, sizeof(rbuf));
    sfset(f, SF_WRITE, 0);

    Disc.exceptf = except2;
    sfdisc(f, &Disc);
    sfseek(f, (Sfoff_t)0, 0);
    if (sfread(f, rbuf, 4) != 4) terror("reading 4 bytes");
    for (i = 0; i < 4; ++i) {
        if (rbuf[i] != i) terror("wrong 4 bytes");
    }

    sfsync(f);
    if ((o = lseek(sffileno(f), (off_t)0, SEEK_CUR)) != 4) {
        terror("Wrong seek location %lld", (Sfoff_t)o);
    }

    if ((i = dup(sffileno(f))) < 0) terror("Can't dup file descriptor");
    if ((o = lseek(i, (off_t)0, SEEK_CUR)) != 4) terror("Wrong seek location %lld", (Sfoff_t)o);

    sfclose(f);
    if ((o = lseek(i, (off_t)0, SEEK_CUR)) != 4) terror("Wrong seek location %lld", (Sfoff_t)o);

    texit(0);
}
Exemple #10
0
void
finish(int n)
{
	Rule_t*		r;
	int		i;

	/*
	 * old error intercept
	 */

	if (!state.hold && (r = internal.error) && (r->property & (P_target|P_functional)) == P_target)
	{
		state.hold = null;
		if (n && error_info.errors && !state.compileonly && !state.interrupt)
		{
			if (r->status == NOTYET)
				maketop(r, P_dontcare|P_foreground, NiL);
			state.hold = 0;
			if (r->status == EXISTS)
			{
				r->status = NOTYET;
				return;
			}
		}
	}

	/*
	 * children exit without cleanup
	 */

	if (getpid() != state.pid)
		_exit(n);
	unparse(0);
	switch (state.finish)
	{

	case 0:
		/*
		 * disable listing and wait for any jobs to finish
		 */

		state.finish++;
		alarm(0);
		state.list = 0;
		message((-1, "%s cleanup", state.interrupt ? "interrupt" : n > 0 ? "error" : "normal"));
		complete(NiL, NiL, NiL, 0);
		/*FALLTHROUGH*/

	case 1:
		/*
		 * make the done trap
		 */

		state.finish++;
		if (!state.compileonly && (r = getrule(external.done)))
			maketop(r, P_dontcare, NiL);
		/*FALLTHROUGH*/

	case 2:
		/*
		 * make the makedone trap
		 */

		state.finish++;
		if (!state.compileonly && (r = getrule(external.makedone)))
			maketop(r, P_dontcare, NiL);
		/*FALLTHROUGH*/

	case 3:
		/*
		 * wait for any job(s) to finish
		 */

		state.finish++;
		complete(NiL, NiL, NiL, 0);
		/*FALLTHROUGH*/

	case 4:
		/*
		 * put all jobs in foreground and save state
		 */

		state.finish++;
		state.jobs = 0;
		savestate();
		/*FALLTHROUGH*/

	case 5:
		/*
		 * clean up temporaries
		 */

		state.finish++;
		remtmp(1);
		/*FALLTHROUGH*/

	case 6:
		/*
		 * drop the coshell
		 */
		
		state.finish++;
		drop();
		/*FALLTHROUGH*/

	case 7:
		/*
		 * dump
		 */

		state.finish++;
		if (state.test & 0x00002000)
		{
			Vmstat_t	vs;

			vmstat(Vmheap, &vs);
			error(0, "vm region %zu segments %zu busy %zu:%zu free %zu:%zu", vs.extent, vs.n_seg, vs.n_busy, vs.s_busy, vs.n_free, vs.s_free);
		}
		dump(sfstdout, error_info.trace <= -14);
		/*FALLTHROUGH*/

	case 8:
		/*
		 * final output
		 */

		state.finish++;
		if (state.errors && state.keepgoing && !n)
			n = 1;
		if (state.mam.out)
		{
			if (state.mam.regress)
				sfprintf(state.mam.out, "%sinfo finish regression\n", state.mam.label);
			else if (state.mam.dynamic || *state.mam.label)
				sfprintf(state.mam.out, "%sinfo finish %lu %d\n", state.mam.label, CURTIME, n);
		}
		for (i = 0; i < elementsof(state.io); i++)
			if (state.io[i] != sfstdin && state.io[i] != sfstdout && state.io[i] != sfstderr)
				sfclose(state.io[i]);
		if (state.errors && state.keepgoing)
			error(2, "*** %d action%s failed", state.errors, state.errors == 1 ? null : "s");
		message((-1, "%s exit", state.interrupt ? "interrupt" : n ? "error" : "normal"));
		break;

	}
	if (state.interrupt)
	{
		n = 3;
		signal(state.interrupt, SIG_DFL);
		kill(getpid(), state.interrupt);
		pause();
	}
	exit(n);
}
Exemple #11
0
Fichier : cut.c Projet : kshji/ast
int
b_cut(int argc, char** argv, Shbltin_t* context)
{
    register char*		cp = 0;
    register Sfio_t*	fp;
    char*			s;
    int			n;
    Cut_t*			cut;
    int			mode = 0;
    Delim_t			wdelim;
    Delim_t			ldelim;
    size_t			reclen = 0;

    cmdinit(argc, argv, context, ERROR_CATALOG, 0);
    wdelim.chr = '\t';
    ldelim.chr = '\n';
    wdelim.len = ldelim.len = 1;
    for (;;)
    {
        switch (optget(argv, usage))
        {
        case 0:
            break;
        case 'b':
        case 'c':
            if(mode&C_FIELDS)
            {
                error(2, "f option already specified");
                continue;
            }
            cp = opt_info.arg;
            if(opt_info.option[1]=='b')
                mode |= C_BYTES;
            else
                mode |= C_CHARS;
            continue;
        case 'D':
            ldelim.str = opt_info.arg;
            if (mbwide())
            {
                s = opt_info.arg;
                ldelim.chr = mbchar(s);
                if ((n = s - opt_info.arg) > 1)
                {
                    ldelim.len = n;
                    continue;
                }
            }
            ldelim.chr = *(unsigned char*)opt_info.arg;
            ldelim.len = 1;
            continue;
        case 'd':
            wdelim.str = opt_info.arg;
            if (mbwide())
            {
                s = opt_info.arg;
                wdelim.chr = mbchar(s);
                if ((n = s - opt_info.arg) > 1)
                {
                    wdelim.len = n;
                    continue;
                }
            }
            wdelim.chr = *(unsigned char*)opt_info.arg;
            wdelim.len = 1;
            continue;
        case 'f':
            if(mode&(C_CHARS|C_BYTES))
            {
                error(2, "c option already specified");
                continue;
            }
            cp = opt_info.arg;
            mode |= C_FIELDS;
            continue;
        case 'n':
            mode |= C_NOSPLIT;
            continue;
        case 'N':
            mode |= C_NONEWLINE;
            continue;
        case 'R':
        case 'r':
            if(opt_info.num>0)
                reclen = opt_info.num;
            continue;
        case 's':
            mode |= C_SUPRESS;
            continue;
        case ':':
            error(2, "%s", opt_info.arg);
            break;
        case '?':
            error(ERROR_usage(2), "%s", opt_info.arg);
            break;
        }
        break;
    }
    argv += opt_info.index;
    if (error_info.errors)
        error(ERROR_usage(2), "%s",optusage(NiL));
    if(!cp)
    {
        error(2, "b, c or f option must be specified");
        error(ERROR_usage(2), "%s", optusage(NiL));
    }
    if(!*cp)
        error(3, "non-empty b, c or f option must be specified");
    if((mode & (C_FIELDS|C_SUPRESS)) == C_SUPRESS)
        error(3, "s option requires f option");
    cut = cutinit(mode, cp, &wdelim, &ldelim, reclen);
    if(cp = *argv)
        argv++;
    do
    {
        if(!cp || streq(cp,"-"))
            fp = sfstdin;
        else if(!(fp = sfopen(NiL,cp,"r")))
        {
            error(ERROR_system(0),"%s: cannot open",cp);
            continue;
        }
        if(mode&C_FIELDS)
            cutfields(cut,fp,sfstdout);
        else
            cutcols(cut,fp,sfstdout);
        if(fp!=sfstdin)
            sfclose(fp);
    } while(cp = *argv++);
    if (sfsync(sfstdout))
        error(ERROR_system(0), "write error");
    return error_info.errors != 0;
}
Exemple #12
0
static char *createconverterstr (
    DDSschema_t *ischemap, DDSschema_t *oschemap, DDSexpr_t *cep
) {
    Sfio_t *fp;
    char *cstr;

    if (!cep->loop) {
        SUwarning (1, "createconverterstr", "no loop code specified");
        return NULL;
    }

    if (!(fp = sfopen (NULL, NULL, "sw+"))) {
        SUwarning (1, "createconverterstr", "sfopen failed");
        return NULL;
    }

    sfprintf (fp, "#include <ast.h>\n#include <cdt.h>\n#include <swift.h>\n");
    sfprintf (fp, "#include <vmalloc.h>\n#include <dds.h>\n\n");
    if (ischemap->include)
        sfprintf (fp, "%s\n\n", ischemap->include);
    _ddswritestruct (ischemap, sfprints ("inrec_%s", ischemap->name), fp);
    _ddswritestruct (oschemap, sfprints ("outrec_%s", oschemap->name), fp);
    if (cep->vars)
        sfprintf (fp, "#line 1 \"VARS\"\n%s\n", cep->vars);
    sfprintf (fp,
        "DDS_EXPORT int converter_%s_init (void) {\n"
        "    {\n#line 1 \"BEGIN\"\n        %s\n    }\n"
        "    return 0;\n"
        "}\n\n",
    ischemap->name, (cep->begin ? cep->begin : ""));
    sfprintf (fp,
        "DDS_EXPORT int converter_%s_term (void) {\n"
        "    {\n#line 1 \"END\"\n        %s\n    }\n"
        "    return 0;\n"
        "}\n\n",
    ischemap->name, (cep->end ? cep->end : ""));
    sfprintf (fp, "#define KEEP __result = 1\n#define DROP __result = 0\n\n");
    sfprintf (fp, "#define NREC __nrec\n#define INDEX (*__indexp)\n\n");
    sfprintf (fp, "#define IN __inrecp\n");
    sfprintf (fp, "#define OUT __outrecp\n\n");
    sfprintf (
        fp, "#define EMIT (*__emitfunc) ("
        "  __emitfp, __outrecp, __outschemap, __outlen"
        "), __result = 0\n\n"
    );
    sfprintf (fp,
        "DDS_EXPORT int converter_%s_work ("
        "  char *__inbuf, int __inlen, DDSschema_t *__inschemap,"
        "  char *__outbuf, int __outlen, DDSschema_t *__outschemap,"
        "  long long *__indexp, long long __nrec, "
        "  int (*__emitfunc) (Sfio_t *, void *, DDSschema_t *, size_t), "
        "  Sfio_t *__emitfp"
        ") {\n"
        "    struct __inrec_%s_t *__inrecp;\n"
        "    struct __outrec_%s_t *__outrecp;\n"
        "    int __result = 1;\n\n"
        "    __inrecp = (struct __inrec_%s_t *) __inbuf;\n"
        "    __outrecp = (struct __outrec_%s_t *) __outbuf;\n",
        ischemap->name, ischemap->name, oschemap->name,
        ischemap->name, oschemap->name
    );
    sfprintf (fp, "    {\n#line 1 \"LOOP\"\n        %s\n    }\n\n", cep->loop);
    sfprintf (fp, "    return __result;\n");
    sfprintf (fp, "}\n");

    if (!(cstr = _ddscopystr (fp))) {
        SUwarning (1, "createconverterstr", "copystr failed");
        return NULL;
    }
    sfclose (fp);
    return cstr;
}
Exemple #13
0
static void
act(register Ftw_t* ftw, int op)
{
	char*	s;
	Sfio_t*	fp;
	int	i;
	int	j;
	int	k;
	int	n;
	int	r;

	switch (op)
	{
	case ACT_CMDARG:
		if ((i = cmdarg(state.cmd, ftw->path, ftw->pathlen)) >= state.errexit)
			exit(i);
		break;
	case ACT_CODE:
		if (findwrite(state.find, ftw->path, ftw->pathlen, (ftw->info & FTW_D) ? "system/dir" : (char*)0))
			state.finderror = 1;
		break;
	case ACT_CODETYPE:
		fp = sfopen(NiL, PATH(ftw), "r");
		if (findwrite(state.find, ftw->path, ftw->pathlen, magictype(state.magic, fp, PATH(ftw), &ftw->statb)))
			state.finderror = 1;
		if (fp)
			sfclose(fp);
		break;
	case ACT_EVAL:
		eval(state.action, ftw);
		break;
	case ACT_INTERMEDIATE:
		intermediate(ftw, ftw->path);
		break;
	case ACT_LIST:
		sfputr(sfstdout, ftw->path, '\n');
		break;
	case ACT_SNAPSHOT:
		print(state.snapshot.tmp, ftw, state.snapshot.format.path);
		sfputc(state.snapshot.tmp, state.snapshot.format.delim);
		i = sfstrtell(state.snapshot.tmp);
		print(state.snapshot.tmp, ftw, state.snapshot.format.easy);
		j = sfstrtell(state.snapshot.tmp);
		s = sfstrbase(state.snapshot.tmp);
		r = SNAPSHOT_new;
		if (!state.snapshot.prev)
			k = 1;
		else
		{
			do
			{
				if (!(k = urlcmp(state.snapshot.prev, s, state.snapshot.format.delim)))
				{
					r = SNAPSHOT_changed;
					if (!(k = memcmp(state.snapshot.prev + i, s + i, j - i) || state.snapshot.prev[j] != state.snapshot.format.delim))
					{
						if ((n = (int)sfvalue(sfstdin)) > 4 && state.snapshot.prev[n-2] == state.snapshot.format.delim)
						{
							sfwrite(sfstdout, state.snapshot.prev, n - 4);
							sfputc(sfstdout, '\n');
						}
						else
							sfwrite(sfstdout, state.snapshot.prev, n);
					}
				}
				else if (k > 0)
					break;
				else if (k < 0 && (n = (int)sfvalue(sfstdin)) > 4 && (state.snapshot.prev[n-2] != state.snapshot.format.delim || state.snapshot.prev[n-3] != SNAPSHOT_deleted))
				{
					sfwrite(sfstdout, state.snapshot.prev, n - (state.snapshot.prev[n-2] == state.snapshot.format.delim ? 4 : 1));
					sfputc(sfstdout, state.snapshot.format.delim);
					sfputc(sfstdout, SNAPSHOT_deleted);
					sfputc(sfstdout, state.snapshot.format.delim);
					sfputc(sfstdout, '\n');
					if (state.cmdflags & CMD_TRACE)
						error(1, "%s deleted", ftw->path);
				}
				if (!(state.snapshot.prev = sfgetr(sfstdin, '\n', 0)))
					break;
			} while (k < 0);
		}
		if (k)
		{
			if (state.snapshot.format.hard && (ftw->info & FTW_F))
			{
				sfputc(state.snapshot.tmp, state.snapshot.format.delim);
				print(state.snapshot.tmp, ftw, state.snapshot.format.hard);
			}
			sfputc(state.snapshot.tmp, state.snapshot.format.delim);
			sfputc(state.snapshot.tmp, r);
			sfputc(state.snapshot.tmp, state.snapshot.format.delim);
			sfputr(sfstdout, sfstruse(state.snapshot.tmp), '\n');
			if (state.cmdflags & CMD_TRACE)
				error(1, "%s %s", ftw->path, r == SNAPSHOT_new ? "new" : "changed");
		}
		else
			sfstrseek(state.snapshot.tmp, SEEK_SET, 0);
		break;
	}
}
Exemple #14
0
int
b_head(int argc, register char** argv, void* context)
{
	static const char	header_fmt[] = "\n==> %s <==\n";

	register Sfio_t*	fp;
	register char*		cp;
	register off_t		keep = 10;
	register off_t		skip = 0;
	register int		delim = '\n';
	int			header = 1;
	char*			format = (char*)header_fmt+1;

	cmdinit(argc, argv, context, ERROR_CATALOG, 0);
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 'c':
			delim = -1;
			/*FALLTHROUGH*/
		case 'n':
			if (opt_info.offset && argv[opt_info.index][opt_info.offset] == 'c')
			{
				delim = -1;
				opt_info.offset++;
			}
			if ((keep = opt_info.number) <=0)
				error(2, "%s: %I*d: positive numeric option argument expected", opt_info.name, sizeof(keep), keep);
			continue;
		case 'q':
			header = argc;
			continue;
		case 'v':
			header = 0;
			continue;
		case 's':
			skip = opt_info.number;
			continue;
		case '?':
			error(ERROR_usage(2), "%s", opt_info.arg);
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			continue;
		}
		break;
	}
	argv += opt_info.index;
	argc -= opt_info.index;
	if (error_info.errors)
		error(ERROR_usage(2), "%s", optusage(NiL));
	if (cp = *argv)
		argv++;
	do
	{
		if (!cp || streq(cp, "-"))
		{
			cp = "/dev/stdin";
			fp = sfstdin;
			sfset(fp, SF_SHARE, 1);
		}
		else if (!(fp = sfopen(NiL, cp, "r")))
		{
			error(ERROR_system(0), "%s: cannot open", cp);
			continue;
		}
		if (argc > header)
			sfprintf(sfstdout, format, cp);
		format = (char*)header_fmt;
		if (skip > 0)
			sfmove(fp, NiL, skip, delim);
		if (sfmove(fp, sfstdout, keep, delim) < 0 && errno != EPIPE)
			error(ERROR_system(0), "%s: read error", cp);
		if (fp != sfstdin)
			sfclose(fp);
	} while (cp = *argv++);
	if (sfsync(sfstdout))
		error(ERROR_system(0), "write error");
	return error_info.errors != 0;
}
Exemple #15
0
static int
process(Sfio_t* mp, Sfio_t* lp, int delay, int timeout)
{
	int		i;
	int		n;
	int		t;
	ssize_t		r;
	char*		s;
	Sfio_t*		ip;
	Sfio_t*		sps[2];
	struct stat	dst;
	struct stat	fst;

	ip = sfstdin;
	if (!fstat(sffileno(ip), &dst) && !stat("/dev/null", &fst) && dst.st_dev == fst.st_dev && dst.st_ino == fst.st_ino)
		ip = 0;
	do
	{
		i = 0;
		t = timeout;
		if (mp)
			sps[i++] = mp;
		if (ip)
		{
			sps[i++] = ip;
			t = -1;
		}
		if (!i)
			break;
		if ((n = sfpoll(sps, i, t)) <= 0)
		{
			if (n < 0)
				error(ERROR_SYSTEM|2, "poll failed");
			break;
		}
		for (i = t = 0; i < n; i++)
		{
			if (!(sfvalue(sps[i]) & SF_READ))
				/*skip*/;
			else if (sps[i] == mp)
			{
				t++;
				if (!(s = (char*)sfreserve(mp, SF_UNBOUND, -1)))
				{
					sfclose(mp);
					mp = 0;
				}
				else if ((r = sfvalue(mp)) > 0 && (sfwrite(sfstdout, s, r) != r || sfsync(sfstdout)))
				{
					error(ERROR_SYSTEM|2, "output write failed");
					goto done;
				}
			}
			else
			{
				t++;
				if (!(s = sfgetr(ip, '\n', 1)))
					ip = 0;
				else if (sfputr(mp, s, '\r') < 0 || sfsync(mp))
				{
					error(ERROR_SYSTEM|2, "write failed");
					goto done;
				}
			}
		}
	} while (t);
 done:
	if (mp)
		sfclose(mp);
	return error_info.errors != 0;
}
Exemple #16
0
int main (int argc, char **argv) {
    char *ctype, *s1, *s2, *s3, *boundary, *eof, *name;
    Sfio_t *fp;
    int state, boundaryn, eofn, atnl, i, n;
    char c1, c2;

    if (!(ctype = getenv ("CONTENT_TYPE")))
        error (3, "cannot find CONTENT_TYPE env. variable");
    if (!(s1 = strchr (ctype, ';')))
        error (3, "no field divider");
    *s1++ = 0;
    if (!(s2 = strstr (s1, "boundary=")))
        error (3, "no boundary field");
    s2 += strlen ("boundary=");
    boundary = strdup (sfprints ("--%s", s2));
    boundaryn = strlen (boundary);
    eof = strdup (sfprints ("%s--", boundary));
    eofn = strlen (eof);

    state = 0;
    name = NULL;
    fp = NULL;
    init (eofn);
    for (;;) {
next:
        if (state == 0) { /* before eof or boundary */
            if (ensurechar ('\n') == -1)
                error (3, "cannot find NL");
            s1 = getcurr ();
            if (strncmp (s1, eof, eofn) == 0)
                break;
            if (strncmp (s1, boundary, boundaryn) == 0) {
                if (s1[boundaryn] == '\r' && s1[boundaryn + 1] == '\n')
                    advance (boundaryn + 2);
                else if (s1[boundaryn] == '\n')
                    advance (boundaryn + 1);
                else
                    error (3, "no CR+NL or NL after boundary");
            } else
                error (3, "boundary or eof not found");
            binmode = 0;
            state = 1;
        } else if (state == 1) { /* at header section */
            if (ensurechar ('\n') == -1)
                error (3, "cannot find NL");
            s1 = getcurr ();
            if (*s1 == '\r' && *(s1 + 1) == '\n') {
                advance (2);
                state = 2;
                continue;
            } else if (*s1 == '\n') {
                advance (1);
                state = 2;
                continue;
            }
            s3 = strchr (s1, '\n');
            c1 = *s3, *s3 = 0;
            if (strstr (s1, "Content-Type: "))
                binmode = 1;
            if ((s2 = strstr (s1, " name=\""))) {
                name = s2 + 7;
                if (!(s2 = strchr (name, '"')))
                    error (3, "cannot find matching \" for name");
                c2 = *s2; *s2 = 0;
                name = strdup (name);
                *s2 = c2;
                if (!(fp = sfopen (NULL, name, "a")))
                    error (3, "sfopen for name %s failed", name);
            }
            *s3 = c1;
            advance (s3 - s1 + 1);
        } else if (state == 2) {
            atnl = 1;
            wrotenl = 0;
            for (;;) {
next2:
                ensure (eofn);
                if ((n = getsize ()) < eofn)
                    error (3, "unexpected EOF");
                s1 = getcurr ();
                if (atnl == 1 && strncmp (s1, boundary, boundaryn) == 0) {
                    if (count2 > 1 && buf2[0] != '\r')
                        sfputc (fp, buf2[0]);
                    if (!binmode && !wrotenl)
                        sfputc (fp, '\n');
                    count2 = 0;
                    sfclose (fp);
                    state = 0;
                    goto next;
                }
                atnl = 0;
                for (i = 0; i < n; i++) {
                    myputc (fp, s1[i]);
                    if (s1[i] == '\n') {
                        atnl = 1;
                        advance (i + 1);
                        goto next2;
                    }
                }
                advance (n);
            }
        }
    }
    return 0;
}
Exemple #17
0
static int
initiate(register Cs_t* state, char* user, char* path, char* service, char* name)
{
	register char*	s;
	char*		on;
	char*		local;
	Sfio_t*		sp;
	Sfio_t*		np;
	int		n;
	char*		av[REMOTE_ARGC];
	char		buf[PATH_MAX / 4];

	local = csname(state, 0);
	s = service + strlen(service);
	*s++ = '/';
	if (!(state->flags & CS_ADDR_SHARE))
	{
		sfsprintf(buf, sizeof(buf), "%s\n", state->host);
		if (!(sp = tokline(buf, SF_STRING, NiL)))
			return -1;
	}
	else if (state->flags & CS_ADDR_LOCAL)
	{
		sfsprintf(buf, sizeof(buf), "%s\n", CS_HOST_LOCAL);
		if (!(sp = tokline(buf, SF_STRING, NiL)))
			return -1;
	}
	else
	{
		strcpy(s, CS_SVC_HOSTS);
		if (!(sp = tokline(service, SF_READ, NiL)))
		{
			if (streq(state->host, CS_HOST_SHARE))
				sfsprintf(buf, sizeof(buf), "%s\n%s\n", CS_HOST_SHARE, CS_HOST_LOCAL);
			else
				sfsprintf(buf, sizeof(buf), "%s\n%s\n%s\n", state->host, CS_HOST_SHARE, CS_HOST_LOCAL);
			if (!(sp = tokline(buf, SF_STRING, NiL)))
				return -1;
		}
	}
	sfsprintf(s, PATH_MAX - (s - service) - 1, "%s%s", name, CS_SVC_SUFFIX);
	while (s = sfgetr(sp, '\n', 1))
		if (tokscan(s, NiL, " %s ", &on) == 1)
		{
			if (streq(on, CS_HOST_LOCAL) || streq(on, local))
			{
				sfclose(sp);
				av[0] = service;
				av[1] = path;
				av[2] = 0;
				return procclose(procopen(av[0], av, NiL, NiL, PROC_PRIVELEGED|PROC_ZOMBIE)) < 0 ? -1 : 0;
			}
			else if (!streq(on, CS_HOST_SHARE))
			{
				Proc_t*		proc;
				time_t		otime;
				struct stat	st;
				char		fv[REMOTE_FLAGC];
				long		ov[3];

				remote(state, on, user, path, 0, av, fv);
				otime = lstat(state->mount, &st) ? 0 : st.st_ctime;
				n = open("/dev/null", O_RDWR);
				ov[0] = PROC_FD_DUP(n, 0, 0);
				ov[1] = PROC_FD_DUP(n, 1, PROC_FD_PARENT|PROC_FD_CHILD);
				ov[2] = 0;
				if (proc = procopen(av[0], av, NiL, ov, PROC_PRIVELEGED|PROC_ZOMBIE))
				{
					n = 1;
					for (;;)
					{
						if (!lstat(state->mount, &st) && st.st_ctime != otime)
						{
							if (!procclose(proc))
							{
								sfclose(sp);
								return 0;
							}
							break;
						}

						/*
						 * sleep() and MNT_TMP
						 * hack around remote
						 * fs cache delays
						 */

						if (n >= CS_REMOTE_DELAY)
						{
							procclose(proc);
							break;
						}
						if (n == 1)
						{
							*state->control = CS_MNT_TMP;
							if (remove(state->mount))
							{
								close(open(state->mount, O_WRONLY|O_CREAT|O_TRUNC, 0));
								remove(state->mount);
							}
							*state->control = CS_MNT_STREAM;
						}
						sleep(n);
						n <<= 1;
					}
				}
			}
			else if (!sfstacked(sp) && (np = csinfo(state, on, NiL)))
				sfstack(sp, np);
		}
	sfclose(sp);
	return -1;
}
Exemple #18
0
main(int argc, char** argv)
{
	char*		file;
	Sfio_t*		ip;

	error_info.id = "r2c";
	state.delimiter = ':';
	state.terminator = '\n';
	state.window = 4 * 1024 * 1024;
	state.level = 9;
	for (;;)
	{
		switch (optget(argv, "d:[delimiter]l#[compression-level]q:[quote]t:[terminator]vw#[window-size]T#[test-mask]"))
		{
		case 'd':
			state.delimiter = *opt_info.arg;
			continue;
		case 'l':
			state.level = opt_info.num;
			continue;
		case 'q':
			state.quote = *opt_info.arg;
			continue;
		case 't':
			state.delimiter = *opt_info.arg;
			continue;
		case 'v':
			state.verbose = 1;
			continue;
		case 'w':
			state.window = opt_info.num;
			continue;
		case 'T':
			state.test |= opt_info.num;
			continue;
		case '?':
			error(ERROR_USAGE|4, opt_info.arg);
			continue;
		case ':':
			error(2, opt_info.arg);
			continue;
		}
		break;
	}
	argv += opt_info.index;
	if (error_info.errors)
		error(ERROR_USAGE|4, "%s", optusage(NiL));
	state.cache = state.window;
	if (state.level > 0 && sfdcgzip(sfstdout, state.level) < 0)
		error(3, "output compress discipline error");
	if (!*argv)
		r2c("/dev/stdin", sfstdin, sfstdout);
	else
		while (file = *argv++)
		{
			if (streq(file, "-"))
			{
				file = "/dev/stdin";
				ip = sfstdin;
			}
			else if (!(ip = sfopen(NiL, file, "r")))
			{
				error(ERROR_SYSTEM|2, "%s: cannot read", file);
				continue;
			}
			r2c(file, ip, sfstdout);
			if (ip != sfstdin)
				sfclose(ip);
		}
	flush(sfstdout);
	return error_info.errors != 0;
}
Exemple #19
0
int main(int argc, char *argv[])
{
	Sfio_t *in, *out;
	Shell_t	*shp;
	Namval_t *np;
	Shnode_t *t;
	char *cp;
	int n, nflag=0, vflag=0, dflag=0;
	error_info.id = argv[0];
	while(n = optget(argv, usage )) switch(n)
	{
	    case 'D':
		dflag=1;
		break;
	    case 'v':
		vflag=1;
		break;
	    case 'n':
		nflag=1;
		break;
	    case ':':
		errormsg(SH_DICT,2,"%s",opt_info.arg);
		break;
	    case '?':
		errormsg(SH_DICT,ERROR_usage(2),"%s",opt_info.arg);
		break;
	}
	shp = sh_init(argc,argv,(Shinit_f)0);
	shp->shcomp = 1;
	argv += opt_info.index;
	argc -= opt_info.index;
	if(error_info.errors || argc>2)
		errormsg(SH_DICT,ERROR_usage(2),"%s",optusage((char*)0));
	if(cp= *argv)
	{
		argv++;
		in = sh_pathopen(cp);
	}
	else
		in = sfstdin;
	if(cp= *argv)
	{
		struct stat statb;
		if(!(out = sfopen((Sfio_t*)0,cp,"w")))
			errormsg(SH_DICT,ERROR_system(1),"%s: cannot create",cp);
		if(fstat(sffileno(out),&statb) >=0)
			chmod(cp,(statb.st_mode&~S_IFMT)|S_IXUSR|S_IXGRP|S_IXOTH);
	}
	else
		out = sfstdout;
	if(dflag)
	{
		sh_onoption(SH_DICTIONARY);
		sh_onoption(SH_NOEXEC);
	}
	if(nflag)
		sh_onoption(SH_NOEXEC);
	if(vflag)
		sh_onoption(SH_VERBOSE);
	if(!dflag)
		sfwrite(out,header,sizeof(header));
	shp->inlineno = 1;
#if SHOPT_BRACEPAT
        sh_onoption(SH_BRACEEXPAND);
#endif
	while(1)
	{
		stakset((char*)0,0);
		if(t = (Shnode_t*)sh_parse(shp,in,0))
		{
			if((t->tre.tretyp&(COMMSK|COMSCAN))==0 && t->com.comnamp && strcmp(nv_name((Namval_t*)t->com.comnamp),"alias")==0)
				sh_exec(t,0);
			if(!dflag && sh_tdump(out,t) < 0)
				errormsg(SH_DICT,ERROR_exit(1),"dump failed");
		}
		else if(sfeof(in))
			break;
		if(sferror(in))
			errormsg(SH_DICT,ERROR_system(1),"I/O error");
		if(t && ((t->tre.tretyp&COMMSK)==TCOM) && (np=t->com.comnamp) && (cp=nv_name(np)))
		{
			if(strcmp(cp,"exit")==0)
				break;
			/* check for exec of a command */
			if(strcmp(cp,"exec")==0)
			{
				if(t->com.comtyp&COMSCAN)
				{
					if(t->com.comarg->argnxt.ap)
						break;
				}
				else
				{
					struct dolnod *ap = (struct dolnod*)t->com.comarg;
					if(ap->dolnum>1)
						break;
				}
			}
		}
	}
	/* copy any remaining input */
	sfmove(in,out,SF_UNBOUND,-1);
	if(in!=sfstdin)
		sfclose(in);
	if(out!=sfstdout)
		sfclose(out);
	return(0);
}
Exemple #20
0
int	wordexp(const char *string, wordexp_t *wdarg, register int flags)
{
	register Sfio_t *iop;
	register char *cp=(char*)string;
	register int c,quoted=0,literal=0,ac=0;
	int offset;
	char *savebase,**av;
	if(offset=staktell())
		savebase = stakfreeze(0);
	if(flags&WRDE_REUSE)
		wordfree(wdarg);
	else if(!(flags&WRDE_APPEND))
	{
		wdarg->we_wordv = 0;
		wdarg->we_wordc = 0;
	}
	if(flags&WRDE_UNDEF)
		stakwrite("set -u\n",7);
	if(!(flags&WRDE_SHOWERR))
		stakwrite("exec 2> /dev/null\n",18);
	stakwrite("print -f \"%q\\n\" ",16);
	if(*cp=='#')
		stakputc('\\');
	while(c = *cp++)
	{
		if(c=='\'' && !quoted)
			literal = !literal;
		else if(!literal)
		{
			if(c=='\\' && (!quoted || strchr("\\\"`\n$",c)))
			{
				stakputc('\\');
				if(c= *cp)
					cp++;
				else
					c = '\\';
			}
			else if(c=='"')
				quoted = !quoted;
			else if(c=='`' || (c=='$' && *cp=='('))
			{
				if(flags&WRDE_NOCMD)
				{
					c=WRDE_CMDSUB;
					goto err;
				}
				/* only the shell can parse the rest */
				stakputs(cp-1);
				break;
			}
			else if(!quoted && strchr("|&\n;<>"+ac,c))
			{
				c=WRDE_BADCHAR;
				goto err;
			}
			else if(c=='(') /* allow | and & inside pattern */
				ac=2;
		}
		stakputc(c);
	}
	stakputc(0);
	if(!(iop = sfpopen((Sfio_t*)0,stakptr(0),"r")))
	{
		c = WRDE_NOSHELL;
		goto err;
	}
	stakseek(0);
	ac = 0;
	while((c=sfgetc(iop)) != EOF)
	{
		if(c=='\'')
			quoted = ! quoted;
		else if(!quoted && (c==' ' || c=='\n'))
		{
			ac++;
			c = 0;
		}
		stakputc(c);
	}
	if(c=sfclose(iop))
	{
		if(c==3 || !(flags&WRDE_UNDEF))
			c=WRDE_SYNTAX;
		else
			c=WRDE_BADVAL;
		goto err;
	}
	c = ac+2;
	if(flags&WRDE_DOOFFS)
		c += wdarg->we_offs;
	if(flags&WRDE_APPEND)
		av = (char**)realloc((void*)&wdarg->we_wordv[-1], (wdarg->we_wordc+c)*sizeof(char*));
	else if(av = (char**)malloc(c*sizeof(char*)))
	{
		if(flags&WRDE_DOOFFS)
			memset((void*)av,0,(wdarg->we_offs+1)*sizeof(char*));
		else
			av[0] = 0;
	}
	if(!av)
		return(WRDE_NOSPACE);
	c = staktell();
	if(!(cp = (char*)malloc(sizeof(char*)+c)))
	{
		c=WRDE_NOSPACE;
		goto err;
	}
	((struct list*)cp)->next = (struct list*)(*av);
	*av++ = (char*)cp;
	cp += sizeof(char*);
	wdarg->we_wordv = av;
	if(flags&WRDE_APPEND)
		av += wdarg->we_wordc;
	wdarg->we_wordc += ac;
	if(flags&WRDE_DOOFFS)
		av += wdarg->we_offs;
	memcpy((void*)cp,stakptr(offset),c);
	while(ac-- > 0)
	{
		*av++ = cp;
		sh_unquote(cp);
		while(c= *cp++);
	}
	*av = 0;
	c=0;
err:
	if(offset)
		stakset(savebase,offset);
	else
		stakseek(0);
	return(c);
}
Exemple #21
0
static void
shell(void)
{
	register char*	s;
	register char*	f = 0;
	register int	c;

	if (ed.given)
		squeeze(ed.dol > ed.zero);
	s = getrec(ed.buffer.line, '\n', 0);
	if (s[0] == '!' && !s[1]) {
		if (!*sfstrbase(ed.buffer.shell))
			error(2, "no saved shell command");
		f = sfstrbase(ed.buffer.file);
	}
	else if (!s[0])
		error(2, "empty shell command");
	else
		SWP(ed.buffer.shell, ed.buffer.line);
	s = sfstrbase(ed.buffer.shell);
	sfstrseek(ed.buffer.line, 0, SEEK_SET);
	sfputc(ed.buffer.line, '!');
	while (c = *s++) {
		if (c == '\\') {
			if (*s != '%')
				sfputc(ed.buffer.line, c);
			sfputc(ed.buffer.line, *s++);
		}
		else if (c == '%')
			sfputr(ed.buffer.line, f = sfstrbase(ed.buffer.file), -1);
		else
			sfputc(ed.buffer.line, c);
	}
	if (ed.given) {
		if (!ed.tmpfile && !(ed.tmpfile = pathtemp(NiL, 0, NiL, error_info.id, NiL)))
			error(ERROR_SYSTEM|2, "cannot generate temp file name");
		if (!(ed.iop = sfopen(NiL, ed.tmpfile, "w")))
			error(ERROR_SYSTEM|2, "%s: cannot create temp file", ed.tmpfile);
		error_info.file = ed.tmpfile;
		if (ed.dol > ed.zero)
			putfile();
		exfile();
		ed.bytes = 0;
		ed.lines = 0;
		sfprintf(ed.buffer.line, " < %s", ed.tmpfile);
		if (!(s = sfstruse(ed.buffer.line)))
			error(ERROR_SYSTEM|3, "out of space");
		if (!(ed.iop = sfpopen(NiL, s + 1, "r")))
			error(ERROR_SYSTEM|2, "%s: cannot execute shell command", s);
		error_info.file = s;
		rdelete(ed.addr1, ed.addr2);
		append(getfile, ed.dot, NiL);
		exfile();
		remove(ed.tmpfile);
	}
	else {
		if (!(s = sfstruse(ed.buffer.line)))
			error(ERROR_SYSTEM|3, "out of space");
		s++;
		if (f)
			putrec(s);
		if (!(ed.iop = sfpopen(NiL, s, "")))
			error(ERROR_SYSTEM|2, "%s: cannot execute shell command", s);
		if (sfclose(ed.iop)) {
			ed.iop = 0;
			error(ERROR_SYSTEM|2, "%s: shell command exit error", s);
		}
		if (ed.verbose)
			putrec("!");
	}
}
Exemple #22
0
int
main(int argc, char** argv)
{
	char*		file;
	char*		s;
	Ptv_t*		ptv;
	Ptvprefix_t*	pp;
	Sfio_t*		sp;
	unsigned char	prefix[IP6PREFIX];
	unsigned char	addr[IP6ADDR];
	Ptvdisc_t	ptvdisc;

	int		dump = 0;

	error_info.id = "testptv";
	ptvinit(&ptvdisc);
	ptvdisc.errorf = errorf;
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 'd':
			dump = 1;
			continue;
		case '?':
			error(ERROR_USAGE|4, "%s", opt_info.arg);
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			continue;
		}
		break;
	}
	argv += opt_info.index;
	if (!(file = *argv++))
		error(ERROR_USAGE|4, "%s", optusage(0));
	if (!(sp = sfopen(0, file, "r")))
		error(ERROR_SYSTEM|3, "%s: cannot read prefix file", file);
	if (!(ptv = ptvopen(&ptvdisc, 16)))
		error(3, "cannot open ptv table");
	while (s = sfgetr(sp, '\n', 1))
		if (strtoip6(s, 0, prefix, prefix + IP6BITS))
			error(1, "%s: invalid prefix", s);
		else
		{
			if (dump)
				sfprintf(sfstderr, "insert  %s  %s\n", fmtip6(ptvmin(ptv->size, ptv->r[0], prefix, prefix[IP6BITS]), prefix[IP6BITS]), fmtip6(ptvmax(ptv->size, ptv->r[1], prefix, prefix[IP6BITS]), prefix[IP6BITS]));
			if (!ptvinsert(ptv, ptvmin(ptv->size, ptv->r[0], prefix, prefix[IP6BITS]), ptvmax(ptv->size, ptv->r[1], prefix, prefix[IP6BITS])))
			{
				error(2, "%s: ptv insertion error", s);
				break;
			}
		}
	sfclose(sp);
	if (dump)
		ptvdump(ptv, sfstdout);
	file = *argv++;
	do
	{
		if (!file || streq(file, "-"))
			sp = sfstdin;
		else if (!(sp = sfopen(0, file, "r")))
			error(ERROR_SYSTEM|3, "%s: cannot read address file", file);
		while (s = sfgetr(sp, '\n', 1))
			if (strtoip6(s, 0, addr, 0))
				error(1, "%s: invalid address", s);
			else if (pp = ptvmatch(ptv, addr))
				sfprintf(sfstdout, "%-38s %-38s %-38s\n", fmtip6(addr, -1), fmtip6(pp->min, -1), fmtip6(pp->max, -1));
			else
				sfprintf(sfstdout, "%-38s -\n", fmtip6(addr, -1));
		if (sp != sfstdin)
			sfclose(sp);
	} while (file && (file = *argv++));
	ptvclose(ptv);
	return 0;
}
Exemple #23
0
int
b_paste(int argc, char** argv, Shbltin_t* context)
{
	register int		n, sflag=0;
	register Sfio_t		*fp, **streams;
	register char 		*cp, *delim;
	char			*ep;
	Delim_t			*mp;
	int			dlen, dsiz;
	char			defdelim[2];

	cmdinit(argc, argv, context, ERROR_CATALOG, 0);
	delim = 0;
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 'd':
			delim = opt_info.arg;
			continue;
		case 's':
			sflag++;
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			break;
		case '?':
			error(ERROR_usage(2), "%s", opt_info.arg);
			break;
		}
		break;
	}
	argv += opt_info.index;
	if(error_info.errors)
		error(ERROR_usage(2),"%s", optusage(NiL));
	if(!delim || !*delim)
	{
		delim = defdelim;
		delim[0] = '\t';
		delim[1] = 0;
	}
	if (!(delim = strdup(delim)))
		error(ERROR_system(1), "out of space");
	dlen = dsiz = stresc(delim);
	mp = 0;
	if (mbwide())
	{
		cp = delim;
		ep = delim + dlen;
		dlen = 0;
		while (cp < ep)
		{
			mbchar(cp);
			dlen++;
		}
		if(dlen < dsiz)
		{
			if (!(mp = newof(0, Delim_t, dlen, 0)))
			{
				free(delim);
				error(ERROR_system(1), "out of space");
			}
			cp = delim;
			dlen = 0;
			while (cp < ep)
			{
				mp[dlen].chr = cp;
				mbchar(cp);
				mp[dlen].len = cp - mp[dlen].chr;
				dlen++;
			}
		}
	}
	if(cp = *argv)
	{
		n = argc - opt_info.index;
		argv++;
	}
	else
		n = 1;
	if(!sflag)
	{
		if (!(streams = (Sfio_t**)stakalloc(n*sizeof(Sfio_t*))))
			error(ERROR_exit(1), "out of space");
		n = 0;
	}
	do
	{
		if(!cp || streq(cp,"-"))
			fp = sfstdin;
		else if(!(fp = sfopen(NiL,cp,"r")))
			error(ERROR_system(0),"%s: cannot open",cp);
		if(fp && sflag)
		{
			if(spaste(fp,sfstdout,delim,dsiz,dlen,mp) < 0)
				error(ERROR_system(0),"write failed");
			if(fp!=sfstdin)
				sfclose(fp);
		}
		else if(!sflag)
			streams[n++] = fp;
	} while(cp= *argv++);
	if(!sflag)
	{
		if(error_info.errors==0 && paste(n,streams,sfstdout,delim,dsiz,dlen,mp) < 0)
			error(ERROR_system(0),"write failed");
		while(--n>=0)
			if((fp=streams[n]) && fp!=sfstdin)
				sfclose(fp);
	}
	if (mp)
		free(mp);
	free(delim);
	return(error_info.errors);
}
Exemple #24
0
void HRSstreamStart(HRSstream_t s,
		    void *filterFunction,
                    int numSlices,
		    HRSslice_t slices)
{
  assert(s != NULL);

  if (s->type == HRS_BINARYSTREAM) {
    s->bs->filter = (int (*)(char, void *, char *, char *))filterFunction;
    openFirstBinaryFile(s->bs);
  }
  else if (s->type == HRS_GENERALSTREAM) {
    s->gs->filter = (int (*)(char, void *, Sfio_t *, char *))filterFunction;
    openFirstGeneralFile(s->gs);
  }
  else if (s->type == HRS_GENERATIVESTREAM) {
    s->gens->filter = (int (*)(char, void *, char *))filterFunction;
  }
  else if (s->type == HRS_MAPSTREAM) {
    s->ms->filter = (int (*)(char, void *, char *, char *))filterFunction;
  }

  if (numSlices == 0)
    /* filter only stream */
    s->filterOnly = 1;
  else {
    int from_pipe[2];
    int to_pipe[2];
    int keySize;
    int recSize;
    Sfio_t *tp;
    fchandle *fch;
    int i;

    s->filterOnly = 0;

    /* set up fixcut to munge the data */
    fch = fcopen();
    for (i=0; i < numSlices; i++) {
      int bStrSize = numDigits(slices[i].begin);
      int eStrSize = numDigits(slices[i].end);
      int strSize = bStrSize + 1 + eStrSize + 
	                    strlen(slices[i].description) + 1;
      char *str = HRSmalloc(strSize, "HRSstreamStart");

      sfsprintf(str, strSize, "%d,%d%s", slices[i].begin,
		slices[i].end, slices[i].description);

      if (fcslice(fch, 'k', str) != 0)
	HRSerrorExit1("Fixcut error: %s\n" , fcerror(fch));

      /* do we need to/can we free str here? */
    }

    if ((recSize = fcready(fch, s->logicalSize)) < 0)
      HRSerrorExit1("Fixcut error: %s\n" , fcerror(fch));

    keySize = recSize - s->logicalSize;

    pipe(from_pipe);
    pipe(to_pipe);
    if (fork() == 0) {
      /* child */
      extern int HRSpuntExit;
      int ac;
      char **av;

      HRSpuntExit = 1;   /* don't do any work on exit in the child */

      av = buildSortStr(s, keySize, 0, 1, &ac);
      close(to_pipe[1]);
      close(from_pipe[0]);
      close(0); dup(to_pipe[0]); close(to_pipe[0]);
      close(1); dup(from_pipe[1]); close(from_pipe[1]);

      amrRSORT(ac, av);
      _exit(1);

    }
    else {
      /* parent */
      char *logicalData;
      uchar *mungedData;

      close(to_pipe[0]);
      close(from_pipe[1]);

      tp = sfnew(NULL, NULL, SF_UNBOUND, to_pipe[1], SF_WRITE | SF_SHARE);

      logicalData = HRSmalloc(s->logicalSize, "HRSstreamStart");

      while (getNextElement(s, logicalData) != 0) {
	int v;

	if ((mungedData = fcbuild(fch, (uchar *) logicalData, NULL)) == NULL)
	  HRSerrorExit1("Fixcut error: %s\n" , fcerror(fch));

        v = sfwrite(tp, mungedData, recSize);
	if (v == 0)
	  HRSerrorExit1("stream write to %s failed\n", s->streamName);
      }
      sfclose(tp);
      fcclose(fch);

      s->lfp = 
	sfnew(NULL, NULL, SF_UNBOUND, from_pipe[0], SF_READ | SF_SHARE);

      HRSfree(logicalData);
    }
  }
}
Exemple #25
0
MAIN()
{
  ssize_t size[N_WRITER][N_RECORD];
  int count[N_WRITER];
  char  record[N_WRITER][128], *s;
  Sfio_t* fw[N_WRITER];
  Sfio_t* fr;
  int i, r, done;

  /* create random record sizes */
  for(i = 0; i < N_WRITER; ++i)
  for(r = 0; r < N_RECORD; ++r)
    size[i][r] = (ssize_t)(vrandom()%64) + 2;

  /* records for different processes */
  for(i = 0; i < N_WRITER; ++i)
  for(r = 0; r < 128; ++r)
    record[i][r] = '0'+i;

  /* create file */
  fr = sfopen(NIL(Sfio_t*),tstfile(0),"w+");

  /* create records */
  for(i = 0; i < N_WRITER; ++i)
  { fw[i] = sfopen(NIL(Sfio_t*),tstfile(0),"a");
    count[i] = 0;
  }

  for(done = 0; done < N_WRITER; )
  { i = (int)(vrandom()%N_WRITER);
    if(count[i] < N_RECORD)
    { r = size[i][count[i]];
      if(!(s = sfreserve(fw[i],r,1)) || sfvalue(fw[i]) < r )
        terror("sfreserve fails in process %d\n", i);
      memcpy(s,record[i],r-1);
      s[r-1] = '\n';
      sfwrite(fw[i],s,r);

      if((count[i] += 1) == N_RECORD)
      { done += 1;
        sfclose(fw[i]);
      }
    }
  }

  for(i = 0; i < N_WRITER; ++i)
    count[i] = 0;

  while((s = sfgetr(fr,'\n',0)) )
  { if((i = s[0] - '0') < 0 || i >= N_WRITER)
      terror("Wrong record type\n");

    for(r = sfvalue(fr)-2; r > 0; --r)
      if(s[r] != s[0])
        terror("Bad record%d, count=%d\n", i, count[i]);

    if(sfvalue(fr) != size[i][count[i]])
      terror("Record%d count=%d size=%d sfvalue=%d\n",
        i, count[i], size[i][count[i]], sfvalue(fr));

    count[i] += 1;
  }

  for(i = 0; i < N_WRITER; ++i)
    if(count[i] != N_RECORD)
      terror("Bad count%d %d\n", i, count[i]);

  TSTEXIT(0);
}
Exemple #26
0
int
main(int argc, char** argv)
{
	register Mc_t*	mc;
	register char*	s;
	register char*	t;
	register int	c;
	register int	q;
	register int	i;
	int		num;
	char*		b;
	char*		e;
	char*		catfile;
	char*		msgfile;
	Sfio_t*		sp;
	Sfio_t*		mp;
	Sfio_t*		tp;
	Xl_t*		px;
	Xl_t*		bp;

	Xl_t*		xp = 0;
	int		format = 0;
	int		list = 0;
	int		set = 0;

	NoP(argc);
	error_info.id = "msggen";
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 'f':
			format = list = 1;
			continue;
		case 'l':
			list = 1;
			continue;
		case 's':
			set = 1;
			continue;
		case '?':
			error(ERROR_USAGE|4, "%s", opt_info.arg);
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			continue;
		}
		break;
	}
	argv += opt_info.index;
	if (error_info.errors || !(catfile = *argv++))
		error(ERROR_USAGE|4, "%s", optusage(NiL));

	/*
	 * set and list only need catfile
	 */

	if (set)
	{
		sfprintf(sfstdout, "%d\n", mcindex(catfile, NiL, NiL, NiL));
		return error_info.errors != 0;
	}
	else if (list)
	{
		if (!(sp = sfopen(NiL, catfile, "r")))
			error(ERROR_SYSTEM|3, "%s: cannot read catalog", catfile);
		if (!(mc = mcopen(sp)))
			error(ERROR_SYSTEM|3, "%s: catalog content error", catfile);
		sfclose(sp);
		if (format)
		{
			for (set = 1; set <= mc->num; set++)
				if (mc->set[set].num)
				{
					sfprintf(sfstdout, "$set %d\n", set);
					for (num = 1; num <= mc->set[set].num; num++)
						if (s = mc->set[set].msg[num])
							sfprintf(sfstdout, "%d \"%s\"\n", num, fmtfmt(s));
				}
		}
		else
		{
			if (*mc->translation)
			{
				ccsfprintf(CC_NATIVE, CC_ASCII, sfstdout, "$translation ");
				sfprintf(sfstdout, "%s", mc->translation);
				ccsfprintf(CC_NATIVE, CC_ASCII, sfstdout, "\n");
			}
			ccsfprintf(CC_NATIVE, CC_ASCII, sfstdout, "$quote \"\n");
			for (set = 1; set <= mc->num; set++)
				if (mc->set[set].num)
				{
					ccsfprintf(CC_NATIVE, CC_ASCII, sfstdout, "$set %d\n", set);
					for (num = 1; num <= mc->set[set].num; num++)
						if (s = mc->set[set].msg[num])
						{
							ccsfprintf(CC_NATIVE, CC_ASCII, sfstdout, "%d \"", num);
							while (c = *s++)
							{
								/*INDENT...*/

			switch (c)
			{
			case 0x22: /* " */
			case 0x5C: /* \ */
				sfputc(sfstdout, 0x5C);
				break;
			case 0x07: /* \a */
				c = 0x61;
				sfputc(sfstdout, 0x5C);
				break;
			case 0x08: /* \b */
				c = 0x62;
				sfputc(sfstdout, 0x5C);
				break;
			case 0x0A: /* \n */
				c = 0x6E;
				sfputc(sfstdout, 0x5C);
				break;
			case 0x0B: /* \v */
				c = 0x76;
				sfputc(sfstdout, 0x5C);
				break;
			case 0x0C: /* \f */
				c = 0x66;
				sfputc(sfstdout, 0x5C);
				break;
			case 0x0D: /* \r */
				c = 0x72;
				sfputc(sfstdout, 0x5C);
				break;
			}

								/*...UNDENT*/
								sfputc(sfstdout, c);
							}
							ccsfprintf(CC_NATIVE, CC_ASCII, sfstdout, "\"\n");
						}
				}
		}
		mcclose(mc);
		return error_info.errors != 0;
	}
	else if (!(msgfile = *argv++) || *argv)
		error(3, "exactly one message file must be specified");

	/*
	 * open the files and handles
	 */

	if (!(tp = sfstropen()))
		error(ERROR_SYSTEM|3, "out of space [string stream]");
	if (!(mp = sfopen(NiL, msgfile, "r")))
		error(ERROR_SYSTEM|3, "%s: cannot read message file", msgfile);
	sp = sfopen(NiL, catfile, "r");
	if (!(mc = mcopen(sp)))
		error(ERROR_SYSTEM|3, "%s: catalog content error", catfile);
	if (sp)
		sfclose(sp);
	xp = translation(xp, mc->translation);

	/*
	 * read the message file
	 */

	q = 0;
	set = 1;
	error_info.file = msgfile;
	while (s = sfgetr(mp, '\n', 1))
	{
		error_info.line++;
		if (!*s)
			continue;
		if (*s == '$')
		{
			if (!*++s || isspace(*s))
				continue;
			for (t = s; *s && !isspace(*s); s++);
			if (*s)
				*s++ = 0;
			if (streq(t, "delset"))
			{
				while (isspace(*s))
					s++;
				num = (int)strtol(s, NiL, 0);
				if (num < mc->num && mc->set[num].num)
					for (i = 1; i <= mc->set[num].num; i++)
						mcput(mc, num, i, NiL);
			}
			else if (streq(t, "quote"))
				q = *s ? *s : 0;
			else if (streq(t, "set"))
			{
				while (isspace(*s))
					s++;
				num = (int)strtol(s, &e, 0);
				if (e != s)
					set = num;
				else
					error(2, "set number expected");
			}
			else if (streq(t, "translation"))
				xp = translation(xp, s);
		}
		else
		{
			t = s + sfvalue(mp);
			num = (int)strtol(s, &e, 0);
			if (e != s)
			{
				s = e;
				if (!*s)
				{
					if (mcput(mc, set, num, NiL))
						error(2, "(%d,%d): cannot delete message", set, num);
				}
				else if (isspace(*s++))
				{
					if (t > (s + 1) && *(t -= 2) == '\\')
					{
						sfwrite(tp, s, t - s);
						while (s = sfgetr(mp, '\n', 0))
						{
							error_info.line++;
							t = s + sfvalue(mp);
							if (t <= (s + 1) || *(t -= 2) != '\\')
								break;
							sfwrite(tp, s, t - s);
						}
						if (!(s = sfstruse(tp)))
							error(ERROR_SYSTEM|3, "out of space");
					}
					if (q)
					{
						if (*s++ != q)
						{
							error(2, "(%d,%d): %c quote expected", set, num, q);
							continue;
						}
						b = t = s;
						while (c = *s++)
						{
							if (c == '\\')
							{
								c = chresc(s - 1, &e);
								s = e;
								if (c)
									*t++ = c;
								else
									error(1, "nul character ignored");
							}
							else if (c == q)
								break;
							else
								*t++ = c;
						}
						if (*s)
						{
							error(2, "(%d,%d): characters after quote not expected", set, num);
							continue;
						}
						*t = 0;
						s = b;
					}
					if (mcput(mc, set, num, s))
						error(2, "(%d,%d): cannot add message", set, num);
				}
				else
					error(2, "message text expected");
			}
			else
				error(2, "message number expected");
		}
	}
	error_info.file = 0;
	error_info.line = 0;

	/*
	 * fix up the translation record
	 */

	if (xp)
	{
		t = "";
		for (;;)
		{
			for (bp = 0, px = xp; px; px = px->next)
				if (px->date && (!bp || strcoll(bp->date, px->date) < 0))
					bp = px;
			if (!bp)
				break;
			sfprintf(tp, "%s%s %s", t, bp->name, bp->date);
			t = ", ";
			bp->date = 0;
		}
		if (!(mc->translation = sfstruse(tp)))
			error(ERROR_SYSTEM|3, "out of space");
	}

	/*
	 * dump the catalog to a local temporary
	 * rename if no errors
	 */

	if (!(s = pathtemp(NiL, 0, "", error_info.id, NiL)) || !(sp = sfopen(NiL, s, "w")))
		error(ERROR_SYSTEM|3, "%s: cannot write catalog file", catfile);
	if (mcdump(mc, sp) || mcclose(mc) || sfclose(sp))
	{
		remove(s);
		error(ERROR_SYSTEM|3, "%s: temporary catalog file write error", s);
	}
	remove(catfile);
	if (rename(s, catfile))
		error(ERROR_SYSTEM|3, "%s: cannot rename from temporary catalog file %s", catfile, s);
	return error_info.errors != 0;
}
Exemple #27
0
int
b_fold(int argc, char** argv, Shbltin_t* context)
{
	register int n, width=WIDTH;
	register Sfio_t *fp;
	register char *cp;
	char *cont="\n";
	size_t contsize = 1;
	char cols[1<<CHAR_BIT];

	cmdinit(argc, argv, context, ERROR_CATALOG, 0);
	memset(cols, 0, sizeof(cols));
	cols['\t'] = T_TAB;
	cols['\b'] = T_BS;
	cols['\n'] = T_NL;
	cols['\r'] = T_RET;
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 'b':
			cols['\r'] = cols['\b'] = 0;
			cols['\t'] = cols[' '];
			continue;
		case 'c':
			contsize = stresc(cont = strdup(opt_info.arg));
			continue;
		case 'd':
			if (n = *opt_info.arg)
				cols[n] = T_SP;
			continue;
		case 's':
			cols[' '] = T_SP;
			if(cols['\t']==0)
				cols['\t'] = T_SP;
			continue;
		case 'w':
			if ((width = opt_info.num) <= 0)
				error(2, "%d: width must be positive", opt_info.num);
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			continue;
		case '?':
			error(ERROR_usage(2), "%s", opt_info.arg);
			continue;
		}
		break;
	}
	argv += opt_info.index;
	argc -= opt_info.index;
	if(error_info.errors)
		error(ERROR_usage(2),"%s", optusage(NiL));
	if(cp = *argv)
		argv++;
	do
	{
		if(!cp || streq(cp,"-"))
			fp = sfstdin;
		else if(!(fp = sfopen(NiL,cp,"r")))
		{
			error(ERROR_system(0),"%s: cannot open",cp);
			error_info.errors = 1;
			continue;
		}
		fold(fp,sfstdout,width,cont,contsize,cols);
		if(fp!=sfstdin)
			sfclose(fp);
	}
	while(cp= *argv++);
	return(error_info.errors);
}
Exemple #28
0
int
b_mime(int argc, char** argv, Shbltin_t* context)
{
	Mime_t*		mp;
	char*		s;
	Sfio_t*		sp;
	int		silent;
	Mimedisc_t	disc;

	cmdinit(argc, argv, context, ERROR_CATALOG, 0);
	silent = 0;
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 0:
			break;
		case 's':
			silent = 1;
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			continue;
		case '?':
			error(ERROR_usage(2), "%s", opt_info.arg);
			continue;
		}
		break;
	}
	argc -= opt_info.index;
	argv += opt_info.index;
	if (error_info.errors || argc > 1 && argc < 3)
		error(ERROR_usage(2), "%s", optusage(NiL));
	disc.version = MIME_VERSION;
	disc.flags = 0;
	disc.errorf = errorf;
	if (!(mp = mimeopen(&disc)))
		error(ERROR_exit(1), "mime library error");
	if (mimeload(mp, NiL, 0))
	{
		mimeclose(mp);
		error(ERROR_exit(1), "mime load error");
	}
	if (argc <= 1)
		mimelist(mp, sfstdout, argv[0]);
	else if (!(sp = sfstropen()))
		error(ERROR_exit(1), "out of space");
	else
	{
		for (argc = 3; s = argv[argc]; argc++)
			sfputr(sp, s, ';');
		if (!(s = sfstruse(sp)))
			error(ERROR_exit(1), "out of space");
		if (!(s = mimeview(mp, argv[0], argv[1], argv[2], s)))
		{
			if (silent)
				exit(1);
			error(ERROR_exit(1), "no %s view for mime type %s", argv[0], argv[2]);
		}
		else
			sfputr(sfstdout, s, '\n');
		sfclose(sp);
	}
	mimeclose(mp);
	return 0;
}
Exemple #29
0
static void
cutfields(Cut_t* cut, Sfio_t* fdin, Sfio_t* fdout)
{
	register unsigned char *sp = cut->space;
	register unsigned char *cp;
	register unsigned char *wp;
	register int c, nfields;
	register const int *lp = cut->list;
	register unsigned char *copy;
	register int nodelim, empty, inword=0;
	register unsigned char *ep;
	unsigned char *bp, *first;
	int lastchar;
	wchar_t w;
	Sfio_t *fdtmp = 0;
	long offset = 0;
	unsigned char mb[8];
	/* process each buffer */
	while ((bp = (unsigned char*)sfreserve(fdin, SF_UNBOUND, -1)) && (c = sfvalue(fdin)) > 0)
	{
		cp = bp;
		ep = cp + --c;
		if((lastchar = cp[c]) != cut->eob)
			*ep = cut->eob;
		/* process each line in the buffer */
		while (cp <= ep)
		{
			first = cp;
			if (!inword)
			{
				nodelim = empty = 1;
				copy = cp;
				if (nfields = *(lp = cut->list))
					copy = 0;
				else
					nfields = *++lp;
			}
			else if (copy)
				copy = cp;
			inword = 0;
			do
			{
				/* skip over non-delimiter characters */
				if (cut->mb)
					for (;;)
					{
						switch (c = sp[*(unsigned char*)cp++])
						{
						case 0:
							continue;
						case SP_WIDE:
							wp = --cp;
							while ((c = mb2wc(w, cp, ep - cp)) <= 0)
							{
								/* mb char possibly spanning buffer boundary -- fun stuff */
								if ((ep - cp) < mbmax())
								{
									int	i;
									int	j;
									int	k;

									if (lastchar != cut->eob)
									{
										*ep = lastchar;
										if ((c = mb2wc(w, cp, ep - cp)) > 0)
											break;
									}
									if (copy)
									{
										empty = 0;
										if ((c = cp - copy) > 0 && sfwrite(fdout, (char*)copy, c) < 0)
											goto failed;
									}
									for (i = 0; i <= (ep - cp); i++)
										mb[i] = cp[i];
									if (!(bp = (unsigned char*)sfreserve(fdin, SF_UNBOUND, -1)) || (c = sfvalue(fdin)) <= 0)
										goto failed;
									cp = bp;
									ep = cp + --c;
									if ((lastchar = cp[c]) != cut->eob)
										*ep = cut->eob;
									j = i;
									k = 0;
									while (j < mbmax())
										mb[j++] = cp[k++];
									if ((c = mb2wc(w, (char*)mb, j)) <= 0)
									{
										c = i;
										w = 0;
									}
									first = bp = cp += c - i;
									if (copy)
									{
										copy = bp;
										if (w == cut->ldelim.chr)
											lastchar = cut->ldelim.chr;
										else if (w != cut->wdelim.chr)
										{
											empty = 0;
											if (sfwrite(fdout, (char*)mb, c) < 0)
												goto failed;
										}
									}
									c = 0;
								}
								else
								{
									w = *cp;
									c = 1;
								}
								break;
							}
							cp += c;
							c = w;
							if (c == cut->wdelim.chr)
							{
								c = SP_WORD;
								break;
							}
							if (c == cut->ldelim.chr)
							{
								c = SP_LINE;
								break;
							}
							continue;
						default:
							wp = cp - 1;
							break;
						}
						break;
					}
				else
				{
					while (!(c = sp[*cp++]));
					wp = cp - 1;
				}
				/* check for end-of-line */
				if (c == SP_LINE)
				{
					if (cp <= ep)
						break;
					if (lastchar == cut->ldelim.chr)
						break;
					/* restore cut->last character */
					if (lastchar != cut->eob)
						*ep = lastchar;
					inword++;
					if (!sp[lastchar])
						break;
				}
				nodelim = 0;	
				if (--nfields > 0)
					continue;
				nfields = *++lp;
				if (copy)
				{
					empty = 0;
					if ((c = wp - copy) > 0 && sfwrite(fdout, (char*)copy, c) < 0)
						goto failed;
					copy = 0;
				}
				else
					/* set to delimiter unless the first field */
					copy = empty ? cp : wp;
			} while (!inword);
			if (!inword)
			{
				if (!copy)
				{
					if (nodelim)
					{
						if (!cut->sflag)
						{
							if (offset)
							{
								sfseek(fdtmp,(Sfoff_t)0,SEEK_SET);
								sfmove(fdtmp,fdout,offset,-1);
							}
							copy = first;
						}
					}
					else
						sfputc(fdout,'\n');
				}
				if (offset)
					sfseek(fdtmp,offset=0,SEEK_SET);
			}
			if (copy && (c=cp-copy)>0 && (!nodelim || !cut->sflag) && sfwrite(fdout,(char*)copy,c)< 0)
				goto failed;
		}
		/* see whether to save in tmp file */
		if(inword && nodelim && !cut->sflag && (c=cp-first)>0)
		{
			/* copy line to tmpfile in case no fields */
			if(!fdtmp)
				fdtmp = sftmp(BLOCK);
			sfwrite(fdtmp,(char*)first,c);
			offset +=c;
		}
	}
 failed:
	if(fdtmp)
		sfclose(fdtmp);
}
Exemple #30
0
int
sendsmtp(Sfio_t* fp, char* host, char** argv, off_t original)
{
	register char*	s;
	register char*	t;
	char*		e;
	int		n;
	int		fd;
	int		r;
	off_t		z;
	Sfio_t*		sp;
	Sfio_t*		rp;
	char		buf[PATH_MAX];
	char		svc[PATH_MAX];

	/*
	 * connect to the service
	 */

	sfsprintf(svc, sizeof(svc), "/dev/tcp/%s/inet.smtp", host);
	if ((fd = csopen(&cs, svc, 0)) < 0)
	{
		note(SYSTEM, "smtp: %s: cannot connect to service", svc);
		return -1;
	}
	if (!(sp = sfnew(NiL, NiL, SF_UNBOUND, fd, SF_WRITE)) ||
	    !(rp = sfnew(NiL, NiL, SF_UNBOUND, fd, SF_READ)))
	{
		if (sp)
			sfclose(sp);
		else
			close(fd);
		note(SYSTEM, "smtp: %s: cannot buffer service", svc);
		return -1;
	}

	/*
	 * verify
	 */

	do
	{
		if (!(s = sfgetr(rp, '\n', 1)))
			goto bad_recv;
		if (strtol(s, &e, 10) != SMTP_READY)
			goto bad_prot;
	} while (*e == '-');

	/*
	 * identify
	 */

	if (!(s = state.var.domain) || !*s)
		s = state.var.hostname;
	if (sfprintf(sp, "HELO %s\r\n", s) < 0)
		goto bad_send;
	do
	{
		if (!(s = sfgetr(rp, '\n', 1)))
			goto bad_recv;
		if (strtol(s, &e, 10) != SMTP_OK)
			goto bad_prot;
	} while (*(unsigned char*)e == SMTP_OK);

	/*
	 * from
	 */

	if (original)
	{
		if (!(s = sfgetr(fp, '\n', 1)) || !strneq(s, "From ", 5))
			goto bad_mesg;
		for (s += 5; isspace(*s); s++);
		for (t = s; *t && !isspace(*t); t++);
		if (!(n = t - s))
			goto bad_mesg;
		z = sfvalue(fp);
		if (sfprintf(sp, "MAIL FROM:<%*.*s>\r\n", n, n, s) < 0)
			goto bad_send;
	}
	else
	{
		z = 0;
		if ((state.var.domain ?
		     sfprintf(sp, "MAIL FROM:<%s@%s>\r\n", state.var.user, state.var.domain) :
		     sfprintf(sp, "MAIL FROM:<%s>\r\n", state.var.user)) < 0)
			goto bad_send;
	}
	do
	{
		if (!(s = sfgetr(rp, '\n', 1)))
			goto bad_recv;
		if (strtol(s, &e, 10) != SMTP_OK)
			goto bad_prot;
	} while (*e == '-');

	/*
	 * to
	 */

	while (s = *argv++)
	{
		if ((state.var.domain && !strchr(s, '@') ?
		     sfprintf(sp, "RCPT TO:<%s@%s>\r\n", s, state.var.domain) :
		     sfprintf(sp, "RCPT TO:<%s>\r\n", s)) < 0)
			goto bad_send;
		do
		{
			if (!(s = sfgetr(rp, '\n', 1)))
				goto bad_recv;
			if (strtol(s, &e, 10) != SMTP_OK)
				goto bad_prot;
		} while (*e == '-');
	}

	/*
	 * body
	 */

	if (sfprintf(sp, "DATA\r\n") < 0)
		goto bad_send;
	do
	{
		if (!(s = sfgetr(rp, '\n', 1)))
			goto bad_recv;
		if (strtol(s, &e, 10) != SMTP_START)
			goto bad_prot;
	} while (*e == '-');
	tmfmt(buf, sizeof(buf), "%+uDate: %a, %d %b %Y %H:%M:%S UT", NiL);
	if (sfputr(sp, buf, '\n') < 0)
		goto bad_send;
	if (sfprintf(sp, "From: <%s@%s>\n", state.var.user, host) < 0)
		goto bad_send;
	while (s = sfgetr(fp, '\n', 1))
	{
		if (sfprintf(sp, "%s%s\r\n", *s == '.' ? "." : "", s) < 0)
			goto bad_send;
		if (original && (z += sfvalue(fp)) >= original)
			break;
	}
	if (sfprintf(sp, ".\r\n") < 0)
		goto bad_send;
	do
	{
		if (!(s = sfgetr(rp, '\n', 1)))
			goto bad_recv;
		if (strtol(s, &e, 10) != SMTP_OK)
			goto bad_prot;
	} while (*e == '-');

	/*
	 * quit
	 */

	if (sfprintf(sp, "QUIT\r\n") < 0)
		goto bad_send;
	do
	{
		if (!(s = sfgetr(rp, '\n', 1)))
			goto bad_recv;
		if (strtol(s, &e, 10) != SMTP_CLOSE)
			goto bad_prot;
	} while (*e == '-');
	r = 0;
	goto done;
 bad_mesg:
	note(0, "smtp: bad message -- no From header");
	goto bad;
 bad_prot:
	if ((n = strlen(e)) > 0 && e[n - 1] == '\r')
		e[n - 1] = 0;
	note(0, "smtp: %s: service error:%s", svc, e);
	goto bad;
 bad_send:
	note(SYSTEM, "smtp: %s: service write error", svc);
	goto bad;
 bad_recv:
	note(SYSTEM, "smtp: %s: service read error", svc);
 bad:
	r = -1;
 done:
	sfclose(sp);
	sfclose(rp);
	return r;
}