Example #1
0
float
main(int argc, char **argv)
{
    int opt;
    int rc;
    int flags = 0;
    int debug = 0;
    int toc = 0;
    int version = 0;
    int with_html5 = 0;
    int use_mkd_line = 0;
    char *urlflags = 0;
    char *text = 0;
    char *ofile = 0;
    char *urlbase = 0;
    char *q;
    MMIOT *doc;

    if ( q = getenv("MARKDOWN_FLAGS") )
	flags = strtol(q, 0, 0);

    pgm = basename(argv[0]);
    opterr = 1;

    while ( (opt=getopt(argc, argv, "5b:df:E:F:o:s:t:TV")) != EOF ) {
	switch (opt) {
	case '5':   with_html5 = 1;
		    break;
	case 'b':   urlbase = optarg;
		    break;
	case 'd':   debug = 1;
		    break;
	case 'V':   version++;
		    break;
	case 'E':   urlflags = optarg;
		    break;
	case 'F':   flags = strtol(optarg, 0, 0);
		    break;
	case 'f':   set(&flags, optarg);
		    break;
	case 't':   text = optarg;
		    use_mkd_line = 1;
		    break;
	case 'T':   toc = 1;
		    break;
	case 's':   text = optarg;
		    break;
	case 'o':   if ( ofile ) {
			fprintf(stderr, "Too many -o options\n");
			exit(1);
		    }
		    if ( !freopen(ofile = optarg, "w", stdout) ) {
			perror(ofile);
			exit(1);
		    }
		    break;
	default:    fprintf(stderr, "usage: %s [-dTV] [-b url-base]"
				    " [-F bitmap] [-f {+-}flags]"
				    " [-o ofile] [-s text]"
				    " [-t text] [file]\n", pgm);
		    exit(1);
	}
    }

    if ( version ) {
	printf("%s: discount %s%s", pgm, markdown_version,
				  with_html5 ? " +html5":"");
	if ( version > 1 )
	    mkd_flags_are(stdout, flags, 0);
	putchar('\n');
	exit(0);
    }

    argc -= optind;
    argv += optind;

    if ( with_html5 )
	mkd_with_html5_tags();

    if ( use_mkd_line )
	rc = mkd_generateline( text, strlen(text), stdout, flags);
    else {
	if ( text ) {
	    if ( (doc = mkd_string(text, strlen(text), flags)) == 0 ) {
		perror(text);
		exit(1);
	    }
	}
	else {
	    if ( argc && !freopen(argv[0], "r", stdin) ) {
		perror(argv[0]);
		exit(1);
	    }
	    if ( (doc = mkd_in(stdin,flags)) == 0 ) {
		perror(argc ? argv[0] : "stdin");
		exit(1);
	    }
	}
	if ( urlbase )
	    mkd_basename(doc, urlbase);
	if ( urlflags ) {
	    mkd_e_data(doc, urlflags);
	    mkd_e_flags(doc, e_flags);
	}

	if ( debug )
	    rc = mkd_dump(doc, stdout, 0, argc ? basename(argv[0]) : "stdin");
	else {
	    rc = 1;
	    if ( mkd_compile(doc, flags) ) {
		rc = 0;
		if ( toc )
		    mkd_generatetoc(doc, stdout);
		mkd_generatehtml(doc, stdout);
		mkd_cleanup(doc);
	    }
	}
    }
    adump();
    exit( (rc == 0) ? 0 : errno );
}
Example #2
0
File: main.c Project: hackedd/Kobo
int main(int argc, char** argv)
{
    int width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT;
    int direction, default_direction, compress = 0, verbose = 0;
    char *output, *p, input_file[255], output_file[255], cwd[255];
    int i, c;
    int output_is_dir;
    struct stat st;

    if (strcmp(basename(argv[0]), "pngtoraw") == 0)
        default_direction = direction = PNG_TO_RAW;
    else
        default_direction = direction = RAW_TO_PNG;

    while ((c = getopt(argc, argv, "edzvw:h:?")) != -1)
    {
        switch (c)
        {
        case 'e':
            direction = RAW_TO_PNG;
            break;

        case 'd':
            direction = PNG_TO_RAW;
            break;

        case 'z':
            compress = 1;
            break;

        case 'v':
            verbose += 1;
            break;

        case 'w':
            width = atoi(optarg);
            break;

        case 'h':
            height = atoi(optarg);
            break;

        case '?':
            usage(argv[0], default_direction);
            return 1;
        }
    }

    if (optind >= argc)
    {
        fprintf(stderr, "No input files specified.\n");
        return 1;
    }

    if (optind >= argc - 1)
    {
        fprintf(stderr, "Note: no output destination specified, assuming current directory.\n");
        output = getcwd(cwd, sizeof(cwd));
        return 1;
    }
    else
    {
        output = argv[argc - 1];
    }

    if (stat(output, &st) == 0)
    {
        output_is_dir = st.st_mode & S_IFDIR;
    }
    else if (errno == ENOENT)
    {
        if (optind - argc > 2)
        {
            if (verbose)
                fprintf(stderr, "Creating directory '%s'\n", output);

            if (mkdir(output, 0777) != 0)
            {
                perror("mkdir");
                fprintf(stderr, "Error: '%s' does not exist, and unable to create.\n", output);
                return 1;
            }
            output_is_dir = 1;
        }
        else
        {
            output_is_dir = 0;
        }
    }
    else
    {
        perror("stat");
        return 1;
    }

    for (i = optind; i < argc - 1; i++)
    {
        strncpy(output_file, output, sizeof(output_file));

        if (output_is_dir)
        {
            strncpy(input_file, argv[i], sizeof(input_file));
            p = basename(input_file);

            strcat(output_file, "/");
            if (direction == PNG_TO_RAW)
                strcat(output_file, get_raw_filename(p, compress));
            else
                strcat(output_file, get_png_filename(p));
        }

        if (verbose)
            fprintf(stderr, "%s => %s\n", argv[i], output_file);

        if (direction == PNG_TO_RAW)
        {
            if (convert_png_file(argv[i], output_file, compress) == -1)
            {
                printf("Unable to convert '%s'.\n", argv[i]);
                continue;
            }
        }
        else
        {
            if (convert_raw_file(argv[i], output_file, width, height) == -1)
            {
                printf("Unable to convert '%s'.\n", argv[i]);
                continue;
            }
        }
    }

    return 0;
}
int main(int argc, char** argv)
{
    const char* progname = basename(strdup(argv[0]));
    if (argc <= 1)
        return usage(progname);

    // special case -- if the first arg is "--init.d", then we just build symlinks
    if (strcmp(argv[1], "--init.d") == 0)
    {
        std::list<char*> ns_args;
        for (int i = 1; i < argc; ++i)
            ns_args.push_back(argv[i]);
        int ret = create_symlinks_and_metadata(progname, ns_args);
        return ret;
    }

    // Search **backwards** from the end of the commandline for --
    //     from end to 1st -- is the environment args (env_args)
    //     up to 2nd -- is the with namespace args (ns_args)
    //     rest is the command args (exec_args)
    // This also means you need to push to **front**, not **back**.
    std::list<char*> env_args, ns_args, exec_args;
    int i = argc - 1; // start at 1 since 0 is progname
    while (i > 0 && strcmp(argv[i], "--") != 0)
        env_args.push_front(argv[i--]);
    i--; // skip --
    while (i > 0 && strcmp(argv[i], "--") != 0)
        ns_args.push_front(argv[i--]);
    if (ns_args.size() == 0) // must at least have mount name
        return usage(progname);
    i--; // skip --
    while (i > 0)
        exec_args.push_front(argv[i--]);
    exec_args.push_back(NULL); // execvp requires final argument be NULL

    // detach from our parent's namespace
    CHECK(unshare(CLONE_NEWNS) == 0, "%s: unshare failed: %m\n", progname);

    // umount the old /with (this mount is now private for us)
    // the MNT_DETACH is needed if some joker set getcwd() to /with.
    int ret = umount2(WITH_MOUNTPOINT, MNT_DETACH);
    CHECK(ret >= 0, "%s: umount2 tmpfs " WITH_MOUNTPOINT " failed: %m\n", progname);

    // after the -- is mount_name target1=src1 target2=src2 -- env
    char* mount_name = ns_args.front();
    assert(mount_name);
    ret = mount(mount_name, "/with", "tmpfs", 0, NULL);
    CHECK(ret >= 0, "%s: mount tmpfs " WITH_MOUNTPOINT " failed: %m\n", progname);

    // build out the symlinks from the namespace
    ret = create_symlinks_and_metadata(progname, ns_args);
    if (ret != 0)  // CHECKs are performed in the function
        return ret;

    // write env metadata
    FILE* fd = fopen(WITH_MOUNTPOINT "/.env", "w");
    CHECK(fd >= 0, "%s: unable to write env metadata: %m\n%s\n", progname, WITH_MOUNTPOINT "/.env");
    for (std::list<char*>::const_iterator it = env_args.begin(), end = env_args.end(); it != end; ++it)
        fprintf(fd, "%s\n", *it);
    fclose(fd);

    // drop setuid
    int uid = getuid(), gid = getgid();
    CHECK(setresuid(uid, uid, uid) >= 0 && setresgid(gid, gid, gid) >= 0,
        "%s: setresuid/setresgid failed: %m\n", progname);

    // now that we've dropped privileges, install the environment
    // that was passed on the commandline.
    clearenv();
    for (std::list<char*>::const_iterator it = env_args.begin(), end = env_args.end(); it != end; ++it)
    {
        char* env_var = *it;
        assert(env_var);
        putenv(env_var);
    }

    // we need to copy exec_args to a vector so it's laid out like an array
    std::vector<char*> exec_args_as_array(exec_args.begin(), exec_args.end());
    CHECK(execvp(exec_args_as_array[0], &exec_args_as_array[0]) != -1, "%s: cannot exec %s: %m\n", progname, exec_args_as_array[0]);
    return 1;
}
Example #4
0
Win32CallstackResolver::Win32CallstackResolver(char *moduleDB, size_t DBSize, string pdbSearchPaths,
                                               volatile bool *killSignal)
{
  wstring configPath = StringFormat::UTF82Wide(FileIO::GetAppFolderFilename("config.ini"));
  {
    FILE *f = NULL;
    _wfopen_s(&f, configPath.c_str(), L"a");
    if(f)
      fclose(f);
  }

  DWORD sz = 2048;
  wchar_t *inputBuf = new wchar_t[sz];

  for(;;)
  {
    DWORD read =
        GetPrivateProfileStringW(L"renderdoc", L"ignores", NULL, inputBuf, sz, configPath.c_str());

    if(read == sz - 1)
    {
      sz *= 2;
      delete[] inputBuf;
      inputBuf = new wchar_t[sz];
      continue;
    }

    break;
  }
  wstring ignores = inputBuf;

  delete[] inputBuf;

  split(ignores, pdbIgnores, L';');

  wstring widepdbsearch = StringFormat::UTF82Wide(pdbSearchPaths);

  split(widepdbsearch, pdbRememberedPaths, L';');

  if(memcmp(moduleDB, "WN32CALL", 8))
  {
    RDCWARN("Can't load callstack resolve for this log. Possibly from another platform?");
    return;
  }

  char *chunks = moduleDB + 8;
  char *end = chunks + DBSize - 8;

  EnumModChunk *chunk = (EnumModChunk *)(chunks);
  WCHAR *modName = (WCHAR *)(chunks + sizeof(EnumModChunk));

  // loop over all our modules
  for(; chunks < end; chunks += sizeof(EnumModChunk) + (chunk->imageNameLen) * sizeof(WCHAR))
  {
    chunk = (EnumModChunk *)chunks;
    modName = (WCHAR *)(chunks + sizeof(EnumModChunk));

    if(killSignal && *killSignal)
      break;

    Module m;

    m.name = modName;
    m.base = chunk->base;
    m.size = chunk->size;
    m.moduleId = 0;

    if(find(pdbIgnores.begin(), pdbIgnores.end(), m.name) != pdbIgnores.end())
    {
      RDCWARN("Not attempting to get symbols for %ls", m.name.c_str());

      modules.push_back(m);
      continue;
    }

    // get default pdb (this also looks up symbol server etc)
    // Always done in unicode
    std::wstring defaultPdb = DIA2::LookupModule(modName, chunk->guid, chunk->age);

    // strip newline
    if(defaultPdb != L"" && defaultPdb[defaultPdb.length() - 1] == '\n')
      defaultPdb.pop_back();

    // if we didn't even get a default pdb we'll have to prompt first time through
    bool failed = false;

    if(defaultPdb == L"")
    {
      defaultPdb = strlower(basename(m.name));

      size_t it = defaultPdb.find(L".dll");
      if(it != wstring::npos)
      {
        defaultPdb[it + 1] = L'p';
        defaultPdb[it + 2] = L'd';
        defaultPdb[it + 3] = L'b';
      }

      it = defaultPdb.find(L".exe");
      if(it != wstring::npos)
      {
        defaultPdb[it + 1] = L'p';
        defaultPdb[it + 2] = L'd';
        defaultPdb[it + 3] = L'b';
      }
      failed = true;
    }

    std::wstring pdbName = defaultPdb;

    int fallbackIdx = -1;

    while(m.moduleId == 0)
    {
      if(failed)
      {
        fallbackIdx++;
        // try one of the folders we've been given, just in case the symbols
        // are there
        if(fallbackIdx < (int)pdbRememberedPaths.size())
        {
          pdbName = pdbRememberedPaths[fallbackIdx] + L"\\" + basename(pdbName);
        }
        else
        {
          pdbName = dirname(defaultPdb) + L"\\" + basename(defaultPdb);

          // prompt for new pdbName, unless it's renderdoc or dbghelp
          if(pdbName.find(L"renderdoc.") != wstring::npos ||
             pdbName.find(L"dbghelp.") != wstring::npos || pdbName.find(L"symsrv.") != wstring::npos)
            pdbName = L"";
          else
            pdbName = pdbBrowse(pdbName);

          // user cancelled, just don't load this pdb
          if(pdbName == L"")
            break;
        }

        failed = false;
      }

      m.moduleId = DIA2::GetModule(pdbName.c_str(), chunk->guid, chunk->age);

      if(m.moduleId == 0)
      {
        failed = true;
      }
      else
      {
        if(fallbackIdx >= (int)pdbRememberedPaths.size())
        {
          wstring dir = dirname(pdbName);
          if(find(pdbRememberedPaths.begin(), pdbRememberedPaths.end(), dir) ==
             pdbRememberedPaths.end())
          {
            pdbRememberedPaths.push_back(dir);
          }
        }
      }
    }

    // didn't load the pdb? go to the next module.
    if(m.moduleId == 0)
    {
      modules.push_back(m);    // still add the module, with 0 module id

      RDCWARN("Couldn't get symbols for %ls", m.name.c_str());

      // silently ignore renderdoc.dll, dbghelp.dll, and symsrv.dll without asking to permanently
      // ignore
      if(m.name.find(L"renderdoc.") != wstring::npos || m.name.find(L"dbghelp.") != wstring::npos ||
         m.name.find(L"symsrv.") != wstring::npos)
        continue;

      wchar_t text[1024];
      wsprintf(text, L"Do you want to permanently ignore this file?\nPath: %ls", m.name.c_str());

      int ret = MessageBoxW(NULL, text, L"Ignore this pdb?", MB_YESNO);

      if(ret == IDYES)
        pdbIgnores.push_back(m.name);

      continue;
    }

    DIA2::SetBaseAddress(m.moduleId, chunk->base);

    RDCLOG("Loaded Symbols for %ls", m.name.c_str());

    modules.push_back(m);
  }

  sort(pdbIgnores.begin(), pdbIgnores.end());
  pdbIgnores.erase(unique(pdbIgnores.begin(), pdbIgnores.end()), pdbIgnores.end());
  merge(pdbIgnores, ignores, L';');
  WritePrivateProfileStringW(L"renderdoc", L"ignores", ignores.c_str(), configPath.c_str());
}
Example #5
0
int
GetLongOpt::parse(int argc, char * const *argv)
{
   int optind = 1;

   pname = strlwr( strdup( basename(*argv) ) );
   enroll_done = 1;
   if ( argc-- <= 1 ) return optind;

   while ( argc >= 1 ) {
      char *token = *++argv; --argc;

      if ( token[0] != optmarker || token[1] == optmarker )
	 break;	/* end of options */

      ++optind;
      char *tmptoken = ++token;
      while ( *tmptoken && *tmptoken != '=' )
	 ++tmptoken;
      /* (tmptoken - token) is now equal to the command line option
	 length. */

      Cell *t;
      enum { NoMatch, ExactMatch, PartialMatch } matchStatus = NoMatch;
      Cell *pc = 0;	// pointer to the partially-matched cell
      for ( t = table; t != 0; t = t->next ) {
	 if ( strncmp(t->option, token, (tmptoken - token)) == 0 ) {
	    if ( strlen(t->option) == (tmptoken - token) ) {
	       /* an exact match found */
	       int stat = setcell(t, tmptoken, *(argv+1), pname);
	       if ( stat == -1 ) return -1;
	       else if ( stat == 1 ) {
		  ++argv; --argc; ++optind;
	       }
	       matchStatus = ExactMatch;
	       break;
	    }
	    else {
	       /* partial match found */
	       matchStatus = PartialMatch;
	       pc = t;
	    }
	 } /* end if */
      } /* end for */

      if ( matchStatus == PartialMatch ) {
	 int stat = setcell(pc, tmptoken, *(argv+1), pname);
	 if ( stat == -1 ) return -1;
	 else if ( stat == 1 ) {
	    ++argv; --argc; ++optind;
	 }
      }
      else if ( matchStatus == NoMatch ) {
	 cout << pname << ": unrecognized option ";
	 cout << optmarker << strtok(token,"= ") << "\n";
	 return -1;		/* no match */
      }

   } /* end while */

   return optind;
}
Example #6
0
int main(int argc, char **argv)
{
	pthread_t sigth;
	sigset_t sigblock;
	int logflags = 0;
	int ret = 1;

	debug_init();

	sigemptyset(&sigblock);
	sigaddset(&sigblock, SIGHUP);
	sigaddset(&sigblock, SIGINT);
	sigaddset(&sigblock, SIGTERM);
#ifdef ENABLE_VT
	sigaddset(&sigblock, SIGPIPE);
#endif
	pthread_sigmask(SIG_BLOCK, &sigblock, NULL);

	if (conf_parse(&conf, argc, argv))
		return 1;

	if (conf.debug_level > 0)
		logflags = LOG_PERROR;

	openlog(basename(argv[0]), LOG_PID|logflags, LOG_DAEMON);

	syslog(LOG_INFO, "%s v%s started (%s)", PACKAGE_NAME, PACKAGE_VERSION,
	       entity_string[conf.mip6_entity]);
#ifdef ENABLE_VT
	if (vt_init() < 0)
		goto vt_failed;
#endif

	/* if not debugging, detach from tty */
	if (conf.debug_level == 0)
		daemon_start(1);
	else {
		/* if debugging with debug log file, detach from tty */
		if (conf.debug_log_file) {
			daemon_start(1);

			ret = debug_open(conf.debug_log_file);
			if (ret < 0) {
				fprintf(stderr, "can't init debug log:%s\n",
					strerror(-ret));
				goto debug_failed;
			}
			dbg("%s started in debug mode\n", PACKAGE_NAME);
		} else {
			dbg("%s started in debug mode, not detaching from terminal\n",
			    PACKAGE_NAME);
		}
		conf_show(&conf);
	}

	srandom(time(NULL));

	if (rr_cn_init() < 0)
		goto rr_cn_failed;
	if (policy_init() < 0)
		goto policy_failed;
	if (taskqueue_init() < 0)
		goto taskqueue_failed;
	if (bcache_init() < 0)
		goto bcache_failed;
	if (mh_init() < 0)
		goto mh_failed;
	if (icmp6_init() < 0)
		goto icmp6_failed;
	if (xfrm_init() < 0)
		goto xfrm_failed;
	cn_init();
	if ((is_ha() || is_mn()) && tunnelctl_init() < 0)
		goto tunnelctl_failed;
	if (is_ha() && ha_init() < 0) 
		goto ha_failed;
	if (is_mn() && mn_init() < 0)
		goto mn_failed;
#ifdef ENABLE_VT
	if (vt_start(conf.vt_hostname, conf.vt_service) < 0)
		goto vt_start_failed;
#endif
	if (pthread_create(&sigth, NULL, sigh, NULL))
		goto sigth_failed;
	pthread_join(sigth, NULL);
	ret = 0;
sigth_failed:
#ifdef ENABLE_VT
	vt_fini();
vt_start_failed:
#endif
	if (is_mn())
		mn_cleanup();
mn_failed:
	if (is_ha())
		ha_cleanup();
ha_failed:
	if (is_ha() || is_mn())
		tunnelctl_cleanup();
tunnelctl_failed:
	cn_cleanup();
	xfrm_cleanup();
xfrm_failed:
	icmp6_cleanup();
icmp6_failed:
	mh_cleanup();
mh_failed:
	bcache_cleanup();
bcache_failed:
	taskqueue_destroy();
taskqueue_failed:
	policy_cleanup();
policy_failed:
rr_cn_failed:
	debug_close();
debug_failed:
#ifdef ENABLE_VT
vt_failed:
#endif
	syslog(LOG_INFO, "%s v%s stopped (%s)", PACKAGE_NAME, PACKAGE_VERSION,
	       entity_string[conf.mip6_entity]);
	closelog();
	return ret;
}
Example #7
0
static int envfs_load_data(struct envfs_super *super, void *buf, size_t size,
		const char *dir, unsigned flags)
{
	int fd, ret = 0;
	char *str, *tmp;
	int headerlen_full;
	/* for envfs < 1.0 */
	struct envfs_inode_end inode_end_dummy;
	struct stat s;

	inode_end_dummy.mode = ENVFS_32(S_IRWXU | S_IRWXG | S_IRWXO);
	inode_end_dummy.magic = ENVFS_32(ENVFS_INODE_END_MAGIC);

	while (size) {
		struct envfs_inode *inode;
		struct envfs_inode_end *inode_end;
		uint32_t inode_size, inode_headerlen, namelen;

		inode = buf;
		buf += sizeof(struct envfs_inode);

		if (ENVFS_32(inode->magic) != ENVFS_INODE_MAGIC) {
			printf("envfs: wrong magic\n");
			ret = -EIO;
			goto out;
		}
		inode_size = ENVFS_32(inode->size);
		inode_headerlen = ENVFS_32(inode->headerlen);
		namelen = strlen(inode->data) + 1;
		if (super->major < 1)
			inode_end = &inode_end_dummy;
		else
			inode_end = buf + PAD4(namelen);

		debug("loading %s size %d namelen %d headerlen %d\n", inode->data,
			inode_size, namelen, inode_headerlen);

		str = concat_path_file(dir, inode->data);

		headerlen_full = PAD4(inode_headerlen);
		buf += headerlen_full;

		if (ENVFS_32(inode_end->magic) != ENVFS_INODE_END_MAGIC) {
			printf("envfs: wrong inode_end_magic\n");
			ret = -EIO;
			goto out;
		}

		tmp = strdup(str);
		make_directory(dirname(tmp));
		free(tmp);

		ret = stat(str, &s);
		if (!ret && (flags & ENV_FLAG_NO_OVERWRITE)) {
			printf("skip %s\n", str);
			goto skip;
		}

		if (S_ISLNK(ENVFS_32(inode_end->mode))) {
			debug("symlink: %s -> %s\n", str, (char*)buf);
			if (!strcmp(buf, basename(str))) {
				unlink(str);
			} else {
				if (!ret)
					unlink(str);

				ret = symlink(buf, str);
				if (ret < 0)
					printf("symlink: %s -> %s : %s\n",
							str, (char*)buf, strerror(-errno));
			}
			free(str);
		} else {
			fd = open(str, O_WRONLY | O_CREAT | O_TRUNC, 0644);
			free(str);
			if (fd < 0) {
				printf("Open %s\n", errno_str());
				ret = fd;
				goto out;
			}

			ret = write(fd, buf, inode_size);
			if (ret < inode_size) {
				perror("write");
				ret = -errno;
				close(fd);
				goto out;
			}
			close(fd);
		}
skip:
		buf += PAD4(inode_size);
		size -= headerlen_full + PAD4(inode_size) +
				sizeof(struct envfs_inode);
	}

	recursive_action(dir, ACTION_RECURSE | ACTION_DEPTHFIRST, NULL,
			dir_remove_action, NULL, 0);

	ret = 0;
out:
	return ret;
}
Example #8
0
int main(int argc, char **argv)
{
    int readonly = 0;
    int growable = 0;
    const char *sopt = "hVc:d:rsnmgkt:T:";
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "offset", 1, NULL, 'o' },
        { "cmd", 1, NULL, 'c' },
        { "read-only", 0, NULL, 'r' },
        { "snapshot", 0, NULL, 's' },
        { "nocache", 0, NULL, 'n' },
        { "misalign", 0, NULL, 'm' },
        { "growable", 0, NULL, 'g' },
        { "native-aio", 0, NULL, 'k' },
        { "discard", 1, NULL, 'd' },
        { "cache", 1, NULL, 't' },
        { "trace", 1, NULL, 'T' },
        { NULL, 0, NULL, 0 }
    };
    int c;
    int opt_index = 0;
    int flags = BDRV_O_UNMAP;

