Example #1
0
static void
nmea_reader_parse( NmeaReader*  r )
{
   /* we received a complete sentence, now parse it to generate
    * a new GPS fix...
    */
    NmeaTokenizer  tzer[1];
    Token          tok;

    D("Received: '%.*s'", r->pos, r->in);
    if (r->pos < 9) {
        D("Too short. discarded.");
        return;
    }

    nmea_tokenizer_init(tzer, r->in, r->in + r->pos);
#if GPS_DEBUG
    {
        int  n;
        D("Found %d tokens", tzer->count);
        for (n = 0; n < tzer->count; n++) {
            Token  tok = nmea_tokenizer_get(tzer,n);
            D("%2d: '%.*s'", n, tok.end-tok.p, tok.p);
        }
    }
#endif

    tok = nmea_tokenizer_get(tzer, 0);
    if (tok.p + 5 > tok.end) {
        D("sentence id '%.*s' too short, ignored.", tok.end-tok.p, tok.p);
        return;
    }

    // ignore first two characters.
    tok.p += 2;
    if ( !memcmp(tok.p, "GGA", 3) ) {
        // GPS fix
        Token  tok_time          = nmea_tokenizer_get(tzer,1);
        Token  tok_latitude      = nmea_tokenizer_get(tzer,2);
        Token  tok_latitudeHemi  = nmea_tokenizer_get(tzer,3);
        Token  tok_longitude     = nmea_tokenizer_get(tzer,4);
        Token  tok_longitudeHemi = nmea_tokenizer_get(tzer,5);
        Token  tok_altitude      = nmea_tokenizer_get(tzer,9);
        Token  tok_altitudeUnits = nmea_tokenizer_get(tzer,10);

        nmea_reader_update_time(r, tok_time);
        nmea_reader_update_latlong(r, tok_latitude,
                                      tok_latitudeHemi.p[0],
                                      tok_longitude,
                                      tok_longitudeHemi.p[0]);
        nmea_reader_update_altitude(r, tok_altitude, tok_altitudeUnits);

    } else if ( !memcmp(tok.p, "GSA", 3) ) {
        // do something ?
    } else if ( !memcmp(tok.p, "RMC", 3) ) {
        Token  tok_time          = nmea_tokenizer_get(tzer,1);
        Token  tok_fixStatus     = nmea_tokenizer_get(tzer,2);
        Token  tok_latitude      = nmea_tokenizer_get(tzer,3);
        Token  tok_latitudeHemi  = nmea_tokenizer_get(tzer,4);
        Token  tok_longitude     = nmea_tokenizer_get(tzer,5);
        Token  tok_longitudeHemi = nmea_tokenizer_get(tzer,6);
        Token  tok_speed         = nmea_tokenizer_get(tzer,7);
        Token  tok_bearing       = nmea_tokenizer_get(tzer,8);
        Token  tok_date          = nmea_tokenizer_get(tzer,9);

        D("in RMC, fixStatus=%c", tok_fixStatus.p[0]);
        if (tok_fixStatus.p[0] == 'A')
        {
            nmea_reader_update_date( r, tok_date, tok_time );

            nmea_reader_update_latlong( r, tok_latitude,
                                           tok_latitudeHemi.p[0],
                                           tok_longitude,
                                           tok_longitudeHemi.p[0] );

            nmea_reader_update_bearing( r, tok_bearing );
            nmea_reader_update_speed  ( r, tok_speed );
        }
    } else {
        tok.p -= 2;
        D("unknown sentence '%.*s", tok.end-tok.p, tok.p);
    }
    if (r->fix.flags != 0) {
#if GPS_DEBUG
        char   temp[256];
        char*  p   = temp;
        char*  end = p + sizeof(temp);
        struct tm   utc;

        p += snprintf( p, end-p, "sending fix" );
        if (r->fix.flags & GPS_LOCATION_HAS_LAT_LONG) {
            p += snprintf(p, end-p, " lat=%g lon=%g", r->fix.latitude, r->fix.longitude);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_ALTITUDE) {
            p += snprintf(p, end-p, " altitude=%g", r->fix.altitude);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_SPEED) {
            p += snprintf(p, end-p, " speed=%g", r->fix.speed);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_BEARING) {
            p += snprintf(p, end-p, " bearing=%g", r->fix.bearing);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_ACCURACY) {
            p += snprintf(p,end-p, " accuracy=%g", r->fix.accuracy);
        }
        gmtime_r( (time_t*) &r->fix.timestamp, &utc );
        p += snprintf(p, end-p, " time=%s", asctime( &utc ) );
        //D(temp);
#endif
        if (r->callback) {
            r->callback( &r->fix );
            r->fix.flags = 0;
        }
        else {
            D("no callback, keeping data until needed !");
        }
    }
}
Example #2
0
static void AddTimeClass(EvalContext *ctx, time_t time)
{
    struct tm parsed_time;
    struct tm gmt_parsed_time;
    char buf[CF_BUFSIZE];
    int day_text_index, quarter, interval_start, interval_end;

    if (localtime_r(&time, &parsed_time) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Unable to parse passed time. (localtime_r: %s)", GetErrorStr());
        return;
    }

    if (gmtime_r(&time, &gmt_parsed_time) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Unable to parse passed date. (gmtime_r: %s)", GetErrorStr());
        return;
    }

/* Lifecycle */

    snprintf(buf, CF_BUFSIZE, "Lcycle_%d", ((parsed_time.tm_year + 1900) % 3));
    EvalContextHeapAddHard(ctx, buf);

/* Year */

    snprintf(VYEAR, CF_BUFSIZE, "%04d", parsed_time.tm_year + 1900);
    snprintf(buf, CF_BUFSIZE, "Yr%04d", parsed_time.tm_year + 1900);
    EvalContextHeapAddHard(ctx, buf);

/* Month */

    strlcpy(VMONTH, MONTH_TEXT[parsed_time.tm_mon], 4);
    EvalContextHeapAddHard(ctx, MONTH_TEXT[parsed_time.tm_mon]);

/* Day of week */

/* Monday  is 1 in tm_wday, 0 in DAY_TEXT
   Tuesday is 2 in tm_wday, 1 in DAY_TEXT
   ...
   Sunday  is 0 in tm_wday, 6 in DAY_TEXT */
    day_text_index = (parsed_time.tm_wday + 6) % 7;
    EvalContextHeapAddHard(ctx, DAY_TEXT[day_text_index]);

/* Day */

    snprintf(VDAY, CF_BUFSIZE, "%d", parsed_time.tm_mday);
    snprintf(buf, CF_BUFSIZE, "Day%d", parsed_time.tm_mday);
    EvalContextHeapAddHard(ctx, buf);

/* Shift */

    strcpy(VSHIFT, SHIFT_TEXT[parsed_time.tm_hour / 6]);
    EvalContextHeapAddHard(ctx, VSHIFT);

/* Hour */

    snprintf(buf, CF_BUFSIZE, "Hr%02d", parsed_time.tm_hour);
    EvalContextHeapAddHard(ctx, buf);

/* GMT hour */

    snprintf(buf, CF_BUFSIZE, "GMT_Hr%d\n", gmt_parsed_time.tm_hour);
    EvalContextHeapAddHard(ctx, buf);

/* Quarter */

    quarter = parsed_time.tm_min / 15 + 1;

    snprintf(buf, CF_BUFSIZE, "Q%d", quarter);
    EvalContextHeapAddHard(ctx, buf);
    snprintf(buf, CF_BUFSIZE, "Hr%02d_Q%d", parsed_time.tm_hour, quarter);
    EvalContextHeapAddHard(ctx, buf);

/* Minute */

    snprintf(buf, CF_BUFSIZE, "Min%02d", parsed_time.tm_min);
    EvalContextHeapAddHard(ctx, buf);

    interval_start = (parsed_time.tm_min / 5) * 5;
    interval_end = (interval_start + 5) % 60;

    snprintf(buf, CF_BUFSIZE, "Min%02d_%02d", interval_start, interval_end);
    EvalContextHeapAddHard(ctx, buf);
}
Example #3
0
PHPAPI struct tm *php_gmtime_r(const time_t *const timep, struct tm *p_tm)
{
	if (gmtime_r(timep, p_tm) == 0)
		return (p_tm);
	return (NULL);
}
Example #4
0
int64_t client_tzoffset(int64_t local, int isdst) {
  struct tm tm;
  gmtime_r((const time_t*)&local, &tm);
  return (int64_t)(local + (isdst ? 3600 : 0) - mktime(&tm));
}
Example #5
0
static void AddTimeClass(EvalContext *ctx, time_t time)
{
    // The first element is the local timezone
    const char* tz_prefix[2] = { "", "GMT_" };
    const char* tz_function[2] = { "localtime_r", "gmtime_r" };
    struct tm tz_parsed_time[2];
    const struct tm* tz_tm[2] = {
        localtime_r(&time, &(tz_parsed_time[0])),
        gmtime_r(&time, &(tz_parsed_time[1]))
    };

    for (int tz = 0; tz < 2; tz++)
    {
        char buf[CF_BUFSIZE];
        int day_text_index, quarter, interval_start, interval_end;

        if (tz_tm[tz] == NULL)
        {
            Log(LOG_LEVEL_ERR, "Unable to parse passed time. (%s: %s)", tz_function[tz], GetErrorStr());
            return;
        }

/* Lifecycle */

        snprintf(buf, CF_BUFSIZE, "%sLcycle_%d", tz_prefix[tz], ((tz_parsed_time[tz].tm_year + 1900) % 3));
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Year */

        snprintf(buf, CF_BUFSIZE, "%sYr%04d", tz_prefix[tz], tz_parsed_time[tz].tm_year + 1900);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Month */

        snprintf(buf, CF_BUFSIZE, "%s%s", tz_prefix[tz], MONTH_TEXT[tz_parsed_time[tz].tm_mon]);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Day of week */

/* Monday  is 1 in tm_wday, 0 in DAY_TEXT
   Tuesday is 2 in tm_wday, 1 in DAY_TEXT
   ...
   Sunday  is 0 in tm_wday, 6 in DAY_TEXT */
        day_text_index = (tz_parsed_time[tz].tm_wday + 6) % 7;
        snprintf(buf, CF_BUFSIZE, "%s%s", tz_prefix[tz], DAY_TEXT[day_text_index]);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Day */

        snprintf(buf, CF_BUFSIZE, "%sDay%d", tz_prefix[tz], tz_parsed_time[tz].tm_mday);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Shift */

        snprintf(buf, CF_BUFSIZE, "%s%s", tz_prefix[tz], SHIFT_TEXT[tz_parsed_time[tz].tm_hour / 6]);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Hour */

        snprintf(buf, CF_BUFSIZE, "%sHr%02d", tz_prefix[tz], tz_parsed_time[tz].tm_hour);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");
        snprintf(buf, CF_BUFSIZE, "%sHr%d", tz_prefix[tz], tz_parsed_time[tz].tm_hour);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Quarter */

        quarter = tz_parsed_time[tz].tm_min / 15 + 1;

        snprintf(buf, CF_BUFSIZE, "%sQ%d", tz_prefix[tz], quarter);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");
        snprintf(buf, CF_BUFSIZE, "%sHr%02d_Q%d", tz_prefix[tz], tz_parsed_time[tz].tm_hour, quarter);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

/* Minute */

        snprintf(buf, CF_BUFSIZE, "%sMin%02d", tz_prefix[tz], tz_parsed_time[tz].tm_min);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");

        interval_start = (tz_parsed_time[tz].tm_min / 5) * 5;
        interval_end = (interval_start + 5) % 60;

        snprintf(buf, CF_BUFSIZE, "%sMin%02d_%02d", tz_prefix[tz], interval_start, interval_end);
        EvalContextClassPutHard(ctx, buf, "time_based,source=agent");
    }
}
Example #6
0
struct tm *gmtime (const time_t *tt) {
  static struct tm _mytm;
  return gmtime_r (tt, &_mytm);
}
Example #7
0
bool GetSunriseSunset(time_t &tSunrise,time_t &tSunset,time_t &tSunriseTomorrow,time_t &tSunsetTomorrow,float latitude,float longitude)
{
    longitude*=-1; // For some reason this is reversed from all the databases I found
    time_t rawtime;
    tm ptm;
    time ( &rawtime );
    gmtime_r ( &rawtime, &ptm );
    float JD=calcJD(ptm.tm_year+1900,ptm.tm_mon+1,ptm.tm_mday);

    time_t seconds;
    time_t tseconds;
    struct tm  tm;

    tm.tm_year= ptm.tm_year;
    tm.tm_mon=ptm.tm_mon;  /* Jan = 0, Feb = 1,.. Dec = 11 */
    tm.tm_mday=ptm.tm_mday;
    tm.tm_hour=0;
    tm.tm_min=0;
    tm.tm_sec=0;
    tm.tm_isdst=-1;  

    seconds = mktime(&tm);
    //int dst=tm.tm_isdst;

    gmtime_r ( &seconds, &ptm );
    int delta= ptm.tm_hour;

    tseconds= seconds;
    seconds= seconds + calcSunriseUTC( JD,  latitude,  longitude)*60;
    tSunrise = seconds - delta*3600;

    seconds=tseconds;
    seconds+=calcSunsetUTC( JD,  latitude,  longitude)*60;
    tSunset= seconds - delta*3600;

    // Don't know why sometimes this returns yesterday's sunrise/sunset
    if( tSunrise<rawtime && tSunset<rawtime )
    {
        tseconds += 86400;
        JD+=1;

        seconds=tseconds;
        seconds= seconds + calcSunriseUTC( JD,  latitude,  longitude)*60;
        tSunrise = seconds - delta*3600;

        seconds=tseconds;
        seconds+=calcSunsetUTC( JD,  latitude,  longitude)*60;
        tSunset= seconds - delta*3600;
    }
    // Or doesn't return the next sunrise/sunset if we're close
    else if( tSunrise>rawtime && tSunset>rawtime )
    {
        tseconds -= 86400;
        JD-=1;

        seconds=tseconds;
        seconds= seconds + calcSunriseUTC( JD,  latitude,  longitude)*60;
        tSunrise = seconds - delta*3600;

        seconds=tseconds;
        seconds+=calcSunsetUTC( JD,  latitude,  longitude)*60;
        tSunset= seconds - delta*3600;
    }

    seconds=tseconds+86400; // 1 day forward
    seconds= seconds + calcSunriseUTC( JD+1,  latitude,  longitude)*60;
    tSunriseTomorrow = seconds - delta*3600;

    seconds=tseconds+86400; // 1 day forward
    seconds+=calcSunsetUTC( JD+1,  latitude,  longitude)*60;
    tSunsetTomorrow= seconds - delta*3600;

    return true;

}
Example #8
0
/**
* @brief Sends a "/alarm" message to the service associated with this alarm.
*
* {"alarmId":1,"fired":true,"key":"appkey"}
*
* @param  alarm
*/
static void
fire_alarm(_Alarm *alarm)
{
	bool retVal;
	char buf_alarm[STD_ASCTIME_BUF_SIZE];

	struct tm tm_alarm;
	time_t rtctime = 0;

	gmtime_r(&alarm->expiry, &tm_alarm);
	asctime_r(&tm_alarm, buf_alarm);

	nyx_system_query_rtc_time(GetNyxSystemDevice(), &rtctime);

	SLEEPDLOG_DEBUG("fire_alarm() : Alarm (%s %s %s) fired at %s (rtc %ld)",
	                alarm->serviceName,
	                alarm->applicationName, alarm->key, buf_alarm, rtctime);

	GString *payload = g_string_sized_new(255);
	g_string_append_printf(payload, "{\"alarmId\":%d,\"fired\":true", alarm->id);

	if (alarm->key)
	{
		g_string_append_printf(payload, ",\"key\":\"%s\"", alarm->key);
	}

	if (alarm->applicationName && strcmp(alarm->applicationName, "") != 0)
	{
		g_string_append_printf(payload, ",\"applicationName\":\"%s\"",
		                       alarm->applicationName);
	}

	g_string_append_printf(payload, "}");

	LSError lserror;
	LSErrorInit(&lserror);

	if (alarm->serviceName && strcmp(alarm->serviceName, "") != 0)
	{
		char *uri = g_strdup_printf("luna://%s/alarm", alarm->serviceName);
		retVal = LSCall(GetLunaServiceHandle(), uri, payload->str,
		                NULL, NULL, NULL, &lserror);

		if (!retVal)
		{
			LSErrorPrint(&lserror, stderr);
			LSErrorFree(&lserror);
		}

		g_free(uri);
	}

	if (alarm->message)
	{
		retVal = LSMessageReply(GetLunaServiceHandle(), alarm->message,
		                        payload->str, &lserror);

		if (!retVal)
		{
			LSErrorPrint(&lserror, stderr);
			LSErrorFree(&lserror);
		}
	}

	g_string_free(payload, TRUE);
}
Example #9
0
static int get_basetimes(int fd)
{
	struct tm	tm;
	struct rtc_time	rtc;

	/* this process works in RTC time, except when working
	 * with the system clock (which always uses UTC).
	 */
	if (clock_mode == CM_UTC)
		setenv("TZ", "UTC", 1);
	tzset();

	/* read rtc and system clocks "at the same time", or as
	 * precisely (+/- a second) as we can read them.
	 */
	if (ioctl(fd, RTC_RD_TIME, &rtc) < 0) {
		perror(_("read rtc time"));
		return -1;
	}
	sys_time = time(0);
	if (sys_time == (time_t)-1) {
		perror(_("read system time"));
		return -1;
	}

	/* convert rtc_time to normal arithmetic-friendly form,
	 * updating tm.tm_wday as used by asctime().
	 */
	memset(&tm, 0, sizeof tm);
	tm.tm_sec = rtc.tm_sec;
	tm.tm_min = rtc.tm_min;
	tm.tm_hour = rtc.tm_hour;
	tm.tm_mday = rtc.tm_mday;
	tm.tm_mon = rtc.tm_mon;
	tm.tm_year = rtc.tm_year;
	tm.tm_isdst = -1;  /* assume the system knows better than the RTC */
	rtc_time = mktime(&tm);

	if (rtc_time == (time_t)-1) {
		perror(_("convert rtc time"));
		return -1;
	}

	if (verbose) {
		/* Unless the system uses UTC, either delta or tzone
		 * reflects a seconds offset from UTC.  The value can
		 * help sort out problems like bugs in your C library.
		 */
		printf("\tdelta   = %ld\n", sys_time - rtc_time);
		printf("\ttzone   = %ld\n", timezone);

		printf("\ttzname  = %s\n", tzname[daylight]);
		gmtime_r(&rtc_time, &tm);
		printf("\tsystime = %ld, (UTC) %s",
				(long) sys_time, asctime(gmtime(&sys_time)));
		printf("\trtctime = %ld, (UTC) %s",
				(long) rtc_time, asctime(&tm));
	}

	return 0;
}
Example #10
0
File: date.c Project: 0branch/boron
void date_toString( UThread* ut, const UCell* cell, UBuffer* str, int depth )
{
    char tmp[ 30 ];
    struct tm st;
    time_t tt;
    long timeZone;
    int hour;
    char* cp = tmp;
    double sec = ur_double(cell);
    //double frac;

    (void) ut;
    (void) depth;

    tt = (time_t) sec;
#if defined(_WIN32)
#if _MSC_VER >= 1400
    localtime_s( &st, &tt );
#else
    st = *localtime( &tt );
#endif
#else
    localtime_r( &tt, &st );
    //gmtime_r( &tt, &st );
#endif

#if defined(_WIN32)
#if _MSC_VER >= 1400
    _get_timezone( &timeZone );
    timeZone = -timeZone;
#else
    timeZone = -timezone;
#endif
#elif defined(__sun__)
    {
        struct tm gt;
        int days, hours;

        gmtime_r( &tt, &gt );
        days = st.tm_yday - gt.tm_yday;
        hours = (days < -1 ? 24 : days > 1 ? -24 : days * 24) +
                 st.tm_hour - gt.tm_hour;
        timeZone = (hours * 60 + st.tm_min - gt.tm_min) * 60;
    }
#else
    timeZone = st.tm_gmtoff;
#endif
    //printf( "KR gmtoff %ld %ld\n", st.tm_gmtoff, timezone );

    {
        int year = st.tm_year + 1900;
        cp = append02d( cp, year / 100 );
        cp = append02d( cp, year % 100 );
    }
    *cp++ = '-';
    cp = append02d( cp, st.tm_mon + 1 );
    *cp++ = '-';
    cp = append02d( cp, st.tm_mday );

    if( st.tm_hour || st.tm_min || st.tm_sec )
    {
        *cp++ = 'T';
        cp = append02d( cp, st.tm_hour );
        *cp++ = ':';
        cp = append02d( cp, st.tm_min );
        if( st.tm_sec )
        {
            *cp++ = ':';
            cp = append02d( cp, st.tm_sec );

            /*
            if( st.tm_sec < 10 )
                *cp++ = '0';
            frac = sec - floor(sec);
            if( frac )
                appendDecimal( out, frac );
            */
        }
    }

    if( timeZone )
    {
        if( timeZone < 0 )
        {
            *cp++ = '-';
            timeZone = -timeZone;
        }
        else
        {
            *cp++ = '+';
        }
        hour = timeZone / 3600;
        cp = append02d( cp, hour );
        *cp++ = ':';
        cp = append02d( cp, (timeZone / 60) - (hour * 60) );
    }
    else
    {
        *cp++ = 'Z';
    }
    *cp = '\0';

    ur_strAppendCStr( str, tmp );
}
Example #11
0
/* client has requested a file, so check for it and send the file.  Do not
 * refer to the client_t afterwards.  return 0 for success, -1 on error.
 */
