예제 #1
0
파일: persist.c 프로젝트: gvx/deja
char *make_persist_path(V fname)
{
    NewString *s = toNewString(fname);
    char *pathbase = getenv("XDG_DATA_HOME");
    size_t plen;
    char *home = NULL;
    if (pathbase == NULL)
    {
        home = getenv("HOME");
        plen = strlen(home) + strlen("/.local/share");
        pathbase = malloc(plen + 1);
        sprintf(pathbase, "%s/.local/share", home);
    }
    else
    {
        plen = strlen(pathbase);
    }
    char *data = malloc(plen + strlen("/deja/persist/") + s->size + 3 + 1);
    sprintf(data, "%s/deja/persist/%*s.vu", pathbase, (int)s->size, s->text);
    if (home)
    {   // if home is not NULL, that means we allocated pathbase
        free(pathbase);
    }
    makedirs(data);
    return data;
}
예제 #2
0
파일: util.c 프로젝트: infoburp/patch
/* Create FILE with OPEN_FLAGS, and with MODE adjusted so that
   we can read and write the file and that the file is not executable.
   Return the file descriptor.  */
int
create_file (char const *file, int open_flags, mode_t mode,
	     bool to_dir_known_to_exist)
{
  int try_makedirs_errno = to_dir_known_to_exist ? 0 : ENOENT;
  int fd;
  mode |= S_IRUSR | S_IWUSR;
  mode &= ~ (S_IXUSR | S_IXGRP | S_IXOTH);
  do
    {
      if (! (O_CREAT && O_TRUNC))
	close (creat (file, mode));
      fd = open (file, O_CREAT | O_TRUNC | open_flags, mode);
      if (fd < 0)
	{
	  char *f;
	  if (errno != try_makedirs_errno)
	    pfatal ("Can't create file %s", quotearg (file));
	  f = xstrdup (file);
	  makedirs (f);
	  free (f);
	  try_makedirs_errno = 0;
	}
    } while (fd < 0);
  return fd;
}
예제 #3
0
CacheSession::CacheSession(ClientSession *session, const char *url, uint32_t file_ttl,
						   uint32_t dir_ttl)
	: FilterSession(session)
{
	m_dir_ttl = file_ttl;
	m_dir_ttl = dir_ttl;
	string tmp(url);
	make_hash64("md5", tmp, m_url_hash, true);
	tmp = url + string(":meta:") + get_client_id();
	make_hash64("md5", tmp, m_meta_key, true);
	tmp = url + string(":data:") + get_client_id();
	make_hash64("md5", tmp, m_data_key, true);
	m_base_dir = cacheBaseDir() + SEPSTR + m_url_hash;
	if (!dir_exists(m_base_dir.c_str()) && makedirs(m_base_dir.c_str()) < 0)
	{
		m_enable = false;
		_DEBUG("Disabling Cache Session: can't create");
	}
#if 0
	else if (!can_write_dir(m_base_dir.c_str()))
	{
		m_enable = false;
		_DEBUG("Disabling Cache Session: can't write");
	}
#endif
	else
	{
		m_enable = true;
		_DEBUG("Enabling Cache Session");
	}
}
예제 #4
0
void main(int argc, char** argv) {
    args::Parser parser(argv[0], "Plays a replay into a set of images and a log of sounds");

    String replay_path(utf8::decode(argv[0]));
    parser.add_argument("replay", store(replay_path))
    .help("an Antares replay script")
    .required();

    Optional<String> output_dir;
    parser.add_argument("-o", "--output", store(output_dir))
    .help("place output in this directory");

    int interval = 60;
    int width = 640;
    int height = 480;
    parser.add_argument("-i", "--interval", store(interval))
    .help("take one screenshot per this many ticks (default: 60)");
    parser.add_argument("-w", "--width", store(width))
    .help("screen width (default: 640)");
    parser.add_argument("-h", "--height", store(height))
    .help("screen height (default: 480)");

    parser.add_argument("--help", help(parser, 0))
    .help("display this help screen");

    String error;
    if (!parser.parse_args(argc - 1, argv + 1, error)) {
        print(io::err, format("{0}: {1}\n", parser.name(), error));
        exit(1);
    }

    if (output_dir.has()) {
        makedirs(*output_dir, 0755);
    }

    Preferences::set_preferences(new Preferences);
    Preferences::preferences()->set_screen_size(Size(width, height));
    Preferences::preferences()->set_play_music_in_game(true);
    PrefsDriver::set_driver(new NullPrefsDriver);

    scoped_ptr<OffscreenVideoDriver> video(new OffscreenVideoDriver(
            Preferences::preferences()->screen_size(), output_dir));
    video->schedule_event(make_linked_ptr(new MouseMoveEvent(0, Point(320, 240))));
    // TODO(sfiera): add recurring snapshots to OffscreenVideoDriver.
    for (int64_t i = 1; i < 72000; i += interval) {
        video->schedule_snapshot(i);
    }
    VideoDriver::set_driver(video.release());

    if (output_dir.has()) {
        String out(format("{0}/sound.log", *output_dir));
        SoundDriver::set_driver(new LogSoundDriver(out));
    } else {
        SoundDriver::set_driver(new NullSoundDriver);
    }
    Ledger::set_ledger(new NullLedger);

    MappedFile replay_file(replay_path);
    VideoDriver::driver()->loop(new ReplayMaster(replay_file.data()));
}
예제 #5
0
파일: blobcache.c 프로젝트: Hr-/showtime
void
blobcache_put(const char *key, const char *stash,
	      const void *data, size_t size, int maxage)
{
  char path[PATH_MAX];
  int fd;
  uint8_t d[20];

  digest_key(key, stash, d);
  snprintf(path, sizeof(path), "%s/blobcache/%02x", showtime_cache_path, d[0]);

  if(makedirs(path))
    return;

  digest_to_path(d, path, sizeof(path));

  if((fd = open(path, O_CREAT | O_WRONLY, 0666)) == -1)
    return;

  // max 30 days of cache
  if(maxage > 86400 * 30) 
    maxage = 86400 * 30;

  if(blobcache_save(fd, data, size, time(NULL) + maxage, d[0]))
    unlink(path);

  close(fd);
}
예제 #6
0
/*
 * Create timeshift directories (for a given instance)
 */