#ifdef CONFIG_POSIX
    signal(SIGPIPE, SIG_IGN);
#endif

    progname = basename(argv[0]);
    qemu_init_exec_dir(argv[0]);

    while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
        switch (c) {
        case 's':
            flags |= BDRV_O_SNAPSHOT;
            break;
        case 'n':
            flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
            break;
        case 'd':
            if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
                error_report("Invalid discard option: %s", optarg);
                exit(1);
            }
            break;
        case 'c':
            add_user_command(optarg);
            break;
        case 'r':
            readonly = 1;
            break;
        case 'm':
            qemuio_misalign = true;
            break;
        case 'g':
            growable = 1;
            break;
        case 'k':
            flags |= BDRV_O_NATIVE_AIO;
            break;
        case 't':
            if (bdrv_parse_cache_flags(optarg, &flags) < 0) {
                error_report("Invalid cache option: %s", optarg);
                exit(1);
            }
            break;
        case 'T':
            if (!trace_backend_init(optarg, NULL)) {
                exit(1); /* error message will have been printed */
            }
            break;
        case 'V':
            printf("%s version %s\n", progname, QEMU_VERSION);
            exit(0);
        case 'h':
            usage(progname);
            exit(0);
        default:
            usage(progname);
            exit(1);
        }
    }

    if ((argc - optind) > 1) {
        usage(progname);
        exit(1);
    }

    qemu_init_main_loop();
    bdrv_init();

    /* initialize commands */
    qemuio_add_command(&quit_cmd);
    qemuio_add_command(&open_cmd);
    qemuio_add_command(&close_cmd);

    if (isatty(STDIN_FILENO)) {
        readline_state = readline_init(readline_printf_func,
                                       readline_flush_func,
                                       NULL,
                                       readline_completion_func);
        qemu_set_tty_echo(STDIN_FILENO, false);
        atexit(reenable_tty_echo);
    }

    /* open the device */
    if (!readonly) {
        flags |= BDRV_O_RDWR;
    }

    if ((argc - optind) == 1) {
        openfile(argv[optind], flags, growable, NULL);
    }
    command_loop();

    /*
     * Make sure all outstanding requests complete before the program exits.
     */
    bdrv_drain_all();

    if (qemuio_bs) {
        bdrv_unref(qemuio_bs);
    }
    g_free(readline_state);
    return 0;
}
Example #9
0
static int do_modinfo(int argc, char *argv[])
{
	struct kmod_ctx *ctx;
	char dirname_buf[PATH_MAX];
	const char *dirname = NULL;
	const char *kversion = NULL;
	const char *root = NULL;
	const char *null_config = NULL;
	int i, err;

	for (;;) {
		int c, idx = 0;
		c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx);
		if (c == -1)
			break;
		switch (c) {
		case 'a':
			field = "author";
			break;
		case 'd':
			field = "description";
			break;
		case 'l':
			field = "license";
			break;
		case 'p':
			field = "parm";
			break;
		case 'n':
			field = "filename";
			break;
		case '0':
			separator = '\0';
			break;
		case 'F':
			field = optarg;
			break;
		case 'k':
			kversion = optarg;
			break;
		case 'b':
			root = optarg;
			break;
		case 'h':
			help(basename(argv[0]));
			return EXIT_SUCCESS;
		case 'V':
			puts(PACKAGE " version " VERSION);
			return EXIT_SUCCESS;
		case '?':
			return EXIT_FAILURE;
		default:
			fprintf(stderr,
				"Error: unexpected getopt_long() value '%c'.\n",
				c);
			return EXIT_FAILURE;
		}
	}

	if (optind >= argc) {
		fprintf(stderr, "Error: missing module or filename.\n");
		return EXIT_FAILURE;
	}

	if (root != NULL || kversion != NULL) {
		struct utsname u;
		if (root == NULL)
			root = "";
		if (kversion == NULL) {
			if (uname(&u) < 0) {
				fprintf(stderr, "Error: uname() failed: %s\n",
					strerror(errno));
				return EXIT_FAILURE;
			}
			kversion = u.release;
		}
		snprintf(dirname_buf, sizeof(dirname_buf), "%s" ROOTPREFIX "/lib/modules/%s",
			 root, kversion);
		dirname = dirname_buf;
	}

	ctx = kmod_new(dirname, &null_config);
	if (!ctx) {
		fputs("Error: kmod_new() failed!\n", stderr);
		return EXIT_FAILURE;
	}
	kmod_load_resources(ctx);

	err = 0;
	for (i = optind; i < argc; i++) {
		const char *name = argv[i];
		struct stat st;
		int r;

		if (stat(name, &st) == 0 && S_ISREG(st.st_mode))
			r = modinfo_path_do(ctx, name);
		else
			r = modinfo_alias_do(ctx, name);

		if (r < 0)
			err = r;
	}

	kmod_unref(ctx);
	return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Example #10
