Beispiel #1
0
bool IsDir(const Stroka& path) {
    return isdir(path.c_str()) == 0;
}
Beispiel #2
0
bool sbbs_t::pack_rep(uint hubnum)
{
	char		str[MAX_PATH+1];
	char 		tmp[MAX_PATH+1],tmp2[MAX_PATH+1];
	char		hubid_upper[LEN_QWKID+1];
	char		hubid_lower[LEN_QWKID+1];
	int 		file,mode;
	uint		i,j,k;
	long		msgcnt,submsgs,packedmail,netfiles=0,deleted;
	uint32_t	u;
	uint32_t	posts;
	uint32_t	mailmsgs;
	ulong		msgs;
	uint32_t	last;
	post_t*		post;
	mail_t*		mail;
	FILE*		rep;
	FILE*		hdrs=NULL;
	DIR*		dir;
	DIRENT*		dirent;
	smbmsg_t	msg;

	msgcnt=0L;
	delfiles(cfg.temp_dir,ALLFILES);

	SAFECOPY(hubid_upper,cfg.qhub[hubnum]->id);
	strupr(hubid_upper);
	SAFECOPY(hubid_lower,cfg.qhub[hubnum]->id);
	strlwr(hubid_lower);

	SAFEPRINTF2(str,"%s%s.REP",cfg.data_dir,hubid_upper);
	if(fexistcase(str)) {
		eprintf(LOG_INFO,"Updating %s", str);
		external(cmdstr(cfg.qhub[hubnum]->unpack,str,ALLFILES,NULL),EX_OFFLINE);
	} else
		eprintf(LOG_INFO,"Creating %s", str);
	/*************************************************/
	/* Create SYSID.MSG, write header and leave open */
	/*************************************************/
	SAFEPRINTF2(str,"%s%s.MSG",cfg.temp_dir,hubid_upper);
	fexistcase(str);
	if((rep=fnopen(&file,str,O_CREAT|O_WRONLY|O_TRUNC))==NULL) {
		errormsg(WHERE,ERR_CREATE,str,O_CREAT|O_WRONLY|O_TRUNC);
		return(false);
	}
	if(filelength(file)<1) { 							/* New REP packet */
		SAFEPRINTF2(str,"%-*s"
			,QWK_BLOCK_LEN,hubid_upper);		/* So write header */
		fwrite(str,QWK_BLOCK_LEN,1,rep); 
	}
	fseek(rep,0L,SEEK_END);

	/* Always includes HEADERS.DAT in .REP packets which are only for QWKnet hubs */
	/* And *usually* a Synchronet system */
	SAFEPRINTF(str,"%sHEADERS.DAT",cfg.temp_dir);
	fexistcase(str);
	if((hdrs=fopen(str,"a"))==NULL)
		errormsg(WHERE,ERR_CREATE,str,0);

	/*********************/
	/* Pack new messages */
	/*********************/
	SAFEPRINTF(smb.file,"%smail",cfg.data_dir);
	smb.retry_time=cfg.smb_retry_time;
	smb.subnum=INVALID_SUB;
	if((i=smb_open(&smb))!=0) {
		fclose(rep);
		if(hdrs!=NULL)
			fclose(hdrs);
		errormsg(WHERE,ERR_OPEN,smb.file,i,smb.last_error);
		return(false); 
	}

	/***********************/
	/* Pack E-mail, if any */
	/***********************/
	qwkmail_last=0;
	mail=loadmail(&smb,&mailmsgs,0,MAIL_YOUR,0);
	packedmail=0;
	if(mailmsgs) {
		eprintf(LOG_INFO,"Packing NetMail for %s", cfg.qhub[hubnum]->id);
		for(u=0;u<mailmsgs;u++) {
	//		bprintf("\b\b\b\b\b%-5lu",u+1);

			memset(&msg,0,sizeof(msg));
			msg.idx=mail[u];
			if(msg.idx.number>qwkmail_last)
				qwkmail_last=msg.idx.number;
			if(!loadmsg(&msg,mail[u].number))
				continue;

			SAFEPRINTF(str,"%s/",cfg.qhub[hubnum]->id);
			if(msg.to_net.type!=NET_QWK
				|| (strcmp((char *)msg.to_net.addr,cfg.qhub[hubnum]->id)
				&& strncmp((char *)msg.to_net.addr,str,strlen(str)))) {
				smb_unlockmsghdr(&smb,&msg);
				smb_freemsgmem(&msg);
				continue; 
			}

			msgtoqwk(&msg,rep,QM_TO_QNET|QM_REP|A_LEAVE,INVALID_SUB,0,hdrs);
			packedmail++;
			smb_unlockmsghdr(&smb,&msg);
			smb_freemsgmem(&msg); 
			YIELD();	/* yield */
		}
		eprintf(LOG_INFO,"Packed %d NetMail messages",packedmail); 
	}
	smb_close(&smb);					/* Close the e-mail */
	if(mailmsgs)
		free(mail);

	for(i=0;i<cfg.qhub[hubnum]->subs;i++) {
		j=cfg.qhub[hubnum]->sub[i]; 			/* j now equals the real sub num */
		msgs=getlastmsg(j,&last,0);
		lncntr=0;						/* defeat pause */
		if(!msgs || last<=subscan[j].ptr) {
			if(subscan[j].ptr>last) {
				subscan[j].ptr=last;
				subscan[j].last=last; 
			}
			eprintf(LOG_INFO,remove_ctrl_a(text[NScanStatusFmt],tmp)
				,cfg.grp[cfg.sub[j]->grp]->sname
				,cfg.sub[j]->lname,0L,msgs);
			continue; 
		}

		SAFEPRINTF2(smb.file,"%s%s"
			,cfg.sub[j]->data_dir,cfg.sub[j]->code);
		smb.retry_time=cfg.smb_retry_time;
		smb.subnum=j;
		if((k=smb_open(&smb))!=0) {
			errormsg(WHERE,ERR_OPEN,smb.file,k,smb.last_error);
			continue; 
		}

		post=loadposts(&posts,j,subscan[j].ptr,LP_BYSELF|LP_OTHERS|LP_PRIVATE|LP_REP,NULL);
		eprintf(LOG_INFO,remove_ctrl_a(text[NScanStatusFmt],tmp)
			,cfg.grp[cfg.sub[j]->grp]->sname
			,cfg.sub[j]->lname,posts,msgs);
		if(!posts)	{ /* no new messages */
			smb_close(&smb);
			continue; 
		}

		subscan[j].ptr=last;                   /* set pointer */
		eprintf(LOG_INFO,"%s",remove_ctrl_a(text[QWKPackingSubboard],tmp));	/* ptr to last msg	*/
		submsgs=0;
		for(u=0;u<posts;u++) {
	//		bprintf("\b\b\b\b\b%-5lu",u+1);

			memset(&msg,0,sizeof(msg));
			msg.idx=post[u];
			if(!loadmsg(&msg,post[u].number))
				continue;

			if(msg.from_net.type && msg.from_net.type!=NET_QWK &&
				!(cfg.sub[j]->misc&SUB_GATE)) {
				smb_freemsgmem(&msg);
				smb_unlockmsghdr(&smb,&msg);
				continue; 
			}

			if(!strnicmp(msg.subj,"NE:",3) || (msg.from_net.type==NET_QWK &&
				route_circ((char *)msg.from_net.addr,cfg.qhub[hubnum]->id))) {
				smb_freemsgmem(&msg);
				smb_unlockmsghdr(&smb,&msg);
				continue; 
			}

			mode=cfg.qhub[hubnum]->mode[i]|QM_TO_QNET|QM_REP;
			if(mode&A_LEAVE) mode|=(QM_VIA|QM_TZ|QM_MSGID);
			if(msg.from_net.type!=NET_QWK)
				mode|=QM_TAGLINE;

			msgtoqwk(&msg,rep,mode,j,cfg.qhub[hubnum]->conf[i],hdrs);

			smb_freemsgmem(&msg);
			smb_unlockmsghdr(&smb,&msg);
			msgcnt++;
			submsgs++; 
			if(!(u%50))
				YIELD(); /* yield */
		}
		eprintf(LOG_INFO,remove_ctrl_a(text[QWKPackedSubboard],tmp),submsgs,msgcnt);
		free(post);
		smb_close(&smb); 
		YIELD();	/* yield */
	}

	if(hdrs!=NULL)
		fclose(hdrs);
	fclose(rep);			/* close HUB_ID.MSG */
	CRLF;
							/* Look for extra files to send out */
	SAFEPRINTF2(str,"%sqnet/%s.out",cfg.data_dir,hubid_lower);
	dir=opendir(str);
	while(dir!=NULL && (dirent=readdir(dir))!=NULL) {
		SAFEPRINTF3(str,"%sqnet/%s.out/%s",cfg.data_dir,hubid_lower,dirent->d_name);
		if(isdir(str))
			continue;
		SAFEPRINTF2(tmp2,"%s%s",cfg.temp_dir,dirent->d_name);
		eprintf(LOG_INFO,remove_ctrl_a(text[RetrievingFile],tmp),str);
		if(!mv(str,tmp2,/* copy: */TRUE))
			netfiles++;
	}
	if(dir!=NULL)
		closedir(dir);
	if(netfiles)
		CRLF;

	if(!msgcnt && !netfiles && !packedmail) {
		eprintf(LOG_INFO,remove_ctrl_a(text[QWKNoNewMessages],tmp));
		return(true);	// Changed from false Mar-11-2005 (needs to be true to save updated ptrs)
	}

	/*******************/
	/* Compress Packet */
	/*******************/
	SAFEPRINTF2(str,"%s%s.REP",cfg.data_dir,hubid_upper);
	SAFEPRINTF2(tmp2,"%s%s",cfg.temp_dir,ALLFILES);
	i=external(cmdstr(cfg.qhub[hubnum]->pack,str,tmp2,NULL)
		,EX_OFFLINE|EX_WILDCARD);
	if(!fexistcase(str)) {
		eprintf(LOG_WARNING,"%s",remove_ctrl_a(text[QWKCompressionFailed],tmp));
		if(i)
			errormsg(WHERE,ERR_EXEC,cmdstr(cfg.qhub[hubnum]->pack,str,tmp2,NULL),i);
		else
			lprintf(LOG_ERR, "Couldn't compress REP packet");
		return(false); 
	}
	SAFEPRINTF2(str,"%sqnet/%s.out/",cfg.data_dir,hubid_lower);
	delfiles(str,ALLFILES);

	if(packedmail) {						/* Delete NetMail */
		SAFEPRINTF(smb.file,"%smail",cfg.data_dir);
		smb.retry_time=cfg.smb_retry_time;
		smb.subnum=INVALID_SUB;
		if((i=smb_open(&smb))!=0) {
			errormsg(WHERE,ERR_OPEN,smb.file,i,smb.last_error);
			return(true); 
		}

		mail=loadmail(&smb,&mailmsgs,0,MAIL_YOUR,0);

		if((i=smb_locksmbhdr(&smb))!=0) {			  /* Lock the base, so nobody */
			if(mailmsgs)
				free(mail);
			smb_close(&smb);
			errormsg(WHERE,ERR_LOCK,smb.file,i,smb.last_error);	/* messes with the index */
			return(true); 
		}

		if((i=smb_getstatus(&smb))!=0) {
			if(mailmsgs)
				free(mail);
			smb_close(&smb);
			errormsg(WHERE,ERR_READ,smb.file,i,smb.last_error);
			return(true); 
		}

		deleted=0;
		/* Mark as READ and DELETE */
		for(u=0;u<mailmsgs;u++) {
			if(mail[u].number>qwkmail_last)
				continue;
			memset(&msg,0,sizeof(msg));
			/* !IMPORTANT: search by number (do not initialize msg.idx.offset) */
			if(!loadmsg(&msg,mail[u].number))
				continue;

			SAFEPRINTF(str,"%s/",cfg.qhub[hubnum]->id);
			if(msg.to_net.type!=NET_QWK
				|| (strcmp((char *)msg.to_net.addr,cfg.qhub[hubnum]->id)
				&& strncmp((char *)msg.to_net.addr,str,strlen(str)))) {
				smb_unlockmsghdr(&smb,&msg);
				smb_freemsgmem(&msg);
				continue; 
			}

			msg.hdr.attr|=MSG_DELETE;
			msg.idx.attr=msg.hdr.attr;
			if((i=smb_putmsg(&smb,&msg))!=0)
				errormsg(WHERE,ERR_WRITE,smb.file,i,smb.last_error);
			else
				deleted++;
			smb_unlockmsghdr(&smb,&msg);
			smb_freemsgmem(&msg); 
		}

		if(deleted && cfg.sys_misc&SM_DELEMAIL)
			delmail(0,MAIL_YOUR);
		smb_close(&smb);
		if(mailmsgs)
			free(mail); 
		eprintf(LOG_INFO,"Deleted %d sent NetMail messages",deleted); 
	}

	return(true);
}
Beispiel #3
0
void main(int argc,String *argv) {
  
  String batname=Sconc(JPATH(),"/tmp/forall.bat");

  ArgParser a=ArgParser(argc,argv);
//    a.comment("Syntax: forall <files> do <command>\n");
//    a.comment("    or: forall in <filename> do <command>\n");
    a.comment("  <command> may use %f as the filename,");
    a.comment("    %s as the filename stripped of extensions,");
    a.comment("    %e as the filename's extension,");
    a.comment("    %l as %f in lower case,");
    a.comment("    %L as %w in lower case,");
    a.comment("    %w as the whole path of the filename,");
    a.comment("    %n as the number of the file being processed,");
    a.comment("    %a as & , %p as > , %q as \" ,");
    a.comment("    and : to seperate commands.");
    #ifdef DOS
      a.comment("    For DOS, use $ instead of %");
    #endif
  bool dirsonly=a.argexists("-dirsonly","execute command on directories only");
  bool filesonly=a.argexists("-filesonly","execute command on non-directories only");
  bool linkeddirsok=a.argexists("-followdirs","follow sym linked directories");
  bool linkedfilesok=!a.argexists("-nofollowfiles","don't follow sym linked files");
  bool showprogress=a.argexists("-showprog","show progress");
  bool shell=a.argexists("-shell","run commands through a shell file");
  a.comment("    A forall command in shell mode is not the same in non-shell mode");
  a.comment("    since in the shell program the state will persist between each file.");
  bool ccomments =!a.argexists("-//","[in]: ignore // commenting");
  bool shcomments=!a.argexists("-#"," [in]: ignore # commenting");
  quiet=a.argexists("-stealth","don't print stuff");
  int padzeros=a.intafter("-padzeros","pad %n with this many 0s on left",3);
  String padzeroformat=Sformat("%s0%ii","%",padzeros);
  bool checkforfilename=false;
  if (argc<3 || a.helpon) {
    a.com="forall <files> do <command>   OR\nforall in <filename> do <command>";
    a.helpon=true;
    a.done();
    exit(0);
  }

  // Read files until do
  if (showprogress)
    printf("Files: ");
  List<String> fs;
  if (!Seq(a.arg(1),"in")) { // Files provided as arguments
    String s="";
    while (!Seq(s,"do") && a.argsleft()) {
      s=a.getarg(1);
      if (!Seq(s,"do")) {
        if (showprogress)
          printf("%s ",s);
        boolean okay=true;
//        if (checkforfilename)
//          fs.add(getfiles(s));
//        else
/*        if (!fileexists(s)) {
          if (!quiet)
            printf("Didn't find file %s\n",s);
          okay=false;
        }*/
        if (isdir(s)) {
          if (filesonly)
            okay=false;
          if (islink(s) && !linkeddirsok)
            okay=false;
        } else { // not dir => file
          if (dirsonly)
            okay=false;
          if (islink(s) && !linkedfilesok)
            okay=false;
        }
        if ( (dirsonly || filesonly) &&
             !fileexists(s) )
          okay=false;
        if ((Sinstr(s,"*")>0) || (Sinstr(s,"?")>0)) { // Unresolved wildcard
          okay=false;
          if (!quiet)
            printf("forall: Did not find any \"%s\"\n",s);
        }
        if (Slen(s)==0)
          okay=false;
        if (okay)
          fs.add(s);
      }
    }
  } else { // Points to file containing list of files for forall
    String tmp=a.getarg(1);
    String fname=a.getarg(1);
    tmp=a.getarg(1);
    if (!Seq(tmp,"do"))
      error("Expected do in forall in <fname> do ...");
    fs.add(readlinesfromfile(fname));
    for (int i=1;i<=fs.len;i++) {
      String s=fs.num(i);
      if ( Slen(s)==0
        || (dirsonly && !isdir(s))
        || (filesonly && isdir(s))
        || (ccomments && Sstarts(s,"//"))
        || (shcomments && Sstarts(s,"#")) ) {
        fs.removenumkeeporder(i);
        i--;
      }
    }
    if (showprogress)
      printf("%s ",fs.num(fs.len));
  }
  if (showprogress)
    printf("\n");

  // Read command after do
  if (showprogress)
    printf("Command: ");
  a.com=Sconc(a.com,"do <command> ");
  List<String> ls;
  while (a.argsleft()) {
    ls.add(Ssplitaround(a.getarg(1)," "));
    if (showprogress)
      printf("\"%s\" ",ls.num(ls.len));
  }
  if (showprogress)
    printf("\n");
  if (ls.len==0)
    a.error("You must provide <command>");
  a.done();
  
  FILE *progress=NULL;
  progress=fopen("forall.progress","w");
  List<String> coms;
  for (int i=1;i<=fs.len;i++) {
    String whole=fs.num(i);
    if (Slen(whole)>0) {
      String fname;
      int n=max(Sinstrlast(whole,"/"),Sinstrlast(whole,"\\"));
      if (n==0)
        fname=whole;
      else
        fname=Sfrom(whole,n+1);
      String strlow=Stolower(fname);
      String wholelow=Stolower(whole);
      /* Remove all '.'s
      int k;
      while ((k=Sinstr(str,"."))>0) {
        str=Sleft(str,k-1);
      } */
      int k=Sinstrlast(fname,".");
      String str=( k<=0 ? fname : Sleft(fname,k-1) );
      String ext=( k<=0 ? Snew("") : Sfrom(fname,k+1) );
      // List<String> coms;
      if (!shell)
        coms.clear();
      String com="";
      for (int j=1;j<=ls.len;j++) {
        String arg=ls.num(j);
  //      if (showprogress)
  //        printf("%s -> ",arg);
        #ifdef DOS
        arg=Sreplaceall(arg,"$n",Sformat(padzeroformat,i));
        arg=Sreplaceall(arg,"$a","&");
        arg=Sreplaceall(arg,"$f",fname);
        arg=Sreplaceall(arg,"$w",whole);
        arg=Sreplaceall(arg,"$s",str);
        arg=Sreplaceall(arg,"$e",ext);
        arg=Sreplaceall(arg,"$l",strlow);
        arg=Sreplaceall(arg,"$L",wholelow);
        arg=Sreplaceall(arg,"$p",">");
        arg=Sreplaceall(arg,"$q","\"");
        #else
        arg=Sreplaceall(arg,"\%n",Sformat(padzeroformat,i));
        arg=Sreplaceall(arg,"\%a","&");
        arg=Sreplaceall(arg,"\%f",fname);
        arg=Sreplaceall(arg,"\%w",whole);
        arg=Sreplaceall(arg,"\%s",str);
        arg=Sreplaceall(arg,"\%e",ext);
        arg=Sreplaceall(arg,"\%l",strlow);
        arg=Sreplaceall(arg,"\%L",wholelow);
        arg=Sreplaceall(arg,"\%p",">");
        arg=Sreplaceall(arg,"\%q","\"");
        #endif
  //      if (showprogress)
  //        printf("%s -> ",arg);
        if (Seq(arg,":")) {
          com=Srls(com);
          if (!quiet) {
            // printf("# (%03i/%i) %s\n",i,fs.len,com);
            String output=Sformat("# (%03i/%i) %s",i,fs.len,com);
            if (shell) // Print it later when the shell is being executed
              coms.add(Sconc("echo \"",Stoechoformat(output),"\""));
            else
              printf("%s\n",output);
          }
          if (shell)
            coms.add(com);
          else
            system(com);
          com="";
        } else
          com=Sconc(com," ",arg);
  /*      if (showprogress) {
          printf("%s\n>",com);
          for (int k=1;k<=ls.len;k++)
            printf("%s ",ls.num(k));
          printf("\n");
        }*/
      }
      com=Srls(com);
          if (!quiet) {
            String output=Sformat("# (%03i/%i) %s",i,fs.len,com);
            if (shell) // Print it later when the shell is being executed
              coms.add(Sconc("echo \"",Stoechoformat(output),"\""));
            else
              printf("%s\n",output);
          }
      if (progress!=NULL)
        fprintf(progress,"-%03i/%i- %s\n",i,fs.len,com);
      if (shell)
        coms.add(com);
      else
        system(com);
    }
  }
Beispiel #4
0
static int amatch(char *s, char *p)
{
    register int scc;
    int ok, lc;
    char *sgpathp;
    struct stat stb;
    int c, cc;

    globbed = 1;
    for (;;) {
	scc = *s++ & TRIM;
	switch (c = *p++) {

	case '{':
	    return (execbrc(p - 1, s - 1));

	case '[':
	    ok = 0;
	    lc = 077777;
	    while ((cc = *p++)) {
		if (cc == ']') {
		    if (ok)
			break;
		    return (0);
		}
		if (cc == '-') {
		    if (lc <= scc && scc <= *p++)
			ok++;
		}
		else if (scc == (lc = cc))
		    ok++;
	    }
	    if (cc == 0) {
		globerr = "Missing ]";
		return (0);
	    }
	    continue;

	case '*':
	    if (!*p)
		return (1);
	    if (*p == '/') {
		p++;
		goto slash;
	    }
	    s--;
	    do {
		if (amatch(s, p))
		    return (1);
	    } while (*s++);
	    return (0);

	case 0:
	    return (scc == 0);

	default:
	    if (c != scc)
		return (0);
	    continue;

	case '?':
	    if (scc == 0)
		return (0);
	    continue;

	case '/':
	    if (scc)
		return (0);
	  slash:
	    s = entp;
	    sgpathp = gpathp;
	    while (*s)
		addpath(*s++);
	    addpath('/');
	    if (stat(gpath, &stb) == 0 && isdir(stb))
		if (*p == 0) {
		    Gcat(gpath, "");
		    globcnt++;
		}
		else
		    expand(p);
	    gpathp = sgpathp;
	    *gpathp = 0;
	    return (0);
	}
    }
}
Beispiel #5
0
// install installs the library, package, or binary associated with dir,
// which is relative to $GOROOT/src.
static void
install(char *dir)
{
	char *name, *p, *elem, *prefix, *exe;
	bool islib, ispkg, isgo, stale, ispackcmd;
	Buf b, b1, path;
	Vec compile, files, link, go, missing, clean, lib, extra;
	Time ttarg, t;
	int i, j, k, n, doclean, targ;

	if(vflag) {
		if(!streq(goos, gohostos) || !streq(goarch, gohostarch))
			errprintf("%s (%s/%s)\n", dir, goos, goarch);
		else
			errprintf("%s\n", dir);
	}

	binit(&b);
	binit(&b1);
	binit(&path);
	vinit(&compile);
	vinit(&files);
	vinit(&link);
	vinit(&go);
	vinit(&missing);
	vinit(&clean);
	vinit(&lib);
	vinit(&extra);


	// path = full path to dir.
	bpathf(&path, "%s/src/%s", goroot, dir);
	name = lastelem(dir);

	// For misc/prof, copy into the tool directory and we're done.
	if(hasprefix(dir, "misc/")) {
		copy(bpathf(&b, "%s/%s", tooldir, name),
			bpathf(&b1, "%s/misc/%s", goroot, name), 1);
		goto out;
	}

	// For release, cmd/prof is not included.
	if((streq(dir, "cmd/prof")) && !isdir(bstr(&path))) {
		if(vflag > 1)
			errprintf("skipping %s - does not exist\n", dir);
		goto out;
	}

	// set up gcc command line on first run.
	if(gccargs.len == 0) {
		bprintf(&b, "%s %s", defaultcc, defaultcflags);
		splitfields(&gccargs, bstr(&b));
		for(i=0; i<nelem(proto_gccargs); i++)
			vadd(&gccargs, proto_gccargs[i]);
		if(defaultcflags[0] == '\0') {
			for(i=0; i<nelem(proto_gccargs2); i++)
				vadd(&gccargs, proto_gccargs2[i]);
		}
		if(contains(gccargs.p[0], "clang")) {
			// disable ASCII art in clang errors, if possible
			vadd(&gccargs, "-fno-caret-diagnostics");
			// clang is too smart about unused command-line arguments
			vadd(&gccargs, "-Qunused-arguments");
		}
		// disable word wrapping in error messages
		vadd(&gccargs, "-fmessage-length=0");
		if(streq(gohostos, "darwin")) {
			// golang.org/issue/5261
			vadd(&gccargs, "-mmacosx-version-min=10.6");
		}
	}
	if(ldargs.len == 0 && defaultldflags[0] != '\0') {
		bprintf(&b, "%s", defaultldflags);
		splitfields(&ldargs, bstr(&b));
	}

	islib = hasprefix(dir, "lib") || streq(dir, "cmd/cc") || streq(dir, "cmd/gc");
	ispkg = hasprefix(dir, "pkg");
	isgo = ispkg || streq(dir, "cmd/go") || streq(dir, "cmd/cgo");

	exe = "";
	if(streq(gohostos, "windows"))
		exe = ".exe";

	// Start final link command line.
	// Note: code below knows that link.p[targ] is the target.
	ispackcmd = 0;
	if(islib) {
		// C library.
		vadd(&link, "ar");
		if(streq(gohostos, "plan9"))
			vadd(&link, "rc");
		else
			vadd(&link, "rsc");
		prefix = "";
		if(!hasprefix(name, "lib"))
			prefix = "lib";
		targ = link.len;
		vadd(&link, bpathf(&b, "%s/pkg/obj/%s_%s/%s%s.a", goroot, gohostos, gohostarch, prefix, name));
	} else if(ispkg) {
		// Go library (package).
		ispackcmd = 1;
		vadd(&link, "pack"); // program name - unused here, but all the other cases record one
		p = bprintf(&b, "%s/pkg/%s_%s/%s", goroot, goos, goarch, dir+4);
		*xstrrchr(p, '/') = '\0';
		xmkdirall(p);
		targ = link.len;
		vadd(&link, bpathf(&b, "%s/pkg/%s_%s/%s.a", goroot, goos, goarch, dir+4));
	} else if(streq(dir, "cmd/go") || streq(dir, "cmd/cgo")) {
		// Go command.
		vadd(&link, bpathf(&b, "%s/%sl", tooldir, gochar));
		vadd(&link, "-o");
		elem = name;
		if(streq(elem, "go"))
			elem = "go_bootstrap";
		targ = link.len;
		vadd(&link, bpathf(&b, "%s/%s%s", tooldir, elem, exe));
	} else {
		// C command. Use gccargs and ldargs.
		if(streq(gohostos, "plan9")) {
			vadd(&link, bprintf(&b, "%sl", gohostchar));
			vadd(&link, "-o");
			targ = link.len;
			vadd(&link, bpathf(&b, "%s/%s", tooldir, name));
		} else {
			vcopy(&link, gccargs.p, gccargs.len);
			vcopy(&link, ldargs.p, ldargs.len);
			if(sflag)
				vadd(&link, "-static");
			vadd(&link, "-o");
			targ = link.len;
			vadd(&link, bpathf(&b, "%s/%s%s", tooldir, name, exe));
			if(streq(gohostarch, "amd64"))
				vadd(&link, "-m64");
			else if(streq(gohostarch, "386"))
				vadd(&link, "-m32");
		}
	}
	ttarg = mtime(link.p[targ]);

	// Gather files that are sources for this target.
	// Everything in that directory, and any target-specific
	// additions.
	xreaddir(&files, bstr(&path));

	// Remove files beginning with . or _,
	// which are likely to be editor temporary files.
	// This is the same heuristic build.ScanDir uses.
	// There do exist real C files beginning with _,
	// so limit that check to just Go files.
	n = 0;
	for(i=0; i<files.len; i++) {
		p = files.p[i];
		if(hasprefix(p, ".") || (hasprefix(p, "_") && hassuffix(p, ".go")))
			xfree(p);
		else
			files.p[n++] = p;
	}
	files.len = n;

	for(i=0; i<nelem(deptab); i++) {
		if(streq(dir, deptab[i].prefix) ||
		   (hassuffix(deptab[i].prefix, "/") && hasprefix(dir, deptab[i].prefix))) {
			for(j=0; (p=deptab[i].dep[j])!=nil; j++) {
				breset(&b1);
				bwritestr(&b1, p);
				bsubst(&b1, "$GOROOT", goroot);
				bsubst(&b1, "$GOOS", goos);
				bsubst(&b1, "$GOARCH", goarch);
				p = bstr(&b1);
				if(hassuffix(p, ".a")) {
					vadd(&lib, bpathf(&b, "%s", p));
					continue;
				}
				if(hassuffix(p, "/*")) {
					bpathf(&b, "%s/%s", bstr(&path), p);
					b.len -= 2;
					xreaddir(&extra, bstr(&b));
					bprintf(&b, "%s", p);
					b.len -= 2;
					for(k=0; k<extra.len; k++)
						vadd(&files, bpathf(&b1, "%s/%s", bstr(&b), extra.p[k]));
					continue;
				}
				if(hasprefix(p, "-")) {
					p++;
					n = 0;
					for(k=0; k<files.len; k++) {
						if(hasprefix(files.p[k], p))
							xfree(files.p[k]);
						else
							files.p[n++] = files.p[k];
					}
					files.len = n;
					continue;
				}
				vadd(&files, p);
			}
		}
	}
	vuniq(&files);

	// Convert to absolute paths.
	for(i=0; i<files.len; i++) {
		if(!isabs(files.p[i])) {
			bpathf(&b, "%s/%s", bstr(&path), files.p[i]);
			xfree(files.p[i]);
			files.p[i] = btake(&b);
		}
	}

	// Is the target up-to-date?
	stale = rebuildall;
	n = 0;
	for(i=0; i<files.len; i++) {
		p = files.p[i];
		for(j=0; j<nelem(depsuffix); j++)
			if(hassuffix(p, depsuffix[j]))
				goto ok;
		xfree(files.p[i]);
		continue;
	ok:
		t = mtime(p);
		if(t != 0 && !hassuffix(p, ".a") && !shouldbuild(p, dir)) {
			xfree(files.p[i]);
			continue;
		}
		if(hassuffix(p, ".go"))
			vadd(&go, p);
		if(t > ttarg)
			stale = 1;
		if(t == 0) {
			vadd(&missing, p);
			files.p[n++] = files.p[i];
			continue;
		}
		files.p[n++] = files.p[i];
	}
	files.len = n;

	// If there are no files to compile, we're done.
	if(files.len == 0)
		goto out;
	
	for(i=0; i<lib.len && !stale; i++)
		if(mtime(lib.p[i]) > ttarg)
			stale = 1;

	if(!stale)
		goto out;

	// For package runtime, copy some files into the work space.
	if(streq(dir, "pkg/runtime")) {
		copy(bpathf(&b, "%s/arch_GOARCH.h", workdir),
			bpathf(&b1, "%s/arch_%s.h", bstr(&path), goarch), 0);
		copy(bpathf(&b, "%s/defs_GOOS_GOARCH.h", workdir),
			bpathf(&b1, "%s/defs_%s_%s.h", bstr(&path), goos, goarch), 0);
		p = bpathf(&b1, "%s/signal_%s_%s.h", bstr(&path), goos, goarch);
		if(isfile(p))
			copy(bpathf(&b, "%s/signal_GOOS_GOARCH.h", workdir), p, 0);
		copy(bpathf(&b, "%s/os_GOOS.h", workdir),
			bpathf(&b1, "%s/os_%s.h", bstr(&path), goos), 0);
		copy(bpathf(&b, "%s/signals_GOOS.h", workdir),
			bpathf(&b1, "%s/signals_%s.h", bstr(&path), goos), 0);
	}

	// Generate any missing files; regenerate existing ones.
	for(i=0; i<files.len; i++) {
		p = files.p[i];
		elem = lastelem(p);
		for(j=0; j<nelem(gentab); j++) {
			if(gentab[j].gen == nil)
				continue;
			if(hasprefix(elem, gentab[j].nameprefix)) {
				if(vflag > 1)
					errprintf("generate %s\n", p);
				gentab[j].gen(bstr(&path), p);
				// Do not add generated file to clean list.
				// In pkg/runtime, we want to be able to
				// build the package with the go tool,
				// and it assumes these generated files already
				// exist (it does not know how to build them).
				// The 'clean' command can remove
				// the generated files.
				goto built;
			}
		}
		// Did not rebuild p.
		if(find(p, missing.p, missing.len) >= 0)
			fatal("missing file %s", p);
	built:;
	}

	// One more copy for package runtime.
	// The last batch was required for the generators.
	// This one is generated.
	if(streq(dir, "pkg/runtime")) {
		copy(bpathf(&b, "%s/zasm_GOOS_GOARCH.h", workdir),
			bpathf(&b1, "%s/zasm_%s_%s.h", bstr(&path), goos, goarch), 0);
	}

	// Generate .c files from .goc files.
	if(streq(dir, "pkg/runtime")) {
		for(i=0; i<files.len; i++) {
			p = files.p[i];
			if(!hassuffix(p, ".goc"))
				continue;
			// b = path/zp but with _goos_goarch.c instead of .goc
			bprintf(&b, "%s%sz%s", bstr(&path), slash, lastelem(p));
			b.len -= 4;
			bwritef(&b, "_%s_%s.c", goos, goarch);
			goc2c(p, bstr(&b));
			vadd(&files, bstr(&b));
		}
		vuniq(&files);
	}

	if((!streq(goos, gohostos) || !streq(goarch, gohostarch)) && isgo) {
		// We've generated the right files; the go command can do the build.
		if(vflag > 1)
			errprintf("skip build for cross-compile %s\n", dir);
		goto nobuild;
	}

	// Compile the files.
	for(i=0; i<files.len; i++) {
		if(!hassuffix(files.p[i], ".c") && !hassuffix(files.p[i], ".s"))
			continue;
		name = lastelem(files.p[i]);

		vreset(&compile);
		if(!isgo) {
			// C library or tool.
			if(streq(gohostos, "plan9")) {
				vadd(&compile, bprintf(&b, "%sc", gohostchar));
				vadd(&compile, "-FTVwp");
				vadd(&compile, "-DPLAN9");
				vadd(&compile, "-D__STDC__=1");
				vadd(&compile, "-D__SIZE_TYPE__=ulong"); // for GNU Bison
				vadd(&compile, bpathf(&b, "-I%s/include/plan9", goroot));
				vadd(&compile, bpathf(&b, "-I%s/include/plan9/%s", goroot, gohostarch));
			} else {
				vcopy(&compile, gccargs.p, gccargs.len);
				vadd(&compile, "-c");
				if(streq(gohostarch, "amd64"))
					vadd(&compile, "-m64");
				else if(streq(gohostarch, "386"))
					vadd(&compile, "-m32");
	
				vadd(&compile, "-I");
				vadd(&compile, bpathf(&b, "%s/include", goroot));
			}

			if(streq(dir, "lib9"))
				vadd(&compile, "-DPLAN9PORT");


			vadd(&compile, "-I");
			vadd(&compile, bstr(&path));

			// lib9/goos.c gets the default constants hard-coded.
			if(streq(name, "goos.c")) {
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOOS=\"%s\"", goos));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOARCH=\"%s\"", goarch));
				bprintf(&b1, "%s", goroot_final);
				bsubst(&b1, "\\", "\\\\");  // turn into C string
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOROOT=\"%s\"", bstr(&b1)));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOVERSION=\"%s\"", goversion));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GOARM=\"%s\"", goarm));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GO386=\"%s\"", go386));
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b, "GO_EXTLINK_ENABLED=\"%s\"", goextlinkenabled));
			}

			// gc/lex.c records the GOEXPERIMENT setting used during the build.
			if(streq(name, "lex.c")) {
				xgetenv(&b, "GOEXPERIMENT");
				vadd(&compile, "-D");
				vadd(&compile, bprintf(&b1, "GOEXPERIMENT=\"%s\"", bstr(&b)));
			}
		} else {
			// Supporting files for a Go package.
			if(hassuffix(files.p[i], ".s"))
				vadd(&compile, bpathf(&b, "%s/%sa", tooldir, gochar));
			else {
				vadd(&compile, bpathf(&b, "%s/%sc", tooldir, gochar));
				vadd(&compile, "-F");
				vadd(&compile, "-V");
				vadd(&compile, "-w");
			}
			vadd(&compile, "-I");
			vadd(&compile, workdir);
			vadd(&compile, "-I");
			vadd(&compile, bprintf(&b, "%s/pkg/%s_%s", goroot, goos, goarch));
			vadd(&compile, "-D");
			vadd(&compile, bprintf(&b, "GOOS_%s", goos));
			vadd(&compile, "-D");
			vadd(&compile, bprintf(&b, "GOARCH_%s", goarch));
			vadd(&compile, "-D");
			vadd(&compile, bprintf(&b, "GOOS_GOARCH_%s_%s", goos, goarch));
		}

		bpathf(&b, "%s/%s", workdir, lastelem(files.p[i]));
		doclean = 1;
		if(!isgo && streq(gohostos, "darwin")) {
			// To debug C programs on OS X, it is not enough to say -ggdb
			// on the command line.  You have to leave the object files
			// lying around too.  Leave them in pkg/obj/, which does not
			// get removed when this tool exits.
			bpathf(&b1, "%s/pkg/obj/%s", goroot, dir);
			xmkdirall(bstr(&b1));
			bpathf(&b, "%s/%s", bstr(&b1), lastelem(files.p[i]));
			doclean = 0;
		}

		// Change the last character of the output file (which was c or s).
		if(streq(gohostos, "plan9"))
			b.p[b.len-1] = gohostchar[0];
		else
			b.p[b.len-1] = 'o';
		vadd(&compile, "-o");
		vadd(&compile, bstr(&b));
		vadd(&compile, files.p[i]);
		bgrunv(bstr(&path), CheckExit, &compile);

		vadd(&link, bstr(&b));
		if(doclean)
			vadd(&clean, bstr(&b));
	}
	bgwait();

	if(isgo) {
		// The last loop was compiling individual files.
		// Hand the Go files to the compiler en masse.
		vreset(&compile);
		vadd(&compile, bpathf(&b, "%s/%sg", tooldir, gochar));

		bpathf(&b, "%s/_go_.a", workdir);
		vadd(&compile, "-pack");
		vadd(&compile, "-o");
		vadd(&compile, bstr(&b));
		vadd(&clean, bstr(&b));
		if(!ispackcmd)
			vadd(&link, bstr(&b));

		vadd(&compile, "-p");
		if(hasprefix(dir, "pkg/"))
			vadd(&compile, dir+4);
		else
			vadd(&compile, "main");

		if(streq(dir, "pkg/runtime"))
			vadd(&compile, "-+");

		vcopy(&compile, go.p, go.len);

		runv(nil, bstr(&path), CheckExit, &compile);

		if(ispackcmd) {
			xremove(link.p[targ]);
			dopack(link.p[targ], bstr(&b), &link.p[targ+1], link.len - (targ+1));
			goto nobuild;
		}
	}

	if(!islib && !isgo) {
		// C binaries need the libraries explicitly, and -lm.
		vcopy(&link, lib.p, lib.len);
		if(!streq(gohostos, "plan9"))
			vadd(&link, "-lm");
	}

	// Remove target before writing it.
	xremove(link.p[targ]);

	runv(nil, nil, CheckExit, &link);

