Ejemplo n.º 1
0
int main(int argc, char **argv)
{
    int ifd;
    uint32_t checksum;
    uint32_t addr;
    uint32_t ep;
    struct stat sbuf;
    unsigned char *ptr;
    char *name = "";

    cmdname = *argv;

    addr = ep = 0;

    while (--argc > 0 && **++argv == '-')
    {
        while (*++*argv)
        {
            switch (**argv)
            {
            case 'l':
                lflag = 1;
                break;
            case 'A':
                if ((--argc <= 0) || (opt_arch = get_arch(*++argv)) < 0)
                    usage();
                goto NXTARG;
            case 'C':
                if ((--argc <= 0) || (opt_comp = get_comp(*++argv)) < 0)
                    usage();
                goto NXTARG;
            case 'O':
                if ((--argc <= 0) || (opt_os = get_os(*++argv)) < 0)
                    usage();
                goto NXTARG;
            case 'T':
                if ((--argc <= 0) || (opt_type = get_type(*++argv)) < 0)
                    usage();
                goto NXTARG;

            case 'a':
                if (--argc <= 0)
                    usage();
                addr = strtoul(*++argv, (char **)&ptr, 16);
                if (*ptr)
                {
                    fprintf(stderr,
                            "%s: invalid load address %s\n",
                            cmdname, *argv);
                    exit(EXIT_FAILURE);
                }
                goto NXTARG;
            case 'd':
                if (--argc <= 0)
                    usage();
                datafile = *++argv;
                dflag = 1;
                goto NXTARG;
            case 'e':
                if (--argc <= 0)
                    usage();
                ep = strtoul(*++argv, (char **)&ptr, 16);
                if (*ptr)
                {
                    fprintf(stderr,
                            "%s: invalid entry point %s\n",
                            cmdname, *argv);
                    exit(EXIT_FAILURE);
                }
                eflag = 1;
                goto NXTARG;
            case 'n':
                if (--argc <= 0)
                    usage();
                name = *++argv;
                goto NXTARG;
            case 'v':
                vflag++;
                break;
            case 'x':
                xflag++;
                break;
            default:
                usage();
            }
        }
NXTARG:
        ;
    }

    if ((argc != 1) || ((lflag ^ dflag) == 0))
        usage();

    if (!eflag)
    {
        ep = addr;
        /* If XIP, entry point must be after the U-Boot header */
        if (xflag)
            ep += sizeof(image_header_t);
    }

    /*
     * If XIP, ensure the entry point is equal to the load address plus
     * the size of the U-Boot header.
     */
    if (xflag)
    {
        if (ep != addr + sizeof(image_header_t))
        {
            fprintf(stderr,
                    "%s: For XIP, the entry point must be the load addr + %lu\n",
                    cmdname, (unsigned long)sizeof(image_header_t));
            exit(EXIT_FAILURE);
        }
    }

    imagefile = *argv;

    if (lflag)
    {
        ifd = open(imagefile, O_RDONLY | O_BINARY);
    }
    else
    {
        ifd =
            open(imagefile, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
    }

    if (ifd < 0)
    {
        fprintf(stderr, "%s: Can't open %s: %s\n",
                cmdname, imagefile, strerror(errno));
        exit(EXIT_FAILURE);
    }

    if (lflag)
    {
        int len;
        char *data;
        /*
         * list header information of existing image
         */
        if (fstat(ifd, &sbuf) < 0)
        {
            fprintf(stderr, "%s: Can't stat %s: %s\n",
                    cmdname, imagefile, strerror(errno));
            exit(EXIT_FAILURE);
        }

        if ((unsigned)sbuf.st_size < sizeof(image_header_t))
        {
            fprintf(stderr,
                    "%s: Bad size: \"%s\" is no valid image\n",
                    cmdname, imagefile);
            exit(EXIT_FAILURE);
        }

        ptr = (unsigned char *)mmap(0, sbuf.st_size,
                                    PROT_READ, MAP_SHARED, ifd, 0);
        if ((caddr_t) ptr == (caddr_t) - 1)
        {
            fprintf(stderr, "%s: Can't read %s: %s\n",
                    cmdname, imagefile, strerror(errno));
            exit(EXIT_FAILURE);
        }

        /*
         * create copy of header so that we can blank out the
         * checksum field for checking - this can't be done
         * on the PROT_READ mapped data.
         */
        memcpy(hdr, ptr, sizeof(image_header_t));

        if (ntohl(hdr->ih_magic) != IH_MAGIC)
        {
            fprintf(stderr,
                    "%s: Bad Magic Number: \"%s\" is no valid image\n",
                    cmdname, imagefile);
            exit(EXIT_FAILURE);
        }

        data = (char *)hdr;
        len = sizeof(image_header_t);

        checksum = ntohl(hdr->ih_hcrc);
        hdr->ih_hcrc = htonl(0);        /* clear for re-calculation */

        if (crc32(0, data, len) != checksum)
        {
            fprintf(stderr,
                    "*** Warning: \"%s\" has bad header checksum!\n",
                    imagefile);
        }

        data = (char *)(ptr + sizeof(image_header_t));
        len = sbuf.st_size - sizeof(image_header_t);

        if (crc32(0, data, len) != ntohl(hdr->ih_dcrc))
        {
            fprintf(stderr,
                    "*** Warning: \"%s\" has corrupted data!\n",
                    imagefile);
        }

        /* for multi-file images we need the data part, too */
        print_header((image_header_t *) ptr);

        (void)munmap((void *)ptr, sbuf.st_size);
        (void)close(ifd);

        exit(EXIT_SUCCESS);
    }

    /*
     * Must be -w then:
     *
     * write dummy header, to be fixed later
     */
    memset(hdr, 0, sizeof(image_header_t));

    if (write(ifd, hdr, sizeof(image_header_t)) != sizeof(image_header_t))
    {
        fprintf(stderr, "%s: Write error on %s: %s\n",
                cmdname, imagefile, strerror(errno));
        exit(EXIT_FAILURE);
    }

    if (opt_type == IH_TYPE_MULTI || opt_type == IH_TYPE_SCRIPT)
    {
        char *file = datafile;
        unsigned long size;

        for (;;)
        {
            char *sep = NULL;

            if (file)
            {
                if ((sep = strchr(file, ':')) != NULL)
                {
                    *sep = '\0';
                }

                if (stat(file, &sbuf) < 0)
                {
                    fprintf(stderr, "%s: Can't stat %s: %s\n",
                            cmdname, file, strerror(errno));
                    exit(EXIT_FAILURE);
                }
                size = htonl(sbuf.st_size);
            }
            else
            {
                size = 0;
            }

            if (write(ifd, (char *)&size, sizeof(size)) != sizeof(size))
            {
                fprintf(stderr, "%s: Write error on %s: %s\n",
                        cmdname, imagefile, strerror(errno));
                exit(EXIT_FAILURE);
            }

            if (!file)
            {
                break;
            }

            if (sep)
            {
                *sep = ':';
                file = sep + 1;
            }
            else
            {
                file = NULL;
            }
        }

        file = datafile;

        for (;;)
        {
            char *sep = strchr(file, ':');
            if (sep)
            {
                *sep = '\0';
                copy_file(ifd, file, 1);
                *sep++ = ':';
                file = sep;
            }
            else
            {
                copy_file(ifd, file, 0);
                break;
            }
        }
    }
    else
    {
        copy_file(ifd, datafile, 0);
    }

    /* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
    (void)fdatasync(ifd);
#else
    (void)fsync(ifd);
#endif

    if (fstat(ifd, &sbuf) < 0)
    {
        fprintf(stderr, "%s: Can't stat %s: %s\n",
                cmdname, imagefile, strerror(errno));
        exit(EXIT_FAILURE);
    }

    ptr = (unsigned char *)mmap(0, sbuf.st_size,
                                PROT_READ | PROT_WRITE, MAP_SHARED, ifd,
                                0);
    if (ptr == (unsigned char *)MAP_FAILED)
    {
        fprintf(stderr, "%s: Can't map %s: %s\n",
                cmdname, imagefile, strerror(errno));
        exit(EXIT_FAILURE);
    }

    hdr = (image_header_t *) ptr;

    checksum = crc32(0,
                     (const char *)(ptr + sizeof(image_header_t)),
                     sbuf.st_size - sizeof(image_header_t));

    /* Build new header */
    hdr->ih_magic = htonl(IH_MAGIC);
    hdr->ih_time = htonl(sbuf.st_mtime);
    hdr->ih_size = htonl(sbuf.st_size - sizeof(image_header_t));
    hdr->ih_load = htonl(addr);
    hdr->ih_ep = htonl(ep);
    hdr->ih_dcrc = htonl(checksum);
    hdr->ih_os = opt_os;
    hdr->ih_arch = opt_arch;
    hdr->ih_type = opt_type;
    hdr->ih_comp = opt_comp;

    strncpy((char *)hdr->ih_name, name, IH_NMLEN);

    checksum = crc32(0, (const char *)hdr, sizeof(image_header_t));

    hdr->ih_hcrc = htonl(checksum);

    print_header(hdr);

    (void)munmap((void *)ptr, sbuf.st_size);

    /* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
    (void)fdatasync(ifd);
#else
    (void)fsync(ifd);
#endif

    if (close(ifd))
    {
        fprintf(stderr, "%s: Write error on %s: %s\n",
                cmdname, imagefile, strerror(errno));
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 2
0
void restore_and_error_exit()
{
    fclose(stdout);		/* was going to makefile */
    copy_file(backup, makefile);
    exit(1);
}
Ejemplo n.º 3
0
Archivo: show.c Proyecto: rforge/muste
static int text_show(long rivi1)
{
    int i;
    long jseur;
    int m;
    char llines[16], sline[51];
    char luku[8];
    long li;
    char y1[LLENGTH],y2[LLENGTH];
    char ch;
    int len;
    long jd;
    char *p;

    *sline=EOS;
    edit=laji();
    if (edit<0) return(-1);
    if (edit==1 || edit==2) jmax=ted2;

    putsaa();
    j=1l;
    jseur=rivi1;

    if (!muste_dd_call) // RS 30.5.2014
    {
        i=spec_find("SHOWLOAD",sbuf,LLENGTH);
        if (i>=0)
        {
            direct_showload(sbuf);
            return(1);
        }
    }
    luo_ikkuna();
    tyhjenna_ikkuna();
    putsaa();
    disp_show(jseur);

    if (g>2 && *word[2]=='"') // 19.7.2006
    {
        strcpy(sline,word[2]+1);
        p=strchr(sline,'"');
        if (p!=NULL)
        {
            *p=EOS;
            while ((p=strchr(sline,'_'))!=NULL) *p=' ';

            li=search(sline,jseur);
            if (li<=0L) li=1;
            jseur=li;
            disp_show(jseur);
        }
    }

    while (1)
    {
        if (edit!=0)
            m=nextch("SHOW: ENTER=Exit N=Next P=Prev E=End L=Load S=Search C=Copy");
        else
            m=nextch("SHOW: ENTER=Exit N=Next P=Prev E=End L=Load S=Search C=Copy D,d=Edit W=Win_char U=UTF-8");
        switch (m)
        {
        case CODE_EXIT:
        case CODE_RETURN:
            return(1);
        case CODE_NEXT:
        case 'N':
        case 'n':
            jseur+=(long)ndisp;
            if (jseur+(long)(ndisp-1)>jmax) jseur=jmax-(long)ndisp+1L;
            if (jseur<1L) jseur=1L;
            disp_show(jseur);
            break;

        case CODE_PREV:
        case 'P':
        case 'p':
            jseur-=(long)ndisp;
            if (jseur<1L) jseur=1L;
            else if (jseur>jmax-(long)ndisp) jseur=jmax-(long)ndisp+1L;
            disp_show(jseur);
            break;

        case CODE_HOME:
            if (cdisp) {
                cdisp-=c3+1;
                if (cdisp<0) cdisp=0;
                nayta_cdisp();
            }
            else jseur=1L;
            disp_show(jseur);
            break;

        case CODE_DOWN:
            if (jseur+(long)mdisp>jmax) break;
            j=jseur+(long)mdisp;
            i=etsi(j);
            if (i<0) {
                muste_fclose(text);
                return(-1);
            }
            /* 4.3.1996 */
            i=lue_rivi(line);
            if (edit!=2 && feof(text) && !*line) {
                jmax=j;
                break;
            }
            if (i<0) return(-1);
            SCROLL_UP(rdisp,r3,1);
            PR_EUDL;

//              i=sprintf(sbuf,"%6ld %s",j,line+cdisp);
//                 i=sprintf(sbuf,"%6ld ",j);
            i=sprintf(sbuf,"%6d ",(int)j);
            strncat(sbuf,line+cdisp,c3+1);
            i=strlen(sbuf);
            if (i>c3+8)
//                    write_string(sbuf,c3+8,shadow_code[sdisp],rdisp+mdisp,1);
                write_string(sbuf,c3+8,'4',rdisp+mdisp,1);
            else
            {
//                    write_string(sbuf,i,shadow_code[sdisp],rdisp+mdisp,1);
                write_string(sbuf,i,'4',rdisp+mdisp,1);
//                    write_string(space,c3+8-i,shadow_code[sdisp],rdisp+mdisp,1+i);
                write_string(space,c3+8-i,'4',rdisp+mdisp,1+i);
            }

            /*****************************************************
                            PR_EUDL; LOCATE(rdisp+mdisp,1);
                            strncpy(sbuf,space,c3+8);
                            i=sprintf(sbuf,"%6ld ",j);

                            if (strlen(line)<cdisp)
                                sprintf(sbuf+i,"%.*s",c3+2,space);
                            else
                                sprintf(sbuf+i,"%.*s",c3+2,line+cdisp);

                            write_string(sbuf,c3+8,shadow_code[sdisp],rdisp+mdisp,1);
            *******************************************************/

            ++j;
            ++jseur;
            if (edit!=3 && edit!=2) talleta_alku((long)j,muste_ftell(text));
            break;

        case CODE_UP:
            if (jseur<=1L) break;
            --jseur;
            i=etsi(jseur);
            lue_rivi(line);

            SCROLL_DOWN(rdisp,r3,1);
            PR_EUDL;
//              i=sprintf(sbuf,"%6ld %s",j,line+cdisp);
//                i=sprintf(sbuf,"%6ld ",j);
            i=sprintf(sbuf,"%6d ",(int)j);
            strncat(sbuf,line+cdisp,c3+1);
            i=strlen(sbuf);

            if (i>c3+8)
//                    write_string(sbuf,c3+8,shadow_code[sdisp],rdisp+1,1);
                write_string(sbuf,c3+8,'4',rdisp+1,1);
            else
            {
//                    write_string(sbuf,i,shadow_code[sdisp],rdisp+1,1);
                write_string(sbuf,i,'4',rdisp+1,1);
//                    write_string(space,c3+8-i,'\237',rdisp+1,1+i);
                write_string(space,c3+8-i,'4',rdisp+1,1+i);
            }

            j=jseur+1L;
            break;

        case CODE_RIGHT:
            ++cdisp;
            nayta_cdisp();
            disp_show(jseur);
            break;
        case CODE_LEFT:
            --cdisp;
            if (cdisp<0) cdisp=0;
            nayta_cdisp();
            disp_show(jseur);
            break;
        case CODE_END:
            cdisp+=c3+1;
            nayta_cdisp();
            disp_show(jseur);
            break;
        /*****************************************************
                      case CODE_HELP:
                        show_help();
                        dispw();
                        nayta_cdisp();
                        disp_show(jseur);
                        break;
        ******************************************************/

        /* tavalliset napit !special */

        case 'L':
        case 'l':
            strcpy(llines,muste_ltoa(jseur,luku,10));
            strcat(llines,",");
            strcat(llines,muste_ltoa(jseur+(long)mdisp-1L,luku,10));
            putsaa();
            LOCATE(r3+2,1);
            prompt("Lines to be loaded ? ",llines,15);
            i=load(llines);
            if (i<0) return(1);
            putsaa();
            break;

        case 'S':
        case 's':
            putsaa();
            LOCATE(r3+2,1);
            prompt("Text to be found? ",sline,50);
            li=search(sline,jseur);
            putsaa();
            if (li<=0L) break;
            jseur=li;
            disp_show(jseur);
            break;

        case 'E':
        case 'e':
            i=etsi(jmax);
            if (i<0) jseur=j-(long)ndisp+1L;
            else jseur=jmax-(long)ndisp+1L;
            disp_show(jseur);
            break;

        case 'C':
        case 'c':
            strcpy(llines,muste_ltoa(jseur,luku,10));
            strcat(llines,",");
            strcat(llines,muste_ltoa(jseur+(long)mdisp-1L,luku,10));
            putsaa();
            LOCATE(r3+2,1);
            prompt("Lines to be copied ? ",llines,15);
            LOCATE(r3+2,35);
            PR_EINV;
            prompt("To file ? ",cfile,32);
            i=copy_file(llines,cfile);
            putsaa();
            break;

        case 'D':
        case 'd':
            if (edit) break;
            jd=jseur;
            if (m=='d') jd=jseur+(long)(mdisp-1);
            li=rivit(jd);
            muste_fseek(text,li,0);
            lue_rivi(line);
            for (i=0; i<EDITLEV; ++i)
            {
                ch=line[i+cdisp];
                y1[i]=ch;
                if (ch==EOS) break;
            }
            len=i;
            y1[i]=EOS;
            strcpy(y2,y1);
            putsaa();
            LOCATE(r3+2,1);
            prompt(" Edit: ",y1,len);
            if (strlen(y1)<EDITLEV) strncat(y1,space,EDITLEV-strlen(y1));
            if (strlen(y2)<EDITLEV) strncat(y2,space,EDITLEV-strlen(y2));
            if (strcmp(y1,y2)!=0)
            {
                muste_fclose(text);
                text=muste_fopen(tfile,"r+t");
                muste_fseek(text,li+(long)cdisp,0);
                for (i=0; i<len; ++i) putc((int)y1[i],text);
                muste_fclose(text);
                text=muste_fopen(tfile,"rt");
                muste_fseek(text,li+(long)cdisp,0);
            }
            putsaa();
            disp_show(jseur);
            break;

        case 'W': // 26.3.2003;
        case 'w':
            if (win_conv==0 || win_conv==1) // RS 26.1.2014
            {
                win_conv=1-win_conv;
                if (win_conv)
                    w_codes_load(2);
                disp_show(jseur);
            }
            break;

        case 'U': // RS 26.1.2014
        case 'u':
            if (win_conv==0 || win_conv==999)
            {
                if (win_conv==0)
                {
                    strcpy(cur_encoding,muste_encoding);
                    strcpy(muste_encoding,"UTF-8");
                    win_conv=999;
                }
                else
                {
                    if (win_conv==999) win_conv=0;
                }
                disp_show(jseur);
            }
            break;


            /*
                          case 'A': for (i=0; i<100; ++i) Rprintf(" %ld",rivit[i]);
                                    Rprintf(" jmax=%d mdisp=%d",jmax,mdisp);
                                    break;
            */
        }
    }
}
Ejemplo n.º 4
0
static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
			     DIR *dir)
{
	size_t path_baselen = path->len;
	size_t template_baselen = template_path->len;
	struct dirent *de;

	/* Note: if ".git/hooks" file exists in the repository being
	 * re-initialized, /etc/core-git/templates/hooks/update would
	 * cause "git init" to fail here.  I think this is sane but
	 * it means that the set of templates we ship by default, along
	 * with the way the namespace under .git/ is organized, should
	 * be really carefully chosen.
	 */
	safe_create_dir(path->buf, 1);
	while ((de = readdir(dir)) != NULL) {
		struct stat st_git, st_template;
		int exists = 0;

		strbuf_setlen(path, path_baselen);
		strbuf_setlen(template_path, template_baselen);

		if (de->d_name[0] == '.')
			continue;
		strbuf_addstr(path, de->d_name);
		strbuf_addstr(template_path, de->d_name);
		if (lstat(path->buf, &st_git)) {
			if (errno != ENOENT)
				die_errno(_("cannot stat '%s'"), path->buf);
		}
		else
			exists = 1;

		if (lstat(template_path->buf, &st_template))
			die_errno(_("cannot stat template '%s'"), template_path->buf);

		if (S_ISDIR(st_template.st_mode)) {
			DIR *subdir = opendir(template_path->buf);
			if (!subdir)
				die_errno(_("cannot opendir '%s'"), template_path->buf);
			strbuf_addch(path, '/');
			strbuf_addch(template_path, '/');
			copy_templates_1(path, template_path, subdir);
			closedir(subdir);
		}
		else if (exists)
			continue;
		else if (S_ISLNK(st_template.st_mode)) {
			struct strbuf lnk = STRBUF_INIT;
			if (strbuf_readlink(&lnk, template_path->buf,
					    st_template.st_size) < 0)
				die_errno(_("cannot readlink '%s'"), template_path->buf);
			if (symlink(lnk.buf, path->buf))
				die_errno(_("cannot symlink '%s' '%s'"),
					  lnk.buf, path->buf);
			strbuf_release(&lnk);
		}
		else if (S_ISREG(st_template.st_mode)) {
			if (copy_file(path->buf, template_path->buf, st_template.st_mode))
				die_errno(_("cannot copy '%s' to '%s'"),
					  template_path->buf, path->buf);
		}
		else
			error(_("ignoring template %s"), template_path->buf);
	}
}
Ejemplo n.º 5
0
int launch_container_as_user(const char *user, const char *app_id, 
                   const char *container_id, const char *work_dir,
                   const char *script_name, const char *cred_file,
                   const char* pid_file, char* const* local_dirs,
                   char* const* log_dirs, const char *resources_key,
                   char* const* resources_values) {
  int exit_code = -1;
  char *script_file_dest = NULL;
  char *cred_file_dest = NULL;
  script_file_dest = get_container_launcher_file(work_dir);
  if (script_file_dest == NULL) {
    exit_code = OUT_OF_MEMORY;
    goto cleanup;
  }
  cred_file_dest = get_container_credentials_file(work_dir);
  if (NULL == cred_file_dest) {
    exit_code = OUT_OF_MEMORY;
    goto cleanup;
  }

  // open launch script
  int container_file_source = open_file_as_nm(script_name);
  if (container_file_source == -1) {
    goto cleanup;
  }

  // open credentials
  int cred_file_source = open_file_as_nm(cred_file);
  if (cred_file_source == -1) {
    goto cleanup;
  }

  // setsid 
  pid_t pid = setsid();
  if (pid == -1) {
    exit_code = SETSID_OPER_FAILED;
    goto cleanup;
  }

  // write pid to pidfile
  if (pid_file == NULL
      || write_pid_to_file_as_nm(pid_file, pid) != 0) {
    exit_code = WRITE_PIDFILE_FAILED;
    goto cleanup;
  }

  // cgroups-based resource enforcement
  if (resources_key != NULL && ! strcmp(resources_key, "cgroups")) {

    // write pid to cgroups
    char* const* cgroup_ptr;
    for (cgroup_ptr = resources_values; cgroup_ptr != NULL && 
         *cgroup_ptr != NULL; ++cgroup_ptr) {
      if (strcmp(*cgroup_ptr, "none") != 0 &&
            write_pid_to_cgroup_as_root(*cgroup_ptr, pid) != 0) {
        exit_code = WRITE_CGROUP_FAILED;
        goto cleanup;
      }
    }
  }

  // give up root privs
  if (change_user(user_detail->pw_uid, user_detail->pw_gid) != 0) {
    exit_code = SETUID_OPER_FAILED;
    goto cleanup;
  }

  if (create_container_directories(user, app_id, container_id, local_dirs,
                                   log_dirs, work_dir) != 0) {
    fprintf(LOGFILE, "Could not create container dirs");
    goto cleanup;
  }

  // 700
  if (copy_file(container_file_source, script_name, script_file_dest,S_IRWXU) != 0) {
    goto cleanup;
  }

  // 600
  if (copy_file(cred_file_source, cred_file, cred_file_dest,
        S_IRUSR | S_IWUSR) != 0) {
    goto cleanup;
  }

  fcloseall();
  umask(0027);
  if (chdir(work_dir) != 0) {
    fprintf(LOGFILE, "Can't change directory to %s -%s\n", work_dir,
	    strerror(errno));
    goto cleanup;
  }
  if (execlp(script_file_dest, script_file_dest, NULL) != 0) {
    fprintf(LOGFILE, "Couldn't execute the container launch file %s - %s", 
            script_file_dest, strerror(errno));
    exit_code = UNABLE_TO_EXECUTE_CONTAINER_SCRIPT;
    goto cleanup;
  }
  exit_code = 0;

 cleanup:
  free(script_file_dest);
  free(cred_file_dest);
  return exit_code;
}
Ejemplo n.º 6
0
Archivo: rerere.c Proyecto: emk/git
static int do_plain_rerere(struct string_list *rr, int fd)
{
	struct string_list conflict = { NULL, 0, 0, 1 };
	struct string_list update = { NULL, 0, 0, 1 };
	int i;

	find_conflict(&conflict);

	/*
	 * MERGE_RR records paths with conflicts immediately after merge
	 * failed.  Some of the conflicted paths might have been hand resolved
	 * in the working tree since then, but the initial run would catch all
	 * and register their preimages.
	 */

	for (i = 0; i < conflict.nr; i++) {
		const char *path = conflict.items[i].string;
		if (!string_list_has_string(rr, path)) {
			unsigned char sha1[20];
			char *hex;
			int ret;
			ret = handle_file(path, sha1, NULL);
			if (ret < 1)
				continue;
			hex = xstrdup(sha1_to_hex(sha1));
			string_list_insert(path, rr)->util = hex;
			if (mkdir(git_path("rr-cache/%s", hex), 0755))
				continue;
			handle_file(path, NULL, rr_path(hex, "preimage"));
			fprintf(stderr, "Recorded preimage for '%s'\n", path);
		}
	}

	/*
	 * Now some of the paths that had conflicts earlier might have been
	 * hand resolved.  Others may be similar to a conflict already that
	 * was resolved before.
	 */

	for (i = 0; i < rr->nr; i++) {
		int ret;
		const char *path = rr->items[i].string;
		const char *name = (const char *)rr->items[i].util;

		if (has_resolution(name)) {
			if (!merge(name, path)) {
				if (rerere_autoupdate)
					string_list_insert(path, &update);
				fprintf(stderr,
					"%s '%s' using previous resolution.\n",
					rerere_autoupdate
					? "Staged" : "Resolved",
					path);
				goto mark_resolved;
			}
		}

		/* Let's see if we have resolved it. */
		ret = handle_file(path, NULL, NULL);
		if (ret)
			continue;

		fprintf(stderr, "Recorded resolution for '%s'.\n", path);
		copy_file(rr_path(name, "postimage"), path, 0666);
	mark_resolved:
		rr->items[i].util = NULL;
	}

	if (update.nr)
		update_paths(&update);

	return write_rr(rr, fd);
}
Ejemplo n.º 7
0
static
rc_t run ( srakar_parms *pb )
{
    KFile * outfile;
    rc_t rc;

    const SRAMgr *mgr;

    rc = SRAMgrMakeRead ( & mgr );
    if ( rc != 0 )
        LOGERR ( klogInt, rc, "failed to open SRAMgr" );
    else
    {
        const SRATable *tbl;
        rc = SRAMgrOpenTableRead ( mgr, & tbl, "%s", pb -> src_path );
        if ( rc != 0 )
            PLOGERR ( klogInt, (klogInt, rc,
                "failed to open SRATable '$(spec)'", "spec=%s",
                pb -> src_path ));
        else
        {
            rc = KDirectoryCreateFile (pb->dir, &outfile, false, 0446,
                                       kcmParents | ( pb->force ? kcmInit : kcmCreate) , "%s", pb->dst_path);
            if (rc == 0)
            {
                const KFile * archive;

                rc = SRATableMakeSingleFileArchive (tbl, &archive, pb->lite,
                    NULL);
                if (rc == 0)
                {
                    rc = copy_file (archive, outfile);
                    KFileRelease (archive);
                }
                KFileRelease (outfile);
            }
            SRATableRelease ( tbl );
        }
        SRAMgrRelease (mgr);
    }
/*
    rc = KDirectoryCreateFile (pb->dir, &outfile, false, 0446, kcmParents | ( pb->force ? kcmInit : kcmCreate) , "%s", pb->dst_path);

    if (rc == 0)
    {
        const SRAMgr *mgr;

        rc = SRAMgrMakeRead ( & mgr );
        if ( rc != 0 )
            LOGERR ( klogInt, rc, "failed to open SRAMgr" );
        else
        {
            const SRATable *tbl;
            rc = SRAMgrOpenTableRead ( mgr, & tbl, "%s", pb -> src_path );
            if ( rc != 0 )
                PLOGERR ( klogInt, (klogInt, rc, "failed to open SRATable '$(spec)'", "spec=%s", pb -> src_path ));
            else
            {
                const KFile * archive;

                rc = SRATableMakeSingleFileArchive (tbl, &archive, pb->lite, NULL);
                if (rc == 0)
                {
                    rc = copy_file (archive, outfile);
                    KFileRelease (archive);
                }
                SRATableRelease ( tbl );
            }
            SRAMgrRelease (mgr);
        }
        KFileRelease (outfile);
    }
*/
    return rc;
}
Ejemplo n.º 8
0
/*
 * copydir: copy a directory
 *
 * If recurse is false, subdirectories are ignored.  Anything that's not
 * a directory or a regular file is ignored.
 */