int timeshift_filemgr_makedirs ( int index, char *buf, size_t len )
{
  if (timeshift_filemgr_get_root(buf, len))
    return 1;
  snprintf(buf+strlen(buf), len-strlen(buf), "/%d", index);
  return makedirs(buf, 0700, -1, -1);
}
예제 #7
0
파일: TraderApi.cpp 프로젝트: LegendZX/CTP
void CTraderApi::Connect(const string& szPath,
		const string& szAddresses,
		const string& szBrokerId,
		const string& szInvestorId,
		const string& szPassword,
		THOST_TE_RESUME_TYPE nResumeType,
		const string& szUserProductInfo,
		const string& szAuthCode)
{
	m_szBrokerId = szBrokerId;
	m_szInvestorId = szInvestorId;
	m_szPassword = szPassword;
	m_szUserProductInfo = szUserProductInfo;
	m_szAuthCode = szAuthCode;

	char *pszPath = new char[szPath.length()+20];
	sprintf(pszPath,"%s\\Td\\",szPath.c_str());
	makedirs(pszPath);

	m_pApi = CThostFtdcTraderApi::CreateFtdcTraderApi(pszPath);
	delete[] pszPath;

	m_status = E_inited;
	if(m_msgQueue)
		m_msgQueue->Input_OnConnect(this,NULL,m_status);
	
	if (m_pApi)
	{
		m_pApi->RegisterSpi(this);
		
		//添加地址
		size_t len = szAddresses.length()+1;
		char* buf = new char[len];
		strncpy(buf,szAddresses.c_str(),len);

		char* token = strtok(buf, _QUANTBOXC2CTP_SEPS_);
		while(token)
		{
			if (strlen(token)>0)
			{
				m_pApi->RegisterFront(token);
			}
			token = strtok( NULL, _QUANTBOXC2CTP_SEPS_);
		}
		delete[] buf;

		m_pApi->SubscribePublicTopic(nResumeType);
		m_pApi->SubscribePrivateTopic(nResumeType);
		
		//初始化连接
		m_pApi->Init();
		m_status = E_connecting;
		if(m_msgQueue)
			m_msgQueue->Input_OnConnect(this,NULL,m_status);
	}
}
예제 #8
0
 void snapshot_to(Rect bounds, PrintItem relpath) {
     if (!takes_snapshots()) {
         return;
     }
     bounds.offset(0, _driver._screen_size.height - bounds.height() - bounds.top);
     ArrayPixMap pix(bounds.size());
     _buffer.copy(bounds, pix);
     String path(format("{0}/{1}", *_output_dir, relpath));
     makedirs(path::dirname(path), 0755);
     ScopedFd file(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644));
     write(file, pix);
 }
예제 #9
0
static FILE* create_fopen(char* name, char* mode, int subdirs)
{
   if (subdirs)
   {
      char* p = strrchr(name, '/');
      if (p) {
          char* dir_name = _zzip_strndup(name, p-name);
          makedirs(dir_name); 
          free (dir_name);
      }
   }
   return fopen(name, mode);      
}
예제 #10
0
파일: Setup.cpp 프로젝트: rallan9/inetfs
bool
Setup::createDirIfNeeded(const char *path, int mode)
{
	if (!dir_exists(path))
	{
		if (makedirs(path, mode) != 0 || !dir_exists(path))
		{
			fprintf(stderr, "failed to create missing directory: %s\n", path);
			return false;
		}
	}
	return true;
}
예제 #11
0
static void makedirs(const char* name)
{
      char* p = strrchr(name, '/');
      if (p) {
          char* dir_name = _zzip_strndup(name, p-name);
          makedirs(dir_name);
          free (dir_name);
      } 
      if (_zzip_mkdir(name, 0775) == -1 && errno != EEXIST) 
      {
          DBG3("while mkdir %s : %s", name, strerror(errno));
      }
      errno = 0;
}
예제 #12
0
파일: fa_fs.c 프로젝트: whyz/showtime
static int
fs_makedirs(struct fa_protocol *fap, const char *url,
            char *errbuf, size_t errsize)
{

    int r = makedirs(url);

    if(r) {
        snprintf(errbuf, errsize, "Unable to create directory: %s",
                 strerror(errno));
        return -1;
    }
    return 0;
}
예제 #13
0
void CTraderApi::Connect(const string& szPath,
	ServerInfoField* pServerInfo,
	UserInfoField* pUserInfo)
{
	m_szPath = szPath;
	memcpy(&m_ServerInfo, pServerInfo, sizeof(ServerInfoField));
	memcpy(&m_UserInfo, pUserInfo, sizeof(UserInfoField));
	
	char *pszPath = new char[szPath.length() + 1024];
	srand((unsigned int)time(nullptr));
	sprintf(pszPath, "%s/%s/%s/Td/%d/", szPath.c_str(), m_ServerInfo.BrokerID, m_UserInfo.UserID, rand());
	makedirs(pszPath);

	m_pApi = CUstpFtdcTraderApi::CreateFtdcTraderApi(pszPath);
	delete[] pszPath;

	XRespone(ResponeType::OnConnectionStatus, m_msgQueue, this, ConnectionStatus::Initialized, 0, nullptr, 0, nullptr, 0, nullptr, 0);

	if (m_pApi)
	{
		m_pApi->RegisterSpi(this);

		//添加地址
		size_t len = strlen(m_ServerInfo.Address) + 1;
		char* buf = new char[len];
		strncpy(buf, m_ServerInfo.Address, len);

		char* token = strtok(buf, _QUANTBOX_SEPS_);
		while(token)
		{
			if (strlen(token)>0)
			{
				m_pApi->RegisterFront(token);
			}
			token = strtok(nullptr, _QUANTBOX_SEPS_);
		}
		delete[] buf;

		m_pApi->SubscribePublicTopic((USTP_TE_RESUME_TYPE)pServerInfo->PublicTopicResumeType);
		m_pApi->SubscribePrivateTopic((USTP_TE_RESUME_TYPE)pServerInfo->PrivateTopicResumeType);
		// 如果保留,成交回报会收两条
		//m_pApi->SubscribeUserTopic((USTP_TE_RESUME_TYPE)pServerInfo->Resume);
		m_pApi->SubscribeForQuote(USTP_TERT_RESTART); //订阅询价

		//初始化连接
		m_pApi->Init();
		XRespone(ResponeType::OnConnectionStatus, m_msgQueue, this, ConnectionStatus::Connecting, 0, nullptr, 0, nullptr, 0, nullptr, 0);
	}
}
예제 #14
0
int CTraderApi::_Init()
{
	char *pszPath = new char[m_szPath.length() + 1024];
	srand((unsigned int)time(nullptr));
	sprintf(pszPath, "%s/%s/%s/Td/%d/", m_szPath.c_str(), m_ServerInfo.BrokerID, m_UserInfo.UserID, rand());
	makedirs(pszPath);

	m_pApi = CUstpFtdcTraderApi::CreateFtdcTraderApi(pszPath);
	delete[] pszPath;

	m_msgQueue->Input_NoCopy(ResponeType::OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::Initialized, 0, nullptr, 0, nullptr, 0, nullptr, 0);

	if (m_pApi)
	{
		m_pApi->RegisterSpi(this);

		//添加地址
		size_t len = strlen(m_ServerInfo.Address) + 1;
		char* buf = new char[len];
		strncpy(buf, m_ServerInfo.Address, len);

		char* token = strtok(buf, _QUANTBOX_SEPS_);
		while (token)
		{
			if (strlen(token)>0)
			{
				m_pApi->RegisterFront(token);
			}
			token = strtok(nullptr, _QUANTBOX_SEPS_);
		}
		delete[] buf;

		if (m_ServerInfo.PublicTopicResumeType<ResumeType::Undefined)
			m_pApi->SubscribePublicTopic((USTP_TE_RESUME_TYPE)m_ServerInfo.PublicTopicResumeType);
		if (m_ServerInfo.PrivateTopicResumeType<ResumeType::Undefined)
			m_pApi->SubscribePrivateTopic((USTP_TE_RESUME_TYPE)m_ServerInfo.PrivateTopicResumeType);
		// 如果保留,成交回报会收两条
		//if (m_ServerInfo.UserTopicResumeType<ResumeType::Undefined)
		//	m_pApi->SubscribeUserTopic((USTP_TE_RESUME_TYPE)m_ServerInfo.UserTopicResumeType);
		//m_pApi->SubscribeForQuote(USTP_TERT_RESTART); //订阅询价

		//初始化连接
		m_pApi->Init();
		m_msgQueue->Input_NoCopy(ResponeType::OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::Connecting, 0, nullptr, 0, nullptr, 0, nullptr, 0);
	}

	return 0;
}
예제 #15
0
파일: settings.c 프로젝트: dekarl/tvheadend
int
hts_settings_makedirs ( const char *inpath )
{
  size_t x = strlen(inpath) - 1;
  char path[512];
  strcpy(path, inpath);

  while (x) {
    if (path[x] == '/') {
      path[x] = 0;
      break;
    }
    x--;
  }
  return makedirs(path, 0700);
}
예제 #16
0
void DirectoryLedger::save() {
    const pn::string_view scenario_id = sys.prefs->scenario_identifier();
    const pn::string      path        = pn::format("{0}/{1}.pn", dirs().registry, scenario_id);

    pn::array unlocked_chapters;
    for (std::set<int>::const_iterator it = _chapters.begin(); it != _chapters.end(); ++it) {
        unlocked_chapters.push_back(*it);
    }

    makedirs(path::dirname(path), 0755);
    pn::file file = pn::open(path, "w");
    file.dump(pn::map{
            {"unlocked",
             pn::map{
                     {"chapters", std::move(unlocked_chapters)},
             }},
    });
}
예제 #17
0
/*
 * Like mkdir -p
 */
