static int dateCommand(int argc, char **argv) { if (argc <= 0) { printf("show/set the system clock.\n"); if (argc < 0) { printf("%sThe argument used to set the time, if given,\n", *argv); printf("%sis in the form [MMDDhhmm[[CC]YY][.ss]].\n", *argv); } return COMMAND_OK; } if (argc > 1) { // Set the time. struct tm tm; time_t t = time(NULL); localtime_r(&t, &tm); char *p = argv[1]; // Point to the date string. // Find seconds. char *s = strchr(p, '.'); if (s) { // Seconds here. Terminate p and point to them. *s++ = '\0'; } int left = strlen(p); // Number of characters in non-second string. #define TODEC(v) if (*(p)) { v = 0; v += *p - '0'; ++p; --left; } \ if (*(p)) { v *= 10; v += *p - '0'; ++p; --left; } TODEC(tm.tm_mon) if (tm.tm_mon < 1 || tm.tm_mon > 12) { printf("invalid month: %d\n", tm.tm_mon); return COMMAND_ERROR; } --tm.tm_mon; // In the range of 0 .. 11. TODEC(tm.tm_mday) if (tm.tm_mday < 1 || tm.tm_mday > 31) { printf("invalid day of month: %d\n", tm.tm_mday); return COMMAND_ERROR; } TODEC(tm.tm_hour) if (tm.tm_hour < 0 || tm.tm_hour > 23) { printf("invalid hour: %d\n", tm.tm_hour); return COMMAND_ERROR; } TODEC(tm.tm_min) if (tm.tm_min < 0 || tm.tm_min > 59) { printf("invalid minute: %d\n", tm.tm_min); return COMMAND_ERROR; } if (left >= 2) { int year = 0; if (left >= 4) { // Have a four digit year. TODEC(year) year = year * 100; } else { year = 1900; } int tens = 0; TODEC(tens) year += tens; if (year < 1900) { printf("invalid year: %d\n", year); return COMMAND_ERROR; } tm.tm_year = year - 1900; } if (s) { // Have seconds. p = s; TODEC(tm.tm_sec); if (tm.tm_sec < 0 || tm.tm_sec > 59) { printf("invalid seconds: %d\n", tm.tm_sec); return COMMAND_ERROR; } } time_t sec = mktime(&tm); if (sec == (time_t)-1) { printf("mktime failed %s\n", asctime(&tm)); return COMMAND_ERROR; } struct timeval tv = { sec, 0 }; return settimeofday(&tv, NULL) == 0 ? COMMAND_OK : COMMAND_ERROR; } time_t t = time(NULL); char date[26]; fputs(ctime_r(&t, date), stdout); return COMMAND_OK; }
/** * This method should not be called directly, but rather via ObjectName.start() to * ensure the thread is started correctly. */ void ExecProcess::run() { string **argsString; string **envString; argsString = test->getExecuteCommand(); envString = test->getExecuteEnv(); exitValue = NOT_YET_SET; int process; int pidChild; // create our env file as well ConsoleServer::debugMsg(1,"Opening environment file %s\n\n",test->getEnvFileName().c_str()); try { FILE *envFile = Utils::createF(test->getEnvFileName()); ConsoleServer::debugMsgF(1,envFile,"Agent details :\n"); ConsoleServer::debugMsgF(1,envFile,"---------------\n"); ConsoleServer::debugMsgF(1,envFile,"Host name\n"); ConsoleServer::debugMsgF(1,envFile,"\n",1); ConsoleServer::debugMsgF(1,envFile,"Command :\n"); ConsoleServer::debugMsgF(1,envFile,"---------------------\n"); for (int i = 0; i < (test->getCommandCount()); i++) { ConsoleServer::debugMsgF(1,envFile,"Argument %d is %s\n",i,argsString[i]->c_str()); } ConsoleServer::debugMsgF(1,envFile,"\n"); ConsoleServer::debugMsgF(1,envFile,"Process environment :%d\n",test->getExecuteEnvCount()); ConsoleServer::debugMsgF(1,envFile,"---------------------\n"); for (int i = 0; i < test->getExecuteEnvCount(); i++) { ConsoleServer::debugMsgF(1,envFile,"%s\n",envString[i]->c_str()); } ConsoleServer::debugMsgF(1,envFile,"\n"); pidChild = fork(); if (pidChild == -1) { ConsoleServer::debugMsg(1,"Failed to fork :%s errno=%d\n", strerror(errno),errno); } else{ if (pidChild==0) { // this is the child process // so redirect it's stdout and stderr to file redirectOutput(envFile); // create the prog_args and prog_env arrays char **prog_args = new char*[test->getCommandCount()+1]; for (int i = 0; i < test->getCommandCount(); i++) { prog_args[i] = (char *)argsString[i]->c_str(); } prog_args[test->getCommandCount()]=NULL; char **prog_env = new char*[test->getExecuteEnvCount()+1]; for (int i = 0; i < test->getExecuteEnvCount(); i++) { prog_env[i] = (char *)envString[i]->c_str(); } prog_env[test->getExecuteEnvCount()]=NULL; process = execve(argsString[0]->c_str(), (char*const*)prog_args, (char*const*)prog_env); if ( process < 0 ) { ConsoleServer::debugMsg(1,"Error starting process :%s\n",strerror(errno)); } // clean up prog_args delete prog_args; // clean up env delete prog_env; exit(process); } else { // this is the parent process pid = pidChild; startTime = time(0); char *timebuff = Utils::allocateChars(STR_LENGTH); timebuff = ctime_r(&startTime,timebuff); ConsoleServer::debugMsgF(1,envFile,"Process %d started at %s\n",pidChild,timebuff); delete [] timebuff; timebuff = NULL; fclose(envFile); } } } catch (char * message) { ConsoleServer::debugMsg(1,"Error trying to run the process :%s\n",message); } }
static int crash_handler(int sig) { // extract process name const char *prog = rcpGetProcName(); // extract time char current[50]; time_t now = time(NULL); ctime_r(&now, current); // print error in console fprintf(stderr, "\033[31mError: Process %s creashed on %s\033[0m\n", prog, current); // print process status fprintf(stderr, "********** status **********************\n"); FILE *fp = fopen("/proc/self/status", "r"); if (fp != NULL) { char buf[1000 + 1]; buf[1000] = '\0'; while (fgets(buf, 1000, fp) != NULL) fprintf(stderr, "%s", buf); fclose(fp); } // print memory map fprintf(stderr, "********** memory map **********************\n"); fp = fopen("/proc/self/maps", "r"); if (fp != NULL) { char buf[1000 + 1]; buf[1000] = '\0'; while (fgets(buf, 1000, fp) != NULL) fprintf(stderr, "%s", buf); fclose(fp); } // try to generate the crushdump using gdb fprintf(stderr, "********** stack trace **********************\n"); struct stat buf; if (stat("/usr/bin/gdb", &buf) == 0) { fp = fopen("gdbdump", "w"); if (fp != NULL) { // create a command file fprintf(fp, "set height 0\n"); fprintf(fp, "bt full\n"); fprintf(fp, "quit\n"); fclose(fp); // build gdb command and run it char command[200]; memset(command, 0, 200); snprintf(command, 199, "gdb -batch -x ./gdbdump --pid %d < /dev/null 2>&1", getpid()); int rv = system(command); (void) rv; } } // if not, generate a backtrace else { void *array[30]; size_t size; size = backtrace(array, 30); fprintf(stderr, "Error: signal %d received\n", sig); backtrace_symbols_fd(array, size, 2); } abort(); return 0; }
u32 _gzip_handler(s8 *data, u32 offset, u32 idx) { struct gzip *gz = (struct gzip *) &data[offset]; s8 timebuf[26]; u32 name_len; u32 rc; rc = 0; // name validity check: name_len = 0; if (gz->flg & GZIP_FNAME) { for (name_len = 0; gz->name[name_len]; name_len++) { if (!isprint(gz->name[name_len])) return rc; } } printf("\n\t0x%08x GZIP compressed data {\n", offset); if (name_len) printf("\t %-10s \"%s\"\n", "name:", gz->name); // compression method: printf("\t %-10s ", "method:"); switch(gz->cm) { case 8: printf("deflate%d\n", gz->cm); break; default: printf("%d\n", gz->cm); } printf("\t %-10s ", "type:"); if (gz->flg & GZIP_FTEXT) printf("ASCII\n"); else printf("binary\n"); printf("\t %-10s ", "OS type:"); switch(gz->ostype) { case 0: printf("FAT based\n"); break; case 1: printf("Amiga\n"); break; case 2: printf("VMS\n"); break; case 3: printf("Unix\n"); break; case 4: printf("VM/CMS\n"); break; case 5: printf("Atari TOS\n"); break; case 6: printf("HPFS based\n"); break; case 7: printf("Macintosh\n"); break; case 8: printf("Z-System\n"); break; case 9: printf("CP/M\n"); break; case 10:printf("TOPS-20\n"); break; case 11:printf("NTFS based\n"); break; case 12:printf("QDOS\n"); break; case 13:printf("Acorn RISCOS\n"); break; default: printf("[unknown: %d]\n", gz->ostype); } ctime_r((time_t *)&gz->time, timebuf); timebuf[strlen(timebuf)-1] = '\0'; printf("\t %-10s %s\n", "date:", timebuf); printf("\t}\n"); rc = sizeof(*gz) - signatures[idx].magic_len; return rc; }
void request_info(request *r, suq_serv *cs) { job *j; int search_id; char *arg; int found=0; arg=request_get_arg(r, 2); if (!arg) goto err; if ( strcmp(arg, "all") == 0) { search_id=-1; } else { char *end; search_id=strtol(arg, &end, 10); if (end==arg) { request_reply_errstring(r, "info argument is not a number"); return; } } j=joblist_first(&(cs->jl)); while(j) { job *jnext=joblist_next(&(cs->jl), j); if (search_id == -1 || j->id == search_id) { char timestr[26]; char *loc; ctime_r(&(j->sub_time), timestr); loc=strchr(timestr, '\n'); /* remove newline */ if (loc) *loc=0; /* we found one */ request_reply_printf(r, "Name: %s\n", j->name); request_reply_printf(r, "Job id: %d\n", j->id); request_reply_printf(r, "Priority: %d\n", j->prio); request_reply_printf(r, "State: %s\n", job_state_strings[j->state]); request_reply_printf(r, "Submit time: %s\n", timestr); if (j->state==running || j->state==started) { ctime_r(&(j->start_time), timestr); loc=strchr(timestr, '\n'); /* remove newline */ if (loc) *loc=0; request_reply_printf(r, "Start time: %s\n", timestr); request_reply_printf(r, "Process id: %d\n", j->pid); } if (j->state==run_error || j->state==resource_error) { request_reply_printf(r, "Error string: %s\n", j->error_string); } request_reply_printf(r, "Nr. of tasks: %d\n", j->ntask); request_reply_printf(r, "Command: %s\n", j->cmd); request_reply_printf(r, "Nr. of args: %d\n", j->argc); request_reply_printf(r, "Nr. of env vars: %d\n", j->envc); request_reply_printf(r, "Working directory: %s\n", j->wd); request_reply_printf(r, "\n"); found=1; } j=jnext; } if (!found) request_reply_printf(r, "ERROR: Job not found\n"); return; err: return; }
static void add_entry(struct cvs_file *cf) { FILE *fp; char *entry, path[MAXPATHLEN]; char revbuf[CVS_REV_BUFSZ], tbuf[CVS_TIME_BUFSZ]; char sticky[CVS_ENT_MAXLINELEN]; CVSENTRIES *entlist; if (cvs_noexec == 1) return; sticky[0] = '\0'; entry = xmalloc(CVS_ENT_MAXLINELEN); if (cf->file_status == FILE_REMOVED) { rcsnum_tostr(cf->file_ent->ce_rev, revbuf, sizeof(revbuf)); ctime_r(&cf->file_ent->ce_mtime, tbuf); tbuf[strcspn(tbuf, "\n")] = '\0'; if (cf->file_ent->ce_tag != NULL) (void)xsnprintf(sticky, sizeof(sticky), "T%s", cf->file_ent->ce_tag); /* Remove the '-' prefixing the version number. */ cvs_ent_line_str(cf->file_name, revbuf, tbuf, cf->file_ent->ce_opts ? cf->file_ent->ce_opts : "", sticky, 0, 0, entry, CVS_ENT_MAXLINELEN); } else { if (logmsg != NULL) { (void)xsnprintf(path, MAXPATHLEN, "%s/%s/%s%s", cf->file_wd, CVS_PATH_CVSDIR, cf->file_name, CVS_DESCR_FILE_EXT); if ((fp = fopen(path, "w+")) == NULL) fatal("add_entry: fopen `%s': %s", path, strerror(errno)); if (fputs(logmsg, fp) == EOF) { (void)unlink(path); fatal("add_entry: fputs `%s': %s", path, strerror(errno)); } (void)fclose(fp); } if (cvs_directory_tag != NULL) (void)xsnprintf(sticky, sizeof(sticky), "T%s", cvs_directory_tag); tbuf[0] = '\0'; if (!cvs_server_active) (void)xsnprintf(tbuf, sizeof(tbuf), "Initial %s", cf->file_name); cvs_ent_line_str(cf->file_name, "0", tbuf, kflag ? kbuf : "", sticky, 0, 0, entry, CVS_ENT_MAXLINELEN); } if (cvs_server_active) { cvs_server_send_response("Checked-in %s/", cf->file_wd); cvs_server_send_response("%s", cf->file_path); cvs_server_send_response("%s", entry); } else { entlist = cvs_ent_open(cf->file_wd); cvs_ent_add(entlist, entry); } xfree(entry); }
static const gchar * get_header(Log4gLayout *base) { time_t t; gchar buffer[26]; struct Private *priv = GET_PRIVATE(base); time(&t); g_string_set_size(priv->string, 0); g_string_append(priv->string, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 " "Transitional//EN " "\"http://www.w3.org/TR/html4/loose.dtd\">"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<html>"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<head>"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<title>"); g_string_append(priv->string, priv->title); g_string_append(priv->string, "</title>"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<style type=\"text/css\">"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<!--"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "body, table {font-family: arial,sans-serif; " "font-size: x-small;}"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "th {background: #336699; color: #ffffff; " "text-align: left;}"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "-->"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "</style>"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "</head>"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<body bgcolor=\"#ffffff\" topmargin=\"6\" " "leftmargin=\"6\">"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<hr size=\"1\" noshade />"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, Q_("Log session start time ")); g_string_append(priv->string, ctime_r(&t, buffer)); g_string_erase(priv->string, priv->string->len - 1, 1); g_string_append(priv->string, "<br />"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<br />"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<table cellspacing=\"0\" cellpadding=\"4\" " "border=\"1\" bordercolor=\"#224466\" " "width=\"100%\">"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "<tr>"); g_string_append(priv->string, LOG4G_LAYOUT_LINE_SEP); g_string_append_printf(priv->string, "<th>%s</th>%s", Q_("Time"), LOG4G_LAYOUT_LINE_SEP); g_string_append_printf(priv->string, "<th>%s</th>%s", Q_("Thread"), LOG4G_LAYOUT_LINE_SEP); g_string_append_printf(priv->string, "<th>%s</th>%s", Q_("Level"), LOG4G_LAYOUT_LINE_SEP); g_string_append_printf(priv->string, "<th>%s</th>%s", Q_("Category"), LOG4G_LAYOUT_LINE_SEP); if (priv->info) { g_string_append_printf(priv->string, "<th>%s</th>%s", Q_("File:Line"), LOG4G_LAYOUT_LINE_SEP); } g_string_append_printf(priv->string, "<th>%s</th>%s", Q_("Message"), LOG4G_LAYOUT_LINE_SEP); g_string_append(priv->string, "</tr>"); return priv->string->str; }
void IBN_TimeAccess (u8 nParamsGet_u8,u8 CMD_u8,u32 Param_u32,u8 *String_pu8) { struct tm tm_st; // struct tm tm_st1; u8 Time_u8[30]; time_t now; if (0 == nParamsGet_u8) { CI_LocalPrintf ("Time functions\r\n"); CI_LocalPrintf ("\r\n"); CI_LocalPrintf ("0 Show time\r\n"); CI_LocalPrintf ("1 Set time - HH:MM:SS\r\n"); CI_LocalPrintf ("2 Set date - DD:MM:YY\r\n"); CI_LocalPrintf ("3 Set time in sec\r\n"); CI_LocalPrintf ("4 Write time to flash\r\n"); CI_LocalPrintf ("5 Read time from flash\r\n"); CI_LocalPrintf ("\r\n"); return; } switch (CMD_u8) { case 0 : time (&now); CI_LocalPrintf ("Time %ld\r\n",now); ctime_r (&now,(char*)Time_u8); CI_LocalPrintf ("Time %s\r\n",Time_u8); break; case 1 : if (NULL == String_pu8) { break; } time (&now); localtime_r (&now,&tm_st); tm_st.tm_hour = atoi ((char*)&String_pu8[0]); tm_st.tm_min = atoi ((char*)&String_pu8[3]); tm_st.tm_sec = atoi ((char*)&String_pu8[6]); CI_LocalPrintf ("Set time to %2d:%02d:%02d\r\n",tm_st.tm_hour,tm_st.tm_min,tm_st.tm_sec); now = mktime (&tm_st); set_time (now); break; case 2 : if (NULL == String_pu8) { break; } time (&now); localtime_r (&now,&tm_st); tm_st.tm_mday = atoi ((char*)&String_pu8[0]); tm_st.tm_mon = atoi ((char*)&String_pu8[3]) - 1; tm_st.tm_year = atoi ((char*)&String_pu8[6]); if (50 > tm_st.tm_year) { tm_st.tm_year += 100; } CI_LocalPrintf ("Set date to %2d.%02d.%04d\r\n",tm_st.tm_mday,tm_st.tm_mon+1,1900+tm_st.tm_year); now = mktime (&tm_st); set_time (now); break; case 3 : CI_LocalPrintf ("Set Time %ld\r\n",Param_u32); set_time (Param_u32); time (&now); CI_LocalPrintf ("Time %ld\r\n",now); ctime_r (&now,(char*)Time_u8); CI_LocalPrintf ("Time %s\r\n",Time_u8); break; case 4 : time (&now); CI_LocalPrintf ("Write time %ld -",now); ctime_r (&now,(char*)Time_u8); CI_LocalPrintf ("%s\r\n",Time_u8); WriteDatetime (now); break; case 5 : ReadDatetime (&now); CI_LocalPrintf ("Stored time %ld - ",now); ctime_r (&now,(char*)Time_u8); CI_LocalPrintf ("Time %s\r\n",Time_u8); break; } }
void tLogMonthList(void) { MYSQL_RES *res; MYSQL_ROW field; ExttLogMonthListSelect(); MYSQL_RUN_STORE(res); guI=mysql_num_rows(res); PageMachine("tLogMonthList",1,"");//1 is auto header list guMode. Opens table! //Filter select drop down ExttLogMonthListFilter(); printf("<input type=text size=16 name=gcCommand maxlength=98 value=\"%s\" >",gcCommand); printf("</table>\n"); printf("<table bgcolor=#9BC1B3 border=0 width=100%%>\n"); printf("<tr bgcolor=black><td><font face=arial,helvetica color=white>uLog<td><font face=arial,helvetica color=white>cLabel<td><font face=arial,helvetica color=white>uLogType<td><font face=arial,helvetica color=white>cHash<td><font face=arial,helvetica color=white>uPermLevel<td><font face=arial,helvetica color=white>uLoginClient<td><font face=arial,helvetica color=white>cLogin<td><font face=arial,helvetica color=white>cHost<td><font face=arial,helvetica color=white>uTablePK<td><font face=arial,helvetica color=white>cTableName<td><font face=arial,helvetica color=white>uOwner<td><font face=arial,helvetica color=white>uCreatedBy<td><font face=arial,helvetica color=white>uCreatedDate<td><font face=arial,helvetica color=white>uModBy<td><font face=arial,helvetica color=white>uModDate</tr>"); mysql_data_seek(res,guStart-1); for(guN=0;guN<(guEnd-guStart+1);guN++) { field=mysql_fetch_row(res); if(!field) { printf("<tr><td><font face=arial,helvetica>End of data</table>"); Footer_ism3(); } if(guN % 2) printf("<tr bgcolor=#BBE1D3>"); else printf("<tr>"); time_t luTime12=strtoul(field[12],NULL,10); char cBuf12[32]; if(luTime12) ctime_r(&luTime12,cBuf12); else sprintf(cBuf12,"---"); time_t luTime14=strtoul(field[14],NULL,10); char cBuf14[32]; if(luTime14) ctime_r(&luTime14,cBuf14); else sprintf(cBuf14,"---"); printf("<td><a class=darkLink href=unxsVZ.cgi?gcFunction=tLogMonth&uLogMonth=%s>%s</a>" ,field[0] ,field[0]); printf("<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s</tr>" ,field[1] ,ForeignKey("tLogType","cLabel",strtoul(field[2],NULL,10)) ,field[3] ,field[4] ,field[5] ,field[6] ,field[7] ,field[8] ,field[9] ,ForeignKey("tClient","cLabel",strtoul(field[10],NULL,10)) ,ForeignKey("tClient","cLabel",strtoul(field[11],NULL,10)) ,cBuf12 ,ForeignKey("tClient","cLabel",strtoul(field[13],NULL,10)) ,cBuf14 ); } printf("</table></form>\n"); Footer_ism3(); }//tLogMonthList()
int main(int argc, char **argv) { int bufsize = 1024*1024; char buffer[bufsize], *bstate; int err, i, mode; Net_timeout_t dt; time_t t; osd_id_t id; char print_time[128]; uint64_t bytes, total_bytes; double fb1, fb2; uint64_t base_unit; double units; if (argc < 7) { printf("expire_list host port RID mode time count\n"); printf("\n"); printf(" mode - abs or rel\n"); printf(" time - Future time with format of days:hours:min:sec\n"); printf(" count - Number of allocations to retreive\n"); printf("\n"); return(0); } base_unit = 1024 * 1024; units = base_unit; units = 1.0 / units; i = 1; char *host = argv[i]; i++; int port = atoi(argv[i]); i++; char *rid = argv[i]; i++; mode = 0; if (strcmp(argv[i], "abs") == 0) mode = 1; i++; t = parse_time(argv[i]); i++; int count = atoi(argv[i]); dns_cache_init(10); NetStream_t *ns = new_netstream(); ns_config_sock(ns, -1, 0); set_net_timeout(&dt, 5, 0); err = net_connect(ns, host, port, dt); if (err != 0) { printf("get_alloc: Can't connect to host! host=%s port=%d err=%d\n", host, port, err); return(err); } sprintf(buffer, "1 %d %s %d " TT " %d 10\n", INTERNAL_EXPIRE_LIST, rid, mode, t, count); err = write_netstream(ns, buffer, strlen(buffer), dt); err = readline_netstream(ns, buffer, bufsize, dt); if (err > 0) { err = atoi(string_token(buffer, " ", &bstate, &err)); if (err != IBP_OK) { printf("Error %d returned!\n", err); close_netstream(ns); return(err); } } //** Cycle through the data ** total_bytes = 0; printf("n Time date ID mb_max total_max_mb\n"); printf("------------------------------------------------------------------------------------------------------\n"); err = 0; i = 0; while (err != -1) { buffer[0] = '\0'; err = readline_netstream(ns, buffer, bufsize, dt); //printf("err=%d buf=%s\n", err, buffer); if (err > 0) { if (strcmp("END", buffer) == 0) { //** Finished err = -1; } else { parse_line(buffer, &t, &id, &bytes); ctime_r(&t, print_time); print_time[strlen(print_time)-1] = '\0'; total_bytes = total_bytes + bytes; fb1 = bytes * units; fb2 = total_bytes * units; printf("%4d " TT " * %s * " LU " * %lf * %lf\n", i, t, print_time, id, fb1, fb2); } } i++; } close_netstream(ns); printf("\n"); return(0); }
/* ** Parse a str in GMT format to a local time time_t representation ** Four formats are accepted: ** ** Wkd, 00 Mon 0000 00:00:00 GMT (rfc1123) ** Weekday, 00-Mon-00 00:00:00 GMT (rfc850) ** Wkd Mon 00 00:00:00 0000 GMT (ctime) ** 1*DIGIT (delta-seconds) */ PUBLIC time_t HTParseTime (const char * str, HTUserProfile * up, BOOL expand) { char * s; struct tm tm; time_t t; if (!str) return 0; if ((s = strchr(str, ','))) { /* Thursday, 10-Jun-93 01:29:59 GMT */ s++; /* or: Thu, 10 Jan 1993 01:29:59 GMT */ while (*s && *s==' ') s++; if (strchr(s,'-')) { /* First format */ HTTRACE(CORE_TRACE, "Format...... Weekday, 00-Mon-00 00:00:00 GMT\n"); if ((int)strlen(s) < 18) { HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format \"%s\"\n" _ s); return 0; } tm.tm_mday = strtol(s, &s, 10); tm.tm_mon = make_month(s, &s); tm.tm_year = strtol(++s, &s, 10); tm.tm_hour = strtol(s, &s, 10); tm.tm_min = strtol(++s, &s, 10); tm.tm_sec = strtol(++s, &s, 10); } else { /* Second format */ HTTRACE(CORE_TRACE, "Format...... Wkd, 00 Mon 0000 00:00:00 GMT\n"); if ((int)strlen(s) < 20) { HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format \"%s\"\n" _ s); return 0; } tm.tm_mday = strtol(s, &s, 10); tm.tm_mon = make_month(s, &s); tm.tm_year = strtol(s, &s, 10) - 1900; tm.tm_hour = strtol(s, &s, 10); tm.tm_min = strtol(++s, &s, 10); tm.tm_sec = strtol(++s, &s, 10); } } else if (isdigit((int) *str)) { if (strchr(str, 'T')) { /* ISO (limited format) date string */ HTTRACE(CORE_TRACE, "Format...... YYYY.MM.DDThh:mmStzWkd\n"); s = (char *) str; while (*s && *s==' ') s++; if ((int)strlen(s) < 21) { HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format `%s\'\n" _ s); return 0; } tm.tm_year = strtol(s, &s, 10) - 1900; tm.tm_mon = strtol(++s, &s, 10); tm.tm_mday = strtol(++s, &s, 10); tm.tm_hour = strtol(++s, &s, 10); tm.tm_min = strtol(++s, &s, 10); tm.tm_sec = strtol(++s, &s, 10); } else { /* delta seconds */ t = expand ? time(NULL) + atol(str) : atol(str); #ifdef HTDEBUG if (CORE_TRACE) { if (expand) { #if defined (HAVE_CTIME_R_2) char buffer[CTIME_MAX]; HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds, or in local time: %s" _ str _ (long) t _ (char *) ctime_r(&t, buffer)); #elif defined(HAVE_CTIME_R_3) char buffer[CTIME_MAX]; HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds, or in local time: %s" _ str _ (long) t _ (char *) ctime_r(&t, buffer, CTIME_MAX)); #else HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds, or in local time: %s" _ str _ (long) t _ ctime(&t)); #endif /* HT_REENTRANT */ } else { HTTRACE(CORE_TRACE, "Time string. Delta-time %s parsed to %ld seconds\n" _ str _ (long) t); } } #endif /* HT_DEBUG */ return t; } } else { /* Try the other format: Wed Jun 9 01:29:59 1993 GMT */ HTTRACE(CORE_TRACE, "Format...... Wkd Mon 00 00:00:00 0000 GMT\n"); s = (char *) str; while (*s && *s==' ') s++; HTTRACE(CORE_TRACE, "Trying...... The Wrong time format: %s\n" _ s); if ((int)strlen(s) < 24) { HTTRACE(CORE_TRACE, "ERROR....... Not a valid time format \"%s\"\n" _ s); return 0; } tm.tm_mon = make_month(s, &s); tm.tm_mday = strtol(s, &s, 10); tm.tm_hour = strtol(s, &s, 10); tm.tm_min = strtol(++s, &s, 10); tm.tm_sec = strtol(++s, &s, 10); tm.tm_year = strtol(s, &s, 10) - 1900; } if (tm.tm_sec < 0 || tm.tm_sec > 59 || tm.tm_min < 0 || tm.tm_min > 59 || tm.tm_hour < 0 || tm.tm_hour > 23 || tm.tm_mday < 1 || tm.tm_mday > 31 || tm.tm_mon < 0 || tm.tm_mon > 11 || tm.tm_year <70 || tm.tm_year >120) { HTTRACE(CORE_TRACE, "ERROR....... Parsed illegal time: %02d.%02d.%02d %02d:%02d:%02d\n" _ tm.tm_mday _ tm.tm_mon+1 _ tm.tm_year _ tm.tm_hour _ tm.tm_min _ tm.tm_sec); return 0; } #if 0 #if defined(HAVE_TIMEZONE) && defined(HAVE_ALTZONE) tm.tm_isdst = daylight; /* Already taken into account */ HTTRACE(CORE_TRACE, "Time string. Daylight is %s\n" _ daylight>0 ? "on" : daylight==0 ? "off" : "unknown"); #endif #else /* Let mktime decide whether we have DST or not */ tm.tm_isdst = -1; #endif #ifdef HAVE_MKTIME t = mktime(&tm); t += (up ? HTUserProfile_timezone(up) : HTGetTimeZoneOffset()); #else #ifdef HAVE_TIMEGM t = timegm(&tm); #else #error "Neither mktime nor timegm defined" #endif /* HAVE_TIMEGM */ #endif /* HAVE_MKTIME */ HTTRACE(CORE_TRACE, "Time string. %s parsed to %ld calendar time or `%s' in local time\n" _ str _ (long) t _ ctime(&t)); return t; }
int main(int argc, char * argv[]) { int debug = 0; char m_time[32]; char c_time[32]; char a_time[32]; const char * pSmbPath = NULL; const char * pLocalPath = NULL; struct stat st; if (argc == 1) { pSmbPath = "smb://RANDOM/Public/small"; pLocalPath = "/random/home/samba/small"; } else if (argc == 2) { pSmbPath = argv[1]; pLocalPath = NULL; } else if (argc == 3) { pSmbPath = argv[1]; pLocalPath = argv[2]; } else { printf("usage: " "%s [ smb://path/to/file [ /nfs/or/local/path/to/file ] ]\n", argv[0]); return 1; } smbc_init(get_auth_data_fn, debug); if (smbc_stat(pSmbPath, &st) < 0) { perror("smbc_stat"); return 1; } printf("\nSAMBA\n mtime:%lu/%s ctime:%lu/%s atime:%lu/%s\n", st.st_mtime, ctime_r(&st.st_mtime, m_time), st.st_ctime, ctime_r(&st.st_ctime, c_time), st.st_atime, ctime_r(&st.st_atime, a_time)); if (pLocalPath != NULL) { if (stat(pLocalPath, &st) < 0) { perror("stat"); return 1; } printf("LOCAL\n mtime:%lu/%s ctime:%lu/%s atime:%lu/%s\n", st.st_mtime, ctime_r(&st.st_mtime, m_time), st.st_ctime, ctime_r(&st.st_ctime, c_time), st.st_atime, ctime_r(&st.st_atime, a_time)); } return 0; }
int main(int argc, char *argv[]) { int set_mode = 0; int adjust_time = 0; int time_difference = 0; int retval = 0; int success = 0; int c; // Store the name of the program argv0 = strrchr(argv[0], '/'); if (argv0) argv0++; else argv0 = argv[0]; // Parse parameters while ((c = getopt(argc, argv, "aspuln:t:d:h?")) != -1) { switch(c) { case 'a': adjust_time = 1; break; case 's': set_mode = 1; break; case 'p': print_mode = 1; break; case 'u': use_tcp = 0; break; case 'l': log_mode = 1; break; case 't': timeout = atoi(optarg); break; case 'd': time_difference = atoi(optarg); break; case 'n': service = optarg; break; case 'h': case '?': usage(0); break; default: fprintf(stderr, "Unknown option %c\n", c); usage(1); break; } } // Remove the already parsed parameters argc -= optind; argv += optind; // No hosts on command line ? if (argc<1) usage(1); if (!set_mode && !print_mode) print_mode = 1; if (log_mode) openlog(argv0, LOG_PID, LOG_CRON); // Query each of the servers on the command line for(; argc-- ; argv++) { time_t timeval=0; char timestr[26]; if(!rdate(*argv, &timeval)) { // keep track of the succesful request success = 1; // apply the requested difference timeval += time_difference; // Convert the time to a string ctime_r( &timeval, timestr ); timestr[ strlen(timestr)-1 ] = 0; write_log(0, "[%s]\t%s", *argv, timestr); // Set local time to remote host's ? if (set_mode) { struct timeval tv; if (!adjust_time) { logwtmp("|", "date", ""); tv.tv_sec = timeval; tv.tv_usec = 0; if (settimeofday(&tv, NULL)) { write_log(1, "could not set system time: %s", strerror(errno)); retval = 1; break; } logwtmp("{", "date", ""); } else { struct timeval tv_now; if (gettimeofday(&tv_now, NULL) == -1) { write_log(1, "could not get system time: %s", strerror(errno)); retval = 1; break; } tv.tv_sec = timeval - tv_now.tv_sec; tv.tv_usec = 0; write_log(0, "adjusting local clock by %d seconds.", tv.tv_sec); if (adjtime(&tv, NULL)) { write_log(1, "could not adjust system time: %s", strerror(errno)); retval = 1; break; } } // Only set time to first successful host set_mode = 0; } } } // Close the log if (log_mode) closelog(); // Successful ? if (!retval && !success) retval = 1; return retval; }
void SensorManager::retrieveStatistics(bool ignoreshutdown) { const char* xmlpre = "<vermont>\n\t<sensorData time=\"%s\" epochtime=\"%d.%03d\" host=\"%s\">\n"; const char* xmlpost = "\t</sensorData>\n</vermont>\n"; const char* xmlglobals = "\t\t<%s>%s</%s>\n"; string lockfile = outputFilename + ".lock"; bool haveGraphLock; // we must not wait for the graph lock, else there may be a race condition with // the ConfigManager while (! (haveGraphLock = graphIS->tryLockGraph())) { if (smExitFlag) break; timespec timeout = { 0, 200000 }; nanosleep(&timeout, NULL); } if (!ignoreshutdown && smExitFlag) return; const char* openflags = (append ? "a" : "w"); FILE* file = fopen(outputFilename.c_str(), openflags); if (!file) { THROWEXCEPTION("failed to reopen file %s", outputFilename.c_str()); perror("error:"); } timeval tvcurtime = unixtime(); time_t curtime = tvcurtime.tv_sec; char curtimestr[100]; ctime_r(&curtime, curtimestr); curtimestr[strlen(curtimestr)-1] = 0; fprintf(file, xmlpre, curtimestr, curtime, tvcurtime.tv_usec/1000, hostname); char text[100]; snprintf(text, 100, "%u", static_cast<uint32_t>(getpid())); fprintf(file, xmlglobals, "pid", text, "pid"); char lasttimestr[100]; ctime_r(&lasttime, lasttimestr); lasttimestr[strlen(lasttimestr)-1] = 0; fprintf(file, xmlglobals, "lastTime", lasttimestr, "lastTime"); #if defined(__linux__) const char* xmlglobalsuint = "\t\t<%s>%u</%s>\n"; ThreadCPUInterface::SystemInfo si = ThreadCPUInterface::getSystemInfo(); fprintf(file, "\t\t<jiffyFrequency>%llu</jiffyFrequency>\n", (long long unsigned)hertzValue); fprintf(file, xmlglobalsuint, "processorAmount", si.noCPUs, "processorAmount"); for (uint16_t i=0; i<si.sysJiffies.size(); i++) { double sysutil = (si.sysJiffies[i]-lastSystemInfo.sysJiffies[i])/(static_cast<double>(curtime)-lasttime)/hertzValue*100; double userutil = (si.userJiffies[i]-lastSystemInfo.userJiffies[i])/(static_cast<double>(curtime)-lasttime)/hertzValue*100; fprintf(file, "\t\t<processor id=\"%u\"><util type=\"system\">%.2f</util><util type=\"user\">%.2f</util></processor>\n", i, sysutil, userutil); } fprintf(file, "\t\t<memory><free type=\"bytes\">%llu</free><total type=\"bytes\">%llu</total></memory>\n", (long long unsigned)si.freeMemory, (long long unsigned)si.totalMemory); lastSystemInfo = si; #endif //DPRINTF("*** sensor data at %s", ctime(&curtime)); Graph* g = graphIS->getGraph(); vector<CfgNode*> nodes = g->getNodes(); vector<CfgNode*>::iterator iter = nodes.begin(); while (iter != nodes.end()) { Cfg* cfg = (*iter)->getCfg(); Sensor* s = cfg->getInstance(); vector<uint32_t> nextids = cfg->getNext(); writeSensorXML(file, s, cfg->getName().c_str(), cfg->getID(), true, curtime, lasttime, &nextids); iter++; } // iterate through all non-module sensors mutex.lock(); list<SensorEntry>::const_iterator siter = sensors.begin(); while (siter != sensors.end()) { //DPRINTFL(MSG_ERROR, "non-module cfg->getName()=%s, s=%u", siter->name.c_str(), siter->sensor); writeSensorXML(file, siter->sensor, siter->name.c_str(), siter->id, false, curtime, lasttime, NULL); siter++; } mutex.unlock(); fprintf(file, "%s", xmlpost); fclose(file); if (haveGraphLock) graphIS->unlockGraph(); }
int main(int argc, char *argv[]) { char *p, tmbuf[PFL_CTIME_BUFSIZ], *cursor_file = NULL, c; uint64_t newtxg = 0, newfid = 0, fid, cycle, newcycle; int dump = 0, verbose = 0, fd, rc; struct psc_journal_cursor cursor; while ((c = getopt(argc, argv, "c:df:vx:")) != -1) switch (c) { case 'c': cursor_file = optarg; break; case 'd': dump = 1; break; case 'f': newfid = strtol(optarg, NULL, 0); break; case 'v': verbose = 1; break; case 'x': newtxg = strtol(optarg, NULL, 0); break; default: usage(); } argc -= optind; if (argc || !cursor_file) usage(); fd = open(cursor_file, O_RDWR); if (fd < 0) err(1, "failed to open %s", cursor_file); rc = pread(fd, &cursor, sizeof(struct psc_journal_cursor), 0); if (rc != sizeof(struct psc_journal_cursor)) err(1, "cursor file read"); ctime_r((time_t *)&cursor.pjc_timestamp, tmbuf); p = strchr(tmbuf, '\n'); if (p) *p = '\0'; cycle = FID_GET_CYCLE(cursor.pjc_fid); if (dump || verbose) { printf("Cursor contents of %s:\n" "\tmagic %"PRIx64"\n" "\tversion %"PRIx64"\n" "\ttimestamp %"PRId64" (%s)\n" "\tuuid %s\n" "\tcommit_txg %"PRId64"\n" "\tdistill_xid %"PRId64"\n" "\tfid %#"PRIx64" " "(flag=%"PRIx64", siteid=%"PRIx64", " "cycle=%"PRIx64", inum=%"PRIx64")\n" "\tseqno_lwm %"PRIx64"\n" "\tseqno_hwm %"PRIx64"\n" "\ttail %"PRIx64"\n" "\tupdate_seqno %"PRIx64"\n" "\treclaim_seqno %"PRIx64"\n" "\treplay_xid %"PRIx64"\n\n", cursor_file, cursor.pjc_magic, cursor.pjc_version, cursor.pjc_timestamp, tmbuf, cursor.pjc_uuid, cursor.pjc_commit_txg, cursor.pjc_distill_xid, cursor.pjc_fid, FID_GET_FLAGS(cursor.pjc_fid), FID_GET_SITEID(cursor.pjc_fid), FID_GET_CYCLE(cursor.pjc_fid), FID_GET_INUM(cursor.pjc_fid), cursor.pjc_seqno_lwm, cursor.pjc_seqno_hwm, cursor.pjc_tail, cursor.pjc_update_seqno, cursor.pjc_reclaim_seqno, cursor.pjc_replay_xid); fid = cursor.pjc_fid; fid = fid | FID_MAX_INUM; printf("The max FID for this cycle is %#"PRIx64"\n", fid); if (cycle < ((UINT64_C(1) << SLASH_FID_CYCLE_BITS) - 1)) { fid++; printf("The first FID for the next cycle is %#"PRIx64"\n", fid); } if (dump) exit(0); } if (!newtxg && !newfid) errx(1, "neither fid nor txg was specified"); if (newtxg) cursor.pjc_commit_txg = newtxg; if (newfid) { newcycle = FID_GET_CYCLE(newfid); if (newcycle <= cycle) errx(1, "cycle must be increased when setting a new FID"); cursor.pjc_fid = newfid; } rc = pwrite(fd, &cursor, sizeof(struct psc_journal_cursor), 0); if (rc != sizeof(struct psc_journal_cursor)) err(1, "cursor file write"); if (close(fd) == -1) err(1, "cursor file close"); exit(0); }
PHPAPI char *php_ctime_r(const time_t *clock, char *buf) { if (ctime_r(clock, buf, 26) != -1) return (buf); return (NULL); }
int main( int argc, const char * argv[] ) { #pragma unused(argc) #pragma unused(argv) int my_tests_count, i; int err; int my_failures = 0; int list_the_tests = 0; const char * my_targetp; time_t my_start_time, my_end_time; struct stat my_stat_buf; char my_buffer[64]; uid_t sudo_uid = 0; const char * sudo_uid_env; gid_t sudo_gid; const char * sudo_gid_env; sranddev( ); /* set up seed for our random name generator */ g_cmd_namep = argv[0]; /* make sure SIGCHLD is not ignored, so wait4 calls work */ signal(SIGCHLD, SIG_DFL); /* NOTE - code in create_target_directory will append '/' if it is necessary */ my_targetp = getenv("TMPDIR"); if ( my_targetp == NULL ) my_targetp = "/tmp"; /* make sure we are running as root */ if ( ( getuid() != 0 ) || ( geteuid() != 0 ) ) { printf( "Test must be run as root\n", g_cmd_namep ); exit( -1 ); } sudo_uid_env = getenv("SUDO_UID"); if ( sudo_uid_env ) { sudo_uid = strtol(sudo_uid_env, NULL, 10); } /* switch real uid to a non_root user, while keeping effective uid as root */ if ( sudo_uid != 0 ) { setreuid( sudo_uid, 0 ); } else { /* Default to 501 if no sudo uid found */ setreuid( 501, 0 ); } /* restore the gid if run through sudo */ sudo_gid_env = getenv("SUDO_GID"); if ( sudo_gid_env ) { sudo_gid = strtol(sudo_gid_env, NULL, 10); } if ( getgid() == 0 ) { if ( sudo_gid != 0 ) { setgid( sudo_gid ); } else { /* Default to 20 if no sudo gid found */ setgid( 20 ); } } /* parse input parameters */ for ( i = 1; i < argc; i++ ) { if ( strcmp( argv[i], "-u" ) == 0 ) { usage( ); } if ( strcmp( argv[i], "-t" ) == 0 || strcmp( argv[i], "-target" ) == 0 ) { if ( ++i >= argc ) { printf( "invalid target parameter \n" ); usage( ); } /* verify our target directory exists */ my_targetp = argv[i]; err = stat( my_targetp, &my_stat_buf ); if ( err != 0 || S_ISDIR(my_stat_buf.st_mode) == 0 ) { printf( "invalid target path \n" ); if ( err != 0 ) { printf( "stat call failed with error %d - \"%s\" \n", errno, strerror( errno) ); } usage( ); } continue; } if ( strcmp( argv[i], "-f" ) == 0 || strcmp( argv[i], "-failures" ) == 0 ) { if ( ++i >= argc ) { printf( "invalid failures parameter \n" ); usage( ); } /* get our max number of failures */ g_max_failures = strtol( argv[i], NULL, 10 ); continue; } if ( strcmp( argv[i], "-l" ) == 0 || strcmp( argv[i], "-list" ) == 0 ) { /* list all the tests this tool will do. */ list_the_tests = 1; continue; } if ( strcmp( argv[i], "-r" ) == 0 || strcmp( argv[i], "-run" ) == 0 ) { if ( ++i >= argc ) { printf( "invalid run tests parameter \n" ); usage( ); } /* get which tests to run */ if ( parse_tests_to_run( argc, argv, &i ) != 0 ) { printf( "invalid run tests parameter \n" ); usage( ); } continue; } if ( strcmp( argv[i], "-s" ) == 0 || strcmp( argv[i], "-skip" ) == 0 ) { /* set that want to skip the setuid related tests - this is useful for debgugging since since I can't * get setuid tests to work while in gdb. */ g_skip_setuid_tests = 1; continue; } if ( strcmp( argv[i], "-testbot" ) == 0 ) { g_testbots_active = 1; continue; } printf( "invalid argument \"%s\" \n", argv[i] ); usage( ); } /* done parsing. */ /* Check if we are running under testbots */ #if RUN_UNDER_TESTBOTS g_testbots_active = 1; #endif /* Code added to run xnu_quick_test under testbots */ if ( g_testbots_active == 1 ) { printf("[TEST] xnu_quick_test \n"); /* Declare the beginning of test suite */ } /* Populate groups list if we're in single user mode */ if (setgroups_if_single_user()) { return 1; } if ( list_the_tests != 0 ) { list_all_tests( ); return 0; } /* build a test target directory that we use as our path to create any test * files and directories. */ create_target_directory( my_targetp ); printf( "Will allow %ld failures before testing is aborted \n", g_max_failures ); my_start_time = time( NULL ); printf( "\nBegin testing - %s \n", ctime_r( &my_start_time, &my_buffer[0] ) ); printf( "Current architecture is %s\n", current_arch() ); /* Code added to run xnu_quick_test under testbots */ /* run each test that is marked to run in our table until we complete all of them or * hit the maximum number of failures. */ my_tests_count = (sizeof( g_tests ) / sizeof( g_tests[0] )); for ( i = 0; i < (my_tests_count - 1); i++ ) { int my_err; test_entryp my_testp; my_testp = &g_tests[i]; if ( my_testp->test_run_it == 0 || my_testp->test_routine == NULL ) continue; if ( g_testbots_active == 1 ) { printf("[BEGIN] %s \n", my_testp->test_infop); } printf( "test #%d - %s \n", (i + 1), my_testp->test_infop ); fflush(stdout); my_err = my_testp->test_routine( my_testp->test_input ); if ( my_err != 0 ) { printf("\t--> FAILED \n"); printf("SysCall %s failed", my_testp->test_infop); printf("Result %d", my_err); my_failures++; if ( my_failures > g_max_failures ) { printf( "\n Reached the maximum number of failures - Aborting xnu_quick_test. \n" ); /* Code added to run xnu_quick_test under testbots */ if ( g_testbots_active == 1 ) { printf("[FAIL] %s \n", my_testp->test_infop); } goto exit_this_routine; } /* Code added to run xnu_quick_test under testbots */ if ( g_testbots_active == 1 ) { printf("\n[FAIL] %s \n", my_testp->test_infop); } continue; } /* Code added to run xnu_quick_test under testbots */ if ( g_testbots_active == 1 ) { printf("[PASS] %s \n", my_testp->test_infop); } } exit_this_routine: my_end_time = time( NULL ); printf( "\nEnd testing - %s \n", ctime_r( &my_end_time, &my_buffer[0] ) ); /* clean up our test directory */ rmdir( &g_target_path[0] ); /* exit non zero if there are any failures */ return my_failures != 0; } /* main */
int main() { time_t xmas2002 = 1040786563ll; struct tm* tm_ptr; // Make sure stime() always fails. printf("stime: %d\n", stime(&xmas2002)); // Verify that tzname sets *something*. tzset(); printf("tzname[0] set: %d\n", strlen(tzname[0]) >= 3); printf("tzname[1] set: %d\n", strlen(tzname[1]) >= 3); // Verify gmtime() creates correct struct. tm_ptr = gmtime(&xmas2002); printf("sec: %d\n", tm_ptr->tm_sec); printf("min: %d\n", tm_ptr->tm_min); printf("hour: %d\n", tm_ptr->tm_hour); printf("day: %d\n", tm_ptr->tm_mday); printf("mon: %d\n", tm_ptr->tm_mon); printf("year: %d\n", tm_ptr->tm_year); printf("wday: %d\n", tm_ptr->tm_wday); printf("yday: %d\n", tm_ptr->tm_yday); printf("dst: %d\n", tm_ptr->tm_isdst); printf("off: %d\n", tm_ptr->tm_gmtoff); printf("zone: %s\n", tm_ptr->tm_zone); // Verify timegm() reverses gmtime. printf("timegm <-> gmtime: %d\n", timegm(tm_ptr) == xmas2002); // Verify gmtime_r() doesn't clobber static data. time_t t1 = 0; struct tm tm1; gmtime_r(&t1, &tm1); printf("old year: %d\n", tm_ptr->tm_year); printf("new year: %d\n", tm1.tm_year); gmtime(&xmas2002); printf("old year again: %d\n", tm_ptr->tm_year); // Verify localtime() picks up timezone data. time_t t2 = xmas2002 - 60 * 60 * 24 * 30 * 6; tm_ptr = localtime(&t2); time_t dst_diff = (tm_ptr->tm_isdst == 1) ? tm_ptr->tm_isdst * 60 * 60 : 0; printf("localtime timezone: %d\n", (_timezone + tm_ptr->tm_gmtoff == dst_diff)); // glibc needs printf("localtime daylight: %d\n", _daylight == tm_ptr->tm_isdst); // no prefix "_"s printf("localtime tzname: %d\n", (!strcmp(tzname[0], tm_ptr->tm_zone) || !strcmp(tzname[1], tm_ptr->tm_zone))); // Verify localtime() and mktime() reverse each other. printf("localtime <-> mktime: %d\n", mktime(localtime(&xmas2002)) == xmas2002); // Verify localtime_r() doesn't clobber static data. time_t t3 = 0; struct tm tm2; localtime_r(&t3, &tm2); printf("localtime_r(1): %d\n", tm2.tm_year != tm_ptr->tm_year); localtime(&xmas2002); printf("localtime_r(2): %d\n", tm2.tm_year != tm_ptr->tm_year); // Verify time() returns reasonable value (between 2011 and 2030). time_t t4 = 0; time(&t4); timespec ts; assert(clock_gettime(0, &ts) == 0); assert(abs(ts.tv_sec - t4) <= 2); printf("time: %d\n", t4 > 1309635200ll && t4 < 1893362400ll); // Verify difftime() calculates accurate time difference. time_t t5 = 1309635200ll; printf("difftime+: %lf\n", difftime(t5, xmas2002)); printf("difftime-: %lf\n", difftime(xmas2002, t5)); // Verify dysize() knows its leap years. printf("1854 days: %d\n", dysize(1854)); printf("2000 days: %d\n", dysize(2000)); printf("2001 days: %d\n", dysize(2001)); printf("2004 days: %d\n", dysize(2004)); // Verify asctime() formatting(). printf("asctime: %s", asctime(gmtime(&xmas2002))); // Verify asctime_r() doesn't clobber static data. time_t t6 = 1309635200ll; tm_ptr = gmtime(&xmas2002); char* formatted = asctime(tm_ptr); char buffer[32]; asctime_r(gmtime(&t6), buffer); printf("old asctime: %s", formatted); printf("new asctime_r: %s", buffer); asctime_r(tm_ptr, buffer); printf("old asctime again: %s", formatted); // Verify that clock() advances. time_t start_t = time(NULL); clock_t start = clock(); printf("clock(start): %d\n", start >= 0); while (clock() - start < 2 * CLOCKS_PER_SEC); // Poor man's sleep(). clock_t diff = time(NULL) - start_t; printf("clock(end): %d\n", diff >= 2 && diff < 30); // Verify that ctime_r(x, buf) is equivalent to asctime_r(localtime(x), buf). time_t t7 = time(0); char buffer2[30]; char buffer3[30]; printf("ctime: %d\n", strcmp(ctime_r(&t7, buffer2), asctime_r(localtime(&t7), buffer3))); return 0; }
int fh_list(int num, int count) { struct fileheader fh; int i, posttime; char timetext[STRLEN]; if (num <= 0) num = 1; lseek(fd, (num - 1) * sizeof(struct fileheader), SEEK_SET); for (i=0; i<count; i++) { if (read(fd, &fh, sizeof(struct fileheader)) > 0) { if (fhbool.filename[0]) if (strcmp(fh.filename, fhopt.filename) != 0) continue; if (fhbool.id) if (fh.id != fhopt.id) continue; if (fhbool.groupid) if (fh.groupid != fhopt.groupid) continue; if (fhbool.reid) if (fh.reid != fhopt.reid) continue; if (fhbool.o_bid) if (fh.o_bid != fhopt.o_bid) continue; if (fhbool.o_id) if (fh.o_id != fhopt.o_id) continue; if (fhbool.o_groupid) if (fh.o_groupid != fhopt.o_groupid) continue; if (fhbool.o_reid) if (fh.o_reid != fhopt.o_reid) continue; if (fhbool.innflag[0]) if ((fh.innflag[0] != fhopt.innflag[0]) || (fh.innflag[1] != fhopt.innflag[1])) continue; if (fhbool.owner[0]) if (strcmp(fh.owner, fhopt.owner) != 0) continue; if (fhbool.eff_size) if (fh.eff_size != fhopt.eff_size) continue; if (fhbool.attachment) if (fh.attachment != fhopt.attachment) continue; if (fhbool.title[0]) if (strcmp(fh.title, fhopt.title) != 0) continue; if (fhbool.accessed[0]) if (fh.accessed[0] != fhopt.accessed[0]) continue; if (fhbool.accessed[1]) if (fh.accessed[1] != fhopt.accessed[1]) continue; if (fhbool.accessed[2]) if (fh.accessed[2] != fhopt.accessed[2]) continue; if (fhbool.accessed[3]) if (fh.accessed[3] != fhopt.accessed[3]) continue; if (binary) { fwrite(&fh, sizeof(struct fileheader), 1, stdout); } else { if (simple) printf("%d\n", num + i); else { posttime = get_posttime(&fh); ctime_r((time_t *)&posttime, timetext); timetext[strlen(timetext)-1] = 0; printf("%7d %-14s %-25.25s %s\n", num + i, fh.owner, timetext, fh.title); } } } } return 1; }
void tTemplateSetList(void) { MYSQL_RES *res; MYSQL_ROW field; ExttTemplateSetListSelect(); mysql_query(&gMysql,gcQuery); if(mysql_error(&gMysql)[0]) htmlPlainTextError(mysql_error(&gMysql)); res=mysql_store_result(&gMysql); guI=mysql_num_rows(res); PageMachine("tTemplateSetList",1,"");//1 is auto header list guMode. Opens table! //Filter select drop down ExttTemplateSetListFilter(); printf("<input type=text size=16 name=gcCommand maxlength=98 value=\"%s\" >",gcCommand); printf("</table>\n"); printf("<table bgcolor=#9BC1B3 border=0 width=100%%>\n"); printf("<tr bgcolor=black><td><font face=arial,helvetica color=white>uTemplateSet<td><font face=arial,helvetica color=white>cLabel<td><font face=arial,helvetica color=white>uOwner<td><font face=arial,helvetica color=white>uCreatedBy<td><font face=arial,helvetica color=white>uCreatedDate<td><font face=arial,helvetica color=white>uModBy<td><font face=arial,helvetica color=white>uModDate</tr>"); mysql_data_seek(res,guStart-1); for(guN=0;guN<(guEnd-guStart+1);guN++) { field=mysql_fetch_row(res); if(!field) { printf("<tr><td><font face=arial,helvetica>End of data</table>"); Footer_ism3(); } if(guN % 2) printf("<tr bgcolor=#BBE1D3>"); else printf("<tr>"); time_t luTime4=strtoul(field[4],NULL,10); char cBuf4[32]; if(luTime4) ctime_r(&luTime4,cBuf4); else sprintf(cBuf4,"---"); time_t luTime6=strtoul(field[6],NULL,10); char cBuf6[32]; if(luTime6) ctime_r(&luTime6,cBuf6); else sprintf(cBuf6,"---"); printf("<td><input type=submit name=ED%s value=Edit> %s<td>%s<td>%s<td>%s<td>%s<td>%s<td>%s</tr>" ,field[0] ,field[0] ,field[1] ,ForeignKey(TCLIENT,"cLabel",strtoul(field[2],NULL,10)) ,ForeignKey(TCLIENT,"cLabel",strtoul(field[3],NULL,10)) ,cBuf4 ,ForeignKey(TCLIENT,"cLabel",strtoul(field[5],NULL,10)) ,cBuf6 ); } printf("</table></form>\n"); Footer_ism3(); }//tTemplateSetList()
static inline std::string time2str(const time_t &t) { char timebuf[26]; // I apologize for the magic constant. // ^^ See man 3 ctime_r return ctime_r(&t, timebuf); }
int main(int argc, char *argv[]) { long minn, maxn, mid, n, n2, ns, i; long besti; /* 0 for TC, 1, 2, ... for FFT(K0*3^(bestK-1)) */ long bestK; long K, K0 = 3; /* try K0, 3*K0, 9*K0 */ double T[4]; /* T[0] is for TC, T[1] for K0, T[2] for 3*K0, T[3] for 9*K0 */ double t1[4], t2[4]; unsigned long *a, *b, *c, *t, *u, *v; int nsz = 0; int tc_takes_too_long = 0; const char * reference = "TC"; maxn = 1000000; // default minn = GF2X_MUL_FFT_BEGIN_TUNE / 2 + 1; char * progname = argc ? argv[0] : ""; argc--,argv++; for( ; argc ; argc--,argv++) { int r; if (strcmp(argv[0], "--help") == 0) { usage(0); } if (strcmp(argv[0], "--no-toom") == 0) { tc_takes_too_long = 1; reference = "F1(K0)"; continue; } r = handle_tuning_mulstep(&argc, &argv); if (r < 0) usage(1); else if (r) continue; r = handle_tuning_outfile(&argc, &argv); if (r < 0) usage(1); else if (r) continue; if (strcmp(argv[0], "-k0") == 0) { argc--,argv++; if (! argc) usage(1); K0 = atoi(argv[0]); continue; } if (nsz == 0) { maxn = atoi(argv[0]); nsz++; continue; } if (nsz == 1) { minn = maxn; maxn = atoi(argv[0]); nsz++; continue; } usage(1); } if (nsz == 0) usage(1); set_tuning_output(); { char date[40]; time_t t; size_t u; struct utsname buf; time(&t); ctime_r(&t, date); u = strlen(date); for (; u && isspace(date[u - 1]); date[--u] = '\0'); uname(&buf); /* strip the dirname */ char * ptr = strrchr(progname, '/'); if (ptr) { ptr++; } else { ptr = progname; } fprintf(rp, "info-fft \"%s -s %.2f %ld run on %s on %s ; based on %s\"\n", ptr,mulstep,maxn,buf.nodename,date,GF2X_TOOM_TUNING_INFO); } printf("Tuning FFT multiplication to wordsize %ld\n\n", maxn); a = (unsigned long *) malloc(maxn * sizeof(unsigned long)); b = (unsigned long *) malloc(maxn * sizeof(unsigned long)); c = (unsigned long *) malloc(2 * maxn * sizeof(unsigned long)); u = (unsigned long *) malloc(2 * maxn * sizeof(unsigned long)); v = (unsigned long *) malloc(2 * maxn * sizeof(unsigned long)); t = (unsigned long *) malloc(gf2x_toomspace(maxn) * sizeof(unsigned long)); random_wordstring(a, maxn); random_wordstring(b, maxn); /* Skip n if (2*n < GF2X_MUL_FFT_BEGIN_TUNE) as this is too small for the FFT */ for (n = minn; n <= maxn;) { n2 = next_step(n, 3 * K0); // End of interval if (n2 > maxn) // Only go as far n2 = maxn; // as maxn. mid = (n + n2) / 2; // Mid-point printf("%ld..%ld ", n, n2); fflush(stdout); if (tc_takes_too_long) { T[0] = DBL_MAX; } else { TIME(T[0], gf2x_mul_toom(u, a, b, mid, t)); // Time Toom-Cook printf("TC:%1.1e ", T[0]); } fflush(stdout); besti = 0; bestK = 1; K = K0; i = 1; ugly_label: for ( ; i <= 3; i++, K *= 3) { TIME(t1[i], gf2x_mul_fft(c, a, mid, b, mid, K)); if (tc_takes_too_long) { memcpy(u, c, 2 * maxn * sizeof(unsigned long)); } check(a, mid, b, mid, reference, u, "F1", c); if (K >= GF2X_WORDSIZE) { TIME(t2[i], gf2x_mul_fft(v, a, mid, b, mid, -K)); check(a, mid, b, mid, "F1", c, "F2", v); } else { t2[i] = DBL_MAX; } if (t1[i] < t2[i]) { T[i] = t1[i]; printf("F1(%ld):%1.1e ", K, T[i]); } else { T[i] = t2[i]; printf("F2(%ld):%1.1e ", K, T[i]); } fflush(stdout); if (T[i] < T[besti]) { besti = i; bestK = (t2[i] > t1[i]) ? K : -K; /* -K for FFT2(|K|) */ } } if (T[3] < T[1] && T[3] < T[2]) { if (besti) { if (besti == 1) abort(); besti--; } K0 *= 3; /* K just stays as it was */ i = 3; T[1] = T[2]; T[2] = T[3]; goto ugly_label; /* Notice that we can't loop forever here. If we have T[3] < * T[2], this will ensure T[2] < T[1] at the next turn, * thereby forcing the other case not to happen */ } else if (T[1] < T[2] && T[1] < T[3] && K0 > 3) { K0 /= 3; } /* OK, this stair is done */ if (bestK == 1) printf("TC"); else { if (bestK > 0) printf("F1(%ld)", bestK); else printf("F2(%ld)", -bestK); } printf("\n"); fflush(stdout); if (T[0] >= 4 * T[besti] && !tc_takes_too_long) { printf("TC is taking too long, disabling for next sizes\n"); tc_takes_too_long = 1; reference = "F1(K0)"; } /* go to next size */ ns = n; n = next_step(n, 3 * K0); /* middle value of K */ if (n > n2) n = n2; /* end of last stair if K0 increased */ n++; if (n < mid) { /* redo the last stair if K0 decreased */ n = ns; } else { fprintf(rp, "fft %ld %ld\n", ns == minn ? 1 : ns, ns == minn ? 1 : bestK); } } free(a); free(b); free(c); free(t); free(u); free(v); return 0; }
inline int add_logfile_entry(time_t date, struct in_addr src_ip, unsigned long src_port, struct in_addr dst_ip, unsigned long dst_port, double packets, double bytes, struct t_ip_groups *groups ) { char date_str[80]; int src_grp, dst_grp; int traf_idx; int flag_local1, flag_local2; /* Если начальное время еще неопределено, берем его из перой строки */ if (groups->start == (time_t)-1) { struct tm t; /* Округляем время на начало часа */ localtime_r(&date, &t); t.tm_sec = 0; t.tm_min = 0; groups->start = mktime(&t); if ( groups->start == (time_t)-1 ) { fprintf(stderr, "cannot convert time\n"); return -1; } } traf_idx = time2idx(groups->start, date); if ( traf_idx < 0 || traf_idx >= MAX_HOUR_CNT) { ctime_r(&groups->start, date_str); date_str[24]='\0'; fprintf(stderr, "timedate out of range +Start time: %s, max num hour: %u\n", date_str, MAX_HOUR_CNT); return -2; } /* Максимальный индекс для опеределения с какого и по какое время выдавать результат */ if ( groups->traf_max < traf_idx) groups->traf_max = traf_idx; src_grp = lookup_ip(groups, src_ip, &flag_local1); dst_grp = lookup_ip(groups, dst_ip, &flag_local2); if ( (src_grp == -1) && (dst_grp >= 0) ) { /* Входящий трафик (к клиенту) */ groups->grp[dst_grp].traf_inb[traf_idx] += bytes; }else if ( (src_grp >= 0) && (dst_grp == -1) ) { /* Исходящий трафик (от клиента) */ groups->grp[src_grp].traf_outb[traf_idx] += bytes; }else if ( (src_grp >= 0) && (dst_grp >= 0) ) { /* * Локальный трафик (либо между узлами определенными в группах) * Его надо либо не считать, либо записывать только в одну группу * Если его записывать в обе группы, он испортит общую статистику * по загрузке. */ /* groups->grp[dst_grp].traf_inb[traf_idx] += bytes; */ /* Выводим трафик как локальный. local_flag устанавливается чтобы * выводить меньше одинаковых строк локального трафика */ if ( !flag_local1 || !flag_local2 ) { char src_ip_str[16]; char dst_ip_str[16]; set_local_flag(groups, src_ip, 1); set_local_flag(groups, dst_ip, 1); strncpy(src_ip_str, inet_ntoa(src_ip), sizeof(src_ip_str) - 1); strncpy(dst_ip_str, inet_ntoa(dst_ip), sizeof(dst_ip_str) - 1); ctime_r(&date, date_str); date_str[24]='\0'; fprintf(stderr, "local: %s(%i) from %s:%lu(%i) to %s:%lu(%i) - %lg packets %lg bytes\n", date_str, traf_idx, src_ip_str, src_port, src_grp>=0?groups->grp[src_grp].num:src_grp, dst_ip_str, dst_port, dst_grp>=0?groups->grp[dst_grp].num:dst_grp, packets, bytes); } }else /*if ( (src_grp == -1 ) && (dst_grp == -1) ) */ { /* Неопределенный трафик */ char src_ip_str[16]; char dst_ip_str[16]; strncpy(src_ip_str, inet_ntoa(src_ip), sizeof(src_ip_str) - 1); strncpy(dst_ip_str, inet_ntoa(dst_ip), sizeof(dst_ip_str) - 1); ctime_r(&date, date_str); date_str[24]='\0'; fprintf(stderr, "unknown: %s(%i) from %s:%lu(%i) to %s:%lu(%i) - %lg packets %lg bytes\n", date_str, traf_idx, src_ip_str, src_port, src_grp>=0?groups->grp[src_grp].num:src_grp, dst_ip_str, dst_port, dst_grp>=0?groups->grp[dst_grp].num:dst_grp, packets, bytes); } return 0; }
void vsyslog(int pri, const char *fmt, va_list ap) { int cnt; char ch, *p; time_t now; int fd, saved_errno; char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64]; FILE *fp, *fmt_fp; struct bufcookie tbuf_cookie; struct bufcookie fmt_cookie; #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID /* Check for invalid bits. */ if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) { syslog(INTERNALLOG, "syslog: unknown facility/priority: %x", pri); pri &= LOG_PRIMASK|LOG_FACMASK; } saved_errno = errno; THREAD_LOCK(); /* Check priority against setlogmask values. */ if (!(LOG_MASK(LOG_PRI(pri)) & LogMask)) { THREAD_UNLOCK(); return; } /* Set default facility if none specified. */ if ((pri & LOG_FACMASK) == 0) pri |= LogFacility; /* Create the primary stdio hook */ tbuf_cookie.base = tbuf; tbuf_cookie.left = sizeof(tbuf); fp = fwopen(&tbuf_cookie, writehook); if (fp == NULL) { THREAD_UNLOCK(); return; } /* Build the message. */ (void)time(&now); (void)fprintf(fp, "<%d>", pri); (void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4); if (LogStat & LOG_PERROR) { /* Transfer to string buffer */ (void)fflush(fp); stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left); } if (LogTag == NULL) LogTag = _getprogname(); if (LogTag != NULL) (void)fprintf(fp, "%s", LogTag); if (LogStat & LOG_PID) (void)fprintf(fp, "[%d]", getpid()); if (LogTag != NULL) { (void)fprintf(fp, ": "); } /* Check to see if we can skip expanding the %m */ if (strstr(fmt, "%m")) { /* Create the second stdio hook */ fmt_cookie.base = fmt_cpy; fmt_cookie.left = sizeof(fmt_cpy) - 1; fmt_fp = fwopen(&fmt_cookie, writehook); if (fmt_fp == NULL) { fclose(fp); THREAD_UNLOCK(); return; } /* * Substitute error message for %m. Be careful not to * molest an escaped percent "%%m". We want to pass it * on untouched as the format is later parsed by vfprintf. */ for ( ; (ch = *fmt); ++fmt) { if (ch == '%' && fmt[1] == 'm') { ++fmt; strerror_r(saved_errno, errstr, sizeof(errstr)); fputs(errstr, fmt_fp); } else if (ch == '%' && fmt[1] == '%') { ++fmt; fputc(ch, fmt_fp); fputc(ch, fmt_fp); } else { fputc(ch, fmt_fp); } } /* Null terminate if room */ fputc(0, fmt_fp); fclose(fmt_fp); /* Guarantee null termination */ fmt_cpy[sizeof(fmt_cpy) - 1] = '\0'; fmt = fmt_cpy; } (void)vfprintf(fp, fmt, ap); (void)fclose(fp); cnt = sizeof(tbuf) - tbuf_cookie.left; /* Remove a trailing newline */ if (tbuf[cnt - 1] == '\n') cnt--; /* Output to stderr if requested. */ if (LogStat & LOG_PERROR) { struct iovec iov[2]; struct iovec *v = iov; v->iov_base = stdp; v->iov_len = cnt - (stdp - tbuf); ++v; v->iov_base = "\n"; v->iov_len = 1; (void)_writev(STDERR_FILENO, iov, 2); } /* Get connected, output the message to the local logger. */ if (!opened) openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0); connectlog(); /* * If the send() failed, there are two likely scenarios: * 1) syslogd was restarted * 2) /var/run/log is out of socket buffer space, which * in most cases means local DoS. * We attempt to reconnect to /var/run/log[priv] to take care of * case #1 and keep send()ing data to cover case #2 * to give syslogd a chance to empty its socket buffer. * * If we are working with a priveleged socket, then take * only one attempt, because we don't want to freeze a * critical application like su(1) or sshd(8). * */ if (send(LogFile, tbuf, cnt, 0) < 0) { if (errno != ENOBUFS) { disconnectlog(); connectlog(); } do { if (status == CONNPRIV) break; _usleep(1); if (send(LogFile, tbuf, cnt, 0) >= 0) { THREAD_UNLOCK(); return; } } while (errno == ENOBUFS); } else { THREAD_UNLOCK(); return; } /* * Output the message to the console; try not to block * as a blocking console should not stop other processes. * Make sure the error reported is the one from the syslogd failure. */ if (LogStat & LOG_CONS && (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >= 0) { struct iovec iov[2]; struct iovec *v = iov; p = strchr(tbuf, '>') + 1; v->iov_base = p; v->iov_len = cnt - (p - tbuf); ++v; v->iov_base = "\r\n"; v->iov_len = 2; (void)_writev(fd, iov, 2); (void)_close(fd); } THREAD_UNLOCK(); }
int gw_em_mad_check_credentials(char *info) { int rc; gss_cred_id_t gss_cred = GSS_C_NO_CREDENTIAL; OM_uint32 major_status; OM_uint32 minor_status; OM_uint32 lifetime; time_t goodtill; static time_t last_goodtill = 0; char goodtill_str[26]; info[0] = '\0'; /* (Re)adquire credentials */ major_status = globus_gss_assist_acquire_cred(&minor_status, GSS_C_INITIATE, &gss_cred); if (major_status != GSS_S_COMPLETE) { sprintf(info, "Error loading credentials"); return 1; } gss_inquire_cred(&minor_status, gss_cred, NULL, &lifetime, NULL, NULL); goodtill = time(NULL) + lifetime; #ifdef GWSOLARIS ctime_r(&(goodtill), goodtill_str, sizeof(char)*26); #else ctime_r(&(goodtill), goodtill_str); #endif goodtill_str[24]='\0'; printf("TIMER - SUCCESS Credential is valid until %s\n", goodtill_str); if (last_goodtill == 0) { last_goodtill = goodtill; } else if (goodtill > last_goodtill) { rc = globus_gram_client_set_credentials(gss_cred); if (rc != 0) { sprintf(info, "Error setting credentials"); return 1; } printf("TIMER - SUCCESS Refreshing credentials until %s\n", goodtill_str); last_goodtill = goodtill; rc = gw_em_mad_refresh(gss_cred, info); if (rc != 0) { return 1; } } return 0; }
void log_request(struct wsgi_request *wsgi_req) { // optimize this (please) char time_request[26]; time_t microseconds, microseconds2; int rlen; int app_req = -1; char *msg2 = " "; char *via = msg2; char mempkt[4096]; char logpkt[4096]; struct iovec logvec[4]; int logvecpos = 0; const char *msecs = "msecs"; const char *micros = "micros"; long int rt; char *tsize = (char *) msecs; #ifdef UWSGI_SENDFILE char *msg1 = " via sendfile() "; #endif char *msg3 = " via route() "; char *msg4 = " via offload() "; struct uwsgi_app *wi; if (wsgi_req->do_not_log) return; if (wsgi_req->app_id >= 0) { wi = &uwsgi_apps[wsgi_req->app_id]; if (wi->requests > 0) { app_req = wi->requests; } } #ifdef UWSGI_SENDFILE if (wsgi_req->sendfile_fd > -1 && wsgi_req->sendfile_obj == wsgi_req->async_result) { //wsgi_req->sendfile_fd_size > 0 ) { via = msg1; } #endif // mark route() requests if (wsgi_req->status == -17) { via = msg3; } else if (wsgi_req->status == -30) { via = msg4; } #ifdef __sun__ ctime_r((const time_t *) &wsgi_req->start_of_request.tv_sec, time_request, 26); #else ctime_r((const time_t *) &wsgi_req->start_of_request.tv_sec, time_request); #endif microseconds = wsgi_req->end_of_request.tv_sec * 1000000 + wsgi_req->end_of_request.tv_usec; microseconds2 = wsgi_req->start_of_request.tv_sec * 1000000 + wsgi_req->start_of_request.tv_usec; rt = (long int) (microseconds - microseconds2); if (uwsgi.log_micros) { tsize = (char *) micros; } else { rt /= 1000; } if (uwsgi.vhost) { logvec[logvecpos].iov_base = wsgi_req->host; logvec[logvecpos].iov_len = wsgi_req->host_len; logvecpos++; logvec[logvecpos].iov_base = " "; logvec[logvecpos].iov_len = 1; logvecpos++; } if (uwsgi.shared->options[UWSGI_OPTION_MEMORY_DEBUG] == 1) { #ifndef UNBIT rlen = snprintf(mempkt, 4096, "{address space usage: %lld bytes/%lluMB} {rss usage: %llu bytes/%lluMB} ", (unsigned long long) uwsgi.workers[uwsgi.mywid].vsz_size, (unsigned long long) uwsgi.workers[uwsgi.mywid].vsz_size / 1024 / 1024, (unsigned long long) uwsgi.workers[uwsgi.mywid].rss_size, (unsigned long long) uwsgi.workers[uwsgi.mywid].rss_size / 1024 / 1024); #else rlen = snprintf(mempkt, 4096, "{address space usage: %lld bytes/%lluMB} ", (unsigned long long) uwsgi.workers[uwsgi.mywid].vsz_size, (unsigned long long) uwsgi.workers[uwsgi.mywid].vsz_size / 1024 / 1024); #endif logvec[logvecpos].iov_base = mempkt; logvec[logvecpos].iov_len = rlen; logvecpos++; } rlen = snprintf(logpkt, 4096, "[pid: %d|app: %d|req: %d/%llu] %.*s (%.*s) {%d vars in %d bytes} [%.*s] %.*s %.*s => generated %llu bytes in %ld %s%s(%.*s %d) %d headers in %llu bytes (%d switches on core %d)\n", (int) uwsgi.mypid, wsgi_req->app_id, app_req, (unsigned long long) uwsgi.workers[0].requests, wsgi_req->remote_addr_len, wsgi_req->remote_addr, wsgi_req->remote_user_len, wsgi_req->remote_user, wsgi_req->var_cnt, wsgi_req->uh.pktsize, 24, time_request, wsgi_req->method_len, wsgi_req->method, wsgi_req->uri_len, wsgi_req->uri, (unsigned long long) wsgi_req->response_size, rt, tsize, via, wsgi_req->protocol_len, wsgi_req->protocol, wsgi_req->status, wsgi_req->header_cnt, (unsigned long long) wsgi_req->headers_size, wsgi_req->switches, wsgi_req->async_id); logvec[logvecpos].iov_base = logpkt; logvec[logvecpos].iov_len = rlen; // do not check for errors rlen = writev(2, logvec, logvecpos + 1); }
/* * Called by pcap_loop; prints a text description of the packet. */ static void handle_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) { /* * note; there is lots of double writing in this function (first stuff is * written to tmpbuf, then its copied from there to buf) but the code is * "safer" this way (no need to keep track of buffer offsets, etc.) and so * far performance isn't an issue. */ char buf[1024] = "", tmpbuf[1024] = ""; int buflen = sizeof(buf); int tmpbuflen = sizeof(tmpbuf); ++pkt_count; if (use_numbering) snprintf(buf, buflen, "%u: ", pkt_count); switch (tsfmt) { case TS_NONE: /* do nothing */ break; case TS_ABS: snprintf(tmpbuf, tmpbuflen, "[%u.%06ld] ", h->ts.tv_sec, h->ts.tv_usec); break; case TS_REL: { static struct timeval last_ts = {0, 0}; assert(h->ts.tv_sec >= last_ts.tv_sec); if (last_ts.tv_sec == 0) { snprintf(tmpbuf, tmpbuflen, "[%u.%06ld] ", 0, 0l); } else if (h->ts.tv_usec >= last_ts.tv_usec) { snprintf(tmpbuf, tmpbuflen, "[%u.%06ld] ", h->ts.tv_sec - last_ts.tv_sec, h->ts.tv_usec - last_ts.tv_usec); } else { /* h->ts.tv_usec < last_ts.tv_usec */ assert(h->ts.tv_sec > last_ts.tv_sec); snprintf(tmpbuf, tmpbuflen, "[%u.%06ld] ", h->ts.tv_sec - last_ts.tv_sec - 1, 1000000l + h->ts.tv_usec - last_ts.tv_usec); } last_ts = h->ts; } case TS_CTIME: { char datebuf[32]; time_t t = h->ts.tv_sec; ctime_r(&t, datebuf + 1); /* move the year to the front, overwriting the day-of-week */ memcpy(datebuf, datebuf + 21, 4); datebuf[4] = ' '; datebuf[20] = '\0'; /* chop the trailing year and newline */ snprintf(tmpbuf, tmpbuflen, "[%s.%06ld] ", datebuf, h->ts.tv_usec); break; } default: assert(0); /* bad value for tsfmt */ } if (strlcat(buf, tmpbuf, buflen) >= buflen) return; int start_buflen = strlen(buf); int flags = 0; if ((enabled_layers[1] + enabled_layers[2] + enabled_layers[3]) == 0) { /* if only layer 0 (MAC) is enabled, then ignore bad LLC values */ flags |= PKTPARSE_IGNORE_BADLLC; } struct packet pkt; if (pktparse_parse(h, sp, dlt, &pkt, flags) == -1) { if (quiet) return; snprintf(tmpbuf, tmpbuflen, "bad packet: %s", pkt.errmsg); strlcat(buf, tmpbuf, buflen); goto finish; } u_char print_sep = 0; /* datalink layer */ if (enabled_layers[0] && ((pkt.ether_hdr != NULL) || (pkt.wifi_hdr != NULL))) { int flags = (enabled_layers[0] > 1) ? PKTPARSE_PRINT_VERBOSE : 0; if (pkt.ether_hdr) { pktparse_print_ethernet(tmpbuf, tmpbuflen, pkt.ether_hdr, flags); } else if (pkt.wifi_hdr) { pktparse_print_wifi(tmpbuf, tmpbuflen, pkt.wifi_hdr, pkt.mgmt_body, flags); } if (strlcat(buf, tmpbuf, buflen) >= buflen) goto finish; /* if enabled, also include the FCS field at the end */ if (print_fcs) { /* if packet was truncated at all, then we lost the FCS at the end */ if ((pkt.caplen == pkt.wirelen) && (pkt.caplen >= 4)) { uint32_t index = pkt.caplen - 4; uint32_t fcs = EXTRACT_LE_32BITS(pkt.raw_packet + index); snprintf(tmpbuf, tmpbuflen, "FCS %08x ", fcs); if (strlcat(buf, tmpbuf, buflen) >= buflen) goto finish; } } print_sep = 1; } /* if both network and transport layers are enabled, print them together */ if (enabled_layers[1] && enabled_layers[2]) { int flags = 0; if ((enabled_layers[1] > 1) || (enabled_layers[2] > 1)) flags |= PKTPARSE_PRINT_VERBOSE; tmpbuf[0] = '\0'; switch (pkt.ethertype) { case -1: /* no ethertype parsed from packet */ break; case ETHERTYPE_IP: if (pkt.ip_hdr) { if (pkt.tcp_hdr) pktparse_print_tcpip(tmpbuf, tmpbuflen, pkt.ip_hdr, pkt.tcp_hdr, pkt.trans_len, flags); else if (pkt.udp_hdr) pktparse_print_udpip(tmpbuf, tmpbuflen, pkt.ip_hdr, pkt.udp_hdr, pkt.trans_len, flags); else pktparse_print_ip_proto(tmpbuf, tmpbuflen, pkt.ip_hdr, pkt.ipproto, pkt.trans_len, flags); } else snprintf(tmpbuf, tmpbuflen, "IP "); break; case ETHERTYPE_IPV6: if (pkt.ip6_hdr) { if (pkt.tcp_hdr) pktparse_print_tcpip6(tmpbuf, tmpbuflen, pkt.ip6_hdr, pkt.tcp_hdr, pkt.trans_len, flags); else if (pkt.udp_hdr) pktparse_print_udpip6(tmpbuf, tmpbuflen, pkt.ip6_hdr, pkt.udp_hdr, pkt.trans_len, flags); else pktparse_print_ip6_proto(tmpbuf, tmpbuflen, pkt.ip6_hdr, pkt.ipproto, pkt.trans_len, flags); } else snprintf(tmpbuf, tmpbuflen, "IPv6 "); break; case ETHERTYPE_ARP: snprintf(tmpbuf, tmpbuflen, "ARP "); break; default: snprintf(tmpbuf, tmpbuflen, "ethertype 0x%04X ", pkt.ethertype); break; } if (strlen(tmpbuf) > 0) { if (print_sep) { if (strlcat(buf, "~ ", buflen) >= buflen) goto finish; print_sep = 0; } if (strlcat(buf, tmpbuf, buflen) >= buflen) goto finish; } } else { /* if we can't merge network and transport layers, print whichever is enabled */ tmpbuf[0] = '\0'; if (enabled_layers[1]) { int flags = (enabled_layers[1] > 1) ? PKTPARSE_PRINT_VERBOSE : 0; switch (pkt.ethertype) { case -1: /* no ethertype parsed from packet */ break; case ETHERTYPE_IP: if (pkt.ip_hdr) pktparse_print_ip(tmpbuf, tmpbuflen, pkt.ip_hdr, pkt.trans_len, flags); break; case ETHERTYPE_IPV6: if (pkt.ip6_hdr) pktparse_print_ip6(tmpbuf, tmpbuflen, pkt.ip6_hdr, pkt.trans_len, flags); break; case ETHERTYPE_ARP: snprintf(tmpbuf, tmpbuflen, "ARP "); break; default: snprintf(tmpbuf, tmpbuflen, "ethertype 0x%04X ", pkt.ethertype); break; } } else if (enabled_layers[2]) { int flags = (enabled_layers[2] > 1) ? PKTPARSE_PRINT_VERBOSE : 0; switch (pkt.ipproto) { case -1: /* no ip-proto parsed from packet */ break; case IPPROTO_IP: snprintf(tmpbuf, tmpbuflen, "IP (encapsulation) "); break; case IPPROTO_ICMP: snprintf(tmpbuf, tmpbuflen, "ICMP "); break; case IPPROTO_IGMP: snprintf(tmpbuf, tmpbuflen, "IGMP "); break; case IPPROTO_TCP: if (pkt.tcp_hdr) pktparse_print_tcp(tmpbuf, tmpbuflen, pkt.tcp_hdr, pkt.trans_len, flags); else snprintf(tmpbuf, tmpbuflen, "TCP "); break; case IPPROTO_UDP: if (pkt.udp_hdr) pktparse_print_udp(tmpbuf, tmpbuflen, pkt.udp_hdr, pkt.trans_len, flags); else snprintf(tmpbuf, tmpbuflen, "UDP "); break; default: snprintf(tmpbuf, tmpbuflen, "ipproto 0x%02X ", pkt.ipproto); break; } } if (strlen(tmpbuf) > 0) { if (print_sep) { if (strlcat(buf, "~ ", buflen) >= buflen) goto finish; print_sep = 0; } if (strlcat(buf, tmpbuf, buflen) >= buflen) goto finish; } } /* application layer */ if (enabled_layers[3]) { /* only HTTP request parsing is implemented so far */ struct http_request *req = NULL; if (pkt.tcp_hdr != NULL) { req = pktparse_parse_http_request((char*)pkt.unparsed, pkt.unparsed_len); } if (req != NULL) { if (req->resource[0] == '/') snprintf(tmpbuf, tmpbuflen, "%s %s%s ", req->method, req->host, req->resource); else snprintf(tmpbuf, tmpbuflen, "%s %s/%s ", req->method, req->host, req->resource); if (strlcat(buf, tmpbuf, buflen) >= buflen) goto finish; /* if verbose printing is enabled, include the User-Agent string */ if (enabled_layers[3] > 1) { snprintf(tmpbuf, tmpbuflen, "User-Agent: %s", req->user_agent); if (strlcat(buf, tmpbuf, buflen) >= buflen) goto finish; } free(req); } } finish: if (strlen(buf) > start_buflen) printf("%s\n", buf); }