示例#1
2
int main(int argc,char *argv[]) {
	DIR *dfd;
	struct dirent *dp;
	char filename[NAME_MAX];
	char absfilename[NAME_MAX];
	char foldername[NAME_MAX];
	char tempchar[NAME_MAX];
	char buffer[BUF_SIZE];
	char bytesname;
	char *stroka;
	ssize_t read_bytes;
	ssize_t data_read_bytes;
	ssize_t data_need_bytes;
	ssize_t written_bytes;
	int inp_file_d;
	int out_file_d;
	struct stat statfile;
	if (argc!=4) {
		printf("Arguments required.\narchivator -glue/-unglue ");
		printf("input_folder/input_file output_file/output_folder\n");
	} else {
		if (strcmp(argv[1],"-glue")==0) {
			printf("Glue operation is started.\n");
			strcpy(foldername, argv[2]);
			strcpy(filename, argv[3]);
			dfd=opendir(foldername);
			//out_file_d=open(filename, O_RDWR|O_CREAT, S_IWUSR | S_IRUSR);
			out_file_d=creat(filename, S_IWUSR | S_IRUSR);
			while((dp=readdir(dfd))!=NULL) {
				if(strcmp(dp->d_name,".")!=0 &&
				strcmp(dp->d_name,"..")!=0) {
					memset(absfilename,0,sizeof(absfilename));
					sprintf(absfilename,"./%s/%s", foldername, dp->d_name);
					printf("Open file: %s...\n",absfilename);
					inp_file_d=open(absfilename, O_RDONLY);
					fstat(inp_file_d, &statfile);
					//printf(" %s %lld", dp->d_name, (long long)statfile.st_size);
					memset(tempchar,0,sizeof(tempchar));
					sprintf(tempchar,"%s", dp->d_name);
					//printf(" %s", tempchar);
					bytesname=strlen(tempchar);
					//printf("%d\n",bytesname);
					written_bytes=write(out_file_d, &bytesname, 1);
					written_bytes=write(out_file_d, tempchar, bytesname);
					memset(tempchar,0,sizeof(tempchar));
					sprintf(tempchar,"%lld", (long long)statfile.st_size);
					//printf(" %s", tempchar);
					stroka=inttobytes((long long)statfile.st_size);
					//printf("%s\n%d\n",stroka,bytestoint(stroka));
					bytesname=strlen(stroka);
					written_bytes=write(out_file_d, &bytesname, 1);
					written_bytes=write(out_file_d, stroka, bytesname);
					data_read_bytes=(size_t)0;
					do {
						read_bytes=read(inp_file_d, buffer,BUF_SIZE);
						//printf("%s\n%lld\n",buffer,(long long)read_bytes);
						data_read_bytes+=read_bytes;
						written_bytes=write(out_file_d, buffer, read_bytes);
					} while(data_read_bytes!=statfile.st_size);
					close(inp_file_d);
					printf("File %s successfully added to archieve.\n",absfilename);
				}
			}
			close(out_file_d);
			closedir(dfd);
			printf("\nClue operation is completed.\n");
		} else if (strcmp(argv[1],"-unglue")==0) {
			printf("Unglue operation is started.\n");
			strcpy(filename, argv[2]);
			strcpy(foldername, argv[3]);
			//dfd=opendir(foldername);
			mkdir(foldername,DEFAULT_MODE);
			inp_file_d=open(filename, O_RDONLY);
			memset(tempchar,0,sizeof(tempchar));
			do {
				read_bytes=read(inp_file_d, tempchar,1);
				if (read_bytes==(size_t)0) break;
				bytesname=tempchar[0];
				memset(tempchar,0,sizeof(tempchar));
				read_bytes=read(inp_file_d, tempchar,bytesname);
				memset(absfilename,0,sizeof(absfilename));
				sprintf(absfilename,"./%s/%s", foldername, tempchar);
				out_file_d=open(absfilename, O_RDWR|O_CREAT, S_IWUSR | S_IRUSR);
				printf("Unclue file %s.\n", absfilename);
				read_bytes=read(inp_file_d, tempchar,1);
				bytesname=tempchar[0];
				memset(tempchar,0,sizeof(tempchar));
				read_bytes=read(inp_file_d, tempchar,bytesname);
				//printf("%s.\n", tempchar);
				long long tempbytes=0;
				//sscanf(tempchar,"%lld",&tempbytes);
				tempbytes=bytestoint(tempchar);
				data_need_bytes=(size_t) tempbytes;
				printf("%lld bytes.\n", (long long)data_need_bytes);
				//printf("debug\n");
				do {
					if (BUF_SIZE<=data_need_bytes) {
						read_bytes=read(inp_file_d, buffer,BUF_SIZE);
					} else {
						read_bytes=read(inp_file_d, buffer,data_need_bytes);
					}
					data_need_bytes-=read_bytes;
					//printf("%s\n%lld\n",buffer,(long long)read_bytes);
					written_bytes=write(out_file_d, buffer, read_bytes);
				} while(data_need_bytes!=(size_t)0);
				close(out_file_d);
				printf("File %s unclued.\n", absfilename);
			} while(1);
			close(inp_file_d);
			//closedir(dfd);
			printf("Unclue operation is completed.\n");
		} else {
			printf ("Wrong second argument.\n");
		}
	}
	return 0;
}
示例#2
0
/* recursively create the directory named by 'pathname'
 * (similar to "mkdir -p" on the command line) */
int rrd_mkdir_p(const char *pathname_unsafe, mode_t mode)
{
    struct stat sb;

    char *pathname;
    char *pathname_copy;
    char *base_dir;

    if ((NULL == pathname_unsafe) || ('\0' == *pathname_unsafe)) {
        errno = EINVAL;
        return -1;
    }

    /* dirname returns repeatedly same pointer - make pathname safe (bsd)*/
    if (NULL == (pathname = strdup(pathname_unsafe)))
        return -1;

    if (0 == stat(pathname, &sb)) {
        free(pathname);
        if (! S_ISDIR(sb.st_mode)) {
            errno = ENOTDIR;
            return -1;
        }
        return 0;
    }

    /* keep errno as set by stat() */
    if (ENOENT != errno) {
        free(pathname);
        return -1;
    }

    /* dirname might modify its first argument */
    if (NULL == (pathname_copy = strdup(pathname))) {
        free(pathname);
        return -1;
    }

#ifndef _MSC_VER
    /* the data pointed to by dirname might change too (bsd) */
    if (NULL == (base_dir = strdup(dirname(pathname_copy)))) {
        free(pathname);
        free(pathname_copy);
        return -1;
    }
#else
    if (NULL == (base_dir = strdup(pathname_copy))) {
        free(pathname);
        free(pathname_copy);
        return -1;
    }

    _splitpath(pathname_copy, NULL, base_dir, NULL, NULL);
#endif

    if (0 != rrd_mkdir_p(base_dir, mode)) {
        int orig_errno = errno;
        free(pathname);
        free(pathname_copy);
        free(base_dir);
        errno = orig_errno;
        return -1;
    }

    free(pathname_copy);
    free(base_dir);

    /* keep errno as set by mkdir() */
#ifdef _MSC_VER
    if (0 != mkdir(pathname)) {
        free(pathname);
        return -1;
    }
#else
    if ((mkdir(pathname, mode) != 0) && (errno != EEXIST)) {
        free(pathname);
        return -1;
    }
#endif
    free(pathname);
    return 0;
} /* rrd_mkdir_p */
示例#3
0
int main(int argc, char *argv[])
{
    struct stat st;
    static int socket_serv_fd = -1;
    char buf[64], shell[PATH_MAX], *result, debuggable[PROPERTY_VALUE_MAX];
    char enabled[PROPERTY_VALUE_MAX], build_type[PROPERTY_VALUE_MAX];
    char root_settings[PROPERTY_VALUE_MAX];
    int i, dballow;
    mode_t orig_umask;

    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command")) {
            if (++i < argc) {
                su_to.command = argv[i];
            } else {
                usage();
            }
        } else if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--shell")) {
            if (++i < argc) {
                strncpy(shell, argv[i], sizeof(shell));
                shell[sizeof(shell) - 1] = 0;
            } else {
                usage();
            }
        } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) {
            printf("%s\n", VERSION);
            exit(EXIT_SUCCESS);
        } else if (!strcmp(argv[i], "-V")) {
            printf("%d\n", VERSION_CODE);
            exit(EXIT_SUCCESS);
        } else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
            usage();
        } else if (!strcmp(argv[i], "-") || !strcmp(argv[i], "-l") ||
                !strcmp(argv[i], "--login")) {
            ++i;
            break;
        } else {
            break;
        }
    }
    if (i < argc-1) {
        usage();
    }
    if (i == argc-1) {
        struct passwd *pw;
        pw = getpwnam(argv[i]);
        if (!pw) {
            su_to.uid = atoi(argv[i]);
        } else {
            su_to.uid = pw->pw_uid;
        }
    }

    if (from_init(&su_from) < 0) {
        deny();
    }

    property_get("ro.debuggable", debuggable, "0");
    property_get(ROOT_ACCESS_PROPERTY, enabled, ROOT_ACCESS_DEFAULT);
    property_get("ro.build.type", build_type, "");
    property_get(ROOT_SETTINGS_PROPERTY, root_settings, "");

    orig_umask = umask(027);

    // Root Settings-specific behavior
    if (strcmp("1", root_settings) == 0) {
        // only allow su on debuggable builds
        if (strcmp("1", debuggable) != 0) {
            LOGE("Root access is disabled on non-debug builds");
            deny();
        }

        // enforce persist.sys.root_access on non-eng builds
        if (strcmp("eng", build_type) != 0 &&
               (atoi(enabled) & 1) != 1 ) {
            LOGE("Root access is disabled by system setting - enable it under settings -> developer options");
            deny();
        }

        // disallow su in a shell if appropriate
        if (su_from.uid == AID_SHELL && (atoi(enabled) == 1)) {
            LOGE("Root access is disabled by a system setting - enable it under settings -> developer options");
            deny();
        }
    }

    if (su_from.uid == AID_ROOT || su_from.uid == AID_SHELL)
        allow(shell, orig_umask);

    if (stat(REQUESTOR_DATA_PATH, &st) < 0) {
        PLOGE("stat");
        deny();
    }

    if (st.st_gid != st.st_uid)
    {
        LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
                (int)st.st_uid, (int)st.st_gid);
        deny();
    }

    if (mkdir(REQUESTOR_CACHE_PATH, 0770) >= 0) {
        chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
    }

    setgroups(0, NULL);
    setegid(st.st_gid);
    seteuid(st.st_uid);

    LOGE("sudb - Opening database");
    db = database_init();
    if (!db) {
        LOGE("sudb - Could not open database, prompt user");
        // if the database could not be opened, we can assume we need to
        // prompt the user
        dballow = DB_INTERACTIVE;
    } else {
        LOGE("sudb - Database opened");
        dballow = database_check(db, &su_from, &su_to);
        // Close the database, we're done with it. If it stays open,
        // it will cause problems
        sqlite3_close(db);
        db = NULL;
        LOGE("sudb - Database closed");
    }

    switch (dballow) {
        case DB_DENY: deny();
        case DB_ALLOW: allow(shell, orig_umask);
        case DB_INTERACTIVE: break;
        default: deny();
    }
    
    socket_serv_fd = socket_create_temp();
    if (socket_serv_fd < 0) {
        deny();
    }

    signal(SIGHUP, cleanup_signal);
    signal(SIGPIPE, cleanup_signal);
    signal(SIGTERM, cleanup_signal);
    signal(SIGABRT, cleanup_signal);
    atexit(cleanup);

    if (send_intent(&su_from, &su_to, socket_path, -1, 0) < 0) {
        deny();
    }

    if (socket_receive_result(socket_serv_fd, buf, sizeof(buf)) < 0) {
        deny();
    }

    close(socket_serv_fd);
    socket_cleanup();

    result = buf;

    if (!strcmp(result, "DENY")) {
        deny();
    } else if (!strcmp(result, "ALLOW")) {
        allow(shell, orig_umask);
    } else {
        LOGE("unknown response from Superuser Requestor: %s", result);
        deny();
    }

    deny();
    return -1;
}
示例#4
0
文件: fs.c 项目: SeriousBug/firejail
// chroot into an existing directory; mount exiting /dev and update /etc/resolv.conf
void fs_chroot(const char *rootdir) {
	assert(rootdir);
	
	//***********************************
	// mount-bind a /dev in rootdir
	//***********************************
	// mount /dev
	char *newdev;
	if (asprintf(&newdev, "%s/dev", rootdir) == -1)
		errExit("asprintf");
	if (arg_debug)
		printf("Mounting /dev on %s\n", newdev);
	if (mount("/dev", newdev, NULL, MS_BIND|MS_REC, NULL) < 0)
		errExit("mounting /dev");
	
	// some older distros don't have a /run directory
	// create one by default
	// no exit on error, let the user deal with any problems
	char *rundir;
	if (asprintf(&rundir, "%s/run", rootdir) == -1)
		errExit("asprintf");
	if (!is_dir(rundir)) {
		int rv = mkdir(rundir, S_IRWXU | S_IRWXG | S_IRWXO);
		(void) rv;
		rv = chown(rundir, 0, 0);
		(void) rv;
	}
	
	// copy /etc/resolv.conf in chroot directory
	// if resolv.conf in chroot is a symbolic link, this will fail
	// no exit on error, let the user deal with the problem
	char *fname;
	if (asprintf(&fname, "%s/etc/resolv.conf", rootdir) == -1)
		errExit("asprintf");
	if (arg_debug)
		printf("Updating /etc/resolv.conf in %s\n", fname);
	if (copy_file("/etc/resolv.conf", fname) == -1)
		fprintf(stderr, "Warning: /etc/resolv.conf not initialized\n");
		
	// chroot into the new directory
	if (arg_debug)
		printf("Chrooting into %s\n", rootdir);
	if (chroot(rootdir) < 0)
		errExit("chroot");
	// mount a new tmpfs in /run/firejail/mnt - the old one was lost in chroot
	fs_build_remount_mnt_dir();
		
	// update /var directory in order to support multiple sandboxes running on the same root directory
	if (!arg_private_dev)
		fs_dev_shm();
	fs_var_lock();
	fs_var_tmp();
	fs_var_log();
	fs_var_lib();
	fs_var_cache();
	fs_var_utmp();

	// don't leak user information
	restrict_users();

	disable_firejail_config();
}
示例#5
0
bool User::saveData()
{
    std::string outfile = Map::get().mapDirectory+"/players/"+this->nick+".dat";
    // Try to create parent directories if necessary
    struct stat stFileInfo;
    if(stat(outfile.c_str(), &stFileInfo) != 0)
    {
        std::string outdir = Map::get().mapDirectory+"/players";

        if(stat(outdir.c_str(), &stFileInfo) != 0)
        {
#ifdef WIN32
            if(_mkdir(outdir.c_str()) == -1)
#else
            if(mkdir(outdir.c_str(), 0755) == -1)
#endif

                return false;
        }
    }

    NBT_Value val(NBT_Value::TAG_COMPOUND);
    val.Insert("OnGround", new NBT_Value((sint8)1));
    val.Insert("Air", new NBT_Value((sint16)300));
    val.Insert("AttackTime", new NBT_Value((sint16)0));
    val.Insert("DeathTime", new NBT_Value((sint16)0));
    val.Insert("Fire", new NBT_Value((sint16)-20));
    val.Insert("Health", new NBT_Value((sint16)health));
    val.Insert("HurtTime", new NBT_Value((sint16)0));
    val.Insert("FallDistance", new NBT_Value(54.f));

    NBT_Value *nbtInv = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_COMPOUND);

    //Start with main items
    Item *slots   = (Item *)&inv.main;
    char slotid   = 0;
    char itemslot = 0;
    for(int i = 0; i < 36+4+4; i++)
    {
        //Crafting items after main
        if(i == 36)
        {
            slots    = (Item *)&inv.crafting;
            itemslot = 80;
            slotid   = 0;
        }
        //Equipped items last
        else if(i == 36+4)
        {
            slots    = (Item *)&inv.equipped;
            itemslot = 100;
            slotid   = 0;
        }
        if(slots[(uint8)slotid].count)
        {
            NBT_Value *val = new NBT_Value(NBT_Value::TAG_COMPOUND);
            val->Insert("Count", new NBT_Value((sint8)slots[(uint8)slotid].count));
            val->Insert("Slot", new NBT_Value((sint8)itemslot));
            val->Insert("Damage", new NBT_Value((sint16)slots[(uint8)slotid].health));
            val->Insert("id", new NBT_Value((sint16)slots[(uint8)slotid].type));
            nbtInv->GetList()->push_back(val);
        }

        slotid++;
        itemslot++;
    }

    val.Insert("Inventory", nbtInv);

    NBT_Value *nbtPos = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_DOUBLE);
    nbtPos->GetList()->push_back(new NBT_Value((double)pos.x));
    nbtPos->GetList()->push_back(new NBT_Value((double)pos.y));
    nbtPos->GetList()->push_back(new NBT_Value((double)pos.z));
    val.Insert("Pos", nbtPos);


    NBT_Value *nbtRot = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_FLOAT);
    nbtRot->GetList()->push_back(new NBT_Value((float)pos.yaw));
    nbtRot->GetList()->push_back(new NBT_Value((float)pos.pitch));
    val.Insert("Rotation", nbtRot);


    NBT_Value *nbtMotion = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_DOUBLE);
    nbtMotion->GetList()->push_back(new NBT_Value((double)0.0));
    nbtMotion->GetList()->push_back(new NBT_Value((double)0.0));
    nbtMotion->GetList()->push_back(new NBT_Value((double)0.0));
    val.Insert("Motion", nbtMotion);

    val.SaveToFile(outfile);

    return true;

}
示例#6
0
static void copydir(const char * src, const char * dst)
{
    struct dfs_fd fd;
    struct dirent dirent;
    struct stat stat;
    int length;

    if (dfs_file_open(&fd, src, DFS_O_DIRECTORY) < 0)
    {
        rt_kprintf("open %s failed\n", src);
        return ;
    }

    do
    {
        rt_memset(&dirent, 0, sizeof(struct dirent));
        length = dfs_file_getdents(&fd, &dirent, sizeof(struct dirent));
        if (length > 0)
        {
            char * src_entry_full = RT_NULL;
            char * dst_entry_full = RT_NULL;

            if (strcmp(dirent.d_name, "..") == 0 || strcmp(dirent.d_name, ".") == 0)
                continue;

            /* build full path for each file */
            if ((src_entry_full = dfs_normalize_path(src, dirent.d_name)) == RT_NULL)
            {
                rt_kprintf("out of memory!\n");
                break;
            }
            if ((dst_entry_full = dfs_normalize_path(dst, dirent.d_name)) == RT_NULL)
            {
                rt_kprintf("out of memory!\n");
                rt_free(src_entry_full);
                break;
            }

            rt_memset(&stat, 0, sizeof(struct stat));
            if (dfs_file_stat(src_entry_full, &stat) != 0)
            {
                rt_kprintf("open file: %s failed\n", dirent.d_name);
                continue;
            }

            if (DFS_S_ISDIR(stat.st_mode))
            {
                mkdir(dst_entry_full, 0);
                copydir(src_entry_full, dst_entry_full);
            }
            else
            {
                copyfile(src_entry_full, dst_entry_full);
            }
            rt_free(src_entry_full);
            rt_free(dst_entry_full);
        }
    }while(length > 0);

    dfs_file_close(&fd);
}
示例#7
0
int main(int argc, char ** argv)
{
    bool success=true;
    const char *versionString = "V3.00 2010_07";

    // Use command line arguments, when some
    if(!processArgv(argc, argv, versionString))
        return 1;

    // some simple check if working dir is dirty
    else
    {
        std::string sdir = std::string(szWorkDirWmo) + "/dir";
        std::string sdir_bin = std::string(szWorkDirWmo) + "/dir_bin";
        struct stat status;
        if (!stat(sdir.c_str(), &status) || !stat(sdir_bin.c_str(), &status))
        {
            printf("Your output directory seems to be polluted, please use an empty directory!\n");
            printf("<press return to exit>");
            char garbage[2];
            scanf("%c", garbage);
            return 1;
        }
    }

    printf("Extract %s. Beginning work ....\n",versionString);
    //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    // Create the working directory
    if(mkdir(szWorkDirWmo
#ifdef __linux__
                    , 0711
#endif
                    ))
            success = (errno == EEXIST);

    // prepare archive name list
    std::vector<std::string> archiveNames;
    fillArchiveNameVector(archiveNames);
    for (size_t i=0; i < archiveNames.size(); ++i)
    {
        MPQArchive *archive = new MPQArchive(archiveNames[i].c_str());
        if(!gOpenArchives.size() || gOpenArchives.front() != archive)
            delete archive;
    }

    if(gOpenArchives.empty())
    {
        printf("FATAL ERROR: None MPQ archive found by path '%s'. Use -d option with proper path.\n",input_path);
        return 1;
    }
    ReadLiquidTypeTableDBC();

    // extract data
    if(success)
        success = ExtractWmo();

    //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    //map.dbc
    if(success)
    {
        DBCFile * dbc = new DBCFile("DBFilesClient\\Map.dbc");
        if(!dbc->open())
        {
            delete dbc;
            printf("FATAL ERROR: Map.dbc not found in data file.\n");
            return 1;
        }
        map_count=dbc->getRecordCount ();
        map_ids=new map_id[map_count];
        for(unsigned int x=0;x<map_count;++x)
        {
            map_ids[x].id=dbc->getRecord (x).getUInt(0);
            strcpy(map_ids[x].name,dbc->getRecord(x).getString(1));
            printf("Map - %s\n",map_ids[x].name);
        }


        delete dbc;
        ParsMapFiles();
        delete [] map_ids;
        //nError = ERROR_SUCCESS;
    }

    printf("\n");
    if(!success)
    {
        printf("ERROR: Extract %s. Work NOT complete.\n   Precise vector data=%d.\nPress any key.\n",versionString, preciseVectorData);
        getchar();
    }

    printf("Extract %s. Work complete. No errors.\n",versionString);
    delete [] LiqType;
    return 0;
}
示例#8
0
/* Function: main
 * 
 * Description: Main function to extract frames from 2 video files and runs the
 *     rest of the program using them. Takes at least 10 commandline arguments, 
 *     in the order: 
 *        <number of camera pairs>
 *        <pair 1 camera 1 filename>
 *        <pair 1 camera 1 frame number>
 *        <pair 1 camera 2 filename>
 *        <pair 1 camera 2 frame number>
 *        <pair 1 view name>
 *        <pair 1 camera coefficients filename>
 *        ...
 *        <TPS smoothing parameter>
 *        <feature detector>
 *        <output directory>
 * 
 * Parameters:
 *     argc: number of commandline arguments
 *     argv: string array of commandline arguments
 * 
 * Returns: 0 on success, 1 on error.
 */