nobuild:
	// In package runtime, we install runtime.h and cgocall.h too,
	// for use by cgo compilation.
	if(streq(dir, "pkg/runtime")) {
		copy(bpathf(&b, "%s/pkg/%s_%s/cgocall.h", goroot, goos, goarch),
			bpathf(&b1, "%s/src/pkg/runtime/cgocall.h", goroot), 0);
		copy(bpathf(&b, "%s/pkg/%s_%s/runtime.h", goroot, goos, goarch),
			bpathf(&b1, "%s/src/pkg/runtime/runtime.h", goroot), 0);
	}


out:
	for(i=0; i<clean.len; i++)
		xremove(clean.p[i]);

	bfree(&b);
	bfree(&b1);
	bfree(&path);
	vfree(&compile);
	vfree(&files);
	vfree(&link);
	vfree(&go);
	vfree(&missing);
	vfree(&clean);
	vfree(&lib);
	vfree(&extra);
}
Beispiel #6
0
static int
deep_remove_dir (const char *path)
{
    DIR		  *dirp;
    struct dirent *dp;

    if (rmdir (path) != 0)
    {
	if (errno == ENOTEMPTY
	    || errno == EEXIST
	    /* Ugly workaround for ugly AIX 4.1 (and 3.2) header bug
	       (it defines ENOTEMPTY and EEXIST to 17 but actually
	       returns 87).  */
	    || (ENOTEMPTY == 17 && EEXIST == 17 && errno == 87))
	{
	    if ((dirp = CVS_OPENDIR (path)) == NULL)
		/* If unable to open the directory return
		 * an error
		 */
		return -1;

	    errno = 0;
	    while ((dp = CVS_READDIR (dirp)) != NULL)
	    {
		char *buf;

		if (strcmp (dp->d_name, ".") == 0 ||
			    strcmp (dp->d_name, "..") == 0)
		    continue;

		buf = Xasprintf ("%s/%s", path, dp->d_name);

		/* See comment in unlink_file_dir explanation of why we use
		   isdir instead of just calling unlink and checking the
		   status.  */
		if (isdir (buf)) 
		{
		    if (deep_remove_dir (buf))
		    {
			CVS_CLOSEDIR (dirp);
			free (buf);
			return -1;
		    }
		}
		else
		{
		    if (CVS_UNLINK (buf) != 0)
		    {
			CVS_CLOSEDIR (dirp);
			free (buf);
			return -1;
		    }
		}
		free (buf);

		errno = 0;
	    }
	    if (errno != 0)
	    {
		int save_errno = errno;
		CVS_CLOSEDIR (dirp);
		errno = save_errno;
		return -1;
	    }
	    CVS_CLOSEDIR (dirp);
	    return rmdir (path);
	}
	else
	    return -1;
    }

    /* Was able to remove the directory return 0 */
    return 0;
}
/*
 * Delete the results of a package installation.
 *
 * This is here rather than in the pkg_delete code because pkg_add needs to
 * run it too in cases of failure.
 */