int fserve_client_create (client_t *httpclient, const char *path)
{
    int bytes;
    struct stat file_buf;
    const char *range = NULL;
    off_t new_content_len = 0;
    off_t rangenumber = 0, content_length;
    int rangeproblem = 0;
    int ret = 0;
    char *fullpath;
    int m3u_requested = 0, m3u_file_available = 1;
    const char * xslt_playlist_requested = NULL;
    int xslt_playlist_file_available = 1;
    ice_config_t *config;
    FILE *file;

    fullpath = util_get_path_from_normalised_uri (path);
    INFO2 ("checking for file %H (%H)", path, fullpath);

    if (strcmp (util_get_extension (fullpath), "m3u") == 0)
        m3u_requested = 1;

    if (strcmp (util_get_extension (fullpath), "xspf") == 0)
        xslt_playlist_requested = "xspf.xsl";

    if (strcmp (util_get_extension (fullpath), "vclt") == 0)
        xslt_playlist_requested = "vclt.xsl";

    /* check for the actual file */
    if (stat (fullpath, &file_buf) != 0)
    {
        /* the m3u can be generated, but send an m3u file if available */
        if (m3u_requested == 0 && xslt_playlist_requested == NULL)
        {
            WARN2 ("req for file \"%H\" %s", fullpath, strerror (errno));
            client_send_404 (httpclient, "The file you requested could not be found");
            free (fullpath);
            return -1;
        }
        m3u_file_available = 0;
        xslt_playlist_file_available = 0;
    }

    httpclient->refbuf->len = PER_CLIENT_REFBUF_SIZE;

    if (m3u_requested && m3u_file_available == 0)
    {
        const char *host = httpp_getvar (httpclient->parser, "host");
        char *sourceuri = strdup (path);
        char *dot = strrchr(sourceuri, '.');

        /* at least a couple of players (fb2k/winamp) are reported to send a 
         * host header but without the port number. So if we are missing the
         * port then lets treat it as if no host line was sent */
        if (host && strchr (host, ':') == NULL)
            host = NULL;

        *dot = 0;
        httpclient->respcode = 200;
        if (host == NULL)
        {
            config = config_get_config();
            snprintf (httpclient->refbuf->data, BUFSIZE,
                    "HTTP/1.0 200 OK\r\n"
                    "Content-Type: audio/x-mpegurl\r\n\r\n"
                    "http://%s:%d%s\r\n", 
                    config->hostname, config->port,
                    sourceuri
                    );
            config_release_config();
        }
        else
        {
            snprintf (httpclient->refbuf->data, BUFSIZE,
                    "HTTP/1.0 200 OK\r\n"
                    "Content-Type: audio/x-mpegurl\r\n\r\n"
                    "http://%s%s\r\n", 
                    host, 
                    sourceuri
                    );
        }
        httpclient->refbuf->len = strlen (httpclient->refbuf->data);
        fserve_add_client (httpclient, NULL);
        free (sourceuri);
        free (fullpath);
        return 0;
    }
    if (xslt_playlist_requested && xslt_playlist_file_available == 0)
    {
        xmlDocPtr doc;
        char *reference = strdup (path);
        char *eol = strrchr (reference, '.');
        if (eol)
            *eol = '\0';
        doc = stats_get_xml (0, reference);
        free (reference);
        admin_send_response (doc, httpclient, TRANSFORMED, xslt_playlist_requested);
        xmlFreeDoc(doc);
        return 0;
    }

    /* on demand file serving check */
    config = config_get_config();
    if (config->fileserve == 0)
    {
        DEBUG1 ("on demand file \"%H\" refused", fullpath);
        client_send_404 (httpclient, "The file you requested could not be found");
        config_release_config();
        free (fullpath);
        return -1;
    }
    config_release_config();

    if (S_ISREG (file_buf.st_mode) == 0)
    {
        client_send_404 (httpclient, "The file you requested could not be found");
        WARN1 ("found requested file but there is no handler for it: %H", fullpath);
        free (fullpath);
        return -1;
    }

    file = fopen (fullpath, "rb");
    if (file == NULL)
    {
        WARN1 ("Problem accessing file \"%H\"", fullpath);
        client_send_404 (httpclient, "File not readable");
        free (fullpath);
        return -1;
    }
    free (fullpath);

    content_length = file_buf.st_size;
    range = httpp_getvar (httpclient->parser, "range");

    /* full http range handling is currently not done but we deal with the common case */
    if (range != NULL) {
        ret = 0;
        if (strncasecmp (range, "bytes=", 6) == 0)
            ret = sscanf (range+6, "%" SCN_OFF_T "-", &rangenumber);

        if (ret != 1) {
            /* format not correct, so lets just assume
               we start from the beginning */
            rangeproblem = 1;
        }
        if (rangenumber < 0) {
            rangeproblem = 1;
        }
        if (!rangeproblem) {
            ret = fseeko (file, rangenumber, SEEK_SET);
            if (ret != -1) {
                new_content_len = content_length - rangenumber;
                if (new_content_len < 0) {
                    rangeproblem = 1;
                }
            }
            else {
                rangeproblem = 1;
            }
            if (!rangeproblem) {
                /* Date: is required on all HTTP1.1 responses */
                char currenttime[50];
                time_t now;
                int strflen;
                struct tm result;
                off_t endpos = rangenumber+new_content_len-1;
                char *type;

                if (endpos < 0) {
                    endpos = 0;
                }
                time(&now);
                strflen = strftime(currenttime, 50, "%a, %d-%b-%Y %X GMT",
                                   gmtime_r(&now, &result));
                httpclient->respcode = 206;
                type = fserve_content_type (path);
                bytes = snprintf (httpclient->refbuf->data, BUFSIZE,
                    "HTTP/1.1 206 Partial Content\r\n"
                    "Date: %s\r\n"
                    "Accept-Ranges: bytes\r\n"
                    "Content-Length: %" PRI_OFF_T "\r\n"
                    "Content-Range: bytes %" PRI_OFF_T \
                    "-%" PRI_OFF_T "/%" PRI_OFF_T "\r\n"
                    "Content-Type: %s\r\n\r\n",
                    currenttime,
                    new_content_len,
                    rangenumber,
                    endpos,
                    content_length,
                    type);
                free (type);
            }
            else {
                goto fail;
            }
        }
        else {
            goto fail;
        }
    }
    else {
        char *type = fserve_content_type(path);
        httpclient->respcode = 200;
        bytes = snprintf (httpclient->refbuf->data, BUFSIZE,
            "HTTP/1.0 200 OK\r\n"
            "Accept-Ranges: bytes\r\n"
            "Content-Length: %" PRI_OFF_T "\r\n"
            "Content-Type: %s\r\n\r\n",
            content_length,
            type);
        free (type);
    }
    httpclient->refbuf->len = bytes;
    httpclient->pos = 0;

    stats_event_inc (NULL, "file_connections");
    fserve_add_client (httpclient, file);

    return 0;

fail:
    fclose (file);
    httpclient->respcode = 416;
    sock_write (httpclient->con->sock, 
            "HTTP/1.0 416 Request Range Not Satisfiable\r\n\r\n");
    client_destroy (httpclient);
    return -1;
}
Example #12
0
/*! \brief Internal function which validates provided Contact headers to confirm that they are acceptable, and returns number of contacts */
static int registrar_validate_contacts(const pjsip_rx_data *rdata, struct ao2_container *contacts, struct ast_sip_aor *aor, int *added, int *updated, int *deleted)
{
	pjsip_contact_hdr *previous = NULL, *contact = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
	struct registrar_contact_details details = {
		.pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Contact Comparison", 256, 256),
	};

	if (!details.pool) {
		return -1;
	}

	while ((contact = (pjsip_contact_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact->next))) {
		int expiration = registrar_get_expiration(aor, contact, rdata);
		RAII_VAR(struct ast_sip_contact *, existing, NULL, ao2_cleanup);
		char contact_uri[pjsip_max_url_size];

		if (contact->star) {
			/* The expiration MUST be 0 when a '*' contact is used and there must be no other contact */
			if ((expiration != 0) || previous) {
				pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
				return -1;
			}
			continue;
		} else if (previous && previous->star) {
			/* If there is a previous contact and it is a '*' this is a deal breaker */
			pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
			return -1;
		}
		previous = contact;

		if (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri)) {
			continue;
		}

		details.uri = pjsip_uri_get_uri(contact->uri);

		/* pjsip_uri_print returns -1 if there's not enough room in the buffer */
		if (pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri)) < 0) {
			/* If the total length of the uri is greater than pjproject can handle, go no further */
			pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
			return -1;
		}

		if (details.uri->host.slen >= pj_max_hostname) {
			/* If the length of the hostname is greater than pjproject can handle, go no further */
			pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
			return -1;
		}

		/* Determine if this is an add, update, or delete for policy enforcement purposes */
		if (!(existing = ao2_callback(contacts, 0, registrar_find_contact, &details))) {
			if (expiration) {
				(*added)++;
			}
		} else if (expiration) {
			(*updated)++;
		} else {
			(*deleted)++;
		}
	}

	/* The provided contacts are acceptable, huzzah! */
	pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
	return 0;
}