static void
makedirs(const char *dir)
{
    DIR *d;
    char *dirtmp, *basedir;

    if ((d = opendir(dir)) != NULL) {
        closedir(d);
        return;
    }
    if (mkdir(dir, 0755) < 0) {
        dirtmp = strdup(dir);
        basedir = dirname(dirtmp);
        makedirs(basedir);
        free(dirtmp);
        mkdir(dir, 0755);
    }
}
예제 #18
0
int
hts_settings_makedirs ( const char *inpath )
{
  size_t x = strlen(inpath) - 1;
  char *path = alloca(x + 2);

  if (path == NULL) return -1;
  strcpy(path, inpath);

  while (x) {
    if (path[x] == '/') {
      path[x] = 0;
      break;
    }
    x--;
  }
  return makedirs("settings", path, 0700, 1, -1, -1);
}
예제 #19
0
static int
makedirs(const char *path)
{
  struct stat st;
  char *p;
  int l, r;

  if(stat(path, &st) == 0 && S_ISDIR(st.st_mode)) 
    return 0; /* Dir already there */

  if(mkdir(path, 0777) == 0)
    return 0; /* Dir created ok */

  if(errno == ENOENT) {

    /* Parent does not exist, try to create it */
    /* Allocate new path buffer and strip off last directory component */

    l = strlen(path);
    p = alloca(l + 1);
    memcpy(p, path, l);
    p[l--] = 0;
  
    for(; l >= 0; l--)
      if(p[l] == '/')
	break;
    if(l == 0) {
      return ENOENT;
    }
    p[l] = 0;

    if((r = makedirs(p)) != 0)
      return r;
  
    /* Try again */
    if(mkdir(path, 0777) == 0)
      return 0; /* Dir created ok */
  }
  r = errno;

  tvhlog(LOG_ERR, "dvr", "Unable to create directory \"%s\" -- %s",
	 path, strerror(r));
  return r;
}
예제 #20
0
    virtual void become_front() {
        switch (_state) {
          case NEW:
            _state = REPLAY;
            init();
            Randomize(4);  // For the decision to replay intro.
            _game_result = NO_GAME;
            g.random.seed = _random_seed;
            stack()->push(new MainPlay(
                            Handle<Level>(_replay_data.chapter_id - 1), true, &_input_source,
                            false, &_game_result));
            break;

          case REPLAY:
            if (_output_path.has()) {
                String path(format("{0}/debriefing.txt", *_output_path));
                makedirs(path::dirname(path), 0755);
                ScopedFd outcome(open(path, O_WRONLY | O_CREAT, 0644));
                if ((g.victory_text >= 0)) {
                    Resource rsrc("text", "txt", g.victory_text);
                    sfz::write(outcome, rsrc.data());
                    if (_game_result == WIN_GAME) {
                        sfz::write(outcome, "\n\n");
                        Handle<Admiral> player(0);
                        String text = DebriefingScreen::build_score_text(
                                g.time, g.level->parTime,
                                GetAdmiralLoss(player), g.level->parLosses,
                                GetAdmiralKill(player), g.level->parKills);
                        sfz::write(outcome, utf8::encode(text));
                    }
                    sfz::write(outcome, "\n");
                }
            }
            stack()->pop(this);
            break;
        }
    }
예제 #21
0
파일: util.c 프로젝트: infoburp/patch
void
create_backup (char const *to, const struct stat *to_st, bool leave_original)
{
  /* When the input to patch modifies the same file more than once, patch only
     backs up the initial version of each file.

     To figure out which files have already been backed up, patch remembers the
     files that replace the original files.  Files not known already are backed
     up; files already known have already been backed up before, and are
     skipped.

     When a patch tries to delete a file, in order to not break the above
     logic, we merely remember which file to delete.  After the entire patch
     file has been read, we delete all files marked for deletion which have not
     been recreated in the meantime.  */

  if (to_st && ! (S_ISREG (to_st->st_mode) || S_ISLNK (to_st->st_mode)))
    fatal ("File %s is not a %s -- refusing to create backup",
	   to, S_ISLNK (to_st->st_mode) ? "symbolic link" : "regular file");

  if (to_st && lookup_file_id (to_st) == CREATED)
    {
      if (debug & 4)
	say ("File %s already seen\n", quotearg (to));
    }
  else
    {
      int try_makedirs_errno = 0;
      char *bakname;

      if (origprae || origbase || origsuff)
	{
	  char const *p = origprae ? origprae : "";
	  char const *b = origbase ? origbase : "";
	  char const *s = origsuff ? origsuff : "";
	  char const *t = to;
	  size_t plen = strlen (p);
	  size_t blen = strlen (b);
	  size_t slen = strlen (s);
	  size_t tlen = strlen (t);
	  char const *o;
	  size_t olen;

	  for (o = t + tlen, olen = 0;
	       o > t && ! ISSLASH (*(o - 1));
	       o--)
	    /* do nothing */ ;
	  olen = t + tlen - o;
	  tlen -= olen;
	  bakname = xmalloc (plen + tlen + blen + olen + slen + 1);
	  memcpy (bakname, p, plen);
	  memcpy (bakname + plen, t, tlen);
	  memcpy (bakname + plen + tlen, b, blen);
	  memcpy (bakname + plen + tlen + blen, o, olen);
	  memcpy (bakname + plen + tlen + blen + olen, s, slen + 1);

	  if ((origprae
	       && (contains_slash (origprae + FILE_SYSTEM_PREFIX_LEN (origprae))
		   || contains_slash (to)))
	      || (origbase && contains_slash (origbase)))
	    try_makedirs_errno = ENOENT;
	}
      else
	{
	  bakname = find_backup_file_name (to, backup_type);
	  if (!bakname)
	    xalloc_die ();
	}

      if (! to_st)
	{
	  int fd;

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

	  try_makedirs_errno = ENOENT;
	  unlink (bakname);
	  while ((fd = creat (bakname, 0666)) < 0)
	    {
	      if (errno != try_makedirs_errno)
		pfatal ("Can't create file %s", quotearg (bakname));
	      makedirs (bakname);
	      try_makedirs_errno = 0;
	    }
	  if (close (fd) != 0)
	    pfatal ("Can't close file %s", quotearg (bakname));
	}
      else if (leave_original)
	create_backup_copy (to, bakname, to_st, try_makedirs_errno == 0);
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, to), quotearg_n (1, bakname));
	  while (rename (to, bakname) != 0)
	    {
	      if (errno == try_makedirs_errno)
		{
		  makedirs (bakname);
		  try_makedirs_errno = 0;
		}
	      else if (errno == EXDEV)
		{
		  create_backup_copy (to, bakname, to_st,
				      try_makedirs_errno == 0);
		  unlink (to);
		  break;
		}
	      else
		pfatal ("Can't rename file %s to %s",
			quotearg_n (0, to), quotearg_n (1, bakname));
	    }
	}
      free (bakname);
    }
}
예제 #22
0
/**
 * Showtime main
 */