int
delete_package(Boolean ign_err, package_t *pkg, Boolean NoDeleteFiles,
    const char *destdir)
{
	plist_t *p;
	const char *last_file = "";
	int     fail = SUCCESS;
	Boolean preserve;
	char    tmp[MaxPathSize];
	const char *prefix = NULL, *name = NULL;

	if (!pkgdb_open(ReadWrite)) {
		err(EXIT_FAILURE, "cannot open pkgdb");
	}

	preserve = find_plist_option(pkg, "preserve") ? TRUE : FALSE;

	for (p = pkg->head; p; p = p->next) {
		switch (p->type) {
		case PLIST_NAME:
			name = p->name;
			break;
		case PLIST_CWD:
			if (prefix == NULL)
				prefix = p->name;
			break;
		default:
			break;
		}
	}

	if (name == NULL || prefix == NULL)
		errx(EXIT_FAILURE, "broken PLIST");

	/*
	 * Remove database entries first, directory removal is done
	 * in the main loop below.
	 */
	for (p = pkg->head; p; p = p->next) {
		if (p->type == PLIST_PKGDIR)
			delete_pkgdir(name, prefix, p->name);
	}

	for (p = pkg->head; p; p = p->next) {
		switch (p->type) {
		case PLIST_NAME:
			/* Handled already */
			break;

		case PLIST_PKGDIR:
		case PLIST_DIR_RM:
			(void) snprintf(tmp, sizeof(tmp), "%s/%s",
			    prefix, p->name);
			if (has_pkgdir(tmp))
				continue;
			(void) snprintf(tmp, sizeof(tmp), "%s%s%s/%s",
			    destdir ? destdir : "", destdir ? "/" : "",
			    prefix, p->name);
			if (!fexists(tmp)) {
				if (p->type == PLIST_PKGDIR)
					warnx("Directory `%s' disappeared, skipping", tmp);
			} else if (!isdir(tmp)) {
				warnx("attempting to delete a file `%s' as a directory\n"
				    "this packing list is incorrect - ignoring delete request", tmp);
			} else if (delete_with_parents(tmp, ign_err, TRUE))
				fail = FAIL;
			break;

		case PLIST_IGNORE:
			p = p->next;
			break;

		case PLIST_UNEXEC:
			if (NoDeleteFiles)
				break;
			format_cmd(tmp, sizeof(tmp), p->name, prefix, last_file);
			printf("Executing `%s'\n", tmp);
			if (!Fake && system(tmp)) {
				warnx("unexec command for `%s' failed", tmp);
				fail = FAIL;
			}
			break;

		case PLIST_FILE:
			last_file = p->name;
			(void) snprintf(tmp, sizeof(tmp), "%s%s%s/%s",
			    destdir ? destdir : "", destdir ? "/" : "",
			    prefix, p->name);
			if (isdir(tmp)) {
				warnx("attempting to delete directory `%s' as a file\n"
				    "this packing list is incorrect - ignoring delete request", tmp);
			} else {
				int     restored = 0;	/* restored from preserve? */

				if (p->next && p->next->type == PLIST_COMMENT) {
					if (strncmp(p->next->name, CHECKSUM_HEADER, ChecksumHeaderLen) == 0) {
						char   *cp, buf[LegibleChecksumLen];

						if ((cp = MD5File(tmp, buf)) != NULL) {
							/* Mismatch? */
							if (strcmp(cp, p->next->name + ChecksumHeaderLen) != 0) {
								printf("original MD5 checksum failed, %s: %s\n",
								    Force ? "deleting anyway" : "not deleting", tmp);
								if (!Force) {
									fail = FAIL;
									goto pkgdb_cleanup;
								}
							}
						}
					} else if (strncmp(p->next->name, SYMLINK_HEADER, SymlinkHeaderLen) == 0) {
						char	buf[MaxPathSize + SymlinkHeaderLen];
						int	cc;

						(void) strlcpy(buf, SYMLINK_HEADER,
						    sizeof(buf));
						if ((cc = readlink(tmp, &buf[SymlinkHeaderLen],
							  sizeof(buf) - SymlinkHeaderLen - 1)) < 0) {
							warn("can't readlink `%s'", tmp);
							goto pkgdb_cleanup;
						}
						buf[SymlinkHeaderLen + cc] = 0x0;
						if (strcmp(buf, p->next->name) != 0) {
							if ((cc = readlink(&buf[SymlinkHeaderLen], &buf[SymlinkHeaderLen],
								  sizeof(buf) - SymlinkHeaderLen)) < 0) {
								printf("symlink %s is not same as recorded value, %s: %s\n",
								    buf, Force ? "deleting anyway" : "not deleting", tmp);
								if (!Force) {
									fail = FAIL;
									goto pkgdb_cleanup;
								}
							}
							buf[SymlinkHeaderLen + cc] = 0x0;
							if (strcmp(buf, p->next->name) != 0) {
								printf("symlink %s is not same as recorded value, %s: %s\n",
								    buf, Force ? "deleting anyway" : "not deleting", tmp);
								if (!Force) {
									fail = FAIL;
									goto pkgdb_cleanup;
								}
							}
						}
					}
				}
				if (Verbose && !NoDeleteFiles)
					printf("Delete file %s\n", tmp);
				if (!Fake && !NoDeleteFiles) {
					if (delete_with_parents(tmp, ign_err, FALSE))
						fail = FAIL;
					if (preserve && name) {
						char    tmp2[MaxPathSize];

						if (make_preserve_name(tmp2, MaxPathSize, name, tmp)) {
							if (fexists(tmp2)) {
								if (rename(tmp2, tmp))
									warn("preserve: unable to restore %s as %s",
									    tmp2, tmp);
								else
									restored = 1;
							}
						}
					}
				}

pkgdb_cleanup:
				if (!Fake) {
					if (!restored) {
						errno = 0;
						if (pkgdb_remove(tmp) && errno)
							perror("pkgdb_remove");
					}
				}
			}
			break;
		default:
			break;
		}
	}
	pkgdb_close();
	return fail;
}
Beispiel #8
0
int main(int argc, char **argv)
{
	char	str[MAX_PATH+1];
	char	fname[MAX_PATH+1];
	char	ini_fname[MAX_PATH+1];
	char*	p;
	char*	arg;
	int 	i;
	int		retval;
	uint	fnames=0;
	FILE*	fp;
	BOOL	tcp_nodelay;
	char	compiler[32];
	str_list_t fname_list;

	fname_list=strListInit();

	DESCRIBE_COMPILER(compiler);

	errfp=stderr;
#ifdef __unix__
	statfp=stderr;
#else
	statfp=stdout;
#endif

	sscanf("$Revision: 1.77 $", "%*s %s", revision);

	fprintf(statfp,"\nSynchronet External X/Y/Zmodem  v%s-%s"
		"  Copyright %s Rob Swindell\n\n"
		,revision
		,PLATFORM_DESC
		,__DATE__+7
		);

	xmodem_init(&xm,NULL,&mode,lputs,xmodem_progress,send_byte,recv_byte,is_connected,NULL);
	zmodem_init(&zm,NULL,lputs,zmodem_progress,send_byte,recv_byte,is_connected,NULL,data_waiting);

	/* Generate path/sexyz[.host].ini from path/sexyz[.exe] */
	SAFECOPY(str,argv[0]);
	p=getfname(str);
	SAFECOPY(fname,p);
	*p=0;
	if((p=getfext(fname))!=NULL) 
		*p=0;
	strcat(fname,".ini");
	
	iniFileName(ini_fname,sizeof(ini_fname),str,fname);
	if((fp=fopen(ini_fname,"r"))!=NULL)
		fprintf(statfp,"Reading %s\n",ini_fname);

	tcp_nodelay				=iniReadBool(fp,ROOT_SECTION,"TCP_NODELAY",TRUE);

	telnet					=iniReadBool(fp,ROOT_SECTION,"Telnet",TRUE);
	debug_tx				=iniReadBool(fp,ROOT_SECTION,"DebugTx",FALSE);
	debug_rx				=iniReadBool(fp,ROOT_SECTION,"DebugRx",FALSE);
	debug_telnet			=iniReadBool(fp,ROOT_SECTION,"DebugTelnet",FALSE);

	pause_on_exit			=iniReadBool(fp,ROOT_SECTION,"PauseOnExit",FALSE);
	pause_on_abend			=iniReadBool(fp,ROOT_SECTION,"PauseOnAbend",FALSE);

	log_level				=iniReadLogLevel(fp,ROOT_SECTION,"LogLevel",log_level);

	outbuf.highwater_mark	=iniReadInteger(fp,ROOT_SECTION,"OutbufHighwaterMark",1100);
	outbuf_drain_timeout	=iniReadInteger(fp,ROOT_SECTION,"OutbufDrainTimeout",10);
	outbuf_size				=iniReadInteger(fp,ROOT_SECTION,"OutbufSize",16*1024);

	progress_interval		=iniReadInteger(fp,ROOT_SECTION,"ProgressInterval",1);

	if(iniReadBool(fp,ROOT_SECTION,"Debug",FALSE))
		log_level=LOG_DEBUG;

	xm.send_timeout			=iniReadInteger(fp,"Xmodem","SendTimeout",xm.send_timeout);	/* seconds */
	xm.recv_timeout			=iniReadInteger(fp,"Xmodem","RecvTimeout",xm.recv_timeout);	/* seconds */
	xm.byte_timeout			=iniReadInteger(fp,"Xmodem","ByteTimeout",xm.byte_timeout);	/* seconds */
	xm.ack_timeout			=iniReadInteger(fp,"Xmodem","AckTimeout",xm.ack_timeout);	/* seconds */
	xm.block_size			=iniReadInteger(fp,"Xmodem","BlockSize",xm.block_size);		/* 128 or 1024 */
	xm.max_errors			=iniReadInteger(fp,"Xmodem","MaxErrors",xm.max_errors);
	xm.g_delay				=iniReadInteger(fp,"Xmodem","G_Delay",xm.g_delay);

	zm.init_timeout			=iniReadInteger(fp,"Zmodem","InitTimeout",zm.init_timeout);	/* seconds */
	zm.send_timeout			=iniReadInteger(fp,"Zmodem","SendTimeout",zm.send_timeout);	/* seconds */
	zm.recv_timeout			=iniReadInteger(fp,"Zmodem","RecvTimeout",zm.recv_timeout);	/* seconds */
	zm.crc_timeout			=iniReadInteger(fp,"Zmodem","CrcTimeout",zm.crc_timeout);	/* seconds */
	zm.block_size			=iniReadInteger(fp,"Zmodem","BlockSize",zm.block_size);			/* 1024  */
	zm.max_block_size		=iniReadInteger(fp,"Zmodem","MaxBlockSize",zm.max_block_size);	/* 1024 or 8192 */
	zm.max_errors			=iniReadInteger(fp,"Zmodem","MaxErrors",zm.max_errors);
	zm.recv_bufsize			=iniReadInteger(fp,"Zmodem","RecvBufSize",0);
	zm.no_streaming			=!iniReadBool(fp,"Zmodem","Streaming",TRUE);
	zm.want_fcs_16			=!iniReadBool(fp,"Zmodem","CRC32",TRUE);
	zm.escape_telnet_iac	=iniReadBool(fp,"Zmodem","EscapeTelnetIAC",TRUE);
	zm.escape_8th_bit		=iniReadBool(fp,"Zmodem","Escape8thBit",FALSE);
	zm.escape_ctrl_chars	=iniReadBool(fp,"Zmodem","EscapeCtrlChars",FALSE);

	dszlog_path				=iniReadBool(fp,"DSZLOG","Path",TRUE);
	dszlog_short			=iniReadBool(fp,"DSZLOG","Short",FALSE);
	dszlog_quotes			=iniReadBool(fp,"DSZLOG","Quotes",FALSE);

	if(fp!=NULL)
		fclose(fp);

	if(zm.recv_bufsize > 0xffff)
		zm.recv_bufsize = 0xffff;

	if(outbuf_size < MIN_OUTBUF_SIZE)
		outbuf_size = MIN_OUTBUF_SIZE;
	else if(outbuf_size > MAX_OUTBUF_SIZE)
		outbuf_size = MAX_OUTBUF_SIZE;
	
	fprintf(statfp,"Output buffer size: %u\n", outbuf_size);
	RingBufInit(&outbuf, outbuf_size);

#if !defined(RINGBUF_EVENT)
	outbuf_empty=CreateEvent(NULL,/* ManualReset */TRUE, /*InitialState */TRUE,NULL);
#endif

#if 0
	if(argc>1) {
		fprintf(statfp,"Command line: ");
		for(i=1;i<argc;i++)
			fprintf(statfp,"%s ",argv[i]);
		fprintf(statfp,"\n",statfp);
	}
#endif


	for(i=1;i<argc;i++) {

		if(sock==INVALID_SOCKET && isdigit(argv[i][0])) {
			sock=atoi(argv[i]);
			continue;
		}

		if(!(mode&(SEND|RECV))) {
			if(toupper(argv[i][0])=='S' || toupper(argv[i][0])=='R') { /* cmd */
				if(toupper(argv[i][0])=='R')
					mode|=RECV;
				else
					mode|=SEND;

				switch(argv[i][1]) {
					case 'c':
					case 'C':
						mode|=XMODEM|CRC;
						break;
					case 'x':
						xm.block_size=128;
					case 'X':
						mode|=XMODEM;
						break;
					case 'b':	/* sz/rz compatible */
					case 'B':
					case 'y':
						xm.block_size=128;
					case 'Y':
						mode|=(YMODEM|CRC);
						break;
					case 'g':
					case 'G':
						mode|=(YMODEM|CRC|GMODE);
						break;
					case 'z':
					case 'Z':
						mode|=(ZMODEM|CRC);
						break;
					default:
						fprintf(statfp,"Unrecognized command '%s'\n\n",argv[i]);
						fprintf(statfp,usage);
						bail(1); 
				} 
				continue;
			}

			if(toupper(argv[i][0])=='V') {

				fprintf(statfp,"%-8s %s\n",getfname(__FILE__)		,revision);
				fprintf(statfp,"%-8s %s\n",getfname(xmodem_source()),xmodem_ver(str));
				fprintf(statfp,"%-8s %s\n",getfname(zmodem_source()),zmodem_ver(str));
#ifdef _DEBUG
				fprintf(statfp,"Debug\n");
#endif
				fprintf(statfp,"Compiled %s %.5s with %s\n",__DATE__,__TIME__,compiler);
				fprintf(statfp,"%s\n",os_version(str));
				bail(0);
			}

			arg=argv[i];
			if(*arg=='-') {
				while(*arg=='-')
					arg++;
				if(stricmp(arg,"telnet")==0) {
					telnet=TRUE;
					continue;
				}
				if(stricmp(arg,"rlogin")==0 || stricmp(arg,"ssh")==0 || stricmp(arg,"raw")==0) {
					telnet=FALSE;
					continue;
				}
				if(stricmp(arg,"debug")==0) {
					log_level=LOG_DEBUG;
					continue;
				}
				if(stricmp(arg,"quotes")==0) {
					dszlog_quotes=TRUE;
					continue;
				}
				switch(toupper(*arg)) {
					case 'K':	/* sz/rz compatible */
						xm.block_size=1024;
						break;
					case 'C':	/* sz/rz compatible */
						mode|=CRC;
						break;
					case '2':
						zm.max_block_size=2048;
						break;
					case '4':
						zm.max_block_size=4096;
						break;
					case '8':	/* ZedZap */
						zm.max_block_size=8192;
						break;
					case 'O':	/* disable Zmodem CRC-32 */
						zm.want_fcs_16=TRUE;
						break;
					case 'S':	/* disable Zmodem streaming */
						zm.no_streaming=TRUE;
						break;
					case 'G':	/* Ymodem-G */
						mode|=GMODE;
						break;
					case 'Y':
						mode|=OVERWRITE;
						break;
					case '!':
						pause_on_abend=TRUE;
						break;
				}
			}
		}

		else if((argv[i][0]=='+' || argv[i][0]=='@') && fexist(argv[i]+1)) {
			if(mode&RECVDIR) {
				fprintf(statfp,"!Cannot specify both directory and filename\n");
				bail(1); 
			}
			sprintf(str,"%s",argv[i]+1);
			if((fp=fopen(str,"r"))==NULL) {
				fprintf(statfp,"!Error %d opening filelist: %s\n",errno,str);
				bail(1); 
			}
			while(!feof(fp) && !ferror(fp)) {
				if(!fgets(str,sizeof(str),fp))
					break;
				truncsp(str);
				strListAppend(&fname_list,strdup(str),fnames++);
			}
			fclose(fp); 
		}

		else if(mode&(SEND|RECV)){
			if(isdir(argv[i])) { /* is a directory */
				if(mode&RECVDIR) {
					fprintf(statfp,"!Only one directory can be specified\n");
					bail(1); 
				}
				if(fnames) {
					fprintf(statfp,"!Cannot specify both directory and filename\n");
					bail(1); 
				}
				if(mode&SEND) {
					fprintf(statfp,"!Cannot send directory '%s'\n",argv[i]);
					bail(1);
				}
				mode|=RECVDIR; 
			}
			strListAppend(&fname_list,argv[i],fnames++);
		} 
	}

	if(!telnet)
		zm.escape_telnet_iac = FALSE;

	if(sock==INVALID_SOCKET || sock<1) {
#ifdef __unix__
		if(STDOUT_FILENO > STDIN_FILENO)
			sock=STDOUT_FILENO;
		else
			sock=STDIN_FILENO;
		stdio=TRUE;
		
		fprintf(statfp,"No socket descriptor specified, using STDIO\n");
		telnet=FALSE;
#else
		fprintf(statfp,"!No socket descriptor specified\n\n");
		fprintf(errfp,usage);
		bail(1);
#endif
	}
#ifdef __unix__
	else
		statfp=stdout;
#endif

	if(!(mode&(SEND|RECV))) {
		fprintf(statfp,"!No command specified\n\n");
		fprintf(statfp,usage);
		bail(1); 
	}

	if(mode&(SEND|XMODEM) && !fnames) { /* Sending with any or recv w/Xmodem */
		fprintf(statfp,"!Must specify filename or filelist\n\n");
		fprintf(statfp,usage);
		bail(1); 
	}

#ifdef __unix__
	if(stdio) {
		struct termios term;
		memset(&term,0,sizeof(term));
		cfsetispeed(&term,B19200);
		cfsetospeed(&term,B19200);
		term.c_iflag &= ~(IMAXBEL|IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
		term.c_oflag &= ~OPOST;
		term.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
		term.c_cflag &= ~(CSIZE|PARENB);
		term.c_cflag |= CS8;
		atexit(resetterm);
		tcgetattr(STDOUT_FILENO, &origterm);
		tcsetattr(STDOUT_FILENO, TCSADRAIN, &term);
	}
#endif

	/* Code disabled.  Why?  ToDo */
/*	if(mode&RECVDIR)
		backslash(fname[0]); */

	if(!winsock_startup())
		bail(-1);

	/* Enable the Nagle Algorithm */
#ifdef __unix__
	if(!stdio) {
#endif
		lprintf(LOG_DEBUG,"Setting TCP_NODELAY to %d",tcp_nodelay);
		setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char*)&tcp_nodelay,sizeof(tcp_nodelay));
#ifdef __unix__
	}
