Exemple #1
0
static int update_volume(libubi_t libubi, int fdsw, struct img_type *img,
	struct ubi_vol_info *vol)
{
	long long bytes;
	int fdout;
	char node[64];
	int err;
	unsigned long offset = 0;
	uint32_t checksum = 0;
	char sbuf[128];

	bytes = img->size;

	if (!libubi) {
		ERROR("Request to write into UBI, but no UBI on system");
		return -1;
	}

	if (bytes > vol->rsvd_bytes) {
		ERROR("\"%s\" (size %lld) will not fit volume \"%s\" (size %lld)",
		       img->fname, bytes, img->volname, vol->rsvd_bytes);
		return -1;
	}

	snprintf(node, sizeof(node), "/dev/ubi%d_%d",
		vol->dev_num,
		vol->vol_id);

	err = ubi_probe_node(libubi, node);

	if (err == 1) {
		ERROR("\"%s\" is an UBI device node, not an UBI volume node",
			node);
		return -1;
	}
	if (err < 0) {
		if (errno == ENODEV)
			ERROR("%s is not an UBI volume node", node);
		else
			ERROR("error while probing %s", node);
		return -1;
	}

	fdout = open(node, O_RDWR);
	if (fdout < 0) {
		ERROR("cannot open UBI volume \"%s\"", node);
		return -1;
	}
	err = ubi_update_start(libubi, fdout, bytes);
	if (err) {
		ERROR("cannot start volume \"%s\" update", node);
		return -1;
	}

	snprintf(sbuf, sizeof(sbuf), "Installing image %s into volume %s(%s)",
		img->fname, node, img->volname);
	notify(RUN, RECOVERY_NO_ERROR, sbuf);

	printf("Updating UBI : %s %lld %lu\n",
			img->fname, img->size, offset);
	if (copyfile(fdsw, fdout, img->size, (unsigned long *)&img->offset, 0,
		img->compressed, &checksum) < 0) {
		ERROR("Error copying extracted file");
		err = -1;
	}
	close(fdout);
	return err;
}
Exemple #2
0
static void remote_filereq(int idx, char *from, char *file)
{
    char *p = NULL, *what = NULL, *dir = NULL,
          *s1 = NULL, *reject = NULL, *s = NULL;
    FILE *fdb = NULL;
    int i = 0;
    filedb_entry *fdbe = NULL;

    malloc_strcpy(what, file);
    p = strrchr(what, '/');
    if (p) {
        *p = 0;
        malloc_strcpy(dir, what);
        strcpy(what, p + 1);
    } else {
        malloc_strcpy(dir, "");
    }
    fdb = filedb_open(dir, 0);
    if (!fdb) {
        reject = FILES_DIRDNE;
    } else {
        filedb_readtop(fdb, NULL);
        fdbe = filedb_matchfile(fdb, ftell(fdb), what);
        filedb_close(fdb);
        if (!fdbe) {
            reject = FILES_FILEDNE;
        } else {
            if ((!(fdbe->stat & FILE_SHARE)) ||
                    (fdbe->stat & (FILE_HIDDEN | FILE_DIR)))
                reject = FILES_NOSHARE;
            else {
                s1 = nmalloc(strlen(dccdir) + strlen(dir) + strlen(what) + 2);
                /* Copy to /tmp if needed */
                sprintf(s1, "%s%s%s%s", dccdir, dir, dir[0] ? "/" : "", what);
                if (copy_to_tmp) {
                    s = nmalloc(strlen(tempdir) + strlen(what) + 1);
                    sprintf(s, "%s%s", tempdir, what);
                    copyfile(s1, s);
                } else
                    s = s1;
                i = raw_dcc_send(s, "*remote", FILES_REMOTE, s);
                if (i > 0) {
                    wipe_tmp_filename(s, -1);
                    reject = FILES_SENDERR;
                }
                if (s1 != s)
                    my_free(s);
                my_free(s1);
            }
            free_fdbe(&fdbe);
        }
    }
    s1 = nmalloc(strlen(botnetnick) + strlen(dir) + strlen(what) + 3);
    simple_sprintf(s1, "%s:%s/%s", botnetnick, dir, what);
    if (reject) {
        botnet_send_filereject(idx, s1, from, reject);
        my_free(s1);
        my_free(what);
        my_free(dir);
        return;
    }
    /* Grab info from dcc struct and bounce real request across net */
    i = dcc_total - 1;
    s = nmalloc(40);              /* Enough? */
    simple_sprintf(s, "%d %u %d", iptolong(getmyip()), dcc[i].port,
                   dcc[i].u.xfer->length);
    botnet_send_filesend(idx, s1, from, s);
    putlog(LOG_FILES, "*", FILES_REMOTEREQ, dir, dir[0] ? "/" : "", what);
    my_free(s1);
    my_free(s);
    my_free(what);
    my_free(dir);
}
/*
 * The Mac OS "copyfile()" API copies the extended metadata for a
 * file into a separate file in AppleDouble format (see RFC 1740).
 *
 * Mac OS tar and cpio implementations store this extended
 * metadata as a separate entry just before the regular entry
 * with a "._" prefix added to the filename.
 *
 * Note that this is currently done unconditionally; the tar program has
 * an option to discard this information before the archive is written.
 *
 * TODO: If there's a failure, report it and return ARCHIVE_WARN.
 */
static int
setup_mac_metadata(struct archive_read_disk *a,
    struct archive_entry *entry, int *fd)
{
	int tempfd = -1;
	int copyfile_flags = COPYFILE_NOFOLLOW | COPYFILE_ACL | COPYFILE_XATTR;
	struct stat copyfile_stat;
	int ret = ARCHIVE_OK;
	void *buff = NULL;
	int have_attrs;
	const char *name, *tempdir;
	struct archive_string tempfile;

	(void)fd; /* UNUSED */
	name = archive_entry_sourcepath(entry);
	if (name == NULL)
		name = archive_entry_pathname(entry);
	if (name == NULL) {
		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
		    "Can't open file to read extended attributes: No name");
		return (ARCHIVE_WARN);
	}

	if (a->tree != NULL) {
		if (a->tree_enter_working_dir(a->tree) != 0) {
			archive_set_error(&a->archive, errno,
				    "Couldn't change dir");
				return (ARCHIVE_FAILED);
		}
	}

	/* Short-circuit if there's nothing to do. */
	have_attrs = copyfile(name, NULL, 0, copyfile_flags | COPYFILE_CHECK);
	if (have_attrs == -1) {
		archive_set_error(&a->archive, errno,
			"Could not check extended attributes");
		return (ARCHIVE_WARN);
	}
	if (have_attrs == 0)
		return (ARCHIVE_OK);

	tempdir = NULL;
	if (issetugid() == 0)
		tempdir = getenv("TMPDIR");
	if (tempdir == NULL)
		tempdir = _PATH_TMP;
	archive_string_init(&tempfile);
	archive_strcpy(&tempfile, tempdir);
	archive_strcat(&tempfile, "tar.md.XXXXXX");
	tempfd = mkstemp(tempfile.s);
	if (tempfd < 0) {
		archive_set_error(&a->archive, errno,
		    "Could not open extended attribute file");
		ret = ARCHIVE_WARN;
		goto cleanup;
	}
	__archive_ensure_cloexec_flag(tempfd);

	/* XXX I wish copyfile() could pack directly to a memory
	 * buffer; that would avoid the temp file here.  For that
	 * matter, it would be nice if fcopyfile() actually worked,
	 * that would reduce the many open/close races here. */
	if (copyfile(name, tempfile.s, 0, copyfile_flags | COPYFILE_PACK)) {
		archive_set_error(&a->archive, errno,
		    "Could not pack extended attributes");
		ret = ARCHIVE_WARN;
		goto cleanup;
	}
	if (fstat(tempfd, &copyfile_stat)) {
		archive_set_error(&a->archive, errno,
		    "Could not check size of extended attributes");
		ret = ARCHIVE_WARN;
		goto cleanup;
	}
	buff = malloc(copyfile_stat.st_size);
	if (buff == NULL) {
		archive_set_error(&a->archive, errno,
		    "Could not allocate memory for extended attributes");
		ret = ARCHIVE_WARN;
		goto cleanup;
	}
	if (copyfile_stat.st_size != read(tempfd, buff, copyfile_stat.st_size)) {
		archive_set_error(&a->archive, errno,
		    "Could not read extended attributes into memory");
		ret = ARCHIVE_WARN;
		goto cleanup;
	}
	archive_entry_copy_mac_metadata(entry, buff, copyfile_stat.st_size);

cleanup:
	if (tempfd >= 0) {
		close(tempfd);
		unlink(tempfile.s);
	}
	archive_string_free(&tempfile);
	free(buff);
	return (ret);
}
Exemple #4
0
/* Because this function is called at the beginning, and if it returns -1 
 * the program will exit soon. So there is no need to free resource here.
 */
static int load_friends() {
	int distance = 0, line = 0;
	FILE *fp;
	char buf[EACH_MSG_LEN*2], curr_user[IDLEN+1], tar_user[IDLEN+1];
	char *ptr;
	UserNode *punode_op = NULL, *punode_ta = NULL;
	Relationship *pr;

	if(!file_exist(MY_BBS_HOME "/friends.dump")) //可运行时dump
		return 0;

	fp = fopen(MY_BBS_HOME "/friends.dump", "r");
	if(fp == NULL)
		return -1;

	curr_user[0] = '\0';
	while(fgets(buf, sizeof(buf)-1, fp)) {
		if(*buf == '\n' || *buf == '\0') //空行,文件结束
			break;		
		if(*buf == '#') { //新的user
			if((ptr = strchr(buf, '\n')) != NULL)
				*ptr = '\0';
			strncpy(curr_user, buf+1, sizeof(curr_user));
			punode_op = get_afriend(curr_user);
			if(punode_op == NULL)
				return -1;
		} else {
			if(punode_op == NULL) //bad file-format
				return -1;
			ptr = strchr(buf, ' ');
			if(ptr == NULL) //bad file-format
				return -1;
			*ptr = '\0';
			strncpy(tar_user, buf, sizeof(tar_user));
			distance = atoi(ptr+1);
			
			punode_ta = get_afriend(tar_user);
			if(punode_ta == NULL)
				return -1;
			
			pr = calloc(1, sizeof(Relationship));
			if(pr == NULL)
				return -1;
			pr->ptr = punode_ta;
			pr->distance = distance;
			if(insert_node(punode_op->to, pr) == -1)
				return -1;
			
			pr = calloc(1, sizeof(Relationship));
			if(pr == NULL)
				return -1;
			pr->ptr = punode_op;
			pr->distance = distance;
			if(insert_node(punode_ta->from, pr) == -1)
				return -1;
		}
		line++;
	}
	fclose(fp);
	if(line > 0)
		copyfile(MY_BBS_HOME "/friends.dump", MY_BBS_HOME "/friends.dump.good");
	
	return 0;
}
Exemple #5
0
tb_bool_t tb_file_copy(tb_char_t const* path, tb_char_t const* dest)
{
    // check
    tb_assert_and_check_return_val(path && dest, tb_false);

#ifdef TB_CONFIG_POSIX_HAVE_COPYFILE

    // the full path
    tb_char_t full0[TB_PATH_MAXN];
    path = tb_path_absolute(path, full0, TB_PATH_MAXN);
    tb_assert_and_check_return_val(path, tb_false);

    // the dest path
    tb_char_t full1[TB_PATH_MAXN];
    dest = tb_path_absolute(dest, full1, TB_PATH_MAXN);
    tb_assert_and_check_return_val(dest, tb_false);

    // attempt to copy it directly
    if (!copyfile(path, dest, 0, COPYFILE_ALL)) return tb_true;
    else
    {
        // attempt to copy it again after creating directory
        tb_char_t dir[TB_PATH_MAXN];
        if (tb_directory_create(tb_path_directory(dest, dir, sizeof(dir))))
            return !copyfile(path, dest, 0, COPYFILE_ALL);
    }

    // failed
    return tb_false;
#else
    tb_int_t    ifd = -1;
    tb_int_t    ofd = -1;
    tb_bool_t   ok = tb_false;
    do
    {
        // get the absolute source path
        tb_char_t data[8192];
        path = tb_path_absolute(path, data, sizeof(data));
        tb_assert_and_check_break(path);

        // get stat.st_mode first
#ifdef TB_CONFIG_POSIX_HAVE_STAT64
        struct stat64 st = {0};
        if (stat64(path, &st)) break;
#else
        struct stat st = {0};
        if (stat(path, &st)) break;
#endif

        // open source file
        ifd = open(path, O_RDONLY);
        tb_check_break(ifd >= 0);

        // get the absolute source path
        dest = tb_path_absolute(dest, data, sizeof(data));
        tb_assert_and_check_break(dest);

        // open destinate file and copy file mode
        ofd = open(dest, O_RDWR | O_CREAT | O_TRUNC, st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO));
        if (ofd < 0)
        {
            // attempt to open it again after creating directory
            tb_char_t dir[TB_PATH_MAXN];
            if (tb_directory_create(tb_path_directory(dest, dir, sizeof(dir))))
                ofd = open(dest, O_RDWR | O_CREAT | O_TRUNC, st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO));
        }
        tb_check_break(ofd >= 0);

        // get file size
        tb_hize_t size = tb_file_size(tb_fd2file(ifd));

        // init write size
        tb_hize_t writ = 0; 
       
        // attempt to copy file using `sendfile`
#ifdef TB_CONFIG_POSIX_HAVE_SENDFILE
        while (writ < size)
        {
            off_t seek = writ;
            tb_hong_t real = sendfile(ofd, ifd, &seek, (size_t)(size - writ));
            if (real > 0) writ += real;
            else break;
        }

        /* attempt to copy file directly if sendfile failed 
         *
         * sendfile() supports regular file only after "since Linux 2.6.33".
         */
        if (writ != size) 
        {
            lseek(ifd, 0, SEEK_SET);
            lseek(ofd, 0, SEEK_SET);
        }
        else
        {
            ok = tb_true;
            break;
        }
#endif

        // copy file using `read` and `write`
        writ = 0;
        while (writ < size)
        {
            // read some data
            tb_int_t real = read(ifd, data, (size_t)tb_min(size - writ, sizeof(data)));
            if (real > 0)
            {
                real = write(ofd, data, real);
                if (real > 0) writ += real;
                else break;
            }
            else break;
        }

        // ok?
        ok = (writ == size);

    } while (0);

    // close source file
    if (ifd >= 0) close(ifd);
    ifd = -1;

    // close destinate file
    if (ofd >= 0) close(ofd);
    ofd = -1;

    // ok?
    return ok;
