Example #1
0
void Dirs::initUsersDir()
{
    settings.usersDir = settings.serverConfigDir + "/users/";
    if (mkdir_r(settings.usersDir.c_str()))
    {
        // TRANSLATORS: directory creation error
        logger->error(strprintf(_("%s doesn't exist and can't be created!"),
            settings.usersDir.c_str()));
    }

    settings.npcsDir = settings.serverConfigDir + "/npcs/";
    if (mkdir_r(settings.npcsDir.c_str()))
    {
        // TRANSLATORS: directory creation error
        logger->error(strprintf(_("%s doesn't exist and can't be created!"),
            settings.npcsDir.c_str()));
    }

    settings.usersIdDir = settings.serverConfigDir + "/usersid/";
    if (mkdir_r(settings.usersIdDir.c_str()))
    {
        // TRANSLATORS: directory creation error
        logger->error(strprintf(_("%s doesn't exist and can't be created!"),
            settings.usersIdDir.c_str()));
    }
}
Example #2
0
void Dirs::initScreenshotDir()
{
    if (!settings.options.screenshotDir.empty())
    {
        settings.screenshotDir = settings.options.screenshotDir;
        if (mkdir_r(settings.screenshotDir.c_str()))
        {
            logger->log(strprintf(
                // TRANSLATORS: directory creation error
                _("Error: %s doesn't exist and can't be created! "
                "Exiting."), settings.screenshotDir.c_str()));
        }
    }
    else if (settings.screenshotDir.empty())
    {
#ifdef __native_client__
        settings.screenshotDir = _nacl_dir + "/screenshots/";
#else  // __native_client__
        settings.screenshotDir = decodeBase64String(
            config.getStringValue("screenshotDirectory3"));
        if (settings.screenshotDir.empty())
        {
#ifdef __ANDROID__
            settings.screenshotDir = getSdStoragePath()
                + std::string("/images");

            if (mkdir_r(settings.screenshotDir.c_str()))
            {
                logger->log(strprintf(
                    // TRANSLATORS: directory creation error
                    _("Error: %s doesn't exist and can't be created! "
                    "Exiting."), settings.screenshotDir.c_str()));
            }
#else  // ANDROID
            settings.screenshotDir = getPicturesDir();
#endif  // ANDROID
            if (config.getBoolValue("useScreenshotDirectorySuffix"))
            {
                const std::string configScreenshotSuffix =
                    branding.getValue("screenshots", "ManaPlus");

                if (!configScreenshotSuffix.empty())
                {
                    settings.screenshotDir.append(dirSeparator).append(
                        configScreenshotSuffix);
                }
            }
            config.setValue("screenshotDirectory3",
                encodeBase64String(settings.screenshotDir));
        }
#endif  // __native_client__
    }
    logger->log("screenshotDirectory: " + settings.screenshotDir);
}
Example #3
0
/**
 * Initializes the home directory. On UNIX and FreeBSD, ~/.mana is used. On
 * Windows and other systems we use the current working directory.
 */
void ConfigManager::initServerConfig(const std::string &serverName)
{
    settings.serverConfigDir = settings.configDir + dirSeparator + serverName;

    if (mkdir_r(settings.serverConfigDir.c_str()))
    {
        // TRANSLATORS: directory creation error
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
            "Exiting."), settings.serverConfigDir.c_str()));
    }
    const std::string configPath = settings.serverConfigDir + "/config.xml";
    FILE *configFile = fopen(configPath.c_str(), "r");
    if (!configFile)
    {
        configFile = fopen(configPath.c_str(), "wt");
        logger->log("Creating new server config: " + configPath);
    }
    if (configFile)
    {
        fclose(configFile);
        serverConfig.init(configPath);
        serverConfig.setDefaultValues(getConfigDefaults());
        logger->log("serverConfigPath: " + configPath);
    }

    int val = serverConfig.getValue("enableManaMarketBot", -1);
    if (val == -1)
    {
        if (client->isTmw())
            val = 1;
        else
            val = 0;
        serverConfig.setValue("enableManaMarketBot", val);
    }
}
Example #4
0
bool Game::saveScreenshot(SDL_Surface *const screenshot)
{
    std::string screenshotDirectory = client->getScreenshotDirectory();

    if (mkdir_r(screenshotDirectory.c_str()) != 0)
    {
        logger->log("Directory %s doesn't exist and can't be created! "
                    "Setting screenshot directory to home.",
                    screenshotDirectory.c_str());
        screenshotDirectory = std::string(PhysFs::getUserDir());
    }

    // Search for an unused screenshot name
    std::stringstream filenameSuffix;
    std::stringstream filename;
    std::fstream testExists;
    bool found = false;
    static unsigned int screenshotCount = 0;
    do
    {
        screenshotCount++;
        filenameSuffix.str("");
        filename.str("");
        filename << screenshotDirectory << "/";
        filenameSuffix << branding.getValue("appName", "ManaPlus")
                       << "_Screenshot_" << screenshotCount << ".png";
        filename << filenameSuffix.str();
        testExists.open(filename.str().c_str(), std::ios::in);
        found = !testExists.is_open();
        testExists.close();
    }
    while (!found);

    const bool success = ImageWriter::writePNG(screenshot, filename.str());

    if (success)
    {
        std::stringstream chatlogentry;
        // TRANSLATORS: save file message
        chatlogentry << strprintf(_("Screenshot saved as %s"),
            filenameSuffix.str().c_str());
        if (localChatTab)
            localChatTab->chatLog(chatlogentry.str(), BY_SERVER);
    }
    else
    {
        if (localChatTab)
        {
            // TRANSLATORS: save file message
            localChatTab->chatLog(_("Saving screenshot failed!"),
                                  BY_SERVER);
        }
        logger->log1("Error: could not save screenshot.");
    }

    MSDL_FreeSurface(screenshot);

    return success;
}
Example #5
0
bool mkdir_r(char* path) {
	bool ret = true;
	char* const sep = strrchr(path,'/');
	if(sep && sep != path) {
		*sep = '\0';
		ret = mkdir_r(path);
		*sep = '/';
	}
	return ret && (!mkdir(path,0755) || errno == EEXIST);
}
Example #6
0
File: db.c Project: AdUser/xa-tags
void
db_open(void)
{
  int flags = SQLITE_OPEN_READWRITE;
  struct stat st;
  char *err = NULL;

  errno = 0;
  if (stat(opts.db.path, &st) == -1 && errno == ENOENT)
    {
#ifdef DB_AUTOCREATE
      mkdir_r(opts.db.path, 0755);
      flags |= SQLITE_OPEN_CREATE;
      if (sqlite3_open_v2(opts.db.path, &db_conn, flags, NULL) != SQLITE_OK)
        msg(msg_error, COMMON_ERR_FMTN, MSG_D_FAILOPEN, sqlite3_errmsg(db_conn));
      if (sqlite3_exec(db_conn, SQL_DB_CREATE_1, NULL, NULL, &err) != SQLITE_OK)
        msg(msg_error, COMMON_ERR_FMTN, MSG_D_FAILCREATE, err);
      if (sqlite3_exec(db_conn, SQL_DB_CREATE_2, NULL, NULL, &err) != SQLITE_OK)
        msg(msg_error, COMMON_ERR_FMTN, MSG_D_FAILCREATE, err);
      if (sqlite3_exec(db_conn, SQL_DB_CREATE_3, NULL, NULL, &err) != SQLITE_OK)
        msg(msg_error, COMMON_ERR_FMTN, MSG_D_FAILCREATE, err);
#ifdef UNIQ_TAGS_LIST
      if (sqlite3_exec(db_conn, SQL_DB_CREATE_UNIQ,   NULL, NULL, &err) != SQLITE_OK)
        msg(msg_error, COMMON_ERR_FMTN, MSG_D_FAILCREATE, err);
#endif
      if (sqlite3_exec(db_conn, SQL_DB_INIT,   NULL, NULL, &err) != SQLITE_OK)
        msg(msg_error, COMMON_ERR_FMTN, MSG_D_FAILCREATE, err);
      FREE(err);
      sqlite3_close(db_conn);
      errno = 0;
      msg(msg_warn, COMMON_MSG_FMTN, MSG_D_DBCREATED, opts.db.path);
#else
      err = strerror(errno);
      msg(msg_error, COMMON_ERR_FMTN, err, opts.db.path);
#endif
    }

  if (errno != 0)
    msg(msg_error, COMMON_ERR_FMTN, MSG_U_UNKNERR, strerror(errno));

  if (opts.db.readonly == true)
    flags = SQLITE_OPEN_READONLY;

  msg(msg_debug, "%s v%s: %s\n", MSG_D_LOADED, DB_VERSION, opts.db.path);

  if (sqlite3_open_v2(opts.db.path, &db_conn, flags, NULL) != SQLITE_OK)
    msg(msg_error, COMMON_ERR_FMTN, MSG_D_FAILOPEN, sqlite3_errmsg(db_conn));

  sqlite3_exec(db_conn, SQL_DB_CHECK_VERSION, _db_check_version, NULL, NULL);
  sqlite3_exec(db_conn, SQL_DB_CHECK_UNIQ,    _db_check_uniq,    NULL, NULL);

#ifdef ASYNC_DB_WRITE
  sqlite3_exec(db_conn, "BEGIN  TRANSACTION;", NULL, NULL, NULL);
#endif
}
Example #7
0
void Dirs::initTempDir()
{
    settings.tempDir = settings.localDataDir + dirSeparator + "temp";

    if (mkdir_r(settings.tempDir.c_str()))
    {
        // TRANSLATORS: directory creation error
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
            "Exiting."), settings.tempDir.c_str()));
    }
