Esempio n. 1
0
static char * ATTRIBUTE_WARN_UNUSED_RESULT
human_time (struct timespec t)
{
  /* STR must be at least this big, either because localtime_rz fails,
     or because the time zone is truly outlandish so that %z expands
     to a long string.  */
  enum { intmax_bufsize = INT_BUFSIZE_BOUND (intmax_t) };

  static char str[intmax_bufsize
                  + INT_STRLEN_BOUND (int) /* YYYY */
                  + 1 /* because YYYY might equal INT_MAX + 1900 */
                  + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +"];
  static timezone_t tz;
  if (!tz)
    tz = tzalloc (getenv ("TZ"));
  struct tm tm;
  int ns = t.tv_nsec;
  if (localtime_rz (tz, &t.tv_sec, &tm))
    nstrftime (str, sizeof str, "%Y-%m-%d %H:%M:%S.%N %z", &tm, tz, ns);
  else
    {
      char secbuf[INT_BUFSIZE_BOUND (intmax_t)];
      sprintf (str, "%s.%09d", timetostr (t.tv_sec, secbuf), ns);
    }
  return str;
}
Esempio n. 2
0
int
main (int argc, char **argv)
{
  char limit[1 + MAX (INT_BUFSIZE_BOUND (intmax_t),
                      INT_BUFSIZE_BOUND (uintmax_t))];

  initialize_main (&argc, &argv);
  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  initialize_exit_failure (EXIT_FAILURE);
  atexit (close_stdout);

  parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, VERSION,
                      usage, AUTHORS, (char const *) NULL);

#define print_int(TYPE)                                                  \
  sprintf (limit + 1, "%"PRIuMAX, (uintmax_t) TYPE##_MAX);               \
  printf (#TYPE"_MAX=%s\n", limit + 1);                                  \
  printf (#TYPE"_OFLOW=%s\n", decimal_absval_add_one (limit));           \
  if (TYPE##_MIN)                                                        \
    {                                                                    \
      sprintf (limit + 1, "%"PRIdMAX, (intmax_t) TYPE##_MIN);            \
      printf (#TYPE"_MIN=%s\n", limit + 1);                              \
      printf (#TYPE"_UFLOW=%s\n", decimal_absval_add_one (limit));       \
    }

#define print_float(TYPE)                                                \
  printf (#TYPE"_MIN=%Le\n", (long double)TYPE##_MIN);                   \
  printf (#TYPE"_MAX=%Le\n", (long double)TYPE##_MAX);

  /* Variable sized ints */
  print_int (CHAR);
  print_int (SCHAR);
  print_int (UCHAR);
  print_int (SHRT);
  print_int (INT);
  print_int (UINT);
  print_int (LONG);
  print_int (ULONG);
  print_int (SIZE);
  print_int (SSIZE);
  print_int (TIME_T);
  print_int (UID_T);
  print_int (GID_T);
  print_int (PID_T);
  print_int (OFF_T);
  print_int (INTMAX);
  print_int (UINTMAX);

  /* Variable sized floats */
  print_float (FLT);
  print_float (DBL);
  print_float (LDBL);
}
Esempio n. 3
0
File: expr.c Progetto: DonCN/haiku
static char *
mpz_get_str (char const *str, int base, mpz_t z)
{
  char buf[INT_BUFSIZE_BOUND (intmax_t)];
  (void) str; (void) base;
  return xstrdup (imaxtostr (z[0], buf));
}
Esempio n. 4
0
File: expr.c Progetto: DonCN/haiku
static int
mpz_out_str (FILE *stream, int base, mpz_t z)
{
  char buf[INT_BUFSIZE_BOUND (intmax_t)];
  (void) base;
  return fputs (imaxtostr (z[0], buf), stream) != EOF;
}
Esempio n. 5
0
static bool
check_sparse_region (struct tar_sparse_file *file, off_t beg, off_t end)
{
  if (!lseek_or_error (file, beg))
    return false;

  while (beg < end)
    {
      size_t bytes_read;
      size_t rdsize = BLOCKSIZE < end - beg ? BLOCKSIZE : end - beg;
      char diff_buffer[BLOCKSIZE];

      bytes_read = safe_read (file->fd, diff_buffer, rdsize);
      if (bytes_read == SAFE_READ_ERROR)
	{
          read_diag_details (file->stat_info->orig_file_name,
	                     beg,
			     rdsize);
	  return false;
	}
      if (!zero_block_p (diff_buffer, bytes_read))
	{
	  char begbuf[INT_BUFSIZE_BOUND (off_t)];
 	  report_difference (file->stat_info,
			     _("File fragment at %s is not a hole"),
			     offtostr (beg, begbuf));
	  return false;
	}

      beg += bytes_read;
    }
  return true;
}
Esempio n. 6
0
int virPidFileWritePath(const char *pidfile,
                        pid_t pid)
{
    int rc;
    int fd;
    char pidstr[INT_BUFSIZE_BOUND(pid)];

    if ((fd = open(pidfile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR)) < 0) {
        rc = -errno;
        goto cleanup;
    }

    snprintf(pidstr, sizeof(pidstr), "%lld", (long long) pid);

    if (safewrite(fd, pidstr, strlen(pidstr)) < 0) {
        rc = -errno;
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }

    rc = 0;

cleanup:
    if (VIR_CLOSE(fd) < 0)
        rc = -errno;

    return rc;
}
Esempio n. 7
0
static void
read_negative_num (FILE *fp, intmax_t min_val, intmax_t *pval)
{
  int c;
  size_t i;
  char buf[INT_BUFSIZE_BOUND (intmax_t)];
  char *ep;
  buf[0] = '-';

  for (i = 1; ISDIGIT (c = getc (fp)); i++)
    {
      if (i == sizeof buf - 1)
	FATAL_ERROR ((0, 0, _("Field too long while reading snapshot file")));
      buf[i] = c;
    }

  if (c < 0)
    {
      if (ferror (fp))
	FATAL_ERROR ((0, errno, _("Read error in snapshot file")));
      else
	FATAL_ERROR ((0, 0, _("Unexpected EOF in snapshot file")));
    }

  buf[i] = 0;
  errno = 0;
  *pval = strtoimax (buf, &ep, 10);
  if (c || errno || *pval < min_val)
    FATAL_ERROR ((0, errno, _("Unexpected field value in snapshot file")));
}
Esempio n. 8
0
/* Read incremental snapshot format 2 */
static void
read_incr_db_2 (void)
{
  struct obstack stk;
  char offbuf[INT_BUFSIZE_BOUND (off_t)];

  obstack_init (&stk);

  read_timespec (listed_incremental_stream, &newer_mtime_option);

  for (;;)
    {
      intmax_t i;
      struct timespec mtime;
      dev_t dev;
      ino_t ino;
      bool nfs;
      char *name;
      char *content;
      size_t s;

      if (! read_num (listed_incremental_stream, "nfs", 0, 1, &i))
	return; /* Normal return */

      nfs = i;

      read_timespec (listed_incremental_stream, &mtime);

      if (! read_num (listed_incremental_stream, "dev",
		      TYPE_MINIMUM (dev_t), TYPE_MAXIMUM (dev_t), &i))
	break;
      dev = i;

      if (! read_num (listed_incremental_stream, "ino",
		      TYPE_MINIMUM (ino_t), TYPE_MAXIMUM (ino_t), &i))
	break;
      ino = i;

      if (read_obstack (listed_incremental_stream, &stk, &s))
	break;

      name = obstack_finish (&stk);

      while (read_obstack (listed_incremental_stream, &stk, &s) == 0 && s > 1)
	;
      if (getc (listed_incremental_stream) != 0)
	FATAL_ERROR ((0, 0, _("%s: byte %s: %s"),
		      quotearg_colon (listed_incremental_option),
		      offtostr (ftello (listed_incremental_stream), offbuf),
		      _("Missing record terminator")));

      content = obstack_finish (&stk);
      note_directory (name, mtime, dev, ino, nfs, false, content);
      obstack_free (&stk, content);
    }
  FATAL_ERROR ((0, 0, "%s: %s",
		quotearg_colon (listed_incremental_option),
		_("Unexpected EOF in snapshot file")));
}
Esempio n. 9
0
extern char *
uid_to_name (uid_t uid)
{
    char buf[INT_BUFSIZE_BOUND (intmax_t)];
    struct passwd *pwd = getpwuid (uid);
    return xstrdup (pwd ? pwd->pw_name
                    : TYPE_SIGNED (uid_t) ? imaxtostr (uid, buf)
                    : umaxtostr (uid, buf));
}
Esempio n. 10
0
extern char *
gid_to_name (gid_t gid)
{
    char buf[INT_BUFSIZE_BOUND (intmax_t)];
    struct group *grp = getgrgid (gid);
    return xstrdup (grp ? grp->gr_name
                    : TYPE_SIGNED (gid_t) ? imaxtostr (gid, buf)
                    : umaxtostr (gid, buf));
}
Esempio n. 11
0
static char * ATTRIBUTE_WARN_UNUSED_RESULT
human_time (struct timespec t)
{
  static char str[MAX (INT_BUFSIZE_BOUND (intmax_t),
                       (INT_STRLEN_BOUND (int) /* YYYY */
                        + 1 /* because YYYY might equal INT_MAX + 1900 */
                        + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +ZZZZ"))];
  struct tm const *tm = localtime (&t.tv_sec);
  if (tm == NULL)
    return timetostr (t.tv_sec, str);
  nstrftime (str, sizeof str, "%Y-%m-%d %H:%M:%S.%N %z", tm, 0, t.tv_nsec);
  return str;
}
Esempio n. 12
0
static void
out_of_range_header (char const *keyword, char const *value,
		     intmax_t minval, uintmax_t maxval)
{
  char minval_buf[INT_BUFSIZE_BOUND (intmax_t)];
  char maxval_buf[UINTMAX_STRSIZE_BOUND];
  char *minval_string = imaxtostr (minval, minval_buf);
  char *maxval_string = umaxtostr (maxval, maxval_buf);

  /* TRANSLATORS: The first %s is the pax extended header keyword
     (atime, gid, etc.).  */
  ERROR ((0, 0, _("Extended header %s=%s is out of range %s..%s"),
	  keyword, value, minval_string, maxval_string));
}
Esempio n. 13
0
/*
 * Bridge parameters can be set via sysfs on newish kernels,
 * or by  ioctl on older kernels. Perhaps we could just use
 * ioctl for every kernel, but its not clear what the long
 * term lifespan of the ioctl interface is...
 */
static int virNetDevBridgeSet(const char *brname,
                              const char *paramname,  /* sysfs param name */
                              unsigned long value,    /* new value */
                              int fd,                 /* control socket */
                              struct ifreq *ifr)      /* pre-filled bridge name */
{
    char *path = NULL;
    int ret = -1;

    if (virAsprintf(&path, "%s/%s/bridge/%s", SYSFS_NET_DIR, brname, paramname) < 0) {
        virReportOOMError();
        return -1;
    }

    if (virFileExists(path)) {
        char valuestr[INT_BUFSIZE_BOUND(value)];
        snprintf(valuestr, sizeof(valuestr), "%lu", value);
        if (virFileWriteStr(path, valuestr, 0) < 0) {
            virReportSystemError(errno,
                                 _("Unable to set bridge %s %s"), brname, paramname);
            goto cleanup;
        }
    } else {
        unsigned long paramid;
        if (STREQ(paramname, "stp_state")) {
            paramid = BRCTL_SET_BRIDGE_STP_STATE;
        } else if (STREQ(paramname, "forward_delay")) {
            paramid = BRCTL_SET_BRIDGE_FORWARD_DELAY;
        } else {
            virReportSystemError(EINVAL,
                                 _("Unable to set bridge %s %s"), brname, paramname);
            goto cleanup;
        }
        unsigned long args[] = { paramid, value, 0, 0 };
        ifr->ifr_data = (char*)&args;
        if (ioctl(fd, SIOCDEVPRIVATE, ifr) < 0) {
            virReportSystemError(errno,
                                 _("Unable to set bridge %s %s"), brname, paramname);
            goto cleanup;
        }
    }

    ret = 0;
cleanup:
    VIR_FREE(path);
    return ret;
}
Esempio n. 14
0
/* Return the positive decimal contents of the given
 * DIR/cpu%u/FILE, or -1 on error.  If MISSING_OK and the
 * file could not be found, return 1 instead of an error; this is
 * because some machines cannot hot-unplug cpu0, or because
 * hot-unplugging is disabled.  */
static int
virNodeGetCpuValue(const char *dir, unsigned int cpu, const char *file,
                   bool missing_ok)
{
    char *path;
    FILE *pathfp;
    int value = -1;
    char value_str[INT_BUFSIZE_BOUND(value)];
    char *tmp;

    if (virAsprintf(&path, "%s/cpu%u/%s", dir, cpu, file) < 0) {
        virReportOOMError();
        return -1;
    }

    pathfp = fopen(path, "r");
    if (pathfp == NULL) {
        if (missing_ok && errno == ENOENT)
            value = 1;
        else
            virReportSystemError(errno, _("cannot open %s"), path);
        goto cleanup;
    }

    if (fgets(value_str, sizeof(value_str), pathfp) == NULL) {
        virReportSystemError(errno, _("cannot read from %s"), path);
        goto cleanup;
    }
    if (virStrToLong_i(value_str, &tmp, 10, &value) < 0) {
        nodeReportError(VIR_ERR_INTERNAL_ERROR,
                        _("could not convert '%s' to an integer"),
                        value_str);
        goto cleanup;
    }

cleanup:
    VIR_FORCE_FCLOSE(pathfp);
    VIR_FREE(path);

    return value;
}
Esempio n. 15
0
int virPidFileReadPath(const char *path,
                       pid_t *pid)
{
    int fd;
    int rc;
    ssize_t bytes;
    long long pid_value = 0;
    char pidstr[INT_BUFSIZE_BOUND(pid_value)];
    char *endptr = NULL;

    *pid = 0;

    if ((fd = open(path, O_RDONLY)) < 0) {
        rc = -errno;
        goto cleanup;
    }

    bytes = saferead(fd, pidstr, sizeof(pidstr));
    if (bytes < 0) {
        rc = -errno;
        VIR_FORCE_CLOSE(fd);
        goto cleanup;
    }
    pidstr[bytes] = '\0';

    if (virStrToLong_ll(pidstr, &endptr, 10, &pid_value) < 0 ||
        !(*endptr == '\0' || c_isspace(*endptr)) ||
        (pid_t) pid_value != pid_value) {
        rc = -1;
        goto cleanup;
    }

    *pid = pid_value;
    rc = 0;

cleanup:
    if (VIR_CLOSE(fd) < 0)
        rc = -errno;

    return rc;
}
Esempio n. 16
0
static int
build_policy (pskc_key_t * kp, xmlNodePtr keyp)
{
  int keyusage_p;
  int keyusages = pskc_get_key_policy_keyusages (kp, &keyusage_p);
  const struct tm *startdate = pskc_get_key_policy_startdate (kp);
  const struct tm *expirydate = pskc_get_key_policy_expirydate (kp);
  const char *pinkeyid = pskc_get_key_policy_pinkeyid (kp);
  int pinusagemode_p;
  pskc_pinusagemode pinusagemode =
    pskc_get_key_policy_pinusagemode (kp, &pinusagemode_p);
  int attempts_p;
  uint32_t attempts =
    pskc_get_key_policy_pinmaxfailedattempts (kp, &attempts_p);
  int pinmin_p;
  uint32_t pinmin = pskc_get_key_policy_pinminlength (kp, &pinmin_p);
  int pinmax_p;
  uint32_t pinmax = pskc_get_key_policy_pinmaxlength (kp, &pinmax_p);
  int pinencoding_p;
  pskc_valueformat pinencoding =
    pskc_get_key_policy_pinencoding (kp, &pinencoding_p);
  int numberoftransactions_p;
  uint64_t numberoftransactions = pskc_get_key_policy_numberoftransactions
    (kp, &numberoftransactions_p);
  xmlNodePtr policy, pinpolicy;

  if (!keyusage_p && !startdate && !expirydate && !pinkeyid && !pinusagemode_p
      && !attempts_p && !pinmin_p && !pinmax_p && !pinencoding_p)
    return PSKC_OK;

  policy = xmlNewChild (keyp, NULL, BAD_CAST "Policy", NULL);

  if (startdate)
    {
      char t[100];
      strftime (t, sizeof (t), "%Y-%m-%dT%H:%M:%SZ", startdate);
      xmlNewTextChild (policy, NULL, BAD_CAST "StartDate", BAD_CAST t);
    }

  if (expirydate)
    {
      char t[100];
      strftime (t, sizeof (t), "%Y-%m-%dT%H:%M:%SZ", expirydate);
      xmlNewTextChild (policy, NULL, BAD_CAST "ExpiryDate", BAD_CAST t);
    }

  if (pinkeyid || pinusagemode_p || attempts_p
      || pinmin_p || pinmax_p || pinencoding_p)
    {
      pinpolicy = xmlNewChild (policy, NULL, BAD_CAST "PINPolicy", NULL);

      if (pinkeyid)
	xmlNewProp (pinpolicy, BAD_CAST "PINKeyId", BAD_CAST pinkeyid);

      if (pinusagemode_p)
	xmlNewProp (pinpolicy, BAD_CAST "PINUsageMode",
		    BAD_CAST pskc_pinusagemode2str (pinusagemode));

      if (attempts_p)
	{
	  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
	  char *p = umaxtostr (attempts, buf);
	  xmlNewProp (pinpolicy, BAD_CAST "MaxFailedAttempts", BAD_CAST p);
	}

      if (pinmin_p)
	{
	  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
	  char *p = umaxtostr (pinmin, buf);
	  xmlNewProp (pinpolicy, BAD_CAST "MinLength", BAD_CAST p);
	}

      if (pinmax_p)
	{
	  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
	  char *p = umaxtostr (pinmax, buf);
	  xmlNewProp (pinpolicy, BAD_CAST "MaxLength", BAD_CAST p);
	}

      if (pinencoding_p)
	xmlNewProp (pinpolicy, BAD_CAST "PINEncoding",
		    BAD_CAST pskc_valueformat2str (pinencoding));
    }

  if (keyusage_p)
    {
      int i;
      for (i = 1; i <= PSKC_KEYUSAGE_LAST; i = i << 1)
	{
	  const char *keyusage_str = pskc_keyusage2str (i);

	  if (keyusages & i)
	    xmlNewTextChild (policy, NULL, BAD_CAST "KeyUsage",
			     BAD_CAST keyusage_str);
	}
    }

  if (numberoftransactions_p)
    {
      char buf[INT_BUFSIZE_BOUND (uintmax_t)];
      char *p = umaxtostr (numberoftransactions, buf);
      xmlNewTextChild (policy, NULL, BAD_CAST "NumberOfTransactions",
		       BAD_CAST p);
    }

  return PSKC_OK;
}
Esempio n. 17
0
static bool
read_num (FILE *fp, char const *fieldname,
	  intmax_t min_val, uintmax_t max_val, intmax_t *pval)
{
  int i;
  char buf[INT_BUFSIZE_BOUND (intmax_t)];
  char offbuf[INT_BUFSIZE_BOUND (off_t)];
  char minbuf[INT_BUFSIZE_BOUND (intmax_t)];
  char maxbuf[INT_BUFSIZE_BOUND (intmax_t)];
  int conversion_errno;
  int c = getc (fp);
  bool negative = c == '-';

  for (i = 0; (i == 0 && negative) || ISDIGIT (c); i++)
    {
      buf[i] = c;
      if (i == sizeof buf - 1)
	FATAL_ERROR ((0, 0,
		      _("%s: byte %s: %s %.*s... too long"),
		      quotearg_colon (listed_incremental_option),
		      offtostr (ftello (fp), offbuf),
		      fieldname, i + 1, buf));
      c = getc (fp);
    }

  buf[i] = 0;

  if (c < 0)
    {
      if (ferror (fp))
	read_fatal (listed_incremental_option);
      if (i != 0)
	FATAL_ERROR ((0, 0, "%s: %s",
		      quotearg_colon (listed_incremental_option),
		      _("Unexpected EOF in snapshot file")));
      return false;
    }

  if (c)
    {
      unsigned uc = c;
      FATAL_ERROR ((0, 0,
		    _("%s: byte %s: %s %s followed by invalid byte 0x%02x"),
		    quotearg_colon (listed_incremental_option),
		    offtostr (ftello (fp), offbuf),
		    fieldname, buf, uc));
    }

  *pval = strtosysint (buf, NULL, min_val, max_val);
  conversion_errno = errno;

  switch (conversion_errno)
    {
    case ERANGE:
      FATAL_ERROR ((0, conversion_errno,
		    _("%s: byte %s: (valid range %s..%s)\n\t%s %s"),
		    quotearg_colon (listed_incremental_option),
		    offtostr (ftello (fp), offbuf),
		    imaxtostr (min_val, minbuf),
		    umaxtostr (max_val, maxbuf), fieldname, buf));
    default:
      FATAL_ERROR ((0, conversion_errno,
		    _("%s: byte %s: %s %s"),
		    quotearg_colon (listed_incremental_option),
		    offtostr (ftello (fp), offbuf), fieldname, buf));
    case 0:
      break;
    }

  return true;
}
Esempio n. 18
0
File: userspec.c Progetto: 8l/csolve
static char const *
parse_with_separator (char const *spec, char const *separator,
                      uid_t *uid, gid_t *gid,
                      char **username, char **groupname)
{
  static const char *E_invalid_user = N_("invalid user");
  static const char *E_invalid_group = N_("invalid group");
  static const char *E_bad_spec = N_("invalid spec");

  const char *error_msg;
  struct passwd *pwd;
  struct group *grp;
  char *u;
  char const *g;
  char *gname = NULL;
  uid_t unum = *uid;
  gid_t gnum = *gid;

  error_msg = NULL;
  *username = *groupname = NULL;

  /* Set U and G to nonzero length strings corresponding to user and
     group specifiers or to NULL.  If U is not NULL, it is a newly
     allocated string.  */

  u = NULL;
  if (separator == NULL)
    {
      if (*spec)
        u = xstrdup (spec);
    }
  else
    {
      size_t ulen = separator - spec;
      if (ulen != 0)
        {
          u = xmemdup (spec, ulen + 1);
          u[ulen] = '\0';
        }
    }

  g = (separator == NULL || *(separator + 1) == '\0'
       ? NULL
       : separator + 1);

#ifdef __DJGPP__
  /* Pretend that we are the user U whose group is G.  This makes
     pwd and grp functions ``know'' about the UID and GID of these.  */
  if (u && !is_number (u))
    setenv ("USER", u, 1);
  if (g && !is_number (g))
    setenv ("GROUP", g, 1);
#endif

  if (u != NULL)
    {
      /* If it starts with "+", skip the look-up.  */
      pwd = (*u == '+' ? NULL : getpwnam (u));
      if (pwd == NULL)
        {
          bool use_login_group = (separator != NULL && g == NULL);
          if (use_login_group)
            {
              /* If there is no group,
                 then there may not be a trailing ":", either.  */
              error_msg = E_bad_spec;
            }
          else
            {
              unsigned long int tmp;
              if (xstrtoul (u, NULL, 10, &tmp, "") == LONGINT_OK
                  && tmp <= MAXUID && (uid_t) tmp != (uid_t) -1)
                unum = tmp;
              else
                error_msg = E_invalid_user;
            }
        }
      else
        {
          unum = pwd->pw_uid;
          if (g == NULL && separator != NULL)
            {
              /* A separator was given, but a group was not specified,
                 so get the login group.  */
              char buf[INT_BUFSIZE_BOUND (uintmax_t)];
              gnum = pwd->pw_gid;
              grp = getgrgid (gnum);
              gname = xstrdup (grp ? grp->gr_name : umaxtostr (gnum, buf));
              endgrent ();
            }
        }
      endpwent ();
    }

  if (g != NULL && error_msg == NULL)
    {
      /* Explicit group.  */
      /* If it starts with "+", skip the look-up.  */
      grp = (*g == '+' ? NULL : getgrnam (g));
      if (grp == NULL)
        {
          unsigned long int tmp;
          if (xstrtoul (g, NULL, 10, &tmp, "") == LONGINT_OK
              && tmp <= MAXGID && (gid_t) tmp != (gid_t) -1)
            gnum = tmp;
          else
            error_msg = E_invalid_group;
        }
      else
        gnum = grp->gr_gid;
      endgrent ();              /* Save a file descriptor.  */
      gname = xstrdup (g);
    }

  if (error_msg == NULL)
    {
      *uid = unum;
      *gid = gnum;
      *username = u;
      *groupname = gname;
      u = NULL;
    }
  else
    free (gname);

  free (u);
  return _(error_msg);
}
Esempio n. 19
0
int linuxNodeGetCPUStats(FILE *procstat,
                         int cpuNum,
                         virNodeCPUStatsPtr params,
                         int *nparams)
{
    int ret = -1;
    char line[1024];
    unsigned long long usr, ni, sys, idle, iowait;
    unsigned long long irq, softirq, steal, guest, guest_nice;
    char cpu_header[3 + INT_BUFSIZE_BOUND(cpuNum)];

    if ((*nparams) == 0) {
        /* Current number of cpu stats supported by linux */
        *nparams = LINUX_NB_CPU_STATS;
        ret = 0;
        goto cleanup;
    }

    if ((*nparams) != LINUX_NB_CPU_STATS) {
        nodeReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

    if (cpuNum == VIR_NODE_CPU_STATS_ALL_CPUS) {
        strcpy(cpu_header, "cpu");
    } else {
        snprintf(cpu_header, sizeof(cpu_header), "cpu%d", cpuNum);
    }

    while (fgets(line, sizeof(line), procstat) != NULL) {
        char *buf = line;

        if (STRPREFIX(buf, cpu_header)) { /* aka logical CPU time */
            int i;

            if (sscanf(buf,
                       "%*s %llu %llu %llu %llu %llu" // user ~ iowait
                       "%llu %llu %llu %llu %llu",    // irq  ~ guest_nice
                       &usr, &ni, &sys, &idle, &iowait,
                       &irq, &softirq, &steal, &guest, &guest_nice) < 4) {
                continue;
            }

            for (i = 0; i < *nparams; i++) {
                virNodeCPUStatsPtr param = &params[i];

                switch (i) {
                case 0: /* fill kernel cpu time here */
                    if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_KERNEL) == NULL) {
                        nodeReportError(VIR_ERR_INTERNAL_ERROR,
                                        "%s", _("Field kernel cpu time too long for destination"));
                        goto cleanup;
                    }
                    param->value = (sys + irq + softirq) * TICK_TO_NSEC;
                    break;

                case 1: /* fill user cpu time here */
                    if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_USER) == NULL) {
                        nodeReportError(VIR_ERR_INTERNAL_ERROR,
                                        "%s", _("Field kernel cpu time too long for destination"));
                        goto cleanup;
                    }
                    param->value = (usr + ni) * TICK_TO_NSEC;
                    break;

                case 2: /* fill idle cpu time here */
                    if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_IDLE) == NULL) {
                        nodeReportError(VIR_ERR_INTERNAL_ERROR,
                                        "%s", _("Field kernel cpu time too long for destination"));
                        goto cleanup;
                    }
                    param->value = idle * TICK_TO_NSEC;
                    break;

                case 3: /* fill iowait cpu time here */
                    if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_IOWAIT) == NULL) {
                        nodeReportError(VIR_ERR_INTERNAL_ERROR,
                                        "%s", _("Field kernel cpu time too long for destination"));
                        goto cleanup;
                    }
                    param->value = iowait * TICK_TO_NSEC;
                    break;

                default:
                    break;
                    /* should not hit here */
                }
            }
            ret = 0;
            goto cleanup;
        }
    }

    nodeReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid cpu number"));

cleanup:
    return ret;
}
Esempio n. 20
0
/* Convert a gid_t to string.  Do not use this function directly.
   Instead, use it via the gidtostr macro.
   Beware that it returns a pointer to static storage.  */
static char *
gidtostr_ptr (gid_t const *gid)
{
  static char buf[INT_BUFSIZE_BOUND (uintmax_t)];
  return umaxtostr (*gid, buf);
}
Esempio n. 21
0
static int
build_data (pskc_key_t * kp, xmlNodePtr keyp)
{
  const char *b64secret = pskc_get_key_data_b64secret (kp);
  int counter_p;
  uint64_t counter = pskc_get_key_data_counter (kp, &counter_p);
  int t_p;
  uint32_t t = pskc_get_key_data_time (kp, &t_p);
  int tinterval_p;
  uint32_t tinterval = pskc_get_key_data_timeinterval (kp, &tinterval_p);
  int tdrift_p;
  uint32_t tdrift = pskc_get_key_data_timedrift (kp, &tdrift_p);
  xmlNodePtr data, sub;

  if (!b64secret && !counter_p && !t_p && !tinterval_p && !tdrift_p)
    return PSKC_OK;

  data = xmlNewChild (keyp, NULL, BAD_CAST "Data", NULL);

  if (b64secret)
    {
      sub = xmlNewChild (data, NULL, BAD_CAST "Secret", NULL);
      xmlNewTextChild (sub, NULL, BAD_CAST "PlainValue", BAD_CAST b64secret);
    }

  if (counter_p)
    {
      char buf[INT_BUFSIZE_BOUND (uintmax_t)];
      char *p = umaxtostr (counter, buf);

      sub = xmlNewChild (data, NULL, BAD_CAST "Counter", NULL);
      xmlNewTextChild (sub, NULL, BAD_CAST "PlainValue", BAD_CAST p);
    }

  if (t_p)
    {
      char buf[INT_BUFSIZE_BOUND (uintmax_t)];
      char *p = umaxtostr (t, buf);

      sub = xmlNewChild (data, NULL, BAD_CAST "Time", NULL);
      xmlNewTextChild (sub, NULL, BAD_CAST "PlainValue", BAD_CAST p);
    }

  if (tinterval_p)
    {
      char buf[INT_BUFSIZE_BOUND (uintmax_t)];
      char *p = umaxtostr (tinterval, buf);

      sub = xmlNewChild (data, NULL, BAD_CAST "TimeInterval", NULL);
      xmlNewTextChild (sub, NULL, BAD_CAST "PlainValue", BAD_CAST p);
    }

  if (tdrift_p)
    {
      char buf[INT_BUFSIZE_BOUND (uintmax_t)];
      char *p = umaxtostr (tdrift, buf);

      sub = xmlNewChild (data, NULL, BAD_CAST "TimeDrift", NULL);
      xmlNewTextChild (sub, NULL, BAD_CAST "PlainValue", BAD_CAST p);
    }

  return PSKC_OK;
}
Esempio n. 22
0
int virPidFileAcquirePath(const char *path,
                          pid_t pid)
{
    int fd = -1;
    char pidstr[INT_BUFSIZE_BOUND(pid)];

    if (path[0] == '\0')
        return 0;

    while (1) {
        struct stat a, b;
        if ((fd = open(path, O_WRONLY|O_CREAT, 0644)) < 0) {
            virReportSystemError(errno,
                                 _("Failed to open pid file '%s'"),
                                 path);
            return -1;
        }

        if (virSetCloseExec(fd) < 0) {
            virReportSystemError(errno,
                                 _("Failed to set close-on-exec flag '%s'"),
                                 path);
            VIR_FORCE_CLOSE(fd);
            return -1;
        }

        if (fstat(fd, &b) < 0) {
            virReportSystemError(errno,
                                 _("Unable to check status of pid file '%s'"),
                                 path);
            VIR_FORCE_CLOSE(fd);
            return -1;
        }

        if (virFileLock(fd, false, 0, 1) < 0) {
            virReportSystemError(errno,
                                 _("Failed to acquire pid file '%s'"),
                                 path);
            VIR_FORCE_CLOSE(fd);
            return -1;
        }

        /* Now make sure the pidfile we locked is the same
         * one that now exists on the filesystem
         */
        if (stat(path, &a) < 0) {
            char ebuf[1024] ATTRIBUTE_UNUSED;
            VIR_DEBUG("Pid file '%s' disappeared: %s",
                      path, virStrerror(errno, ebuf, sizeof(ebuf)));
            VIR_FORCE_CLOSE(fd);
            /* Someone else must be racing with us, so try agin */
            continue;
        }

        if (a.st_ino == b.st_ino)
            break;

        VIR_DEBUG("Pid file '%s' was recreated", path);
        VIR_FORCE_CLOSE(fd);
        /* Someone else must be racing with us, so try agin */
    }
Esempio n. 23
0
int
virHostCPUGetStatsLinux(FILE *procstat,
                        int cpuNum,
                        virNodeCPUStatsPtr params,
                        int *nparams)
{
    int ret = -1;
    char line[1024];
    unsigned long long usr, ni, sys, idle, iowait;
    unsigned long long irq, softirq, steal, guest, guest_nice;
    char cpu_header[4 + INT_BUFSIZE_BOUND(cpuNum)];

    if ((*nparams) == 0) {
        /* Current number of cpu stats supported by linux */
        *nparams = LINUX_NB_CPU_STATS;
        ret = 0;
        goto cleanup;
    }

    if ((*nparams) != LINUX_NB_CPU_STATS) {
        virReportInvalidArg(*nparams,
                            _("nparams in %s must be equal to %d"),
                            __FUNCTION__, LINUX_NB_CPU_STATS);
        goto cleanup;
    }

    if (cpuNum == VIR_NODE_CPU_STATS_ALL_CPUS) {
        strcpy(cpu_header, "cpu ");
    } else {
        snprintf(cpu_header, sizeof(cpu_header), "cpu%d ", cpuNum);
    }

    while (fgets(line, sizeof(line), procstat) != NULL) {
        char *buf = line;

        if (STRPREFIX(buf, cpu_header)) { /* aka logical CPU time */
            if (sscanf(buf,
                       "%*s %llu %llu %llu %llu %llu" // user ~ iowait
                       "%llu %llu %llu %llu %llu",    // irq  ~ guest_nice
                       &usr, &ni, &sys, &idle, &iowait,
                       &irq, &softirq, &steal, &guest, &guest_nice) < 4) {
                continue;
            }

            if (virHostCPUStatsAssign(&params[0], VIR_NODE_CPU_STATS_KERNEL,
                                      (sys + irq + softirq) * TICK_TO_NSEC) < 0)
                goto cleanup;

            if (virHostCPUStatsAssign(&params[1], VIR_NODE_CPU_STATS_USER,
                                      (usr + ni) * TICK_TO_NSEC) < 0)
                goto cleanup;

            if (virHostCPUStatsAssign(&params[2], VIR_NODE_CPU_STATS_IDLE,
                                      idle * TICK_TO_NSEC) < 0)
                goto cleanup;

            if (virHostCPUStatsAssign(&params[3], VIR_NODE_CPU_STATS_IOWAIT,
                                      iowait * TICK_TO_NSEC) < 0)
                goto cleanup;

            ret = 0;
            goto cleanup;
        }
    }

    virReportInvalidArg(cpuNum,
                        _("Invalid cpuNum in %s"),
                        __FUNCTION__);

 cleanup:
    return ret;
}
Esempio n. 24
0
static int
build_algparm (pskc_key_t * kp, xmlNodePtr keyp)
{
  const char *suite = pskc_get_key_algparm_suite (kp);
  int chall_encoding_p;
  pskc_valueformat chall_encoding = pskc_get_key_algparm_chall_encoding
    (kp, &chall_encoding_p);
  int chall_min_p;
  uint32_t chall_min = pskc_get_key_algparm_chall_min (kp, &chall_min_p);
  int chall_max_p;
  uint32_t chall_max = pskc_get_key_algparm_chall_max (kp, &chall_max_p);
  int chall_checkdigits_p;
  int chall_checkdigits = pskc_get_key_algparm_chall_checkdigits
    (kp, &chall_checkdigits_p);
  int resp_encoding_p;
  pskc_valueformat resp_encoding = pskc_get_key_algparm_resp_encoding
    (kp, &resp_encoding_p);
  int resp_length_p;
  uint32_t resp_length =
    pskc_get_key_algparm_resp_length (kp, &resp_length_p);
  int resp_checkdigits_p;
  int resp_checkdigits = pskc_get_key_algparm_resp_checkdigits
    (kp, &resp_checkdigits_p);
  xmlNodePtr algparm;

  if (!suite && !chall_encoding_p && !chall_min_p && !chall_max_p
      && !chall_checkdigits_p && !resp_encoding_p && !resp_length_p
      && !resp_checkdigits_p)
    return PSKC_OK;

  algparm = xmlNewChild (keyp, NULL, BAD_CAST "AlgorithmParameters", NULL);

  if (suite)
    xmlNewTextChild (algparm, NULL, BAD_CAST "Suite", BAD_CAST suite);

  if (chall_encoding_p || chall_min_p || chall_max_p || resp_checkdigits_p)
    {
      xmlNodePtr chall;

      chall = xmlNewChild (algparm, NULL, BAD_CAST "ChallengeFormat", NULL);

      if (chall_encoding_p)
	xmlNewProp (chall, BAD_CAST "Encoding",
		    BAD_CAST pskc_valueformat2str (chall_encoding));


      if (chall_min_p)
	{
	  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
	  char *p = umaxtostr (chall_min, buf);
	  xmlNewProp (chall, BAD_CAST "Min", BAD_CAST p);
	}

      if (chall_max_p)
	{
	  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
	  char *p = umaxtostr (chall_max, buf);
	  xmlNewProp (chall, BAD_CAST "Max", BAD_CAST p);
	}

      if (chall_checkdigits_p && chall_checkdigits)
	xmlNewProp (chall, BAD_CAST "CheckDigits", BAD_CAST "true");
    }

  if (resp_encoding_p || resp_length_p || resp_checkdigits_p)
    {
      xmlNodePtr resp;

      resp = xmlNewChild (algparm, NULL, BAD_CAST "ResponseFormat", NULL);

      if (resp_encoding_p)
	xmlNewProp (resp, BAD_CAST "Encoding",
		    BAD_CAST pskc_valueformat2str (resp_encoding));

      if (resp_length_p)
	{
	  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
	  char *p = umaxtostr (resp_length, buf);
	  xmlNewProp (resp, BAD_CAST "Length", BAD_CAST p);
	}

      if (resp_checkdigits_p && resp_checkdigits)
	xmlNewProp (resp, BAD_CAST "CheckDigits", BAD_CAST "true");
    }

  return PSKC_OK;
}