#endif

	if(!socket_check(sock, NULL, NULL, 0)) {
		lprintf(LOG_WARNING,"No socket connection");
		bail(-1); 
	}

	if((dszlog=getenv("DSZLOG"))!=NULL) {
		if((logfp=fopen(dszlog,"w"))==NULL) {
			lprintf(LOG_WARNING,"Error %d opening DSZLOG file: %s",errno,dszlog);
			bail(-1); 
		}
	}

	/* Install Ctrl-C/Break signal handler here */
#if defined(_WIN32)
	SetConsoleCtrlHandler(ControlHandler, TRUE /* Add */);
#elif defined(__unix__)
	signal(SIGQUIT,break_handler);
	signal(SIGINT,break_handler);
	signal(SIGTERM,break_handler);

	signal(SIGHUP,SIG_IGN);

	/* Don't die on SIGPIPE  */
	signal(SIGPIPE,SIG_IGN);
#endif

#if !SINGLE_THREADED
	_beginthread(output_thread,0,NULL);
#endif

	if(mode&RECV)
		retval=receive_files(fname_list, fnames);
	else
		retval=send_files(fname_list, fnames);

#if !SINGLE_THREADED
	lprintf(LOG_DEBUG,"Waiting for output buffer to empty... ");
	if(WaitForEvent(outbuf_empty,5000)!=WAIT_OBJECT_0)
		lprintf(LOG_DEBUG,"FAILURE");
#endif

	terminate=TRUE;	/* stop output thread */
	/* Code disabled.  Why?  ToDo */
/*	sem_post(outbuf.sem);
	sem_post(outbuf.highwater_sem); */

	fprintf(statfp,"Exiting - Error level: %d, flows: %u, select_errors=%u"
		,retval, flows, select_errors);
	fprintf(statfp,"\n");

	bail(retval);
}
Beispiel #9
0
static int send_files(char** fname, uint fnames)
{
	char	path[MAX_PATH+1];
	int		i;
	uint	errors;
	uint	fnum;
	uint	cps;
	glob_t	g;
	int		gi;
	BOOL	success=TRUE;
	long	fsize;
	ulong	sent_bytes;
	ulong	total_bytes=0;
	time_t	t,startfile;
	time_t	startall;
	FILE*	fp;

	startall=time(NULL);

	/****************************************************/
	/* Search through all to find total files and bytes */
	/****************************************************/
	for(fnum=0;fnum<fnames;fnum++) {
		if(glob(fname[fnum],0,NULL,&g)) {
			lprintf(LOG_WARNING,"%s not found",fname[fnum]);
			continue;
		}
		for(i=0;i<(int)g.gl_pathc;i++) {
			if(isdir(g.gl_pathv[i]))
				continue;
			xm.total_files++;
			xm.total_bytes+=flength(g.gl_pathv[i]);
		} 
		globfree(&g);
	}

	if(xm.total_files<1) {
		lprintf(LOG_ERR,"No files to send");
		return(-1);
	}
	if(xm.total_files>1)
		lprintf(LOG_INFO,"Sending %u files (%lu KB total)"
			,xm.total_files,xm.total_bytes/1024);

	zm.files_remaining = xm.total_files;
	zm.bytes_remaining = xm.total_bytes;

	/***********************************************/
	/* Send every file matching names or filespecs */
	/***********************************************/
	for(fnum=0;fnum<fnames;fnum++) {
		if(glob(fname[fnum],0,NULL,&g)) {
			lprintf(LOG_WARNING,"%s not found",fname[fnum]);
			continue;
		}
		for(gi=0;gi<(int)g.gl_pathc;gi++) {
			SAFECOPY(path,g.gl_pathv[gi]);
			if(isdir(path))
				continue;

			if((fp=fnopen(NULL,path,O_RDONLY|O_BINARY))==NULL
				&& (fp=fopen(path,"rb"))==NULL) {
				lprintf(LOG_ERR,"Error %d opening %s for read",errno,path);
				continue;
			}
			setvbuf(fp,NULL,_IOFBF,0x10000);

			fsize=filelength(fileno(fp));

			errors=0;
			success=FALSE;
			startfile=time(NULL);

			lprintf(LOG_INFO,"Sending %s (%lu KB) via %s"
				,path,fsize/1024
				,mode&XMODEM ? "Xmodem" : mode&YMODEM ? "Ymodem" : "Zmodem");

			if(mode&ZMODEM)
					success=zmodem_send_file(&zm, path, fp, /* ZRQINIT? */fnum==0, &startfile, &sent_bytes);
			else	/* X/Ymodem */
					success=xmodem_send_file(&xm, path, fp, &startfile, &sent_bytes);

			fclose(fp);

			if((t=time(NULL)-startfile)<=0) 
				t=1;
			if((cps=sent_bytes/t)==0)
				cps=1;
			if(success) {
				xm.sent_files++;
				xm.sent_bytes+=fsize;
				lprintf(LOG_INFO,"Successful - Time: %lu:%02lu  CPS: %lu"
						,t/60,t%60,cps);

				if(xm.total_files-xm.sent_files)
					lprintf(LOG_INFO,"Remaining - Time: %lu:%02lu  Files: %u  KBytes: %lu"
						,((xm.total_bytes-xm.sent_bytes)/cps)/60
						,((xm.total_bytes-xm.sent_bytes)/cps)%60
						,xm.total_files-xm.sent_files
						,(xm.total_bytes-xm.sent_bytes)/1024
						);
			} else
				lprintf(LOG_WARNING,"File Transfer %s", aborted ? "Aborted" : "Failure");

			/* DSZLOG entry */
			if(logfp) {
				lprintf(LOG_DEBUG,"Updating DSZLOG: %s", dszlog);
				fprintf(logfp,"%c %7lu %5u bps %6lu cps %3u errors %5u %4u "
					"%s -1\n"
					,success ? (mode&ZMODEM ? 'z':'S') 
						: (mode&ZMODEM && zm.file_skipped) ? 's' 
						: 'E'
					,sent_bytes
					,115200 /* baud */
					,cps
					,mode&ZMODEM ? zm.errors : xm.errors
					,flows
					,mode&ZMODEM ? zm.block_size : xm.block_size
					,dszlog_filename(path)); 
				fflush(logfp);
			}
			total_bytes += sent_bytes;

			if(aborted) {
				xm.cancelled=FALSE;
				xmodem_cancel(&xm);
				break;
			}

			if(xm.cancelled || zm.cancelled)
				break;

		} /* while(gi<(int)g.gl_pathc) */

		if(gi<(int)g.gl_pathc)/* error occurred */
			break;
	}

	if(mode&ZMODEM && !zm.cancelled && is_connected(NULL))
		zmodem_get_zfin(&zm);

	if(fnum<fnames) /* error occurred */
		return(-1);

	if(!success)
		return(-1);

	if(mode&XMODEM)
		return(0);
	if(mode&YMODEM) {

		if(xmodem_get_mode(&xm)) {

			lprintf(LOG_INFO,"Sending Ymodem termination block");

			memset(block,0,128);	/* send short block for terminator */
			xmodem_put_block(&xm, block, 128 /* block_size */, 0 /* block_num */);
			if(!xmodem_get_ack(&xm,6,0)) {
				lprintf(LOG_WARNING,"Failed to receive ACK after terminating block"); 
			} 
		}
	}
	if(xm.total_files>1) {
		t=time(NULL)-startall;
		if(!t) t=1;
		lprintf(LOG_INFO,"Overall - Time %02lu:%02lu  KBytes: %lu  CPS: %lu"
			,t/60,t%60,total_bytes/1024,total_bytes/t); 
	}
	return(0);	/* success */
}
Beispiel #10
0
/*
 * Delete the results of a package installation.
 *
 * This is here rather than in the pkg_delete code because pkg_add needs to
 * run it too in cases of failure.
 */
int
delete_package(Boolean ign_err, Boolean nukedirs, Package *pkg)
{
    PackingList p;
    const char *Where = ".", *last_file = "";
    Boolean fail = SUCCESS;
    Boolean preserve;
    char tmp[FILENAME_MAX], *name = NULL;
    char *prefix = NULL;

    preserve = find_plist_option(pkg, "preserve") ? TRUE : FALSE;
    for (p = pkg->head; p; p = p->next) {
	switch (p->type)  {
	case PLIST_NAME:
	    name = p->name;
	    break;

	case PLIST_IGNORE:
	    p = p->next;
	    break;

	case PLIST_CWD:
	    if (!prefix)
		prefix = p->name;
	    Where = (p->name == NULL) ? prefix : p->name;
	    if (Verbose)
		printf("Change working directory to %s\n", Where);
	    break;

	case PLIST_UNEXEC:
	    format_cmd(tmp, FILENAME_MAX, p->name, Where, last_file);
	    if (Verbose)
		printf("Execute '%s'\n", tmp);
	    if (!Fake && system(tmp)) {
		warnx("unexec command for '%s' failed", tmp);
		fail = FAIL;
	    }
	    break;

	case PLIST_FILE:
	    last_file = p->name;
	    if (*p->name == '/')
		strlcpy(tmp, p->name, FILENAME_MAX);
	    else
		sprintf(tmp, "%s/%s", Where, p->name);
	    if (isdir(tmp) && fexists(tmp) && !issymlink(tmp)) {
		warnx("cannot delete specified file '%s' - it is a directory!\n"
	   "this packing list is incorrect - ignoring delete request", tmp);
	    }
	    else {
		if (p->next && p->next->type == PLIST_COMMENT && !strncmp(p->next->name, "MD5:", 4)) {
		    char *cp = NULL, buf[33];

		    /*
		     * For packing lists whose version is 1.1 or greater, the md5
		     * hash for a symlink is calculated on the string returned
		     * by readlink().
		     */
		    if (issymlink(tmp) && verscmp(pkg, 1, 0) > 0) {
			int len;
			char linkbuf[FILENAME_MAX];

			if ((len = readlink(tmp, linkbuf, FILENAME_MAX)) > 0)
			     cp = MD5Data((unsigned char *)linkbuf, len, buf);
		    } else if (isfile(tmp) || verscmp(pkg, 1, 1) < 0)
			cp = MD5File(tmp, buf);

		    if (cp != NULL) {
			/* Mismatch? */
			if (strcmp(cp, p->next->name + 4)) {
			    warnx("'%s' fails original MD5 checksum - %s",
				  tmp, Force ? "deleted anyway." : "not deleted.");
			    if (!Force) {
				fail = FAIL;
				continue;
			    }
			}
		    }
		}
		if (Verbose)
		    printf("Delete file %s\n", tmp);
		if (!Fake) {
		    if (delete_hierarchy(tmp, ign_err, nukedirs))
			fail = FAIL;
		    if (preserve && name) {
			char tmp2[FILENAME_MAX];
			    
			if (make_preserve_name(tmp2, FILENAME_MAX, name, tmp)) {
			    if (fexists(tmp2)) {
				if (rename(tmp2, tmp))
				   warn("preserve: unable to restore %s as %s",
					tmp2, tmp);
			    }
			}
		    }
		}
	    }
	    break;

	case PLIST_DIR_RM:
	    sprintf(tmp, "%s/%s", Where, p->name);
	    if (!isdir(tmp) && fexists(tmp)) {
		warnx("cannot delete specified directory '%s' - it is a file!\n"
	"this packing list is incorrect - ignoring delete request", tmp);
	    }
	    else {
		if (Verbose)
		    printf("Delete directory %s\n", tmp);
		if (!Fake && delete_hierarchy(tmp, ign_err, FALSE)) {
		    warnx("unable to completely remove directory '%s'", tmp);
		    fail = FAIL;
		}
	    }
	    last_file = p->name;
	    break;

	default:
	    break;
	}
    }
    return fail;
}
Beispiel #11
0
static int
hg_probe(vccontext_t* context)
{
    return isdir(".hg");
}
Beispiel #12
0
gint layout_set_path(LayoutWindow *lw, const gchar *path)
{
	gint have_file = FALSE;

	if (!layout_valid(&lw)) return FALSE;

	if (!path || !isname(path)) return FALSE;
	if (lw->path && path && strcmp(path, lw->path) == 0)
		{
		return TRUE;
		}

	if (isdir(path))
		{
		g_free(lw->path);
		lw->path = g_strdup(path);
		}
	else
		{
		gchar *base;

		base = remove_level_from_path(path);
		if (lw->path && strcmp(lw->path, base) == 0)
			{
			g_free(base);
			}
		else if (isdir(base))
			{
			g_free(lw->path);
			lw->path = base;
			}
		else
			{
			g_free(base);
			return FALSE;
			}
		if (isfile(path)) have_file = TRUE;
		}

	if (lw->path_entry) tab_completion_append_to_history(lw->path_entry, lw->path);
	layout_sync_path(lw);

	if (have_file)
		{
		gint row;

		row = layout_list_get_index(lw, path);
		if (row >= 0)
			{
			layout_image_set_index(lw, row);
			}
		else
			{
			layout_image_set_path(lw, path);
			}
		}
	else if (!lazy_image_sync)
		{
		layout_image_set_index(lw, 0);
		}

	return TRUE;
}
Beispiel #13
0
int vms_copy(char *vms1,char *vms2,COP_PARAM *cop_param)
{
    int     bFailIfExists   = FALSE;
    int     nError          = 0;
    char    dos1[MAX_TOKEN];
    char    dos2[MAX_TOKEN];
    char    vms0[MAX_TOKEN];
    char    directory1[_MAX_PATH];
    char    directory2[_MAX_PATH];
    char    drive1[_MAX_DRIVE];
    char    dir1[_MAX_DIR];
    char    file1[_MAX_FNAME];
    char    ext1[_MAX_EXT];
    char    drive2[_MAX_DRIVE];
    char    dir2[_MAX_DIR];
    char    file2[_MAX_FNAME];
    char    ext2[_MAX_EXT];
    size_t  i = 0;
    int    retcod = DCL_OK;

    *dos1 = 0; *drive1 = 0; *dir1 = 0; *file1 = 0; *ext1 =0; *directory1 = 0;
    *dos2 = 0; *drive2 = 0; *dir2 = 0; *file2 = 0; *ext2 =0; *directory2 = 0;

    cvfs_vms_to_dos(vms1,dos1,(int *)&i);
    _splitpath(dos1,drive1,dir1,file1,ext1);
    cvfs_vms_to_dos(vms2,dos2,(int *)&i);
    if (isdir(dos2) && dos2[strlen(dos2)-1] != SLASH_CHR)
            strcat(dos2,SLASH_STR);
    if (dos1[strlen(dos1)-1] == SLASH_CHR)
        dos1[strlen(dos1)-1] = '\0';
    if (!cvfs_check_device(dos2)) {
        _splitpath(dos2,drive2,dir2,file2,ext2);
        if (!*file2)
            strcpy(file2,file1);
        if (*file2 == '*')
            strcpy(file2,file1);
        if (!*ext2)
            strcpy(ext2,ext1);
        if (strncmp(ext2,".*",2)==0)
            strcpy(ext2,ext1);
        for (i = 0;i < strlen(file2); i++)
            if (file2[i] == '?') file2[i] = file1[i];
        for (i = 0;i < strlen(ext2); i++)
            if (ext2[i] == '?') ext2[i] = ext1[i];
        _makepath(dos2,drive2,dir2,file2,ext2);
        cvfs_dos_to_vms(dos2,vms2);

        if (cop_param->fnew) {
            if (filetstamp(dos1) <= filetstamp(dos2)) {
                goto exit_label;
            }
        }
    }

    _makepath(directory1,drive1,dir1,NULL,NULL);
    if (SUBDIR) {
        for(i = 1; i < strlen(dir1) && dir1[i] != SLASH_CHR; i++) ;
        if (dir1[i] == SLASH_CHR) i++;
        strcat(dir2, &dir1[i]);
        _makepath(dos2,drive2,dir2,file2,ext2);
    }
    _makepath(directory2,drive2,dir2,NULL,NULL);

    bFailIfExists = cop_param->replace ? FALSE : TRUE;
    
    (void)_mkdir(directory2);
    if (*file2) {
        nError = filecopy(dos1, dos2, bFailIfExists);
    }
    
    if (nError) {
        (void)dcl_printf(dcl[D].SYS_OUTPUT,"%s: %s\n",vms1,strerror(errno));
        _STATUS = nError;
        _SEVERITY = 2;
        retcod = DCL_ERROR;
    }
    else {
        cop_param->file_copied++;
        if (cop_param->log) {
            cvfs_dos_to_vms(dos2,vms0);
            (void)dcl_printf(dcl[D].SYS_OUTPUT,"%s copied to %s.\n",vms1,vms0);
        }
    }

exit_label:
    return(retcod);
}
Beispiel #14
0
			bool makedir(const char* dir) {
				if (isdir(dir))
					return true;
				return mkdir(dir, 0755) == 0;
			}