//    ResourceManager::deleteFilesInDirectory(settings.tempDir);
}
Example #8
0
/* generate local directory recursively --------------------------------------*/
static int mkdir_r(const char *dir)
{
    char pdir[1024],*p;
    
#ifdef WIN32
    HANDLE h;
    WIN32_FIND_DATA data;
    
    if (!*dir||strstr(dir,":\\")) return 1;
    
    strcpy(pdir,dir);
    if ((p=strrchr(pdir,FILEPATHSEP))) {
        *p='\0';
        h=FindFirstFile(pdir,&data);
        if (h==INVALID_HANDLE_VALUE) {
            if (!mkdir_r(pdir)) return 0;
        }
        else FindClose(h);
    }
    return CreateDirectory(dir,NULL)||GetLastError()==ERROR_ALREADY_EXISTS;
#else
    FILE *fp;
    
    if (!*dir) return 1;
    
    strcpy(pdir,dir);
    if ((p=strrchr(pdir,FILEPATHSEP))) {
        *p='\0';
        if (!(fp=fopen(pdir,"r"))) {
            if (!mkdir_r(pdir)) return 0;
        }
        else fclose(fp);
    }
    return !mkdir(dir,0777)||errno==EEXIST;
#endif
}
Example #9
0
static void check_dir(const char *path)
{
    char *path_org = NULL;
    const char *dir = NULL;
    if (strstr(path, "/")) {//file with dir
        path_org = strdup(path);
        dir = get_dir(path_org);
        if (-1 == access(dir, F_OK|W_OK|R_OK)) {
            if (-1 == mkdir_r(dir, 0775)) {
                fprintf(stderr, "mkdir %s failed\n", path_org);
            }
        }
        free(path_org);
    }
}
Example #10
0
void Dirs::initConfigDir()
{
    settings.configDir = settings.options.configDir;

    if (settings.configDir.empty())
    {
#ifdef __APPLE__
        settings.configDir = settings.localDataDir + dirSeparator
            + branding.getValue("appShort", "mana");
#elif defined __HAIKU__
        settings.configDir = std::string(PhysFs::getUserDir()) +
           "/config/settings/Mana" +
           branding.getValue("appName", "ManaPlus");
#elif defined WIN32
        settings.configDir = getSpecialFolderLocation(CSIDL_APPDATA);
        if (settings.configDir.empty())
        {
            settings.configDir = settings.localDataDir;
        }
        else
        {
            settings.configDir.append("/mana/").append(branding.getValue(
                "appShort", "mana"));
        }
#elif defined __ANDROID__
        settings.configDir = getSdStoragePath() + branding.getValue(
            "appShort", "ManaPlus").append("/config");
#elif defined __native_client__
        settings.configDir = _nacl_dir.append("/config");
#else  // __APPLE__

        settings.configDir = std::string(PhysFs::getUserDir()).append(
            "/.config/mana/").append(branding.getValue("appShort", "mana"));
#endif  // __APPLE__

        logger->log("Generating config dir: " + settings.configDir);
    }

    if (mkdir_r(settings.configDir.c_str()))
    {
        // TRANSLATORS: directory creation error
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
            "Exiting."), settings.configDir.c_str()));
    }
}
Example #11
0
void Dirs::initLocalDataDir()
{
    settings.localDataDir = settings.options.localDataDir;

    if (settings.localDataDir.empty())
    {
#ifdef __APPLE__
        // Use Application Directory instead of .mana
        settings.localDataDir = std::string(PhysFs::getUserDir()) +
            "/Library/Application Support/" +
            branding.getValue("appName", "ManaPlus");
#elif defined __HAIKU__
        settings.localDataDir = std::string(PhysFs::getUserDir()) +
           "/config/data/Mana";
#elif defined WIN32
        settings.localDataDir = getSpecialFolderLocation(CSIDL_LOCAL_APPDATA);
        if (settings.localDataDir.empty())
            settings.localDataDir = std::string(PhysFs::getUserDir());
        settings.localDataDir.append("/Mana");
#elif defined __ANDROID__
        settings.localDataDir = getSdStoragePath() + branding.getValue(
            "appShort", "ManaPlus") + "/local";
#elif defined __native_client__
        settings.localDataDir = _nacl_dir.append("/local");
#else  // __APPLE__

        settings.localDataDir = std::string(PhysFs::getUserDir()) +
            ".local/share/mana";
#endif  // __APPLE__
    }

    if (mkdir_r(settings.localDataDir.c_str()))
    {
        // TRANSLATORS: directory creation error
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
            "Exiting."), settings.localDataDir.c_str()));
    }
#ifdef USE_PROFILER
    Perfomance::init(settings.localDataDir + "/profiler.log");