int main (int argc, char *argv[])
{    
    // check for minimum number of commandline arguments
    if (argc < 11)
    {
        printf("Usage:\nvideos\n\t<number of camera pairs>\n\t<pair 1 camera 1 filename>\n\t<pair 1 camera 1 frame number>\n\t<pair 1 camera 2 filename>\n\t<pair 1 camera 2 frame number>\n\t<pair 1 view name>\n\t<pair 1 camera coefficients filename>\n\t...\n\t<TPS smoothing parameter>\n\t<feature detector>\n\t<output directory>\n");
        exit(1);
    }
    
    // get the number of camera pairs
    int numCameraPairs = atoi(argv[1]);
    
    if (numCameraPairs <= 0)
    {
        printf("Invalid number of camera pairs.\n");
        exit(1);
    }
    
    // number of commandline arguments should be numCameraPairs*6 + 5
    if (argc != numCameraPairs*6 + 5)
    {
        printf("Usage:\nvideos\n\t<number of camera pairs>\n\t<pair 1 camera 1 filename>\n\t<pair 1 camera 1 frame number>\n\t<pair 1 camera 2 filename>\n\t<pair 1 camera 2 frame number>\n\t<pair 1 view name>\n\t<pair 1 camera coefficients filename>\n\t...\n\t<TPS smoothing parameter>\n\t<feature detector>\n\t<output directory>\n");
        exit(1);
    }
    
    // allocate memory to store information for camera pairs
    char **camera1Filenames = (char **)malloc(numCameraPairs * sizeof(char *));
    int *camera1Frames = (int *)malloc(numCameraPairs * sizeof(int));
    
    if (camera1Filenames == NULL || camera1Frames == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    char **camera2Filenames = (char **)malloc(numCameraPairs * sizeof(char *));
    int *camera2Frames = (int *)malloc(numCameraPairs * sizeof(int));
    
    if (camera2Filenames == NULL || camera2Frames == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    char **cameraNames = (char **)malloc(numCameraPairs * sizeof(char *));
    
    if (cameraNames == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    char **cameraCoefficientsFilenames = (char **)malloc(numCameraPairs * sizeof(char *));
    
    if (cameraCoefficientsFilenames == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    int argIndex = 2;
    
    for (int i = 0; i < numCameraPairs; i++)
    {        
        camera1Filenames[i] = argv[argIndex];    
        camera1Frames[i] = atoi(argv[argIndex+1]);
        camera2Filenames[i] = argv[argIndex+2];
        camera2Frames[i] = atoi(argv[argIndex+3]);
        cameraNames[i] = argv[argIndex+4];
        cameraCoefficientsFilenames[i] = argv[argIndex+5];
        
        // make sure input video frames are valid
        if (camera1Frames[i] <= 0)
        {
            printf("Invalid frame number for pair %d camera 1.\n", i+1);
            exit(1);
        }
        
        if (camera2Frames[i] <= 0)
        {
            printf("Invalid frame number for pair %d camera 1.\n", i+1);
            exit(1);
        }
        
        // make sure input filenames are valid
        if (!fileExists(camera1Filenames[i]))
        {
            printf("Could not open pair %d camera 1 video file.\n", i+1);
            exit(1);
        }
        
        if (!fileExists(camera2Filenames[i]))
        {
            printf("Could not open pair %d camera 2 video file.\n", i+1);
            exit(1);
        }
        
        if (!fileExists(cameraCoefficientsFilenames[i]))
        {
            printf("Could not open pair %d camera coefficients file.\n", i+1);
            exit(1);
        }
        
        argIndex += 6;
    }
    
    double regularization = atof(argv[argIndex]);
    char *featureDetector = argv[argIndex+1];
    char *outputDirectory = argv[argIndex+2];
            
    // make sure input feature dectector is recognized
    if (strcasecmp(featureDetector, FAST_FEATURE_DETECTOR) &&        
        strcasecmp(featureDetector, GFTT_FEATURE_DETECTOR) &&      
        strcasecmp(featureDetector, SURF_FEATURE_DETECTOR) &&
        strcasecmp(featureDetector, SIFT_FEATURE_DETECTOR) &&
        strcasecmp(featureDetector, SPEEDSIFT_FEATURE_DETECTOR))
    {
        printf("Feature Detector not recognized. Please select from the following:\n\t%s\n\t%s\n\t%s\n\t%s\n\t%s\n",
               FAST_FEATURE_DETECTOR,
               GFTT_FEATURE_DETECTOR,
               SURF_FEATURE_DETECTOR,
               SIFT_FEATURE_DETECTOR,
               SPEEDSIFT_FEATURE_DETECTOR);
        
        exit(1);
    }
    
    // make sure regularization parameter for TPS is valid
    if (regularization <= 0.0 || regularization == HUGE_VAL)
    {
        printf("Invalid smoothing parameter value.\n");
        exit(1);
    }
    
    // if output directory doesn't end with '/' char, append '/' to the string.
    // this is so we can later append a filename to the directory when we want 
    // to write the file to that directory
    if (outputDirectory[strlen(outputDirectory)-1] != '/')
    {
        strcat(outputDirectory, "/");
    }
    
    DIR *dir = opendir(outputDirectory);
    
    // if output directory does not exist, create it with correct permissions
    if (dir == NULL)
    {
        printf("Output directory does not exist.\n");
        
        if (mkdir(outputDirectory, S_IRWXO | S_IRWXG | S_IRWXU))
        {
            printf("Could not create output directory.\n");
            exit(1);
        }
        else
        {
            printf("Created output directory.\n");
        }
    }
    else
    {
        closedir(dir);
    }    
    
    // string for the MATLAB commands
    char command[500]; 
    
    Engine *matlabEngine;
    
    // open MATLAB engine
    if (!(matlabEngine = engOpen("\0")))
    {
        printf("Can't start MATLAB engine\n");        
        exit(1);
    }
    
    // create MATLAB arrays to retrieve values from MATLAB workspace
    mxArray **c1ImageData = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *));
    mxArray **c1ImageDimensions = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *));
    mxArray **c1ImagePaddedWidths = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *));
    
    if (c1ImageData == NULL || c1ImageDimensions == NULL || c1ImagePaddedWidths == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    mxArray **c2ImageData = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *));
    mxArray **c2ImageDimensions = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *));
    mxArray **c2ImagePaddedWidths = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *));
    
    if (c2ImageData == NULL || c2ImageDimensions == NULL || c2ImagePaddedWidths == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    // create IplImage arrays for camera 1 and 2 images for all camera pairs
    IplImage **c1Images = (IplImage **)malloc(numCameraPairs * sizeof(IplImage *));
    IplImage **c2Images = (IplImage **)malloc(numCameraPairs * sizeof(IplImage *));
    
    if (c1Images == NULL || c2Images == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    // for each camera pair, get the specified frames from cameras 1 and 2, using
    // MATLAB functions
    for (int i = 0; i < numCameraPairs; i++)
    {
        char video1Extension[6];
        
        // get the video file extension for the first video file
        if (getVideoFileExtension(camera1Filenames[i], video1Extension) == INVALID_VIDEO_FILE_EXTENSION_ERROR)
        {
            printf("Video files must be of extension .mrf or .cine.\n");
            exit(1);
        }
        
        // call appropriate MATLAB function depending on whether video file is .cine 
        // or .mrf to extract the frame as a MATLAB image. If neither, error.
        if ((strcasecmp(video1Extension, ".cine") == 0) || (strcasecmp(video1Extension, ".cin") == 0))
        {
            sprintf(command, "c1 = cineRead('%s', %d);", camera1Filenames[i], camera1Frames[i]);
            engEvalString(matlabEngine, command);
        }
        else if (strcasecmp(video1Extension, ".mrf") == 0)
        {
            sprintf(command, "c1 = mrfRead('%s', %d);", camera1Filenames[i], camera1Frames[i]);
            engEvalString(matlabEngine, command);
        }
        else
        {
            printf("Videos must be of extension .mrf or .cine.\n");
            exit(1);
        }
        
        char video2Extension[6];
        
        // get the video file extension for the second video file
        if (getVideoFileExtension(camera2Filenames[i], video2Extension) == INVALID_VIDEO_FILE_EXTENSION_ERROR)
        {
            printf("Video files must be of extension .mrf or .cine.\n");
            exit(1);
        }
        
        // call appropriate MATLAB function depending on whether video file is .cine 
        // or .mrf to extract the frame as a MATLAB image. If neither, error.
        if ((strcasecmp(video2Extension, ".cine") == 0) || (strcasecmp(video2Extension, ".cin") == 0))
        {
            sprintf(command, "c2 = cineRead('%s', %d);", camera2Filenames[i], camera2Frames[i]);
            engEvalString(matlabEngine, command);
        }
        else if (strcasecmp(video2Extension, ".mrf") == 0)
        {
            sprintf(command, "c2 = mrfRead('%s', %d);", camera2Filenames[i], camera2Frames[i]);
            engEvalString(matlabEngine, command);
        }
        else
        {
            printf("Videos must be of extension .mrf or .cine.\n");
            exit(1);
        }
        
        // call MATLAB function convert_image_matlab2cv_gs on MATLAB images to convert
        // them into a format that will be compatible with the IplImages of OpenCV
        sprintf(command, "[c1_img c1_dim c1_padded_width] = convert_image_matlab2cv_gs(c1);");    
        engEvalString(matlabEngine, command);
        
        sprintf(command, "[c2_img c2_dim c2_padded_width] = convert_image_matlab2cv_gs(c2);");
        engEvalString(matlabEngine, command);
        
        // retrieve the image data, image dimensions, and image padded width variables 
        // from MATLAB for both camera images
        c1ImageData[i] = engGetVariable(matlabEngine, "c1_img");
        c1ImageDimensions[i] = engGetVariable(matlabEngine, "c1_dim");
        c1ImagePaddedWidths[i] = engGetVariable(matlabEngine, "c1_padded_width");
        
        c2ImageData[i] = engGetVariable(matlabEngine, "c2_img");
        c2ImageDimensions[i] = engGetVariable(matlabEngine, "c2_dim");
        c2ImagePaddedWidths[i] = engGetVariable(matlabEngine, "c2_padded_width");    
        
        if (c1ImageData[i] == NULL || 
            c1ImageDimensions[i] == NULL || 
            c1ImagePaddedWidths[i] == NULL)
        {        
            printf("Could not retrieve all necessary information for pair %d camera 1 frame %d from MATLAB.\n", i+1, camera1Frames[i]);
            exit(1);
        }
        
        if (c2ImageData[i] == NULL || 
            c2ImageDimensions[i] == NULL || 
            c2ImagePaddedWidths[i] == NULL)
        {        
            printf("Could not retrieve all necessary information for pair %d camera 2 frame %d from MATLAB.\n", i+1, camera2Frames[i]);
            exit(1);
        }
        
        int c1Status, c2Status;
        
        ImageInfo c1ImageInfo, c2ImageInfo;            
        
        // extract the image information from the MATLAB variables in the form of 
        // mxArrays, and store in ImageInfo structs
        c1Status = getInputImageInfo(&c1ImageInfo, c1ImageData[i], c1ImageDimensions[i], c1ImagePaddedWidths[i]);
        c2Status = getInputImageInfo(&c2ImageInfo, c2ImageData[i], c2ImageDimensions[i], c2ImagePaddedWidths[i]);
        
        if (c1Status == IMAGE_INFO_DATA_ERROR)
        {
            printf("Pair %d camera 1: Images must have two dimensions.\n", i+1);
            exit(1);
        }
        
        if (c2Status == IMAGE_INFO_DATA_ERROR)
        {
            printf("Pair %d camera 2: Images must have two dimensions.\n", i+1);
            exit(1);
        }
        
        if (c1Status == IMAGE_INFO_DIMENSIONS_ERROR)
        {
            printf("Pair %d camera 1: Image dimension vectors must contain two elements: [width, height].\n", i+1);
            exit(1);
        }
        
        if (c2Status == IMAGE_INFO_DIMENSIONS_ERROR)
        {
            printf("Pair %d camera 2: Image dimension vectors must contain two elements: [width, height].\n", i+1);
            exit(1);
        }
        
        if (c1Status == IMAGE_INFO_PADDED_WIDTH_ERROR)
        {
            printf("Pair %d camera 1: Padded image widths must be scalars.\n", i+1);
            exit(1);
        }
        
        if (c2Status == IMAGE_INFO_PADDED_WIDTH_ERROR)
        {
            printf("Pair %d camera 2: Padded image widths must be scalars.\n", i+1);
            exit(1);
        }
        
        if (c1Status == IMAGE_DEPTH_ERROR)
        {
            printf("Pair %d camera 1: Images must be represented by 8 or 16-bit integers.\n", i+1);
            exit(1);
        }
        
        if (c2Status == IMAGE_DEPTH_ERROR)
        {
            printf("Pair %d camera 2: Images must be represented by 8 or 16-bit integers.\n", i+1);
            exit(1);
        }
        
        // create IplImages using values in ImageInfo structs
        c1Status = createIplImageFromImageInfo(&(c1Images[i]), c1ImageInfo);
        c2Status = createIplImageFromImageInfo(&(c2Images[i]), c2ImageInfo);
        
        if (c1Status == OUT_OF_MEMORY_ERROR ||
            c2Status == OUT_OF_MEMORY_ERROR)
        {
            printf("Out of memory error.\n");
            exit(1);
        }
        
        // flip the images over the y-axis to compensate for the differences in axial
        // labels between MATLAB and OpenCV (camera coefficients would not correctly
        // correspond to image otherwise)
        cvFlip(c1Images[i], NULL, 1);
        cvFlip(c2Images[i], NULL, 1);
    }
    
    char errorMessage[500];
    
    int numContours;
    char **contourNames;
    CvPoint3D32f **features3D;
    char **validFeatureIndicator;
    int *numFeaturesInContours;
    
    char contoursFilename[MAX_FILENAME_LENGTH];
    
    // for each camera pair, run features and triangulation
    for (int i = 0; i < numCameraPairs; i++)
    {
        // create the output 2D features filename as "frame<frame number>_features2D_<camera name>.txt"
        char features2DFilename[MAX_FILENAME_LENGTH];    
        sprintf(features2DFilename, "%sframe%d_features2D_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]);
        
        // create the output contours filename as "frame<frame number>_contours_<camera name>.txt"
        char tempContoursFilename[MAX_FILENAME_LENGTH];    
        sprintf(tempContoursFilename, "%sframe%d_contours_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]);
        
        printf("Camera pair for %s view:\n", cameraNames[i]);
        
        // run the features program to extract matching 2D features from the 2 
        // images within user defined contour
        if (features(c1Images[i], c2Images[i], features2DFilename, tempContoursFilename, featureDetector, errorMessage))
        {
            printf("Features: %s\n", errorMessage);
            exit(1);
        }
        
        // we only need to save the contour(s) for the first camera pair, as that 
        // is the one we will use to create the meshes, and we only use the contours
        // with the same name(s) in subsequent camera pairs
        if (i == 0)
        {
            strcpy(contoursFilename, tempContoursFilename);
            
            // get the contour names of the contours selected in features function for
            // output file naming and contour matching in other camera pairs
            int status = readContourNamesFromInputFile(&numContours, &contourNames, contoursFilename);
            
            if (status == INPUT_FILE_OPEN_ERROR)
            {
                printf("Could not open contour vertices file.\n");
                exit(1);
            }
            
            if (status == INCORRECT_INPUT_FILE_FORMAT_ERROR)
            {
                printf("Contour vertices file has incorrect format.\n");
                exit(1);
            }
            
            if (status == OUT_OF_MEMORY_ERROR)
            {
                printf("Out of memory error.\n");
                exit(1);
            }
            
            // allocate memory for 3D features
            features3D = (CvPoint3D32f **)malloc(numContours * sizeof(CvPoint3D32f *));
            validFeatureIndicator = (char **)malloc(numContours * sizeof(char *));
            numFeaturesInContours = (int *)malloc(numContours * sizeof(int));
            
            if (features3D == NULL || numFeaturesInContours == NULL || validFeatureIndicator == NULL)
            {
                printf("Out of memory error.\n");
                exit(1);
            }
            
            for (int j = 0; j < numContours; j++)
            {
                features3D[j] = (CvPoint3D32f *)malloc(MAX_FEATURES_IN_CONTOUR * sizeof(CvPoint3D32f));
                validFeatureIndicator[j] = (char *)malloc(MAX_FEATURES_IN_CONTOUR * sizeof(char));
                
                if (features3D[j] == NULL || validFeatureIndicator[j] == NULL)
                {
                    printf("Out of memory error.\n");
                    exit(1);
                }
                
                numFeaturesInContours[j] = 0;
            }
        }
        
        // create the output 3D features filename as "frame<frame number>_features3D_<camera name>.txt"
        char features3DFilename[MAX_FILENAME_LENGTH];    
        sprintf(features3DFilename, "%sframe%d_features3D_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]);
        
        // triangulate the matching 2D features between cameras to find the 3D coordinates 
        // of the features, and remove invalid features
        if (triangulation(cameraCoefficientsFilenames[i], features2DFilename, features3DFilename, c1Images[i], errorMessage))
        {
            printf("Triangulation: %s\n", errorMessage);
            exit(1);
        }
        
        // if features from triangulation lie within contours that have the same
        // names as those defined for the first camera pair, add them to the
        // 3D features array for mesh creation
        int status = read3DFeaturesFromFileForMatchingContours(features3DFilename, features3D, numFeaturesInContours, numContours, contourNames);
        
        if (status == INPUT_FILE_OPEN_ERROR)
        {
            printf("Could not open 3D features file.\n");
            exit(1);
        }
        
        if (status == INVALID_NUM_CONTOURS_ERROR)
        {
            printf("At least 1 contour region required.\n");
            exit(1);
        }
        
        if (status == INCORRECT_INPUT_FILE_FORMAT_ERROR)
        {
            printf("3D features file has incorrect format.\n");
            exit(1);
        }
    }        
    
    // for each contour (defined for the first camera pair), perform RANSAC on
    // the cumulative 3D features from all camera pairs that lie within the contour
    for (int i = 0; i < numContours; i++)
    {    
        memset(validFeatureIndicator[i], 1, numFeaturesInContours[i] * sizeof(char));

        // perform RANSAC to remove points that lie too far off a best-fit surface
        if (ransac(features3D[i], validFeatureIndicator[i], numFeaturesInContours[i], errorMessage))
        {
            printf("RANSAC: %s\n", errorMessage);
            exit(1);
        }
        
        int numValidFeatures = 0;
        
        for (int j = 0; j < numFeaturesInContours[i]; j++)
        {
            if (validFeatureIndicator[i][j])
            {
                numValidFeatures++;
            }
        }
        
        printf("Total valid features after RANSAC for contour %s: %d\n", contourNames[i], numValidFeatures);

    }
    
    // create the output 3D features filename for all camera pairs as 
    // "frame<frame number>_features3D.txt", and write the result of RANSAC to
    // the file
    char features3DFilename[MAX_FILENAME_LENGTH];    
    sprintf(features3DFilename, "%sframe%d_features3D.txt", outputDirectory, camera1Frames[0]);
    
    int status = write3DFeaturesToFile(features3D, validFeatureIndicator, numFeaturesInContours, contourNames, numContours, features3DFilename);
    
    if (status == OUTPUT_FILE_OPEN_ERROR)
    {
        sprintf(errorMessage, "Could not open output file.");
        return 1;
    }
    
    char **meshFilenames = (char **)malloc(numContours * sizeof(char *));
    
    if (meshFilenames == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    // for each contour, create a different mesh output file
    for (int i = 0; i < numContours; i++)
    {
        meshFilenames[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char));
        
        if (meshFilenames[i] == NULL)
        {
            printf("Out of memory error.\n");
            exit(1);
        }
        
        // create the output mesh filename as "frame<frame number>_mesh_<contour name>_<camera name>.txt"
        sprintf(meshFilenames[i], "%sframe%d_mesh_%s.txt", outputDirectory, camera1Frames[0], contourNames[i]);
    }
    
    // create the wing meshes from the triangulated 3D points and the user-selected
    // contours, and write each mesh to a different file for each contour
    if (mesh(features3DFilename, contoursFilename, cameraCoefficientsFilenames[0], meshFilenames, numContours, regularization, errorMessage))
    {
        printf("Mesh: %s\n", errorMessage);
        exit(1);
    }
    
    // we only calculate the flow of a wing mesh if there is a mesh file with the
    // same contour name in the output directory for the previous video frame
    char **flowFilenames = (char **)malloc(numContours * sizeof(char *));
    
    if (flowFilenames == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    for (int i = 0; i < numContours; i++)
    {
        flowFilenames[i] = NULL;
    }
    
    int numFilesInDirectory;
    char **filenamesInDirectory = (char **)malloc(MAX_FILES_IN_DIRECTORY * sizeof(char *));
    
    if (filenamesInDirectory == NULL)
    {
        printf("Out of memory error.\n");
        exit(1);
    }
    
    for (int i = 0; i < MAX_FILES_IN_DIRECTORY; i++)
    {
        filenamesInDirectory[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char));
        
        if (filenamesInDirectory[i] == NULL)
        {
            printf("Out of memory error.\n");
            exit(1);
        }
    }
    
    // get all files in the output directory
    getAllFilenamesInDirectory(outputDirectory, &numFilesInDirectory, filenamesInDirectory);
     
    // for each contour check if previous frame mesh file for same contour exists
    // in output directory
    for (int i = 0; i < numContours; i++)
    {
        // set substring indicating match to be "frame<previous frame number>_mesh_<contour name>.txt"
        char filenameToMatch[MAX_FILENAME_LENGTH];
        sprintf(filenameToMatch, "frame%d_mesh_%s.txt", camera1Frames[0]-1, contourNames[i]);
        
        // try to find a filename from the output directory that contains the
        // substring indicating a match for a previous frame mesh for the same
        // contour
        int fileExists = getIndexOfMatchingString(filenamesInDirectory, numFilesInDirectory, filenameToMatch);
        
        // if filename was found, create a flow output file for current contour 
        // and call flow to calculate the flow between previous contour mesh and 
        // current contour mesh
        if (fileExists != -1)
        {
            flowFilenames[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char));
            
            if (flowFilenames[i] == NULL)
            {
                printf("Out of memory error.\n");
                exit(1);
            }
            
            // create the output flow filename as "frame<frame number>_flow_<contour name>_<camera name>.txt"
            sprintf(flowFilenames[i], "%sframe%d_flow_%s.txt", outputDirectory, camera1Frames[0], contourNames[i]);
            
            // add the output directory name to the beginning of the previous mesh
            // filename
            char prevFrameMeshFile[MAX_FILENAME_LENGTH];
            sprintf(prevFrameMeshFile, "%s%s", outputDirectory, filenameToMatch);
            
            // call flow to find the flow between the previous mesh file and the
            // current mesh file for each mesh point current contour
            if (flow(prevFrameMeshFile, meshFilenames[i], flowFilenames[i], errorMessage))
            {
                printf("Flow: %s\n", errorMessage);
                exit(1);
            }
        }
        
        else
        {
            printf("Mesh points file for previous frame not found for contour %s. Unable to calculate flow.\n", contourNames[i]);
        }
    }
    
    sprintf(command, "hold on;");
    engEvalString(matlabEngine, command);
    
    // for each contour, display MATLAB 3D plot of the mesh, as well as the flow 
    // for the mesh, if applicable
    for (int i = 0; i < numContours; i++)
    {        
        if (flowFilenames[i] != NULL)
        {
            sprintf(command, "flows = load('%s');", flowFilenames[i]);
            engEvalString(matlabEngine, command);
            
            // plot the flows of the mesh points
            sprintf(command, "quiver3(flows(:,1), flows(:,2), flows(:,3), flows(:,4), flows(:,5), flows(:,6), 4, 'r-');");
            engEvalString(matlabEngine, command);
            
        }
        
        sprintf(command, "mesh = importdata('%s', ' ', 1);", meshFilenames[i]);
        engEvalString(matlabEngine, command);
        
        // plot the mesh points
        sprintf(command, "plot3(mesh.data(:,1), mesh.data(:,2), mesh.data(:,3), 'b.');");
        engEvalString(matlabEngine, command);
    }
    
    // reverse the z and y coordinates in the display
    sprintf(command, "set(gca,'zdir','reverse','ydir','reverse');");
    engEvalString(matlabEngine, command);
    
    // scale the axes to be equal
    sprintf(command, "axis equal");
    engEvalString(matlabEngine, command);
    
    // wait for the user to hit enter
    printf("Hit return to continue.\n");
    fgetc(stdin);
    
    // close MATLAB engine
    engClose(matlabEngine);
    
    // cleanup
    free(camera1Filenames);
    free(camera1Frames);
    free(camera2Filenames);
    free(camera2Frames);
    free(cameraNames);
    free(cameraCoefficientsFilenames);
    
    for (int i = 0; i < numCameraPairs; i++)
    {
        mxDestroyArray(c1ImageData[i]);
        mxDestroyArray(c1ImageDimensions[i]);
        mxDestroyArray(c1ImagePaddedWidths[i]);
        
        mxDestroyArray(c2ImageData[i]);
        mxDestroyArray(c2ImageDimensions[i]);
        mxDestroyArray(c2ImagePaddedWidths[i]);
        
        free(c1Images[i]->imageData);
        cvReleaseImageHeader(&c1Images[i]);
        
        free(c2Images[i]->imageData);
        cvReleaseImageHeader(&c2Images[i]);
    }
    
    free(c1ImageData);
    free(c1ImageDimensions);
    free(c1ImagePaddedWidths);
    
    free(c2ImageData);
    free(c2ImageDimensions);
    free(c2ImagePaddedWidths);
    
    free(c1Images);
    free(c2Images);
    
    for (int i = 0; i < MAX_FILES_IN_DIRECTORY; i++)
    {
        free(filenamesInDirectory[i]);
    }
    
    free(filenamesInDirectory);
    
    for (int i = 0; i < numContours; i++)
    {
        free(contourNames[i]);
        free(features3D[i]);
        free(validFeatureIndicator[i]);
                
        free(meshFilenames[i]);
        
        if (flowFilenames[i] != NULL)
        {
            free(flowFilenames[i]);
        }
    }
    
    free(contourNames);
    free(features3D);
    free(validFeatureIndicator);
    free(numFeaturesInContours);
    
    free(meshFilenames);
    free(flowFilenames);
    
    exit(0);
}
示例#9
0
文件: main.c 项目: Tydus/deadbeef
int
main (int argc, char *argv[]) {
#if PORTABLE
    strcpy (dbinstalldir, argv[0]);
    char *e = dbinstalldir + strlen (dbinstalldir);
    while (e >= dbinstalldir && *e != '/') {
        e--;
    }
    *e = 0;
#else
    strcpy (dbinstalldir, PREFIX);
#endif

#ifdef __linux__
    signal (SIGSEGV, sigsegv_handler);
#endif
    setlocale (LC_ALL, "");
    setlocale (LC_NUMERIC, "C");
#ifdef ENABLE_NLS
//    fprintf (stderr, "enabling gettext support: package=" PACKAGE ", dir=" LOCALEDIR "...\n");
#if PORTABLE
    char localedir[PATH_MAX];
    snprintf (localedir, sizeof (localedir), "%s/locale", dbinstalldir);
	bindtextdomain (PACKAGE, localedir);
#else
	bindtextdomain (PACKAGE, LOCALEDIR);
#endif
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	textdomain (PACKAGE);
#endif

    int staticlink = 0;
    int portable = 0;
#if STATICLINK
    staticlink = 1;
#endif
#if PORTABLE
    portable = 1;
#endif

    fprintf (stderr, "starting deadbeef " VERSION "%s%s\n", staticlink ? " [static]" : "", portable ? " [portable]" : "");
    srand (time (NULL));
#ifdef __linux__
    prctl (PR_SET_NAME, "deadbeef-main", 0, 0, 0, 0);
#endif

#if PORTABLE_FULL
    if (snprintf (confdir, sizeof (confdir), "%s/config", dbinstalldir) > sizeof (confdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }

    strcpy (dbconfdir, confdir);
#else
    char *homedir = getenv ("HOME");
    if (!homedir) {
        fprintf (stderr, "unable to find home directory. stopping.\n");
        return -1;
    }

    char *xdg_conf_dir = getenv ("XDG_CONFIG_HOME");
    if (xdg_conf_dir) {
        if (snprintf (confdir, sizeof (confdir), "%s", xdg_conf_dir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: XDG_CONFIG_HOME value is too long: %s\n", xdg_conf_dir);
            return -1;
        }
    }
    else {
        if (snprintf (confdir, sizeof (confdir), "%s/.config", homedir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: HOME value is too long: %s\n", homedir);
            return -1;
        }
    }
    if (snprintf (dbconfdir, sizeof (dbconfdir), "%s/deadbeef", confdir) > sizeof (dbconfdir)) {
        fprintf (stderr, "fatal: out of memory while configuring\n");
        return -1;
    }
    mkdir (confdir, 0755);
#endif


#if PORTABLE
    if (snprintf (dbdocdir, sizeof (dbdocdir), "%s/doc", dbinstalldir) > sizeof (dbdocdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/plugins", dbinstalldir) > sizeof (dbplugindir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/pixmaps", dbinstalldir) > sizeof (dbpixmapdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    mkdir (dbplugindir, 0755);
#else
    if (snprintf (dbdocdir, sizeof (dbdocdir), "%s", DOCDIR) > sizeof (dbdocdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/deadbeef", LIBDIR) > sizeof (dbplugindir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
    if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/share/deadbeef/pixmaps", PREFIX) > sizeof (dbpixmapdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }
#endif

    for (int i = 1; i < argc; i++) {
        // help, version and nowplaying are executed with any filter
        if (!strcmp (argv[i], "--help") || !strcmp (argv[i], "-h")) {
            print_help ();
            return 0;
        }
        else if (!strcmp (argv[i], "--version")) {
            fprintf (stdout, "DeaDBeeF " VERSION " Copyright © 2009-2011 Alexey Yakovenko\n");
            return 0;
        }
        else if (!strcmp (argv[i], "--gui")) {
            strncpy (use_gui_plugin, argv[i], sizeof(use_gui_plugin) - 1);
            use_gui_plugin[sizeof(use_gui_plugin) - 1] = 0;
        }
    }

    trace ("installdir: %s\n", dbinstalldir);
    trace ("confdir: %s\n", confdir);
    trace ("docdir: %s\n", dbdocdir);
    trace ("plugindir: %s\n", dbplugindir);
    trace ("pixmapdir: %s\n", dbpixmapdir);

    mkdir (dbconfdir, 0755);

    int size = 0;
    char *cmdline = prepare_command_line (argc, argv, &size);

    // try to connect to remote player
    int s, len;
    struct sockaddr_un remote;

    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    memset (&remote, 0, sizeof (remote));
    remote.sun_family = AF_UNIX;
#if USE_ABSTRACT_NAME
    memcpy (remote.sun_path, server_id, sizeof (server_id));
    len = offsetof(struct sockaddr_un, sun_path) + sizeof (server_id)-1;
#else
    char *socketdirenv = getenv ("DDB_SOCKET_DIR");
    snprintf (remote.sun_path, sizeof (remote.sun_path), "%s/socket", socketdirenv ? socketdirenv : dbconfdir);
    len = offsetof(struct sockaddr_un, sun_path) + strlen (remote.sun_path);
#endif
    if (connect(s, (struct sockaddr *)&remote, len) == 0) {
        // pass args to remote and exit
        if (send(s, cmdline, size, 0) == -1) {
            perror ("send");
            exit (-1);
        }
        // end of message
        shutdown(s, SHUT_WR);

        int sz = -1;
        char *out = read_entire_message(s, &sz);
        if (sz == -1) {
            fprintf (stderr, "failed to pass args to remote!\n");
            exit (-1);
        }
        else {
            // check if that's nowplaying response
            const char np[] = "nowplaying ";
            const char err[] = "error ";
            if (!strncmp (out, np, sizeof (np)-1)) {
                const char *prn = &out[sizeof (np)-1];
                fwrite (prn, 1, strlen (prn), stdout);
            }
            else if (!strncmp (out, err, sizeof (err)-1)) {
                const char *prn = &out[sizeof (err)-1];
                fwrite (prn, 1, strlen (prn), stderr);
            }
            else if (sz > 0 && out[0]) {
                fprintf (stderr, "%s\n", out);
            }
        }
        close (s);
        exit (0);
    }
//    else {
//        perror ("INFO: failed to connect to existing session:");
//    }
    close(s);

    // become a server
    if (server_start () < 0) {
        exit (-1);
    }

    // hack: report nowplaying
    if (!strcmp (cmdline, "--nowplaying")) {
        char nothing[] = "nothing";
        fwrite (nothing, 1, sizeof (nothing)-1, stdout);
        return 0;
    }

    pl_init ();
    conf_init ();
    conf_load (); // required by some plugins at startup

    if (use_gui_plugin[0]) {
        conf_set_str ("gui_plugin", use_gui_plugin);
    }

    conf_set_str ("deadbeef_version", VERSION);

    volume_set_db (conf_get_float ("playback.volume", 0)); // volume need to be initialized before plugins start
    messagepump_init (); // required to push messages while handling commandline
    if (plug_load_all ()) { // required to add files to playlist from commandline
        exit (-1);
    }
    pl_load_all ();
    plt_set_curr_idx (conf_get_int ("playlist.current", 0));

    // execute server commands in local context
    int noloadpl = 0;
    if (argc > 1) {
        int res = server_exec_command_line (cmdline, size, NULL, 0);
        // some of the server commands ran on 1st instance should terminate it
        if (res == 2) {
            noloadpl = 1;
        }
        else if (res > 0) {
            exit (0);
        }
        else if (res < 0) {
            exit (-1);
        }
    }

    free (cmdline);

#if 0
    signal (SIGTERM, sigterm_handler);
    atexit (atexit_handler); // helps to save in simple cases
#endif

    // start all subsystems
    messagepump_push (DB_EV_PLAYLISTCHANGED, 0, 0, 0);

    streamer_init ();

    plug_connect_all ();

    if (!noloadpl) {
        restore_resume_state ();
    }

    server_tid = thread_start (server_loop, NULL);
    // this runs in main thread (blocks right here)
    player_mainloop ();

    // terminate server and wait for completion
    if (server_tid) {
        server_terminate = 1;
        thread_join (server_tid);
        server_tid = 0;
    }

    // save config
    pl_save_all ();
    conf_save ();

    // delete legacy session file
    {
        char sessfile[1024]; // $HOME/.config/deadbeef/session
        if (snprintf (sessfile, sizeof (sessfile), "%s/deadbeef/session", confdir) < sizeof (sessfile)) {
            unlink (sessfile);
        }
    }

    // stop receiving messages from outside
    server_close ();

    // plugins might still hood references to playitems,
    // and query configuration in background
    // so unload everything 1st before final cleanup
    plug_disconnect_all ();
    plug_unload_all ();

    // at this point we can simply do exit(0), but let's clean up for debugging
    pl_free (); // may access conf_*
    conf_free ();
    messagepump_free ();
    plug_cleanup ();

    fprintf (stderr, "hej-hej!\n");
    return 0;
}
示例#10
0
void execute(int nargs, char* args[]) {
  int pfd[2];
  if(args[0] == NULL) {
    return;
  }
  else if(strcmp(args[0], "exit") == 0) {
    exit(nargs > 1 ? atoi(args[1]) : 0);
  }
  else if(strcmp(args[0], "cd") == 0) {
    if(nargs < 2) {
      chdir(getenv("HOME"));
      getwd(pwd);
    }
    else {
      if(chdir(args[1]) == 0) {
        getwd(pwd);
      }
      else {
        printf("Error! Could not change directory.\n");
      }
    }
    char* pathvar = malloc(strlen(defpath) + strlen(pwd) + 2);
    strcat(pathvar, pwd);
    strcpy(pathvar, ":");
    strcpy(pathvar, defpath);
    setenv("PATH", pathvar, 1);
    free(pathvar);
  }
  else if(strcmp(args[0], "pwd") == 0) {
    printf("%s\n", pwd);
  }
  else if(strcmp(args[0], "mkdir") == 0) {
    if(nargs > 1) {
      if(mkdir(args[1], 0755) != 0) {
        printf("Error! Could not create directory.\n");
      }
    }
  }
  else if(strcmp(args[0], "rmdir") == 0) {
    if(nargs > 1) {
      if(rmdir(args[1]) == -1) {
        printf("Error! Could not delete directory.\n");
      }
    }
  }
  else if(strcmp(args[0], "show") == 0) {
    printf("%s\n", (nargs > 1 ? getenv(args[1]) : ""));
  }
  else if(strcmp(args[0], "set") == 0) {
    if(nargs > 2) {
      setenv(args[1], args[2], 1);
      printf("Set %s as %s.\n", args[1], args[2]);
    }
  }
  else if(strcmp(args[0], "unset") == 0) {
    if(nargs > 1) {
      unsetenv(args[1]);
      printf("Unset %s.\n", args[1]);
    }
  }
  else if(strlen(args[0]) > 0) {
    int redct = redirect(args);
    int pipe = pipecmd(args, pfd);
    if(redct == -1 || pipe == -1) {
      return;
    }
    pid_t child = fork();
    if(child == -1) {
      printf("Error! Could not create new process.\n");
    }
    else if(child == 0) {
      if(pipe > 0) {
        pid_t fc = fork();
        if(fc == -1) {
          printf("Error! Could not create new process.\n");
        }
        else if(fc == 0) {
          close(pfd[0]);
          fflush(stdout);
          dup2(pfd[1], STDOUT_FILENO);
          close(pfd[1]);
          execvp(args[0], args);
          printf("Error! Could not execute command \"%s\".\n", args[0]);
        }
        else {
          close(pfd[1]);
          fflush(stdin);
          dup2(pfd[0], STDIN_FILENO);
          close(pfd[0]);
          execute(nargs - pipe - 1, args + pipe + 1);
        }
      }
      else {
        execvp(args[0], args);
        printf("Error! Could not execute command \"%s\".\n", args[0]);
      }
      exit(EXIT_FAILURE);
    }
    else {
      if(pipe > 0) {
        close(pfd[0]);
        close(pfd[1]);
      }
      wait(NULL);
    }
  }
}
示例#11
0
文件: handy.c 项目: goneri/burp
int mkpath(char **rpath, const char *limit)
{
	char *cp=NULL;
	struct stat buf;
	//printf("mkpath: %s\n", *rpath);
	if((cp=strrchr(*rpath, '/')))
	{
#ifdef HAVE_WIN32
		int windows_stupidity=0;
		*cp='\0';
		if(strlen(*rpath)==2 && (*rpath)[1]==':')
		{
			(*rpath)[1]='\0';
			windows_stupidity++;
		}
#else
		*cp='\0';
#endif
		if(!**rpath)
		{
			// We are down to the root, which is OK.
		}
		else if(lstat(*rpath, &buf))
		{
			// does not exist - recurse further down, then come
			// back and try to mkdir it.
			if(mkpath(rpath, limit)) return -1;

			// Require that the user has set up the required paths
			// on the server correctly. I have seen problems with
			// part of the path being a temporary symlink that
			// gets replaced by burp with a proper directory.
			// Allow it to create the actual directory specified,
			// though.

			// That is, if limit is:
			// /var/spool/burp
			// and /var/spool exists, the directory will be
			// created.
			// If only /var exists, the directory will not be
			// created.

			// Caller can give limit=NULL to create the whole
			// path with no limit, as in a restore.
			if(limit && pathcmp(*rpath, limit)<0)
			{
				logp("will not mkdir %s\n", *rpath);
#ifdef HAVE_WIN32
				if(windows_stupidity) (*rpath)[1]=':';
#endif
				*cp='/';
				return -1;
			}
			if(mkdir(*rpath, 0777))
			{
				logp("could not mkdir %s: %s\n", *rpath, strerror(errno));
#ifdef HAVE_WIN32
				if(windows_stupidity) (*rpath)[1]=':';
#endif
				*cp='/';
				return -1;
			}
		}
		else if(S_ISDIR(buf.st_mode))
		{
			// Is a directory - can put the slash back and return.
		}
		else if(S_ISLNK(buf.st_mode))
		{
			// to help with the 'current' symlink
		}
		else
		{
			// something funny going on
			logp("warning: wanted '%s' to be a directory\n",
				*rpath);
		}
#ifdef HAVE_WIN32
		if(windows_stupidity) (*rpath)[1]=':';
#endif
		*cp='/';
	}
	return 0;
}
示例#12
0
文件: scp.c 项目: projectarkc/psiphon
void
sink(int argc, char **argv)
{
    static BUF buffer;
    struct stat stb;
    enum {
        YES, NO, DISPLAYED
    } wrerr;
    BUF *bp;
    off_t i;
    size_t j, count;
    int amt, exists, first, ofd;
    mode_t mode, omode, mask;
    off_t size, statbytes;
    int setimes, targisdir, wrerrno = 0;
    char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
    struct timeval tv[2];

#define	atime	tv[0]
#define	mtime	tv[1]
#define	SCREWUP(str)	{ why = str; goto screwup; }

    setimes = targisdir = 0;
    mask = umask(0);
    if (!pflag)
        (void) umask(mask);
    if (argc != 1) {
        run_err("ambiguous target");
        exit(1);
    }
    targ = *argv;
    if (targetshouldbedirectory)
        verifydir(targ);

    (void) atomicio(vwrite, remout, "", 1);
    if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
        targisdir = 1;
    for (first = 1;; first = 0) {
        cp = buf;
        if (atomicio(read, remin, cp, 1) != 1)
            return;
        if (*cp++ == '\n')
            SCREWUP("unexpected <newline>");
        do {
            if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
                SCREWUP("lost connection");
            *cp++ = ch;
        } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
        *cp = 0;
        if (verbose_mode)
            fprintf(stderr, "Sink: %s", buf);

        if (buf[0] == '\01' || buf[0] == '\02') {
            if (iamremote == 0)
                (void) atomicio(vwrite, STDERR_FILENO,
                                buf + 1, strlen(buf + 1));
            if (buf[0] == '\02')
                exit(1);
            ++errs;
            continue;
        }
        if (buf[0] == 'E') {
            (void) atomicio(vwrite, remout, "", 1);
            return;
        }
        if (ch == '\n')
            *--cp = 0;

        cp = buf;
        if (*cp == 'T') {
            setimes++;
            cp++;
            mtime.tv_sec = strtol(cp, &cp, 10);
            if (!cp || *cp++ != ' ')
                SCREWUP("mtime.sec not delimited");
            mtime.tv_usec = strtol(cp, &cp, 10);
            if (!cp || *cp++ != ' ')
                SCREWUP("mtime.usec not delimited");
            atime.tv_sec = strtol(cp, &cp, 10);
            if (!cp || *cp++ != ' ')
                SCREWUP("atime.sec not delimited");
            atime.tv_usec = strtol(cp, &cp, 10);
            if (!cp || *cp++ != '\0')
                SCREWUP("atime.usec not delimited");
            (void) atomicio(vwrite, remout, "", 1);
            continue;
        }
        if (*cp != 'C' && *cp != 'D') {
            /*
             * Check for the case "rcp remote:foo\* local:bar".
             * In this case, the line "No match." can be returned
             * by the shell before the rcp command on the remote is
             * executed so the ^Aerror_message convention isn't
             * followed.
             */
            if (first) {
                run_err("%s", cp);
                exit(1);
            }
            SCREWUP("expected control record");
        }
        mode = 0;
        for (++cp; cp < buf + 5; cp++) {
            if (*cp < '0' || *cp > '7')
                SCREWUP("bad mode");
            mode = (mode << 3) | (*cp - '0');
        }
        if (*cp++ != ' ')
            SCREWUP("mode not delimited");

        for (size = 0; isdigit(*cp);)
            size = size * 10 + (*cp++ - '0');
        if (*cp++ != ' ')
            SCREWUP("size not delimited");
        if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
            run_err("error: unexpected filename: %s", cp);
            exit(1);
        }
        if (targisdir) {
            static char *namebuf;
            static size_t cursize;
            size_t need;

            need = strlen(targ) + strlen(cp) + 250;
            if (need > cursize) {
                if (namebuf)
                    xfree(namebuf);
                namebuf = xmalloc(need);
                cursize = need;
            }
            (void) snprintf(namebuf, need, "%s%s%s", targ,
                            strcmp(targ, "/") ? "/" : "", cp);
            np = namebuf;
        } else
            np = targ;
        curfile = cp;
        exists = stat(np, &stb) == 0;
        if (buf[0] == 'D') {
            int mod_flag = pflag;
            if (!iamrecursive)
                SCREWUP("received directory without -r");
            if (exists) {
                if (!S_ISDIR(stb.st_mode)) {
                    errno = ENOTDIR;
                    goto bad;
                }
                if (pflag)
                    (void) chmod(np, mode);
            } else {
                /* Handle copying from a read-only
                   directory */
                mod_flag = 1;
                if (mkdir(np, mode | S_IRWXU) < 0)
                    goto bad;
            }
            vect[0] = xstrdup(np);
            sink(1, vect);
            if (setimes) {
                setimes = 0;
                if (utimes(vect[0], tv) < 0)
                    run_err("%s: set times: %s",
                            vect[0], strerror(errno));
            }
            if (mod_flag)
                (void) chmod(vect[0], mode);
            if (vect[0])
                xfree(vect[0]);
            continue;
        }
        omode = mode;
        mode |= S_IWRITE;
        if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
bad:
            run_err("%s: %s", np, strerror(errno));
            continue;
        }
        (void) atomicio(vwrite, remout, "", 1);
        if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
            (void) close(ofd);
            continue;
        }
        cp = bp->buf;
        wrerr = NO;

        statbytes = 0;
        if (showprogress)
            start_progress_meter(curfile, size, &statbytes);
        set_nonblock(remin);
        for (count = i = 0; i < size; i += bp->cnt) {
            amt = bp->cnt;
            if (i + amt > size)
                amt = size - i;
            count += amt;
            do {
                j = atomicio6(read, remin, cp, amt,
                              scpio, &statbytes);
                if (j == 0) {
                    run_err("%s", j != EPIPE ?
                            strerror(errno) :
                            "dropped connection");
                    exit(1);
                }
                amt -= j;
                cp += j;
            } while (amt > 0);

            if (count == bp->cnt) {
                /* Keep reading so we stay sync'd up. */
                if (wrerr == NO) {
                    if (atomicio(vwrite, ofd, bp->buf,
                                 count) != count) {
                        wrerr = YES;
                        wrerrno = errno;
                    }
                }
                count = 0;
                cp = bp->buf;
            }
        }
        unset_nonblock(remin);
        if (showprogress)
            stop_progress_meter();
        if (count != 0 && wrerr == NO &&
                atomicio(vwrite, ofd, bp->buf, count) != count) {
            wrerr = YES;
            wrerrno = errno;
        }
        if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
                ftruncate(ofd, size) != 0) {
            run_err("%s: truncate: %s", np, strerror(errno));
            wrerr = DISPLAYED;
        }
        if (pflag) {
            if (exists || omode != mode)
#ifdef HAVE_FCHMOD
                if (fchmod(ofd, omode)) {
#else /* HAVE_FCHMOD */
                if (chmod(np, omode)) {
#endif /* HAVE_FCHMOD */
                    run_err("%s: set mode: %s",
                            np, strerror(errno));
                    wrerr = DISPLAYED;
                }
        } else {
            if (!exists && omode != mode)
#ifdef HAVE_FCHMOD
                if (fchmod(ofd, omode & ~mask)) {
#else /* HAVE_FCHMOD */
                if (chmod(np, omode & ~mask)) {
#endif /* HAVE_FCHMOD */
                    run_err("%s: set mode: %s",
                            np, strerror(errno));
                    wrerr = DISPLAYED;
                }
        }
        if (close(ofd) == -1) {
            wrerr = YES;
            wrerrno = errno;
        }
        (void) response();
        if (setimes && wrerr == NO) {
            setimes = 0;
            if (utimes(np, tv) < 0) {
                run_err("%s: set times: %s",
                        np, strerror(errno));
                wrerr = DISPLAYED;
            }
        }
        switch (wrerr) {
        case YES:
            run_err("%s: %s", np, strerror(wrerrno));
            break;
        case NO:
            (void) atomicio(vwrite, remout, "", 1);
            break;
        case DISPLAYED:
            break;
        }
    }
screwup:
    run_err("protocol error: %s", why);
    exit(1);
}

int
response(void)
{
    char ch, *cp, resp, rbuf[2048];

    if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
        lostconn(0);

    cp = rbuf;
    switch (resp) {
    case 0:		/* ok */
        return (0);
    default:
        *cp++ = resp;
    /* FALLTHROUGH */
    case 1:		/* error, followed by error msg */
    case 2:		/* fatal error, "" */
        do {
            if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
                lostconn(0);
            *cp++ = ch;
        } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');

        if (!iamremote)
            (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
        ++errs;
        if (resp == 1)
            return (-1);
        exit(1);
    }
    /* NOTREACHED */
}

void
usage(void)
{
    (void) fprintf(stderr,
                   "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
                   "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
                   "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
    exit(1);
}
示例#13
0
int main()

{
	char root[16]; //as pids can get much longer
	int gen_ret_val, ch_ret_val, level;
	int ret_val;
	int generate(), check();
	char path_list_string[PATH_STRING_LENGTH + 1];
	int status;
	int len;
	int term();

	slash[0] = '/';
	slash[1] = '\0';

	strcpy(path_string, "inode");
	sprintf(root, "A%d", getpid());
	strcat(path_string, root);

	strcpy(rm_string, "rm -rf ");
	strcat(rm_string, path_string);

	setup();

	if (signal(SIGTERM, (void (*)())term) == SIG_ERR) {
		fprintf(temp, "\tSIGTERM signal set failed!, errno=%d\n", errno);
		fail_exit();
	}

	blenter();

	/********************************/
	/*				*/
	/*  make the root directory for */
	/*  the tree			*/
	/*				*/
	/********************************/

	ret_val = mkdir(path_string, DIRECTORY_MODE);

	if (ret_val == -1) {
		perror("mkdir error");
		fprintf(temp,"\tcreating directory '%s'\n", path_string);
		fprintf(temp,"\t\n%s Impossible to create directory %s\n", root, path_string);
		fail_exit();
	}

#ifdef PRINT
	printf("\n%s\n", path_string);
#endif

	/****************************************/
	/*					*/
	/*  create the "path_list" file, in	*/
	/*  which the list of generated paths   */
	/*  will be stored so that they later	*/
	/*  may be checked			*/
	/*					*/
	/****************************************/

	strcpy(path_list_string, path_string);
	strcat(path_list_string, slash);
	strcat(path_list_string, "path_list");
	list_id = creat(path_list_string, FILE_MODE);
	if (list_id == -1) {
		fprintf(temp,"\t\n%s The path_list file cannot be created, errno=%d \n", root, errno);
		fail_exit();
	}

	/****************************************/
	/*					*/
	/*   and store its name in path_list	*/
	/*					*/
	/****************************************/

	strcpy(write_string, path_string);
	len = strlen(write_string);
	write_string[len++] = 'D';
	write_string[len] = '\0';
	escrivez(write_string);

	/****************************************/
	/*					*/
	/*   generate the directory-file tree	*/
	/*					*/
	/****************************************/

	level = 0;

#ifdef PRINT
	printf("\n\t%s\n\n", "GENERATING:");
#endif

	gen_ret_val = generate(path_string, level);

	if (gen_ret_val)
	{
		fprintf(temp,"Failure occured in generate routine, return value %d\n", gen_ret_val);
		local_flag = FAILED;
	}

	blexit();
	blenter();

	close(list_id);
	list_id = open(path_list_string, READ);
	if (list_id == -1) {
		fprintf(temp,"\t\n%s The path_list file cannot be opened for reading, errno=%d\n", root, errno);
		fail_exit();
	}
	list_stream = fdopen(list_id, "r");

	/****************************************/
	/*					*/
	/*   check the directory-file tree	*/
	/*      for correctness			*/
	/*					*/
	/****************************************/

#ifdef PRINT
	printf("\n\t%s\n\n", "CHECKING:");
#endif

	ch_ret_val = check();

	if (ch_ret_val)
	{
		fprintf(temp,"Failure occured in check routine, return value %d\n", ch_ret_val);
		local_flag = FAILED;
	}

        status = fclose(list_stream);
        if (status != 0) {
                fprintf(temp,"Failed to close list_stream: ret=%d errno=%d (%s)\n",
                        status, errno, strerror(errno));
                local_flag = FAILED;
        }

	blexit();

	/*
	 * Now fork and exec a system call to remove the directory.
	 */

#ifdef DEBUG
	fprintf(temp,"\nClean up:\trm string = %s\n", rm_string);
#endif
	fflush(stdout);
	fflush(temp);

	status = system(rm_string);

	if (status) {
		fprintf(temp,"Caution-``%s'' may have failed\n", rm_string);
		fprintf(temp, "rm command exit status = %d\n", status);
	}

	/****************************************/
	/*					*/
	/*         .....and exit main		*/
	/*					*/
	/****************************************/

	anyfail();
        /***** NOT REACHED ******/
	tst_exit();
}
示例#14
0
static void do_directory(char *path, struct cramfs_inode *i)
{
	int pathlen = strlen(path);
	int count = i->size;
	unsigned long offset = i->offset << 2;
	char *newpath = malloc(pathlen + 256);

	if (!newpath) {
		die(FSCK_ERROR, 1, "malloc failed");
	}
	if (offset == 0 && count != 0) {
		die(FSCK_UNCORRECTED, 0, "directory inode has zero offset and non-zero size: %s", path);
	}
	if (offset != 0 && offset < start_dir) {
		start_dir = offset;
	}
	/* TODO: Do we need to check end_dir for empty case? */
	memcpy(newpath, path, pathlen);
	newpath[pathlen] = '/';
	pathlen++;
	if (opt_verbose) {
		print_node('d', i, path);
	}
	if (opt_extract) {
		if (mkdir(path, i->mode) < 0) {
			die(FSCK_ERROR, 1, "mkdir failed: %s", path);
		}
		change_file_status(path, i);
	}
	while (count > 0) {
		struct cramfs_inode *child = iget(offset);
		int size;
		int newlen = child->namelen << 2;

		size = sizeof(struct cramfs_inode) + newlen;
		count -= size;

		offset += sizeof(struct cramfs_inode);

		memcpy(newpath + pathlen, romfs_read(offset), newlen);
		newpath[pathlen + newlen] = 0;
		if (newlen == 0) {
			die(FSCK_UNCORRECTED, 0, "filename length is zero");
		}
		if ((pathlen + newlen) - strlen(newpath) > 3) {
			die(FSCK_UNCORRECTED, 0, "bad filename length");
		}
		expand_fs(newpath, child);

		offset += newlen;

		if (offset <= start_dir) {
			die(FSCK_UNCORRECTED, 0, "bad inode offset");
		}
		if (offset > end_dir) {
			end_dir = offset;
		}
		iput(child); /* free(child) */
	}
	free(newpath);
}
示例#15
0
bool game::opening_screen()
{
    WINDOW* w_background = newwin(TERMY, TERMX, 0, 0);

    werase(w_background);
    wrefresh(w_background);

    WINDOW* w_open = newwin(25, 80, (TERMY > 25) ? (TERMY-25)/2 : 0, (TERMX > 80) ? (TERMX-80)/2 : 0);
    const int iMenuOffsetX = 2;
    int iMenuOffsetY = 22;

    std::vector<std::string> vSubItems;
    vSubItems.push_back("Custom Character");
    vSubItems.push_back("Preset Character");
    vSubItems.push_back("Random Character");

    print_menu(w_open, 0, iMenuOffsetX, iMenuOffsetY);

    std::vector<std::string> savegames, templates;
    std::string tmp;
    dirent *dp;
    DIR *dir = opendir("save");
    if (!dir) {
        #if (defined _WIN32 || defined __WIN32__)
            mkdir("save");
        #else
            mkdir("save", 0777);
        #endif
        dir = opendir("save");
    }
    if (!dir) {
        dbg(D_ERROR) << "game:opening_screen: Unable to make save directory.";
        debugmsg("Could not make './save' directory");
        endwin();
        exit(1);
    }
    while ((dp = readdir(dir))) {
        tmp = dp->d_name;
        if (tmp.find(".sav") != std::string::npos)
            savegames.push_back(tmp.substr(0, tmp.find(".sav")));
    }
    closedir(dir);
    dir = opendir("data");
    while ((dp = readdir(dir))) {
        tmp = dp->d_name;
        if (tmp.find(".template") != std::string::npos)
            templates.push_back(tmp.substr(0, tmp.find(".template")));
    }

    int sel1 = 1, sel2 = 1, layer = 1;
    InputEvent input;
    int chInput;
    bool start = false;

    // Load MOTD and store it in a string
    std::vector<std::string> motd;
    std::ifstream motd_file;
    motd_file.open("data/motd");
    if (!motd_file.is_open())
        motd.push_back("No message today.");
    else {
        while (!motd_file.eof()) {
            std::string tmp;
            getline(motd_file, tmp);
            if (tmp[0] != '#')
                motd.push_back(tmp);
        }
    }

    // Load Credits and store it in a string
    std::vector<std::string> credits;
    std::ifstream credits_file;
    credits_file.open("data/credits");
    if (!credits_file.is_open())
        credits.push_back("No message today.");
    else {
        while (!credits_file.eof()) {
            std::string tmp;
            getline(credits_file, tmp);
            if (tmp[0] != '#')
                credits.push_back(tmp);
        }
    }

    while(!start) {
        if (layer == 1) {
            print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY, (sel1 == 0 || sel1 == 7) ? false : true);

            if (sel1 == 0) {	// Print the MOTD.
                for (int i = 0; i < motd.size() && i < 16; i++)
                    mvwprintz(w_open, i + 7, 8, c_ltred, motd[i].c_str());

                wrefresh(w_open);
                refresh();
            } else if (sel1 == 7) {	// Print the Credits.
                for (int i = 0; i < credits.size() && i < 16; i++)
                    mvwprintz(w_open, i + 7, 8, c_ltred, credits[i].c_str());

                wrefresh(w_open);
                refresh();
            }

            chInput = getch();

            if (chInput == 'm' || chInput == 'M') {
                sel1 = 0;
                chInput = '\n';
            } else if (chInput == 'n' || chInput == 'N') {
                sel1 = 1;
                chInput = '\n';
            } else if (chInput == 'L') {
                sel1 = 2;
                chInput = '\n';
            } else if (chInput == 'r' || chInput == 'R') {
                sel1 = 3;
                chInput = '\n';
            } else if (chInput == 's' || chInput == 'S') {
                sel1 = 4;
                chInput = '\n';
            } else if (chInput == 'o' || chInput == 'O') {
                sel1 = 5;
                chInput = '\n';
            } else if (chInput == 'H') {
                sel1 = 6;
                chInput = '\n';
            } else if (chInput == 'c' || chInput == 'C') {
                sel1 = 7;
                chInput = '\n';
            } else if (chInput == 'q' || chInput == 'Q' || chInput == KEY_ESCAPE) {
                sel1 = 8;
                chInput = '\n';
            }

            if (chInput == KEY_LEFT || chInput == 'h') {
                if (sel1 > 0)
                    sel1--;
                else
                    sel1 = 8;
            } else if (chInput == KEY_RIGHT || chInput == 'l') {
                if (sel1 < 8)
                    sel1++;
                else
                    sel1 = 0;
            } else if ((chInput == KEY_UP || chInput == 'k' || chInput == '\n') && sel1 > 0 && sel1 != 7) {
                if (sel1 == 5) {
                    show_options();
                } else if (sel1 == 6) {
                    help();
                } else if (sel1 == 8) {
                    uquit = QUIT_MENU;
                    return false;
                } else {
                    sel2 = 0;
                    layer = 2;
                    print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY, (sel1 == 0 || sel1 == 7) ? false : true);
                }
            }
        } else if (layer == 2) {
            if (sel1 == 1) {	// New Character
                print_menu_items(w_open, vSubItems, sel2, iMenuOffsetY-2, iMenuOffsetX+7);
                wrefresh(w_open);
                refresh();
                chInput = getch();

                if (chInput == 'c' || chInput == 'C') {
                    sel2 = 0;
                    chInput = '\n'  ;
                } else if (chInput == 'p' || chInput == 'P') {
                    sel2 = 1;
                    chInput = '\n';
                } else if (chInput == 'r' || chInput == 'R') {
                    sel2 = 2;
                    chInput = '\n';
                }

                if (chInput == KEY_LEFT || chInput == 'h') {
                    if (sel2 > 0)
                        sel2--;
                    else
                        sel2 = 2;
                } if (chInput == KEY_RIGHT || chInput == 'l') {
                    if (sel2 < 2)
                        sel2++;
                    else
                        sel2 = 0;
                } else if (chInput == KEY_DOWN || chInput == 'j' || chInput == KEY_ESCAPE) {
                    layer = 1;
                    sel1 = 1;
                }
                if (chInput == KEY_UP || chInput == 'k' || chInput == '\n') {
                    if (sel2 == 0 || sel2 == 2) {
                        if (!u.create(this, (sel2 == 0) ? PLTYPE_CUSTOM : PLTYPE_RANDOM)) {
                            u = player();
                            delwin(w_open);
                            return (opening_screen());
                        }

                        werase(w_background);
                        wrefresh(w_background);
                        start_game();
                        start = true;
                    } else if (sel2 == 1) {
                        layer = 3;
                        sel1 = 0;
                        print_menu_items(w_open, vSubItems, sel2, iMenuOffsetY-2, iMenuOffsetX+7);
                    }
                }
            } else if (sel1 == 2) {	// Load Character
                if (savegames.size() == 0)
                    mvwprintz(w_open, iMenuOffsetY - 2, 19 + iMenuOffsetX, c_red, "No save games found!");
                else {
                    for (int i = 0; i < savegames.size(); i++) {
                        int line = iMenuOffsetY - 2 - i;
                        mvwprintz(w_open, line, 19 + iMenuOffsetX, (sel2 == i ? h_white : c_white), savegames[i].c_str());
                    }
                }
                wrefresh(w_open);
                refresh();
                input = get_input();
                if (savegames.size() == 0 && (input == DirectionS || input == Confirm)) {
                    layer = 1;
                } else if (input == DirectionS) {
                    if (sel2 > 0)
                        sel2--;
                    else
                        sel2 = savegames.size() - 1;
                } else if (input == DirectionN) {
                    if (sel2 < savegames.size() - 1)
                        sel2++;
                    else
                        sel2 = 0;
                } else if (input == DirectionW || input == Cancel) {
                    layer = 1;
                }
                if (input == DirectionE || input == Confirm) {
                    if (sel2 >= 0 && sel2 < savegames.size()) {
                        werase(w_background);
                        wrefresh(w_background);
                        load(savegames[sel2]);
                        start = true;
                    }
                }
            } else if (sel1 == 3) {  // Delete world
                if (query_yn("Delete the world and all saves?")) {
                    delete_save();
                    savegames.clear();
                    MAPBUFFER.reset();
                    MAPBUFFER.make_volatile();
                }

                layer = 1;
            } else if (sel1 == 4) {	// Special game
                for (int i = 1; i < NUM_SPECIAL_GAMES; i++) {
                    mvwprintz(w_open, iMenuOffsetY-i-1, 34 + iMenuOffsetX, (sel2 == i-1 ? h_white : c_white),
                    special_game_name( special_game_id(i) ).c_str());
                }
                wrefresh(w_open);
                refresh();
                input = get_input();
                if (input == DirectionS) {
                    if (sel2 > 0)
                        sel2--;
                    else
                        sel2 = NUM_SPECIAL_GAMES - 2;
                } else if (input == DirectionN) {
                    if (sel2 < NUM_SPECIAL_GAMES - 2)
                        sel2++;
                    else
                        sel2 = 0;
                } else if (input == DirectionW || input == Cancel) {
                    layer = 1;
                }
                if (input == DirectionE || input == Confirm) {
                    if (sel2 >= 0 && sel2 < NUM_SPECIAL_GAMES - 1) {
                        delete gamemode;
                        gamemode = get_special_game( special_game_id(sel2+1) );
                        if (!gamemode->init(this)) {
                            delete gamemode;
                            gamemode = new special_game;
                            u = player();
                            delwin(w_open);
                            return (opening_screen());
                        }
                        start = true;
                    }
                }
            }
        } else if (layer == 3) {	// Character Templates
            if (templates.size() == 0)
                mvwprintz(w_open, iMenuOffsetY-4, iMenuOffsetX+27, c_red, "No templates found!");
            else {
                for (int i = 0; i < templates.size(); i++) {
                    int line = iMenuOffsetY - 4 - i;
                    mvwprintz(w_open, line, 27 + iMenuOffsetX, (sel1 == i ? h_white : c_white), templates[i].c_str());
                }
            }
            wrefresh(w_open);
            refresh();
            input = get_input();
            if (input == DirectionS) {
                if (sel1 > 0)
                    sel1--;
                else
                    sel1 = templates.size() - 1;
            } else if (templates.size() == 0 && (input == DirectionN || input == Confirm)) {
                sel1 = 1;
                layer = 2;
                print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY);
            } else if (input == DirectionN) {
                if (sel1 < templates.size() - 1)
                    sel1++;
                else
                    sel1 = 0;
            } else if (input == DirectionW  || input == Cancel || templates.size() == 0) {
                sel1 = 1;
                layer = 2;
                print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY);
            } else if (input == DirectionE || input == Confirm) {
                if (!u.create(this, PLTYPE_TEMPLATE, templates[sel1])) {
                    u = player();
                    delwin(w_open);
                    return (opening_screen());
                }

                werase(w_background);
                wrefresh(w_background);
                start_game();
                start = true;
            }
        }
    }
    delwin(w_open);
    if (start == false)
        uquit = QUIT_MENU;
    return start;
}
/*-----------------------------------------------------------------\
 Function Name	: main
 Returns Type	: int
 	----Parameter List
	1. int argc, 
	2.  char **argv, 
 	------------------
 Exit Codes	: 
 Side Effects	: 
--------------------------------------------------------------------
 Comments:
 
--------------------------------------------------------------------
 Changes:
 
\------------------------------------------------------------------*/
int main (int argc, char **argv)
{
	struct RIPMIME_globals glb;
	int result = 0;

	/* if the user has just typed in "ripmime" and nothing else, then we had better give them
	 * the rundown on how to use this program */

	if (argc < 2)
	{
		fprintf (stderr, "%s\n%s", version, help);
		return RIPMIME_ERROR_INSUFFICIENT_PARAMETERS;
	}

	// Set the global pointer ripmime_globals to point to
	//		the glb struct, so that if we have a timeout condition
	//		we can use the data
	ripmime_globals = &glb;


	// Set up our initial logging mode - so that we can always get
	//              report messages if need be.

	LOGGER_set_output_mode (_LOGGER_STDOUT);

	// Perform system initialisations

	MIME_init ();
	RIPMIME_init (&glb);

	// Setup our default behaviours */

	MIME_set_uniquenames (1);
	MIME_set_paranoid (0);
	MIME_set_header_longsearch(1); // 20040310-0117:PLD - Added by default as it seems stable, use --disable-qmail-bounce to turn off
	MIME_set_renamemethod (_MIME_RENAME_METHOD_INFIX);


	RIPMIME_parse_parameters (&glb, argc, argv);


	// if our input filename wasn't specified, then we better let the user know!
	if (!glb.inputfile)
	{
		LOGGER_log("Error: No input file was specified\n");
		return RIPMIME_ERROR_NO_INPUT_FILE;
	}

	// Fire up the randomizer

	srand (time (NULL));

	// clean up the output directory name if required (remove any trailing /'s, as suggested by James Cownie 03/02/2001

	if (glb.dir[strlen (glb.dir) - 1] == '/')
	{
		glb.dir[strlen (glb.dir) - 1] = '\0';
	}

	// Create the output directory required as specified by the -d parameter

	if (glb.dir != defaultdir)
	{
		result = mkdir (glb.dir, S_IRWXU);

		// if we had a problem creating a directory, and it wasn't just
		// due to the directory already existing, then we have a bit of
		// a problem on our hands, hence, report it.
		//

		if ((result == -1) && (errno != EEXIST))
		{
			LOGGER_log("ripMIME: Cannot create directory '%s' (%s)\n",
					glb.dir, strerror (errno));

			return RIPMIME_ERROR_CANT_CREATE_OUTPUT_DIR;
		}
	}

	// Unpack the contents
	RIPMIME_unpack(&glb);



	// Possible exit codes include;
	//		0 - all okay
	//		240 - processing stopped due to recursion limit

	if (glb.use_return_codes == 0) result = 0;

	return result;

}
示例#17
0
/* lock a byte range in a open file */
int main(int argc, char *argv[])
{
	int nprocs, i;
	char *tname = "ALL";
#define NREPEATS 10
	struct {
		const char *name;
		void *(*fn)(int );
	} tests[] = {
		{"noop", test_noop},
		{"malloc", test_malloc},
		{"setreuid", test_setreuid},
		{"readwrite", test_readwrite},
		{"stat", test_stat},
		{"fstat", test_fstat},
		{"dir", test_dir},
		{"dirsingle", test_dirsingle},
		{"create", test_create},
		{"lock", test_lock},
		{NULL, NULL}
	};

	if (argc <= 1) {
		printf("thread_perf NPROCS\n");
		exit(1);
	}

	nprocs = atoi(argv[1]);

	if (argc > 2) {
		tname = argv[2];
	}

	id_data = calloc(nprocs, sizeof(*id_data));
	if (!id_data) {
		exit(1);
	}

#ifndef NO_THREADS
	printf("NOTE! for accurate process results please compile with -DNO_THREADS and don't link to -lpthread\n\n");
#endif

	for (i=0;i<nprocs;i++) {
		char s[30];
		sprintf(s, "testd_%d", i);
		id_data[i].dname = strdup(s);

		sprintf(s, "%s/test.dat", id_data[i].dname);
		id_data[i].fname = strdup(s);

		rmdir(id_data[i].dname);
		if (mkdir(id_data[i].dname, 0777) != 0) {
			fprintf(stderr, "Failed to create %s\n", id_data[i].dname);
			exit(1);
		}

		unlink(id_data[i].fname);
	}

	for (i=0;tests[i].name;i++) {
		double t_threads[NREPEATS];
		double t_processes[NREPEATS];
		int j;

		if (strcasecmp(tname, "ALL") && strcasecmp(tests[i].name, tname)) {
			continue;
		}

		printf("Running test '%s' with %d tasks\n", tests[i].name, nprocs);

		for (j=0;j<NREPEATS;j++) {
#ifndef NO_THREADS
			t_threads[j]   = run_threads(nprocs, tests[i].fn);
#endif
			t_processes[j] = run_processes(nprocs, tests[i].fn);
		}
#ifndef NO_THREADS
		show_result("Threads  ", t_threads, NREPEATS);
#endif
		show_result("Processes", t_processes, NREPEATS);

		printf("\n");
		fflush(stdout);
	}

	for (i=0;i<nprocs;i++) {
		if (rmdir(id_data[i].dname) != 0) {
			fprintf(stderr, "Failed to delete %s\n", id_data[i].dname);
			exit(1);
		}
	}

	for (i=0;i<nprocs;i++) {
		free(id_data[i].dname);
		free(id_data[i].fname);
	}
	free(id_data);

	return 0;
}
示例#18
0
int
b_mkdir(int argc, char** argv, void* context)
{
	register char*	path;
	register int	n;
	register mode_t	mode = DIRMODE;
	register mode_t	mask = 0;
	register int	mflag = 0;
	register int	pflag = 0;
	register int	vflag = 0;
	int		made;
	char*		part;
	mode_t		dmode;
	struct stat	st;

	cmdinit(argc, argv, context, ERROR_CATALOG, 0);
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 'm':
			mflag = 1;
			mode = strperm(opt_info.arg, &part, mode);
			if (*part)
				error(ERROR_exit(0), "%s: invalid mode", opt_info.arg);
			continue;
		case 'p':
			pflag = 1;
			continue;
		case 'v':
			vflag = 1;
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			break;
		case '?':
			error(ERROR_usage(2), "%s", opt_info.arg);
			break;
		}
		break;
	}
	argv += opt_info.index;
	if (error_info.errors || !*argv)
		error(ERROR_usage(2), "%s", optusage(NiL));
	mask = umask(0);
	if (mflag || pflag)
	{
		dmode = DIRMODE & ~mask;
		if (!mflag)
			mode = dmode;
		dmode |= S_IWUSR | S_IXUSR;
	}
	else
	{
		mode &= ~mask;
		umask(mask);
		mask = 0;
	}
	while (path = *argv++)
	{
		if (!mkdir(path, mode))
		{
			if (vflag)
				error(0, "%s: directory created", path);
			made = 1;
		}
		else if (!pflag || !(errno == ENOENT || errno == EEXIST || errno == ENOTDIR))
		{
			error(ERROR_system(0), "%s:", path);
			continue;
		}
		else if (errno == EEXIST)
			continue;
		else
		{
			/*
			 * -p option, preserve intermediates
			 * first eliminate trailing /'s
			 */

			made = 0;
			n = strlen(path);
			while (n > 0 && path[--n] == '/');
			path[n + 1] = 0;
			for (part = path, n = *part; n;)
			{
				/* skip over slashes */
				while (*part == '/')
					part++;
				/* skip to next component */
				while ((n = *part) && n != '/')
					part++;
				*part = 0;
				if (mkdir(path, n ? dmode : mode) < 0 && errno != EEXIST && access(path, F_OK) < 0)
				{
					error(ERROR_system(0), "%s: cannot create intermediate directory", path);
					*part = n;
					break;
				}
				if (vflag)
					error(0, "%s: directory created", path);
				if (!(*part = n))
				{
					made = 1;
					break;
				}
			}
		}
		if (made && (mode & (S_ISVTX|S_ISUID|S_ISGID)))
		{
			if (stat(path, &st))
			{
				error(ERROR_system(0), "%s: cannot stat", path);
				break;
			}
			if ((st.st_mode & (S_ISVTX|S_ISUID|S_ISGID)) != (mode & (S_ISVTX|S_ISUID|S_ISGID)) && chmod(path, mode))
			{
				error(ERROR_system(0), "%s: cannot change mode from %s to %s", path, fmtperm(st.st_mode & (S_ISVTX|S_ISUID|S_ISGID)), fmtperm(mode));
				break;
			}
		}
	}
	if (mask)
		umask(mask);
	return error_info.errors != 0;
}
示例#19
0
void copy(const char *src, const char *dst)
{
#define FLAG_SRC_TYPE      0x03
#define FLAG_SRC_IS_DIR    0x01
#define FLAG_SRC_IS_FILE   0x02
#define FLAG_SRC_NON_EXSIT 0x00

#define FLAG_DST_TYPE      0x0C
#define FLAG_DST_IS_DIR    0x04
#define FLAG_DST_IS_FILE   0x08
#define FLAG_DST_NON_EXSIT 0x00

    struct stat stat;
    rt_uint32_t flag = 0;

    /* check the staus of src and dst */
    if (dfs_file_stat(src, &stat) < 0)
    {
        rt_kprintf("copy failed, bad %s\n", src);
        return;
    }
    if (DFS_S_ISDIR(stat.st_mode))
        flag |= FLAG_SRC_IS_DIR;
    else
        flag |= FLAG_SRC_IS_FILE;

    if (dfs_file_stat(dst, &stat) < 0)
    {
        flag |= FLAG_DST_NON_EXSIT;
    }
    else
    {
        if (DFS_S_ISDIR(stat.st_mode))
            flag |= FLAG_DST_IS_DIR;
        else
            flag |= FLAG_DST_IS_FILE;
    }

    //2. check status
    if ((flag & FLAG_SRC_IS_DIR) && (flag & FLAG_DST_IS_FILE))
    {
        rt_kprintf("cp faild, cp dir to file is not permitted!\n");
        return ;
    }

    //3. do copy
    if (flag & FLAG_SRC_IS_FILE)
    {
        if (flag & FLAG_DST_IS_DIR)
        {
            char * fdst;
            fdst = dfs_normalize_path(dst, _get_path_lastname(src));
            if (fdst == NULL)
            {
                rt_kprintf("out of memory\n");
                return;
            }
            copyfile(src, fdst);
            rt_free(fdst);
        }
        else
        {
            copyfile(src, dst);
        }
    }
    else //flag & FLAG_SRC_IS_DIR
    {
        if (flag & FLAG_DST_IS_DIR)
        {
            char * fdst;
            fdst = dfs_normalize_path(dst, _get_path_lastname(src));
            if (fdst == NULL)
            {
                rt_kprintf("out of memory\n");
                return;
            }
            mkdir(fdst, 0);
            copydir(src, fdst);
            rt_free(fdst);
        }
        else if ((flag & FLAG_DST_TYPE) == FLAG_DST_NON_EXSIT)
        {
            mkdir(dst, 0);
            copydir(src, dst);
        }
        else
        {
            copydir(src, dst);
        }
    }
}
示例#20
0
main(int argc, char *argv[]){
int sockfd;
char buffer[BUFSIZE+1];
int bytereceive = 0;
struct sockaddr_in serv_addr;
char createname[20];
char deletename[20];
static struct sigaction act;

void catchin(int);

act.sa_handler = catchin;
sigfillset(&(act.sa_mask));

sigaction(SIGINT, &act, (void *) 0);


if(argc <= 1){
printf("How to use : %s remoteIPaddress [example: ./client 127.0.0.1]\n", argv[0]); exit(1); }

bzero( (char*) &serv_addr, sizeof(serv_addr) );
serv_addr.sin_family = AF_INET ;
serv_addr.sin_port = htons (SERV_TCP_PORT);
inet_pton (AF_INET, argv[1], &serv_addr.sin_addr);

if( (sockfd = socket(AF_INET, SOCK_STREAM, 0) ) < 0) {
perror("Client: socket() error \n");
exit(1); }

if(connect (sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <0 ) {
perror("Client: connect() error\n");
exit(1);}

/* Get the user name */ 
	char *buf; 
	buf=(char *)malloc(10*sizeof(char)); 
	buf=getlogin(); 

	/* set the 'client_file' path */ 
	char str[30]; 
	strcpy(str, "/home/"); 
	strcat(str, buf); 
	strcat(str, "/client_file/"); 

	/* Check the path exist or not, if not, create one */ 
	struct stat s; 
	if(stat(str, &s) == -1){ 
	mkdir(str, 0700); }

do{
bzero( buffer, sizeof(buffer));
recv(sockfd, buffer, BUFSIZE, 0);
printf("\n%s\n", buffer); 
gets(buffer);
send(sockfd,buffer, BUFSIZE, 0);


if(!strcmp(buffer, "1"))
{
	bzero( buffer, sizeof(buffer));
	recv(sockfd, buffer, BUFSIZE, 0);
	printf("\n%s\n", buffer); 
	gets(buffer);
	send(sockfd,buffer, BUFSIZE, 0);
	
   	char filename[30];
    	strcpy(filename, "/home/"); 
    	strcat(filename, buf); 
    	strcat(filename, "/client_file/");
    	strcat(filename, buffer);
    
    	FILE *fp;
    	fp = fopen(filename, "ab"); 

		if(NULL == fp)
    	{
        	printf("Error opening file");
        
    	}
    
    	bzero( buffer, sizeof(buffer));
    
    	bytereceive = recv(sockfd, buffer, BUFSIZE, 0);
    	fwrite(buffer,1,bytereceive,fp);
   
}


else if(!strcmp(buffer, "2"))
{

		
	DIR *dir;
	struct dirent *ent;

	char directoryName[30];
   	strcpy(directoryName, "/home/"); 
    	strcat(directoryName, buf); 
    	strcat(directoryName, "/client_file/");

	if ((dir = opendir (directoryName)) != NULL) {
		
		printf("\n[List of files in Client Directory]\n");
  		// print all the files and directories within directory 
  		while ((ent = readdir (dir)) != NULL) {

		printf("%s\n", ent->d_name);    }

 		closedir (dir);
	}

	printf("\nPlease enter one of the filename from above including extension\n");
	
	bzero( buffer, sizeof(buffer));
	gets(buffer);
	send(sockfd,buffer, BUFSIZE, 0);

	char filename[30];
	strcpy(filename, "/home/"); 
	strcat(filename, buf); 
	strcat(filename, "/client_file/");
	    
	strcat(filename, buffer);

	FILE *fp;
    	fp = fopen(filename, "r"); 

	bzero( buffer, sizeof(buffer));
	int nread = fread(buffer,1,256,fp);
	send(sockfd, buffer, nread, 0);	
}


else if(!strcmp(buffer, "3"))
{
	printf("Enter directory name that you want to create: ");
	scanf("%s", createname);

	/* set the path/name of the directory that want to create */ 
	char createDirectory[30]; 
	strcpy(createDirectory, "/home/"); 
	strcat(createDirectory, buf); 
	strcat(createDirectory, "/"); 
	strcat(createDirectory, createname);

	/* Check the path exist or not, if not, create one */ 
	struct stat s; 
	if(stat(createDirectory, &s) == -1){ 
	mkdir(createDirectory, 0700); } 
}


else if(!strcmp(buffer, "4"))
{
	printf("Enter directory name that you want to delete: ");
	scanf("%s", deletename);

	/* set the path of the directory that want to delete */ 
	char deleteDirectory[30]; 
	strcpy(deleteDirectory, "/home/"); 
	strcat(deleteDirectory, buf); 
	strcat(deleteDirectory, "/"); 
	strcat(deleteDirectory, deletename);

	/* select all the files inside the directory that want to delete */
	char selectSubDirectory[50];
	strcpy(selectSubDirectory, "exec rm -r ");
	strcat(selectSubDirectory, "/home/"); 
	strcat(selectSubDirectory, buf); 
	strcat(selectSubDirectory, "/"); 
	strcat(selectSubDirectory, deletename);
	strcat(selectSubDirectory, "/*"); 

	/* Check the path exist or not, if exist, delete it */ 
	struct stat s; 
	if(stat(deleteDirectory, &s) != -1){
	system(selectSubDirectory);
	rmdir(deleteDirectory); } 
}

}while (strcmp(buffer, "/q"));
close(sockfd);
}
示例#21
0
文件: fs.c 项目: SeriousBug/firejail
void fs_overlayfs(void) {
	// check kernel version
	struct utsname u;
	int rv = uname(&u);
	if (rv != 0)
		errExit("uname");
	int major;
	int minor;
	if (2 != sscanf(u.release, "%d.%d", &major, &minor)) {
		fprintf(stderr, "Error: cannot extract Linux kernel version: %s\n", u.version);
		exit(1);
	}
	
	if (arg_debug)
		printf("Linux kernel version %d.%d\n", major, minor);
	int oldkernel = 0;
	if (major < 3) {
		fprintf(stderr, "Error: minimum kernel version required 3.x\n");
		exit(1);
	}
	if (major == 3 && minor < 18)
		oldkernel = 1;
	
	// build overlay directories
	fs_build_mnt_dir();

	char *oroot;
	if(asprintf(&oroot, "%s/oroot", RUN_MNT_DIR) == -1)
		errExit("asprintf");
	if (mkdir(oroot, S_IRWXU | S_IRWXG | S_IRWXO))
		errExit("mkdir");
	if (chown(oroot, 0, 0) < 0)
		errExit("chown");
	if (chmod(oroot, S_IRWXU  | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0)
		errExit("chmod");

	char *basedir = RUN_MNT_DIR;
	if (arg_overlay_keep) {
		// set base for working and diff directories
		basedir = cfg.overlay_dir;
		if (mkdir(basedir, S_IRWXU | S_IRWXG | S_IRWXO) != 0) {
			fprintf(stderr, "Error: cannot create overlay directory\n");
			exit(1);
		}
	}

	char *odiff;
	if(asprintf(&odiff, "%s/odiff", basedir) == -1)
		errExit("asprintf");
	if (mkdir(odiff, S_IRWXU | S_IRWXG | S_IRWXO))
		errExit("mkdir");
	if (chown(odiff, 0, 0) < 0)
		errExit("chown");
	if (chmod(odiff, S_IRWXU  | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0)
		errExit("chmod");
	
	char *owork;
	if(asprintf(&owork, "%s/owork", basedir) == -1)
		errExit("asprintf");
	if (mkdir(owork, S_IRWXU | S_IRWXG | S_IRWXO))
		errExit("mkdir");
	if (chown(owork, 0, 0) < 0)
		errExit("chown");
	if (chmod(owork, S_IRWXU  | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0)
		errExit("chmod");
	
	// mount overlayfs
	if (arg_debug)
		printf("Mounting OverlayFS\n");
	char *option;
	if (oldkernel) { // old Ubuntu/OpenSUSE kernels
		if (arg_overlay_keep) {
			fprintf(stderr, "Error: option --overlay= not available for kernels older than 3.18\n");
			exit(1);
		}
		if (asprintf(&option, "lowerdir=/,upperdir=%s", odiff) == -1)
			errExit("asprintf");
		if (mount("overlayfs", oroot, "overlayfs", MS_MGC_VAL, option) < 0)
			errExit("mounting overlayfs");
	}
	else { // kernel 3.18 or newer
		if (asprintf(&option, "lowerdir=/,upperdir=%s,workdir=%s", odiff, owork) == -1)
			errExit("asprintf");
//printf("option #%s#\n", option);			
		if (mount("overlay", oroot, "overlay", MS_MGC_VAL, option) < 0)
			errExit("mounting overlayfs");
	}
	printf("OverlayFS configured in %s directory\n", basedir);
	
	// mount-bind dev directory
	if (arg_debug)
		printf("Mounting /dev\n");
	char *dev;
	if (asprintf(&dev, "%s/dev", oroot) == -1)
		errExit("asprintf");
	if (mount("/dev", dev, NULL, MS_BIND|MS_REC, NULL) < 0)
		errExit("mounting /dev");

	// chroot in the new filesystem
	if (chroot(oroot) == -1)
		errExit("chroot");
	// update /var directory in order to support multiple sandboxes running on the same root directory
	if (!arg_private_dev)
		fs_dev_shm();
	fs_var_lock();
	fs_var_tmp();
	fs_var_log();
	fs_var_lib();
	fs_var_cache();
	fs_var_utmp();

	// don't leak user information
	restrict_users();

	disable_firejail_config();

	// cleanup and exit
	free(option);
	free(oroot);
	free(odiff);
}
示例#22
0
static int store_spool_save(Msg *msg)
{
    char id[UUID_STR_LEN + 1];
    Octstr *id_s;

    /* always set msg id and timestamp */
    if (msg_type(msg) == sms && uuid_is_null(msg->sms.id))
        uuid_generate(msg->sms.id);

    if (msg_type(msg) == sms && msg->sms.time == MSG_PARAM_UNDEFINED)
        time(&msg->sms.time);

    if (spool == NULL)
        return 0;

    /* blocke here if store still not loaded */
    gwlist_consume(loaded);

    switch(msg_type(msg)) {
        case sms:
        {
            Octstr *os = store_msg_pack(msg);
            Octstr *filename, *dir;
            int fd;
            size_t wrc;

            if (os == NULL) {
                error(0, "Could not pack message.");
                return -1;
            }
            uuid_unparse(msg->sms.id, id);
            id_s = octstr_create(id);
            dir = octstr_format("%S/%ld", spool, octstr_hash_key(id_s) % MAX_DIRS);
            octstr_destroy(id_s);
            if (mkdir(octstr_get_cstr(dir), S_IRUSR|S_IWUSR|S_IXUSR) == -1 && errno != EEXIST) {
                error(errno, "Could not create directory `%s'.", octstr_get_cstr(dir));
                octstr_destroy(dir);
                octstr_destroy(os);
                return -1;
            }
            filename = octstr_format("%S/%s", dir, id);
            octstr_destroy(dir);
            if ((fd = open(octstr_get_cstr(filename), O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR)) == -1) {
                error(errno, "Could not open file `%s'.", octstr_get_cstr(filename));
                octstr_destroy(filename);
                octstr_destroy(os);
                return -1;
            }
            for (wrc = 0; wrc < octstr_len(os); ) {
                size_t rc = write(fd, octstr_get_cstr(os) + wrc, octstr_len(os) - wrc);
                if (rc == -1) {
                    /* remove file */
                    error(errno, "Could not write message to `%s'.", octstr_get_cstr(filename));
                    close(fd);
                    if (unlink(octstr_get_cstr(filename)) == -1)
                        error(errno, "Oops, Could not remove failed file `%s'.", octstr_get_cstr(filename));
                    octstr_destroy(os);
                    octstr_destroy(filename);
                    return -1;
                }
                wrc += rc;
            }
            close(fd);
            counter_increase(counter);
            octstr_destroy(filename);
            octstr_destroy(os);
            break;
        }
        case ack:
        {
            Octstr *filename;
            uuid_unparse(msg->ack.id, id);
            id_s = octstr_create(id);
            filename = octstr_format("%S/%ld/%s", spool, octstr_hash_key(id_s) % MAX_DIRS, id);
            octstr_destroy(id_s);
            if (unlink(octstr_get_cstr(filename)) == -1) {
                error(errno, "Could not unlink file `%s'.", octstr_get_cstr(filename));
                octstr_destroy(filename);
                return -1;
            }
            counter_decrease(counter);
            octstr_destroy(filename);
            break;
        }
        default:
            return -1;
    }

    return 0;
}
示例#23
0
static int
mkstemp_custom (char *tmpl, int kind)
{
  char *copy;
  int count, fd, i, len, rc;
  int save_errno = errno;
  time_t junk;
  struct stat file_stats;

  /* characters used in temporary filenames */
  static const char letters[] =
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

  /* determine length of template and allocate storage */
  len = (int) strlen (tmpl);
  copy = (char *) malloc ((len + 1) * sizeof (char));

  /* initialize random number generator */
  time (&junk);
#ifdef HAVE_LRAND48
  srand48 (((long) junk + (long) getpid ()) % (long) 1073741824);
#elif defined(HAVE_RANDOM)
  srandom (((unsigned int) junk + (unsigned int) getpid ()) % (unsigned int) 1073741824);
#else
  srand (((unsigned int) junk + (unsigned int) getpid ()) % (unsigned int) 1073741824);
#endif

  for (count = 0; count < TMP_MAX; ++count)
    {
      strcpy (copy, tmpl);

      for (i = 0; i < len; ++i)
        if (copy[i] == 'X')
#if defined(HAVE_LRAND48)
          copy[i] = letters[(int) lrand48 () % 62];
#elif defined(HAVE_RANDOM)
          copy[i] = letters[(int) random () % 62];
#else
          copy[i] = letters[(int) rand () % 62];
#endif

      switch (kind)
        {
        case GT_FILE:
          fd = open (copy, O_RDWR | O_CREAT | O_EXCL, 0600);
          if (fd >= 0)
            {
              errno = save_errno;
              strcpy (tmpl, copy);
              free (copy);
              return (fd);
            }
          else if (errno != EEXIST)
            {
              /* any other error will apply also to other names we might
                 try, and there are VERY many of them, so give up now */
              free (copy);
              return (-1);
            }
          break;

        case GT_DIR:
          rc = mkdir (copy, 0700);
          if (rc == 0)
            {
              errno = save_errno;
              strcpy (tmpl, copy);
              free (copy);
              return (0);
            }
          else if (errno != EEXIST)
            {
              /* any other error will apply also to other names we might
                 try, and there are VERY many of them, so give up now */
              free (copy);
              return (-1);
            }
          break;

        case GT_NOCREATE:
          rc = stat (copy, &file_stats);
          if (rc < 0)
            {
              if (errno == ENOENT)
                {
                  errno = save_errno;
                  strcpy (tmpl, copy);
                  free (copy);
                  return (0);
                }
              else
                {
                  /* any other error will apply also to other names we might
                     try, and there are VERY many of them, so give up now */
                  free (copy);
                  return (-1);
                }
            }
          break;

        default:
          fprintf (stderr, "tempname assertion failure: bad switch logic\n");
          return (-2);
        }
    }

  /* tried too many times, bailing... */
  errno = EEXIST;
  free (copy);
  return (-1);
}
示例#24
0
文件: main.c 项目: CameronNemo/pimd
int main(int argc, char *argv[])
{
    int dummysigalrm, foreground = 0;
    struct timeval tv, difftime, curtime, lasttime, *timeout;
    fd_set rfds, readers;
    int nfds, n, i, secs, ch;
    struct sigaction sa;
    time_t boottime;
    struct option long_options[] = {
	{"config", 1, 0, 'c'},
	{"debug", 2, 0, 'd'},
	{"foreground", 0, 0, 'f'},
	{"disable-vifs", 0, 0, 'N'},
	{"help", 0, 0, 'h'},
	{"version", 0, 0, 'v'},
	{"quit-daemon", 0, 0, 'q'},
	{"reload-config", 0, 0, 'l'},
	{"show-routes", 0, 0, 'r'},
	/* {"show-cache", 0, 0, 'i'}, */
	/* {"show-debug", 0, 0, 'p'}, */
	{0, 0, 0, 0}
    };

    snprintf(versionstring, sizeof (versionstring), "pimd version %s", todaysversion);

    while ((ch = getopt_long(argc, argv, "c:d::fhlNvqr", long_options, NULL)) != EOF) {
	switch (ch) {
	    case 'c':
		config_file = optarg;
		break;

	    case 'd':
		if (!optarg) {
		    debug = DEBUG_DEFAULT;
		} else {
		    char *p,*q;
		    size_t i, len;
		    struct debugname *d;

		    debug = 0;
		    p = optarg; q = NULL;
		    while (p) {
			q = strchr(p, ',');
			if (q)
			    *q++ = '\0';
			len = strlen(p);
			for (i = 0, d = debugnames; i < ARRAY_LEN(debugnames); i++, d++) {
			    if (len >= d->nchars && strncmp(d->name, p, len) == 0)
				break;
			}

			if (i == ARRAY_LEN(debugnames))
			    return usage();

			debug |= d->level;
			p = q;
		    }
		}
		break;

	    case 'f':
		foreground = 1;
		break;

	    case 'h':
		return usage();

	    case 'l':
		killshow(SIGHUP, NULL);
		return 0;

	    case 'N':
		disable_all_by_default = 1;
		break;

	    case 'v':
		printf("%s\n", versionstring);
		return 0;

	    case 'q':
		killshow(SIGTERM, NULL);
		return 0;

	    case 'r':
		killshow(SIGUSR1, _PATH_PIMD_DUMP);
		return 0;
#if 0 /* XXX: TODO */
	    case 'i':
		killshow(SIGUSR2, _PATH_PIMD_CACHE);
		return 0;

	    case 'p':
		killshow(SIGQUIT, NULL);
		return 0;
#endif
	    default:
		return usage();
	}
    }

    argc -= optind;
    argv += optind;

    if (argc > 0) {
	return usage();
    }

    if (geteuid() != 0) {
	fprintf(stderr, "%s: must be root\n", __progname);
	exit(1);
    }
    setlinebuf(stderr);

    if (debug != 0) {
	struct debugname *d;
	char c;
	int tmpd = debug;

	fprintf(stderr, "debug level 0x%lx ", debug);
	c = '(';
	for (d = debugnames; d < debugnames + ARRAY_LEN(debugnames); d++) {
	    if ((tmpd & d->level) == d->level) {
		tmpd &= ~d->level;
		fprintf(stderr, "%c%s", c, d->name);
		c = ',';
	    }
	}
	fprintf(stderr, ")\n");
    }

    /*
     * Create directory for runtime files
     */
    mkdir(_PATH_PIMD_RUNDIR, 0755);

    /*
     * Setup logging
     */
#ifdef LOG_DAEMON
    openlog("pimd", LOG_PID, LOG_DAEMON);
    setlogmask(LOG_UPTO(LOG_NOTICE));
#else
    openlog("pimd", LOG_PID);
#endif /* LOG_DAEMON */

    logit(LOG_NOTICE, 0, "%s starting ...", versionstring);

    do_randomize();
    time(&boottime);

    /* Start up the log rate-limiter */
    resetlogging(NULL);

    callout_init();
    init_igmp();
    init_pim();
#ifdef HAVE_ROUTING_SOCKETS
    init_routesock();
#endif /* HAVE_ROUTING_SOCKETS */
    init_pim_mrt();
    init_timers();

    /* TODO: check the kernel DVMRP/MROUTED/PIM support version */

    init_vifs();
    init_rp_and_bsr();   /* Must be after init_vifs() */

#ifdef RSRR
    rsrr_init();
#endif /* RSRR */

    sa.sa_handler = handler;
    sa.sa_flags = 0;	/* Interrupt system calls */
    sigemptyset(&sa.sa_mask);
    sigaction(SIGALRM, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGUSR1, &sa, NULL);
    sigaction(SIGUSR2, &sa, NULL);

    FD_ZERO(&readers);
    FD_SET(igmp_socket, &readers);
    nfds = igmp_socket + 1;
    for (i = 0; i < nhandlers; i++) {
	FD_SET(ihandlers[i].fd, &readers);
	if (ihandlers[i].fd >= nfds)
	    nfds = ihandlers[i].fd + 1;
    }

    IF_DEBUG(DEBUG_IF)
	dump_vifs(stderr);
    IF_DEBUG(DEBUG_PIM_MRT)
	dump_pim_mrt(stderr);

    /* schedule first timer interrupt */
    timer_setTimer(TIMER_INTERVAL, timer, NULL);

    if (!debug && !foreground) {
	/* Detach from the terminal */
	haveterminal = 0;
	if (fork())
	    exit(0);
	close(0);
	close(1);
	close(2);
	open("/", 0);
	dup2(0, 1);
	dup2(0, 2);
#ifdef SYSV
	setpgrp();
#else
#ifdef TIOCNOTTY
	n = open("/dev/tty", 2);
	if (n >= 0) {
	    (void)ioctl(n, TIOCNOTTY, (char *)0);
	    (void)close(n);
	}
#else
	if (setsid() < 0)
	    perror("setsid");
#endif /* TIOCNOTTY */
#endif /* SYSV */
    } /* End of child process code */

    if (pidfile(NULL)) {
	warn("Cannot create pidfile");
    }

    /*
     * Main receive loop.
     */
    dummysigalrm = SIGALRM;
    difftime.tv_usec = 0;
    gettimeofday(&curtime, NULL);
    lasttime = curtime;
    while (1) {
	memcpy(&rfds, &readers, sizeof(rfds));
	secs = timer_nextTimer();
	if (secs == -1)
	    timeout = NULL;
	else {
	    timeout = &tv;
	    timeout->tv_sec = secs;
	    timeout->tv_usec = 0;
	}

	if (boottime) {
	    time_t n;

	    time(&n);
	    if (n > boottime + 15) {
		struct rp_hold *rph = g_rp_hold;

		while(rph) {
		    add_rp_grp_entry(&cand_rp_list, &grp_mask_list,
				     rph->address, 1, (u_int16)0xffffff,
				     rph->group, rph->mask,
				     curr_bsr_hash_mask, curr_bsr_fragment_tag);
		    rph = rph->next;
		}
		boottime = 0;
	    }
	}

	if (sighandled) {
	    if (sighandled & GOT_SIGINT) {
		sighandled &= ~GOT_SIGINT;
		break;
	    }
	    if (sighandled & GOT_SIGHUP) {
		sighandled &= ~GOT_SIGHUP;
		restart(SIGHUP);

		/* reconstruct readers and nfds */
		FD_ZERO(&readers);
		FD_SET(igmp_socket, &readers);
		nfds = igmp_socket + 1;
		for (i = 0; i < nhandlers; i++) {
		    FD_SET(ihandlers[i].fd, &readers);
		    if (ihandlers[i].fd >= nfds)
			nfds = ihandlers[i].fd + 1;
		}
		memcpy(&rfds, &readers, sizeof(rfds));
	    }
	    if (sighandled & GOT_SIGUSR1) {
		sighandled &= ~GOT_SIGUSR1;
		fdump(SIGUSR1);
	    }
	    if (sighandled & GOT_SIGUSR2) {
		sighandled &= ~GOT_SIGUSR2;
		cdump(SIGUSR2);
	    }
	    if (sighandled & GOT_SIGALRM) {
		sighandled &= ~GOT_SIGALRM;
		timer(&dummysigalrm);
	    }
	}
	if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
	    if (errno != EINTR) /* SIGALRM is expected */
		logit(LOG_WARNING, errno, "select failed");
	    continue;
	}
	if (n > 0) {
	    /* TODO: shall check first igmp_socket for better performance? */
	    for (i = 0; i < nhandlers; i++) {
		if (FD_ISSET(ihandlers[i].fd, &rfds)) {
		    (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
		}
	    }
	}

	/*
	 * Handle timeout queue.
	 *
	 * If select + packet processing took more than 1 second,
	 * or if there is a timeout pending, age the timeout queue.
	 *
	 * If not, collect usec in difftime to make sure that the
	 * time doesn't drift too badly.
	 *
	 * If the timeout handlers took more than 1 second,
	 * age the timeout queue again.  XXX This introduces the
	 * potential for infinite loops!
	 */
	do {
	    /*
	     * If the select timed out, then there's no other
	     * activity to account for and we don't need to
	     * call gettimeofday.
	     */
	    if (n == 0) {
		curtime.tv_sec = lasttime.tv_sec + secs;
		curtime.tv_usec = lasttime.tv_usec;
		n = -1;	/* don't do this next time through the loop */
	    } else
		gettimeofday(&curtime, NULL);
	    difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec;
	    difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec;
	    while (difftime.tv_usec >= 1000000) {
		difftime.tv_sec++;
		difftime.tv_usec -= 1000000;
	    }
	    if (difftime.tv_usec < 0) {
		difftime.tv_sec--;
		difftime.tv_usec += 1000000;
	    }
	    lasttime = curtime;
	    if (secs == 0 || difftime.tv_sec > 0)
		age_callout_queue(difftime.tv_sec);
	    secs = -1;
	} while (difftime.tv_sec > 0);
    } /* Main loop */

    logit(LOG_NOTICE, 0, "%s exiting.", versionstring);
    cleanup();
    exit(0);
}
/******************************************************************************

  start_master()

  Start the master server.

******************************************************************************/
void start_master()
{
    arg_list_t al;
    int err, i;
    char master_out[PATH_MAX];
    char master_err[PATH_MAX];
    char temp[PATH_MAX], temp2[PATH_MAX];

    // remove old berkeley db log files that can confuse the server
    removef("%s/log.*", master_dir);

    // remove stale binary logs
    removef("%s/var/log/*-bin.*", mysql_test_dir);

    // remove stale binary logs
    removef("%s/var/log/*.index", mysql_test_dir);

    // remove master.info file
    removef("%s/master.info", master_dir);

    // remove relay files
    removef("%s/var/log/*relay*", mysql_test_dir);

    // remove relay-log.info file
    removef("%s/relay-log.info", master_dir);

    // init script
    if (master_init_script[0] != NULL)
    {
        // run_init_script(master_init_script);

        // TODO: use the scripts
        if (strindex(master_init_script, "repair_part2-master.sh") != NULL)
        {
            FILE *fp;

            // create an empty index file
            snprintf(temp, PATH_MAX, "%s/test/t1.MYI", master_dir);
            fp = fopen(temp, "wb+");

            fputs("1", fp);

            fclose(fp);
        }

    }

    // redirection files
    snprintf(master_out, PATH_MAX, "%s/var/run/master%u.out",
             mysql_test_dir, restarts);
    snprintf(master_err, PATH_MAX, "%s/var/run/master%u.err",
             mysql_test_dir, restarts);

    snprintf(temp2,PATH_MAX,"%s/var",mysql_test_dir);
    mkdir(temp2,0);
    snprintf(temp2,PATH_MAX,"%s/var/log",mysql_test_dir);
    mkdir(temp2,0);

    // args
    init_args(&al);
    add_arg(&al, "%s", mysqld_file);
    add_arg(&al, "--no-defaults");
    add_arg(&al, "--log-bin=%s/var/log/master-bin",mysql_test_dir);
    add_arg(&al, "--server-id=1");
    add_arg(&al, "--basedir=%s", base_dir);
    add_arg(&al, "--port=%u", master_port);
    add_arg(&al, "--local-infile");
    add_arg(&al, "--core");
    add_arg(&al, "--datadir=%s", master_dir);
    add_arg(&al, "--pid-file=%s", master_pid);
    add_arg(&al, "--character-sets-dir=%s", char_dir);
    add_arg(&al, "--tmpdir=%s", mysql_tmp_dir);
    add_arg(&al, "--language=%s", lang_dir);
    add_arg(&al, "--log-bin-trust-routine-creators");
    add_arg(&al, "--log-slow-queries");
    add_arg(&al, "--log-queries-not-using-indexes");
#ifdef DEBUG	//only for debug builds
    add_arg(&al, "--debug");
#endif

    if (use_openssl)
    {
        add_arg(&al, "--ssl-ca=%s", ca_cert);
        add_arg(&al, "--ssl-cert=%s", server_cert);
        add_arg(&al, "--ssl-key=%s", server_key);
    }

    // $MASTER_40_ARGS
    add_arg(&al, "--rpl-recovery-rank=1");
    add_arg(&al, "--init-rpl-role=master");

    // $SMALL_SERVER
    add_arg(&al, "-O");
    add_arg(&al, "key_buffer_size=1M");
    add_arg(&al, "-O");
    add_arg(&al, "sort_buffer=256K");
    add_arg(&al, "-O");
    add_arg(&al, "max_heap_table_size=1M");

    // $EXTRA_MASTER_OPT
    if (master_opt[0] != NULL)
    {
        char *p;

        p = (char *)str_tok(master_opt, " \t");
        if (!strstr(master_opt, "timezone"))
        {
            while (p)
            {
                add_arg(&al, "%s", p);
                p = (char *)str_tok(NULL, " \t");
            }
        }
    }

    // remove the pid file if it exists
    remove(master_pid);

    // spawn
    if ((err= spawn(mysqld_file, &al, FALSE, NULL, master_out, master_err)) == 0)
    {
        sleep_until_file_exists(master_pid);

        if ((err = wait_for_server_start(bin_dir, user, password, master_port,
                                         mysql_tmp_dir)) == 0)
        {
            master_running = TRUE;
        }
        else
        {
            log_error("The master server went down early.");
        }
    }
    else
    {
        log_error("Unable to start master server.");
    }

    // free_args
    free_args(&al);
}
示例#26
0
文件: sftp.c 项目: SunnyBingoMe/codes
static int
parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
    int err_abort)
{
	char *path1, *path2, *tmp;
	int pflag, lflag, iflag, cmdnum, i;
	unsigned long n_arg;
	Attrib a, *aa;
	char path_buf[MAXPATHLEN];
	int err = 0;
	glob_t g;

	path1 = path2 = NULL;
	cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
	    &path1, &path2);

	if (iflag != 0)
		err_abort = 0;

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

	/* Perform command */
	switch (cmdnum) {
	case 0:
		/* Blank line */
		break;
	case -1:
		/* Unrecognized command */
		err = -1;
		break;
	case I_GET:
		err = process_get(conn, path1, path2, *pwd, pflag);
		break;
	case I_PUT:
		err = process_put(conn, path1, path2, *pwd, pflag);
		break;
	case I_RENAME:
		path1 = make_absolute(path1, *pwd);
		path2 = make_absolute(path2, *pwd);
		err = do_rename(conn, path1, path2);
		break;
	case I_SYMLINK:
		path2 = make_absolute(path2, *pwd);
		err = do_symlink(conn, path1, path2);
		break;
	case I_RM:
		path1 = make_absolute(path1, *pwd);
		remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
		for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
			printf(gettext("Removing %s\n"), g.gl_pathv[i]);
			err = do_rm(conn, g.gl_pathv[i]);
			if (err != 0 && err_abort)
				break;
		}
		break;
	case I_MKDIR:
		path1 = make_absolute(path1, *pwd);
		attrib_clear(&a);
		a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
		a.perm = 0777;
		err = do_mkdir(conn, path1, &a);
		break;
	case I_RMDIR:
		path1 = make_absolute(path1, *pwd);
		err = do_rmdir(conn, path1);
		break;
	case I_CHDIR:
		path1 = make_absolute(path1, *pwd);
		if ((tmp = do_realpath(conn, path1)) == NULL) {
			err = 1;
			break;
		}
		if ((aa = do_stat(conn, tmp, 0)) == NULL) {
			xfree(tmp);
			err = 1;
			break;
		}
		if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
			error("Can't change directory: Can't check target");
			xfree(tmp);
			err = 1;
			break;
		}
		if (!S_ISDIR(aa->perm)) {
			error("Can't change directory: \"%s\" is not "
			    "a directory", tmp);
			xfree(tmp);
			err = 1;
			break;
		}
		xfree(*pwd);
		*pwd = tmp;
		break;
	case I_LS:
		if (!path1) {
			do_globbed_ls(conn, *pwd, *pwd, lflag);
			break;
		}

		/* Strip pwd off beginning of non-absolute paths */
		tmp = NULL;
		if (*path1 != '/')
			tmp = *pwd;

		path1 = make_absolute(path1, *pwd);
		err = do_globbed_ls(conn, path1, tmp, lflag);
		break;
	case I_LCHDIR:
		if (chdir(path1) == -1) {
			error("Couldn't change local directory to "
			    "\"%s\": %s", path1, strerror(errno));
			err = 1;
		}
		break;
	case I_LMKDIR:
		if (mkdir(path1, 0777) == -1) {
			error("Couldn't create local directory "
			    "\"%s\": %s", path1, strerror(errno));
			err = 1;
		}
		break;
	case I_LLS:
		local_do_ls(cmd);
		break;
	case I_SHELL:
		local_do_shell(cmd);
		break;
	case I_LUMASK:
		umask(n_arg);
		printf(gettext("Local umask: %03lo\n"), n_arg);
		break;
	case I_CHMOD:
		path1 = make_absolute(path1, *pwd);
		attrib_clear(&a);
		a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
		a.perm = n_arg;
		remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
		for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
			printf(gettext("Changing mode on %s\n"), g.gl_pathv[i]);
			err = do_setstat(conn, g.gl_pathv[i], &a);
			if (err != 0 && err_abort)
				break;
		}
		break;
	case I_CHOWN:
	case I_CHGRP:
		path1 = make_absolute(path1, *pwd);
		remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
		for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
			if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
				if (err != 0 && err_abort)
					break;
				else
					continue;
			}
			if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
				error("Can't get current ownership of "
				    "remote file \"%s\"", g.gl_pathv[i]);
				if (err != 0 && err_abort)
					break;
				else
					continue;
			}
			aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
			if (cmdnum == I_CHOWN) {
				printf(gettext("Changing owner on %s\n"), g.gl_pathv[i]);
				aa->uid = n_arg;
			} else {
				printf(gettext("Changing group on %s\n"), g.gl_pathv[i]);
				aa->gid = n_arg;
			}
			err = do_setstat(conn, g.gl_pathv[i], aa);
			if (err != 0 && err_abort)
				break;
		}
		break;
	case I_PWD:
		printf(gettext("Remote working directory: %s\n"), *pwd);
		break;
	case I_LPWD:
		if (!getcwd(path_buf, sizeof(path_buf))) {
			error("Couldn't get local cwd: %s", strerror(errno));
			err = -1;
			break;
		}
		printf(gettext("Local working directory: %s\n"), path_buf);
		break;
	case I_QUIT:
		/* Processed below */
		break;
	case I_HELP:
		help();
		break;
	case I_VERSION:
		printf(gettext("SFTP protocol version %u\n"), sftp_proto_version(conn));
		break;
	case I_PROGRESS:
		showprogress = !showprogress;
		if (showprogress)
			printf("Progress meter enabled\n");
		else
			printf("Progress meter disabled\n");
		break;
	default:
		fatal("%d is not implemented", cmdnum);
	}

	if (g.gl_pathc)
		globfree(&g);
	if (path1)
		xfree(path1);
	if (path2)
		xfree(path2);

	/* If an unignored error occurs in batch mode we should abort. */
	if (err_abort && err != 0)
		return (-1);
	else if (cmdnum == I_QUIT)
		return (1);

	return (0);
}
示例#27
0
/* Process the images inside each directory */
bool processDir(std::string path, std::string image_name, std::string metrics_file) {

    /* Create the data output file for images that were processed */
    std::ofstream data_stream;
    data_stream.open(metrics_file, std::ios::app);
    if (!data_stream.is_open()) {
        std::cerr << "Could not open the data output file." << std::endl;
        return false;
    }

    // Create the output directory
    std::string out_directory = path + "result/";
    struct stat st = {0};
    if (stat(out_directory.c_str(), &st) == -1) {
        mkdir(out_directory.c_str(), 0700);
    }
    out_directory = out_directory + image_name + "/";
    st = {0};
    if (stat(out_directory.c_str(), &st) == -1) {
        mkdir(out_directory.c_str(), 0700);
    }

    // Count the number of images
    std::string dir_name = path + "jpg/" + image_name + "/";
    DIR *read_dir = opendir(dir_name.c_str());
    if (!read_dir) {
        std::cerr << "Could not open directory '" << dir_name << "'" << std::endl;
        return false;
    }
    struct dirent *dir = NULL;
    uint8_t z_count = 0;
    bool collect_name_pattern = false;
    std::string end_pattern;
    while ((dir = readdir(read_dir))) {
        if (!strcmp (dir->d_name, ".") || !strcmp (dir->d_name, "..")) continue;
        if (!collect_name_pattern) {
            std::string delimiter = "c1+";
            end_pattern = dir->d_name;
            size_t pos = end_pattern.find(delimiter);
            end_pattern.erase(0, pos);
            collect_name_pattern = true;
        }
        z_count++;
    }

    std::vector<cv::Mat>    blue_list(NUM_Z_LAYERS_COMBINED), 
                            green_list(NUM_Z_LAYERS_COMBINED), 
                            red_list(NUM_Z_LAYERS_COMBINED);
    for (uint8_t z_index = 1; z_index <= z_count; z_index++) {

        // Create the input filename and rgb stream output filenames
        std::string in_filename;
        if (z_count < 10) {
            in_filename = dir_name + image_name + 
                                        "_z" + std::to_string(z_index) + end_pattern;
        } else {
            if (z_index < 10) {
                in_filename = dir_name + image_name + 
                                        "_z0" + std::to_string(z_index) + end_pattern;
            } else if (z_index < 100) {
                in_filename = dir_name + image_name + 
                                        "_z" + std::to_string(z_index) + end_pattern;
            } else { // assuming number of z plane layers will never exceed 99
                std::cerr << "Does not support more than 99 z layers curently" << std::endl;
                return false;
            }
        }

        // Extract the bgr streams for each input image
        cv::Mat img = cv::imread(in_filename.c_str(), -1);
        if (img.empty()) return false;

        // Original image
        std::string out_original = out_directory + "zlayer_" + 
                                        std::to_string(z_index) + "_a_original.jpg";
        if (DEBUG_FLAG) cv::imwrite(out_original.c_str(), img);

        std::vector<cv::Mat> channel(3);
        cv::split(img, channel);
        blue_list[(z_index-1)%NUM_Z_LAYERS_COMBINED]  = channel[0];
        green_list[(z_index-1)%NUM_Z_LAYERS_COMBINED] = channel[1];
        red_list[(z_index-1)%NUM_Z_LAYERS_COMBINED]   = channel[2];

        // Continue collecting layers if needed
        //if (z_index%NUM_Z_LAYERS_COMBINED && (z_index != z_count)) continue;
        if (z_index < NUM_Z_LAYERS_COMBINED) continue;

        data_stream << image_name << ","
                    << std::to_string(z_index - NUM_Z_LAYERS_COMBINED + 1) << ","
                    << std::to_string(z_index) << ",";

        // Merge some layers together
        cv::Mat blue  = cv::Mat::zeros(channel[0].size(), CV_8UC1);
        cv::Mat green = cv::Mat::zeros(channel[1].size(), CV_8UC1);
        cv::Mat red   = cv::Mat::zeros(channel[1].size(), CV_8UC1);
        for (unsigned int merge_index = 0; 
                    merge_index < NUM_Z_LAYERS_COMBINED; merge_index++) {
            bitwise_or(blue, blue_list[merge_index], blue);
            bitwise_or(green, green_list[merge_index], green);
            bitwise_or(red, red_list[merge_index], red);
        }

        /** Gather BGR channel information needed for feature extraction **/

        /* Enhance layers */

        // Red channel
        cv::Mat red_enhanced;
        if(!enhanceImage(red, ChannelType::RED, &red_enhanced)) return false;
        std::string out_red = out_directory + "zlayer_" + 
                                        std::to_string(z_index) + "_red_enhanced.jpg";
        if (DEBUG_FLAG) cv::imwrite(out_red.c_str(), red_enhanced);

        // Purple channel
        cv::Mat purple_enhanced;
        if(!enhanceImage(red, ChannelType::PURPLE, &purple_enhanced)) return false;
        //cv::Mat red_enhanced_negative = cv::Mat::zeros(red_enhanced.size(), CV_8UC1);
        //bitwise_not(red_enhanced, red_enhanced_negative);
        //bitwise_and(purple_enhanced, red_enhanced_negative, purple_enhanced);
        std::string out_purple = out_directory + "zlayer_" + 
                                        std::to_string(z_index) + "_purple_enhanced.jpg";
        if (DEBUG_FLAG) cv::imwrite(out_purple.c_str(), purple_enhanced);

        // Blue channel
        cv::Mat blue_enhanced;
        if(!enhanceImage(blue, ChannelType::BLUE, &blue_enhanced)) return false;
        //cv::Mat purple_enhanced_negative = cv::Mat::zeros(purple_enhanced.size(), CV_8UC1);
        //bitwise_not(purple_enhanced, purple_enhanced_negative);
        //bitwise_and(blue_enhanced, purple_enhanced_negative, blue_enhanced);
        std::string out_blue = out_directory + "zlayer_" + 
                                        std::to_string(z_index) + "_blue_enhanced.jpg";
        if (DEBUG_FLAG) cv::imwrite(out_blue.c_str(), blue_enhanced);


        /* Segment */

        // Blue channel
        cv::Mat blue_segmented;
        std::vector<std::vector<cv::Point>> contours_blue;
        std::vector<cv::Vec4i> hierarchy_blue;
        std::vector<HierarchyType> blue_contour_mask;
        std::vector<double> blue_contour_area;
        contourCalc(    blue_enhanced,
                        MIN_NUCLEUS_SIZE,
                        &blue_segmented, 
                        &contours_blue,
                        &hierarchy_blue, 
                        &blue_contour_mask,
                        &blue_contour_area  );
        std::vector<std::vector<cv::Point>> contours_blue_filtered;
        filterCells(    ChannelType::BLUE, 
                        blue_enhanced, 
                        contours_blue, 
                        blue_contour_mask, 
                        &contours_blue_filtered );

        // Red channel
        cv::Mat red_segmented;
        std::vector<std::vector<cv::Point>> contours_red;
        std::vector<cv::Vec4i> hierarchy_red;
        std::vector<HierarchyType> red_contour_mask;
        std::vector<double> red_contour_area;
        contourCalc(    red_enhanced,
                        1.0,
                        &red_segmented, 
                        &contours_red,
                        &hierarchy_red, 
                        &red_contour_mask,
                        &red_contour_area  );


        /* Classify the cells */
        std::vector<std::vector<cv::Point>> contours_neural_soma;
        std::vector<std::vector<cv::Point>> contours_neural_nuclei, contours_astrocytes;
        cv::Mat purple_intersection = cv::Mat::zeros(purple_enhanced.size(), CV_8UC1);
        for (size_t i = 0; i < contours_blue_filtered.size(); i++) {
            std::vector<cv::Point> purple_contour;
            cv::Mat temp;
            if (findCellSoma( contours_blue_filtered[i], purple_enhanced, &temp, &purple_contour )) {
                contours_neural_soma.push_back(purple_contour);
                contours_neural_nuclei.push_back(contours_blue_filtered[i]);
                bitwise_or(purple_intersection, temp, purple_intersection);
                cv::Mat temp_not;
                bitwise_not(temp, temp_not);
                bitwise_and(purple_enhanced, temp_not, purple_enhanced);
            } else {
                contours_astrocytes.push_back(contours_blue_filtered[i]);
            }
        }


        /** Collect the metrics **/

        /* Cells */

        data_stream << contours_blue_filtered.size() << ",";

        float mean_dia = 0.0, stddev_dia = 0.0;
        float mean_aspect_ratio = 0.0, stddev_aspect_ratio = 0.0;
        float mean_error_ratio = 0.0, stddev_error_ratio = 0.0;

        // Characterize neural nuclei
        separationMetrics(  contours_neural_nuclei, 
                            &mean_dia, 
                            &stddev_dia, 
                            &mean_aspect_ratio, 
                            &stddev_aspect_ratio, 
                            &mean_error_ratio, 
                            &stddev_error_ratio
                        );
        data_stream << contours_neural_nuclei.size() << "," 
                    << mean_dia << "," 
                    << stddev_dia << "," 
                    << mean_aspect_ratio << "," 
                    << stddev_aspect_ratio << "," 
                    << mean_error_ratio << "," 
                    << stddev_error_ratio << ",";

        // Characterize the soma size
        separationMetrics(  contours_neural_soma, 
                            &mean_dia, 
                            &stddev_dia, 
                            &mean_aspect_ratio, 
                            &stddev_aspect_ratio, 
                            &mean_error_ratio, 
                            &stddev_error_ratio
                        );
        data_stream << mean_dia << "," 
                    << stddev_dia << "," 
                    << mean_aspect_ratio << "," 
                    << stddev_aspect_ratio << "," 
                    << mean_error_ratio << "," 
                    << stddev_error_ratio << ",";

        // Characterize the astrocyte nuclei
        separationMetrics(  contours_astrocytes, 
                            &mean_dia, 
                            &stddev_dia, 
                            &mean_aspect_ratio, 
                            &stddev_aspect_ratio, 
                            &mean_error_ratio, 
                            &stddev_error_ratio
                        );
        data_stream << contours_astrocytes.size() << "," 
                    << mean_dia << "," 
                    << stddev_dia << "," 
                    << mean_aspect_ratio << "," 
                    << stddev_aspect_ratio << "," 
                    << mean_error_ratio << "," 
                    << stddev_error_ratio << ",";


        /* Synapses */
        std::string red_output;
        binArea(red_contour_mask, red_contour_area, &red_output);
        data_stream << red_output << ",";

        data_stream << std::endl;


        /** Display analyzed images **/

        // Initialize
        cv::Mat drawing_blue  = blue;
        cv::Mat drawing_green = green;
        cv::Mat drawing_red   = red;

        // Draw soma
        for (size_t i = 0; i < contours_neural_soma.size(); i++) {
            drawContours(drawing_blue, contours_neural_soma, i, 255, 1, 8);
            drawContours(drawing_green, contours_neural_soma, i, 255, 1, 8);
            drawContours(drawing_red, contours_neural_soma, i, 255, 1, 8);
        }

        // Draw synapses
        for (size_t i = 0; i < contours_red.size(); i++) {
            drawContours(drawing_blue, contours_red, i, 0, 0, 8);
            drawContours(drawing_green, contours_red, i, 0, 0, 8);
            drawContours(drawing_red, contours_red, i, 255, -1, 8);
        }

        // Merge the modified red, blue and green layers
        std::vector<cv::Mat> merge_analyzed;
        merge_analyzed.push_back(drawing_blue);
        merge_analyzed.push_back(drawing_green);
        merge_analyzed.push_back(drawing_red);
        cv::Mat color_analyzed;
        cv::merge(merge_analyzed, color_analyzed);

        // Draw the analyzed image
        std::vector<int> compression_params;
        compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
        compression_params.push_back(101);
        cv::imwrite("/tmp/img.jpg", color_analyzed, compression_params);
        std::string out_analyzed = out_directory + "zlayer_" + 
                                        std::to_string(z_index) + "_analyzed.tif";
        std::string cmd = "convert -quiet /tmp/img.jpg " + out_analyzed;
        system(cmd.c_str());
        system("rm /tmp/img.jpg");
    }
    closedir(read_dir);
    data_stream.close();

    return true;
}
示例#28
0
文件: fs.c 项目: nevali/spool
/* Create the storage area for a job */
static ASSET *
fs_create_container(STORAGE *me, JOB *job)
{
	size_t c, max, pp, start, end;
	struct stat sbuf;
	ASSET *asset;
	int r;

	asset = asset_create();
	if(!asset)
	{
		return NULL;
	}
	asset->container = 1;
	/* Ensure the base path is reset back to its original value */
	me->path[me->pathlen] = 0;
	/* Construct a base path based upon HIERWIDTH and HIERDEPTH, derived
	 * from job->id. If HIERWIDTH was 3 and HIERDEPTH was 4, the result
	 * would be:
	 *
	 * path/AAA/BBB/CCC/DDD/AAABBBCCDDDEEE...
	 */	
	pp = me->pathlen;
	max = strlen(job->id->canonical);
	for(c = 0; c < HIERDEPTH; c++)
	{
		start = c * HIERWIDTH;
		if(start > max)
		{
			break;
		}
		end = start + HIERWIDTH;
		if(end > max)
		{
			end = max;
		}
		me->path[pp] = '/';
		pp++;
		memcpy(&(me->path[pp]), &(job->id->canonical[start]), end - start);
		pp += end - start;
		me->path[pp] = 0;
		r = stat(me->path, &sbuf);
		if(!r)
		{
			/* File exists */
			if(S_ISDIR(sbuf.st_mode))
			{
				/* It's a directory */
				continue;
			}
		}
		r = mkdir(me->path, 0777);
		if(r < 0)
		{
			fprintf(stderr, "%s: %s: %s\n", short_program_name, me->path, strerror(errno));
			asset_free(asset);
			return NULL;
		}
	}
	me->path[pp] = '/';
	pp++;
	strcpy(&(me->path[pp]), job->id->canonical);
	r = mkdir(me->path, 0777);
	if(r < 0)
	{
		fprintf(stderr, "%s: %s: %s\n", short_program_name, me->path, strerror(errno));
		asset_free(asset);
		return NULL;
	}
	r = asset_set_path(asset, me->path);
	if(r < 0)
	{
		asset_free(asset);
		return NULL;
	}
	me->path[me->pathlen] = 0;	
	return asset;
}
示例#29
0
static int sis_try_deduplicate(const char *rootdir, const char *fname)
{
	const char *p, *hash, *hashdir, *path, *hashes_dir, *hashes_path;
	struct stat st;
	ino_t inode;
	int ret;

	/* fname should be in <hash>-<guid> format */
	p = strchr(fname, '-');
	i_assert(p != NULL);

	hash = t_strdup_until(fname, p);
	hashdir = sis_get_dir(rootdir, hash);
	path = t_strdup_printf("%s/%s", hashdir, fname);

	hashes_dir = t_strconcat(hashdir, "/", HASH_DIR_NAME, NULL);
	hashes_path = t_strconcat(hashes_dir, "/", hash, NULL);
	if (link(path, hashes_path) == 0) {
		/* first file with this hash. we're done */
		return 0;
	}
	if (errno == ENOENT) {
		/* either path was already deleted or hashes dir
		   doesn't exist */
		if (mkdir(hashes_dir, 0700) < 0) {
			if (errno == EEXIST)
				return 0;
			i_error("mkdir(%s) failed: %m", hashes_dir);
			return -1;
		}
		/* try again */
		if (link(path, hashes_path) == 0 || errno == ENOENT)
			return 0;
	}
	if (errno != EEXIST) {
		i_error("link(%s, %s) failed: %m", path, hashes_path);
		return -1;
	}

	/* need to do a byte-by-byte comparison. but check first if someone
	   else already had deduplicated the file. */
	if (stat(path, &st) < 0) {
		if (errno == ENOENT) {
			/* just got deleted */
			return 0;
		}
		i_error("stat(%s) failed: %m", path);
		return -1;
	}
	if (st.st_nlink > 1) {
		/* already deduplicated */
		return 0;
	}

	ret = file_contents_equal(path, hashes_path, &inode);
	if (ret < 0) {
		if (errno == ENOENT) {
			/* either path or hashes_path was deleted. */
			return sis_try_deduplicate(rootdir, fname);
		}
		return -1;
	}
	if (ret > 0) {
		/* equal, replace with hard link */
		ret = hardlink_replace(hashes_path, path, inode);
		if (ret > 0)
			return 0;
		else if (ret < 0)
			return -1;
		/* too many hard links or inode changed */
	}

	/* replace hashes link with this  */
	return hardlink_replace(path, hashes_path, st.st_ino) < 0 ? -1 : 0;
}
示例#30
0
/* 香港广场显示用户导入next界面  */
int ncmUNext_hk(utShmHead *psShmHead, int iFd,utMsgHead *psMsgHead)
{
    pasDbCursor *psCur;
    char caTemp[400];
    FILE *fp;
    int i,iNum,iReturn;

    long lSid,lCount,lFlags;
    utPltDbHead *psDbHead;

    char caFile[256];
    char imp_file[129]="";
    char temp_file[129]="";
    char sqlbuf[1024]="";
    int  m=0;
    char caLocal[128],caRemote[128],caType[128];
    char caText[256],caBuf[16002];
    unsigned id=0;
    char name[36];
    char caGroupname[36],caDispname[36];
    char caGroupid[20];
    unsigned long lGroupid;
    char *p;
#ifdef LDEBUG
    utMsgPrintMsg(psMsgHead);
#endif
    utMsgPrintMsg(psMsgHead);
    psDbHead = utPltInitDb();
    if(!utFileIsExist("/home/ncmysql/ncsrv/upload")) {
        if(mkdir("/home/ncmysql/ncsrv/upload",777)!=0) {
            utWebDispMsg(iFd,psMsgHead,"nc/ncmsg_back.htm","导入","打开文件出错");
            return 0;

        }
    }
    system("chmod -Rf 777 /home/ncmysql/ncsrv/upload");
//chmod("/home/ncmysql/ncs/upload",777);

    /*取单位*/
    sprintf(sqlbuf,"select groupid,groupname,dispname from ncsrvgroup where 1=1 ");
    sprintf(sqlbuf+strlen(sqlbuf)," order by groupname limit 0,2000 ");
    psCur=pasDbOpenSql(sqlbuf,0);
    if(psCur==NULL)
    {
        utWebDispMsg(iFd,psMsgHead,"nc/ncmsg_back.htm","导入","打开文件出错");
        return 0;
    }
    iReturn=0;
    m=0;
    while((iReturn==0)||(iReturn==1405))
    {
        memset(caGroupname,0,sizeof(caGroupname));
        lGroupid=0;
        memset(caDispname,0,sizeof(caDispname));
        iReturn=pasDbFetchInto(psCur,
                               UT_TYPE_LONG,4,&lGroupid,
                               UT_TYPE_STRING,30,caGroupname,
                               UT_TYPE_STRING,30,caDispname);

        if((iReturn==0)||(iReturn==1405))
        {
            m++;
            utPltPutLoopVar(psDbHead,"name",m,caDispname);
            sprintf(caTemp,"%d_%s",lGroupid,caGroupname);
            utPltPutLoopVar(psDbHead,"id",m,caTemp);
        }
    }
    pasDbCloseCursor(psCur);


    utMsgGetSomeNVar(psMsgHead,2,"fname",UT_TYPE_STRING,  255,imp_file,
                     "groupid",UT_TYPE_STRING,15,caGroupid);

    sprintf(caTemp,"select dispname,groupname from ncsrvgroup where groupid=%s ",caGroupid);
    memset(caDispname,0,sizeof(caDispname));
    memset(caGroupname,0,sizeof(caGroupname));
    pasDbOneRecord(caTemp,0,UT_TYPE_STRING,63,caDispname,
                   UT_TYPE_STRING,31,caGroupname);
    utPltPutVar(psDbHead,"name",caDispname);
    utPltPutVarF(psDbHead,"id","%s_%s",caGroupid,caGroupname);

    printf("imp_file=%s,groupid=%s\n",imp_file,caGroupid);
    if(strlen(imp_file)!=0)
    {
        p=utStrSkipSpaces(imp_file);
        p=utStrGetWord(p,temp_file,200,";\n");
        if((*p)==';')
            p=utStrGetWord(p+1,temp_file,200,";\n");

        fp=fopen(temp_file,"r");
        printf("temp_file=%s\n",temp_file);
        if(fp == NULL)
        {
            utWebDispMsg(iFd,psMsgHead,"nc/ncmsg_back.htm","导入","打开文件出错");
            return 0;
        }


        p = fgets(caBuf,16000,fp);
        iNum = 0;
        while(p && *p) {
            p = utStrGetWord(p,caTemp,300,",\r\n");
            if(!utStrIsSpaces(caTemp)) {
                iNum++;
                utPltPutLoopVar(psDbHead,"caTemp",iNum,caTemp);
                utPltPutLoopVarF(psDbHead,"iNum",iNum,"%lu",iNum-1);

                if(iNum==1)
                {
                    utPltPutVar(psDbHead,"username",caTemp);
                    utPltPutVarF(psDbHead,"username_num","%lu",iNum-1);
                }
                if(iNum==2)
                {
                    utPltPutVar(psDbHead,"dispname",caTemp);
                    utPltPutVarF(psDbHead,"dispname_num","%lu",iNum-1);
                }

                if(iNum==3)
                {
                    utPltPutVar(psDbHead,"pass",caTemp);
                    utPltPutVarF(psDbHead,"pass_num","%lu",iNum-1);
                }
                if(iNum==4)
                {
                    utPltPutVar(psDbHead,"openid",caTemp);
                    utPltPutVarF(psDbHead,"openid_num","%lu",iNum-1);
                }
                if(iNum==5)
                {
                    utPltPutVar(psDbHead,"mark",caTemp);
                    utPltPutVarF(psDbHead,"mark_num","%lu",iNum-1);
                }
                if(iNum==6)
                {
                    utPltPutVar(psDbHead,"usermac",caTemp);
                    utPltPutVarF(psDbHead,"usermac_num","%lu",iNum-1);
                }
            }
            if(*p != ',') {
                break;
            }
            p++;
        }
        fclose(fp);


    }
    utPltPutVar(psDbHead,"fname",temp_file);
    utPltPutVar(psDbHead,"groupid",caGroupid);
    utPltOutToHtml(iFd,psMsgHead,psDbHead,"nc/cust_import_next_hk.htm");
    return 0;
}