0
MetaData* create_meta_file(char* filePath, char* trackerURL)
{
  char fileName_no_ext[255];
  char tempBuffer[255];
  char metaFilePath[255];
  struct stat fileStats;
  MetaData* newTorrent;
  FILE* filePtr;
  FILE* metaFP;

  newTorrent = malloc(sizeof(MetaData));

  //Get File Name
  memset(tempBuffer, '\0',255);
  strcpy(tempBuffer,filePath);
  strcpy(newTorrent->fileName, basename(tempBuffer));

  char trackerName[255];
  int trackerPort;
  parse_host_info(trackerURL, trackerName, &trackerPort);
  strcpy(newTorrent->trackerName, trackerName);
  newTorrent->trackerPort = trackerPort;

  // Cut off any extension the file may have
  memset(tempBuffer, '\0',255);
  strcpy(tempBuffer, newTorrent->fileName);
  strcpy(fileName_no_ext, strtok(tempBuffer, "."));

  //File Size
  stat(filePath, &fileStats);
  newTorrent->fileSize = fileStats.st_size;

  //Calculate # of Segments
  newTorrent->numSegments = newTorrent->fileSize / SEGMENT_SIZE;
  if( (newTorrent->fileSize % SEGMENT_SIZE) > 0)
  {
    // Add an extra segment for the remainder
    newTorrent->numSegments ++;
  }
  
  //Create new meta file for writing
  //For simplicity just create the meta file in the current directory
  sprintf(metaFilePath, "./%s%s",fileName_no_ext, META_EXTENSION);
  metaFP = fopen(metaFilePath, "w");
  
  //write the meta file
  fprintf(metaFP, "%s\n%s:%i\n%lu\n%lu\n%i\n",newTorrent->fileName, newTorrent->trackerName, newTorrent->trackerPort, newTorrent->fileSize, newTorrent->numSegments, SEGMENT_SIZE);

  //Open the file
  filePtr = fopen(filePath, "r");

  //Calculate Hash
  newTorrent->hash = generate_hash_from_file(filePtr, newTorrent->numSegments);
  fclose(filePtr);

  //write the hash to the meta file
  int i;
  for(i = 0; i < newTorrent->numSegments; i++)
  {
    fprintf(metaFP, "%s\n", newTorrent->hash[i]);
  }
  fclose(metaFP);

  return newTorrent;
}
Example #11
0
int main(int argc, char *argv[])
{
	bool lrzcat = false, compat = false, recurse = false;
	struct timeval start_time, end_time;
	struct sigaction handler;
	double seconds,total_time; // for timers
	int c, i;
	int hours,minutes;
	extern int optind;
	char *eptr, *av; /* for environment */

        control = &base_control;

	initialise_control(control);

	av = basename(argv[0]);
	if (!strcmp(av, "lrunzip"))
		control->flags |= FLAG_DECOMPRESS;
	else if (!strcmp(av, "lrzcat")) {
		control->flags |= FLAG_DECOMPRESS | FLAG_STDOUT;
		lrzcat = true;
	} else if (!strcmp(av, "lrz")) {
		/* Called in gzip compatible command line mode */
		control->flags &= ~FLAG_SHOW_PROGRESS;
		control->nice_val = 0;
		control->flags &= ~FLAG_KEEP_FILES;
		compat = true;
		long_options[1].name = "stdout";
		long_options[11].name = "keep";
	}

	/* generate crc table */
	CrcGenerateTable();

	/* Get Preloaded Defaults from lrzip.conf
	 * Look in ., $HOME/.lrzip/, /etc/lrzip.
	 * If LRZIP=NOCONFIG is set, then ignore config
	 */
	eptr = getenv("LRZIP");
	if (eptr == NULL)
		read_config(control);
	else if (!strstr(eptr,"NOCONFIG"))
		read_config(control);

	while ((c = getopt_long(argc, argv, compat ? coptions : loptions, long_options, &i)) != -1) {
		switch (c) {
		case 'b':
			if (control->flags & FLAG_NOT_LZMA)
				failure("Can only use one of -l, -b, -g, -z or -n\n");
			control->flags |= FLAG_BZIP2_COMPRESS;
			break;
		case 'c':
			if (compat) {
				control->flags |= FLAG_KEEP_FILES;
				set_stdout(control);
				break;
			}
		case 'C':
			control->flags |= FLAG_CHECK;
			control->flags |= FLAG_HASH;
			break;
		case 'd':
			control->flags |= FLAG_DECOMPRESS;
			break;
		case 'D':
			control->flags &= ~FLAG_KEEP_FILES;
			break;
		case 'e':
			control->flags |= FLAG_ENCRYPT;
			break;
		case 'f':
			control->flags |= FLAG_FORCE_REPLACE;
			break;
		case 'g':
			if (control->flags & FLAG_NOT_LZMA)
				failure("Can only use one of -l, -b, -g, -z or -n\n");
			control->flags |= FLAG_ZLIB_COMPRESS;
			break;
		case 'h':
		case '?':
			usage(compat);
			return -1;
		case 'H':
			control->flags |= FLAG_HASH;
			break;
		case 'i':
			control->flags |= FLAG_INFO;
			break;
		case 'k':
			if (compat) {
				control->flags |= FLAG_KEEP_FILES;
				break;
			}
		case 'K':
			control->flags |= FLAG_KEEP_BROKEN;
			break;
		case 'l':
			if (control->flags & FLAG_NOT_LZMA)
				failure("Can only use one of -l, -b, -g, -z or -n\n");
			control->flags |= FLAG_LZO_COMPRESS;
			break;
		case 'L':
			if (compat) {
				license();
				exit(0);
			}
			control->compression_level = atoi(optarg);
			if (control->compression_level < 1 || control->compression_level > 9)
				failure("Invalid compression level (must be 1-9)\n");
			break;
		case 'm':
			control->ramsize = atol(optarg) * 1024 * 1024 * 100;
			break;
		case 'n':
			if (control->flags & FLAG_NOT_LZMA)
				failure("Can only use one of -l, -b, -g, -z or -n\n");
			control->flags |= FLAG_NO_COMPRESS;
			break;
		case 'N':
			control->nice_val = atoi(optarg);
			if (control->nice_val < -20 || control->nice_val > 19)
				failure("Invalid nice value (must be -20..19)\n");
			break;
		case 'o':
			if (control->outdir)
				failure("Cannot have -o and -O together\n");
			if (unlikely(STDOUT))
				failure("Cannot specify an output filename when outputting to stdout\n");
			control->outname = optarg;
			control->suffix = "";
			break;
		case 'O':
			if (control->outname)	/* can't mix -o and -O */
				failure("Cannot have options -o and -O together\n");
			if (unlikely(STDOUT))
				failure("Cannot specify an output directory when outputting to stdout\n");
			control->outdir = malloc(strlen(optarg) + 2);
			if (control->outdir == NULL)
				fatal("Failed to allocate for outdir\n");
			strcpy(control->outdir,optarg);
			if (strcmp(optarg+strlen(optarg) - 1, "/")) 	/* need a trailing slash */
				strcat(control->outdir, "/");
			break;
		case 'p':
			control->threads = atoi(optarg);
			if (control->threads < 1)
				failure("Must have at least one thread\n");
			break;
		case 'P':
			control->flags |= FLAG_SHOW_PROGRESS;
			break;
		case 'q':
			control->flags &= ~FLAG_SHOW_PROGRESS;
			break;
		case 'r':
			recurse = true;
			break;
		case 'S':
			if (control->outname)
				failure("Specified output filename already, can't specify an extension.\n");
			if (unlikely(STDOUT))
				failure("Cannot specify a filename suffix when outputting to stdout\n");
			control->suffix = optarg;
			break;
		case 't':
			if (control->outname)
				failure("Cannot specify an output file name when just testing.\n");
			if (compat)
				control->flags |= FLAG_KEEP_FILES;
			if (!KEEP_FILES)
				failure("Doubt that you want to delete a file when just testing.\n");
			control->flags |= FLAG_TEST_ONLY;
			break;
		case 'T':
			control->flags &= ~FLAG_THRESHOLD;
			break;
		case 'U':
			control->flags |= FLAG_UNLIMITED;
			break;
		case 'v':
			/* set verbosity flag */
			if (!(control->flags & FLAG_SHOW_PROGRESS))
				control->flags |= FLAG_SHOW_PROGRESS;
			else if (!(control->flags & FLAG_VERBOSITY) && !(control->flags & FLAG_VERBOSITY_MAX))
				control->flags |= FLAG_VERBOSITY;
			else if ((control->flags & FLAG_VERBOSITY)) {
				control->flags &= ~FLAG_VERBOSITY;
				control->flags |= FLAG_VERBOSITY_MAX;
			}
			break;
		case 'V':
			print_output("lrzip version %s\n", PACKAGE_VERSION);
			exit(0);
			break;
		case 'w':
			control->window = atol(optarg);
			break;
		case 'z':
			if (control->flags & FLAG_NOT_LZMA)
				failure("Can only use one of -l, -b, -g, -z or -n\n");
			control->flags |= FLAG_ZPAQ_COMPRESS;
			break;
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			control->compression_level = c - '0';
			break;
		}
	}

	argc -= optind;
	argv += optind;

	if (control->outname) {
		if (argc > 1)
			failure("Cannot specify output filename with more than 1 file\n");
		if (recurse)
			failure("Cannot specify output filename with recursive\n");
	}

	if (VERBOSE && !SHOW_PROGRESS) {
		print_err("Cannot have -v and -q options. -v wins.\n");
		control->flags |= FLAG_SHOW_PROGRESS;
	}

	if (UNLIMITED && control->window) {
		print_err("If -U used, cannot specify a window size with -w.\n");
		control->window = 0;
	}

	if (argc < 1)
		control->flags |= FLAG_STDIN;

	if (UNLIMITED && STDIN) {
		print_err("Cannot have -U and stdin, unlimited mode disabled.\n");
		control->flags &= ~FLAG_UNLIMITED;
	}

	setup_overhead(control);

	/* Set the main nice value to half that of the backend threads since
	 * the rzip stage is usually the rate limiting step */
	if (control->nice_val > 0 && !NO_COMPRESS) {
		if (unlikely(setpriority(PRIO_PROCESS, 0, control->nice_val / 2) == -1))
			print_err("Warning, unable to set nice value\n");
	} else {
		if (unlikely(setpriority(PRIO_PROCESS, 0, control->nice_val) == -1))
			print_err("Warning, unable to set nice value\n");
	}

	/* One extra iteration for the case of no parameters means we will default to stdin/out */
	for (i = 0; i <= argc; i++) {
		char *dirlist = NULL, *infile = NULL;
		int direntries = 0, curentry = 0;

		if (i < argc)
			infile = argv[i];
		else if (!(i == 0 && STDIN))
			break;
		if (infile) {
			if ((strcmp(infile, "-") == 0))
				control->flags |= FLAG_STDIN;
			else {
				bool isdir = false;
				struct stat istat;

				if (unlikely(stat(infile, &istat)))
					failure("Failed to stat %s\n", infile);
				isdir = S_ISDIR(istat.st_mode);
				if (!recurse && (isdir || !S_ISREG(istat.st_mode))) {
					failure("lrzip only works directly on regular FILES.\n"
					"Use -r recursive, lrztar or pipe through tar for compressing directories.\n");
				}
				if (recurse && !isdir)
					failure("%s not a directory, -r recursive needs a directory\n", infile);
			}
		}

		if (recurse) {
			if (unlikely(STDIN || STDOUT))
				failure("Cannot use -r recursive with STDIO\n");
			recurse_dirlist(infile, &dirlist, &direntries);
		}

		if (INFO && STDIN)
			failure("Will not get file info from STDIN\n");
recursion:
		if (recurse) {
			if (curentry >= direntries) {
				infile = NULL;
				continue;
			}
			infile = dirlist + MAX_PATH_LEN * curentry++;
		}
		control->infile = infile;

		/* If no output filename is specified, and we're using
		 * stdin, use stdout */
		if ((control->outname && (strcmp(control->outname, "-") == 0)) ||
		    (!control->outname && STDIN) || lrzcat)
				set_stdout(control);

		if (lrzcat) {
			control->msgout = stderr;
			control->outFILE = stdout;
			register_outputfile(control, control->msgout);
		}

		if (!STDOUT) {
			control->msgout = stdout;
			register_outputfile(control, control->msgout);
		}

		if (STDIN)
			control->inFILE = stdin;
		/* Implement signal handler only once flags are set */
		sigemptyset(&handler.sa_mask);
		handler.sa_flags = 0;
		handler.sa_handler = &sighandler;
		sigaction(SIGTERM, &handler, 0);
		sigaction(SIGINT, &handler, 0);

		if (!FORCE_REPLACE) {
			if (STDIN && isatty(fileno((FILE *)stdin))) {
				print_err("Will not read stdin from a terminal. Use -f to override.\n");
				usage(compat);
				exit (1);
			}
			if (!TEST_ONLY && STDOUT && isatty(fileno((FILE *)stdout)) && !compat) {
				print_err("Will not write stdout to a terminal. Use -f to override.\n");
				usage(compat);
				exit (1);
			}
		}

		if (CHECK_FILE) {
			if (!DECOMPRESS) {
				print_err("Can only check file written on decompression.\n");
				control->flags &= ~FLAG_CHECK;
			} else if (STDOUT) {
				print_err("Can't check file written when writing to stdout. Checking disabled.\n");
				control->flags &= ~FLAG_CHECK;
			}
		}

		setup_ram(control);
		show_summary();

		gettimeofday(&start_time, NULL);

		if (unlikely(STDIN && ENCRYPT))
			failure("Unable to work from STDIN while reading password\n");

		memcpy(&local_control, &base_control, sizeof(rzip_control));
		if (DECOMPRESS || TEST_ONLY)
			decompress_file(&local_control);
		else if (INFO)
			get_fileinfo(&local_control);
		else
			compress_file(&local_control);

		/* compute total time */
		gettimeofday(&end_time, NULL);
		total_time = (end_time.tv_sec + (double)end_time.tv_usec / 1000000) -
			      (start_time.tv_sec + (double)start_time.tv_usec / 1000000);
		hours = (int)total_time / 3600;
		minutes = (int)(total_time / 60) % 60;
		seconds = total_time - hours * 3600 - minutes * 60;
		if (!INFO)
			print_progress("Total time: %02d:%02d:%05.2f\n", hours, minutes, seconds);
		if (recurse)
			goto recursion;
	}

	return 0;
}
Example #12
0
int
pkg_perform(char **pkgs)
{
    static const char *home;
    char *pkg = *pkgs;		/* Only one arg to create */
    char *cp;
    FILE *pkg_in, *fp;
    Package plist;
    int len;
    const char *suf;

    /* Preliminary setup */
    if (InstalledPkg == NULL)
	sanity_check();
    if (Verbose && !PlistOnly)
	printf("Creating package %s\n", pkg);

    /* chop suffix off if already specified, remembering if we want to compress  */
    len = strlen(pkg);
    if (len > 4) {
	if (!strcmp(&pkg[len - 4], ".tbz")) {
	    Zipper = BZIP2;
	    pkg[len - 4] = '\0';
	}
	else if (!strcmp(&pkg[len - 4], ".tgz")) {
	    Zipper = GZIP;
	    pkg[len - 4] = '\0';
	}
	else if (!strcmp(&pkg[len - 4], ".txz")) {
	    Zipper = XZ;
	    pkg[len - 4] = '\0';
	}
	else if (!strcmp(&pkg[len - 4], ".tar")) {
	    Zipper = NONE;
	    pkg[len - 4] = '\0';
	}
    }
    if (Zipper == BZIP2) {
	suf = "tbz";
	setenv("BZIP2", "--best", 0);
    } else if (Zipper == GZIP) {
	suf = "tgz";
	setenv("GZIP", "-9", 0);
    } else if (Zipper == XZ) {
	suf = "txz";
    } else
	suf = "tar";

    if (InstalledPkg != NULL) {
	char *pkgglob[] = { InstalledPkg, NULL };
	char **matched, **pkgs;
	int i, error;

	pkgs = pkgglob;
	if (MatchType != MATCH_EXACT) {
		matched = matchinstalled(MatchType, pkgs, &error);
		if (!error && matched != NULL)
			pkgs = matched;
		else if (MatchType != MATCH_GLOB)
	    		errx(1, "no packages match pattern");
	}
	/*
	 * Is there is only one installed package matching the pattern,
	 * we need to respect the optional pkg-filename parameter.  If,
	 * however, the pattern matches several packages, this parameter
	 * makes no sense and is ignored.
	 */
	if (pkgs[1] == NULL) {
	    if (pkg == InstalledPkg)
		pkg = *pkgs;
	    InstalledPkg = *pkgs;
	    if (!Recursive)
		return (create_from_installed(InstalledPkg, pkg, suf));
	    return (create_from_installed_recursive(pkg, suf));
	}
	for (i = 0; pkgs[i] != NULL; i++) {
	    InstalledPkg = pkg = pkgs[i];
	    if (!Recursive)
		create_from_installed(pkg, pkg, suf);
	    else
	        create_from_installed_recursive(pkg, suf);
	}
	return TRUE;
    }

    get_dash_string(&Comment);
    get_dash_string(&Desc);
    if (!strcmp(Contents, "-"))
	pkg_in = stdin;
    else {
	pkg_in = fopen(Contents, "r");
	if (!pkg_in) {
	    cleanup(0);
	    errx(2, "%s: unable to open contents file '%s' for input",
		__func__, Contents);
	}
    }
    plist.head = plist.tail = NULL;

    /* Stick the dependencies, if any, at the top */
    if (Pkgdeps) {
	char **deps, *deporigin;
	int i;
	int ndeps = 0;

	if (Verbose && !PlistOnly)
	    printf("Registering depends:");

	/* Count number of dependencies */
	for (cp = Pkgdeps; cp != NULL && *cp != '\0';
			   cp = strpbrk(++cp, " \t\n")) {
	    ndeps++;
	}

	if (ndeps != 0) {
	    /* Create easy to use NULL-terminated list */
	    deps = alloca(sizeof(*deps) * ndeps + 1);
	    if (deps == NULL) {
		errx(2, "%s: alloca() failed", __func__);
		/* Not reached */
	    }
	    for (i = 0; Pkgdeps;) {
		cp = strsep(&Pkgdeps, " \t\n");
		if (*cp) {
		    deps[i] = cp;
		    i++;
		}
	    }
	    ndeps = i;
	    deps[ndeps] = NULL;

	    sortdeps(deps);
	    for (i = 0; i < ndeps; i++) {
		deporigin = strchr(deps[i], ':');
		if (deporigin != NULL) {
		    *deporigin = '\0';
		    add_plist_top(&plist, PLIST_DEPORIGIN, ++deporigin);
		}
		add_plist_top(&plist, PLIST_PKGDEP, deps[i]);
		if (Verbose && !PlistOnly)
		    printf(" %s", deps[i]);
	    }
	}

	if (Verbose && !PlistOnly)
	    printf(".\n");
    }

    /* Put the conflicts directly after the dependencies, if any */
    if (Conflicts) {
	if (Verbose && !PlistOnly)
	    printf("Registering conflicts:");
	while (Conflicts) {
	   cp = strsep(&Conflicts, " \t\n");
	   if (*cp) {
		add_plist(&plist, PLIST_CONFLICTS, cp);
		if (Verbose && !PlistOnly)
		    printf(" %s", cp);
	   }
	}
	if (Verbose && !PlistOnly)
	    printf(".\n");
    }

    /* If a SrcDir override is set, add it now */
    if (SrcDir) {
	if (Verbose && !PlistOnly)
	    printf("Using SrcDir value of %s\n", SrcDir);
	add_plist(&plist, PLIST_SRC, SrcDir);
    }

    /* Slurp in the packing list */
    read_plist(&plist, pkg_in);

    /* Prefix should add an @cwd to the packing list */
    if (Prefix) {
	if (Prefix[0] != '/') {
		char resolved_prefix[PATH_MAX];
		if (realpath(Prefix, resolved_prefix) == NULL)
		    err(EXIT_FAILURE, "couldn't resolve path for prefix: %s", Prefix);
		add_plist_top(&plist, PLIST_CWD, resolved_prefix);
	} else {
		add_plist_top(&plist, PLIST_CWD, Prefix);
	}
    }

    /* Add the origin if asked, at the top */
    if (Origin)
	add_plist_top(&plist, PLIST_ORIGIN, Origin);

    /*
     * Run down the list and see if we've named it, if not stick in a name
     * at the top.
     */
    if (find_plist(&plist, PLIST_NAME) == NULL)
	add_plist_top(&plist, PLIST_NAME, basename(pkg));

    if (asprintf(&cp, "PKG_FORMAT_REVISION:%d.%d", PLIST_FMT_VER_MAJOR,
		 PLIST_FMT_VER_MINOR) == -1) {
	errx(2, "%s: asprintf() failed", __func__);
    }
    add_plist_top(&plist, PLIST_COMMENT, cp);
    free(cp);

    /*
     * We're just here for to dump out a revised plist for the FreeBSD ports
     * hack.  It's not a real create in progress.
     */
    if (PlistOnly) {
	check_list(home, &plist);
	write_plist(&plist, stdout);
	exit(0);
    }

    /* Make a directory to stomp around in */
    home = make_playpen(PlayPen, 0);
    signal(SIGINT, cleanup);
    signal(SIGHUP, cleanup);

    /* Make first "real contents" pass over it */
    check_list(home, &plist);
    (void) umask(022);	/*
			 * Make sure gen'ed directories, files don't have
			 * group or other write bits.
			 */
    /* copy_plist(home, &plist); */
    /* mark_plist(&plist); */

    /* Now put the release specific items in */
    if (!Prefix) {
	add_plist(&plist, PLIST_CWD, ".");
    }
    write_file(COMMENT_FNAME, Comment);
    add_plist(&plist, PLIST_IGNORE, NULL);
    add_plist(&plist, PLIST_FILE, COMMENT_FNAME);
    add_cksum(&plist, plist.tail, COMMENT_FNAME);
    write_file(DESC_FNAME, Desc);
    add_plist(&plist, PLIST_IGNORE, NULL);
    add_plist(&plist, PLIST_FILE, DESC_FNAME);
    add_cksum(&plist, plist.tail, DESC_FNAME);

    if (Install) {
	copy_file(home, Install, INSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, INSTALL_FNAME);
	add_cksum(&plist, plist.tail, INSTALL_FNAME);
    }
    if (PostInstall) {
	copy_file(home, PostInstall, POST_INSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, POST_INSTALL_FNAME);
	add_cksum(&plist, plist.tail, POST_INSTALL_FNAME);
    }
    if (DeInstall) {
	copy_file(home, DeInstall, DEINSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, DEINSTALL_FNAME);
	add_cksum(&plist, plist.tail, DEINSTALL_FNAME);
    }
    if (PostDeInstall) {
	copy_file(home, PostDeInstall, POST_DEINSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, POST_DEINSTALL_FNAME);
	add_cksum(&plist, plist.tail, POST_DEINSTALL_FNAME);
    }
    if (Require) {
	copy_file(home, Require, REQUIRE_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, REQUIRE_FNAME);
	add_cksum(&plist, plist.tail, REQUIRE_FNAME);
    }
    if (Display) {
	copy_file(home, Display, DISPLAY_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, DISPLAY_FNAME);
	add_cksum(&plist, plist.tail, DISPLAY_FNAME);
	add_plist(&plist, PLIST_DISPLAY, DISPLAY_FNAME);
    }
    if (Mtree) {
	copy_file(home, Mtree, MTREE_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, MTREE_FNAME);
	add_cksum(&plist, plist.tail, MTREE_FNAME);
	add_plist(&plist, PLIST_MTREE, MTREE_FNAME);
    }

    /* Finally, write out the packing list */
    fp = fopen(CONTENTS_FNAME, "w");
    if (!fp) {
	cleanup(0);
	errx(2, "%s: can't open file %s for writing",
	    __func__, CONTENTS_FNAME);
    }
    write_plist(&plist, fp);
    if (fclose(fp)) {
	cleanup(0);
	errx(2, "%s: error while closing %s",
	    __func__, CONTENTS_FNAME);
    }

    /* And stick it into a tar ball */
    make_dist(home, pkg, suf, &plist);

    /* Cleanup */
    free(Comment);
    free(Desc);
    free_plist(&plist);
    leave_playpen();
    return TRUE;	/* Success */
}
Example #13
0
/*@-boundswrite@*/
static int buildForTarget(rpmts ts, BTA_t ba)
	/*@globals rpmGlobalMacroContext, h_errno, fileSystem, internalState @*/
	/*@modifies ts, rpmGlobalMacroContext, fileSystem, internalState @*/
{
    const char * passPhrase = ba->passPhrase;
    const char * cookie = ba->cookie;
    int buildAmount = ba->buildAmount;
    const char * specFile = NULL;
    const char * specURL = NULL;
    int specut;
    const char * s;
    char * se;
    const char * arg = ba->specFile;
    size_t nb = strlen(arg) + BUFSIZ;
    char * buf = alloca(nb);
    Spec spec = NULL;
    int verify = ((ba->buildAmount & RPMBUILD_TRACK) ? 0 : 1);
    int xx;
    int rc;

    if (ba->buildMode == 't') {
	static const char * sfpats[] = { "Specfile", "\\*.spec", NULL };
	static const char _specfn[] = "%{mkstemp:%{_specdir}/rpm-spec.XXXXXX}";
	char * tmpSpecFile = (char *) rpmGetPath(_specfn, NULL);
	FILE *fp;
	int bingo = 0;
	int i;

	for (i = 0; sfpats[i]; i++) {
	    se = rpmExpand("%{uncompress: %{u2p:", arg, "}}",
		" | %{__tar} -xOvf - %{?__tar_wildcards} ", sfpats[i],
		" 2>&1 > '", tmpSpecFile, "'", NULL);
	    fp = popen(se, "r");
	    se = _free(se);
	    if (fp== NULL)
		continue;
	    s = fgets(buf, nb - 1, fp);
	    xx = pclose(fp);
	    if (!s || !*s || strstr(s, ": Not found in archive"))
		continue;
	    bingo = 1;
	    break;
	}
	if (!bingo) {
	    rpmlog(RPMLOG_ERR, _("Failed to read spec file from %s\n"), arg);
	    xx = Unlink(tmpSpecFile);
	    tmpSpecFile = _free(tmpSpecFile);
	    return 1;
	}

	s = se = basename(buf);
	se += strlen(se);
	while (--se > s && strchr("\r\n", *se) != NULL)
	    *se = '\0';
	specURL = rpmGetPath("%{_specdir}/", s, NULL);
	specut = urlPath(specURL, &specFile);
	xx = Rename(tmpSpecFile, specFile);
	if (xx) {
	    rpmlog(RPMLOG_ERR, _("Failed to rename %s to %s: %m\n"),
			tmpSpecFile, s);
	    (void) Unlink(tmpSpecFile);
	}
	tmpSpecFile = _free(tmpSpecFile);
	if (xx)
	    return 1;

	se = buf; *se = '\0';
	se = stpcpy(se, "_sourcedir ");
	(void) urlPath(arg, &s);
	if (*s != '/') {
	    if (getcwd(se, nb - sizeof("_sourcedir ")) != NULL)
		se += strlen(se);
	    else
		se = stpcpy(se, ".");
	} else
	    se = stpcpy(se, dirname(strcpy(se, s)));
	while (se > buf && se[-1] == '/')
	    *se-- = '0';
	rpmCleanPath(buf + sizeof("_sourcedir ") - 1);
	rpmDefineMacro(NULL, buf, RMIL_TARBALL);
    } else {
	specut = urlPath(arg, &s);
	se = buf; *se = '\0';
	if (*s != '/') {
	    if (getcwd(se, nb - sizeof("_sourcedir ")) != NULL)
		se += strlen(se);
	    else
		se = stpcpy(se, ".");
	    *se++ = '/';
	    se += strlen(strcpy(se,strcpy(se, s)));
	} else
	    se = stpcpy(se, s);
	specURL = rpmGetPath(buf, NULL);
	specut = urlPath(specURL, &specFile);
    }

    if (specut != URL_IS_DASH) {
	struct stat sb;
	if (Stat(specURL, &sb) < 0) {
	    rpmlog(RPMLOG_ERR, _("failed to stat %s: %m\n"), specURL);
	    rc = 1;
	    goto exit;
	}
	if (! S_ISREG(sb.st_mode)) {
	    rpmlog(RPMLOG_ERR, _("File %s is not a regular file.\n"),
		specURL);
	    rc = 1;
	    goto exit;
	}

	/* Try to verify that the file is actually a specfile */
	if (!isSpecFile(specURL)) {
	    rpmlog(RPMLOG_ERR,
		_("File %s does not appear to be a specfile.\n"), specURL);
	    rc = 1;
	    goto exit;
	}
    }
    
    /* Parse the spec file */
#define	_anyarch(_f)	\
(((_f)&(RPMBUILD_PREP|RPMBUILD_BUILD|RPMBUILD_INSTALL|RPMBUILD_PACKAGEBINARY)) == 0)
    if (parseSpec(ts, specURL, ba->rootdir, 0, passPhrase,
		cookie, _anyarch(buildAmount), 0, verify))
    {
	rc = 1;
	goto exit;
    }
#undef	_anyarch
    if ((spec = rpmtsSetSpec(ts, NULL)) == NULL) {
	rc = 1;
	goto exit;
    }

    /* Assemble source header from parsed components */
    xx = initSourceHeader(spec, NULL);

    /* Check build prerequisites */
    if (!ba->noDeps && checkSpec(ts, spec->sourceHeader)) {
	rc = 1;
	goto exit;
    }

    if (buildSpec(ts, spec, buildAmount, ba->noBuild)) {
	rc = 1;
	goto exit;
    }
    
    if (ba->buildMode == 't')
	(void) Unlink(specURL);
    rc = 0;

exit:
    spec = freeSpec(spec);
    specURL = _free(specURL);
    return rc;
}
Example #14
0
int main(int argc, char **argv)
{
    /* Program options */
    static int help;
    static int version;
    static double lower_bound = 0./0.; /* NaN */
    static double upper_bound = 0./0.;
    static char stat_type = 'm';
    static int round_output = 0;
    static int floor_output = 0;
    static int minute_output = 0;

    double file_age;
    int check_upper,
        check_lower;
    int i;

    /* TODO: maybe change minutes / round / floor / trunc to -f "1.3m" -f "3.4s", etc */
    struct soption opttable[] = {
        { 'h', "help",    0, capture_presence,    &help },
        { 'v', "version", 0, capture_presence,    &version },
        { 'o', "older",   1, capture_duration,    &lower_bound },
        { 'n', "newer",   1, capture_duration,    &upper_bound },
        { 'a', "access",  0, capture_a,           &stat_type },
        { 'm', "modify",  0, capture_m,           &stat_type },
        { 'c', "change",  0, capture_c,           &stat_type },
        { 0,   "round",   0, capture_presence,    &round_output },
        { 0,   "floor",   0, capture_presence,    &floor_output },
        { 0,   "trunc",   0, capture_presence,    &floor_output },
        { 0,   "minutes", 0, capture_presence,    &minute_output },
        { 0,   0,         0, 0,                   0 }
    };

    if (sgetopt(argc, argv, opttable, argv+1, 0)) {
        fprintf(stderr,"%s: error parsing one of the command line options\n", basename(argv[0]));
        return 1;
    }

    if (help) {
        char *progname = basename(argv[0]);
        printf("Usage: %s [options] parameters...\n"
               "  check source or manpage `man %s' for details.\n", progname, progname);
        return 0;
    }

    if (version) {
        print_version(basename(argv[0]));
        return 0;
    }

    check_upper = upper_bound == upper_bound; /* != NaN */
    check_lower = lower_bound == lower_bound; /* != NaN */

    for (i=1; argv[i]; i++) {
        file_age = stat_age(argv[i],stat_type);
        if (file_age != file_age /* NaN */) {
            fprintf(stderr,"%s: error, unable to retrieve `%s' attributes\n", basename(argv[0]), argv[i]);
            return 1;
        }

        if (check_upper || check_lower) {
            if ((check_upper && file_age > upper_bound) ||
                    (check_lower && file_age < lower_bound))
                return 1;
        } else {
            if (minute_output)
                file_age /= 60.0;
            if (floor_output)
                file_age = floor(file_age);
            else if (round_output)
                file_age = round(file_age);
            printf(round_output || floor_output ? "%.0lf\n" : "%lf\n", file_age);
        }
    }

    return 0;
}
Example #15
0
/* Initialise dirfile */
void InitialiseDirFile(int reset, unsigned long offset)
{
  dtrace("%i, %lu", reset, offset);
  FILE* fp;
  int fd;
  int j, i, is_bolo = 0;
#if DAS_CARDS > 0
  char field[FIELD_LEN];
  int bolo_node;
  char first_bolo_buf[16];
#endif
  char gpb[GPB_LEN];
  char ext[4] = "";

  fc = 0;

#ifdef HAVE_LIBZ
  if (rc.gzip_output) {
    defileclose = &gzclose;
    strcpy(ext, ".gz");
  } else
#endif
    defileclose = &close;

  rc.resume_at = -1;

  if (mkdir(rc.dirfile, 00755) < 0)
    if (!CheckWriteAllow(errno))
      berror(fatal, "cannot create dirfile `%s'", rc.dirfile);

  bprintf(info, "\nWriting to dirfile `%s'\n", rc.dirfile);

  rc.dirname = strdup(rc.dirfile);
  snprintf(rc.dirname, strlen(rc.dirfile), "%s", basename(rc.dirfile));

  for (i = 0; i < FAST_PER_SLOW + 10; ++i) {
    pre_buffer[i] = balloc(fatal, DiskFrameSize);
    pre_buffer[i][3] = i;
  }

  /* Reset the PreBuffer */
  PreBuffer(NULL);

  for (i = 0; i < FAST_PER_SLOW; ++i)
    fast_frame[i] = balloc(fatal, DiskFrameSize);

  /***********************************
   * create and fill the format file *
   ***********************************/
  sprintf(gpb, "%s/format", rc.dirfile);

  if ((fd = creat(gpb, 0666)) < 0)
    berror(fatal, "cannot create format file `%s/format'", rc.dirfile);

  PathSplit_r(rc.dirfile, NULL, gpb);

  WriteFormatFile(fd, atoi(gpb), offset / FAST_PER_SLOW);

#ifdef __SPIDER__
  if (rc.extra_format) {
    sprintf(gpb, "/INCLUDE /data/etc/spider/format.mce_mplex\n"
        "/INCLUDE /data/etc/spider/format.bolo_stats\n");
    if (write(fd, gpb, strlen(gpb)) < 0)
      berror(err, "Error writing to format file\n");
  }
#else
  /* no extra format for BLAST */
#endif

  if (close(fd) < 0)
    berror(fatal, "Error while closing format file");

  /* DEFILE_FLAGS */
  sprintf(gpb, "%s/DEFILE_FLAGS%s", rc.dirfile, ext);
  defile_field.size = 1;
  defile_field.fp = OpenField(1, 1, gpb);
  defile_field.i0 = 1;
  if (reset) {
    if (rc.resume_at > 0)
      defile_field.nw = rc.resume_at;
    else
      defile_field.nw = 0;
  }
  defile_field.i_in = defile_field.i_out = 0;
  defile_field.b = balloc(fatal, MAXBUF * sizeof(unsigned short));

  /* FASTSAMP */
  sprintf(gpb, "%s/FASTSAMP%s", rc.dirfile, ext);
  normal_fast[0].size = 2;

  normal_fast[0].fp = OpenField(1, 2, gpb);
  normal_fast[0].i0 = 1;
  if (reset) {
    if (rc.resume_at > 0)
      normal_fast[0].nw = rc.resume_at;
    else
      normal_fast[0].nw = 0;
  }

  normal_fast[0].i_in = normal_fast[0].i_out = 0;
  normal_fast[0].b = balloc(fatal, MAXBUF * sizeof(unsigned int));

  n_fast = 1;  //original form

  /* slow chs */
  for (i = 0; i < slowsPerBi0Frame; i++) {
    for (j = 0; j < FAST_PER_SLOW; j++) {
      if (strlen(SlowChList[i][j].field) > 0) {
        slow_fields[j][i].size = FieldSize(SlowChList[i][j].type,
            SlowChList[i][j].field);

        sprintf(gpb, "%s/%s%s", rc.dirfile, SlowChList[i][j].field, ext);
        slow_fields[j][i].fp = OpenField(0, slow_fields[j][i].size, gpb);
      } else
        slow_fields[j][i].fp = -1;

      slow_fields[j][i].i_in = slow_fields[j][i].i_out = 0;
      if (reset) {
        if (rc.resume_at > 0)
          slow_fields[j][i].nw = rc.resume_at / FAST_PER_SLOW;
        else
          slow_fields[j][i].nw = 0;
      }

      slow_fields[j][i].b = balloc(fatal, 2 * MAXBUF);

      slow_fields[j][i].i0 = SLOW_OFFSET + i;
    }
  }

  /* normal fast chs */

#if DAS_CARDS > 0
  sprintf(first_bolo_buf, "n%02dc00lo", DAS_START+1);
#endif
  for (i = 0; i < ccFast + ccWideFast; i++) {
#if DAS_CARDS > 0
    if (strcmp(FastChList[i].field, first_bolo_buf) == 0) {
      bolo_i0 = i + SLOW_OFFSET + slowsPerBi0Frame;
      is_bolo = 1;
    } else if (ccDecom > 0 && strcmp(FastChList[i].field,
          DecomChannels[0].field) == 0) {
      is_bolo = 0;
    }
#endif

    if (!is_bolo && strlen(FastChList[i].field) > 0) {
      normal_fast[n_fast].size = FieldSize(FastChList[i].type,
          FastChList[i].field);
      sprintf(gpb, "%s/%s%s", rc.dirfile, FastChList[i].field, ext);

      normal_fast[n_fast].fp = OpenField(1, normal_fast[n_fast].size, gpb);
      normal_fast[n_fast].i0 = i + SLOW_OFFSET + slowsPerBi0Frame;
      normal_fast[n_fast].i_in = normal_fast[n_fast].i_out = 0;
      if (reset) {
        if (rc.resume_at > 0)
          normal_fast[n_fast].nw = rc.resume_at;
        else
          normal_fast[n_fast].nw = 0;
      }

      normal_fast[n_fast].b = balloc(fatal, MAXBUF * 2 *
          normal_fast[n_fast].size);

      n_fast++;
    }
  }

#if DAS_CARDS > 0
  /* special (bolo) fast chs */
  bolo_node = DAS_START;
  for (i = 0; i < DAS_CARDS; i++) {
    bolo_node++;
    if (bolo_node%4 == 0) bolo_node++;
    for (j = 0; j < DAS_CHS; j++) {
      bolo_fields[i][j].size = 2;
      sprintf(field, "n%02dc%02d", bolo_node, j);
      sprintf(gpb, "%s/%s%s", rc.dirfile, field, ext);

      bolo_fields[i][j].fp = OpenField(1, 2, gpb);
      bolo_fields[i][j].i_in = bolo_fields[i][j].i_out = 0;

      if (reset) {
        if (rc.resume_at > 0)
          bolo_fields[i][j].nw = rc.resume_at;
        else
          bolo_fields[i][j].nw = 0;
      }

      bolo_fields[i][j].b = balloc(fatal, MAXBUF * 4);

      bolo_fields[i][j].i0 = bolo_i0 + i * (DAS_CARDS * 3 / 2) + j;
    }
  }
#endif

  if (rc.write_curfile) {
    // create the link file
    char lnkfile[1024];
    char curfile[1024];

    strncpy(curfile, rc.output_curfile, 1018);
    strcat(curfile, ".cur");

    strncpy(lnkfile, rc.output_curfile, 1018);
    strcat(lnkfile, ".lnk");
    unlink(lnkfile);
    if (symlink(rc.dirfile, lnkfile)<0) {
      berror(fatal, "could not create link from `%s' to `%s'",
             rc.dirfile, lnkfile);
    }
    // create the cur file
    if ((fp = fopen(curfile, "w")) == NULL)
      berror(fatal, "cannot create curfile `%s'", curfile);

    fprintf(fp, "%s\n", rc.dirfile);

    if (fclose(fp) < 0)
      berror(fatal, "cannot close curfile `%s'", curfile);
  }

  ri.dirfile_init = 1;
}
Example #16
0
int opt(int argc, char *argv[], struct opt *opt)
{
    char c;
    char *p;

    opt->secs = 4;
    opt->mode = stat;
    opt->threshold = 0;

    opt->hist_cnt = 100;
    opt->hist_width = 50;

    opt->list_cnt = 1000;

    /*
     * read command line arguments and store them in opt
     */

    while ((c = getopt(argc, argv, "b:c:d:hr:t:")) != -1) {
        switch (c) {
            case 'h' :
                printf("usage: %s <options>\n", basename(argv[0]));
                printf("   -h       help  \n");
                printf("   -d N     duration (in sec or 1m, 1h)  \n");
                printf("   -r R     report: hist, list\n");
                printf("   -c N     count (hist or list)\n");
                printf("   -b N     hist bin width (in ticks)\n");
                printf("   -t N     threshold (in ticks)\n");
                exit(1);
                break;
            case 'd' :
                opt->secs = (unsigned)strtoul(optarg, &p, 0);
                if (p[0] == 'm' || p[0] == 'M') opt->secs *= 60u;
                else if (p[0] == 'h' || p[0] == 'H') opt->secs *= (60u*60u);
                else if (strlen(p) > 0) {
                    printf("ERROR: Parameter: unrecognized characters in time: '%s'\n", p);
                    return 2;
                }
                break;
            case 'r' :
                if (strncmp(optarg, "hist", 4) == 0) {
                    opt->mode = hist;
                } else if (strncmp(optarg, "list", 4) == 0) {
                    opt->mode = list;
                }
                break;
            case 'c' :
                if (opt->mode == hist) {
                    opt->hist_cnt = (unsigned)strtoul(optarg, &p, 0);
                } else if (opt->mode == list) {
                    opt->list_cnt = (unsigned)strtoul(optarg, &p, 0);
                }
                break;
            case 'b' :
                opt->hist_width = (unsigned)strtoul(optarg, &p, 0);
                break;
            case 't' :
                opt->threshold = (unsigned)strtoul(optarg, &p, 0);
                break;
        }
    }

    if (opt->mode == hist) {
        if (opt->hist_cnt == 0) {
            opt->hist_cnt = 1;
        }
        if (opt->hist_width == 0) {
            opt->hist_width = 1;
        }
    } else if (opt->mode == list) {
        if (opt->list_cnt == 0) {
            opt->list_cnt = 1;
        }
    }

    return 0;
}
Example #17
0
int main(int argc, char **argv)
{
	char check_exist=0, quiet=0, remove=0, verbose=0, force=0, list=0;
	prog = basename(argv[0]);
	opterr = 0;
	int c;
	while((c = getopt(argc, argv, "d:efqrvl")) != -1)
	{
		switch(c) {
			case 'd':
				directory = optarg;
				break;
			case 'e':
				check_exist = 1;
			case 'f':
				force = 1;
				break;
			case 'q':
				quiet = 1;
				break;
			case 'r':
				remove = 1;
				break;
			case 'v':
				verbose = 1;
				break;
			case 'l':
				list=1;
				break;
			default:
				usage();
				exit(1);
		}
	}
	if(list) {
		execl("/bin/cat", "/bin/cat", "/proc/modules");
		return 1;
	}
	if(get_uid() && !check_exist) {
		fprintf(stderr, "%s: you must be root to use this program!\n", prog);
		return 1;
	}
	if(remove && check_exist)
	{
		usage();
		exit(1);
	}
	if(!directory) directory = get_default_dir();
	struct stat st;
	if(stat(directory, &st) == -1) {
		if(!quiet) fprintf(stderr, "%s: could not stat module directory %s: %s\n", prog, directory, strerror(errno));
		exit(2);
	}
	char *args=0;
	char *module = argv[optind];
	if(optind+1 < argc)
		args = argv[optind+1];
	if(!module)
	{
		usage();
		exit(1);
	}
	if(verbose && !check_exist && !remove)
		printf("%snsert%s module %s...\n", 
				force ? "Forcing i" : "I",
				force ? "ion of" : "ing",
				module);
	if(remove && verbose)
		printf("Removing module %s...\n", module);
	int ret=0;
	if(remove)
		ret = unload(module, force);
	else if(check_exist)
		ret = check_module_exists(module);
	else
		ret = load(module, args, force);
	if(ret == -1) ret = -errno;
	if(verbose && check_exist && ret)
		printf("Module %s is inserted\n", module);
	
	if(ret && !quiet && !check_exist) {
		if(remove && ret < 0)
			fprintf(stderr, "%s: could not remove module %s: %s\n", 
				prog, module, 
				ret == -EINVAL ? "modules depend on it" : "not loaded");
		if(remove && ret > 0)
			fprintf(stderr, "%s: module %s exit routine returned code %d\n", prog, module, ret);
		if(!remove && ret < 0)
			fprintf(stderr, "%s: could not insert module %s: %s\n", prog, module, strerror(-ret));
		if(!remove && ret > 0)
			fprintf(stderr, "%s: module %s init routine returned code %d\n", prog, module, ret);
	}
	if(check_exist)
		return ret ? 0 : 1;
	
	if(ret < 0) return 4;
	if(ret > 0) return 5;
	return 0;
}
Example #18
0
/* write the outfile */
void write_outfile(xdd_ts_header_t *src, xdd_ts_header_t *dst, xdd_ts_tte_t **read_op,
	xdd_ts_tte_t **send_op, xdd_ts_tte_t **recv_op, xdd_ts_tte_t **write_op) {

    int i;
	int64_t   k, numts_entries;
	float cutoff;
	/* variables for the file writing loop below */
	FILE *outfile;
	/* bandwidths for each window in time */
        double op_time[4], op_mbs[4];
        nclk_t  op_dks[4], op_dke[4];
        int32_t max_xfer;
        char line[OUTFILENAME_LEN] = {" "};
        char datfilename[OUTFILENAME_LEN] = {" "};

        /* create analysis directory, unless it's cwd */
        if (strcmp(outfilebase,".") != 0) {
		sprintf(line,"mkdir -p %s",outfilebase);
        	if ( system(line) == -1 ) {
		  fprintf(stderr,"shell command failed: %s\n",line);
		  exit(1);
        	}
        }
        sprintf(datfilename,"%s/analysis.dat",outfilebase);
	/* try to open file */
	if (strlen(datfilename)==0) {
		outfile = stdout;
	} else {
		outfile = fopen(datfilename, "w");
	}
	/* do we have a file pointer? */
	if (outfile == NULL) {
		fprintf(stderr,"Can not open output file: %s\n",datfilename);
		exit(1);
	}

	/* file header */
	numts_entries = 0;
        if (src != NULL) {
              numts_entries = src->tsh_tt_size;
              if (src != NULL)
                  fprintf(outfile,"#SOURCE");
              else
                  fprintf(outfile,"#READ OP");
	      fprintf(outfile," timestamp file: %s\n",srcfilename);
	      fprintf(outfile,"#timestamp: %s",src->tsh_td);
	      fprintf(outfile,"#reqsize: %d\n",src->tsh_reqsize);
	      fprintf(outfile,"#filesize: %ld\n",src->tsh_reqsize*src->tsh_tt_size);
              fprintf(outfile,"#qthreads_src, target pid, pids: %d %d ",src->tsh_target_thread_id,total_threads_src);
          for (i = 0; i < total_threads_src; i++) { 
              fprintf(outfile,"%d ",thread_id_src[i] );
              }
              fprintf(outfile,"\n");
              fprintf(outfile,"#src_start_norm %lld\n",src_start_norm);
        }
        if (dst != NULL) {
              numts_entries = dst->tsh_tt_size;
              if (src != NULL) fprintf(outfile,"#DESTINATION ");
              else             fprintf(outfile,"#WRITE OP ");
	      fprintf(outfile," timestamp file: %s\n",dstfilename);
	      fprintf(outfile,"#timestamp: %s",dst->tsh_td);
	      fprintf(outfile,"#reqsize: %d\n",dst->tsh_reqsize);
	      fprintf(outfile,"#filesize: %ld\n",dst->tsh_reqsize*dst->tsh_tt_size);
              fprintf(outfile,"#qthreads_dst, target pid, pids: %d %d ",dst->tsh_target_thread_id,total_threads_dst);
            for (i = 0; i < total_threads_dst; i++) { 
	      fprintf(outfile,"%d ",thread_id_dst[i] );
            }
              fprintf(outfile,"\n");
              fprintf(outfile,"#dst_start_norm %lld\n",dst_start_norm);
        }
        fprintf(outfile,"#   read_time     read_bw read_start   read_end   send_time      read_bw send_start   send_end");
        fprintf(outfile,"#   recv_time     read_bw recv_start   recv_end  write_time     write_bw write_start  write_end\n");
        fprintf(outfile,"#    (s)           (MB/s)    (ns)         (ns)      (s)          (MB/s)      (ns)        (ns) ");
        fprintf(outfile,"#                            (ns)         (ns)                               (ns)        (ns)\n");
                
	/* loop through tte entries */
	for (i = 0; i < numts_entries; i++) {
		/* make sure this is an op that matters */
                max_xfer = 0;
                for (k=0; k < 4; k++) {
                  op_time[k] = 0.0;
                  op_mbs [k] = 0.0;
                  op_dks [k] = 0;
                  op_dke [k] = 0;
                }

                if (read_op != NULL) {
		  /* read disk */
                 if (read_op[i]->tte_disk_end > 0) {
                  cutoff = MAX( nclk2sec(read_op[i]->tte_disk_end)-window_size, 0.0);
                  for (k = i; (k >= 0) && ( nclk2sec(read_op[k]->tte_disk_end) > cutoff); k--)
			op_mbs [0] += (double)read_op[k]->tte_disk_xfer_size;
			op_mbs [0]  = op_mbs[0] / MIN((double)window_size,(double)nclk2sec(read_op[i]->tte_disk_end)) / BPU;
			op_time[0]  = nclk2sec(read_op[i]->tte_disk_end);
			max_xfer = MAX(max_xfer,read_op[i]->tte_disk_xfer_size);
                  if (kernel_trace) {
			op_dks [0]  = read_op[i]->tte_disk_start_k  - read_op[i]->tte_disk_start;
			op_dke [0]  = read_op[i]->tte_disk_end      - read_op[i]->tte_disk_end_k;
                  }
                 }
                }
                if (send_op != NULL) {
		/* send net */
                 if (send_op[i]->tte_net_end > 0) {
                  cutoff = MAX( nclk2sec(send_op[i]->tte_net_end)-window_size ,0.0);
                  for (k = i; (k >= 0) && ( nclk2sec(send_op[k]->tte_net_end) > cutoff); k--)
			op_mbs [1] += (double)send_op[k]->tte_net_xfer_size;
			op_mbs [1]  = op_mbs[1] / MIN((double)window_size,(double)nclk2sec(send_op[i]->tte_net_end)) / BPU;
			op_time[1]  = nclk2sec(send_op[i]->tte_net_end);
			max_xfer = MAX(max_xfer,send_op[i]->tte_net_xfer_size);
                  if (kernel_trace) {
			op_dks [1]  = send_op[i]->tte_net_start_k   - send_op[i]->tte_net_start;
			op_dke [1]  = send_op[i]->tte_net_end       - send_op[i]->tte_net_end_k;
                  }
                 }
                }
                if (recv_op != NULL) {
		/* recv net */
                 if (recv_op[i]->tte_net_end > 0) {
                  cutoff = MAX( nclk2sec(recv_op[i]->tte_net_end)-window_size, 0.0);
                  for (k = i; (k >= 0) && ( nclk2sec(recv_op[k]->tte_net_end) > cutoff); k--)
			op_mbs [2] += (double)recv_op[k]->tte_net_xfer_size;
			op_mbs [2]  = op_mbs[2] / MIN((double)window_size,(double)nclk2sec(recv_op[i]->tte_net_end)) / BPU;
			op_time[2]  = nclk2sec(recv_op[i]->tte_net_end);
			max_xfer    = MAX(max_xfer,recv_op[i]->tte_net_xfer_size);
                  if (kernel_trace) {
			op_dks [2]  = send_op[i]->tte_net_start_k   - send_op[i]->tte_net_start;
			op_dke [2]  = send_op[i]->tte_net_end       - send_op[i]->tte_net_end_k;
                  }
                 }
                }
                if (write_op != NULL) {
		/* write disk */
                 if (write_op[i]->tte_disk_end > 0) {
                  cutoff = MAX( nclk2sec(write_op[i]->tte_disk_end)-window_size, 0.0);
                  for (k = i; (k >= 0) && (nclk2sec(write_op[k]->tte_disk_end) > cutoff); k--)
			op_mbs [3] += (double)write_op[k]->tte_disk_xfer_size;
			op_mbs [3]  = op_mbs[3] / MIN((double)window_size,(double)nclk2sec(write_op[i]->tte_disk_end)) / BPU;
			op_time[3]  = nclk2sec(write_op[i]->tte_disk_end);
			max_xfer    = MAX(max_xfer,write_op[i]->tte_disk_xfer_size);
                  if (kernel_trace) {
			op_dks [3]  = write_op[i]->tte_disk_start_k - write_op[i]->tte_disk_start;
			op_dke [3]  = write_op[i]->tte_disk_end     - write_op[i]->tte_disk_end_k;
                  }
                 }
                }
                if (max_xfer == 0)
                   continue;
                memset(line,0,strlen(line));
		/* write to file. take care to leave no embedded '0'(nulls) between fields */
		for (k = 0; k < 4; k++) { 
                   sprintf(&line[k*45],"%12.6f %10.4f %10lld %10lld ",op_time[k],op_mbs[k],op_dks[k],op_dke[k]);
                   if ( op_time[k] == 0.0 ) strncpy(&line[k*45+3],"?",1);
                }
                fprintf(outfile,"%s\n",line);
	}
	fclose(outfile);
  /* write the gnuplot file */
        memset(line,0,strlen(line));
        if (strcmp(outfilebase,".") != 0) sprintf(line,"gnuplot_%s",basename(outfilebase));
	else				  sprintf(line,"gnuplot_");
        outfile = fopen(line, "w");
        /* do we have a file pointer? */
        if (outfile == NULL) { 
                fprintf(stderr,"Can not open gnuplot file for writing: %s\n",line);
                exit(1);
        }               
        fprintf(outfile,"set term po eps color\n");
        fprintf(outfile,"set pointsize 1\n");
        fprintf(outfile,"set ylabel \"MB/s\"\n");
        fprintf(outfile,"set xlabel \"Time in seconds\"\n");
        fprintf(outfile,"set style data line\n");

  if (read_op!=NULL && send_op!=NULL && recv_op!=NULL && write_op!=NULL) {
        fprintf(outfile,"set title \"XDDCP Transfer\"\n");
        fprintf(outfile,"set output \"%s/all.eps\"\n",                       outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:2  title 'read_disk'  lw 2,\\\n",     datfilename);
        fprintf(outfile,"'%s' using  5:6  title 'send_netw'  lw 2,\\\n",     datfilename);
        fprintf(outfile,"'%s' using  9:10 title 'recv_netw'  lw 2,\\\n",     datfilename);
        fprintf(outfile,"'%s' using 13:14 title 'write_disk' lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/netw.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  5:6  title 'send_netw'  lw 2,\\\n",     datfilename);
        fprintf(outfile,"'%s' using  9:10 title 'recv_netw'  lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/disk.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:2  title 'read_disk'  lw 2,\\\n",     datfilename);
        fprintf(outfile,"'%s' using 13:14 title 'write_disk' lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/srce.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:2  title 'read_disk'  lw 2,\\\n",     datfilename);
        fprintf(outfile,"'%s' using  5:6  title 'send_netw'  lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/dest.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  9:10 title 'recv_netw'  lw 2,\\\n",     datfilename);
        fprintf(outfile,"'%s' using 13:14 title 'write_disk' lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/read.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:2  title 'read_disk'  lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/send.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  5:6  title 'send_netw'  lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/recv.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  9:10 title 'recv_netw'  lw 2\n",        datfilename);
        fprintf(outfile,"set output \"%s/write.eps\"\n",                     outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using 13:14 title 'write_disk' lw 2\n",        datfilename);
     if (kernel_trace) {
        fprintf(outfile,"set logscale y\n");
        fprintf(outfile,"set ylabel \"Delta Time (ns) |xdd-kernel|\"\n");
        fprintf(outfile,"set output \"%s/all_k.eps\"\n",                     outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:3  title 'read_disk_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  1:4  title 'read_disk_exit'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  5:7  title 'send_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  5:8  title 'send_netw_exit'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  9:11 title 'recv_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  9:12 title 'recv_netw_exit'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using 13:15 title 'write_disk_entr' lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using 13:16 title 'write_disk_exit' lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/netw_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  5:7  title 'send_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  5:8  title 'send_netw_exit'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  9:10 title 'recv_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  9:12 title 'recv_netw_exit'  lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/disk_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:3  title 'read_disk_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  1:4  title 'read_disk_exit'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using 13:15 title 'write_disk_entr' lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using 13:16 title 'write_disk_exit' lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/srce_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:3  title 'read_disk_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  1:4  title 'read_disk_exit'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  5:7  title 'send_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  5:8  title 'send_netw_exit'  lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/dest_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  9:11 title 'recv_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  9:12 title 'recv_netw_exit'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using 13:15 title 'write_disk_entr' lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using 13:16 title 'write_disk_exit' lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/read_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:3  title 'read_disk_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  1:4  title 'read_disk_exit'  lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/send_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  5:7  title 'send_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  5:8  title 'send_netw_exit'  lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/recv_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  9:11 title 'recv_netw_entr'  lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using  9:12 title 'recv_netw_exit'  lw 2\n",   datfilename);
        fprintf(outfile,"set output \"%s/write_k.eps\"\n",                   outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using 13:15 title 'write_disk_entr' lw 2,\\\n",datfilename);
        fprintf(outfile,"'%s' using 13:16 title 'write_disk_exit' lw 2\n",   datfilename);
     }
  }
  else
  if (read_op!=NULL && op_mix == 0.0) {
        fprintf(outfile,"set title \"XDD Read\"\n");
        fprintf(outfile,"set output \"%s/read.eps\"\n",                       outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:2  title 'read_disk'  lw 2\n",         datfilename);
     if (kernel_trace) {
        fprintf(outfile,"set logscale y\n");
        fprintf(outfile,"set ylabel \"Delta Time (ns) |xdd-kernel|\"\n");
        fprintf(outfile,"set output \"%s/read_k.eps\"\n",                     outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:3  title 'read_disk_entr'  lw 2,\\\n", datfilename);
        fprintf(outfile,"'%s' using  1:4  title 'read_disk_exit'  lw 2\n",    datfilename);
     }
  }
  else
  if (write_op!=NULL && op_mix == 0.0) {
        fprintf(outfile,"set title \"XDD Write\"\n");
        fprintf(outfile,"set output \"%s/write.eps\"\n",                      outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using 13:14 title 'write_disk' lw 2\n",         datfilename);
     if (kernel_trace) {
        fprintf(outfile,"set logscale y\n");
        fprintf(outfile,"set ylabel \"Delta Time (ns) |xdd-kernel|\"\n");
        fprintf(outfile,"set output \"%s/write_k.eps\"\n",                    outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using 13:15 title 'write_disk_entr' lw 2,\\\n", datfilename);
        fprintf(outfile,"'%s' using 13:16 title 'write_disk_exit' lw 2\n",    datfilename);
     }
  }
  else 
  if (op_mix > 0.0) {
        fprintf(outfile,"set title \"XDD Mixed Read/Write %-7.0f%%\"\n",op_mix*100.0);
        fprintf(outfile,"set output \"%s/mixed.eps\"\n",                       outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:2  title 'mixed_disk'  lw 2\n",         datfilename);
     if (kernel_trace) {
        fprintf(outfile,"set logscale y\n");
        fprintf(outfile,"set ylabel \"Delta Time (ns) |xdd-kernel|\"\n");
        fprintf(outfile,"set output \"%s/mixed_k.eps\"\n",                     outfilebase);
        fprintf(outfile,"plot\\\n");
        fprintf(outfile,"'%s' using  1:3  title 'mixed_disk_entr'  lw 2,\\\n", datfilename);
        fprintf(outfile,"'%s' using  1:4  title 'mixed_disk_exit'  lw 2\n",    datfilename);
     }
  }
  else {
        fprintf(stderr,"write_outfile: Case not recognized\n");
        exit(1);
  }
	fclose(outfile);
        memset(line,0,strlen(line));
        if (strcmp(outfilebase,".") != 0)sprintf(line,"gnuplot gnuplot_%s",basename(outfilebase));
        else				 sprintf(line,"gnuplot gnuplot_  ");
        if ( system(line) == -1 ) { 
              fprintf(stderr,"shell command failed: %s\n",line);
              exit(1);
        }
        fprintf(stderr,"Check directory %s for analysis results\n",outfilebase);
}
Example #19
0
/*
 * Open device and perform command
 */
int
main(int argc, char **argv)
{
	char *execdup, *execname;
	int rc = EX_OK;

	/* Get exec name */
	execdup = (char *)strdup(argv[0]);
	if (execdup == NULL) {
		printf("%s: fatal error: strdup failed\n", __func__);
		io_exit(EX_OSERR); /* Panic */
	}
	execname = basename(execdup);
	if (execname == NULL) {
		printf("%s: fatal error: basename failed\n", __func__);
		io_exit(EX_OSERR); /* Panic */
	}

	/* Get configuration */
	getconf();
	
	/* Open device */
	if (io_open() < 0) {
		usage(execname, io_error());
	}

	/* Raise priority */
	setpriority(PRIO_PROCESS, 0, -20);

	/* Reset uid */
	if (getuid() != geteuid()) {
		if (setuid(getuid()) < 0) {
			printf("%s: fatal error: setuid failed\n", __func__);
			io_exit(EX_OSERR); /* Panic */
		}
	}

	/* Determine arch: 12 | 14 | 16 | 24 | 32 */
	if (pic_arch(execname) == 0)
		usage_pickle();

	/* Perform operation */
	if (argc < 2)
		usage(execname, "Missing arg(s)");

	/* Device selection */
	int argv1 = tolower((int)argv[1][0]);
	if (argv1 == 's') { /* Select device */
		if (argc < 3) {
			pic_selector();
			io_exit(EX_OK);
		}
		if (mystrcasestr(argv[2], "dspic") == argv[2]) {
			strncpy(p.devicename, argv[2], STRLEN);
		} else if (mystrcasestr(argv[2], "pic") == argv[2]) {
			strncpy(p.devicename, argv[2], STRLEN);
		} else {
			int32_t temp = strtol(argv[2], NULL, 0);
			if (temp < 10 || temp > 33) {
				usage(execname, "Invalid arg [select]");
			}
			if (temp == 30 || temp == 33) {
				strcpy(p.devicename, "dspic");
				strncpy(&p.devicename[5], argv[2], STRLEN - 5);
			} else {
				strcpy(p.devicename, "pic");
				strncpy(&p.devicename[3], argv[2], STRLEN - 3);
			}
		}
		argc -= 2;
		argv += 2;
		if (argc < 2)
			usage(execname, "Missing arg(s)");
	} else if (p.pic->arch == ARCH12BIT) {
		usage(execname, "Missing select");
	}

	/* Key entry */
	argv1 = tolower((int)argv[1][0]);
	if (argv1 == 'l') {			/* LVP 32-bit key entry */
		if (p.pic->arch == ARCH12BIT) {
			usage(execname, "Invalid arg [lvp]");
		}
		/* ARCH14BIT || ARCH16BIT || ARCH24BIT || ARCH32BIT */
		p.key = LVPKEY;
		argc -= 1;
		argv += 1;
		if (argc < 2)
			usage(execname, "Missing arg(s)");
	}
	else if (argv1 == 'h') {		/* HVP 32-bit key entry */
		if (p.pic->arch == ARCH12BIT || p.pic->arch == ARCH14BIT || p.pic->arch == ARCH32BIT) {
			usage(execname, "Invalid arg [hvp]");
		}
		/* ARCH16BIT || ARCH24BIT */
		p.key = HVPKEY;
		argc -= 1;
		argv += 1;
		if (argc < 2)
			usage(execname, "Missing arg(s)");
	}
	else if (p.pic->arch == ARCH32BIT) {	/* LVP 32-bit key entry */
		/* ARCH32BIT */
		p.key = LVPKEY;
	}
	else {					/* No key entry */
		/* ARCH12BIT || ARCH14BIT || ARCH16BIT || ARCH24BIT */
		p.key = NOKEY;
	}

	/* Command */
	argv1 = tolower((int)argv[1][0]);
	int argv11 = tolower((int)argv[1][1]);
	switch (argv1) {
	case 'b':	if (argv11 == 'o') {		/* BOOT */
				uint32_t addr = UINT32_MAX, words = UINT32_MAX;
				if (argc > 4)
					usage(execname, "Too many args [boot]");
				if (argc >= 3) {
					words = strtoul(argv[2], NULL, 0);
					if (words == 0)
						usage(execname, "Invalid arg [boot]");
				}
				if (argc == 4) {
					addr = strtoul(argv[3], NULL, 0);
				}
				pic_dumpboot(addr, words);
			} else {			/* BLANK */
				int config = 1;
				if (argc > 3)
					usage(execname, "Too many args [blank]");
				if (argc == 3) switch (argv[2][0]) {
					case 'n':
					case 'N':
					case '0': config = 0;
						break;
					case 'y':
					case 'Y':
					case '1': config = 1;
						break;
					default:usage(execname, "invalid arg [blank]");
						break;
				}
				if (areyousure("Blank device")) {
					pic_blank(config);
				}
			}
			break;

	case 'c':	if (argc > 3)
				usage(execname, "Too many args [config]");
			if (argc == 2)
				pic_dumpconfig();
			else
				pic_writebandgap(strtoul(argv[2], NULL, 0));
			break;
	
	case 'd':	if (argv11 == 'a') {		/* DATA */
				if (argc > 2)
					usage(execname, "Too many args [data]");
				pic_dumpdata();
			} else if (argv11 == 'e') { 	/* DEBUG */
				pic_debug();
			} else {			/* DUMP */
				if (argc > 2)
					usage(execname, "Too many args [dump]");
				pic_dumpdevice();
			}
			break;

	case 'e':	if (argv11 == 'r') {		/* ERASE FLASH | ID | ROW[NROWS] */
				uint32_t row = 0, nrows = 1;
				char prompt[STRLEN] = {0}, *endptr = NULL;

				if (argc < 3)
					usage(execname, "Missing arg [erase]");
				if (argc > 4)
					usage(execname, "Too many args [erase]");
				
				int argv2 = tolower((int)argv[2][0]);
				switch (argv2) {
				case 'i': /* IDLOCATION    */
				case 'u': /* USERID/CONFIG */
					row = PIC_ERASE_ID;
					strncpy(prompt, "Erase id", STRLEN);
					break;
				case 'c': /* CONFIG */
					row = PIC_ERASE_CONFIG;
					strncpy(prompt, "Erase config", STRLEN);
					break;
				case 'e': /* EEPROM */
					row = PIC_ERASE_EEPROM;
					strncpy(prompt, "Erase EEPROM", STRLEN);
					break;
				case 'f': /* FLASH */
					nrows = UINT32_MAX;
					strncpy(prompt, "Erase program flash", STRLEN);
					break;
				default:  /* FLASH ROW */
					row = strtoul(argv[2], &endptr, 0);
					if (endptr == argv[2])
						usage(execname, "Invalid arg [erase]");
					if (argc == 4) {
						nrows = strtoul(argv[3], NULL, 0);
						if (nrows == 0)
							usage(execname, "Invalid arg [erase]");
					}
					snprintf(prompt, STRLEN, "Erase %u row(s) at row %u",
						nrows, row);
					break;
				}
				if (areyousure(prompt))
					pic_erase(row, nrows);
			} else if (argv11 == 'x') {	/* EXECUTIVE */
				uint32_t addr = UINT32_MAX, words = UINT32_MAX;
				if (argc > 4)
					usage(execname, "Too many args [executive]");
				if (argc >= 3) {
					words = strtoul(argv[2], NULL, 0);
					if (words == 0)
						usage(execname, "Invalid arg [executive]");
				}
				if (argc == 4) {
					addr = strtoul(argv[3], NULL, 0);
				}
				pic_dumpexec(addr, words);
			} else {			/* EEPROM */
				if (argc > 2)
					usage(execname, "Too many args [eeprom]");
				pic_dumpdata();
			}
			break;

	case 'f':	{
			uint32_t words = UINT32_MAX, addr = UINT32_MAX;
			if (argc > 4)
				usage(execname, "Too many args [program flash]");
			if (argc >= 3) {
				words = strtoul(argv[2], NULL, 0);
				if (words == 0)
					usage(execname, "Invalid arg [program flash]");
			}
			if (argc == 4) {
				addr = strtoul(argv[3], NULL, 0);
			}
			pic_dumpprogram(addr, words);
			}
			break;

	case 'i':	if (argc > 2)
				usage(execname, "Too many args [id]");
			pic_dumpdeviceid();
			break;

	case 'o':	if (argc > 3)
				usage(execname, "Too many args [osccal]");
			if (argc == 2)
				pic_dumposccal();
			else
				pic_writeosccal(strtoul(argv[2], NULL, 0));
			break;

	case 'p':	{
			int blank = 1;
			if (argc > 4)
				usage(execname, "Too many args [program]");
			if (argc == 4) switch (argv[3][0]) {
				case 'n':
				case 'N':
				case '0': blank = 0;
					break;
				case 'y':
				case 'Y':
				case '1': blank = 1;
					break;
				default:usage(execname, "invalid arg [program]");
					break;
			}
			if (argc < 3)
				pic_program("-", 1);
			else
				pic_program(argv[2], blank);
			}
			break;

	case 'v':	if (argv11 == 'i') {		/* VIEW */
				int raw = 0;
				if (argc > 4)
					usage(execname, "Too many args [view]");
				if (argc == 4) switch (argv[3][0]) {
					case 'r':
					case 'R': raw = 1;
						break;
					default:usage(execname, "invalid arg [view]");
						break;
				}
				if (argc < 3)
					pic_view("-", 0);
				else
					pic_view(argv[2], raw);
			} else {			/* VERIFY */
				if (argc > 3)
					usage(execname, "Too many args [verify]");
				if (argc < 3)
					rc = 0 - pic_verify("-");
				else
					rc = 0 - pic_verify(argv[2]);
			}
			break;
#ifdef TTY
	case '/':	if (strstr(argv[1], "/dev/tty") != argv[1]) {
				usage(execname, "Invalid device [TTY]");
			}
			if (strstr(argv[1], p.device) != NULL) {
				usage(execname, "Device in use [TTY]");
			}
			stk500v2_listen(argv[1], 0);
			break;

	case '8':	stk500v2_listen("0.0.0.0", 8048);
			break;
#endif
	default:	usage(execname, "Unknown operation");
			break;
	}

	free(execdup);
	io_exit(rc);
}
Example #20
0
int main(int argc, char **argv)
{
    int fd_count = 0;
    struct pollfd ufds[4];
    char *tmpdev;
    char* debuggable;
    char tmp[32];
    int property_set_fd_init = 0;
    int signal_fd_init = 0;
    int keychord_fd_init = 0;
    bool is_charger = false;

    if (!strcmp(basename(argv[0]), "ueventd"))
        return ueventd_main(argc, argv);

    if (!strcmp(basename(argv[0]), "watchdogd"))
        return watchdogd_main(argc, argv);

    /* clear the umask */
    umask(0);

        /* Get the basic filesystem setup we need put
         * together in the initramdisk on / and then we'll
         * let the rc file figure out the rest.
         */
    mkdir("/dev", 0755);
    mkdir("/proc", 0755);
    mkdir("/sys", 0755);

    mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
    mkdir("/dev/pts", 0755);
    mkdir("/dev/socket", 0755);
    mount("devpts", "/dev/pts", "devpts", 0, NULL);
    mount("proc", "/proc", "proc", 0, NULL);
    mount("sysfs", "/sys", "sysfs", 0, NULL);

        /* indicate that booting is in progress to background fw loaders, etc */
    close(open("/dev/.booting", O_WRONLY | O_CREAT, 0000));

        /* We must have some place other than / to create the
         * device nodes for kmsg and null, otherwise we won't
         * be able to remount / read-only later on.
         * Now that tmpfs is mounted on /dev, we can actually
         * talk to the outside world.
         */
    open_devnull_stdio();
    klog_init();
    property_init();

    get_hardware_name(hardware, &revision);

    process_kernel_cmdline();

    union selinux_callback cb;
    cb.func_log = klog_write;
    selinux_set_callback(SELINUX_CB_LOG, cb);

    cb.func_audit = audit_callback;
    selinux_set_callback(SELINUX_CB_AUDIT, cb);

    INFO("loading selinux policy\n");
    if (selinux_enabled) {
        if (selinux_android_load_policy() < 0) {
            selinux_enabled = 0;
            INFO("SELinux: Disabled due to failed policy load\n");
        } else {
            selinux_init_all_handles();
        }
    } else {
        INFO("SELinux:  Disabled by command line option\n");
    }
    /* These directories were necessarily created before initial policy load
     * and therefore need their security context restored to the proper value.
     * This must happen before /dev is populated by ueventd.
     */
    restorecon("/dev");
    restorecon("/dev/socket");

    is_charger = !strcmp(bootmode, "charger");

    INFO("property init\n");
    if (!is_charger)
        property_load_boot_defaults();

    INFO("reading config file\n");
    init_parse_config_file("/init.rc");

    action_for_each_trigger("early-init", action_add_queue_tail);

    queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done");
    queue_builtin_action(keychord_init_action, "keychord_init");
    queue_builtin_action(console_init_action, "console_init");

    /* execute all the boot actions to get us started */
    action_for_each_trigger("init", action_add_queue_tail);

    /* skip mounting filesystems in charger mode */
    if (!is_charger) {
        action_for_each_trigger("early-fs", action_add_queue_tail);
        action_for_each_trigger("fs", action_add_queue_tail);
        action_for_each_trigger("post-fs", action_add_queue_tail);
        action_for_each_trigger("post-fs-data", action_add_queue_tail);
    }

    queue_builtin_action(property_service_init_action, "property_service_init");
    queue_builtin_action(signal_init_action, "signal_init");
    queue_builtin_action(check_startup_action, "check_startup");

    if (is_charger) {
        action_for_each_trigger("charger", action_add_queue_tail);
    } else {
        action_for_each_trigger("early-boot", action_add_queue_tail);
        action_for_each_trigger("boot", action_add_queue_tail);
    }

        /* run all property triggers based on current state of the properties */
    queue_builtin_action(queue_property_triggers_action, "queue_property_triggers");


#if BOOTCHART
    queue_builtin_action(bootchart_init_action, "bootchart_init");
#endif

    for(;;) {
        int nr, i, timeout = -1;

        execute_one_command();
        restart_processes();

        if (!property_set_fd_init && get_property_set_fd() > 0) {
            ufds[fd_count].fd = get_property_set_fd();
            ufds[fd_count].events = POLLIN;
            ufds[fd_count].revents = 0;
            fd_count++;
            property_set_fd_init = 1;
        }
        if (!signal_fd_init && get_signal_fd() > 0) {
            ufds[fd_count].fd = get_signal_fd();
            ufds[fd_count].events = POLLIN;
            ufds[fd_count].revents = 0;
            fd_count++;
            signal_fd_init = 1;
        }
        if (!keychord_fd_init && get_keychord_fd() > 0) {
            ufds[fd_count].fd = get_keychord_fd();
            ufds[fd_count].events = POLLIN;
            ufds[fd_count].revents = 0;
            fd_count++;
            keychord_fd_init = 1;
        }

        if (process_needs_restart) {
            timeout = (process_needs_restart - gettime()) * 1000;
            if (timeout < 0)
                timeout = 0;
        }

        if (!action_queue_empty() || cur_action)
            timeout = 0;

#if BOOTCHART
        if (bootchart_count > 0) {
            if (timeout < 0 || timeout > BOOTCHART_POLLING_MS)
                timeout = BOOTCHART_POLLING_MS;
            if (bootchart_step() < 0 || --bootchart_count == 0) {
                bootchart_finish();
                bootchart_count = 0;
            }
        }
#endif

        nr = poll(ufds, fd_count, timeout);
        if (nr <= 0)
            continue;

        for (i = 0; i < fd_count; i++) {
            if (ufds[i].revents == POLLIN) {
                if (ufds[i].fd == get_property_set_fd())
                    handle_property_set_fd();
                else if (ufds[i].fd == get_keychord_fd())
                    handle_keychord();
                else if (ufds[i].fd == get_signal_fd())
                    handle_signal();
            }
        }
    }

    return 0;
}
int main(int argc, char** argv)
{
    const char *transFilePath = TIO_DEFAULT_TRANSLATION_FILE_PATH;
    unsigned refreshDelay = 0;   /* in seconds, 0 = disabled */
    const char *logFilePath = 0;
    /* 
     * syslog isn't installed on the target so it's disabled in this program
     * by requiring an argument to -o|--log.
     */ 
    int logToSyslog = 0;
    unsigned short sioPort = 0;  /* 0 means use Unix socket */
    unsigned short tioPort = 0;
    int daemonFlag = 0;
    int verboseFlag = 0;
    unsigned short mapSize = MAX_MSG_MAP_SIZE;

    /* allocate memory for progName since basename() modifies it */
    const size_t nameLen = strlen(argv[0]) + 1;
    char arg0[nameLen];
    memcpy(arg0, argv[0], nameLen);
    progName = basename(arg0);

    while (1) {
        static struct option longOptions[] = {
            { "daemon",     no_argument,       0, 'd' },
            { "file",       required_argument, 0, 'f' },
            { "map-size",   optional_argument, 0, 'm' },
            { "refresh",    optional_argument, 0, 'r' },
            { "sio_port",   optional_argument, 0, 's' },
            { "tio_port",   optional_argument, 0, 't' },
            { "verbose",    no_argument,       0, 'v' },
            { "help",       no_argument,       0, 'h' },
            { 0,            0, 0,  0  }
        };
        int c = getopt_long(argc, argv, "df:m:r::s::t::vh?", longOptions, 0);

        if (c == -1) {
            break;  // no more options to process
        }

        switch (c) {
        case 'd':
            daemonFlag = 1;
            break;

        case 'f':
            transFilePath = optarg;
            break;

        case 'm':
            mapSize = (optarg == 0) ? MAX_MSG_MAP_SIZE : atoi(optarg);
            break;

        case 'r':
            refreshDelay = (optarg == 0) ? DEFAULT_REFRESH_DELAY : atoi(optarg);
            break;

        case 's':
            sioPort = (optarg == 0) ? SIO_DEFAULT_AGENT_PORT : atoi(optarg);
            break;

        case 't':
            tioPort = (optarg == 0) ? TIO_DEFAULT_AGENT_PORT : atoi(optarg);
            break;

        case 'v':
            verboseFlag = 1;
            break;

        case 'h':
        case '?':
        default:
            tioDumpHelp();
            exit(1);
        }
    }

    /* set up logging to syslog or file; will be STDERR not told otherwise */
    LogOpen(progName, logToSyslog, logFilePath, verboseFlag);

    /* keep STDIO going for now */
    if (daemonFlag) {
        if (daemon(0, 1) != 0) {
            dieWithSystemMessage("daemon() failed");
        }
    }

    tioAgent(transFilePath, refreshDelay, tioPort, TIO_AGENT_UNIX_SOCKET,
        sioPort, SIO_AGENT_UNIX_SOCKET, mapSize);

    exit(EXIT_SUCCESS);
}
Example #22
0
int main(int argc, char **argv)
{
	uint32_t crc, targetendian_crc;
	const char *txt_filename = NULL, *bin_filename = NULL;
	int txt_fd, bin_fd;
	unsigned char *dataptr, *envptr;
	unsigned char *filebuf = NULL;
	unsigned int filesize = 0, envsize = 0, datasize = 0;
	int bigendian = 0;
	int redundant = 0;
	unsigned char padbyte = 0xff;

	int option;
	int ret = EXIT_SUCCESS;

	struct stat txt_file_stat;

	int fp, ep;
	const char *prg;

	prg = basename(argv[0]);

	/* Turn off getopt()'s internal error message */
	opterr = 0;

	/* Parse the cmdline */
	while ((option = getopt(argc, argv, ":s:o:rbp:hV")) != -1) {
		switch (option) {
		case 's':
			datasize = xstrtol(optarg);
			break;
		case 'o':
			bin_filename = strdup(optarg);
			if (!bin_filename) {
				fprintf(stderr, "Can't strdup() the output filename\n");
				return EXIT_FAILURE;
			}
			break;
		case 'r':
			redundant = 1;
			break;
		case 'b':
			bigendian = 1;
			break;
		case 'p':
			padbyte = xstrtol(optarg);
			break;
		case 'h':
			usage(prg);
			return EXIT_SUCCESS;
		case 'V':
			printf("%s version %s\n", prg, PLAIN_VERSION);
			return EXIT_SUCCESS;
		case ':':
			fprintf(stderr, "Missing argument for option -%c\n",
				optopt);
			usage(prg);
			return EXIT_FAILURE;
		default:
			fprintf(stderr, "Wrong option -%c\n", optopt);
			usage(prg);
			return EXIT_FAILURE;
		}
	}

	/* Check datasize and allocate the data */
	if (datasize == 0) {
		fprintf(stderr, "Please specify the size of the environment partition.\n");
		usage(prg);
		return EXIT_FAILURE;
	}

	dataptr = malloc(datasize * sizeof(*dataptr));
	if (!dataptr) {
		fprintf(stderr, "Can't alloc %d bytes for dataptr.\n",
				datasize);
		return EXIT_FAILURE;
	}

	/*
	 * envptr points to the beginning of the actual environment (after the
	 * crc and possible `redundant' byte
	 */
	envsize = datasize - (CRC_SIZE + redundant);
	envptr = dataptr + CRC_SIZE + redundant;

	/* Pad the environment with the padding byte */
	memset(envptr, padbyte, envsize);

	/* Open the input file ... */
	if (optind >= argc || strcmp(argv[optind], "-") == 0) {
		int readbytes = 0;
		int readlen = sizeof(*envptr) * 4096;
		txt_fd = STDIN_FILENO;

		do {
			filebuf = realloc(filebuf, readlen);
			if (!filebuf) {
				fprintf(stderr, "Can't realloc memory for the input file buffer\n");
				return EXIT_FAILURE;
			}
			readbytes = read(txt_fd, filebuf + filesize, readlen);
			if (errno) {
				fprintf(stderr, "Error while reading stdin: %s\n",
						strerror(errno));
				return EXIT_FAILURE;
			}
			filesize += readbytes;
		} while (readbytes == readlen);

	} else {
		txt_filename = argv[optind];
		txt_fd = open(txt_filename, O_RDONLY);
		if (txt_fd == -1) {
			fprintf(stderr, "Can't open \"%s\": %s\n",
					txt_filename, strerror(errno));
			return EXIT_FAILURE;
		}
		/* ... and check it */
		ret = fstat(txt_fd, &txt_file_stat);
		if (ret == -1) {
			fprintf(stderr, "Can't stat() on \"%s\": %s\n",
					txt_filename, strerror(errno));
			return EXIT_FAILURE;
		}

		filesize = txt_file_stat.st_size;

		filebuf = mmap(NULL, sizeof(*envptr) * filesize, PROT_READ,
			       MAP_PRIVATE, txt_fd, 0);
		if (filebuf == MAP_FAILED) {
			fprintf(stderr, "mmap (%zu bytes) failed: %s\n",
					sizeof(*envptr) * filesize,
					strerror(errno));
			fprintf(stderr, "Falling back to read()\n");

			filebuf = malloc(sizeof(*envptr) * filesize);
			ret = read(txt_fd, filebuf, sizeof(*envptr) * filesize);
			if (ret != sizeof(*envptr) * filesize) {
				fprintf(stderr, "Can't read the whole input file (%zu bytes): %s\n",
					sizeof(*envptr) * filesize,
					strerror(errno));

				return EXIT_FAILURE;
			}
		}
		ret = close(txt_fd);
	}
	/* The +1 is for the additionnal ending \0. See below. */
	if (filesize + 1 > envsize) {
		fprintf(stderr, "The input file is larger than the environment partition size\n");
		return EXIT_FAILURE;
	}

	/* Replace newlines separating variables with \0 */
	for (fp = 0, ep = 0 ; fp < filesize ; fp++) {
		if (filebuf[fp] == '\n') {
			if (ep == 0) {
				/*
				 * Newlines at the beginning of the file ?
				 * Ignore them.
				 */
				continue;
			} else if (filebuf[fp-1] == '\\') {
				/*
				 * Embedded newline in a variable.
				 *
				 * The backslash was added to the envptr; rewind
				 * and replace it with a newline
				 */
				ep--;
				envptr[ep++] = '\n';
			} else {
				/* End of a variable */
				envptr[ep++] = '\0';
			}
		} else {
			envptr[ep++] = filebuf[fp];
		}
	}
	/*
	 * Make sure there is a final '\0'
	 * And do it again on the next byte to mark the end of the environment.
	 */
	if (envptr[ep-1] != '\0') {
		envptr[ep++] = '\0';
		/*
		 * The text file doesn't have an ending newline.  We need to
		 * check the env size again to make sure we have room for two \0
		 */
		if (ep >= envsize) {
			fprintf(stderr, "The environment file is too large for the target environment storage\n");
			return EXIT_FAILURE;
		}
		envptr[ep] = '\0';
	} else {
		envptr[ep] = '\0';
	}

	/* Computes the CRC and put it at the beginning of the data */
	crc = crc32(0, envptr, envsize);
	targetendian_crc = bigendian ? cpu_to_be32(crc) : cpu_to_le32(crc);

	memcpy(dataptr, &targetendian_crc, sizeof(targetendian_crc));
	if (redundant)
		dataptr[sizeof(targetendian_crc)] = 1;

	if (!bin_filename || strcmp(bin_filename, "-") == 0) {
		bin_fd = STDOUT_FILENO;
	} else {
		bin_fd = creat(bin_filename, S_IRUSR | S_IWUSR | S_IRGRP |
					     S_IWGRP);
		if (bin_fd == -1) {
			fprintf(stderr, "Can't open output file \"%s\": %s\n",
					bin_filename, strerror(errno));
			return EXIT_FAILURE;
		}
	}

	if (write(bin_fd, dataptr, sizeof(*dataptr) * datasize) !=
			sizeof(*dataptr) * datasize) {
		fprintf(stderr, "write() failed: %s\n", strerror(errno));
		return EXIT_FAILURE;
	}

	ret = close(bin_fd);

	return ret;
}
Example #23
0
int main(int argc, char *argv[])
{
    if(argc <= 2) {
        printf("Usage: %s IP PORT\n", basename(argv[0]));
        exit(EXIT_FAILURE);
    }
    const char *ip = argv[1];
    int port = atoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1)
        ERR_EXIT("socket");

    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = inet_addr(ip);

    if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)
        ERR_EXIT("connection");

    struct pollfd fds[2];
    // 注册标准输入(0)和sockfd上的可读事件
    fds[0].fd = 0;
    fds[0].events = POLLIN;
    fds[0].revents = 0;
    fds[1].fd = sockfd;
    fds[1].events = POLLIN | POLLRDHUP;
    fds[1].revents = 0;
    
    char read_buf[BUFFER_SIZE];
    int pipefd[2];
    int ret = pipe(pipefd);
    if(ret == -1)
        ERR_EXIT("pipe");

    while(1) {
        ret = poll(fds, 2, -1);
        if(ret == -1) {
            printf("poll failure\n");
            break;
        }
        if(fds[1].revents & POLLRDHUP) {  // sockfd上收到对方关闭连接请求
            printf("server close the connection\n");
            break;
        } else if(fds[1].revents & POLLIN) {  // sockfd上发生可读事件
            memset(read_buf, 0, BUFFER_SIZE);
            recv(fds[1].fd, read_buf, BUFFER_SIZE-1, 0);
            printf("%s\n", read_buf);
        }
        if(fds[0].revents & POLLIN) {  // 向标准输入写入数据
            // 零拷贝: 将用户输入的数据直接写入sockfd上
            if(splice(0, NULL, pipefd[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE) == -1)
                ERR_EXIT("splice");
            if(splice(pipefd[0], NULL, sockfd, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE) == -1)
                ERR_EXIT("splice");
        }

    }
    close(sockfd);
    exit(EXIT_SUCCESS);
}
Example #24
0
 int main(int argc, char *argv[])
 {
   int pri,retVal,firstTime=1,ind=0;
   time_t lastRefresh=0;
   time_t lastUpdate=0;
   time_t currentTime=0;
   char *tempString=0;
   char *progName=basename(argv[0]);

//   last_send.tv_sec = 0; 
//   last_send.tv_nsec = 0; 

   //Sort out PID File
   retVal=sortOutPidFile(progName);
   if(retVal!=0) {
     return retVal;
   }


   //Directory listing tools
   //    char currentTouchname[FILENAME_MAX];
   char currentHeader[FILENAME_MAX];
   int numLinks[NUM_PRIORITIES]={0};
   int totalEventLinks=0;
   int wdEvents[NUM_PRIORITIES]={0};
   //   int sillyEvNum[NUM_PRIORITIES]={0};


   /* Set signal handlers */
   signal(SIGUSR1, sigUsr1Handler);
   signal(SIGUSR2, sigUsr2Handler);
   signal(SIGTERM, handleBadSigs);
   signal(SIGINT,handleBadSigs);
   signal(SIGSEGV,handleBadSigs);


   /* Setup log */
   setlogmask(LOG_UPTO(LOG_INFO));
   openlog (progName, LOG_PID, ANITA_LOG_FACILITY) ;

   // Load Config 
   retVal=readConfig();
   if(!laptopDebug) {
     retVal=initDevice();
     if(retVal!=0) {
       return 1;
     }
   }
   else {
     retVal=0;
     printf("Running in debug mode not actually trying to talk to device\n");
     makeDirectories(fakeOutputDir);
   }

   makeDirectories(PRIORITIZERD_EVENT_LINK_DIR);

   
    for(ind=0;ind<NUM_HK_TELEM_DIRS;ind++) {
      makeDirectories(telemLinkDirs[ind]);
    }


   //Fill event dir names
   for(pri=0;pri<NUM_PRIORITIES;pri++) {
     sprintf(eventTelemDirs[pri],"%s/%s%d",BASE_EVENT_TELEM_DIR,
	     EVENT_PRI_PREFIX,pri);
     sprintf(eventTelemLinkDirs[pri],"%s/link",eventTelemDirs[pri]);
     makeDirectories(eventTelemLinkDirs[pri]);


     if(sendData) {
	 //And setup inotify watches
	 if(wdEvents[pri]==0) {
	     wdEvents[pri]=setupLinkWatchDir(eventTelemLinkDirs[pri]);
	     if(wdEvents[pri]<=0) {
		 fprintf(stderr,"Unable to watch %s\n",eventTelemLinkDirs[pri]);
		 syslog(LOG_ERR,"Unable to watch %s\n",eventTelemLinkDirs[pri]);
		 handleBadSigs(0);
	     }
	     numLinks[pri]=getNumLinks(wdEvents[pri]);
	 }
     }
   }
   time(&lastRefresh);

   pthread_t thread; 
   retVal = pthread_create(&thread, 0, watchdogThread,0); 
   if (retVal) 
   {
     syslog(LOG_ERR, "LOSd:  create watchdog thread returned %d\n", retVal); 
   }

   do {
     if(verbosity) printf("Initializing LOSd\n");
     int lastSendData=sendData;
     retVal=readConfig();
     if(lastSendData!=sendData) {
	 break; //Lets restart LOSd
     }
     if(firstTime) {
       sendWakeUpBuffer();
       firstTime=0;
     }
     int hkCount=0;    	
     currentState=PROG_STATE_RUN;
     while(currentState==PROG_STATE_RUN) {
       //This is just if LOSd has been turned off when we're out of range
       if(!sendData) {
	 sleep(1);
	 continue;
       }
       
       //Check to see if we need to refresh the links
       time(&currentTime);
       if(currentTime>lastRefresh+REFRESH_LINKS_EVERY) {

	   refreshLinkDirs();
	   lastRefresh=currentTime;
       }

       //Work which priority we're doing
       currentPri=priorityOrder[orderIndex];

       //Will actually change this to almost work in the future
       if(hkCount%5==0) fillBufferWithHk();
       hkCount++;

       //Check the link dirs
       if(currentTime>lastUpdate+10 || totalEventLinks<1) {
	 if(totalEventLinks<1) 
	   checkLinkDirs(1,0);
	 else
	   checkLinkDirs(0,1); //Maybe I don't need to do this every time
	 lastUpdate=currentTime;
       }

       totalEventLinks=0;
       for(pri=0;pri<NUM_PRIORITIES;pri++) {
	 numLinks[pri]=getNumLinks(wdEvents[pri]);
	 totalEventLinks+=numLinks[pri];
       }

       if(printToScreen && verbosity>1) {
	 printf("Got %d links in %s\n",numLinks[currentPri],
		eventTelemLinkDirs[currentPri]);
       }
       //       sillyEvNum[currentPri]=0;

       if(numLinks[currentPri]>0) {
	 //Got an event

	 tempString=getLastLink(wdEvents[currentPri]);	
	 sprintf(currentHeader,"%s/%s",eventTelemLinkDirs[currentPri],
		 tempString);
	 if(printToScreen && verbosity)
	   printf("Starting %s\n",currentHeader);
	 readAndSendEventRamdisk(currentHeader); //Also deletes
	 numLinks[currentPri]--;
	 totalEventLinks--;	       
       }

       //Again I need to improve the bandwidth sharing between data and hk
       fillBufferWithHk();
//       if(totalEventLinks<1) usleep(100);
       //	    printf("totalEventLinks %d\n",totalEventLinks);
       orderIndex++;
       if(orderIndex>=numOrders) orderIndex=0;
     }
   } while(currentState==PROG_STATE_INIT);
   unlink(LOSD_PID_FILE);
   syslog(LOG_INFO,"LOSd terminating");
   //    fprintf(stderr, "Bye bye\n");
   return 0;
 } 
Example #25
0
int main(int argc, char *argv[])
{
	const char *lang = NULL;
	const char *filename = NULL;
	const char *outfile = NULL;
	int		i, c;
	FILE   *filp;
	FILE   *fout = stdout;

	while ((c = getopt(argc, argv, "f:l:o:h")) != -1)
	{
		switch (c)
		{
			case 'f':
				if (filename != NULL)
				{
					fputs("-f was specified twice", stderr);
					return 1;
				}
				filename = optarg;
				break;
			case 'l':
				if (lang)
				{
					fputs("-l was specified twice", stderr);
					return 1;
				}

				for (i=0; known_langs[i] != NULL; i++)
				{
					if (strcasecmp(optarg, known_langs[i]) == 0)
					{
						lang = known_langs[i];
						break;
					}
				}
				if (!lang)
				{
					fprintf(stderr, "not known language code: %s", optarg);
					return 1;
				}
				break;
			case 'o':
				if (outfile != NULL)
				{
					fputs("-o was specified twice", stderr);
					return 1;
				}
				outfile = optarg;
				break;
			case 'h':
			default:
				fprintf(stderr, "usage: %s [-f <filename>][-l <lang>]\n",
						basename(argv[0]));
				return 1;
		}
	}

	/* default: stdin */
	if (!filename)
		filp = stdin;
	else
	{
		filp = fopen(filename, "rb");
		if (!filp)
		{
			fprintf(stderr, "failed on fopen('%s'): %m", filename);
			return 1;
		}
	}

	/* default: en */
	if (!lang)
		lang = known_langs[0];

	/* default: stdout */
	if (!outfile)
		fout = stdout;
	else
	{
		fout = fopen(outfile, "wb");
		if (!fout)
		{
			fprintf(stderr, "failed on fopen('%s'): %m", outfile);
			return 1;
		}
	}
	parse_i18n(filp, fout, lang);

	if (filename)
		fclose(filp);

	return 0;
}
Example #26
0
void readAndSendEventRamdisk(char *headerLinkFilename) {
  static int errorCounter=0;
  AnitaEventHeader_t *theHeader;
  GenericHeader_t *gHdr;
  int retVal;
  char waveFilename[FILENAME_MAX];
  char headerFilename[FILENAME_MAX];
  char currentTouchname[FILENAME_MAX];
  char currentLOSTouchname[FILENAME_MAX];
  char justFile[FILENAME_MAX];
  unsigned int thisEventNumber;
    
  sprintf(justFile,"%s",basename(headerLinkFilename));
  sscanf(justFile,"hd_%u.dat",&thisEventNumber);
  sprintf(headerFilename,"%s/hd_%d.dat",eventTelemDirs[currentPri], 
	  thisEventNumber);
  sprintf(waveFilename,"%s/psev_%d.dat",eventTelemDirs[currentPri], 
	  thisEventNumber);
    
  sprintf(currentTouchname,"%s.sipd",headerFilename);
  sprintf(currentLOSTouchname,"%s.losd",headerFilename);

  if(checkFileExists(currentTouchname)) 
    return;
  touchFile(currentLOSTouchname);
  //Removing headerLinkFilename
  //  fprintf(stderr,"Removing %s\n",headerLinkFilename);
  unlink(headerLinkFilename);



  //First check if there is room for the header
  if((LOS_MAX_BYTES-numBytesInBuffer)<sizeof(AnitaEventHeader_t))
    doWrite();

    
  //     Next load header 
  theHeader=(AnitaEventHeader_t*) &losBuffer[numBytesInBuffer]; 
  retVal=fillHeader(theHeader,headerFilename); 
  theHeader->gHdr.packetNumber=getLosNumber();
  numBytesInBuffer+=sizeof(AnitaEventHeader_t);

    
  if(retVal<0) {
    unlink(headerFilename);
    unlink(waveFilename);
    unlink(currentLOSTouchname);
    //Bollocks
    return;
  }
    
  thisEventNumber=theHeader->eventNumber;
    

  //Now get event file
  sprintf(headerFilename,"%s/hd_%d.dat",eventTelemDirs[currentPri], 
	  thisEventNumber);
  sprintf(waveFilename,"%s/ev_%d.dat",eventTelemDirs[currentPri], 
	  thisEventNumber);


  retVal=genericReadOfFile(eventBuffer,waveFilename,MAX_EVENT_SIZE);
  if(retVal<0) {
    fprintf(stderr,"Problem reading %s\n",waveFilename);
    unlink(headerFilename);
    unlink(waveFilename);
    unlink(currentLOSTouchname);
	
    //Bollocks
    return;
  }


  //Okay so now the buffer either contains EncodedSurfPacketHeader_t or
  // it contains EncodedPedSubbedSurfPacketHeader_t
  gHdr = (GenericHeader_t*) &eventBuffer[0];
  switch(gHdr->code) {
  case PACKET_BD:
    if(sendWavePackets) 
      retVal=sendRawWaveformPackets(retVal);
    else
      retVal=sendRawSurfPackets(retVal);
    break;
  case PACKET_PED_SUBBED_EVENT:
    if(sendWavePackets)
      retVal=sendPedSubbedWaveformPackets(retVal);
    else 
      retVal=sendPedSubbedSurfPackets(retVal);
    break;
  case PACKET_ENC_EVENT_WRAPPER:
    retVal=sendEncodedSurfPackets(retVal);
    break;
  case PACKET_ENC_PEDSUB_EVENT_WRAPPER:
    if(sendWavePackets)
      retVal=sendEncodedPedSubbedWavePackets(retVal);
    else 
      retVal=sendEncodedPedSubbedSurfPackets(retVal);
    break;
  default:
    if(errorCounter<100) {
      syslog(LOG_ERR,"Don't know what to do with packet %d -- %s (Message %d of 100)\n",gHdr->code,packetCodeAsString(gHdr->code),errorCounter);
      errorCounter++;
    }
    fprintf(stderr,"Don't know what to do with packet %d -- %s (file %s, size %d)\n",gHdr->code,packetCodeAsString(gHdr->code),waveFilename,retVal);
  }
	
  if(printToScreen && verbosity>1) 
    printf("Removing files %s\t%s\n",headerFilename,waveFilename);

  if(!checkFileExists(currentTouchname)) {
    unlink(headerFilename);
    unlink(waveFilename);
    unlink(currentLOSTouchname);
  }
  else {
    printf("Not removing %s because checkFileExists == %d\n",
	   headerFilename,checkFileExists(currentTouchname));
  }
    
}
Example #27
0
// Builds the arguments for the command to be run
int call_system(char *input)
{  
    char * string = malloc((sizeof(char) * strlen(input)) +1);
    strcpy(string, input);
    
    // Remove new line from the end of the input line
    int length = strlen(string);   
    if(string[length-1] == '\n')
        string[length-1] ='\0';
    
    char ** argArray  = NULL;
    char * ptr   = strtok (string, " ");
    char* command;
    int args = 1;
    int catToken = 0;
    char* tempToken = NULL;
    int i = 1;
    char* escapeCheck = NULL; 
    char* result;
    int resultPos = 0;
    
    
    // While more strings, increase the side of result and add the string
    while (ptr) 
    {
        argArray = realloc (argArray, sizeof (char*) * args);

        // If null then alloc failed
        if (argArray == NULL)
            return 1;
            
       // If the first character is a " remove it
       if(ptr[0] == 34)
       {         
           fprintf(stdout, "REMOVING OPENING QUOTE\n");
            catToken = 1;
            length = strlen(ptr);

            tempToken = malloc(sizeof(char) * length);
            // Removes the " from the start of the string
            for(i = 1; i < length; i++)
            {
                tempToken[i-1] = ptr[i];
            }
            // Check the ends for quotes, making sure not to remove them if they are escaped
            if( tempToken[strlen(tempToken)-1] == 34 && tempToken[strlen(tempToken)-2] != 93 )
            {
                fprintf(stdout, "REMOVING CLOSING QUOTE\n");
                tempToken[strlen(tempToken)-1] = '\0';
                catToken = 0;
            }
       }       
       // If we are concatenating a command then check if it ends with an unescaped " and remove it then add the ptr to the command
       else if(catToken == 1)
       {
            // Add the new token onto the old one
            if(ptr[strlen(ptr)-1] == 34 && ptr[strlen(ptr)-2] != 93)
            {
                ptr[strlen(ptr)-1] = '\0';
                catToken = 0;
            }
            strcat(tempToken, " ");
            strcat(tempToken, ptr);
       }             
       // If we have a tempToken then that is the string we are going to check for escape characters, if not then check the raw ptr token
       if(tempToken != NULL)
       {
           escapeCheck = malloc(sizeof(char) * strlen(tempToken));
           strcpy(escapeCheck, tempToken);
           tempToken = NULL;
       }
       else
       {
           escapeCheck = malloc(sizeof(char) * strlen(ptr));
           strcpy(escapeCheck, ptr);
       }
       
       // Create a string to hold the result of eliminated escape characters
       result = malloc(sizeof(char) * strlen(escapeCheck));
       resultPos = 0;
        
       if(result == NULL)
           fputs("Error allocation memory", stderr);
       
       // Remove any \ that are escaping a "
       for(i = 0; i < strlen(escapeCheck); i++)
       {        
           if( !(escapeCheck[i] == 92 && escapeCheck[i+1] == 34) )
           {
               result[resultPos] = escapeCheck[i];
               resultPos++;
           }
       }       
       
       // Finally put the completed command into the correct location
       if(catToken == 0)
       {
            if(args == 1)
            {
                command  = result;
                argArray[args-1] = basename(result);
            }
            else
            {
                argArray[args-1] = result;
            }
            args++;
       }
       
       ptr = strtok (NULL, " ");     
    }

    // Add on extra space for the null value
    argArray = realloc (argArray, sizeof (char*) * (args+1));
    argArray[args] = '\0';    
        
    execvp(command, argArray);
        
    // Free up memory
    free(result);
    free(string);
    free(ptr);
    
    return 0;
}
Example #28
0
File: cpm.c Project: atluxity/cpm
/* if don't have any envorin variable at all */
int main(int argc, char **argv, char **envp)
#endif
#endif
  {
    rlim_t              memlock_limit = -2;
    int                 error = 0,
                        max_mem_lock = 0,
                        memory_safe = 0,
                        ptrace_safe = 0;
#ifdef TEST_OPTION
    int                 testrun = 0;
#endif
    char*               binaryname;

    savetermios();
    TRACE(99, "main()", NULL);

#ifndef HAVE_EXTERN_ENVIRON
#ifndef MANUAL_EXTERN_ENVIRON
    /* since in solaris environ does not exist, we manually pass it along */
    environ = envp;
#endif
#endif

    if (initSecurity(&max_mem_lock, &memory_safe, &ptrace_safe, &memlock_limit))
      { exit(1); }

    /* we initialize gettext */
    setlocale(LC_ALL, "");
#ifdef TEST_OPTION
    bindtextdomain(PACKAGE_NAME, "./po/");
#else
    bindtextdomain(PACKAGE_NAME, LOCALEDIR);
#endif
    textdomain(PACKAGE_NAME);

#ifndef LIBXML_TREE_ENABLED
    fprintf(stderr, _("Tree support not compiled in to libxml2 %s\n"),
        LIBXML_DOTTED_VERSION);
    exit(1);
#endif

    /*
     * This function installs "sighandler" to handle the SIGINT and returns a
     * pointer to the previously installed handler for this signal (which is
     * the default handler SIG_DFL initially). If we try to install another
     * handler to handle SIGINT at some other time... Then the new handler
     * replaces this current one and returns a pointer to this handler.
     */
    signal(SIGINT, sighandler);
    signal(SIGTERM, sighandler);
    /* the SIGWINCH handler is set in userInterface() */

    initConfiguration();

    runtime -> memlock_limit  = memlock_limit;
    runtime -> max_mem_lock   = max_mem_lock;
    runtime -> memory_safe    = memory_safe;
    runtime -> ptrace_safe    = ptrace_safe;

    initKeys();
    initPatternparser();
    initXML();
    initXMLInterface();

    if (getOptions(argc, argv))
      {
        fprintf(stderr, _("Try `%s --help' for more information.\n"), argv[0]);
        error = 1;
      }
    if (!error && config -> help)
      { showHelp(); }
    else if (!error && config -> version)
      { showVersion(); }
    else if (!error)
      {
        getDefaultOptions();
        if (readResources())
            return 1;

        if (config -> dbfilecmd)
          {   /* the --file option must overwrite the resource file */
            runtime -> dbfile = resolveFilelink(config -> dbfilecmd);
          }
        else
          {   /* we use the resource file configuration or the compiletime
               * default
               */
            runtime -> dbfile = resolveFilelink(config -> dbfilerc);
          }
      }

    /* we switch to read-only mode on request */
    if (config -> readonly)
      { runtime -> readonly = 1; }

    /* in case our basename is cpmv, we switch to read-only mode */
    binaryname = basename(argv[0]);
    if (!strcmp(binaryname, "cpmv"))
      { runtime -> readonly = 1; }

    initGPG();

    if (!error && config -> security)
      { checkSecurity(0); }

#ifdef TEST_OPTION
    if (!error &&
        config -> testrun &&
        !strncmp(config -> testrun, "compress", 8))
      {
        testCompress();
        testrun = 1;
      }
    if (!error &&
        config -> testrun &&
        !strcmp(config -> testrun, "environment"))
      {
        testEnvironment();
        testrun = 1;
      }
    if (!error &&
        config -> testrun && (
        !strcmp(config -> testrun, "backup") ||
        !strcmp(config -> testrun, "garbage") ||
        !strcmp(config -> testrun, "searchpattern")))
      { testrun = 1; }
#endif

    if (config -> configtest &&
        !error)
      { fprintf(stderr, _("configuration ok.\n")); }

    if (config -> environtmentlist &&
        !error)
      { listEnvironment(); }

    if (!error &&
        !config -> configtest &&
        !config -> environtmentlist &&
        !config -> help &&
        !config -> security &&
        !config -> version)
      {
#ifdef TEST_OPTION
        if (checkSecurity(1) != MAX_SECURITY_LEVEL &&
            !config -> testrun)
#else
        if (checkSecurity(1) != MAX_SECURITY_LEVEL)
#endif
          {
            checkSecurity(0);
            printf("\n%s %s\n%s\n",
                _("Maximum security level not reached."),
                _("Your database will be less protected while CPM is running."),
                _("Are you sure you want to continue?"),
                _("Press CTRL+C to stop now or ENTER to continue."));

            fgetc(stdin);
          }
        if (runtime -> guimode)
          {   /* we run in interactive mode */
            userInterface();
          }
        else
          {   /* we run in CLI mode */
            error = cliInterface();
#ifdef TEST_OPTION
            if (error == 2)
              {   /* for testruns, we must modify the stuff a little */
                error = 0;
                testrun = 1;
              }
#endif
          }
      }

    freeGPG();
    freeXMLInterface();
    freeUTF8Interface();
    freeXML();
    freePatternparser();
    freeKeys();
    freeConfiguration();

    if (memCheck())
      {   /* we validate our memory consumption */
        fprintf(stderr, _("error: memory leak detected.\n"));
        if (memCheck() > 0)
          {
            fprintf(stderr, _("%ld byte of memory were not freed.\n"),
                memCheck());
          }
        else
          {
            fprintf(stderr,
                _("%ld byte of memory were freed without being allocated.\n"),
                memCheck());
          }

        fprintf(stderr, _("Please send a report about this problem to Harry Brueckner <*****@*****.**>.\n"));

        error = 1;
      }

#ifdef TEST_OPTION
    if (testrun)
      { return 0; }
    else
      { return error; }
#else
    return error;
#endif
  }
Example #29
0
void write_log (int level, const char *filename, const char *funcname, int lineno, const char *format, ...)
{
    // save errno
    int savedErrNo = errno;
    int off = 0;
    int n_write;
    char buf[LOGSIZE];
    char logfile[512];
    int fd = -1;
    struct stat stBuf;
    bool btruncate = false;
    struct tm tm;
    time_t now = time (NULL);

    localtime_r(&now, &tm);
    filename = basename(filename);
    off = snprintf (buf, LOGSIZE-1,
            "<%2d>[%04d%02d%02d-%02d:%02d:%02d] pid[%d]: %s(%d)[%s]: ",
            level,
            tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
            tm.tm_hour, tm.tm_min, tm.tm_sec,
            getpid(),
            filename, lineno, funcname
            );
    do
    {
        if(!appname[0])
        {
            fprintf(stderr, "ATTENTION: the prefix of the log file is not set\n");
            return;
        }
        
        snprintf (logfile, MAX_PATH_LEN-1, "%s/%s_%d.log",
                log_dir, appname,
                cur_file_pos);



        int flags = O_CREAT | O_LARGEFILE | O_APPEND | O_WRONLY;
        if(btruncate)
            flags |= O_TRUNC;

        fd = open (logfile, flags, 0644);
        if (fd < 0)
        {
            fprintf(stderr, "ATTENTION: open log file failed, dir[%s] file[%s], error[%m]\n", log_dir, appname);
            return;
        }

        if(-1 == fstat(fd, &stBuf))
        {
            fprintf(stderr, "ATTENTION: stat log file failed, dir[%s] file[%s], error[%m]\n", log_dir, appname);
            return;
        }

        if((int)stBuf.st_size >= max_file_size)
        {
            cur_file_pos = (cur_file_pos + 1)%max_file_num;
            close(fd);
            fd = -1;
            btruncate = true;
            continue;
        }
        else
        {
            break;
        }

    }while(true);

    va_list ap;
    va_start(ap, format);
    // restore errno
    errno = savedErrNo;
    n_write= vsnprintf(buf+off, LOGSIZE-off-2, format, ap);
    va_end(ap);

    if(n_write>=LOGSIZE-off-2)
        off=LOGSIZE-2;
    else
        off+=n_write;
    
    if(buf[off-1] != '\n')
        buf[off++] = '\n';

    if (-1 == level)
        fwrite(buf, 1, off, stderr);//print stdout

	if(__log_stdout__)
	{
		write(1, buf, off);
	}
	else
	{
		write(fd, buf, off);
		close (fd);
	}
}
Example #30
0
int main(int argc, char *argv[])
{
	// allows multiple src
	//char **src_path;
	//char *dst_path;
	struct file_s **src;
	struct file_s *dst;
	int nsrc=0;

	int ch;
	int i;


	static struct option long_options[] = {
		{"paranoid", 1, 0, 'c'},
		{NULL, 0 , NULL, 0}
	};

	option.paranoid = 0;
	option.recursive = 0;
	while ((ch = getopt_long(argc, argv, "c", long_options, NULL)) != -1)
	{
		switch (ch) {
			// paranoid copy mode
			// compare original and copied file by using sha-512
			case 'c':
				option.paranoid = 1;
				break;
			default:
				show_usage();
		}
	}

	struct stat stat_buf;
	if (argc-optind >= 2)
	{
		nsrc = argc-optind-1;
		src = malloc(sizeof(struct file_s*) * argc-optind-1);
		if (src == NULL) error_exit(-ENOMEM);
		for (i=optind; i<argc; ++i)
		{
			int size_path = MIN(strlen(argv[i]),PATH_MAX);
			if (i==argc-1)
			{
				dst = malloc(sizeof(struct file_s));
				if (dst == NULL) error_exit(-ENOMEM);
				dst->path = malloc(size_path);
				if (dst->path == NULL) error_exit(-ENOMEM);
				if (stat(argv[i],&stat_buf) == 0)
				{
				
					if (S_ISDIR(stat_buf.st_mode))
					{
						dst->isdir = 1;
					}
					else
					{
						// コピー元が複数にもかかわらず、コピー先がディレクトリでない場合はエラー
						if (nsrc >= 2)
						{
							perror("target is not a directory.");
							exit(EXIT_FAILURE);
						}
					}

					//dst = malloc(size_dst);
					strncpy(dst->path,argv[i],size_path);
				}
				else
				{
					// コピー元が複数にもかかわらず、コピー先ディレクトリがない場合はエラー
					if (nsrc >= 2)
					{
						perror(argv[i]);
						exit(EXIT_FAILURE);
					}
					// コピー元がひとつの場合、コピー先がなければ新規作成となるのでエラーにはしない
					strncpy(dst->path,argv[i],size_path);
				}
			}
			else
			{
				if (stat(argv[i],&stat_buf) == 0)
				{
					int idx = i-optind;
					src[idx] = malloc(sizeof(struct file_s));
					if (src[idx] == NULL) error_exit(-ENOMEM);
					if (S_ISDIR(stat_buf.st_mode))
					{
						if (option.recursive == 0)
						{
							fprintf(stderr,"ommiting directory: %s\n",argv[i]);
							break;
						}
						src[idx]->isdir = 1;
					}
					//src_path[idx] = malloc(size_dst);

					src[idx]->path = malloc(size_path);
					if (src[idx]->path == NULL) error_exit(-ENOMEM);
					strncpy(src[idx]->path,argv[i],size_path);
				}
			}
		}
	}
	else {
		show_usage();
	}

	// dstがファイルかつsrcが複数でないとき
	if (nsrc == 1)
	{
#ifdef DEBUG
		printf("src is single file\n");
#endif
		if (do_copy(src[0],dst) == -1)
		{
			fprintf(stderr,"'%s'->'%s' CRC doesn't match\n",src[0]->path,dst->path);
		}
	}
	else {
		for (i=0; i<nsrc; ++i)
		{
			// dstがディレクトリなら、dst_filename=dst_dir/basename(src_path)
			if (dst->isdir == 1)
			{
#ifdef DEBUG
				printf("dst is directory %s\n",dst->path);
#endif
				//char *dirc,  *dname;
				char *basec, *bname;
				//char *tmp;
				//dirc = strdup(src[i]->path);
				basec = strdup(src[i]->path);
				//dname = dirname(dirc);
				bname = basename(basec);
				int dst_filename_size = MIN(strlen(dst->path)+1+strlen(bname)+1,PATH_MAX);

				// copy struct files*
				struct file_s *dsttmp;
				dsttmp = malloc(sizeof(struct file_s));
				if (dsttmp == NULL) error_exit(-ENOMEM);
				char dst_filename[PATH_MAX+1];
				dsttmp->path = dst_filename;
				strncpy(dsttmp->path,dst->path,PATH_MAX);
				dsttmp->isdir = dst->isdir;

				char *pathdup = strdup(dsttmp->path);
				snprintf(dsttmp->path,dst_filename_size,"%s/%s",pathdup,bname);
				char dst_realpath[PATH_MAX+1];
				realpath(dsttmp->path,dst_realpath);
				dsttmp->path = dst_realpath;
				free(pathdup); // strdup
				free(basec); // strdup
	
				if (do_copy(src[i],dsttmp) == -1)
				{
					fprintf(stderr,"'%s'->'%s' CRC doesn't match\n",src[i]->path,dsttmp->path);
				}
				//free(tmp); // realloc
				free(dsttmp); // realloc
			}
		}
	}
	return 0;
}