Beispiel #1
0
int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){
#  ifdef USE_OPENSSL
	X509 *certificate=NULL;
	X509_NAME *subj=NULL;
	char timestamp[50] = "";
	char cn[MAX_CN_LENGTH]= "";
	char *tz;
	
	int cnlen =-1;
	int status=STATE_UNKNOWN;

	ASN1_STRING *tm;
	int offset;
	struct tm stamp;
	float time_left;
	int days_left;
	int time_remaining;
	time_t tm_t;

	certificate=SSL_get_peer_certificate(s);
	if (!certificate) {
		printf("%s\n",_("CRITICAL - Cannot retrieve server certificate."));
		return STATE_CRITICAL;
	}

	/* Extract CN from certificate subject */
	subj=X509_get_subject_name(certificate);

	if (!subj) {
		printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject."));
		return STATE_CRITICAL;
	}
	cnlen = X509_NAME_get_text_by_NID(subj, NID_commonName, cn, sizeof(cn));
	if (cnlen == -1)
		strcpy(cn, _("Unknown CN"));

	/* Retrieve timestamp of certificate */
	tm = X509_get_notAfter(certificate);

	/* Generate tm structure to process timestamp */
	if (tm->type == V_ASN1_UTCTIME) {
		if (tm->length < 10) {
			printf("%s\n", _("CRITICAL - Wrong time format in certificate."));
			return STATE_CRITICAL;
		} else {
			stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
			if (stamp.tm_year < 50)
				stamp.tm_year += 100;
			offset = 0;
		}
	} else {
		if (tm->length < 12) {
			printf("%s\n", _("CRITICAL - Wrong time format in certificate."));
			return STATE_CRITICAL;
		} else {
			stamp.tm_year =
				(tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
				(tm->data[2] - '0') * 10 + (tm->data[3] - '0');
			stamp.tm_year -= 1900;
			offset = 2;
		}
	}
	stamp.tm_mon =
		(tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
	stamp.tm_mday =
		(tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
	stamp.tm_hour =
		(tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
	stamp.tm_min =
		(tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
	stamp.tm_sec =
		(tm->data[10 + offset] - '0') * 10 + (tm->data[11 + offset] - '0');
	stamp.tm_isdst = -1;

	tm_t = timegm(&stamp);
	time_left = difftime(tm_t, time(NULL));
	days_left = time_left / 86400;
	tz = getenv("TZ");
	setenv("TZ", "GMT", 1);
	tzset();
	strftime(timestamp, 50, "%c %z", localtime(&tm_t));
	if (tz)
		setenv("TZ", tz, 1);
	else
		unsetenv("TZ");
	tzset();

	if (days_left > 0 && days_left <= days_till_exp_warn) {
		printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, days_left, timestamp);
		if (days_left > days_till_exp_crit)
			status = STATE_WARNING;
		else
			status = STATE_CRITICAL;
	} else if (days_left == 0 && time_left > 0) {
		if (time_left >= 3600)
			time_remaining = (int) time_left / 3600;
		else
			time_remaining = (int) time_left / 60;

		printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"),
			(days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", cn, time_remaining,
			time_left >= 3600 ? "hours" : "minutes", timestamp);

		if ( days_left > days_till_exp_crit)
			status = STATE_WARNING;
		else
			status = STATE_CRITICAL;
	} else if (time_left < 0) {
		printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), cn, timestamp);
		status=STATE_CRITICAL;
	} else if (days_left == 0) {
		printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, timestamp);
		if (days_left > days_till_exp_crit)
			status = STATE_WARNING;
		else
			status = STATE_CRITICAL;
	} else {
		printf(_("OK - Certificate '%s' will expire on %s.\n"), cn, timestamp);
		status = STATE_OK;
	}
	X509_free(certificate);
	return status;
#  else /* ifndef USE_OPENSSL */
	printf("%s\n", _("WARNING - Plugin does not support checking certificates."));
	return STATE_WARNING;
#  endif /* USE_OPENSSL */
}
Beispiel #2
0
time_t
asn_GT2time_frac(const GeneralizedTime_t *st, int *frac_value, int *frac_digits, struct tm *ret_tm, int as_gmt) {
    struct tm tm_s;
    uint8_t *buf;
    uint8_t *end;
    int gmtoff_h = 0;
    int gmtoff_m = 0;
    int gmtoff = 0;    /* h + m */
    int offset_specified = 0;
    int fvalue = 0;
    int fdigits = 0;
    time_t tloc;

    if(!st || !st->buf) {
        errno = EINVAL;
        return -1;
    } else {
        buf = st->buf;
        end = buf + st->size;
    }

    if(st->size < 10) {
        errno = EINVAL;
        return -1;
    }

    /*
     * Decode first 10 bytes: "AAAAMMJJhh"
     */
    memset(&tm_s, 0, sizeof(tm_s));
#undef    B2F
#undef    B2T
#define    B2F(var)    do {                    \
        unsigned ch = *buf;                \
        if(ch < 0x30 || ch > 0x39) {            \
            errno = EINVAL;                \
            return -1;                \
        } else {                    \
            var = var * 10 + (ch - 0x30);        \
            buf++;                    \
        }                        \
    } while(0)
#define    B2T(var)    B2F(tm_s.var)

    B2T(tm_year);    /* 1: A */
    B2T(tm_year);    /* 2: A */
    B2T(tm_year);    /* 3: A */
    B2T(tm_year);    /* 4: A */
    B2T(tm_mon);    /* 5: M */
    B2T(tm_mon);    /* 6: M */
    B2T(tm_mday);    /* 7: J */
    B2T(tm_mday);    /* 8: J */
    B2T(tm_hour);    /* 9: h */
    B2T(tm_hour);    /* 0: h */

    if(buf == end) goto local_finish;

    /*
     * Parse [mm[ss[(.|,)ffff]]]
     *        ^^
     */
    switch(*buf) {
    case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
    case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
        tm_s.tm_min = (*buf++) - 0x30;
        if(buf == end) { errno = EINVAL; return -1; }
        B2T(tm_min);
        break;
    case 0x2B: case 0x2D:    /* +, - */
        goto offset;
    case 0x5A:        /* Z */
        goto utc_finish;
    default:
        errno = EINVAL;
        return -1;
    }

    if(buf == end) goto local_finish;

    /*
     * Parse [mm[ss[(.|,)ffff]]]
     *           ^^
     */
    switch(*buf) {
    case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
    case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
        tm_s.tm_sec = (*buf++) - 0x30;
        if(buf == end) { errno = EINVAL; return -1; }
        B2T(tm_sec);
        break;
    case 0x2B: case 0x2D:    /* +, - */
        goto offset;
    case 0x5A:        /* Z */
        goto utc_finish;
    default:
        errno = EINVAL;
        return -1;
    }

    if(buf == end) goto local_finish;

    /*
     * Parse [mm[ss[(.|,)ffff]]]
     *               ^ ^
     */
    switch(*buf) {
    case 0x2C: case 0x2E: /* (.|,) */
        /*
         * Process fractions of seconds.
         */
        for(buf++; buf < end; buf++) {
            int v = *buf;
            /* GCC 4.x is being too smart without volatile */
            switch(v) {
            case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
            case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
                if(fvalue < INT_MAX/10) {
                    fvalue = fvalue * 10 + (v - 0x30);
                    fdigits++;
                } else {
                    /* Not enough precision, ignore */
                }
                continue;
            default:
                break;
            }
            break;
        }
    }

    if(buf == end) goto local_finish;

    switch(*buf) {
    case 0x2B: case 0x2D:    /* +, - */
        goto offset;
    case 0x5A:        /* Z */
        goto utc_finish;
    default:
        errno = EINVAL;
        return -1;
    }


offset:

    if(end - buf < 3) {
        errno = EINVAL;
        return -1;
    }
    buf++;
    B2F(gmtoff_h);
    B2F(gmtoff_h);
    if(buf[-3] == 0x2D)    /* Negative */
        gmtoff = -1;
    else
        gmtoff = 1;

    if((end - buf) == 2) {
        B2F(gmtoff_m);
        B2F(gmtoff_m);
    } else if(end != buf) {
        errno = EINVAL;
        return -1;
    }

    gmtoff = gmtoff * (3600 * gmtoff_h + 60 * gmtoff_m);

    /* Fall through */
utc_finish:

    offset_specified = 1;

    /* Fall through */
local_finish:

    /*
     * Validation.
     */
    if((tm_s.tm_mon > 12 || tm_s.tm_mon < 1)
    || (tm_s.tm_mday > 31 || tm_s.tm_mday < 1)
    || (tm_s.tm_hour > 23)
    || (tm_s.tm_sec > 60)
    ) {
        errno = EINVAL;
        return -1;
    }

    /* Canonicalize */
    tm_s.tm_mon -= 1;    /* 0 - 11 */
    tm_s.tm_year -= 1900;
    tm_s.tm_isdst = -1;

    tm_s.tm_sec -= gmtoff;

    /*** AT THIS POINT tm_s is either GMT or local (unknown) ****/

    if(offset_specified) {
        tloc = timegm(&tm_s);
    } else {
        /*
         * Without an offset (or "Z"),
         * we can only guess that it is a local zone.
         * Interpret it in this fashion.
         */
        tloc = mktime(&tm_s);
    }
    if(tloc == -1) {
        errno = EINVAL;
        return -1;
    }

    if(ret_tm) {
        if(as_gmt) {
            if(offset_specified) {
                *ret_tm = tm_s;
            } else {
                if(gmtime_r(&tloc, ret_tm) == 0) {
                    errno = EINVAL;
                    return -1;
                }
            }
        } else {
            if(localtime_r(&tloc, ret_tm) == 0) {
                errno = EINVAL;
                return -1;
            }
        }
    }

    /* Fractions of seconds */
    if(frac_value) *frac_value = fvalue;
    if(frac_digits) *frac_digits = fdigits;

    return tloc;
}
Beispiel #3
0
/**
 * twitter_date_to_time_val:
 * @date: a timestamp coming from Twitter
 * @time_: return location for a #GTimeVal
 *
 * Converts a Twitter date into a #GTimeVal. The timestamp is relative
 * to UTC.
 *
 * Return value: %TRUE if the conversion was successful
 */