/*! \brief Callback function which prunes static contacts */
static int registrar_prune_static(void *obj, void *arg, int flags)
{
	struct ast_sip_contact *contact = obj;

	return ast_tvzero(contact->expiration_time) ? CMP_MATCH : 0;
}

/*! \brief Internal function used to delete a contact from an AOR */
static int registrar_delete_contact(void *obj, void *arg, int flags)
{
	struct ast_sip_contact *contact = obj;
	const char *aor_name = arg;

	ast_sip_location_delete_contact(contact);
	if (!ast_strlen_zero(aor_name)) {
		ast_verb(3, "Removed contact '%s' from AOR '%s' due to request\n", contact->uri, aor_name);
		ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
				"Contact: %s\r\n"
				"AOR: %s\r\n"
				"UserAgent: %s",
				contact->uri,
				aor_name,
				contact->user_agent);
	}

	return 0;
}

/*! \brief Internal function which adds a contact to a response */
static int registrar_add_contact(void *obj, void *arg, int flags)
{
	struct ast_sip_contact *contact = obj;
	pjsip_tx_data *tdata = arg;
	pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(tdata->pool);
	pj_str_t uri;

	pj_strdup2_with_null(tdata->pool, &uri, contact->uri);
	hdr->uri = pjsip_parse_uri(tdata->pool, uri.ptr, uri.slen, PJSIP_PARSE_URI_AS_NAMEADDR);
	hdr->expires = ast_tvdiff_ms(contact->expiration_time, ast_tvnow()) / 1000;

	pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr);

	return 0;
}