void
copydir(char *fromdir, char *todir, bool recurse)
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		fromfile[MAXPGPATH];
	char		tofile[MAXPGPATH];

	if (mkdir(todir, S_IRWXU) != 0)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create directory \"%s\": %m", todir)));

	xldir = AllocateDir(fromdir);
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not open directory \"%s\": %m", fromdir)));

	while ((xlde = ReadDir(xldir, fromdir)) != NULL)
	{
		struct stat fst;

		/* If we got a cancel signal during the copy of the directory, quit */
		CHECK_FOR_INTERRUPTS();

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

		snprintf(fromfile, MAXPGPATH, "%s/%s", fromdir, xlde->d_name);
		snprintf(tofile, MAXPGPATH, "%s/%s", todir, xlde->d_name);

		if (lstat(fromfile, &fst) < 0)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not stat file \"%s\": %m", fromfile)));

		if (S_ISDIR(fst.st_mode))
		{
			/* recurse to handle subdirectories */
			if (recurse)
				copydir(fromfile, tofile, true);
		}
		else if (S_ISREG(fst.st_mode))
			copy_file(fromfile, tofile);
	}
	FreeDir(xldir);

	/*
	 * Be paranoid here and fsync all files to ensure the copy is really done.
	 * But if fsync is disabled, we're done.
	 */
	if (!enableFsync)
		return;

	xldir = AllocateDir(todir);
	if (xldir == NULL)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not open directory \"%s\": %m", todir)));

	while ((xlde = ReadDir(xldir, todir)) != NULL)
	{
		struct stat fst;

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

		snprintf(tofile, MAXPGPATH, "%s/%s", todir, xlde->d_name);

		/*
		 * We don't need to sync subdirectories here since the recursive
		 * copydir will do it before it returns
		 */
		if (lstat(tofile, &fst) < 0)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not stat file \"%s\": %m", tofile)));

		if (S_ISREG(fst.st_mode))
			fsync_fname(tofile, false);
	}
	FreeDir(xldir);

	/*
	 * It's important to fsync the destination directory itself as individual
	 * file fsyncs don't guarantee that the directory entry for the file is
	 * synced. Recent versions of ext4 have made the window much wider but
	 * it's been true for ext3 and other filesystems in the past.
	 */
	fsync_fname(todir, true);
}
Ejemplo n.º 9
0
/* Return:
 * -1 error, copy not made
 *  0 copy is made or user answered "no" in interactive mode
 *    (failures to preserve mode/owner/times are not reported in exit code)
 */
int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
{
	/* This is a recursive function, try to minimize stack usage */
	/* NB: each struct stat is ~100 bytes */
	struct stat source_stat;
	struct stat dest_stat;
	signed char retval = 0;
	signed char dest_exists = 0;
	signed char ovr;

/* Inverse of cp -d ("cp without -d") */
#define FLAGS_DEREF (flags & (FILEUTILS_DEREFERENCE + FILEUTILS_DEREFERENCE_L0))

	if ((FLAGS_DEREF ? stat : lstat)(source, &source_stat) < 0) {
		/* This may be a dangling symlink.
		 * Making [sym]links to dangling symlinks works, so... */
		if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK))
			goto make_links;
		bb_perror_msg("can't stat '%s'", source);
		return -1;
	}

	if (lstat(dest, &dest_stat) < 0) {
		if (errno != ENOENT) {
			bb_perror_msg("can't stat '%s'", dest);
			return -1;
		}
	} else {
		if (source_stat.st_dev == dest_stat.st_dev
		 && source_stat.st_ino == dest_stat.st_ino
		) {
			bb_error_msg("'%s' and '%s' are the same file", source, dest);
			return -1;
		}
		dest_exists = 1;
	}

#if ENABLE_SELINUX
	if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
		security_context_t con;
		if (lgetfilecon(source, &con) >= 0) {
			if (setfscreatecon(con) < 0) {
				bb_perror_msg("can't set setfscreatecon %s", con);
				freecon(con);
				return -1;
			}
		} else if (errno == ENOTSUP || errno == ENODATA) {
			setfscreatecon_or_die(NULL);
		} else {
			bb_perror_msg("can't lgetfilecon %s", source);
			return -1;
		}
	}