#endif  // USE_PROFILER
}
Example #12
0
int
main(int argc, char *argv[])
{
	long timeout_val;
	int c;
	int flushcache = 0;
	int unmount_automounted = 0;	// Unmount automounted mounts
	struct autodir *dir, *d;
	char real_mntpnt[PATH_MAX];
	struct stat stbuf;
	char *master_map = "auto_master";
	int null;
	struct statfs *mntp;
	int count = 0;
	char *stack[STACKSIZ];
	char **stkptr;
	char *defval;
	int fd;
	int flags, altflags;
	struct staticmap *static_ent;

	/*
	 * Read in the values from config file first before we check
	 * commandline options so the options override the file.
	 */
	if ((defopen(AUTOFSADMIN)) == 0) {
		if ((defval = defread("AUTOMOUNT_TIMEOUT=")) != NULL) {
			errno = 0;
			timeout_val = strtol(defval, (char **)NULL, 10);
			if (errno == 0 && timeout_val > 0 &&
			    timeout_val <= INT_MAX)
				mount_timeout = (int)timeout_val;
		}
		if ((defval = defread("AUTOMOUNT_VERBOSE=")) != NULL) {
			if (strncasecmp("true", defval, 4) == 0)
				verbose = TRUE;
			else
				verbose = FALSE;
		}
		if ((defval = defread("AUTOMOUNTD_TRACE=")) != NULL) {
			/*
			 * Turn on tracing here too if the automountd
			 * is set up to do it - since automount calls
			 * many of the common library functions.
			 */
			errno = 0;
			trace = (int)strtol(defval, (char **)NULL, 10);
			if (errno != 0)
				trace = 0;
		}

		/* close defaults file */
		defopen(NULL);
	}

	while ((c = getopt(argc, argv, "mM:D:f:t:vcu?")) != EOF) {
		switch (c) {
		case 'm':
			pr_msg("Warning: -m option not supported");
			break;
		case 'M':
			pr_msg("Warning: -M option not supported");
			break;
		case 'D':
			pr_msg("Warning: -D option not supported");
			break;
		case 'f':
			pr_msg("Error: -f option no longer supported");
			usage();
			break;
		case 't':
			if (strchr(optarg, '=')) {
				pr_msg("Error: invalid value for -t");
				usage();
			}
			mount_timeout = atoi(optarg);
			break;
		case 'v':
			verbose++;
			break;
		case 'c':
			flushcache++;
			break;
		case 'u':
			unmount_automounted++;
			break;
		default:
			usage();
			break;
		}
	}

	if (optind < argc) {
		pr_msg("%s: command line mountpoints/maps "
			"no longer supported",
			argv[optind]);
		usage();
	}

	/*
	 * Get an array of current system mounts
	 */
	num_current_mounts = getmntinfo(&current_mounts, MNT_NOWAIT);
	if (num_current_mounts == 0) {
		pr_msg("Couldn't get current mounts: %m");
		exit(1);
	}

	autofs_control_fd = open("/dev/" AUTOFS_CONTROL_DEVICE, O_RDONLY);
	if (autofs_control_fd == -1 && errno == ENOENT) {
		/*
		 * Oops, we probably don't have the autofs kext
		 * loaded.
		 */
		FTS *fts;
		static char *const paths[] = { "/Network", NULL };
		FTSENT *ftsent;
		int error;

		/*
		 * This means there can't be any autofs mounts yet, so
		 * this is the first time we're being run since a reboot.
		 * Clean out any stuff left in /Network from the reboot.
		 */
		fts = fts_open(paths, FTS_NOCHDIR|FTS_PHYSICAL|FTS_XDEV,
		    NULL);
		if (fts != NULL) {
			while ((ftsent = fts_read(fts)) != NULL) {
				/*
				 * We only remove directories - if
				 * there are files, we assume they're
				 * there for a purpose.
				 *
				 * We remove directories after we've
				 * removed their children, so we want
				 * to process directories visited in
				 * post-order.
				 *
				 * We don't remove /Network itself.
				 */
				if (ftsent->fts_info == FTS_DP &&
				    ftsent->fts_level > FTS_ROOTLEVEL)
					rmdir(ftsent->fts_accpath);
			}
			fts_close(fts);
		}

		/*
		 * Now load it.
		 */
		error = load_autofs();
		if (error != 0) {
			pr_msg("can't load autofs kext");
			exit(1);
		}

		/*
		 * Try the open again.
		 */
		autofs_control_fd = open("/dev/" AUTOFS_CONTROL_DEVICE,
		    O_RDONLY);
	}
	if (autofs_control_fd == -1) {
		if (errno == EBUSY)
			pr_msg("Another automount is running");
		else
			pr_msg("Couldn't open %s: %m", "/dev/" AUTOFS_CONTROL_DEVICE);
		exit(1);
	}

	/*
	 * Update the mount timeout.
	 */
	if (ioctl(autofs_control_fd, AUTOFS_SET_MOUNT_TO, &mount_timeout) == -1)
		pr_msg("AUTOFS_SET_MOUNT_TO failed: %m");

	/*
	 * Attempt to unmount any non-busy triggered mounts; this includes
	 * not only autofs mounts, but, for example SMB Dfs mounts.
	 *
	 * This is done before sleep, and after a network change, to
	 * try to get rid of as many network mounts as we can; each
	 * unmounted network mount is a network mount on which we
	 * can't hang.
	 */
	if (unmount_automounted) {
		if (verbose)
			pr_msg("Unmounting triggered mounts");
		if (ioctl(autofs_control_fd, AUTOFS_UNMOUNT_TRIGGERED, 0) == -1)
			pr_msg("AUTOFS_UNMOUNT_TRIGGERED failed: %m");
		exit(0);
	}

	if (flushcache) {
		/*
		 * Notify the automounter that it should flush its caches,
		 * as we might be on a different network with different maps.
		 */
		if (ioctl(autofs_control_fd, AUTOFS_NOTIFYCHANGE, 0) == -1)
			pr_msg("AUTOFS_NOTIFYCHANGE failed: %m");
	}

	(void) umask(0);
	ns_setup(stack, &stkptr);

	(void) loadmaster_map(master_map, "", stack, &stkptr);

	/*
	 * Mount the daemon at its mount points.
	 */
	for (dir = dir_head; dir; dir = dir->dir_next) {

		if (realpath(dir->dir_name, real_mntpnt) == NULL) {
			/*
			 * We couldn't get the real path for this,
			 * perhaps because it doesn't exist.
			 * If it's not because it doesn't exist, just
			 * give up on this entry.  Otherwise, just null
			 * out the real path - we'll try creating the
			 * directory later, and will set dir_realpath
			 * then, if that succeeds.
			 */
			if (errno != ENOENT) {
				pr_msg("%s: Can't convert to real path: %m",
				    dir->dir_name);
				continue;
			}
			dir->dir_realpath = NULL;
		} else {
			dir->dir_realpath = strdup(real_mntpnt);
			if (dir->dir_realpath == NULL) {
				pr_msg("Couldn't allocate real path: %m");
				exit(1);
			}
		}

		/*
		 * Skip null entries
		 */
		if (strcmp(dir->dir_map, "-null") == 0)
			continue;

		/*
		 * Skip null'ed entries
		 */
		null = 0;
		for (d = dir->dir_prev; d; d = d->dir_prev) {
			if (paths_match(dir, d))
				null = 1;
		}
		if (null)
			continue;

		/*
		 * If this is -fstab, and there are no fstab "net" entries,
		 * skip this map if our directory search path doesn't
		 * include Active Directory.  We don't want /Network/Servers
		 * (or wherever it shows up) to exist if this system isn't
		 * using AD (AD supplies fstab entries on the fly, so they
		 * might not exist right now) and we don't have any fstab
		 * entries.
		 */
		if (strcmp(dir->dir_map, "-fstab") == 0) {
			if (!have_ad() && !havefstabkeys()) {
				/*
				 * We're not using AD, and fstab is
				 * inaccessible or devoid of "net" entries.
				 */
				free(dir->dir_map);
				dir->dir_map = strdup("-null");
				continue;
			}
			endfsent();
		}

		/*
		 * If this is -fstab or -static, and there's another entry
		 * that's supposed to mount something on the same directory
		 * and isn't "-fstab" or "-static", ignore this; we might
		 * have a server that's supplying real automounter maps for
		 * the benefit of OS X systems with autofs and also supplying
		 * fstab entries for the benefit of older OS X systems, and
		 * we want to mount the real automounter map, not the -fstab
		 * or -static map, in that case.
		 */
		if (strcmp(dir->dir_map, "-fstab") == 0 ||
		    strcmp(dir->dir_map, "-static") == 0) {
			for (d = dir_head; d; d = d->dir_next) {
				if (paths_match(dir, d) &&
				    strcmp(d->dir_map, "-fstab") != 0 &&
				    strcmp(d->dir_map, "-static") != 0) {
					pr_msg("%s: ignoring redundant %s map",
					    dir->dir_name, dir->dir_map);
					break;
				}
			}
			if (d != NULL) {
				continue;
			}
		}

		/*
		 * Parse the mount options and get additional flags to pass
		 * to mount() (standard mount options) and autofs mount
		 * options.
		 *
		 * XXX - we ignore flags on an update; if they're different
		 * from the current flags for that mount, we'd need to do a
		 * remount.
		 */
		if (!parse_mntopts(dir->dir_opts, &flags, &altflags)) {
			/*
			 * Failed.
			 */
			continue;
		}

		/*
		 * If this is -static, check whether the entry refers
		 * to this host; if so, make the appropriate symlink
		 * exist at the "mount point" path.
		 */
		if (strcmp(dir->dir_map, "-static") == 0) {
			static_ent = get_staticmap_entry(dir->dir_name);
			if (static_ent == NULL) {
				/*
				 * Whiskey tango foxtrot?  There should
				 * be an entry here.  Log an error and
				 * ignore this mount.
				 */
				pr_msg("can't find fstab entry for %s",
				    dir->dir_name);
				continue;
			}
			if (host_is_us(static_ent->host, strlen(static_ent->host)) ||
			    self_check(static_ent->host)) {
				/*
				 * Yup, this is us.
				 * Try to make the appropriate symlink.
				 */
				make_symlink(static_ent->localpath,
				    dir->dir_name);
				release_staticmap_entry(static_ent);
				continue;
			}
			release_staticmap_entry(static_ent);
		}

		/*
		 * Check whether there's already an entry
		 * in the mnttab for this mountpoint.
		 */
		if (dir->dir_realpath != NULL &&
		    (mntp = find_mount(dir->dir_realpath)) != NULL) {
			struct autofs_update_args au;

			/*
			 * If it's not an autofs mount - don't
			 * mount over it.
			 */
			if (strcmp(mntp->f_fstypename, MNTTYPE_AUTOFS) != 0) {
				pr_msg("%s: already mounted on %s",
					mntp->f_mntfromname, dir->dir_realpath);
				continue;
			}

			/*
			 * This is already mounted, so just update it.
			 * We don't bother to check whether any options are
			 * changing, as we'd have to make a trip into the
			 * kernel to get the current options to check them,
			 * so we might as well just make a trip to do the
			 * update.
			 */
			au.fsid		= mntp->f_fsid;
			au.opts		= dir->dir_opts;
			au.map		= dir->dir_map;
			au.mntflags	= altflags;
			au.direct 	= dir->dir_direct;
			au.node_type	= dir->dir_direct ? NT_TRIGGER : 0;

			if (ioctl(autofs_control_fd, AUTOFS_UPDATE_OPTIONS,
			    &au) < 0) {
				pr_msg("update %s: %m", dir->dir_realpath);
				continue;
			}
			if (verbose)
				pr_msg("%s updated", dir->dir_realpath);
		} else {
			struct autofs_args ai;
			int st_flags = 0;

			/*
			 * This trigger isn't already mounted; either
			 * the path doesn't exist at all, or it
			 * exists but nothing is mounted on it.
			 *
			 * Create a mount point if necessary
			 * If the path refers to an existing symbolic
			 * link, refuse to mount on it.  This avoids
			 * future problems.  (We don't use dir->dir_realpath
			 * because that's never a symbolic link.)
			 */
			if (lstat(dir->dir_name, &stbuf) == 0) {
				if ((stbuf.st_mode & S_IFMT) != S_IFDIR) {
					pr_msg("%s: Not a directory", dir->dir_name);
					continue;
				}
				st_flags = stbuf.st_flags;

				/*
				 * Either realpath() succeeded or it
				 * failed with ENOENT; otherwise, we
				 * would have quit before getting here.
				 *
				 * If it failed, report an error, as
				 * the problem isn't that "dir->dir_name"
				 * doesn't exist, the problem is that,
				 * somehow, we got ENOENT even though
				 * it exists.
				 */
				if (dir->dir_realpath == NULL) {
					errno = ENOENT;
					pr_msg("%s: Can't convert to real path: %m",
					    dir->dir_name);
					continue;
				}
			} else {
				/*
				 * Mountpoint doesn't exist.
				 *
				 * Create it unless it's under /Volumes.
				 * At boot time it's possible the volume
				 * containing the mountpoint hasn't mounted yet.
				 */
				if (strncmp(dir->dir_name, "/Volumes/", 9) == 0) {
					pr_msg("%s: mountpoint unavailable", dir->dir_name);
					continue;
				}

				if (mkdir_r(dir->dir_name)) {
					pr_msg("%s: %m", dir->dir_name);
					continue;
				}

				/*
				 * realpath() presumably didn't succeed,
				 * as dir->dir_name couldn't be statted.
				 * Call it again, to get the real path
				 * corresponding to the newly-created
				 * mount point.
				 */
				if (realpath(dir->dir_name, real_mntpnt) == NULL) {
					/*
					 * Failed.
					 */
					pr_msg("%s: Can't convert to real path: %m",
					    dir->dir_name);
					continue;
				}
				dir->dir_realpath = strdup(real_mntpnt);
				if (dir->dir_realpath == NULL) {
					pr_msg("Couldn't allocate real path for %s: %m",
					    dir->dir_name);
					continue;
				}
			}

			/*
			 * If the "hidefromfinder" option is set for
			 * this autofs mountpoint then also set the
			 * UF_HIDDEN bit on the directory so it'll still
			 * be invisible to the Finder even if not mounted on.
			 */
			if (altflags & AUTOFS_MNT_HIDEFROMFINDER)
				st_flags |= UF_HIDDEN;
			else
				st_flags &= ~UF_HIDDEN;
			if (chflags(dir->dir_name, st_flags) < 0)
				pr_msg("%s: can't set hidden", dir->dir_name);

			/*
			 * Mount it.  Use the real path (symlink-free),
			 * for reasons mentioned above.
			 */
			ai.version	= AUTOFS_ARGSVERSION;
			ai.path 	= dir->dir_realpath;
			ai.opts		= dir->dir_opts;
			ai.map		= dir->dir_map;
			ai.subdir	= "";
			ai.direct 	= dir->dir_direct;
			if (dir->dir_direct)
				ai.key = dir->dir_name;
			else
				ai.key = "";
			ai.mntflags	= altflags;
			ai.mount_type	= MOUNT_TYPE_MAP;	/* top-level autofs mount */
			ai.node_type	= dir->dir_direct ? NT_TRIGGER : 0;

			if (mount(MNTTYPE_AUTOFS, dir->dir_realpath,
			    MNT_DONTBROWSE | MNT_AUTOMOUNTED | flags,
			    &ai) < 0) {
				pr_msg("mount %s: %m", dir->dir_realpath);
				continue;
			}
			if (verbose)
				pr_msg("%s mounted", dir->dir_realpath);
		}

		count++;
	}

	if (verbose && count == 0)
		pr_msg("no mounts");

	/*
	 * Now compare the /etc/mnttab with the master
	 * map.  Any autofs mounts in the /etc/mnttab
	 * that are not in the master map must be
	 * unmounted
	 *
	 * XXX - if there are no autofs mounts left, should we
	 * unload autofs, or arrange that it be unloaded?
	 */
	do_unmounts();

	/*
	 * Let PremountHomeDirectoryWithAuthentication() know that we're
	 * done.
	 */
	fd = open("/var/run/automount.initialized", O_CREAT|O_WRONLY, 0600);
	close(fd);

	return (0);
}
Example #13
0
int wav_mix(char *in1, char *in2, char *out, int samplerate, int swap, int stereo) {
	FILE *f_in1 = NULL;
	FILE *f_in2 = NULL;
	FILE *f_out = NULL;

	char *bitstream_buf1 = NULL;
	char *bitstream_buf2 = NULL;
	char *p1;
	char *f1;
	char *p2;
	char *f2;
	short int zero = 0;
	long file_size1;
	long file_size2 = 0;

	/* combine two wavs */
	f_in1 = fopen(in1, "r");
	if(!f_in1) {
		syslog(LOG_ERR,"File [%s] cannot be opened for read.\n", in1);
		return 1;
	}
	if(in2 != NULL) {
		f_in2 = fopen(in2, "r");
		if(!f_in2) {
			fclose(f_in1);
			syslog(LOG_ERR,"File [%s] cannot be opened for read.\n", in2);
			return 1;
		}
	}
	for(int passOpen = 0; passOpen < 2; passOpen++) {
		if(passOpen == 1) {
			char *pointToLastDirSeparator = strrchr(out, '/');
			if(pointToLastDirSeparator) {
				*pointToLastDirSeparator = 0;
				mkdir_r(out, 0777);
				*pointToLastDirSeparator = '/';
			} else {
				break;
			}
		}
		f_out = fopen(out, "w");
		if(f_out) {
			break;
		}
	}
	if(!f_out) {
		if(f_in1 != NULL)
			fclose(f_in1);
		if(f_in2 != NULL)
			fclose(f_in2);
		syslog(LOG_ERR,"File [%s] cannot be opened for write.\n", out);
		return 1;
	}
	char f_out_buffer[32768];
	setvbuf(f_out, f_out_buffer, _IOFBF, 32768);

	wav_write_header(f_out, samplerate, stereo);

	fseek(f_in1, 0, SEEK_END);
	file_size1 = ftell(f_in1);
	fseek(f_in1, 0, SEEK_SET);

	if(in2 != NULL) {
		fseek(f_in2, 0, SEEK_END);
		file_size2 = ftell(f_in2);
		fseek(f_in2, 0, SEEK_SET);
	}

	bitstream_buf1 = new FILE_LINE char[file_size1];
	if(!bitstream_buf1) {
		if(f_in1 != NULL)
			fclose(f_in1);
		if(f_in2 != NULL)
			fclose(f_in2);
		if(f_out != NULL)
			fclose(f_out);
		syslog(LOG_ERR,"Cannot malloc bitsream_buf1[%ld]", file_size1);
		return 1;
	}

	if(in2 != NULL) {
		bitstream_buf2 = new FILE_LINE char[file_size2];
		if(!bitstream_buf2) {
			fclose(f_in1);
			fclose(f_in2);
			fclose(f_out);
			delete [] bitstream_buf1;
			syslog(LOG_ERR,"Cannot malloc bitsream_buf2[%ld]", file_size1);
			return 1;
		}
	}
	fread(bitstream_buf1, file_size1, 1, f_in1);
	p1 = bitstream_buf1;
	f1 = bitstream_buf1 + file_size1;

	if(in2 != NULL) {
		fread(bitstream_buf2, file_size2, 1, f_in2);
		p2 = bitstream_buf2;
		f2 = bitstream_buf2 + file_size2;
	} else {
		p2 = f2 = 0;
	}

	while(p1 < f1 || p2 < f2 ) {
		if(p1 < f1 && p2 < f2) {
			if(stereo) {
			/* stereo */
				if(swap) {
					fwrite(p2, 2, 1, f_out);
					fwrite(p1, 2, 1, f_out);
				} else {
					fwrite(p1, 2, 1, f_out);
					fwrite(p2, 2, 1, f_out);
				}
			} else {
			/* mono */
				slinear_saturated_add((short int*)p1, (short int*)p2);
				fwrite(p1, 2, 1, f_out);
			}
			p1 += 2;
			p2 += 2;
		} else if ( p1 < f1 ) {
			if(swap) {
				if(stereo) {
					fwrite(&zero, 2, 1, f_out);
				}
				fwrite(p1, 2, 1, f_out);
			} else {
				fwrite(p1, 2, 1, f_out);
				if(stereo) {
					fwrite(&zero, 2, 1, f_out);
				}
			}
			p1 += 2;
		} else if ( p2 < f2 ) {
			if(swap) {
				fwrite(p2, 2, 1, f_out);
				if(stereo) {
					fwrite(&zero, 2, 1, f_out);
				}
			} else {
				if(stereo) {
					fwrite(&zero, 2, 1, f_out);
				}
				fwrite(p2, 2, 1, f_out);
			}
			p2 += 2;
		}
	}

	wav_update_header(f_out);
	if(bitstream_buf1)
		delete [] bitstream_buf1;
	if(bitstream_buf2)
		delete [] bitstream_buf2;
	fclose(f_out);
	fclose(f_in1);
	if(f_in2) fclose(f_in2);

	return 0;
}
Example #14
0
// main for normal game usage
int main(int argc, char *argv[])
{
#if defined(__MINGW32__)
    // load mingw crash handler. Won't fail if dll is not present.
    // may load libray from current dir, it may not same as program dir
    LoadLibrary("exchndl.dll");
#endif

    selfName = argv[0];

    parseOptions(argc, argv);

    if (settings.options.printHelp)
    {
        printHelp();
        _exit(0);
    }
    else if (settings.options.printVersion)
    {
        printVersion();
        _exit(0);
    }

#ifdef ANDROID
    mkdir_r(getSdStoragePath().c_str());
#endif

    PhysFs::init(argv[0]);
    XML::initXML();
#if SDL_IMAGE_VERSION_ATLEAST(1, 2, 11)
    IMG_Init(IMG_INIT_PNG);
#endif
#if SDL_MIXER_VERSION_ATLEAST(1, 2, 11)
    Mix_Init(MIX_INIT_OGG);
#endif

#ifdef WIN32
    SetCurrentDirectory(PhysFs::getBaseDir());
#endif
    setPriority(true);
    client = new Client;
    int ret = 0;
    if (!settings.options.testMode)
    {
        client->gameInit();
        ret = client->gameExec();
    }
    else
    {
        client->testsInit();
        ret = client->testsExec();
    }
    delete2(client);

#if SDL_MIXER_VERSION_ATLEAST(1, 2, 11)
    Mix_Quit();
#endif
#if SDL_IMAGE_VERSION_ATLEAST(1, 2, 11)
    IMG_Quit();
#endif

#ifdef DUMP_LEAKED_RESOURCES
    reportRWops();
#endif
#ifdef DEBUG_PHYSFS
    reportPhysfsLeaks();
#endif
    return ret;
}
Example #15
0
/**
 * Initializes the home directory. On UNIX and FreeBSD, ~/.mana is used. On
 * Windows and other systems we use the current working directory.
 */