int
main(int argc, char **argv)
{
    struct timeval tv;
    const char *settingspath = NULL;
    const char *uiargs[16];
    const char *argv0 = argc > 0 ? argv[0] : "showtime";
    const char *forceview = NULL;
    int nuiargs = 0;
    int can_standby = 0;
    int can_poweroff = 0;
    int r;

    trace_level = TRACE_INFO;

    gettimeofday(&tv, NULL);
    srand(tv.tv_usec);

    arch_set_default_paths(argc, argv);

    /* We read options ourselfs since getopt() is broken on some (nintento wii)
       targets */

    argv++;
    argc--;

    while(argc > 0) {
        if(!strcmp(argv[0], "-h") || !strcmp(argv[0], "--help")) {
            printf("HTS Showtime %s\n"
                   "Copyright (C) 2007-2010 Andreas Öman\n"
                   "\n"
                   "Usage: %s [options] [<url>]\n"
                   "\n"
                   "  Options:\n"
                   "   -h, --help        - This help text.\n"
                   "   -d                - Enable debug output.\n"
                   "   --ffmpeglog       - Print ffmpeg log messages.\n"
                   "   --with-standby    - Enable system standby.\n"
                   "   --with-poweroff   - Enable system power-off.\n"
                   "   -s <path>         - Non-default Showtime settings path.\n"
                   "   --ui <ui>         - Use specified user interface.\n"
                   "   -L <ip:host>      - Send log messages to remote <ip:host>.\n"
                   "   --syslog          - Send log messages to syslog.\n"
#if ENABLE_STDIN
                   "   --stdin           - Listen on stdin for events.\n"
#endif
                   "   -v <view>         - Use specific view for <url>.\n"
                   "   --cache <path>    - Set path for cache [%s].\n"
#if ENABLE_SERDEV
                   "   --serdev          - Probe service ports for devices.\n"
#endif
                   "\n"
                   "  URL is any URL-type supported by Showtime, "
                   "e.g., \"file:///...\"\n"
                   "\n",
                   htsversion_full,
                   argv0,
                   showtime_cache_path);
            exit(0);
            argc--;
            argv++;

        } else if(!strcmp(argv[0], "-d")) {
            trace_level++;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--ffmpeglog")) {
            ffmpeglog = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--syslog")) {
            trace_to_syslog = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--stdin")) {
            listen_on_stdin = 1;
            argc -= 1;
            argv += 1;
            continue;
#if ENABLE_SERDEV
        } else if(!strcmp(argv[0], "--serdev")) {
            enable_serdev = 1;
            argc -= 1;
            argv += 1;
            continue;
#endif
        } else if(!strcmp(argv[0], "--with-standby")) {
            can_standby = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--with-poweroff")) {
            can_poweroff = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "-s") && argc > 1) {
            settingspath = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        } else if(!strcmp(argv[0], "--ui") && argc > 1) {
            if(nuiargs < 16)
                uiargs[nuiargs++] = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        } else if(!strcmp(argv[0], "-L") && argc > 1) {
            showtime_logtarget = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        } else if (!strcmp(argv[0], "-v") && argc > 1) {
            forceview = argv[1];
            argc -= 2;
            argv += 2;
        } else if (!strcmp(argv[0], "--cache") && argc > 1) {
            mystrset(&showtime_cache_path, argv[1]);
            argc -= 2;
            argv += 2;
#ifdef __APPLE__
            /* ignore -psn argument, process serial number */
        } else if(!strncmp(argv[0], "-psn", 4)) {
            argc -= 1;
            argv += 1;
            continue;
#endif
        } else
            break;
    }


    unicode_init();

    /* Initialize property tree */
    prop_init();
    init_global_info();

    /* Initiailize logging */
    trace_init();

    /* Callout framework */
    callout_init();

    /* Notification framework */
    notifications_init();

    /* Architecture specific init */
    arch_init();

    htsmsg_store_init();

    /* Try to create cache path */
    if(showtime_cache_path != NULL &&
            (r = makedirs(showtime_cache_path)) != 0) {
        TRACE(TRACE_ERROR, "cache", "Unable to create cache path %s -- %s",
              showtime_cache_path, strerror(r));
        showtime_cache_path = NULL;
    }

    /* Initializte blob cache */
    blobcache_init();

    /* Try to create settings path */
    if(showtime_settings_path != NULL &&
            (r = makedirs(showtime_settings_path)) != 0) {
        TRACE(TRACE_ERROR, "settings", "Unable to create settings path %s -- %s",
              showtime_settings_path, strerror(r));
        showtime_settings_path = NULL;
    }

    /* Initialize keyring */
    keyring_init();

    /* Initialize settings */
    settings_init();

    /* Initialize libavcodec & libavformat */
    av_lockmgr_register(fflockmgr);
    av_log_set_callback(fflog);
    av_register_all();

    /* Freetype keymapper */
#if ENABLE_LIBFREETYPE
    freetype_init();
#endif

    /* Global keymapper */
    keymapper_init();

    /* Initialize media subsystem */
    media_init();

    /* Service handling */
    service_init();

    /* Initialize backend content handlers */
    backend_init();

    /* Initialize navigator */
    nav_init();

    /* Initialize audio subsystem */
    audio_init();

    /* Initialize bookmarks */
    bookmarks_init();

    /* Initialize plugin manager and load plugins */
    plugins_init();

    /* Internationalization */
    i18n_init();


    nav_open(NAV_HOME, NULL);

    /* Open initial page */
    if(argc > 0)
        nav_open(argv[0], forceview);

    /* Various interprocess communication stuff (D-Bus on Linux, etc) */
    ipc_init();

    /* Service discovery. Must be after ipc_init() (d-bus and threads, etc) */
    sd_init();

    /* Initialize various external APIs */
    api_init();

    /* HTTP server and UPNP */
#if ENABLE_HTTPSERVER
    http_server_init();
    upnp_init();
#endif


    /* */
    runcontrol_init(can_standby, can_poweroff);

    TRACE(TRACE_DEBUG, "core", "Starting UI");

    /* Initialize user interfaces */
    ui_start(nuiargs, uiargs, argv0);

    finalize();
}
예제 #23
0
/**
 * Filename generator
 *
 * - convert from utf8
 * - avoid duplicate filenames
 *
 */