Beispiel #15
0
static int
svn_probe(vccontext_t *context)
{
    return isdir(".svn");
}
Beispiel #16
0
/*******************************************************************
 *	根據 URLParaType 執行 GET 的要求
 *
 *	
 *	return WebRespondType
 *******************************************************************/
int 
DoGetRequest(REQUEST_REC * rc, BOARDHEADER * board, POST_FILE * pf)
{
	char *p, *boardname;
	int URLParaType = rc->URLParaType;
	char fname[PATHLEN];

	boardname = board->filename;

	if (URLParaType == Redirect)
	{
		/* redirect target must set in ParseURI() */
		return WEB_REDIRECT;
	}

	if (PSCorrect != Correct
	    && (URLParaType == MailList
		|| URLParaType == MailRead
		|| URLParaType == SkinModify))
	{
		return WEB_USER_NOT_LOGIN;
	}

	if (URLParaType == PostList
	    || URLParaType == PostRead
	    || URLParaType == TreaList
	    || URLParaType == TreaRead
	    || URLParaType == SkinModify
	    || URLParaType == Board)
	{
		int perm;

		if (get_board(board, boardname) <= 0 || board->filename[0] == '\0')
			return WEB_BOARD_NOT_FOUND;

		if ((perm = CheckBoardPerm(board, &curuser)) != WEB_OK)
			return perm;

		if (board->brdtype & BRD_WEBSKIN)	/* Board has custom html skin */
		{
			char *skin, web_board_dir[PATHLEN];

			if (URLParaType == SkinModify)
			{
				if (strlen(pf->POST_NAME) != 0)
				{
					xstrncpy(web_board_dir, pf->POST_NAME, PATHLEN);
					skin = strrchr(web_board_dir, '/') + 1;
					setskinfile(pf->POST_NAME, boardname, skin);
				}
			}
			else if (!strstr(skin_file->filename, HTML_BoardModify))
			{
				/* set specfic skin file to custom file */
				xstrncpy(web_board_dir, skin_file->filename, PATHLEN);
				skin = strrchr(web_board_dir, '/') + 1;
				setskinfile(skin_file->filename, boardname, skin);
			}
		}
		else
		{
			if (strstr(skin_file->filename, HTML_SkinModify))
				return WEB_FILE_NOT_FOUND;
		}
	}

	if (strstr(skin_file->filename, HTML_BoardModify)
	    && (!HAS_PERM(PERM_SYSOP) || PSCorrect != Correct))
	{
		return WEB_FILE_NOT_FOUND;
	}

	switch (URLParaType)
	{
		case TreaRead:
		case PostRead:
			if (GetPostInfo(board, pf) != WEB_OK)
				return WEB_FILE_NOT_FOUND;

			break;

		case TreaList:
		case PostList:
			pf->total_rec = get_num_records(pf->POST_NAME, FH_SIZE);

			break;

		case MailList:
			if (PSCorrect == Correct)
				pf->total_rec = get_num_records(pf->POST_NAME, FH_SIZE);
			else
				pf->total_rec = 0;
			break;

		case MailRead:
			if (PSCorrect == Correct)
			{
				int RESULT = GetPostInfo(board, pf);

				if (RESULT != WEB_OK)
					return RESULT;
			}
			break;

		case UserList:
		case BoardList:
		case TreaBoardList:
		case UserData:
		case SkinModify:
			/* do nothing here.. */

			break;

		case UserQuery:
			/* put USER_REC in curuser for query */
			if (!get_passwd(&curuser, username))
			{
				bzero(&curuser, sizeof(USEREC));
				return WEB_USER_NOT_FOUND;
			}
			break;

		case Board:	/* cuscom webboard */
		case Mail:	/* ?? */
#if 0
			fprintf(fp_out, "DoGetRequest Board,Mail:[%s]", skin_file->filename);
			fflush(fp_out);
#endif
			if (CacheState(skin_file->filename, NULL) < 0
			    && !isfile(skin_file->filename))
			{
				return WEB_FILE_NOT_FOUND;
			}
			break;

		default:
#if 0
			fprintf(fp_out, "DoGetRequest default:[%s]\r\n", skin_file->filename);
			fflush(fp_out);
#endif

			xstrncpy(fname, skin_file->filename, sizeof(fname));

			if (isBadURI(fname))
			{
				BBS_SUBDIR[0] = 0x00;
				return WEB_BAD_REQUEST;
			}

			sprintf(skin_file->filename, "%s%s", HTML_PATH, fname + 1);

			if (CacheState(skin_file->filename, NULL) == -1)	/* file not in cache */
			{
				if (isdir(skin_file->filename))
				{
					p = skin_file->filename + strlen(skin_file->filename) - 1;
					if (*p == '/')
					{
						strcat(skin_file->filename, DEFAULT_HTML);
					}
					else
					{
						sprintf(skin_file->filename, "%s/", fname);
						return WEB_REDIRECT;
					}
				}
				else
				{
					if ((p = strrchr(fname + 1, '/')) == NULL)
						p = fname;
					if (!strcmp(p, "/boards")
					    || !strcmp(p, "/treasure")
					    || !strcmp(p, "/mail")
					    || !strcmp(p, "/users"))
					{
						sprintf(skin_file->filename, "%s/", fname);
						return WEB_REDIRECT;
					}
				}

				if (!isfile(skin_file->filename))
				{
					BBS_SUBDIR[0] = 0x00;
					return WEB_FILE_NOT_FOUND;
				}
			}

#ifdef WEB_LOGIN_CHECK
			return WebLoginCheck();
#endif

	}

	return WEB_OK;

}
Beispiel #17
0
/* search_for_exec_prefix requires that argv0_path be no more than
   MAXPATHLEN bytes long.
*/
static int
search_for_exec_prefix(wchar_t *argv0_path, wchar_t *home, wchar_t *_exec_prefix)
{
    size_t n;

    /* If PYTHONHOME is set, we believe it unconditionally */
    if (home) {
        wchar_t *delim;
        delim = wcschr(home, DELIM);
        if (delim)
            wcsncpy(exec_prefix, delim+1, MAXPATHLEN);
        else
            wcsncpy(exec_prefix, home, MAXPATHLEN);
        joinpath(exec_prefix, lib_python);
        joinpath(exec_prefix, L"lib-dynload");
        return 1;
    }

    /* Check to see if argv[0] is in the build directory. "pybuilddir.txt"
       is written by setup.py and contains the relative path to the location
       of shared library modules. */
    wcscpy(exec_prefix, argv0_path);
    joinpath(exec_prefix, L"pybuilddir.txt");
    if (isfile(exec_prefix)) {
        FILE *f = _Py_wfopen(exec_prefix, L"rb");
        if (f == NULL)
            errno = 0;
        else {
            char buf[MAXPATHLEN+1];
            PyObject *decoded;
            wchar_t rel_builddir_path[MAXPATHLEN+1];
            n = fread(buf, 1, MAXPATHLEN, f);
            buf[n] = '\0';
            fclose(f);
            decoded = PyUnicode_DecodeUTF8(buf, n, "surrogateescape");
            if (decoded != NULL) {
                Py_ssize_t k;
                k = PyUnicode_AsWideChar(decoded,
                                         rel_builddir_path, MAXPATHLEN);
                Py_DECREF(decoded);
                if (k >= 0) {
                    rel_builddir_path[k] = L'\0';
                    wcscpy(exec_prefix, argv0_path);
                    joinpath(exec_prefix, rel_builddir_path);
                    return -1;
                }
            }
        }
    }

    /* Search from argv0_path, until root is found */
    copy_absolute(exec_prefix, argv0_path, MAXPATHLEN+1);
    do {
        n = wcslen(exec_prefix);
        joinpath(exec_prefix, lib_python);
        joinpath(exec_prefix, L"lib-dynload");
        if (isdir(exec_prefix))
            return 1;
        exec_prefix[n] = L'\0';
        reduce(exec_prefix);
    } while (exec_prefix[0]);

    /* Look at configure's EXEC_PREFIX */
    wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN);
    joinpath(exec_prefix, lib_python);
    joinpath(exec_prefix, L"lib-dynload");
    if (isdir(exec_prefix))
        return 1;

    /* Fail */
    return 0;
}
Beispiel #18
0
int 
f_put (char **vec)
{
	int     append;
#ifdef	BRIDGE
	int     result;
	char  *dst;
#else
	int	    sglobbed;
	char  *bp,
			 *dst,
			 **gp,
			 **src;
	char   *freedst = NULL,
			buffer[BUFSIZ];
#endif

	append = strcmp (*vec, "append") == 0;

	if (*++vec == NULL) {
#ifdef	BRIDGE
		return NOTOK;
#else
		if (getftamline ("source: ", buffer) == NOTOK || str2vec (buffer, vec) < 1)
			return OK;
		dst = NULL;
#endif
	} else {
#ifdef	BRIDGE
		dst = *vec;
#else
		char **ap;

		for (ap = vec; *ap; ap++)
			continue;
		if (--ap != vec)
			dst = *ap, *ap = NULL;
		else
			dst = NULL;
#endif
	}
#ifndef	BRIDGE
	if (!(src = xglob (vec, 0)))
		return OK;
	sglobbed = xglobbed;

	if (dst == NULL) {
		if (getftamline ("destination: ", buffer) == NOTOK) {
			blkfree (src);
			return OK;
		}
		switch (str2vec (buffer, vec)) {
		case 0:
			break;

		case 1:
			dst = *vec;
			break;

		default:
			advise (NULLCP, "too many destinations");
			goto out;
		}
	}
	if (dst && !(dst = freedst = xglob1val (dst, 0)))
		goto out;

	if (src[1] == NULL) {
		if (interrupted)
			goto out;

		if (dst == NULL) {
			switch (realstore) {
			case RFS_UNIX:
				if (dst = rindex (*src, '/'))
					dst++;
				if (dst == NULL || *dst == NULL)
					dst = *src;
				break;

			default:
				dst = *src;
				break;
			}
			dst = str2file (dst);

ask_it:
			;
			if (query)
				switch (ask ("%s %s %s", append ? "append" : "put", *src,
							 dst)) {
				case NOTOK:
					goto out;

				case OK:
				default:
					break;

				case DONE:
					goto out;
				}
		} else
			switch (realstore) {
			case RFS_UNIX:
				if (isdir (dst, NULLCP, 1) == NOTOK)
					break;
#ifdef apollo
				if (*dst == '/')
					 sprintf (bp = buffer, "%s", dst);
				else
#endif
					 sprintf (bp = buffer, "%s/", dst);
				bp += strlen (bp);
				if (dst = rindex (*src, '/'))
					dst++;
				if (dst == NULL || *dst == NULL)
					dst = *src;
				 strcpy (bp, dst);
				dst = buffer;
				goto ask_it;

			default:
				break;
			}

		dst = str2file (dst);
		 put (*src, dst, append);
		goto out;
	}

	switch (realstore) {
	case RFS_UNKNOWN:
		advise (NULLCP, "%s", rs_unknown);
		goto out;

	case RFS_UNIX:
		if (dst)
#ifdef apollo
			if (*(bp = str2file (dst)) == '/') {
				 strcpy (buffer, bp);
				bp = buffer;
			} else
#endif
				 sprintf (bp = buffer, "%s/", str2file (dst));
		else if (rcwd)
			 sprintf (bp = buffer, "%s", str2file (""));
		else
			 strcpy (bp = buffer, "./");
		bp += strlen (bp);
		break;

	default:
		advise (NULLCP, "%s", rs_support);
		goto out;
	}

	if (isdir (str2file (buffer), NULLCP, 0) == NOTOK)
		goto out;

	for (gp = src; *gp && !interrupted; gp++) {
		switch (realstore) {
		case RFS_UNIX:
			if (dst = rindex (*gp, '/'))
				dst++;
			if (dst == NULL || *dst == NULL)
				dst = *gp;
			break;

		default:
			dst = *gp;
			break;
		}
		 strcpy (bp, dst);
		dst = str2file (buffer);

		if (sglobbed) {
			if (query)
				switch (ask ("%s %s %s", append ? "append" : "put", *gp, dst)) {
				case NOTOK:
					continue;

				case OK:
				default:
					break;

				case DONE:
					goto out;
				}
			else
				advise (NULLCP, "%s %s %s", append ? "append" : "put", *gp,
						dst);
		}

		 put (*gp, dst, append);

		if (ftamfd == NOTOK)
			break;
	}

out:
	;
	blkfree (src);
	if (freedst)
		free (freedst);

	return OK;
#else
	result = put (dst, append);
	return result;
#endif
}
Beispiel #19
0
ReturnStatus
FileMetaDAO::movDir(const std::string &srcPath,
                    const std::string &destPath)
{
	Channel* pDataChannel = ChannelManager::getInstance()->Mapping(m_BucketId);
	NameSpace *DataNS = pDataChannel->m_DataNS;
	
    int rt = 0;
    int error = 0;

    ReturnStatus rs;

    // check src path

    rs = isdir(srcPath);

    if (!rs.success()) {
        if (NOT_DIRECTORY == rs.errorCode) {
            return ReturnStatus(MU_FAILED, SRC_PATH_NOT_DIRECTORY);

        } else if (PATH_INVALID == rs.errorCode) {
            return ReturnStatus(MU_FAILED, SRC_PATH_INVALID);

        } else if (PATH_NOT_EXIST == rs.errorCode) {
            return ReturnStatus(MU_FAILED, SRC_PATH_NOT_EXIST);
        }

        return rs;
    }

    // check dest path

    rs = isdir(prefix(destPath));

    if (!rs.success()) {
        if (MU_UNKNOWN_ERROR != rs.errorCode) {
            return ReturnStatus(MU_FAILED, DEST_PATH_INVALID);
        }

        return rs;
    }

    rt = DataNS->Move(srcPath.c_str(), destPath.c_str());

    if (-1 == rt) {
        error = errno;
        ERROR_LOG("src path %s, dest path %s, rename() error, %s.",
                  srcPath.c_str(), destPath.c_str(), strerror(error));

        if (ENOTDIR == error) {
            return ReturnStatus(MU_FAILED, NOT_DIRECTORY);

        } else if (ENOTEMPTY == error || EEXIST == error) {
            return ReturnStatus(MU_FAILED, DIRECTORY_NOT_EMPTY);

        } else {
            return ReturnStatus(MU_FAILED, MU_UNKNOWN_ERROR);
        }
    }

    return ReturnStatus(MU_SUCCESS);
}
Beispiel #20
0
/* search_for_exec_prefix requires that argv0_path be no more than
   MAXPATHLEN bytes long.
*/
static int
search_for_exec_prefix(char *argv0_path, char *home)
{
    size_t n;

    /* If PYTHONHOME is set, we believe it unconditionally */
    if (home) {
        char *delim;
        delim = strchr(home, DELIM);
        if (delim)
            strncpy(exec_prefix, delim+1, MAXPATHLEN);
        else
            strncpy(exec_prefix, home, MAXPATHLEN);
        joinpath(exec_prefix, lib_python);
        joinpath(exec_prefix, "lib-dynload");
        return 1;
    }

    /* Check to see if argv[0] is in the build directory. "pybuilddir.txt"
       is written by setup.py and contains the relative path to the location
       of shared library modules. */
    strcpy(exec_prefix, argv0_path);
    joinpath(exec_prefix, "pybuilddir.txt");
    if (isfile(exec_prefix)) {
      FILE *f = fopen(exec_prefix, "r");
      if (f == NULL)
	errno = 0;
      else {
	char rel_builddir_path[MAXPATHLEN+1];
	size_t n;
	n = fread(rel_builddir_path, 1, MAXPATHLEN, f);
	rel_builddir_path[n] = '\0';
	fclose(f);
	if (n >= 0) {
	  strcpy(exec_prefix, argv0_path);
	  joinpath(exec_prefix, rel_builddir_path);
	  return -1;
	}
      }
    }

    /* Search from argv0_path, until root is found */
    copy_absolute(exec_prefix, argv0_path);
    do {
        n = strlen(exec_prefix);
        joinpath(exec_prefix, lib_python);
        joinpath(exec_prefix, "lib-dynload");
        if (isdir(exec_prefix))
            return 1;
        exec_prefix[n] = '\0';
        reduce(exec_prefix);
    } while (exec_prefix[0]);

    /* Look at configure's EXEC_PREFIX */
    strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN);
    joinpath(exec_prefix, lib_python);
    joinpath(exec_prefix, "lib-dynload");
    if (isdir(exec_prefix))
        return 1;

    /* Fail */
    return 0;
}
Beispiel #21
0
FILE *
collect(struct header *hp, int printheaders)
{
	FILE *fbuf;
	int lc, cc, fd, c, t, lastlong, rc, sig;
	int escape, eofcount, longline;
	char getsub;
	char linebuf[LINESIZE], tempname[PATHSIZE], *cp;

	collf = NULL;
	eofcount = 0;
	hadintr = 0;
	lastlong = 0;
	longline = 0;
	if ((cp = value("escape")) != NULL)
		escape = *cp;
	else
		escape = ESCAPE;
	noreset++;

	(void)snprintf(tempname, sizeof(tempname),
	    "%s/mail.RsXXXXXXXXXX", tmpdir);
	if ((fd = mkstemp(tempname)) == -1 ||
	    (collf = Fdopen(fd, "w+")) == NULL) {
		warn("%s", tempname);
		goto err;
	}
	(void)rm(tempname);

	/*
	 * If we are going to prompt for a subject,
	 * refrain from printing a newline after
	 * the headers (since some people mind).
	 */
	t = GTO|GSUBJECT|GCC|GNL;
	getsub = 0;
	if (hp->h_subject == NULL && value("interactive") != NULL &&
	    (value("ask") != NULL || value("asksub") != NULL))
		t &= ~GNL, getsub++;
	if (printheaders) {
		puthead(hp, stdout, t);
		fflush(stdout);
	}
	if (getsub && gethfromtty(hp, GSUBJECT) == -1)
		goto err;

	if (0) {
cont:
		/* Come here for printing the after-suspend message. */
		if (isatty(0)) {
			puts("(continue)");
			fflush(stdout);
		}
	}
	for (;;) {
		c = readline(stdin, linebuf, LINESIZE, &sig);

		/* Act on any signal caught during readline() ignoring 'c' */
		switch (sig) {
		case 0:
			break;
		case SIGINT:
			if (collabort())
				goto err;
			continue;
		case SIGHUP:
			rewind(collf);
			savedeadletter(collf);
			/*
			 * Let's pretend nobody else wants to clean up,
			 * a true statement at this time.
			 */
			exit(1);
		default:
			/* Stopped due to job control */
			(void)kill(0, sig);
			goto cont;
		}

		/* No signal, check for error */
		if (c < 0) {
			if (value("interactive") != NULL &&
			    value("ignoreeof") != NULL && ++eofcount < 25) {
				puts("Use \".\" to terminate letter");
				continue;
			}
			break;
		}
		lastlong = longline;
		longline = (c == LINESIZE - 1);
		eofcount = 0;
		hadintr = 0;
		if (linebuf[0] == '.' && linebuf[1] == '\0' &&
		    value("interactive") != NULL && !lastlong &&
		    (value("dot") != NULL || value("ignoreeof") != NULL))
			break;
		if (linebuf[0] != escape || value("interactive") == NULL ||
		    lastlong) {
			if (putline(collf, linebuf, !longline) < 0)
				goto err;
			continue;
		}
		c = linebuf[1];
		switch (c) {
		default:
			/*
			 * On double escape, just send the single one.
			 * Otherwise, it's an error.
			 */
			if (c == escape) {
				if (putline(collf, &linebuf[1], !longline) < 0)
					goto err;
				else
					break;
			}
			puts("Unknown tilde escape.");
			break;
		case '!':
			/*
			 * Shell escape, send the balance of the
			 * line to sh -c.
			 */
			shell(&linebuf[2]);
			break;
		case ':':
		case '_':
			/*
			 * Escape to command mode, but be nice!
			 */
			execute(&linebuf[2], 1);
			goto cont;
		case '.':
			/*
			 * Simulate end of file on input.
			 */
			goto out;
		case 'q':
			/*
			 * Force a quit of sending mail.
			 * Act like an interrupt happened.
			 */
			hadintr++;
			collabort();
			fputs("Interrupt\n", stderr);
			goto err;
		case 'x':
			/*
			 * Force a quit of sending mail.
			 * Do not save the message.
			 */
			goto err;
		case 'h':
			/*
			 * Grab a bunch of headers.
			 */
			grabh(hp, GTO|GSUBJECT|GCC|GBCC);
			goto cont;
		case 't':
			/*
			 * Add to the To list.
			 */
			hp->h_to = cat(hp->h_to, extract(&linebuf[2], GTO));
			break;
		case 's':
			/*
			 * Set the Subject list.
			 */
			cp = &linebuf[2];
			while (isspace(*cp))
				cp++;
			hp->h_subject = savestr(cp);
			break;
		case 'c':
			/*
			 * Add to the CC list.
			 */
			hp->h_cc = cat(hp->h_cc, extract(&linebuf[2], GCC));
			break;
		case 'b':
			/*
			 * Add stuff to blind carbon copies list.
			 */
			hp->h_bcc = cat(hp->h_bcc, extract(&linebuf[2], GBCC));
			break;
		case 'd':
			linebuf[2] = '\0';
			strlcat(linebuf, getdeadletter(), sizeof(linebuf));
			/* fall into . . . */
		case 'r':
		case '<':
			/*
			 * Invoke a file:
			 * Search for the file name,
			 * then open it and copy the contents to collf.
			 */
			cp = &linebuf[2];
			while (isspace(*cp))
				cp++;
			if (*cp == '\0') {
				puts("Interpolate what file?");
				break;
			}
			cp = expand(cp);
			if (cp == NULL)
				break;
			if (isdir(cp)) {
				printf("%s: Directory\n", cp);
				break;
			}
			if ((fbuf = Fopen(cp, "r")) == NULL) {
				warn("%s", cp);
				break;
			}
			printf("\"%s\" ", cp);
			fflush(stdout);
			lc = 0;
			cc = 0;
			while ((rc = readline(fbuf, linebuf, LINESIZE, NULL)) >= 0) {
				if (rc != LINESIZE - 1)
					lc++;
				if ((t = putline(collf, linebuf,
						 rc != LINESIZE-1)) < 0) {
					(void)Fclose(fbuf);
					goto err;
				}
				cc += t;
			}
			(void)Fclose(fbuf);
			printf("%d/%d\n", lc, cc);
			break;
		case 'w':
			/*
			 * Write the message on a file.
			 */
			cp = &linebuf[2];
			while (*cp == ' ' || *cp == '\t')
				cp++;
			if (*cp == '\0') {
				fputs("Write what file!?\n", stderr);
				break;
			}
			if ((cp = expand(cp)) == NULL)
				break;
			rewind(collf);
			exwrite(cp, collf, 1);
			break;
		case 'm':
		case 'M':
		case 'f':
		case 'F':
			/*
			 * Interpolate the named messages, if we
			 * are in receiving mail mode.  Does the
			 * standard list processing garbage.
			 * If ~f is given, we don't shift over.
			 */
			if (forward(linebuf + 2, collf, tempname, c) < 0)
				goto err;
			goto cont;
		case '?':
			if ((fbuf = Fopen(_PATH_TILDE, "r")) == NULL) {
				warn(_PATH_TILDE);
				break;
			}
			while ((t = getc(fbuf)) != EOF)
				(void)putchar(t);
			(void)Fclose(fbuf);
			break;
		case 'p':
			/*
			 * Print out the current state of the
			 * message without altering anything.
			 */
			rewind(collf);
			puts("-------\nMessage contains:");
			puthead(hp, stdout, GTO|GSUBJECT|GCC|GBCC|GNL);
			while ((t = getc(collf)) != EOF)
				(void)putchar(t);
			goto cont;
		case '|':
			/*
			 * Pipe message through command.
			 * Collect output as new message.
			 */
			rewind(collf);
			mespipe(collf, &linebuf[2]);
			goto cont;
		case 'v':
		case 'e':
			/*
			 * Edit the current message.
			 * 'e' means to use EDITOR
			 * 'v' means to use VISUAL
			 */
			rewind(collf);
			mesedit(collf, c);
			goto cont;
		}
	}

	if (value("interactive") != NULL) {
		if (value("askcc") != NULL || value("askbcc") != NULL) {
			if (value("askcc") != NULL) {
				if (gethfromtty(hp, GCC) == -1)
					goto err;
			}
			if (value("askbcc") != NULL) {
				if (gethfromtty(hp, GBCC) == -1)
					goto err;
			}
		} else {
			puts("EOT");
			(void)fflush(stdout);
		}
	}
	goto out;
err:
	if (collf != NULL) {
		(void)Fclose(collf);
		collf = NULL;
	}
out:
	if (collf != NULL)
		rewind(collf);
	noreset--;
	return(collf);
}
Beispiel #22
0
Walkqid*
devwalk(Chan *c, Chan *nc, char **name, int nname, Dirtab *tab, int ntab, Devgen *gen)
{
	int i, j, alloc;
	Walkqid *wq;
	char *n;
	Dir dir;

	if(nname > 0)
		isdir(c);

	alloc = 0;
	wq = smalloc(sizeof(Walkqid)+(nname-1)*sizeof(Qid));
	if(waserror()){
		if(alloc && wq->clone!=nil)
			cclose(wq->clone);
		free(wq);
		return nil;
	}
	if(nc == nil){
		nc = devclone(c);
		nc->type = 0;	/* device doesn't know about this channel yet */
		alloc = 1;
	}
	wq->clone = nc;

	for(j=0; j<nname; j++){
		if(!(nc->qid.type&QTDIR)){
			if(j==0)
				error(Enotdir);
			goto Done;
		}
		n = name[j];
		if(strcmp(n, ".") == 0){
    Accept:
			wq->qid[wq->nqid++] = nc->qid;
			continue;
		}
		if(strcmp(n, "..") == 0){
			if((*gen)(nc, nil, tab, ntab, DEVDOTDOT, &dir) != 1){
				print("devgen walk .. in dev%s %llux broken\n",
					devtab[nc->type]->name, nc->qid.path);
				error("broken devgen");
			}
			nc->qid = dir.qid;
			goto Accept;
		}
		/*
		 * Ugly problem: If we're using devgen, make sure we're
		 * walking the directory itself, represented by the first
		 * entry in the table, and not trying to step into a sub-
		 * directory of the table, e.g. /net/net. Devgen itself
		 * should take care of the problem, but it doesn't have
		 * the necessary information (that we're doing a walk).
		 */
		if(gen==devgen && nc->qid.path!=tab[0].qid.path)
			goto Notfound;
		for(i=0;; i++) {
			switch((*gen)(nc, n, tab, ntab, i, &dir)){
			case -1:
			Notfound:
				if(j == 0)
					error(Enonexist);
				kstrcpy(up->errstr, Enonexist, ERRMAX);
				goto Done;
			case 0:
				continue;
			case 1:
				if(strcmp(n, dir.name) == 0){
					nc->qid = dir.qid;
					goto Accept;
				}
				continue;
			}
		}
	}
	/*
	 * We processed at least one name, so will return some data.
	 * If we didn't process all nname entries succesfully, we drop
	 * the cloned channel and return just the Qids of the walks.
	 */
Done:
	poperror();
	if(wq->nqid < nname){
		if(alloc)
			cclose(wq->clone);
		wq->clone = nil;
	}else if(wq->clone){
		/* attach cloned channel to same device */
		wq->clone->type = c->type;
	}
	return wq;
}
Beispiel #23
0
// setup sets up the tree for the initial build.
static void
setup(void)
{
	int i;
	Buf b;
	char *p;

	binit(&b);

	// Create bin directory.
	p = bpathf(&b, "%s/bin", goroot);
	if(!isdir(p))
		xmkdir(p);

	// Create package directory.
	p = bpathf(&b, "%s/pkg", goroot);
	if(!isdir(p))
		xmkdir(p);
	p = bpathf(&b, "%s/pkg/%s_%s", goroot, gohostos, gohostarch);
	if(rebuildall)
		xremoveall(p);
	xmkdirall(p);
	if(!streq(goos, gohostos) || !streq(goarch, gohostarch)) {
		p = bpathf(&b, "%s/pkg/%s_%s", goroot, goos, goarch);
		if(rebuildall)
			xremoveall(p);
		xmkdirall(p);
	}

	// Create object directory.
	// We keep it in pkg/ so that all the generated binaries
	// are in one tree.  If pkg/obj/libgc.a exists, it is a dreg from
	// before we used subdirectories of obj.  Delete all of obj
	// to clean up.
	bpathf(&b, "%s/pkg/obj/libgc.a", goroot);
	if(isfile(bstr(&b)))
		xremoveall(bpathf(&b, "%s/pkg/obj", goroot));
	p = bpathf(&b, "%s/pkg/obj/%s_%s", goroot, gohostos, gohostarch);
	if(rebuildall)
		xremoveall(p);
	xmkdirall(p);

	// Create tool directory.
	// We keep it in pkg/, just like the object directory above.
	if(rebuildall)
		xremoveall(tooldir);
	xmkdirall(tooldir);

	// Remove tool binaries from before the tool/gohostos_gohostarch
	xremoveall(bpathf(&b, "%s/bin/tool", goroot));

	// Remove old pre-tool binaries.
	for(i=0; i<nelem(oldtool); i++)
		xremove(bpathf(&b, "%s/bin/%s", goroot, oldtool[i]));

	// If $GOBIN is set and has a Go compiler, it must be cleaned.
	for(i=0; gochars[i]; i++) {
		if(isfile(bprintf(&b, "%s%s%c%s", gobin, slash, gochars[i], "g"))) {
			for(i=0; i<nelem(oldtool); i++)
				xremove(bprintf(&b, "%s%s%s", gobin, slash, oldtool[i]));
			break;
		}
	}

	// For release, make sure excluded things are excluded.
	if(hasprefix(goversion, "release.") || hasprefix(goversion, "go")) {
		for(i=0; i<nelem(unreleased); i++)
			if(isdir(bpathf(&b, "%s/%s", goroot, unreleased[i])))
				fatal("%s should not exist in release build", bstr(&b));
	}

	bfree(&b);
}
Beispiel #24
0
/*
 * Name:	averify
 * Description:	This function verifies and (if fix > 0) fixes the attributes
 *		of the file at the path provided.
 * Arguments:	fix - 0 - do not fix entries, 1 - fix entries
 *		ftype - single character "type" the entry is supposed to be
 *		path - path to file
 *		ainfo - attribute info structure representing the attributes
 *			the entry is supposed to be
 * NOTE:	attributes are links and permissions
 * Possible return values:
 * - 0 = successful
 * - VE_EXIST = path name does not exist
 * - VE_FTYPE = path file type is not recognized, is not supported,
 *		or is not what was expected
 * - VE_ATTR = path mode/group/user is not what was expected
 * - VE_CONT = mod time/link target/major/minor/size/file system type/current
 *		directory is not what was expected
 * - VE_FAIL = utime/target directory/link/stat/symlink/mknod/chmod/statvfs/
 *		chown failed
 */