gboolean
twitter_date_to_time_val (const gchar *date,
                          GTimeVal    *time_)
{
  time_t res;
  SoupDate *soup_date;

  g_return_val_if_fail (date != NULL, FALSE);
  g_return_val_if_fail (time_ != NULL, FALSE);

  /* XXX - this code is here in case there's a sudden onset of sanity
   * at Twitter and they switch to using any format supported by libsoup
   */
  soup_date = soup_date_new_from_string (date);
  if (soup_date)
    {
      res = soup_date_to_time_t (soup_date);
      soup_date_free (soup_date);

      time_->tv_sec = res;
      time_->tv_usec = 0;

      return TRUE;
    }

#ifdef HAVE_STRPTIME
  {
    struct tm tmp;

    /* OMFG, ctime()? really? what are they? insane? I swear, this is
     * what happens when you let ruby developers write public APIs
     *
     * what happened to ISO8601 and web datestamps? you work on the web,
     * people!
     */
    strptime (date, "%a %b %d %T %z %Y", &tmp);

#ifdef HAVE_TIMEGM
    time_->tv_sec = timegm (&tmp);
    time_->tv_usec = 0;

    return TRUE;
#else
    {
      res = 0;

      if (tmp.tm_mon < 0 || tmp.tm_mon > 11)
        {
          time_->tv_sec = res;
          time_->tv_usec = 0;

          return FALSE;
        }

      res += (tmp.tm_year - 70) * 365;
      res += (tmp.tm_year - 68) / 4;
      res += days_before[tmp.tm_mon] + tmp.tm_mday - 1;

      if (tmp.tm_year % 4 == 0 && tmp.tm_mon < 2)
        res -= 1;

      res = ((((res * 24) + tmp.tm_hour) * 60) + tmp.tm_min) * 60 + tmp.tm_sec;

      time_->tv_sec = res;
      time_->tv_usec = 0;

      return TRUE;
    }
#endif /* HAVE_TIMEGM */
  }
#endif /* HAVE_STRPTIME */

  return FALSE;
}
Beispiel #4
0
/*
 * Convert an ASN.1 UTCTime structure into unix time format
 */