#endif

	if (S_ISDIR(source_stat.st_mode)) {
		DIR *dp;
		const char *tp;
		struct dirent *d;
		mode_t saved_umask = 0;

		if (!(flags & FILEUTILS_RECUR)) {
			bb_error_msg("omitting directory '%s'", source);
			return -1;
		}

		/* Did we ever create source ourself before? */
		tp = is_in_ino_dev_hashtable(&source_stat);
		if (tp) {
			/* We did! it's a recursion! man the lifeboats... */
			bb_error_msg("recursion detected, omitting directory '%s'",
					source);
			return -1;
		}

		/* Create DEST */
		if (dest_exists) {
			if (!S_ISDIR(dest_stat.st_mode)) {
				bb_error_msg("target '%s' is not a directory", dest);
				return -1;
			}
			/* race here: user can substitute a symlink between
			 * this check and actual creation of files inside dest */
		} else {
			mode_t mode;
			saved_umask = umask(0);

			mode = source_stat.st_mode;
			if (!(flags & FILEUTILS_PRESERVE_STATUS))
				mode = source_stat.st_mode & ~saved_umask;
			/* Allow owner to access new dir (at least for now) */
			mode |= S_IRWXU;
			if (mkdir(dest, mode) < 0) {
				umask(saved_umask);
				bb_perror_msg("can't create directory '%s'", dest);
				return -1;
			}
			umask(saved_umask);
			/* need stat info for add_to_ino_dev_hashtable */
			if (lstat(dest, &dest_stat) < 0) {
				bb_perror_msg("can't stat '%s'", dest);
				return -1;
			}
		}
		/* remember (dev,inode) of each created dir.
		 * NULL: name is not remembered */
		add_to_ino_dev_hashtable(&dest_stat, NULL);

		/* Recursively copy files in SOURCE */
		dp = opendir(source);
		if (dp == NULL) {
			retval = -1;
			goto preserve_mode_ugid_time;
		}

		while ((d = readdir(dp)) != NULL) {
			char *new_source, *new_dest;

			new_source = concat_subpath_file(source, d->d_name);
			if (new_source == NULL)
				continue;
			new_dest = concat_path_file(dest, d->d_name);
			if (copy_file(new_source, new_dest, flags & ~FILEUTILS_DEREFERENCE_L0) < 0)
				retval = -1;
			free(new_source);
			free(new_dest);
		}
		closedir(dp);

		if (!dest_exists
		 && chmod(dest, source_stat.st_mode & ~saved_umask) < 0
		) {
			bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
			/* retval = -1; - WRONG! copy *WAS* made */
		}
		goto preserve_mode_ugid_time;
	}

	if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) {
		int (*lf)(const char *oldpath, const char *newpath);
 make_links:
		/* Hmm... maybe
		 * if (DEREF && MAKE_SOFTLINK) source = realpath(source) ?
		 * (but realpath returns NULL on dangling symlinks...) */
		lf = (flags & FILEUTILS_MAKE_SOFTLINK) ? symlink : link;
		if (lf(source, dest) < 0) {
			ovr = ask_and_unlink(dest, flags);
			if (ovr <= 0)
				return ovr;
			if (lf(source, dest) < 0) {
				bb_perror_msg("can't create link '%s'", dest);
				return -1;
			}
		}
		/* _Not_ jumping to preserve_mode_ugid_time:
		 * (sym)links don't have those */
		return 0;
	}

	if (/* "cp thing1 thing2" without -R: just open and read() from thing1 */
	    !(flags & FILEUTILS_RECUR)
	    /* "cp [-opts] regular_file thing2" */
	 || S_ISREG(source_stat.st_mode)
	 /* DEREF uses stat, which never returns S_ISLNK() == true.
	  * So the below is never true: */
	 /* || (FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) */
	) {
		int src_fd;
		int dst_fd;
		mode_t new_mode;

		if (!FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) {
			/* "cp -d symlink dst": create a link */
			goto dont_cat;
		}

		if (ENABLE_FEATURE_PRESERVE_HARDLINKS && !FLAGS_DEREF) {
			const char *link_target;
			link_target = is_in_ino_dev_hashtable(&source_stat);
			if (link_target) {
				if (link(link_target, dest) < 0) {
					ovr = ask_and_unlink(dest, flags);
					if (ovr <= 0)
						return ovr;
					if (link(link_target, dest) < 0) {
						bb_perror_msg("can't create link '%s'", dest);
						return -1;
					}
				}
				return 0;
			}
			add_to_ino_dev_hashtable(&source_stat, dest);
		}

		src_fd = open_or_warn(source, O_RDONLY);
		if (src_fd < 0)
			return -1;

		/* Do not try to open with weird mode fields */
		new_mode = source_stat.st_mode;
		if (!S_ISREG(source_stat.st_mode))
			new_mode = 0666;

		// POSIX way is a security problem versus (sym)link attacks
		if (!ENABLE_FEATURE_NON_POSIX_CP) {
			dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
		} else { /* safe way: */
			dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
		}
		if (dst_fd == -1) {
			ovr = ask_and_unlink(dest, flags);
			if (ovr <= 0) {
				close(src_fd);
				return ovr;
			}
			/* It shouldn't exist. If it exists, do not open (symlink attack?) */
			dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
			if (dst_fd < 0) {
				close(src_fd);
				return -1;
			}
		}

#if ENABLE_SELINUX
		if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
		 && is_selinux_enabled() > 0
		) {
			security_context_t con;
			if (getfscreatecon(&con) == -1) {
				bb_perror_msg("getfscreatecon");
				return -1;
			}
			if (con) {
				if (setfilecon(dest, con) == -1) {
					bb_perror_msg("setfilecon:%s,%s", dest, con);
					freecon(con);
					return -1;
				}
				freecon(con);
			}
		}