int
averify(int fix, char *ftype, char *path, struct ainfo *ainfo)
{
	struct group	*grp; 	/* group entry buffer */
	struct passwd	*pwd;
	int		n;
	int		setval;
	int		uid, gid;
	int		dochown;
	int		retcode;
	int		statError = 0;
	int		targ_is_dir = 0;	/* replacing a directory */
	char		myftype;
	char		buf[PATH_MAX];
	ino_t		my_ino;
	dev_t		my_dev;
	char 		cwd[MAXPATHLEN];
	char 		*cd;
	char 		*c;

	setval = (*ftype == '?');
	retcode = 0;
	reperr(NULL);

	if (get_disable_attribute_check()) {
		return (0);
	}

	if (*ftype == 'l') {
		if (stat(path, &status) < 0) {
			retcode = VE_EXIST;
			reperr(pkg_gt(ERR_EXIST));
		}

		my_ino = status.st_ino;
		my_dev = status.st_dev;

		/* Get copy of the current working directory */
		if (getcwd(cwd, MAXPATHLEN) == NULL) {
			reperr(pkg_gt(ERR_GETWD));
			return (VE_FAIL);
		}

		/*
		 * Change to the directory in which the hard
		 * link is to be created.
		 */
		cd = strdup(path);
		c = strrchr(cd, '/');
		if (c) {
			/* bugid 4247895 */
			if (strcmp(cd, c) == 0)
				(void) strcpy(cd, "/");
			else
				*c = NULL;

			if (chdir(cd) != 0) {
				reperr(pkg_gt(ERR_CHDIR), cd);
				return (VE_FAIL);
			}
		}
		free(cd);

		if (retcode || (status.st_nlink < 2) ||
		    (stat(ainfo->local, &status) < 0) ||
		    (my_dev != status.st_dev) || (my_ino != status.st_ino)) {
			if (fix) {
				/*
				 * Don't want to do a hard link to a
				 * directory.
				 */
				if (!isdir(ainfo->local)) {
					(void) chdir(cwd);
					reperr(pkg_gt(ERR_LINKISDIR),
					    ainfo->local);
					return (VE_FAIL);
				}
				/* Now do the link. */
				if (!clear_target(path, ftype, targ_is_dir))
					return (VE_FAIL);

				if (link(ainfo->local, path)) {
					(void) chdir(cwd);
					reperr(pkg_gt(ERR_LINKFAIL),
					    ainfo->local);
					return (VE_FAIL);
				}
				retcode = 0;
			} else {
				/* Go back to previous working directory */
				if (chdir(cwd) != 0)
					reperr(pkg_gt(ERR_CHDIR), cwd);

				reperr(pkg_gt(ERR_LINK), ainfo->local);
				return (VE_CONT);
			}
		}

		/* Go back to previous working directory */
		if (chdir(cwd) != 0) {
			reperr(pkg_gt(ERR_CHDIR), cwd);
			return (VE_CONT);
		}

		return (retcode);
	}

	retcode = 0;

	/* If we are to process symlinks the old way then we follow the link */
	if (nonABI_symlinks()) {
		if ((*ftype == 's') ? lstat(path, &status) :
			stat(path, &status)) {
			reperr(pkg_gt(ERR_EXIST));
			retcode = VE_EXIST;
			myftype = '?';
			statError++;
		}
	/* If not then we inspect the target of the link */
	} else {
		if ((n = lstat(path, &status)) == -1) {
			reperr(pkg_gt(ERR_EXIST));
			retcode = VE_EXIST;
			myftype = '?';
			statError++;
		}
	}
	if (!statError) {
		/* determining actual type of existing object */
		switch (status.st_mode & S_IFMT) {
		    case S_IFLNK:
			myftype = 's';
			break;

		    case S_IFIFO:
			myftype = 'p';
			break;

		    case S_IFCHR:
			myftype = 'c';
			break;

		    case S_IFDIR:
			myftype = 'd';
			targ_is_dir = 1;
			break;

		    case S_IFBLK:
			myftype = 'b';
			break;

		    case S_IFREG:
		    case 0:
			myftype = 'f';
			break;

		    case S_IFDOOR:
			myftype = 'D';
			break;

		    default:
			reperr(pkg_gt(ERR_UNKNOWN));
			return (VE_FTYPE);
		}
	}

	if (setval) {
		/*
		 * Check to make sure that a package or an installf that uses
		 * wild cards '?' to assume the ftype of an object on the
		 * system is not assuming a door ftype. Doors are not supported
		 * but should be ignored.
		 */
		if (myftype == 'D') {
			reperr(pkg_gt(ERR_FTYPED), path);
			retcode = VE_FTYPE;
			return (VE_FTYPE);
		} else {
			*ftype = myftype;
		}
	} else if (!retcode && (*ftype != myftype) &&
	    ((myftype != 'f') || !strchr("ilev", *ftype)) &&
	    ((myftype != 'd') || (*ftype != 'x'))) {
		reperr(pkg_gt(ERR_FTYPE), *ftype, myftype);
		retcode = VE_FTYPE;
	}

	if (!retcode && (*ftype == 's')) {
		/* make sure that symbolic link is correct */
		n = readlink(path, buf, PATH_MAX);
		if (n < 0) {
			reperr(pkg_gt(ERR_SLINK), ainfo->local);
			retcode = VE_CONT;
		} else if (ainfo->local != NULL) {
			buf[n] = '\0';
			if (strcmp(buf, ainfo->local)) {
				reperr(pkg_gt(ERR_SLINK), ainfo->local);
				retcode = VE_CONT;
			}
		} else if (ainfo->local == NULL) {
			/*
			 * Since a sym link target exists, insert it
			 * into the ainfo structure
			 */
			buf[n] = '\0';
			ainfo->local = strdup(buf);
		}
	}

	if (retcode) {
		/* The path doesn't exist or is different than it should be. */
		if (fix) {
			/*
			 * Clear the way for the write. If it won't clear,
			 * there's nothing we can do.
			 */
			if (!clear_target(path, ftype, targ_is_dir))
				return (VE_FAIL);

			if ((*ftype == 'd') || (*ftype == 'x')) {
				char	*pt, *p;

				/* Try to make it the easy way */
				if (mkdir(path, ainfo->mode)) {
					/*
					 * Failing that, walk through the
					 * parent directories creating
					 * whatever is needed.
					 */
					p = strdup(path);
					pt = (*p == '/') ? p+1 : p;
					do {
						if (pt = strchr(pt, '/'))
							*pt = '\0';
						if (access(p, 0) &&
						    mkdir(p, ainfo->mode))
							break;
						if (pt)
							*pt++ = '/';
					} while (pt);
					free(p);
				}
				if (stat(path, &status) < 0) {
					reperr(pkg_gt(ERR_DIRFAIL));
					return (VE_FAIL);
				}
			} else if (*ftype == 's') {
				if (symlink(ainfo->local, path)) {
					reperr(pkg_gt(ERR_SLINKFAIL),
					    ainfo->local);
					return (VE_FAIL);
				}

			} else if (*ftype == 'c') {
				int wilddevno = 0;
				/*
				 * The next three if's support 2.4 and older
				 * packages that use "?" as device numbers.
				 * This should be considered for removal by
				 * release 2.7 or so.
				 */
				if (ainfo->major == BADMAJOR) {
					ainfo->major = 0;
					wilddevno = 1;
				}

				if (ainfo->minor == BADMINOR) {
					ainfo->minor = 0;
					wilddevno = 1;
				}

				if (wilddevno) {
					wilddevno = 0;
					logerr(MSG_WLDDEVNO, path,
					    ainfo->major, ainfo->minor);
				}

				if (mknod(path, ainfo->mode | S_IFCHR,
				    makedev(ainfo->major, ainfo->minor)) ||
				    (stat(path, &status) < 0)) {
					reperr(pkg_gt(ERR_CDEVFAIL));
					return (VE_FAIL);
				}
			} else if (*ftype == 'b') {
				int wilddevno = 0;
				/*
				 * The next three if's support 2.4 and older
				 * packages that use "?" as device numbers.
				 * This should be considered for removal by
				 * release 2.7 or so.
				 */
				if (ainfo->major == BADMAJOR) {
					ainfo->major = 0;
					wilddevno = 1;
				}

				if (ainfo->minor == BADMINOR) {
					ainfo->minor = 0;
					wilddevno = 1;
				}

				if (wilddevno) {
					wilddevno = 0;
					logerr(MSG_WLDDEVNO, path,
					    ainfo->major, ainfo->minor);
				}

				if (mknod(path, ainfo->mode | S_IFBLK,
				    makedev(ainfo->major, ainfo->minor)) ||
				    (stat(path, &status) < 0)) {
					reperr(pkg_gt(ERR_BDEVFAIL));
					return (VE_FAIL);
				}
			} else if (*ftype == 'p') {
				if (mknod(path, ainfo->mode | S_IFIFO, NULL) ||
				    (stat(path, &status) < 0)) {
					reperr(pkg_gt(ERR_PIPEFAIL));
					return (VE_FAIL);
				}
			} else
				return (retcode);

		} else
			return (retcode);
	}

	if (*ftype == 's')
		return (0); /* don't check anything else */
	if (*ftype == 'i')
		return (0); /* don't check anything else */

	retcode = 0;
	if ((myftype == 'c') || (myftype == 'b')) {
		if (setval || (ainfo->major == BADMAJOR))
			ainfo->major = major(status.st_rdev);
		if (setval || (ainfo->minor == BADMINOR))
			ainfo->minor = minor(status.st_rdev);
		/* check major & minor */
		if (status.st_rdev != makedev(ainfo->major, ainfo->minor)) {
			reperr(pkg_gt(ERR_MAJMIN), ainfo->major, ainfo->minor,
			    major(status.st_rdev), minor(status.st_rdev));
			retcode = VE_CONT;
		}
	}

	/* compare specified mode w/ actual mode excluding sticky bit */
	if (setval || (ainfo->mode == BADMODE) || (ainfo->mode == WILDCARD))
		ainfo->mode = status.st_mode & 07777;
	else if ((ainfo->mode & 06777) != (status.st_mode & 06777)) {
		if (fix) {
			if ((ainfo->mode == BADMODE) ||
			    (chmod(path, ainfo->mode) < 0))
				retcode = VE_FAIL;
		} else {
			reperr(pkg_gt(ERR_PERM), ainfo->mode,
				status.st_mode & 07777);
			if (!retcode)
				retcode = VE_ATTR;
		}
	}

	dochown = 0;

	/* get group entry for specified group */
	if (setval || strcmp(ainfo->group, BADGROUP) == 0) {
		grp = cgrgid(status.st_gid);
		if (grp)
			(void) strcpy(ainfo->group, grp->gr_name);
		else {
			if (!retcode)
				retcode = VE_ATTR;
			reperr(pkg_gt(ERR_BADGRPID), status.st_gid);
		}
		gid = status.st_gid;
	} else if ((grp = cgrnam(ainfo->group)) == NULL) {
		reperr(pkg_gt(ERR_BADGRPNM), ainfo->group);
		if (!retcode)
			retcode = VE_ATTR;
	} else if ((gid = grp->gr_gid) != status.st_gid) {
		if (fix) {
			/* save specified GID */
			gid = grp->gr_gid;
			dochown++;
		} else {
			if ((grp = cgrgid((int)status.st_gid)) ==
			    (struct group *)NULL) {
				reperr(pkg_gt(ERR_GROUP), ainfo->group,
				    "(null)");
			} else {
				reperr(pkg_gt(ERR_GROUP), ainfo->group,
				    grp->gr_name);
			}
			if (!retcode)
				retcode = VE_ATTR;
		}
	}

	/* get password entry for specified owner */
	if (setval || strcmp(ainfo->owner, BADOWNER) == 0) {
		pwd = cpwuid((int)status.st_uid);
		if (pwd)
			(void) strcpy(ainfo->owner, pwd->pw_name);
		else {
			if (!retcode)
				retcode = VE_ATTR;
			reperr(pkg_gt(ERR_BADUSRID), status.st_uid);
		}
		uid = status.st_uid;
	} else if ((pwd = cpwnam(ainfo->owner)) == NULL) {
		/* UID does not exist in password file */
		reperr(pkg_gt(ERR_BADUSRNM), ainfo->owner);
		if (!retcode)
			retcode = VE_ATTR;
	} else if ((uid = pwd->pw_uid) != status.st_uid) {
		/* get owner name for actual UID */
		if (fix) {
			uid = pwd->pw_uid;
			dochown++;
		} else {
			pwd = cpwuid((int)status.st_uid);
			if (pwd == NULL)
				reperr(pkg_gt(ERR_BADUSRID),
				    (int)status.st_uid);
			else
				reperr(pkg_gt(ERR_OWNER), ainfo->owner,
				    pwd->pw_name);

			if (!retcode)
				retcode = VE_ATTR;
		}
	}

	if (statvfs(path, &vfsstatus) < 0) {
		reperr(pkg_gt(ERR_EXIST));
		retcode = VE_FAIL;
	} else {
		if (dochown) {
			/* pcfs doesn't support file ownership */
			if (strcmp(vfsstatus.f_basetype, "pcfs") != 0 &&
			    chown(path, uid, gid) < 0) {
				retcode = VE_FAIL; /* chown failed */
			}
		}
	}

	if (retcode == VE_FAIL)
		reperr(pkg_gt(ERR_ATTRFAIL));
	return (retcode);
}
Beispiel #25
0
static int
rootgen(struct chan *c, char *name,
		struct dirtab *tab, int nd, int s, struct dir *dp)
{
	int p, i;
	struct rootdata *r;
	int iter;
	printd("rootgen, path is %d, tap %p, nd %d s %d name %s\n", c->qid.path,
	       tab, nd, s, name);

