Ejemplo n.º 1
0
/**
 * Get system start time
 * @return seconds since unix epoch
 */
static time_t get_starttime() {
        struct sysinfo info;
        if (sysinfo(&info) < 0) {
                LogError("system statistic error -- cannot get system uptime: %s\n", STRERROR);
                return 0;
        }
        return Time_now() - info.uptime;
}
Ejemplo n.º 2
0
void Time_init(void) {
	/* =================================================== */

	memcpy(days_in_month, monthdays, sizeof(TimeInt) * MAX_MONTHS);
	memset(cum_monthdays, 0, sizeof(TimeInt) * MAX_MONTHS);
	cum_monthdays[NoMonth] = 1000;

	Time_now(); /* set structure's time to current */
}
Ejemplo n.º 3
0
int usb_serial_write( const void *buffer, uint32_t size )
{
	uint32_t len;
	Time start;
	const uint8_t *src = (const uint8_t *)buffer;
	uint8_t *dest;

	tx_noautoflush = 1;
	while ( size > 0 )
	{
		if ( !tx_packet )
		{
			start = Time_now();
			while ( 1 )
			{
				if ( !usb_configuration )
				{
					tx_noautoflush = 0;
					return -1;
				}
				if ( usb_tx_packet_count( CDC_TX_ENDPOINT ) < TX_PACKET_LIMIT )
				{
					tx_noautoflush = 1;
					tx_packet = usb_malloc();
					if ( tx_packet )
						break;
					tx_noautoflush = 0;
				}
				if ( Time_duration_ms( start ) > TX_TIMEOUT_MS || transmit_previous_timeout )
				{
					transmit_previous_timeout = 1;
					return -1;
				}
				yield();
			}
		}
		transmit_previous_timeout = 0;
		len = CDC_TX_SIZE - tx_packet->index;
		if ( len > size )
			len = size;
		dest = tx_packet->buf + tx_packet->index;
		tx_packet->index += len;
		size -= len;
		while ( len-- > 0 )
			*dest++ = *src++;
		if ( tx_packet->index >= CDC_TX_SIZE )
		{
			tx_packet->len = CDC_TX_SIZE;
			usb_tx( CDC_TX_ENDPOINT, tx_packet );
			tx_packet = NULL;
		}
		usb_cdc_transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
	}
	tx_noautoflush = 0;
	return 0;
}
Ejemplo n.º 4
0
inline void LED_scan()
{
	// Latency measurement start
	Latency_start_time( ledLatencyResource );

	// Check for current change event
	if ( LED_currentEvent )
	{
		// Turn LEDs off in low power mode
		if ( LED_currentEvent < 150 )
		{
			LED_enable_current = 0;

			// Pause animations and clear display
			Pixel_setAnimationControl( AnimationControl_WipePause );
		}
		else
		{
			LED_enable_current = 1;

			// Start animations
			Pixel_setAnimationControl( AnimationControl_Forward );
		}

		LED_currentEvent = 0;
	}

	// Check if an LED_pause is set
	// Some ISSI operations need a clear buffer, but still have the chip running
	if ( LED_pause )
		goto led_finish_scan;

	// Check enable state
	if ( LED_enable && LED_enable_current )
	{
		// Disable Hardware shutdown of ISSI chips (pull high)
		GPIO_Ctrl( hardware_shutdown_pin, GPIO_Type_DriveHigh, GPIO_Config_Pullup );
	}
	// Only write pages to I2C if chip is enabled (i.e. Hardware shutdown is disabled)
	else
	{
		// Enable hardware shutdown
		GPIO_Ctrl( hardware_shutdown_pin, GPIO_Type_DriveLow, GPIO_Config_Pullup );
		goto led_finish_scan;
	}

	// Check if any I2C buses have errored
	// Reset the buses and restart the Frame State
	if ( i2c_error() )
	{
		i2c_reset();
		Pixel_FrameState = FrameState_Update;
	}

	// Only start if we haven't already
	// And if we've finished updating the buffers
	if ( Pixel_FrameState == FrameState_Sending )
		goto led_finish_scan;

	// Only send frame to ISSI chip if buffers are ready
	if ( Pixel_FrameState != FrameState_Ready )
		goto led_finish_scan;

	// Adjust frame rate (i.e. delay and do something else for a bit)
	Time duration = Time_duration( LED_timePrev );
	if ( duration.ms < LED_framerate )
		goto led_finish_scan;

	// FPS Display
	if ( LED_displayFPS )
	{
		// Show frame calculation
		dbug_msg("1frame/");
		printInt32( Time_ms( duration ) );
		print("ms + ");
		printInt32( duration.ticks );
		print(" ticks");

		// Check if we're not meeting frame rate
		if ( duration.ms > LED_framerate )
		{
			print(" - Could not meet framerate: ");
			printInt32( LED_framerate );
		}

		print( NL );
	}

	// Emulated brightness control
	// Lower brightness by LED_brightness
#if ISSI_Chip_31FL3731_define == 1
	for ( uint8_t chip = 0; chip < ISSI_Chips_define; chip++ )
	{
		for ( uint8_t ch = 0; ch < LED_EnableBufferLength; ch++ )
		{
			LED_pageBuffer_brightness[ chip ].ledctrl[ ch ] = LED_pageBuffer[ chip ].ledctrl[ ch ];
		}

		for ( uint8_t ch = 0; ch < LED_BufferLength; ch++ )
		{
			// Don't modify is 0
			if ( LED_pageBuffer[ chip ].buffer[ ch ] == 0 || LED_brightness == 0 )
			{
				LED_pageBuffer_brightness[ chip ].buffer[ ch ] = 0;
				continue;
			}

			// XXX (HaaTa) Yes, this is a bit slow, but it's pretty accurate
			LED_pageBuffer_brightness[ chip ].buffer[ ch ] =
				(LED_pageBuffer[ chip ].buffer[ ch ] * LED_brightness) / 0xFF;
		}
	}
#endif

	// Update frame start time
	LED_timePrev = Time_now();

	// Set the page of all the ISSI chips
	// This way we can easily link the buffers to send the brightnesses in the background
	for ( uint8_t ch = 0; ch < ISSI_Chips_define; ch++ )
	{
		uint8_t bus = LED_ChannelMapping[ ch ].bus;
		// Page Setup
		LED_setupPage(
			bus,
			LED_ChannelMapping[ ch ].addr,
			ISSI_LEDPwmPage
		);
	}

	// Send current set of buffers
	// Uses interrupts to send to all the ISSI chips
	// Pixel_FrameState will be updated when complete
	LED_chipSend = 0; // Start with chip 0
	LED_linkedSend();

led_finish_scan:
	// Latency measurement end
	Latency_end_time( ledLatencyResource );
}
Ejemplo n.º 5
0
// Setup
inline void LED_setup()
{
	// Register Scan CLI dictionary
	CLI_registerDictionary( ledCLIDict, ledCLIDictName );
#if Storage_Enable_define == 1
	Storage_registerModule(&LedStorage);
#endif

	// Zero out FPS time
	LED_timePrev = Time_now();

	// Initialize framerate
	LED_framerate = ISSI_FrameRate_ms_define;

	// Global brightness setting
	LED_brightness = ISSI_Global_Brightness_define;

	// Initialize I2C error counters
	i2c_initial();

	// Initialize I2C
	i2c_setup();

	// Setup LED_pageBuffer addresses and brightness section
	LED_pageBuffer[0].i2c_addr = LED_MapCh1_Addr_define;
	LED_pageBuffer[0].reg_addr = ISSI_LEDPwmRegStart;
#if ISSI_Chips_define >= 2
	LED_pageBuffer[1].i2c_addr = LED_MapCh2_Addr_define;
	LED_pageBuffer[1].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 3
	LED_pageBuffer[2].i2c_addr = LED_MapCh3_Addr_define;
	LED_pageBuffer[2].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 4
	LED_pageBuffer[3].i2c_addr = LED_MapCh4_Addr_define;
	LED_pageBuffer[3].reg_addr = ISSI_LEDPwmRegStart;
#endif

	// Brightness emulation
#if ISSI_Chip_31FL3731_define
	// Setup LED_pageBuffer addresses and brightness section
	LED_pageBuffer_brightness[0].i2c_addr = LED_MapCh1_Addr_define;
	LED_pageBuffer_brightness[0].reg_addr = ISSI_LEDPwmRegStart;
#if ISSI_Chips_define >= 2
	LED_pageBuffer_brightness[1].i2c_addr = LED_MapCh2_Addr_define;
	LED_pageBuffer_brightness[1].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 3
	LED_pageBuffer_brightness[2].i2c_addr = LED_MapCh3_Addr_define;
	LED_pageBuffer_brightness[2].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 4
	LED_pageBuffer_brightness[3].i2c_addr = LED_MapCh4_Addr_define;
	LED_pageBuffer_brightness[3].reg_addr = ISSI_LEDPwmRegStart;
#endif
#endif

	// LED default setting
	LED_enable = ISSI_Enable_define;
	LED_enable_current = ISSI_Enable_define; // Needs a default setting, almost always unset immediately

	// Enable Hardware shutdown (pull low)
	GPIO_Ctrl( hardware_shutdown_pin, GPIO_Type_DriveSetup, GPIO_Config_Pullup );
	GPIO_Ctrl( hardware_shutdown_pin, GPIO_Type_DriveLow, GPIO_Config_Pullup );

#if ISSI_Chip_31FL3733_define == 1 || ISSI_Chip_31FL3736_define == 1
	// Reset I2C bus (pull high, then low)
	// NOTE: This GPIO may be shared with the debug LED
	GPIO_Ctrl( iirst_pin, GPIO_Type_DriveSetup, GPIO_Config_Pullup );
	GPIO_Ctrl( iirst_pin, GPIO_Type_DriveHigh, GPIO_Config_Pullup );
	delay_us(50);
	GPIO_Ctrl( iirst_pin, GPIO_Type_DriveLow, GPIO_Config_Pullup );
#endif

	// Zero out Frame Registers
	// This needs to be done before disabling the hardware shutdown (or the leds will do undefined things)
	LED_zeroControlPages();

	// Disable Hardware shutdown of ISSI chips (pull high)
	if ( LED_enable && LED_enable_current )
	{
		GPIO_Ctrl( hardware_shutdown_pin, GPIO_Type_DriveHigh, GPIO_Config_Pullup );
	}

	// Reset LED sequencing
	LED_reset();

	// Allocate latency resource
	ledLatencyResource = Latency_add_resource("ISSILed", LatencyOption_Ticks);
}
Ejemplo n.º 6
0
int main(void) {

        setenv("TZ", "CET", 1);
        tzset();
        
        Bootstrap(); // Need to initialize library

        printf("============> Start Time Tests\n\n");


        printf("=> Test1: check string ouput\n");
        {
                char result[30];
                Time_string(1267441200, result); /* 01 Mar 2010 12:00:00 */
                printf("\tResult: unix time 1267441200 to localtime:\n\t %s\n", result);
                assert(Str_isEqual(result, "Mon, 01 Mar 2010 12:00:00"));
                Time_gmtstring(1267441200, result); /* 01 Mar 2010 12:00:00 GMT */
                printf("\tResult: unix time 1267441200 to UTC:\n\t %s\n", result);
                assert(Str_isEqual("Mon, 01 Mar 2010 11:00:00 GMT", result));
        }
        printf("=> Test1: OK\n\n");

        printf("=> Test2: check current time\n");
        {
                struct timeval tv;
                assert(!gettimeofday(&tv, NULL));
                assert(Time_now() == tv.tv_sec);
        }
        printf("=> Test2: OK\n\n");

        printf("=> Test3: sleep 1s\n");
        {
                time_t now;
                now = Time_now();
                Time_usleep(1000000);
                assert((now + 1) == Time_now());
        }
        printf("=> Test3: OK\n\n");

        printf("=> Test4: uptime\n");
        {
                time_t days = 668040;
                time_t hours = 63240;
                time_t min = 2040;
                char result[24];
                printf("\tResult: uptime days: %s\n", Time_uptime(days, result));
                assert(Str_isEqual(result, "7d, 17h, 34m"));
                printf("\tResult: uptime hours: %s\n", Time_uptime(hours, result));
                assert(Str_isEqual(result, "17h, 34m"));
                printf("\tResult: uptime min: %s\n", Time_uptime(min, result));
                assert(Str_isEqual(result, "34m"));
                printf("\tResult: uptime 0: %s\n", Time_uptime(0, result));
                assert(Str_isEqual(result, ""));
                assert(Time_uptime(0, NULL) == NULL);
        }
        printf("=> Test4: OK\n\n");

        printf("=> Test5: Time attributes\n");
        {
                char b[STRLEN];
                time_t time = 730251059; // Sun, 21. Feb 1993 00:30:59
                printf("\tResult: %s (winter time)\n", Time_string(time, b));
                assert(Time_seconds(time) == 59);
                assert(Time_minutes(time) == 30);
                assert(Time_hour(time) == 0);
                assert(Time_weekday(time) == 0);
                assert(Time_day(time) == 21);
                assert(Time_month(time) == 2);
                assert(Time_year(time) == 1993);
                time = 1253045894; // Tue, 15 Sep 2009 22:18:14 +0200
                printf("\tResult: %s (DTS/summer time)\n", Time_string(time, b));
                assert(Str_startsWith(b, "Tue, 15 Sep 2009 22:18:14"));
        }
        printf("=> Test5: OK\n\n");

        printf("=> Test6: Time_build\n");
        {
                time_t time = Time_build(2001, 1, 29, 12, 0, 0);
                assert(Time_seconds(time) == 0);
                assert(Time_minutes(time) == 0);
                assert(Time_hour(time) == 12);
                assert(Time_day(time) == 29);
                assert(Time_month(time) == 1);
                assert(Time_year(time) == 2001);
                // Verify assert on out of range
                TRY
                {
                        Time_build(1969, 1, 29, 12, 0, 0);
                        printf("Test failed\n");
                        exit(1);
                }
                CATCH (AssertException)
                END_TRY;
                TRY
                {
                        Time_build(1970, 0, 29, 12, 0, 0);
                        printf("Test failed\n");
                        exit(1);
                }
                CATCH (AssertException)
                END_TRY;
        }
        printf("=> Test6: OK\n\n");

        printf("=> Test7: Time_incron\n");
        {
                const char *exactmatch = "27 11 5 7 2";
                const char *matchall = "* * * * *";
                const char *invalid1 = "a bc d";
                const char *invalid2 = "* * * *  "; // Too few fields
                const char *invalid3 = "* * * * * * "; // Too many fields
                const char *range1 = "* 10-11 1-5 * 1-5";
                const char *rangeoutside = "1-10 9-10 1-5 * 1-5";
                const char *sequence = "* 10,11 1-3,5,6 * *";
                const char *sequenceoutside = "* 10,11,12 4,5,6 * 0,6";
                time_t time = Time_build(2011, 7, 5, 11, 27, 5);
                assert(Time_incron(exactmatch, time));
                assert(Time_incron(matchall, time));
                assert(! Time_incron(invalid1, time));
                assert(! Time_incron(invalid2, time));
                assert(! Time_incron(invalid3, time));
                assert(Time_incron(range1, time));
                assert(! Time_incron(rangeoutside, time));
                assert(Time_incron(sequence, time));
                assert(! Time_incron(sequenceoutside, time));
        }
        printf("=> Test7: OK\n\n");

        printf("============> Time Tests: OK\n\n");

        return 0;
}
Ejemplo n.º 7
0
static int _commandExecute(Service_T S, command_t c, char *msg, int msglen, int64_t *timeout) {
        ASSERT(S);
        ASSERT(c);
        ASSERT(msg);
        msg[0] = 0;
        int status = -1;
        Command_T C = NULL;
        TRY
        {
                // May throw exception if the program doesn't exist (was removed while Monit was up)
                C = Command_new(c->arg[0], NULL);
        }
        ELSE
        {
                snprintf(msg, msglen, "Program %s failed: %s", c->arg[0], Exception_frame.message);
        }
        END_TRY;
        if (C) {
                for (int i = 1; i < c->length; i++)
                        Command_appendArgument(C, c->arg[i]);
                if (c->has_uid)
                        Command_setUid(C, c->uid);
                if (c->has_gid)
                        Command_setGid(C, c->gid);
                Command_setEnv(C, "MONIT_DATE", Time_string(Time_now(), (char[26]){}));
                Command_setEnv(C, "MONIT_SERVICE", S->name);
                Command_setEnv(C, "MONIT_HOST", Run.system->name);
                Command_setEnv(C, "MONIT_EVENT", c == S->start ? "Started" : c == S->stop ? "Stopped" : "Restarted");
                Command_setEnv(C, "MONIT_DESCRIPTION", c == S->start ? "Started" : c == S->stop ? "Stopped" : "Restarted");
                if (S->type == Service_Process) {
                        Command_vSetEnv(C, "MONIT_PROCESS_PID", "%d", Util_isProcessRunning(S, false));
                        Command_vSetEnv(C, "MONIT_PROCESS_MEMORY", "%ld", S->inf->priv.process.mem_kbyte);
                        Command_vSetEnv(C, "MONIT_PROCESS_CHILDREN", "%d", S->inf->priv.process.children);
                        Command_vSetEnv(C, "MONIT_PROCESS_CPU_PERCENT", "%d", S->inf->priv.process.cpu_percent);
                }
                Process_T P = Command_execute(C);
                Command_free(&C);
                if (P) {
                        do {
                                Time_usleep(RETRY_INTERVAL);
                                *timeout -= RETRY_INTERVAL;
                        } while ((status = Process_exitStatus(P)) < 0 && *timeout > 0 && ! (Run.flags & Run_Stopped));
                        if (*timeout <= 0)
                                snprintf(msg, msglen, "Program %s timed out", c->arg[0]);
                        int n, total = 0;
                        char buf[STRLEN];
                        do {
                                if ((n = _getOutput(Process_getErrorStream(P), buf, sizeof(buf))) <= 0)
                                        n = _getOutput(Process_getInputStream(P), buf, sizeof(buf));
                                if (n > 0) {
                                        buf[n] = 0;
                                        DEBUG("%s", buf);
                                        // Report the first message (override existing plain timeout message if some program output is available)
                                        if (! total)
                                                snprintf(msg, msglen, "%s: %s%s", c->arg[0], *timeout <= 0 ? "Program timed out -- " : "", buf);
                                        total += n;
                                }
                        } while (n > 0 && Run.debug && total < 2048); // Limit the debug output (if the program will have endless output, such as 'yes' utility, we have to stop at some point to not spin here forever)
                        Process_free(&P); // Will kill the program if still running
                }
        }
Ejemplo n.º 8
0
Archivo: event.c Proyecto: kemadz/monit
/**
 * Add the partialy handled event to the global queue
 * @param E An event object
 */
static void _queueAdd(Event_T E) {
        ASSERT(E);
        ASSERT(E->flag != Handler_Succeeded);

        if (! file_checkQueueDirectory(Run.eventlist_dir)) {
                LogError("Aborting event - cannot access the directory %s\n", Run.eventlist_dir);
                return;
        }

        if (! file_checkQueueLimit(Run.eventlist_dir, Run.eventlist_slots)) {
                LogError("Aborting event - queue over quota\n");
                return;
        }

        /* compose the file name of actual timestamp and service name */
        char file_name[PATH_MAX];
        snprintf(file_name, PATH_MAX, "%s/%lld_%lx", Run.eventlist_dir, (long long)Time_now(), (long unsigned)E->source->name);

        LogInfo("Adding event to the queue file %s for later delivery\n", file_name);

        FILE *file = fopen(file_name, "w");
        if (! file) {
                LogError("Aborting event - cannot open the event file %s -- %s\n", file_name, STRERROR);
                return;
        }

        boolean_t rv;

        /* write event structure version */
        int version = EVENT_VERSION;
        if (! (rv = file_writeQueue(file, &version, sizeof(int))))
                goto error;

        /* write event structure */
        if (! (rv = file_writeQueue(file, E, sizeof(*E))))
                goto error;

        /* write source */
        if (! (rv = file_writeQueue(file, E->source->name, strlen(E->source->name) + 1)))
                goto error;

        /* write message */
        if (! (rv = file_writeQueue(file, E->message, E->message ? strlen(E->message) + 1 : 0)))
                goto error;

        /* write event action */
        Action_Type action = Event_get_action(E);
        if (! (rv = file_writeQueue(file, &action, sizeof(Action_Type))))
                goto error;

error:
        fclose(file);
        if (! rv) {
                LogError("Aborting event - unable to save event information to %s\n",  file_name);
                if (unlink(file_name) < 0)
                        LogError("Failed to remove event file '%s' -- %s\n", file_name, STRERROR);
        } else {
                if (! (Run.flags & Run_HandlerInit) && E->flag & Handler_Alert)
                        Run.handler_queue[Handler_Alert]++;
                if (! (Run.flags & Run_HandlerInit) && E->flag & Handler_Mmonit)
                        Run.handler_queue[Handler_Mmonit]++;
        }
}
Ejemplo n.º 9
0
int main(void) {

        setenv("TZ", "CET", 1);
        tzset();
        
        Bootstrap(); // Need to initialize library

        printf("============> Start Time Tests\n\n");


        printf("=> Test1: check string ouput\n");
        {
                char result[STRLEN];
                Time_string(1267441200, result); /* 01 Mar 2010 12:00:00 */
                printf("\tResult: unix time 1267441200 to localtime:\n\t %s\n", result);
                assert(Str_isEqual(result, "Mon, 01 Mar 2010 12:00:00"));
                Time_gmtstring(1267441200, result); /* 01 Mar 2010 12:00:00 GMT */
                printf("\tResult: unix time 1267441200 to UTC:\n\t %s\n", result);
                assert(Str_isEqual("Mon, 01 Mar 2010 11:00:00 GMT", result));
                Time_fmt(result, STRLEN, "%D %T", 1267441200);
                printf("\tResult: 1267441200 -> %s\n", result);
                assert(Str_isEqual(result, "03/01/10 12:00:00"));
                Time_fmt(result, STRLEN, "%D %z", 1267441200);
                printf("\tResult: 1267441200 -> %s\n", result);
#ifdef AIX
                assert(Str_startsWith(result, "03/01/10 CET"));
#else
                assert(Str_startsWith(result, "03/01/10 +"));
#endif
        }
        printf("=> Test1: OK\n\n");

        printf("=> Test2: check current time\n");
        {
                struct timeval tv;
                assert(!gettimeofday(&tv, NULL));
                assert(Time_now() == tv.tv_sec);
        }
        printf("=> Test2: OK\n\n");

        printf("=> Test3: sleep 1s\n");
        {
                time_t now;
                now = Time_now();
                Time_usleep(1000000);
                assert((now + 1) == Time_now());
        }
        printf("=> Test3: OK\n\n");

        printf("=> Test4: uptime\n");
        {
                time_t days = 668040;
                time_t hours = 63240;
                time_t min = 2040;
                char result[24];
                printf("\tResult: uptime days: %s\n", Time_uptime(days, result));
                assert(Str_isEqual(result, "7d, 17h, 34m"));
                printf("\tResult: uptime hours: %s\n", Time_uptime(hours, result));
                assert(Str_isEqual(result, "17h, 34m"));
                printf("\tResult: uptime min: %s\n", Time_uptime(min, result));
                assert(Str_isEqual(result, "34m"));
                printf("\tResult: uptime 0: %s\n", Time_uptime(0, result));
                assert(Str_isEqual(result, ""));
                assert(Time_uptime(0, NULL) == NULL);
        }
        printf("=> Test4: OK\n\n");

        printf("=> Test5: Time attributes\n");
        {
                char b[STRLEN];
                time_t time = 730251059; // Sun, 21. Feb 1993 00:30:59
                printf("\tResult: %s (winter time)\n", Time_string(time, b));
                assert(Time_seconds(time) == 59);
                assert(Time_minutes(time) == 30);
                assert(Time_hour(time) == 0);
                assert(Time_weekday(time) == 0);
                assert(Time_day(time) == 21);
                assert(Time_month(time) == 2);
                assert(Time_year(time) == 1993);
                time = 1253045894; // Tue, 15 Sep 2009 22:18:14 +0200
                printf("\tResult: %s (DTS/summer time)\n", Time_string(time, b));
                assert(Str_startsWith(b, "Tue, 15 Sep 2009 22:18:14"));
        }
        printf("=> Test5: OK\n\n");

        printf("=> Test6: Time_build\n");
        {
                time_t time = Time_build(2001, 1, 29, 12, 0, 0);
                assert(Time_seconds(time) == 0);
                assert(Time_minutes(time) == 0);
                assert(Time_hour(time) == 12);
                assert(Time_day(time) == 29);
                assert(Time_month(time) == 1);
                assert(Time_year(time) == 2001);
                // Verify assert on out of range
                TRY
                {
                        Time_build(1969, 1, 29, 12, 0, 0);
                        printf("Test failed\n");
                        exit(1);
                }
                CATCH (AssertException)
                END_TRY;
                TRY
                {
                        Time_build(1970, 0, 29, 12, 0, 0);
                        printf("Test failed\n");
                        exit(1);
                }
                CATCH (AssertException)
                END_TRY;
        }
        printf("=> Test6: OK\n\n");

        printf("=> Test7: Time_incron\n");
        {
                const char *exactmatch = "27 11 5 7 2";
                const char *matchall = "* * * * *";
                const char *invalid1 = "a bc d";
                const char *invalid2 = "* * * *  "; // Too few fields
                const char *invalid3 = "* * * * * * "; // Too many fields
                const char *range1 = "* 10-11 1-5 * 1-5";
                const char *rangeoutside = "1-10 9-10 1-5 * 1-5";
                const char *sequence = "* 10,11 1-3,5,6 * *";
                const char *sequenceoutside = "* 10,11,12 4,5,6 * 0,6";
                time_t time = Time_build(2011, 7, 5, 11, 27, 5);
                assert(Time_incron(exactmatch, time));
                assert(Time_incron(matchall, time));
                assert(! Time_incron(invalid1, time));
                assert(! Time_incron(invalid2, time));
                assert(! Time_incron(invalid3, time));
                assert(Time_incron(range1, time));
                assert(! Time_incron(rangeoutside, time));
                assert(Time_incron(sequence, time));
                assert(! Time_incron(sequenceoutside, time));
        }
        printf("=> Test7: OK\n\n");

        printf("=> Test8: Time_toDateTime\n");
        {
#if HAVE_STRUCT_TM_TM_GMTOFF
#define TM_GMTOFF tm_gmtoff
#else
#define TM_GMTOFF tm_wday
#endif
                struct tm t;
                // DateTime ISO-8601 format
                assert(Time_toDateTime("2013-12-14T09:38:08Z", &t));
                assert(t.tm_year == 2013);
                assert(t.tm_mon  == 11);
                assert(t.tm_mday == 14);
                assert(t.tm_hour == 9);
                assert(t.tm_min  == 38);
                assert(t.tm_sec  == 8);
                // Date
                assert(Time_toDateTime("2013-12-14", &t));
                assert(t.tm_year == 2013);
                assert(t.tm_mon  == 11);
                assert(t.tm_mday == 14);
                // Time
                assert(Time_toDateTime("09:38:08", &t));
                assert(t.tm_hour == 9);
                assert(t.tm_min  == 38);
                assert(t.tm_sec  == 8);
                // Compressed DateTime
                assert(Time_toDateTime(" 20131214093808", &t));
                assert(t.tm_year == 2013);
                assert(t.tm_mon  == 11);
                assert(t.tm_mday == 14);
                assert(t.tm_hour == 9);
                assert(t.tm_min  == 38);
                assert(t.tm_sec  == 8);
                // Compressed Date
                assert(Time_toDateTime(" 20131214 ", &t));
                assert(t.tm_year == 2013);
                assert(t.tm_mon  == 11);
                assert(t.tm_mday == 14);
                // Compressed Time
                assert(Time_toDateTime("093808", &t));
                assert(t.tm_hour == 9);
                assert(t.tm_min  == 38);
                assert(t.tm_sec  == 8);
                // Reverse DateTime
                assert(Time_toDateTime(" 09:38:08 2013-12-14", &t));
                assert(t.tm_year == 2013);
                assert(t.tm_mon  == 11);
                assert(t.tm_mday == 14);
                assert(t.tm_hour == 9);
                assert(t.tm_min  == 38);
                assert(t.tm_sec  == 8);
                // DateTime with timezone Zulu (UTC)
                assert(Time_toDateTime("The Battle of Stamford Bridge 1066-09-25 12:15:33+00:00", &t));
                assert(t.tm_year == 1066);
                assert(t.tm_mon  == 8);
                assert(t.tm_mday == 25);
                assert(t.tm_hour == 12);
                assert(t.tm_min  == 15);
                assert(t.tm_sec  == 33);
                assert(t.TM_GMTOFF == 0); // offset from UTC in seconds
                // Time with timezone
                assert(Time_toDateTime(" 09:38:08+01:45", &t));
                assert(t.tm_hour == 9);
                assert(t.tm_min  == 38);
                assert(t.tm_sec  == 8);
                assert(t.TM_GMTOFF == 6300);
                // Time with timezone PST compressed
                assert(Time_toDateTime("Pacific Time Zone 09:38:08 -0800 ", &t));
                assert(t.tm_hour == 9);
                assert(t.tm_min  == 38);
                assert(t.tm_sec  == 8);
                assert(t.TM_GMTOFF == -28800);
                // Date without time, tz should not be set
                assert(Time_toDateTime("2013-12-15-0800 ", &t));
                assert(t.TM_GMTOFF == 0);
                // Invalid date
                TRY {
                        Time_toDateTime("1901-123-45", &t);
                        printf("\t Test Failed\n");
                        exit(1);
                } CATCH (AssertException) {
                        // OK
                } ELSE {
                        printf("\t Test Failed with wrong exception\n");
                        exit(1);
                }
                END_TRY;
        }
        printf("=> Test8: OK\n\n");

        printf("=> Test9: Time_toTimestamp\n");
        {
                // Time, fraction of second is ignored. No timezone in string means UTC
                time_t t = Time_toTimestamp("2013-12-15 00:12:58.123456");
                assert(t == 1387066378);
                // TimeZone east
                t = Time_toTimestamp("Tokyo timezone: 2013-12-15 09:12:58+09:00");
                assert(t == 1387066378);
                // TimeZone west
                t = Time_toTimestamp("New York timezone: 2013-12-14 19:12:58-05:00");
                assert(t == 1387066378);
                // TimeZone east with hour and minute offset
                t = Time_toTimestamp("Nepal timezone: 2013-12-15 05:57:58+05:45");
                assert(t == 1387066378);
                // TimeZone Zulu
                t = Time_toTimestamp("Grenwich timezone: 2013-12-15 00:12:58Z");
                assert(t == 1387066378);
                // Compressed
                t = Time_toTimestamp("20131214191258-0500");
                assert(t == 1387066378);
                // Invalid timestamp string
                TRY {
                        Time_toTimestamp("1901-123-45 10:12:14");
                        // Should not come here
                        printf("\t Test Failed\n");
                        exit(1);
                } CATCH (AssertException) {
                        // OK
                } ELSE {
                        printf("\t Test Failed with wrong exception\n");
                        exit(1);
                }
                END_TRY;
        }
        printf("=> Test9: OK\n\n");

        printf("============> Time Tests: OK\n\n");

        return 0;
}
Ejemplo n.º 10
0
/**
 * Execute the given command. If the execution fails, the wait_start()
 * thread in control.c should notice this and send an alert message.
 * @param S A Service object
 * @param C A Command object
 * @param E An optional event object. May be NULL.
 */
void spawn(Service_T S, command_t C, Event_T E) {
        pid_t pid;
        sigset_t mask;
        sigset_t save;
        int stat_loc = 0;
        int exit_status;
        char date[42];

        ASSERT(S);
        ASSERT(C);

        if(access(C->arg[0], X_OK) != 0) {
                LogError("Error: Could not execute %s\n", C->arg[0]);
                return;
        }

        /*
         * Block SIGCHLD
         */
        sigemptyset(&mask);
        sigaddset(&mask, SIGCHLD);
        pthread_sigmask(SIG_BLOCK, &mask, &save);

        Time_string(Time_now(), date);
        pid = fork();
        if(pid < 0) {
                LogError("Cannot fork a new process -- %s\n", STRERROR);
                exit(1);
        }

        if(pid == 0) {

                /*
                 * Reset to the original umask so programs will inherit the
                 * same file creation mask monit was started with
                 */
                umask(Run.umask);

                /*
                 * Switch uid/gid if requested
                 */
                if(C->has_gid) {
                        if(0 != setgid(C->gid)) {
                                stat_loc |= setgid_ERROR;
                        }
                }
                if(C->has_uid) {
                        if(0 != setuid(C->uid)) {
                                stat_loc |= setuid_ERROR;
                        }
                }

                set_monit_environment(S, C, E, date);

                if(! Run.isdaemon) {
                        for(int i = 0; i < 3; i++)
                                if(close(i) == -1 || open("/dev/null", O_RDWR) != i)
                                        stat_loc |= redirect_ERROR;
                }

                Util_closeFds();

                setsid();

                pid = fork();
                if(pid < 0) {
                        stat_loc |= fork_ERROR;
                        _exit(stat_loc);
                }

                if(pid == 0) {
                        /*
                         * Reset all signals, so the spawned process is *not* created
                         * with any inherited SIG_BLOCKs
                         */
                        sigemptyset(&mask);
                        pthread_sigmask(SIG_SETMASK, &mask, NULL);
                        signal(SIGINT, SIG_DFL);
                        signal(SIGHUP, SIG_DFL);
                        signal(SIGTERM, SIG_DFL);
                        signal(SIGUSR1, SIG_DFL);
                        signal(SIGPIPE, SIG_DFL);

                        (void) execv(C->arg[0], C->arg);
                        _exit(errno);
                }

                /* Exit first child and return errors to parent */
                _exit(stat_loc);
        }

        /* Wait for first child - aka second parent, to exit */
        if(waitpid(pid, &stat_loc, 0) != pid) {
                LogError("Waitpid error\n");
        }

        exit_status = WEXITSTATUS(stat_loc);
        if (exit_status & setgid_ERROR)
                LogError("Failed to change gid to '%d' for '%s'\n", C->gid, C->arg[0]);
        if (exit_status & setuid_ERROR)
                LogError("Failed to change uid to '%d' for '%s'\n", C->uid, C->arg[0]);
        if (exit_status & fork_ERROR)
                LogError("Cannot fork a new process for '%s'\n", C->arg[0]);
        if (exit_status & redirect_ERROR)
                LogError("Cannot redirect IO to /dev/null for '%s'\n", C->arg[0]);

        /*
         * Restore the signal mask
         */
        pthread_sigmask(SIG_SETMASK, &save, NULL);

        /*
         * We do not need to wait for the second child since we forked twice,
         * the init system-process will wait for it. So we just return
         */

}
Ejemplo n.º 11
0
/**
 * Send mail messages via SMTP
 * @param mail A Mail object
 * @return FALSE if failed, TRUE if succeeded
 */
int sendmail(Mail_T mail) {

  int i;
  int rv;
  Mail_T m;
  SendMail_T S;
  char *b64 = NULL;
  char now[STRLEN];
  
  ASSERT(mail);
  
  S.socket = NULL;
  if(sigsetjmp(S.error, TRUE)) {
    rv = FALSE;
    goto exit;
  } else {
    rv = TRUE;
  }
  
  open_server(&S);
  
  Time_gmtstring(Time_now(), now);
  
  snprintf(S.localhost, sizeof(S.localhost), "%s", Run.mail_hostname ? Run.mail_hostname : Run.localhostname);
  
  do_status(&S);

  /* Use EHLO if TLS or Authentication is requested */
  if((S.ssl.use_ssl && S.ssl.version == SSL_VERSION_TLS) || S.username) {
    do_send(&S, "EHLO %s\r\n", S.localhost);
  } else {
    do_send(&S, "HELO %s\r\n", S.localhost);
  }
  do_status(&S);

  /* Switch to TLS now if configured */
  if(S.ssl.use_ssl && S.ssl.version == SSL_VERSION_TLS) {
    do_send(&S, "STARTTLS\r\n"); 
    do_status(&S);
    if(!socket_switch2ssl(S.socket, S.ssl)) {
      rv = FALSE;
      goto exit;
    }
    /* After starttls, send ehlo again: RFC 3207: 4.2 Result of the STARTTLS Command */
    do_send(&S, "EHLO %s\r\n", S.localhost);
    do_status(&S);
  }

  /* Authenticate if possible */
  if(S.username) {
    unsigned char buffer[STRLEN];
    int len;

    len = snprintf((char *)buffer, STRLEN, "%c%s%c%s", '\0', S.username, '\0', S.password?S.password:"");
    b64 = encode_base64(len, buffer);
    do_send(&S, "AUTH PLAIN %s\r\n", b64); 
    do_status(&S);
  }
  
  for(i = 0, m= mail; m; m= m->next, i++) { 
    do_send(&S, "MAIL FROM: <%s>\r\n", m->from);
    do_status(&S);
    do_send(&S, "RCPT TO: <%s>\r\n", m->to);
    do_status(&S);
    do_send(&S, "DATA\r\n");
    do_status(&S);
    do_send(&S, "From: %s\r\n", m->from);
    if (m->replyto)
      do_send(&S, "Reply-To: %s\r\n", m->replyto);
    do_send(&S, "To: %s\r\n", m->to);
    do_send(&S, "Subject: %s\r\n", m->subject);
    do_send(&S, "Date: %s\r\n", now);
    do_send(&S, "X-Mailer: %s %s\r\n", prog, VERSION);
    do_send(&S, "Mime-Version: 1.0\r\n");
    do_send(&S, "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n");
    do_send(&S, "Content-Transfer-Encoding: 8bit\r\n");
    do_send(&S, "Message-id: <%ld.%lu@%s>\r\n", time(NULL), random(), S.localhost);
    do_send(&S, "\r\n");
    do_send(&S, "%s\r\n", m->message);
    do_send(&S, ".\r\n");
    do_status(&S);
  }
  do_send(&S, "QUIT\r\n");
  do_status(&S);
  
exit:
  if(S.socket)
    socket_free(&S.socket);
  
  FREE(b64);

  return rv;
}
Ejemplo n.º 12
0
inline void LED_scan()
{
	// Latency measurement start
	Latency_start_time( ledLatencyResource );

	// Check for current change event
	if ( LED_currentEvent )
	{
		// Turn LEDs off in low power mode
		if ( LED_currentEvent < 150 )
		{
			LED_enable = 0;

			// Pause animations and clear display
			Pixel_setAnimationControl( AnimationControl_WipePause );
		}
		else
		{
			LED_enable = 1;

			// Start animations
			Pixel_setAnimationControl( AnimationControl_Forward );
		}

		LED_currentEvent = 0;
	}

	// Check if an LED_pause is set
	// Some ISSI operations need a clear buffer, but still have the chip running
	if ( LED_pause )
		goto led_finish_scan;

	// Check enable state
	if ( LED_enable )
	{
		// Disable Hardware shutdown of ISSI chips (pull high)
		GPIOB_PSOR |= (1<<16);
	}
	// Only write pages to I2C if chip is enabled (i.e. Hardware shutdown is disabled)
	else
	{
		// Enable hardware shutdown
		GPIOB_PCOR |= (1<<16);
		goto led_finish_scan;
	}

	// Only start if we haven't already
	// And if we've finished updating the buffers
	if ( Pixel_FrameState == FrameState_Sending )
		goto led_finish_scan;

	// Only send frame to ISSI chip if buffers are ready
	if ( Pixel_FrameState != FrameState_Ready )
		goto led_finish_scan;

	// Adjust frame rate (i.e. delay and do something else for a bit)
	Time duration = Time_duration( LED_timePrev );
	if ( duration.ms < LED_framerate )
		goto led_finish_scan;

	// FPS Display
	if ( LED_displayFPS )
	{
		// Show frame calculation
		dbug_msg("1frame/");
		printInt32( Time_ms( duration ) );
		print("ms + ");
		printInt32( duration.ticks );
		print(" ticks");

		// Check if we're not meeting frame rate
		if ( duration.ms > LED_framerate )
		{
			print(" - Could not meet framerate: ");
			printInt32( LED_framerate );
		}

		print( NL );
	}

	// Emulated brightness control
	// Lower brightness by LED_brightness
#if ISSI_Chip_31FL3731_define == 1
	uint8_t inverse_brightness = 0xFF - LED_brightness;
	for ( uint8_t chip = 0; chip < ISSI_Chips_define; chip++ )
	{
		for ( uint8_t ch = 0; ch < LED_BufferLength; ch++ )
		{
			// Don't modify is 0
			if ( LED_pageBuffer[ chip ].buffer[ ch ] == 0 )
			{
				LED_pageBuffer_brightness[ chip ].buffer[ ch ] = 0;
				continue;
			}

			LED_pageBuffer_brightness[ chip ].buffer[ ch ] =
				LED_pageBuffer[ chip ].buffer[ ch ] - inverse_brightness < 0
				? 0x0
				: LED_pageBuffer[ chip ].buffer[ ch ] - inverse_brightness;
		}
	}
#endif

	// Update frame start time
	LED_timePrev = Time_now();

	// Set the page of all the ISSI chips
	// This way we can easily link the buffers to send the brightnesses in the background
	for ( uint8_t ch = 0; ch < ISSI_Chips_define; ch++ )
	{
		uint8_t bus = LED_ChannelMapping[ ch ].bus;
		// Page Setup
		LED_setupPage(
			bus,
			LED_ChannelMapping[ ch ].addr,
			ISSI_LEDPwmPage
		);

#if ISSI_Chip_31FL3731_define == 1 || ISSI_Chip_31FL3732_define == 1
		// Reset LED enable mask
		// XXX At high speeds, the IS31FL3732 seems to have random bit flips
		//     To get around this, just re-set the enable mask before each send
		// XXX Might be sufficient to do this every N frames though
		while ( i2c_send( bus, (uint16_t*)&LED_ledEnableMask[ ch ], sizeof( LED_EnableBuffer ) / 2 ) == -1 )
			delay_us( ISSI_SendDelay );
#endif
	}

	// Send current set of buffers
	// Uses interrupts to send to all the ISSI chips
	// Pixel_FrameState will be updated when complete
	LED_chipSend = 0; // Start with chip 0
	LED_linkedSend();

led_finish_scan:
	// Latency measurement end
	Latency_end_time( ledLatencyResource );
}
Ejemplo n.º 13
0
// Setup
inline void LED_setup()
{
	// Register Scan CLI dictionary
	CLI_registerDictionary( ledCLIDict, ledCLIDictName );

	// Zero out FPS time
	LED_timePrev = Time_now();

	// Initialize framerate
	LED_framerate = ISSI_FrameRate_ms_define;

	// Global brightness setting
	LED_brightness = ISSI_Global_Brightness_define;

	// Initialize I2C
	i2c_setup();

	// Setup LED_pageBuffer addresses and brightness section
	LED_pageBuffer[0].i2c_addr = LED_MapCh1_Addr_define;
	LED_pageBuffer[0].reg_addr = ISSI_LEDPwmRegStart;
#if ISSI_Chips_define >= 2
	LED_pageBuffer[1].i2c_addr = LED_MapCh2_Addr_define;
	LED_pageBuffer[1].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 3
	LED_pageBuffer[2].i2c_addr = LED_MapCh3_Addr_define;
	LED_pageBuffer[2].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 4
	LED_pageBuffer[3].i2c_addr = LED_MapCh4_Addr_define;
	LED_pageBuffer[3].reg_addr = ISSI_LEDPwmRegStart;
#endif

	// Brightness emulation
#if ISSI_Chip_31FL3731_define
	// Setup LED_pageBuffer addresses and brightness section
	LED_pageBuffer_brightness[0].i2c_addr = LED_MapCh1_Addr_define;
	LED_pageBuffer_brightness[0].reg_addr = ISSI_LEDPwmRegStart;
#if ISSI_Chips_define >= 2
	LED_pageBuffer_brightness[1].i2c_addr = LED_MapCh2_Addr_define;
	LED_pageBuffer_brightness[1].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 3
	LED_pageBuffer_brightness[2].i2c_addr = LED_MapCh3_Addr_define;
	LED_pageBuffer_brightness[2].reg_addr = ISSI_LEDPwmRegStart;
#endif
#if ISSI_Chips_define >= 4
	LED_pageBuffer_brightness[3].i2c_addr = LED_MapCh4_Addr_define;
	LED_pageBuffer_brightness[3].reg_addr = ISSI_LEDPwmRegStart;
#endif
#endif

	// LED default setting
	LED_enable = ISSI_Enable_define;

	// Enable Hardware shutdown (pull low)
	GPIOB_PDDR |= (1<<16);
	PORTB_PCR16 = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
	GPIOB_PCOR |= (1<<16);

#if ISSI_Chip_31FL3733_define == 1
	// Reset I2C bus (pull high, then low)
	// NOTE: This GPIO may be shared with the debug LED
	GPIOA_PDDR |= (1<<5);
	PORTA_PCR5 = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
	GPIOC_PSOR |= (1<<5);
	delay_us(50);
	GPIOC_PCOR |= (1<<5);
#endif

	// Zero out Frame Registers
	// This needs to be done before disabling the hardware shutdown (or the leds will do undefined things)
	LED_zeroControlPages();

	// Disable Hardware shutdown of ISSI chips (pull high)
	if ( LED_enable )
	{
		GPIOB_PSOR |= (1<<16);
	}

	// Reset LED sequencing
	LED_reset();

	// Allocate latency resource
	ledLatencyResource = Latency_add_resource("ISSILed", LatencyOption_Ticks);
}
Ejemplo n.º 14
0
int main(void) {

        Bootstrap(); // Need to initialize library
        
        printf("============> Start Time Tests\n\n");
        
        printf("=> Test1: Parse String\n");
        {
                long r;
                char d1[STRLEN];
                char s[] = " Thu, 17 Oct 2002 19:10:01; ";
                char y[] = "Year: 2011 Day: 14 Month: June";
                printf("\tParsing a null date string: %ld\n", Time_parse(NULL));
                assert(Time_parse(NULL) == -1);
                r = Time_parse(s);
                printf("\tParsed datestring has value: %ld\n", r);
                assert(r == 1034874601);
                printf("\tWhich transform to the local date: %s\n", Time_fmt(d1, STRLEN, "%a, %d %b %Y %H:%M:%S %z", r));
                r = Time_parse(y);
                printf("\tSecond parsed datestring has value: %ld\n", r);
                assert(r == 1308002400);
                printf("\tWhich transform to the local date: %s\n", Time_fmt(d1, STRLEN, "%a, %d %b %Y %H:%M:%S %z", r));
        }
        printf("=> Test1: OK\n\n");
        
        printf("=> Test2: check string ouput\n");
        {
                char result[30];
                Time_string(1267441200, result); /* 01 Mar 2010 12:00:00 */
                printf("\tResult: local unix time 1267441200 to localtime:\n\t %s\n", result);
                assert(Str_isEqual(result, "Mon, 01 Mar 2010 12:00:00"));
                Time_gmtstring(1267441200, result); /* 01 Mar 2010 12:00:00 GMT */
                printf("\tResult: local unix time 1267441200 to UTC:\n\t %s\n", result);
                assert(Str_isEqual("Mon, 01 Mar 2010 11:00:00 GMT", result));
        }
        printf("=> Test2: OK\n\n");
        
        printf("=> Test3: check current time\n");
        {
                struct timeval tv;
                assert(!gettimeofday(&tv, NULL));
                assert(Time_now() == tv.tv_sec);
        }
        printf("=> Test3: OK\n\n");
        
        printf("=> Test4: convert CEST time_t to GMT\n");
        {
                assert(Time_gmt(1267441200) == 1267437600);
        }
        printf("=> Test4: OK\n\n");
        
        printf("=> Test5: sleep 1s\n");
        {
                time_t now;
                now = Time_now();
                Time_usleep(1000000);
                assert((now + 1) == Time_now());
        }
        printf("=> Test5: OK\n\n");
                
        printf("=> Test6: uptime\n");
        {
                time_t days = 668040;
                time_t hours = 63240;
                time_t min = 2040;
                char result[24];
                printf("\tResult: uptime days: %s\n", Time_uptime(days, result));
                assert(Str_isEqual(result, "7d, 17h, 34m"));
                printf("\tResult: uptime hours: %s\n", Time_uptime(hours, result));
                assert(Str_isEqual(result, "17h, 34m"));
                printf("\tResult: uptime min: %s\n", Time_uptime(min, result));
                assert(Str_isEqual(result, "34m"));
                printf("\tResult: uptime 0: %s\n", Time_uptime(0, result));
                assert(Str_isEqual(result, ""));
                assert(Time_uptime(0, NULL) == NULL);
        }
        printf("=> Test6: OK\n\n");
        
        printf("=> Test7: fmt\n");
        {
                
                char result[STRLEN];
                Time_fmt(result, STRLEN, "%D %T", 1267441200);
                printf("\tResult: 1267441200 -> %s\n", result);
                assert(Str_isEqual(result, "03/01/10 12:00:00"));
                Time_fmt(result, STRLEN, "%D", 1267441200);
                printf("\tResult: 1267441200 -> %s\n", result);
                assert(Str_startsWith(result, "03/01/10"));
        }
        printf("=> Test7: OK\n\n");
        
        printf("=> Test8: Time attributes\n");
        {
                char b[STRLEN];
                time_t time = 730251059; // Sun, 21. Feb 1993 00:30:59
                printf("\tResult: %s (winter time)\n", Time_string(time, b));
                assert(Time_seconds(time) == 59);
                assert(Time_minutes(time) == 30);
                assert(Time_hour(time) == 0);
                assert(Time_weekday(time) == 0);
                assert(Time_day(time) == 21);
                assert(Time_month(time) == 2);
                assert(Time_year(time) == 1993);
                time = 1253045894; // Tue, 15 Sep 2009 22:18:14 +0200
                printf("\tResult: %s (DTS/summer time)\n", Time_string(time, b));
                assert(Str_startsWith(b, "Tue, 15 Sep 2009 22:18:14"));
        }
        printf("=> Test8: OK\n\n");

        printf("=> Test9: Time_add\n");
        {
                char b[STRLEN];
                time_t t = 730251059; // Sun, 21. Feb 1993 00:30:59
                time_t time = Time_add(t, -1, -1, 8); // Wed, 29 Jan 1992 00:30:59
                printf("\tResult: %s\n", Time_string(time, b));
                assert(Time_seconds(time) == 59);
                assert(Time_minutes(time) == 30);
                assert(Time_hour(time) == 0);
                assert(Time_day(time) == 29);
                assert(Time_month(time) == 1);
                assert(Time_year(time) == 1992);
        }
        printf("=> Test9: OK\n\n");
        
        printf("=> Test10: Time_build\n");
        {
                time_t time = Time_build(2001, 1, 29, 12, 0, 0);
                assert(Time_seconds(time) == 0);
                assert(Time_minutes(time) == 0);
                assert(Time_hour(time) == 12);
                assert(Time_day(time) == 29);
                assert(Time_month(time) == 1);
                assert(Time_year(time) == 2001);
                // Verify assert on out of range
                TRY
                {
                        Time_build(1969, 1, 29, 12, 0, 0);
                        printf("Test failed\n");
                        exit(1);
                }
                CATCH (AssertException)
                END_TRY;
                TRY
                {
                        Time_build(1970, 0, 29, 12, 0, 0);
                        printf("Test failed\n");
                        exit(1);
                }
                CATCH (AssertException)
                END_TRY;
        }
        printf("=> Test10: OK\n\n");
        
        printf("=> Test11: Time_daysBetween\n");
        {
                time_t from = Time_build(2001, 1, 29, 0, 0, 0);
                time_t to = from;
                assert(Time_daysBetween(from, to) == 0);
                assert(Time_daysBetween(from, Time_build(2001, 1, 30, 0, 0, 0)) == 1);
                assert(Time_daysBetween(from, Time_build(2001, 1, 28, 0, 0, 0)) == 1);
                assert(Time_daysBetween(Time_build(2001, 1, 1, 0, 0, 0), Time_build(2002, 1, 1, 0, 0, 0)) == 365);
        }
        printf("=> Test11: OK\n\n");
        
        printf("=> Test12: Time_incron\n");
        {
                const char *exactmatch = "27 11 5 7 2";
                const char *matchall = "* * * * *";
                const char *invalid1 = "a bc d";
                const char *invalid2 = "* * * *  "; // Too few fields
                const char *invalid3 = "* * * * * * "; // Too many fields
                const char *range1 = "* 10-11 1-5 * 1-5";
                const char *rangeoutside = "1-10 9-10 1-5 * 1-5";
                const char *sequence = "* 10,11 1-3,5,6 * *";
                const char *sequenceoutside = "* 10,11,12 4,5,6 * 0,6";
                time_t time = Time_build(2011, 7, 5, 11, 27, 5);
                assert(Time_incron(exactmatch, time));
                assert(Time_incron(matchall, time));
                assert(! Time_incron(invalid1, time));
                assert(! Time_incron(invalid2, time));
                assert(! Time_incron(invalid3, time));
                assert(Time_incron(range1, time));
                assert(! Time_incron(rangeoutside, time));
                assert(Time_incron(sequence, time));
                assert(! Time_incron(sequenceoutside, time));
        }
        printf("=> Test12: OK\n\n");

        printf("============> Time Tests: OK\n\n");

        return 0;
}
Ejemplo n.º 15
0
Archivo: Ssl.c Proyecto: Nejuf/monit
static int _checkExpiration(T C, X509_STORE_CTX *ctx, X509 *certificate) {
        if (C->minimumValidDays) {
                // If we have warn-X-days-before-expire condition, check the certificate validity (already expired certificates are catched in preverify => we don't need to handle them here).
                int deltadays = 0;
#ifdef HAVE_ASN1_TIME_DIFF
                int deltaseconds;
                if (! ASN1_TIME_diff(&deltadays, &deltaseconds, NULL, X509_get_notAfter(certificate))) {
                        X509_STORE_CTX_set_error(ctx, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
                        snprintf(C->error, sizeof(C->error), "invalid time format (in certificate's notAfter field)");
                        return 0;
                }
#else
                ASN1_GENERALIZEDTIME *t = ASN1_TIME_to_generalizedtime(X509_get_notAfter(certificate), NULL);
                if (! t) {
                        X509_STORE_CTX_set_error(ctx, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
                        snprintf(C->error, sizeof(C->error), "invalid time format (in certificate's notAfter field)");
                        return 0;
                }
                TRY
                {
                        deltadays = (double)(Time_toTimestamp((const char *)t->data) - Time_now()) / 86400.;
                }
                ELSE
                {
                        X509_STORE_CTX_set_error(ctx, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
                        snprintf(C->error, sizeof(C->error), "invalid time format (in certificate's notAfter field) -- %s", t->data);
                }
                FINALLY
                {
                        ASN1_STRING_free(t);
                }
                END_TRY;
#endif
                if (deltadays < C->minimumValidDays) {
                        X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
                        snprintf(C->error, sizeof(C->error), "certificate expire in %d days matches check limit [valid > %d days]", deltadays, C->minimumValidDays);
                        return 0;
                }
        }