#endif
}
Exemple #6
0
main(int argc, char *argv[])
{
	int c, usgflg = 0, inputfd, printerfd, sendport;
	char *desthostname, *hnend;
	char portstr[4];

	if (signal(SIGALRM, alarmhandler) == SIG_ERR) {
		fprintf(stderr, "failed to set alarm handler\n");
		exit(1);
	}
	while ((c = getopt(argc, argv, "Dd:k:qs:t:H:P:")) != -1)
		switch (c) {
		case 'D':
			debugflag = 1;
			debug("debugging on\n");
			break;
		case 'd':
			printername = optarg;
			break;
		case 'k':
			if (statflag) {
				fprintf(stderr, "cannot have both -k and -q flags\n");
				exit(1);
			}	
			killflag = 1;
			killarg = optarg;
			break;
		case 'q':
			if (killflag) {
				fprintf(stderr, "cannot have both -q and -k flags\n");
				exit(1);
			}	
			statflag = 1;
			break;
		case 's':
			seqno = strtol(optarg, NULL, 10);
			if (seqno < 0 || seqno > 999)
				seqno = 0;
			break;
		case 't':
			switch (filetype) {
			case 'c':
			case 'd':
			case 'f':
			case 'g':
			case 'l':
			case 'n':
			case 'o':
			case 'p':
			case 'r':
			case 't':
			case 'v':
			case 'z':
				filetype = optarg[0];
				break;
			default:
				usgflg++;
				break;
			}
			break;
		case 'H':
			strncpy(hostname, optarg, MAXHOSTNAMELEN);
			break;
		case 'P':
			username = optarg;
			break;
		default:
		case '?':
			fprintf(stderr, "unknown option %c\n", c);
			usgflg++;
		}
	if (argc < 2) usgflg++;
	if (optind < argc) {
		desthostname = argv[optind++];
	} else
		usgflg++;
	if (usgflg) {
		fprintf(stderr, "usage: to send a job - %s -d printer -H hostname -P username [-s seqno] [-t[cdfgklnoprtvz]] desthost [filename]\n", argv[0]);
		fprintf(stderr, "     to check status - %s -d printer -q desthost\n", argv[0]);
		fprintf(stderr, "       to kill a job - %s -d printer -P username -k jobname desthost\n", argv[0]);
		exit(1);
	}

/* make sure the file to send is here and ready
 * otherwise the TCP connection times out.
 */
	if (!statflag && !killflag) {
		if (optind < argc) {
			inputname = argv[optind++];
			debug("open("); debug(inputname); debug(")\n");
			inputfd = open(inputname, O_RDONLY);
			if (inputfd < 0) {
				fprintf(stderr, "open(%s) failed\n", inputname);
				exit(1);
			}
		} else {
			inputname = "stdin";
			tmpnam(tmpfilename);
			debug("using stdin\n");
			if ((inputfd = open(tmpfilename, O_RDWR|O_CREAT, 0600)) < 0) {
				fprintf(stderr, "open(%s) failed\n", tmpfilename);
				exit(1);
			}
			atexit(cleanup);
			debug("copy input to temp file ");
			debug(tmpfilename);
			debug("\n");
			if (!copyfile(0, inputfd, 0L)) {
				fprintf(stderr, "failed to copy file to temporary file\n");
				exit(1);
			}
			if (lseek(inputfd, 0L, 0) < 0) {
				fprintf(stderr, "failed to seek back to the beginning of the temporary file\n");
				exit(1);
			}
		}
	}

	sprintf(strbuf, "%s", netmkaddr(desthostname, "tcp", "printer"));
	fprintf(stderr, "connecting to %s\n", strbuf);
	for (sendport=721; sendport<=731; sendport++) {
		sprintf(portstr, "%3.3d", sendport);
		fprintf(stderr, " trying from port %s...", portstr);
		debug(" dial("); debug(strbuf); debug(", "); debug(portstr); debug(", 0, 0) ...");
		printerfd = dial(strbuf, portstr, 0, 0);
		if (printerfd >= 0) {
			fprintf(stderr, "connected\n");
			break;
		}
		fprintf(stderr, "failed\n");
		sleep(REDIALTIMEOUT);
	}
	if (printerfd < 0) {
		fprintf(stderr, "Cannot open a valid port!\n");
		fprintf(stderr, "-  All source ports [721-731] may be busy.\n");
		fprintf(stderr, "-  Is recipient ready and online?\n");
		fprintf(stderr, "-  If all else fails, cycle the power!\n");
		exit(1);
	}
/*	hostname[8] = '\0'; */
#ifndef PLAN9
	if (gethostname(hostname, sizeof(hostname)) < 0) {
		perror("gethostname");
		exit(1);
	}
#endif
/*	if ((hnend = strchr(hostname, '.')) != NULL)
		*hnend = '\0';
 */
	if (statflag) {
		checkqueue(printerfd);
	} else if (killflag) {
		killjob(printerfd);
	} else {
		sendjob(inputfd, printerfd);
	}
	exit(0);
}
Exemple #7
0
int main (int argc, char **argv)
{
    int i;
    int fd[argc];
    int outfd = 1;
    int ix;
    
    /* Process Option Arguments */
    ix = 1;
    if (argc > ix && argv[ix][0] == '-' && argv[ix][1] == 'd') {
	debug = 1;
	ix++;
    }
    if (argc > ix && argv[ix][0] == '-')
	{
	    if (argv[ix][1] == 'o' && argv[ix][2] == 0 && argc > 2)
		{
		    /* Open the output file. */
		    outfd = open (argv[ix+1], O_WRONLY|O_CREAT|O_TRUNC,
				  0777);
		    if (outfd < 0)
			{
			    write (2, "Can not open output file ", 25);
			    write (2, argv[ix+1], strlen(argv[ix+1]));
			    write (2, ".\n", 2);
			    exit (1);
			}
		    
		    /* Adjust argv/argc to ignore -o option. */
		    ix += 2;
		}
	    else if (strcmp(argv[ix], "-f") == 0)
	      {
		debug = 1;
	      }
	    else
		{
		    write (2, "Usage: ", 7);
		    write (2, argv[0], strlen(argv[0]));
		    write (2, " [-d] [-o file] [files ...]\n", 28);
			exit (1);
		}
	}
    
    if (argc == 1)
	{  /* Read from standard in! */
	    copyfile (0, outfd);
	}
    else
	{ /* For each argument, open the file, copy it to outfd, close it. */
	    for (i = ix; i < argc; i++)
		{
		    fd[i] = open (argv[i], O_RDONLY, 0);
		    if (fd[i] < 0)
			{
			    write (2, "Can not open file ", 18);
			    write (2, argv[i], strlen(argv[i]));
			    write (2, ".\n", 2);
			    exit (1);
			}
		    copyfile (fd[i], outfd);
		}
	    for (i = ix; i < argc; i++)
		close (fd[i]);
	}
    
    /* Done successfully */
    close(outfd);
    exit (0);
}
Exemple #8
0
static void _inotify_event_handler(struct inotify_event *event)
{
	/* Perform event dependent handler routines */
	/* The mask is the magic that tells us what file operation occurred */
    if(strstr(event->name,UNIX_Z)==0)
    {
        /*File was closed */
        if(event->mask & IN_CLOSE_WRITE)
        {
            #ifdef DEBUG
            printf("wd:%d",event->wd);
            printf("IN_CLOSE_WRITE\n");
            printf("event->name: %s\n", event->name);
            #endif

            char command[COMMAND_SIZE]={0};
            FILE *pf;
            //get the command to compress the file with unix.z
            if(event->wd==1)
                sprintf(command,"compress -f %s%s",uploadPath->BDLocalPathPrefix,event->name);
            else
                sprintf(command,"compress -f %s%s",uploadPath->GNSSLocalPathPrefix,event->name);
            //execute the command of compression
            if((pf=popen(command,"r"))==NULL)
            {
                //compression failed
                #ifdef _DEBUG
                perror("压缩失败");
                #endif
            }
            pclose(pf);
            up_delay();

        }

        /* File was deleted means the compression is over*/
        if(event->mask & IN_DELETE)
        {
            #ifdef DEBUG
            printf("IN_DELETE\n");
            printf("event->name: %s\n", event->name);
            #endif
            int type = event-> wd;
            char name[STD_FILENAME_SIZE]="0";
            strcpy(name,event->name);
            if(nodeIsExist(name,type)==1)
            {
                char * dir;
                UploadNode *p0;
                p0=(UploadNode *)malloc(sizeof(UploadNode));

                int len1 = strlen(name)+strlen(UNIX_Z)+1;
                p0->filename=(char *)malloc(len1);
                memset(p0->filename,0, len1);
                sprintf(p0->filename,"%s%s",name,UNIX_Z);
                printf("filename:%s\n",p0->filename);
                //move the file to the backup folder

                dir = (char *)malloc(10);
                memset(dir,0,10);

                //move the file to the backup folder
                copyfile(p0->filename,type,dir);

                //BEIDOU
                if(type==1)
                {
                    int len2=strlen(uploadPath->BDLocalPathPrefix)+1;
                    p0->analysisCenterPath=(char *)malloc(len2);
                    memset(p0->analysisCenterPath,0, len2);
                    strcpy(p0->analysisCenterPath,uploadPath->BDLocalPathPrefix);

                    int len3 = strlen(uploadPath->BDRemotePathPrefix)+strlen(dir)+strlen(PATH_SUFFIX)+1;
                    p0->productCenterPath=(char *)malloc(len3);
                    memset(p0->productCenterPath,0, len3);
                    sprintf(p0->productCenterPath,"%s%s%s",uploadPath->BDRemotePathPrefix,dir,PATH_SUFFIX);
                }
                //GNSS
                else
                {
                    int len2=strlen(uploadPath->GNSSLocalPathPrefix)+1;
                    p0->analysisCenterPath=(char *)malloc(len2);
                    memset(p0->analysisCenterPath,0, len2);
                    strcpy(p0->analysisCenterPath,uploadPath->GNSSLocalPathPrefix);

                    int len3 = strlen(uploadPath->GNSSRemotePathPrefix)+strlen(dir)+strlen(PATH_SUFFIX)+1;
                    p0->productCenterPath=(char *)malloc(len3);
                    memset(p0->productCenterPath,0, len3);
                    sprintf(p0->productCenterPath,"%s%s%s",uploadPath->GNSSRemotePathPrefix,dir,PATH_SUFFIX);
                }



                p0->state=UPLOAD_FILE_EXIST;
                p0->type = type;
                p0->server=fs->next;
                #ifdef DEBUG
                printf("filename:%s\n",p0->filename);
                printf("传入:%s\n",p0->filename);
                log_checktask(p0->filename,"文件创建");
                #endif
                //create a new node
                insertlist(p0);
            }



    }

    }
}
Exemple #9
0
/* -------------------------------------------------------------------- */
static void makeSendFile(void)
{
    char line[100], line2[100];
    label troo;
    label fn;
    FILE *file;
    int i = 0, rm;
    
    if ((file = fopen(roomreqin, "rb")) == NULL)
    {
        perror("Error opening roomreq.in");
    }

    doccr();
    cPrintf(" Fetching:");
    doccr();

    GetStr(file, troo, LABELSIZE);
    
    while(strlen(troo) && !feof(file))
    {
        if ((rm = roomExists(troo)) != ERROR)
        {
	    if (nodecanseeroom(node.ndname, rm))
            {
                sprintf(fn, "room.%d", i);
                cPrintf(" %-20s  ", troo);
                if( !((i+1) % 3) ) doccr();
                NewRoom(rm, fn);
            }
            else
            {
                doccr();
                cPrintf(" No access to %s room.", troo);
                doccr();
                amPrintf(" '%s' room not available to remote.\n", troo);
                netError = TRUE;
            }
        }
        else
        {
            doccr();
            cPrintf(" No %s room on system.", troo);
            doccr();
            amPrintf(" '%s' room not found for remote.\n", troo);
            netError = TRUE;
        }

        i++;
        GetStr(file, troo, LABELSIZE);
    }
    doccr();
    fclose(file);
    unlink(roomreqin);

    cPrintf(" Copying mail file.");
    doccr();
    sprintf(line,  "%s\\%s",         cfg.transpath, node.ndmailtmp);
    sprintf(line2, "%s\\mesg.tmp",   cfg.temppath);
    if ((file = fopen(line2, "wb")) != NULL)
    {
        fclose(file);
    }
    copyfile(line, line2);
    
    cPrintf(" Compressing message files.");
    doccr();
    
    /* 
     * Zip them up
     */
    sformat(line, node.zip, "df", roomdataout, "mesg.tmp room.*");
    apsystem(line);
    
    /* 
     * Remove them.
     */
    ambigUnlink("room.*",   FALSE);
    unlink("mesg.tmp");
}
Exemple #10
0
/*
 * Yymain initializes each of the utility
 * clusters and then starts the processing
 * by calling yyparse.
 */
yymain()
{

#ifdef OBJ
/*
 * initialize symbol table temp files
 */
	startnlfile();
#endif
	/*
	 * Initialize the scanner
	 */
#ifdef PXP
	if (bracket == 0) {
#endif
		if (getline() == -1) {
			Perror(filename, "No lines in file");
			pexit(NOSTART);
		}
#ifdef PXP
	} else
		yyline = 0;
#endif

#ifdef PI
#   ifdef OBJ
	magic();
#   endif OBJ
#endif
	line = 1;
	errpfx = 'E';
	/*
	 * Initialize the clusters
	 *
	initstring();
	 */
	inithash();
	inittree();
#ifdef PI
	initnl();
#endif

	/*
	 * Process the input
	 */
	yyparse();
#ifdef PI
#   ifdef OBJ

	/*
	 * save outermost block of namelist
	 */
	savenl(NLNIL);

	magic2();
#   endif OBJ
#   ifdef DEBUG
	dumpnl(NLNIL);
#   endif
#endif

#ifdef PXP
	prttab();
	if (onefile) {
		extern int outcol;

		if (outcol)
			pchr('\n');
		flush();
		if (eflg) {
			writef(2, "File not rewritten because of errors\n");
			pexit(ERRS);
		}
		(void) signal(SIGHUP, SIG_IGN);
		(void) signal(SIGINT, SIG_IGN);
		copyfile();
	}
#endif
	pexit(eflg ? ERRS : AOK);
}
int main(int argc, char *argv[])
{
unsigned int repeat=0;
char **tags;
int i;
int a;
int b;
float gdivide_a;
float gdivide_b;


char are_you_sure[100];

#ifdef NAJI_DEBUG

 fprintf(stderr, "\n\n");
 fprintf(stderr, "NAJI_DEBUG - check if two commands are displayed as one joined string,\n");
 fprintf(stderr, "             you might have missed a , in najitool_valid_commands[]\n\n");

 for (i=0; i<NAJITOOL_MAX_COMMANDS; i++)               
 fprintf(stderr, "%s ", najitool_valid_commands[i]);
 fgetc(stdin);

#endif /* NAJI_DEBUG */



#ifdef NAJI_DEBUG
    fprintf(stderr, "\n\nNAJI_DEBUG - YOUR PARAMETERS/ARGUMENTS:\n\n");
    
    for (i=0; i<argc; i++)
    fprintf(stderr, "%s ", argv[i]);
    
    fprintf(stderr, "\n\n");

    fgetc(stdin);
#endif /* NAJI_DEBUG */



    if (argc >= 2)
    {
    tolowers(argv[1]);
    najitool_check_command(argv[1]);
    }


    if (argc == 1)
    {
    printf("\n\n");


/*
printf("           __    |         \n");
printf("          /  \\   |        \n");
printf("     /   _____|  | o \\    \n");
printf("    |    \\  o    |___|    \n");
printf("     \\____\\              \n");
printf("      o o    T O O L       \n");
*/


printf("           __    |          ********************************************\n");
printf("          /  \\   |               najitool 0.8.4 using libnaji 0.6.4     \n");
printf("     /   _____|  | o \\            both written by NECDET COKYAZICI      \n");
printf("    |    \\  o    |___|                   and contributors              \n");
printf("     \\____\\                 ********************************************\n");
printf("      o o    T O O L         No warranty, to view the license type:     \n");
printf("                                         najitool license               \n");
printf("  http://najitool.sf.net/   ********************************************\n");
printf("                             To view the credits type: najitool credits \n");
printf("  Public Domain, 2003-2011  ********************************************\n");
printf("\n");


forhelp();


    return 0;
    }



    if (argc >= 2)
    {


        if (!strcmp(argv[1], "mp3taged"))
        {

            if ((argc % 2 != 1) | (argc == 3))
            {
            printf("mp3taged: too few arguments '%s'\n", argv[1]);
            return 1;
            }

            /*
             * we save the tags' options:
             * tags[i] = <tag name>
             * tags[i+1] = <user content>
             * ..
             */

            tags = (char**) malloc (sizeof(char*)*(argc-3)*2);

            for (i=0; i<(argc-3)*2; i+=2)
            tags[i] = (char*) malloc(7*sizeof(char));

            for (i=1; i<(argc-3)*2; i+=2)
            tags[i] = argv[i+2];

            for (i=0; i<(argc-3)*2; i+=2)
            memcpy (tags[i], argv[i+2], 7);

            mp3editag (argv[argc-1], tags, argc-3);

            for (i=0; i<(argc-3)*2; i+=2)
            free(tags[i]);

            free(tags);

        return 0;
        }

        if (!strcmp(argv[1], "credits"))
        {

            if (argc > 2)
            tooparam("credits");

            naji_credits();

            return 0;
        }

        if (!strcmp(argv[1], "asctable"))
        {

            if (argc > 2)
            tooparam("asctable");

            asctable();
            return 0;
        }

        if (!strcmp(argv[1], "engnum"))
        {

            if (argc > 2)
            tooparam("engnum");

            engnum();
            return 0;
        }

        if (!strcmp(argv[1], "turnum"))
        {

            if (argc > 2)
            tooparam("turnum");
     
            turnum();
            return 0;
        }

        if (!strcmp(argv[1], "najcrypt"))
        {

            if (argc > 2)
            tooparam("najcrypt");

            najcrypt();
            return 0;
        }

        if (!strcmp(argv[1], "database"))
        {

            if (argc > 2)
            tooparam("database");
    
            naji_database();
            return 0;
        }

        if (!strcmp(argv[1], "html_db"))
        {

            if (argc > 2)
            tooparam("html_db");

            naji_html_database();
            return 0;
        }

        if (!strcmp(argv[1], "calc"))
        {

            if (argc > 2)
            tooparam("calc");

            naji_calc();
            return 0;
        }

        if (!strcmp(argv[1], "length"))
        {

            if (argc > 2)
            tooparam("length");

            length();
            return 0;
        }

        if (!strcmp(argv[1], "mathgame"))
        {

            if (argc > 2)
            tooparam("mathgame");

            mathgame();
            return 0;
        }

        if (!strcmp(argv[1], "license"))
        {

            if (argc > 2)
            tooparam("license");

            naji_license();
            return 0;
        }

        if (!strcmp(argv[1], "ttt"))
        {

            if (argc > 2)
            tooparam("ttt");

            ttt();
            return 0;
        }

        if (!strcmp(argv[1], "naji_bmp"))
        {
            if (argc > 2)
            tooparam("naji_bmp");

            naji_bmp();
            return 0;
        }

        if (!strcmp(argv[1], "unihtml"))
        {

            if (argc > 2)
            tooparam("unihtml");

            naji_gen_unicode_html_pages();
            return 0;
        }
    
        if (!strcmp(argv[1], "rmunihtm"))
        {

            if (argc > 2)
            tooparam("rmunihtm");
    
            naji_del_gen_unicode_html_pages();
            return 0;
        }
    
        if (!strcmp(argv[1], "cat_text"))
        {

            if (argc == 2)
            {
            naji_stdin_msg();
            cat_text_stdin();
            return 0;
            }

            if (argc == 3)
            {
            cat_text(argv[2]);
            return 0;
            }

            if (argc > 3)
            tooparam("cat_text");

            return 0;
        }

        if (!strcmp(argv[1], "kitten"))
        {

            if (argc == 2)
            {
            naji_stdin_msg();
            kitten_stdin();
            return 0;
            }

            if (argc == 3)
            {
            kitten(argv[2]);
            return 0;
            }

            if (argc > 3)
            tooparam("kitten");

        return 0;
        }

        if (!strcmp(argv[1], "genlic"))
        {

            if (argc > 2)
            tooparam("genlic");

            naji_genlic();
            return 0;
        }

        if (!strcmp(argv[1], "genhelp"))
        {

            if (argc > 2)
            tooparam("genhelp");

            najitool_generate_help();
            return 0;
        }

        if (!strcmp(argv[1], "htmlhelp"))
        {
            if (argc > 2)
            tooparam("htmlhelp");

            najitool_generate_help_html();
            return 0;
        }

        if (!strcmp(argv[1], "systemdt"))
        {
            if (argc > 2)
            tooparam("systemdt");
        
            systemdt();
            return 0;
        }


        if (!strcmp(argv[1], "datetime"))
        {

            if (argc > 2)
            tooparam("datetime");

            datetime();
            return 0;
        }

        if (!strcmp(argv[1], "telltime"))
        {

            if (argc > 2)
            tooparam("telltime");

            printf("\n\n");
            telltime();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "today"))
        {

            if (argc > 2)
            tooparam("today");

            printf("\n\n");
            today();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "dayofmon"))
        {

            if (argc > 2)
            tooparam("dayofmon");
    
            printf("\n\n");
            dayofmon();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "month"))
        {

            if (argc > 2)
            tooparam("month");

            printf("\n\n");
            month();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "year"))
        {

            if (argc > 2)
            tooparam("year");

            printf("\n\n");
            year();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "saatarih"))
        {

            if (argc > 2)
            tooparam("saatarih");

            saatarih();
            return 0;
        }

        if (!strcmp(argv[1], "saat"))
        {

            if (argc > 2)
            tooparam("saat");

            printf("\n\n");
            saat();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "bugun"))
        {
            if (argc > 2)
            tooparam("bugun");

            printf("\n\n");
            bugun();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "ayinkaci"))
        {

            if (argc > 2)
            tooparam("ayinkaci");

            printf("\n\n");
            ayinkaci();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "ay"))
        {

            if (argc > 2)
            tooparam("ay");

            printf("\n\n");
            ay();
            printf("\n\n");

            return 0;
        }

        if (!strcmp(argv[1], "yil"))
        {
            if (argc > 2)
            tooparam("yil");

            printf("\n\n");
            yil();
            printf("\n\n");

            return 0;
        }


        if (!strcmp(argv[1], "allbmp16"))
        {
            if (argc > 2)
            tooparam("allbmp16");

            printf("\n\n");
            allbmp16();
            printf("\n\n");

            return 0;
        }


        if (!strcmp(argv[1], "help"))
        {

            if (argc == 2)
            {
            printf("\n\nAvailable help catagories:\n\n");
            printf("commands\n");
            printf("\n\n");
            forhelp();
            return 0;
            }


            if (argc == 3)
            {

                  if (!strcmp(argv[2], "commands"))
                  najitool_help_commands();

                  else najitool_command_help(argv[2]);

                  return 0;
            }


            if (argc > 3)
            tooparam("help");

            return 0;
        }



begin_cmd("mergline", 7)
mergline(argv[2], argv[3], argv[4], argv[5], argv[6]);
end_cmd()

begin_cmd("mp3split", 6)
mp3split(argv[4], argv[5], atoi(argv[2]), atoi(argv[3]));
end_cmd()

begin_cmd("rrrchars", 6)
rrrchars(argv[2], argv[3], atoi(argv[4]), atoi(argv[5]));
end_cmd()

begin_cmd("chstr", 6)
chstr(argv[2], argv[3], argv[4], argv[5]);
end_cmd()

begin_cmd("chchars", 6)
chchars(argv[2], argv[3], argv[4], argv[5]);
end_cmd()

begin_cmd("chchar", 6)
chchar(argv[2], argv[3], argv[4][0], argv[5][0]);
end_cmd()