static int
pvr_generate_filename(dvr_entry_t *de, const streaming_start_t *ss)
{
  char fullname[1000];
  char path[500];
  int tally = 0;
  struct stat st;
  char filename[1000];
  struct tm tm;
  dvr_config_t *cfg = dvr_config_find_by_name_default(de->de_config_name);

  dvr_make_title(filename, sizeof(filename), de);
  cleanupfilename(filename,cfg->dvr_flags);

  snprintf(path, sizeof(path), "%s", cfg->dvr_storage);

  /* Remove trailing slash */

  if (path[strlen(path)-1] == '/')
    path[strlen(path)-1] = '\0';

  /* Append per-day directory */

  if(cfg->dvr_flags & DVR_DIR_PER_DAY) {
    localtime_r(&de->de_start, &tm);
    strftime(fullname, sizeof(fullname), "%F", &tm);
    cleanupfilename(fullname,cfg->dvr_flags);
    snprintf(path + strlen(path), sizeof(path) - strlen(path), 
	     "/%s", fullname);
  }

  /* Append per-channel directory */

  if(cfg->dvr_flags & DVR_DIR_PER_CHANNEL) {

    char *chname = strdup(DVR_CH_NAME(de));
    cleanupfilename(chname,cfg->dvr_flags);
    snprintf(path + strlen(path), sizeof(path) - strlen(path), 
	     "/%s", chname);
    free(chname);
  }

  // TODO: per-brand, per-season

  /* Append per-title directory */

  if(cfg->dvr_flags & DVR_DIR_PER_TITLE) {

    char *title = strdup(lang_str_get(de->de_title, NULL));
    cleanupfilename(title,cfg->dvr_flags);
    snprintf(path + strlen(path), sizeof(path) - strlen(path), 
	     "/%s", title);
    free(title);
  }


  /* */
  if(makedirs(path, 0777) != 0) {
    return -1;
  }
  

  /* Construct final name */
  
  snprintf(fullname, sizeof(fullname), "%s/%s.%s",
	   path, filename, muxer_suffix(de->de_mux, ss));

  while(1) {
    if(stat(fullname, &st) == -1) {
      tvhlog(LOG_DEBUG, "dvr", "File \"%s\" -- %s -- Using for recording",
	     fullname, strerror(errno));
      break;
    }

    tvhlog(LOG_DEBUG, "dvr", "Overwrite protection, file \"%s\" exists", 
	   fullname);

    tally++;

    snprintf(fullname, sizeof(fullname), "%s/%s-%d.%s",
	     path, filename, tally, muxer_suffix(de->de_mux, ss));
  }

  tvh_str_set(&de->de_filename, fullname);

  return 0;
}
예제 #24
0
int main(int argc, char **argv)
{
	loginit(LEVEL_TRACE);
	/* parse command line */
	std::string indir;
	Argv opts;
	opts.addBoolOption("recusive,r","recursive the directory");
	opts.startGroup("Hidden",false);
	opts.addTextOption("inputdir,d","directory for scan").setOptionPostion("inputdir,d",1);
	opts.stopGroup();
	if (!opts.parse(argc,argv))
	{
		/* command options parsing error */
		opts.showHelp(std::cout);
		LOG(error)<< "Input error";
		return 1;
	}
	else
	{
		indir=opts.getTextOption("inputdir","");
	}
	if (indir.size()<1)
	{
		/* inputdir isnot specified */
		opts.showHelp(std::cout,true);
		LOG(error)<< "Directory must be specified";
		return 1;
	}
	LOG(trace)<< "Current Path:"<<bfs::current_path().generic_string();
	LOG(trace)<< "Input directory:"<<indir;

	bfs::path p(indir);
	bfs::path fullp;
	/* checek input directory */
	if (!bfs::exists(p))
	{
		LOG(error)<<"Not exists";
		return 1;
	}
	else
	{
		if (!bfs::is_directory(p))
		{
			LOG(error)<<"Not a directory";
			return 1;
		}
		else
		{
			/* bfs::absolute will remain '..' or '.' */
			fullp=bfs::canonical(p);
			LOG(trace)<<"Full path:"<<fullp.generic_string();
		}
	}

	/* list files */
	walk(fullp,item_action,opts.getBoolOption("recusive"));

	/* generate a unique filename, used for temperary file */
	std::cout<<bfs::unique_path().generic_string()<<std::endl;

	/* make dir */
	bfs::path tmpfile("temp/abc/def");
	/* path.parent_path() must exist for bfs::create_directory(path) */
	/* makedirs(path) will call create_directory() repeatly until path is created */
	makedirs(tmpfile);
	/* create a temperary file */
	tmpfile/=bfs::unique_path();
	LOG(trace)<<tmpfile.generic_string();
	std::ofstream ofs(tmpfile.generic_string());
	ofs<<"test\n";
	ofs.close();
	/* remove directory */
	bfs::remove_all("temp");
	/* other file operation:
	 * copy, copy_directory, copy_file, copy_symlink
	 *   copy will automaticall choose copy_directory/copy_file/copy_symlink
	 * remove, remove_all
	 *   remove for file, remove_all for directory
	 * rename
	 */

	std::vector<bfs::path> vec;
	findInPath("vim",{"."},vec);
	std::copy(vec.cbegin(),vec.cend(),std::ostream_iterator<bfs::path>(std::cout,"\n"));
	return 0;
}
예제 #25
0
static void
finish(void)
{
    int i, ret;
    char *cmd, *mntpt, *errq = NULL, *fs;

    // Sort the partitions according to the order they have to be mounted
    qsort(parts, part_count, sizeof(struct partition *), mountpoint_sort_func);
    for (i = 0; i < part_count; i++) {
        fs = parts[i]->op.filesystem;
        if (fs == NULL)
            fs = parts[i]->fstype;
        else {
            // Create the file system/swap
            if (strcmp(fs, "swap") == 0) {
                append_message("partconf: Creating swap on %s\n", parts[i]->path);
                asprintf(&cmd, "mkswap %s >/dev/null 2>>/var/log/messages", parts[i]->path);
                ret = system(cmd);
                free(cmd);
                if (ret != 0) {
                    errq = "partconf/failed-mkswap";
                    break;
                }
            } else {
		char *mkfs_opts="";
		/* mkfs.reiserfs is interactive unless passed a -q */
		if (strcmp(fs, "reiserfs") == 0) {
			mkfs_opts="-q";
		}
		/* mkfs.xfs will not overwrite existing filesystems unless
		 * one passes -f. at this point, user has claimed "yes, do
		 * as I say!" so let's force it here. */
		else if (strcmp(fs, "xfs") == 0) {
		  	mkfs_opts="-f";
		}
                append_message("partconf: Creating %s file system on %s\n", fs, parts[i]->path);
                asprintf(&cmd, "mkfs.%s %s %s >/dev/null 2>>/var/log/messages", fs, mkfs_opts, parts[i]->path);
                ret = system(cmd);
                free(cmd);
                if (ret != 0) {
                    errq = "partconf/failed-mkfs";
                    debconf_subst(debconf,errq, "FS", parts[i]->op.filesystem);
                    break;
                }
            }
        }
        if (fs != NULL) {
            if (strcmp(fs, "swap") == 0 && !check_proc_swaps(parts[i]->path)) {
                // Activate swap
                append_message("partconf: Activating swap on %s\n", parts[i]->path);
                asprintf(&cmd, "swapon %s >/dev/null 2>>/var/log/messages", parts[i]->path);
                ret = system(cmd);
                free(cmd);
                /* 
                 * Since we check if the swap is already activated, it may
                 * make sense to make this fatal. For now, it is, anyway.
                 */
                if (ret != 0) {
                    errq = "partconf/failed-swapon";
                    break;
                }
            } else if (parts[i]->op.mountpoint != NULL) {
                // And mount
                append_message("partconf: Mounting %s on %s\n",
                        parts[i]->path, parts[i]->op.mountpoint);
                asprintf(&mntpt, "/target%s", parts[i]->op.mountpoint);
                makedirs(mntpt);
                fs = parts[i]->op.filesystem ? parts[i]->op.filesystem : parts[i]->fstype;
                ret = mount(parts[i]->path, mntpt, fs, 0xC0ED0000, NULL);
                // Ignore failure due to unknown filesystem
                if (ret < 0 && errno != ENODEV) {
                    append_message("mount: %s\n", strerror(errno));
                    errq = "partconf/failed-mount";
                    debconf_subst(debconf, errq, "MOUNT", mntpt);
                    free(mntpt);
                    break;
                }
                free(mntpt);
            }
        }
    }
    if (errq != NULL) {
        debconf_subst(debconf, errq, "PARTITION", parts[i]->path);
        debconf_input(debconf,"critical", errq);
        debconf_go(debconf);
        exit(30);
    }
    mkfstab();

    exit(0);
}
예제 #26
0
파일: inp.c 프로젝트: Hooman3/minix
static bool
plan_a(const char *filename)
{
	int		ifd, statfailed;
	char		*p, *s, lbuf[MAXLINELEN];
	struct stat	filestat;
	off_t		i;
	ptrdiff_t	sz;
	size_t		iline, lines_allocated;

#ifdef DEBUGGING
	if (debug & 8)
		return false;
#endif

	if (filename == NULL || *filename == '\0')
		return false;

	statfailed = stat(filename, &filestat);
	if (statfailed && ok_to_create_file) {
		if (verbose)
			say("(Creating file %s...)\n", filename);

		/*
		 * in check_patch case, we still display `Creating file' even
		 * though we're not. The rule is that -C should be as similar
		 * to normal patch behavior as possible
		 */
		if (check_only)
			return true;
		makedirs(filename, true);
		close(creat(filename, 0666));
		statfailed = stat(filename, &filestat);
	}
	if (statfailed && check_only)
		fatal("%s not found, -C mode, can't probe further\n", filename);
	/* For nonexistent or read-only files, look for RCS or SCCS versions.  */
	if (statfailed ||
	    /* No one can write to it.  */
	    (filestat.st_mode & 0222) == 0 ||
	    /* I can't write to it.  */
	    ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
		const char	*cs = NULL, *filebase, *filedir;
		struct stat	cstat;
		char *tmp_filename1, *tmp_filename2;

		tmp_filename1 = strdup(filename);
		tmp_filename2 = strdup(filename);
		if (tmp_filename1 == NULL || tmp_filename2 == NULL)
			fatal("strdupping filename");
		filebase = basename(tmp_filename1);
		filedir = dirname(tmp_filename2);

		/* Leave room in lbuf for the diff command.  */
		s = lbuf + 20;

#define try(f, a1, a2, a3) \
	(snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)

		if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
		    try("%s/RCS/%s%s", filedir, filebase, "") ||
		    try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
			snprintf(buf, buf_len, CHECKOUT, filename);
			snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
			cs = "RCS";
		} else if (try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
		    try("%s/%s%s", filedir, SCCSPREFIX, filebase)) {
			snprintf(buf, buf_len, GET, s);
			snprintf(lbuf, sizeof lbuf, SCCSDIFF, s, filename);
			cs = "SCCS";
		} else if (statfailed)
			fatal("can't find %s\n", filename);

		free(tmp_filename1);
		free(tmp_filename2);

		/*
		 * else we can't write to it but it's not under a version
		 * control system, so just proceed.
		 */
		if (cs) {
			if (!statfailed) {
				if ((filestat.st_mode & 0222) != 0)
					/* The owner can write to it.  */
					fatal("file %s seems to be locked "
					    "by somebody else under %s\n",
					    filename, cs);
				/*
				 * It might be checked out unlocked.  See if
				 * it's safe to check out the default version
				 * locked.
				 */
				if (verbose)
					say("Comparing file %s to default "
					    "%s version...\n",
					    filename, cs);
				if (system(lbuf))
					fatal("can't check out file %s: "
					    "differs from default %s version\n",
					    filename, cs);
			}
			if (verbose)
				say("Checking out file %s from %s...\n",
				    filename, cs);
			if (system(buf) || stat(filename, &filestat))
				fatal("can't check out file %s from %s\n",
				    filename, cs);
		}
	}
	filemode = filestat.st_mode;
	if (!S_ISREG(filemode))
		fatal("%s is not a normal file--can't patch\n", filename);
	i_size = filestat.st_size;
	if (out_of_mem) {
		set_hunkmax();	/* make sure dynamic arrays are allocated */
		out_of_mem = false;
		return false;	/* force plan b because plan a bombed */
	}
	if ((uintmax_t)i_size > (uintmax_t)SIZE_MAX) {
		say("block too large to mmap\n");
		return false;
	}
	if ((ifd = open(filename, O_RDONLY)) < 0)
		pfatal("can't open file %s", filename);

	if (i_size) {
		i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
		if (i_womp == MAP_FAILED) {
			perror("mmap failed");
			i_womp = NULL;
			close(ifd);
			return false;
		}
	} else {
		i_womp = NULL;
	}

	close(ifd);