/*! \brief Helper function which adds a Date header to a response */
static void registrar_add_date_header(pjsip_tx_data *tdata)
{
	char date[256];
	struct tm tm;
	time_t t = time(NULL);

	gmtime_r(&t, &tm);
	strftime(date, sizeof(date), "%a, %d %b %Y %T GMT", &tm);

	ast_sip_add_header(tdata, "Date", date);
}
Example #13
0
void log_category_vlog(struct log_category *category, enum log_priority priority, const char *format, va_list args) {
	struct timeval t;
	struct tm tm;

	char *buf = alloca(LOG_BUFFER_SIZE);
	vsnprintf(buf, LOG_BUFFER_SIZE, format, args);

	if (appender_stdout >= priority) {
		char *color;

		gettimeofday(&t, NULL);
		gmtime_r(&t.tv_sec, &tm);

		switch (priority) {
		case LOG_PRIORITY_ERROR:
			color = "\033[0;31m";
			break;
		case LOG_PRIORITY_WARN:
			color = "\033[0;32m";
			break;
		case LOG_PRIORITY_INFO:
			color = "\033[0;33m";
			break;
		default:
		case LOG_PRIORITY_DEBUG:
			color = "\033[0;34m";
		}

#if defined(WIN32)
		printf("%02d.%03ld %-6s %s - %s\n",
		       t.tv_sec,
		       (long)(t.tv_usec / 1000),
		       log_priority_to_string(priority), category->name, buf);
#else
		printf("%s%04d%02d%02d %02d:%02d:%02d.%03ld %-6s %s - %s\033[0m\n",
		       color,
		       tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
		       tm.tm_hour, tm.tm_min, tm.tm_sec,
		       (long)(t.tv_usec / 1000),
		       log_priority_to_string(priority), category->name, buf);

#endif
	}

#ifdef HAVE_SYSLOG
	if (appender_syslog >= priority) {
		char *ptr, *lasts = NULL;

		/* log individual lines to syslog */
		ptr = strtok_r(buf, "\n", &lasts);
		syslog(priority, "%-6s %s - %s", log_priority_to_string(priority), category->name, ptr);

		ptr = strtok_r(NULL, "\n", &lasts);
		while (ptr) {
			syslog(priority, "%s", ptr);
			ptr = strtok_r(NULL, "\n", &lasts);
		}
	}
#endif

	return;
}
Example #14
0
void usec_to_tm(uint64_t usec, struct tm *result) {
  time_t sec = usec_to_sec(usec);
  gmtime_r(&sec, result);
}
Example #15
0
void
cf_fault_event_nostack(const cf_fault_context context,
		const cf_fault_severity severity, const char *fn, const int line,
		char *msg, ...)
{

	/* Prefilter: don't construct messages we won't end up writing */
	if (severity > cf_fault_filter[context])
		return;

	va_list argp;
	char mbuf[1024];
	time_t now;
	struct tm nowtm;

	/* Make sure there's always enough space for the \n\0. */
	size_t limit = sizeof(mbuf) - 2;

	/* Set the timestamp */
	now = time(NULL);
	gmtime_r(&now, &nowtm);
	size_t pos = strftime(mbuf, limit, "%b %d %Y %T %Z: ", &nowtm);

	/* Set the context/scope/severity tag */
	pos += snprintf(mbuf + pos, limit - pos, "%s (%s): ", cf_fault_severity_strings[severity], cf_fault_context_strings[context]);

	/*
	 * snprintf() and vsnprintf() will not write more than the size specified,
	 * but they return the size that would have been written without truncation.
	 * These checks make sure there's enough space for the final \n\0.
	 */
	if (pos > limit) {
		pos = limit;
	}

	/* Set the location */
	if (fn)
		pos += snprintf(mbuf + pos, limit - pos, "(%s:%d) ", fn, line);

	if (pos > limit) {
		pos = limit;
	}

	/* Append the message */
	va_start(argp, msg);
	pos += vsnprintf(mbuf + pos, limit - pos, msg, argp);
	va_end(argp);

	if (pos > limit) {
		pos = limit;
	}

	pos += snprintf(mbuf + pos, 2, "\n");

	/* Route the message to the correct destinations */
	if (0 == cf_fault_sinks_inuse) {
		/* If no fault sinks are defined, use stderr for important messages */
		if (severity <= NO_SINKS_LIMIT)
			fprintf(stderr, "%s", mbuf);
	} else {
		for (int i = 0; i < cf_fault_sinks_inuse; i++) {
			if ((severity <= cf_fault_sinks[i].limit[context]) || (CF_CRITICAL == severity)) {
				if (0 >= write(cf_fault_sinks[i].fd, mbuf, pos)) {
					// this is OK for a bit in case of a HUP. It's even better to queue the buffers and apply them
					// after the hup. TODO.
					fprintf(stderr, "internal failure in fault message write: %s\n", cf_strerror(errno));
				}
			}
		}
	}

	/* Critical errors */
	if (CF_CRITICAL == severity) {
		fflush(NULL);

		// these signals don't throw stack traces in our system
		raise(SIGINT);
	}
}
Example #16
0
/* gmtime */
struct tm * gmtime(time_t const * t)
{
	static struct tm ret;