	if (s == DEVDOTDOT) {
		panic("this is busted");
		p = rootdata[c->qid.path].dotdot;
		// XXX we need to set the vers too.  equiv to mkqid(&c->qid, ...)
		c->qid.path = p;
		c->qid.type = QTDIR;
		name = devname();
		if (p != 0) {
			/* TODO: what is this doing?  do we want to walk the entire table,
			 * or are we just walking the siblings of our parent? */
			for (i = p;;) {
				if (roottab[i].qid.path == c->qid.path) {
					name = roottab[i].name;
					break;
				}
				i = roottab[i].qid.vers;
				if (!i)
					break;
			}
		}
		devdir(c, c->qid, name, 0, eve, 0777, dp);
		return 1;
	}

	if (c->qid.type != QTDIR) {
		/* return ourselved the first time; after that, -1 */
		if (s)
			return -1;
		tab = &roottab[c->qid.path];
		devdir(c, tab->qid, tab->name, tab->length, eve, tab->perm, dp);
		return 1;
	}

	if (name != NULL) {
		int path = c->qid.path;
		isdir(c);
		tab = &roottab[rootdata[path].child];
		/* we're starting at a directory. It might be '.' */
		for (iter = 0, i = rootdata[path].child; /* break */; iter++) {
			if (strncmp(tab->name, name, KNAMELEN) == 0) {
				printd("Rootgen returns 1 for %s\n", name);
				devdir(c, tab->qid, tab->name, tab->length, eve, tab->perm, dp);
				printd("return 1 with [%d, %d, %d]\n", dp->qid.path,
				       dp->qid.vers, dp->qid.type);
				return 1;
			}
			if (iter > rootmaxq) {
				printk("BUG:");
				dumprootdev();
				printk("name %s\n", name);
				return -1;
			}
			i = roottab[i].qid.vers;
			if (!i)
				break;
			tab = &roottab[i];
		}
		printd("rootgen: :%s: failed at path %d\n", name, path);
		return -1;
	}
	/* need to gen the file or the contents of the directory we are currently
	 * at.  but i think the tab entries are all over the place.  nd is how
	 * many entries the directory has. */
	if (s >= nd) {
		printd("S OVERFLOW\n");
		return -1;
	}
	//tab += s;	/* this would only work if our entries were contig in the tab */
	for (i = rootdata[c->qid.path].child; i; i = roottab[i].qid.vers) {
		tab = &roottab[i];
		if (s-- == 0)
			break;
	}
	if (!i) {
		printd("I OVERFLOW\n");
		return -1;
	}
	printd("root scan find returns path %p name %s\n", tab->qid.path, tab->name);
	devdir(c, tab->qid, tab->name, tab->length, eve, tab->perm, dp);
	return 1;
}
/*--------------------------------------------------------------------------*/
void Initialize(void)
{
	static char env[1024];
	static char initstr[]="exec(\"SCI/etc/scilab.start\",-1);quit;";
	static int iflag = -1, stacksize = 1000000, ierr = 0;

#ifdef _MSC_VER
#define nb_args 3
	static char *argv[nb_args];
	static char JavaSciInterf[]="javasci";
	static char nw[]="-nw";
	static char nb[]="-nb";
#endif


	char *sciPath = (char*)getenv("SCI");

#ifdef _MSC_VER
	/* Delete the windows mode and the banner */
	{
		argv[0] = JavaSciInterf;
		argv[1] = nw;
		argv[2] = nb;
		setCommandLineArgs(argv, nb_args);
	}

#endif

#ifdef _MSC_VER
	if ( sciPath == NULL )
	{
		/* Detection Scilab path */
		char modname[PATH_MAX+1];
		if (!GetModuleFileName (GetModuleHandle("javasci.dll"), modname, PATH_MAX))
		{
			MessageBox(NULL,"javasci.dll not found","Warning",MB_ICONWARNING);
		}
		else
		{
			char *p = NULL;
			if ((p = strrchr (modname, '\\')) == NULL) exit(1); /* remove \javasci.dll from modname */
			else
			{
				*p='\0';
				if ((p = strrchr (modname, '\\')) == NULL) exit(1); /* remove \bin from modname */
				else
				{
					*p='\0';
					SetScilabEnvironmentVariables(modname);
				}
			}
		}
	}
	else
	{
		char *pathSCI = strdup(sciPath);
		SetScilabEnvironmentVariables(pathSCI);
		if (pathSCI) { FREE(pathSCI); pathSCI  =NULL; }
	}
#else
	if (sciPath==NULL)
	{
		fprintf(stderr,"Please define SCI environment variable\n");
		exit(EXIT_FAILURE);
	}
	else
	{
		sprintf (env, "%s=%s", "SCI", sciPath);
		setSCIpath(SCI);
		putenv (env);
	}

	/*
	* This stuff is a workaround when the user is using javasci in the Scilab
	* official binary
	* The problem in this case is that the TCL_LIBRARY & TK_LIBRARY are not
	* set correctly and TCL has trouble to find himself.
	*
	* As we are sure to use the binary, we know where to find
	* See: http://bugzilla.scilab.org/show_bug.cgi?id=3605
	*/
#ifndef _MSC_VER
#ifdef WITH_TK
#define BASEPATHTOTHIRDPARTY "/../../thirdparty/"
#define DIRECTORYOFTCL "tcl"
#define DIRECTORYOFTK "tk"
	int commonPart=strlen(sciPath)+strlen(BASEPATHTOTHIRDPARTY)+strlen(".")+strlen(TCL_VERSION)+1;
	char *pathToTcl=(char*)MALLOC((strlen(DIRECTORYOFTCL)+commonPart)*sizeof(char));
	sprintf(pathToTcl, "%s%s%s%s", sciPath, BASEPATHTOTHIRDPARTY, DIRECTORYOFTCL, TCL_VERSION);

	/* Test if we find the thirdparty directory. If it is the case, it is most
	* probable that we are working with the binary version of Scilab
	*/
	if (isdir(pathToTcl)){
#define EXPORTTCL "TCL_LIBRARY="
#define EXPORTTK "TK_LIBRARY="
		char *pathToTk=(char*)MALLOC((strlen(DIRECTORYOFTK)+commonPart)*sizeof(char));
		sprintf(pathToTk, "%s%s%s%s", sciPath, BASEPATHTOTHIRDPARTY, DIRECTORYOFTK, TCL_VERSION);

		char *exportTcl=(char*)MALLOC((strlen(EXPORTTCL)+strlen(pathToTcl)+1)*sizeof(char));
		char *exportTk=(char*)MALLOC((strlen(EXPORTTK)+strlen(pathToTk)+1)*sizeof(char));
		sprintf(exportTcl,"%s%s",EXPORTTCL,pathToTcl);
		sprintf(exportTk,"%s%s",EXPORTTK,pathToTk);
		/* Export both TCL_LIBRARY & TK_LIBRARY */
		putenv(exportTcl);
		putenv(exportTk);
	}
#endif
#endif

#endif
	/* set TMPDIR */
	C2F(settmpdir)();

	/* For the initialization of the Scilab primivite : fromjava() */
	SetFromJavaToON();

	InitializeLaunchScilabSignal();

	/* Scilab Initialization */
	C2F(inisci)(&iflag,&stacksize,&ierr);
	if ( ierr > 0 )
	{
		fprintf(stderr,"Scilab initialization failed !\n");
		exit(1);
	}

	/* Load of Scilab.start */
	C2F(scirun)(initstr,(int)strlen(initstr));
}
Beispiel #27
0
bool CHttpServer::decide(String const &method, String const &arg_uri, String const &query,
                         HeaderList const &headers, String const &body/*, IResponseSender& respSender*/ )
{
    if (verbose) RAWTRACE1("Decide what to do with uri %s", arg_uri.c_str());
    callback_t callback = registered(arg_uri);
    if (callback) {
        if (verbose) RAWTRACE1("Uri %s is registered callback, so handle it appropriately", arg_uri.c_str());

        if ( callback == rho_http_ruby_proc_callback )
            call_ruby_proc( query, body );
        else
            callback(this, query.length() ? query : body);

        return false;
    }

    String uri = arg_uri;

    String fullPath = CFilePath::join(m_root, uri);
#ifndef RHO_NO_RUBY_API    
    if (rho_ruby_is_started())
    {
        Route route;
        if (dispatch(uri, route)) {
            if (verbose) RAWTRACE1("Uri %s is correct route, so enable MVC logic", uri.c_str());
            
            VALUE req = create_request_hash(route.application, route.model, route.action, route.id,
                                            method, uri, query, headers, body);
            VALUE data = callFramework(req);
            String reply(getStringFromValue(data), getStringLenFromValue(data));
            rho_ruby_releaseValue(data);

            bool isRedirect = String_startsWith(reply, "HTTP/1.1 301") ||
                              String_startsWith(reply, "HTTP/1.1 302");

            if (!send_response(reply, isRedirect))
                return false;

            if (method == "GET")
                rho_rhodesapp_keeplastvisitedurl(uri.c_str());

		    if ( sync::RhoconnectClientManager::haveRhoconnectClientImpl() ) {

			    if (!route.id.empty()) {
				    sync::RhoconnectClientManager::rho_sync_addobjectnotify_bysrcname(route.model.c_str(), route.id.c_str());
			    }			
		    }
            
            return true;
        }
        
        if (isdir(fullPath)) {
            if (verbose) RAWTRACE1("Uri %s is directory, redirecting to index", uri.c_str());
            String q = query.empty() ? "" : "?" + query;
            
            HeaderList headers;
            headers.push_back(Header("Location", CFilePath::join( uri, "index" RHO_ERB_EXT) + q));
            
            send_response(create_response("301 Moved Permanently", headers), true);
            return false;
        }

        if (isindex(uri)) {
            if (!isfile(fullPath)) {
                if (verbose) RAWLOG_ERROR1("The file %s was not found", fullPath.c_str());
                String error = "<!DOCTYPE html><html><font size=\"+4\"><h2>404 Not Found.</h2> The file " + uri + " was not found.</font></html>";
                send_response(create_response("404 Not Found",error));
                return false;
            }
            
            if (verbose) RAWTRACE1("Uri %s is index file, call serveIndex", uri.c_str());

            VALUE req = create_request_hash(route.application, route.model, route.action, route.id,
                                            method, uri, query, headers, body);

            VALUE data = callServeIndex((char *)fullPath.c_str(), req);
            String reply(getStringFromValue(data), getStringLenFromValue(data));
            rho_ruby_releaseValue(data);

            if (!send_response(reply))
                return false;

            if (method == "GET")
                rho_rhodesapp_keeplastvisitedurl(uri.c_str());

            return true;
        }
    }
#endif
    // Try to send requested file
    if (verbose) RAWTRACE1("Uri %s should be regular file, trying to send it", uri.c_str());

    PROF_START("READ_FILE");
    bool bRes = send_file(uri, headers);
    PROF_STOP("READ_FILE");

    return bRes;
}
Beispiel #28
0
/**************************************************************
 * 寄信給站上使用者
 **************************************************************/