#endif
		if (bb_copyfd_eof(src_fd, dst_fd) == -1)
			retval = -1;
		/* Ok, writing side I can understand... */
		if (close(dst_fd) < 0) {
			bb_perror_msg("can't close '%s'", dest);
			retval = -1;
		}
		/* ...but read size is already checked by bb_copyfd_eof */
		close(src_fd);
		/* "cp /dev/something new_file" should not
		 * copy mode of /dev/something */
		if (!S_ISREG(source_stat.st_mode))
			return retval;
		goto preserve_mode_ugid_time;
	}
 dont_cat:

	/* Source is a symlink or a special file */
	/* We are lazy here, a bit lax with races... */
	if (dest_exists) {
		errno = EEXIST;
		ovr = ask_and_unlink(dest, flags);
		if (ovr <= 0)
			return ovr;
	}
	if (S_ISLNK(source_stat.st_mode)) {
		char *lpath = xmalloc_readlink_or_warn(source);
		if (lpath) {
			int r = symlink(lpath, dest);
			free(lpath);
			if (r < 0) {
				bb_perror_msg("can't create symlink '%s'", dest);
				return -1;
			}
			if (flags & FILEUTILS_PRESERVE_STATUS)
				if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
					bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
		}
		/* _Not_ jumping to preserve_mode_ugid_time:
		 * symlinks don't have those */
		return 0;
	}
	if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
	 || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
	) {
		if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
			bb_perror_msg("can't create '%s'", dest);
			return -1;
		}
	} else {
		bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
		return -1;
	}

 preserve_mode_ugid_time:

	if (flags & FILEUTILS_PRESERVE_STATUS
	/* Cannot happen: */
	/* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
	) {
		struct timeval times[2];

		times[1].tv_sec = times[0].tv_sec = source_stat.st_mtime;
		times[1].tv_usec = times[0].tv_usec = 0;
		/* BTW, utimes sets usec-precision time - just FYI */
		if (utimes(dest, times) < 0)
			bb_perror_msg("can't preserve %s of '%s'", "times", dest);
		if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
			source_stat.st_mode &= ~(S_ISUID | S_ISGID);
			bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
		}
		if (chmod(dest, source_stat.st_mode) < 0)
			bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
	}

	return retval;
}
Ejemplo n.º 10
0
int
main (int argc, char **argv)
{
	int ifd = -1;
	struct stat sbuf;
	unsigned char *ptr;
	int retval = 0;
	struct image_type_params *tparams = NULL;

	/* Init Kirkwood Boot image generation/list support */
	init_kwb_image_type ();
	/* Init Freescale imx Boot image generation/list support */
	init_imx_image_type ();
	/* Init FIT image generation/list support */
	init_fit_image_type ();
	/* Init Default image generation/list support */
	init_default_image_type ();

	params.cmdname = *argv;
	params.addr = params.ep = 0;

	while (--argc > 0 && **++argv == '-') {
		while (*++*argv) {
			switch (**argv) {
			case 'l':
				params.lflag = 1;
				break;
			case 'A':
				if ((--argc <= 0) ||
					(params.arch =
					genimg_get_arch_id (*++argv)) < 0)
					usage ();
				goto NXTARG;
			case 'C':
				if ((--argc <= 0) ||
					(params.comp =
					genimg_get_comp_id (*++argv)) < 0)
					usage ();
				goto NXTARG;
			case 'D':
				if (--argc <= 0)
					usage ();
				params.dtc = *++argv;
				goto NXTARG;

			case 'O':
				if ((--argc <= 0) ||
					(params.os =
					genimg_get_os_id (*++argv)) < 0)
					usage ();
				goto NXTARG;
			case 'T':
				if ((--argc <= 0) ||
					(params.type =
					genimg_get_type_id (*++argv)) < 0)
					usage ();
				goto NXTARG;

			case 'a':
				if (--argc <= 0)
					usage ();
				params.addr = strtoul (*++argv,
					(char **)&ptr, 16);
				if (*ptr) {
					fprintf (stderr,
						"%s: invalid load address %s\n",
						params.cmdname, *argv);
					exit (EXIT_FAILURE);
				}
				goto NXTARG;
			case 'd':
				if (--argc <= 0)
					usage ();
				params.datafile = *++argv;
				params.dflag = 1;
				goto NXTARG;
			case 'e':
				if (--argc <= 0)
					usage ();
				params.ep = strtoul (*++argv,
						(char **)&ptr, 16);
				if (*ptr) {
					fprintf (stderr,
						"%s: invalid entry point %s\n",
						params.cmdname, *argv);
					exit (EXIT_FAILURE);
				}
				params.eflag = 1;
				goto NXTARG;
			case 'f':
				if (--argc <= 0)
					usage ();
				/*
				 * The flattened image tree (FIT) format
				 * requires a flattened device tree image type
				 */
				params.type = IH_TYPE_FLATDT;
				params.datafile = *++argv;
				params.fflag = 1;
				goto NXTARG;
			case 'n':
				if (--argc <= 0)
					usage ();
				params.imagename = *++argv;
				goto NXTARG;
			case 'v':
				params.vflag++;
				break;
			case 'x':
				params.xflag++;
				break;
			default:
				usage ();
			}
		}
NXTARG:		;
	}

	if (argc != 1)
		usage ();

	/* set tparams as per input type_id */
	tparams = mkimage_get_type(params.type);
	if (tparams == NULL) {
		fprintf (stderr, "%s: unsupported type %s\n",
			params.cmdname, genimg_get_type_name(params.type));
		exit (EXIT_FAILURE);
	}

	/*
	 * check the passed arguments parameters meets the requirements
	 * as per image type to be generated/listed
	 */
	if (tparams->check_params)
		if (tparams->check_params (&params))
			usage ();

	if (!params.eflag) {
		params.ep = params.addr;
		/* If XIP, entry point must be after the U-Boot header */
		if (params.xflag)
			params.ep += tparams->header_size;
	}

	params.imagefile = *argv;

	if (params.fflag){
		if (tparams->fflag_handle)
			/*
			 * in some cases, some additional processing needs
			 * to be done if fflag is defined
			 *
			 * For ex. fit_handle_file for Fit file support
			 */
			retval = tparams->fflag_handle(&params);

		if (retval != EXIT_SUCCESS)
			exit (retval);
	}

	if (params.lflag || params.fflag) {
		ifd = open (params.imagefile, O_RDONLY|O_BINARY);
	} else {
		ifd = open (params.imagefile,
			O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0666);
	}

	if (ifd < 0) {
		fprintf (stderr, "%s: Can't open %s: %s\n",
			params.cmdname, params.imagefile,
			strerror(errno));
		exit (EXIT_FAILURE);
	}

	if (params.lflag || params.fflag) {
		/*
		 * list header information of existing image
		 */
		if (fstat(ifd, &sbuf) < 0) {
			fprintf (stderr, "%s: Can't stat %s: %s\n",
				params.cmdname, params.imagefile,
				strerror(errno));
			exit (EXIT_FAILURE);
		}

		if ((unsigned)sbuf.st_size < tparams->header_size) {
			fprintf (stderr,
				"%s: Bad size: \"%s\" is not valid image\n",
				params.cmdname, params.imagefile);
			exit (EXIT_FAILURE);
		}

		ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, ifd, 0);
		if (ptr == MAP_FAILED) {
			fprintf (stderr, "%s: Can't read %s: %s\n",
				params.cmdname, params.imagefile,
				strerror(errno));
			exit (EXIT_FAILURE);
		}

		/*
		 * scan through mkimage registry for all supported image types
		 * and verify the input image file header for match
		 * Print the image information for matched image type
		 * Returns the error code if not matched
		 */
		retval = mkimage_verify_print_header (ptr, &sbuf);

		(void) munmap((void *)ptr, sbuf.st_size);
		(void) close (ifd);

		exit (retval);
	}

	/*
	 * Must be -w then:
	 *
	 * write dummy header, to be fixed later
	 */
	memset (tparams->hdr, 0, tparams->header_size);

	if (write(ifd, tparams->hdr, tparams->header_size)
					!= tparams->header_size) {
		fprintf (stderr, "%s: Write error on %s: %s\n",
			params.cmdname, params.imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	if (params.type == IH_TYPE_MULTI || params.type == IH_TYPE_SCRIPT) {
		char *file = params.datafile;
		uint32_t size;

		for (;;) {
			char *sep = NULL;

			if (file) {
				if ((sep = strchr(file, ':')) != NULL) {
					*sep = '\0';
				}

				if (stat (file, &sbuf) < 0) {
					fprintf (stderr, "%s: Can't stat %s: %s\n",
						params.cmdname, file, strerror(errno));
					exit (EXIT_FAILURE);
				}
				size = cpu_to_uimage (sbuf.st_size);
			} else {
				size = 0;
			}

			if (write(ifd, (char *)&size, sizeof(size)) != sizeof(size)) {
				fprintf (stderr, "%s: Write error on %s: %s\n",
					params.cmdname, params.imagefile,
					strerror(errno));
				exit (EXIT_FAILURE);
			}

			if (!file) {
				break;
			}

			if (sep) {
				*sep = ':';
				file = sep + 1;
			} else {
				file = NULL;
			}
		}

		file = params.datafile;

		for (;;) {
			char *sep = strchr(file, ':');
			if (sep) {
				*sep = '\0';
				copy_file (ifd, file, 1);
				*sep++ = ':';
				file = sep;
			} else {
				copy_file (ifd, file, 0);
				break;
			}
		}
	} else {
		copy_file (ifd, params.datafile, 0);
	}

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && \
   !defined(__sun__) && \
   !defined(__FreeBSD__) && \
   !defined(__APPLE__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif

	if (fstat(ifd, &sbuf) < 0) {
		fprintf (stderr, "%s: Can't stat %s: %s\n",
			params.cmdname, params.imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	ptr = mmap(0, sbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, ifd, 0);
	if (ptr == MAP_FAILED) {
		fprintf (stderr, "%s: Can't map %s: %s\n",
			params.cmdname, params.imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	/* Setup the image header as per input image type*/
	if (tparams->set_header)
		tparams->set_header (ptr, &sbuf, ifd, &params);
	else {
		fprintf (stderr, "%s: Can't set header for %s: %s\n",
			params.cmdname, tparams->name, strerror(errno));
		exit (EXIT_FAILURE);
	}

	/* Print the image information by processing image header */
	if (tparams->print_header)
		tparams->print_header (ptr);
	else {
		fprintf (stderr, "%s: Can't print header for %s: %s\n",
			params.cmdname, tparams->name, strerror(errno));
		exit (EXIT_FAILURE);
	}

	(void) munmap((void *)ptr, sbuf.st_size);

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && \
   !defined(__sun__) && \
   !defined(__FreeBSD__) && \
   !defined(__APPLE__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif

	if (close(ifd)) {
		fprintf (stderr, "%s: Write error on %s: %s\n",
			params.cmdname, params.imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	exit (EXIT_SUCCESS);
}
Ejemplo n.º 11
0
int
main (int argc, char **argv)
{
	int ifd = -1;
	uint32_t checksum;
	uint32_t addr;
	uint32_t ep;
	struct stat sbuf;
	unsigned char *ptr;
	char *name = "";

	cmdname = *argv;

	addr = ep = 0;

	while (--argc > 0 && **++argv == '-') {
		while (*++*argv) {
			switch (**argv) {
			case 'l':
				lflag = 1;
				break;
			case 'A':
				if ((--argc <= 0) ||
				    (opt_arch = genimg_get_arch_id (*++argv)) < 0)
					usage ();
				goto NXTARG;
			case 'C':
				if ((--argc <= 0) ||
				    (opt_comp = genimg_get_comp_id (*++argv)) < 0)
					usage ();
				goto NXTARG;
			case 'D':
				if (--argc <= 0)
					usage ();
				opt_dtc = *++argv;
				goto NXTARG;

			case 'O':
				if ((--argc <= 0) ||
				    (opt_os = genimg_get_os_id (*++argv)) < 0)
					usage ();
				goto NXTARG;
			case 'T':
				if ((--argc <= 0) ||
				    (opt_type = genimg_get_type_id (*++argv)) < 0)
					usage ();
				goto NXTARG;

			case 'a':
				if (--argc <= 0)
					usage ();
				addr = strtoul (*++argv, (char **)&ptr, 16);
				if (*ptr) {
					fprintf (stderr,
						"%s: invalid load address %s\n",
						cmdname, *argv);
					exit (EXIT_FAILURE);
				}
				goto NXTARG;
			case 'd':
				if (--argc <= 0)
					usage ();
				datafile = *++argv;
				dflag = 1;
				goto NXTARG;
			case 'e':
				if (--argc <= 0)
					usage ();
				ep = strtoul (*++argv, (char **)&ptr, 16);
				if (*ptr) {
					fprintf (stderr,
						"%s: invalid entry point %s\n",
						cmdname, *argv);
					exit (EXIT_FAILURE);
				}
				eflag = 1;
				goto NXTARG;
			case 'f':
				if (--argc <= 0)
					usage ();
				datafile = *++argv;
				fflag = 1;
				goto NXTARG;
			case 'n':
				if (--argc <= 0)
					usage ();
				name = *++argv;
				goto NXTARG;
			case 'v':
				vflag++;
				break;
			case 'x':
				xflag++;
				break;
			default:
				usage ();
			}
		}
NXTARG:		;
	}

	if ((argc != 1) ||
		(dflag && (fflag || lflag)) ||
		(fflag && (dflag || lflag)) ||
		(lflag && (dflag || fflag)))
		usage();

	if (!eflag) {
		ep = addr;
		/* If XIP, entry point must be after the U-Boot header */
		if (xflag)
			ep += image_get_header_size ();
	}

	/*
	 * If XIP, ensure the entry point is equal to the load address plus
	 * the size of the U-Boot header.
	 */
	if (xflag) {
		if (ep != addr + image_get_header_size ()) {
			fprintf (stderr,
				"%s: For XIP, the entry point must be the load addr + %lu\n",
				cmdname,
				(unsigned long)image_get_header_size ());
			exit (EXIT_FAILURE);
		}
	}

	imagefile = *argv;

	if (!fflag){
		if (lflag) {
			ifd = open (imagefile, O_RDONLY|O_BINARY);
		} else {
			ifd = open (imagefile,
				O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0666);
		}

		if (ifd < 0) {
			fprintf (stderr, "%s: Can't open %s: %s\n",
				cmdname, imagefile, strerror(errno));
			exit (EXIT_FAILURE);
		}
	}

	if (lflag) {
		/*
		 * list header information of existing image
		 */
		if (fstat(ifd, &sbuf) < 0) {
			fprintf (stderr, "%s: Can't stat %s: %s\n",
				cmdname, imagefile, strerror(errno));
			exit (EXIT_FAILURE);
		}

		if ((unsigned)sbuf.st_size < image_get_header_size ()) {
			fprintf (stderr,
				"%s: Bad size: \"%s\" is no valid image\n",
				cmdname, imagefile);
			exit (EXIT_FAILURE);
		}

		ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, ifd, 0);
		if (ptr == MAP_FAILED) {
			fprintf (stderr, "%s: Can't read %s: %s\n",
				cmdname, imagefile, strerror(errno));
			exit (EXIT_FAILURE);
		}

		if (fdt_check_header (ptr)) {
			/* old-style image */
			image_verify_header ((char *)ptr, sbuf.st_size);
			image_print_contents ((image_header_t *)ptr);
		} else {
			/* FIT image */
			fit_print_contents (ptr);
		}

		(void) munmap((void *)ptr, sbuf.st_size);
		(void) close (ifd);

		exit (EXIT_SUCCESS);
	} else if (fflag) {
		/* Flattened Image Tree (FIT) format  handling */
		debug ("FIT format handling\n");
		fit_handle_file ();
		exit (EXIT_SUCCESS);
	}

	/*
	 * Must be -w then:
	 *
	 * write dummy header, to be fixed later
	 */
	memset (hdr, 0, image_get_header_size ());

	if (write(ifd, hdr, image_get_header_size ()) != image_get_header_size ()) {
		fprintf (stderr, "%s: Write error on %s: %s\n",
			cmdname, imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	if (opt_type == IH_TYPE_MULTI || opt_type == IH_TYPE_SCRIPT) {
		char *file = datafile;
		uint32_t size;

		for (;;) {
			char *sep = NULL;

			if (file) {
				if ((sep = strchr(file, ':')) != NULL) {
					*sep = '\0';
				}

				if (stat (file, &sbuf) < 0) {
					fprintf (stderr, "%s: Can't stat %s: %s\n",
						cmdname, file, strerror(errno));
					exit (EXIT_FAILURE);
				}
				size = cpu_to_uimage (sbuf.st_size);
			} else {
				size = 0;
			}

			if (write(ifd, (char *)&size, sizeof(size)) != sizeof(size)) {
				fprintf (stderr, "%s: Write error on %s: %s\n",
					cmdname, imagefile, strerror(errno));
				exit (EXIT_FAILURE);
			}

			if (!file) {
				break;
			}

			if (sep) {
				*sep = ':';
				file = sep + 1;
			} else {
				file = NULL;
			}
		}

		file = datafile;

		for (;;) {
			char *sep = strchr(file, ':');
			if (sep) {
				*sep = '\0';
				copy_file (ifd, file, 1);
				*sep++ = ':';
				file = sep;
			} else {
				copy_file (ifd, file, 0);
				break;
			}
		}
	} else {
		copy_file (ifd, datafile, 0);
	}

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__) && !defined(__APPLE__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif

	if (fstat(ifd, &sbuf) < 0) {
		fprintf (stderr, "%s: Can't stat %s: %s\n",
			cmdname, imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	ptr = mmap(0, sbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, ifd, 0);
	if (ptr == MAP_FAILED) {
		fprintf (stderr, "%s: Can't map %s: %s\n",
			cmdname, imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	hdr = (image_header_t *)ptr;

	checksum = crc32 (0,
			  (const char *)(ptr + image_get_header_size ()),
			  sbuf.st_size - image_get_header_size ()
			 );

	/* Build new header */
	image_set_magic (hdr, IH_MAGIC);
	image_set_time (hdr, sbuf.st_mtime);
	image_set_size (hdr, sbuf.st_size - image_get_header_size ());
	image_set_load (hdr, addr);
	image_set_ep (hdr, ep);
	image_set_dcrc (hdr, checksum);
	image_set_os (hdr, opt_os);
	image_set_arch (hdr, opt_arch);
	image_set_type (hdr, opt_type);
	image_set_comp (hdr, opt_comp);

	image_set_name (hdr, name);

	checksum = crc32 (0, (const char *)hdr, image_get_header_size ());

	image_set_hcrc (hdr, checksum);

	image_print_contents (hdr);

	(void) munmap((void *)ptr, sbuf.st_size);

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__) && !defined(__APPLE__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif

	if (close(ifd)) {
		fprintf (stderr, "%s: Write error on %s: %s\n",
			cmdname, imagefile, strerror(errno));
		exit (EXIT_FAILURE);
	}

	exit (EXIT_SUCCESS);
}
Ejemplo n.º 12
0
int main()
{

	pspDebugScreenInit();
	
	pspDebugScreenSetBackColor(0xFF0000);
	pspDebugScreenSetTextColor(0x00FFFF);
	pspDebugScreenClear();

	printf("Recovery Mode by Dark_Alex, in-eboot by BlackSith\n\n\n\n");
	printf("Press start to activate USB Mass.\n");
	printf("Press triangle to flash ms0:/index.dat to flash0.\n");
	printf("Press cross to start the program under ms0:/PSP/GAME/UPDATE/EBOOT.PBP\n");
	printf("Press home to exit.\n\n\n\n");

	sceIoUnassign("flash0:");
	sceIoAssign("flash0:", "lflash0:0,0", "flashfat0:", IOASSIGN_RDWR, NULL, 0);

	while (1)
	{
		SceCtrlData pad;

		int keyprocessed = 0;

		sceCtrlReadBufferPositive(&pad, 1);

		if (pad.Buttons & PSP_CTRL_START)
		{
			start_usb();
			printf("Usb started.\n");
			keyprocessed = 1;
		}
		else if (pad.Buttons & PSP_CTRL_TRIANGLE)
		{
			if (copy_file("ms0:/index.dat", "flash0:/vsh/etc/index.dat") < 0)
				printf("Cannot copy file. (file missing?).\n");
			else
				printf("File copied succesfully.\n");

			keyprocessed = 1;
		}
		else if (pad.Buttons & PSP_CTRL_CROSS)
		{
			struct SceKernelLoadExecParam param;

			memset(&param, 0, sizeof(param));

			param.size = sizeof(param);
			param.args = strlen(PROGRAM)+1;
			param.argp = PROGRAM;
			param.key = "updater";

			printf("Starting program...\n");
			sceKernelLoadExec(PROGRAM, &param);

			keyprocessed = 1;
		}
		else if (pad.Buttons & PSP_CTRL_HOME)
		{
			break;
		}

		sceKernelDelayThread((keyprocessed) ? 200000 : 50000);
	}

	sceKernelExitGame();

	return 0;
}
Ejemplo n.º 13
0
void 
check_syntax_source( const char *source_dir, SyntaxDef *syntax, Bool module )
{
	int i ;
	char *syntax_dir = NULL ;
	char *obsolete_dir ;
	struct direntry  **list = NULL;
	int list_len ;

	if( syntax )
	{	
		if( get_hash_item( ProcessedSyntaxes, AS_HASHABLE(syntax), NULL ) == ASH_Success )
			return ;

		if( syntax->doc_path != NULL && syntax->doc_path[0] != '\0' )
			syntax_dir = make_file_name (source_dir, syntax->doc_path); 
	}
	if( syntax_dir == NULL ) 
		syntax_dir = mystrdup( source_dir );
	
	obsolete_dir = make_file_name (syntax_dir, "obsolete" );
	
	if( CheckDir(syntax_dir) != 0 )
		if( !make_doc_dir( syntax_dir ) ) 
		{
			free( syntax_dir );
			return;
		}

	if( syntax ) 
	{	
		add_hash_item( ProcessedSyntaxes, AS_HASHABLE(syntax), NULL );   

		/* pass one: lets see which of the existing files have no related options : */
		list_len = my_scandir ((char*)syntax_dir, &list, ignore_dots, NULL);
		for (i = 0; i < list_len; i++)
		{	
			int k ;
			if (!S_ISDIR (list[i]->d_mode))
			{	
				char *name = list[i]->d_name ;
				show_progress( "checking \"%s\" ... ", name );
				if( name[0] != '_' ) 
				{	
					for (k = 0; syntax->terms[k].keyword; k++)
						if( mystrcasecmp(name, syntax->terms[k].keyword ) == 0 ) 
							break;
					if( syntax->terms[k].keyword == NULL || get_flags( syntax->terms[k].flags, TF_OBSOLETE) ) 
					{
						/* obsolete option - move it away */
						char *obsolete_fname = make_file_name (obsolete_dir, name );
						char *fname = make_file_name (syntax_dir, name );
						Bool no_dir = False ;
						if( CheckDir(obsolete_dir) != 0 )
							no_dir = !make_doc_dir( obsolete_dir ) ;
						if( !no_dir )
						{
							copy_file (fname, obsolete_fname);
							show_progress( "Option \"%s\" is obsolete - moving away!", name );
							unlink(fname);
						}
						free( fname );
						free( obsolete_fname ); 
					}	 
				}
			}		
			free( list[i] );
		}
		if( list )
			free (list);
		/* pass two: lets see which options are missing : */
		for (i = 0; syntax->terms[i].keyword; i++)
		{	
			if( !get_flags( syntax->terms[i].flags, TF_OBSOLETE) )
			{	
				SyntaxDef *sub_syntax = syntax->terms[i].sub_syntax ; 
				if( sub_syntax == pPopupFuncSyntax ) 
					sub_syntax = pFuncSyntax ;
				if (sub_syntax)
					check_syntax_source( source_dir, sub_syntax, False );
				if( isalnum( syntax->terms[i].keyword[0] ) )					
					check_option_source( syntax_dir, syntax->terms[i].keyword, sub_syntax, module?syntax->doc_path:NULL ) ;
			}
		}
		for (i = module?0:1; StandardSourceEntries[i] != NULL ; ++i)
			check_option_source( syntax_dir, StandardSourceEntries[i], NULL, module?syntax->doc_path:NULL ) ;
		if( module ) 
		{
			check_option_source( syntax_dir, BaseOptionsEntry, NULL, syntax->doc_path ) ;
			check_option_source( syntax_dir, MyStylesOptionsEntry, NULL, syntax->doc_path ) ;
		}	 
	}else
		generate_main_source( syntax_dir );

	free( obsolete_dir );
	free( syntax_dir );
}	 
Ejemplo n.º 14
0
int main(int argc, char **argv)
{
	int encrypt_opt = 0;
	int decrypt_opt = 0;
	int input_opt = 0;
	int output_opt = 0;
	char *input_filename = NULL;
	char *output_filename = NULL;
 
	int input_fd;
	int output_fd;
	off_t file_len;
	char *p;
	char buf[sizeof(image_header_t) + 3];
	image_header_t *header;
 
	while (1) {
		static struct option long_options[] = {
			{"encrypt", no_argument,       0, 'e'},
			{"decrypt", no_argument,       0, 'd'},
			{"input",   required_argument, 0, 'i'},
			{"output",  required_argument, 0, 'o'},
			{0,         0,                 0, 0  }
		};
		int option_index = 0;
		int c = getopt_long(argc, argv, "dei:o:",
		                long_options, &option_index);
		if (c == -1)
			break;
 
		switch (c) {
		case 'd':
			decrypt_opt++;
			if (decrypt_opt > 1) {
				fprintf(stderr, "%s: decrypt may only be specified once\n",
				        argv[0]);
				show_usage(argv[0]);
			}
			break;
 
		case 'e':
			encrypt_opt++;
			if (encrypt_opt > 1) {
				fprintf(stderr, "%s: encrypt may only be specified once\n",
				        argv[0]);
				show_usage(argv[0]);
			}
			break;
 
		case 'i':
			input_opt++;
			if (input_opt > 1) {
				fprintf(stderr, "%s: only one input file may be specified\n",
				        argv[0]);
				show_usage(argv[0]);
			}
			if (strcmp("-", optarg) != 0) {
				input_filename = optarg;
			}
			break;
 
		case 'o':
			output_opt++;
			if (output_opt > 1) {
				fprintf(stderr, "%s: only one output file may be specified\n",
				        argv[0]);
				show_usage(argv[0]);
			}
			if (strcmp("-", optarg) != 0) {
				output_filename = optarg;
			}
			break;
 
		case '?':
			exit(-1);
 
		default:
			abort();
		}
	}
 
	if (decrypt_opt && encrypt_opt) {
		fprintf(stderr, "%s: decrypt and encrypt may not be used together\n",
		        argv[0]);
		show_usage(argv[0]);
	}
 
	if (!decrypt_opt && !encrypt_opt) {
		fprintf(stderr, "%s: neither decrypt or encrypt were specified\n",
		        argv[0]);
		show_usage(argv[0]);
	}
 
	temp_fd = fileno(tmpfile());
	if (temp_fd < 0) {
		fprintf(stderr, "Can't create temporary file\n");
		exit(EXIT_FAILURE);
	}
 
	atexit(exit_cleanup);
	DES_set_key_unchecked((const_DES_cblock *)DES_KEY, &schedule);
 
	if (input_filename) {
		input_fd = open(input_filename, O_RDONLY);
		if (input_fd < 0) {
			fprintf(stderr, "Can't open %s for reading: %s\n", input_filename,
			        strerror(errno));
			exit(EXIT_FAILURE);
		}
		copy_file(input_fd, temp_fd);
		close(input_fd);
	}
	else {
		copy_file(STDIN_FILENO, temp_fd);
	}
 
	file_len = lseek(temp_fd, 0, SEEK_CUR);
	if (file_len < 64) {
		fprintf(stderr, "Not enough data\n");
		exit(EXIT_FAILURE);
	}
 
	p = mmap(0, file_len, PROT_READ|PROT_WRITE, MAP_SHARED, temp_fd, 0);
	if (p == MAP_FAILED) {
		fprintf(stderr, "mmap failed: %s\n", strerror(errno));
		exit(EXIT_FAILURE);
	}	
 
	if (encrypt_opt) {
		header = (image_header_t *)p;
		off_t len = min(file_len,
		                ntohl(header->ih_size) + sizeof(image_header_t));
		if (ntohl(header->ih_magic) != IH_MAGIC) {
			fprintf(stderr, "Header magic incorrect: "
			        "expected 0x%08X, got 0x%08X\n",
			        IH_MAGIC, ntohl(header->ih_magic));
			munmap(p, file_len);
			exit(EXIT_FAILURE);
		}
		do_encrypt(p, len);
		munmap(p, file_len);
		if (len != file_len) {
			if (ftruncate(temp_fd, len) < 0) {
				fprintf(stderr, "ftruncate failed: %s\n", strerror(errno));
				exit(EXIT_FAILURE);
			}
		}		
	}
 
	if (decrypt_opt) {
		off_t header_len = min(file_len, sizeof(image_header_t) + 3);
		memcpy(buf, p, header_len);
		do_decrypt(buf, header_len);
		header = (image_header_t *)buf;
		if (ntohl(header->ih_magic) != IH_MAGIC) {
			fprintf(stderr, "Header magic incorrect: "
			        "expected 0x%08X, got 0x%08X\n",
			        IH_MAGIC, ntohl(header->ih_magic));
			exit(EXIT_FAILURE);
		}
		do_decrypt(p, file_len);
		munmap(p, file_len);
	}
 
	lseek(temp_fd, 0, SEEK_SET);
	if (output_filename) {
		output_fd = creat(output_filename, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
		if (output_fd < 0) {
			fprintf(stderr, "Can't open %s for writing: %s\n",
			        output_filename, strerror(errno));
			exit(EXIT_FAILURE);
		}
		copy_file(temp_fd, output_fd);
		close(output_fd);
	}
	else {
		copy_file(temp_fd, STDOUT_FILENO);
	}
 
	exit(EXIT_SUCCESS);
	return 0;
}
Ejemplo n.º 15
0
int check_infofile(
    char        *infodir,
    disklist_t  *dl,
    char       **errmsg)
{
    disk_t      *dp, *diskp;
    char        *hostinfodir, *old_hostinfodir, *Xhostinfodir;
    char        *diskdir,     *old_diskdir,     *Xdiskdir;
    char        *infofile,    *old_infofile,    *Xinfofile;
    struct stat  statbuf;
    int other_dle_match;

    if (stat(infodir, &statbuf) != 0) {
	return 0;
    }

    for (dp = dl->head; dp != NULL; dp = dp->next) {
	hostinfodir = sanitise_filename(dp->host->hostname);
	diskdir     = sanitise_filename(dp->name);
	infofile = vstralloc(infodir, "/", hostinfodir, "/", diskdir,
			     "/info", NULL);
	if (stat(infofile, &statbuf) == -1 && errno == ENOENT) {
	    old_hostinfodir = old_sanitise_filename(dp->host->hostname);
	    old_diskdir     = old_sanitise_filename(dp->name);
	    old_infofile    = vstralloc(infodir, old_hostinfodir, "/",
					old_diskdir, "/info", NULL);
	    if (stat(old_infofile, &statbuf) == 0) {
		other_dle_match = 0;
		diskp = dl->head;
		while (diskp != NULL) {
		    Xhostinfodir = sanitise_filename(diskp->host->hostname);
		    Xdiskdir     = sanitise_filename(diskp->name);
		    Xinfofile = vstralloc(infodir, "/", Xhostinfodir, "/",
					  Xdiskdir, "/info", NULL);
		    if (strcmp(old_infofile, Xinfofile) == 0) {
			other_dle_match = 1;
			diskp = NULL;
		    }
		    else {
			diskp = diskp->next;
		    }
		}
		if (other_dle_match == 0) {
		    if(mkpdir(infofile, (mode_t)0755, (uid_t)-1,
			      (gid_t)-1) == -1) {
			*errmsg = vstralloc("Can't create directory for ",
					    infofile, NULL);
			return -1;
		    }
		    if(copy_file(infofile, old_infofile, errmsg) == -1) 
			return -1;
		}
	    }
	    amfree(old_hostinfodir);
	    amfree(old_diskdir);
	    amfree(old_infofile);
	}
	amfree(diskdir);
	amfree(hostinfodir);
	amfree(infofile);
    }
    return 0;
}
Ejemplo n.º 16
0
int install_main(int argc, char **argv)
{
	struct stat statbuf;
	mode_t mode;
	uid_t uid;
	gid_t gid;
	char *arg, *last;
	const char *gid_str;
	const char *uid_str;
	const char *mode_str;
	int copy_flags = FILEUTILS_DEREFERENCE | FILEUTILS_FORCE;
	int opts;
	int min_args = 1;
	int ret = EXIT_SUCCESS;
	int isdir = 0;
#if ENABLE_SELINUX
	security_context_t scontext;
	bool use_default_selinux_context = 1;
#endif
	enum {
		OPT_c             = 1 << 0,
		OPT_v             = 1 << 1,
		OPT_b             = 1 << 2,
		OPT_MKDIR_LEADING = 1 << 3,
		OPT_DIRECTORY     = 1 << 4,
		OPT_PRESERVE_TIME = 1 << 5,
		OPT_STRIP         = 1 << 6,
		OPT_GROUP         = 1 << 7,
		OPT_MODE          = 1 << 8,
		OPT_OWNER         = 1 << 9,
#if ENABLE_SELINUX
		OPT_SET_SECURITY_CONTEXT = 1 << 10,
		OPT_PRESERVE_SECURITY_CONTEXT = 1 << 11,
#endif
	};

#if ENABLE_FEATURE_INSTALL_LONG_OPTIONS
	applet_long_options = install_longopts;
#endif
	opt_complementary = "s--d:d--s" IF_FEATURE_INSTALL_LONG_OPTIONS(IF_SELINUX(":Z--\xff:\xff--Z"));
	/* -c exists for backwards compatibility, it's needed */
	/* -v is ignored ("print name of each created directory") */
	/* -b is ignored ("make a backup of each existing destination file") */
	opts = getopt32(argv, "cvb" "Ddpsg:m:o:" IF_SELINUX("Z:"),
			&gid_str, &mode_str, &uid_str IF_SELINUX(, &scontext));
	argc -= optind;
	argv += optind;

#if ENABLE_SELINUX
	if (opts & (OPT_PRESERVE_SECURITY_CONTEXT|OPT_SET_SECURITY_CONTEXT)) {
		selinux_or_die();
		use_default_selinux_context = 0;
		if (opts & OPT_PRESERVE_SECURITY_CONTEXT) {
			copy_flags |= FILEUTILS_PRESERVE_SECURITY_CONTEXT;
		}
		if (opts & OPT_SET_SECURITY_CONTEXT) {
			setfscreatecon_or_die(scontext);
			copy_flags |= FILEUTILS_SET_SECURITY_CONTEXT;
		}
	}
#endif

	/* preserve access and modification time, this is GNU behaviour,
	 * BSD only preserves modification time */
	if (opts & OPT_PRESERVE_TIME) {
		copy_flags |= FILEUTILS_PRESERVE_STATUS;
	}
	mode = 0755; /* GNU coreutils 6.10 compat */
	if (opts & OPT_MODE)
		bb_parse_mode(mode_str, &mode);
	uid = (opts & OPT_OWNER) ? get_ug_id(uid_str, xuname2uid) : getuid();
	gid = (opts & OPT_GROUP) ? get_ug_id(gid_str, xgroup2gid) : getgid();

	last = argv[argc - 1];
	if (!(opts & OPT_DIRECTORY)) {
		argv[argc - 1] = NULL;
		min_args++;

		/* coreutils install resolves link in this case, don't use lstat */
		isdir = stat(last, &statbuf) < 0 ? 0 : S_ISDIR(statbuf.st_mode);
	}

	if (argc < min_args)
		bb_show_usage();

	while ((arg = *argv++) != NULL) {
		char *dest = last;
		if (opts & OPT_DIRECTORY) {
			dest = arg;
			/* GNU coreutils 6.9 does not set uid:gid
			 * on intermediate created directories
			 * (only on last one) */
			if (bb_make_directory(dest, 0755, FILEUTILS_RECUR)) {
				ret = EXIT_FAILURE;
				goto next;
			}
		} else {
			if (opts & OPT_MKDIR_LEADING) {
				char *ddir = xstrdup(dest);
				bb_make_directory(dirname(ddir), 0755, FILEUTILS_RECUR);
				/* errors are not checked. copy_file
				 * will fail if dir is not created. */
				free(ddir);
			}
			if (isdir)
				dest = concat_path_file(last, bb_basename(arg));
			if (copy_file(arg, dest, copy_flags) != 0) {
				/* copy is not made */
				ret = EXIT_FAILURE;
				goto next;
			}
			if (opts & OPT_STRIP) {
				char *args[4];
				args[0] = (char*)"strip";
				args[1] = (char*)"-p"; /* -p --preserve-dates */
				args[2] = dest;
				args[3] = NULL;
				if (spawn_and_wait(args)) {
					bb_perror_msg("strip");
					ret = EXIT_FAILURE;
				}
			}
		}

		/* Set the file mode (always, not only with -m).
		 * GNU coreutils 6.10 is not affected by umask. */
		if (chmod(dest, mode) == -1) {
			bb_perror_msg("can't change %s of %s", "permissions", dest);
			ret = EXIT_FAILURE;
		}
#if ENABLE_SELINUX
		if (use_default_selinux_context)
			setdefaultfilecon(dest);
#endif
		/* Set the user and group id */
		if ((opts & (OPT_OWNER|OPT_GROUP))
		 && lchown(dest, uid, gid) == -1
		) {
			bb_perror_msg("can't change %s of %s", "ownership", dest);
			ret = EXIT_FAILURE;
		}
 next:
		if (ENABLE_FEATURE_CLEAN_UP && isdir)
			free(dest);
	}

	return ret;
}
Ejemplo n.º 17
0
Archivo: file.c Proyecto: jrealm/TCW
int copy_file (const char * from, const char * to)
{
    char buf[128];
    int from_fd, to_fd;
    int num_read, num_written;
    char *write_ptr;
    extern svalue_t apply_ret_value;

    from = check_valid_path(from, current_object, "move_file", 0);
    assign_svalue(&from_sv, &apply_ret_value);

    to = check_valid_path(to, current_object, "move_file", 1);
    assign_svalue(&to_sv, &apply_ret_value);

    if (from == 0)
        return -1;
    if (to == 0)
        return -2;

    if (lstat(from, &from_stats) != 0) {
        error("/%s: lstat failed\n", from);
        return 1;
    }
    if (lstat(to, &to_stats) == 0) {
#ifdef WIN32
        if (!strcmp(from, to))
#else
        if (from_stats.st_dev == to_stats.st_dev
            && from_stats.st_ino == to_stats.st_ino)
#endif
        {
            error("`/%s' and `/%s' are the same file", from, to);
            return 1;
        }
    } else if (errno != ENOENT) {
        error("/%s: unknown error\n", to);
        return 1;
    }

    from_fd = open(from, OPEN_READ);
    if (from_fd < 0)
        return -1;

    if (file_size(to) == -2) {
        /* Target is a directory; build full target filename. */
        const char *cp;
        char newto[MAX_FNAME_SIZE + MAX_PATH_LEN + 2];

        cp = strrchr(from, '/');
        if (cp)
            cp++;
        else
            cp = from;

        sprintf(newto, "%s/%s", to, cp);
        close(from_fd);
        return copy_file(from, newto);
    }
    to_fd = open(to, OPEN_WRITE | O_CREAT | O_TRUNC, 0666);
    if (to_fd < 0) {
        close(from_fd);
        return -2;
    }
    while ((num_read = read(from_fd, buf, 128)) != 0) {
        if (num_read < 0) {
            debug_perror("copy_file: read", from);
            close(from_fd);
            close(to_fd);
            return -3;
        }
        write_ptr = buf;
        while (write_ptr != (buf + num_read)) {
            num_written = write(to_fd, write_ptr, num_read);
            if (num_written < 0) {
                debug_perror("copy_file: write", to);
                close(from_fd);
                close(to_fd);
                return -3;
            }
            write_ptr += num_written;
        }
    }
    close(from_fd);
    close(to_fd);
    return 1;
}
Ejemplo n.º 18
0
static HRESULT WINAPI IAssemblyCacheImpl_InstallAssembly(IAssemblyCache *iface,
                                                         DWORD dwFlags,
                                                         LPCWSTR pszManifestFilePath,
                                                         LPCFUSION_INSTALL_REFERENCE pRefData)
{
    static const WCHAR format[] =
        {'%','s','\\','%','s','\\','%','s','_','_','%','s','\\',0};
    static const WCHAR format_v40[] =
        {'%','s','\\','%','s','\\','v','4','.','0','_','%','s','_','_','%','s','\\',0};
    static const WCHAR ext_exe[] = {'.','e','x','e',0};
    static const WCHAR ext_dll[] = {'.','d','l','l',0};
    IAssemblyCacheImpl *cache = impl_from_IAssemblyCache(iface);
    ASSEMBLY *assembly;
    const WCHAR *extension, *filename, *src_dir;
    WCHAR *name = NULL, *token = NULL, *version = NULL, *asmpath = NULL;
    WCHAR asmdir[MAX_PATH], *p, **external_files = NULL, *dst_dir = NULL;
    PEKIND architecture;
    char *clr_version;
    DWORD i, count = 0, src_len, dst_len = sizeof(format_v40)/sizeof(format_v40[0]);
    HRESULT hr;

    TRACE("(%p, %d, %s, %p)\n", iface, dwFlags,
          debugstr_w(pszManifestFilePath), pRefData);

    if (!pszManifestFilePath || !*pszManifestFilePath)
        return E_INVALIDARG;

    if (!(extension = strrchrW(pszManifestFilePath, '.')))
        return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);

    if (lstrcmpiW(extension, ext_exe) && lstrcmpiW(extension, ext_dll))
        return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);

    if (GetFileAttributesW(pszManifestFilePath) == INVALID_FILE_ATTRIBUTES)
        return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);

    hr = assembly_create(&assembly, pszManifestFilePath);
    if (FAILED(hr))
    {
        hr = COR_E_ASSEMBLYEXPECTED;
        goto done;
    }

    hr = assembly_get_name(assembly, &name);
    if (FAILED(hr))
        goto done;

    hr = assembly_get_pubkey_token(assembly, &token);
    if (FAILED(hr))
        goto done;

    hr = assembly_get_version(assembly, &version);
    if (FAILED(hr))
        goto done;

    hr = assembly_get_runtime_version(assembly, &clr_version);
    if (FAILED(hr))
        goto done;

    hr = assembly_get_external_files(assembly, &external_files, &count);
    if (FAILED(hr))
        goto done;

    cache_lock( cache );

    architecture = assembly_get_architecture(assembly);
    get_assembly_directory(asmdir, MAX_PATH, clr_version, architecture);

    dst_len += strlenW(asmdir) + strlenW(name) + strlenW(version) + strlenW(token);
    if (!(dst_dir = HeapAlloc(GetProcessHeap(), 0, dst_len * sizeof(WCHAR))))
    {
        hr = E_OUTOFMEMORY;
        goto done;
    }
    if (!strcmp(clr_version, "v4.0.30319"))
        dst_len = sprintfW(dst_dir, format_v40, asmdir, name, version, token);
    else
        dst_len = sprintfW(dst_dir, format, asmdir, name, version, token);

    create_full_path(dst_dir);

    hr = assembly_get_path(assembly, &asmpath);
    if (FAILED(hr))
        goto done;

    if ((p = strrchrW(asmpath, '\\')))
    {
        filename = p + 1;
        src_dir  = asmpath;
        src_len  = filename - asmpath;
    }
    else
    {
        filename = asmpath;
        src_dir  = NULL;
        src_len  = 0;
    }
    hr = copy_file(src_dir, src_len, dst_dir, dst_len, filename);
    if (FAILED(hr))
        goto done;

    for (i = 0; i < count; i++)
    {
        hr = copy_file(src_dir, src_len, dst_dir, dst_len, external_files[i]);
        if (FAILED(hr))
            break;
    }

done:
    HeapFree(GetProcessHeap(), 0, name);
    HeapFree(GetProcessHeap(), 0, token);
    HeapFree(GetProcessHeap(), 0, version);
    HeapFree(GetProcessHeap(), 0, asmpath);
    HeapFree(GetProcessHeap(), 0, dst_dir);
    for (i = 0; i < count; i++) HeapFree(GetProcessHeap(), 0, external_files[i]);
    HeapFree(GetProcessHeap(), 0, external_files);
    assembly_release(assembly);
    cache_unlock( cache );
    return hr;
}
Ejemplo n.º 19
0
int copy_file(const char *source, const char *dest, int flags)
{
	struct stat source_stat;
	struct stat dest_stat;
	int dest_exists = 0;
	int status = 0;

	if ((!(flags & FILEUTILS_DEREFERENCE) &&
			lstat(source, &source_stat) < 0) ||
			((flags & FILEUTILS_DEREFERENCE) &&
			 stat(source, &source_stat) < 0)) {
		bb_perror_msg("%s", source);
		return -1;
	}

	if (lstat(dest, &dest_stat) < 0) {
		if (errno != ENOENT) {
			bb_perror_msg("unable to stat `%s'", dest);
			return -1;
		}
	} else {
		if (source_stat.st_dev == dest_stat.st_dev &&
			source_stat.st_ino == dest_stat.st_ino)
		{
			bb_error_msg("`%s' and `%s' are the same file", source, dest);
			return -1;
		}
		dest_exists = 1;
	}

	if (S_ISDIR(source_stat.st_mode)) {
		DIR *dp;
		struct dirent *d;
		mode_t saved_umask = 0;

		if (!(flags & FILEUTILS_RECUR)) {
			bb_error_msg("%s: omitting directory", source);
			return -1;
		}

		/* Create DEST.  */
		if (dest_exists) {
			if (!S_ISDIR(dest_stat.st_mode)) {
				bb_error_msg("`%s' is not a directory", dest);
				return -1;
			}
		} else {
			mode_t mode;
			saved_umask = umask(0);

			mode = source_stat.st_mode;
			if (!(flags & FILEUTILS_PRESERVE_STATUS))
				mode = source_stat.st_mode & ~saved_umask;
			mode |= S_IRWXU;

			if (mkdir(dest, mode) < 0) {
				umask(saved_umask);
				bb_perror_msg("cannot create directory `%s'", dest);
				return -1;
			}

			umask(saved_umask);
		}

		/* Recursively copy files in SOURCE.  */
		if ((dp = bb_opendir(source)) == NULL) {
			status = -1;
			goto preserve_status;
		}

		while ((d = readdir(dp)) != NULL) {
			char *new_source, *new_dest;

			new_source = concat_subpath_file(source, d->d_name);
			if(new_source == NULL)
				continue;
			new_dest = concat_path_file(dest, d->d_name);
			if (copy_file(new_source, new_dest, flags) < 0)
				status = -1;
			free(new_source);
			free(new_dest);
		}
		/* closedir have only EBADF error, but "dp" not changes */
		closedir(dp);

		if (!dest_exists &&
				chmod(dest, source_stat.st_mode & ~saved_umask) < 0) {
			bb_perror_msg("unable to change permissions of `%s'", dest);
			status = -1;
		}
	} else if (S_ISREG(source_stat.st_mode) ||
		   (S_ISLNK(source_stat.st_mode) && (flags & FILEUTILS_DEREFERENCE)))
	{
		int src_fd;
		int dst_fd;
		if (ENABLE_FEATURE_PRESERVE_HARDLINKS) {
			char *link_name;

			if (!(flags & FILEUTILS_DEREFERENCE) &&
					is_in_ino_dev_hashtable(&source_stat, &link_name)) {
				if (link(link_name, dest) < 0) {
					bb_perror_msg("unable to link `%s'", dest);
					return -1;
				}

				return 0;
			}
			add_to_ino_dev_hashtable(&source_stat, dest);
		}
		src_fd = open(source, O_RDONLY);
		if (src_fd == -1) {
			bb_perror_msg("unable to open `%s'", source);
			return(-1);
		}

		if (dest_exists) {
			if (flags & FILEUTILS_INTERACTIVE) {
				fprintf(stderr, "%s: overwrite `%s'? ", bb_applet_name, dest);
				if (!bb_ask_confirmation()) {
					close (src_fd);
					return 0;
				}
			}

			dst_fd = open(dest, O_WRONLY|O_TRUNC);
			if (dst_fd == -1) {
				if (!(flags & FILEUTILS_FORCE)) {
					bb_perror_msg("unable to open `%s'", dest);
					close(src_fd);
					return -1;
				}

				if (unlink(dest) < 0) {
					bb_perror_msg("unable to remove `%s'", dest);
					close(src_fd);
					return -1;
				}

				goto dest_removed;
			}
		} else {
dest_removed:
			dst_fd = open(dest, O_WRONLY|O_CREAT, source_stat.st_mode);
			if (dst_fd == -1) {
				bb_perror_msg("unable to open `%s'", dest);
				close(src_fd);
				return(-1);
			}
		}

		if (bb_copyfd_eof(src_fd, dst_fd) == -1)
			status = -1;

		if (close(dst_fd) < 0) {
			bb_perror_msg("unable to close `%s'", dest);
			status = -1;
		}

		if (close(src_fd) < 0) {
			bb_perror_msg("unable to close `%s'", source);
			status = -1;
		}
	} else if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode) ||
	    S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode) ||
	    S_ISLNK(source_stat.st_mode)) {

		if (dest_exists) {
			if((flags & FILEUTILS_FORCE) == 0) {
				fprintf(stderr, "`%s' exists\n", dest);
				return -1;
			}
			if(unlink(dest) < 0) {
				bb_perror_msg("unable to remove `%s'", dest);
				return -1;
			}
		}
		if (S_ISFIFO(source_stat.st_mode)) {
			if (mkfifo(dest, source_stat.st_mode) < 0) {
				bb_perror_msg("cannot create fifo `%s'", dest);
				return -1;
			}
		} else if (S_ISLNK(source_stat.st_mode)) {
			char *lpath;

			lpath = xreadlink(source);
			if (symlink(lpath, dest) < 0) {
				bb_perror_msg("cannot create symlink `%s'", dest);
				return -1;
			}
			free(lpath);

			if (flags & FILEUTILS_PRESERVE_STATUS)
				if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
					bb_perror_msg("unable to preserve ownership of `%s'", dest);

			return 0;

		} else {
			if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
				bb_perror_msg("unable to create `%s'", dest);
				return -1;
			}
		}
	} else {
		bb_error_msg("internal error: unrecognized file type");
		return -1;
	}

preserve_status:

	if (flags & FILEUTILS_PRESERVE_STATUS) {
		struct utimbuf times;
		char *msg="unable to preserve %s of `%s'";

		times.actime = source_stat.st_atime;
		times.modtime = source_stat.st_mtime;
		if (utime(dest, &times) < 0)
			bb_perror_msg(msg, "times", dest);
		if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
			source_stat.st_mode &= ~(S_ISUID | S_ISGID);
			bb_perror_msg(msg, "ownership", dest);
		}
		if (chmod(dest, source_stat.st_mode) < 0)
			bb_perror_msg(msg, "permissions", dest);
	}

	return status;
}
Ejemplo n.º 20
0
static void skel(const char *homedir, uid_t u, gid_t g) {
	char *fname;
	// zsh
	if (arg_zsh) {
		// copy skel files
		if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
			errExit("asprintf");
		struct stat s;
		// don't copy it if we already have the file
		if (stat(fname, &s) == 0)
			return;
		if (stat("/etc/skel/.zshrc", &s) == 0) {
			if (copy_file("/etc/skel/.zshrc", fname) == 0) {
				if (chown(fname, u, g) == -1)
					errExit("chown");
			}
		}
		else { // 
			FILE *fp = fopen(fname, "w");
			if (fp) {
				fprintf(fp, "\n");
				fclose(fp);
				if (chown(fname, u, g) == -1)
					errExit("chown");
				if (chmod(fname, S_IRUSR | S_IWUSR) < 0)
					errExit("chown");
			}
		}
		free(fname);
	}
	// csh
	else if (arg_csh) {
		// copy skel files
		if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
			errExit("asprintf");
		struct stat s;
		// don't copy it if we already have the file
		if (stat(fname, &s) == 0)
			return;
		if (stat("/etc/skel/.cshrc", &s) == 0) {
			if (copy_file("/etc/skel/.cshrc", fname) == 0) {
				if (chown(fname, u, g) == -1)
					errExit("chown");
			}
		}
		else { // 
			FILE *fp = fopen(fname, "w");
			if (fp) {
				fprintf(fp, "\n");
				fclose(fp);
				if (chown(fname, u, g) == -1)
					errExit("chown");
				if (chmod(fname, S_IRUSR | S_IWUSR) < 0)
					errExit("chown");
			}
		}
		free(fname);
	}
	// bash etc.
	else {
		// copy skel files
		if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
			errExit("asprintf");
		struct stat s;
		// don't copy it if we already have the file
		if (stat(fname, &s) == 0)
			return;
		if (stat("/etc/skel/.bashrc", &s) == 0) {
			if (copy_file("/etc/skel/.bashrc", fname) == 0) {
				if (chown(fname, u, g) == -1)
					errExit("chown");
			}
		}
		free(fname);
	}
}
Ejemplo n.º 21
0
int
copy(char *argv[], enum op type, int fts_options)
{
	struct stat to_stat;
	FTS *ftsp;
	FTSENT *curr;
	int base, nlen, rval;
	char *p, *target_mid;
	base = 0;

	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
		err(1, NULL);
	for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
		switch (curr->fts_info) {
		case FTS_NS:
		case FTS_DNR:
		case FTS_ERR:
			warnx("%s: %s",
			    curr->fts_path, strerror(curr->fts_errno));
			rval = 1;
			continue;
		case FTS_DC:
			warnx("%s: directory causes a cycle", curr->fts_path);
			rval = 1;
			continue;
		}

		/*
		 * If we are in case (2) or (3) above, we need to append the
		 * source name to the target name.
		 */
		if (type != FILE_TO_FILE) {
			/*
			 * Need to remember the roots of traversals to create
			 * correct pathnames.  If there's a directory being
			 * copied to a non-existent directory, e.g.
			 *	cp -R a/dir noexist
			 * the resulting path name should be noexist/foo, not
			 * noexist/dir/foo (where foo is a file in dir), which
			 * is the case where the target exists.
			 *
			 * Also, check for "..".  This is for correct path
			 * concatenation for paths ending in "..", e.g.
			 *	cp -R .. /tmp
			 * Paths ending in ".." are changed to ".".  This is
			 * tricky, but seems the easiest way to fix the problem.
			 *
			 * XXX
			 * Since the first level MUST be FTS_ROOTLEVEL, base
			 * is always initialized.
			 */
			if (curr->fts_level == FTS_ROOTLEVEL) {
				if (type != DIR_TO_DNE) {
					p = find_last_component(curr->fts_path);
					base = p - curr->fts_path;
					
					if (!strcmp(&curr->fts_path[base],
					    ".."))
						base += 1;
				} else
					base = curr->fts_pathlen;
			}

			p = &curr->fts_path[base];
			nlen = curr->fts_pathlen - base;
			target_mid = to.target_end;
			if (*p != '/' && target_mid[-1] != '/')
				*target_mid++ = '/';
			*target_mid = '\0';
			if (target_mid - to.p_path + nlen >= MAXPATHLEN) {
				warnx("%s%s: name too long (not copied)",
				    to.p_path, p);
				rval = 1;
				continue;
			}
			(void)strncat(target_mid, p, nlen);
			to.p_end = target_mid + nlen;
			*to.p_end = '\0';
		}

		/* Not an error but need to remember it happened */
		if (stat(to.p_path, &to_stat) == -1) {
			if (curr->fts_info == FTS_DP)
				continue;
			/*
			 * We use fts_pointer as a boolean to indicate that
			 * we created this directory ourselves.  We'll use
			 * this later on via the fts_dne macro to decide
			 * whether or not to set the directory mode during
			 * the post-order pass.
			 */
			curr->fts_pointer = (void *)1;
		} else {
			/*
			 * Set directory mode/user/times on the post-order
			 * pass.  We can't do this earlier because the mode
			 * may not allow us write permission.  Furthermore,
			 * if we set the times during the pre-order pass,
			 * they will get changed later when the directory
			 * is populated.
			 */
			if (curr->fts_info == FTS_DP) {
				if (!S_ISDIR(to_stat.st_mode))
					continue;
				/*
				 * If not -p and directory didn't exist, set
				 * it to be the same as the from directory,
				 * unmodified by the umask; arguably wrong,
				 * but it's been that way forever.
				 */
				if (pflag && setfile(curr->fts_statp, 0))
					rval = 1;
				else if (fts_dne(curr))
					(void)chmod(to.p_path,
					    curr->fts_statp->st_mode);
				continue;
			}
			if (to_stat.st_dev == curr->fts_statp->st_dev &&
			    to_stat.st_ino == curr->fts_statp->st_ino) {
				warnx("%s and %s are identical (not copied).",
				    to.p_path, curr->fts_path);
				rval = 1;
				if (S_ISDIR(curr->fts_statp->st_mode))
					(void)fts_set(ftsp, curr, FTS_SKIP);
				continue;
			}
			if (!S_ISDIR(curr->fts_statp->st_mode) &&
			    S_ISDIR(to_stat.st_mode)) {
		warnx("cannot overwrite directory %s with non-directory %s",
				    to.p_path, curr->fts_path);
				rval = 1;
				continue;
			}
		}

		switch (curr->fts_statp->st_mode & S_IFMT) {
		case S_IFLNK:
			if (copy_link(curr, !fts_dne(curr)))
				rval = 1;
			break;
		case S_IFDIR:
			if (!Rflag && !rflag) {
				warnx("%s is a directory (not copied).",
				    curr->fts_path);
				(void)fts_set(ftsp, curr, FTS_SKIP);
				rval = 1;
				break;
			}
			/*
			 * If the directory doesn't exist, create the new
			 * one with the from file mode plus owner RWX bits,
			 * modified by the umask.  Trade-off between being
			 * able to write the directory (if from directory is
			 * 555) and not causing a permissions race.  If the
			 * umask blocks owner writes, we fail..
			 */
			if (fts_dne(curr)) {
				if (mkdir(to.p_path,
				    curr->fts_statp->st_mode | S_IRWXU) < 0)
					err(1, "%s", to.p_path);
			} else if (!S_ISDIR(to_stat.st_mode)) {
				errno = ENOTDIR;
				err(1, "%s", to.p_path);
			}
			break;
		case S_IFBLK:
		case S_IFCHR:
			if (Rflag) {
				if (copy_special(curr->fts_statp, !fts_dne(curr)))
					rval = 1;
			} else
				if (copy_file(curr, fts_dne(curr)))
					rval = 1;
			break;
		case S_IFIFO:
			if (Rflag) {
				if (copy_fifo(curr->fts_statp, !fts_dne(curr)))
					rval = 1;
			} else
				if (copy_file(curr, fts_dne(curr)))
					rval = 1;
			break;
		case S_IFSOCK:
			warnx("%s: %s", curr->fts_path, strerror(EOPNOTSUPP));
			break;
		default:
			if (copy_file(curr, fts_dne(curr)))
				rval = 1;
			break;
		}
	}
	if (errno)
		err(1, "fts_read");
	(void)fts_close(ftsp);
	return (rval);
}
Ejemplo n.º 22
0
int
copy(char *argv[], enum op type, int fts_options)
{
	struct stat to_stat;
	FTS *ftsp;
	FTSENT *curr;
	int base, dne, sval;
	int this_failed, any_failed;
	size_t nlen;
	char *p, *target_mid;

	base = 0;	/* XXX gcc -Wuninitialized (see comment below) */

	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
		err(EXIT_FAILURE, "%s", argv[0]);
		/* NOTREACHED */
	for (any_failed = 0; (curr = fts_read(ftsp)) != NULL;) {
		this_failed = 0;
		switch (curr->fts_info) {
		case FTS_NS:
		case FTS_DNR:
		case FTS_ERR:
			warnx("%s: %s", curr->fts_path,
					strerror(curr->fts_errno));
			this_failed = any_failed = 1;
			continue;
		case FTS_DC:			/* Warn, continue. */
			warnx("%s: directory causes a cycle", curr->fts_path);
			this_failed = any_failed = 1;
			continue;
		}

		/*
		 * If we are in case (2) or (3) above, we need to append the 
                 * source name to the target name.  
                 */
		if (type != FILE_TO_FILE) {
			if ((curr->fts_namelen +
			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
				warnx("%s/%s: name too long (not copied)",
						to.p_path, curr->fts_name);
				this_failed = any_failed = 1;
				continue;
			}

			/*
			 * Need to remember the roots of traversals to create
			 * correct pathnames.  If there's a directory being
			 * copied to a non-existent directory, e.g.
			 *	cp -R a/dir noexist
			 * the resulting path name should be noexist/foo, not
			 * noexist/dir/foo (where foo is a file in dir), which
			 * is the case where the target exists.
			 *
			 * Also, check for "..".  This is for correct path
			 * concatentation for paths ending in "..", e.g.
			 *	cp -R .. /tmp
			 * Paths ending in ".." are changed to ".".  This is
			 * tricky, but seems the easiest way to fix the problem.
			 *
			 * XXX
			 * Since the first level MUST be FTS_ROOTLEVEL, base
			 * is always initialized.
			 */
			if (curr->fts_level == FTS_ROOTLEVEL) {
				if (type != DIR_TO_DNE) {
					p = strrchr(curr->fts_path, '/');
					base = (p == NULL) ? 0 : 
					    (int)(p - curr->fts_path + 1);

					if (!strcmp(&curr->fts_path[base], 
					    ".."))
						base += 1;
				} else
					base = curr->fts_pathlen;
			}

			p = &curr->fts_path[base];
			nlen = curr->fts_pathlen - base;
			target_mid = to.target_end;
			if (*p != '/' && target_mid[-1] != '/')
				*target_mid++ = '/';
			*target_mid = 0;

			if (target_mid - to.p_path + nlen >= PATH_MAX) {
				warnx("%s%s: name too long (not copied)",
				    to.p_path, p);
				this_failed = any_failed = 1;
				continue;
			}
			(void)strncat(target_mid, p, nlen);
			to.p_end = target_mid + nlen;
			*to.p_end = 0;
			STRIP_TRAILING_SLASH(to);
		}

		sval = Pflag ? lstat(to.p_path, &to_stat) : stat(to.p_path, &to_stat);
		/* Not an error but need to remember it happened */
		if (sval == -1)
			dne = 1;
		else {
			if (to_stat.st_dev == curr->fts_statp->st_dev &&
			    to_stat.st_ino == curr->fts_statp->st_ino) {
				warnx("%s and %s are identical (not copied).",
				    to.p_path, curr->fts_path);
				this_failed = any_failed = 1;
				if (S_ISDIR(curr->fts_statp->st_mode))
					(void)fts_set(ftsp, curr, FTS_SKIP);
				continue;
			}
			if (!S_ISDIR(curr->fts_statp->st_mode) &&
			    S_ISDIR(to_stat.st_mode)) {
		warnx("cannot overwrite directory %s with non-directory %s",
				    to.p_path, curr->fts_path);
				this_failed = any_failed = 1;
				continue;
			}
			dne = 0;
		}

		switch (curr->fts_statp->st_mode & S_IFMT) {
		case S_IFLNK:
			/* Catch special case of a non dangling symlink */
			if((fts_options & FTS_LOGICAL) ||
			   ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
				if (copy_file(curr, dne))
					this_failed = any_failed = 1;
			} else {	
				if (copy_link(curr, !dne))
					this_failed = any_failed = 1;
			}
			break;
		case S_IFDIR:
			if (!Rflag && !rflag) {
				if (curr->fts_info == FTS_D)
					warnx("%s is a directory (not copied).",
					    curr->fts_path);
				(void)fts_set(ftsp, curr, FTS_SKIP);
				this_failed = any_failed = 1;
				break;
			}

                        /*
                         * Directories get noticed twice:
                         *  In the first pass, create it if needed.
                         *  In the second pass, after the children have been copied, set the permissions.
                         */
			if (curr->fts_info == FTS_D) /* First pass */
			{
				/*
				 * If the directory doesn't exist, create the new
				 * one with the from file mode plus owner RWX bits,
				 * modified by the umask.  Trade-off between being
				 * able to write the directory (if from directory is
				 * 555) and not causing a permissions race.  If the
				 * umask blocks owner writes, we fail..
				 */
				pushdne(dne);
				if (dne) {
					if (mkdir(to.p_path, 
					    curr->fts_statp->st_mode | S_IRWXU) < 0)
						err(EXIT_FAILURE, "%s",
						    to.p_path);
						/* NOTREACHED */
				} else if (!S_ISDIR(to_stat.st_mode)) {
					errno = ENOTDIR;
					err(EXIT_FAILURE, "%s",
						to.p_path);
					/* NOTREACHED */
				}
			}
			else if (curr->fts_info == FTS_DP) /* Second pass */
			{
	                        /*
				 * If not -p and directory didn't exist, set it to be
				 * the same as the from directory, umodified by the 
                        	 * umask; arguably wrong, but it's been that way 
                        	 * forever.
				 */
				if (pflag && setfile(curr->fts_statp, 0))
					this_failed = any_failed = 1;
				else if ((dne = popdne()))
					(void)chmod(to.p_path, 
					    curr->fts_statp->st_mode);
			}
			else
			{
				warnx("directory %s encountered when not expected.",
				    curr->fts_path);
				this_failed = any_failed = 1;
				break;
			}

			break;
		case S_IFBLK:
		case S_IFCHR:
			if (Rflag) {
				if (copy_special(curr->fts_statp, !dne))
					this_failed = any_failed = 1;
			} else
				if (copy_file(curr, dne))
					this_failed = any_failed = 1;
			break;
		case S_IFIFO:
			if (Rflag) {
				if (copy_fifo(curr->fts_statp, !dne))
					this_failed = any_failed = 1;
			} else 
				if (copy_file(curr, dne))
					this_failed = any_failed = 1;
			break;
		default:
			if (copy_file(curr, dne))
				this_failed = any_failed = 1;
			break;
		}
		if (vflag && !this_failed)
			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
	}
	if (errno) {
		err(EXIT_FAILURE, "fts_read");
		/* NOTREACHED */
	}
	(void)fts_close(ftsp);
	return (any_failed);
}
Ejemplo n.º 23
0
/**
 * Function to prepare the application directories for the container.
 */
int initialize_app(const char *user, const char *app_id,
                   const char* nmPrivate_credentials_file,
                   char* const* local_dirs, char* const* log_roots,
                   char* const* args) {
  if (app_id == NULL || user == NULL) {
    fprintf(LOGFILE, "Either app_id is null or the user passed is null.\n");
    return INVALID_ARGUMENT_NUMBER;
  }

  // create the user directory on all disks
  int result = initialize_user(user, local_dirs);
  if (result != 0) {
    return result;
  }

  ////////////// create the log directories for the app on all disks
  char* const* log_root;
  char *any_one_app_log_dir = NULL;
  for(log_root=log_roots; *log_root != NULL; ++log_root) {
    char *app_log_dir = get_app_log_directory(*log_root, app_id);
    if (app_log_dir == NULL) {
      // try the next one
    } else if (create_directory_for_user(app_log_dir) != 0) {
      free(app_log_dir);
      return -1;
    } else if (any_one_app_log_dir == NULL) {
      any_one_app_log_dir = app_log_dir;
    } else {
      free(app_log_dir);
    }
  }

  if (any_one_app_log_dir == NULL) {
    fprintf(LOGFILE, "Did not create any app-log directories\n");
    return -1;
  }
  free(any_one_app_log_dir);
  ////////////// End of creating the log directories for the app on all disks

  // open up the credentials file
  int cred_file = open_file_as_nm(nmPrivate_credentials_file);
  if (cred_file == -1) {
    return -1;
  }

  // give up root privs
  if (change_user(user_detail->pw_uid, user_detail->pw_gid) != 0) {
    return -1;
  }

  // 750
  mode_t permissions = S_IRWXU | S_IRGRP | S_IXGRP;
  char* const* nm_root;
  char *primary_app_dir = NULL;
  for(nm_root=local_dirs; *nm_root != NULL; ++nm_root) {
    char *app_dir = get_app_directory(*nm_root, user, app_id);
    if (app_dir == NULL) {
      // try the next one
    } else if (mkdirs(app_dir, permissions) != 0) {
      free(app_dir);
    } else if (primary_app_dir == NULL) {
      primary_app_dir = app_dir;
    } else {
      free(app_dir);
    }
  }

  if (primary_app_dir == NULL) {
    fprintf(LOGFILE, "Did not create any app directories\n");
    return -1;
  }

  char *nmPrivate_credentials_file_copy = strdup(nmPrivate_credentials_file);
  // TODO: FIXME. The user's copy of creds should go to a path selected by
  // localDirAllocatoir
  char *cred_file_name = concatenate("%s/%s", "cred file", 2,
				   primary_app_dir, basename(nmPrivate_credentials_file_copy));
  if (cred_file_name == NULL) {
	free(nmPrivate_credentials_file_copy);
    return -1;
  }
  if (copy_file(cred_file, nmPrivate_credentials_file,
		  cred_file_name, S_IRUSR|S_IWUSR) != 0){
	free(nmPrivate_credentials_file_copy);
    return -1;
  }

  free(nmPrivate_credentials_file_copy);

  fclose(stdin);
  fflush(LOGFILE);
  if (LOGFILE != stdout) {
    fclose(stdout);
  }
  if (ERRORFILE != stderr) {
    fclose(stderr);
  }
  if (chdir(primary_app_dir) != 0) {
    fprintf(LOGFILE, "Failed to chdir to app dir - %s\n", strerror(errno));
    return -1;
  }
  execvp(args[0], args);
  fprintf(ERRORFILE, "Failure to exec app initialization process - %s\n",
	  strerror(errno));
  return -1;
}
Ejemplo n.º 24
0
void
move_file (char const *from, int volatile *from_needs_removal,
	   char *to, mode_t mode, int backup)
{
  struct stat to_st;
  int to_errno = ! backup ? -1 : stat (to, &to_st) == 0 ? 0 : errno;

  if (backup)
    {
      int try_makedirs_errno = 0;
      char *bakname;

      if (origprae || origbase)
	{
	  char const *p = origprae ? origprae : "";
	  char const *b = origbase ? origbase : "";
	  char const *o = base_name (to);
	  size_t plen = strlen (p);
	  size_t tlen = o - to;
	  size_t blen = strlen (b);
	  size_t osize = strlen (o) + 1;
	  bakname = xmalloc (plen + tlen + blen + osize);
	  memcpy (bakname, p, plen);
	  memcpy (bakname + plen, to, tlen);
	  memcpy (bakname + plen + tlen, b, blen);
	  memcpy (bakname + plen + tlen + blen, o, osize);
	  for (p += FILESYSTEM_PREFIX_LEN (p);  *p;  p++)
	    if (ISSLASH (*p))
	      {
		try_makedirs_errno = ENOENT;
		break;
	      }
	}
      else
	{
	  bakname = find_backup_file_name (to, backup_type);
	  if (!bakname)
	    memory_fatal ();
	}

      if (to_errno)
	{
	  int fd;

	  if (debug & 4)
	    say ("Creating empty unreadable file %s\n", quotearg (bakname));

	  try_makedirs_errno = ENOENT;
	  unlink (bakname);
	  while ((fd = creat (bakname, 0)) < 0)
	    {
	      if (errno != try_makedirs_errno)
		pfatal ("Can't create file %s", quotearg (bakname));
	      makedirs (bakname);
	      try_makedirs_errno = 0;
	    }
	  if (close (fd) != 0)
	    pfatal ("Can't close file %s", quotearg (bakname));
	}
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, to), quotearg_n (1, bakname));
	  while (rename (to, bakname) != 0)
	    {
	      if (errno != try_makedirs_errno)
		pfatal ("Can't rename file %s to %s",
			quotearg_n (0, to), quotearg_n (1, bakname));
	      makedirs (bakname);
	      try_makedirs_errno = 0;
	    }
	}

      free (bakname);
    }

  if (from)
    {
      if (debug & 4)
	say ("Renaming file %s to %s\n",
	     quotearg_n (0, from), quotearg_n (1, to));

      if (rename (from, to) == 0)
	*from_needs_removal = 0;
      else
	{
	  int to_dir_known_to_exist = 0;

	  if (errno == ENOENT
	      && (to_errno == -1 || to_errno == ENOENT))
	    {
	      makedirs (to);
	      to_dir_known_to_exist = 1;
	      if (rename (from, to) == 0)
		{
		  *from_needs_removal = 0;
		  return;
		}
	    }

	  if (errno == EXDEV)
	    {
	      if (! backup)
		{
		  if (unlink (to) == 0)
		    to_dir_known_to_exist = 1;
		  else if (errno != ENOENT)
		    pfatal ("Can't remove file %s", quotearg (to));
		}
	      if (! to_dir_known_to_exist)
		makedirs (to);
	      copy_file (from, to, 0, mode);
	      return;
	    }

	  pfatal ("Can't rename file %s to %s",
		  quotearg_n (0, from), quotearg_n (1, to));
	}
    }
  else if (! backup)
    {
      if (debug & 4)
	say ("Removing file %s\n", quotearg (to));
      if (unlink (to) != 0)
	pfatal ("Can't remove file %s", quotearg (to));
    }
}
Ejemplo n.º 25
0
int main(int argc, const char *argv[])
{
#define MAXINCDIR 1024
#define MAXFILE 16384
    const char *incdirlist[MAXINCDIR];
    char *filelist[MAXFILE];
    int nincdir, nfiles;
    DIR *dirp;
    struct dirent *ent;

    /* This code used to append dependencies to the makefiles.
       Now it generates dependencies on STDOUT and does not
       mess with the makefiles at all.  However, the old stuff
       is left in here just in case.   To recover the old version
       recompile with -DAPPENDMAKEFILE */

#ifdef ADDPENDMAKEFILE
    /* Figure out the name of the makefile */

    if (access("makefile",R_OK|W_OK) == 0)
	makefile = "makefile";
    else if (access("Makefile",R_OK|W_OK) == 0)
	makefile = "Makefile";
    else {
	fprintf(stderr,"dependencies: makefile/Makefile not found\n");
	exit(1);
    }

    /* Make a backup copy */

    copy_file(makefile, backup);

    /* Reopen the makefile as standard output, copy the backup
       over it truncating before the magic line.  Write the magic
       line and then do the dependency analysis */

    if (!freopen(makefile, "w", stdout)) {
	perror("dependencies: failed reopening stdout");
	exit(1);
    }

    copy_truncate_makefile(backup);
#endif

    /* Extract list of include paths */

    nincdir = 1; incdirlist[0] = ".";

    while (argc > 1) {
	argc--;
	if (strncmp("-I",argv[argc],2) == 0) {
	    if (nincdir >= MAXINCDIR) {
		fprintf(stderr,"dependencies: too many include directories\n");
		restore_and_error_exit();
	    }
	    incdirlist[nincdir++] = argv[argc]+2;
	}
	else {
	    fprintf(stderr,"usage: dependencies [-Idir] [-Idir] ...\n");
	    restore_and_error_exit();
	}
    }

    /* Generate list of .F or .c files in the current directory 
       ... don't acutually need to store the list but it is convenient */

    if (!(dirp = opendir("."))) {
	perror("dependencies: failed to open current directory");
	restore_and_error_exit();
    }

    nfiles = 0;
    while ((ent = readdir(dirp))) {
	char *name = ent->d_name;
	int len = strlen(name);
	if ( (strncmp(".c",name+len-2,2) == 0) ||
             (strncmp(".F",name+len-2,2) == 0)) {
	    if (nfiles >= MAXFILE) {
		fprintf(stderr,"dependencies: too many files\n");
		restore_and_error_exit();
	    }
	    filelist[nfiles++] = strdup(name);
	}
    }

    (void) closedir(dirp);

    /* Loop thru files */

    while (nfiles--) {
	char *name = filelist[nfiles];
	char *objname = strdup(name);
	FILE *file;
	int i;
#define MAXINCFILE 8192
	char *incfiles[MAXINCFILE];
	int nincfile;
	int prev;

	objname[strlen(objname)-1] = 'o';

	/* Form sorted list of unique include files */

	/* printf("%d\t%s\n",nfiles,name); */
	if (!(file = fopen(name,"r"))) {
	    fprintf(stderr,"dependencies: failed to open %s : ",name);
	    perror(" ");
	    restore_and_error_exit();
	}

	nincfile = 0;
	while ((i = getc(file)) != EOF) {
	    char *tmp;
/************************************************************************\
Original code:
	    if (i == '#') 
		if ((tmp = include_directive(file))) {
		    if (nincfile >= MAXINCFILE) {
			fprintf(stderr,"dependencies: too many includes\n");
			restore_and_error_exit();
		    }
		    incfiles[nincfile++] = tmp;
		}
	    else
	       skip_to_eol(file);
\***********************************************************************/

/* makeing sure that # is the first character takes care of fortran comments
   but it does not take care of c style comments or includes that are dependent
   upon cpp flags.  The latter is the difficult one.
*/
	    if (i == '#') 
		{
		    if ((tmp = include_directive(file))) {
			if (nincfile >= MAXINCFILE) {
			    fprintf(stderr,"dependencies: too many includes\n");
			    restore_and_error_exit();
			}
			incfiles[nincfile++] = tmp;
		    }
		}
/*          else                  *\
  removed this "else" because 
  include_directive stops after 
  the second '"' and not the end 
  of the line.  Therefore all 
  lines parsed must go to EOL.
\*                                */
               skip_to_eol(file);
	}
	fclose(file);

	if (nincfile == 0)	/* If no included files skip this file */
	    continue;

	printf("$(LIBRARY_PATH)(%s):\t",objname);
	
	qsort(incfiles, nincfile, sizeof(char *), compar);
	
	prev = 0;		/* Remove and free duplicates */
	for (i=1; i<nincfile; i++) {
	    if (strcmp(incfiles[i],incfiles[prev]) == 0) {
		free(incfiles[i]);
		incfiles[i] = 0; /* For paranoia */
	    }
	    else
		incfiles[++prev] = incfiles[i];
	}
	nincfile = prev + 1;
	
	/* Loop thru the include files figuring out where each is */
	
    while (nincfile--) {
        char *incname = incfiles[nincfile];
        char path[256];

        for (i=0; i<nincdir; i++) {
            (void) sprintf(path, "%s/%s", incdirlist[i], incname);
            if (access(path, R_OK) == 0) {
                break;
            }
            path[0] = 0;
        }
        if (!path[0]) {
            (void) sprintf(path, "$(INCDIR)/%s", incname);
        }
        /* Skip mpif.h header since it is an external header. */
        if (0 != strcmp(incname, "mpif.h")) {
            printf("%s ",path);
        }
        free(incname);
    }
	printf("\n");
	free(objname);
    }
    return 0;
}
Ejemplo n.º 26
0
static int build_container(soc_type_t soc, uint32_t sector_size,
			   bool emmc_fastboot, image_t *image_stack,
			   bool dcd_skip, uint8_t fuse_version,
			   uint16_t sw_version, int ofd)
{
	static imx_header_v3_t imx_header;
	image_t *img_sp = image_stack;
	int file_off;
	uint8_t *tmp;
	struct stat sbuf;
	char *tmp_filename = NULL;
	uint32_t size = 0;
	uint32_t file_padding = 0;
	int ret;

	int container = -1;
	int cont_img_count = 0; /* indexes to arrange the container */

	memset((char *)&imx_header, 0, sizeof(imx_header_v3_t));

	if (!image_stack) {
		fprintf(stderr, "Empty image stack ");
		exit(EXIT_FAILURE);
	}

	if (soc == QX)
		fprintf(stdout, "Platform:\ti.MX8QXP B0\n");
	else if (soc == QM)
		fprintf(stdout, "Platform:\ti.MX8QM B0\n");

	set_imx_hdr_v3(&imx_header, 0);
	set_imx_hdr_v3(&imx_header, 1);

	file_off = get_container_image_start_pos(image_stack, sector_size);
	fprintf(stdout, "container image offset (aligned):%x\n", file_off);

	/* step through image stack and generate the header */
	img_sp = image_stack;

	/* stop once we reach null terminator */
	while (img_sp->option != NO_IMG) {
		switch (img_sp->option) {
		case AP:
		case M40:
		case M41:
		case SCFW:
		case DATA:
		case MSG_BLOCK:
			if (container < 0) {
				fprintf(stderr, "No container found\n");
				exit(EXIT_FAILURE);
			}
			check_file(&sbuf, img_sp->filename);
			tmp_filename = img_sp->filename;
			set_image_array_entry(&imx_header.fhdr[container],
					      soc, img_sp, file_off,
					      ALIGN(sbuf.st_size, sector_size),
					      tmp_filename, dcd_skip);
			img_sp->src = file_off;

			file_off += ALIGN(sbuf.st_size, sector_size);
			cont_img_count++;
			break;

		case SECO:
			if (container < 0) {
				fprintf(stderr, "No container found\n");
				exit(EXIT_FAILURE);
			}
			check_file(&sbuf, img_sp->filename);
			tmp_filename = img_sp->filename;
			set_image_array_entry(&imx_header.fhdr[container],
					      soc,
					      img_sp,
					      file_off,
					      sbuf.st_size,
					      tmp_filename, dcd_skip);
			img_sp->src = file_off;

			file_off += sbuf.st_size;
			cont_img_count++;
			break;

		case NEW_CONTAINER:
			container++;
			set_container(&imx_header.fhdr[container], sw_version,
				      CONTAINER_ALIGNMENT,
				      CONTAINER_FLAGS_DEFAULT,
				      fuse_version);
			/* reset img count when moving to new container */
			cont_img_count = 0;
			scfw_flags = 0;
			break;

		case APPEND:
			/*
			 * nothing to do here, the container is appended
			 * in the output
			 */
			break;
		case FLAG:
			/*
			 * override the flags for scfw in current container
			 * mask off bottom 16 bits.
			 */
			scfw_flags = img_sp->entry & 0xFFFF0000;
			break;
		case FILEOFF:
			if (file_off > img_sp->dst) {
				fprintf(stderr, "FILEOFF address less than current file offset!!!\n");
				exit(EXIT_FAILURE);
			}
			if (img_sp->dst != ALIGN(img_sp->dst, sector_size)) {
				fprintf(stderr, "FILEOFF address is not aligned to sector size!!!\n");
				exit(EXIT_FAILURE);
			}
			file_off = img_sp->dst;
			break;
		case PARTITION:
			/*
			 * keep custom partition until next executable image
			 * use a global var for default behaviour
			 */
			custom_partition = img_sp->entry;
			break;
		default:
			fprintf(stderr, "unrecognized option in input stack (%d)\n", img_sp->option);
			exit(EXIT_FAILURE);
		}
		img_sp++; /* advance index */
	}

	/* Append container (if specified) */
	img_sp = image_stack;
	do {
		if (img_sp->option == APPEND) {
			copy_file(ofd, img_sp->filename, 0, 0);
			file_padding += FIRST_CONTAINER_HEADER_LENGTH;
		}
		img_sp++;
	} while (img_sp->option != NO_IMG);

	/* Add padding or skip appended container */
	ret = lseek(ofd, file_padding, SEEK_SET);
	if (ret < 0) {
		fprintf(stderr, "%s: lseek error %s\n",
			__func__, strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (container >= 0) {
		/* Note: Image offset are not contained in the image */
		tmp = flatten_container_header(&imx_header, container + 1,
					       &size, file_padding);
		/* Write image header */
		if (write(ofd, tmp, size) != size) {
			fprintf(stderr, "error writing image hdr\n");
			exit(EXIT_FAILURE);
		}

		/* Clean-up memory used by the headers */
		free(tmp);
	}

	/*
	 * step through the image stack again this time copying
	 * images to final bin, stop once we reach null terminator.
	 */
	img_sp = image_stack;
	while (img_sp->option != NO_IMG) {
		if (img_sp->option == M40 || img_sp->option == M41 ||
		    img_sp->option == AP || img_sp->option == DATA ||
		    img_sp->option == SCD || img_sp->option == SCFW ||
		    img_sp->option == SECO || img_sp->option == MSG_BLOCK) {
			copy_file_aligned(ofd, img_sp->filename, img_sp->src,
					  sector_size);
		}
		img_sp++;
	}

	return 0;
}
Ejemplo n.º 27
0
Archivo: mh.c Proyecto: buzz/claws
static gint mh_copy_msgs(Folder *folder, FolderItem *dest, MsgInfoList *msglist, 
			 GHashTable *relation)
{
	gboolean dest_need_scan = FALSE;
	gboolean src_need_scan = FALSE;
	FolderItem *src = NULL;
	gchar *srcfile;
	gchar *destfile;
	FolderItemPrefs *prefs;
	MsgInfo *msginfo = NULL;
	MsgInfoList *cur = NULL;
	gint curnum = 0, total = 0;
	gchar *srcpath = NULL;
	gboolean full_fetch = FALSE;
	time_t last_dest_mtime = (time_t)0;
	time_t last_src_mtime = (time_t)0;

	cm_return_val_if_fail(dest != NULL, -1);
	cm_return_val_if_fail(msglist != NULL, -1);
	
	msginfo = (MsgInfo *)msglist->data;

	cm_return_val_if_fail(msginfo != NULL, -1);

	if (msginfo->folder == dest) {
		g_warning("the src folder is identical to the dest.");
		return -1;
	}

	if (msginfo->folder->folder != dest->folder)
		full_fetch = TRUE;
	
	if (FOLDER_TYPE(msginfo->folder->folder) == F_MH) {
		src = msginfo->folder;
	}

	if (dest->last_num < 0) {
		mh_get_last_num(folder, dest);
		if (dest->last_num < 0) return -1;
	}

	prefs = dest->prefs;

	srcpath = folder_item_get_path(msginfo->folder);

	dest_need_scan = mh_scan_required(dest->folder, dest);
	last_dest_mtime = dest->mtime;

	if (src) {
		src_need_scan = mh_scan_required(src->folder, src);
		last_src_mtime = src->mtime;
	}

	total = g_slist_length(msglist);
	if (total > 100) {
		if (MSG_IS_MOVE(msginfo->flags))
			statusbar_print_all(_("Moving messages..."));
		else
			statusbar_print_all(_("Copying messages..."));
	}
	for (cur = msglist; cur; cur = cur->next) {
		msginfo = (MsgInfo *)cur->data;
		if (!msginfo) {
			goto err_reset_status;
		}
		if (!full_fetch) {
			srcfile = g_strconcat(srcpath, 
				G_DIR_SEPARATOR_S, 
				itos(msginfo->msgnum), NULL);
		} else {
			srcfile = procmsg_get_message_file(msginfo);
		}
		if (!srcfile) {
			goto err_reset_status;
		}
		destfile = mh_get_new_msg_filename(dest);
		if (!destfile) {
			g_free(srcfile);
			goto err_reset_status;
		}

		if (total > 100) {
			statusbar_progress_all(curnum, total, 100);
			if (curnum % 100 == 0)
				GTK_EVENTS_FLUSH();
			curnum++;
		}

		debug_print("Copying message %s%c%d to %s ...\n",
			    msginfo->folder->path, G_DIR_SEPARATOR,
			    msginfo->msgnum, dest->path);


		if (MSG_IS_MOVE(msginfo->flags)) {
			msginfo->flags.tmp_flags &= ~MSG_MOVE_DONE;
			if (move_file(srcfile, destfile, TRUE) < 0) {
				FILE_OP_ERROR(srcfile, "move");
				if (copy_file(srcfile, destfile, TRUE) < 0) {
					FILE_OP_ERROR(srcfile, "copy");
					g_free(srcfile);
					g_free(destfile);
					goto err_reset_status;
				}
			} else {
				/* say unlinking's not necessary */
				msginfo->flags.tmp_flags |= MSG_MOVE_DONE;
			}
		} else if (copy_file(srcfile, destfile, TRUE) < 0) {
			FILE_OP_ERROR(srcfile, "copy");
			g_free(srcfile);
			g_free(destfile);
			goto err_reset_status;
		} 
		if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
			if (chmod(destfile, prefs->folder_chmod) < 0)
				FILE_OP_ERROR(destfile, "chmod");
		}
		if (relation) {
			if (g_hash_table_lookup(relation, msginfo) != NULL)
				g_warning("already in: %p", msginfo);
			
			g_hash_table_insert(relation, msginfo, GINT_TO_POINTER(dest->last_num+1));
		}
		g_free(srcfile);
		g_free(destfile);
		dest->last_num++;
	}

	g_free(srcpath);
	mh_write_sequences(dest, TRUE);

	if (dest->mtime == last_dest_mtime && !dest_need_scan) {
		mh_set_mtime(folder, dest);
	}

	if (src && src->mtime == last_src_mtime && !src_need_scan) {
		mh_set_mtime(folder, src);
	}

	if (total > 100) {
		statusbar_progress_all(0,0,0);
		statusbar_pop_all();
	}
	return dest->last_num;
err_reset_status:
	g_free(srcpath);
	mh_write_sequences(dest, TRUE);
	if (total > 100) {
		statusbar_progress_all(0,0,0);
		statusbar_pop_all();
	}
	return -1;

}
Ejemplo n.º 28
0
void
main_init(int argc, char* argv[])
{
	char**		ptr; 
	MyString		job_queue_name;
 
	int argc_count = 1;
	for(ptr = argv + 1, argc_count = 1; argc_count<argc && *ptr; ptr++,argc_count++)
	{
		if(ptr[0][0] != '-')
		{
			usage(argv[0]);
		}
		switch(ptr[0][1])
		{
		  case 'n':
			if (Name) {
				free(Name);
			}
			Name = build_valid_daemon_name( *(++ptr) );
			break;
		  default:
			usage(argv[0]);
		}
	}

		// Tell Attrlist to publish the server time
	AttrList_setPublishServerTime( true );

		// Initialize DaemonCore's use of ProcFamily. We do this so that we
		// launch a ProcD if necessary so that any Starters that we launch
		// for Local Universe jobs can share a single ProcD, instead of
		// each creating their own
	daemonCore->Proc_Family_Init();

#if defined(HAVE_DLOPEN)
	ClassAdLogPluginManager::Load();
	ScheddPluginManager::Load();

	ScheddPluginManager::EarlyInitialize();
	ClassAdLogPluginManager::EarlyInitialize();
#endif

/* schedd doesn't care about other daemons.  only that it has the ability
 * to run jobs.  so the following code is for now not needed.

	// ZKM HACK TO MAKE SURE SCHEDD HAS USER CREDENTIALS
	//
	// if we are using the credd and credmon, we need to init them before
	// doing anything!
	char* p = param("SEC_CREDENTIAL_DIRECTORY");
	if(p) {
		free(p);
		dprintf(D_ALWAYS, "SCHEDD: INITIALIZING USER CREDS\n");
		Daemon *my_credd;

		// we will abort if we can't locate the credd, so let's try a
		// few times. locate() caches the result so we have to destroy
		// the object and make a new one each time.
		int retries = 20;
		bool success = false;
		do {
			// allocate a credd
			my_credd = new Daemon(DT_CREDD);
			if(my_credd) {
				// call locate
				bool loc_rc = my_credd->locate();
				if(loc_rc) {
					// get a connected relisock
					CondorError errstack;
					ReliSock* r = (ReliSock*)my_credd->startCommand(
						CREDD_REFRESH_ALL, Stream::reli_sock, 20, &errstack);
					if ( r ) {
						// ask the credd to get us some fresh user creds
						ClassAd ad;
						putClassAd(r, ad);
						r->end_of_message();
						r->decode();
						getClassAd(r, ad);
						r->end_of_message();
						dprintf(D_SECURITY | D_FULLDEBUG, "SCHEDD: received ad from CREDD:\n");
						dPrintAd(D_SECURITY | D_FULLDEBUG, ad);
						MyString result;
						ad.LookupString("Result", result);
						if(result == "success") {
							success = true;
						} else {
							dprintf(D_FULLDEBUG, "SCHEDD: warning, creddmon returned failure.\n");
						}

						// clean up.
						delete r;
					} else {
						dprintf(D_FULLDEBUG, "SCHEDD: warning, startCommand failed, %s\n", errstack.getFullText(true).c_str());
					}
				} else {
					dprintf(D_FULLDEBUG, "SCHEDD: warning, locate failed.\n");
				}

				// clean up.
				delete my_credd;
			} else {
				dprintf(D_FULLDEBUG, "SCHEDD: warning, new Daemon(DT_CREDD) failed.\n");
			}

			// if something went wrong, sleep and retry (finit number of times)
			if(!success) {
				dprintf(D_FULLDEBUG, "SCHEDD: sleeping and trying again %i times.\n", retries);
				sleep(1);
				retries--;
			}
		} while ((retries > 0) && (success == false));

		// except if fail
		if (!success) {
			EXCEPT("FAILED TO INITIALIZE USER CREDS (locate failed)");
		}
	}
	// END ZKM HACK
*/

#ifndef WIN32
	// if using the SEC_CREDENTIAL_DIRECTORY, confirm we are "up-to-date".
	// at the moment, we take an "all-or-nothing" approach.  ultimately, this
	// should be per-user, and the SchedD should start normally and run jobs
	// for users who DO have valid credentials, and simply holding on to jobs
	// in idle state for users who do NOT have valid credentials.
	//
	char* p = param("SEC_CREDENTIAL_DIRECTORY");
	if(p) {
		free(p);
		bool success = false;
		int retries = 60;
		do {
			// look for existence of file that says everything is up-to-date.
			success = credmon_poll(NULL, false, false);
			if(!success) {
				dprintf(D_ALWAYS, "SCHEDD: User credentials not up-to-date.  Start-up delayed.  Waiting 10 seconds and trying %i more times.\n", retries);
				sleep(10);
				retries--;
			}
		} while ((!success) && (retries > 0));

		// we tried, we give up.
		if(!success) {
			EXCEPT("User credentials unavailable after 10 minutes");
		}
	}
	// User creds good to go, let's start this thing up!
#endif  // WIN32

		// Initialize all the modules
	scheduler.Init();
	scheduler.Register();

		// Initialize the job queue
	char *job_queue_param_name = param("JOB_QUEUE_LOG");

	if (job_queue_param_name == NULL) {
		// the default place for the job_queue.log is in spool
		job_queue_name.formatstr( "%s/job_queue.log", Spool);
	} else {
		job_queue_name = job_queue_param_name; // convert char * to MyString
		free(job_queue_param_name);
	}

		// Make a backup of the job queue?
	if ( param_boolean_crufty("SCHEDD_BACKUP_SPOOL", false) ) {
			MyString hostname;
			hostname = get_local_hostname();
			MyString		job_queue_backup;
			job_queue_backup.formatstr( "%s/job_queue.bak.%s.%ld",
			                            Spool, hostname.Value(), (long)time(NULL) );
			if ( copy_file( job_queue_name.Value(), job_queue_backup.Value() ) ) {
				dprintf( D_ALWAYS, "Failed to backup spool to '%s'\n",
						 job_queue_backup.Value() );
			} else {
				dprintf( D_FULLDEBUG, "Spool backed up to '%s'\n",
						 job_queue_backup.Value() );
			}
	}

	int max_historical_logs = param_integer( "MAX_JOB_QUEUE_LOG_ROTATIONS", DEFAULT_MAX_JOB_QUEUE_LOG_ROTATIONS );

	InitJobQueue(job_queue_name.Value(),max_historical_logs);
	PostInitJobQueue();

		// Initialize the dedicated scheduler stuff
	dedicated_scheduler.initialize();

		// Do a timeout now at startup to get the ball rolling...
	scheduler.timeout();

#if defined(HAVE_DLOPEN)
	ScheddPluginManager::Initialize();
	ClassAdLogPluginManager::Initialize();
#endif

	daemonCore->InstallAuditingCallback( AuditLogNewConnection );
} 
Ejemplo n.º 29
0
int
main(int argc, char **argv)
{
	FILE * volatile f;
	char		*s;
	volatile int	left;
	volatile off_t	initline;
	volatile int	prnames = 0;
	volatile int	initopt = 0;
	volatile int	srchopt = 0;
	int		clearit = 0;
	int		ch;
	char		initbuf[80];

	setlocale(LC_ALL, "");

	/* all signals just use a stub handler and interrupt syscalls */
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sa.sa_handler = onsignal;

	nfiles = argc;
	fnames = argv;
	initterm();
	nscroll = Lpp/2 - 1;
	if (nscroll <= 0)
		nscroll = 1;
	if ((s = getenv("MORE")) != NULL && *s != '\0')
		argscan(s);
	while (--nfiles > 0) {
		if ((ch = (*++fnames)[0]) == '-')
			argscan(*fnames + 1);
		else if (ch == '+') {
			s = *fnames;
			if (*++s == '/') {
				srchopt++;
				(void)strlcpy(initbuf, ++s, sizeof(initbuf));
			} else {
				initopt++;
				for (initline = 0; *s != '\0'; s++) {
					if (isdigit(*s))
						initline =
						    initline * 10 + *s - '0';
				}
				--initline;
			}
		} else
			break;
	}
	/*
	 * Allow clreol only if Home and eraseln and EodClr strings are
	 * defined, and in that case, make sure we are in noscroll mode.
	 */
	if (clreol) {
		if (Home == NULL || *Home == '\0' || eraseln == NULL ||
		    *eraseln == '\0' || EodClr == NULL || *EodClr == '\0')
			clreol = 0;
		else
			noscroll = 1;
	}
	if (dlines == 0)
		dlines = Lpp - 1;
	left = dlines;
	if (nfiles > 1)
		prnames++;
	if (!no_intty && nfiles == 0)
		usage();
	else
		f = stdin;
	if (!no_tty) {
		struct sigaction osa;

		(void)sigaction(SIGQUIT, &sa, NULL);
		(void)sigaction(SIGINT, &sa, NULL);
		(void)sigaction(SIGWINCH, &sa, NULL);
		if (sigaction(SIGTSTP, &osa, NULL) == 0 &&
		    osa.sa_handler == SIG_DFL) {
			(void)sigaction(SIGTSTP, &sa, NULL);
			(void)sigaction(SIGTTIN, &sa, NULL);
			(void)sigaction(SIGTTOU, &sa, NULL);
			catch_susp++;
		}
		set_tty();
	}
	if (no_intty) {
		if (no_tty)
			copy_file(stdin);
		else {
			if ((ch = Getc(f)) == '\f')
				doclear();
			else {
				Ungetc(ch, f);
				if (noscroll && ch != EOF) {
					if (clreol)
						home();
					else
						doclear();
				}
			}
			if (srchopt) {
				if (search(initbuf, stdin, 1) == 0 && noscroll)
					left--;
			} else if (initopt)
				skiplns(initline, stdin);
			screen(stdin, left);
		}
		no_intty = 0;
		dup2(STDERR_FILENO, STDIN_FILENO);	/* stderr is a tty */
		prnames++;
		firstf = 0;
	}

	while (fnum < nfiles) {
		if ((f = checkf(fnames[fnum], &clearit)) != NULL) {
			context.line = context.chrctr = 0;
			Currline = 0;
		restart:
			if (firstf) {
				firstf = 0;
				if (srchopt) {
					if (search(initbuf, f, 1) < 0)
						goto restart;
					if (noscroll)
						left--;
				} else if (initopt)
					skiplns(initline, f);
			} else if (fnum < nfiles && !no_tty)
				left = command(fnames[fnum], f);
			if (left != 0) {
				if ((noscroll || clearit) &&
				    (file_size != LONG_MAX)) {
					if (clreol)
						home();
					else
						doclear();
				}
				if (prnames) {
					if (bad_so)
						erasep(0);
					if (clreol)
						cleareol();
					fputs("::::::::::::::", stdout);
					if (promptlen > 14)
						erasep(14);
					putchar('\n');
					if (clreol)
						cleareol();
					printf("%s\n", fnames[fnum]);
					if (clreol)
						cleareol();
					fputs("::::::::::::::\n", stdout);
					if (left > Lpp - 4)
						left = Lpp - 4;
				}
				if (no_tty)
					copy_file(f);
				else {
					within++;
					screen(f, left);
					within = 0;
				}
			}
			fflush(stdout);
			fclose(f);
			screen_start.line = screen_start.chrctr = 0L;
			context.line = context.chrctr = 0L;
		}
		fnum++;
		firstf = 0;
	}
	reset_tty();
	exit(0);
}
Ejemplo n.º 30
0
int main(int argc, char **argv) {
    FILE	*f;
    char	*s;
    char	*p;
    int		ch;
    int		left;
    int		prnames = 0;
    int		initopt = 0;
    int		srchopt = 0;
    int		clearit = 0;
    int		initline = 0;
    char	initbuf[INIT_BUF];

    setlocale(LC_ALL, "");
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);

    nfiles = argc;
    fnames = argv;
    setlocale(LC_ALL, "");
    initterm ();

    /* Auto set no scroll on when binary is called page */
    if (!(strcmp(program_invocation_short_name, "page")))
       noscroll++;

    prepare_line_buffer();

    nscroll = Lpp/2 - 1;
    if (nscroll <= 0)
	nscroll = 1;

    if ((s = getenv("MORE")) != NULL)
	    argscan(s);

    while (--nfiles > 0) {
	if ((ch = (*++fnames)[0]) == '-') {
	    argscan(*fnames+1);
	}
	else if (ch == '+') {
	    s = *fnames;
	    if (*++s == '/') {
		srchopt++;
		for (++s, p = initbuf; p < initbuf + (INIT_BUF - 1) && *s != '\0';)
		    *p++ = *s++;
		*p = '\0';
	    }
	    else {
		initopt++;
		for (initline = 0; *s != '\0'; s++)
		    if (isdigit (*s))
			initline = initline*10 + *s -'0';
		--initline;
	    }
	}
	else break;
    }
    /* allow clreol only if Home and eraseln and EodClr strings are
     *  defined, and in that case, make sure we are in noscroll mode
     */
    if (clreol) {
        if((Home == NULL) || (*Home == '\0') ||
	   (eraseln == NULL) || (*eraseln == '\0') ||
           (EodClr == NULL) || (*EodClr == '\0') )
	      clreol = 0;
	else noscroll = 1;
    }
    if (dlines == 0)
	    dlines = Lpp - 1;	/* was: Lpp - (noscroll ? 1 : 2) */
    left = dlines;
    if (nfiles > 1)
	prnames++;
    if (!no_intty && nfiles == 0)
	usage(stderr);
    else
	f = stdin;
    if (!no_tty) {
	signal(SIGQUIT, onquit);
	signal(SIGINT, end_it);
#ifdef SIGWINCH
	signal(SIGWINCH, chgwinsz);
#endif /* SIGWINCH */
	if (signal (SIGTSTP, SIG_IGN) == SIG_DFL) {
	    signal(SIGTSTP, onsusp);
	    catch_susp++;
	}
	stty (fileno(stderr), &otty);
    }
    if (no_intty) {
	if (no_tty)
	    copy_file (stdin);
	else {
	    if ((ch = Getc (f)) == '\f')
		doclear();
	    else {
		Ungetc (ch, f);
		if (noscroll && (ch != EOF)) {
		    if (clreol)
			home ();
		    else
			doclear ();
		}
	    }
	    if (srchopt)
	    {
		search (initbuf, stdin, 1);
		if (noscroll)
		    left--;
	    }
	    else if (initopt)
		skiplns (initline, stdin);
	    screen (stdin, left);
	}
	no_intty = 0;
	prnames++;
	firstf = 0;
    }

    while (fnum < nfiles) {
	if ((f = checkf (fnames[fnum], &clearit)) != NULL) {
	    context.line = context.chrctr = 0;
	    Currline = 0;
	    if (firstf) sigsetjmp (restore, 1);
	    if (firstf) {
		firstf = 0;
		if (srchopt) {
		    search (initbuf, f, 1);
		    if (noscroll)
			left--;
		}
		else if (initopt)
		    skiplns (initline, f);
	    }
	    else if (fnum < nfiles && !no_tty) {
		sigsetjmp (restore, 1);
		left = command (fnames[fnum], f);
	    }
	    if (left != 0) {
		if ((noscroll || clearit) && (file_size != LONG_MAX)) {
		    if (clreol)
			home ();
		    else
			doclear ();
		}
		if (prnames) {
		    if (bad_so)
			erasep (0);
		    if (clreol)
			cleareol ();
		    putsout("::::::::::::::");
		    if (promptlen > 14)
			erasep (14);
		    putchar('\n');
		    if(clreol) cleareol();
		    puts(fnames[fnum]);
		    if(clreol) cleareol();
		    puts("::::::::::::::");
		    if (left > Lpp - 4)
			left = Lpp - 4;
		}
		if (no_tty)
		    copy_file (f);
		else {
		    within++;
		    screen(f, left);
		    within = 0;
		}
	    }
	    sigsetjmp (restore, 1);
	    fflush(stdout);
	    fclose(f);
	    screen_start.line = screen_start.chrctr = 0L;
	    context.line = context.chrctr = 0L;
	}
	fnum++;
	firstf = 0;
    }
    reset_tty ();
    exit(EXIT_SUCCESS);
}