	return gmtime_r(t, &ret);
}
Example #17
0
int main(int argc, char *argv[])
{
   int c, i;
   long tmask = 0, sslMode=0,sslOMode=0, tracelevel=0;
   char * tracefile = NULL;
#ifdef HAVE_UDS
   int enableUds=0;
#endif
   int enableHttp=0,enableHttps=0,useChunking=0,doBa=0,enableInterOp=0,httpLocalOnly=0;
   int syslogLevel=LOG_ERR;
   long dSockets,sSockets,pSockets;
   char *pauseStr;

   /* SF 3462309 - If there is an instance running already, return */
   int pid_found = 0;
   if ((pid_found = sfcb_is_running()) != 0) {
      mlogf(M_ERROR, M_SHOW, " --- A previous instance of sfcbd [%d] is running. Exiting.\n", pid_found);
      exit(1);
   }

   name = strrchr(argv[0], '/');
   if (name != NULL) ++name;
   else name = argv[0];

   collectStat=0;
   colorTrace=0;
   processName="sfcbd";
   provPauseStr=getenv("SFCB_PAUSE_PROVIDER");
   httpPauseStr=getenv("SFCB_PAUSE_CODEC");
   currentProc=sfcBrokerPid=getpid();
   restartArgc=argc;
   restartArgv=argv;


   exFlags = 0;

   static struct option const long_options[] =
       {
	   { "config-file",      required_argument, 0,        'c' },
	   { "daemon",           no_argument,       0,        'd' },
	   { "help",             no_argument,       0,        'h' },
	   { "color-trace",      no_argument,       0,        'k' },
	   { "collect-stats",    no_argument,       0,        's' },
	   { "syslog-level",     required_argument, 0,        'l' },
	   { "trace-components", required_argument, 0,        't' },
	   { "version",          no_argument,       0,        'v' },
           { "disable-repository-default-inst-provider", no_argument,       0,        'i' },
	   { 0, 0, 0, 0 }
       };

   while ((c = getopt_long(argc, argv, "c:dhkst:vil:", long_options, 0)) != -1)
   {
       switch(c)
       {
	   case 0:
	       break;

	   case 'c':
	       configfile = strdup(optarg);
	       break;

	   case 'd':
	       daemon(0, 0);
	       currentProc=sfcBrokerPid=getpid(); /* req. on some systems */
	       break;

	   case 'h':
	       usage(0);

	   case 'k':
	       colorTrace = 1;
	       break;

	   case 's':
	       collectStat = 1;
	       break;

	   case 't':
	       if (*optarg == '?') {
		   fprintf(stdout, "---   Traceable Components:     Int       Hex\n");
		   for (i = 0; traceIds[i].id; i++)
		       fprintf(stdout, "--- \t%18s:    %d\t0x%05X\n", traceIds[i].id, traceIds[i].code, traceIds[i].code);
		   exit(0);
	       } else if (isdigit(*optarg)) {
		   char *ep;
		   tmask = strtol(optarg, &ep, 0);
	       } else {
		   fprintf(stderr, "Try %s -t ? for a list of the trace components and bitmasks.\n", name);
		   exit(1);
	       }
	       break;

	   case 'v':
	       version();

           case 'i':
               disableDefaultProvider=1;
               break;

	   case 'l':
            if (strcmp(optarg,"LOG_ERR")==0) {
                syslogLevel=LOG_ERR;
            } else if (strcmp(optarg,"LOG_INFO")==0) {
                syslogLevel=LOG_INFO;
            } else if (strcmp(optarg,"LOG_DEBUG")==0) {
                syslogLevel=LOG_DEBUG;
            } else {
                fprintf(stderr,"Invalid value for syslog-level.\n");
	            usage(3);
            }
            break;
        
	   default:
	       usage(3);
       }
   }

   if (optind < argc)
   {
      fprintf(stderr,"SFCB not started: unrecognized config property %s\n",argv[optind]);
      usage(1);
   }

   startLogging(syslogLevel,1);

   mlogf(M_INFO,M_SHOW,"--- %s V" sfcHttpDaemonVersion " started - %d\n", name, currentProc);

   //get the creation timestamp for the sequence context
   struct timeval  tv;
   struct timezone tz;
   gettimeofday(&tv, &tz);
   struct tm cttm;
   sfcBrokerStart = (char *) malloc(15 * sizeof(char));
   memset((void *)sfcBrokerStart, 0, 15 * sizeof(char));
   if (gmtime_r(&tv.tv_sec, &cttm) != NULL) {
     strftime((char *)sfcBrokerStart, 15, "%Y%m%d%H%M%S", &cttm);
   }

   if (collectStat) {
       mlogf(M_INFO,M_SHOW,"--- Statistics collection enabled\n");
       remove("sfcbStat");
   }

   setupControl(configfile);      
   
   _SFCB_TRACE_INIT();

   if (tmask == 0) {
     /* trace mask not specified, check in config file */
     getControlNum("traceMask",&tmask);
   }
   
   if (tmask) {
     if (getControlNum("traceLevel",&tracelevel) || tracelevel == 0) {
       /* no tracelevel found in config file, use default */
       tracelevel = 1;
     }
     if (getenv("SFCB_TRACE_FILE") == NULL && 
	 getControlChars("traceFile",&tracefile) == 0) {
       /* only set tracefile from config file if not specified via env */
       _SFCB_TRACE_SETFILE(tracefile);
     }
     _SFCB_TRACE_START(tracelevel,tmask);
   }

//        SFCB_DEBUG
#ifndef SFCB_DEBUG
   if (tmask)
      mlogf(M_ERROR,M_SHOW,"--- SCFB_DEBUG not configured. -t %d ignored\n",tmask);
#endif

   if ((pauseStr=getenv("SFCB_PAUSE_PROVIDER"))) {
     printf("--- Provider pausing for: %s\n",pauseStr);
   }
      
   if (getControlBool("enableHttp", &enableHttp))
      enableHttp=1;

#ifdef HAVE_UDS
   if (getControlBool("enableUds", &enableUds))
      enableUds=1;
#endif
      
#if defined USE_SSL
   if (getControlBool("enableHttps", &enableHttps))
      enableHttps=0;

   sslMode=enableHttps;
#ifdef HAVE_UDS
   sslOMode=sslMode & !enableHttp & !enableUds;
#else
   sslOMode=sslMode & !enableHttp;
#endif
#else
   mlogf(M_INFO,M_SHOW,"--- SSL not configured\n");
   enableHttps=0;
   sslMode=0;
   sslOMode=0;
#endif
   
   if (getControlBool("useChunking", &useChunking))
      useChunking=0;
   if (useChunking==0)
         mlogf(M_INFO,M_SHOW,"--- Chunking disabled\n");

   if (getControlBool("doBasicAuth", &doBa))
      doBa=0;
   if (!doBa)
      mlogf(M_INFO,M_SHOW,"--- User authentication disabled\n");

   if (getControlBool("enableInterOp", &enableInterOp))
       enableInterOp=0;

   if (getControlNum("httpProcs", (long*)&dSockets))
      dSockets = 10;
   if (getControlNum("httpsProcs", (long*)&sSockets))
      sSockets = 10;
   if (getControlNum("provProcs", (long*)&pSockets))
      pSockets = 16;

   if (getControlBool("httpLocalOnly", &httpLocalOnly))
      httpLocalOnly=0;   
   if (httpLocalOnly)
      mlogf(M_INFO,M_SHOW,"--- External HTTP connections disabled; using loopback only\n");

   if (getControlNum("providerSampleInterval", (long*)&provSampleInterval))
      provSampleInterval = 30;
   if (getControlNum("providerTimeoutInterval", (long*)&provTimeoutInterval))
      provTimeoutInterval = 60;
   if (getControlBool("providerAutoGroup", (int*)&provAutoGroup))
      provAutoGroup=1;

   resultSockets=getSocketPair("sfcbd result");
   sfcbSockets=getSocketPair("sfcbd sfcb");

   if (enableInterOp==0)
       mlogf(M_INFO,M_SHOW,"--- InterOp namespace disabled\n");
   else
       exFlags = exFlags | 2;

   if ((enableInterOp && pSockets < 4 ) || pSockets < 3) {
     /* adjusting provider number */
     if (enableInterOp) {
       pSockets = 4;
     } else {
       pSockets = 3;
     }
     mlogf(M_INFO,M_SHOW,
	   "--- Max provider process number adjusted to %d\n", pSockets);
   }

   // Check for whitespace trimming option
   if (getControlBool("trimWhitespace", &trimws)) {
     trimws = 0;
   }

   if ((enableHttp || enableHttps) && dSockets > 0) {
     startHttp = 1;
   }
   
   initSem(dSockets,sSockets,pSockets);
   initProvProcCtl(pSockets);
   init_sfcBroker();
   initSocketPairs(pSockets,dSockets,sSockets);

   setSignal(SIGQUIT, handleSigquit,0);
   setSignal(SIGINT,  handleSigquit,0);
   
   setSignal(SIGTERM, handleSigquit,0);
   setSignal(SIGHUP,  handleSigHup,0);

   atexit(uninitGarbageCollector);

   startLocalConnectServer();
   
#ifndef LOCAL_CONNECT_ONLY_ENABLE
   if (startHttp) {
     startHttpd(argc, argv, sslMode);
   }
#endif // LOCAL_CONNECT_ONLY_ENABLE
   
#ifdef HAVE_JDBC
   //Start dbProtocol-Daemon
   if (startDbp) {
      if (sslMode)
         startDbpd(argc, argv,1);
      if (!sslOMode)
         startDbpd(argc, argv,0);
   }
#endif	


   setSignal(SIGSEGV, handleSigSegv,SA_ONESHOT);
   setSignal(SIGCHLD, handleSigChld,0);
   
   processProviderMgrRequests();

   return 0;
}
Example #18
0
void TimeSync::readNtpPacket(void)
{
    ssize_t n;
    long int tmit;   // the time -- This is a time_t sort of
    time_t t;
    struct sockaddr_storage saddr;
    socklen_t saddr_len = sizeof(saddr);
    uint32_t buf[1500/sizeof(uint32_t)];

    n = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&saddr, &saddr_len);   // try to read data (should succeed)
    if(n < 0) {                                               // failed? quit
        Debug::out(LOG_ERROR, "TimeSync: could not recieve packet: %s", strerror(errno));
        eState = NTP_FAILED;
        return;
    }
    char addr_str[48] = "";
    unsigned short port = 0;
    if(saddr.ss_family == AF_INET) {
        port = ntohs(((struct sockaddr_in *)&saddr)->sin_port);
        inet_ntop(saddr.ss_family, &((struct sockaddr_in *)&saddr)->sin_addr, addr_str, sizeof(addr_str));
    }
    Debug::out(LOG_DEBUG, "TimeSync: NTP Packet received from %s:%hu %ldbytes", addr_str, port, (long)n);

    /*
     * The high word of transmit time is the 10th word we get back
     * tmit is the time in seconds not accounting for network delays which
     * should be way less than a second if this is a local NTP server
     */
    tmit = ntohl((time_t)buf[4]);    //# get transmit time

    /*
     * Convert time to unix standard time NTP is number of seconds since 0000
     * UT on 1 January 1900 unix time is seconds since 0000 UT on 1 January
     * 1970 There has been a trend to add a 2 leap seconds every 3 years.
     * Leap seconds are only an issue the last second of the month in June and
     * December if you don't try to set the clock then it can be ignored but
     * this is importaint to people who coordinate times with GPS clock sources.
     */

    tmit -= 2208988800U;
    //printf("tmit=%d\n",tmit);
    /* use unix library function to show me the local time (it takes care
     * of timezone issues for both north and south of the equator and places
     * that do Summer time/ Daylight savings time.
     */

    //#compare to system time
    Debug::out(LOG_DEBUG, "TimeSync: NTP time is %s", ctime(&tmit));
    t = time(NULL);
    Debug::out(LOG_DEBUG, "TimeSync: System time is %ld seconds off", (t-tmit));

    //------------
    // check date validity, reject if it seems bad
    struct tm gmTime;
    memset(&gmTime, 0, sizeof(gmTime));         // clear struct
    gmtime_r(&tmit, &gmTime);                  // convert int time to struct time
    int year = gmTime.tm_year + 1900;
    Debug::out(LOG_DEBUG, "TimeSync: date from NTP is: %04d-%02d-%02d", year, gmTime.tm_mon + 1, gmTime.tm_mday);

    if(year < 2018 || year > 2050) {
        Debug::out(LOG_ERROR, "TimeSync: NTP year %04d seems to be invalid (it's not between 2018 and 2050), syncByNtp fail", year);
        eState = NTP_FAILED;
        return;
    }

    timeval tv;
    tv.tv_sec   = tmit;
    tv.tv_usec  = 0;

    if(settimeofday(&tv,NULL) < 0) {
        Debug::out(LOG_ERROR, "TimeSync: settimeofday(): %s", strerror(errno));
        eState = NTP_FAILED;
        return;
    }

    Debug::out(LOG_DEBUG, "TimeSync: date set to %d", tmit);
    eState = DATE_SET;
}
Example #19
0
struct tm *Time_toDateTime(const char *s, struct tm *t) {
        assert(t);
        assert(s);
        struct tm tm = {.tm_isdst = -1}; 
        int has_date = false, has_time = false;
        const char *limit = s + strlen(s), *marker, *token, *cursor = s;
	while (true) {
		if (cursor >= limit) {
                        if (has_date || has_time) {
                                *(struct tm*)t = tm;
                                return t;
                        }
                        THROW(SQLException, "Invalid date or time");
                }
                token = cursor;
                
#line 187 "<stdout>"
{
	unsigned char yych;
	unsigned int yyaccept = 0;
	static const unsigned char yybm[] = {
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		128, 128, 128, 128, 128, 128, 128, 128, 
		128, 128,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
		  0,   0,   0,   0,   0,   0,   0,   0, 
	};
	yych = *cursor;
	if (yych <= ',') {
		if (yych == '+') goto yy4;
	} else {
		if (yych <= '-') goto yy4;
		if (yych <= '/') goto yy2;
		if (yych <= '9') goto yy5;
	}
yy2:
	++cursor;
yy3:
#line 243 "src/system/Time.re"
	{
                        continue;
                 }
#line 240 "<stdout>"
yy4:
	yyaccept = 0;
	yych = *(marker = ++cursor);
	if (yych <= '/') goto yy3;
	if (yych <= '9') goto yy6;
	goto yy3;
yy5:
	yyaccept = 0;
	yych = *(marker = ++cursor);
	if (yych <= '/') goto yy3;
	if (yych <= '9') goto yy8;
	goto yy3;
yy6:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy9;
yy7:
	cursor = marker;
	if (yyaccept <= 1) {
		if (yyaccept == 0) {
			goto yy3;
		} else {
			goto yy10;
		}
	} else {
		if (yyaccept == 2) {
			goto yy26;
		} else {
			goto yy32;
		}
	}
yy8:
	yych = *++cursor;
	if (yych <= '/') goto yy11;
	if (yych <= '9') goto yy12;
	goto yy11;
yy9:
	yyaccept = 1;
	yych = *(marker = ++cursor);
	if (yych == '\n') goto yy10;
	if (yych <= '/') goto yy13;
	if (yych <= '9') goto yy14;
	goto yy13;
yy10:
#line 230 "src/system/Time.re"
	{ // Timezone: +-HH:MM, +-HH or +-HHMM is offset from UTC in seconds
                        if (has_time) { // Only set timezone if time has been seen
                                tm.TM_GMTOFF = _a2i(token + 1, 2) * 3600;
                                if (isdigit(token[3]))
                                        tm.TM_GMTOFF += _a2i(token + 3, 2) * 60;
                                else if (isdigit(token[4]))
                                        tm.TM_GMTOFF += _a2i(token + 4, 2) * 60;
                                if (token[0] == '-')
                                        tm.TM_GMTOFF *= -1;
                        }
                        continue;
                 }
#line 298 "<stdout>"
yy11:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy15;
	goto yy7;
yy12:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy16;
	goto yy7;
yy13:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy17;
	goto yy7;
yy14:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy18;
	goto yy7;
yy15:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy19;
	goto yy7;
yy16:
	yych = *++cursor;
	if (yych <= '/') goto yy20;
	if (yych <= '9') goto yy21;
	goto yy20;
yy17:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy22;
	goto yy7;
yy18:
	yych = *++cursor;
	if (yych <= '/') goto yy10;
	if (yych <= '9') goto yy22;
	goto yy10;
yy19:
	yych = *++cursor;
	if (yych <= '/') goto yy23;
	if (yych <= '9') goto yy7;
	goto yy23;
yy20:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy24;
	goto yy7;
yy21:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy25;
	goto yy7;
yy22:
	yych = *++cursor;
	goto yy10;
yy23:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy27;
	goto yy7;
yy24:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy28;
	goto yy7;
yy25:
	yyaccept = 2;
	yych = *(marker = ++cursor);
	if (yych <= '-') {
		if (yych == ',') goto yy29;
	} else {
		if (yych <= '.') goto yy29;
		if (yych <= '/') goto yy26;
		if (yych <= '9') goto yy30;
	}
yy26:
#line 222 "src/system/Time.re"
	{ // Compressed Time: HHMMSS
                        tm.tm_hour = _a2i(token, 2);
                        tm.tm_min  = _a2i(token + 2, 2);
                        tm.tm_sec  = _a2i(token + 4, 2);
                        has_time = true;
                        continue;
                 }
#line 386 "<stdout>"
yy27:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy31;
	goto yy7;
yy28:
	yych = *++cursor;
	if (yych <= '/') goto yy33;
	if (yych <= '9') goto yy7;
	goto yy33;
yy29:
	yych = *++cursor;
	if (yybm[0+yych] & 128) {
		goto yy34;
	}
	goto yy7;
yy30:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy36;
	goto yy7;
yy31:
	yyaccept = 3;
	yych = *(marker = ++cursor);
	if (yych == ',') goto yy38;
	if (yych == '.') goto yy38;
yy32:
#line 214 "src/system/Time.re"
	{ // Time: HH:MM:SS
                        tm.tm_hour = _a2i(token, 2);
                        tm.tm_min  = _a2i(token + 3, 2);
                        tm.tm_sec  = _a2i(token + 6, 2);
                        has_time = true;
                        continue;
                 }
#line 422 "<stdout>"
yy33:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy39;
	goto yy7;
yy34:
	++cursor;
	yych = *cursor;
	if (yybm[0+yych] & 128) {
		goto yy34;
	}
	goto yy26;
yy36:
	++cursor;
#line 206 "src/system/Time.re"
	{ // Compressed Date: YYYYMMDD
                        tm.tm_year  = _a2i(token, 4);
                        tm.tm_mon   = _a2i(token + 4, 2) - 1;
                        tm.tm_mday  = _a2i(token + 6, 2);
                        has_date = true;
                        continue;
                 }
#line 445 "<stdout>"
yy38:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy40;
	goto yy7;
yy39:
	yych = *++cursor;
	if (yych <= '/') goto yy7;
	if (yych <= '9') goto yy42;
	goto yy7;
yy40:
	++cursor;
	yych = *cursor;
	if (yych <= '/') goto yy32;
	if (yych <= '9') goto yy40;
	goto yy32;
yy42:
	++cursor;
#line 198 "src/system/Time.re"
	{ // Date: YYYY-MM-DD
                        tm.tm_year  = _a2i(token, 4);
                        tm.tm_mon   = _a2i(token + 5, 2) - 1;
                        tm.tm_mday  = _a2i(token + 8, 2);
                        has_date = true;
                        continue;
                 }
#line 472 "<stdout>"
}
#line 246 "src/system/Time.re"

        }
	return NULL;
}