#if !defined(__minix)
	if (i_size)
		madvise(i_womp, i_size, MADV_SEQUENTIAL);
#endif /* !defined(__minix) */

	/* estimate the number of lines */
	lines_allocated = i_size / 25;
	if (lines_allocated < 100)
		lines_allocated = 100;

	if (!reallocate_lines(&lines_allocated))
		return false;

	/* now scan the buffer and build pointer array */
	iline = 1;
	i_ptr[iline] = i_womp;
	/* test for NUL too, to maintain the behavior of the original code */
	for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
		if (*s == '\n') {
			if (iline == lines_allocated) {
				if (!reallocate_lines(&lines_allocated))
					return false;
			}
			/* these are NOT NUL terminated */
			i_ptr[++iline] = s + 1;
		}
	}
	/* if the last line contains no EOL, append one */
	if (i_size > 0 && i_womp[i_size - 1] != '\n') {
		last_line_missing_eol = true;
		/* fix last line */
		sz = s - i_ptr[iline];
		p = malloc(sz + 1);
		if (p == NULL) {
			free(i_ptr);
			i_ptr = NULL;
			munmap(i_womp, i_size);
			i_womp = NULL;
			return false;
		}

		memcpy(p, i_ptr[iline], sz);
		p[sz] = '\n';
		i_ptr[iline] = p;
		/* count the extra line and make it point to some valid mem */
		i_ptr[++iline] = empty_line;
	} else
		last_line_missing_eol = false;

	input_lines = iline - 1;

	/* now check for revision, if any */

	if (revision != NULL) {
		if (!rev_in_string(i_womp)) {
			if (force) {
				if (verbose)
					say("Warning: this file doesn't appear "
					    "to be the %s version--patching anyway.\n",
					    revision);
			} else if (batch) {
				fatal("this file doesn't appear to be the "
				    "%s version--aborting.\n",
				    revision);
			} else {
				ask("This file doesn't appear to be the "
				    "%s version--patch anyway? [n] ",
				    revision);
				if (*buf != 'y')
					fatal("aborted\n");
			}
		} else if (verbose)
			say("Good.  This file appears to be the %s version.\n",
			    revision);
	}
	return true;		/* plan a will work */
}

