static gboolean absolute_val_from_string(fvalue_t *fv, const char *s, gchar **err_msg) { struct tm tm; char *curptr; memset(&tm, 0, sizeof(tm)); curptr = strptime(s,"%b %d, %Y %H:%M:%S", &tm); if (curptr == NULL) curptr = strptime(s,"%Y-%m-%dT%H:%M:%S", &tm); if (curptr == NULL) curptr = strptime(s,"%Y-%m-%d %H:%M:%S", &tm); if (curptr == NULL) curptr = strptime(s,"%Y-%m-%d %H:%M", &tm); if (curptr == NULL) curptr = strptime(s,"%Y-%m-%d %H", &tm); if (curptr == NULL) curptr = strptime(s,"%Y-%m-%d", &tm); if (curptr == NULL) goto fail; tm.tm_isdst = -1; /* let the computer figure out if it's DST */ fv->value.time.secs = mktime(&tm); if (*curptr != '\0') { /* * Something came after the seconds field; it must be * a nanoseconds field. */ if (*curptr != '.') goto fail; /* it's not */ curptr++; /* skip the "." */ if (!g_ascii_isdigit((unsigned char)*curptr)) goto fail; /* not a digit, so not valid */ if (!get_nsecs(curptr, &fv->value.time.nsecs)) goto fail; } else { /* * No nanoseconds value - it's 0. */ fv->value.time.nsecs = 0; } if (fv->value.time.secs == -1) { /* * XXX - should we supply an error message that mentions * that the time specified might be syntactically valid * but might not actually have occurred, e.g. a time in * the non-existent time range after the clocks are * set forward during daylight savings time (or possibly * that it's in the time range after the clocks are set * backward, so that there are two different times that * it could be)? */ goto fail; } return TRUE; fail: if (err_msg != NULL) *err_msg = g_strdup_printf("\"%s\" is not a valid absolute time. Example: \"Nov 12, 1999 08:55:44.123\" or \"2011-07-04 12:34:56\"", s); return FALSE; }
static int parse_format (GLogItem * glog, const char *fmt, const char *date_format, char *str) { const char *p; double serve_secs; int special = 0; struct tm tm; unsigned long long bandw, serve_time; if (str == NULL || *str == '\0') return 1; memset (&tm, 0, sizeof (tm)); /* iterate over the log format */ for (p = fmt; *p; p++) { if (*p == '%') { special++; continue; } if (special && *p != '\0') { char *pch, *sEnd, *bEnd, *tkn = NULL, *end = NULL; errno = 0; bandw = 0; serve_time = 0; serve_secs = 0; switch (*p) { /* date */ case 'd': if (glog->date) return 1; /* parse date format including dates containing spaces, * i.e., syslog date format (Jul 15 20:10:56) */ tkn = parse_string (&str, p[1], count_matches (date_format, ' ') + 1); if (tkn == NULL) return 1; end = strptime (tkn, date_format, &tm); if (end == NULL || *end != '\0') { free (tkn); return 1; } glog->date = tkn; break; /* remote hostname (IP only) */ case 'h': if (glog->host) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (invalid_ipaddr (tkn)) { free (tkn); return 1; } glog->host = tkn; break; /* request method */ case 'm': if (glog->method) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (invalid_method (tkn)) { free (tkn); return 1; } glog->method = tkn; break; /* request not including method or protocol */ case 'U': if (glog->req) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL || *tkn == '\0') return 1; if ((glog->req = decode_url (tkn)) == NULL) return 1; free (tkn); break; /* request protocol */ case 'H': if (glog->protocol) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (invalid_protocol (tkn)) { free (tkn); return 1; } glog->protocol = tkn; break; /* request, including method + protocol */ case 'r': if (glog->req) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; glog->req = parse_req (tkn, glog); free (tkn); break; /* Status Code */ case 's': if (glog->status) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; strtol (tkn, &sEnd, 10); if (tkn == sEnd || *sEnd != '\0' || errno == ERANGE) { free (tkn); return 1; } glog->status = tkn; break; /* size of response in bytes - excluding HTTP headers */ case 'b': if (glog->resp_size) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; bandw = strtol (tkn, &bEnd, 10); if (tkn == bEnd || *bEnd != '\0' || errno == ERANGE) bandw = 0; glog->resp_size = bandw; conf.bandwidth = 1; free (tkn); break; /* referrer */ case 'R': if (glog->ref) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) tkn = alloc_string ("-"); if (tkn != NULL && *tkn == '\0') { free (tkn); tkn = alloc_string ("-"); } glog->ref = tkn; break; /* user agent */ case 'u': if (glog->agent) return 1; tkn = parse_string (&str, p[1], 1); if (tkn != NULL && *tkn != '\0') { /* Make sure the user agent is decoded (i.e.: CloudFront) * and replace all '+' with ' ' (i.e.: w3c) */ glog->agent = char_replace (decode_url (tkn), '+', ' '); free (tkn); break; } else if (tkn != NULL && *tkn == '\0') { free (tkn); tkn = alloc_string ("-"); } /* must be null */ else { tkn = alloc_string ("-"); } glog->agent = tkn; break; /* time taken to serve the request, in seconds */ case 'T': if (glog->serve_time) return 1; /* ignore seconds if we have microseconds */ if (strstr (fmt, "%D") != NULL) break; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (strchr (tkn, '.') != NULL) serve_secs = strtod (tkn, &bEnd); else serve_secs = strtoull (tkn, &bEnd, 10); if (tkn == bEnd || *bEnd != '\0' || errno == ERANGE) serve_secs = 0; /* convert it to microseconds */ if (serve_secs > 0) glog->serve_time = serve_secs * SECS; else glog->serve_time = 0; conf.serve_usecs = 1; free (tkn); break; /* time taken to serve the request, in microseconds */ case 'D': if (glog->serve_time) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; serve_time = strtoull (tkn, &bEnd, 10); if (tkn == bEnd || *bEnd != '\0' || errno == ERANGE) serve_time = 0; glog->serve_time = serve_time; conf.serve_usecs = 1; free (tkn); break; /* everything else skip it */ default: if ((pch = strchr (str, p[1])) != NULL) str += pch - str; } if ((str == NULL) || (*str == '\0')) return 0; special = 0; } else if (special && isspace (p[0])) { return 1; } else str++; } return 0; }
int command_touch (int argc, char **argv) { int i; char *ptr, *c; struct tm *m; progname = argv[0]; time (&now); t.actime = now; t.modtime = now; for (i = 1; i < argc; ++i) { ptr = argv[i]; if (*ptr == '-') { while (*++ptr) switch (*ptr) { case '-': if (!strcmp (ptr, "-help")) { puts (help_text); return (EXIT_SUCCESS); } else if (!strcmp (ptr, "-version")) { puts ("touch: version "VERSION); return (EXIT_SUCCESS); } case 'a': flag_access = 1; continue; case 'c': flag_create = 0; continue; case 'm': flag_modification = 1; continue; case 'r': if (++i >= argc) terror ("missing operand to `-r' option"); lstat (argv[i], &s); t.actime = s.st_atime; t.modtime = s.st_mtime; break; case 't': if (++i >= argc) terror ("missing operand to `-t' option"); m = xmalloc (sizeof (struct tm)); memset (m, '\0', sizeof (*m)); c = strptime (argv[i], "%C%Y%m%d%H%M%S", m); t.actime = mktime (m); t.modtime = mktime (m); break; } } else do_touch (argv[i]); } return (EXIT_SUCCESS); }
void run_loader(int thread, char *filename) { bson_t *record; mongoc_client_t *conn; mongoc_collection_t *collection; bson_error_t error; bson_t reply; int count; FILE *infile; char *rptr; char ilinebuf[BUFSIZ]; char rlinebuf[BUFSIZ]; char *ritem; char *rlast = NULL; int rfcount = 0; int batchcount = 0; char *str; int total = 0; //Get the highest used value on that shard so far conn = mongoc_client_new(DEFAULT_URI); if (!conn) { fprintf(stderr, "Failed to parse URI.\n"); exit(1); } collection = mongoc_client_get_collection(conn, DATA_DB, DATA_COLLECTION); long long chunkno = carve_chunk(conn, collection); printf("Thread %d reading %s\n", thread, filename); infile = fopen(filename, "r"); if (infile == NULL) { perror("Opening results file"); exit(1); } mongoc_bulk_operation_t *bulk = mongoc_collection_create_bulk_operation( collection, true, NULL); if(!bulk) { printf("Failed to create bulk op\n"); } rptr = fgets(rlinebuf, BUFSIZ, infile); rlinebuf[strlen(rlinebuf) - 1] = '\0'; //Read the Results Line while (rptr) { total++; if (total % (INSERT_THREADS_PER_SHARD * nshards) == thread) { ritem = strtok_r(rptr, "|", &rlast); rfcount = 0; record = bson_new(); //Two part ID - a loader (32 bits for that) and a one_up bson_append_int64(record, "_id", -1, (chunkno << 32) + total); while (ritem) { switch (resulttype[rfcount]) { case 0: //printf("%s\n",ritem); bson_append_utf8(record, resultfields[rfcount], -1, ritem, -1); break; case 1: bson_append_int32(record, resultfields[rfcount], -1, atoi(ritem)); break; case 2: if (strncmp(ritem, "NULL", 4)) { struct tm tm; if (strptime(ritem, "%Y-%m-%d", &tm)) { time_t t = mktime(&tm); // t is now your desired time_t bson_append_date_time(record, resultfields[rfcount], -1, (long long) t * 1000); } } break; default: printf("Unknown type col %d = %d\n", rfcount, resulttype[rfcount]); } ritem = strtok_r(NULL, "|", &rlast); rfcount++; } mongoc_bulk_operation_insert(bulk, record); bson_destroy(record); if (batchcount == (BATCHSIZE - 1)) { int ret = mongoc_bulk_operation_execute(bulk, &reply, &error); if (!ret) { printf( "Error: %s\n", error.message); } if (thread == 0) printf("%s %d\n", filename, total); bson_destroy(&reply); mongoc_bulk_operation_destroy(bulk); batchcount = 0; bulk = mongoc_collection_create_bulk_operation(collection, true, NULL); } else { batchcount++; } } //Read next line from file rptr = fgets(rlinebuf, BUFSIZ, infile); rlinebuf[strlen(rlinebuf) - 1] = '\0'; } int ret = mongoc_bulk_operation_execute(bulk, &reply, &error); if (!ret) { fprintf(stderr, "Error: %s\n", error.message); } if (thread == 0) printf("%s %d\n", filename, total); bson_destroy(&reply); mongoc_collection_destroy(collection); mongoc_bulk_operation_destroy(bulk); mongoc_client_destroy(conn); }
static time_t parsetime(char *str, time_t current) { struct tm *cur, t; int zulu = 0; char *format; size_t len = strlen(str); cur = localtime(¤t); t.tm_isdst = -1; switch (len) { /* -t flag argument */ case 8: t.tm_sec = 0; t.tm_year = cur->tm_year; format = "%m%d%H%M"; break; case 10: t.tm_sec = 0; format = "%y%m%d%H%M"; break; case 11: t.tm_year = cur->tm_year; format = "%m%d%H%M.%S"; break; case 12: t.tm_sec = 0; format = "%Y%m%d%H%M"; break; case 13: format = "%y%m%d%H%M.%S"; break; case 15: format = "%Y%m%d%H%M.%S"; break; /* -d flag argument */ case 19: format = "%Y-%m-%dT%H:%M:%S"; break; case 20: /* only Zulu-timezone supported */ if (str[19] != 'Z') eprintf("Invalid time zone\n"); str[19] = 0; zulu = 1; format = "%Y-%m-%dT%H:%M:%S"; break; default: eprintf("Invalid date format length\n", str); } if (!strptime(str, format, &t)) weprintf("strptime %s: Invalid date format\n", str); if (zulu) { t.tm_hour += t.tm_gmtoff / 60; t.tm_gmtoff = 0; t.tm_zone = "Z"; } return mktime(&t); }
bool CScrobbler::LoadJournal() { int journalVersion = 0; SubmissionJournalEntry entry; TiXmlDocument xmlDoc; CStdString JournalFileName = GetJournalFileName(); CSingleLock lock(m_queueLock); m_vecSubmissionQueue.clear(); if (!xmlDoc.LoadFile(JournalFileName)) { CLog::Log(LOGDEBUG, "%s: %s, Line %d (%s)", m_strLogPrefix.c_str(), JournalFileName.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } TiXmlElement *pRoot = xmlDoc.RootElement(); if (strcmpi(pRoot->Value(), "asjournal") != 0) { CLog::Log(LOGDEBUG, "%s: %s missing <asjournal>", m_strLogPrefix.c_str(), JournalFileName.c_str()); return false; } if (pRoot->Attribute("version")) journalVersion = atoi(pRoot->Attribute("version")); TiXmlNode *pNode = pRoot->FirstChild("entry"); for (; pNode; pNode = pNode->NextSibling("entry")) { entry.Clear(); XMLUtils::GetString(pNode, "artist", entry.strArtist); XMLUtils::GetString(pNode, "album", entry.strAlbum); XMLUtils::GetString(pNode, "title", entry.strTitle); XMLUtils::GetString(pNode, "length", entry.strLength); entry.length = atoi(entry.strLength.c_str()); XMLUtils::GetString(pNode, "starttime", entry.strStartTime); XMLUtils::GetString(pNode, "musicbrainzid", entry.strMusicBrainzID); if (journalVersion > 0) { XMLUtils::GetString(pNode, "tracknum", entry.strTrackNum); XMLUtils::GetString(pNode, "source", entry.strSource); XMLUtils::GetString(pNode, "rating", entry.strRating); } else { // Update from journal v0 // Convert start time stamp struct tm starttm; time_t startt; if (!strptime(entry.strStartTime.c_str(), "%Y-%m-%d %H:%M:%S", &starttm)) continue; if ((startt = mktime(&starttm)) == -1) continue; entry.strStartTime.Format("%d", startt); // url encode entries CURL::Encode(entry.strArtist); CURL::Encode(entry.strTitle); CURL::Encode(entry.strAlbum); CURL::Encode(entry.strMusicBrainzID); } m_vecSubmissionQueue.push_back(entry); } CLog::Log(LOGDEBUG, "%s: Journal loaded with %"PRIuS" entries.", m_strLogPrefix.c_str(), m_vecSubmissionQueue.size()); return !m_vecSubmissionQueue.empty(); }
int request_handler(struct mg_connection *conn){ char tmpBuf[1024]; sprintf(tmpBuf, "%s %s from %s", conn->request_method, conn->uri, conn->remote_ip); log_line(tmpBuf, LOG_INFO); if(strcmp(STATS_JSON_URI, conn->uri) == 0){ return stats_json(conn); } #ifndef DEBUG // serve assets from resources.c size_t asset_size; int is_modified = 0; const char *asset_content = NULL, *if_modifier_since_header = NULL; char date_str[48], cache_control[58], expires[48], last_modified[48]; time_t current_time, expires_time, if_modified_time, modified_time; struct tm *current_time_tm, *expires_tm, if_modifier_since, *last_modified_tm; last_modified_tm = gmtime(&globalOptions.start_time); strftime(last_modified, sizeof(last_modified), CONST_RFC1945_TIME_FORMAT, last_modified_tm); if_modifier_since_header = mg_get_header(conn, "If-Modified-Since"); if(if_modifier_since_header){ strptime(if_modifier_since_header, CONST_RFC1945_TIME_FORMAT, &if_modifier_since); if_modified_time = mktime(&if_modifier_since); modified_time = mktime(last_modified_tm); if(modified_time <= if_modified_time){ mg_send_status(conn, 304); is_modified = 1; } } if(strcmp("/", conn->uri) == 0){ asset_content = find_embedded_file("public/index.html", &asset_size); mg_send_header(conn, "Content-Type", "text/html; charset=utf-8"); }else if(strcmp("/assets/app.js", conn->uri) == 0){ asset_content = find_embedded_file("public/assets/app.js", &asset_size); mg_send_header(conn, "Content-Type", "application/x-javascript; charset=utf-8"); }else if(strcmp("/assets/app.css", conn->uri) == 0){ asset_content = find_embedded_file("public/assets/app.css", &asset_size); mg_send_header(conn, "Content-Type", "text/css; charset=utf-8"); } if(asset_content != NULL){ current_time = time(NULL); current_time_tm = gmtime(¤t_time); strftime(date_str, sizeof(date_str), CONST_RFC1945_TIME_FORMAT, current_time_tm); sprintf(cache_control, "max-age=%d, public", CACHE_LIMIT); expires_time = time(NULL) + CACHE_LIMIT; expires_tm = gmtime(&expires_time); strftime(expires, sizeof(expires), CONST_RFC1945_TIME_FORMAT, expires_tm); mg_send_header(conn, "Date", date_str); mg_send_header(conn, "Cache-Control", cache_control); mg_send_header(conn, "Vary", "Accept-Encoding"); mg_send_header(conn, "Expires", expires); if(is_modified == 0){ mg_send_header(conn, "Last-Modified", last_modified); mg_send_data(conn, asset_content, asset_size); }else{ // close connection mg_send_data(conn, "\r\n", 2); } return MG_REQUEST_PROCESSED; } #endif return MG_REQUEST_NOT_PROCESSED; }
static void stime_darg(const char *arg, struct timespec *tvp) { struct tm t = { .tm_sec = 0 }; const char *fmt, *colon; char *p; int val, isutc = 0; tvp[0].tv_nsec = 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 = 100000000; while (isdigit((unsigned char)*p)) { tvp[0].tv_nsec += 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); }
void log_file_exit(logd_file * plf) { pid_t pid; int ret_len = 0; int round_off = 0; /* Get current time and assign to end time*/ time_t cur_time = time(NULL); struct tm ltime; aln_interval *pal = NULL; char tmp_filename[1024] = { 0 }; char cmd[1024] = { 0 }; struct stat file_status; FILE *pipefd = NULL; char path[1024]; char *token = NULL; int field = 0; char trailer_record[SIZE_OF_TIMEBUFFER] = {0}; struct tm mtime; struct tm etime; time_t et; unsigned long tmp_et; uploadInfo *p_uploadInfo = NULL; char gz_filename[MAX_FILE_SZ] = { 0 }; int err = 0; char *bname = NULL, *b = NULL; char *bname_upldinfo = NULL, *b_upldinfo = NULL; char *dname_upldinfo = NULL, *d_upldinfo = NULL; memset(<ime, 0, sizeof(struct tm) ); memset(&etime, 0, sizeof(struct tm) ); if(!plf->fp) { snprintf(cmd,1024,"/bin/ls %s/%s.%d*", "/log/varlog/nkn", plf->filename, plf->cur_fileid); pipefd = popen(cmd, "r"); if(pipefd == NULL) { return; } fscanf(pipefd,"%s\n",path); plf->fullfilename = strdup(path); pclose(pipefd); } strlcpy(tmp_filename,plf->fullfilename,sizeof(tmp_filename)); //Parse the crawl.log file name when started for // the first time parsse from :"crawl.log.0.20120517_09:45:00" if(strcmp(plf->file_start_time,"") == 0){ token = strtok(tmp_filename,"._:"); while(token != NULL) { /* The 3rd field till 5th field indicates the start timestamp*/ if((field >= 3)&&(field <= 5)) { strlcat(plf->file_start_time ,token, sizeof(plf->file_start_time)); } token = strtok(NULL, "._:"); field++; } } //Fix for PR782738 if(strcmp(plf->file_end_time,"") == 0){ if(strcmp(plf->file_start_time,"") != 0) { if(plf->rt_interval){ strptime(plf->file_start_time, "%Y%m%d%H%M", <ime ); et = mktime(<ime); et = et + (60 * plf->rt_interval); localtime_r(&et, &etime); } else { time_t now = time(NULL); localtime_r(&now ,&etime); } strftime(plf->file_end_time, SIZE_OF_TIMEBUFFER, "%G%m%d%H%M", &etime); } } sscanf(plf->file_end_time,"%lu",&tmp_et); if(plf->version_etime == 0){ plf->version_etime = tmp_et; plf->version_number ++; }else{ if(tmp_et > plf->version_etime){ plf->version_number = 0; }else { plf->version_number ++; } plf->version_etime = tmp_et; } if(stat(plf->fullfilename, &file_status) == 0) { //Got the file status if(plf->fp == NULL){ plf->fp = fopen(plf->fullfilename, "a+"); } if(plf->fp != NULL) { localtime_r(&file_status.st_mtime, &mtime); strftime (trailer_record, SIZE_OF_TIMEBUFFER, "%G%m%d%H%M%S", &mtime); fprintf(plf->fp,"\n#Last Modified : %s",trailer_record); } else { lc_log_basic(LOG_ERR, "Failed to update trailer in previous file %s", plf->fullfilename); } } else { lc_log_basic(LOG_ERR, "Failed to get stat of previous file %s", plf->fullfilename); } if(plf->fp){ int ret = 0; pthread_mutex_lock(&plf->fp_lock); ret = fflush(plf->fp); log_write_report_err(ret, plf); fclose(plf->fp); plf->fp=NULL; if(plf->pai){ free(plf->pai); } pthread_mutex_unlock(&plf->fp_lock); } p_uploadInfo = malloc(sizeof(struct uploadInfo)); if (p_uploadInfo == NULL){ complain_error_msg(1, "Memory allocation failed!,may not zip log file"); bail_error(1); } memset(p_uploadInfo, 0, sizeof(struct uploadInfo)); b = basename(bname = strdup(plf->fullfilename)); if((plf->fullfilename)&&(plf->filename)){ if(plf->type == TYPE_CRAWLLOG){ snprintf(gz_filename, MAX_FILE_SZ, "%s/%s_%d_%s_%s", logpath, plf->filename, plf->version_number, plf->file_start_time, plf->file_end_time); } else{ snprintf(gz_filename, MAX_FILE_SZ, "%s", plf->fullfilename); } p_uploadInfo->fullfilename = strdup(gz_filename); p_uploadInfo->filename =strdup(b); p_uploadInfo->logtype = plf->type; } if((plf->remote_url)||(plf->remote_pass)){ p_uploadInfo->remote_url = strdup(plf->remote_url); p_uploadInfo->password = strdup(plf->remote_pass); } b_upldinfo = basename(bname_upldinfo = strdup(p_uploadInfo->fullfilename)); d_upldinfo = dirname(dname_upldinfo = strdup(p_uploadInfo->fullfilename)); if(plf->type == TYPE_CRAWLLOG){ memset(gz_filename, 0, MAX_FILE_SZ); // Append "." to the file name so we dont end up in loosing the file before we zip as in log_file_init the files may be deleted by unlink snprintf(gz_filename, MAX_FILE_SZ, "%s/.%s", d_upldinfo, b_upldinfo); lc_log_basic(LOG_INFO, "log_file.c ...file name......%s", gz_filename); err = lf_rename_file(plf->fullfilename, gz_filename); bail_error(err); } err = post_msg_to_gzip(p_uploadInfo); bail_error(err); bail: safe_free(bname); safe_free(dname_upldinfo); safe_free(bname_upldinfo); return; }
if (std::isnan(MISSING)) { return std::isnan(v); } else { return v == MISSING; } } auto date_xlt = [](const char * str) -> real_type { std::tm parsed = {0}; strptime(str, "%Y-%m-%d %T", &parsed); const auto tp = std::chrono::system_clock::from_time_t(std::mktime(&parsed)); const auto days_since_1900 = std::chrono::duration_cast<std::chrono::hours>(tp.time_since_epoch()).count() / 24; return days_since_1900; }; /* * generic pattern converter for loadtxt */ auto from_list_xlt = [](const std::vector<std::string> & patterns, const char * str) -> real_type { auto matched_it = std::find_if(patterns.cbegin(), patterns.cend(), [&str](const std::string & what) {
char * strptime(const char *buf, const char *fmt, struct tm *tm) { char c; const char *bp; size_t len = 0; int alt_format, i, split_year = 0; bp = buf; while ((c = *fmt) != '\0') { /* Clear `alternate' modifier prior to new conversion. */ alt_format = 0; /* Eat up white-space. */ if (isspace(c)) { while (isspace(*bp)) bp++; fmt++; continue; } if ((c = *fmt++) != '%') goto literal; again: switch (c = *fmt++) { case '%': /* "%%" is converted to "%". */ literal : if (c != *bp++) return (0); break; /* * "Alternative" modifiers. Just set the appropriate flag * and start over again. */ case 'E': /* "%E?" alternative conversion modifier. */ LEGAL_ALT(0); alt_format |= ALT_E; goto again; case 'O': /* "%O?" alternative conversion modifier. */ LEGAL_ALT(0); alt_format |= ALT_O; goto again; /* * "Complex" conversion rules, implemented through recursion. */ case 'c': /* Date and time, using the locale's format. */ LEGAL_ALT(ALT_E); if (!(bp = strptime(bp, "%x %X", tm))) return (0); break; case 'D': /* The date as "%m/%d/%y". */ LEGAL_ALT(0); if (!(bp = strptime(bp, "%m/%d/%y", tm))) return (0); break; case 'R': /* The time as "%H:%M". */ LEGAL_ALT(0); if (!(bp = strptime(bp, "%H:%M", tm))) return (0); break; case 'r': /* The time in 12-hour clock representation. */ LEGAL_ALT(0); if (!(bp = strptime(bp, "%I:%M:%S %p", tm))) return (0); break; case 'T': /* The time as "%H:%M:%S". */ LEGAL_ALT(0); if (!(bp = strptime(bp, "%H:%M:%S", tm))) return (0); break; case 'X': /* The time, using the locale's format. */ LEGAL_ALT(ALT_E); if (!(bp = strptime(bp, "%H:%M:%S", tm))) return (0); break; case 'x': /* The date, using the locale's format. */ LEGAL_ALT(ALT_E); if (!(bp = strptime(bp, "%m/%d/%y", tm))) return (0); break; /* * "Elementary" conversion rules. */ case 'A': /* The day of week, using the locale's form. */ case 'a': LEGAL_ALT(0); for (i = 0; i < 7; i++) { /* Full name. */ len = strlen(day[i]); if (strncasecmp((char *)(day[i]), (char *)bp, len) == 0) break; /* Abbreviated name. */ len = strlen(abday[i]); if (strncasecmp((char *)(abday[i]), (char *)bp, len) == 0) break; } /* Nothing matched. */ if (i == 7) return (0); tm->tm_wday = i; bp += len; break; case 'B': /* The month, using the locale's form. */ case 'b': case 'h': LEGAL_ALT(0); for (i = 0; i < 12; i++) { /* Full name. */ len = strlen(mon[i]); if (strncasecmp((char *)(mon[i]), (char *)bp, len) == 0) break; /* Abbreviated name. */ len = strlen(abmon[i]); if (strncasecmp((char *)(abmon[i]), (char *)bp, len) == 0) break; } /* Nothing matched. */ if (i == 12) return (0); tm->tm_mon = i; bp += len; break; case 'C': /* The century number. */ LEGAL_ALT(ALT_E); if (!(conv_num(&bp, &i, 0, 99))) return (0); if (split_year) { tm->tm_year = (tm->tm_year % 100) + (i * 100); } else { tm->tm_year = i * 100; split_year = 1; } break; case 'd': /* The day of month. */ case 'e': LEGAL_ALT(ALT_O); if (!(conv_num(&bp, &tm->tm_mday, 1, 31))) return (0); break; case 'k': /* The hour (24-hour clock representation). */ LEGAL_ALT(0); /* FALLTHROUGH */ case 'H': LEGAL_ALT(ALT_O); if (!(conv_num(&bp, &tm->tm_hour, 0, 23))) return (0); break; case 'l': /* The hour (12-hour clock representation). */ LEGAL_ALT(0); /* FALLTHROUGH */ case 'I': LEGAL_ALT(ALT_O); if (!(conv_num(&bp, &tm->tm_hour, 1, 12))) return (0); if (tm->tm_hour == 12) tm->tm_hour = 0; break; case 'j': /* The day of year. */ LEGAL_ALT(0); if (!(conv_num(&bp, &i, 1, 366))) return (0); tm->tm_yday = i - 1; break; case 'M': /* The minute. */ LEGAL_ALT(ALT_O); if (!(conv_num(&bp, &tm->tm_min, 0, 59))) return (0); break; case 'm': /* The month. */ LEGAL_ALT(ALT_O); if (!(conv_num(&bp, &i, 1, 12))) return (0); tm->tm_mon = i - 1; break; // case 'p': /* The locale's equivalent of AM/PM. */ // LEGAL_ALT(0); // /* AM? */ // if (strcasecmp(am_pm[0], bp) == 0) // { // if (tm->tm_hour > 11) // return (0); // // bp += strlen(am_pm[0]); // break; // } // /* PM? */ // else if (strcasecmp(am_pm[1], bp) == 0) // { // if (tm->tm_hour > 11) // return (0); // // tm->tm_hour += 12; // bp += strlen(am_pm[1]); // break; // } // // /* Nothing matched. */ // return (0); case 'S': /* The seconds. */ LEGAL_ALT(ALT_O); if (!(conv_num(&bp, &tm->tm_sec, 0, 61))) return (0); break; case 'U': /* The week of year, beginning on sunday. */ case 'W': /* The week of year, beginning on monday. */ LEGAL_ALT(ALT_O); /* * XXX This is bogus, as we can not assume any valid * information present in the tm structure at this * point to calculate a real value, so just check the * range for now. */ if (!(conv_num(&bp, &i, 0, 53))) return (0); break; case 'w': /* The day of week, beginning on sunday. */ LEGAL_ALT(ALT_O); if (!(conv_num(&bp, &tm->tm_wday, 0, 6))) return (0); break; case 'Y': /* The year. */ LEGAL_ALT(ALT_E); if (!(conv_num(&bp, &i, 0, 9999))) return (0); tm->tm_year = i - TM_YEAR_BASE; break; case 'y': /* The year within 100 years of the epoch. */ LEGAL_ALT(ALT_E | ALT_O); if (!(conv_num(&bp, &i, 0, 99))) return (0); if (split_year) { tm->tm_year = ((tm->tm_year / 100) * 100) + i; break; } split_year = 1; if (i <= 68) tm->tm_year = i + 2000 - TM_YEAR_BASE; else tm->tm_year = i + 1900 - TM_YEAR_BASE; break; /* * Miscellaneous conversions. */ case 'n': /* Any kind of white-space. */ case 't': LEGAL_ALT(0); while (isspace(*bp)) bp++; break; default: /* Unknown/unsupported conversion. */ return (0); } } /* LINTED functional specification */ return ((char *)bp); }
static void parse_preamble (void) { struct tm timecode; char *subsecs; char *p; int subseclen; int i; /* * If no "-t" flag was specified, don't attempt to parse a packet * preamble to extract a time stamp. */ if (ts_fmt == NULL) return; /* * Initialize to today localtime, just in case not all fields * of the date and time are specified. */ timecode = timecode_default; ts_usec = 0; /* * Null-terminate the preamble. */ packet_preamble[packet_preamble_len] = '\0'; /* Ensure preamble has more than two chars before atempting to parse. * This should cover line breaks etc that get counted. */ if ( strlen(packet_preamble) > 2 ) { /* Get Time leaving subseconds */ subsecs = strptime( packet_preamble, ts_fmt, &timecode ); if (subsecs != NULL) { /* Get the long time from the tm structure */ /* (will return -1 if failure) */ ts_sec = mktime( &timecode ); } else ts_sec = -1; /* we failed to parse it */ /* This will ensure incorrectly parsed dates get set to zero */ if ( -1 == ts_sec ) { /* Sanitize - remove all '\r' */ char *c; while ((c = strchr(packet_preamble, '\r')) != NULL) *c=' '; fprintf (stderr, "Failure processing time \"%s\" using time format \"%s\"\n (defaulting to Jan 1,1970 00:00:00 GMT)\n", packet_preamble, ts_fmt); if (debug >= 2) { fprintf(stderr, "timecode: %02d/%02d/%d %02d:%02d:%02d %d\n", timecode.tm_mday, timecode.tm_mon, timecode.tm_year, timecode.tm_hour, timecode.tm_min, timecode.tm_sec, timecode.tm_isdst); } ts_sec = 0; /* Jan 1,1970: 00:00 GMT; tshark/wireshark will display date/time as adjusted by timezone */ ts_usec = 0; } else { /* Parse subseconds */ ts_usec = strtol(subsecs, &p, 10); if (subsecs == p) { /* Error */ ts_usec = 0; } else { /* * Convert that number to a number * of microseconds; if it's N digits * long, it's in units of 10^(-N) seconds, * so, to convert it to units of * 10^-6 seconds, we multiply by * 10^(6-N). */ subseclen = (int) (p - subsecs); if (subseclen > 6) { /* * *More* than 6 digits; 6-N is * negative, so we divide by * 10^(N-6). */ for (i = subseclen - 6; i != 0; i--) ts_usec /= 10; } else if (subseclen < 6) { for (i = 6 - subseclen; i != 0; i--) ts_usec *= 10; } } } } if (debug >= 2) { char *c; while ((c = strchr(packet_preamble, '\r')) != NULL) *c=' '; fprintf(stderr, "[[parse_preamble: \"%s\"]]\n", packet_preamble); fprintf(stderr, "Format(%s), time(%u), subsecs(%u)\n", ts_fmt, (guint32)ts_sec, ts_usec); } /* Clear Preamble */ packet_preamble_len = 0; }
gint parse_and_write_detail_data(const gchar *station_id, htmlDocPtr doc, const gchar *result_file){ gchar buff[256], buffer[buff_size], current_temperature[20], current_icon[10], current_title[1024], current_pressure[15], current_humidity[15], current_wind_direction[15], current_wind_speed[15]; gchar temp_buffer[buff_size]; GSList *forecast = NULL; GSList *tmp = NULL; GHashTable *day = NULL; gboolean night_flag; gint size; gint i, j, k, l; GHashTable *hash_for_translate; GHashTable *hash_for_icons; xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj = NULL; xmlXPathObjectPtr xpathObj2 = NULL; xmlXPathObjectPtr xpathObj3 = NULL; xmlXPathObjectPtr xpathObj4 = NULL; xmlXPathObjectPtr xpathObj5 = NULL; xmlXPathObjectPtr xpathObj6 = NULL; xmlXPathObjectPtr xpathObj7 = NULL; xmlXPathObjectPtr xpathObj8 = NULL; xmlXPathObjectPtr xpathObj9 = NULL; xmlNodeSetPtr nodes; gchar *temp_char; gchar *temp_char2; gint pressure; gint speed; gint ppcp; gchar *image = NULL; double time_diff = 0; time_t loc_time; time_t utc_time; gint location_timezone = 0; gboolean timezone_flag = FALSE; gboolean sunrise_flag = FALSE; gboolean flag; struct tm tmp_tm_loc = {0}; struct tm tmp_tm = {0}; struct tm current_tm = {0}; struct tm tm_l = {0}; struct tm tmp_tm2 = {0}; struct tm *tm; time_t t_start = 0, t_end = 0, t_sunrise = 0, t_sunset = 0, current_time = 0; FILE *file_out; int index = 1; file_out = fopen(result_file, "a"); if (!file_out) return -1; hash_for_icons = hash_icons_forecacom_table_create(); /* Create xpath evaluation context */ xpathCtx = xmlXPathNewContext(doc); if(xpathCtx == NULL) { fprintf(stderr,"Error: unable to create new XPath context\n"); return(-1); } /* Register namespaces from list (if any) */ xmlXPathRegisterNs(xpathCtx, (const xmlChar*)"html", (const xmlChar*)"http://www.w3.org/1999/xhtml"); /* Current weather forecast */ /* Evaluate xpath expression */ xpathObj = xmlXPathEvalExpression((const xmlChar*)"/html/body/div/div/table//tr[1]/th[@colspan='4']/text()", xpathCtx); if(xpathObj == NULL) { fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", " /html/body/div/div/table//tr[1]/th[@colspan='4']/text()"); xmlXPathFreeContext(xpathCtx); return(-1); } temp_char = strchr(xpathObj->nodesetval->nodeTab[0]->content, ' '); if (temp_char == NULL || strlen(temp_char)<2) return -1; temp_char = temp_char + 1; temp_char = strchr(temp_char, ' '); if (temp_char != NULL){ for (j=0; j<strlen(temp_char)-1; j++){ if (temp_char[j] == ' ' || temp_char[j] == '\n') continue; else{ temp_char = temp_char + j; break; } } } xpathObj = xmlXPathEvalExpression((const xmlChar*)"/html/body/div/div/table//tr[3]/td[@class='in']/text()", xpathCtx); if (xpathObj && xpathObj->nodesetval->nodeTab[0]->content){ snprintf(buffer, sizeof(buffer)-1,"%s %s", temp_char, xpathObj->nodesetval->nodeTab[0]->content); current_time = time(NULL); tm = localtime(¤t_time); setlocale(LC_TIME, "POSIX"); strptime((const char*)buffer, "%d/%m %H:%M", &tmp_tm); setlocale(LC_TIME, ""); /* set begin of day in localtime */ tmp_tm.tm_year = tm->tm_year; t_start = mktime(&tmp_tm); fprintf(file_out," <period start=\"%li\"", (t_start + 1 - 2*3600)); /* set end of current time in localtime */ t_end = t_start + 3600*4 - 1; fprintf(file_out," end=\"%li\" current=\"true\" >\n", t_end); } if (xpathObj) xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression((const xmlChar*)"/html/body/div/div/table//tr[3]/td[2]/span/text()", xpathCtx); /* added temperature */ if (xpathObj && !xmlXPathNodeSetIsEmpty(xpathObj->nodesetval) && xpathObj->nodesetval->nodeTab[0] && xpathObj->nodesetval->nodeTab[0]->content){ /* fprintf (stderr, "temperature %s\n", xpathObj->nodesetval->nodeTab[0]->content); */ snprintf(buffer, sizeof(buffer)-1,"%s", xpathObj->nodesetval->nodeTab[0]->content); memset(temp_buffer, 0, sizeof(temp_buffer)); for (j = 0 ; (j<(strlen(buffer)) && j < buff_size); j++ ){ if (buffer[j] == '&') break; if ((uint)buffer[j] == 226 || buffer[j] == '-' || (buffer[j]>='0' && buffer[j]<='9')){ if ((uint)buffer[j] == 226) sprintf(temp_buffer,"%s-",temp_buffer); else sprintf(temp_buffer,"%s%c",temp_buffer, buffer[j]); } } /* fprintf(stderr, " <temperature>%s</temperature>\n", temp_buffer); */ fprintf(file_out," <temperature>%s</temperature>\n", temp_buffer); } if (xpathObj) xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression((const xmlChar*)"/html/body/div/div/table//tr[3]/td[3]/img/@alt", xpathCtx); /* added wind direction */ if (xpathObj && !xmlXPathNodeSetIsEmpty(xpathObj->nodesetval) && xpathObj->nodesetval->nodeTab[0] && xpathObj->nodesetval->nodeTab[0]->children->content){ /* fprintf(stderr, "Wind direction .%s. \n", xpathObj->nodesetval->nodeTab[0]->children->content); */ if (strlen(xpathObj->nodesetval->nodeTab[0]->children->content)>0) fprintf(file_out," <wind_direction>%s</wind_direction>\n", xpathObj->nodesetval->nodeTab[0]->children->content); } if (xpathObj) xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression((const xmlChar*)"/html/body/div/div/table//tr[3]/td[3]/text()", xpathCtx); /* added wind speed */ if (xpathObj && !xmlXPathNodeSetIsEmpty(xpathObj->nodesetval) && xpathObj->nodesetval->nodeTab[0] && xpathObj->nodesetval->nodeTab[0]->content){ /* fprintf(stderr, "Wind direction %s \n", xpathObj4->nodesetval->nodeTab[i]->children->content); */ fprintf(file_out," <wind_speed>%s</wind_speed>\n", xpathObj->nodesetval->nodeTab[0]->content); } if (xpathObj) xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression((const xmlChar*)"/html/body/div/div/table//tr[3]/td[4]/img/@src", xpathCtx); /* added icon */ if (xpathObj && !xmlXPathNodeSetIsEmpty(xpathObj->nodesetval) && xpathObj->nodesetval->nodeTab[0] && xpathObj->nodesetval->nodeTab[0]->children->content){ temp_char = strrchr((char*)xpathObj->nodesetval->nodeTab[0]->children->content, '/'); temp_char ++; /* fprintf (stderr, "icon %s %s \n", xpathObj6->nodesetval->nodeTab[i]->children->content, choose_hour_weather_icon(hash_for_icons, temp_char)); */ fprintf(file_out," <icon>%s</icon>\n", choose_hour_weather_icon(hash_for_icons, temp_char)); } if (xpathObj) xmlXPathFreeObject(xpathObj); index = 1; snprintf(buffer, sizeof(buffer)-1,"/html/body/div/div/table//tr[4]/td/text()[%i]", index); xpathObj = xmlXPathEvalExpression((const xmlChar*)buffer, xpathCtx); /* added text */ if (xpathObj && !xmlXPathNodeSetIsEmpty(xpathObj->nodesetval) && xpathObj->nodesetval->nodeTab[0] && xpathObj->nodesetval->nodeTab[0]->content){ if (strstr(xpathObj->nodesetval->nodeTab[0]->content, "Feels Like:") == NULL){ /* fprintf (stderr, "description %s\n", xpathObj7->nodesetval->nodeTab[i]->content); */ snprintf(buffer, sizeof(buffer)-1,"%s", xpathObj->nodesetval->nodeTab[0]->content); memset(temp_buffer, 0, sizeof(temp_buffer)); for (j = 0 ; (j<(strlen(buffer)) && j < buff_size); j++ ){ if (buffer[j] == 13 || buffer[j] == 10) continue; sprintf(temp_buffer,"%s%c",temp_buffer, buffer[j]); } index ++; fprintf(file_out," <description>%s</description>\n", temp_buffer); } } if (xpathObj) xmlXPathFreeObject(xpathObj); snprintf(buffer, sizeof(buffer)-1,"/html/body/div/div/table//tr[4]/td/text()[%i]", index); xpathObj = xmlXPathEvalExpression((const xmlChar*)buffer, xpathCtx); temp_char = strstr(xpathObj->nodesetval->nodeTab[0]->content, "Feels Like:"); if (temp_char != NULL){ temp_char = strchr(temp_char, ':'); temp_char = temp_char + 2; snprintf(buffer, sizeof(buffer)-1,"%s", temp_char); memset(temp_buffer, 0, sizeof(temp_buffer)); for (j = 0 ; (j<(strlen(buffer)) && j < buff_size); j++ ){ if (buffer[j] == '&') break; if ((uint)buffer[j] == 226 || buffer[j] == '-' || (buffer[j]>='0' && buffer[j]<='9')){ if ((uint)buffer[j] == 226) sprintf(temp_buffer,"%s-",temp_buffer); else sprintf(temp_buffer,"%s%c",temp_buffer, buffer[j]); } } /* fprintf(stderr, " <temperature>%s</temperature>\n", temp_buffer); */ fprintf(file_out," <flike>%s</flike>\n", temp_buffer); } fprintf(file_out," </period>\n"); /* To DO sunrise and sunset */ xpathObj = xmlXPathEvalExpression("/html/body/div/div/table//tr[th]/*/text()", xpathCtx); /* Day weather forecast */ nodes = xpathObj->nodesetval; size = (nodes) ? nodes->nodeNr : 0; snprintf(buffer, sizeof(buffer)-1,"(/html/body/div/div/table//tr/th/text() | /html/body/div/div/table//tr/td[@class='in']/text() | /html/body/div/div/table//tr/td/span/text() | /html/body/div/div/table//tr/td/img/@alt | /html/body/div/div/table//tr/td/text() | /html/body/div/div/table//tr/td/img/@src )"); xpathObj2 = xmlXPathEvalExpression(buffer, xpathCtx); k = 0; for(i = 1; i < (size) ; ++i) { nodes = xpathObj2->nodesetval; flag = FALSE; for (j = 0; j <(nodes->nodeNr); ++j){ if (!flag && xpathObj2->nodesetval->nodeTab[j]->content && xpathObj->nodesetval->nodeTab[i]->content && !strcmp(xpathObj->nodesetval->nodeTab[i]->content, xpathObj2->nodesetval->nodeTab[j]->content)){ flag = TRUE; k = 0; } if (flag && i+1 < size && xpathObj2->nodesetval->nodeTab[j]->content && xpathObj->nodesetval->nodeTab[i+1]->content && !strcmp(xpathObj->nodesetval->nodeTab[i+1]->content, xpathObj2->nodesetval->nodeTab[j]->content)){ flag = FALSE; } if (flag){ switch (k){ case 1: { current_time = time(NULL); tm = localtime(¤t_time); snprintf(buffer, sizeof(buffer)-1,"%s %s", xpathObj->nodesetval->nodeTab[i]->content, xpathObj2->nodesetval->nodeTab[j]->content); fprintf(stderr," Buffer %s\n", buffer); setlocale(LC_TIME, "POSIX"); strptime((const char*)buffer, "%A %b %d %H:%M", &tmp_tm); setlocale(LC_TIME, ""); /* set begin of day in localtime */ tmp_tm.tm_year = tm->tm_year; t_start = mktime(&tmp_tm); fprintf(file_out," <period start=\"%li\"", (t_start)); /* set end of current time in localtime */ t_end = t_start + 3600*6 - 1; fprintf(file_out," end=\"%li\" hour=\"true\">\n", t_end); break; } case 2: { /* added temperature */ if (xpathObj2->nodesetval->nodeTab[j]->content){ /* fprintf (stderr, "temperature %s\n", xpathObj->nodesetval->nodeTab[0]->content); */ snprintf(buffer, sizeof(buffer)-1,"%s", xpathObj2->nodesetval->nodeTab[j]->content); memset(temp_buffer, 0, sizeof(temp_buffer)); for (l = 0 ; (l<(strlen(buffer)) && l < buff_size); l++ ){ if (buffer[l] == '&') break; if ((uint)buffer[l] == 226 || buffer[l] == '-' || (buffer[l]>='0' && buffer[l]<='9')){ if ((uint)buffer[l] == 226) sprintf(temp_buffer,"%s-",temp_buffer); else sprintf(temp_buffer,"%s%c",temp_buffer, buffer[l]); } } /* fprintf(stderr, " <temperature>%s</temperature>\n", temp_buffer); */ fprintf(file_out," <temperature>%s</temperature>\n", temp_buffer); } break; } case 4: { if (strlen(xpathObj2->nodesetval->nodeTab[j]->children->content)>0) fprintf(file_out," <wind_direction>%s</wind_direction>\n", xpathObj2->nodesetval->nodeTab[j]->children->content); break; } case 5: { if (xpathObj2->nodesetval->nodeTab[j] && xpathObj2->nodesetval->nodeTab[j]->content){ /* fprintf(stderr, "Wind direction %s \n", xpathObj4->nodesetval->nodeTab[i]->children->content); */ fprintf(file_out," <wind_speed>%s</wind_speed>\n", xpathObj2->nodesetval->nodeTab[j]->content); } break; } case 6: { if (strlen(xpathObj2->nodesetval->nodeTab[j]->children->content)>0){ temp_char = strrchr((char*)xpathObj2->nodesetval->nodeTab[j]->children->content, '/'); temp_char ++; fprintf(file_out," <icon>%s</icon>\n", choose_hour_weather_icon(hash_for_icons, temp_char)); } break; } case 7: { if (strlen(xpathObj2->nodesetval->nodeTab[j]->children->content)>0){ fprintf(file_out," <description>%s</description>\n", xpathObj2->nodesetval->nodeTab[j]->children->content); } k = 0; fprintf(file_out," </period>\n"); } } k++; } } } fclose(file_out); return 1; }
gint parse_and_write_xml_data(const gchar *station_id, htmlDocPtr doc, const gchar *result_file){ gchar buff[256], buffer[buff_size], current_temperature[20], current_icon[10], current_title[1024], current_pressure[15], current_humidity[15], current_wind_direction[15], current_wind_speed[15]; gchar temp_buffer[buff_size]; GSList *forecast = NULL; GSList *tmp = NULL; GHashTable *day = NULL; gboolean flag; gboolean night_flag; gint size; gint i, j; GHashTable *hash_for_translate; GHashTable *hash_for_icons; xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj = NULL; xmlXPathObjectPtr xpathObj2 = NULL; xmlXPathObjectPtr xpathObj3 = NULL; xmlXPathObjectPtr xpathObj4 = NULL; xmlXPathObjectPtr xpathObj5 = NULL; xmlXPathObjectPtr xpathObj6 = NULL; xmlXPathObjectPtr xpathObj7 = NULL; xmlXPathObjectPtr xpathObj8 = NULL; xmlXPathObjectPtr xpathObj9 = NULL; xmlNodeSetPtr nodes; gchar *temp_char; gchar *temp_char2; gint pressure; gint speed; gint ppcp; gchar *image = NULL; double time_diff = 0; time_t loc_time; time_t utc_time; gint location_timezone = 0; gboolean timezone_flag = FALSE; gboolean sunrise_flag = FALSE; struct tm tmp_tm_loc = {0}; struct tm tmp_tm = {0}; struct tm current_tm = {0}; struct tm tm_l = {0}; struct tm tmp_tm2 = {0}; struct tm *tm; time_t t_start = 0, t_end = 0, t_sunrise = 0, t_sunset = 0, current_time = 0; FILE *file_out; file_out = fopen(result_file, "w"); if (!file_out) return -1; fprintf(file_out,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<station name=\"Station name\" id=\"%s\" xmlns=\"http://omweather.garage.maemo.org/schemas\">\n", station_id); fprintf(file_out," <units>\n <t>C</t>\n <ws>m/s</ws>\n <wg>m/s</wg>\n <d>km</d>\n"); fprintf(file_out," <h>%%</h> \n <p>mmHg</p>\n </units>\n"); hash_for_icons = hash_icons_forecacom_table_create(); /* Create xpath evaluation context */ xpathCtx = xmlXPathNewContext(doc); if(xpathCtx == NULL) { fprintf(stderr,"Error: unable to create new XPath context\n"); return(-1); } /* Register namespaces from list (if any) */ xmlXPathRegisterNs(xpathCtx, (const xmlChar*)"html", (const xmlChar*)"http://www.w3.org/1999/xhtml"); /* Day weather forecast */ /* Evaluate xpath expression */ xpathObj = xmlXPathEvalExpression((const xmlChar*)"/html/body/div/div/table//tr/th[@colspan='3']", xpathCtx); if(xpathObj == NULL) { fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", "/html/body/div/div/table//tr/th[@colspan='3']/text()"); xmlXPathFreeContext(xpathCtx); return(-1); } nodes = xpathObj->nodesetval; size = (nodes) ? nodes->nodeNr : 0; if (size > 10) size = 10; /* fprintf(stderr, "SIZE!!!!!!!!!!!!!!: %i\n", size); */ xpathObj2 = xmlXPathEvalExpression("/html/body/div/div/table//tr/td[@class='in']//span[1]/text()", xpathCtx); xpathObj3 = xmlXPathEvalExpression("/html/body/div/div/table//tr/td[@class='in']//span[2]/text()", xpathCtx); xpathObj4 = xmlXPathEvalExpression("/html/body/div/div/table//tr/td[2]/img/@alt", xpathCtx); xpathObj5 = xmlXPathEvalExpression("/html/body/div/div/table//tr/td[2]/text()", xpathCtx); xpathObj6 = xmlXPathEvalExpression("/html/body/div/div/table//tr/td[3]/img/@src", xpathCtx); xpathObj7 = xmlXPathEvalExpression("/html/body/div/div/table//tr/td[@class='in2']/text()[1]", xpathCtx); xpathObj8 = xmlXPathEvalExpression("/html/body/div/div/table//tr/td[@class='in2']/text()[2]", xpathCtx); /* fprintf(stderr, "Result (%d nodes):\n", size); */ for(i = 0; i < size; ++i) { day = NULL; /* Take time: */ if (!nodes->nodeTab[i]->children->content) continue; temp_char = strstr(nodes->nodeTab[i]->children->content, " "); int j = 0; if (temp_char != NULL){ for (j=0; j<strlen(temp_char)-1; j++){ if (temp_char[j] == ' ' || temp_char[j] == '\n') continue; else{ temp_char = temp_char + j; break; } } } if (temp_char == NULL) continue; current_time = time(NULL); tm = localtime(¤t_time); setlocale(LC_TIME, "POSIX"); strptime((const char*)temp_char, "%b %d", &tmp_tm); setlocale(LC_TIME, ""); /* set begin of day in localtime */ tmp_tm.tm_year = tm->tm_year; tmp_tm.tm_hour = 0; tmp_tm.tm_min = 0; tmp_tm.tm_sec = 0; t_start = mktime(&tmp_tm); fprintf(file_out," <period start=\"%li\"", (t_start +1)); /* set end of day in localtime */ t_end = t_start + 3600*24 - 1; fprintf(file_out," end=\"%li\">\n", t_end); /* added hi temperature */ if (xpathObj2 && !xmlXPathNodeSetIsEmpty(xpathObj2->nodesetval) && xpathObj2->nodesetval->nodeTab[i] && xpathObj2->nodesetval->nodeTab[i]->content){ /* fprintf (stderr, "temperature %s\n", xpathObj2->nodesetval->nodeTab[i]->content); */ snprintf(buffer, sizeof(buffer)-1,"%s", xpathObj2->nodesetval->nodeTab[i]->content); memset(temp_buffer, 0, sizeof(temp_buffer)); for (j = 0 ; (j<(strlen(buffer)) && j < buff_size); j++ ){ if (buffer[j] == '&') break; if ((uint)buffer[j] == 226 || buffer[j] == '-' || (buffer[j]>='0' && buffer[j]<='9')){ if ((uint)buffer[j] == 226) sprintf(temp_buffer,"%s-",temp_buffer); else sprintf(temp_buffer,"%s%c",temp_buffer, buffer[j]); } } /* fprintf(stderr, " <temperature>%s</temperature>\n", temp_buffer); */ fprintf(file_out," <temperature_hi>%s</temperature_hi>\n", temp_buffer); } /* added lo temperature */ if (xpathObj3 && !xmlXPathNodeSetIsEmpty(xpathObj3->nodesetval) && xpathObj3->nodesetval->nodeTab[i] && xpathObj3->nodesetval->nodeTab[i]->content){ /* fprintf (stderr, "temperature %s\n", xpathObj3->nodesetval->nodeTab[i]->content); */ snprintf(buffer, sizeof(buffer)-1,"%s", xpathObj3->nodesetval->nodeTab[i]->content); memset(temp_buffer, 0, sizeof(temp_buffer)); for (j = 0 ; (j<(strlen(buffer)) && j < buff_size); j++ ){ if (buffer[j] == '&') break; if ((uint)buffer[j] == 226 || buffer[j] == '-' || (buffer[j]>='0' && buffer[j]<='9')){ if ((uint)buffer[j] == 226) sprintf(temp_buffer,"%s-",temp_buffer); else sprintf(temp_buffer,"%s%c",temp_buffer, buffer[j]); } } /* fprintf(stderr, " <temperature>%s</temperature>\n", temp_buffer); */ fprintf(file_out," <temperature_low>%s</temperature_low>\n", temp_buffer); } /* added wind direction */ if (xpathObj4 && !xmlXPathNodeSetIsEmpty(xpathObj4->nodesetval) && xpathObj4->nodesetval->nodeTab[i] && xpathObj4->nodesetval->nodeTab[i]->children->content){ /* fprintf(stderr, "Wind direction %s \n", xpathObj4->nodesetval->nodeTab[i]->children->content); */ fprintf(file_out," <wind_direction>%s</wind_direction>\n", xpathObj4->nodesetval->nodeTab[i]->children->content); } /* added wind speed */ if (xpathObj5 && !xmlXPathNodeSetIsEmpty(xpathObj5->nodesetval) && xpathObj5->nodesetval->nodeTab[i] && xpathObj5->nodesetval->nodeTab[i]->content){ /* fprintf(stderr, "Wind direction %s \n", xpathObj4->nodesetval->nodeTab[i]->children->content); */ fprintf(file_out," <wind_speed>%s</wind_speed>\n", xpathObj5->nodesetval->nodeTab[i]->content); } /* added icon */ if (xpathObj6 && !xmlXPathNodeSetIsEmpty(xpathObj6->nodesetval) && xpathObj6->nodesetval->nodeTab[i] && xpathObj6->nodesetval->nodeTab[i]->children->content){ temp_char = strrchr((char*)xpathObj6->nodesetval->nodeTab[i]->children->content, '/'); temp_char ++; /* fprintf (stderr, "icon %s %s \n", xpathObj6->nodesetval->nodeTab[i]->children->content, choose_hour_weather_icon(hash_for_icons, temp_char)); */ fprintf(file_out," <icon>%s</icon>\n", choose_hour_weather_icon(hash_for_icons, temp_char)); } /* added text */ if (xpathObj7 && !xmlXPathNodeSetIsEmpty(xpathObj7->nodesetval) && xpathObj7->nodesetval->nodeTab[i] && xpathObj7->nodesetval->nodeTab[i]->content){ snprintf(buffer, sizeof(buffer)-1,"%s", xpathObj7->nodesetval->nodeTab[i]->content); memset(temp_buffer, 0, sizeof(temp_buffer)); for (j = 0 ; (j<(strlen(buffer)) && j < buff_size); j++ ){ if (buffer[j] == 13 || buffer[j] == 10) continue; sprintf(temp_buffer,"%s%c",temp_buffer, buffer[j]); } fprintf(file_out," <description>%s</description>\n", temp_buffer); } /* added ppcp */ if (xpathObj8 && !xmlXPathNodeSetIsEmpty(xpathObj8->nodesetval) && xpathObj8->nodesetval->nodeTab[i] && xpathObj8->nodesetval->nodeTab[i]->content){ snprintf(buffer, sizeof(buffer) - 1, "%s", xpathObj8->nodesetval->nodeTab[i]->content); memset(temp_buffer, 0, sizeof(temp_buffer)); for (j = 0 ; (j<(strlen(buffer)) && j < strlen(buffer)); j++ ){ if (buffer[j] == '%') break; if ( (buffer[j]>='0' && buffer[j]<='9')){ sprintf(temp_buffer,"%s%c",temp_buffer, buffer[j]); } } fprintf(file_out," <ppcp>%s</ppcp>\n", temp_buffer); } fprintf(file_out," </period>\n"); } /* Cleanup */ if (xpathObj) xmlXPathFreeObject(xpathObj); if (xpathObj2) xmlXPathFreeObject(xpathObj2); if (xpathObj3) xmlXPathFreeObject(xpathObj3); if (xpathObj4) xmlXPathFreeObject(xpathObj4); if (xpathObj5) xmlXPathFreeObject(xpathObj5); if (xpathObj6) xmlXPathFreeObject(xpathObj6); if (xpathObj7) xmlXPathFreeObject(xpathObj7); if (xpathObj8) xmlXPathFreeObject(xpathObj8); /* Clean */ g_hash_table_destroy(hash_for_icons); fclose(file_out); return size; }
int parse_timestamp(const char *t, usec_t *usec) { static const struct { const char *name; const int nr; } day_nr[] = { { "Sunday", 0 }, { "Sun", 0 }, { "Monday", 1 }, { "Mon", 1 }, { "Tuesday", 2 }, { "Tue", 2 }, { "Wednesday", 3 }, { "Wed", 3 }, { "Thursday", 4 }, { "Thu", 4 }, { "Friday", 5 }, { "Fri", 5 }, { "Saturday", 6 }, { "Sat", 6 }, }; const char *k; const char *utc; struct tm tm, copy; time_t x; usec_t x_usec, plus = 0, minus = 0, ret; int r, weekday = -1; unsigned i; /* * Allowed syntaxes: * * 2012-09-22 16:34:22 * 2012-09-22 16:34 (seconds will be set to 0) * 2012-09-22 (time will be set to 00:00:00) * 16:34:22 (date will be set to today) * 16:34 (date will be set to today, seconds to 0) * now * yesterday (time is set to 00:00:00) * today (time is set to 00:00:00) * tomorrow (time is set to 00:00:00) * +5min * -5days * @2147483647 (seconds since epoch) * */ assert(t); assert(usec); if (t[0] == '@') return parse_sec(t + 1, usec); ret = now(CLOCK_REALTIME); if (streq(t, "now")) goto finish; else if (t[0] == '+') { r = parse_sec(t+1, &plus); if (r < 0) return r; goto finish; } else if (t[0] == '-') { r = parse_sec(t+1, &minus); if (r < 0) return r; goto finish; } else if ((k = endswith(t, " ago"))) { t = strndupa(t, k - t); r = parse_sec(t, &minus); if (r < 0) return r; goto finish; } else if ((k = endswith(t, " left"))) { t = strndupa(t, k - t); r = parse_sec(t, &plus); if (r < 0) return r; goto finish; } utc = endswith_no_case(t, " UTC"); if (utc) t = strndupa(t, utc - t); x = ret / USEC_PER_SEC; x_usec = 0; assert_se(localtime_or_gmtime_r(&x, &tm, utc)); tm.tm_isdst = -1; if (streq(t, "today")) { tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto from_tm; } else if (streq(t, "yesterday")) { tm.tm_mday--; tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto from_tm; } else if (streq(t, "tomorrow")) { tm.tm_mday++; tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto from_tm; } for (i = 0; i < ELEMENTSOF(day_nr); i++) { size_t skip; if (!startswith_no_case(t, day_nr[i].name)) continue; skip = strlen(day_nr[i].name); if (t[skip] != ' ') continue; weekday = day_nr[i].nr; t += skip + 1; break; } copy = tm; k = strptime(t, "%y-%m-%d %H:%M:%S", &tm); if (k) { if (*k == '.') goto parse_usec; else if (*k == 0) goto from_tm; } tm = copy; k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm); if (k) { if (*k == '.') goto parse_usec; else if (*k == 0) goto from_tm; } tm = copy; k = strptime(t, "%y-%m-%d %H:%M", &tm); if (k && *k == 0) { tm.tm_sec = 0; goto from_tm; } tm = copy; k = strptime(t, "%Y-%m-%d %H:%M", &tm); if (k && *k == 0) { tm.tm_sec = 0; goto from_tm; } tm = copy; k = strptime(t, "%y-%m-%d", &tm); if (k && *k == 0) { tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto from_tm; } tm = copy; k = strptime(t, "%Y-%m-%d", &tm); if (k && *k == 0) { tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto from_tm; } tm = copy; k = strptime(t, "%H:%M:%S", &tm); if (k) { if (*k == '.') goto parse_usec; else if (*k == 0) goto from_tm; } tm = copy; k = strptime(t, "%H:%M", &tm); if (k && *k == 0) { tm.tm_sec = 0; goto from_tm; } return -EINVAL; parse_usec: { unsigned add; k++; r = parse_fractional_part_u(&k, 6, &add); if (r < 0) return -EINVAL; if (*k) return -EINVAL; x_usec = add; } from_tm: x = mktime_or_timegm(&tm, utc); if (x == (time_t) -1) return -EINVAL; if (weekday >= 0 && tm.tm_wday != weekday) return -EINVAL; ret = (usec_t) x * USEC_PER_SEC + x_usec; finish: ret += plus; if (ret > minus) ret -= minus; else ret = 0; *usec = ret; return 0; }
int cgiMain() { static char title[] = "List of existing Certificates"; char sorting[16] = "desc"; char certfilestr[225] = ""; FILE *certfile = NULL; BIO *membio = NULL; BIO *outbio = NULL; char membio_buf[128] = ""; X509 *cert = NULL; X509_NAME *certsubject = NULL; ASN1_TIME *start_date = NULL; ASN1_TIME *expiration_date = NULL; struct tm start_tm; struct tm expiration_tm; time_t now = time(NULL); time_t start = time(NULL); time_t expiration = time(NULL); double available_secs = 0; double remaining_secs = 0; struct dirent **certstore_files = NULL; int pagenumber = 1; int certcounter = 0; int tempcounter = 0; int pagecounter = 0; int dispcounter = 0; int dispmaxlines = 0; int certvalidity = 0; div_t disp_calc; div_t oddline_calc; double percent = 0; cert = X509_new(); certsubject = X509_NAME_new(); /* -------------------------------------------------------------------------- * * Get the list of .pem files from the cert directory * * ---------------------------------------------------------------------------*/ certcounter = scandir(CACERTSTORE, &certstore_files, file_select, hexsort); if(certcounter<=0) int_error("Error: No certificate files found."); /* -------------------------------------------------------------------------- * * calculate how many pages we get with MAXCERTDISPLAY * * ---------------------------------------------------------------------------*/ if(certcounter<=MAXCERTDISPLAY) pagecounter = 1; else { disp_calc = div(certcounter, MAXCERTDISPLAY); /* if the count of certs divided by MAXCERTDISPLAY has no remainder */ if(disp_calc.rem == 0) pagecounter = disp_calc.quot; /* with a remainder, we must prepare an extra page for the rest */ else pagecounter = disp_calc.quot +1; } /* -------------------------------------------------------------------------- * * Check if we have been subsequently called with a pagenumber & sort request * * ---------------------------------------------------------------------------*/ if(cgiFormInteger("page", &pagenumber, 1) == cgiFormSuccess) if(pagenumber > pagecounter || pagenumber <=0) int_error("Error: Page does not exist."); if(cgiFormString("sort", sorting, sizeof(sorting)) != cgiFormSuccess) strncpy(sorting, "desc", sizeof(sorting)); /* -------------------------------------------------------------------------- * * now we know how many certs we have in total and we can build the page(s). * * For every MAXCERTDISPLAY certs we start a new page and cycle through by * * calling ourself with the requested certs in range. * * ---------------------------------------------------------------------------*/ if(strcmp(sorting, "asc") == 0) { if(certcounter <= MAXCERTDISPLAY) { dispmaxlines = certcounter; tempcounter = 0; } else if(pagenumber == pagecounter && ( pagecounter * MAXCERTDISPLAY) - certcounter != 0) { tempcounter = (pagecounter * MAXCERTDISPLAY) - MAXCERTDISPLAY; dispmaxlines = certcounter - ((pagecounter-1) * MAXCERTDISPLAY); } else { tempcounter = (pagenumber * MAXCERTDISPLAY) - MAXCERTDISPLAY; dispmaxlines = MAXCERTDISPLAY; } } if(strcmp(sorting, "desc") == 0) { if(certcounter <= MAXCERTDISPLAY) { dispmaxlines = certcounter; tempcounter = certcounter; } else if(pagenumber == pagecounter && ( pagecounter * MAXCERTDISPLAY) - certcounter != 0) { tempcounter = certcounter - ((pagecounter-1) * MAXCERTDISPLAY); dispmaxlines = certcounter - ((pagecounter-1) * MAXCERTDISPLAY); } else { tempcounter = certcounter - (pagenumber*MAXCERTDISPLAY) + MAXCERTDISPLAY; dispmaxlines = MAXCERTDISPLAY; } } /* -------------------------------------------------------------------------- * * start the html output * * ---------------------------------------------------------------------------*/ outbio = BIO_new(BIO_s_file()); BIO_set_fp(outbio, cgiOut, BIO_NOCLOSE); pagehead(title); //debugging only: //printf("Number of certs: %d\n", certcounter); //printf("Num tempcounter: %d\n", tempcounter); //printf("Number of pages: %d\n", pagecounter); //printf("Div Quotient: %d\n", disp_calc.quot); //printf("Div Remainder: %d\n", disp_calc.rem); //fprintf(cgiOut, "</BODY></HTML>\n"); //exit(0); /* -------------------------------------------------------------------------- * * start the form output * * ---------------------------------------------------------------------------*/ fprintf(cgiOut, "<table>\n"); fprintf(cgiOut, "<tr>\n"); fprintf(cgiOut, "<th width=\"20\">"); fprintf(cgiOut, "#"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "<th width=\"495\">"); fprintf(cgiOut, "Certificate Subject Information"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "<th colspan=\"2\" width=\"60\">"); fprintf(cgiOut, "Expiry"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "<th width=\"65\">"); fprintf(cgiOut, "Action"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "</tr>\n"); for(dispcounter=0; dispcounter < dispmaxlines; dispcounter++) { /* zero certificate values and flags */ certvalidity = 0; percent = 0; available_secs = 0; remaining_secs = 0; cert = X509_new(); certsubject = X509_NAME_new(); if(strcmp(sorting, "desc") == 0) tempcounter--; snprintf(certfilestr, sizeof(certfilestr), "%s/%s", CACERTSTORE, certstore_files[tempcounter]->d_name); fprintf(cgiOut, "<tr>\n"); fprintf(cgiOut, "<th rowspan=\"2\">"); fprintf(cgiOut, "%d", tempcounter+1); fprintf(cgiOut, "</th>\n"); oddline_calc = div(tempcounter+1, 2); if(oddline_calc.rem) fprintf(cgiOut, "<td rowspan=\"2\" class=\"odd\">"); else fprintf(cgiOut, "<td rowspan=\"2\" class=\"even\">"); if ( (certfile = fopen(certfilestr, "r")) != NULL) { PEM_read_X509(certfile, &cert, NULL, NULL); certsubject = X509_get_subject_name(cert); /* display the subject data, use the UTF-8 flag to show * * Japanese Kanji, also needs the separator flag to work */ X509_NAME_print_ex_fp(cgiOut, certsubject, 0, ASN1_STRFLGS_UTF8_CONVERT|XN_FLAG_SEP_CPLUS_SPC); /* store certificate start date for later eval */ start_date = X509_get_notBefore(cert); /* store certificate expiration date for later eval */ expiration_date = X509_get_notAfter(cert); /* check the start and end dates in the cert */ if (X509_cmp_current_time (X509_get_notBefore (cert)) >= 0) /* flag the certificate as not valid yet */ certvalidity = 0; else if (X509_cmp_current_time (X509_get_notAfter (cert)) <= 0) /* flag the certificate as expired */ certvalidity = 0; else /* flag the certificate is still valid */ certvalidity = 1; fclose(certfile); } else fprintf(cgiOut, "Error: Can't open certificate file %s for reading.", certfilestr); fprintf(cgiOut, "</td>\n"); if(certvalidity == 0) { /* expiration bar display column */ fprintf(cgiOut, "<th rowspan=\"2\">\n"); fprintf(cgiOut, "<table class=\"led\">\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, "</table>\n"); fprintf(cgiOut, "</th>\n"); /* remaining days before expiration column */ fprintf(cgiOut, "<th class=\"exnok\" rowspan=\"2\">\n"); fprintf(cgiOut, "Inval<br />Expd"); fprintf(cgiOut, "</th>\n"); } if(certvalidity == 1) { /* ------ START get the certificate lifetime in seconds ------ */ /* copy the start date into a string */ membio = BIO_new(BIO_s_mem()); ASN1_TIME_print(membio, start_date); BIO_gets(membio, membio_buf, sizeof(membio_buf)); BIO_free(membio); /* parse the start date string into a time struct */ memset (&start_tm, '\0', sizeof(start_tm)); strptime(membio_buf, "%h %d %T %Y %z", &start_tm); start = mktime(&start_tm); /* ------ START get the certificate remaining time in seconds ------ */ /* copy the expiration date into a string */ membio = BIO_new(BIO_s_mem()); ASN1_TIME_print(membio, expiration_date); BIO_gets(membio, membio_buf, sizeof(membio_buf)); BIO_free(membio); /* parse the expiration date string into a time struct */ memset (&expiration_tm, '\0', sizeof(expiration_tm)); strptime(membio_buf, "%h %d %T %Y %z", &expiration_tm); /* get the current time */ now = time(NULL); expiration = mktime(&expiration_tm); /* get the time difference between expiration time and current time */ remaining_secs = difftime(expiration, now); /* ------ END get the certificate remaining time in seconds ------ */ /* get the time difference between start and expiration time */ available_secs = difftime(expiration, start); /* ------ END get the certificate lifetime in seconds ------ */ /* ------ START calculate percentage of lifetime left ------ */ /* remaining_secs *100 */ /* ------------------- = X, rounded down with floor() */ /* available_secs */ percent = floor((remaining_secs*100)/available_secs); /* ------ END calculate percentage of lifetime left ------ */ /* expiration bar display column */ fprintf(cgiOut, "<th rowspan=\"2\">\n"); fprintf(cgiOut, "<table class=\"led\">\n"); if (percent >= 90) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#00FF00\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 80) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#00FF33\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 70) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#99FF33\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 60) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#FFFF00\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 50) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#FFCC00\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 40) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#FF9900\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 30) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#FF6600\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 20) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#FF3300\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); if (percent >= 10) fprintf(cgiOut, " <tr><td class=\"led\" bgcolor=\"#FF0000\"></td></tr>\n"); else fprintf(cgiOut, " <tr><td class=\"led-off\"></td></tr>\n"); fprintf(cgiOut, "</table>\n"); fprintf(cgiOut, "</th>\n"); /* remaining days before expiration column */ //fprintf(cgiOut, membio_buf); if (percent < 10) fprintf(cgiOut, "<th class=\"exnok\" rowspan=\"2\">\n"); else fprintf(cgiOut, "<th class=\"exok\" rowspan=\"2\">\n"); if(floor(remaining_secs/63072000) > 0) fprintf(cgiOut, "%.f<br />years", remaining_secs/31536000); else if(floor(remaining_secs/86400) > 0 ) fprintf(cgiOut, "%.f<br />days", remaining_secs/86400); else if(floor(remaining_secs/3600) > 0 ) fprintf(cgiOut, "%.f<br />hours", remaining_secs/3600); else if(floor(remaining_secs/60) > 0 ) fprintf(cgiOut, "%.f<br />mins", remaining_secs/60); else fprintf(cgiOut, "%.f<br />secs", remaining_secs); fprintf(cgiOut, "</th>\n"); } /* action column */ fprintf(cgiOut, "<th>"); fprintf(cgiOut, "<form action=\"getcert.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"cfilename\" "); fprintf(cgiOut, "value=\"%s\" />\n", certstore_files[tempcounter]->d_name); fprintf(cgiOut, "<input type=\"hidden\" name=\"format\" value=\"text\" />\n"); fprintf(cgiOut, "<input class=\"getcert\" type=\"submit\" value=\"Detail\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "</tr>\n"); fprintf(cgiOut, "<tr>\n"); fprintf(cgiOut, "<th>\n"); fprintf(cgiOut, "<form action=\"certrenew.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"cert-renew\" "); fprintf(cgiOut, "value=\""); PEM_write_bio_X509(outbio, cert); fprintf(cgiOut, "\" />\n"); fprintf(cgiOut, "<input class=\"getcert\" type=\"submit\" value=\"Renew\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "</tr>\n"); if(strcmp(sorting, "asc") == 0) tempcounter++; } fprintf(cgiOut, "<tr>\n"); fprintf(cgiOut, "<th colspan=\"5\">"); fprintf(cgiOut, "Total # of certs: %d | ", certcounter); fprintf(cgiOut, "Page %d of %d", pagenumber, pagecounter); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "</tr>\n"); fprintf(cgiOut, "</table>\n"); fprintf(cgiOut, "<p></p>\n"); fprintf(cgiOut, "<table>\n"); fprintf(cgiOut, "<tr>\n"); fprintf(cgiOut, "<th>\n"); fprintf(cgiOut, "<form action=\"certstore.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"sort\" "); fprintf(cgiOut, "value=\"desc\" />\n"); fprintf(cgiOut, "<input type=\"submit\" name=\"sort\""); fprintf(cgiOut, " value=\"Latest Certs first\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "<th>\n"); fprintf(cgiOut, "<form action=\"certstore.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"sort\" "); fprintf(cgiOut, "value=\"asc\" />\n"); fprintf(cgiOut, "<input type=\"submit\" name=\"sort\""); fprintf(cgiOut, " value=\"Oldest Certs first\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); // filler 1 fprintf(cgiOut, "<th width=\"15\">"); fprintf(cgiOut, " "); fprintf(cgiOut, "</th>\n"); // goto page 1 fprintf(cgiOut, "<th width=\"5\">\n"); fprintf(cgiOut, "<form action=\"certstore.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"submit\" value=\"<<\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); // goto page before fprintf(cgiOut, "<th width=\"5\">\n"); fprintf(cgiOut, "<form action=\"certstore.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" "); fprintf(cgiOut, "value=\"%d\" />\n", certcounter); fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" "); fprintf(cgiOut, "value=\"%d\" />\n", pagecounter); fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" "); fprintf(cgiOut, "value=\""); tempcounter = 0; if(pagenumber > 1) tempcounter = pagenumber - 1; else tempcounter = 1; fprintf(cgiOut, "%d", tempcounter); fprintf(cgiOut, "\" />\n"); fprintf(cgiOut, "<input type=\"submit\" value=\"< 1\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); // goto page after fprintf(cgiOut, "<th width=\"5\">\n"); fprintf(cgiOut, "<form action=\"certstore.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" "); fprintf(cgiOut, "value=\"%d\" />\n", certcounter); fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" "); fprintf(cgiOut, "value=\"%d\" />\n", pagecounter); fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" "); fprintf(cgiOut, "value=\""); tempcounter = 0; if(pagecounter > pagenumber) tempcounter = pagenumber + 1; else tempcounter = pagecounter; fprintf(cgiOut, "%d", tempcounter); fprintf(cgiOut, "\" />\n"); fprintf(cgiOut, "<input type=\"submit\" value=\"1 >\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); // goto last page fprintf(cgiOut, "<th width=\"5\">\n"); fprintf(cgiOut, "<form action=\"certstore.cgi\" method=\"post\">"); fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" "); fprintf(cgiOut, "value=\"%d\" />\n", certcounter); fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" "); fprintf(cgiOut, "value=\"%d\" />\n", pagecounter); fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" "); fprintf(cgiOut, "value=\"%d\" />\n", pagecounter); fprintf(cgiOut, "<input type=\"submit\" value=\">>\" />\n"); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); // goto page number fprintf(cgiOut, "<th width=\"120\">\n"); fprintf(cgiOut, "<form class=\"setpage\" action=\"certstore.cgi\" method=\"post\">\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" "); fprintf(cgiOut, "value=\""); fprintf(cgiOut, "%d", certcounter); fprintf(cgiOut, "\" />\n"); fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" "); fprintf(cgiOut, "value=\""); fprintf(cgiOut, "%d", pagecounter); fprintf(cgiOut, "\" />\n"); fprintf(cgiOut, "<input class=\"goto\" type=\"submit\" value=\"Goto\" />\n"); fprintf(cgiOut, "<input class=\"page\" type=\"text\" name=\"page\" "); fprintf(cgiOut, "value=\"%d\" />\n", pagecounter); fprintf(cgiOut, "</form>\n"); fprintf(cgiOut, "</th>\n"); fprintf(cgiOut, "</tr>\n"); fprintf(cgiOut, "</table>\n"); /* ---------------------------------------------------------------------------* * end the html output * * ---------------------------------------------------------------------------*/ pagefoot(); BIO_free(outbio); return(0); }
int http_response_handle_cachable(server *srv, connection *con, buffer *mtime, buffer *etag) { data_string *http_if_none_match; data_string *http_if_modified_since; UNUSED(srv); /* * 14.26 If-None-Match * [...] * If none of the entity tags match, then the server MAY perform the * requested method as if the If-None-Match header field did not exist, * but MUST also ignore any If-Modified-Since header field(s) in the * request. That is, if no entity tags match, then the server MUST NOT * return a 304 (Not Modified) response. */ http_if_none_match = (data_string *)array_get_element(con->request.headers, CONST_STR_LEN("if-none-match")); http_if_modified_since = (data_string *)array_get_element(con->request.headers, CONST_STR_LEN("if-modified-since")); /* last-modified handling */ if (http_if_none_match) { if (etag_is_equal(etag, BUF_STR(http_if_none_match->value))) { if (con->request.http_method == HTTP_METHOD_GET || con->request.http_method == HTTP_METHOD_HEAD) { /* check if etag + last-modified */ if (http_if_modified_since) { size_t used_len; char *semicolon; if (NULL == (semicolon = strchr(BUF_STR(http_if_modified_since->value), ';'))) { used_len = http_if_modified_since->value->used - 1; } else { used_len = semicolon - BUF_STR(http_if_modified_since->value); } if (0 == strncmp(BUF_STR(http_if_modified_since->value), mtime->ptr, used_len)) { if ('\0' == mtime->ptr[used_len]) con->http_status = 304; return HANDLER_FINISHED; } else { #ifdef HAVE_STRPTIME char buf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")]; time_t t_header, t_file; struct tm tm; /* check if we can safely copy the string */ if (used_len >= sizeof(buf)) { TRACE("last-mod check failed as timestamp was too long: %s: %zu, %zu", SAFE_BUF_STR(http_if_modified_since->value), used_len, sizeof(buf) - 1); con->http_status = 412; return HANDLER_FINISHED; } strncpy(buf, BUF_STR(http_if_modified_since->value), used_len); buf[used_len] = '\0'; if (NULL == strptime(buf, "%a, %d %b %Y %H:%M:%S GMT", &tm)) { con->http_status = 412; return HANDLER_FINISHED; } tm.tm_isdst = 0; t_header = mktime(&tm); strptime(mtime->ptr, "%a, %d %b %Y %H:%M:%S GMT", &tm); tm.tm_isdst = 0; t_file = mktime(&tm); if (t_file > t_header) return HANDLER_GO_ON; con->http_status = 304; return HANDLER_FINISHED; #else return HANDLER_GO_ON; #endif } } else { con->http_status = 304; return HANDLER_FINISHED; } } else { con->http_status = 412; return HANDLER_FINISHED; } } } else if (http_if_modified_since) { size_t used_len; char *semicolon; if (NULL == (semicolon = strchr(BUF_STR(http_if_modified_since->value), ';'))) { used_len = http_if_modified_since->value->used - 1; } else { used_len = semicolon - BUF_STR(http_if_modified_since->value); } if (0 == strncmp(BUF_STR(http_if_modified_since->value), mtime->ptr, used_len)) { if ('\0' == mtime->ptr[used_len]) con->http_status = 304; return HANDLER_FINISHED; } else { #ifdef HAVE_STRPTIME char buf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")]; time_t t_header, t_file; struct tm tm; /* convert to timestamp */ if (used_len >= sizeof(buf)) return HANDLER_GO_ON; strncpy(buf, BUF_STR(http_if_modified_since->value), used_len); buf[used_len] = '\0'; if (NULL == strptime(buf, "%a, %d %b %Y %H:%M:%S GMT", &tm)) { return HANDLER_GO_ON; } tm.tm_isdst = 0; t_header = mktime(&tm); strptime(mtime->ptr, "%a, %d %b %Y %H:%M:%S GMT", &tm); tm.tm_isdst = 0; t_file = mktime(&tm); if (t_file > t_header) return HANDLER_GO_ON; con->http_status = 304; return HANDLER_FINISHED; #else return HANDLER_GO_ON; #endif } } return HANDLER_GO_ON; }
/** * Analyzes a file and copies it if it contains image data. * @param fpath The filename of the current entry. * @param sb A pointer to the stat structure. * @param typeflag The current entry type. */ static int _ftw_callback(char const* fpath, struct stat const* sb, int typeflag) { int rc; ExifData* exif_data; ExifEntry* exif_entry; char exif_entry_val[20]; struct tm tm; // The current entry is not a file. Skip it. if (!S_ISREG(sb->st_mode)) { return 0; } // The current entry has no EXIF data. Skip it. exif_data = exif_data_new_from_file(fpath); if (exif_data == NULL) { return 0; } rc = 0; exif_entry = exif_content_get_entry(*(exif_data->ifd), EXIF_TAG_DATE_TIME); if (exif_entry != NULL && exif_entry_get_value(exif_entry, exif_entry_val, 20) != NULL && strptime(exif_entry_val, "%Y:%m:%d %H:%M:%S", &tm) != 0) { size_t dst_size; char* dst; dst_size = strlen(_DST) + 12; dst = (char*) malloc(dst_size); // Create the destination path. if (snprintf(dst, dst_size, "%s/%d/%02d/%02d", _DST, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday) >= 0 && _mkdir_recursive(dst) == 0) { size_t offset; char* dst_fpath; offset = strlen(fpath); while (offset > 0 && fpath[offset - 1] != '/') { --offset; } // Copy the file. dst_fpath = (char*) malloc(strlen(dst) + strlen(fpath + offset) + 2); sprintf(dst_fpath, "%s/%s", dst, fpath + offset); rc = _cp(dst_fpath, fpath); free(dst_fpath); if (rc == -1 && errno == EEXIST) { rc = 0; } } free(dst); } exif_data_unref(exif_data); return rc; }
char * strptime(const char *buf, const char *fmt, struct tm *tm) { unsigned char c; const unsigned char *bp, *ep; int alt_format, i, split_year = 0, neg = 0, offs; const char *new_fmt; bp = (const u_char *)buf; while (bp != NULL && (c = *fmt++) != '\0') { /* Clear `alternate' modifier prior to new conversion. */ alt_format = 0; i = 0; /* Eat up white-space. */ if (isspace(c)) { while (isspace(*bp)) bp++; continue; } if (c != '%') goto literal; again: switch (c = *fmt++) { case '%': /* "%%" is converted to "%". */ literal: if (c != *bp++) return NULL; LEGAL_ALT(0); continue; /* * "Alternative" modifiers. Just set the appropriate flag * and start over again. */ case 'E': /* "%E?" alternative conversion modifier. */ LEGAL_ALT(0); alt_format |= ALT_E; goto again; case 'O': /* "%O?" alternative conversion modifier. */ LEGAL_ALT(0); alt_format |= ALT_O; goto again; /* * "Complex" conversion rules, implemented through recursion. */ #ifdef _ctloc case 'c': /* Date and time, using the locale's format. */ new_fmt = _ctloc(d_t_fmt); goto recurse; #endif case 'D': /* The date as "%m/%d/%y". */ new_fmt = "%m/%d/%y"; LEGAL_ALT(0); goto recurse; case 'F': /* The date as "%Y-%m-%d". */ new_fmt = "%Y-%m-%d"; LEGAL_ALT(0); goto recurse; case 'R': /* The time as "%H:%M". */ new_fmt = "%H:%M"; LEGAL_ALT(0); goto recurse; #ifdef _ctloc case 'r': /* The time in 12-hour clock representation. */ new_fmt =_ctloc(t_fmt_ampm); LEGAL_ALT(0); goto recurse; #endif case 'T': /* The time as "%H:%M:%S". */ new_fmt = "%H:%M:%S"; LEGAL_ALT(0); goto recurse; #ifdef _ctloc case 'X': /* The time, using the locale's format. */ new_fmt =_ctloc(t_fmt); goto recurse; #endif #ifdef _ctloc case 'x': /* The date, using the locale's format. */ new_fmt =_ctloc(d_fmt); #endif recurse: bp = (const u_char *)strptime((const char *)bp, new_fmt, tm); LEGAL_ALT(ALT_E); continue; /* * "Elementary" conversion rules. */ case 'A': /* The day of week, using the locale's form. */ case 'a': bp = find_string(bp, &tm->tm_wday, LOCALE_DAY, LOCALE_ABDAY, 7); LEGAL_ALT(0); continue; case 'B': /* The month, using the locale's form. */ case 'b': case 'h': bp = find_string(bp, &tm->tm_mon, LOCALE_MON, LOCALE_ABMON, 12); LEGAL_ALT(0); continue; case 'C': /* The century number. */ i = 20; bp = conv_num(bp, &i, 0, 99); i = i * 100 - TM_YEAR_BASE; if (split_year) i += tm->tm_year % 100; split_year = 1; tm->tm_year = i; LEGAL_ALT(ALT_E); continue; case 'd': /* The day of month. */ case 'e': bp = conv_num(bp, &tm->tm_mday, 1, 31); LEGAL_ALT(ALT_O); continue; case 'k': /* The hour (24-hour clock representation). */ LEGAL_ALT(0); /* FALLTHROUGH */ case 'H': bp = conv_num(bp, &tm->tm_hour, 0, 23); LEGAL_ALT(ALT_O); continue; case 'l': /* The hour (12-hour clock representation). */ LEGAL_ALT(0); /* FALLTHROUGH */ case 'I': bp = conv_num(bp, &tm->tm_hour, 1, 12); if (tm->tm_hour == 12) tm->tm_hour = 0; LEGAL_ALT(ALT_O); continue; case 'j': /* The day of year. */ i = 1; bp = conv_num(bp, &i, 1, 366); tm->tm_yday = i - 1; LEGAL_ALT(0); continue; case 'M': /* The minute. */ bp = conv_num(bp, &tm->tm_min, 0, 59); LEGAL_ALT(ALT_O); continue; case 'm': /* The month. */ i = 1; bp = conv_num(bp, &i, 1, 12); tm->tm_mon = i - 1; LEGAL_ALT(ALT_O); continue; #ifdef _ctloc case 'p': /* The locale's equivalent of AM/PM. */ bp = find_string(bp, &i, _ctloc(am_pm), NULL, 2); if (tm->tm_hour > 11) return NULL; tm->tm_hour += i * 12; LEGAL_ALT(0); continue; #endif case 'S': /* The seconds. */ bp = conv_num(bp, &tm->tm_sec, 0, 61); LEGAL_ALT(ALT_O); continue; #ifndef TIME_MAX #define TIME_MAX INT64_MAX #endif #ifdef _ctloc case 's': /* seconds since the epoch */ { time_t sse = 0; uint64_t rulim = TIME_MAX; if (*bp < '0' || *bp > '9') { bp = NULL; continue; } do { sse *= 10; sse += *bp++ - '0'; rulim /= 10; } while ((sse * 10 <= TIME_MAX) && rulim && *bp >= '0' && *bp <= '9'); if (sse < 0 || (uint64_t)sse > TIME_MAX) { bp = NULL; continue; } if (localtime_r(&sse, tm) == NULL) bp = NULL; } continue; #endif case 'U': /* The week of year, beginning on sunday. */ case 'W': /* The week of year, beginning on monday. */ /* * XXX This is bogus, as we can not assume any valid * information present in the tm structure at this * point to calculate a real value, so just check the * range for now. */ bp = conv_num(bp, &i, 0, 53); LEGAL_ALT(ALT_O); continue; case 'w': /* The day of week, beginning on sunday. */ bp = conv_num(bp, &tm->tm_wday, 0, 6); LEGAL_ALT(ALT_O); continue; case 'u': /* The day of week, monday = 1. */ bp = conv_num(bp, &i, 1, 7); tm->tm_wday = i % 7; LEGAL_ALT(ALT_O); continue; case 'g': /* The year corresponding to the ISO week * number but without the century. */ bp = conv_num(bp, &i, 0, 99); continue; case 'G': /* The year corresponding to the ISO week * number with century. */ do bp++; while (isdigit(*bp)); continue; case 'V': /* The ISO 8601:1988 week number as decimal */ bp = conv_num(bp, &i, 0, 53); continue; case 'Y': /* The year. */ i = TM_YEAR_BASE; /* just for data sanity... */ bp = conv_num(bp, &i, 0, 9999); tm->tm_year = i - TM_YEAR_BASE; LEGAL_ALT(ALT_E); continue; case 'y': /* The year within 100 years of the epoch. */ /* LEGAL_ALT(ALT_E | ALT_O); */ bp = conv_num(bp, &i, 0, 99); if (split_year) /* preserve century */ i += (tm->tm_year / 100) * 100; else { split_year = 1; if (i <= 68) i = i + 2000 - TM_YEAR_BASE; else i = i + 1900 - TM_YEAR_BASE; } tm->tm_year = i; continue; case 'Z': _tzset(); if (strncmp((const char *)bp, gmt, 3) == 0) { tm->tm_isdst = 0; #ifdef TM_GMTOFF tm->TM_GMTOFF = 0; #endif #ifdef TM_ZONE tm->TM_ZONE = gmt; #endif bp += 3; } else { ep = find_string(bp, &i, (const char * const *)tzname, NULL, 2); if (ep != NULL) { tm->tm_isdst = i; #ifdef TM_GMTOFF tm->TM_GMTOFF = -(timezone); #endif #ifdef TM_ZONE tm->TM_ZONE = tzname[i]; #endif } bp = ep; } continue; case 'z': /* * We recognize all ISO 8601 formats: * Z = Zulu time/UTC * [+-]hhmm * [+-]hh:mm * [+-]hh * We recognize all RFC-822/RFC-2822 formats: * UT|GMT * North American : UTC offsets * E[DS]T = Eastern : -4 | -5 * C[DS]T = Central : -5 | -6 * M[DS]T = Mountain: -6 | -7 * P[DS]T = Pacific : -7 | -8 * Military * [A-IL-M] = -1 ... -9 (J not used) * [N-Y] = +1 ... +12 */ while (isspace(*bp)) bp++; switch (*bp++) { case 'G': if (*bp++ != 'M') return NULL; /*FALLTHROUGH*/ case 'U': if (*bp++ != 'T') return NULL; /*FALLTHROUGH*/ case 'Z': tm->tm_isdst = 0; #ifdef TM_GMTOFF tm->TM_GMTOFF = 0; #endif #ifdef TM_ZONE tm->TM_ZONE = utc; #endif continue; case '+': neg = 0; break; case '-': neg = 1; break; default: --bp; ep = find_string(bp, &i, nast, NULL, 4); if (ep != NULL) { #ifdef TM_GMTOFF tm->TM_GMTOFF = -5 - i; #endif #ifdef TM_ZONE tm->TM_ZONE = __UNCONST(nast[i]); #endif bp = ep; continue; } ep = find_string(bp, &i, nadt, NULL, 4); if (ep != NULL) { tm->tm_isdst = 1; #ifdef TM_GMTOFF tm->TM_GMTOFF = -4 - i; #endif #ifdef TM_ZONE tm->TM_ZONE = __UNCONST(nadt[i]); #endif bp = ep; continue; } if ((*bp >= 'A' && *bp <= 'I') || (*bp >= 'L' && *bp <= 'Y')) { #ifdef TM_GMTOFF /* Argh! No 'J'! */ if (*bp >= 'A' && *bp <= 'I') tm->TM_GMTOFF = ('A' - 1) - (int)*bp; else if (*bp >= 'L' && *bp <= 'M') tm->TM_GMTOFF = 'A' - (int)*bp; else if (*bp >= 'N' && *bp <= 'Y') tm->TM_GMTOFF = (int)*bp - 'M'; #endif #ifdef TM_ZONE tm->TM_ZONE = NULL; /* XXX */ #endif bp++; continue; } return NULL; } offs = 0; for (i = 0; i < 4; ) { if (isdigit(*bp)) { offs = offs * 10 + (*bp++ - '0'); i++; continue; } if (i == 2 && *bp == ':') { bp++; continue; } break; } switch (i) { case 2: offs *= 100; break; case 4: i = offs % 100; if (i >= 60) return NULL; /* Convert minutes into decimal */ offs = (offs / 100) * 100 + (i * 50) / 30; break; default: return NULL; } if (neg) offs = -offs; tm->tm_isdst = 0; /* XXX */ #ifdef TM_GMTOFF tm->TM_GMTOFF = offs; #endif #ifdef TM_ZONE tm->TM_ZONE = NULL; /* XXX */ #endif continue; /* * Miscellaneous conversions. */ case 'n': /* Any kind of white-space. */ case 't': while (isspace(*bp)) bp++; LEGAL_ALT(0); continue; default: /* Unknown/unsupported conversion. */ return NULL; } } return (char*) bp; }
/* extern "C" */ char * /* strptime (const char *buf, const char *format, struct tm *timeptr) */ strptime (const char *buf, const char *format, struct tm *timeptr) { char c; for (; (c = *format) != '\0'; ++format) { char *s; int ret; if (isspace (c)) { while (isspace (*buf)) ++buf; } else if (c == '%' && format[1] != '\0') { c = *++format; if (c == 'E' || c == 'O') c = *++format; switch (c) { case 'A' : ret = match_string (&buf, full_weekdays); if (ret < 0) return NULL; timeptr->tm_wday = ret; break; case 'a' : ret = match_string (&buf, abb_weekdays); if (ret < 0) return NULL; timeptr->tm_wday = ret; break; case 'B' : ret = match_string (&buf, full_month); if (ret < 0) return NULL; timeptr->tm_mon = ret; break; case 'b' : case 'h' : ret = match_string (&buf, abb_month); if (ret < 0) return NULL; timeptr->tm_mon = ret; break; case 'C' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_year = (ret * 100) - tm_year_base; buf = s; break; case 'c' : abort (); case 'D' : /* %m/%d/%y */ s = strptime (buf, "%m/%d/%y", timeptr); if (s == NULL) return NULL; buf = s; break; case 'd' : case 'e' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_mday = ret; buf = s; break; case 'H' : case 'k' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_hour = ret; buf = s; break; case 'I' : case 'l' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; if (ret == 12) timeptr->tm_hour = 0; else timeptr->tm_hour = ret; buf = s; break; case 'j' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_yday = ret - 1; buf = s; break; case 'm' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_mon = ret - 1; buf = s; break; case 'M' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_min = ret; buf = s; break; case 'n' : if (*buf == '\n') ++buf; else return NULL; break; case 'p' : ret = match_string (&buf, ampm); if (ret < 0) return NULL; if (timeptr->tm_hour == 0) { if (ret == 1) timeptr->tm_hour = 12; } else timeptr->tm_hour += 12; break; case 'r' : /* %I:%M:%S %p */ s = strptime (buf, "%I:%M:%S %p", timeptr); if (s == NULL) return NULL; buf = s; break; case 'R' : /* %H:%M */ s = strptime (buf, "%H:%M", timeptr); if (s == NULL) return NULL; buf = s; break; case 'S' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_sec = ret; buf = s; break; case 't' : if (*buf == '\t') ++buf; else return NULL; break; case 'T' : /* %H:%M:%S */ case 'X' : s = strptime (buf, "%H:%M:%S", timeptr); if (s == NULL) return NULL; buf = s; break; case 'u' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_wday = ret - 1; buf = s; break; case 'w' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_wday = ret; buf = s; break; case 'U' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; set_week_number_sun (timeptr, ret); buf = s; break; case 'V' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; set_week_number_mon4 (timeptr, ret); buf = s; break; case 'W' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; set_week_number_mon (timeptr, ret); buf = s; break; case 'x' : s = strptime (buf, "%Y:%m:%d", timeptr); if (s == NULL) return NULL; buf = s; break; case 'y' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; if (ret < 70) timeptr->tm_year = 100 + ret; else timeptr->tm_year = ret; buf = s; break; case 'Y' : ret = strtol (buf, &s, 10); if (s == buf) return NULL; timeptr->tm_year = ret - tm_year_base; buf = s; break; case 'Z' : abort (); case '\0' : --format; /* FALLTHROUGH */ case '%' : if (*buf == '%') ++buf; else return NULL; break; default : if (*buf == '%' || *++buf == c) ++buf; else return NULL; break; } } else { if (*buf == c) ++buf; else return NULL; } } return (char *)buf; }
/* convert a filename from a share relative path, to a path in the snapshot directory */ static char *convert_shadow2_name(vfs_handle_struct *handle, const char *fname, const char *gmt_path) { TALLOC_CTX *tmp_ctx = talloc_new(handle->data); const char *snapdir, *relpath, *baseoffset, *basedir; size_t baselen; char *ret; struct tm timestamp; time_t timestamp_t; char snapshot[MAXPATHLEN]; const char *fmt; fmt = lp_parm_const_string(SNUM(handle->conn), "shadow", "format", SHADOW_COPY2_DEFAULT_FORMAT); snapdir = shadow_copy2_find_snapdir(tmp_ctx, handle); if (snapdir == NULL) { DEBUG(2,("no snapdir found for share at %s\n", handle->conn->connectpath)); talloc_free(tmp_ctx); return NULL; } basedir = shadow_copy2_find_basedir(tmp_ctx, handle); if (basedir == NULL) { DEBUG(2,("no basedir found for share at %s\n", handle->conn->connectpath)); talloc_free(tmp_ctx); return NULL; } if (strncmp(fname, "@GMT-", 5) != 0) { fname = shadow_copy2_normalise_path(tmp_ctx, fname, gmt_path); if (fname == NULL) { talloc_free(tmp_ctx); return NULL; } } ZERO_STRUCT(timestamp); relpath = strptime(fname, SHADOW_COPY2_GMT_FORMAT, ×tamp); if (relpath == NULL) { talloc_free(tmp_ctx); return NULL; } /* relpath is the remaining portion of the path after the @GMT-xxx */ if (lp_parm_bool(SNUM(handle->conn), "shadow", "localtime", SHADOW_COPY2_DEFAULT_LOCALTIME)) { timestamp_t = timegm(×tamp); localtime_r(×tamp_t, ×tamp); } strftime(snapshot, MAXPATHLEN, fmt, ×tamp); baselen = strlen(basedir); baseoffset = handle->conn->connectpath + baselen; /* some sanity checks */ if (strncmp(basedir, handle->conn->connectpath, baselen) != 0 || (handle->conn->connectpath[baselen] != 0 && handle->conn->connectpath[baselen] != '/')) { DEBUG(0,("convert_shadow2_name: basedir %s is not a parent of %s\n", basedir, handle->conn->connectpath)); talloc_free(tmp_ctx); return NULL; } if (*relpath == '/') relpath++; if (*baseoffset == '/') baseoffset++; ret = talloc_asprintf(handle->data, "%s/%s/%s/%s", snapdir, snapshot, baseoffset, relpath); DEBUG(6,("convert_shadow2_name: '%s' -> '%s'\n", fname, ret)); talloc_free(tmp_ctx); return ret; }
void parse_request(router_request_t *req, tdata_t *tdata, HashGrid *hg, int opt, char *optarg) { const char delim[2] = ","; char *token; switch (opt) { case 'a': req->arrive_by = true; break; case 'd': req->arrive_by = false; break; case 'r': srand(time(NULL)); router_request_randomize(req, tdata); break; case 'D': { struct tm ltm; memset (<m, 0, sizeof(struct tm)); strptime (optarg, "%Y-%m-%dT%H:%M:%S", <m); ltm.tm_isdst = -1; router_request_from_epoch (req, tdata, mktime(<m)); // from struct_tm instead? } break; case 'f': req->from = strtol(optarg, NULL, 10); break; case 't': req->to = strtol(optarg, NULL, 10); break; case 'V': req->via = strtol(optarg, NULL, 10); break; case 's': req->walk_slack = strtol(optarg, NULL, 10); break; case 'S': req->walk_speed = strtod(optarg, NULL); break; case 'o': req->optimise = 0; token = strtok(optarg, delim); while ( token != NULL ) { if (strcmp(token, "shortest") == 0) req->optimise |= o_shortest; if (strcmp(token, "transfers") == 0) req->optimise |= o_transfers; if (strcmp(token, "all") == 0) req->optimise = o_all; token = strtok(NULL, delim); } break; case 'l': case 'L': if (hg) { token = strtok(optarg, delim); if (token != NULL) { double lat = strtod(token, NULL); token = strtok(NULL, delim); if (token != NULL) { double lon = strtod(token, NULL); HashGridResult result; coord_t qc; double radius_meters = 150; coord_from_lat_lon (&qc, lat, lon); HashGrid_query (hg, &result, qc, radius_meters); uint32_t item = HashGridResult_closest (&result); if (opt == 'l') { req->from = item; } else { req->to = item; } } } } break; case 'm': req->mode = 0; token = strtok(optarg, delim); while ( token != NULL ) { if (strcmp(token, "tram") == 0) req->mode |= m_tram; if (strcmp(token, "subway") == 0) req->mode |= m_subway; if (strcmp(token, "rail") == 0) req->mode |= m_rail; if (strcmp(token, "bus") == 0) req->mode |= m_bus; if (strcmp(token, "ferry") == 0) req->mode |= m_ferry; if (strcmp(token, "cablecar") == 0) req->mode |= m_cablecar; if (strcmp(token, "gondola") == 0) req->mode |= m_gondola; if (strcmp(token, "funicular") == 0) req->mode |= m_funicular; if (strcmp(token, "all") == 0) req->mode = m_all; token = strtok(NULL, delim); } break; case 'A': token = strtok(optarg, delim); while ( token != NULL ) { if (strcmp(token, "accessible") == 0) req->trip_attributes |= ta_accessible; if (strcmp(token, "toilet") == 0) req->trip_attributes |= ta_toilet; if (strcmp(token, "wifi") == 0) req->trip_attributes |= ta_wifi; if (strcmp(token, "none") == 0) req->trip_attributes = ta_none; token = strtok(NULL, delim); } break; case 'x': token = strtok(optarg, delim); while ( token != NULL ) { if (strlen(token) > 0) { long int tmp = strtol(token, NULL, 10); if (tmp >= 0) { req->banned_route = tmp; req->n_banned_routes = 1; } } token = strtok(NULL, delim); } break; case 'y': token = strtok(optarg, delim); while ( token != NULL ) { if (strlen(token) > 0) { long int tmp = strtol(token, NULL, 10); if (tmp >= 0) { req->banned_stop = tmp; req->n_banned_stops = 1; } } token = strtok(NULL, delim); } break; case 'z': token = strtok(optarg, delim); while ( token != NULL ) { if (strlen(token) > 0) { long int tmp_route = strtol(token, NULL, 10); if (tmp_route >= 0) { token = strtok(NULL, delim); long int tmp_trip = strtol(token, NULL, 10); if (tmp_trip >= 0) { req->banned_trip_route = tmp_route; req->banned_trip_offset = tmp_trip; req->n_banned_trips = 1; } } } token = strtok(NULL, delim); } break; case 'Q': { uint32_t tmp_route = NONE; uint32_t tmp_trip = NONE; for (token = strtok(optarg, delim); token != NULL; token = strtok(NULL, delim)) { if (strlen(token) > 0) { if (tmp_route != NONE) { tmp_trip = strtol(token, NULL, 10); } else { tmp_route = strtol(token, NULL, 10); } } } if (tmp_trip != NONE) { req->start_trip_route = tmp_route; req->start_trip_trip = tmp_trip; } break; } case 'w': token = strtok(optarg, delim); while ( token != NULL ) { if (strlen(token) > 0) { long int tmp = strtol(token, NULL, 10); if (tmp >= 0) { req->banned_stop_hard = tmp; req->n_banned_stops_hard = 1; } } token = strtok(NULL, delim); } break; } }
int main(int argc, char** argv) { int opt; int i; int err; int option_index; char buf[MAX_BUF_SIZE]; char date_format[MAX_BUF_SIZE]; char date_string[MAX_BUF_SIZE]; struct jtm j; struct tm g; struct jdate_action action = {0}; /* Long options, see 'jdate.h' for complete list. */ struct option long_options[] = { {DATE_OPT, 1, 0, 'd'}, {REF_OPT, 1, 0, 'r'}, {ACC_OPT, 1, 0, 'a'}, {RFC2822_OPT, 0, 0, 'R'}, {UTC_OPT, 0, 0, 'u'}, {JALALI_OPT, 1, 0, 'j'}, {GREGORIAN_OPT, 1, 0, 'g'}, {UNIVERSAL_OPT, 0, 0, 'u'}, {HELP_OPT, 0, 0, 'h'}, {VERSION_OPT, 0, 0, 'V'}, {0, 0, 0, 0} }; action.normal = 1; time_t t; time(&t); jlocaltime_r(&t, &j); while ((opt = getopt_long(argc, argv, JDATE_VALID_ARGS, long_options, &option_index)) != -1) { switch (opt) { /* last access time. */ case 'a': action.access = 1; action.access_ptr = optarg; break; /* last modification time. */ case 'r': action.reference = 1; action.reference_ptr = optarg; break; /* display time described by FORMAT and DATE_STRING, not `now'. */ case 'd': action.date = 1; action.date_ptr = optarg; break; /* convert a jalali date to gregorian. */ case 'g': action.gregorian = 1; action.gregorian_ptr = optarg; break; /* convert a gregorian date to jalali. */ case 'j': action.jalali = 1; action.jalali_ptr = optarg; break; /* * output date and time in RFC 2822 format. * %h, %m %b %Y %H:%M:%S %z */ case 'R': action.normal = 0; action.format = 0; action.rfc2822 = 1; break; /* print Coordinated Universal Time */ case 'u': action.utc = 1; break; /* help */ case 'h': action.help = 1; action.normal = 0; action.format = 0; action.rfc2822 = 0; break; /* version */ case 'V': action.version = 1; action.help = 0; action.normal = 0; action.format = 0; action.rfc2822 = 0; break; default: fprintf(stderr, "jdate: usage [OPTION]... [+FORMAT]\n"); exit(EXIT_FAILURE); } } /* * Format string handler. INPUT_FORMAT and DATE_STRING * are separated using a semicolon. ';' * e.g. "%Y/%m/%d %H:%M:%S;1390/03/06 18:35:41" */ for (i=1; i<argc; i++) { if (argv[i][0] == '+') { action.format = 1; action.format_ptr = &argv[i][1]; } } /* *@action_handlers */ if (action.jalali) { if (!strptime(action.jalali_ptr, "%Y/%m/%d", &g)) { fprintf(stderr, "Specify gregorian date in the following format\n"); fprintf(stderr, "%%Y/%%m/%%d e.g. 2011/06/15\n"); exit(EXIT_FAILURE); } g.tm_hour = 0; g.tm_min = 0; g.tm_sec = 0; t = mktime(&g); } else if (action.gregorian) { if (!jstrptime(action.gregorian_ptr, "%Y/%m/%d", &j)) { fprintf(stderr, "Specify jalali date in the following format\n"); fprintf(stderr, "%%Y/%%m/%%d e.g. 1390/03/25\n"); exit(EXIT_FAILURE); } jalali_update(&j); j.tm_hour = 0; j.tm_min = 0; j.tm_sec = 0; t = jmktime(&j); } if (action.date) { char* ptr; ptr = strchr(action.date_ptr, ';'); if (!ptr) { fprintf(stderr, "Malformed date string."); fprintf(stderr, " Use ';' to specify format and date string\n"); exit(EXIT_FAILURE); } sscanf(action.date_ptr, "%[^;];%s", date_format, date_string); jstrptime(date_string, date_format, &j); jalali_update(&j); t = jmktime(&j); } if (action.access) { err = mod_time(action.access_ptr, &t, 1); if (err != 0) { fprintf(stderr, "jdate: %s: No such file or directory\n", action.access_ptr); exit(EXIT_FAILURE); } } if (action.reference) { err = mod_time(action.reference_ptr, &t, 0); if (err != 0) { fprintf(stderr, "jdate: %s: No such file or directory\n", action.reference_ptr); exit(EXIT_FAILURE); } } if (action.rfc2822) { if (!action.gregorian) { action.utc ? jgmtime_r(&t, &j) : jlocaltime_r(&t, &j); jstrftime(buf, MAX_BUF_SIZE, "%h, %d %b %Y %H:%M:%S %z", &j); } else { action.utc ? gmtime_r(&t, &g) : localtime_r(&t, &g); strftime(buf, MAX_BUF_SIZE, "%a, %d %b %Y %H:%M:%S %z", &g); } printf("%s\n", buf); exit(EXIT_SUCCESS); } if (action.format) { if (!action.gregorian) { action.utc ? jgmtime_r(&t, &j) : jlocaltime_r(&t, &j); jstrftime(buf, MAX_BUF_SIZE, action.format_ptr, &j); } else { action.utc ? gmtime_r(&t, &g) : localtime_r(&t, &g); strftime(buf, MAX_BUF_SIZE, action.format_ptr, &g); } printf("%s\n", buf); exit(EXIT_SUCCESS); } if (action.normal) { if (!action.gregorian) { action.utc ? jgmtime_r(&t, &j) : jlocaltime_r(&t, &j); jstrftime(buf, MAX_BUF_SIZE, "%h %b %d %H:%M:%S %Z %Y", &j); } else { action.utc ? gmtime_r(&t, &g) : localtime_r(&t, &g); strftime(buf, MAX_BUF_SIZE, "%a %b %d %H:%M:%S %Z %Y", &g); } printf("%s\n", buf); exit(EXIT_SUCCESS); } if (action.help) { printf("%s\n", HELP_STR); exit(EXIT_SUCCESS); } if (action.version) { printf("jdate %s (libjalali-%s)\n", JDATE_VERSION, LIBJALALI_VERSION); printf("Written by Ashkan Ghassemi.\n"); exit(EXIT_SUCCESS); } return 0; }
// ------------------------------------------------------------------------- // This software is furnished "as is", without technical // support, and with no warranty, express or implied, as to its usefulness for // any purpose. // // gcal.c // This file acts as the wrapper around the sp_func.py python library // // Author: Vedvyas Shanbhogue // ------------------------------------------------------------------------*/ #ifdef IDENT_C static const char* const <filename>_c_Id = "$Id$"; #endif #include <Python.h> // -- global ----------------------------------------------------------------- // get_calendar_events() // // Returns: // 0 - success // 1 - error // On success return, the duration is set to the duration of the event // if no event was found then duration is returned as 0 // -------------------------------------------------------------------------*/ int get_calendar_events( time_t *duration) { PyObject *pName, *pModule, *pDict, *pFunc, *pValue; struct tm start_time, end_time; char *start, *end, *name; char *argv[] = { "sp", "sp_func", "get_cal_events" }; // Initialize the Python Interpreter Py_Initialize(); // Build the name object pName = PyString_FromString(argv[1]); // Load the module object PySys_SetArgv(1, argv); PyErr_Print(); pModule = PyImport_Import(pName); PyErr_Print(); // pDict is a borrowed reference pDict = PyModule_GetDict(pModule); // pFunc is also a borrowed reference pFunc = PyDict_GetItemString(pDict, argv[2]); if ( !PyCallable_Check(pFunc) ) { PyErr_Print(); Py_DECREF(pModule); Py_DECREF(pName); Py_Finalize(); return 1; } // Get the calendar events from google calendar pValue = PyObject_CallObject(pFunc, NULL); // Extract the start time, end time and event name strings if ( PyArg_ParseTuple(pValue, "sss", &start, &end, &name) == 0 ) { PyErr_Print(); Py_DECREF(pModule); Py_DECREF(pName); Py_Finalize(); return 1; } *duration = 0; // check if any event returned if ( strlen(start) && strlen(end) && strlen(name) && (strcmp(name, "Sprinkler On") == 0) ) { // Turn time strings into struct tm strptime(start, "%Y-%m-%dT%T", &start_time); strptime(end, "%Y-%m-%dT%T", &end_time); // Check if it is time to start the sprinker if ( time(NULL) >= mktime(&start_time) && time(NULL) < mktime(&end_time) ) { // Time to start the sprinker for specified duration *duration = mktime(&end_time) - time(NULL); } } Py_DECREF(pModule); Py_DECREF(pName); Py_Finalize(); return 0; }
/**************************************************************************** * http_request * Retrieves the specified URL, and stores it in the specified file or buffer ***************************************************************************/ int http_request(const char *url, FILE *hfile, u8 *buffer, u32 maxsize, bool silent, bool accept_encoding) { int res = 0; int chunked = 0; char http_host[64]; char http_path[256]; char content_encoding[16] = ""; u16 http_port; #ifdef DEBUGHEADERS int debugging = 0; #endif http_res result; u32 sizeread = 0; content_length = 0; int linecount; if(maxsize > MAX_SIZE){ #ifdef DEBUGERRORS InfoPrompt("maxsize > MAX_SIZE"); #endif return 0; } if (url == NULL || (hfile == NULL && buffer == NULL)){ #ifdef DEBUGERRORS InfoPrompt("!url || (!hfile && !buffer)"); #endif return 0; } if(!silent) ShowAction("Sending data..."); split_res = http_split_url(http_host, http_path, url); // 2 : https ; 1 : http ; 0 : invalid url if (split_res == 2){ http_port = 443; writeFunc = ssl_write; readFunc = ssl_read; }else if( split_res == 1 ){ http_port = 80; writeFunc = net_write; readFunc = net_read; }else{ #ifdef DEBUGERRORS InfoPrompt("Invalid url"); #endif return 0; } http_status = 404; int s = tcp_connect(http_host, http_port); if (s < 0) { result = HTTPR_ERR_CONNECT; #ifdef DEBUGERRORS InfoPrompt("Socket!"); #endif return 0; } int ssl_context = 0; if(split_res == 2){ ssl_context = ssl_setup(http_host, s); #ifdef DEBUGERRORS if(ssl_context < 0){ InfoPrompt("ssl_context() failed"); } #endif if(ssl_context < 0){ net_close(s); return 0; } scktctx = &ssl_context; } else{ scktctx = &s; } if(curl_request){ //Request made by through the CURL class res = tcp_write(*scktctx, (u8 *) curl_request, strlen(curl_request)); }else{ char request[1024]; char *r = request; r += sprintf(r, "GET %s HTTP/1.1\r\n", http_path); r += sprintf(r, "Host: %s\r\n", http_host); if(accept_encoding && hfile){ r += sprintf(r, "Accept-Encoding: gzip, deflate\r\n"); } r += sprintf(r, "Cache-Control: no-cache\r\n\r\n"); res = tcp_write(*scktctx, (u8 *) request, strlen(request)); } if(!silent) CancelAction(); #ifdef DEBUGHEADERS InfoPrompt(http_path); #endif char line[1024]; //Twitter sends a long header for (linecount = 0; linecount < 45; linecount++) { if (tcp_readln(*scktctx, line, 1024) != 0) { #ifdef DEBUGERRORS InfoPrompt("tcp_readln != 0"); #endif http_status = 404; result = HTTPR_ERR_REQUEST; break; } if (!line[0]) break; #ifdef DEBUGHEADERS if(sscanf(line, "HTTP/1.%*u %u", &http_status)){ if(http_status != 200) debugging = 1; } if(sscanf(line, "Content-Length: %u", &content_length) || sscanf(line, "Content-Encoding: %s", content_encoding)){ if(!debugging){ InfoPrompt(line); } } if(!strncmp(line, "Transfer-Encoding: chunked", 25)){ InfoPrompt("Transfer-Encoding: chunked"); chunked = 1; } #else sscanf(line, "HTTP/1.%*u %u", &http_status); sscanf(line, "Content-Length: %u", &content_length); sscanf(line, "Content-Encoding: %s", content_encoding); if(!strncmp(line, "Transfer-Encoding: chunked", 25)) chunked = 1; #endif u32 api_ratelimit=0; if(sscanf(line, "X-RateLimit-Remaining: %u", &api_ratelimit) && api_ratelimit <= 10 && api_ratelimit % 5 == 0){ WindowPrompt("You are on fire!", "You are about to reach Twitter's requests limit. WiiTweet will not work correctly then.", "I'll take a break", 0); } if(get_timeoffset){ if(!strncasecmp(line, "Date:", 5)){ //Case insensitiveness just in case... const char format[] = "%a, %d %b %Y %H:%M:%S %Z"; const char *pointline = line; pointline += 6; struct tm tm; memset(&tm, 0, sizeof(tm)); strptime(pointline, format, &tm); timeoffset = mktime(&tm) - time(NULL); get_timeoffset = 0; } } #ifdef DEBUGHEADERS if(debugging){ InfoPrompt(line); } #endif } if (http_status != 200) { result = HTTPR_ERR_STATUS; #ifdef DEBUGERRORS if(ssl_context){ if(ssl_shutdown(ssl_context)){ InfoPrompt("ssl_shutdown() 1"); } } net_close(s); #else if(ssl_context){ssl_shutdown(ssl_context);} net_close(s); #endif #ifdef DEBUGERRORS char status[64]; sprintf(status, "HTTP Status = %d", http_status); InfoPrompt(status); #endif return 0; }//Try to read anyways? ssl gets rude if it is not convinced there is no data //length unknown - just read as much as we can if(content_length == 0) { content_length = maxsize; } else if (content_length > maxsize) //ssl_shutdown() would fail in this case (?), but it is not likely for our purposes... { result = HTTPR_ERR_TOOBIG; #ifdef DEBUGERRORS if(ssl_context){ if(ssl_shutdown(ssl_context)){ InfoPrompt("ssl_shutdown() 2"); } } net_close(s); #else if(ssl_context){ssl_shutdown(ssl_context);} net_close(s); #endif #ifdef DEBUGERRORS InfoPrompt("content_length > maxsize"); #endif return 0; } unsigned int inflatetype = 0; if(!strncasecmp(content_encoding, "gzip", 4)){ inflatetype = 2; }else if(!strncasecmp(content_encoding, "deflate", 7)){ inflatetype = 1; }else if(content_encoding[0] != '\0'){//Unsupported encoding. This should never happen. #ifdef DEBUGERRORS if(ssl_context){ if(ssl_shutdown(ssl_context)){ InfoPrompt("ssl_shutdown() 3"); } } net_close(s); #else if(ssl_context){ssl_shutdown(ssl_context);} net_close(s); #endif #ifdef DEBUGERRORS InfoPrompt("Unsupported encoding"); #endif return 0; } if (buffer != NULL) { if(!silent) ShowAction("Downloading..."); if(inflatetype){ //Compressed content u8 * inflate_me = (u8 *) mem2_malloc(content_length, MEM2_OTHER); if(!inflate_me){ #ifdef DEBUGERRORS if(ssl_context){ if(ssl_shutdown(ssl_context)){ InfoPrompt("ssl_shutdown() 4"); } } net_close(s); #else if(ssl_context){ssl_shutdown(ssl_context);} net_close(s); #endif #ifdef DEBUGERRORS InfoPrompt("!inflate_me"); #endif return 0; } #ifdef DEBUGHEADERS int tcpread = tcp_read(*scktctx, inflate_me, content_length, chunked); char atoi[64]; sprintf(atoi, "%d", tcpread); WindowPrompt("tcp_read()", atoi, "ok", 0); #else int tcpread = tcp_read(*scktctx, inflate_me, content_length, chunked); #endif /* static int s = 0; char path[256]; sprintf(path, "sd:/catcha%d", s++); SaveFile ((char *)inflate_me, path, tcpread, 1); */ sizeread = httpInflate(buffer, inflate_me, tcpread, inflatetype); if(sizeread < 0){ mem2_free(inflate_me, MEM2_OTHER); #ifdef DEBUGERRORS if(ssl_context){ if(ssl_shutdown(ssl_context)){ InfoPrompt("ssl_shutdown() 5"); } } net_close(s); #else if(ssl_context){ssl_shutdown(ssl_context);} net_close(s); #endif #ifdef DEBUGERRORS InfoPrompt("sizeread < 0"); #endif return 0; } mem2_free(inflate_me, MEM2_OTHER); }else{ //Uncomprpessed content sizeread = tcp_read(*scktctx, buffer, content_length, chunked); } if(!silent) CancelAction(); } else // write into file { /* Uncompressed data. This may fail if the content is chunked and longer than 32KB+2B but chunked is not used in such scenarios */ u32 bufSize = (1024 * 32); u32 bytesLeft = content_length; u32 readSize; if(!silent) ShowProgress("Downloading...", 0, content_length); u8 * fbuffer = (u8 *) malloc(bufSize); if(fbuffer) { while (bytesLeft > 0) { if (bytesLeft < bufSize) readSize = bytesLeft; else readSize = bufSize; res = tcp_read(*scktctx, fbuffer, readSize, chunked); if (!res) break; sizeread += res; bytesLeft -= res; res = fwrite(fbuffer, 1, res, hfile); if (!res) break; if(!silent) ShowProgress("Downloading...", (content_length - bytesLeft), content_length); } free(fbuffer); } if(!silent) CancelAction(); } #ifdef DEBUGERRORS if(ssl_context){ if(ssl_shutdown(ssl_context)){ InfoPrompt("ssl_shutdown() 6"); } } net_close(s); #else if(ssl_context){ssl_shutdown(ssl_context);} net_close(s); #endif if (content_length < maxsize && sizeread != content_length && !inflatetype) { #ifdef DEBUGERRORS InfoPrompt("ERR_RECEIVE"); #endif result = HTTPR_ERR_RECEIVE; return 0; } if (http_status != 200){ #ifdef DEBUGERRORS InfoPrompt("http_status != 200"); #endif return 0; } if(result) //Avoid ugly compiler warning :p result = HTTPR_OK; return sizeread; }
int parse_timestamp(const char *t, usec_t *usec) { static const struct { const char *name; const int nr; } day_nr[] = { { "Sunday", 0 }, { "Sun", 0 }, { "Monday", 1 }, { "Mon", 1 }, { "Tuesday", 2 }, { "Tue", 2 }, { "Wednesday", 3 }, { "Wed", 3 }, { "Thursday", 4 }, { "Thu", 4 }, { "Friday", 5 }, { "Fri", 5 }, { "Saturday", 6 }, { "Sat", 6 }, }; const char *k; struct tm tm, copy; time_t x; usec_t plus = 0, minus = 0, ret; int r, weekday = -1; unsigned i; /* * Allowed syntaxes: * * 2012-09-22 16:34:22 * 2012-09-22 16:34 (seconds will be set to 0) * 2012-09-22 (time will be set to 00:00:00) * 16:34:22 (date will be set to today) * 16:34 (date will be set to today, seconds to 0) * now * yesterday (time is set to 00:00:00) * today (time is set to 00:00:00) * tomorrow (time is set to 00:00:00) * +5min * -5days * @2147483647 (seconds since epoch) * */ assert(t); assert(usec); x = time(NULL); assert_se(localtime_r(&x, &tm)); tm.tm_isdst = -1; if (streq(t, "now")) goto finish; else if (streq(t, "today")) { tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto finish; } else if (streq(t, "yesterday")) { tm.tm_mday --; tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto finish; } else if (streq(t, "tomorrow")) { tm.tm_mday ++; tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto finish; } else if (t[0] == '+') { r = parse_sec(t+1, &plus); if (r < 0) return r; goto finish; } else if (t[0] == '-') { r = parse_sec(t+1, &minus); if (r < 0) return r; goto finish; } else if (t[0] == '@') return parse_sec(t + 1, usec); else if (endswith(t, " ago")) { _cleanup_free_ char *z; z = strndup(t, strlen(t) - 4); if (!z) return -ENOMEM; r = parse_sec(z, &minus); if (r < 0) return r; goto finish; } else if (endswith(t, " left")) { _cleanup_free_ char *z; z = strndup(t, strlen(t) - 4); if (!z) return -ENOMEM; r = parse_sec(z, &plus); if (r < 0) return r; goto finish; } for (i = 0; i < ELEMENTSOF(day_nr); i++) { size_t skip; if (!startswith_no_case(t, day_nr[i].name)) continue; skip = strlen(day_nr[i].name); if (t[skip] != ' ') continue; weekday = day_nr[i].nr; t += skip + 1; break; } copy = tm; k = strptime(t, "%y-%m-%d %H:%M:%S", &tm); if (k && *k == 0) goto finish; tm = copy; k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm); if (k && *k == 0) goto finish; tm = copy; k = strptime(t, "%y-%m-%d %H:%M", &tm); if (k && *k == 0) { tm.tm_sec = 0; goto finish; } tm = copy; k = strptime(t, "%Y-%m-%d %H:%M", &tm); if (k && *k == 0) { tm.tm_sec = 0; goto finish; } tm = copy; k = strptime(t, "%y-%m-%d", &tm); if (k && *k == 0) { tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto finish; } tm = copy; k = strptime(t, "%Y-%m-%d", &tm); if (k && *k == 0) { tm.tm_sec = tm.tm_min = tm.tm_hour = 0; goto finish; } tm = copy; k = strptime(t, "%H:%M:%S", &tm); if (k && *k == 0) goto finish; tm = copy; k = strptime(t, "%H:%M", &tm); if (k && *k == 0) { tm.tm_sec = 0; goto finish; } return -EINVAL; finish: x = mktime(&tm); if (x == (time_t) -1) return -EINVAL; if (weekday >= 0 && tm.tm_wday != weekday) return -EINVAL; ret = (usec_t) x * USEC_PER_SEC; ret += plus; if (ret > minus) ret -= minus; else ret = 0; *usec = ret; return 0; }
/* converts a ISO 8601 time string to a time_t value */ time_t parseISO8601Date(gchar *date) { struct tm tm; time_t t, t2, offset = 0; gboolean success = FALSE; gchar *pos; if (date == NULL) return -1; memset(&tm, 0, sizeof(struct tm)); /* we expect at least something like "2003-08-07T15:28:19" and don't require the second fractions and the timezone info the most specific format: YYYY-MM-DDThh:mm:ss.sTZD */ /* full specified variant */ if(NULL != (pos = strptime((const char *)date, "%Y-%m-%dT%H:%M:%SZ", &tm))) { /* Parse seconds */ if (*pos == ':') pos++; if (isdigit(pos[0]) && !isdigit(pos[1])) { tm.tm_sec = pos[0] - '0'; pos++; } else if (isdigit(pos[0]) && isdigit(pos[1])) { tm.tm_sec = 10*(pos[0]-'0') + pos[1] - '0'; pos +=2; } /* Parse timezone */ if (*pos == 'Z') offset = 0; else if ((*pos == '+' || *pos == '-') && isdigit(pos[1]) && isdigit(pos[2]) && strlen(pos) >= 3) { offset = (10*(pos[1] - '0') + (pos[2] - '0')) * 60 * 60; if (pos[3] == ':' && isdigit(pos[4]) && isdigit(pos[5])) offset += (10*(pos[4] - '0') + (pos[5] - '0')) * 60; else if (isdigit(pos[3]) && isdigit(pos[4])) offset += (10*(pos[3] - '0') + (pos[4] - '0')) * 60; offset *= (pos[0] == '+') ? 1 : -1; } success = TRUE; /* only date */ } else if(NULL != strptime((const char *)date, "%t%Y-%m-%d", &tm)) success = TRUE; /* there were others combinations too... */ if(TRUE == success) { if((time_t)(-1) != (t = mktime(&tm))) { /* Correct for the local timezone*/ t = t - offset; t2 = mktime(gmtime(&t)); t = t - (t2 - t); return t; } else { g_warning("internal error! time conversion error! mktime failed!\n"); } } else { g_warning("Invalid ISO8601 date format! Ignoring <dc:date> information!\n"); } return 0; }
main( int ac, char *av[] ) { MYSQL mysql; MYSQL_RES *result; MYSQL_ROW row; char *ip, *cksum, *from, *escaped_from, *reason; char query[ 1024 ]; int c, err = 0, len, rc; struct tm tm; time_t then, now; double dt; extern int optind; while (( c = getopt( ac, av, "f:" )) != -1 ) { switch ( c ) { case 'f' : config = optarg; break; case '?' : default : err++; break; } } if ( ac - optind != 1 ) { err++; } if ( err ) { fprintf( stderr, "usage: %s [ -f mysql-config ] reason\n", av[ 0 ] ); exit( 0 ); } reason = av[ optind ]; if (( cksum = getenv( "SIMTA_CHECKSUM" )) == NULL ) { fprintf( stderr, "SIMTA_CHECKSUM not set\n" ); exit( 0 ); } if (( ip = getenv( "SIMTA_REMOTE_IP" )) == NULL ) { fprintf( stderr, "SIMTA_REMOTE_IP not set\n" ); exit( 0 ); } if (( from = getenv( "SIMTA_SMTP_MAIL_FROM" )) == NULL ) { fprintf( stderr, "SIMTA_SMTP_MAIL_FROM not set\n" ); exit( 0 ); } if ( mysql_init( &mysql ) == NULL ) { perror( "mysql_init" ); exit( 0 ); } if ( mysql_options( &mysql, MYSQL_READ_DEFAULT_FILE, config ) != 0 ) { fprintf( stderr, "mysql_options %s failed\n", config ); exit( 0 ); } if ( mysql_real_connect( &mysql, NULL, NULL, NULL, NULL, 0, NULL, 0 ) == NULL ) { fprintf( stderr, "MySQL connection failed: %s\n", mysql_error( &mysql )); exit( 0 ); } len = strlen( from ); if (( escaped_from = malloc( len * 2 + 1 )) == NULL ) { perror( "malloc" ); exit( 0 ); } mysql_real_escape_string( &mysql, escaped_from, from, len ); if (( len = snprintf( query, sizeof( query ), "INSERT INTO signatures () VALUES" " ('%s', '%s', '%s', DEFAULT, '%s')", cksum, ip, escaped_from, reason )) >= sizeof( query )) { fprintf( stderr, "INSERT too long! %d\n", len ); exit( 0 ); } if (( rc = mysql_real_query( &mysql, query, len )) == 0 ) { /* * Should I commit this transaction? Should I close the connection? */ printf( "PenaltyBox: Record: [%s] <%s> %s\n", ip, from, reason ); exit( 1 ); } if ( ER_DUP_ENTRY != mysql_errno( &mysql )) { fprintf( stderr, "INSERT %s\n", mysql_error( &mysql )); exit( 0 ); } if (( len = snprintf( query, sizeof( query ), "SELECT time, reason FROM signatures WHERE" " checksum = '%s' AND ip_address = '%s' AND from_address = '%s'" " LIMIT 1", cksum, ip, escaped_from )) >= sizeof( query )) { fprintf( stderr, "SELECT too long! %d\n", len ); exit( 0 ); } if ( mysql_real_query( &mysql, query, len ) != 0 ) { fprintf( stderr, "SELECT failed: %s\n", mysql_error( &mysql )); exit( 0 ); } if (( result = mysql_store_result( &mysql )) == NULL ) { fprintf( stderr, "mysql_store_result failed: %s\n", mysql_error( &mysql )); exit( 0 ); } if (( row = mysql_fetch_row( result )) == NULL ) { fprintf( stderr, "mysql_fetch_row failed: %s\n", mysql_error( &mysql )); exit( 0 ); } /* time is in the format YYYY-MM-DD HH:MM:SS */ tm.tm_isdst = -1; if ( strptime( row[ 0 ], "%Y-%m-%d %H:%M:%S", &tm ) == NULL ) { fprintf( stderr, "Could not parse timestamp: %s\n", row[ 0 ] ); exit( 0 ); } then = mktime( &tm ); now = time( NULL ); if (( dt = difftime( now, then )) < 5 * 60 ) { printf( "PenaltyBox: Window: %ds [%s] <%s> %s\n", (int)dt, ip, from, row[ 1 ] ); exit( 1 ); } if (( len = snprintf( query, sizeof( query ), "DELETE FROM signatures WHERE" " checksum = '%s' AND ip_address = '%s' AND from_address = '%s'" " LIMIT 1", cksum, ip, escaped_from )) >= sizeof( query )) { fprintf( stderr, "DELETE too long! %d\n", len ); exit( 0 ); } if ( mysql_real_query( &mysql, query, len ) != 0 ) { fprintf( stderr, "DELETE failed: %s\n", mysql_error( &mysql )); exit( 0 ); } printf( "PenaltyBox: Accept: %ds [%s] <%s> %s\n", (int)dt, ip, from, row[ 1 ] ); exit( 0 ); }
int cloudfs_list_directory(const char *path, dir_entry **dir_list) { char container[MAX_PATH_SIZE * 3] = ""; char object[MAX_PATH_SIZE] = ""; char last_subdir[MAX_PATH_SIZE] = ""; int prefix_length = 0; int response = 0; int retval = 0; int entry_count = 0; *dir_list = NULL; xmlNode *onode = NULL, *anode = NULL, *text_node = NULL; xmlParserCtxtPtr xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL); if (!strcmp(path, "") || !strcmp(path, "/")) { path = ""; strncpy(container, "/?format=xml", sizeof(container)); } else { sscanf(path, "/%[^/]/%[^\n]", container, object); char *encoded_container = curl_escape(container, 0); char *encoded_object = curl_escape(object, 0); // The empty path doesn't get a trailing slash, everything else does char *trailing_slash; prefix_length = strlen(object); if (object[0] == 0) trailing_slash = ""; else { trailing_slash = "/"; prefix_length++; } snprintf(container, sizeof(container), "%s?format=xml&delimiter=/&prefix=%s%s", encoded_container, encoded_object, trailing_slash); curl_free(encoded_container); curl_free(encoded_object); } response = send_request("GET", container, NULL, xmlctx, NULL); xmlParseChunk(xmlctx, "", 0, 1); if (xmlctx->wellFormed && response >= 200 && response < 300) { xmlNode *root_element = xmlDocGetRootElement(xmlctx->myDoc); for (onode = root_element->children; onode; onode = onode->next) { if (onode->type != XML_ELEMENT_NODE) continue; char is_object = !strcasecmp((const char *)onode->name, "object"); char is_container = !strcasecmp((const char *)onode->name, "container"); char is_subdir = !strcasecmp((const char *)onode->name, "subdir"); if (is_object || is_container || is_subdir) { entry_count++; dir_entry *de = (dir_entry *)malloc(sizeof(dir_entry)); de->next = NULL; de->size = 0; de->last_modified = time(NULL); if (is_container || is_subdir) de->content_type = strdup("application/directory"); for (anode = onode->children; anode; anode = anode->next) { char *content = "<?!?>"; for (text_node = anode->children; text_node; text_node = text_node->next) if (text_node->type == XML_TEXT_NODE) content = (char *)text_node->content; if (!strcasecmp((const char *)anode->name, "name")) { de->name = strdup(content + prefix_length); // Remove trailing slash char *slash = strrchr(de->name, '/'); if (slash && (0 == *(slash + 1))) *slash = 0; if (asprintf(&(de->full_name), "%s/%s", path, de->name) < 0) de->full_name = NULL; } if (!strcasecmp((const char *)anode->name, "bytes")) de->size = strtoll(content, NULL, 10); if (!strcasecmp((const char *)anode->name, "content_type")) { de->content_type = strdup(content); char *semicolon = strchr(de->content_type, ';'); if (semicolon) *semicolon = '\0'; } if (!strcasecmp((const char *)anode->name, "last_modified")) { struct tm last_modified; strptime(content, "%FT%T", &last_modified); de->last_modified = mktime(&last_modified); } } de->isdir = de->content_type && ((strstr(de->content_type, "application/folder") != NULL) || (strstr(de->content_type, "application/directory") != NULL)); if (de->isdir) { if (!strncasecmp(de->name, last_subdir, sizeof(last_subdir))) { cloudfs_free_dir_list(de); continue; } strncpy(last_subdir, de->name, sizeof(last_subdir)); } de->next = *dir_list; *dir_list = de; } else { debugf("unknown element: %s", onode->name); } } retval = 1; } debugf("entry count: %d", entry_count); xmlFreeDoc(xmlctx->myDoc); xmlFreeParserCtxt(xmlctx); return retval; }
int list_directory(const char *path, dir_entry **dir_list) { char container[MAX_PATH_SIZE * 3] = ""; char object[MAX_PATH_SIZE] = ""; int response = 0; int retval = 0; *dir_list = NULL; xmlNode *onode = NULL, *anode = NULL, *text_node = NULL; xmlParserCtxtPtr xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL); if (!strcmp(path, "") || !strcmp(path, "/")) { path = ""; strncpy(container, "/?format=xml", sizeof(container)); } else { sscanf(path, "/%[^/]/%[^\n]", container, object); char *encoded_container = curl_escape(container, 0); char *encoded_object = curl_escape(object, 0); snprintf(container, sizeof(container), "%s?format=xml&path=%s", encoded_container, encoded_object); curl_free(encoded_container); curl_free(encoded_object); } response = send_request("GET", container, NULL, xmlctx, NULL); xmlParseChunk(xmlctx, "", 0, 1); if (xmlctx->wellFormed && response >= 200 && response < 300) { xmlNode *root_element = xmlDocGetRootElement(xmlctx->myDoc); for (onode = root_element->children; onode; onode = onode->next) if ((onode->type == XML_ELEMENT_NODE) && (!strcasecmp((const char *)onode->name, "object") || !strcasecmp((const char *)onode->name, "container"))) { dir_entry *de = (dir_entry *)malloc(sizeof(dir_entry)); de->size = 0; de->last_modified = time(NULL); if (!strcasecmp((const char *)onode->name, "container")) de->content_type = strdup("application/directory"); for (anode = onode->children; anode; anode = anode->next) { char *content = "<?!?>"; for (text_node = anode->children; text_node; text_node = text_node->next) if (text_node->type == XML_TEXT_NODE) content = (char *)text_node->content; if (!strcasecmp((const char *)anode->name, "name")) { if (strrchr(content, '/')) de->name = strdup(strrchr(content, '/')+1); else de->name = strdup(content); if (asprintf(&(de->full_name), "%s/%s", path, de->name) < 0) de->full_name = NULL; } if (!strcasecmp((const char *)anode->name, "bytes")) de->size = atoi(content); if (!strcasecmp((const char *)anode->name, "content_type")) { de->content_type = strdup(content); char *semicolon = strchr(de->content_type, ';'); if (semicolon) *semicolon = '\0'; } if (!strcasecmp((const char *)anode->name, "last_modified")) { struct tm last_modified; strptime(content, "%FT%T", &last_modified); de->last_modified = mktime(&last_modified); } } de->isdir = de->content_type && ((strstr(de->content_type, "application/folder") != NULL) || (strstr(de->content_type, "application/directory") != NULL)); de->next = *dir_list; *dir_list = de; } retval = 1; } xmlFreeDoc(xmlctx->myDoc); xmlFreeParserCtxt(xmlctx); return retval; }