char *Time_toString(time_t time, char result[20]) {
        assert(result);
        char x[2];
        struct tm ts = {.tm_isdst = -1};
        gmtime_r(&time, &ts);
        memcpy(result, "YYYY-MM-DD HH:MM:SS\0", 20);
        /*              0    5  8  11 14 17 */
        _i2a((ts.tm_year+1900)/100);
        result[0] = x[0];
        result[1] = x[1];
        _i2a((ts.tm_year+1900)%100);
        result[2] = x[0];
        result[3] = x[1];
        _i2a(ts.tm_mon + 1); // Months in 01-12
        result[5] = x[0];
        result[6] = x[1];
        _i2a(ts.tm_mday);
        result[8] = x[0];
        result[9] = x[1];
        _i2a(ts.tm_hour);
        result[11] = x[0];
        result[12] = x[1];
        _i2a(ts.tm_min);
        result[14] = x[0];
        result[15] = x[1];
        _i2a(ts.tm_sec);
        result[17] = x[0];
        result[18] = x[1];
	return result;
}


time_t Time_now(void) {
	struct timeval t;
	if (gettimeofday(&t, NULL) != 0)
                THROW(AssertException, "%s", System_getLastError());
	return t.tv_sec;
}


long long Time_milli(void) {
	struct timeval t;
	if (gettimeofday(&t, NULL) != 0)
                THROW(AssertException, "%s", System_getLastError());
	return (long long)t.tv_sec * 1000  +  (long long)t.tv_usec / 1000;
}