/* Keep (virtually) nothing in memory. */

static void
plan_b(const char *filename)
{
	FILE	*ifp;
	size_t	i = 0, j, maxlen = 1;
	char	*p;
	bool	found_revision = (revision == NULL);

	using_plan_a = false;
	if ((ifp = fopen(filename, "r")) == NULL)
		pfatal("can't open file %s", filename);
	unlink(TMPINNAME);
	if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
		pfatal("can't open file %s", TMPINNAME);
	while (fgets(buf, buf_len, ifp) != NULL) {
		if (revision != NULL && !found_revision && rev_in_string(buf))
			found_revision = true;
		if ((i = strlen(buf)) > maxlen)
			maxlen = i;	/* find longest line */
	}
	last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
	if (last_line_missing_eol && maxlen == i)
		maxlen++;

	if (revision != NULL) {
		if (!found_revision) {
			if (force) {
				if (verbose)
					say("Warning: this file doesn't appear "
					    "to be the %s version--patching anyway.\n",
					    revision);
			} else if (batch) {
				fatal("this file doesn't appear to be the "
				    "%s version--aborting.\n",
				    revision);
			} else {
				ask("This file doesn't appear to be the %s "
				    "version--patch anyway? [n] ",
				    revision);
				if (*buf != 'y')
					fatal("aborted\n");
			}
		} else if (verbose)
			say("Good.  This file appears to be the %s version.\n",
			    revision);
	}
	fseek(ifp, 0L, SEEK_SET);	/* rewind file */
	lines_per_buf = BUFFERSIZE / maxlen;
	tireclen = maxlen;
	tibuf[0] = malloc(BUFFERSIZE + 1);
	if (tibuf[0] == NULL)
		fatal("out of memory\n");
	tibuf[1] = malloc(BUFFERSIZE + 1);
	if (tibuf[1] == NULL)
		fatal("out of memory\n");
	for (i = 1;; i++) {
		p = tibuf[0] + maxlen * (i % lines_per_buf);
		if (i % lines_per_buf == 0)	/* new block */
			if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
				pfatal("can't write temp file");
		if (fgets(p, maxlen + 1, ifp) == NULL) {
			input_lines = i - 1;
			if (i % lines_per_buf != 0)
				if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
					pfatal("can't write temp file");
			break;
		}
		j = strlen(p);
		/* These are '\n' terminated strings, so no need to add a NUL */
		if (j == 0 || p[j - 1] != '\n')
			p[j] = '\n';
	}
	fclose(ifp);
	close(tifd);
	if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
		pfatal("can't reopen file %s", TMPINNAME);
}

/*
 * Fetch a line from the input file, \n terminated, not necessarily \0.
 */
char *
ifetch(LINENUM line, int whichbuf)
{
	if (line < 1 || line > input_lines) {
		if (warn_on_invalid_line) {
			say("No such line %ld in input file, ignoring\n", line);
			warn_on_invalid_line = false;
		}
		return NULL;
	}
	if (using_plan_a)
		return i_ptr[line];
	else {
		LINENUM	offline = line % lines_per_buf;
		LINENUM	baseline = line - offline;

		if (tiline[0] == baseline)
			whichbuf = 0;
		else if (tiline[1] == baseline)
			whichbuf = 1;
		else {
			tiline[whichbuf] = baseline;

			if (lseek(tifd, (off_t) (baseline / lines_per_buf *
			    BUFFERSIZE), SEEK_SET) < 0)
				pfatal("cannot seek in the temporary input file");

			if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
				pfatal("error reading tmp file %s", TMPINNAME);
		}
		return tibuf[whichbuf] + (tireclen * offline);
	}
}

/*
 * True if the string argument contains the revision number we want.
 */