time_t utc2unix(ASN1_UTCTIME *utctime, time_t *unixtime)
{
	char *utcchars;
	int length, temp;
	time_t utime;
	char *current;
	struct tm tms;

	memset(&tms, '\0', sizeof(tms));

	utime = -1;				/* preset with error return */

	/*
	 * XXX Here we are making the assumption that all times are (UTC/ZULU)
	 * XXX and that all times include the seconds value.
	 */
	length = utctime->length;
	if (length != 13)
		goto returntime;

	utcchars = (char*) utctime->data;
	if (utcchars[12] != 'Z')
		goto returntime;

	current = utcchars;
	temp = (current[0]-'0')*10 + (current[1]-'0');	/* get year value */
	if (temp < 50)		/* UTCTime runs from 1950 - 2049 */
		temp += 100;	/* Must use GeneralizedTime after 2049 */
	tms.tm_year = temp;

	current+=2;
	temp = (current[0]-'0')*10 + (current[1]-'0');	/* get month value */
	temp--;			/* make it zero based */
	tms.tm_mon = temp;

	current+=2;
	temp = (current[0]-'0')*10 + (current[1]-'0');	/* get day of the month value */
	tms.tm_mday = temp;

	current+=2;
	temp = (current[0]-'0')*10 + (current[1]-'0');	/* get hour value */
	tms.tm_hour = temp;

	current+=2;
	temp = (current[0]-'0')*10 + (current[1]-'0');	/* get minute value */
	tms.tm_min = temp;

	current+=2;
	temp = (current[0]-'0')*10 + (current[1]-'0');	/* get seconds value */
	tms.tm_sec = temp;

	tms.tm_isdst = -1;		/* Forces mktime to check DST */

#if defined(OPENBSD) || defined(_DARWIN)
	/*
	 * mktime() doesn't seem to work the same on OpenBSD
	 * as others (like linux and Solaris).  It would seem
	 * that this should be a call to timelocal().
	 * But hey, it works...
	 */
	utime = timegm(&tms);
#else
	tzset();										/* Make sure timezone & daylight are set */
	utime = mktime(&tms);		/* get unix time (GMT) */
	if (utime != -1) {
		utime = utime - timezone + daylight*3600;
	}
#endif

  returntime:

	if (unixtime)
		*unixtime = utime;
	return utime;
}
Beispiel #5
0
/* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
   (i.e. English) day/month names, and it doesn't work correctly with %z. */