int Time_usleep(long u) {
        struct timeval t;
        t.tv_sec = u / USEC_PER_SEC;
        t.tv_usec = (suseconds_t)(u % USEC_PER_SEC);
        select(0, 0, 0, 0, &t);
        return true;
}
DebitRequestPacket::DebitRequestPacket( uint16 packetID, 
                                        uint16 requestID,
                                        uint32 UIN,
                                        uint32 messageID,
                                        uint32 debInfo,
                                        uint32 date,
                                        uint32 operationType,
                                        uint32 sentSize,
                                        const char* userOrigin,
                                        const char* serverID,
                                        const char* operationDescription,
                                        uint32 nbrTransactions,
                                        uint32 originIP,
                                        uint16 originPort )
      : RequestPacket( MAX_PACKET_SIZE,
                       DEBIT_REQUEST_PRIO,
                       Packet::PACKETTYPE_DEBITREQUEST,
                       packetID,
                       requestID,
                       MAX_UINT32 )
{
   //Fill packet
   int pos = REQUEST_HEADER_SIZE;
   setOriginIP( originIP );
   setOriginPort( originPort );
   incWriteLong( pos, UIN );
   incWriteLong( pos, messageID );
   incWriteLong( pos, debInfo );
   incWriteLong( pos, date );
   incWriteLong( pos, operationType );
   incWriteLong( pos, sentSize );
   incWriteLong( pos, nbrTransactions );
   incWriteString( pos, userOrigin );
   incWriteString( pos, serverID );   
   incWriteString( pos, operationDescription);
   setLength( pos );
   
   MC2String debitFilename = 
      Properties::getProperty( "DEBIT_FILENAME", "" );

   if ( ! debitFilename.empty() ) {
      //Append to file
      char buffer[1024];
      uint32 size = 0;
   
      //Log time
      size += sprintf( buffer + size, "%d\t", date );
      
      time_t time = date;
      struct tm result;
      size += strftime( buffer + size, 1023 - size, 
                        "%a, %d %b %Y %H:%M:%S GMT\t", gmtime_r( &time, &result ) );
   
      //Log UIN
      size += sprintf( buffer + size, "%u\t", UIN );

      //Log server and user
      size += sprintf( buffer + size, "%s\t", userOrigin );
      size += sprintf( buffer + size, "%s\t", serverID );
   
      //Log nbr of sent sms/bytes
      size += sprintf( buffer + size, "%u\t", sentSize );

      //Log messageID
      size += sprintf( buffer + size, "%u\t", messageID );
   
      //Log operationType
      size += sprintf( buffer + size, "%u\t", operationType );
   
      //Log operationDescription
      size += sprintf( buffer + size, "%s\t", operationDescription );
   
      //Add a linefeed
      size += sprintf( buffer + size, "\n" );
   
      //Write to file
      ofstream outf;
   
      outf.open( debitFilename.c_str(), ios::app );
   
      if( !outf )
         cout << buffer;
      else
         outf << buffer;
   }
}
Example #21
0
static void nn_global_submit_errors (int i, struct nn_sock *s,
    char *name, int value)
{
    /*  TODO(tailhook) dynamically allocate buffer  */
    char buf[4096];
    char *curbuf;
    int buf_left;
    char timebuf[20];
    time_t numtime;
    struct tm strtime;
    int len;
    struct nn_list_item *it;
    struct nn_ep *ep;

    if (self.statistics_socket >= 0) {
        /*  TODO(tailhook) add HAVE_GMTIME_R ifdef  */
        time(&numtime);
#ifdef NN_HAVE_GMTIME_R
        gmtime_r (&numtime, &strtime);
#else
#error
#endif
        strftime (timebuf, 20, "%Y-%m-%dT%H:%M:%S", &strtime);
        if(*s->socket_name) {
            len = sprintf (buf, "ESTP:%s:%s:socket.%s:%s: %sZ 10 %d\n",
                self.hostname, self.appname, s->socket_name, name,
                timebuf, value);
        } else {
            len = sprintf (buf, "ESTP:%s:%s:socket.%d:%s: %sZ 10 %d\n",
                self.hostname, self.appname, i, name,
                timebuf, value);
        }
        buf_left = sizeof(buf) - len;
        curbuf = buf + len;


        for (it = nn_list_begin (&s->eps);
              it != nn_list_end (&s->eps);
              it = nn_list_next (&s->eps, it)) {
            ep = nn_cont (it, struct nn_ep, item);

            if (ep->last_errno) {
#ifdef NN_HAVE_WINDOWS
                len = _snprintf_s (curbuf, buf_left, _TRUNCATE,
                    " nanomsg: Endpoint %d [%s] error: %s\n",
                    ep->eid, nn_ep_getaddr (ep), nn_strerror (ep->last_errno));
#else
                 len = snprintf (curbuf, buf_left,
                     " nanomsg: Endpoint %d [%s] error: %s\n",
                     ep->eid, nn_ep_getaddr (ep), nn_strerror (ep->last_errno));
#endif
                if (buf_left < len)
                    break;
                curbuf += len;
                buf_left -= len;
            }

        }

        (void) nn_send (self.statistics_socket,
            buf, sizeof(buf) - buf_left, NN_DONTWAIT);
    }
Example #22
0
struct tm *_qdbm_gmtime(const time_t *timep, struct tm *result) {
    return gmtime_r(timep, result);
}
Example #23
0
TimeZone getLocalTimeZone()
{
   // this function is not reentrant, but it's ok, as
   // the worst thing that may happen in MT or multiprocess
   // is double calculation of the cached value.

   // infer timezone by checking gmtime/localtime
   if( s_cached_timezone == tz_local )
   {
      struct tm gmt;
      struct tm loc;
      time_t now;
      time( &now );
      localtime_r( &now, &loc );
      gmtime_r( &now, &gmt );

      // great, let's determine the time shift
      int64 tgmt = mktime( &gmt );
      int64 tloc = mktime( &loc );
      long shift = (long) (tloc - tgmt);
      if ( loc.tm_isdst )
      {
         shift += 3600;
      }

      long hours = shift / 3600;
      long minutes = (shift/60) % 60;


      // and now, let's see if we have one of our zones:
      switch( hours )
      {
         case 1: s_cached_timezone = tz_UTC_E_1; break;
         case 2: s_cached_timezone = tz_UTC_E_2; break;
         case 3: s_cached_timezone = tz_UTC_E_3; break;
         case 4: s_cached_timezone = tz_UTC_E_4; break;
         case 5: s_cached_timezone = tz_UTC_E_5; break;
         case 6: s_cached_timezone = tz_UTC_E_6; break;
         case 7: s_cached_timezone = tz_UTC_E_7; break;
         case 8: s_cached_timezone = tz_UTC_E_8; break;
         case 9:
            if( minutes == 30 )
                  s_cached_timezone = tz_ACST;
               else
                  s_cached_timezone = tz_UTC_E_9;
            break;

         case 10:
            if( minutes == 30 )
               s_cached_timezone = tz_ACDT;
            else
               s_cached_timezone = tz_UTC_E_10;
         break;

         case 11:
            if( minutes == 30 )
               s_cached_timezone = tz_NFT;
            else
               s_cached_timezone = tz_UTC_E_11;
         break;

         case 12: s_cached_timezone = tz_UTC_E_11; break;

         case -1: s_cached_timezone = tz_UTC_W_1;
         case -2:
            if( minutes == 30 )
               s_cached_timezone = tz_HAT;
            else
               s_cached_timezone = tz_UTC_W_2;
            break;
         case -3:
            if( minutes == 30 )
               s_cached_timezone = tz_NST;
            else
               s_cached_timezone = tz_UTC_W_3;
            break;
         case -4: s_cached_timezone = tz_UTC_W_4; break;
         case -5: s_cached_timezone = tz_UTC_W_5; break;
         case -6: s_cached_timezone = tz_UTC_W_6; break;
         case -7: s_cached_timezone = tz_UTC_W_7; break;
         case -8: s_cached_timezone = tz_UTC_W_8; break;
         case -9: s_cached_timezone = tz_UTC_W_9; break;
         case -10: s_cached_timezone = tz_UTC_W_10; break;
         case -11: s_cached_timezone = tz_UTC_W_11; break;
         case -12: s_cached_timezone = tz_UTC_W_12; break;

         default:
            s_cached_timezone = tz_NONE;
      }
   }

   return s_cached_timezone;
}
Example #24
0
/*
 * pcf_poll - called by the transmit procedure
 */
static void
pcf_poll(
	int unit,
	struct peer *peer
	)
{
	struct refclockproc *pp;
	char buf[LENPCF];
	struct tm tm, *tp;
	time_t t;
	
	pp = peer->procptr;

	buf[0] = 0;
	if (read(pp->io.fd, buf, sizeof(buf)) < (ssize_t)sizeof(buf) || buf[0] != 9) {
		refclock_report(peer, CEVNT_FAULT);
		return;
	}

	ZERO(tm);

	tm.tm_mday = buf[11] * 10 + buf[10];
	tm.tm_mon = buf[13] * 10 + buf[12] - 1;
	tm.tm_year = buf[15] * 10 + buf[14];
	tm.tm_hour = buf[7] * 10 + buf[6];
	tm.tm_min = buf[5] * 10 + buf[4];
	tm.tm_sec = buf[3] * 10 + buf[2];
	tm.tm_isdst = (buf[8] & 1) ? 1 : (buf[8] & 2) ? 0 : -1;

	/*
	 * Y2K convert the 2-digit year
	 */
	if (tm.tm_year < 99)
		tm.tm_year += 100;
	
	t = mktime(&tm);
	if (t == (time_t) -1) {
		refclock_report(peer, CEVNT_BADTIME);
		return;
	}

#if defined(__GLIBC__) && defined(_BSD_SOURCE)
	if ((tm.tm_isdst > 0 && tm.tm_gmtoff != 7200)
	    || (tm.tm_isdst == 0 && tm.tm_gmtoff != 3600)
	    || tm.tm_isdst < 0) {
#ifdef DEBUG
		if (debug)
			printf ("local time zone not set to CET/CEST\n");
#endif
		refclock_report(peer, CEVNT_BADTIME);
		return;
	}
#endif

	pp->lencode = strftime(pp->a_lastcode, BMAX, "%Y %m %d %H %M %S", &tm);

#if defined(_REENTRANT) || defined(_THREAD_SAFE)
	tp = gmtime_r(&t, &tm);
#else
	tp = gmtime(&t);
#endif
	if (!tp) {
		refclock_report(peer, CEVNT_FAULT);
		return;
	}

	get_systime(&pp->lastrec);
	pp->polls++;
	pp->year = tp->tm_year + 1900;
	pp->day = tp->tm_yday + 1;
	pp->hour = tp->tm_hour;
	pp->minute = tp->tm_min;
	pp->second = tp->tm_sec;
	pp->nsec = buf[16] * 31250000;
	if (buf[17] & 1)
		pp->nsec += 500000000;

#ifdef DEBUG
	if (debug)
		printf ("pcf%d: time is %04d/%02d/%02d %02d:%02d:%02d UTC\n",
			unit, pp->year, tp->tm_mon + 1, tp->tm_mday, pp->hour,
			pp->minute, pp->second);
#endif

	if (!refclock_process(pp)) {
		refclock_report(peer, CEVNT_BADTIME);
		return;
	}
	record_clock_stats(&peer->srcadr, pp->a_lastcode);
	if ((buf[1] & 1) && !(pp->sloppyclockflag & CLK_FLAG2))
		pp->leap = LEAP_NOTINSYNC;
	else
		pp->leap = LEAP_NOWARNING;
	pp->lastref = pp->lastrec;
	refclock_receive(peer);
}
Example #25
0
static void RemoveTimeClass(EvalContext *ctx, time_t time)
{
    // The first element is the local timezone
    const char* tz_prefix[2] = { "", "GMT_" };
    const char* tz_function[2] = { "localtime_r", "gmtime_r" };
    struct tm tz_parsed_time[2];
    const struct tm* tz_tm[2] = {
        localtime_r(&time, &(tz_parsed_time[0])),
        gmtime_r(&time, &(tz_parsed_time[1]))
    };

    for (int tz = 0; tz < 2; tz++)
    {
        int i, j;
        char buf[CF_BUFSIZE];

        if (tz_tm[tz] == NULL)
        {
            Log(LOG_LEVEL_ERR, "Unable to parse passed time. (%s: %s)", tz_function[tz], GetErrorStr());
            return;
        }

/* Lifecycle */

        for( i = 0; i < 3; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%sLcycle_%d", tz_prefix[tz], i);
            EvalContextClassRemove(ctx, NULL, buf);
        }

/* Year */

        snprintf(buf, CF_BUFSIZE, "%sYr%04d", tz_prefix[tz], tz_parsed_time[tz].tm_year - 1 + 1900);
        EvalContextClassRemove(ctx, NULL, buf);
        snprintf(buf, CF_BUFSIZE, "%sYr%04d", tz_prefix[tz], tz_parsed_time[tz].tm_year + 1900);
        EvalContextClassRemove(ctx, NULL, buf);

/* Month */

        for( i = 0; i < 12; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%s%s", tz_prefix[tz], MONTH_TEXT[i]);
            EvalContextClassRemove(ctx, NULL, buf);
        }

/* Day of week */

        for( i = 0; i < 7; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%s%s", tz_prefix[tz], DAY_TEXT[i]);
            EvalContextClassRemove(ctx, NULL, buf);
        }

/* Day */

        for( i = 1; i < 32; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%sDay%d", tz_prefix[tz], i);
            EvalContextClassRemove(ctx, NULL, buf);
        }

/* Shift */

        for( i = 0; i < 4; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%s%s", tz_prefix[tz], SHIFT_TEXT[i]);
            EvalContextClassRemove(ctx, NULL, buf);
        }

/* Hour */

        for( i = 0; i < 24; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%sHr%02d", tz_prefix[tz], i);
            EvalContextClassRemove(ctx, NULL, buf);
            snprintf(buf, CF_BUFSIZE, "%sHr%d", tz_prefix[tz], i);
            EvalContextClassRemove(ctx, NULL, buf);
        }

/* Quarter */

        for( i = 1; i <= 4; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%sQ%d", tz_prefix[tz], i);
            EvalContextClassRemove(ctx, NULL, buf);
            for( j = 0; j < 24; j++ )
            {
                snprintf(buf, CF_BUFSIZE, "%sHr%02d_Q%d", tz_prefix[tz], j, i);
                EvalContextClassRemove(ctx, NULL, buf);
            }
        }

/* Minute */

        for( i = 0; i < 60; i++ )
        {
            snprintf(buf, CF_BUFSIZE, "%sMin%02d", tz_prefix[tz], i);
            EvalContextClassRemove(ctx, NULL, buf);
        }

        for( i = 0; i < 60; i += 5 )
        {
            snprintf(buf, CF_BUFSIZE, "%sMin%02d_%02d", tz_prefix[tz], i, (i + 5) % 60);
            EvalContextClassRemove(ctx, NULL, buf);
        }
    }
}
Example #26
0
/* cf_fault_event
 * Respond to a fault */
void
cf_fault_event(const cf_fault_context context, const cf_fault_severity severity,
		const char *file_name, const char * function_name, const int line,
		char *msg, ...)
{
	/* Prefilter: don't construct messages we won't end up writing */
	if (severity > cf_fault_filter[context])
		return;

	va_list argp;
	char mbuf[1024];
	time_t now;
	struct tm nowtm;
	size_t pos;


	/* Make sure there's always enough space for the \n\0. */
	size_t limit = sizeof(mbuf) - 2;

	/* Set the timestamp */
	now = time(NULL);

	if (g_use_local_time) {
		localtime_r(&now, &nowtm);
		pos = strftime(mbuf, limit, "%b %d %Y %T GMT%z: ", &nowtm);
	}
	else {
		gmtime_r(&now, &nowtm);
		pos = strftime(mbuf, limit, "%b %d %Y %T %Z: ", &nowtm);
	}

	/* Set the context/scope/severity tag */
	pos += snprintf(mbuf + pos, limit - pos, "%s (%s): ", cf_fault_severity_strings[severity], cf_fault_context_strings[context]);

	/*
	 * snprintf() and vsnprintf() will not write more than the size specified,
	 * but they return the size that would have been written without truncation.
	 * These checks make sure there's enough space for the final \n\0.
	 */
	if (pos > limit) {
		pos = limit;
	}

	/* Set the location: FileName, Optional FunctionName, and Line.  It is
	 * expected that we'll use FunctionName ONLY for debug() and detail(),
	 * hence we must treat function_name as optional.  */
	const char * func_name = ( function_name == NULL ) ? "" : function_name;
	if (file_name) {
		pos += snprintf(mbuf + pos, limit - pos, "(%s:%s:%d) ",
				file_name, func_name, line);
	}

	if (pos > limit) {
		pos = limit;
	}

	/* Append the message */
	va_start(argp, msg);
	pos += vsnprintf(mbuf + pos, limit - pos, msg, argp);
	va_end(argp);

	if (pos > limit) {
		pos = limit;
	}

	pos += snprintf(mbuf + pos, 2, "\n");

	/* Route the message to the correct destinations */
	if (0 == cf_fault_sinks_inuse) {
		/* If no fault sinks are defined, use stderr for important messages */
		if (severity <= NO_SINKS_LIMIT)
			fprintf(stderr, "%s", mbuf);
	} else {
		for (int i = 0; i < cf_fault_sinks_inuse; i++) {
			if ((severity <= cf_fault_sinks[i].limit[context]) || (CF_CRITICAL == severity)) {
				if (0 >= write(cf_fault_sinks[i].fd, mbuf, pos)) {
					// this is OK for a bit in case of a HUP. It's even better to queue the buffers and apply them
					// after the hup. TODO.
					fprintf(stderr, "internal failure in fault message write: %s\n", cf_strerror(errno));
				}
			}
		}
	}

	/* Critical errors */
	if (CF_CRITICAL == severity) {
		fflush(NULL);

		// Our signal handler will log a stack trace.
		abort();
	}
} // end cf_fault_event()
Example #27
0
struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result)
	{
	struct tm *ts = NULL;

#if defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_OS2) && !defined(__CYGWIN32__) && (!defined(OPENSSL_SYS_VMS) || defined(gmtime_r)) && !defined(OPENSSL_SYS_MACOSX) && !defined(OPENSSL_SYS_SUNOS) && !defined(PLAYSTATION3)
	/* should return &data, but doesn't on some systems,
	   so we don't even look at the return value */
	gmtime_r(timer,result);
	ts = result;
#elif !defined(OPENSSL_SYS_VMS)
	ts = gmtime(timer);
	if (ts == NULL)
		return NULL;

	memcpy(result, ts, sizeof(struct tm));
	ts = result;
#endif
#ifdef OPENSSL_SYS_VMS
	if (ts == NULL)
		{
		static $DESCRIPTOR(tabnam,"LNM$DCL_LOGICAL");
		static $DESCRIPTOR(lognam,"SYS$TIMEZONE_DIFFERENTIAL");
		char logvalue[256];
		unsigned int reslen = 0;
		struct {
			short buflen;
			short code;
			void *bufaddr;
			unsigned int *reslen;
		} itemlist[] = {
			{ 0, LNM$_STRING, 0, 0 },
			{ 0, 0, 0, 0 },
		};
		int status;
		time_t t;

		/* Get the value for SYS$TIMEZONE_DIFFERENTIAL */
		itemlist[0].buflen = sizeof(logvalue);
		itemlist[0].bufaddr = logvalue;
		itemlist[0].reslen = &reslen;
		status = sys$trnlnm(0, &tabnam, &lognam, 0, itemlist);
		if (!(status & 1))
			return NULL;
		logvalue[reslen] = '\0';

		t = *timer;

/* The following is extracted from the DEC C header time.h */
/*
**  Beginning in OpenVMS Version 7.0 mktime, time, ctime, strftime
**  have two implementations.  One implementation is provided
**  for compatibility and deals with time in terms of local time,
**  the other __utc_* deals with time in terms of UTC.
*/
/* We use the same conditions as in said time.h to check if we should
   assume that t contains local time (and should therefore be adjusted)
   or UTC (and should therefore be left untouched). */
#if __CRTL_VER < 70000000 || defined _VMS_V6_SOURCE
		/* Get the numerical value of the equivalence string */
		status = atoi(logvalue);

		/* and use it to move time to GMT */
		t -= status;
#endif

		/* then convert the result to the time structure */

		/* Since there was no gmtime_r() to do this stuff for us,
		   we have to do it the hard way. */
		{
		/* The VMS epoch is the astronomical Smithsonian date,
		   if I remember correctly, which is November 17, 1858.
		   Furthermore, time is measure in thenths of microseconds
		   and stored in quadwords (64 bit integers).  unix_epoch
		   below is January 1st 1970 expressed as a VMS time.  The
		   following code was used to get this number:

		   #include <stdio.h>
		   #include <stdlib.h>
		   #include <lib$routines.h>
		   #include <starlet.h>

		   main()
		   {
		     unsigned long systime[2];
		     unsigned short epoch_values[7] =
		       { 1970, 1, 1, 0, 0, 0, 0 };

		     lib$cvt_vectim(epoch_values, systime);

		     printf("%u %u", systime[0], systime[1]);
		   }
		*/
		unsigned long unix_epoch[2] = { 1273708544, 8164711 };
		unsigned long deltatime[2];
		unsigned long systime[2];
		struct vms_vectime
			{
			short year, month, day, hour, minute, second,
				centi_second;
			} time_values;
		long operation;

		/* Turn the number of seconds since January 1st 1970 to
		   an internal delta time.
		   Note that lib$cvt_to_internal_time() will assume
		   that t is signed, and will therefore break on 32-bit
		   systems some time in 2038.
		*/
		operation = LIB$K_DELTA_SECONDS;
		status = lib$cvt_to_internal_time(&operation,
			&t, deltatime);

		/* Add the delta time with the Unix epoch and we have
		   the current UTC time in internal format */
		status = lib$add_times(unix_epoch, deltatime, systime);

		/* Turn the internal time into a time vector */
		status = sys$numtim(&time_values, systime);

		/* Fill in the struct tm with the result */
		result->tm_sec = time_values.second;
		result->tm_min = time_values.minute;
		result->tm_hour = time_values.hour;
		result->tm_mday = time_values.day;
		result->tm_mon = time_values.month - 1;
		result->tm_year = time_values.year - 1900;

		operation = LIB$K_DAY_OF_WEEK;
		status = lib$cvt_from_internal_time(&operation,
			&result->tm_wday, systime);
		result->tm_wday %= 7;

		operation = LIB$K_DAY_OF_YEAR;
		status = lib$cvt_from_internal_time(&operation,
			&result->tm_yday, systime);
		result->tm_yday--;

		result->tm_isdst = 0; /* There's no way to know... */

		ts = result;
		}
		}
#endif
	return ts;
	}	