static int SendMail_Local(char *fname,char *from, const char *to, char *title,
						char ident)
{
	USEREC urcTmp;
	char pathTmp[PATHLEN];
	int retval, fsize;

	retval = CheckMail(&urcTmp, to, FALSE);
	if (retval == -1)
		return -1;
	/* kmwang:20000610:blacklist */
/* bug fixed by lasehu 2002/05/22
	if (in_blacklist(to, from))
		return -1;
		*/
	if (!is_emailaddr(from) && in_blacklist(to, from))
		return -1;
	else if (retval > 0)
	{
		bbslog("SENDMAIL", "from=%s, to=%s, total=%d, stat=ENOSPC",
			from, to, retval);
		return -2;
	}

	/* Auto-Forward */
	if ((urcTmp.flags[0] & FORWARD_FLAG) && is_emailaddr(urcTmp.email))
	{
#ifdef NSYSUBBS
		if (strncmp(urcTmp.email, "bbs@", 4) && !strstr(urcTmp.email, ".."))
		{
#endif
			if (SendMail_Internet(-1, fname, from, urcTmp.email, title, urcTmp.userid) == 0)
				return 0;
#ifdef NSYSUBBS
		}
#endif
		bbslog("ERR", "auto-forward: %s", urcTmp.email);
	}

	setmailfile(pathTmp, to, NULL);
	if (!isdir(pathTmp))
	{
		if (mkdir(pathTmp, 0700) == -1)
			return -1;
	}

	if (!(fsize = get_num_records(fname, sizeof(char))))
		return -2;

	if (fsize > MAX_MAIL_SIZE)
	{
		bbslog("SENDMAIL", "from=%s, to=%s, size=%d, stat=EFBIG",
		       from, to, fsize);
		return -3;
	}

#ifdef USE_THREADING	/* syhu */
	if (append_article(fname, pathTmp, from, title, ident, NULL, FALSE, 0, NULL, -1, -1 ) == -1)		/* syhu */
#else
	if (append_article(fname, pathTmp, from, title, ident, NULL, FALSE, 0, NULL) == -1)
#endif
		return -1;

	return 0;
}
Beispiel #29
0
static int
pkgxfer(char *srcinst, int options)
{
	int	r;
	struct pkginfo info;
	FILE	*fp, *pp;
	char	*pt, *src, *dst;
	char	dstdir[PATH_MAX],
		temp[PATH_MAX],
		srcdir[PATH_MAX],
		cmd[CMDSIZE],
		pkgname[NON_ABI_NAMELNGTH];
	int	i, n, part, nparts, maxpartsize, curpartcnt, iscomp;
	char	volnos[128], tmpvol[128];
	struct	statvfs64 svfsb;
	longlong_t free_blocks;
	struct	stat	srcstat;

	info.pkginst = NULL; /* required initialization */

	/*
	 * when this routine is entered, the first part of
	 * the package to transfer is already available in
	 * the directory indicated by 'src' --- unless the
	 * source device is a datstream, in which case only
	 * the pkginfo and pkgmap files are available in 'src'
	 */
	src = srcdev.dirname;
	dst = dstdev.dirname;

	if (!(options & PT_SILENT))
		(void) fprintf(stderr, pkg_gt(MSG_TRANSFER), srcinst);
	(void) strlcpy(dstinst, srcinst, sizeof (dstinst));

	if (!(options & PT_ODTSTREAM)) {
		/* destination is a (possibly mounted) directory */
		(void) snprintf(dstdir, sizeof (dstdir),
		    "%s/%s", dst, dstinst);

		/*
		 * need to check destination directory to assure
		 * that we will not be duplicating a package which
		 * already resides there (though we are allowed to
		 * overwrite the same version)
		 */
		pkgdir = src;
		if (fpkginfo(&info, srcinst)) {
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_NOEXISTS), srcinst);
			(void) fpkginfo(&info, NULL);
			return (1);
		}
		pkgdir = dst;

		(void) strlcpy(temp, srcinst, sizeof (temp));
		if (pt = strchr(temp, '.'))
			*pt = '\0';
		(void) strlcat(temp, ".*", sizeof (temp));

		if (pt = fpkginst(temp, info.arch, info.version)) {
			/*
			 * the same instance already exists, although
			 * its pkgid might be different
			 */
			if (options & PT_OVERWRITE) {
				(void) strlcpy(dstinst, pt, sizeof (dstinst));
				(void) snprintf(dstdir, sizeof (dstdir),
				    "%s/%s", dst, dstinst);
			} else {
				progerr(pkg_gt(ERR_TRANSFER));
				logerr(pkg_gt(MSG_DUPVERS), srcinst);
				(void) fpkginfo(&info, NULL);
				(void) fpkginst(NULL);
				return (2);
			}
		} else if (options & PT_RENAME) {
			/*
			 * find next available instance by appending numbers
			 * to the package abbreviation until the instance
			 * does not exist in the destination directory
			 */
			if (pt = strchr(temp, '.'))
				*pt = '\0';
			for (i = 2; (access(dstdir, 0) == 0); i++) {
				(void) snprintf(dstinst, sizeof (dstinst),
				    "%s.%d", temp, i);
				(void) snprintf(dstdir, sizeof (dstdir),
				    "%s/%s", dst, dstinst);
			}
		} else if (options & PT_OVERWRITE) {
			/*
			 * we're allowed to overwrite, but there seems
			 * to be no valid package to overwrite, and we are
			 * not allowed to rename the destination, so act
			 * as if we weren't given permission to overwrite
			 * --- this keeps us from removing a destination
			 * instance which is named the same as the source
			 * instance, but really reflects a different pkg!
			 */
			options &= (~PT_OVERWRITE);
		}
		(void) fpkginfo(&info, NULL);
		(void) fpkginst(NULL);

		if (ckoverwrite(dst, dstinst, options))
			return (2);

		if (isdir(dstdir) && mkdir(dstdir, 0755)) {
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_MKDIR), dstdir);
			return (1);
		}

		(void) snprintf(srcdir, sizeof (srcdir),
		    "%s/%s", src, srcinst);
		if (stat(srcdir, &srcstat) != -1) {
			if (chmod(dstdir, (srcstat.st_mode & S_IAMB)) == -1) {
				progerr(pkg_gt(ERR_TRANSFER));
				logerr(pkg_gt(MSG_CHMODDIR), dstdir);
				return (1);
			}
		} else {
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_STATDIR), srcdir);
			return (1);
		}
	}

	if (!(options & PT_SILENT) && strcmp(dstinst, srcinst))
		(void) fprintf(stderr, pkg_gt(MSG_RENAME), dstinst);

	(void) snprintf(srcdir, sizeof (srcdir), "%s/%s", src, srcinst);
	if (chdir(srcdir)) {
		progerr(pkg_gt(ERR_TRANSFER));
		logerr(pkg_gt(MSG_CHDIR), srcdir);
		return (1);
	}

	if (ids_name) {	/* unpack the datatstream into a directory */
		/*
		 * transfer pkginfo & pkgmap first
		 */
		(void) snprintf(cmd, sizeof (cmd),
		    "%s -pudm %s", CPIOPROC, dstdir);
		if ((pp = epopen(cmd, "w")) == NULL) {
			rpterr();
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_POPEN), cmd, errno);
			return (1);
		}
		(void) fprintf(pp, "%s\n%s\n", PKGINFO, PKGMAP);

		(void) sighold(SIGINT);
		(void) sighold(SIGHUP);
		r = epclose(pp);
		(void) sigrelse(SIGINT);
		(void) sigrelse(SIGHUP);

		if (r != 0) {
			rpterr();
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_PCLOSE), cmd, errno);
			return (1);
		}

		if (options & PT_INFO_ONLY)
			return (0); /* don't transfer objects */

		if (chdir(dstdir)) {
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_CHDIR), dstdir);
			return (1);
		}

		/*
		 * for each part of the package, use cpio() to
		 * unpack the archive into the destination directory
		 */
		nparts = ds_findpkg(srcdev.cdevice, srcinst);
		if (nparts < 0) {
			progerr(pkg_gt(ERR_TRANSFER));
			return (1);
		}
		for (part = 1; part <= nparts; /* void */) {
			if (ds_getpkg(srcdev.cdevice, part, dstdir)) {
				progerr(pkg_gt(ERR_TRANSFER));
				return (1);
			}
			part++;
			if (dstdev.mount) {
				(void) chdir("/");
				if (pkgumount(&dstdev))
					return (1);
				if (part <= nparts) {
					if (n = pkgmount(&dstdev, NULL, part+1,
					    nparts, 1))
						return (n);
					if (ckoverwrite(dst, dstinst, options))
						return (1);
					if (isdir(dstdir) &&
					    mkdir(dstdir, 0755)) {
						progerr(
						    pkg_gt(ERR_TRANSFER));
						logerr(pkg_gt(MSG_MKDIR),
						    dstdir);
						return (1);
					}
					/*
					 * since volume is removable, each part
					 * must contain a duplicate of the
					 * pkginfo file to properly identify the
					 * volume
					 */
					if (chdir(srcdir)) {
						progerr(
						    pkg_gt(ERR_TRANSFER));
						logerr(pkg_gt(MSG_CHDIR),
						    srcdir);
						return (1);
					}
					if ((pp = epopen(cmd, "w")) == NULL) {
						rpterr();
						progerr(
						    pkg_gt(ERR_TRANSFER));
						logerr(pkg_gt(MSG_POPEN),
						    cmd, errno);
						return (1);
					}
					(void) fprintf(pp, "pkginfo");

					(void) sighold(SIGINT);
					(void) sighold(SIGHUP);
					r = epclose(pp);
					(void) sigrelse(SIGINT);
					(void) sigrelse(SIGHUP);

					if (r != 0) {
						rpterr();
						progerr(
						    pkg_gt(ERR_TRANSFER));
						logerr(pkg_gt(MSG_PCLOSE),
						    cmd, errno);
						return (1);
					}
					if (chdir(dstdir)) {
						progerr(
						    pkg_gt(ERR_TRANSFER));
						logerr(pkg_gt(MSG_CHDIR),
						    dstdir);
						return (1);
					}
				}
			}
		}
		return (0);
	}

	if ((fp = fopen(PKGMAP, "r")) == NULL) {
		progerr(pkg_gt(ERR_TRANSFER));
		logerr(pkg_gt(MSG_NOPKGMAP), srcinst);
		return (1);
	}

	nparts = 1;
	if (!rd_map_size(fp, &nparts, &maxpartsize, &compressedsize))
		return (1);
	else
		(void) fclose(fp);

	if (srcdev.mount) {
		if (ckvolseq(srcdir, 1, nparts)) {
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_SEQUENCE));
			return (1);
		}
	}

	/* write each part of this package */
	if (options & PT_ODTSTREAM) {
		char line[128];
		(void) mgets(line, 128);
		curpartcnt = -1;
		/* LINTED E_SEC_SCANF_UNBOUNDED_COPY */
		if (sscanf(line, "%s %d %d %[ 0-9]", pkgname, &nparts,
		    &maxpartsize, volnos) == 4) {
			(void) sscanf(volnos,
			    "%d %[ 0-9]", &curpartcnt, tmpvol);
			(void) strlcpy(volnos, tmpvol, sizeof (volnos));
		}
	}

	for (part = 1; part <= nparts; /* void */) {
		if (curpartcnt == 0 && (options & PT_ODTSTREAM)) {
			char prompt[128];
			int index;
			ds_volno++;
			(void) ds_close(0);
			(void) sprintf(prompt,
			    pkg_gt("Insert %%v %d of %d into %%p"),
			    ds_volno, ds_volcnt);
			if (n = getvol(ods_name, NULL, DM_FORMAT, prompt))
				return (n);
			if ((ds_fd = open(dstdev.cdevice, O_WRONLY)) < 0) {
				progerr(pkg_gt(ERR_TRANSFER));
				logerr(pkg_gt(MSG_OPEN), dstdev.cdevice,
				    errno);
				return (1);
			}
			if (ds_ginit(dstdev.cdevice) < 0) {
				progerr(pkg_gt(ERR_TRANSFER));
				logerr(pkg_gt(MSG_OPEN), dstdev.cdevice,
				    errno);
				(void) ds_close(0);
				return (1);
			}

			(void) sscanf(volnos, "%d %[ 0-9]", &index, tmpvol);
			(void) strlcpy(volnos, tmpvol, sizeof (volnos));
			curpartcnt += index;
		}

		if (options & PT_INFO_ONLY)
			nparts = 0;

		if (part == 1) {
			(void) snprintf(cmd, sizeof (cmd),
			    "find %s %s", PKGINFO, PKGMAP);
			if (nparts && (isdir(INSTALL) == 0)) {
				(void) strlcat(cmd, " ", sizeof (cmd));
				(void) strlcat(cmd, INSTALL, sizeof (cmd));
			}
		} else
			(void) snprintf(cmd, sizeof (cmd), "find %s", PKGINFO);

		if (nparts > 1) {
			(void) snprintf(temp, sizeof (temp),
			    "%s.%d", RELOC, part);
			if (iscpio(temp, &iscomp) || isdir(temp) == 0) {
				(void) strlcat(cmd, " ", sizeof (cmd));
				(void) strlcat(cmd, temp, sizeof (cmd));
			}
			(void) snprintf(temp, sizeof (temp),
			    "%s.%d", ROOT, part);
			if (iscpio(temp, &iscomp) || isdir(temp) == 0) {
				(void) strlcat(cmd, " ", sizeof (cmd));
				(void) strlcat(cmd, temp, sizeof (cmd));
			}
			(void) snprintf(temp, sizeof (temp),
			    "%s.%d", ARCHIVE, part);
			if (isdir(temp) == 0) {
				(void) strlcat(cmd, " ", sizeof (cmd));
				(void) strlcat(cmd, temp, sizeof (cmd));
			}
		} else if (nparts) {
			for (i = 0; reloc_names[i] != NULL; i++) {
				if (iscpio(reloc_names[i], &iscomp) ||
				    isdir(reloc_names[i]) == 0) {
					(void) strlcat(cmd, " ", sizeof (cmd));
					(void) strlcat(cmd, reloc_names[i],
					    sizeof (cmd));
				}
			}
			for (i = 0; root_names[i] != NULL; i++) {
				if (iscpio(root_names[i], &iscomp) ||
				    isdir(root_names[i]) == 0) {
					(void) strlcat(cmd, " ", sizeof (cmd));
					(void) strlcat(cmd, root_names[i],
					    sizeof (cmd));
				}
			}
			if (isdir(ARCHIVE) == 0) {
				(void) strlcat(cmd, " ", sizeof (cmd));
				(void) strlcat(cmd, ARCHIVE, sizeof (cmd));
			}
		}
		if (options & PT_ODTSTREAM) {
			(void) snprintf(cmd + strlen(cmd),
			    sizeof (cmd) - strlen(cmd),
			    " -print | %s -ocD -C %d",
			    CPIOPROC, (int)BLK_SIZE);
		} else {
			if (statvfs64(dstdir, &svfsb) == -1) {
				progerr(pkg_gt(ERR_TRANSFER));
				logerr(pkg_gt(MSG_STATVFS), dstdir, errno);
				return (1);
			}

			free_blocks = (((long)svfsb.f_frsize > 0) ?
			    howmany(svfsb.f_frsize, DEV_BSIZE) :
			    howmany(svfsb.f_bsize, DEV_BSIZE)) * svfsb.f_bavail;

			if ((has_comp_size ? compressedsize : maxpartsize) >
			    free_blocks) {
				progerr(pkg_gt(ERR_TRANSFER));
				logerr(pkg_gt(MSG_NOSPACE),
				    has_comp_size ?
				    (long)compressedsize : (long)maxpartsize,
				    free_blocks);
				return (1);
			}
			(void) snprintf(cmd + strlen(cmd),
			    sizeof (cmd) - strlen(cmd),
			    " -print | %s -pdum %s",
			    CPIOPROC, dstdir);
		}

		n = esystem(cmd, -1, (options & PT_ODTSTREAM) ? ds_fd : -1);
		if (n) {
			rpterr();
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_CMDFAIL), cmd, n);
			return (1);
		}

		part++;
		if (srcdev.mount && (nparts > 1)) {
			/* unmount current source volume */
			(void) chdir("/");
			if (pkgumount(&srcdev))
				return (1);
			/* loop until volume is mounted successfully */
			while (part <= nparts) {
				/* read only */
				n = pkgmount(&srcdev, NULL, part, nparts, 1);
				if (n)
					return (n);
				if (chdir(srcdir)) {
					progerr(pkg_gt(ERR_TRANSFER));
					logerr(pkg_gt(MSG_CORRUPT));
					(void) chdir("/");
					(void) pkgumount(&srcdev);
					continue;
				}
				if (ckvolseq(srcdir, part, nparts)) {
					(void) chdir("/");
					(void) pkgumount(&srcdev);
					continue;
				}
				break;
			}
		}
		if (!(options & PT_ODTSTREAM) && dstdev.mount) {
			/* unmount current volume */
			if (pkgumount(&dstdev))
				return (1);
			/* loop until next volume is mounted successfully */
			while (part <= nparts) {
				/* writable */
				n = pkgmount(&dstdev, NULL, part, nparts, 1);
				if (n)
					return (n);
				if (ckoverwrite(dst, dstinst, options))
					continue;
				if (isdir(dstdir) && mkdir(dstdir, 0755)) {
					progerr(pkg_gt(ERR_TRANSFER));
					logerr(pkg_gt(MSG_MKDIR), dstdir);
					continue;
				}
				break;
			}
		}

		if ((options & PT_ODTSTREAM) && part <= nparts) {
			if (curpartcnt >= 0 && part > curpartcnt) {
				char prompt[128];
				int index;
				ds_volno++;
				if (ds_close(0))
					return (1);
				(void) sprintf(prompt,
				    pkg_gt("Insert %%v %d of %d into %%p"),
				    ds_volno, ds_volcnt);
				if (n = getvol(ods_name, NULL, DM_FORMAT,
				    prompt))
					return (n);
				if ((ds_fd = open(dstdev.cdevice, 1)) < 0) {
					progerr(pkg_gt(ERR_TRANSFER));
					logerr(pkg_gt(MSG_OPEN),
					    dstdev.cdevice, errno);
					return (1);
				}
				if (ds_ginit(dstdev.cdevice) < 0) {
					progerr(pkg_gt(ERR_TRANSFER));
					logerr(pkg_gt(MSG_OPEN),
					    dstdev.cdevice, errno);
					(void) ds_close(0);
					return (1);
				}

				(void) sscanf(volnos, "%d %[ 0-9]", &index,
				    tmpvol);
				(void) strlcpy(volnos, tmpvol, sizeof (volnos));
				curpartcnt += index;
			}
		}

	}
	return (0);
}
Beispiel #30
0
int MakeTempDir(char path[/*FILENAME_MAX*/], const char* prefix) {
    int ret;

    Stroka sysTmp;

#ifdef _win32_
    if (!prefix || *prefix == '/') {
#else
    if (!prefix) {
#endif
        sysTmp = GetSystemTempDir();
        prefix = ~sysTmp;
    }

    if ((ret = ResolvePath(prefix, NULL, path, 1)) != 0)
        return ret;
    if ((ret = isdir(path)) != 0)
        return ret;
    if ((strlcat(path, "tmpXXXXXX", FILENAME_MAX) > FILENAME_MAX - 100))
        return EINVAL;
    if (!(mkdtemp(path)))
        return errno ? errno : EINVAL;
    strcat(path, LOCSLASH_S);
    return 0;
}

int RemoveTempDir(const char* dirName) {
    DIR *dir;
#ifndef DT_DIR
    struct stat sbp;
#endif
    if ((dir = opendir(dirName)) == 0)
        return errno ? errno : ENOENT;

    int ret;
    dirent ent, *pent;
    char path[FILENAME_MAX], *ptr;
    size_t len = strlcpy(path, dirName, FILENAME_MAX);

    if (path[len-1] != LOCSLASH_C) {
        path[len] = LOCSLASH_C;
        path[++len] = 0;
    }
    ptr = path + len;
    while ((ret = readdir_r(dir, &ent, &pent)) == 0 && pent == &ent) {
        if (!strcmp(ent.d_name, ".") || !strcmp(ent.d_name, ".."))
            continue;
#ifdef DT_DIR
        if (ent.d_type == DT_DIR)
#else
        lstat(ent.d_name, &sbp);
        if (S_ISREG(sbp.st_mode))
#endif
        {
            ret = ENOTEMPTY;
            break;
        }
        strcpy(ptr, ent.d_name);
        if (unlink(path)) {
            ret = errno ? errno : ENOENT;
            break;
        }
    }
    closedir(dir);
    if (ret)
        return ret;
    *ptr = 0;
    if (rmdir(path))
        return errno ? errno : ENOTEMPTY;
    return 0;
}