int parse_date_basic(const char *date, unsigned long *timestamp, int *offset)
{
	struct tm tm;
	int tm_gmt;
	unsigned long dummy_timestamp;
	int dummy_offset;

	if (!timestamp)
		timestamp = &dummy_timestamp;
	if (!offset)
		offset = &dummy_offset;

	memset(&tm, 0, sizeof(tm));
	tm.tm_year = -1;
	tm.tm_mon = -1;
	tm.tm_mday = -1;
	tm.tm_isdst = -1;
	tm.tm_hour = -1;
	tm.tm_min = -1;
	tm.tm_sec = -1;
	*offset = -1;
	tm_gmt = 0;

	if (*date == '@' &&
	    !match_object_header_date(date + 1, timestamp, offset))
		return 0; /* success */
	for (;;) {
		int match = 0;
		unsigned char c = *date;

		/* Stop at end of string or newline */
		if (!c || c == '\n')
			break;

		if (isalpha(c))
			match = match_alpha(date, &tm, offset);
		else if (isdigit(c))
			match = match_digit(date, &tm, offset, &tm_gmt);
		else if ((c == '-' || c == '+') && isdigit(date[1]))
			match = match_tz(date, offset);

		if (!match) {
			/* BAD CRAP */
			match = 1;
		}

		date += match;
	}

	/* timegm uses local timezone */
	*timestamp = tm_to_time_t(&tm);
	if (*offset == -1) {
		time_t temp_time = timegm(&tm);
		if ((time_t)*timestamp > temp_time) {
			*offset = ((time_t)*timestamp - temp_time) / 60;
		} else {
			*offset = -(int)((temp_time - (time_t)*timestamp) / 60);
		}
	}

	if (*timestamp == -1)
		return -1;

	if (!tm_gmt)
		*timestamp -= *offset * 60;
	return 0; /* success */
}
Beispiel #6
0
bool File::read_next(const bool ignore_text, const bool verify)
{
    static const int MAX_LINE = 8192;

    char linebuf[MAX_LINE + 1];

    enum state_t {
        STATE_ERROR,
        STATE_TAGS,
        STATE_PROPS,
        STATE_BODY,
        STATE_NEXT
    } state = STATE_NEXT;

    int  prop_content_length = -1;
    int  text_content_length = -1;
    bool saw_node_path       = false;

    while (handle->good() && ! handle->eof()) {
        switch (state) {
        case STATE_NEXT:
            prop_content_length = -1;
            text_content_length = -1;
            saw_node_path       = false;

            curr_node.reset();

            if (handle->peek() == '\n')
                handle->read(linebuf, 1);
            state = STATE_TAGS;

        // fall through...

        case STATE_TAGS:
            handle->getline(linebuf, MAX_LINE);

            if (const char * p = std::strchr(linebuf, ':')) {
                std::string property
                (linebuf, 0, static_cast<std::string::size_type>(p - linebuf));
                switch (property[0]) {
                case 'C':
                    break;

                case 'N':
                    if (property == "Node-path") {
                        curr_node.curr_txn += 1;
                        curr_node.pathname = p + 2;
                        saw_node_path = true;
                    }
                    else if (property == "Node-kind") {
                        if (*(p + 2) == 'f')
                            curr_node.kind = Node::KIND_FILE;
                        else if (*(p + 2) == 'd')
                            curr_node.kind = Node::KIND_DIR;
                    }
                    else if (property == "Node-action") {
                        if (*(p + 2) == 'a')
                            curr_node.action = Node::ACTION_ADD;
                        else if (*(p + 2) == 'd')
                            curr_node.action = Node::ACTION_DELETE;
                        else if (*(p + 2) == 'c')
                            curr_node.action = Node::ACTION_CHANGE;
                        else if (*(p + 2) == 'r')
                            curr_node.action = Node::ACTION_REPLACE;
                    }
                    else if (property == "Node-copyfrom-rev") {
                        curr_node.copy_from_rev = std::atoi(p + 2);
                    }
                    else if (property == "Node-copyfrom-path") {
                        curr_node.copy_from_path = p + 2;
                    }
                    break;

                case 'P':
                    if (property == "Prop-content-length")
                        prop_content_length = std::atoi(p + 2);
                    break;

                case 'R':
                    if (property == "Revision-number") {
                        curr_rev  = std::atoi(p + 2);
                        rev_log   = none;
                        curr_node.curr_txn = -1;
                    }
                    break;

                case 'T':
                    if (property == "Text-content-length")
                        text_content_length = std::atoi(p + 2);
                    else if (verify && property == "Text-content-md5")
                        curr_node.md5_checksum = p + 2;
                    else if (verify && property == "Text-content-sha1")
                        curr_node.sha1_checksum = p + 2;
                    break;
                }
            }
            else if (linebuf[0] == '\0') {
                if (prop_content_length > 0)
                    state = STATE_PROPS;
                else if (text_content_length > 0)
                    state = STATE_BODY;
                else if (saw_node_path)
                    goto success;
                else
                    state = STATE_NEXT;
            }
            break;

        case STATE_PROPS: {
            assert(prop_content_length > 0);

            char *      buf;
            bool        allocated;
            char *      p;
            char *      q;
            int         len;
            bool        is_key;
            std::string property;

            if (curr_node.curr_txn >= 0) {
                // Ignore properties that don't describe the revision itself;
                // we just don't need to know for the purposes of this
                // utility.
                handle->seekg(prop_content_length, std::ios::cur);
                goto end_props;
            }

            if (prop_content_length < MAX_LINE) {
                handle->read(linebuf, prop_content_length);
                buf = linebuf;
                allocated = false;
            } else {
                buf = new char[prop_content_length + 1];
                allocated = true;
                handle->read(buf, prop_content_length);
            }

            p = buf;
            while (p - buf < prop_content_length) {
                is_key = *p == 'K';
                if (is_key || *p == 'V') {
                    q = std::strchr(p, '\n');
                    assert(q != nullptr);
                    *q = '\0';
                    len = std::atoi(p + 2);
                    p = q + 1;
                    q = p + len;
                    *q = '\0';

                    if (is_key)
                        property   = p;
                    else if (property == "svn:date") {
                        struct tm then;
                        strptime(p, "%Y-%m-%dT%H:%M:%S", &then);
                        rev_date   = timegm(&then);
                    }
                    else if (property == "svn:author")
                        rev_author = p;
                    else if (property == "svn:log")
                        rev_log    = p;
                    else if (property == "svn:sync-last-merged-rev")
                        last_rev   = std::atoi(p);

                    p = q + 1;
                } else {
                    assert(p - buf == prop_content_length - 10);
                    assert(std::strncmp(p, "PROPS-END\n", 10) == 0);
                    break;
                }
            }

            if (allocated)
                delete[] buf;

end_props:
            if (text_content_length > 0)
                state = STATE_BODY;
            else if (curr_rev == -1 || curr_node.curr_txn == -1)
                state = STATE_NEXT;
            else
                goto success;
            break;
        }

        case STATE_BODY:
            if (ignore_text) {
                handle->seekg(text_content_length, std::ios::cur);
            } else {
                assert(text_content_length > 0);

                if (text_content_length > STATIC_BUFLEN) {
                    curr_node.text = new char[text_content_length];
                    curr_node.text_allocated = true;
                } else {
                    curr_node.text = curr_node.static_buffer;
                }
                curr_node.text_len = static_cast<std::size_t>(text_content_length);

                handle->read(curr_node.text, text_content_length);

#ifdef HAVE_LIBCRYPTO
                if (verify) {
                    unsigned char id[20];
                    char          checksum[41];
#ifdef HAVE_OPENSSL_MD5_H
                    if (curr_node.has_md5()) {
                        MD5(reinterpret_cast<const unsigned char *>(curr_node.get_text()),
                            curr_node.get_text_length(), id);
                        std::sprintf(checksum,
                                     "%02x%02x%02x%02x%02x%02x%02x%02x"
                                     "%02x%02x%02x%02x%02x%02x%02x%02x",
                                     id[0],  id[1],  id[2],  id[3],
                                     id[4],  id[5],  id[6],  id[7],
                                     id[8],  id[9],  id[10], id[11],
                                     id[12], id[13], id[14], id[15]);
                        assert(curr_node.get_text_md5() == checksum);
                    }
#endif // HAVE_OPENSSL_MD5_H
#ifdef HAVE_OPENSSL_SHA_H
                    if (curr_node.has_sha1()) {
                        SHA1(reinterpret_cast<const unsigned char *>(curr_node.get_text()),
                             curr_node.get_text_length(), id);
                        std::sprintf(checksum,
                                     "%02x%02x%02x%02x%02x%02x%02x%02x"
                                     "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                                     id[0],  id[1],  id[2],  id[3],
                                     id[4],  id[5],  id[6],  id[7],
                                     id[8],  id[9],  id[10], id[11],
                                     id[12], id[13], id[14], id[15],
                                     id[16], id[17], id[18], id[19]);
                        assert(curr_node.get_text_sha1() == checksum);
                    }
#endif // HAVE_OPENSSL_SHA_H
                }
#endif // HAVE_LIBCRYPTO
            }

            if (curr_rev == -1 || curr_node.curr_txn == -1)
                state = STATE_NEXT;
            else
                goto success;

        case STATE_ERROR:
            assert(false);
            return false;
        }
    }
    return false;

success:
    curr_node.rev_author = rev_author;
    curr_node.rev_date   = rev_date;
    curr_node.rev_log    = rev_log;
    curr_node.curr_rev   = curr_rev;

    return true;
}
Beispiel #7
0
/*
 * get the remote time of a server via srvsvc_NetRemoteTOD
 */