void Client::initHomeDir()
{
    mLocalDataDir = mOptions.localDataDir;

    if (mLocalDataDir.empty())
    {
#ifdef __APPLE__
        // Use Application Directory instead of .mana
        mLocalDataDir = std::string(PHYSFS_getUserDir()) +
            "/Library/Application Support/" +
            branding.getValue("appName", "Mana");
#elif defined __HAIKU__
        mLocalDataDir = std::string(PHYSFS_getUserDir()) +
           "/config/data/Mana";
#elif defined _WIN32
        mLocalDataDir = getSpecialFolderLocation(CSIDL_LOCAL_APPDATA);
        if (mLocalDataDir.empty())
            mLocalDataDir = std::string(PHYSFS_getUserDir());
        mLocalDataDir += "/Mana";
#else
        mLocalDataDir = std::string(PHYSFS_getUserDir()) +
            "/.local/share/mana";
#endif
    }

    if (mkdir_r(mLocalDataDir.c_str()))
    {
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
                                  "Exiting."), mLocalDataDir.c_str()));
    }

    mConfigDir = mOptions.configDir;

    if (mConfigDir.empty())
    {
        const std::string app = branding.getValue("appShort", "manasource");
#ifdef __APPLE__
        mConfigDir = mLocalDataDir + "/" + app;
#elif defined __HAIKU__
        mConfigDir = std::string(PHYSFS_getUserDir()) +
           "/config/settings/Mana" +
           branding.getValue("appName", "manasource");
#elif defined _WIN32
        mConfigDir = getSpecialFolderLocation(CSIDL_APPDATA);
        if (mConfigDir.empty())
            mConfigDir = mLocalDataDir;
        else
            mConfigDir += "/mana/" + app;
#else
        mConfigDir = std::string(PHYSFS_getUserDir()) + "/.config/mana/" + app;
#endif
    }

    if (mkdir_r(mConfigDir.c_str()))
    {
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
                                  "Exiting."), mConfigDir.c_str()));
    }

    struct stat statbuf;
    std::string newConfigFile = mConfigDir + "/config.xml";
    if (stat(newConfigFile.c_str(), &statbuf))
    {
        std::string oldConfigFile = std::string(PHYSFS_getUserDir()) +
            "/.tmw/config.xml";
        if (mRootDir.empty() && !stat(oldConfigFile.c_str(), &statbuf)
            && S_ISREG(statbuf.st_mode))
        {
            std::ifstream oldConfig;
            std::ofstream newConfig;
            logger->log("Copying old TMW settings.");

            oldConfig.open(oldConfigFile.c_str(), std::ios::binary);
            newConfig.open(newConfigFile.c_str(), std::ios::binary);

            if (!oldConfig.is_open() || !newConfig.is_open())
                logger->log("Unable to copy old settings.");
            else
            {
                newConfig << oldConfig.rdbuf();
                newConfig.close();
                oldConfig.close();
            }
        }
    }
}
Example #16
0
/* execute download ----------------------------------------------------------*/
static int exec_down(const path_t *path, char *remot_p, const char *usr,
                     const char *pwd, const char *proxy, int opts, int *n,
                     FILE *fp)
{
    char dir[1024],errfile[1024],tmpfile[1024],cmd[4096],env[1024]="";
    char opt[1024]="",*opt2="",*p;
    int ret,proto;
    
#ifndef WIN32
    opt2=" 2> /dev/null";
#endif
    strcpy(dir,path->local);
    if ((p=strrchr(dir,FILEPATHSEP))) *p='\0';
    
    if      (!strncmp(path->remot,"ftp://" ,6)) proto=0;
    else if (!strncmp(path->remot,"http://",7)) proto=1;
    else {
        trace(2,"exec_down: invalid path %s\n",path->remot);
        showmsg("STAT=X");
        if (fp) fprintf(fp,"%s ERROR (INVALID PATH)\n",path->remot);
        n[1]++;
        return 0;
    }
    /* test local file existence */
    if (!(opts&DLOPT_FORCE)&&test_file(path->local)) {
        showmsg("STAT=.");
        if (fp) fprintf(fp,"%s in %s\n",path->remot,dir);
        n[2]++;
        return 0;
    }
    showmsg("STAT=_");
    
    /* get remote file list */
    if ((p=strrchr(path->remot,'/'))&&
        strncmp(path->remot,remot_p,p-path->remot)) {
        
        if (get_list(path,usr,pwd,proxy)) {
            strcpy(remot_p,path->remot);
        }
    }
    /* test file in listing */
    if (proto==0&&!test_list(path)) {
        showmsg("STAT=x");
        if (fp) fprintf(fp,"%s NO_FILE\n",path->remot);
        n[1]++;
        return 0;
    }
    /* generate local directory recursively */
    if (!mkdir_r(dir)) {
        showmsg("STAT=X");
        if (fp) fprintf(fp,"%s -> %s ERROR (LOCAL DIR)\n",path->remot,dir);
        n[3]++;
        return 0;
    }
    /* proxy option */
    if (*proxy) {
        sprintf(env,"set %s_proxy=http://%s & ",proto==0?"ftp":"http",proxy);
        sprintf(opt," --proxy=on ");
    }
    /* download command */
    sprintf(errfile,"%s.err",path->local);
    if (proto==0) {
        sprintf(cmd,"%s%s %s --ftp-user=%s --ftp-password=%s --glob=off "
                "--passive-ftp %s-t %d -T %d -O \"%s\" -o \"%s\"%s\n",
                env,FTP_CMD,path->remot,usr,pwd,opt,FTP_RETRY,FTP_TIMEOUT,
                path->local,errfile,opt2);
    }
    else {
        if (*pwd) {
            sprintf(opt+strlen(opt)," --http-user=%s --http-password=%s ",usr,
                    pwd);
        }
        sprintf(cmd,"%s%s %s %s-t %d -T %d -O \"%s\" -o \"%s\"%s\n",env,FTP_CMD,
                path->remot,opt,FTP_RETRY,FTP_TIMEOUT,path->local,errfile,opt2);
    }
    if (fp) fprintf(fp,"%s -> %s",path->remot,dir);
    
    /* execute download command */
    if ((ret=execcmd_to(cmd))) {
        if ((proto==0&&ret==FTP_NOFILE)||
            (proto==1&&ret==HTTP_NOFILE)) {
            showmsg("STAT=x");
            if (fp) fprintf(fp," NO_FILE\n");
            n[1]++;
        }
        else {
            trace(2,"exec_down: %s error %d\n",proto==0?"ftp":"http",ret);
            showmsg("STAT=X");
            if (fp) fprintf(fp," ERROR (%d)\n",ret);
            n[3]++;
        }
        remove(path->local);
        if (!(opts&DLOPT_HOLDERR)) {
            remove(errfile);
        }
        return ret==2;
    }
    remove(errfile);
    
    /* uncompress download file */
    if (!(opts&DLOPT_KEEPCMP)&&(p=strrchr(path->local,'.'))&&
        (!strcmp(p,".z")||!strcmp(p,".gz")||!strcmp(p,".zip")||
         !strcmp(p,".Z")||!strcmp(p,".GZ")||!strcmp(p,".ZIP"))) {
        
        if (uncompress(path->local,tmpfile)) {
            remove(path->local);
        }
        else {
            trace(2,"exec_down: uncompress error\n");
            showmsg("STAT=C");
            if (fp) fprintf(fp," ERROR (UNCOMP)\n");
            n[3]++;
            return 0;
        }
    }
    showmsg("STAT=o");
    if (fp) fprintf(fp," OK\n");
    n[0]++;
    return 0;
}
Example #17
0
int main(int argc, char** argv)
{
    if (argc < 2)
        exit(1);
    mkdir_r(argv[1]);
}
Example #18
0
int main(int argc, char* argv[]) {
	int opt;
	char* outdir = NULL;
	bool orphaned_check = false, recreate = false, quiet = false;
	while((opt = getopt(argc,argv,"roqd:hD")) != -1)
		switch(opt) {
			case 'o': orphaned_check = true; break;
			case 'r': recreate = true; break;
			case 'd': outdir = optarg; break;
			case 'q': quiet = true; break;
			case 'D': puts(doc); return 0;
			case 'h': usage(argv[0],1);
			default : usage(argv[0],0);
		}
	if(argc - optind != 1)
		usage(argv[0],0);
	if(recreate && !outdir)
		outdir = ".";

	const char* browsefile = argv[optind];
	FILE* f = fopen(browsefile,"rb");
	if(!f)
		bail("%s could not be read.\n",browsefile);


	char buf[15];
	CHECKREAD(buf,1,15,f);
	if(memcmp(buf,magic,15))
		bail("%s: Not a valid JBF.\n",browsefile);

	uint16_t version[2];
	READBE(version,2,2,f);

	uint32_t nb_images;
	READLE(&nb_images,4,1,f);

	char path[256];
	CHECKREAD(path,1,256,f);
	path[255] = '\0';

	char volume[32];
	CHECKREAD(volume,1,32,f);
	volume[31] = '\0';

	fseek(f,713,SEEK_CUR); // End header


	if(!quiet) {
		printf("JBF version %d.%d (PSP %s)\n",version[0],version[1],ver_lookup(version[0],version[1]));
		if(volume[0]) printf("[%s] ",volume);
		printf("%s\n%d images\n",path,nb_images);
		puts("   type   resolution   bpp        size  modified              name");
	}

	size_t outdir_len;
	if(outdir)
		outdir_len = strlen(outdir);
	if(recreate) {
		outdir_len += strlen(path);
		outdir = strcpy(malloc(outdir_len+1),outdir);
		char* pp = path,* op = outdir + strlen(outdir);
		*op++ = '/';
		do switch(*pp) {
			case '\\': *op++ = '/';  break;
			case '/' : *op++ = '\\'; break;
			case ':' :               break;
			default  : *op++ = *pp;
		} while(*pp++);
	}
	char* browsedir;
	size_t browsedir_len;
	if(orphaned_check) {
		char* browsecpy = strdup(browsefile);
		browsedir = strdup(dirname(browsecpy));
		browsedir_len = strlen(browsedir);
		free(browsecpy);
	}


	for(uint32_t i = 0; i < nb_images; i++) {
		uint32_t name_len;
		if(version[0] == 1 && version[1] == 0)
			name_len = 13;
		else
			READLE(&name_len,4,1,f);
		if(name_len > 255) //Windows maximum, image names from valid JBFs shouldn't exceed this
			bail("%s+%lx: Filename too long for image #%"PRIu32" (%"PRIu32")\n",browsefile,ftell(f)-4,i,name_len);
		char name[256];
		READLE(name,1,name_len,f);
		name[name_len] = '\0';
		if(version[0] == 1 && version[1] == 0)
			name_len--;

		uint32_t type, width, height, depth, pels, filesize;
		time_t epochtime;
		char type_v1[4] = {'\0'};
		if(version[0] > 1) {
			uint64_t filetime;
			READLE(&filetime,8,1,f);
			epochtime = MSFILETIME_TO_EPOCHTIME(filetime);

			READLE(&type,4,1,f);
		}
		else if(version[1] < 3) { //1.3 has no type code
			READBE(type_v1,3,1,f);
			CHECKREAD(type_v1+3,1,1,f); // \0
		}
		READLE(&width,4,1,f);
		READLE(&height,4,1,f);
		READLE(&depth,4,1,f);
		if(version[0] == 2)
			READLE(&pels,4,1,f); // Still not sure what this field is for, roughly equals w*h*channels
		READLE(&filesize,4,1,f);

		if(version[0] == 1) {
			uint32_t filetime;
			READLE(&filetime,4,1,f);
			epochtime = filetime;
		}

		// Truncated file entries contain a single null word in place of the '0x00000002 0x00000001 0xFFFFFFFF' pattern
		uint32_t has_thumb = true;
		if(version[0] == 2)
			READLE(&has_thumb,4,1,f);


		bool orphaned = false;
		if(orphaned_check) {
			char test[browsedir_len+name_len+2];
			sprintf(test,"%s/%s",browsedir,name);
			orphaned = access(test,F_OK);
		}
		bool extract = outdir && (!orphaned_check || orphaned);
		if(!quiet)
			printf("%c%6s  %6"PRIu32"x%-6"PRIu32"  %2"PRIu32"  %10"PRIu32"  %.20s %s %s %s\n",
			       (has_thumb?' ':'-'),version[0]<2?type_v1:type_lookup(type),width,height,depth,filesize,ctime(&epochtime)+4,(orphaned?"\033[1;31m":""),name,(orphaned?"\033[0m":""));


		if(!has_thumb)
			continue;

		if(extract && recreate) {
			if(!mkdir_r(outdir))
				bail("%s: Couldn't recreate path: %s\n%s\n",browsefile,outdir,strerror(errno));

#if !defined(_WIN32) || (WINVER >= 0x0600) // place a symlink back to the source jbf
			char* browsecpy = strdup(browsefile);
			char* browsebase = basename(browsecpy);
			free(browsecpy);
			char linkback[outdir_len+strlen(browsebase)+1];
			strcat(strcpy(linkback,outdir),browsebase);
			char* browseabs = realpath(browsefile,NULL);
			symlink(browseabs,linkback);
			free(browseabs);
#endif
			recreate = false;
		}

		if(version[0] == 2) {
			uint32_t sig[3] = {has_thumb};
			READLE(sig+1,4,2,f);
			if(memcmp(sig,v2_thumb_signature,sizeof(v2_thumb_signature)))
				bail("%s+%lx: Wrong signature (%08"PRIX32" %08"PRIX32" %08"PRIX32"); parse integrity lost.\n",browsefile,ftell(f)-3,sig[0],sig[1],sig[2]);

			uint32_t imglen;
			READLE(&imglen,4,1,f);

			if(extract) {
				char writepath[outdir_len+name_len+6];
				sprintf(writepath,"%s/%s.jpg",outdir,name);
				FILE* thumb = fopen(writepath,"wb");
				if(thumb) {
					char* buf = malloc(imglen);
					if(!buf)
						bail("%s+%lx: Allocation failed for image #%"PRIu32", length %"PRIu32"\n",browsefile,ftell(f)-4,i,imglen);
					imglen = fread(buf,1,imglen,f); // If the file is truncated for any reason we will write a partial JPEG and fail the next time around
					if(fwrite(buf,1,imglen,thumb) != imglen)
						fprintf(stderr,"Error writing to %s\n",writepath);
					fclose(thumb);
					free(buf);
					utime(writepath,&(struct utimbuf){epochtime,epochtime});
					continue;
				}
				fprintf(stderr,"Unable to open %s\n",writepath);
			}
			fseek(f,imglen,SEEK_CUR);
		}
Example #19
0
bool Game::saveScreenshot(SDL_Surface *const screenshot)
{
    std::string screenshotDirectory = settings.screenshotDir;
    if (mkdir_r(screenshotDirectory.c_str()) != 0)
    {
        logger->log("Directory %s doesn't exist and can't be created! "
                    "Setting screenshot directory to home.",
                    screenshotDirectory.c_str());
        screenshotDirectory = std::string(PhysFs::getUserDir());
    }

    // Search for an unused screenshot name
    std::stringstream filename;
    std::fstream testExists;
    bool found = false;
    static unsigned int screenshotCount = 0;

    time_t rawtime;
    char buffer [100];
    time(&rawtime);
    struct tm *const timeinfo = localtime(&rawtime);
    strftime(buffer, 99, "%Y-%m-%d_%H-%M-%S", timeinfo);

    const std::string serverName = settings.serverName;
    std::string screenShortStr;
    if (serverName.empty())
    {
        screenShortStr = strprintf("%s_Screenshot_%s_",
            branding.getValue("appName", "Elmlor").c_str(),
            buffer);
    }
    else
    {
        screenShortStr = strprintf("%s_Screenshot_%s_%s_",
            branding.getValue("appName", "Elmlor").c_str(),
            serverName.c_str(), buffer);
    }

    do
    {
        screenshotCount++;
        filename.str("");
        filename << screenshotDirectory << "/";
        filename << screenShortStr << screenshotCount << ".png";
        testExists.open(filename.str().c_str(), std::ios::in);
        found = !testExists.is_open();
        testExists.close();
    }
    while (!found);

    const std::string fileNameStr = filename.str();
    const bool success = ImageWriter::writePNG(screenshot, fileNameStr);
    if (success)
    {
        if (localChatTab)
        {
            // TRANSLATORS: save file message
            std::string str = strprintf(_("Screenshot saved as %s"),
                fileNameStr.c_str());
            localChatTab->chatLog(str, ChatMsgType::BY_SERVER);
        }
    }
    else
    {
        if (localChatTab)
        {
            // TRANSLATORS: save file message
            localChatTab->chatLog(_("Saving screenshot failed!"),
                                  ChatMsgType::BY_SERVER);
        }
        logger->log1("Error: could not save screenshot.");
    }

    MSDL_FreeSurface(screenshot);
    return success;
}
Example #20
0
int main(int argc, char **argv) {
    char * tmpdir = getenv("_FAKEUSER_DIR_");
    char *passwd_file, *group_file;

    name = argv[0];
    int opt, ret = 0;
    int action = 0, uid = 0, gid = 0;
    char *name = NULL, *passwd = NULL, *members = NULL, *shell = NULL, *gecos = NULL, *dir = NULL;
    extern char *optarg;

    while ((opt = getopt(argc, argv, "UGu:g:n:p:m:s:c:d:h")) != -1) {
        switch (opt) {
        case 'U':
            action = 'U';
            break;
        case 'G':
            action = 'G';
            break;
        case 'u':
            uid = atoi(optarg);
            break;
        case 'g':
            gid = atoi(optarg);
            break;
        case 'n':
            name = optarg;
            break;
        case 'p':
            passwd = optarg;
            break;
        case 'm':
            members = optarg;
            break;
        case 's':
            shell = optarg;
            break;
        case 'c':
            gecos = optarg;
            break;
        case 'd':
            dir = optarg;
            break;
        case 'h':
            help();
            exit(EXIT_SUCCESS);
        default: /* '?' */
            usage_fd(stderr);
            exit(EXIT_FAILURE);
        }
    }
    if (action == 0 || name == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }
    // only continue when environment variable with directory found.
    if (!tmpdir) {
        fputs("Error! Not in fakeuser environment\n", stderr);
        exit(EXIT_FAILURE);
    }
    // init file paths
    passwd_file = (char*)malloc(strlen(tmpdir)+10);
    strcpy(passwd_file, tmpdir);
    strcat(passwd_file, "/passwd");

    group_file = (char*)malloc(strlen(tmpdir)+10);
    strcpy(group_file, tmpdir);
    strcat(group_file, "/group");

    // Create directory structure
    mkdir_r(tmpdir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

    if (action == 'U') {
        // create and append passwd entry
        struct passwd pw;
        pw.pw_name = name;
        pw.pw_passwd = passwd ? passwd : "";
        pw.pw_gecos = gecos ? gecos : "";
        pw.pw_dir = dir ? dir : "";
        pw.pw_shell = shell ? shell : "";
        pw.pw_uid = uid;
        pw.pw_gid = gid;
        // append to file with error handling.
        FILE * pwf = fopen(passwd_file, "a");
        if (pwf) {
            if(putpwent(&pw, pwf))
                ret = EIO;
            if (fclose(pwf))
                ret = EIO;
        } else
            ret = EIO;
    } else if (action == 'G') {
        // create and append group entry
        struct group gr;
        gr.gr_name = name;
        gr.gr_passwd = passwd ? passwd : "";
        gr.gr_gid = gid;
        char *strings;
        gr.gr_mem = members ? string_to_array(members, " ,;", &strings) : (char *[]) {
            NULL
        };
        // append to file with error handling.
        FILE * pwf = fopen(group_file, "a");
        if (pwf) {
            if(putgrent(&gr, pwf))
                ret = EIO;
            if (fclose(pwf))
                ret = EIO;
        } else
            ret = EIO;
    }
    // return 0 on success or the error value
    return ret;
}