begin_cmd("filechop", 6)
filechop( (strtol(argv[2], NULL, 0)), argv[3], argv[4], argv[5]);
end_cmd()
        
begin_cmd("putlines", 6)
putlines(argv[2], argv[3], argv[4], argv[5]);
end_cmd()

begin_cmd("copyoffs", 6)
copyoffs(argv[2], strtoul(argv[3], NULL, 0), strtoul(argv[4], NULL, 0), argv[5]);
end_cmd()

begin_cmd("istrael", 6)
istrael(argv[2], atoi(argv[3]), argv[4], argv[5]);
end_cmd()

begin_cmd("addline", 6)
addline(argv[2], argv[3], argv[4], strtoul(argv[5], NULL, 0));
end_cmd()

begin_cmd("replacel", 6)
replacel(argv[2], argv[3], argv[4], strtoul(argv[5], NULL, 0));
end_cmd()


begin_cmd("bremline", 5)
bremline(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("eremline", 5)
eremline(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("remline", 5)
remline(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("skipstr", 5)
skipstr(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("makarray", 5)
makarray(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("streline", 5)
streline(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("strbline", 5)
strbline(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("swapfeb", 5)
swapfeb(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("filbreed", 5)
filbreed(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("skipchar", 5)
skipchar(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("onlychar", 5)
onlychar(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("repchar", 5)
repeat = (unsigned int) atoi(argv[4]);
repchar(argv[2], argv[3], repeat);
end_cmd()

begin_cmd("linesnip", 5)
repeat = (unsigned int) atoi(argv[2]);
linesnip(repeat, argv[3], argv[4]);
end_cmd()

begin_cmd("charwarp", 5)
repeat = (unsigned int) atoi(argv[4]);
charwrap(repeat, argv[2], argv[3]);
end_cmd()

begin_cmd("repcharp", 5)
repeat = (unsigned int) atoi(argv[4]);
repcharp(argv[2], argv[3], repeat);
end_cmd()

begin_cmd("coffset", 5)
coffset(argv[2], strtoul(argv[3], NULL, 0), strtoul(argv[4], NULL, 0));
end_cmd()

begin_cmd("dumpoffs", 5)
dumpoffs(argv[2], strtoul(argv[3], NULL, 0), strtoul(argv[4], NULL, 0));
end_cmd()

begin_cmd("bin2c", 5)
bin2c(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("filejoin", 5)
filejoin(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("mkpatch", 5)
mkpatch(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("charfile", 5)
repeat = (unsigned int) atoi(argv[3]);
charfile(argv[2], repeat, argv[4][0]);
end_cmd()

begin_cmd("strfile", 5)
repeat = (unsigned int) atoi(argv[3]);
strfile(argv[2], repeat, argv[4]);
end_cmd()

begin_cmd("tabspace", 5)
repeat = atoi(argv[2]);
tabspace(repeat, argv[3], argv[4]);
end_cmd()

begin_cmd("charaftr", 5)
charaftr(argv[2], argv[3], argv[4][0]);
end_cmd()

begin_cmd("charbefr", 5)
charbefr(argv[2], argv[3], argv[4][0]);
end_cmd()

begin_cmd("strachar", 5)
strachar(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("strbchar", 5)
strbchar(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("rstrach", 5)
rstrach(atoi(argv[2]), argv[3], argv[4]);
end_cmd()

begin_cmd("rstrbch", 5)
rstrbch(atoi(argv[2]), argv[3], argv[4]);
end_cmd()

begin_cmd("cpfroml", 5)
cpfroml(atoi(argv[2]), argv[3], argv[4]);
end_cmd()

begin_cmd("cptiline", 5)
cptiline(atoi(argv[2]), argv[3], argv[4]);
end_cmd()

begin_cmd("n2ch", 5)
n2ch(argv[2][0], argv[3], argv[4]);
end_cmd()

begin_cmd("n2str", 5)
n2str(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("weakrypt", 5)
weakrypt(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("sp2ce2sp", 5)
sp2ce2sp(argv[2][0], argv[3], argv[4]);
end_cmd()

begin_cmd("istreml", 5)
istreml(argv[2], argv[3], argv[4]);
end_cmd()

begin_cmd("removel", 5)
removel(argv[2], argv[3], strtoul(argv[4], NULL, 0));
end_cmd()




begin_cmd("printftx", 4)
printftx(argv[2], argv[3]);
end_cmd()

begin_cmd("lensorts", 4)
lensorts(argv[2], argv[3]);
end_cmd()

begin_cmd("lensortl", 4)
lensortl(argv[2], argv[3]);
end_cmd()

begin_cmd("find", 4)
find(argv[2], argv[3]);
end_cmd()

begin_cmd("findi", 4)
findi(argv[2], argv[3]);
end_cmd()

begin_cmd("cfind", 4)
cfind(argv[2], argv[3]);
end_cmd()

begin_cmd("cfindi", 4)
cfindi(argv[2], argv[3]);
end_cmd()

begin_cmd("showline", 4)
showline(argv[2], atoi(argv[3]));
end_cmd()

begin_cmd("cat_tail", 4)
cat_tail(argv[2], atoi(argv[3]));
end_cmd()

begin_cmd("cat_head", 4)
cat_head(argv[2], atoi(argv[3]));
end_cmd()

begin_cmd("getlinks", 4)
getlinks(argv[2], argv[3]);
end_cmd()

begin_cmd("f2upper", 4)
f2upper(argv[2], argv[3]);
end_cmd()

begin_cmd("f2lower", 4)
f2lower(argv[2], argv[3]);
end_cmd()

begin_cmd("fswpcase", 4)
fswpcase(argv[2], argv[3]);
end_cmd()

begin_cmd("downlist", 4)
downlist(argv[2], argv[3]);
end_cmd()

begin_cmd("hilist", 4)
hilist(argv[2], argv[3]);
end_cmd()

begin_cmd("rtcafter", 4)
rtcafter(argv[2], argv[3]);
end_cmd()

begin_cmd("rtcbefor", 4)
rtcbefor(argv[2], argv[3]);
end_cmd()

begin_cmd("rbcafter", 4)
rbcafter(argv[2], argv[3]);
end_cmd()

begin_cmd("rbcbefor", 4)
rbcbefor(argv[2], argv[3]);
end_cmd()

begin_cmd("numlines", 4)
numlines(argv[2], argv[3]);
end_cmd()

begin_cmd("file2dec", 4)
file2dec(argv[2], argv[3]);
end_cmd()

begin_cmd("file2hex", 4)
file2hex(argv[2], argv[3]);
end_cmd()

begin_cmd("file2bin", 4)
file2bin(argv[2], argv[3]);
end_cmd()

begin_cmd("wordline", 4)
wordline(argv[2], argv[3]);
end_cmd()

begin_cmd("8bit256", 4)
repeat = (unsigned int) atoi(argv[3]);
_8bit256(argv[2], repeat);
end_cmd()

begin_cmd("eng2arab", 4)
eng2arab(argv[2], argv[3]);
end_cmd()

begin_cmd("arab2eng", 4)
arab2eng(argv[2], argv[3]);
end_cmd()

begin_cmd("e2ahtml", 4)
e2ahtml(argv[2], argv[3]);
end_cmd()

begin_cmd("freverse", 4)
freverse(argv[2], argv[3]);
end_cmd()

begin_cmd("repcat", 4)
repeat = (unsigned int) atoi(argv[3]);
repcat(argv[2], repeat);
end_cmd()

begin_cmd("repcatpp", 4)
repeat = (unsigned int) atoi(argv[3]);
repcatpp(argv[2], repeat);
end_cmd()

begin_cmd("copyfile", 4)
copyfile(argv[2], argv[3]);
end_cmd()

begin_cmd("qpatch", 4)
qpatch(argv[2], argv[3]);
end_cmd()

begin_cmd("flipcopy", 4)
flipcopy(argv[2], argv[3]);
end_cmd()

begin_cmd("fillfile", 4)
fillfile(argv[2], argv[3][0]);
end_cmd()

begin_cmd("bin2text", 4)
bin2text(argv[2], argv[3]);
end_cmd()

begin_cmd("bin2hexi", 4)
bin2hexi(argv[2], argv[3]);
end_cmd()

begin_cmd("rndbfile", 4)
rndbfile(argv[2], strtoul(argv[3], NULL, 0));
end_cmd()

begin_cmd("rndtfile", 4)
rndtfile(argv[2], strtoul(argv[3], NULL, 0));
end_cmd()

begin_cmd("skipcat", 4)
skipcat(argv[2], argv[3]);
end_cmd()

begin_cmd("onlycat", 4)
onlycat(argv[2], argv[3]);
end_cmd()

begin_cmd("bigascif", 4)
bigascif(argv[2], argv[3]);
end_cmd()

begin_cmd("leetfile", 4)
leetfile(argv[2], argv[3]);
end_cmd()

begin_cmd("asc2ebc", 4)
asc2ebc(argv[2], argv[3]);
end_cmd()

begin_cmd("ebc2asc", 4)
ebc2asc(argv[2], argv[3]);
end_cmd()

begin_cmd("unix2dos", 4)
unix2dos(argv[2], argv[3]);
end_cmd()

begin_cmd("dos2unix", 4)
dos2unix(argv[2], argv[3]);
end_cmd()

begin_cmd("uuencode", 4)
uuencode(argv[2], argv[3]);
end_cmd()

begin_cmd("uudecode", 4)
uudecode(argv[2], argv[3]);
end_cmd()

begin_cmd("wordwrap", 4)
wordwrap(argv[2], argv[3]);
end_cmd()

begin_cmd("compare", 4)
compare(argv[2], argv[3]);
end_cmd()

begin_cmd("ccompare", 4)
ccompare(argv[2], argv[3]);
end_cmd()

begin_cmd("hmakerf", 4)
hmakerf(argv[2], argv[3]);
end_cmd()

begin_cmd("qcrypt", 4)
qcrypt(argv[2], argv[3]);
end_cmd()

begin_cmd("revlines", 4)
revlines(argv[2], argv[3]);
end_cmd()

begin_cmd("html2txt", 4)
html2txt(argv[2], argv[3]);
end_cmd()

begin_cmd("txt2html", 4)
txt2html(argv[2], argv[3]);
end_cmd()

begin_cmd("htmlfast", 4)
htmlfast(argv[2], argv[3]);
end_cmd()

begin_cmd("onlalnum", 4)
onlalnum(argv[2], argv[3]);
end_cmd()

begin_cmd("onlalpha", 4)
onlalpha(argv[2], argv[3]);
end_cmd()

begin_cmd("onlcntrl", 4)
onlcntrl(argv[2], argv[3]);
end_cmd()

begin_cmd("onldigit", 4)
onldigit(argv[2], argv[3]);
end_cmd()

begin_cmd("onlgraph", 4)
onlgraph(argv[2], argv[3]);
end_cmd()

begin_cmd("onllower", 4)
onllower(argv[2], argv[3]);
end_cmd()

begin_cmd("onlprint", 4)
onlprint(argv[2], argv[3]);
end_cmd()

begin_cmd("onlpunct", 4)
onlpunct(argv[2], argv[3]);
end_cmd()

begin_cmd("onlspace", 4)
onlspace(argv[2], argv[3]);
end_cmd()

begin_cmd("onlupper", 4)
onlupper(argv[2], argv[3]);
end_cmd()

begin_cmd("onlxdigt", 4)
onlxdigt(argv[2], argv[3]);
end_cmd()

begin_cmd("skpalnum", 4)
skpalnum(argv[2], argv[3]);
end_cmd()

begin_cmd("skpalpha", 4)
skpalpha(argv[2], argv[3]);
end_cmd()

begin_cmd("skpcntrl", 4)
skpcntrl(argv[2], argv[3]);
end_cmd()

begin_cmd("skpdigit", 4)
skpdigit(argv[2], argv[3]);
end_cmd()

begin_cmd("skpgraph", 4)
skpgraph(argv[2], argv[3]);
end_cmd()

begin_cmd("skplower", 4)
skplower(argv[2], argv[3]);
end_cmd()

begin_cmd("skpprint", 4)
skpprint(argv[2], argv[3]);
end_cmd()

begin_cmd("skppunct", 4)
skppunct(argv[2], argv[3]);
end_cmd()

begin_cmd("skpspace", 4)
skpspace(argv[2], argv[3]);
end_cmd()

begin_cmd("skpupper", 4)
skpupper(argv[2], argv[3]);
end_cmd()

begin_cmd("skpxdigt", 4)
skpxdigt(argv[2], argv[3]);
end_cmd()

begin_cmd("ftothe", 4)
ftothe(argv[2], argv[3]);
end_cmd()

begin_cmd("blanka", 4)
blanka(argv[2], argv[3]);
end_cmd()

begin_cmd("unblanka", 4)
unblanka(argv[2], argv[3]);
end_cmd()

begin_cmd("najirle", 4)
najirle(argv[2], argv[3]);
end_cmd()

begin_cmd("unajirle", 4)
unajirle(argv[2], argv[3]);
end_cmd()


begin_cmd("gplus", 4)
a = atoi(argv[2]);
b = atoi(argv[3]);
gplus(a, b);
end_cmd()


begin_cmd("gminus", 4)
a = atoi(argv[2]);
b = atoi(argv[3]);
gminus(a, b);
end_cmd()


begin_cmd("gtimes", 4)
a = atoi(argv[2]);
b = atoi(argv[3]);
gtimes(a, b);
end_cmd()


begin_cmd("gdivide", 4)
gdivide_a = atof(argv[2]);
gdivide_b = atof(argv[3]);
gdivide(gdivide_a, gdivide_b);
end_cmd()


begin_cmd("bytsplit", 4)
bytsplit(argv[2], atol(argv[3]));
end_cmd()

begin_cmd("kbsplit", 4)
kbsplit(argv[2], atol(argv[3]));
end_cmd()

begin_cmd("mbsplit", 4)
mbsplit(argv[2], atol(argv[3]));
end_cmd()

begin_cmd("gbsplit", 4)
gbsplit(argv[2], atol(argv[3]));
end_cmd()

begin_cmd("mjoin", 4)
mjoin(argv[2], argv[3]);
end_cmd()


begin_cmd("listdigt", 4)
listdigt(atoi(argv[2]), argv[3]);
end_cmd()

begin_cmd("listlowr", 4)
listlowr(atoi(argv[2]), argv[3]);
end_cmd()

begin_cmd("listprnt", 4)
listprnt(atoi(argv[2]), argv[3]);
end_cmd()

begin_cmd("listuppr", 4)
listuppr(atoi(argv[2]), argv[3]);
end_cmd()

begin_cmd("charsort", 4)
charsort(argv[2], argv[3]);
end_cmd()

begin_cmd("sp2re2sp", 4)
sp2re2sp(argv[2], argv[3]);
end_cmd()









begin_cmd("lcvfiles", 3)
lcvfiles(argv[2]);
end_cmd()

begin_cmd("rcvfiles", 3)
rcvfiles(argv[2]);
end_cmd()


begin_cmd("mp3tagnf", 3)
mp3info(argv[2]);
end_cmd()

begin_cmd("catrandl", 3)
catrandl(argv[2]);
end_cmd()

begin_cmd("leetstr", 3)
printf("\n\n");
leetstr(argv[2]);
printf("\n\n");
end_cmd()

begin_cmd("lcharvar", 3)
lcharvar(argv[2]);
end_cmd()

begin_cmd("rcharvar", 3)
rcharvar(argv[2]);
end_cmd()

begin_cmd("hexicat", 3)
hexicat(argv[2]);
end_cmd()

begin_cmd("rndffill", 3)
rndffill(argv[2]);
end_cmd()

begin_cmd("zerokill", 3)
zerokill(argv[2]);
end_cmd()

begin_cmd("randkill", 3)
randkill(argv[2]);
end_cmd()

begin_cmd("najisum", 3)
najisum(argv[2]);
end_cmd()


begin_cmd("rndbsout", 3)
rndbsout(strtoul(argv[2], NULL, 0));
end_cmd()

begin_cmd("rndtsout", 3)
rndtsout(strtoul(argv[2], NULL, 0));
end_cmd()

begin_cmd("patch", 3)
patch(argv[2]);
end_cmd()

begin_cmd("revcat", 3)
revcat(argv[2]);
end_cmd()

begin_cmd("copyself", 3)
copyfile(argv[0], argv[2]);
end_cmd()

begin_cmd("bigascii", 3)
bigascii(argv[2]);
end_cmd()

begin_cmd("hmaker", 3)
hmaker(argv[2]);
end_cmd()

begin_cmd("wrdcount", 3)
printf("\n\n%i\n\n", wrdcount(argv[2]));
end_cmd()

begin_cmd("addim", 3)
addim(atoi(argv[2]));
end_cmd()

begin_cmd("allfiles", 3)

fprintf(stderr, 
"\n"
"NOTE: On most systems you can stop with Ctrl+C\n"
"WARNING: This will make a lot of files.\n"
"Are you sure? type YES to continue\n"
"or anything else to quit.\n"
);
safegets(are_you_sure, 80);
            
if (!strcmp(are_you_sure, "YES"))
allfiles(atol(argv[2]));
end_cmd();        

begin_cmd("tothe", 3)
tothe(argv[2]);
end_cmd()

begin_cmd("vowelwrd", 3)
vowelwrd(argv[2]);
end_cmd()

begin_cmd("gigabyte", 3)
gigabyte(strtoul(argv[2], NULL, 0));
end_cmd()

begin_cmd("sort", 3)
sort(argv[2]);
end_cmd()

begin_cmd("sortlast", 3)
sortlast(argv[2]);
end_cmd()

begin_cmd("lineback", 3)
lineback(argv[2]);
end_cmd()

begin_cmd("longline", 3)
longline(argv[2]);
end_cmd()

begin_cmd("howline", 3)
howline(argv[2]);
end_cmd()

begin_cmd("rndlines", 3)
rndlines(argv[2]);
end_cmd()

begin_cmd("spyramid", 3)
spyramid(argv[2]);
end_cmd()


    } /* if (argc >= 2) */

return 0;         
}
Exemple #12
0
int
main(int argc, char **argv)
{
    int onlydir, dodir, dolink, dorelsymlink, dotimes, opt, len, lplen, tdlen, bnlen, exists, fromfd, tofd, cc, wc;
    mode_t mode = 0755;
    char *linkprefix, *owner, *group, *cp, *cwd, *todir, *toname, *name, *base, *linkname, *bp, buf[BUFSIZ];
    uid_t uid;
    gid_t gid;
    struct stat sb, tosb, fromsb;
    struct utimbuf utb;

    program = argv[0];
    cwd = linkname = linkprefix = owner = group = 0;
    onlydir = dodir = dolink = dorelsymlink = dotimes = lplen = 0;

    while ((opt = getopt(argc, argv, "C:DdlL:Rm:o:g:t")) != EOF) {
	switch (opt) {
	  case 'C':
	    cwd = optarg;
	    break;
	  case 'D':
	    onlydir = 1;
	    break;
	  case 'd':
	    dodir = 1;
	    break;
	  case 'l':
	    dolink = 1;
	    break;
	  case 'L':
	    linkprefix = optarg;
	    lplen = strlen(linkprefix);
	    dolink = 1;
	    break;
     case 'R':
	    dolink = dorelsymlink = 1;
	    break;
	  case 'm':
	    mode = strtoul(optarg, &cp, 8);
	    if (mode == 0 && cp == optarg)
		usage();
	    break;
	  case 'o':
	    owner = optarg;
	    break;
	  case 'g':
	    group = optarg;
	    break;
	  case 't':
	    dotimes = 1;
	    break;
	  default:
	    usage();
	}
    }

    argc -= optind;
    argv += optind;
    if (argc < 2 - onlydir)
	usage();

    todir = argv[argc-1];
    if ((stat(todir, &sb) < 0 || !S_ISDIR(sb.st_mode)) &&
	mkdirs(todir, 0777) < 0) {
	fail("cannot make directory %s", todir);
    }
    if (onlydir)
	return 0;

    if (!cwd) {
#ifndef NEEDS_GETCWD
#ifndef GETCWD_CANT_MALLOC
	cwd = getcwd(0, PATH_MAX);
#else
	cwd = malloc(PATH_MAX + 1);
	cwd = getcwd(cwd, PATH_MAX);
#endif
#else
	cwd = malloc(PATH_MAX + 1);
	cwd = getwd(cwd);
#endif
    }

    xchdir(todir);
#ifndef NEEDS_GETCWD
#ifndef GETCWD_CANT_MALLOC
    todir = getcwd(0, PATH_MAX);
#else
    todir = malloc(PATH_MAX + 1);
    todir = getcwd(todir, PATH_MAX);
#endif
#else
    todir = malloc(PATH_MAX + 1);
    todir = getwd(todir);
#endif
    tdlen = strlen(todir);
    xchdir(cwd);
    tdlen = strlen(todir);

    uid = owner ? touid(owner) : (uid_t)(-1);
    gid = group ? togid(group) : (gid_t)(-1);

    while (--argc > 0) {
	name = *argv++;
	len = strlen(name);
	base = xbasename(name);
	bnlen = strlen(base);
	toname = xmalloc((unsigned int)(tdlen + 1 + bnlen + 1));
	sprintf(toname, "%s%s%s", todir, _DIRECTORY_SEPARATOR, base);
	exists = (lstat(toname, &tosb) == 0);

	if (dodir) {
	    /* -d means create a directory, always */
	    if (exists && !S_ISDIR(tosb.st_mode)) {
		(void) unlink(toname);
		exists = 0;
	    }
	    if (!exists && mkdir(toname, mode) < 0)
		fail("cannot make directory %s", toname);
	    if ((owner || group) && chown(toname, uid, gid) < 0)
		fail("cannot change owner of %s", toname);
	} else if (dolink) {
            if (access(name, R_OK) != 0) {
                fail("cannot access %s", name);
            }
	    if (*name == '/') {
		/* source is absolute pathname, link to it directly */
		linkname = 0;
	    } else {
		if (linkprefix) {
		    /* -L implies -l and prefixes names with a $cwd arg. */
		    len += lplen + 1;
		    linkname = xmalloc((unsigned int)(len + 1));
		    sprintf(linkname, "%s/%s", linkprefix, name);
		} else if (dorelsymlink) {
		    /* Symlink the relative path from todir to source name. */
		    linkname = xmalloc(PATH_MAX);

		    if (*todir == '/') {
			/* todir is absolute: skip over common prefix. */
			lplen = relatepaths(todir, cwd, linkname);
			strcpy(linkname + lplen, name);
		    } else {
			/* todir is named by a relative path: reverse it. */
			reversepath(todir, name, len, linkname);
			xchdir(cwd);
		    }

		    len = strlen(linkname);
		}
		name = linkname;
	    }

	    /* Check for a pre-existing symlink with identical content. */
	    if ((exists && (!S_ISLNK(tosb.st_mode) ||
						readlink(toname, buf, sizeof buf) != len ||
						strncmp(buf, name, (unsigned int)len) != 0)) || 
			((stat(name, &fromsb) == 0) && 
			 (fromsb.st_mtime > tosb.st_mtime))) {
		(void) (S_ISDIR(tosb.st_mode) ? rmdir : unlink)(toname);
		exists = 0;
	    }
	    if (!exists && symlink(name, toname) < 0)
		fail("cannot make symbolic link %s", toname);
#ifdef HAVE_LCHOWN
	    if ((owner || group) && lchown(toname, uid, gid) < 0)
		fail("cannot change owner of %s", toname);
#endif

	    if (linkname) {
		free(linkname);
		linkname = 0;
	    }
	} else {
	    /* Copy from name to toname, which might be the same file. */
      if( stat(name, &sb) == 0 && S_IFDIR & sb.st_mode )
      {
        /* then is directory: must explicitly create destination dir  */
        /*  and manually copy files over                              */
        copydir( name, todir, mode, group, owner, dotimes, uid, gid );
      } 
      else
      {
        copyfile(name, toname, mode, group, owner, dotimes, uid, gid);
      }
    }

	free(toname);
    }

    free(cwd);
    free(todir);
    return 0;
}
Exemple #13
0
void create_sliced_system(boost::filesystem::path input_file, boost::filesystem::path output_file,
                          vec_mp * linears, int num_to_add,
                          const WitnessSet & W)
{
#ifdef functionentry_output
	std::cout << "create_sliced_system" << std::endl;
#endif
	
	
	
	
	if (W.num_var_names()==0) {
		std::cout << "trying to create a sliced system, but witness set does not have the variable names." << std::endl;
		deliberate_segfault();
	}
	int *declarations = NULL;
	
	partition_parse(&declarations, input_file, "func_input", "config", 0); // the 0 means not self conjugate.
	free(declarations);
	
	FILE *OUT = safe_fopen_write(output_file);
	FILE *IN = safe_fopen_read("func_input");
	
	
	
	
	fprintf(OUT,"INPUT\n\n");
	copyfile(IN,OUT);
	fclose(IN);
	
	std::vector< int > indicators;
	for (int ii=0; ii<num_to_add; ii++) {
		indicators.push_back(rand());
	}
	
	for (int ii=0; ii<num_to_add; ii++) {
		std::stringstream linname;
		linname << "supp_lin_" << indicators[ii];
		write_vector_as_constants(linears[ii], linname.str(), OUT);
		
		linname.clear();  linname.str("");
	}
	
	for (int ii=0; ii<num_to_add; ii++) {
		fprintf(OUT,"function supp_lin_%d;\n",indicators[ii]);
	}
	for (int ii=0; ii<num_to_add; ii++) {
		fprintf(OUT,"supp_lin_%d = supp_lin_%d_1",indicators[ii],indicators[ii]);
		for (int jj=1; jj<W.num_variables(); jj++) {
			fprintf(OUT," + %s*supp_lin_%d_%d",W.name(jj).c_str(), indicators[ii],jj+1);
		}
		fprintf(OUT, ";\n\n");
	}
	fprintf(OUT,"END;\n\n\n\n");
	
    
    for (unsigned int ii=0; ii<W.num_patches(); ii++) {
		std::stringstream linname;
		linname << "patch_" << ii;
		write_vector_as_constants(W.patch(ii), linname.str(), OUT);
		linname.clear();  linname.str("");
	}
    
	fclose(OUT);
	
	
	
	
}
Exemple #14
0
static ssize_t uv__fs_copyfile(uv_fs_t* req) {
#if defined(__APPLE__) && !TARGET_OS_IPHONE
  /* On macOS, use the native copyfile(3). */
  copyfile_flags_t flags;

  flags = COPYFILE_ALL;

  if (req->flags & UV_FS_COPYFILE_EXCL)
    flags |= COPYFILE_EXCL;

  return copyfile(req->path, req->new_path, NULL, flags);
#else
  uv_fs_t fs_req;
  uv_file srcfd;
  uv_file dstfd;
  struct stat statsbuf;
  int dst_flags;
  int result;
  int err;
  size_t bytes_to_send;
  int64_t in_offset;

  dstfd = -1;
  err = 0;

  /* Open the source file. */
  srcfd = uv_fs_open(NULL, &fs_req, req->path, O_RDONLY, 0, NULL);
  uv_fs_req_cleanup(&fs_req);

  if (srcfd < 0)
    return srcfd;

  /* Get the source file's mode. */
  if (fstat(srcfd, &statsbuf)) {
    err = -errno;
    goto out;
  }

  dst_flags = O_WRONLY | O_CREAT | O_TRUNC;

  if (req->flags & UV_FS_COPYFILE_EXCL)
    dst_flags |= O_EXCL;

  /* Open the destination file. */
  dstfd = uv_fs_open(NULL,
                     &fs_req,
                     req->new_path,
                     dst_flags,
                     statsbuf.st_mode,
                     NULL);
  uv_fs_req_cleanup(&fs_req);

  if (dstfd < 0) {
    err = dstfd;
    goto out;
  }

  if (fchmod(dstfd, statsbuf.st_mode) == -1) {
    err = -errno;
    goto out;
  }

  bytes_to_send = statsbuf.st_size;
  in_offset = 0;
  while (bytes_to_send != 0) {
    err = uv_fs_sendfile(NULL,
                         &fs_req,
                         dstfd,
                         srcfd,
                         in_offset,
                         bytes_to_send,
                         NULL);
    uv_fs_req_cleanup(&fs_req);
    if (err < 0)
      break;
    bytes_to_send -= fs_req.result;
    in_offset += fs_req.result;
  }

out:
  if (err < 0)
    result = err;
  else
    result = 0;

  /* Close the source file. */
  err = uv__close_nocheckstdio(srcfd);

  /* Don't overwrite any existing errors. */
  if (err != 0 && result == 0)
    result = err;

  /* Close the destination file if it is open. */
  if (dstfd >= 0) {
    err = uv__close_nocheckstdio(dstfd);

    /* Don't overwrite any existing errors. */
    if (err != 0 && result == 0)
      result = err;

    /* Remove the destination file if something went wrong. */
    if (result != 0) {
      uv_fs_unlink(NULL, &fs_req, req->new_path, NULL);
      /* Ignore the unlink return value, as an error already happened. */
      uv_fs_req_cleanup(&fs_req);
    }
  }

  return result;
#endif
}
void dochallenge() {
  string inpfile = CONFIG->GetTmpfile_path() + tmpnam();
  retbott.Settype(CHALLENGE_REPORT);
  datagen = NULL;
  retbott.Setcha_id(bott->Getcha_id());
  if (set_data(inpfile)) {
    //failtogen
    retbott.Setcha_result("Challenge Error");
    retbott.Setcha_detail("Generator Failed: " + datagen->Getresult());
    if (datagen != NULL) delete datagen;
  } else {
    string check_result_filename = CONFIG->GetTmpfile_path() + tmpnam();
    int check_stat = check_data(bott->Getpid(), inpfile, check_result_filename);
    if (check_stat == 1) {
      retbott.Setcha_result("Challenge Error");
      retbott.Setcha_detail("Data Check Failed: " + checker->Getresult() +
      "\nChecker Output Detail:\n--------------------------\n" +
      Loadallfromfile(check_result_filename) +
      "\n--------------------------\nInvalid Data!!");
    } else if (check_stat == -1) {
      retbott.Setcha_result("Challenge Error");
      retbott.Setcha_detail("No Config File For Problem: " +
      Inttostring(bott->Getpid()));
    } else {
      stdprogram = new Program;
      int stdres = run_program(stdprogram, inpfile,
                               Loadallfromfile(problem->Getsolution_filename()),
                               problem->Getsolution_language());
      while (stdprogram->Getresult() == "Compile Error") {
        stdprogram->Setcompiled(false);
        stdprogram->Run();
        if (stdprogram->Getresult() != "Normal") stdres = 1;
        else stdres = 0;
      }
      usrprogram = new Program;
      int usrres = run_program(usrprogram, inpfile, bott->Getsrc(),
                               bott->Getlanguage());
      while (usrprogram->Getresult() == "Compile Error") {
        usrprogram->Setcompiled(false);
        usrprogram->Run();
        if (usrprogram->Getresult() != "Normal") usrres = 1;
        else usrres = 0;
      }
      if (stdres != 0) {
        retbott.Setcha_result("Challenge Error");
        retbott.Setcha_detail(
            "Standard Program Failed: " + stdprogram->Getresult());
      } else if (usrres != 0) {
        retbott.Setcha_result("Challenge Success");
        string newf = "cha_" + tmpnam();
        copyfile(
            stdprogram->Getin_filename(),
            "testdata/" + Inttostring(bott->Getpid()) + "/" + newf + ".in");
        copyfile(
            stdprogram->Getout_filename(),
            "testdata/" + Inttostring(bott->Getpid()) + "/" + newf + ".out");
        retbott.Setcha_detail("Standard: " + stdprogram->Getresult() +
            "  User: "******"Challenge Failed");
          retbott.Setcha_detail("Same Result.");
        } else if (cres == PE_STATUS) {
          retbott.Setcha_result("Challenge Success");
          retbott.Setcha_detail(
              "Presentation Error.\nComparator Output Detail:"
              "\n--------------------------\n" + cmp->Getdetail() +
              "\n--------------------------");
          string newf = "cha_" + tmpnam();
          copyfile(
              stdprogram->Getin_filename(),
              "testdata/" + Inttostring(bott->Getpid()) + "/" + newf + ".in");
          copyfile(
              stdprogram->Getout_filename(),
              "testdata/" + Inttostring(bott->Getpid()) + "/" + newf + ".out");
        } else if (cres == JE_STATUS) {
          retbott.Setcha_result("Challenge Failed");
          retbott.Setcha_detail("No SPJ.");
        } else {
          retbott.Setcha_result("Challenge Success");
          string newf = "cha_" + tmpnam();
          copyfile(
              stdprogram->Getin_filename(),
              "testdata/" + Inttostring(bott->Getpid()) + "/" + newf + ".in");
          copyfile(
              stdprogram->Getout_filename(),
              "testdata/" + Inttostring(bott->Getpid()) + "/" + newf + ".out");
          retbott.Setcha_detail(
              "Wrong Answer.\nComparator Output Detail:"
              "\n--------------------------\n" + cmp->Getdetail() +
              "\n--------------------------");
        }
        delete cmp;
      }
      delete stdprogram;
      delete usrprogram;
    }
    delete problem;
    delete checker;
    if (datagen != NULL) delete datagen;
  }
  retbott.Setout_filename("cha_results/" + Inttostring(retbott.Getcha_id()));
  retbott.toFile();
  send_result(retbott.Getout_filename());
}
Exemple #16
0
/*
 * Like copyfile, but takes a position for file f.  Returns with
 * f and g pointing just past the copied data.
 */
int copyfilepos(FILE * f, FILE * g, word32 longcount, word32 fpos)
{
    fseek(f, fpos, SEEK_SET);
    return copyfile(f, g, longcount);
}
Exemple #17
0
void filecache_update(TARGET *t)
{
	MD5SUM blobmd5sum;
	int haveblobmd5sum = 0;
	const char *cachedname;
	const char *blobname;
	int cacheerror;

	if (!t->filecache_generate)
		return;

	/* If the buildmd5sum is empty, then the file doesn't exist. */
	cacheerror = ismd5empty(t->buildmd5sum);
	if (cacheerror)
		return;

	haveblobmd5sum = 0;
	cachedname = filecache_getfilename(t, t->buildmd5sum, NULL);
	if (!cachedname)
		return;

	/* Search for the appropriate .link file that matches the target. */
	haveblobmd5sum = filecache_findlink(cachedname, blobmd5sum);

	/* If we weren't able to determine the target md5sum, do it now. */
	if (!haveblobmd5sum)
	{
#ifdef OPT_BUILTIN_LUA_SUPPORT_EXT
		LIST *md5callback;

		pushsettings( t->settings );
		md5callback = var_get( "MD5CALLBACK" );
		popsettings( t->settings );

		if ( md5callback )
		{
			luahelper_md5callback(t->boundname, blobmd5sum, md5callback->string);
		}
		else
		{
#endif
			md5file(t->boundname, blobmd5sum);
#ifdef OPT_BUILTIN_LUA_SUPPORT_EXT
		}
#endif
		memcpy(t->contentmd5sum, blobmd5sum, sizeof(MD5SUM));
		if (ismd5empty(t->contentmd5sum))
			return;
	}

	{
		/* Is the blob already there? */
		time_t blobtime;
		blobname = filecache_getfilename(t, blobmd5sum, ".blob");
		if (file_time(blobname, &blobtime) == -1)
		{
			time_t blobpartialtime;
			const char *blobpartialname;

			if(DEBUG_MD5HASH)
				printf("Caching %s as %s\n", t->name, cachedname);
			else
				printf("Caching %s\n", t->name);

			/* Write the new .blob to the cache. */
			blobpartialname = filecache_getfilename(t, blobmd5sum, ".blob.partial");
			if (file_time(blobpartialname, &blobpartialtime) == -1)
			{
				if (copyfile(blobpartialname, t->boundname, &blobmd5sum) == 0  ||
					rename(blobpartialname, blobname) != 0)
				{
					printf("** Unable to write %s to cache.\n", t->name, cachedname);
					filecache_disable(t);
					return;
				}
			}
		}
	}

	/* Write the new .link file to the cache. */
	{
		FILE *file;
		BUFFER linknamebuff;
		buffer_init(&linknamebuff);
		buffer_addstring(&linknamebuff, cachedname, strlen(cachedname));
		buffer_addchar(&linknamebuff, '-');
		buffer_addstring(&linknamebuff, md5tostring(blobmd5sum), 32);
		buffer_addstring(&linknamebuff, ".link", 5);
		buffer_addchar(&linknamebuff, 0);

		file_mkdir(buffer_ptr(&linknamebuff));
		file = fopen(buffer_ptr(&linknamebuff), "wb");
		if (file)
		{
			write_md5sum(file, blobmd5sum);
			write_string(file, t->name);
			fclose(file);
		}

		buffer_free(&linknamebuff);
	}
}
Exemple #18
0
/*
 * Like rename() but will try to copy the file if the rename fails.
 * This is because under OS's with multiple physical volumes if the
 * source and destination are on different volumes the rename will fail
 */
int rename2(char *srcFile, char *destFile)
{
    FILE *f, *g;
#ifdef MACTC5
	int copy=-1;
#endif
    int status = 0;
    long fileLength;

#ifdef MACTC5
	copy=MoveRename(srcFile,destFile);
if (copy)
#else
#if defined(VMS) || defined(C370)
    if (rename(srcFile, destFile) != 0)
#else
    if (rename(srcFile, destFile) == -1)
#endif
#endif
    {
	/* Rename failed, try a copy */
	if (((f = fopen(srcFile, FOPRBIN)) == NULL) ||
	    ((g = fopen(destFile, FOPWBIN)) == NULL))
	    /* Can't open files */
	    return -1;

#ifdef MACTC5
		{
		FInfo finderInfo;
		c2pstr(srcFile);
		c2pstr(destFile);
		if(GetFInfo((uchar *)srcFile,0,&finderInfo)==0)
			SetFInfo((uchar *)destFile,0,&finderInfo);
		p2cstr((uchar *)srcFile);
		p2cstr((uchar *)destFile);
		}
#endif

	/* Get file length and copy it */
	fseek(f, 0L, SEEK_END);
	fileLength = ftell(f);
	rewind(f);
	status = copyfile(f, g, fileLength);
	if (write_error(g))
	    status = -1;

	/* Zap source file if the copy went OK, otherwise zap the (possibly
	   incomplete) destination file */
	if (status >= 0) {
	    wipeout(f);		/* Zap source file */
	    fclose(f);
	    remove(srcFile);
	    fclose(g);
	} else {
	    if (is_regular_file(destFile)) {
		wipeout(g);	/* Zap destination file */
		fclose(g);
		remove(destFile);
	    } else {
		fclose(g);
	    }
	    fclose(f);
	}
    }
    return status;
}
int
main(int argc, char **argv)
{
	const char *av = NULL;
	int func_total, file_total;
        char arg_dbpath[MAXPATHLEN];
	const char *index = NULL;
	int optchar;
        int option_index = 0;
	STATISTICS_TIME *tim;

	arg_dbpath[0] = 0;
	basic_check();
	/*
	 * Setup GTAGSCONF and GTAGSLABEL environment variable
	 * according to the --gtagsconf and --gtagslabel option.
	 */
	preparse_options(argc, argv);
	/*
	 * Load configuration values.
	 */
	if (!vgetcwd(cwdpath, sizeof(cwdpath)))
		die("cannot get current directory.");
	openconf(cwdpath);
	configuration();
	/*
	 * setup_langmap() is needed to use decide_lang().
	 */
	setup_langmap(langmap);
	save_environment(argc, argv);
	/*
	 * insert htags_options at the head of argv.
	 */
	setenv_from_config();
	{
		char *env = getenv("HTAGS_OPTIONS");
		if (env && *env)
			argv = prepend_options(&argc, argv, env);
	}
	while ((optchar = getopt_long(argc, argv, "acd:DfFghIm:nNoqst:Tvwx", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			/* already flags set */
			break;
		case OPT_AUTO_COMPLETION:
			auto_completion = 1;
			if (optarg) {
				if (atoi(optarg) > 0)
					auto_completion_limit = optarg;
				else
					die("The option value of --auto-completion must be numeric.");
			}
			break;
		case OPT_CFLOW:
			call_file = optarg;
			break;
		case OPT_CALL_TREE:
			call_file = optarg;
			break;
		case OPT_CALLEE_TREE:
			callee_file = optarg;
			break;
		case OPT_CVSWEB:
			cvsweb_url = optarg;
			break;
		case OPT_CVSWEB_CVSROOT:
			cvsweb_cvsroot = optarg;
			break;
		case OPT_GTAGSCONF:
		case OPT_GTAGSLABEL:
			/* These options are already parsed in preparse_options() */
			break;
		case OPT_INSERT_FOOTER:
			insert_footer = optarg;
			break;
		case OPT_INSERT_HEADER:
			insert_header = optarg;
			break;
		case OPT_HTML_HEADER:
			{
				STATIC_STRBUF(sb);
				if (!test("r", optarg))
					die("file '%s' not found.", optarg);
				strbuf_clear(sb);
				loadfile(optarg, sb);
				html_header = strbuf_value(sb);
			}
			break;
		case OPT_ITEM_ORDER:
			item_order = optarg;
			break;
		case OPT_TABS:
			if (atoi(optarg) > 0)
				tabs = atoi(optarg);
			else
				die("--tabs option requires numeric value.");
                        break;
		case OPT_NCOL:
			if (atoi(optarg) > 0)
				ncol = atoi(optarg);
			else
				die("--ncol option requires numeric value.");
                        break;
		case OPT_TREE_VIEW:
			tree_view = 1;
			if (optarg)
				tree_view_type = optarg;
			break;
                case 'a':
                        aflag++;
                        break;
                case 'd':
			strlimcpy(arg_dbpath, optarg, sizeof(arg_dbpath));
                        break;
                case 'D':
			dynamic = 1;
                        break;
                case 'f':
                        fflag++;
                        break;
                case 'F':
                        Fflag++;
                        break;
                case 'g':
                        gflag++;
                        break;
                case 'h':
			definition_header = AFTER_HEADER;
			if (optarg) {
				if (!strcmp(optarg, "before"))
					definition_header = BEFORE_HEADER;
				else if (!strcmp(optarg, "right"))
					definition_header = RIGHT_HEADER;
				else if (!strcmp(optarg, "after"))
					definition_header = AFTER_HEADER;
				else
					die("The option value of --func-header must be one of 'before', 'right' and 'after'.");
			}
                        break;
                case 'I':
                        Iflag++;
                        break;
                case 'm':
			main_func = optarg;
                        break;
                case 'n':
                        nflag++;
			if (optarg) {
				if (atoi(optarg) > 0)
					ncol = atoi(optarg);
				else
					die("The option value of --line-number must be numeric.");
			}
                        break;
                case 'o':
			other_files = 1;
                        break;
                case 's':
			symbol = 1;
                        break;
                case 'T':
			table_flist = 1;
			if (optarg) {
				if (atoi(optarg) > 0)
					flist_fields = atoi(optarg);
				else
					die("The option value of the --table-flist must be numeric.");
			}
                        break;
                case 't':
			title = optarg;
                        break;
                case 'q':
                        qflag++;
			setquiet();
                        break;
                case 'v':
                        vflag++;
			setverbose();
                        break;
                case 'w':
                        wflag++;
                        break;
                default:
                        usage();
                        break;
		}
	}
	/*
	 * Leaving everything to htags.
	 * Htags selects popular options for you.
	 */
	if (suggest2)
		suggest = 1;
	if (suggest) {
		int gtags_not_found = 0;
		char dbpath[MAXPATHLEN];

		aflag = Iflag = nflag = vflag = 1;
		setverbose();
		definition_header = AFTER_HEADER;
		other_files = symbol = show_position = table_flist = fixed_guide = 1;
		if (arg_dbpath[0]) {
			if (!test("f", makepath(arg_dbpath, dbname(GTAGS), NULL)))
				gtags_not_found = 1;
		} else if (gtagsexist(".", dbpath, sizeof(dbpath), 0) == 0) {
			gtags_not_found = 1;
		}
		if (gtags_not_found)
			gflag = 1;
	}
	if (suggest2) {
		Fflag = 1;				/* uses frame */
		fflag = dynamic = 1;			/* needs a HTTP server */
		auto_completion = tree_view = 1;	/* needs javascript */
	}
	if (call_file && !test("fr", call_file))
		die("cflow file not found. '%s'", call_file);
	if (callee_file && !test("fr", callee_file))
		die("cflow file not found. '%s'", callee_file);
	if (insert_header && !test("fr", insert_header))
		die("page header file '%s' not found.", insert_header);
	if (insert_footer && !test("fr", insert_footer))
		die("page footer file '%s' not found.", insert_footer);
	if (!fflag)
		auto_completion = 0;
        argc -= optind;
        argv += optind;
        if (!av)
                av = (argc > 0) ? *argv : NULL;

	if (debug)
		setdebug();
	settabs(tabs);					/* setup tab skip */
        if (qflag) {
                setquiet();
		vflag = 0;
	}
        if (show_version)
                version(av, vflag);
        if (show_help)
                help();
	/*
	 * Invokes gtags beforehand.
	 */
	if (gflag) {
		STRBUF *sb = strbuf_open(0);

		strbuf_puts(sb, gtags_path);
		if (vflag)
			strbuf_puts(sb, " -v");
		if (wflag)
			strbuf_puts(sb, " -w");
		if (suggest2 && enable_idutils && usable("mkid"))
			strbuf_puts(sb, " -I");
		if (arg_dbpath[0]) {
			strbuf_putc(sb, ' ');
			strbuf_puts(sb, arg_dbpath);
		}
		if (system(strbuf_value(sb)))
			die("cannot execute gtags(1) command.");
		strbuf_close(sb);
	}
	/*
	 * get dbpath.
	 */
	if (arg_dbpath[0]) {
		strlimcpy(dbpath, arg_dbpath, sizeof(dbpath));
	} else {
		int status = setupdbpath(0);
		if (status < 0)
			die_with_code(-status, "%s", gtags_dbpath_error);
		strlimcpy(dbpath, get_dbpath(), sizeof(dbpath));
	}
	if (!title) {
		char *p = strrchr(cwdpath, sep);
		title = p ? p + 1 : cwdpath;
	}
	if (cvsweb_url && test("d", "CVS"))
		use_cvs_module = 1;
	/*
	 * decide directory in which we make hypertext.
	 */
	if (av) {
		char realpath[MAXPATHLEN];

		if (!test("dw", av))
			die("'%s' is not writable directory.", av);
		if (chdir(av) < 0)
			die("directory '%s' not found.", av);
		if (!vgetcwd(realpath, sizeof(realpath)))
			die("cannot get current directory");
		if (chdir(cwdpath) < 0)
			die("cannot return to original directory.");
		snprintf(distpath, sizeof(distpath), "%s/HTML", realpath);
	} else {
		snprintf(distpath, sizeof(distpath), "%s/HTML", cwdpath);
	}
	/*
	 * Existence check of tag files.
	 */
	{
		int i;
		const char *path;
		GTOP *gtop;

		for (i = GPATH; i < GTAGLIM; i++) {
			path = makepath(dbpath, dbname(i), NULL);
			gtags_exist[i] = test("fr", path);
		}
		/*
		 * Real GRTAGS includes virtual GSYMS.
		 */
		gtags_exist[GSYMS] = symbol ? 1 : 0;
		if (!gtags_exist[GPATH] || !gtags_exist[GTAGS] || !gtags_exist[GRTAGS])
			die("GPATH, GTAGS and/or GRTAGS not found. Please reexecute htags with the -g option.");
		/*
		 * version check.
		 * Do nothing, but the version of tag file will be checked.
		 */
		gtop = gtags_open(dbpath, cwdpath, GTAGS, GTAGS_READ, 0);
		gtags_close(gtop);
		/*
		 * Check whether GRTAGS is empty.
		 */
		gtop = gtags_open(dbpath, cwdpath, GRTAGS, GTAGS_READ, 0);
		if (gtags_first(gtop, NULL, 0) == NULL)
			grtags_is_empty = 1;
		gtags_close(gtop);
	}
	/*
	 * make dbpath absolute.
	 */
	{
		char buf[MAXPATHLEN];
		if (realpath(dbpath, buf) == NULL)
			die("cannot get realpath of dbpath.");
		strlimcpy(dbpath, buf, sizeof(dbpath));
	}
	/*
	 * The older version (4.8.7 or former) of GPATH doesn't have files
         * other than source file. The oflag requires new version of GPATH.
	 */
	if (other_files) {
		GFIND *gp = gfind_open(dbpath, NULL, 0, 0);
		if (gp->version < 2)
			die("GPATH is old format. Please remake it by invoking gtags(1).");
		gfind_close(gp);
	}
	/*
	 * for global(1) and gtags(1).
	 */
	set_env("GTAGSROOT", cwdpath);
	set_env("GTAGSDBPATH", dbpath);
	set_env("GTAGSLIBPATH", "");
	/*------------------------------------------------------------------
	 * MAKE FILES
	 *------------------------------------------------------------------
	 *       HTML/cgi-bin/global.cgi ... CGI program (1)
	 *       HTML/cgi-bin/ghtml.cgi  ... unzip script (1)
	 *       HTML/.htaccess          ... skeleton of .htaccess (1)
	 *       HTML/help.html          ... help file (2)
	 *       HTML/R/                 ... references (3)
	 *       HTML/D/                 ... definitions (3)
	 *       HTML/search.html        ... search index (4)
	 *       HTML/defines.html       ... definitions index (5)
	 *       HTML/defines/           ... definitions index (5)
	 *       HTML/files/             ... file index (6)
	 *       HTML/index.html         ... index file (7)
	 *       HTML/mains.html         ... main index (8)
	 *       HTML/null.html          ... main null html (8)
	 *       HTML/S/                 ... source files (9)
	 *       HTML/I/                 ... include file index (9)
	 *       HTML/rebuild.sh         ... rebuild script (10)
	 *       HTML/style.css          ... style sheet (11)
	 *------------------------------------------------------------------
	 */
	/* for clean up */
	signal_setup();
	sethandler(clean);

        HTML = normal_suffix;

	message("[%s] Htags started", now());
	init_statistics();
	/*
	 * (#) check if GTAGS, GRTAGS is the latest.
	 */
	if (get_dbpath())
		message(" Using %s/GTAGS.", get_dbpath());
	if (grtags_is_empty)
		message(" GRTAGS is empty.");
	if (gpath_open(dbpath, 0) < 0)
		die("GPATH not found.");
	if (!w32) {
		/* UNDER CONSTRUCTION */
	}
	if (auto_completion || tree_view) {
		STATIC_STRBUF(sb);
		strbuf_clear(sb);
		strbuf_puts_nl(sb, "<script type='text/javascript' src='js/jquery.js'></script>");
		if (auto_completion)
			loadfile(makepath(datadir, "gtags/jscode_suggest", NULL), sb);
		if (tree_view)
			loadfile(makepath(datadir, "gtags/jscode_treeview", NULL), sb);
		jscode = strbuf_value(sb);
	}
	/*
	 * (0) make directories
	 */
	message("[%s] (0) making directories ...", now());
	if (!test("d", distpath))
		if (mkdir(distpath, 0777) < 0)
			die("cannot make directory '%s'.", distpath);
	make_directory_in_distpath("files");
	make_directory_in_distpath("defines");
	make_directory_in_distpath(SRCS);
	make_directory_in_distpath(INCS);
	make_directory_in_distpath(INCREFS);
	if (!dynamic) {
		make_directory_in_distpath(DEFS);
		make_directory_in_distpath(REFS);
		if (symbol)
			make_directory_in_distpath(SYMS);
	}
	if (fflag || dynamic)
		make_directory_in_distpath("cgi-bin");
	if (Iflag)
		make_directory_in_distpath("icons");
	if (auto_completion || tree_view)
		 make_directory_in_distpath("js");
	/*
	 * (1) make CGI program
	 */
	if (fflag || dynamic) {
		char cgidir[MAXPATHLEN];

		snprintf(cgidir, sizeof(cgidir), "%s/cgi-bin", distpath);
		message("[%s] (1) making CGI program ...", now());
		if (fflag || dynamic)
			makeprogram(cgidir, "global.cgi", 0755);
		if (auto_completion)
			makeprogram(cgidir, "completion.cgi", 0755);
		makehtaccess(cgidir, ".htaccess", 0644);
	} else {
		message("[%s] (1) making CGI program ...(skipped)", now());
	}
	if (av) {
		const char *path = makepath(distpath, "GTAGSROOT", NULL);
		FILE *op = fopen(path, "w");
		if (op == NULL)
			die("cannot make file '%s'.", path);
		fputs(cwdpath, op);
		fputc('\n', op);
		fclose(op);
	}
	/*
	 * (2) make help file
	 */
	message("[%s] (2) making help.html ...", now());
	makehelp("help.html");
	/*
	 * (#) load GPATH
	 */
	load_gpath(dbpath);

	/*
	 * (3) make function entries (D/ and R/)
	 *     MAKING TAG CACHE
	 */
	message("[%s] (3) making tag lists ...", now());
	cache_open();
	tim = statistics_time_start("Time of making tag lists");
	func_total = makedupindex();
	statistics_time_end(tim);
	message("Total %d functions.", func_total);
	/*
	 * (4) search index. (search.html)
	 */
	if (Fflag && fflag) {
		message("[%s] (4) making search index ...", now());
		makesearchindex("search.html");
	}
	{
		STRBUF *defines = strbuf_open(0);
		STRBUF *files = strbuf_open(0);

		/*
		 * (5) make definition index (defines.html and defines/)
		 *     PRODUCE @defines
		 */
		message("[%s] (5) making definition index ...", now());
		tim = statistics_time_start("Time of making definition index");
		func_total = makedefineindex("defines.html", func_total, defines);
		statistics_time_end(tim);
		message("Total %d functions.", func_total);
		/*
		 * (6) make file index (files.html and files/)
		 *     PRODUCE @files, %includes
		 */
		message("[%s] (6) making file index ...", now());
		init_inc();
		tim = statistics_time_start("Time of making file index");
		file_total = makefileindex("files.html", files);
		statistics_time_end(tim);
		message("Total %d files.", file_total);
		html_count += file_total;
		/*
		 * (7) make call tree using cflow(1)'s output (cflow.html)
		 */
		if (call_file || callee_file) {
			message("[%s] (7) making cflow index ...", now());
			tim = statistics_time_start("Time of making cflow index");
			if (call_file)
				if (makecflowindex("call.html", call_file) < 0)
					call_file = NULL;
			if (callee_file)
				if (makecflowindex("callee.html", callee_file) < 0)
					callee_file = NULL;
			statistics_time_end(tim);
		}
		/*
		 * [#] make include file index.
		 */
		message("[%s] (#) making include file index ...", now());
		tim = statistics_time_start("Time of making include file index");
		makeincludeindex();
		statistics_time_end(tim);
		/*
		 * [#] make a common part for mains.html and index.html
		 *     USING @defines @files
		 */
		message("[%s] (#) making a common part ...", now());
		index = makecommonpart(title, strbuf_value(defines), strbuf_value(files));

		strbuf_close(defines);
		strbuf_close(files);
	}
	/*
	 * (7)make index file (index.html)
	 */
	message("[%s] (7) making index file ...", now());
	makeindex("index.html", title, index);
	/*
	 * (8) make main index (mains.html)
	 */
	message("[%s] (8) making main index ...", now());
	makemainindex("mains.html", index);
	/*
	 * (9) make HTML files (SRCS/)
	 *     USING TAG CACHE, %includes and anchor database.
	 */
	message("[%s] (9) making hypertext from source code ...", now());
	tim = statistics_time_start("Time of making hypertext");
	makehtml(file_total);
	statistics_time_end(tim);
	/*
	 * (10) rebuild script. (rebuild.sh)
	 *
	 * Don't grant execute permission to rebuild script.
	 */
	makerebuild("rebuild.sh");
	if (chmod(makepath(distpath, "rebuild.sh", NULL), 0640) < 0)
		die("cannot chmod rebuild script.");
	/*
	 * (11) style sheet file (style.css)
	 */
	if (enable_xhtml) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];
		snprintf(src, sizeof(src), "%s/gtags/style.css", datadir);
		snprintf(dist, sizeof(dist), "%s/style.css", distpath);
		copyfile(src, dist);
	}
	if (auto_completion || tree_view) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];

		snprintf(src, sizeof(src), "%s/gtags/jquery", datadir);
		snprintf(dist, sizeof(dist), "%s/js", distpath);
		copydirectory(src, dist);
		snprintf(src, sizeof(src), "%s/gtags/jquery/images", datadir);
		snprintf(dist, sizeof(dist), "%s/js/images", distpath);
		copydirectory(src, dist);
	}
	message("[%s] Done.", now());
	if (vflag && (fflag || dynamic || auto_completion)) {
		message("\n[Information]\n");
		message(" o Htags was invoked with the -f, -c, -D or --auto-completion option. You should");
		message("   start http server so that cgi-bin/*.cgi is executed as a CGI script.");
 		message("\n If you are using Apache, 'HTML/.htaccess' might be helpful for you.\n");
		message(" Good luck!\n");
	}
	if (Iflag) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];

		snprintf(src, sizeof(src), "%s/gtags/icons", datadir);
		snprintf(dist, sizeof(dist), "%s/icons", distpath);
		copydirectory(src, dist);
	}
	gpath_close();
	/*
	 * Print statistics information.
	 */
	print_statistics(statistics);
	clean();
	return 0;
}
Exemple #20
0
/*
 * Main function for doing the copying of bits
 */
int
TM_perform_transfer(nvlist_t *targs, void(*prog)(int))
{
	char *logfile = NULL, *buf = NULL, *cprefix;
	char *buf1 = NULL, *layout = NULL, *dbg;
	FILE *cpipe = NULL, *kbd_file;
	float ipercent, rem_percent, cpfiles;
	float calc_factor;
	int kbd = -1, kbd_layout;
	int rv = 0, i;
	struct file_list flist, *cflist;
	clock_t tm;
	struct stat st;
	char zerolist[PATH_MAX];

	if (pthread_mutex_lock(&tran_mutex) != 0) {
		Perror("Unable to acquire Transfer lock ");
		return (1);
	}

	if (nvlist_lookup_string(targs, "mountpoint", &mntpt) != 0) {
		Perror("Alternate root mountpoint not provided. Bailing. ");
		return (1);
	}

	if (prog == NULL) {
		progress = log_progress;
	} else {
		progress = prog;
	}

	logfile = malloc(PATH_MAX);
	if (logfile == NULL) {
		Perror("Malloc failed ");
		return (1);
	}

	(void) snprintf(logfile, PATH_MAX, "%s/%s", mntpt,
	    TM_LOGFILE_NAME);

	lof = fopen(logfile, "w+");
	if (lof == NULL) {
		Perror("Unable to open logfile ");
		goto error_done;
	}

	buf = malloc(BUF_SIZE);
	if (buf == NULL) {
		Perror("Malloc failed ");
		goto error_done;
	}

	buf1 = malloc(BUF_SIZE);
	if (buf1 == NULL) {
		Perror("Malloc failed ");
		goto error_done;
	}

	dbg = getenv("TM_DEBUG");
	if (dbg != NULL && strcmp(dbg, "1") == 0) {
		TM_enable_debug();
	}

	/*
	 * Set TMPDIR to avoid cpio depleting ramdisk space
	 */
	if (putenv(tmpenv) != 0) {
		Perror(tmpenv);
		goto error_done;
	}

	/*
	 * Zero length file list.
	 */
	(void) strlcpy(zerolist, mntpt, PATH_MAX);
	(void) strlcat(zerolist, "/flist.0length", PATH_MAX);
	if ((zerolength = fopen(zerolist, "w+")) == NULL) {
		Perror(zerolist);
		goto error_done;
	}

	tm = time(NULL);
	(void) strftime(buf, PATH_MAX, (char *)0, localtime(&tm));
	INFO_MSG2("-- Starting transfer process, %s --", buf);
	(void) chdir("/");
	CHECK_ABORT;

	(*progress)(0);
	percent = 0;
	opercent = 0;
	total_find_percent = (NUM_PREFIXES - 1) * FIND_PERCENT;

	/*
	 * Get the optimized libc overlay out of the way.
	 */
	if (umount("/lib/libc.so.1") != 0) {
		if (errno != EINVAL) {
			Perror("Can't unmount /lib/libc.so.1 ");
			goto error_done;
		}
	}
	CHECK_ABORT;
	INFO_MSG1("Building file lists for cpio");

	/*
	 * Do a file tree walk of all the mountpoints provided and
	 * build up pathname lists. Pathname lists of all mountpoints
	 * under the same prefix are aggregated in the same file to
	 * reduce the number of cpio invocations.
	 *
	 * This loop builds a linked list where each entry points to
	 * a file containing a pathname list and mentions other info
	 * like the mountpoint from which to copy etc.
	 */
	cprefix = "";
	flist.next = NULL;
	cflist = &flist;
	for (i = 0; cpio_prefixes[i].chdir_prefix != NULL; i++) {
		char *patt;
		regex_t re;

		CHECK_ABORT;
		DBG_MSG3("Cpio dir: %s, Chdir to: %s",
		    cpio_prefixes[i].cpio_dir,
		    cpio_prefixes[i].chdir_prefix);
		patt = cpio_prefixes[i].match_pattern;
		if (strcmp(cprefix,
		    cpio_prefixes[i].chdir_prefix) != 0 ||
		    patt != NULL ||
		    cpio_prefixes[i].clobber_files == 1 ||
		    cpio_prefixes[i].cpio_args != NULL) {

			cprefix = cpio_prefixes[i].chdir_prefix;
			cflist->next = (struct file_list *)
			    malloc(sizeof (struct file_list));
			cflist = cflist->next;
			cflist->next = NULL;
			(void) snprintf(cflist->name, PATH_MAX, "%s/flist%d",
			    mntpt, i);
			DBG_MSG2(" File list tempfile: %s", cflist->name);

			cflist->handle = fopen(cflist->name, "w+");
			if (cflist->handle == NULL) {
				Perror("Unable to open file list ");
				goto error_done;
			}

			cflist->chdir_prefix =
			    cpio_prefixes[i].chdir_prefix;
			if (patt != NULL) {
				DBG_MSG2(" Compiling regexp: %s", patt);
				if (patt[0] == '!') {
					negate = 1;
					patt++;
				} else {
					negate = 0;
				}
				if (regcomp(&re, patt,
				    REG_EXTENDED|REG_NOSUB) != 0) {
					Perror("Regexp error ");
					goto error_done;
				}
				mre = &re;
			} else {
				mre = NULL;
			}

			listfile = cflist->handle;
			cflist->clobber_files =
			    cpio_prefixes[i].clobber_files;
			if (cpio_prefixes[i].cpio_args != NULL) {
				cflist->cpio_args =
				    cpio_prefixes[i].cpio_args;
			} else {
				cflist->cpio_args = DEFAULT_CPIO_ARGS;
			}
		}

		INFO_MSG3("Scanning %s/%s", cflist->chdir_prefix,
		    cpio_prefixes[i].cpio_dir);
		(void) chdir(cflist->chdir_prefix);
		if (nftw(cpio_prefixes[i].cpio_dir, add_files, 10,
		    FTW_MOUNT|FTW_PHYS) < 0) {
			Perror("Nftw failed ");
			goto error_done;
		}
		(void) fflush(cflist->handle);
	}
	(void) fflush(zerolength);

	/*
	 * Now process each entry in the list. cpio is executed with the
	 * -V option where it prints a dot for each pathname processed.
	 * Since we already know the number of files we can show accurate
	 * percentage completion.
	 */
	INFO_MSG1("Beginning cpio actions ...");

	rem_percent = 95 - percent;
	ipercent = percent;
	cflist = flist.next;
	cpfiles = 0;
	opercent = 0;
	percent = 0;
	calc_factor = rem_percent / nfiles;
	while (cflist != NULL) {
		(void) fclose(cflist->handle);
		cflist->handle = NULL;
		CHECK_ABORT;
		if (cflist->clobber_files) {
			if (do_clobber_files(cflist->name) != 0) {
				goto error_done;
			}
		}

		(void) chdir(cflist->chdir_prefix);
		(void) snprintf(buf, PATH_MAX, "%s -%sV %s < %s",
		    CPIO, cflist->cpio_args, mntpt, cflist->name);
		DBG_MSG3("Executing: %s, CWD: %s", buf,
		    cflist->chdir_prefix);

		cpipe = popen(buf, "r");
		if (cpipe == NULL) {
			Perror("Unable to cpio files ");
			goto error_done;
		}

		while (!feof(cpipe)) {
			int ch = fgetc(cpipe);
			if (ch == '.') {
				cpfiles++;
				percent = (int)(cpfiles * calc_factor +
				    ipercent);
				if (percent - opercent >= 1) {
					if (progress != NULL) {
						(*progress)(percent);
					}
					opercent = percent;
				}
			}
			CHECK_ABORT;
		}
		if (ferror(cpipe)) {
			Perror(CPIO);
			goto error_done;
		}

		(void) fclose(cpipe);
		cpipe = NULL;

		(void) unlink(cflist->name);
		cflist->name[0] = '\0';
		cflist = cflist->next;
	}
	(*progress)(percent);
	cpipe = NULL;

	/*
	 * Process zero-length files if any.
	 */
	INFO_MSG1("Creating zero-length files");
	rewind(zerolength);
	while (fgets(buf, BUF_SIZE, zerolength) != NULL) {
		int fd;
		mode_t mod;
		uid_t st_uid, st_gid;
		char *token, *lasts;

		/* Get the newline out of the way */
		buf[strlen(buf) - 1] = '\0';

		/* Parse out ownership and perms */
		GET_TOKEN(token, lasts, buf, ",");
		mod = atoi(token);
		GET_TOKEN(token, lasts, NULL, ",");
		st_uid = atoi(token);
		GET_TOKEN(token, lasts, NULL, ",");
		st_gid = atoi(token);

		GET_TOKEN(token, lasts, NULL, ",");
		(void) snprintf(buf1, PATH_MAX, "%s/%s", mntpt, token);

		fd = open(buf1, O_WRONLY | O_CREAT | O_TRUNC, mod);
		if (fd != -1) {
			(void) fchown(fd, st_uid, st_gid);
			(void) close(fd);
			DBG_MSG2("Created file %s", buf1);
		} else {
			INFO_MSG1("Unable to create file:");
			Perror(buf1);
		}
	}
	(*progress)(97);

	CHECK_ABORT;
	INFO_MSG1("Extracting archive");
	(void) chdir(mntpt);
	(void) snprintf(buf, PATH_MAX, "%s e -so %s | %s -idum",
	    SZIP, ARCHIVE, CPIO);
	DBG_MSG3("Executing: %s, CWD: %s", buf, mntpt);
	if (system(buf) != 0) {
		Perror("Extracting archive failed ");
		goto error_done;
	}
	(*progress)(98);
	CHECK_ABORT;

	/*
	 * Check for the presence of skeleton.cpio before extracting it.
	 * This file may not be present in a Distro Constructor image.
	 */
	if (lstat(SKELETON, &st) == 0 && (S_ISREG(st.st_mode) ||
	    S_ISLNK(st.st_mode))) {
		INFO_MSG1("Extracting skeleton archive");
		(void) snprintf(buf, PATH_MAX, "%s -imu < %s", CPIO,
		    SKELETON, mntpt);
		DBG_MSG3("Executing: %s, CWD: %s", buf, mntpt);
		if (system(buf) != 0) {
			Perror("Skeleton cpio failed ");
			goto error_done;
		}
	}
	(*progress)(99);

	CHECK_ABORT;
	INFO_MSG1("Performing file operations");
	for (i = 0; i < NUM_FILEOPS_LIST; i++) {
		int rv;

		CHECK_ABORT;
		expand_symbols(fileops_list[i].src, buf, PATH_MAX);

		switch (fileops_list[i].op) {
			int op;

		case FILE_OP_UNLINK:
			DBG_MSG2("Unlink: %s", buf);
			(void) unlink(buf);
			rv = 0; /* unlink errors are non-fatal */
			break;

		case FILE_OP_RMDIR:
			DBG_MSG2("Rmdir: %s", buf);
			(void) rmdir(buf);
			rv = 0; /* Ignore rmdir errors for now */
			break;

		case FILE_OP_MKDIR:

			DBG_MSG2("Mkdir: %s", buf);
			rv = 0;
			if (lstat(buf, &st) == 0) {
				op = 0;
				if ((st.st_mode & S_IFMT)
				    != S_IFDIR) {
					rv = unlink(buf);
					op = 1;
				}
				if (rv == 0 && op) {
					rv = mkdir(buf,
					    fileops_list[i].perms);
				}
			} else {
				rv = mkdir(buf,
				    fileops_list[i].perms);
			}
			break;

		case FILE_OP_COPY:
			expand_symbols(fileops_list[i].dst, buf1,
			    PATH_MAX);
			rv = copyfile(buf, buf1);
			break;
		case FILE_OP_CHMOD:
			expand_symbols(fileops_list[i].dst, buf1,
			    PATH_MAX);
			rv = chmod(buf, fileops_list[i].perms);
			break;
		default:
			Perror("Unsupported file operation ");
			rv = 1;
			break;
		}
		if (rv != 0) {
			Perror("File ops error ");
			Perror(buf);
			goto error_done;
		}
	}

	CHECK_ABORT;
	INFO_MSG1("Fetching and updating keyboard layout");
	(void) chdir(mntpt);

	DBG_MSG2("Opening keyboard device: %s", KBD_DEVICE);
	kbd = open(KBD_DEVICE, O_RDWR);
	if (kbd < 0) {
		Perror("Error opening keyboard");
		goto error_done;
	}

	if (ioctl(kbd, KIOCLAYOUT, &kbd_layout)) {
		Perror("ioctl keyboard layout");
		goto error_done;
	}

	CHECK_ABORT;
	if ((layout = get_layout_name(kbd_layout)) == NULL) {
		goto error_done;
	}

	kbd_file = fopen(KBD_DEFAULTS_FILE, "a+");
	if (kbd_file == NULL) {
		Perror("Unable to open kbd defaults file ");
		goto error_done;
	}

	(void) fprintf(kbd_file, "LAYOUT=%s\n", layout);
	(void) fclose(kbd_file);
	DBG_MSG3("Updated keyboard defaults file: %s/%s", mntpt,
	    KBD_DEFAULTS_FILE);

	INFO_MSG2("Detected %s keyboard layout", layout);
	tm = time(NULL);
	(void) strftime(buf, PATH_MAX, (char *)0, localtime(&tm));
	INFO_MSG2("-- Completed transfer process, %s --", buf);

	(*progress)(100);

	goto done;
error_done:
	rv = 1;

done:
	if (lof != NULL)
		(void) fclose(lof);

	if (cpipe != NULL)
		(void) fclose(cpipe);

	free_flist(flist.next);

	if (logfile != NULL)
		free(logfile);

	if (kbd > 0)
		(void) close(kbd);

	if (buf != NULL)
		free(buf);

	if (buf1 != NULL)
		free(buf1);

	if (layout != NULL)
		free(layout);

	if (zerolength != NULL) {
		(void) fclose(zerolength);
		(void) unlink(zerolist);
	}

	do_abort = 0;
	(void) pthread_mutex_unlock(&tran_mutex);

	return (rv);
}
Exemple #21
0
void Banlist_writebans()
/*
 * Prefix codes are:
 *    'n' - <nick>
 *    'b' - <ban>
 *    't' - <time_set>
 *    'e' - <expires>
 *    'u' - <used>
 */
{
	FILE	*f;
	banlrec	*b;
	int	x;
	char	banlist[256], tmpfile[256];

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

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

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

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

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

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

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

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

	fclose(f);

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

	verify_write(x,tmpfile,banlist);
	if(x == 0)
	{
		Log_write(LOG_MAIN,"*","Wrote banlist.");
		Banlist->flags &= ~BANLIST_NEEDS_WRITE;
	}
}
Exemple #22
0
int main( int argc, char **argv )
{
    int err;
    int existingdirents=-1;
#if defined(CYGSEM_FILEIO_BLOCK_USAGE)
    struct cyg_fs_block_usage usage;
#endif

    CYG_TEST_INIT();

    // --------------------------------------------------------------

    err = mount( "/dev/disk0/1", "/", "fatfs" );    
    if( err < 0 ) SHOW_RESULT( mount, err );    

    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/" );
    
    listdir( "/", true, -1, &existingdirents );

    // --------------------------------------------------------------
#if defined(CYGSEM_FILEIO_BLOCK_USAGE)
    err = cyg_fs_getinfo("/", FS_INFO_BLOCK_USAGE, &usage, sizeof(usage));
    if( err < 0 ) SHOW_RESULT( cyg_fs_getinfo, err );
    diag_printf("<INFO>: total size: %6lld blocks, %10lld bytes\n",
		usage.total_blocks, usage.total_blocks * usage.block_size); 
    diag_printf("<INFO>: free size:  %6lld blocks, %10lld bytes\n",
		usage.free_blocks, usage.free_blocks * usage.block_size); 
    diag_printf("<INFO>: block size: %6u bytes\n", usage.block_size);
#endif
    // --------------------------------------------------------------

    createfile( "/foo", 20257 );
    checkfile( "foo" );
    copyfile( "foo", "fee");
    checkfile( "fee" );
    comparefiles( "foo", "/fee" );
    diag_printf("<INFO>: mkdir bar\n");
    err = mkdir( "/bar", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    listdir( "/" , true, existingdirents+3, NULL );

    copyfile( "fee", "/bar/fum" );
    checkfile( "bar/fum" );
    comparefiles( "/fee", "bar/fum" );

    diag_printf("<INFO>: cd bar\n");
    err = chdir( "bar" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/bar" );
    
    diag_printf("<INFO>: rename /foo bundy\n");    
    err = rename( "/foo", "bundy" );
    if( err < 0 ) SHOW_RESULT( rename, err );
    
    listdir( "/", true, existingdirents+2, NULL );
    listdir( "" , true, 4, NULL );

    checkfile( "/bar/bundy" );
    comparefiles("/fee", "bundy" );

#if defined(CYGSEM_FILEIO_BLOCK_USAGE)
    err = cyg_fs_getinfo("/", FS_INFO_BLOCK_USAGE, &usage, sizeof(usage));
    if( err < 0 ) SHOW_RESULT( cyg_fs_getinfo, err );
    diag_printf("<INFO>: total size: %6lld blocks, %10lld bytes\n",
		usage.total_blocks, usage.total_blocks * usage.block_size); 
    diag_printf("<INFO>: free size:  %6lld blocks, %10lld bytes\n",
		usage.free_blocks, usage.free_blocks * usage.block_size); 
    diag_printf("<INFO>: block size: %6u bytes\n", usage.block_size);
#endif
    // --------------------------------------------------------------

    diag_printf("<INFO>: unlink fee\n");    
    err = unlink( "/fee" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink fum\n");        
    err = unlink( "fum" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink /bar/bundy\n");        
    err = unlink( "/bar/bundy" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: cd /\n");        
    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/" );
    
    diag_printf("<INFO>: rmdir /bar\n");        
    err = rmdir( "/bar" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );
    
    listdir( "/", false, existingdirents, NULL );

    // --------------------------------------------------------------

#if 0
    diag_printf("<INFO>: mkdir disk2\n");
    err = mkdir( "/disk2", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );
#else
    diag_printf("<INFO>: mount /disk2\n");    
    err = mount( "/dev/disk0/2", "/disk2", "fatfs" );    
    if( err < 0 ) SHOW_RESULT( mount, err );    
#endif
    
    listdir( "/disk2" , true, -1, &existingdirents);
        
    createfile( "/disk2/tinky", 4567 );
    copyfile( "/disk2/tinky", "/disk2/laalaa" );
    checkfile( "/disk2/tinky");
    checkfile( "/disk2/laalaa");
    comparefiles( "/disk2/tinky", "/disk2/laalaa" );

    diag_printf("<INFO>: cd /disk2\n");    
    err = chdir( "/disk2" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/disk2" );
        
    diag_printf("<INFO>: mkdir noonoo\n");    
    err = mkdir( "noonoo", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    listdir( "/disk2" , true, existingdirents+3, NULL);

    diag_printf("<INFO>: cd noonoo\n");
    err = chdir( "noonoo" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/disk2/noonoo" );
    
    createfile( "tinky", 6789 );
    checkfile( "tinky" );

    createfile( "dipsy", 34567 );
    checkfile( "dipsy" );
    copyfile( "dipsy", "po" );
    checkfile( "po" );
    comparefiles( "dipsy", "po" );

    listdir( ".", true, 5, NULL );
    listdir( "", true, 5, NULL );
    listdir( "..", true, existingdirents+3, NULL );

    // --------------------------------------------------------------

    diag_printf("<INFO>: unlink tinky\n");    
    err = unlink( "tinky" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink dipsy\n");    
    err = unlink( "dipsy" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink po\n");    
    err = unlink( "po" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: cd ..\n"); 
    err = chdir( ".." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/disk2" );
    
    diag_printf("<INFO>: rmdir noonoo\n"); 
    err = rmdir( "noonoo" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    // --------------------------------------------------------------

    err = mkdir( "x", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );
    
    err = mkdir( "x/y", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );
    
    err = mkdir( "x/y/z", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    err = mkdir( "x/y/z/w", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );
    
    diag_printf("<INFO>: cd /disk2/x/y/z/w\n");
    err = chdir( "/disk2/x/y/z/w" );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/disk2/x/y/z/w" );

    diag_printf("<INFO>: cd ..\n");
    err = chdir( ".." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/disk2/x/y/z" );
    
    diag_printf("<INFO>: cd .\n");
    err = chdir( "." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/disk2/x/y/z" );

    diag_printf("<INFO>: cd ../../y\n");
    err = chdir( "../../y" );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/disk2/x/y" );

    diag_printf("<INFO>: cd ../..\n");
    err = chdir( "../.." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/disk2" );

    diag_printf("<INFO>: rmdir x/y/z/w\n"); 
    err = rmdir( "x/y/z/w" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    diag_printf("<INFO>: rmdir x/y/z\n"); 
    err = rmdir( "x/y/z" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    diag_printf("<INFO>: rmdir x/y\n"); 
    err = rmdir( "x/y" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    diag_printf("<INFO>: rmdir x\n"); 
    err = rmdir( "x" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );
    
    // --------------------------------------------------------------

    checkcwd( "/disk2" );
    
    diag_printf("<INFO>: unlink tinky\n");    
    err = unlink( "tinky" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink laalaa\n");    
    err = unlink( "laalaa" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: cd /\n");    
    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/" );

    listdir( "/disk2", true, -1, NULL );
    
#if 0
    diag_printf("<INFO>: rmdir dir\n"); 
    err = rmdir( "disk2" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );
#else
    diag_printf("<INFO>: umount /disk2\n");    
    err = umount( "/disk2" );
    if( err < 0 ) SHOW_RESULT( umount, err );    
#endif
    
#ifdef CYGCFG_FS_FAT_USE_ATTRIBUTES
    // Create file
    diag_printf("<INFO>: create /foo\n");
    createfile( "/foo", 20257 );

    // Verify it is created with archive bit set
    checkattrib( "/foo", S_FATFS_ARCHIVE );

    // Make it System
    diag_printf("<INFO>: attrib -A+S /foo\n");
    err = cyg_fs_set_attrib( "/foo", S_FATFS_SYSTEM );
    if( err < 0 ) SHOW_RESULT( chmod system , err );

    // Verify it is now System
    checkattrib( "/foo", S_FATFS_SYSTEM );

    // Make it Hidden
    diag_printf("<INFO>: attrib -S+H /foo\n");
    err = cyg_fs_set_attrib( "/foo", S_FATFS_HIDDEN );
    if( err < 0 ) SHOW_RESULT( chmod system , err );

    // Verify it is now Hidden
    checkattrib( "/foo", S_FATFS_HIDDEN );

    // Make it Read-only
    diag_printf("<INFO>: attrib -H+R /foo\n");
    err = cyg_fs_set_attrib( "/foo", S_FATFS_RDONLY );
    if( err < 0 ) SHOW_RESULT( chmod system , err );

    // Verify it is now Read-only
    checkattrib( "/foo", S_FATFS_RDONLY );

    // Verify we cannot unlink a read-only file
    diag_printf("<INFO>: unlink /foo\n");
    err = unlink( "/foo" );
    if( (err != -1) || (errno != EPERM) ) SHOW_RESULT( unlink, err );

    // Verify we cannot rename a read-only file
    diag_printf("<INFO>: rename /foo bundy\n");
    err = rename( "/foo", "bundy" );
    if( (err != -1) || (errno != EPERM) ) SHOW_RESULT( rename, err );

    // Verify we cannot open read-only file for writing
    int fd;
    diag_printf("<INFO>: create file /foo\n");
    fd = open( "/foo", O_WRONLY );
    if( (err != -1) || (errno != EACCES) ) SHOW_RESULT( open, err );
    if( err > 0 ) close(fd);

    // Make it Normal
    diag_printf("<INFO>: attrib -H /foo\n");
    err = cyg_fs_set_attrib( "/foo", 0 );
    if( err < 0 ) SHOW_RESULT( chmod none , err );

    // Verify it is now nothing
    checkattrib( "/foo", 0 );

    // Now delete our test file
    diag_printf("<INFO>: unlink /foo\n");
    err = unlink( "/foo" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

#endif // CYGCFG_FS_FAT_USE_ATTRIBUTES

    maxfile("file.max");

    listdir( "/", true, -1, NULL );    
        
    diag_printf("<INFO>: unlink file.max\n");    
    err = unlink( "file.max" );
    if( err < 0 ) SHOW_RESULT( unlink, err );    
    diag_printf("<INFO>: umount /\n");    
    err = umount( "/" );
    if( err < 0 ) SHOW_RESULT( umount, err );    
    
    CYG_TEST_PASS_FINISH("fatfs1");
}
Exemple #23
0
void processcommand( char *command, char *P1, char *P2, char *P3 ) {

    if( strcmp(command, "createvfs") == 0 ) {
        int size = atoi(P2);
        if( (0 == strcmp(P1,"")) || 0 == P2 ) {
            printf("createvfs_FAILURE %s \n",ERR_VFS_CREATE_00);
        } else {
            createvfs (P1,size);
        }
    }
    else if( strcmp(command, "mountvfs") == 0 ) {
        if( (0 == strcmp(P1,"")) ) {
            printf("mountvfs_FAILURE %s \n",ERR_VFS_MOUNT_05);
        } else {
            if( 1 == ui_mountFlag ) {
                printf("mountvfs_FAILURE %s \n",ERR_VFS_MOUNT_04);
            } else {
                mountvfs (P1);
            }
        }
    }
    else if( strcmp(command, "unmountvfs") == 0 ) {
        if( (0 == strcmp(P1,"")) ) {
            printf("unmountvfs_FAILURE %s \n",ERR_VFS_UNMOUNT_00);
        } else {
            if( 0 == ui_mountFlag ) {
                printf("unmountvfs_FAILURE %s \n",ERR_VFS_UNMOUNT_04);
            } else {
                unmountvfs (P1);
            }
        }
    }
    else if( strcmp(command, "makedir") == 0 ) {
        if( (0 == strcmp(P1,"")) || (0 == strcmp(P2,"")) ) {
            printf("makedir_FAILURE %s \n",ERR_VFS_MAKEDIR_00);
        } else {
            if( 0 == ui_mountFlag ) {
                printf("makedir_FAILURE %s \n",ERR_VFS_MAKEDIR_05);
            } else {
                makedir (P1,P2);
            }
        }
    }
    else if( strcmp(command, "deletedir") == 0 )
        deletedir (P1);
    else if( strcmp(command, "movedir") == 0 )
        movedir (P1,P2);
    else if( strcmp(command, "listdir") == 0 ) {
        int flag = atoi(P2);
        listdir (P1,flag,P3);
    }
    else if( strcmp(command, "addfile") == 0 )
        addfile (P1,P2,P3);
    else if( strcmp(command, "listfile") == 0 )
        listfile (P1,P2);
    else if( strcmp(command, "updatefile") == 0 )
        updatefile (P1,P2);
    else if( strcmp(command, "removefile") == 0 )
        removefile (P1);
    else if( strcmp(command, "movefile") == 0 )
        movefile (P1,P2);
    else if( strcmp(command, "copyfile") == 0 )
        copyfile (P1,P2);
    else if( strcmp(command, "exportfile") == 0 )
        exportfile (P1,P2);
    else if( strcmp(command, "searchfile") == 0 )
        searchfile (P1,P2);
    else
        printf("Ignoring invalid command %s\n", command);
}
Exemple #24
0
/* utility fn to copy a directory */
void copydir(char *name, char *destdir)
{
	int err;
	DIR *dirp;

	dirp = opendir(destdir);
	if (dirp==NULL)
	{
		mkdir(destdir, 0777);
	} else
	{
		err = closedir(dirp);
	}

	dirp = opendir(name);
    if( dirp == NULL ) SHOW_RESULT( opendir, -1 );

	for (;;)
	{
		struct dirent *entry = readdir(dirp);

		if (entry == NULL)
			break;

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

		int isDir = 0;
		struct stat buf;
		char fullPath[PATH_MAX];
		strncpy(fullPath, name, PATH_MAX);
		strcat(fullPath, "/");
		strncat(fullPath, entry->d_name, PATH_MAX - strlen(fullPath));

		if (stat(fullPath, &buf) == -1)
		{
			LOG_ERROR("unable to read status from %s", fullPath);
			break;
		}
		isDir = S_ISDIR(buf.st_mode) != 0;

		if (isDir)
			continue;

		//        diag_printf("<INFO>: entry %14s",entry->d_name);
		char fullname[PATH_MAX];
		char fullname2[PATH_MAX];

		strcpy(fullname, name);
		strcat(fullname, "/");
		strcat(fullname, entry->d_name);

		strcpy(fullname2, destdir);
		strcat(fullname2, "/");
		strcat(fullname2, entry->d_name);
		//        diag_printf("from %s to %s\n", fullname, fullname2);
		copyfile(fullname, fullname2);

		//       diag_printf("\n");
	}

	err = closedir(dirp);
    if( err < 0 ) SHOW_RESULT( stat, err );
}
Exemple #25
0
int run(GList **config)
{
	GList *partlist;
	char **nrdevs, *ptr, *op, *np, *dest;
	int ret;
	char my_buffer[MAX_LEN + 1] = "";

	detect_parts(0);

	// select swap partitions to use
	partlist = selswap();

	// format swap partitions
	if(doswap(partlist, config) == -1)
		return(-1);

	// root partition
	ptr = selrootdev();
	if(ptr == NULL)
		return(-1);
	if(formatdev(ptr) == -1)
		return(-1);
	mountdev(ptr, "/", config);

	// move temporarily stuff to the final location
	chdir(TARGETDIR);
	np = g_strdup_printf("%s/%s", TARGETDIR, "/etc/profile.d");
	makepath(np);
	FREE(np);
	op = (char*)data_get(*config, "fstab");
	np = g_strdup_printf("%s/%s", TARGETDIR, "/etc/fstab");
	copyfile(op, np);
	unlink(op);
	chmod (np, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
	data_put(config, "fstab", strdup(np));
	FREE(np);

	np = g_strdup_printf("%s/%s", TARGETDIR, "/etc/sysconfig");
	makepath(np);
	FREE(np);

	// so that 1) the user can't mount a partition as /dev because
	// it'll be used 2) install scriptlets will be able to do
	// >/dev/null
	makepath(TARGETDIR "/dev");
	makepath(TARGETDIR "/proc");
	makepath(TARGETDIR "/sys");
	fw_system("mount none -t devtmpfs " TARGETDIR "/dev");
	fw_system("mount none -t proc " TARGETDIR "/proc");
	fw_system("mount none -t sysfs " TARGETDIR "/sys");

	// non-root partitions
	dialog_vars.backtitle=gen_backtitle(_("Selecting other partitions"));
	while(1)
	{
		dialog_vars.input_result = my_buffer;
		nrdevs = parts2dialog(parts);
		dlg_put_backtitle();
		dlg_clear();
		dialog_vars.cancel_label = _("Continue");
		dialog_vars.input_result = my_buffer;
		dialog_vars.input_result[0]='\0';
		ret = dialog_menu(
		_("Select other Linux partitions for /etc/fstab"),
		_("You may use your other partitions to distribute your Linux "
		"system across more than one partition. Currently, you have "
		"only mounted your / partition. You might want to mount "
		"directories such as /boot, /home or /usr/local on separate "
		"partitions. You should not try to mount /usr, /etc, /sbin or "
		"/bin on their own partitions since they contain utilities "
		"needed to bring the system up and mount partitions. Also, "
		"do not reuse a partition that you've already entered before. "
		"Please select one of the partitions listed below, or if "
		"you're done, hit Continue."),
		0, 0, 0, g_list_length(parts)/2, nrdevs);
		dialog_vars.cancel_label = '\0';
		FREE(nrdevs);
		if (ret != DLG_EXIT_CANCEL)
		{
			if(!strcmp(_("(in use)"), dialog_vars.input_result))
				continue;
			ptr = strdup(dialog_vars.input_result);
			if(formatdev(ptr) == -1)
				return(-1);
			dest = asktowhere(ptr);
			if(dest == NULL)
				return(-1);
			mountdev(ptr, dest, config);
			FREE(dest);
			FREE(ptr);
		}
		else
			break;
	}

	makepath(g_strdup_printf("%s/%s", TARGETDIR, "/var/log"));
	np = g_strdup_printf("%s/%s", TARGETDIR, LOGFILE);
	copyfile(LOGFILE, np);
	unlink(LOGFILE);
	chmod (np, S_IRUSR|S_IWUSR);
	FREE(np);

	// disable caching for cds
	// this is needed here since when the cds is loaded we had no
	// formatted root partition
	if((char*)data_get(*config, "netinstall")==NULL)
	{
		char *pacbindir = g_strdup_printf("%s/frugalware-%s", SOURCEDIR, ARCH);
		char *ptr;

		ptr = g_strdup_printf("%s/var/cache/pacman-g2/pkg", TARGETDIR);
		makepath(ptr);
		FREE(ptr);
		disable_cache(pacbindir);
		FREE(pacbindir);
	}
	return(0);
}
Exemple #26
0
int main( int argc, char **argv )
{
    int err;

    CYG_TEST_INIT();

    // --------------------------------------------------------------

    createfile( "/foo", 202 );
    checkfile( "foo" );
    copyfile( "foo", "fee");
    checkfile( "fee" );
    comparefiles( "foo", "/fee" );

    err = mkdir( "/bar", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    listdir( "/" , false);

    copyfile( "fee", "/bar/fum" );
    checkfile( "bar/fum" );
    comparefiles( "/fee", "bar/fum" );


    err = chdir( "bar" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    err = rename( "/foo", "bundy" );
    if( err < 0 ) SHOW_RESULT( rename, err );

    listdir( "/", true );
    listdir( "" , true );

    checkfile( "/bar/bundy" );
    comparefiles("/fee", "bundy" );

    testfs_dump();

    // --------------------------------------------------------------

    err = unlink( "/fee" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    err = unlink( "fum" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    err = unlink( "/bar/bundy" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    err = rmdir( "/bar" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    listdir( "/", false );

    // --------------------------------------------------------------

    err = mount( "", "/ram", "testfs" );
    if( err < 0 ) SHOW_RESULT( mount, err );

    createfile( "/ram/tinky", 456 );
    copyfile( "/ram/tinky", "/ram/laalaa" );
    checkfile( "/ram/tinky");
    checkfile( "/ram/laalaa");
    comparefiles( "/ram/tinky", "/ram/laalaa" );

    err = chdir( "/ram" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    createfile( "tinky", 678 );
    checkfile( "tinky" );

    maxfile( "dipsy" );
    checkfile( "dipsy" );
    copyfile( "dipsy", "po" );
    checkfile( "po" );
    comparefiles( "dipsy", "po" );

    testfs_dump();

    // --------------------------------------------------------------

    err = unlink( "tinky" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    err = unlink( "dipsy" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    err = unlink( "po" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    err = unlink( "laalaa" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    err = umount( "/ram" );
    if( err < 0 ) SHOW_RESULT( umount, err );

    CYG_TEST_PASS_FINISH("fileio1");
}
int main( int argc, char **argv )
{
    int err;
    //int i;
    int existingdirents=-1;

    CYG_TEST_INIT();

    // --------------------------------------------------------------

    err = mount( CYGDAT_IO_FLASH_BLOCK_DEVICE_NAME_1, "/", "jffs2" );
    if( err < 0 ) SHOW_RESULT( mount, err );

    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/" );

    listdir( "/", true, -1, &existingdirents );
    if ( existingdirents < 2 )
        CYG_TEST_FAIL("Not enough dir entries\n");

    // --------------------------------------------------------------

    createfile( "/foo", 202 );
    checkfile( "foo" );
    copyfile( "foo", "fee");
    checkfile( "fee" );
    comparefiles( "foo", "/fee" );
    diag_printf("<INFO>: mkdir bar\n");
    err = mkdir( "/bar", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    listdir( "/" , true, existingdirents+3, NULL );

    copyfile( "fee", "/bar/fum" );
    checkfile( "bar/fum" );
    comparefiles( "/fee", "bar/fum" );

    diag_printf("<INFO>: cd bar\n");
    err = chdir( "bar" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/bar" );

    diag_printf("<INFO>: rename /foo bundy\n");
    err = rename( "/foo", "bundy" );
    if( err < 0 ) SHOW_RESULT( rename, err );

    listdir( "/", true, existingdirents+2, NULL );
    listdir( "" , true, 4, NULL );

    checkfile( "/bar/bundy" );
    comparefiles("/fee", "bundy" );

    // --------------------------------------------------------------

    createfile( LONGNAME1, 123 );
    checkfile( LONGNAME1 );
    copyfile( LONGNAME1, LONGNAME2 );

    listdir( "", false, 6, NULL );

    diag_printf("<INFO>: unlink " LONGNAME1 "\n");
    err = unlink( LONGNAME1 );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink " LONGNAME2 "\n");
    err = unlink( LONGNAME2 );
    if( err < 0 ) SHOW_RESULT( unlink, err );


    // --------------------------------------------------------------

    diag_printf("<INFO>: unlink fee\n");
    err = unlink( "/fee" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink fum\n");
    err = unlink( "fum" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink /bar/bundy\n");
    err = unlink( "/bar/bundy" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: cd /\n");
    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/" );

    diag_printf("<INFO>: rmdir /bar\n");
    err = rmdir( "/bar" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    listdir( "/", false, existingdirents, NULL );

    // --------------------------------------------------------------

    diag_printf("<INFO>: mount /jffs2 \n");
    err = mount( CYGDAT_IO_FLASH_BLOCK_DEVICE_NAME_1, "/jffs2", "jffs2" );
    if( err < 0 ) SHOW_RESULT( mount, err );

    createfile( "/jffs2/tinky", 456 );
    copyfile( "/jffs2/tinky", "/jffs2/laalaa" );
    checkfile( "/jffs2/tinky");
    checkfile( "/jffs2/laalaa");
    comparefiles( "/jffs2/tinky", "/jffs2/laalaa" );

    diag_printf("<INFO>: cd /jffs2\n");
    err = chdir( "/jffs2" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/jffs2" );

    diag_printf("<INFO>: mkdir noonoo\n");
    err = mkdir( "noonoo", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    listdir( "." , true, existingdirents+3, NULL);

    diag_printf("<INFO>: cd noonoo\n");
    err = chdir( "noonoo" );
    if( err < 0 ) SHOW_RESULT( chdir, err );

    checkcwd( "/jffs2/noonoo" );

    createfile( "tinky", 678 );
    checkfile( "tinky" );

    createfile( "dipsy", 3456 );
    checkfile( "dipsy" );
    copyfile( "dipsy", "po" );
    checkfile( "po" );
    comparefiles( "dipsy", "po" );


    /*for(i=0;i<2048;i++) {
        diag_printf("<INFO>: churningchurningchurning................................ITERATION = %d\n", i);
        createfile( "churningchurningchurning", 4096 );
        diag_printf("<INFO>: unlink churningchurningchurning\n");
        err = unlink( "churningchurningchurning" );
        if( err < 0 ) SHOW_RESULT( unlink, err );
    }*/


    listdir( ".", true, 5, NULL );
    listdir( "", true, 5, NULL );
    listdir( "..", true, existingdirents+3, NULL );

    // --------------------------------------------------------------

    diag_printf("<INFO>: unlink tinky\n");
    err = unlink( "tinky" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink dipsy\n");
    err = unlink( "dipsy" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink po\n");
    err = unlink( "po" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: cd ..\n");
    err = chdir( ".." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/jffs2" );

    diag_printf("<INFO>: rmdir noonoo\n");
    err = rmdir( "noonoo" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    // --------------------------------------------------------------

    err = mkdir( "x", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    err = mkdir( "x/y", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    err = mkdir( "x/y/z", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    err = mkdir( "x/y/z/w", 0 );
    if( err < 0 ) SHOW_RESULT( mkdir, err );

    diag_printf("<INFO>: cd /jffs2/x/y/z/w\n");
    err = chdir( "/jffs2/x/y/z/w" );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/jffs2/x/y/z/w" );

    diag_printf("<INFO>: cd ..\n");
    err = chdir( ".." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/jffs2/x/y/z" );

    diag_printf("<INFO>: cd .\n");
    err = chdir( "." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/jffs2/x/y/z" );

    diag_printf("<INFO>: cd ../../y\n");
    err = chdir( "../../y" );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/jffs2/x/y" );

    diag_printf("<INFO>: cd ../..\n");
    err = chdir( "../.." );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/jffs2" );

    diag_printf("<INFO>: rmdir x/y/z/w\n");
    err = rmdir( "x/y/z/w" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    diag_printf("<INFO>: rmdir x/y/z\n");
    err = rmdir( "x/y/z" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    diag_printf("<INFO>: rmdir x/y\n");
    err = rmdir( "x/y" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    diag_printf("<INFO>: rmdir x\n");
    err = rmdir( "x" );
    if( err < 0 ) SHOW_RESULT( rmdir, err );

    // --------------------------------------------------------------

    diag_printf("<INFO>: unlink tinky\n");
    err = unlink( "tinky" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: unlink laalaa\n");
    err = unlink( "laalaa" );
    if( err < 0 ) SHOW_RESULT( unlink, err );

    diag_printf("<INFO>: cd /\n");
    err = chdir( "/" );
    if( err < 0 ) SHOW_RESULT( chdir, err );
    checkcwd( "/" );

    diag_printf("<INFO>: umount /jffs2\n");
    err = umount( "/jffs2" );
    if( err < 0 ) SHOW_RESULT( umount, err );

    diag_printf("<INFO>: umount /\n");
    err = umount( "/" );
    if( err < 0 ) SHOW_RESULT( umount, err );

    CYG_TEST_PASS_FINISH("jffs2_1");
}
Exemple #28
0
// Copy
//------------------------------------------------------------------------------
/*static*/ bool FileIO::FileCopy( const char * srcFileName, const char * dstFileName,
							  bool allowOverwrite )
{
#if defined( __WINDOWS__ )
	BOOL failIfDestExists = ( allowOverwrite ? FALSE : TRUE );
	BOOL result = CopyFile( srcFileName, dstFileName, failIfDestExists );
	if ( result == FALSE )
	{
		// even if we allow overwrites, Windows will fail if the dest file
		// was read only, so we have to un-mark the read only status and try again
		if ( ( GetLastError() == ERROR_ACCESS_DENIED ) && ( allowOverwrite ) )
		{
			// see if dst file is read-only
			DWORD dwAttrs = GetFileAttributes( dstFileName );
			if ( dwAttrs == INVALID_FILE_ATTRIBUTES )
			{
				return false; // can't even get the attributes, nothing more we can do
			}
			if ( 0 == ( dwAttrs & FILE_ATTRIBUTE_READONLY ) ) 
			{ 
				return false; // file is not read only, so we don't know what the problem is
			}

			// try to remove read-only flag on dst file
			dwAttrs = ( dwAttrs & ~FILE_ATTRIBUTE_READONLY );
			if ( FALSE == SetFileAttributes( dstFileName, dwAttrs ) )
			{
				return false; // failed to remove read-only flag
			}

			// try to copy again
			result = CopyFile( srcFileName, dstFileName, failIfDestExists );
			return ( result == TRUE );
		}
	}

	return ( result == TRUE );
#elif defined( __APPLE__ )
    if ( allowOverwrite == false )
    {
        if ( FileExists( dstFileName ) )
        {
            return false;
        }
    }
    copyfile_state_t s;
    s = copyfile_state_alloc();
    bool result = ( copyfile( srcFileName, dstFileName, s, COPYFILE_DATA | COPYFILE_XATTR ) == 0 );
    copyfile_state_free(s);
    return result;
#elif defined( __LINUX__ )
    if ( allowOverwrite == false )
    {
        if ( FileExists( dstFileName ) )
        {
            return false;
        }
    }
    
    int source = open( srcFileName, O_RDONLY, 0 );
    if ( source < 0 )
    {
        return false;
    }
    
    int dest = open( dstFileName, O_WRONLY | O_CREAT | O_TRUNC, 0644 ); // TODO:LINUX Check args for FileCopy dst
    if ( dest < 0 )
    {
        close( source );
        return false;
    }
    
    struct stat stat_source;
    VERIFY( fstat( source, &stat_source ) == 0 );

    ssize_t bytesCopied = sendfile( dest, source, 0, stat_source.st_size );
    
    close(source);
    close(dest);

    return ( bytesCopied == stat_source.st_size );
#else
    #error Unknown platform
#endif
}
Exemple #29
0
int main(int argc, char *argv[])
{

	int  src, dest;
	struct stat64 sbuf, sbuf2;
	time_t copy_time;
	off64_t size=0, total_size;
	size_t buffer_size = DEFAULT_BUFFER; /* transfer buffer size */
	int rc ;
	char filename[MAXPATHLEN],*inpfile, *outfile;
	char formatted_rate[12], formatted_size[12];
	char extraOption[MAXPATHLEN];
	char allocSpaceOption[MAXPATHLEN];
	char *cp ;
	int c;
	int overwrite = 1;
	int isStdin = 0;
	mode_t mode = 0666;
	char *firstP, *lastP;
	unsigned short first_port, last_port;
	int stage = 0;
	int stagetime = 0;
	int unsafeWrite = 0;
	char *stagelocation = NULL;
	int ahead = 0;
	size_t ra_buffer_size = 1048570L;
	int doCheckSum = 1;

	/* for getopt */
	extern char *optarg;
	extern int optind;

	if (argc < 3) {
		usage();
	}

	extraOption[0] = '\0';
	allocSpaceOption[0] = '\0';

	if( getenv("DCACHE_SHOW_PROGRESS") != NULL) {
		is_feedback_enabled = 1;
	}

	/* FIXME removing the DC_LOCAL_CACHE_BUFFER environment
	 * variable vetos dcap's use of the lcb (the local cache).
	 * This is an ugly work-around needed because the current lcb
	 * code gives terrible performance when the client streams
	 * data in large chunks.  Rather than rewrite LCB, we
	 * introduce this as a "temporary" work-around.
	 *
	 * Although clients should tune their software for their
	 * access patterns, this is "impossible" (or at least
	 * unlikely); therefore LCB should be rewritten to provide
	 * better performance in this case.
	 */
	unsetenv("DC_LOCAL_CACHE_BUFFER");

	while( (c = getopt(argc, argv, "Ad:o:h:iX:Pt:l:aB:b:up:T:r:s:w:cC:H")) != EOF) {

		switch(c) {
			case 'd':
				dc_setStrDebugLevel(optarg);
				break;
			case 'o':
				dc_setOpenTimeout(atol(optarg));
				break;
			case 'h':
				dc_setReplyHostName(optarg);
				break;
			case 'i':
				overwrite = 0;
				break;
			case 'P':
				stage = 1;
				break;
			case 't' :
				stagetime = atoi(optarg);
				break;
			case 'l' :
				stagelocation = optarg;
				break;
			case 'B' :
				buffer_size = atol(optarg);
				break;
			case 'a' :
				ahead = 1;
				break;
			case 'b' :
				ra_buffer_size = atol(optarg);
				break;
			case 'X':
				dc_snaprintf(extraOption, sizeof(extraOption), " %s", optarg);
				break;
			case 'u':
				unsafeWrite = 1;
				break;
			case 'p':
				lastP = strchr(optarg, ':');
				if( lastP == NULL ) {
				    first_port = atoi(optarg);
					last_port = first_port;
				}else{
				    firstP = optarg; /*just to be simple */
					lastP[0] = '\0';

				    first_port = atoi(firstP);
					last_port = atoi(lastP +1);

				}

				dc_setCallbackPortRange(first_port, last_port);
				break;
			case 'T':
				dc_setTunnel(optarg);
				break;
			case 'r':
				dc_setTCPReceiveBuffer( atoi(optarg) );
				break;
			case 's':
				dc_setTCPSendBuffer( atoi(optarg) );
				break;
			case 'w':
				dc_setTunnelType(optarg);
				break;
			case 'c':
				doCheckSum = 0;
				break;
			case 'A':
				dc_setClientActive();
				break;
			case 'C':
				dc_setCloseTimeout(atoi(optarg));
				break;
		        case 'H':
				is_feedback_enabled=1;
				break;
			case '?':
				usage();

		}
	}

	if(((argc - optind) != 2) && (!stage)) {
		usage();
	}

#ifndef WIN32
	dcap_signal();
#endif

	inpfile = argv[optind];
	if(stage) {
		dc_setExtraOption(extraOption);
		if ( (rc = dc_stage(inpfile, stagetime, stagelocation)) < 0 ) {
			dc_perror("dc_stage fail");
			rc = -1;
		}
		return rc;
	}

	outfile = argv[optind+1];

#ifndef WIN32
	if(strcmp(inpfile, "-") == 0) {
		isStdin = 1;
		src = fileno(stdin);
		inpfile = strdup("/dev/stdin");
	}

	if(strcmp(outfile, "-") == 0) {
		outfile = strdup("/dev/stdout");
	}
#endif /* WIN32 */

	if(!isStdin) {
		dc_setExtraOption(extraOption);
		rc = dc_stat64(inpfile, &sbuf);
		if ( (rc == 0) && ( S_ISDIR(sbuf.st_mode) || S_ISCHR(sbuf.st_mode)) ) {
			fprintf(stderr,"file %s: Not a regular file\n",inpfile);
			return -1 ;
		}

		if( rc == 0 ) {
			/* if file do not exist it can be a url, and
				dc_open will handle this */
			mode = sbuf.st_mode & 0777;
			/* tell to pool how many bytes we want to write */
#ifdef WIN32
			dc_snaprintf(allocSpaceOption, sizeof(allocSpaceOption),
			             " -alloc-size=%lld", (__int64)sbuf.st_size);
#else
			dc_snaprintf(allocSpaceOption, sizeof(allocSpaceOption),
			             " -alloc-size=%lld", (long long)sbuf.st_size);
#endif
		}
		total_size = sbuf.st_size;
	} else {
		total_size = SIZE_FOR_UNKNOWN_TRANSFER_LENGTH;
	}

	dc_setExtraOption(extraOption);
	if ( dc_stat64( outfile, &sbuf2) == 0 &&  S_ISDIR(sbuf2.st_mode) ) {
		if ( (cp = strrchr(inpfile,PATH_SEPARATOR))  != NULL  ) {
			cp++;
		}else{
			cp = inpfile;
		}
		sprintf(filename, "%s%c%s", outfile, PATH_SEPARATOR, cp);
	}else{
		strcpy(filename,outfile) ;
	}

	dc_setExtraOption(extraOption);
	if((!overwrite) && (dc_access(filename, F_OK) == 0)) {
		fprintf(stderr, "%s: Skipping existing file %s.\n", argv[0], filename);
		return 0;
	}

	errno = 0 ;

	if(!isStdin) {
		dc_setExtraOption(extraOption);
		src = dc_open(inpfile,O_RDONLY | O_BINARY );
		if (src < 0) {
			dc_perror("Can't open source file");
			return -1;
		}
	}

	if(!ahead || (ra_buffer_size <= buffer_size)) {
		dc_noBuffering(src);
	}else{
		dc_setBufferSize(src,ra_buffer_size);
	}

	errno = 0 ;

#ifdef WIN32
	mode = _S_IWRITE ;
#endif /* WIN32 */

	dc_setExtraOption(extraOption);
	dc_setExtraOption(allocSpaceOption);
	dest = dc_open( filename, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, mode|S_IWUSR);
	if (dest < 0) {
		dc_perror("Can't open destination file");
		return -1;
	}

	if(unsafeWrite) {
		dc_unsafeWrite(dest);
	}

	if( ! doCheckSum ) {
		dc_noCheckSum(dest);
	}

	elapsed_transfer_time( ett_set);
	rc = copyfile(src, dest, buffer_size, &size, total_size);

	if (dc_close(src) < 0) {
		perror("Failed to close source file");
		rc = -1;
	}

	if (dc_close(dest) < 0) {
		perror("Failed to close destination file");
		dc_stat64( outfile, &sbuf2);
		mode = sbuf2.st_mode & S_IFMT;
		if (mode == S_IFREG) dc_unlink(outfile);
		rc = -1;
	}

	if (rc != -1 )  {
		copy_time = elapsed_transfer_time(ett_measure);
		dc_bytes_as_size(formatted_size, size);
		fprintf(stderr,"%ld bytes (%s) in %lu seconds", size, formatted_size, copy_time);
		if ( copy_time > 0) {
			dc_bytes_as_size(formatted_rate, (double)size / copy_time);
			fprintf(stderr," (%s/s)\n", formatted_rate);
		}else{
			fprintf(stderr,"\n");
		}
	}else{
		fprintf(stderr,"dccp failed.\n");

		/* remove destination if copy failed */
		dc_stat64( outfile, &sbuf2);
		mode = sbuf2.st_mode & S_IFMT;
		if (mode == S_IFREG) dc_unlink(outfile);
	}

	return rc;
}
Exemple #30
0
BOOL extra_kingdom_ins_disk(char* kingdom_src, char* kingdom_ins, char* kingdom_ins_android)
{
	char text1[_MAX_PATH], text2[_MAX_PATH];
	BOOL fok;
	walk_campaign_param_t wcp;

	MakeDirectory(std::string(kingdom_ins));

	// 清空目录
	fok = delfile1(kingdom_ins);
	if (!fok) {
		posix_print_mb("删除目录: %s,失败", kingdom_ins);
		return fok;
	}
	fok = delfile1(kingdom_ins_android);
	if (!fok) {
		posix_print_mb("删除目录: %s,失败", kingdom_ins_android);
		// return fok;
	}

	//
	// <kingdom-src>\data
	//

	// 1. images in all campaigns
	wcp.src_campaign_dir = std::string(kingdom_src) + "\\data\\campaigns";
	wcp.ins_campaign_dir = std::string(kingdom_ins) + "\\data\\campaigns";
	fok = walk_dir_win32_deepen(wcp.src_campaign_dir.c_str(), 0, cb_walk_campaign, (uint32_t *)&wcp);
	if (!fok) {
		return fok;
	}
	wcp.ins_campaign_dir = std::string(kingdom_ins_android) + "\\data\\campaigns";
	fok = walk_dir_win32_deepen(wcp.src_campaign_dir.c_str(), 0, cb_walk_campaign, (uint32_t *)&wcp);
	if (!fok) {
		return fok;
	}

	// 2. images in <data>\core root
	MakeDirectory(std::string("") + kingdom_ins + "\\data\\core");
	sprintf(text1, "%s\\data\\core\\images", kingdom_src);
	sprintf(text2, "%s\\data\\core\\images", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	MakeDirectory(std::string("") + kingdom_ins_android + "\\data\\core");
	sprintf(text2, "%s\\data\\core\\images", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// 3. music in <data>\core root
	sprintf(text1, "%s\\data\\core\\music", kingdom_src);
	sprintf(text2, "%s\\data\\core\\music", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\data\\core\\music", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// 4. sounds in <data>\core root
	sprintf(text1, "%s\\data\\core\\sounds", kingdom_src);
	sprintf(text2, "%s\\data\\core\\sounds", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\data\\core\\sounds", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}

	sprintf(text1, "%s\\data\\hardwired", kingdom_src);
	sprintf(text2, "%s\\data\\hardwired", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\data\\hardwired", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}

	sprintf(text1, "%s\\data\\lua", kingdom_src);
	sprintf(text2, "%s\\data\\lua", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\data\\lua", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}

	sprintf(text1, "%s\\data\\tools", kingdom_src);
	sprintf(text2, "%s\\data\\tools", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\data\\tools", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// <kingdom-src>\data\_main_cfg
	sprintf(text1, "%s\\data\\_main.cfg", kingdom_src);
	sprintf(text2, "%s\\data\\_main.cfg", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制文件,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\data\\_main.cfg", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制文件,从%s到%s,失败", text1, text2);
		goto exit;
	}
	//
	// <kingdom-src>\fonts
	//
	sprintf(text1, "%s\\fonts", kingdom_src);
	sprintf(text2, "%s\\fonts", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\fonts", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	//
	// <kingdom-src>\images
	//
	sprintf(text1, "%s\\images", kingdom_src);
	sprintf(text2, "%s\\images", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\images", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	//
	// <kingdom-src>\manual
	//
	sprintf(text1, "%s\\manual", kingdom_src);
	sprintf(text2, "%s\\manual", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// andorid don't copy manual

	//
	// <kingdom-src>\sounds
	//
	sprintf(text1, "%s\\sounds", kingdom_src);
	sprintf(text2, "%s\\sounds", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\sounds", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	//
	// <kingdom-src>\translations
	//
	sprintf(text1, "%s\\translations", kingdom_src);
	sprintf(text2, "%s\\translations", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\translations", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	//
	// <kingdom-src>\xwml
	//
	sprintf(text1, "%s\\xwml", kingdom_src);
	sprintf(text2, "%s\\xwml", kingdom_ins);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}
	// android
	sprintf(text2, "%s\\xwml", kingdom_ins_android);
	posix_print("<data>, copy %s to %s ......\n", text1, text2);
	fok = copyfile(text1, text2);
	if (!fok) {
		posix_print_mb("复制目录,从%s到%s,失败", text1, text2);
		goto exit;
	}

	fok = copy_root_files(kingdom_src, kingdom_ins);
exit:
	if (!fok) {
		delfile1(kingdom_ins);
	}

	return fok;
}