Пример #1
0
bool GlobalEvent::configureEvent(const pugi::xml_node& node)
{
	pugi::xml_attribute nameAttribute = node.attribute("name");
	if (!nameAttribute) {
		std::cout << "[Error - GlobalEvent::configureEvent] Missing name for a globalevent" << std::endl;
		return false;
	}

	m_name = nameAttribute.as_string();
	m_eventType = GLOBALEVENT_NONE;

	pugi::xml_attribute attr;
	if ((attr = node.attribute("time"))) {
		std::vector<int32_t> params = vectorAtoi(explodeString(attr.as_string(), ":"));
		if (params[0] < 0 || params[0] > 23) {
			std::cout << "[Error - GlobalEvent::configureEvent] Invalid hour \"" << attr.as_string() << "\" for globalevent with name: " << m_name << std::endl;
			return false;
		}

		m_interval |= params[0] << 16;
		int32_t hour = params[0];
		int32_t min = 0;
		int32_t sec = 0;

		if (params.size() > 1) {
			if (params[1] < 0 || params[1] > 59) {
				std::cout << "[Error - GlobalEvent::configureEvent] Invalid minute \"" << attr.as_string() << "\" for globalevent with name: " << m_name << std::endl;
				return false;
			}

			min = params[1];

			if (params.size() > 2) {
				if (params[2] < 0 || params[2] > 59) {
					std::cout << "[Error - GlobalEvent::configureEvent] Invalid second \"" << attr.as_string() << "\" for globalevent with name: " << m_name << std::endl;
					return false;
				}

				sec = params[2];
			}
		}

		time_t current_time = time(nullptr);
		tm* timeinfo = localtime(&current_time);
		timeinfo->tm_hour = hour;
		timeinfo->tm_min = min;
		timeinfo->tm_sec = sec;
		time_t difference = (time_t)difftime(mktime(timeinfo), current_time);

		if (difference < 0) {
			difference += 86400;
		}

		m_nextExecution = current_time + difference;
		m_eventType = GLOBALEVENT_TIMER;
	} else if ((attr = node.attribute("type"))) {
		std::string tmpStrValue = asLowerCaseString(attr.as_string());
		if (tmpStrValue == "startup" || tmpStrValue == "start" || tmpStrValue == "load") {
			m_eventType = GLOBALEVENT_STARTUP;
		} else if (tmpStrValue == "shutdown" || tmpStrValue == "quit" || tmpStrValue == "exit") {
			m_eventType = GLOBALEVENT_SHUTDOWN;
		} else if (tmpStrValue == "record" || tmpStrValue == "playersrecord") {
			m_eventType = GLOBALEVENT_RECORD;
		} else {
			std::cout << "[Error - GlobalEvent::configureEvent] No valid type \"" << attr.as_string() << "\" for globalevent with name " << m_name << std::endl;
			return false;
		}
	} else if ((attr = node.attribute("interval"))) {
		m_interval = std::max<int32_t>(SCHEDULER_MINTICKS, pugi::cast<int32_t>(attr.value()));
		m_nextExecution = OTSYS_TIME() + m_interval;
	} else {
		std::cout << "[Error - GlobalEvent::configureEvent] No interval for globalevent with name " << m_name << std::endl;
		return false;
	}
	return true;
}
Пример #2
0
/* Checks for the existence of PR_SHUTMSG_PATH.  deny and disc are
 * filled with the times to deny new connections and disconnect
 * existing ones.
 */
int check_shutmsg(const char *path, time_t *shut, time_t *deny, time_t *disc,
    char *msg, size_t msg_size) {
  FILE *fp;
  char *deny_str, *disc_str, *cp, buf[PR_TUNABLE_BUFFER_SIZE+1] = {'\0'};
  char hr[3] = {'\0'}, mn[3] = {'\0'};
  time_t now, shuttime = (time_t) 0;
  struct tm *tm;

  if (path == NULL) {
    errno = EINVAL;
    return -1;
  }

  fp = fopen(path, "r");
  if (fp != NULL) {
    struct stat st;

    if (fstat(fileno(fp), &st) == 0) {
      if (S_ISDIR(st.st_mode)) {
        fclose(fp);
        errno = EISDIR;
        return -1;
      }
    }

    cp = fgets(buf, sizeof(buf), fp);
    if (cp != NULL) {
      buf[sizeof(buf)-1] = '\0'; CHOP(cp);

      /* We use this to fill in dst, timezone, etc */
      time(&now);
      tm = pr_localtime(NULL, &now);
      if (tm == NULL) {
        fclose(fp);
        return 0;
      }

      tm->tm_year = atoi(safe_token(&cp)) - 1900;
      tm->tm_mon = atoi(safe_token(&cp)) - 1;
      tm->tm_mday = atoi(safe_token(&cp));
      tm->tm_hour = atoi(safe_token(&cp));
      tm->tm_min = atoi(safe_token(&cp));
      tm->tm_sec = atoi(safe_token(&cp));

      deny_str = safe_token(&cp);
      disc_str = safe_token(&cp);

      shuttime = mktime(tm);
      if (shuttime == (time_t) -1) {
        fclose(fp);
        return 0;
      }

      if (deny != NULL) {
        if (strlen(deny_str) == 4) {
          sstrncpy(hr, deny_str, sizeof(hr)); hr[2] = '\0'; deny_str += 2;
          sstrncpy(mn, deny_str, sizeof(mn)); mn[2] = '\0';

          *deny = shuttime - ((atoi(hr) * 3600) + (atoi(mn) * 60));

        } else {
          *deny = shuttime;
        }
      }

      if (disc != NULL) {
        if (strlen(disc_str) == 4) {
          sstrncpy(hr, disc_str, sizeof(hr)); hr[2] = '\0'; disc_str += 2;
          sstrncpy(mn, disc_str, sizeof(mn)); mn[2] = '\0';

          *disc = shuttime - ((atoi(hr) * 3600) + (atoi(mn) * 60));

        } else {
          *disc = shuttime;
        }
      }

      if (fgets(buf, sizeof(buf), fp) && msg) {
        buf[sizeof(buf)-1] = '\0';
	CHOP(buf);
        sstrncpy(msg, buf, msg_size-1);
      }
    }

    fclose(fp);
    if (shut != NULL) {
      *shut = shuttime;
    }

    return 1;
  }

  return -1;
}
Пример #3
0
/*#define TEST_TIMEPERIODS_A 1*/
static timerange *_get_matching_timerange(time_t test_time, const timeperiod *tperiod)
{
	daterange *temp_daterange = NULL;
	time_t start_time = (time_t)0L;
	time_t end_time = (time_t)0L;
	unsigned long days = 0L;
	int year = 0;
	int shift = 0;
	time_t midnight = (time_t)0L;
	struct tm *t, tm_s;
	int daterange_type = 0;
	int test_time_year = 0;
	int test_time_mon = 0;
	int test_time_wday = 0;

	if (tperiod == NULL)
		return NULL;

	t = localtime_r((time_t *)&test_time, &tm_s);
	test_time_year = t->tm_year;
	test_time_mon = t->tm_mon;
	test_time_wday = t->tm_wday;

	/* calculate the start of the day (midnight, 00:00 hours) when the specified test time occurs */
	t->tm_sec = 0;
	t->tm_min = 0;
	t->tm_hour = 0;
	midnight = mktime(t);

	/**** check exceptions first ****/
	for (daterange_type = 0; daterange_type < DATERANGE_TYPES; daterange_type++) {

		for (temp_daterange = tperiod->exceptions[daterange_type]; temp_daterange != NULL; temp_daterange = temp_daterange->next) {

#ifdef TEST_TIMEPERIODS_A
			printf("TYPE: %d\n", daterange_type);
			printf("TEST:     %lu = %s", (unsigned long)test_time, ctime(&test_time));
			printf("MIDNIGHT: %lu = %s", (unsigned long)midnight, ctime(&midnight));
#endif

			/* get the start time */
			switch (daterange_type) {
			case DATERANGE_CALENDAR_DATE:
				t->tm_sec = 0;
				t->tm_min = 0;
				t->tm_hour = 0;
				t->tm_wday = 0;
				t->tm_mday = temp_daterange->smday;
				t->tm_mon = temp_daterange->smon;
				t->tm_year = (temp_daterange->syear - 1900);
				t->tm_isdst = -1;
				start_time = mktime(t);
				break;
			case DATERANGE_MONTH_DATE:
				start_time = calculate_time_from_day_of_month(test_time_year, temp_daterange->smon, temp_daterange->smday);
				break;
			case DATERANGE_MONTH_DAY:
				start_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, temp_daterange->smday);
				break;
			case DATERANGE_MONTH_WEEK_DAY:
				start_time = calculate_time_from_weekday_of_month(test_time_year, temp_daterange->smon, temp_daterange->swday, temp_daterange->swday_offset);
				break;
			case DATERANGE_WEEK_DAY:
				start_time = calculate_time_from_weekday_of_month(test_time_year, test_time_mon, temp_daterange->swday, temp_daterange->swday_offset);
				break;
			default:
				continue;
				break;
			}

			/* get the end time */
			switch (daterange_type) {
			case DATERANGE_CALENDAR_DATE:
				t->tm_sec = 0;
				t->tm_min = 0;
				t->tm_hour = 0;
				t->tm_wday = 0;
				t->tm_mday = temp_daterange->emday;
				t->tm_mon = temp_daterange->emon;
				t->tm_year = (temp_daterange->eyear - 1900);
				t->tm_isdst = -1;
				end_time = mktime(t);
				break;
			case DATERANGE_MONTH_DATE:
				year = test_time_year;
				end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
				/* advance a year if necessary: august 2 - february 5 */
				if (end_time < start_time) {
					year++;
					end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, temp_daterange->emday);
				}
				break;
			case DATERANGE_MONTH_DAY:
				end_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, temp_daterange->emday);
				break;
			case DATERANGE_MONTH_WEEK_DAY:
				year = test_time_year;
				end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
				/* advance a year if necessary: thursday 2 august - monday 3 february */
				if (end_time < start_time) {
					year++;
					end_time = calculate_time_from_weekday_of_month(year, temp_daterange->emon, temp_daterange->ewday, temp_daterange->ewday_offset);
				}
				break;
			case DATERANGE_WEEK_DAY:
				end_time = calculate_time_from_weekday_of_month(test_time_year, test_time_mon, temp_daterange->ewday, temp_daterange->ewday_offset);
				break;
			default:
				continue;
				break;
			}

#ifdef TEST_TIMEPERIODS_A
			printf("START:    %lu = %s", (unsigned long)start_time, ctime(&start_time));
			printf("END:      %lu = %s", (unsigned long)end_time, ctime(&end_time));
#endif

			/* start date was bad, so skip this date range */
			if ((unsigned long)start_time == 0L)
				continue;

			/* end date was bad - see if we can handle the error */
			if ((unsigned long)end_time == 0L) {
				switch (daterange_type) {
				case DATERANGE_CALENDAR_DATE:
					continue;
					break;
				case DATERANGE_MONTH_DATE:
					/* end date can't be helped, so skip it */
					if (temp_daterange->emday < 0)
						continue;

					/* else end date slipped past end of month, so use last day of month as end date */
					/* use same year calculated above */
					end_time = calculate_time_from_day_of_month(year, temp_daterange->emon, -1);
					break;
				case DATERANGE_MONTH_DAY:
					/* end date can't be helped, so skip it */
					if (temp_daterange->emday < 0)
						continue;

					/* else end date slipped past end of month, so use last day of month as end date */
					end_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, -1);
					break;
				case DATERANGE_MONTH_WEEK_DAY:
					/* end date can't be helped, so skip it */
					if (temp_daterange->ewday_offset < 0)
						continue;

					/* else end date slipped past end of month, so use last day of month as end date */
					/* use same year calculated above */
					end_time = calculate_time_from_day_of_month(year, test_time_mon, -1);
					break;
				case DATERANGE_WEEK_DAY:
					/* end date can't be helped, so skip it */
					if (temp_daterange->ewday_offset < 0)
						continue;

					/* else end date slipped past end of month, so use last day of month as end date */
					end_time = calculate_time_from_day_of_month(test_time_year, test_time_mon, -1);
					break;
				default:
					continue;
					break;
				}
			}

			/* calculate skip date start (and end) */
			if (temp_daterange->skip_interval > 1) {

				/* skip start date must be before test time */
				if (start_time > test_time)
					continue;

				/* check if interval is across dlst change and gets the compensation */
				shift = get_dst_shift(&start_time, &midnight);

				/* how many days have passed between skip start date and test time? */
				days = (shift + (unsigned long)midnight - (unsigned long)start_time) / (3600 * 24);

				/* if test date doesn't fall on a skip interval day, bail out early */
				if ((days % temp_daterange->skip_interval) != 0)
					continue;

				/* use midnight of test date as start time */
				else
					start_time = midnight;

				/* if skipping range has no end, use test date as end */
				if ((daterange_type == DATERANGE_CALENDAR_DATE) && (is_daterange_single_day(temp_daterange) == TRUE))
					end_time = midnight;
			}

#ifdef TEST_TIMEPERIODS_A
			printf("NEW START:    %lu = %s", (unsigned long)start_time, ctime(&start_time));
			printf("NEW END:      %lu = %s", (unsigned long)end_time, ctime(&end_time));
			printf("%lu DAYS PASSED\n", days);
			printf("DLST SHIFT:   %i\n", shift);