Example #28
0
/* cf_fault_event -- TWO:  Expand on the LOG ability by being able to
 * print the contents of a BINARY array if we're passed a valid ptr (not NULL).
 * We will print the array according to "format".
 * Parms:
 * (*) scope: The module family (e.g. AS_RW, AS_UDF...)
 * (*) severify: The scope severity (e.g. INFO, DEBUG, DETAIL)
 * (*) file_name: Ptr to the FILE generating the call
 * (*) function_name: Ptr to the function generating the call
 * (*) line: The function (really, the FILE) line number of the source call
 * (*) mem_ptr: Ptr to memory location of binary array (or NULL)
 * (*) len: Length of the binary string
 * (*) format: The single char showing the format (e.g. 'D', 'B', etc)
 * (*) msg: The format msg string
 * (*) ... : The variable set of parameters the correspond to the msg string.
 *
 * NOTE: We will eventually merge this function with the original cf_fault_event()
 **/
void
cf_fault_event2(const cf_fault_context context, const cf_fault_severity severity,
		const char *file_name, const char *function_name, const int line,
		void * mem_ptr, size_t len, cf_display_type dt, char *msg, ...)
{

	/* Prefilter: don't construct messages we won't end up writing */
	if (severity > cf_fault_filter[context])
		return;

	va_list argp;
	char mbuf[MAX_BINARY_BUF_SZ];
	time_t now;
	struct tm nowtm;
	size_t pos;

	char binary_buf[MAX_BINARY_BUF_SZ];

	// Arbitrarily limit output to a fixed maximum length.
	if (len > MAX_BINARY_BUF_SZ) {
		len = MAX_BINARY_BUF_SZ;
	}
	char * labelp = NULL; // initialize to quiet build warning

	/* Make sure there's always enough space for the \n\0. */
	size_t limit = sizeof(mbuf) - 2;

	/* Set the timestamp */
	now = time(NULL);

	if (g_use_local_time) {
		localtime_r(&now, &nowtm);
		pos = strftime(mbuf, limit, "%b %d %Y %T GMT%z: ", &nowtm);
	}
	else {
		gmtime_r(&now, &nowtm);
		pos = strftime(mbuf, limit, "%b %d %Y %T %Z: ", &nowtm);
	}

	// If we're given a valid MEMORY POINTER for a binary value, then
	// compute the string that corresponds to the bytes.
	if (mem_ptr) {
		switch (dt) {
		case CF_DISPLAY_HEX_DIGEST:
			labelp = "Digest";
			generate_packed_hex_string(mem_ptr, len, binary_buf);
			break;
		case CF_DISPLAY_HEX_SPACED:
			labelp = "HexSpaced";
			generate_spaced_hex_string(mem_ptr, len, binary_buf);
			break;
		case CF_DISPLAY_HEX_PACKED:
			labelp = "HexPacked";
			generate_packed_hex_string(mem_ptr, len, binary_buf);
			break;
		case CF_DISPLAY_HEX_COLUMNS:
			labelp = "HexColumns";
			generate_column_hex_string(mem_ptr, len, binary_buf);
			break;
		case CF_DISPLAY_BASE64:
			labelp = "Base64";
			generate_base64_string(mem_ptr, len, binary_buf);
			break;
		case CF_DISPLAY_BITS_SPACED:
			labelp = "BitsSpaced";
			generate_4spaced_bits_string(mem_ptr, len, binary_buf);
			break;
		case CF_DISPLAY_BITS_COLUMNS:
			labelp = "BitsColumns";
			generate_column_bits_string(mem_ptr, len, binary_buf);
			break;
		default:
			labelp = "Unknown Format";
			binary_buf[0] = 0; // make sure it's null terminated.
			break;

		} // end switch
	} // if binary data is present

	/* Set the context/scope/severity tag */
	pos += snprintf(mbuf + pos, limit - pos, "%s (%s): ",
			cf_fault_severity_strings[severity],
			cf_fault_context_strings[context]);

	/*
	 * snprintf() and vsnprintf() will not write more than the size specified,
	 * but they return the size that would have been written without truncation.
	 * These checks make sure there's enough space for the final \n\0.
	 */
	if (pos > limit) {
		pos = limit;
	}

	/* Set the location: FileName, Optional FunctionName, and Line.  It is
	 * expected that we'll use FunctionName ONLY for debug() and detail(),
	 * hence we must treat function_name as optional.  */
	const char * func_name = ( function_name == NULL ) ? "" : function_name;
	if (file_name) {
		pos += snprintf(mbuf + pos, limit - pos, "(%s:%s:%d) ",
				file_name, func_name, line);
	}

	// Check for overflow (see above).
	if (pos > limit) {
		pos = limit;
	}

	/* Append the message */
	va_start(argp, msg);
	pos += vsnprintf(mbuf + pos, limit - pos, msg, argp);
	va_end(argp);

	// Check for overflow (see above).
	if (pos > limit) {
		pos = limit;
	}

	// Append our final BINARY string, if present (some might pass in NULL).
	if ( mem_ptr ) {
		pos += snprintf(mbuf + pos, limit - pos, "<%s>:%s", labelp, binary_buf);
	}

	// Check for overflow (see above).
	if (pos > limit) {
		pos = limit;
	}

	pos += snprintf(mbuf + pos, 2, "\n");

	/* Route the message to the correct destinations */
	if (0 == cf_fault_sinks_inuse) {
		/* If no fault sinks are defined, use stderr for critical messages */
		if (CF_CRITICAL == severity)
			fprintf(stderr, "%s", mbuf);
	} else {
		for (int i = 0; i < cf_fault_sinks_inuse; i++) {
			if ((severity <= cf_fault_sinks[i].limit[context]) || (CF_CRITICAL == severity)) {
				if (0 >= write(cf_fault_sinks[i].fd, mbuf, pos)) {
					// this is OK for a bit in case of a HUP. It's even better to queue the buffers and apply them
					// after the hup. TODO.
					fprintf(stderr, "internal failure in fault message write: %s\n", cf_strerror(errno));
				}
			}
		}
	}

	/* Critical errors */
	if (CF_CRITICAL == severity) {
		fflush(NULL);

		// Our signal handler will log a stack trace.
		abort();
	}
}
Example #29
0
/* Convert *TP to UTC, storing the broken-down time into *TMP.
   Return TMP if successful, NULL otherwise.  This is like gmtime_r(TP, TMP),
   except typically faster if USE_LOCALTIME_RZ.  */
static struct tm *
my_gmtime_r(time_t *tp, struct tm *tmp)
{
	return USE_LOCALTIME_RZ ?
	    localtime_rz(gmtz, tp, tmp) : gmtime_r(tp, tmp);
}
Example #30
0
/*
 *This function given a unix time, set in a mk_pointer
 * the date in the RFC1123 format like:
 *
 *    Wed, 23 Jun 2010 22:32:01 GMT
 *
 * it also adds a 'CRLF' at the end
 */
int mk_utils_utime2gmt(char **data, time_t date)
{
    const int size = 31;
    unsigned short year, mday, hour, min, sec;
    char *buf=0;
    struct tm *gtm;

    if (date == 0) {
        if ((date = time(NULL)) == -1) {
            return -1;
        }
    }
    else {
        /* Maybe it's converted already? */
        if (mk_utils_gmt_cache_get(data, date) == MK_TRUE) {
            return size;
        }
    }

    /* Convert unix time to struct tm */
    gtm = mk_cache_get(mk_cache_utils_gmtime);

    /* If this function was invoked from a non-thread context it should exit */
    mk_bug(!gtm);
    gtm = gmtime_r(&date, gtm);
    if (!gtm) {
        return -1;
    }

    /* struct tm -> tm_year counts number of years after 1900 */
    year = gtm->tm_year + 1900;

    /* Signed division is slow, by using unsigned we gain 25% speed */
    mday = gtm->tm_mday;
    hour = gtm->tm_hour;
    min = gtm->tm_min;
    sec = gtm->tm_sec;

    /* Compose template */
    buf = *data;

    /* Week day */
    memcpy(buf, mk_date_wd[gtm->tm_wday], 5);
    buf += 5;

    /* Day of the month */
    *buf++ = ('0' + (mday / 10));
    *buf++ = ('0' + (mday % 10));
    *buf++ = ' ';

    /* Month */
    memcpy(buf, mk_date_ym[gtm->tm_mon], 4);
    buf += 4;

    /* Year */
    *buf++ = ('0' + (year / 1000) % 10);
    *buf++ = ('0' + (year / 100) % 10);
    *buf++ = ('0' + (year / 10) % 10);
    *buf++ = ('0' + (year % 10));
    *buf++ = ' ';

    /* Hour */
    *buf++ = ('0' + (hour / 10));
    *buf++ = ('0' + (hour % 10));
    *buf++ = ':';

    /* Minutes */
    *buf++ = ('0' + (min / 10));
    *buf++ = ('0' + (min % 10));
    *buf++ = ':';

    /* Seconds */
    *buf++ = ('0' + (sec / 10));
    *buf++ = ('0' + (sec % 10));

    /* GMT Time zone + CRLF */
    memcpy(buf, " GMT\r\n\0", 7);

    /* Add new entry to the cache */
    mk_utils_gmt_cache_add(*data, date);

    /* Set mk_pointer data len */
    return size;
}