static bool
rev_in_string(const char *string)
{
	const char	*s;
	size_t		patlen;

	if (revision == NULL)
		return true;
	patlen = strlen(revision);
	if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
		return true;
	for (s = string; *s; s++) {
		if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
		    isspace((unsigned char)s[patlen + 1])) {
			return true;
		}
	}
	return false;
}
예제 #27
0
void main(int argc, char** argv) {
    args::Parser parser(argv[0], "Plays a replay into a set of images and a log of sounds");

    String replay_path(utf8::decode(argv[0]));
    parser.add_argument("replay", store(replay_path)).help("an Antares replay script").required();

    Optional<String> output_dir;
    parser.add_argument("-o", "--output", store(output_dir))
            .help("place output in this directory");

    int  interval = 60;
    int  width    = 640;
    int  height   = 480;
    bool text     = false;
    bool smoke    = false;
    parser.add_argument("-i", "--interval", store(interval))
            .help("take one screenshot per this many ticks (default: 60)");
    parser.add_argument("-w", "--width", store(width)).help("screen width (default: 640)");
    parser.add_argument("-h", "--height", store(height)).help("screen height (default: 480)");
    parser.add_argument("-t", "--text", store_const(text, true)).help("produce text output");
    parser.add_argument("-s", "--smoke", store_const(smoke, true)).help("run as smoke text");

    parser.add_argument("--help", help(parser, 0)).help("display this help screen");

    String error;
    if (!parser.parse_args(argc - 1, argv + 1, error)) {
        print(io::err, format("{0}: {1}\n", parser.name(), error));
        exit(1);
    }

    if (output_dir.has()) {
        makedirs(*output_dir, 0755);
    }

    Preferences preferences;
    preferences.play_music_in_game = true;
    NullPrefsDriver prefs(preferences);

    EventScheduler scheduler;
    scheduler.schedule_event(unique_ptr<Event>(new MouseMoveEvent(wall_time(), Point(320, 240))));
    // TODO(sfiera): add recurring snapshots to OffscreenVideoDriver.
    for (int64_t i = 1; i < 72000; i += interval) {
        scheduler.schedule_snapshot(i);
    }

    unique_ptr<SoundDriver> sound;
    if (!smoke && output_dir.has()) {
        String out(format("{0}/sound.log", *output_dir));
        sound.reset(new LogSoundDriver(out));
    } else {
        sound.reset(new NullSoundDriver);
    }
    NullLedger ledger;

    MappedFile replay_file(replay_path);
    if (smoke) {
        TextVideoDriver video({width, height}, Optional<String>());
        video.loop(new ReplayMaster(replay_file.data(), output_dir), scheduler);
    } else if (text) {
        TextVideoDriver video({width, height}, output_dir);
        video.loop(new ReplayMaster(replay_file.data(), output_dir), scheduler);
    } else {
        OffscreenVideoDriver video({width, height}, output_dir);
        video.loop(new ReplayMaster(replay_file.data(), output_dir), scheduler);
    }
}
예제 #28
0
파일: util.c 프로젝트: infoburp/patch
void
move_file (char const *from, bool *from_needs_removal,
	   struct stat const *fromst,
	   char const *to, mode_t mode, bool backup)
{
  struct stat to_st;
  int to_errno;

  to_errno = stat_file (to, &to_st);
  if (backup)
    create_backup (to, to_errno ? NULL : &to_st, false);
  if (! to_errno)
    insert_file_id (&to_st, OVERWRITTEN);

  if (from)
    {
      if (S_ISLNK (mode))
	{
	  bool to_dir_known_to_exist = false;

	  /* FROM contains the contents of the symlink we have patched; need
	     to convert that back into a symlink. */
	  char *buffer = xmalloc (PATH_MAX);
	  int fd, size = 0, i;

	  if ((fd = open (from, O_RDONLY | O_BINARY)) < 0)
	    pfatal ("Can't reopen file %s", quotearg (from));
	  while ((i = read (fd, buffer + size, PATH_MAX - size)) > 0)
	    size += i;
	  if (i != 0 || close (fd) != 0)
	    read_fatal ();
	  buffer[size] = 0;

	  if (! backup)
	    {
	      if (unlink (to) == 0)
		to_dir_known_to_exist = true;
	    }
	  if (symlink (buffer, to) != 0)
	    {
	      if (errno == ENOENT && ! to_dir_known_to_exist)
		makedirs (to);
	      if (symlink (buffer, to) != 0)
		pfatal ("Can't create %s %s", "symbolic link", to);
	    }
	  free (buffer);
	  if (lstat (to, &to_st) != 0)
	    pfatal ("Can't get file attributes of %s %s", "symbolic link", to);
	  insert_file_id (&to_st, CREATED);
	}
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, from), quotearg_n (1, to));

	  if (rename (from, to) != 0)
	    {
	      bool to_dir_known_to_exist = false;

	      if (errno == ENOENT
		  && (to_errno == -1 || to_errno == ENOENT))
		{
		  makedirs (to);
		  to_dir_known_to_exist = true;
		  if (rename (from, to) == 0)
		    goto rename_succeeded;
		}

	      if (errno == EXDEV)
		{
		  struct stat tost;
		  if (! backup)
		    {
		      if (unlink (to) == 0)
			to_dir_known_to_exist = true;
		      else if (errno != ENOENT)
			pfatal ("Can't remove file %s", quotearg (to));
		    }
		  copy_file (from, to, &tost, 0, mode, to_dir_known_to_exist);
		  insert_file_id (&tost, CREATED);
		  return;
		}

	      pfatal ("Can't rename file %s to %s",
		      quotearg_n (0, from), quotearg_n (1, to));
	    }

	rename_succeeded:
	  insert_file_id (fromst, CREATED);
	  /* Do not clear *FROM_NEEDS_REMOVAL if it's possible that the
	     rename returned zero because FROM and TO are hard links to
	     the same file.  */
	  if ((0 < to_errno
	       || (to_errno == 0 && to_st.st_nlink <= 1))
	      && from_needs_removal)
	    *from_needs_removal = false;
	}
    }
  else if (! backup)
    {
      if (debug & 4)
	say ("Removing file %s\n", quotearg (to));
      if (unlink (to) != 0 && errno != ENOENT)
	pfatal ("Can't remove file %s", quotearg (to));
    }
}
예제 #29
0
파일: dvr_rec.c 프로젝트: JPP1/tvheadend
/**
 * Filename generator
 *
 * - convert from utf8
 * - avoid duplicate filenames
 *
 */
static int
pvr_generate_filename(dvr_entry_t *de, const streaming_start_t *ss)
{
  char fullname[PATH_MAX];
  char path[PATH_MAX];
  int tally = 0;
  struct stat st;
  char *filename, *s;
  struct tm tm;
  dvr_config_t *cfg;

  if (de == NULL)
    return -1;

  cfg = de->de_config;
  strncpy(path, cfg->dvr_storage, sizeof(path));
  path[sizeof(path)-1] = '\0';

  /* Remove trailing slash */
  if (path[strlen(path)-1] == '/')
    path[strlen(path)-1] = '\0';

  /* Append per-day directory */
  if (cfg->dvr_dir_per_day) {
    localtime_r(&de->de_start, &tm);
    strftime(fullname, sizeof(fullname), "%F", &tm);
    s = cleanup_filename(fullname, cfg);
    if (s == NULL)
      return -1;
    snprintf(path + strlen(path), sizeof(path) - strlen(path), "/%s", s);
    free(s);
  }

  /* Append per-channel directory */
  if (cfg->dvr_channel_dir) {
    char *chname = strdup(DVR_CH_NAME(de));
    s = cleanup_filename(chname, cfg);
    free(chname);
    if (s == NULL)
      return -1;
    snprintf(path + strlen(path), sizeof(path) - strlen(path), "/%s", s);
    free(s);
  }

  // TODO: per-brand, per-season

  /* Append per-title directory */
  if (cfg->dvr_title_dir) {
    char *title = strdup(lang_str_get(de->de_title, NULL));
    s = cleanup_filename(title, cfg);
    free(title);
    if (s == NULL)
      return -1;
    snprintf(path + strlen(path), sizeof(path) - strlen(path), "/%s", s);
    free(s);
  }

  if (makedirs(path, cfg->dvr_muxcnf.m_directory_permissions) != 0)
    return -1;
  
  /* Construct final name */
  dvr_make_title(fullname, sizeof(fullname), de);
  filename = cleanup_filename(fullname, cfg);
  if (filename == NULL)
    return -1;
  snprintf(fullname, sizeof(fullname), "%s/%s.%s",
	   path, filename, muxer_suffix(de->de_chain->prch_muxer, ss));

  while(1) {
    if(stat(fullname, &st) == -1) {
      tvhlog(LOG_DEBUG, "dvr", "File \"%s\" -- %s -- Using for recording",
	     fullname, strerror(errno));
      break;
    }

    tvhlog(LOG_DEBUG, "dvr", "Overwrite protection, file \"%s\" exists", 
	   fullname);

    tally++;

    snprintf(fullname, sizeof(fullname), "%s/%s-%d.%s",
	     path, filename, tally, muxer_suffix(de->de_chain->prch_muxer, ss));
  }
  free(filename);

  tvh_str_set(&de->de_filename, fullname);

  return 0;
}
예제 #30
0
void
move_file (char const *from, int volatile *from_needs_removal,
	   char *to, mode_t mode, int backup)
{
  struct stat to_st;
  int to_errno = ! backup ? -1 : stat (to, &to_st) == 0 ? 0 : errno;

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

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

      if (to_errno)
	{
	  int fd;

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

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

      free (bakname);
    }

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

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

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

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

	  pfatal ("Can't rename file %s to %s",
		  quotearg_n (0, from), quotearg_n (1, to));
	}
    }
  else if (! backup)
    {
      if (debug & 4)
	say ("Removing file %s\n", quotearg (to));
      if (unlink (to) != 0)
	pfatal ("Can't remove file %s", quotearg (to));
    }
}