static NTSTATUS libnet_RemoteTOD_srvsvc(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, union libnet_RemoteTOD *r)
{
        NTSTATUS status;
	struct libnet_RpcConnect c;
	struct srvsvc_NetRemoteTOD tod;
	struct srvsvc_NetRemoteTODInfo *info = NULL;
	struct tm tm;

	ZERO_STRUCT(c);

	/* prepare connect to the SRVSVC pipe of a timeserver */
	c.level             = LIBNET_RPC_CONNECT_SERVER;
	c.in.name           = r->srvsvc.in.server_name;
	c.in.dcerpc_iface   = &ndr_table_srvsvc;

	/* 1. connect to the SRVSVC pipe of a timeserver */
	status = libnet_RpcConnect(ctx, mem_ctx, &c);
	if (!NT_STATUS_IS_OK(status)) {
		r->srvsvc.out.error_string = talloc_asprintf(mem_ctx,
						"Connection to SRVSVC pipe of server '%s' failed: %s",
						r->srvsvc.in.server_name, nt_errstr(status));
		return status;
	}

	/* prepare srvsvc_NetrRemoteTOD */
	tod.in.server_unc = talloc_asprintf(mem_ctx, "\\%s", c.in.name);
	tod.out.info = &info;

	/* 2. try srvsvc_NetRemoteTOD */
	status = dcerpc_srvsvc_NetRemoteTOD_r(c.out.dcerpc_pipe->binding_handle, mem_ctx, &tod);
	if (!NT_STATUS_IS_OK(status)) {
		r->srvsvc.out.error_string = talloc_asprintf(mem_ctx,
						"srvsvc_NetrRemoteTOD on server '%s' failed: %s",
						r->srvsvc.in.server_name, nt_errstr(status));
		goto disconnect;
	}

	/* check result of srvsvc_NetrRemoteTOD */
	if (!W_ERROR_IS_OK(tod.out.result)) {
		r->srvsvc.out.error_string = talloc_asprintf(mem_ctx,
						"srvsvc_NetrRemoteTOD on server '%s' failed: %s",
						r->srvsvc.in.server_name, win_errstr(tod.out.result));
		status = werror_to_ntstatus(tod.out.result);
		goto disconnect;
	}

	/* need to set the out parameters */
	tm.tm_sec = (int)info->secs;
	tm.tm_min = (int)info->mins;
	tm.tm_hour = (int)info->hours;
	tm.tm_mday = (int)info->day;
	tm.tm_mon = (int)info->month -1;
	tm.tm_year = (int)info->year - 1900;
	tm.tm_wday = -1;
	tm.tm_yday = -1;
	tm.tm_isdst = -1;

	r->srvsvc.out.time = timegm(&tm);
	r->srvsvc.out.time_zone = info->timezone * 60;

	goto disconnect;

disconnect:
	/* close connection */
	talloc_free(c.out.dcerpc_pipe);

	return status;
}
Beispiel #8
0
static void 
print_all_info(int fd, apm_info_t aip, int bioscall_available)
{
	struct apm_bios_arg args;
	int apmerr;
	const char *line_msg[] = { "off-line", "on-line" , "backup power"};

	printf("APM version: %d.%d\n", aip->ai_major, aip->ai_minor);
	printf("APM Management: %s\n", aip->ai_status ? "Enabled" : "Disabled");
	printf("AC Line status: ");
	if (aip->ai_acline == APM_UNKNOWN)
		printf("unknown\n");
	else if (aip->ai_acline > 2)
		printf("invalid value (0x%x)\n", aip->ai_acline);
	else
		printf("%s\n", line_msg[aip->ai_acline]);

	print_batt_stat(aip->ai_batt_stat);
	print_batt_life(aip->ai_batt_life);
	print_batt_time(aip->ai_batt_time);

	if (aip->ai_infoversion >= 1) {
		printf("Number of batteries: ");
		if (aip->ai_batteries == ~0U)
			printf("unknown\n");
		else {
			u_int i;
			struct apm_pwstatus aps;

			printf("%d\n", aip->ai_batteries);
			for (i = 0; i < aip->ai_batteries; ++i) {
				bzero(&aps, sizeof(aps));
				aps.ap_device = PMDV_BATT0 + i;
				if (ioctl(fd, APMIO_GETPWSTATUS, &aps) == -1)
					continue;
				printf("Battery %d:\n", i);
				if (aps.ap_batt_flag & APM_BATT_NOT_PRESENT) {
					printf("not present\n");
					continue;
				}
				printf("\t");
				print_batt_stat(aps.ap_batt_stat);
				printf("\t");
				print_batt_life(aps.ap_batt_life);
				printf("\t");
				print_batt_time(aps.ap_batt_time);
			}
		}
	}

	if (bioscall_available) {
		/*
		 * try to get the suspend timer
		 */
		bzero(&args, sizeof(args));
		args.eax = (APM_BIOS) << 8 | APM_RESUMETIMER;
		args.ebx = PMDV_APMBIOS;
		args.ecx = 0x0001;
		if (ioctl(fd, APMIO_BIOS, &args)) {
			printf("Resume timer: unknown\n");
		} else {
			apmerr = APMERR(args.eax);
			if (apmerr == 0x0d || apmerr == 0x86)
				printf("Resume timer: disabled\n");
			else if (apmerr)
				warnx(
		"failed to get the resume timer: APM error0x%x", apmerr);
			else {
				/*
				 * OK.  We have the time (all bcd).
				 * CH - seconds
				 * DH - hours
				 * DL - minutes
				 * xh(SI) - month (1-12)
				 * xl(SI) - day of month (1-31)
				 * DI - year
				 */
				struct tm tm;
				char buf[1024];
				time_t t;

				tm.tm_sec = bcd2int(xh(args.ecx));
				tm.tm_min = bcd2int(xl(args.edx));
				tm.tm_hour = bcd2int(xh(args.edx));
				tm.tm_mday = bcd2int(xl(args.esi));
				tm.tm_mon = bcd2int(xh(args.esi)) - 1;
				tm.tm_year = bcd2int(args.edi) - 1900;
				if (cmos_wall)
					t = mktime(&tm);
				else
					t = timegm(&tm);
				if (t != -1) {
					tm = *localtime(&t);
					strftime(buf, sizeof(buf), "%c", &tm);
					printf("Resume timer: %s\n", buf);
				} else
					printf("Resume timer: unknown\n");
			}
		}

		/*
		 * Get the ring indicator resume state
		 */
		bzero(&args, sizeof(args));
		args.eax  = (APM_BIOS) << 8 | APM_RESUMEONRING;
		args.ebx = PMDV_APMBIOS;
		args.ecx = 0x0002;
		if (ioctl(fd, APMIO_BIOS, &args) == 0) {
			printf("Resume on ring indicator: %sabled\n",
			    args.ecx ? "en" : "dis");
		}
	}

	if (aip->ai_infoversion >= 1) {
		if (aip->ai_capabilities == 0xff00)
		    return;
		printf("APM Capabilities:\n");
		if (aip->ai_capabilities & 0x01)
			printf("\tglobal standby state\n");
		if (aip->ai_capabilities & 0x02)
			printf("\tglobal suspend state\n");
		if (aip->ai_capabilities & 0x04)
			printf("\tresume timer from standby\n");
		if (aip->ai_capabilities & 0x08)
			printf("\tresume timer from suspend\n");
		if (aip->ai_capabilities & 0x10)
			printf("\tRI resume from standby\n");
		if (aip->ai_capabilities & 0x20)
			printf("\tRI resume from suspend\n");
		if (aip->ai_capabilities & 0x40)
			printf("\tPCMCIA RI resume from standby\n");
		if (aip->ai_capabilities & 0x80)
			printf("\tPCMCIA RI resume from suspend\n");
	}

}
GeneralizedTime_t *
asn_time2GT_frac(GeneralizedTime_t *opt_gt, const struct tm *tm, int frac_value, int frac_digits, int force_gmt) {
	struct tm tm_s;
	long gmtoff;
	const unsigned int buf_size =
		4 + 2 + 2	/* yyyymmdd */
		+ 2 + 2 + 2	/* hhmmss */
		+ 1 + 6		/* .ffffff */
		+ 1 + 4		/* +hhmm */
		+ 1		/* '\0' */
		;
	char *buf;
	char *p;
	int size;

	/* Check arguments */
	if(!tm) {
		errno = EINVAL;
		return 0;
	}

	/* Pre-allocate a buffer of sufficient yet small length */
	buf = (char *)MALLOC(buf_size);
	if(!buf) return 0;

	gmtoff = GMTOFF(*tm);

	if(force_gmt && gmtoff) {
		tm_s = *tm;
		tm_s.tm_sec -= gmtoff;
		timegm(&tm_s);	/* Fix the time */
		tm = &tm_s;
#ifdef	HAVE_TM_GMTOFF
		assert(!GMTOFF(tm_s));	/* Will fix itself */
#else	/* !HAVE_TM_GMTOFF */
		gmtoff = 0;
#endif
	}

	size = snprintf(buf, buf_size, "%04d%02d%02d%02d%02d%02d",
		tm->tm_year + 1900,
		tm->tm_mon + 1,
		tm->tm_mday,
		tm->tm_hour,
		tm->tm_min,
		tm->tm_sec
	);
	if(size != 14) {
		/* Could be assert(size == 14); */
		FREEMEM(buf);
		errno = EINVAL;
		return 0;
	}

	p = buf + size;

	/*
	 * Deal with fractions.
	 */
	if(frac_value > 0 && frac_digits > 0) {
		char *end = p + 1 + 6;	/* '.' + maximum 6 digits */
		char *z = p;
		long fbase;
		*z++ = '.';

		/* Place bounds on precision */
		while(frac_digits-- > 6)
			frac_value /= 10;

		/* emulate fbase = pow(10, frac_digits) */
		for(fbase = 1; frac_digits--;)
			fbase *= 10;

		do {
			int digit = frac_value / fbase;
			if(digit > 9) { z = 0; break; }
			*z++ = digit + 0x30;
			frac_value %= fbase;
			fbase /= 10;
		} while(fbase > 0 && frac_value > 0 && z < end);
		if(z) {
			for(--z; *z == 0x30; --z);	/* Strip zeroes */
			p = z + (*z != '.');
			size = p - buf;
		}
	}

	if(force_gmt) {
		*p++ = 0x5a;	/* "Z" */
		*p++ = 0;
		size++;
	} else {
		int ret;
		gmtoff %= 86400;
		ret = snprintf(p, buf_size - size, "%+03ld%02ld",
			gmtoff / 3600, labs(gmtoff % 3600));
		if(ret != 5) {
			FREEMEM(buf);
			errno = EINVAL;
			return 0;
		}
		size += ret;
	}

	if(opt_gt) {
		if(opt_gt->buf)
			FREEMEM(opt_gt->buf);
	} else {
		opt_gt = (GeneralizedTime_t *)CALLOC(1, sizeof *opt_gt);
		if(!opt_gt) { FREEMEM(buf); return 0; }
	}

	opt_gt->buf = (unsigned char *)buf;
	opt_gt->size = size;

	return opt_gt;
}
Beispiel #10
0
/*
**	Parse a str in GMT format to a local time time_t representation
**	Four formats are accepted:
**
**		Wkd, 00 Mon 0000 00:00:00 GMT		(rfc1123)
**		Weekday, 00-Mon-00 00:00:00 GMT		(rfc850)
**		Wkd Mon 00 00:00:00 0000 GMT		(ctime)
**		1*DIGIT					(delta-seconds)
*/
PUBLIC time_t HTParseTime (const char * str, HTUserProfile * up, BOOL expand)
{
    char * s;
    struct tm tm;
    time_t t;

    if (!str) return 0;

    if ((s = strchr(str, ','))) {	 /* Thursday, 10-Jun-93 01:29:59 GMT */
	s++;				/* or: Thu, 10 Jan 1993 01:29:59 GMT */
	while (*s && *s==' ') s++;
	if (strchr(s,'-')) {				     /* First format */
	    HTTRACE(CORE_TRACE, "Format...... Weekday, 00-Mon-00 00:00:00 GMT\n");
	    if ((int)strlen(s) < 18) {
		HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format \"%s\"\n" _ s);
		return 0;
	    }
	    tm.tm_mday = strtol(s, &s, 10);
	    tm.tm_mon = make_month(s, &s);
	    tm.tm_year = strtol(++s, &s, 10);
	    tm.tm_hour = strtol(s, &s, 10);
	    tm.tm_min = strtol(++s, &s, 10);
	    tm.tm_sec = strtol(++s, &s, 10);

	} else {					    /* Second format */
	    HTTRACE(CORE_TRACE, "Format...... Wkd, 00 Mon 0000 00:00:00 GMT\n");
	    if ((int)strlen(s) < 20) {
		HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format \"%s\"\n" _ s);
		return 0;
	    }
	    tm.tm_mday = strtol(s, &s, 10);
	    tm.tm_mon = make_month(s, &s);
	    tm.tm_year = strtol(s, &s, 10) - 1900;
	    tm.tm_hour = strtol(s, &s, 10);
	    tm.tm_min = strtol(++s, &s, 10);
	    tm.tm_sec = strtol(++s, &s, 10);
	}
    } else if (isdigit((int) *str)) {

	if (strchr(str, 'T')) {		        /* ISO (limited format) date string */
	    HTTRACE(CORE_TRACE, "Format...... YYYY.MM.DDThh:mmStzWkd\n");
	    s = (char *) str;
	    while (*s && *s==' ') s++;
	    if ((int)strlen(s) < 21) {
		HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format `%s\'\n" _ s);
		return 0;
	    }
	    tm.tm_year = strtol(s, &s, 10) - 1900;
	    tm.tm_mon  = strtol(++s, &s, 10);
	    tm.tm_mday = strtol(++s, &s, 10);
	    tm.tm_hour = strtol(++s, &s, 10);
	    tm.tm_min  = strtol(++s, &s, 10);
	    tm.tm_sec  = strtol(++s, &s, 10);

	} else {					    /* delta seconds */
	    t = expand ? time(NULL) + atol(str) : atol(str);

#ifdef HTDEBUG
	    if (CORE_TRACE) {
		if (expand) {
#if defined (HAVE_CTIME_R_2)
		    char buffer[CTIME_MAX];
		    HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds, or in local time: %s" _
			    str _ (long) t _ (char *) ctime_r(&t, buffer));
#elif defined(HAVE_CTIME_R_3)
		    char buffer[CTIME_MAX];
		    HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds, or in local time: %s" _
			    str _ (long) t _ (char *) ctime_r(&t, buffer, CTIME_MAX));
#else
		    HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds, or in local time: %s" _
			    str _ (long) t _ ctime(&t));
#endif /* HT_REENTRANT */
		} else {
		    HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds\n" _ str _ (long) t);
		}
	    }
#endif /* HT_DEBUG */
	    return t;
	}

    } else {	      /* Try the other format:  Wed Jun  9 01:29:59 1993 GMT */
	HTTRACE(CORE_TRACE, "Format...... Wkd Mon 00 00:00:00 0000 GMT\n");
	s = (char *) str;
	while (*s && *s==' ') s++;
	HTTRACE(CORE_TRACE, "Trying...... The Wrong time format: %s\n" _ s);
	if ((int)strlen(s) < 24) {
	    HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format \"%s\"\n" _ s);
	    return 0;
	}
	tm.tm_mon = make_month(s, &s);
	tm.tm_mday = strtol(s, &s, 10);
	tm.tm_hour = strtol(s, &s, 10);
	tm.tm_min = strtol(++s, &s, 10);
	tm.tm_sec = strtol(++s, &s, 10);
	tm.tm_year = strtol(s, &s, 10) - 1900;
    }
    if (tm.tm_sec  < 0  ||  tm.tm_sec  > 59  ||
	tm.tm_min  < 0  ||  tm.tm_min  > 59  ||
	tm.tm_hour < 0  ||  tm.tm_hour > 23  ||
	tm.tm_mday < 1  ||  tm.tm_mday > 31  ||
	tm.tm_mon  < 0  ||  tm.tm_mon  > 11  ||
	tm.tm_year <70  ||  tm.tm_year >120) {
	HTTRACE(CORE_TRACE, "ERROR....... Parsed illegal time: %02d.%02d.%02d %02d:%02d:%02d\n" _ 
	       tm.tm_mday _ tm.tm_mon+1 _ tm.tm_year _ 
	       tm.tm_hour _ tm.tm_min _ tm.tm_sec);
	return 0;
    }

#if 0
#if defined(HAVE_TIMEZONE) && defined(HAVE_ALTZONE)
    tm.tm_isdst = daylight;		       /* Already taken into account */
    HTTRACE(CORE_TRACE, "Time string. Daylight is %s\n" _
	    daylight>0 ? "on" : daylight==0 ? "off" : "unknown");
#endif
#else
    /* Let mktime decide whether we have DST or not */
    tm.tm_isdst = -1;
#endif

#ifdef HAVE_MKTIME
    t = mktime(&tm);
    t += (up ? HTUserProfile_timezone(up) : HTGetTimeZoneOffset());
#else
#ifdef HAVE_TIMEGM
    t = timegm(&tm);
#else
#error "Neither mktime nor timegm defined"
#endif /* HAVE_TIMEGM */
#endif /* HAVE_MKTIME */

    HTTRACE(CORE_TRACE, "Time string. %s parsed to %ld calendar time or `%s' in local time\n" _ 
		str _ (long) t _ ctime(&t));
    return t;
}
Beispiel #11
0
time_t SyslogEventPublisher::parseTimeString(const std::string& time_str) {
  struct tm s_tm;
  strptime(time_str.c_str(), kTimeFormat, &s_tm);
  return timegm(&s_tm);
}
Beispiel #12
0
time_t parseDVBtime(const uint8_t *data)
{
	tm t;
	parseDVBtime_impl(t, data);
	return timegm(&t);
}
// https://tools.ietf.org/html/rfc2616#section-3.3.1
// Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
// Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
// Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
bool HttpMime::parseCookieDate(const char *value, size_t valueLen, time_t *time) {
	std::string dateStr(value, valueLen);

	struct tm tm = {};
	// not set by strptime()
	tm.tm_isdst = -1;

	const char *dashPos = (const char*)memchr(value, '-', valueLen);
	const char *commaPos = (const char*)memchr(value, ',', valueLen);

	// Fri, 02 Dec 2016 17:29:41 -0000
	if (dashPos && dashPos + 4 < value + valueLen) {
		if (memcmp(dashPos, "-0000", 5) == 0) {
			dashPos = NULL;
		}
	}

	if (dashPos) {
		if (commaPos) {
			// Sunday, 06-Nov-94 08:49:37 GMT (RFC 850)
			if (strptime(dateStr.c_str(), "%a, %d-%b-%y %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}

			// Sun, 27-Nov-2016 22:15:17 GMT
			if (strptime(dateStr.c_str(), "%a, %d-%b-%Y %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}

			// Sat, 26-11-2026 16:41:30 GMT
			if (strptime(dateStr.c_str(), "%a, %d-%m-%Y %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}
		} else {
			// Thu 31-Dec-2020 00:00:00 GMT
			if (strptime(dateStr.c_str(), "%a %d-%b-%Y %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}

			// 2018-03-21 18:43:07
			if (strptime(dateStr.c_str(), "%Y-%m-%d %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}
		}
	} else {
		if (commaPos) {
			// Sun, 06 Nov 1994 08:49:37 GMT (RFC 1123)
			if (strptime(dateStr.c_str(), "%a, %d %b %Y %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}
		} else {
			// Sun Nov  6 08:49:37 1994 (asctime)
			if (strptime(dateStr.c_str(), "%a %b %d %T %Y", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}

			// Sat 26 Nov 2016 13:38:06 GMT
			if (strptime(dateStr.c_str(), "%a %d %b %Y %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}

			// 23 Nov 2026 23:34:25 GMT
			if (strptime(dateStr.c_str(), "%d %b %Y %T", &tm) != NULL) {
				*time = timegm(&tm);
				return true;
			}
		}
	}

	logTrace(g_conf.m_logTraceHttpMime, "invalid date format='%.*s'", static_cast<int>(valueLen), value);
	return false;
}