#endif

			/* time falls inside the range of days
			 * end time < start_time when range covers end-of-$unit
			 * (fe. end-of-month) */

			if (((midnight >= start_time && (midnight <= end_time || start_time > end_time)) || (midnight <= end_time && start_time > end_time))) {
#ifdef TEST_TIMEPERIODS_A
				printf("(MATCH)\n");
#endif
				return temp_daterange->times;
			}
		}
	}

	return tperiod->days[test_time_wday];
}
Пример #4
0
static unsigned int calc_time(time_t endtime, int change, int alignment, int endofperiod)
{
	int daysinmonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	struct tm *tmbuf;
	time_t result, now;
	int dstsetting = -1;

again:
	tmbuf = localtime(&endtime);
	switch (alignment) {
		case ALIGN_HOUR: 
			tmbuf->tm_hour += change;
			if (endofperiod == END_END) {
				tmbuf->tm_min = tmbuf->tm_sec = 59;
			}
			else if (endofperiod == END_START) {
				tmbuf->tm_min = tmbuf->tm_sec = 0;
			}
			break;

		case ALIGN_DAY:
			tmbuf->tm_mday += change;
			if (endofperiod == END_END) {
				tmbuf->tm_hour = 23;
				tmbuf->tm_min = 59;
				tmbuf->tm_sec = 59;
			}
			else if (endofperiod == END_START) {
				tmbuf->tm_hour = tmbuf->tm_min = tmbuf->tm_sec = 0;
			}
			break;

		case ALIGN_MONTH:
			tmbuf->tm_mon += change;

			if (endofperiod == END_END) {
				/* Need to find the last day of the month */
				tmbuf->tm_mday = daysinmonth[tmbuf->tm_mon];
				if (tmbuf->tm_mon == 1) {
					if (((tmbuf->tm_year + 1900) % 4) == 0) {
						tmbuf->tm_mday = 29;
						if (((tmbuf->tm_year + 1900) % 100) == 0) tmbuf->tm_mday = 28;
						if (((tmbuf->tm_year + 1900) % 400) == 0) tmbuf->tm_mday = 29;
					}
				}

				tmbuf->tm_hour = 23;
				tmbuf->tm_min = 59;
				tmbuf->tm_sec = 59;
			}
			else if (endofperiod == END_START) {
				tmbuf->tm_mday = 1;
				tmbuf->tm_hour = tmbuf->tm_min = tmbuf->tm_sec = 0;
			}
			break;
	}
	tmbuf->tm_isdst = dstsetting;
	result = mktime(tmbuf);
	if ((dstsetting == -1) && (endofperiod == END_END) && (result < endtime)) {
		/* DST->normaltime switchover - redo with forced DST setting */
		dbgprintf("DST rollover with endtime/change/alignment/endodperiod = %u/%d/%d/%d\n",
			(unsigned int)endtime, change, alignment, endofperiod);
		dstsetting = 0;
		goto again;
	}

	/* Dont try to foresee the future */
	now = time(NULL);
	if (result > now) result = now;

	return (unsigned int)result;
}
Пример #5
0
int main(int argc, char *argv[])
{
	int ch, err;
	struct dnet_node *n = NULL;
	struct dnet_config cfg;
	char *remote_addr = NULL;
	int remote_port = -1;
	int remote_family = -1;
	char *logfile = default_log;
	int daemonize = 0;
	FILE *log = NULL;
	struct dnet_check_request r, *req, *req2;
	struct tm tm;
	char *file = NULL;
	int group_num = 0, *groups;
	struct dnet_session *s;

	memset(&cfg, 0, sizeof(struct dnet_config));

	cfg.wait_timeout = 60*60;
	check_logger.log_level = DNET_LOG_INFO;
	cfg.check_timeout = 60;

	memset(&tm, 0, sizeof(tm));

	memset(&r, 0, sizeof(r));

	while ((ch = getopt(argc, argv, "b:B:DN:f:n:t:u:U:MRm:w:l:dr:g:h")) != -1) {
		switch (ch) {
			case 'b':
				r.blob_start = atoi(optarg);
				break;
			case 'B':
				r.blob_num = atoi(optarg);
				break;
			case 'N':
				cfg.ns = optarg;
				cfg.nsize = strlen(optarg);
				break;
			case 'f':
				file = optarg;
				break;
			case 'n':
				r.thread_num = atoi(optarg);
				break;
			case 't':
				if (!strptime(optarg, "%F %T", &tm)) {
					fprintf(stderr, "Invalid timestamp string in -t\n");
					check_usage(argv[0]);
					return -EINVAL;
				}
				r.timestamp = mktime(&tm);
				break;
			case 'u':
				if (!strptime(optarg, "%F %T", &tm)) {
					fprintf(stderr, "Invalid timestamp string in -u\n");
					check_usage(argv[0]);
					return -EINVAL;
				}
				r.updatestamp_start = mktime(&tm);
				break;
			case 'U':
				if (!strptime(optarg, "%F %T", &tm)) {
					fprintf(stderr, "Invalid timestamp string in -U\n");
					check_usage(argv[0]);
					return -EINVAL;
				}
				r.updatestamp_stop = mktime(&tm);
				break;
			case 'D':
				r.flags |= DNET_CHECK_DRY_RUN;
				break;
			case 'M':
				r.flags |= DNET_CHECK_MERGE;
				break;
//			case 'F':
//				r.flags |= DNET_CHECK_FULL;
//				break;
			case 'R':
				r.flags |= DNET_CHECK_DELETE;
				break;
			case 'm':
				check_logger.log_level = strtoul(optarg, NULL, 0);
				break;
			case 'w':
				cfg.check_timeout = cfg.wait_timeout = atoi(optarg);
				break;
			case 'l':
				logfile = optarg;
				break;
			case 'd':
				daemonize = 1;
				break;
			case 'r':
				err = dnet_parse_addr(optarg, &remote_port, &remote_family);
				if (err)
					return err;
				remote_addr = optarg;
				break;
			case 'g':
				group_num = dnet_parse_groups(optarg, &groups);
				if (group_num <= 0)
					return -1;
				break;
			case 'h':
			default:
				check_usage(argv[0]);
				return -1;
		}
	}

	if (!remote_addr) {
		fprintf(stderr, "No remote node specified to route requests.\n");
		return -ENOENT;
	}

	log = fopen(logfile, "a");
	if (!log) {
		err = -errno;
		fprintf(stderr, "Failed to open log file %s: %s.\n", logfile, strerror(errno));
		return err;
	}

	if (daemonize) {
		if (logfile == default_log) {
			fprintf(stderr, "You should specify log file for daemon mode\n");
		} else {
			dnet_background();
		}
	}

	check_logger.log_private = log;
	check_logger.log = dnet_common_log;
	cfg.log = &check_logger;

	n = dnet_node_create(&cfg);
	if (!n)
		return -1;

	err = dnet_add_state(n, remote_addr, remote_port, remote_family, DNET_CFG_NO_ROUTE_LIST);
	if (err)
		return err;

	req = &r;
	if (file) {
		req = dnet_check_gen_request(n, &r, file);
		if (!req)
			return -EINVAL;
	}

	if (group_num > 0) {
		req2 = malloc(sizeof(struct dnet_check_request) + req->obj_num * sizeof(struct dnet_id) + group_num * sizeof(int));
		if (!req2)
			return -ENOMEM;

		memcpy(req2, req, sizeof(struct dnet_check_request) + req->obj_num * sizeof(struct dnet_id));
		memcpy((char *)req2 + sizeof(struct dnet_check_request) + req->obj_num * sizeof(struct dnet_id), groups,
				group_num * sizeof(int));
		req2->group_num = group_num;

		req = req2;
	}

	s = dnet_session_create(n);
	if (!s)
		return -ENOMEM;

	return dnet_request_check(s, req);
}
void IBN_TimeAccess (u8 nParamsGet_u8,u8 CMD_u8,u32 Param_u32,u8 *String_pu8)
{
	struct tm      tm_st;
//	struct tm      tm_st1;

	u8             Time_u8[30];
	time_t now;

	if (0 == nParamsGet_u8)
	{
		CI_LocalPrintf ("Time functions\r\n");
		CI_LocalPrintf ("\r\n");
		CI_LocalPrintf ("0   Show time\r\n");
		CI_LocalPrintf ("1   Set time - HH:MM:SS\r\n");
    CI_LocalPrintf ("2   Set date - DD:MM:YY\r\n");
    CI_LocalPrintf ("3   Set time in sec\r\n");
    CI_LocalPrintf ("4   Write time to flash\r\n");
    CI_LocalPrintf ("5   Read time from flash\r\n");
		CI_LocalPrintf ("\r\n");
		return;
	}
	switch (CMD_u8)
	{
		case 0 :
			time (&now);
			CI_LocalPrintf ("Time %ld\r\n",now);
			ctime_r (&now,(char*)Time_u8);
			CI_LocalPrintf ("Time %s\r\n",Time_u8);
			break;
		case 1 :
			if (NULL == String_pu8)
			{
				break;
			}
			time (&now);
			localtime_r (&now,&tm_st);
			tm_st.tm_hour = atoi ((char*)&String_pu8[0]);
			tm_st.tm_min  = atoi ((char*)&String_pu8[3]);
			tm_st.tm_sec  = atoi ((char*)&String_pu8[6]);
			CI_LocalPrintf ("Set time to %2d:%02d:%02d\r\n",tm_st.tm_hour,tm_st.tm_min,tm_st.tm_sec);
			now = mktime (&tm_st);
			set_time (now);
			break;

		case 2 :
			if (NULL == String_pu8)
			{
				break;
			}
			time (&now);
			localtime_r (&now,&tm_st);
			tm_st.tm_mday = atoi ((char*)&String_pu8[0]);
			tm_st.tm_mon  = atoi ((char*)&String_pu8[3]) - 1;
			tm_st.tm_year = atoi ((char*)&String_pu8[6]);
			if (50 > tm_st.tm_year)
			{
				tm_st.tm_year += 100;
			}
			CI_LocalPrintf ("Set date to %2d.%02d.%04d\r\n",tm_st.tm_mday,tm_st.tm_mon+1,1900+tm_st.tm_year);
			now = mktime (&tm_st);
			set_time (now);
			break;
    case 3 :
      CI_LocalPrintf ("Set Time %ld\r\n",Param_u32);
      set_time (Param_u32);
      time (&now);
      CI_LocalPrintf ("Time %ld\r\n",now);
      ctime_r (&now,(char*)Time_u8);
      CI_LocalPrintf ("Time %s\r\n",Time_u8);
      break;
    case 4 :
      time (&now);
      CI_LocalPrintf ("Write time %ld -",now);
      ctime_r (&now,(char*)Time_u8);
      CI_LocalPrintf ("%s\r\n",Time_u8);
      WriteDatetime (now);
      break;
    case 5 :
      ReadDatetime (&now);
      CI_LocalPrintf ("Stored time %ld - ",now);
      ctime_r (&now,(char*)Time_u8);
      CI_LocalPrintf ("Time %s\r\n",Time_u8);
      break;

	}
}
Пример #7
0
static void
stime_arg1(const char *arg, struct timeval *tvp)
{
	time_t now;
	struct tm *t;
	int yearset;
	char *p;
					/* Start with the current time. */
	now = tvp[0].tv_sec;
	if ((t = localtime(&now)) == NULL)
		err(1, "localtime");
					/* [[CC]YY]MMDDhhmm[.SS] */
	if ((p = strchr(arg, '.')) == NULL)
		t->tm_sec = 0;		/* Seconds defaults to 0. */
	else {
		if (strlen(p + 1) != 2)
			goto terr;
		*p++ = '\0';
		t->tm_sec = ATOI2(p);
	}

	yearset = 0;
	switch(strlen(arg)) {
	case 12:			/* CCYYMMDDhhmm */
		t->tm_year = ATOI2(arg);
		t->tm_year *= 100;
		yearset = 1;
		/* FALLTHROUGH */
	case 10:			/* YYMMDDhhmm */
		if (yearset) {
			yearset = ATOI2(arg);
			t->tm_year += yearset;
		} else {
			yearset = ATOI2(arg);
			if (yearset < 69)
				t->tm_year = yearset + 2000;
			else
				t->tm_year = yearset + 1900;
		}
		t->tm_year -= 1900;	/* Convert to UNIX time. */
		/* FALLTHROUGH */
	case 8:				/* MMDDhhmm */
		t->tm_mon = ATOI2(arg);
		--t->tm_mon;		/* Convert from 01-12 to 00-11 */
		t->tm_mday = ATOI2(arg);
		t->tm_hour = ATOI2(arg);
		t->tm_min = ATOI2(arg);
		break;
	default:
		goto terr;
	}

	t->tm_isdst = -1;		/* Figure out DST. */
	tvp[0].tv_sec = tvp[1].tv_sec = mktime(t);
	if (tvp[0].tv_sec == -1)
		goto terr;

	tvp[0].tv_usec = tvp[1].tv_usec = 0;
	return;

terr:
	errx(1, "out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]");
}
Пример #8
0
void parse_query(void)
{
	cgidata_t *cgidata, *cwalk;
	int sday = 0, smon = 0, syear = 0, eday = 0, emon = 0, eyear = 0;
	int smin = 0, shour = 0, ssec = 0, emin = -1, ehour = -1, esec = -1;
	int hostcount = 0, testcount = 0, alltests = 0;

	cgidata = cgi_request();
	if (cgidata == NULL) return;

	cwalk = cgidata;
	while (cwalk) {
		/*
		 * cwalk->name points to the name of the setting.
		 * cwalk->value points to the value (may be an empty string).
		 */

		if ((strcmp(cwalk->name, "hostpattern") == 0) && cwalk->value && strlen(cwalk->value)) {
			hostpattern = strdup(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "pagepattern") == 0) && cwalk->value && strlen(cwalk->value)) {
			pagepattern = strdup(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "ippattern") == 0)   && cwalk->value && strlen(cwalk->value)) {
			ippattern = strdup(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "classpattern") == 0)   && cwalk->value && strlen(cwalk->value)) {
			classpattern = strdup(cwalk->value);
		}
		else if (strcmp(cwalk->name, "DoReport") == 0) {
			action = A_GENERATE;
		}
		else if ((strcmp(cwalk->name, "hostname") == 0)   && cwalk->value && strlen(cwalk->value)) {
			if (!hosts) hosts = (char **) malloc(sizeof(char *));

			hosts = (char **)realloc(hosts, (hostcount+2) * sizeof(char *));
			hosts[hostcount] = strdup(cwalk->value); hostcount++;

			hosts[hostcount] = NULL;
		}
		else if ((strcmp(cwalk->name, "testname") == 0)   && cwalk->value && strlen(cwalk->value)) {
			if (!tests) tests = (char **) malloc(sizeof(char *));

			if (strcmp(cwalk->value, "ALL") == 0) {
				alltests = 1;
			}
			else {
				tests = (char **)realloc(tests, (testcount+2) * sizeof(char *));
				tests[testcount] = strdup(cwalk->value); testcount++;
			}

			tests[testcount] = NULL;
		}
		else if ((strcmp(cwalk->name, "start-day") == 0)   && cwalk->value && strlen(cwalk->value)) {
			sday = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "start-mon") == 0)   && cwalk->value && strlen(cwalk->value)) {
			smon = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "start-yr") == 0)   && cwalk->value && strlen(cwalk->value)) {
			syear = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "start-hour") == 0)   && cwalk->value && strlen(cwalk->value)) {
			shour = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "start-min") == 0)   && cwalk->value && strlen(cwalk->value)) {
			smin = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "start-sec") == 0)   && cwalk->value && strlen(cwalk->value)) {
			ssec = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "end-day") == 0)   && cwalk->value && strlen(cwalk->value)) {
			eday = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "end-mon") == 0)   && cwalk->value && strlen(cwalk->value)) {
			emon = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "end-yr") == 0)   && cwalk->value && strlen(cwalk->value)) {
			eyear = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "end-hour") == 0)   && cwalk->value && strlen(cwalk->value)) {
			ehour = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "end-min") == 0)   && cwalk->value && strlen(cwalk->value)) {
			emin = atoi(cwalk->value);
		}
		else if ((strcmp(cwalk->name, "end-sec") == 0)   && cwalk->value && strlen(cwalk->value)) {
			esec = atoi(cwalk->value);
		}

		cwalk = cwalk->next;
	}

	if (action == A_GENERATE) {
		struct tm tm;

		memset(&tm, 0, sizeof(tm));
		tm.tm_mday = sday;
		tm.tm_mon = smon - 1;
		tm.tm_year = syear - 1900;
		tm.tm_hour = shour;
		tm.tm_min  = smin;
		tm.tm_sec  = ssec;
		tm.tm_isdst = -1;
		starttime = mktime(&tm);

		if (ehour == -1) ehour = 23;
		if (emin  == -1) emin  = 59;
		if (esec  == -1) esec  = 59;
		memset(&tm, 0, sizeof(tm));
		tm.tm_mday = eday;
		tm.tm_mon = emon - 1;
		tm.tm_year = eyear - 1900;
		tm.tm_hour = ehour;
		tm.tm_min  = emin;
		tm.tm_sec  = esec;
		tm.tm_isdst = -1;
		endtime = mktime(&tm);
	}

	if (alltests) {
		if (tests) xfree(tests); testcount = 0;
		tests = (char **) calloc(8, sizeof(char *));

		if (hostcount == 1) {
			tests[testcount] = strdup("cpu"); testcount++;
			tests[testcount] = strdup("disk"); testcount++;
			tests[testcount] = strdup("memory"); testcount++;
			tests[testcount] = strdup("conn"); testcount++;
		}
		else {
			tests[testcount] = strdup("cpu"); testcount++;
			tests[testcount] = strdup("ram"); testcount++;
			tests[testcount] = strdup("mem"); testcount++;
			tests[testcount] = strdup("swap"); testcount++;
			tests[testcount] = strdup("conn-multi"); testcount++;
			tests[testcount] = strdup("netstat3"); testcount++;
			tests[testcount] = strdup("apache3"); testcount++;
		}

		tests[testcount] = NULL;
	}

	if (hostcount > 1) {
		int i;

		for (i = 0; (i < testcount); i++) {
			if (strcmp(tests[i], "conn") == 0) tests[i] = strdup("conn-multi");
		}
	}
}
time_t toTime( struct tm *tm )
{
    return mktime( tm );
}
Пример #10
0
int main(int argc, char *argv[])
{
    FILE *fd = NULL;
    Tstate prev_state;
    char filename[256];
    time_t rstart, rend, tnow;
    struct tm tm;
    char tag[32] = "default";
    char *home = getenv("HOME");

    // check for explicit tag name
    if (argc > 2 && argv[1][1] == 't') {
        strncpy(tag, argv[2], sizeof(tag));
        argc -= 2;
        argv += 2;
    }

    if (argc < 2) {
        printf("usage: %s", usage);
        exit(EXIT_SUCCESS);
    }

    snprintf(filename, sizeof(filename), "%s/.wtimed/%s", home, tag);

    if ((fd = fopen(filename, "r+")) == NULL) {
        if ((fd = fopen(filename, "w+")) == NULL) {
            fprintf(stderr, "Error while opening data file '%s'.\n", filename);
            exit(EXIT_FAILURE);
        }
    }

    if (argv[1][0] != '-') {
        fprintf(stderr, "Unknown parameter: %s\n", argv[1]);
    } else {
        if ((prev_state = cur_state(fd)) == UNKNOWN) {
            fprintf(stderr, "Corrupted data file '%s'.\n", filename);
            exit(EXIT_FAILURE);
        }
        switch (argv[1][1]) {
        case 'h':
            printf("usage: %s", usage);
            break;
        case 'a':
            if (prev_state == STARTED)
                fprintf(stderr, "We are allready counting.\n");
            else
                start_counting(fd);
            break;
        case 's':
            if (prev_state != STARTED)
                fprintf(stderr, "We are not counting.\n");
						else
                stop_counting(fd);
            break;
        case 'r':
            if (argc == 4) {    // end
                if (strptime(argv[3], "%d-%m-%Y", &tm) == NULL) {
                    fprintf(stderr, "Malformated end date\n");
                    exit(EXIT_FAILURE);
                }
                tm.tm_min = tm.tm_sec = 59;
                tm.tm_hour = 23;
                rend = mktime(&tm);
            } else {
                rend = time(NULL);
            }
            if (argc >= 3) {    // start
                if (strptime(argv[2], "%d-%m-%Y", &tm) == NULL) {
                    fprintf(stderr, "Malformated start date\n");
                    exit(EXIT_FAILURE);
                }
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
                rstart = mktime(&tm);
            } else {            // beginning of month
                tnow = time(NULL);
                tm = *localtime(&tnow);
                tm.tm_mday = 1;
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
                rstart = mktime(&tm);
            }
            if (rstart > rend) {
                fprintf(stderr, "Start date is further then end date.\n");
                exit(EXIT_FAILURE);
            }
            print_report(fd, rstart, rend);
            break;
        case 'c':
            if (prev_state != STARTED) {
                fprintf(stderr, "We are not counting.\n");
								exit(EXIT_FAILURE);
						} else
                print_elapsed(fd);
            break;
        default:
            fprintf(stderr, "Unknown parameter: %s\n", argv[1]);
            break;
        }
    }

    if (fd)
        fclose(fd);

    return (0);
}
Пример #11
0
_CODE_ACCESS struct tm *localtime(const time_t *timer)
{
    struct tm *local_tm_ptr = __TI_TLS_DATA_PTR(local_tm);
    time_t ltime  = timer ? *timer : 0;
 
    local_tm_ptr->tm_sec  = 0;
    local_tm_ptr->tm_min  = 0;
    local_tm_ptr->tm_hour = 0;
    local_tm_ptr->tm_mday = 1;
    local_tm_ptr->tm_mon  = 0;
    local_tm_ptr->tm_year = 0;
 
    if (timer == 0 || ltime == (time_t)-1) return local_tm_ptr;
 
#if INT_MAX <= 32767
    /*------------------------------------------------------------------*/
    /* MAKE SURE THE NUMBER OF SECONDS SINCE Jan 1, 1900 CAN BE         */
    /* REPRESENTED IN SIGNED INTS.                                      */
    /*------------------------------------------------------------------*/
    local_tm_ptr->tm_sec   =  ltime % SECS_IN_MIN;
    local_tm_ptr->tm_min   = (ltime / SECS_IN_MIN) % MINS_IN_HR;
    local_tm_ptr->tm_hour  = (ltime / SECS_IN_HR)  % HRS_IN_DAY;
 
    /*------------------------------------------------------------------*/
    /* CONVERT ltime TO NUMBER OF DAYS                                  */
    /*------------------------------------------------------------------*/
    ltime /= SECS_IN_DAY;
 
    /*------------------------------------------------------------------*/
    /* TO DETERMINE THE YEAR, INSTEAD OF DIVIDING BY 365, DO A SUBTRACT */
    /* LOOP THAT ACCOUNTS FOR LEAP YEARS.                               */
    /*------------------------------------------------------------------*/
    {
	int year = 0;
	while (ltime >= DAYS_IN_YR(year))
	{
	    ltime -= DAYS_IN_YR(year);
	    ++year;
	}
     
	local_tm_ptr->tm_year  = year;
	local_tm_ptr->tm_mday += ltime;
    }
 
#else
    /*------------------------------------------------------------------*/
    /* MAKE SURE THE NUMBER OF SECONDS SINCE Jan 1, 1900 CAN BE         */
    /* REPRESENTED IN SIGNED INTS.                                      */
    /*------------------------------------------------------------------*/
    if ((int)ltime < 0)
    {
	local_tm_ptr->tm_sec  = ltime % 60; 
	local_tm_ptr->tm_min  = ltime / 60; 
    }
    else local_tm_ptr->tm_sec = ltime;
#endif
 
    /*------------------------------------------------------------------*/
    /* MAKE VALUES IN local INTO A VALID TIME.                          */
    /*------------------------------------------------------------------*/
    mktime(local_tm_ptr);
    return local_tm_ptr;
}
Пример #12
0
static int
str_sec(char *str, time_t *tval)
{
	struct tm *lt;
	char *dot = NULL;

	lt = localtime(tval);
	if ((dot = strchr(str, '.')) != NULL) {
		/*
		 * seconds (.ss)
		 */
		*dot++ = '\0';
		if (strlen(dot) != 2)
			return(-1);
		if ((lt->tm_sec = ATOI2(dot)) > 61)
			return(-1);
	} else
		lt->tm_sec = 0;

	switch (strlen(str)) {
	case 10:
		/*
		 * year (yy)
		 * watch out for year 2000
		 */
		if ((lt->tm_year = ATOI2(str)) < 69)
			lt->tm_year += 100;
		str += 2;
		/* FALLTHROUGH */
	case 8:
		/*
		 * month (mm)
		 * watch out months are from 0 - 11 internally
		 */
		if ((lt->tm_mon = ATOI2(str)) > 12)
			return(-1);
		--lt->tm_mon;
		str += 2;
		/* FALLTHROUGH */
	case 6:
		/*
		 * day (dd)
		 */
		if ((lt->tm_mday = ATOI2(str)) > 31)
			return(-1);
		str += 2;
		/* FALLTHROUGH */
	case 4:
		/*
		 * hour (hh)
		 */
		if ((lt->tm_hour = ATOI2(str)) > 23)
			return(-1);
		str += 2;
		/* FALLTHROUGH */
	case 2:
		/*
		 * minute (mm)
		 */
		if ((lt->tm_min = ATOI2(str)) > 59)
			return(-1);
		break;
	default:
		return(-1);
	}
	/*
	 * convert broken-down time to GMT clock time seconds
	 */
	if ((*tval = mktime(lt)) == -1)
		return(-1);
	return(0);
}
Пример #13
0
//根据字符串日期计算得到1900开始的秒
int datetime2second(char *datetime,char *fmt,double *second)
{
	int i=0;
	int iYear=0;
	int iMon=0;
	int iDay=0;
	int iHour=0;
	int iMin=0;
	int iSec=0;
	int ch=0;
	time_t t;
	struct tm tm_t;
	char tmp[5]="";
	char szFmt[100]="";

	strncpy(szFmt, fmt, sizeof(szFmt) - 1);
	toupper_word(szFmt);
	if (strcmp(szFmt, "YYYYMMDDHHMMSS") == 0)
	{
		for (i=0;i<14;i++)
		{
			ch=datetime[i];
			if(!isdigit(ch))
				return E_DATE_FMT;
		}
		memcpy(tmp,datetime,4);
		iYear=atoi(tmp);
		memset(tmp,0,sizeof(tmp));
		memcpy(tmp,datetime+4,2);
		iMon=atoi(tmp);
		memcpy(tmp,datetime+6,2);
		iDay=atoi(tmp);
		memcpy(tmp,datetime+8,2);
		iHour=atoi(tmp);
		memcpy(tmp,datetime+10,2);
		iMin=atoi(tmp);
		memcpy(tmp,datetime+12,2);
		iSec=atoi(tmp);
	}
	else if (strcmp(szFmt, "YYYYMMDD") == 0)
	{
		for (i=0;i<8;i++)
		{
			ch=datetime[i];
			if(!isdigit(ch))
				return E_DATE_FMT;
		}
		memcpy(tmp,datetime,4);
		iYear=atoi(tmp);
		memset(tmp,0,sizeof(tmp));
		memcpy(tmp,datetime+4,2);
		iMon=atoi(tmp);
		memcpy(tmp,datetime+6,2);
		iDay=atoi(tmp);
		iHour=0;
		iMin=0;
		iSec=0;
	}
	memset(&tm_t,0,sizeof(struct tm));
	tm_t.tm_year=iYear-1900;
	tm_t.tm_mon=iMon-1;
	tm_t.tm_mday=iDay;
	tm_t.tm_hour=iHour;
	tm_t.tm_min=iMin;
	tm_t.tm_sec=iSec;
	t=mktime(&tm_t);
	*second=t;
	return 0;
}
Пример #14
0
int DiffTime(char time1[],char time2[],double* second)
{
	int i=0;
	int iYear=0;
	int iMon=0;
	int iDay=0;
	int iHour=0;
	int iMin=0;
	int iSec=0;
	char tmp[5]="";
	int ch=0;
	time_t t1;
	time_t t2;
	struct tm tm_t;

	memset(&t1,0,sizeof(time_t));
	memset(&t2,0,sizeof(time_t));
	memset(&tm_t,0,sizeof(struct tm));

	for (i=0;i<14;i++)
	{
		ch=time1[i];
		if(!isdigit(ch))
			return E_DATE_FMT;
	}
	for (i=0;i<14;i++)
	{
		ch=time2[i];
		if(!isdigit(ch))
			return E_DATE_FMT;
	}

	memcpy(tmp,time1,4);
	iYear=atoi(tmp);
	memset(tmp,0,sizeof(tmp));
	memcpy(tmp,time1+4,2);
	iMon=atoi(tmp);
	memcpy(tmp,time1+6,2);
	iDay=atoi(tmp);
	memcpy(tmp,time1+8,2);
	iHour=atoi(tmp);
	memcpy(tmp,time1+10,2);
	iMin=atoi(tmp);
	memcpy(tmp,time1+12,2);
	iSec=atoi(tmp);

	memset(&tm_t,0,sizeof(struct tm));
	tm_t.tm_year=iYear-1900;
	tm_t.tm_mon=iMon-1;
	tm_t.tm_mday=iDay;
	tm_t.tm_hour=iHour;
	tm_t.tm_min=iMin;
	tm_t.tm_sec=iSec;
	t1=mktime(&tm_t);
	memcpy(tmp,time2,4);
	iYear=atoi(tmp);
	memset(tmp,0,sizeof(tmp));
	memcpy(tmp,time2+4,2);
	iMon=atoi(tmp);
	memcpy(tmp,time2+6,2);
	iDay=atoi(tmp);
	memcpy(tmp,time2+8,2);
	iHour=atoi(tmp);
	memcpy(tmp,time2+10,2);
	iMin=atoi(tmp);
	memcpy(tmp,time2+12,2);
	iSec=atoi(tmp);

	memset(&tm_t,0,sizeof(struct tm));
	tm_t.tm_year=iYear-1900;
	tm_t.tm_mon=iMon-1;
	tm_t.tm_mday=iDay;
	tm_t.tm_hour=iHour;
	tm_t.tm_min=iMin;
	tm_t.tm_sec=iSec;
	t2=mktime(&tm_t);
	*second=difftime(t1,t2);
	return 0;
}
Пример #15
0
//parse NCSA format access.log entry into components
bool NCSALog::parseLine(std::string& line, LogEntry& entry) {

    std::vector<std::string> matches;
    ls_ncsa_entry_start.match(line, &matches);

    if(matches.size()!=5) {
        return 0;
    }

    //get details
    entry.vhost    = matches[0];
    entry.hostname = matches[1];
    //entry.username = matches[1];

    //parse timestamp
    struct tm time_str;

    int day, month, year, hour, minute, second;

    std::string request_str = matches[4];
    std::string datestr     = matches[3];

    matches.clear();
    ls_ncsa_entry_date.match(datestr, &matches);

    if(matches.size()!=8) {
        return 0;
    }

    day    = atoi(matches[0].c_str());
    month  = atoi(matches[1].c_str());
    year   = atoi(matches[2].c_str());
    hour   = atoi(matches[3].c_str());
    minute = atoi(matches[4].c_str());
    second = atoi(matches[5].c_str());

    if(month) {
        month--;
    } else {
        //parse non numeric month
        for(int i=0;i<12;i++) {
            if(strcmp(matches[1].c_str(), ls_ncsa_months[i])==0) {
                month=i;
                break;
            }
        }
    }

    //could not parse month (range 0-11 as used by mktime)
    if(month<0 || month>11) return 0;
    
    //convert zone to utc offset
    int tz_hour = atoi(matches[7].substr(0,2).c_str());
    int tz_min  = atoi(matches[7].substr(2,2).c_str());

    int tz_offset = tz_hour * 3600 + tz_min * 60;

    if(matches[6] == "-") {
        tz_offset = -tz_offset;
    }

    time_str.tm_year = year - 1900;
    time_str.tm_mon  = month;
    time_str.tm_mday = day;
    time_str.tm_hour = hour;
    time_str.tm_min = minute;
    time_str.tm_sec = second;
    time_str.tm_isdst = -1;

    entry.timestamp = mktime(&time_str);

    //apply utc offset
    entry.timestamp -= tz_offset;

    matches.clear();
    ls_ncsa_entry_request.match(request_str, &matches);

    if(matches.size() < 5) {
        return 0;
    }

//    entry.method    = matches[0];
    entry.path      = matches[1];
//    entry.protocol  = matches[2];

    entry.response_code = matches[3];
    entry.response_size = atol(matches[4].c_str());

    if(matches.size() > 5) {
        std::string agentstr = matches[5];
        matches.clear();
        ls_ncsa_entry_agent.match(agentstr, &matches);

        if(matches.size()==3) {
            entry.referrer   = matches[0];
            entry.user_agent = matches[1];
            entry.pid        = matches[2];
        }
    }

    entry.setSuccess();
    entry.setResponseColour();

    return entry.validate();
}
Пример #16
0
FILE *open_pos_file (NV_CHAR *path)
{
  FILE                   *fp;
  NV_INT32               i;
  POS_OUTPUT_T           pos;
  time_t                 tv_sec;
  NV_INT32               tv_nsec;
  struct tm              tm;
  static NV_INT32        tz_set = 0;


  NV_INT32 big_endian ();


  /*  Check the file name for following the naming convention as best we can.  */

  if (path[strlen (path) - 16] != '_' || path[strlen (path) - 9] != '_' || path[strlen (path) - 4] != '.')
    {
      fprintf (stderr, "\n\n\nFilename %s does not conform to standard\n", path);
      fprintf (stderr, "Please correct to match _YYMMDD_NNNN.pos or _YYMMDD_NNNN.out standard.\n\n\n");
      fflush (stderr);
      return (NULL);
    }


  sscanf (&path[strlen (path) - 15], "%02d%02d%02d", &year, &month, &day);


  /*  tm struct wants years since 1900!!!  */

  tm.tm_year = year + 100;
  tm.tm_mon = month - 1;
  tm.tm_mday = day;
  tm.tm_hour = 0.0;
  tm.tm_min = 0.0;
  tm.tm_sec = 0.0;
  tm.tm_isdst = -1;

  if (!tz_set)
    {
#ifdef NVWIN3X
  #ifdef __MINGW64__
      putenv("TZ=GMT");
      tzset();
  #else
      _putenv("TZ=GMT");
      _tzset();
  #endif
#else
      putenv("TZ=GMT");
      tzset();
#endif
      tz_set = 1;
    }


  /*  Get seconds from the epoch (01-01-1970) for the date in the filename. 
      This will also give us the day of the week for the GPS seconds of
      week calculation.  */

  tv_sec = mktime (&tm);
  tv_nsec = 0.0;


  /*  Subtract the number of days since Saturday midnight (Sunday morning) in seconds.  */

  tv_sec = tv_sec - (tm.tm_wday * 86400);
  start_week = tv_sec;


  /*  We have to assume that the file is little endian since there is no
      header and no field that we can use to deduce what it is.  */

  swap = (NV_BOOL) big_endian ();


  if ((fp = fopen (path, "rb")) == NULL)
    {
      return ((FILE *) NULL);
    }
  else
    {
      fread (&pos, sizeof (POS_OUTPUT_T), 1, fp);
      if (swap) swap_pos (&pos);
      start_timestamp = (NV_INT64) (((NV_FLOAT64) start_week + pos.gps_time) * 1000000.0);
      start_record = 0;
      start_gps_time = pos.gps_time;


      i = fseek (fp, -sizeof (POS_OUTPUT_T), SEEK_END);

      fread (&pos, sizeof (POS_OUTPUT_T), 1, fp);
      if (swap) swap_pos (&pos);
      end_timestamp = (NV_INT64) (((NV_FLOAT64) start_week + pos.gps_time) * 1000000.0);


      /*  Check for crossing midnight at end of GPS week (stupid f***ing Applanix bozos).  */

      if (end_timestamp < start_timestamp)
        {
          midnight = NVTrue;
          end_timestamp += ((NV_INT64) WEEK_OFFSET * 1000000);
        }


      end_record = ftell (fp) / sizeof (POS_OUTPUT_T);

      fseek (fp, 0, SEEK_SET);
    }

  return (fp);
}
Пример #17
0
int main(int argc, char *argv[])
{
    extern char *optarg;
    int opt;
    char *alt_config = NULL, *port = "119";
    const char *peer = NULL, *server = "localhost", *wildmat = "*";
    char *authname = NULL, *password = NULL;
    int psock = -1, ssock = -1;
    struct protstream *pin, *pout, *sin, *sout;
    char buf[BUFFERSIZE];
    char sfile[1024] = "";
    int fd = -1, i, n, offered, rejected, accepted, failed;
    time_t stamp;
    char **resp = NULL;
    int newnews = 1;
    char *datefmt = "%y%m%d %H%M%S";

    if (geteuid() == 0) fatal("must run as the Cyrus user", EC_USAGE);

    while ((opt = getopt(argc, argv, "C:s:w:f:a:p:ny")) != EOF) {
	switch (opt) {
	case 'C': /* alt config file */
	    alt_config = optarg;
	    break;

	case 's': /* server */
	    server = xstrdup(optarg);
	    if ((port = strchr(server, ':')))
		*port++ = '\0';
	    else
		port = "119";
	    break;

	case 'w': /* wildmat */
	    wildmat = optarg;
	    break;

	case 'f': /* timestamp file */
	    snprintf(sfile, sizeof(sfile), optarg);
	    break;

	case 'a': /* authname */
	    authname = optarg;
	    break;

	case 'p': /* password */
	    password = optarg;
	    break;

	case 'n': /* no newnews */
	    newnews = 0;
	    break;

	case 'y': /* newsserver is y2k compliant */
	    datefmt = "%Y%m%d %H%M%S";
	    break;

	default:
	    usage();
	    /* NOTREACHED */
	}
    }
    if (argc - optind < 1) {
	usage();
	/* NOTREACHED */
    }

    peer = argv[optind++];

    cyrus_init(alt_config, "fetchnews", 0);

    /* connect to the peer */
    /* xxx configurable port number? */
    if ((psock = init_net(peer, "119", &pin, &pout)) < 0) {
	fprintf(stderr, "connection to %s failed\n", peer);
	cyrus_done();
	exit(-1);
    }

    /* read the initial greeting */
    if (!prot_fgets(buf, sizeof(buf), pin) || strncmp("20", buf, 2)) {
	syslog(LOG_ERR, "peer not available");
	goto quit;
    }

    if (authname) {
	/* authenticate to peer */
	/* XXX this should be modified to support SASL and STARTTLS */

	prot_printf(pout, "AUTHINFO USER %s\r\n", authname);
	if (!prot_fgets(buf, sizeof(buf), pin)) {
	    syslog(LOG_ERR, "AUTHINFO USER terminated abnormally");
	    goto quit;
	}
	else if (!strncmp("381", buf, 3)) {
	    /* password required */
	    if (!password)
		password = getpass("Please enter the password: "******"failed to get password\n");
		goto quit;
	    }

	    prot_printf(pout, "AUTHINFO PASS %s\r\n", password);
	    if (!prot_fgets(buf, sizeof(buf), pin)) {
		syslog(LOG_ERR, "AUTHINFO PASS terminated abnormally");
		goto quit;
	    }
	}

	if (strncmp("281", buf, 3)) {
	    /* auth failed */
	    goto quit;
	}
    }

    /* change to reader mode - not always necessary, so ignore result */
    prot_printf(pout, "MODE READER\r\n");
    prot_fgets(buf, sizeof(buf), pin);

    if (newnews) {
	struct tm ctime, *ptime;

	/* fetch the server's current time */
	prot_printf(pout, "DATE\r\n");

	if (!prot_fgets(buf, sizeof(buf), pin) || strncmp("111 ", buf, 4)) {
	    syslog(LOG_ERR, "error fetching DATE");
	    goto quit;
	}

	/* parse and normalize the server time */
	memset(&ctime, 0, sizeof(struct tm));
	sscanf(buf+4, "%4d%02d%02d%02d%02d%02d",
	       &ctime.tm_year, &ctime.tm_mon, &ctime.tm_mday,
	       &ctime.tm_hour, &ctime.tm_min, &ctime.tm_sec);
	ctime.tm_year -= 1900;
	ctime.tm_mon--;
	ctime.tm_isdst = -1;

	/* read the previous timestamp */
	if (!sfile[0]) {
	    char oldfile[1024];

	    snprintf(sfile, sizeof(sfile), "%s/fetchnews.stamp", config_dir);

	    /* upgrade from the old stamp filename to the new */
	    snprintf(oldfile, sizeof(oldfile), "%s/newsstamp", config_dir);
	    rename(oldfile, sfile);
	}

	if ((fd = open(sfile, O_RDWR | O_CREAT, 0644)) == -1) {
	    syslog(LOG_ERR, "can not open %s", sfile);
	    goto quit;
	}
	if (lock_nonblocking(fd) == -1) {
	    syslog(LOG_ERR, "can not lock %s: %m", sfile);
	    goto quit;
	}

	if (read(fd, &stamp, sizeof(stamp)) < sizeof(stamp)) {
	    /* XXX do something better here */
	    stamp = 0;
	}

	/* ask for new articles */
	if (stamp) stamp -= 180; /* adjust back 3 minutes */
	ptime = gmtime(&stamp);
	ptime->tm_isdst = -1;
	strftime(buf, sizeof(buf), datefmt, ptime);
	prot_printf(pout, "NEWNEWS %s %s GMT\r\n", wildmat, buf);
	
	if (!prot_fgets(buf, sizeof(buf), pin) || strncmp("230", buf, 3)) {
	    syslog(LOG_ERR, "peer doesn't support NEWNEWS");
	    newnews = 0;
	}

	/* prepare server's current time as new timestamp */
	stamp = mktime(&ctime);
	/* adjust for local timezone

	   XXX  We need to do this because we use gmtime() above.
	   We can't change this, otherwise we'd be incompatible
	   with an old localtime timestamp.
	*/
	stamp += gmtoff_of(&ctime, stamp);
    }

    if (!newnews) {
	prot_printf(pout, "LIST ACTIVE %s\r\n", wildmat);
	
	if (!prot_fgets(buf, sizeof(buf), pin) || strncmp("215", buf, 3)) {
	    syslog(LOG_ERR, "peer doesn't support LIST ACTIVE");
	    goto quit;
	}
    }

    /* process the NEWNEWS/LIST ACTIVE list */
    n = 0;
    while (prot_fgets(buf, sizeof(buf), pin)) {
	if (buf[0] == '.') break;

	if (!(n % RESP_GROW)) { /* time to alloc more */
	    resp = (char **)
		xrealloc(resp, (n + RESP_GROW) * sizeof(char *));
	}
	resp[n++] = xstrdup(buf);
    }
    if (buf[0] != '.') {
	syslog(LOG_ERR, "%s terminated abnormally",
	       newnews ? "NEWNEWS" : "LIST ACTIVE");
	goto quit;
    }

    if (!n) {
	/* nothing matches our wildmat */
	goto quit;
    }

    /* connect to the server */
    if ((ssock = init_net(server, port, &sin, &sout)) < 0) {
	fprintf(stderr, "connection to %s failed\n", server);
	goto quit;
    }

    /* read the initial greeting */
    if (!prot_fgets(buf, sizeof(buf), sin) || strncmp("20", buf, 2)) {
	syslog(LOG_ERR, "server not available");
	goto quit;
    }

    /* fetch and store articles */
    offered = rejected = accepted = failed = 0;
    if (newnews) {
	/* response is a list of msgids */
	for (i = 0; i < n; i++) {
	    /* find the end of the msgid */
	    *(strrchr(resp[i], '>') + 1) = '\0';

	    offered++;
	    if (fetch(resp[i], 1, pin, pout, sin, sout,
		      &rejected, &accepted, &failed)) {
		goto quit;
	    }
	}

	/* write the current timestamp */
	lseek(fd, 0, SEEK_SET);
	if (write(fd, &stamp, sizeof(stamp)) < sizeof(stamp))
	    syslog(LOG_ERR, "error writing %s", sfile);
	lock_unlock(fd);
	close(fd);
    }
    else {
	char group[BUFFERSIZE], msgid[BUFFERSIZE], lastbuf[50];
	const char *data;
	unsigned long low, high, last, cur;
	int start;
	int datalen;
	struct txn *tid = NULL;

	newsrc_init(NULL, 0);

	/*
	 * response is a list of groups.
	 * select each group, and STAT each article we haven't seen yet.
	 */
	for (i = 0; i < n; i++) {
	    /* parse the LIST ACTIVE response */
	    sscanf(resp[i], "%s %lu %lu", group, &high, &low);

	    last = 0;
	    if (!DB->fetchlock(newsrc_db, group, strlen(group),
			       &data, &datalen, &tid)) {
		last = strtoul(data, NULL, 10);
	    }
	    if (high <= last) continue;

	    /* select the group */
	    prot_printf(pout, "GROUP %s\r\n", group);
	    if (!prot_fgets(buf, sizeof(buf), pin)) {
		syslog(LOG_ERR, "GROUP terminated abnormally");
		continue;
	    }
	    else if (strncmp("211", buf, 3)) break;

	    for (start = 1, cur = low > last ? low : ++last;; cur++) {
		if (start) {
		    /* STAT the first article we haven't seen */
		    prot_printf(pout, "STAT %lu\r\n", cur);
		} else {
		    /* continue with the NEXT article */
		    prot_printf(pout, "NEXT\r\n");
		}

		if (!prot_fgets(buf, sizeof(buf), pin)) {
		    syslog(LOG_ERR, "STAT/NEXT terminated abnormally");
		    cur--;
		    break;
		}
		if (!strncmp("223", buf, 3)) {
		    /* parse the STAT/NEXT response */
		    sscanf(buf, "223 %lu %s", &cur, msgid);

		    /* find the end of the msgid */
		    *(strrchr(msgid, '>') + 1) = '\0';

		    if (fetch(msgid, 0, pin, pout, sin, sout,
			      &rejected, &accepted, &failed)) {
			cur--;
			break;
		    }
		    offered++;
		    start = 0;
		}

		/* have we reached the highwater mark? */
		if (cur >= high) break;
	    }

	    snprintf(lastbuf, sizeof(lastbuf), "%lu", cur);
	    DB->store(newsrc_db, group, strlen(group),
		      lastbuf, strlen(lastbuf)+1, &tid);
	}

	if (tid) DB->commit(newsrc_db, tid);
	newsrc_done();
    }

    syslog(LOG_NOTICE,
	   "fetchnews: %s offered %d; %s rejected %d, accepted %d, failed %d",
	   peer, offered, server, rejected, accepted, failed);

  quit:
    if (psock >= 0) {
	prot_printf(pout, "QUIT\r\n");
	prot_flush(pout);

	/* Flush the incoming buffer */
	prot_NONBLOCK(pin);
	prot_fill(pin);

	/* close/free socket & prot layer */
	close(psock);
    
	prot_free(pin);
	prot_free(pout);
    }

    if (ssock >= 0) {
	prot_printf(sout, "QUIT\r\n");
	prot_flush(sout);

	/* Flush the incoming buffer */
	prot_NONBLOCK(sin);
	prot_fill(sin);

	/* close/free socket & prot layer */
	close(psock);
    
	prot_free(sin);
	prot_free(sout);
    }

    cyrus_done();
    
    return 0;
}
NS_IMETHODIMP nsScriptableDateFormat::FormatDateTime(
                            const PRUnichar *aLocale, 
                            nsDateFormatSelector dateFormatSelector, 
                            nsTimeFormatSelector timeFormatSelector, 
                            PRInt32 year, 
                            PRInt32 month, 
                            PRInt32 day, 
                            PRInt32 hour, 
                            PRInt32 minute, 
                            PRInt32 second, 
                            PRUnichar **dateTimeString)
{
  // We can't have a valid date with the year, month or day
  // being lower than 1.
  if (year < 1 || month < 1 || day < 1)
    return NS_ERROR_INVALID_ARG;

  nsresult rv;
  nsAutoString localeName(aLocale);
  *dateTimeString = nsnull;

  nsCOMPtr<nsILocale> locale;
  // re-initialise locale pointer only if the locale was given explicitly
  if (!localeName.IsEmpty()) {
    // get locale service
    nsCOMPtr<nsILocaleService> localeService(do_GetService(kLocaleServiceCID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    // get locale
    rv = localeService->NewLocale(localeName, getter_AddRefs(locale));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  nsCOMPtr<nsIDateTimeFormat> dateTimeFormat(do_CreateInstance(kDateTimeFormatCID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  tm tmTime;
  time_t timetTime;

  memset(&tmTime, 0, sizeof(tmTime));
  tmTime.tm_year = year - 1900;
  tmTime.tm_mon = month - 1;
  tmTime.tm_mday = day;
  tmTime.tm_hour = hour;
  tmTime.tm_min = minute;
  tmTime.tm_sec = second;
  tmTime.tm_yday = tmTime.tm_wday = 0;
  tmTime.tm_isdst = -1;
  timetTime = mktime(&tmTime);

  if ((time_t)-1 != timetTime) {
    rv = dateTimeFormat->FormatTime(locale, dateFormatSelector, timeFormatSelector, 
                                     timetTime, mStringOut);
  }
  else {
    // if mktime fails (e.g. year <= 1970), then try NSPR.
    PRTime prtime;
    char string[32];
    sprintf(string, "%.2d/%.2d/%d %.2d:%.2d:%.2d", month, day, year, hour, minute, second);
    if (PR_SUCCESS != PR_ParseTimeString(string, PR_FALSE, &prtime))
      return NS_ERROR_INVALID_ARG;

    rv = dateTimeFormat->FormatPRTime(locale, dateFormatSelector, timeFormatSelector, 
                                      prtime, mStringOut);
  }
  if (NS_SUCCEEDED(rv))
    *dateTimeString = ToNewUnicode(mStringOut);

  return rv;
}
Пример #19
0
Файл: date.c Проект: 86joca/git
/* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
   (i.e. English) day/month names, and it doesn't work correctly with %z. */
int parse_date_basic(const char *date, unsigned long *timestamp, int *offset)
{
	struct tm tm;
	int tm_gmt;
	unsigned long dummy_timestamp;
	int dummy_offset;

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

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

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

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

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

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

		date += match;
	}

	/* do not use mktime(), which uses local timezone, here */
	*timestamp = tm_to_time_t(&tm);
	if (*timestamp == -1)
		return -1;

	if (*offset == -1) {
		time_t temp_time;

		/* gmtime_r() in match_digit() may have clobbered it */
		tm.tm_isdst = -1;
		temp_time = mktime(&tm);
		if ((time_t)*timestamp > temp_time) {
			*offset = ((time_t)*timestamp - temp_time) / 60;
		} else {
			*offset = -(int)((temp_time - (time_t)*timestamp) / 60);
		}
	}

	if (!tm_gmt)
		*timestamp -= *offset * 60;
	return 0; /* success */
}
Пример #20
0
static int
doit(gzFile *infp)
{
	int		i, skip = 0;
	time_t		curtime, ll_time;
	char		*user, node[TBDB_FLEN_NODEID * 2], prog[128];
	char		buf[BUFSIZ], *bp, uid_idx[128], tmp[BUFSIZ];
	struct tm	tm;
	MYSQL_RES	*dbres;
	MYSQL_ROW	dbrow;
	
	while (1) {
		if (gzgets(infp, buf, BUFSIZ) == NULL)
			break;

		/*
		 * If the line does not contain a newline, then we skip it
		 * and try to sync up again. We consider ourselves synced
		 * when the buffer contains a newline in it.
		 */
		if (buf[strlen(buf) - 1] != '\n') {
			skip = 1;
			continue;
		}
		if (skip) {
			skip = 0;
			continue;
 		}

		/*
		 * Thank dog for strptime! Convert the syslog timestamp
		 * into a tm, and then into regular unix time.
		 */
		time(&curtime);
		localtime_r(&curtime, &tm);
		if ((bp = strptime(buf, "%b %e %T", &tm)) == NULL) {
			continue;
		}
		ll_time = mktime(&tm);

		/*
		 * If the constructed time is in the future, then we have
		 * year off by one (cause we are possibly looking at files
		 * created in the previous year). Set the year back by one,
		 * and redo.
		 */
		if (ll_time > curtime) {
			tm.tm_year--;
			ll_time = mktime(&tm);
		}

		/*
		 * Scanf the next part, which looks like:
		 *
		 *	node progname[pid]:
		 *
		 * Ensure we match the proper number of items.
		 */
		bzero(node, sizeof(node));
		if ((sscanf(bp, "%s %s:", node, prog) != 2))
			continue;

		/*
		 * Only sshd matters to us.
		 */
		if (strncmp(prog, SSHD, strlen(SSHD)))
			continue;

		/*
		 * Okay, these kinds of strings matter.
		 *
		 *	FreeBSD:	"Accepted rsa for USER" 
		 *	Linux 6.2:	"log: RSA authentication for USER"
		 *	Linux 7.1:	"session opened for user USER"
		 *      (several ssh2): "Accepted publickey for USER"
		 *      (several ssh2): "Accepted password for USER"
		 *      (several ssh2): "Accepted keyboard-interactive for USER"
		 */
#define L1	"Accepted rsa for "
#define L2	"session opened for user "
#define L3	"log: RSA authentication for "
#define L4	"Accepted publickey for "
#define L5	"Accepted password for "
#define L6	"Accepted keyboard-interactive for "
		
		/* Skip to end of program[pid]: and trailing space */
		bp = strchr(bp, ':');
		bp += 2;

		if (strncmp(bp, L1, strlen(L1)) == 0) {
		  /*fprintf(stdout,"Hit L1: ");*/
			bp += strlen(L1);
		}
		else if (strncmp(bp, L2, strlen(L2)) == 0) {
		  /*fprintf(stdout,"Hit L2: ");*/
			bp += strlen(L2);
		}
		else if (strncmp(bp, L3, strlen(L3)) == 0) {
		  /*fprintf(stdout,"Hit L3: ");*/
			bp += strlen(L3);
		}
		else if (strncmp(bp, L4, strlen(L4)) == 0) {
		  /*fprintf(stdout,"Hit L4: ");*/
			bp += strlen(L4);
		}
		else if (strncmp(bp, L5, strlen(L5)) == 0) {
		  /*fprintf(stdout,"Hit L5: ");*/
			bp += strlen(L5);
		}
		else if (strncmp(bp, L6, strlen(L6)) == 0) {
		  /*fprintf(stdout,"Hit L6: ");*/
			bp += strlen(L6);
		}
		else {
			continue;
		}

		/*
		 * The login name is the next token.
		 */
		if (! (user = strsep(&bp, " ")))
			continue;
		/*fprintf(stdout,"%s on %s\n",user,node);*/

		/* We do not care about ROOT logins. */
		if (strcasecmp(user, "ROOT") == 0)
			continue;

		dbres = mydb_query("select uid_idx from users where uid='%s' "
				   "and status!='archived' and status!='nonlocal'",
				   1, user);

		if (!dbres) {
			syslog(LOG_ERR, "DB error getting user %s", user);
			continue;
		}

		if (!mysql_num_rows(dbres)) {
			syslog(LOG_INFO, "No DB record for user %s", user);
			mysql_free_result(dbres);
			continue;
		}
		dbrow = mysql_fetch_row(dbres);
		strncpy(uid_idx, dbrow[0], sizeof(uid_idx));
		mysql_free_result(dbres);

		/*
		 * Safety first. 
		 */
		mydb_escape_string(tmp, uid_idx, strlen(uid_idx));
		strcpy(uid_idx, tmp);
		mydb_escape_string(tmp, node, strlen(node));
		strcpy(node, tmp);

		if (mydb_update("replace into uidnodelastlogin "
				"(uid, uid_idx, node_id, date, time) "
				"values ('%s', '%s', '%s', "
				"        FROM_UNIXTIME(%ld, '%%Y-%%m-%%d'), "
				"        FROM_UNIXTIME(%ld, '%%T')) ",
				user, uid_idx, node, ll_time, ll_time) == 0)
			break;

		if (strncmp(node, opshostname, strlen(node)) == 0 ||
		    strncmp(node, "ops", strlen(node)) == 0) {
			if (mydb_update("replace into userslastlogin "
					"(uid, uid_idx, date, time) "
					"values ('%s', '%s', "
					"  FROM_UNIXTIME(%ld, '%%Y-%%m-%%d'), "
					"  FROM_UNIXTIME(%ld, '%%T')) ",
					user, uid_idx, ll_time, ll_time) == 0)
				break;
		}
		else {
			if (mydb_update("replace into nodeuidlastlogin "
					"(node_id, uid_idx, uid, date, time) "
					"values ('%s', '%s', '%s', "
					"  FROM_UNIXTIME(%ld, '%%Y-%%m-%%d'), "
					"  FROM_UNIXTIME(%ld, '%%T')) ",
					node, uid_idx, user, ll_time, ll_time) == 0)
				break;
		}
	}
	return 0;
}
Пример #21
0
static void
stime_darg(const char *arg, struct timeval *tvp)
{
	struct tm t = { .tm_sec = 0 };
	const char *fmt, *colon;
	char *p;
	int val, isutc = 0;

	tvp[0].tv_usec = 0;
	t.tm_isdst = -1;
	colon = strchr(arg, ':');
	if (colon == NULL || strchr(colon + 1, ':') == NULL)
		goto bad;
	fmt = strchr(arg, 'T') != NULL ? "%Y-%m-%dT%H:%M:%S" :
	    "%Y-%m-%d %H:%M:%S";
	p = strptime(arg, fmt, &t);
	if (p == NULL)
		goto bad;
	/* POSIX: must have at least one digit after dot */
	if ((*p == '.' || *p == ',') && isdigit((unsigned char)p[1])) {
		p++;
		val = 100000;
		while (isdigit((unsigned char)*p)) {
			tvp[0].tv_usec += val * (*p - '0');
			p++;
			val /= 10;
		}
	}
	if (*p == 'Z') {
		isutc = 1;
		p++;
	}
	if (*p != '\0')
		goto bad;

	tvp[0].tv_sec = isutc ? timegm(&t) : mktime(&t);

	tvp[1] = tvp[0];
	return;

bad:
	errx(1, "out of range or illegal time specification: YYYY-MM-DDThh:mm:SS[.frac][tz]");
}

/* Calculate a time offset in seconds, given an arg of the format [-]HHMMSS. */
int
timeoffset(const char *arg)
{
	int offset;
	int isneg;

	offset = 0;
	isneg = *arg == '-';
	if (isneg)
		arg++;
	switch (strlen(arg)) {
	default:				/* invalid */
		errx(1, "Invalid offset spec, must be [-][[HH]MM]SS");

	case 6:					/* HHMMSS */
		offset = ATOI2(arg);
		/* FALLTHROUGH */
	case 4:					/* MMSS */
		offset = offset * 60 + ATOI2(arg);
		/* FALLTHROUGH */
	case 2:					/* SS */
		offset = offset * 60 + ATOI2(arg);
	}
	if (isneg)
		return (-offset);
	else
		return (offset);
}
Пример #22
0
void __init sbus_time_init(void)
{
	unsigned int year, mon, day, hour, min, sec;
	struct mostek48t02 *mregs;

#ifdef CONFIG_SUN4
	int temp;
	struct intersil *iregs;
#endif

	BTFIXUPSET_CALL(bus_do_settimeofday, sbus_do_settimeofday, BTFIXUPCALL_NORM);
	btfixup();

	if (ARCH_SUN4)
		sun4_clock_probe();
	else
		clock_probe();

	sparc_init_timers(timer_interrupt);
	
#ifdef CONFIG_SUN4
	if(idprom->id_machtype == (SM_SUN4 | SM_4_330)) {
#endif
	mregs = (struct mostek48t02 *)mstk48t02_regs;
	if(!mregs) {
		prom_printf("Something wrong, clock regs not mapped yet.\n");
		prom_halt();
	}		
	spin_lock_irq(&mostek_lock);
	mregs->creg |= MSTK_CREG_READ;
	sec = MSTK_REG_SEC(mregs);
	min = MSTK_REG_MIN(mregs);
	hour = MSTK_REG_HOUR(mregs);
	day = MSTK_REG_DOM(mregs);
	mon = MSTK_REG_MONTH(mregs);
	year = MSTK_CVT_YEAR( MSTK_REG_YEAR(mregs) );
	xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
	xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
        set_normalized_timespec(&wall_to_monotonic,
                                -xtime.tv_sec, -xtime.tv_nsec);
	mregs->creg &= ~MSTK_CREG_READ;
	spin_unlock_irq(&mostek_lock);
#ifdef CONFIG_SUN4
	} else if(idprom->id_machtype == (SM_SUN4 | SM_4_260) ) {
		/* initialise the intersil on sun4 */

		iregs=intersil_clock;
		if(!iregs) {
			prom_printf("Something wrong, clock regs not mapped yet.\n");
			prom_halt();
		}

		intersil_intr(intersil_clock,INTERSIL_INT_100HZ);
		disable_pil_irq(10);
		intersil_stop(iregs);
		intersil_read_intr(intersil_clock, temp);

		temp = iregs->clk.int_csec;

		sec = iregs->clk.int_sec;
		min = iregs->clk.int_min;
		hour = iregs->clk.int_hour;
		day = iregs->clk.int_day;
		mon = iregs->clk.int_month;
		year = MSTK_CVT_YEAR(iregs->clk.int_year);

		enable_pil_irq(10);
		intersil_start(iregs);

		xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
		xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
	        set_normalized_timespec(&wall_to_monotonic,
 	                               -xtime.tv_sec, -xtime.tv_nsec);
		printk("%u/%u/%u %u:%u:%u\n",day,mon,year,hour,min,sec);
	}
#endif

	/* Now that OBP ticker has been silenced, it is safe to enable IRQ. */
	local_irq_enable();
}
Пример #23
0
int read_option_from_file(time_t *start_time, time_t *end_time, int *time_zone)
{
    struct timeval tv;
    struct timezone tz;
    struct tm tm_start, tm_end;
    struct tm *p_start, *p_end, *p_cur;
	int start_sday_of_week, end_sday_of_week;
    int i;
	time_t time_start_mon_1st, time_end_mon_1st; // The 1st day of start/end month of daylight saving time
  	char wday_start_mon_1st, wday_end_mon_1st; // The weekday of the 1th day in both start/end DLS months
   	char days2target_start_day, days2target_end_day;
   	
	
	FILE *fp;
	char buf[24], *pos;
	char daylight_saving_enable[2]={0};
	int start_week = 0, end_week = 0;

	fp = fopen("/var/etc/daylight_saving.conf", "r");
	if (fp == NULL) 
	{
		printf("Could not open /var/etc/daylight_saving.conf\n");
		return 0;
	}
	
	while (fgets(buf, sizeof(buf), fp) != NULL ) 
	{
		pos = buf;
		while (*pos != '\0') {
			if (*pos == '\n') {
				*pos = '\0';
				break;
			}
			pos++;
		}
		pos = strchr(buf, '=');
		
		if (pos == NULL) 
		{
			printf("daylight_saving.conf: invalid line '%s'\n", buf);
			continue;
		}
		pos++;
		
		if(strstr(buf, "enable")) 
			strncpy(daylight_saving_enable, pos, strlen(pos));
		else if(strstr(buf, "zone"))
			*time_zone = atoi(pos);
		else if(strstr(buf, "start_month"))
			tm_start.tm_mon = atoi(pos) - 1;
		else if(strstr(buf, "start_time"))
			tm_start.tm_hour = atoi(pos);
		else if(strstr(buf, "start_day_of_week"))
			tm_start.tm_wday = atoi(pos) - 1 ;
		else if(strstr(buf, "start_week"))
			start_week = atoi(pos);
		else if(strstr(buf, "end_month"))
			tm_end.tm_mon = atoi(pos) - 1;
		else if(strstr(buf, "end_time"))
			tm_end.tm_hour = atoi(pos);
		else if(strstr(buf, "end_day_of_week"))
			tm_end.tm_wday = atoi(pos) - 1;
		else if(strstr(buf, "end_week"))
			end_week = atoi(pos);
	}
	
	fclose(fp);
	  	
   	gettimeofday(&tv,&tz);
  	
	// DL 
	p_cur = localtime(&tv.tv_sec);
	
	DEBUG_MSG("start day of week %d \n",tm_start.tm_wday);
	tm_start.tm_year = p_cur->tm_year;
	tm_start.tm_yday = 0;
	tm_start.tm_mday = 1;
	tm_start.tm_min  = 0;
	tm_start.tm_sec  = 0;
	start_sday_of_week = tm_start.tm_wday;
	for( i = 1; i < tm_start.tm_mon + 1; i++)
	{
        if((tm_start.tm_year % 4) == 0)
       		tm_start.tm_yday += year_month_days[1][i];
       	else
       		tm_start.tm_yday += year_month_days[0][i];	
	}

	time_start_mon_1st = mktime(&tm_start);    
   	p_start = gmtime(&time_start_mon_1st); // only want tm_wday
   	wday_start_mon_1st = p_start->tm_wday;
	
    days2target_start_day = ( (start_week - 1) * 7) - wday_start_mon_1st + start_sday_of_week;

   	tm_start.tm_mday += days2target_start_day; // Now we know what month day is
   	tm_start.tm_yday += days2target_start_day; 		
		
	// End Time
	tm_end.tm_year = p_cur->tm_year;
	tm_end.tm_yday = 0;
	tm_end.tm_mday = 1;
	tm_end.tm_min  = 0;
   	tm_end.tm_sec = 0;
	end_sday_of_week = tm_end.tm_wday;

	for( i = 1; i < tm_end.tm_mon + 1; i++)
	{
   		if((tm_end.tm_year % 4) == 0)
       		tm_end.tm_yday += year_month_days[1][i];
       	else
       		tm_end.tm_yday += year_month_days[0][i];	
	}

   	time_end_mon_1st = mktime(&tm_end);    
  	p_end = gmtime(&time_end_mon_1st); // only want tm_wday
	wday_end_mon_1st = p_end->tm_wday;   
 
	days2target_end_day = (( end_week - 1) * 7) - wday_end_mon_1st + end_sday_of_week;
	tm_end.tm_mday += days2target_end_day; // Now we know what month day is
	tm_end.tm_yday += days2target_end_day; 			

 	DEBUG_MSG("\n,start Year:%d,Month:%d,Day:%d,Hour:%d\n",tm_start.tm_year+1900,tm_start.tm_mon+1,tm_start.tm_mday,tm_start.tm_hour);	
 	DEBUG_MSG("\n,end Year:%d,Month:%d,Day:%d,Hour:%d\n",tm_end.tm_year+1900,tm_end.tm_mon+1,tm_end.tm_mday,tm_end.tm_hour);	
 	//syslog(LOG_INFO,"\n,Year:%d,Month:%d,Day:%d,Hour:%d,Min:%d,Sec:%d\n",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);	

 	// Get Secs 
	*start_time = mktime(&tm_start);                            
	*end_time = mktime(&tm_end); 
          	   
	return 0;
}
Пример #24
0
time_t xml_parse_dateTime(char* xml_time_str)
{
	struct tm tm;
	char * p;
	int h, m;
	char h1, h2, m1, m2;
	int sign= 1;
	signed int timezone_diff= 0;

	p= strptime(xml_time_str, "%F", &tm);
	if(p== NULL)
	{
		printf("error: failed to parse time\n");
		return 0;
	}
	p++;
	p= strptime(p, "%T", &tm);
	if(p== NULL)
	{
		printf("error: failed to parse time\n");
		return 0;
	}
	
	if(*p== '\0')
		goto done;

	if(*p== '.')
	{
		p++;
		/* read the fractionar part of the seconds*/
		while(*p!= '\0' && *p>= '0' && *p<= '9')
		{
			p++;
		}
	}

	if(*p== '\0')
		goto done;

	
	/* read time zone */

	if(*p== 'Z')
	{
		goto done;
	}

	if(*p== '+')
		sign= -1;

	p++;

	if(sscanf(p, "%c%c:%c%c", &h1, &h2, &m1, &m2) < 0) {
		printf("error: failed to parse time\n");
		return 0;
	}
	
	h= (h1- '0')*10+ h2- '0';
	m= (m1- '0')*10+ m2- '0';

	timezone_diff= sign* ((m+ h* 60)* 60);

done:
	return (mktime(&tm) + timezone_diff);	
}
Пример #25
0
/* difference of two utc times in seconds */
double
cmml_utc_diff (CMML_UTC *t2, CMML_UTC *t1)
{
  double diffsec;

  diffsec = (t2->tm_hsec - t1->tm_hsec)/100;
  diffsec += (t2->tm_sec - t1->tm_sec);
  diffsec += 60.0*(t2->tm_min - t1->tm_min);
  diffsec += 3600.0*(t2->tm_hour - t1->tm_hour);
  diffsec += 24.0*3600*(t2->tm_mday - t1->tm_mday);
  /* presuming there are 30.4375 days in each month (=365.25/12)*/
  diffsec += 30.4375*24*3600*(t2->tm_mon - t1->tm_mon);
  diffsec += 12.0*30*24*3600*(t2->tm_year - t1->tm_year);

#ifdef DEBUG
  fprintf(stderr, "t1: Year=%d\tMonth=%d\tDay=%d\n", 
	  t1->tm_year, t1->tm_mon, t1->tm_mday);
  fprintf(stderr, "Hour=%d\tMinutes=%d\tSec=%d\tHSec=%d\n",
	  t1->tm_hour, t1->tm_min, t1->tm_sec, t1->tm_hsec);
  fprintf(stderr, "t2: Year=%d\tMonth=%d\tDay=%d\n", 
	  t2->tm_year, t2->tm_mon, t2->tm_mday);
  fprintf(stderr, "Hour=%d\tMinutes=%d\tSec=%d\tHSec=%d\n",
	  t2->tm_hour, t2->tm_min, t2->tm_sec, t2->tm_hsec);
  fprintf(stderr, "diffsec = %f\n", diffsec);
#endif

  return diffsec;

  /* seems like the system time functions don't work */
#if 0
  time_t time1, time2;
  struct tm tmptm1;
  struct tm tmptm2;
  double diffreturn;

  if (t1 == NULL || t2 == NULL) {
    return -1;
  }

  /* transform t1 to struct tm and seconds from EPOCH */
  tmptm1.tm_sec  = t1->tm_sec;
  tmptm1.tm_min  = t1->tm_min;
  tmptm1.tm_hour = t1->tm_hour;
  tmptm1.tm_mday = t1->tm_mday;
  tmptm1.tm_mon  = t1->tm_mon-1;
  tmptm1.tm_year = t1->tm_year-1900;
  time1 = mktime(&tmptm1);
#ifdef DEBUG
  fprintf(stderr,"time1 %ld\n", time1);
  fprintf(stderr, "Year=%d(%d)\tMonth=%d(%d)\tDay=%d(%d)\n", 
	  tmptm1.tm_year, t1->tm_year, tmptm1.tm_mon, t1->tm_mon, tmptm1.tm_mday, t1->tm_mday);
  fprintf(stderr, "Hour=%d(%d)\tMinutes=%d(%d)\tSec=%d(%d)\tHSec=0(%d)\n",
	  tmptm1.tm_hour, t1->tm_hour, tmptm1.tm_min, t1->tm_min, tmptm1.tm_sec, t1->tm_sec, 
	  t1->tm_hsec);
#endif

  /* convert t2 to struct tm and seconds from EPOCH */
  tmptm2.tm_sec  = t2->tm_sec;
  tmptm2.tm_min  = t2->tm_min;
  tmptm2.tm_hour = t2->tm_hour;
  tmptm2.tm_mday = t2->tm_mday;
  tmptm2.tm_mon  = t2->tm_mon-1;
  tmptm2.tm_year = t2->tm_year-1900;
  time2 = mktime(&tmptm2);
#ifdef DEBUG
  fprintf(stderr,"time2 %ld\n", time2);
  fprintf(stderr, "Year=%d(%d)\tMonth=%d(%d)\tDay=%d(%d)\n", 
	  tmptm2.tm_year, t2->tm_year, tmptm2.tm_mon, t2->tm_mon, tmptm2.tm_mday, t2->tm_mday);
  fprintf(stderr, "Hour=%d(%d)\tMinutes=%d(%d)\tSec=%d(%d)\tHSec=0(%d)\n",
	  tmptm2.tm_hour, t2->tm_hour, tmptm2.tm_min, t2->tm_min, tmptm2.tm_sec, t2->tm_sec, 
	  t2->tm_hsec);
#endif

  /* use system's time difference functions for calculation */
  diffreturn = (double) difftime (time2, time1);
  fprintf(stderr, "diffreturn=%f\n", diffreturn);
  diffreturn += (t2->tm_hsec - t1->tm_hsec)/100;

  return diffreturn;
#endif

}
Пример #26
0
time_t
parsetime(int argc, char **argv)
{
	/*
	 * Do the argument parsing, die if necessary, and return the
	 * time the job should be run.
	 */
	time_t nowtimer, runtimer;
	struct tm nowtime, runtime;
	int hr = 0; /* this MUST be initialized to zero for
	               midnight/noon/teatime */

	nowtimer = time(NULL);
	nowtime = *localtime(&nowtimer);

	runtime = nowtime;
	runtime.tm_sec = 0;

	if (argc <= optind)
		usage();

	init_scanner(argc - optind, argv + optind);

	switch (token()) {
	case NOW:
		if (scc < 1)
			return nowtimer;

		/* now is optional prefix for PLUS tree */
		expect(PLUS);
		/*FALLTHROUGH*/
	case PLUS:
		plus(&runtime);
		break;

	case NUMBER:
		tod(&runtime);
		month(&runtime);
		break;

		/*
		 * evil coding for TEATIME|NOON|MIDNIGHT - we've initialised
		 * hr to zero up above, then fall into this case in such a
		 * way so we add +12 +4 hours to it for teatime, +12 hours
		 * to it for noon, and nothing at all for midnight, then
		 * set our runtime to that hour before leaping into the
		 * month scanner
		 */
	case TEATIME:
		hr += 4;
		/*FALLTHROUGH*/
	case NOON:
		hr += 12;
		/*FALLTHROUGH*/
	case MIDNIGHT:
		if (runtime.tm_hour >= hr) {
			runtime.tm_mday++;
			runtime.tm_wday++;
		}
		runtime.tm_hour = hr;
		runtime.tm_min = 0;
		(void)token();
		/*FALLTHROUGH*/	/* fall through to month setting */
	default:
		month(&runtime);
		break;
	}
	expect(TOKEOF);

	/*
	 * adjust for daylight savings time
	 */
	runtime.tm_isdst = -1;
	runtimer = mktime(&runtime);

	if (runtimer == (time_t)-1)
		panic("Invalid time");

	if (nowtimer > runtimer)
		panic("Trying to travel back in time");

	return runtimer;
}
Пример #27
0
/* returns a time (midnight) of particular (3rd, last) weekday in a given month */
static time_t calculate_time_from_weekday_of_month(int year, int month, int weekday, int weekday_offset)
{
	time_t midnight;
	int days = 0;
	int weeks = 0;
	struct tm t;

	t.tm_sec = 0;
	t.tm_min = 0;
	t.tm_hour = 0;
	t.tm_year = year;
	t.tm_mon = month;
	t.tm_mday = 1;
	t.tm_isdst = -1;

	midnight = mktime(&t);

	/* how many days must we advance to reach the first instance of the weekday this month? */
	days = weekday - (t.tm_wday);
	if (days < 0)
		days += 7;

	/* positive offset (3rd thursday) */
	if (weekday_offset > 0) {

		/* how many weeks must we advance (no more than 5 possible) */
		weeks = (weekday_offset > 5) ? 5 : weekday_offset;
		days += ((weeks - 1) * 7);

		/* make the new time */
		t.tm_mon = month;
		t.tm_year = year;
		t.tm_mday = days + 1;
		t.tm_isdst = -1;
		midnight = mktime(&t);

		/* if we rolled over to the next month, time is invalid */
		/* assume the user's intention is to keep it in the current month */
		if (t.tm_mon != month)
			midnight = (time_t)0L;
	}

	/* negative offset (last thursday, 3rd to last tuesday) */
	else {
		/* find last instance of weekday in the month */
		days += (5 * 7);
		do {
			/* back up a week */
			days -= 7;

			/* make the new time */
			t.tm_mon = month;
			t.tm_year = year;
			t.tm_mday = days + 1;
			t.tm_isdst = -1;
			midnight = mktime(&t);

		} while (t.tm_mon != month);

		/* now that we know the last instance of the weekday, back up more */
		weeks = (weekday_offset < -5) ? -5 : weekday_offset;
		days = ((weeks + 1) * 7);

		/* make the new time */
		t.tm_mon = month;
		t.tm_year = year;
		t.tm_mday += days;
		t.tm_isdst = -1;
		midnight = mktime(&t);

		/* if we rolled over to the previous month, time is invalid */
		/* assume the user's intention is to keep it in the current month */
		if (t.tm_mon != month)
			midnight = (time_t)0L;
	}

	return midnight;
}
Пример #28
0
 int main() {
     int i;
     int command;
     int devices_found=0;
     int devices_new=0;
     float meter_rate = 0;
     char buffer[10];
     char buffer_date[10];
     int input_count=0;
     int parse_state = WAITING;
     int verbosity = QUIET;
     int in_hold;
     int seq[MAX_PROBES];
     int seq_new[MAX_PROBES];
     int interval = 30;
	 int current_time;
	 int dhw_always = 0;
	 int dhw_floor = 38;
	 int dhw_am = 48;
	 int dhw_day = 45;
	 int dhw_recharge = 25;
//	 int dhw_setpoint = 45;
	 float low[5];
	 float oil;
	 float top;
	 int oil_state = COLD;
	 int dhw_state = DAY;
	 const char oil_char[5] = {'c','r','w','R','W'};
	 const char dhw_char[6] = {'n','N','7','S','L','d'};
     const char suppress_char[2] = {'-','*'};

     // See if this makes the USB more stable.
     wait_us(500);

     serial.printf("Heating Control\r");

     suppress = 0;

     for(i=0;i<5;i++){
    	 low[i]=10;
     }
     meter_pulse.fall(&countPulse);
     t.start();
     reading_interval.start();
     led = 1;
     for (i = 0; i < MAX_PROBES; i++){
         probe[i] = new DS1820(p9);
     	 seq[i] = MAX_PROBES+1;
     }
     // Initialise global state variables
     probe[0]->search_ROM_setup();
     // Loop to find all devices on the data line
     while (probe[devices_found]->search_ROM() and devices_found<MAX_PROBES-1)
         devices_found++;
     // If maximum number of probes are found,
     // bump the counter to include the last array entry
     if (probe[devices_found]->ROM[0] != 0xFF)
         devices_found++;

     if (devices_found==0)
         serial.printf("No devices found");
     else {
         serial.printf("Found %d thermometers\n", devices_found);

         // use devices_new to assign sequence for any un-configured thermometers
         for (i=0; i<devices_found; i++){
        	 command = probe[i]->read_scratchpad();
        	 if (command < MAX_PROBES-1){
        		 if(seq[command] == MAX_PROBES+1){
        			 seq[command] = i;
        		 } else {
        			 serial.printf("Two thermometers with same scratchpad value of %d, %d and %d\n",command,i,seq[command]);
        			 seq_new[devices_new]=i;
        			 devices_new++;
        		 }
        	 } else {
        			 serial.printf("Thermometers with scratchpad value out of range %d, %d (new count %d)\n",command,i,devices_new);
        			 seq_new[devices_new]=i;
        			 devices_new++;
        		 }
         }
         if(devices_new > 0){
        	 serial.printf("Total devices without valid positions %d\n",devices_new);
         }
         while (true) {

        	 // Check for commands from host
        	 if (serial.available() > 0) {
        		 command = serial.getc();
        	 } else {
        		 command = EOF;
        	 }
        	 switch(command){
        	 case EOF: // do nothing
        		 break;
        	 case 'i':{
        		 serial.printf("Heating Control on Cortex-M3\n");
        		 serial.printf("Hot Water enable: %d\n",dhw_always);
        		 serial.printf("Hot Water daytime floor  : %d\n",dhw_floor);
        		 serial.printf("Hot Water mornint preheat: %d\n",dhw_am);
        		 serial.printf("Hot Water daytime targer : %d\n",dhw_day);
        		 serial.printf("Hot Water min lower temp : %d\n",dhw_recharge);
        		 break;
        	 }
        	 case 't': {
        		 serial.printf("Enter Time: hhmmss (non-numeric cancels\n");
        		 clock_seconds = time(NULL);
        		 struct tm *clock_tm = localtime(&clock_seconds);
        		 clock_tm_g = *clock_tm;
        		 parse_state = TIME;
             	 break;
        	 }
        	 case 'd': {
        		 serial.printf("Enter Date: yymmdd (non-numeric cancels\n");
        		 clock_seconds = time(NULL);
        		 struct tm *clock_tm = localtime(&clock_seconds);
        		 clock_tm_g = *clock_tm;
        		 parse_state = DATE;
             	 break;
        	 }
        	 case '0':
        	 case '1':
        	 case '2':
        	 case '3':
        	 case '4':
        	 case '5':
        	 case '6':
        	 case '7':
        	 case '8':
        	 case '9':{
        		 switch(parse_state) {
        		 case SET_PORT:
        			 parse_state = SET_ID;
        			 in_hold = command - '0';
        			 serial.printf("Enter report index for probe %d\n",in_hold);
        			 break;
        		 case SET_ID:
        			 parse_state = WAITING;
        			 probe[in_hold]->write_scratchpad(command-'0');
        			 probe[in_hold]->store_scratchpad(DS1820::this_device);
        			 serial.printf("Write done\n");
        			 break;
        		 case TIME:
        			 input_count++;
        			 serial.putc(command);
        			 switch(input_count){
        			 case 1:
        			 case 3:
        			 case 5: in_hold = command - '0'; break;
        			 case 2: clock_tm_g.tm_hour = (in_hold * 10 + (command - '0')); break;
        			 case 4: clock_tm_g.tm_min  = (in_hold * 10 + (command - '0')); break;
        			 case 6: {
        				 clock_tm_g.tm_sec      = (in_hold * 10 + (command - '0'));
        				 parse_state = WAITING;
        				 input_count = 0;

                		 set_time(mktime(&clock_tm_g));
                		 //Check it worked OK
                		 clock_seconds = time(NULL);
                     	 strftime(buffer, 32, "%H%M%S", localtime(&clock_seconds));
                		 reading_interval.reset();
                     	 serial.printf("\nTime set to %s\n", buffer);
        			 break;
        			 }
        			 }
        			 break;
            		 case DATE:
            			 input_count++;
            			 serial.putc(command);
            			 switch(input_count){
            			 case 1:
            			 case 3:
            			 case 5: in_hold = command - '0'; break;
            			 case 2: clock_tm_g.tm_year = (in_hold * 10 + (command - '0')); break;
            			 case 4: clock_tm_g.tm_mon  = (in_hold * 10 + (command - '0')); break;
            			 case 6: {
            				 clock_tm_g.tm_mday      = (in_hold * 10 + (command - '0'));
            				 parse_state = WAITING;
            				 input_count = 0;

                    		 set_time(mktime(&clock_tm_g));
                    		 //Check it worked OK
                    		 clock_seconds = time(NULL);
                         	 strftime(buffer, 32, "%y%m%d", localtime(&clock_seconds));
                         	 serial.printf("\nDate set to %s\n", buffer);
                         	 serial.printf("Now set time\n");
            			 break;
            			 }
            			 }
            			 break;
                		 case SET_FLOOR:
                			 input_count++;
                			 serial.putc(command);
                			 switch(input_count){
                			 case 1: in_hold = command - '0'; break;
                			 case 2: {
                				 dhw_floor = (in_hold * 10 + (command - '0'));
                				 parse_state = WAITING;
                				 input_count = 0;
                             	 serial.printf("\nHot Water daytime floor set to %d\n", dhw_floor);
                			 break;
                			 }
                			 }
                			 break;
                    		 case SET_DAY:
                    			 input_count++;
                    			 serial.putc(command);
                    			 switch(input_count){
                    			 case 1: in_hold = command - '0'; break;
                    			 case 2: {
                    				 dhw_day = (in_hold * 10 + (command - '0'));
                    				 parse_state = WAITING;
                    				 input_count = 0;
                                 	 serial.printf("\nHot Water daytime target set to %d\n", dhw_day);
                    			 break;
                    			 }
                    			 }
                    			 break;                		 case SET_MIN:
                        			 input_count++;
                        			 serial.putc(command);
                        			 switch(input_count){
                        			 case 1: in_hold = command - '0'; break;
                        			 case 2: {
                        				 dhw_recharge = (in_hold * 10 + (command - '0'));
                        				 parse_state = WAITING;
                        				 input_count = 0;
                                     	 serial.printf("\nHot Water nighttime floor set to %d\n", dhw_recharge);
                        			 break;
                        			 }
                        			 }
                        			 break;                		 case SET_NIGHT:
                            			 input_count++;
                            			 serial.putc(command);
                            			 switch(input_count){
                            			 case 1: in_hold = command - '0'; break;
                            			 case 2: {
                            				 dhw_am = (in_hold * 10 + (command - '0'));
                            				 parse_state = WAITING;
                            				 input_count = 0;
                                         	 serial.printf("\nHot Water night setpoint set to %d\n", dhw_am);
                            			 break;
                            			 }
                            			 }
                            			 break;
                            			 default:
        			 serial.printf("Got digit, but no use for it '%c'\n",command);
        			 break;
        	}
        		 break;
        	 case 'v':
        		 verbosity = QUIET;
        		 interval = 30;
        		 serial.printf("Normal verbosity\n");
        		 break;
        	 case 'V':
        		 if (verbosity == DHW){
        		 verbosity = VERBOSE;
        		 interval = 5;
        		 serial.printf("Debug verbosity\n");
        		 } else {
            		 verbosity = DHW;
            		 interval = 30;
            		 serial.printf("Hot Water verbosity\n");
        		 }
        		 break;
        	 case '?':
        		 serial.printf("v/V : Normal/High verbosity\n");
        		 serial.printf("t   : Set Time as hhmmss\n");
        		 serial.printf("d   : Set Date as ddmmyy\n");
        		 serial.printf("i   : Information\n");
        		 serial.printf("e   : Enumerate 1-wire devices\n");
        		 serial.printf("s   : Set thermometer identifier\n");
        		 serial.printf("h/H : Hot water control active\n");
        		 serial.printf("f   : Set DHW floor daytime (38)\n");
        		 serial.printf("F   : Set DHW daytime charge (45)\n");
        		 serial.printf("n   : Set DHW floor nighttime (25)\n");
        		 serial.printf("N   : Set DHW overnight charge (48)\n");
        		 break;
        	 case 'e':
      			serial.printf("\nChecking Thermometers\n\n");
             	 probe[0]->convert_temperature(DS1820::all_devices);
             	 probe[0]->recall_scratchpad(DS1820::all_devices);
             	 for (i=0; i< devices_found; i++){
        			serial.printf("%d:%x %02x%02x_%02x%02x_%02x%02x %-2.3f @ %d",i,probe[i]->ROM[0],
        					probe[i]->ROM[1],probe[i]->ROM[2],probe[i]->ROM[3],
        					probe[i]->ROM[4],probe[i]->ROM[5],probe[i]->ROM[6],
        					probe[i]->temperature('c'),
        					probe[i]->read_scratchpad());
        			if(probe[i]->ROM_checksum_error()){
        				serial.printf("ROM checksum Error ");
        			}
        			if(probe[i]->RAM_checksum_error()){
        				serial.printf("RAM checksum Error ");
        			}
        			serial.printf("\n");
        		}
        		break;
        	 case 'h':
        		 dhw_always = 1;
        		 serial.printf("Hot water always enabled\n");
        		 break;
        	 case 'H':
        		 dhw_always = 0;
        		 serial.printf("Hot water timer control active\n");
        		 break;
        	 case 'f':
        		 parse_state = SET_FLOOR;
        		 serial.printf("Enter daytime DHW floor\n");
        		 break;
        	 case 'F':
        		 parse_state = SET_DAY;
        		 serial.printf("Enter daytime DHW target\n");
        		 break;
        	 case 'n':
        		 parse_state = SET_MIN;
        		 serial.printf("Enter night DHW floor\n");
        		 break;
        	 case 'N':
        		 parse_state = SET_NIGHT;
        		 serial.printf("Enter night heat target\n");
        		 break;

        	 case 's':
        		 parse_state = SET_PORT;
        		 serial.printf("Enter Thermometer index\n");
        		 break;
        	 // Command does not match
        	 default:{
        		 parse_state = WAITING;
        		 serial.printf("  Unknown command '%c'\n",command);
        	 break;
        	 }
        	 }
        	 }
        	 //ToDo: Reset power at midnight
        	 //Power timer wrap round
        	 //Illogical value check
        	 //fix format of all columns


        	 // Print readings every 30 Sec
        	 if(reading_interval.read()>interval) {
        		 reading_interval.reset();
        		 time_t seconds = time(NULL);
             	 probe[0]->convert_temperature(DS1820::all_devices);

             	 strftime(buffer, 10, "%H%M%S", localtime(&seconds));
             	 serial.printf("%s ", buffer);
             	 if (verbosity==QUIET){
             		 interval = 30 + '0' - buffer[5];
             		 if (buffer[4] == '1'){
             			 interval =-10;
             		 }
             		 if (buffer[4] == '2'){
             			 interval =-20;
             		 }
             		 if (interval < 15) {
             			 interval += 30;
             		 }
                         if (meter_rate > 2500 and interval > 15) {
                             interval = 15;
                         }
             	 }
             	 // Detect midnight
             	 if (buffer[0]=='0' && buffer[1]=='0' && buffer[2]=='0' && buffer[3]=='0' && buffer[4]=='0'){
             		clean_pulses = 0;
             	 }


             	 for (i=0; i<MAX_PROBES; i++) {
             		 int temp;
             		 temp = seq[i];
             		 if(temp > devices_found){
             			serial.printf("-00.00 ");
             		 } else {
             			serial.printf("% 2.2f ",probe[seq[i]]->temperature('c'));
             		 }
             	 }
                 // Check that rate is still accurate
                 // Doesn't handle wrap-round case...
		 current_time = t.read_ms();
		 if ((current_time > (meter_previous + meter_interval)) && (current_time > meter_previous)) {
			 meter_interval = current_time - meter_previous;
                         meter_rate = 3600000.0 / meter_interval;
		         // Clip bad numbers
                         if (meter_rate > 4800) {
                             meter_rate = 4803;
                         }
		 }

             	 serial.printf(" : %6.1f %5d", meter_rate, clean_pulses);

             	 serial.printf(" %c%c%c %.1f\n",oil_char[oil_state],dhw_char[dhw_state],suppress_char[suppress],low[4]-low[0]);
             	 if(verbosity != QUIET){
             		 serial.printf("DHW: Top:% 2.2f Low:% 2.2f Rate: % 2.2f\n",top,low[0],low[4]-low[0]);
             	 }


             	 // dump other temp sensors too
             	 i=0;
             	 while(i<devices_new){
             		 serial.printf("%2.2f ",probe[seq_new[i]]->temperature('c'));
             		 i++;
             	 }
            	 //Pipeline low temperatures
            	low[4] = low[3];
            	low[3] = low[2];
            	low[2] = low[1];
            	low[1] = low[0];
        	 }


        	 // Process oil heater state
        	 if(seq[6] == MAX_PROBES+1){
        		 oil=48;
        	 } else {
        		 oil =  probe[seq[6]]->temperature('c');
        		 if(oil<35) {
        			 oil =  probe[seq[6]]->temperature('c');
        		 }
        		 }
        	 switch (oil_state){
        	 case COLD:
        		 if(oil > 47) {
    				 serial.printf("Was cold, passed 47 to reheat\n");
        			 oil_state = RELAX;
        		 } else
        		 {
        			 if (suppress == 0 and dhw_always == 0){
        				 serial.printf("Reached Cold state - suppressing DHW\n");
        				 suppress = 1;
        			 }
        		 }
        		 break;
        	 case RELAX:
        		 if(oil < 42 && oil > 40) {
    				 serial.printf("Heat cycle done\n");
    				 oil_state = WARM;}
        		 if(oil < 36) {
    				 serial.printf("Failed to hear up %f\n",oil);
    				 oil_state = RELAX_MISS;}
        		 break;
        	 case WARM:
        		 if(oil < 32) {
        			 oil_state = WARM_MISS;
    				 serial.printf("Was warm, now cold @ %f\n",oil);
        		 }
        		 break;
        	 case RELAX_MISS:
        		 if(oil > 36) {
    				 serial.printf("Recovered\n");
    				 oil_state = RELAX;}
        		 if(oil < 34) {
    				 serial.printf("Still Failed to hear up %f\n",oil);
    				 oil_state = COLD;}
        		 break;
        	 case WARM_MISS:
        		 if(oil>33) {
        			 oil_state = WARM;
    				 serial.printf("Warm again @ %f\n",oil);
        		 }
        		 if(oil < 31) {
        			 oil_state = COLD;
    				 serial.printf("Was warm, now cold @ %f\n",oil);
        		 }
        		 break;
        	 }

        	 // Process Water heater state
        	 // Probe 0 = top
        	 // Probe 2 = Flow
        	 // Probe 1 = Lower

        	 if(seq[1] == MAX_PROBES+1){
        		 low[0] = 20;
        	 } else {
        		 low[0] = probe[seq[1]]->temperature('c');
        	 }
        	 if(seq[0] == MAX_PROBES+1){
        		 	 top = 40;
        	 } else {
        		 top =  probe[seq[0]]->temperature('c');
        	 }
        	 switch (dhw_state){
        	 // 9pm to 8am (or heat cycle done)
        	 case NIGHT:
        		 if(dhw_always == 0) {
        			 suppress = 1;
        		 }
        		 // Try to catch end of oil cool-down cycle
             	 if (buffer[0]=='0' && buffer[1]=='6' &&(oil < 42 || buffer[2]>'3')) {dhw_state = E7;}
             	 if (buffer[0]=='1' || buffer[1]>'8')  {dhw_state = DAY;}
             	 // Too cold, short heat
             	 if ((low[0] < dhw_recharge) && (oil_state == WARM)) {
             		 suppress = 0;
             		dhw_state = NIGHTBOOST;
             	 }
             	 break;
        	 case NIGHTBOOST:
        		 suppress = 0;
             	 if (top > dhw_day and dhw_always == 0) {
             		 suppress = 1;
             		 dhw_state = NIGHT;
             	 }
        		 if(oil_state != WARM and dhw_always == 0) {
        			 suppress = 1;
        		     dhw_state = NIGHT;
        		 }
        		 break;
        	 case E7:
        		 suppress = 0;
             	 if (top > dhw_am and dhw_always == 0) {
             		 suppress = 1;
             		 dhw_state = DAY;
             	 }
        		 if(oil_state != WARM and dhw_always == 0) {
        			 suppress = 1;
        		     dhw_state = NIGHT;
        		 }
        		 break;
        	 case SHORT:
        		 if ((top > dhw_day) and ((low[0]-low[4]) > .25) and dhw_always == 0) {
        			 suppress = 1;
        		     dhw_state = DAY;
        		 }
        		 if(oil_state != WARM and dhw_always == 0) {
        			 suppress = 1;
        		     dhw_state = DAY;
        		 }
        		 break;
        	 case LONG:
        		 if (top > dhw_am and dhw_always == 0) {
        			 suppress = 1;
        			 dhw_state = DAY;
        		 }
        		 if(oil_state != WARM and dhw_always == 0) {
        			 suppress = 1;
        		     dhw_state = DAY;
        		 }
        		 break;
        	 case DAY:
        		 if(dhw_always == 0) {
        			 suppress = 1;
        		 }
        		 // 10pm is night, no need for any hot water.
             	 if (buffer[0]=='2' &&  buffer[1]>'1' and dhw_always == 0)  {
             		 dhw_state = NIGHT;
             		 suppress = 1;
             		 break;
             	 }
             	 if (buffer[0]=='0' &&  buffer[1]<'6' and dhw_always == 0)  {
             		 dhw_state = NIGHT;
             		 suppress = 1;
             		 break;
             	 }
             	 if ((((low[4]-low[0]) > 1) ||(top < dhw_floor)) && (oil_state == WARM)) {
             		 dhw_state = SHORT;
             		 suppress = 0;
             	 }
             	 if ((low[0]< dhw_recharge) && (oil_state == WARM)) {
             		 dhw_state = LONG;
             		 suppress = 0;
             	 }
        		 break;
        	 }

        	 if (dhw_always == 1){
        		 suppress = 0;
        	 }
        	 // Idle loop processing of meter reading
             if (meter_pulses){
            	 meter_rate = 3600000.0 / meter_interval;
		 // Clip bad numbers
                 if (meter_rate > 4800) {
                     meter_rate = 4803;
                 }
            	 led = !led;
            	 if(verbosity==VERBOSE){
            	 serial.printf("%d Pulse interval %dus, %4.3f W\n",meter_pulses, meter_interval,meter_rate);
            	 }
            	 meter_pulses = 0;
            	 clean_pulses ++;
             }
         }
     }
 }
Пример #29
0
static void _get_next_invalid_time(time_t pref_time, time_t *invalid_time, timeperiod *tperiod)
{
	timeperiodexclusion *temp_timeperiodexclusion = NULL;
	int depth = 0;
	int max_depth = 300; // commonly roughly equal to "days in the future"
	struct tm *t, tm_s;
	time_t earliest_time = pref_time;
	time_t last_earliest_time = 0;
	time_t midnight = (time_t)0L;
	time_t day_range_start = (time_t)0L;
	time_t day_range_end = (time_t)0L;
	time_t potential_time = 0;
	time_t excluded_time = 0;
	time_t last_range_end = 0;
	int have_earliest_time = FALSE;
	timerange *last_range = NULL, *temp_timerange = NULL;

	/* if no period was specified, assume the time is good */
	if (tperiod == NULL || check_time_against_period(pref_time, tperiod) == ERROR) {
		*invalid_time = pref_time;
		return;
	}

	/* first excluded time may well be the time we're looking for */
	for (temp_timeperiodexclusion = tperiod->exclusions; temp_timeperiodexclusion != NULL; temp_timeperiodexclusion = temp_timeperiodexclusion->next) {
		/* if pref_time is excluded, we're done */
		if (check_time_against_period(pref_time, temp_timeperiodexclusion->timeperiod_ptr) != ERROR) {
			*invalid_time = pref_time;
			return;
		}
		_get_next_valid_time(pref_time, &potential_time, temp_timeperiodexclusion->timeperiod_ptr);
		if (!excluded_time || excluded_time > potential_time)
			excluded_time = potential_time;
	}

	while (earliest_time != last_earliest_time && depth < max_depth) {
		have_earliest_time = FALSE;
		depth++;
		last_earliest_time = earliest_time;

		t = localtime_r((time_t *)&earliest_time, &tm_s);
		t->tm_sec = 0;
		t->tm_min = 0;
		t->tm_hour = 0;
		midnight = mktime(t);

		temp_timerange = _get_matching_timerange(earliest_time, tperiod);

		for (; temp_timerange; last_range = temp_timerange, temp_timerange = temp_timerange->next) {
			/* ranges with start/end of zero mean exlude this day */

			day_range_start = (time_t)(midnight + temp_timerange->range_start);
			day_range_end = (time_t)(midnight + temp_timerange->range_end);

#ifdef TEST_TIMEPERIODS_B
			printf("  INVALID RANGE START: %lu (%lu) = %s", temp_timerange->range_start, (unsigned long)day_range_start, ctime(&day_range_start));
			printf("  INVALID RANGE END:   %lu (%lu) = %s", temp_timerange->range_end, (unsigned long)day_range_end, ctime(&day_range_end));
#endif

			if (temp_timerange->range_start == 0 && temp_timerange->range_end == 0)
				continue;

			if (excluded_time && day_range_end > excluded_time) {
				earliest_time = excluded_time;
				have_earliest_time = TRUE;
				break;
			}

			/*
			 * Unless two consecutive days have adjoining timeranges,
			 * the end of the last period is the start of the first
			 * invalid time. This only needs special-casing when the
			 * last range of the previous day ends at midnight, and
			 * also catches the special case when there are only
			 * exceptions in a timeperiod and some days are skipped
			 * entirely.
			 */
			if (last_range && last_range->range_end == SECS_PER_DAY && last_range_end && day_range_start != last_range_end) {
				earliest_time = last_range_end;
				have_earliest_time = TRUE;
				break;
			}

			/* stash this day_range_end in case we skip a day */
			last_range_end = day_range_end;

			if (pref_time <= day_range_end && temp_timerange->range_end != SECS_PER_DAY) {
				earliest_time = day_range_end;
				have_earliest_time = TRUE;
#ifdef TEST_TIMEPERIODS_B
				printf("    EARLIEST INVALID TIME: %lu = %s", (unsigned long)earliest_time, ctime(&earliest_time));
#endif
				break;
			}
		}

		/* if we found this in the exclusions, we're done */
		if (have_earliest_time == TRUE) {
			break;
		}

		earliest_time = midnight + SECS_PER_DAY;
	}
#ifdef TEST_TIMEPERIODS_B
	printf("    FINAL EARLIEST INVALID TIME: %lu = %s", (unsigned long)earliest_time, ctime(&earliest_time));
#endif

	if (depth == max_depth)
		*invalid_time = pref_time;
	else
		*invalid_time = earliest_time;
}
Пример #30
0
SaErrorT
cIpmiInventoryAreaBoard::ParseFruArea( const unsigned char *data, unsigned int size )
{
  cIpmiInventoryField *iif;
  SaErrorT rv;
  unsigned int area_size = *(data+1)*8;

  if ( area_size > size )
  {
       stdlog << "wrong board area length !\n";
       return SA_ERR_HPI_INVALID_DATA;
  }

  if ( IpmiChecksum( data, *(data+1)*8 ) )
     {
       stdlog << "wrong board area checksum !\n";
       return SA_ERR_HPI_INVALID_DATA;
     }

  data += 2;
  size -= 2;

  if ( size < 4 )
       return SA_ERR_HPI_INVALID_DATA;

  // Skip Language
  data++;
  size--;

  time_t mfg_time = (SaHpiTimeT)data[0] + (SaHpiTimeT)data[1] * 256 + (SaHpiTimeT)data[2] * 65536;

  size -= 3;
  data += 3;

  mfg_time *= 60;

  // create date offset
  struct tm tmt;

  tmt.tm_sec  = 0;
  tmt.tm_min  = 0;
  tmt.tm_hour = 0;
  tmt.tm_mday = 1;
  tmt.tm_mon  = 0;
  tmt.tm_year = 96;
  tmt.tm_isdst = 0;

  mfg_time += mktime( &tmt );

  char str[80];
  IpmiDateTimeToString( mfg_time, str );

  iif = new cIpmiInventoryField( m_area_header.AreaId, m_field_id++, SAHPI_IDR_FIELDTYPE_MFG_DATETIME);

  m_field_array.Add( iif );

  iif->SetAscii ( str, strlen( str ) + 1 );

  for ( unsigned int i = 0; i < sizeof(BoardInfoAreaFields)/sizeof(BoardInfoAreaFields[0]); i++ )
  {
      iif = new cIpmiInventoryField( m_area_header.AreaId, m_field_id++, BoardInfoAreaFields[i]);

      m_field_array.Add( iif );

      rv = iif->ReadTextBuffer( data, size );

      if ( rv != SA_OK )
          return rv;
  }

  while( true )
     {
       if ( size < 1 )
	    return SA_ERR_HPI_INVALID_DATA;

       if ( *data == 0xc1 )
	    break;

       iif = new cIpmiInventoryField( m_area_header.AreaId, m_field_id++, SAHPI_IDR_FIELDTYPE_CUSTOM);

       m_field_array.Add( iif );

       rv = iif->ReadTextBuffer( data, size );

       if ( rv != SA_OK )
        return rv;
     }

  m_area_header.NumFields = m_field_array.Num();

  return SA_OK;
}