static gint smtp_session_recv_msg(Session *session, const gchar *msg) { SMTPSession *smtp_session = SMTP_SESSION(session); gboolean cont = FALSE; gint ret = 0; if (strlen(msg) < 4) { log_warning(LOG_PROTOCOL, _("bad SMTP response\n")); return -1; } switch (smtp_session->state) { case SMTP_EHLO: case SMTP_STARTTLS: case SMTP_AUTH: case SMTP_AUTH_PLAIN: case SMTP_AUTH_LOGIN_USER: case SMTP_AUTH_LOGIN_PASS: case SMTP_AUTH_CRAM_MD5: log_print(LOG_PROTOCOL, "ESMTP< %s\n", msg); break; default: log_print(LOG_PROTOCOL, "SMTP< %s\n", msg); break; } /* ignore all multiline responses except for EHLO */ if (msg[3] == '-' && smtp_session->state != SMTP_EHLO) return session_recv_msg(session); if (msg[0] == '5' && msg[1] == '0' && (msg[2] == '4' || msg[2] == '3' || msg[2] == '1')) { log_warning(LOG_PROTOCOL, _("error occurred on SMTP session\n")); smtp_session->state = SMTP_ERROR; smtp_session->error_val = SM_ERROR; g_free(smtp_session->error_msg); smtp_session->error_msg = g_strdup(msg); return -1; } if (!strncmp(msg, "535", 3)) { log_warning(LOG_PROTOCOL, _("error occurred on authentication\n")); smtp_session->state = SMTP_ERROR; smtp_session->error_val = SM_AUTHFAIL; g_free(smtp_session->error_msg); smtp_session->error_msg = g_strdup(msg); return -1; } if (msg[0] != '1' && msg[0] != '2' && msg[0] != '3') { log_warning(LOG_PROTOCOL, _("error occurred on SMTP session\n")); smtp_session->state = SMTP_ERROR; smtp_session->error_val = SM_ERROR; g_free(smtp_session->error_msg); smtp_session->error_msg = g_strdup(msg); return -1; } if (msg[3] == '-') cont = TRUE; else if (msg[3] != ' ' && msg[3] != '\0') { log_warning(LOG_PROTOCOL, _("bad SMTP response\n")); smtp_session->state = SMTP_ERROR; smtp_session->error_val = SM_UNRECOVERABLE; return -1; } switch (smtp_session->state) { case SMTP_READY: if (strstr(msg, "ESMTP")) smtp_session->is_esmtp = TRUE; case SMTP_CONNECTED: #ifdef USE_GNUTLS if (smtp_session->user || session->ssl_type != SSL_NONE || smtp_session->is_esmtp) #else if (smtp_session->user || smtp_session->is_esmtp) #endif ret = smtp_ehlo(smtp_session); else ret = smtp_helo(smtp_session); break; case SMTP_HELO: ret = smtp_from(smtp_session); break; case SMTP_EHLO: ret = smtp_ehlo_recv(smtp_session, msg); if (cont == TRUE) break; if (smtp_session->max_message_size > 0 && smtp_session->max_message_size < smtp_session->send_data_len) { log_warning(LOG_PROTOCOL, _("Message is too big " "(Maximum size is %s)\n"), to_human_readable( (goffset)(smtp_session->max_message_size))); smtp_session->state = SMTP_ERROR; smtp_session->error_val = SM_ERROR; return -1; } #ifdef USE_GNUTLS if (session->ssl_type == SSL_STARTTLS && smtp_session->tls_init_done == FALSE) { ret = smtp_starttls(smtp_session); break; } #endif if (smtp_session->user) { if (smtp_auth(smtp_session) != SM_OK) { #ifdef USE_GNUTLS if (session->ssl_type == SSL_NONE && smtp_session->tls_init_done == FALSE && (smtp_session->avail_auth_type & SMTPAUTH_TLS_AVAILABLE)) ret = smtp_starttls(smtp_session); else #endif ret = smtp_from(smtp_session); } } else ret = smtp_from(smtp_session); break; case SMTP_STARTTLS: #ifdef USE_GNUTLS if (session_start_tls(session) < 0) { log_warning(LOG_PROTOCOL, _("couldn't start TLS session\n")); smtp_session->state = SMTP_ERROR; smtp_session->error_val = SM_ERROR; return -1; } smtp_session->tls_init_done = TRUE; ret = smtp_ehlo(smtp_session); #endif break; case SMTP_AUTH: ret = smtp_auth_recv(smtp_session, msg); break; case SMTP_AUTH_LOGIN_USER: ret = smtp_auth_login_user_recv(smtp_session, msg); break; case SMTP_AUTH_PLAIN: case SMTP_AUTH_LOGIN_PASS: case SMTP_AUTH_CRAM_MD5: ret = smtp_from(smtp_session); break; case SMTP_FROM: if (smtp_session->cur_to) ret = smtp_rcpt(smtp_session); break; case SMTP_RCPT: if (smtp_session->cur_to) ret = smtp_rcpt(smtp_session); else ret = smtp_data(smtp_session); break; case SMTP_DATA: ret = smtp_send_data(smtp_session); break; case SMTP_EOM: smtp_make_ready(smtp_session); break; case SMTP_QUIT: session_disconnect(session); break; case SMTP_ERROR: default: log_warning(LOG_PROTOCOL, _("error occurred on SMTP session\n")); smtp_session->error_val = SM_ERROR; return -1; } if (cont && ret == SM_OK) return session_recv_msg(session); if (ret != SM_OK) smtp_session->error_val = SM_ERROR; return ret == SM_OK ? 0 : -1; }
static void init_args(int argc, char **argv, const char **raceconfig) { int i; char *buf; i = 1; while(i < argc) { if(strncmp(argv[i], "-l", 2) == 0) { i++; if(i < argc) { buf = (char *)malloc(strlen(argv[i]) + 2); sprintf(buf, "%s/", argv[i]); SetLocalDir(buf); free(buf); i++; } } else if(strncmp(argv[i], "-L", 2) == 0) { i++; if(i < argc) { buf = (char *)malloc(strlen(argv[i]) + 2); sprintf(buf, "%s/", argv[i]); SetLibDir(buf); free(buf); i++; } } else if(strncmp(argv[i], "-D", 2) == 0) { i++; if(i < argc) { buf = (char *)malloc(strlen(argv[i]) + 2); sprintf(buf, "%s/", argv[i]); SetDataDir(buf); free(buf); i++; } } else if(strncmp(argv[i], "-s", 2) == 0) { i++; SetSingleTextureMode(); } else if(strncmp(argv[i], "-k", 2) == 0) { i++; // Keep modules in memory (for valgrind) printf("Unloading modules disabled, just intended for valgrind runs.\n"); bKeepModules = true; #ifndef FREEGLUT } else if(strncmp(argv[i], "-m", 2) == 0) { i++; GfuiMouseSetHWPresent(); /* allow the hardware cursor */ #endif } else if(strncmp(argv[i], "-r", 2) == 0) { i++; *raceconfig = ""; if(i < argc) { *raceconfig = argv[i]; i++; } if((strlen(*raceconfig) == 0) || (strstr(*raceconfig, ".xml") == 0)) { printf("Please specify a race configuration xml when using -r\n"); exit(1); } } else { i++; /* ignore bad args */ } } #ifdef FREEGLUT GfuiMouseSetHWPresent(); /* allow the hardware cursor (freeglut pb ?) */ #endif }
void ConvertMcd(char *mcd, char *data) { FILE *f; int i=0; int s = MCD_SIZE; if (strstr(mcd, ".gme")) { f = fopen(mcd, "wb"); if (f != NULL) { fwrite(data-3904, 1, MCD_SIZE+3904, f); fclose(f); } f = fopen(mcd, "r+"); s = s + 3904; fputc('1', f); s--; fputc('2', f); s--; fputc('3', f); s--; fputc('-', f); s--; fputc('4', f); s--; fputc('5', f); s--; fputc('6', f); s--; fputc('-', f); s--; fputc('S', f); s--; fputc('T', f); s--; fputc('D', f); s--; for(i=0;i<7;i++) { fputc(0, f); s--; } fputc(1, f); s--; fputc(0, f); s--; fputc(1, f); s--; fputc('M', f); s--; fputc('Q', f); s--; for(i=0;i<14;i++) { fputc(0xa0, f); s--; } fputc(0, f); s--; fputc(0xff, f); while (s-- > (MCD_SIZE+1)) fputc(0, f); fclose(f); } else if(strstr(mcd, ".mem") || strstr(mcd,".vgs")) { f = fopen(mcd, "wb"); if (f != NULL) { fwrite(data-64, 1, MCD_SIZE+64, f); fclose(f); } f = fopen(mcd, "r+"); s = s + 64; fputc('V', f); s--; fputc('g', f); s--; fputc('s', f); s--; fputc('M', f); s--; for(i=0;i<3;i++) { fputc(1, f); s--; fputc(0, f); s--; fputc(0, f); s--; fputc(0, f); s--; } fputc(0, f); s--; fputc(2, f); while (s-- > (MCD_SIZE+1)) fputc(0, f); fclose(f); } else { f = fopen(mcd, "wb"); if (f != NULL) { fwrite(data, 1, MCD_SIZE, f); fclose(f); } } }
/* * Show previous messages to the user -BEN- * * The screen format uses line 0 and (Term->hgt - 1) for headers and prompts, * skips line 1 and (Term->hgt - 2), and uses line 2 thru (Term->hgt - 3) for * old messages. * * This command shows you which commands you are viewing, and allows * you to "search" for strings in the recall. * * Note that messages may be longer than 80 characters, but they are * displayed using "infinite" length, with a special sub-command to * "slide" the virtual display to the left or right. * * Attempt to only hilite the matching portions of the string. * * Now taking advantages of big-screen. -pav- */ void do_cmd_messages(void) { s32b i, j, k, n, q; s32b wid, hgt; char shower[80]; char finder[80]; /* Wipe finder */ strcpy(finder, ""); /* Wipe shower */ strcpy(shower, ""); /* Total messages */ n = message_num(); /* Start on first message */ i = 0; /* Start at leftmost edge */ q = 0; /* Enter "icky" mode */ character_icky++; /* Save the screen */ Term_save(); /* Process requests until done */ while (1) { /* Clear screen */ Term_clear(); /* Retrieve current screen size */ Term_get_size(&wid, &hgt); /* Dump up to 20 (or more in bigscreen) lines of messages */ for (j = 0; (j < (hgt - 4)) && (i + j < n); j++) { cptr msg = message_str(i + j); byte color = message_color(i + j); /* Apply horizontal scroll */ msg = (strlen(msg) >= q) ? (msg + q) : ""; /* Dump the messages, bottom to top */ display_message(0, (hgt - 3) - j, strlen(msg), color, msg); /* Hilite "shower" */ if (shower[0]) { cptr str = msg; /* Display matches */ while ((str = strstr(str, shower)) != NULL) { s32b len = strlen(shower); /* Display the match */ Term_putstr(str - msg, (hgt - 3) - j, len, TERM_YELLOW, shower); /* Advance */ str += len; } } } /* Display header XXX XXX XXX */ prt(format("Message Recall (%d-%d of %d), Offset %d", i, i + j - 1, n, q), 0, 0); /* Display prompt (not very informative) */ prt("[Press 'p' for older, 'n' for newer, ..., or ESCAPE]", hgt - 1, 0); /* Get a command */ k = inkey(); /* Exit on Escape */ if (k == ESCAPE) break; /* Hack -- Save the old index */ j = i; /* Horizontal scroll */ if (k == '4') { /* Scroll left */ q = (q >= wid / 2) ? (q - wid / 2) : 0; /* Success */ continue; } /* Horizontal scroll */ if (k == '6') { /* Scroll right */ q = q + wid / 2; /* Success */ continue; } /* Hack -- handle show */ if (k == '=') { /* Prompt */ prt("Show: ", hgt - 1, 0); /* Get a "shower" string, or continue */ if (!askfor_aux(shower, 80)) continue; /* Okay */ continue; } /* Hack -- handle find */ if (k == '/') { s16b z; /* Prompt */ prt("Find: ", hgt - 1, 0); /* Get a "finder" string, or continue */ if (!askfor_aux(finder, 80)) continue; /* Show it */ strcpy(shower, finder); /* Scan messages */ for (z = i + 1; z < n; z++) { cptr msg = message_str(z); /* Search for it */ if (strstr(msg, finder)) { /* New location */ i = z; /* Done */ break; } } } /* Recall 1 older message */ if ((k == '8') || (k == '\n') || (k == '\r')) { /* Go newer if legal */ if (i + 1 < n) i += 1; } /* Recall 10 older messages */ if (k == '+') { /* Go older if legal */ if (i + 10 < n) i += 10; } /* Recall one screen of older messages */ if ((k == 'p') || (k == KTRL('P')) || (k == ' ')) { /* Go older if legal */ if (i + (hgt - 4) < n) i += (hgt - 4); } /* Recall one screen of newer messages */ if ((k == 'n') || (k == KTRL('N'))) { /* Go newer (if able) */ i = (i >= (hgt - 4)) ? (i - (hgt - 4)) : 0; } /* Recall 10 newer messages */ if (k == '-') { /* Go newer (if able) */ i = (i >= 10) ? (i - 10) : 0; } /* Recall 1 newer messages */ if (k == '2') { /* Go newer (if able) */ i = (i >= 1) ? (i - 1) : 0; } /* Hack -- Error of some kind */ if (i == j) bell(); } /* Restore the screen */ Term_load(); /* Leave "icky" mode */ character_icky--; }
int FindSRS( const char *pszInput, OGRSpatialReference &oSRS ) { int bGotSRS = FALSE; VSILFILE *fp = NULL; GDALDataset *poGDALDS = NULL; OGRDataSource *poOGRDS = NULL; OGRLayer *poLayer = NULL; char *pszProjection = NULL; CPLErrorHandler oErrorHandler = NULL; int bIsFile = FALSE; OGRErr eErr = CE_None; int bDebug = FALSE; /* temporarily supress error messages we may get from xOpen() */ bDebug = CSLTestBoolean(CPLGetConfigOption("CPL_DEBUG", "OFF")); if ( ! bDebug ) oErrorHandler = CPLSetErrorHandler ( CPLQuietErrorHandler ); /* Test if argument is a file */ fp = VSIFOpenL( pszInput, "r" ); if ( fp ) { bIsFile = TRUE; VSIFCloseL( fp ); CPLDebug( "gdalsrsinfo", "argument is a file" ); } /* try to open with GDAL */ CPLDebug( "gdalsrsinfo", "trying to open with GDAL" ); poGDALDS = (GDALDataset *) GDALOpen( pszInput, GA_ReadOnly ); if ( poGDALDS != NULL && poGDALDS->GetProjectionRef( ) != NULL ) { pszProjection = (char *) poGDALDS->GetProjectionRef( ); if( oSRS.importFromWkt( &pszProjection ) == CE_None ) { CPLDebug( "gdalsrsinfo", "got SRS from GDAL" ); bGotSRS = TRUE; } GDALClose( (GDALDatasetH) poGDALDS ); if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with GDAL" ); } #ifdef OGR_ENABLED /* if unsuccessful, try to open with OGR */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to open with OGR" ); poOGRDS = OGRSFDriverRegistrar::Open( pszInput, FALSE, NULL ); if( poOGRDS != NULL ) { poLayer = poOGRDS->GetLayer( 0 ); if ( poLayer != NULL ) { OGRSpatialReference *poSRS = poLayer->GetSpatialRef( ); if ( poSRS != NULL ) { CPLDebug( "gdalsrsinfo", "got SRS from OGR" ); bGotSRS = TRUE; OGRSpatialReference* poSRSClone = poSRS->Clone(); oSRS = *poSRSClone; OGRSpatialReference::DestroySpatialReference( poSRSClone ); } } OGRDataSource::DestroyDataSource( poOGRDS ); poOGRDS = NULL; } if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with OGR" ); } #endif // OGR_ENABLED /* Try ESRI file */ if ( ! bGotSRS && bIsFile && (strstr(pszInput,".prj") != NULL) ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from ESRI .prj file [%s]", pszInput ); char **pszTemp; if ( strstr(pszInput,"ESRI::") != NULL ) pszTemp = CSLLoad( pszInput+6 ); else pszTemp = CSLLoad( pszInput ); if( pszTemp ) { eErr = oSRS.importFromESRI( pszTemp ); CSLDestroy( pszTemp ); } else eErr = OGRERR_UNSUPPORTED_SRS; if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from ESRI .prj file" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from ESRI .prj file" ); bGotSRS = TRUE; } } /* Last resort, try OSRSetFromUserInput() */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from user input [%s]", pszInput ); eErr = oSRS.SetFromUserInput( pszInput ); if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from user input" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from user input" ); bGotSRS = TRUE; } } /* restore error messages */ if ( ! bDebug ) CPLSetErrorHandler ( oErrorHandler ); return bGotSRS; }
int main(int argc, char *argv[]) { size_t num_files = 0; char **files = (char **) calloc(MAX_FILE_SUPPORT, MAX_FILE_SUPPORT * sizeof(char *)); if (0 > init_log_config(&logconf, argc, argv)) { exit(EXIT_FAILURE); } if (!SSTRISEMPTY(logconf.target) && !SSTRISEMPTY(logconf.interface)) { LOGGER_ERROR("%s", "cannot write to target and interface together. please choose one"); exit(EXIT_FAILURE); } char *f = logconf.watch_files; if (!SSTRISEMPTY(f)) { while (f != NULL) { char *fprime = strsep(&f, ","); if (fprime != NULL) { files[num_files] = strdup(fprime); ++num_files; } } } else { LOGGER_ERROR("%s", "no files..no watch!"); exit(EXIT_FAILURE); } if (0 > epoll_worker_init()) { LOGGER_ERROR("%s", "epoll_worker_init"); exit(EXIT_FAILURE); } ribs_timer(60*1000, dump_stats); tab_event_fds = thashtable_create(); delta_push = thashtable_create(); vmbuf_init(&write_buffer, 4096); vmbuf_init(&mb, 4096); if (SSTRISEMPTY(logconf.interface) && !SSTRISEMPTY(logconf.target)) { file_writer_make(&fw); if (0 > file_writer_init(&fw, logconf.target)) { LOGGER_ERROR("%s", "flie_writer"); exit(EXIT_FAILURE); } write_to_file = true; } else if (!SSTRISEMPTY(logconf.interface)) { if (0 > http_client_pool_init(&client_pool, 20, 20)) { LOGGER_ERROR("http_client_pool_init"); exit(EXIT_FAILURE); } memset(&eserv, 0, sizeof(eserv)); vmbuf_reset(&write_buffer); _replace(logconf.interface, &write_buffer, "http://www.", ""); _replace(logconf.interface, &write_buffer, "http://", ""); char *interface = vmbuf_data(&write_buffer); eserv.context = ribs_strdup(strstr(interface, "/")); char *ln = strchr(interface, '/'); ln = ribs_malloc_sprintf("%.*s", ((int)strlen(interface) - (int)strlen(ln)), interface); if (0 > parse_host_to_inet(ln, eserv.hostname, &eserv.server, &eserv.port)) { LOGGER_ERROR("%s", "server details invalid. cannot parse server"); exit(EXIT_FAILURE); } } else { LOGGER_ERROR("%s", "no target defined. please use target or interface"); exit(EXIT_FAILURE); } char _hostname[1024]; gethostname(_hostname, 1024); hostname = ribs_strdup(_hostname); int wd = inotify_init1(IN_NONBLOCK); if (0 >= wd) { LOGGER_ERROR("%s", "failed to init inotify. cannot proceed. make sure you've inotify and is accessible to this user."); exit(EXIT_FAILURE); } if (!recursive_flush_events(wd, files, num_files)) { LOGGER_ERROR("%s", "collection failed"); abort(); } return 0; }
void *periodicCheckpoint() { char str[100]; FILE *procs,*fp; char processID[100],context[100],check[400]; int noOfProcess,loop; char numberOfProcess[10]; while(1) { OK=0; procs = popen("ps -e -o pid,cmd","r"); noOfProcess=0; fscanf(procs,"%s",processID); fgets(str,100,procs); while(!feof(procs)) { fscanf(procs,"%s",processID); fgets(str,100,procs); if(strstr(str,"a.out")!=NULL) { sprintf(str,"cr_checkpoint --save-all %s",processID); strcpy(check,"\0"); fp=popen(str,"r"); fgets(check,100,fp); fclose(fp); if(strstr(check,"Checkpoint")!=NULL) { printf("\nThe selected file could not be checkpointed"); } else { printf("\nPeriodic Checkpoint successful\n"); sprintf(context,"chmod 777 context.%s",processID); system(context); sprintf(context,"mv context.%s /home/cse4119/context_files/bal/context.%s",processID,processID); system(context); sprintf(context,"/home/cse4119/context_files/bal/context.%s",processID); strcpy(processIDs[noOfProcess],context); noOfProcess++; } } } sprintf(numberOfProcess,"%d ",noOfProcess); strcpy(message,numberOfProcess); for(loop=0;loop<noOfProcess;loop++) { strcat(message,processIDs[loop]); strcat(message," "); } OK = 1; sleep(15); } }
static int testCorrupt(const void *opaque) { const struct testCorruptData *data = opaque; struct daemonConfig *conf = daemonConfigNew(false); int ret = 0; int type = VIR_CONF_NONE; char *newdata = munge_param(data->filedata, data->params, data->paramnum, &type); virErrorPtr err = NULL; if (!newdata) return -1; //VIR_DEBUG("New config [%s]", newdata); if (daemonConfigLoadData(conf, data->filename, newdata) != -1) { VIR_DEBUG("Did not see a failure"); ret = -1; goto cleanup; } err = virGetLastError(); if (!err || !err->message) { VIR_DEBUG("No error or message %p", err); ret = -1; goto cleanup; } #if !WITH_SASL if (strstr(err->message, "unsupported auth sasl")) { VIR_DEBUG("sasl unsupported, skipping this config"); goto cleanup; } #endif switch (type) { case VIR_CONF_LONG: if (!strstr(err->message, "invalid type: got string; expected long")) { VIR_DEBUG("Wrong error for long: '%s'", err->message); ret = -1; } break; case VIR_CONF_STRING: if (!strstr(err->message, "invalid type: got long; expected string")) { VIR_DEBUG("Wrong error for string: '%s'", err->message); ret = -1; } break; case VIR_CONF_LIST: if (!strstr(err->message, "must be a string or list of strings")) { VIR_DEBUG("Wrong error for list: '%s'", err->message); ret = -1; } break; } cleanup: VIR_FREE(newdata); daemonConfigFree(conf); return ret; }
void MonNetworkGatherData(double *cf_this) { FILE *pp; char local[CF_BUFSIZE],remote[CF_BUFSIZE],comm[CF_BUFSIZE]; struct Item *in[ATTR],*out[ATTR]; char *sp; int i; char vbuff[CF_BUFSIZE]; Debug("GatherSocketData()\n"); for (i = 0; i < ATTR; i++) { in[i] = out[i] = NULL; } if (ALL_INCOMING != NULL) { DeleteItemList(ALL_INCOMING); ALL_INCOMING = NULL; } if (ALL_OUTGOING != NULL) { DeleteItemList(ALL_OUTGOING); ALL_OUTGOING = NULL; } sscanf(VNETSTAT[VSYSTEMHARDCLASS],"%s",comm); strcat(comm," -n"); if ((pp = cf_popen(comm,"r")) == NULL) { return; } while (!feof(pp)) { memset(local,0,CF_BUFSIZE); memset(remote,0,CF_BUFSIZE); CfReadLine(vbuff,CF_BUFSIZE,pp); if (strstr(vbuff,"UNIX")) { break; } if (!strstr(vbuff,".")) { continue; } /* Different formats here ... ugh.. */ if (strncmp(vbuff,"tcp",3) == 0) { sscanf(vbuff,"%*s %*s %*s %s %s",local,remote); /* linux-like */ } else { sscanf(vbuff,"%s %s",local,remote); /* solaris-like */ } if (strlen(local) == 0) { continue; } for (sp = local+strlen(local); (*sp != '.') && (sp > local); sp--) { } sp++; if ((strlen(sp) < 5) &&!IsItemIn(ALL_INCOMING,sp)) { PrependItem(&ALL_INCOMING,sp,NULL); } for (sp = remote+strlen(remote); (sp >= remote) && !isdigit((int)*sp); sp--) { } sp++; if ((strlen(sp) < 5) && !IsItemIn(ALL_OUTGOING,sp)) { PrependItem(&ALL_OUTGOING,sp,NULL); } for (i = 0; i < ATTR; i++) { char *spend; for (spend = local+strlen(local)-1; isdigit((int)*spend); spend--) { } spend++; if (strcmp(spend,ECGSOCKS[i].portnr) == 0) { cf_this[ECGSOCKS[i].in]++; AppendItem(&in[i],vbuff,""); } for (spend = remote+strlen(remote)-1; (sp >= remote) && isdigit((int)*spend); spend--) { } spend++; if (strcmp(spend,ECGSOCKS[i].portnr) == 0) { cf_this[ECGSOCKS[i].out]++; AppendItem(&out[i],vbuff,""); } } } cf_pclose(pp); /* Now save the state for ShowState() cf2 version alert function IFF the state is not smaller than the last or at least 40 minutes older. This mirrors the persistence of the maxima classes */ for (i = 0; i < ATTR; i++) { struct stat statbuf; time_t now = time(NULL); Debug("save incoming %s\n",ECGSOCKS[i].name); snprintf(vbuff,CF_MAXVARSIZE,"%s/state/cf_incoming.%s",CFWORKDIR,ECGSOCKS[i].name); if (cfstat(vbuff,&statbuf) != -1) { if ((ByteSizeList(in[i]) < statbuf.st_size) && (now < statbuf.st_mtime+40*60)) { CfOut(cf_verbose,"","New state %s is smaller, retaining old for 40 mins longer\n",ECGSOCKS[i].name); DeleteItemList(in[i]); continue; } } SetNetworkEntropyClasses(ECGSOCKS[i].name,"in",in[i]); RawSaveItemList(in[i],vbuff); DeleteItemList(in[i]); Debug("Saved in netstat data in %s\n",vbuff); } for (i = 0; i < ATTR; i++) { struct stat statbuf; time_t now = time(NULL); Debug("save outgoing %s\n",ECGSOCKS[i].name); snprintf(vbuff,CF_MAXVARSIZE,"%s/state/cf_outgoing.%s",CFWORKDIR,ECGSOCKS[i].name); if (cfstat(vbuff,&statbuf) != -1) { if ((ByteSizeList(out[i]) < statbuf.st_size) && (now < statbuf.st_mtime+40*60)) { CfOut(cf_verbose,"","New state %s is smaller, retaining old for 40 mins longer\n",ECGSOCKS[i].name); DeleteItemList(out[i]); continue; } } SetNetworkEntropyClasses(ECGSOCKS[i].name,"out",out[i]); RawSaveItemList(out[i],vbuff); Debug("Saved out netstat data in %s\n",vbuff); DeleteItemList(out[i]); } }
BOOL ExtractISO(const char* src_iso, const char* dest_dir, bool scan) { size_t i; int j; FILE* fd; BOOL r = FALSE; iso9660_t* p_iso = NULL; udf_t* p_udf = NULL; udf_dirent_t* p_udf_root; LONG progress_style; char* tmp; char path[64]; const char* scan_text = "Scanning ISO image..."; const char* basedir[] = { "i386", "minint" }; const char* tmp_sif = ".\\txtsetup.sif~"; if ((src_iso == NULL) || (dest_dir == NULL)) return FALSE; scan_only = scan; cdio_log_set_handler(log_handler); psz_extract_dir = dest_dir; progress_style = GetWindowLong(hISOProgressBar, GWL_STYLE); if (scan_only) { total_blocks = 0; memset(&iso_report, 0, sizeof(iso_report)); // String array of all isolinux/syslinux locations StrArrayCreate(&config_path, 8); // Change the Window title and static text SetWindowTextU(hISOProgressDlg, scan_text); SetWindowTextU(hISOFileName, scan_text); // Change progress style to marquee for scanning SetWindowLong(hISOProgressBar, GWL_STYLE, progress_style | PBS_MARQUEE); SendMessage(hISOProgressBar, PBM_SETMARQUEE, TRUE, 0); } else { uprintf("Extracting files...\n"); if (total_blocks == 0) { uprintf("Error: ISO has not been properly scanned.\n"); FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|APPERR(ERROR_ISO_SCAN); goto out; } nb_blocks = 0; iso_blocking_status = 0; SetWindowLong(hISOProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE)); SendMessage(hISOProgressBar, PBM_SETPOS, 0, 0); } ShowWindow(hISOProgressDlg, SW_SHOW); UpdateWindow(hISOProgressDlg); /* First try to open as UDF - fallback to ISO if it failed */ p_udf = udf_open(src_iso); if (p_udf == NULL) goto try_iso; uprintf("Disc image is an UDF image\n"); p_udf_root = udf_get_root(p_udf, true, 0); if (p_udf_root == NULL) { uprintf("Couldn't locate UDF root directory\n"); goto out; } if (scan_only) { if (udf_get_logical_volume_id(p_udf, iso_report.label, sizeof(iso_report.label)) <= 0) iso_report.label[0] = 0; } r = udf_extract_files(p_udf, p_udf_root, ""); goto out; try_iso: p_iso = iso9660_open_ext(src_iso, ISO_EXTENSION_ALL); if (p_iso == NULL) { uprintf("Unable to open image '%s'.\n", src_iso); goto out; } i_joliet_level = iso9660_ifs_get_joliet_level(p_iso); uprintf("Disc image is an ISO9660 image\n"); if (scan_only) { if (iso9660_ifs_get_volume_id(p_iso, &tmp)) { safe_strcpy(iso_report.label, sizeof(iso_report.label), tmp); safe_free(tmp); } else iso_report.label[0] = 0; } r = iso_extract_files(p_iso, ""); out: iso_blocking_status = -1; if (scan_only) { // Remove trailing spaces from the label for (j=safe_strlen(iso_report.label)-1; ((j>=0)&&(isspace(iso_report.label[j]))); j--) iso_report.label[j] = 0; // We use the fact that UDF_BLOCKSIZE and ISO_BLOCKSIZE are the same here iso_report.projected_size = total_blocks * ISO_BLOCKSIZE; // We will link the existing isolinux.cfg from a syslinux.cfg we create // If multiple config file exist, choose the one with the shortest path if (iso_report.has_isolinux) { safe_strcpy(iso_report.cfg_path, sizeof(iso_report.cfg_path), config_path.Table[0]); for (i=1; i<config_path.Index; i++) { if (safe_strlen(iso_report.cfg_path) > safe_strlen(config_path.Table[i])) safe_strcpy(iso_report.cfg_path, sizeof(iso_report.cfg_path), config_path.Table[i]); } uprintf("Will use %s for Syslinux\n", iso_report.cfg_path); } if (IS_WINPE(iso_report.winpe)) { // In case we have a WinPE 1.x based iso, we extract and parse txtsetup.sif // during scan, to see if /minint was provided for OsLoadOptions, as it decides // whether we should use 0x80 or 0x81 as the disk ID in the MBR safe_sprintf(path, sizeof(path), "/%s/txtsetup.sif", basedir[((iso_report.winpe&WINPE_I386) == WINPE_I386)?0:1]); ExtractISOFile(src_iso, path, tmp_sif); tmp = get_token_data(tmp_sif, "OsLoadOptions"); if (tmp != NULL) { for (i=0; i<strlen(tmp); i++) tmp[i] = (char)tolower(tmp[i]); uprintf("Checking txtsetup.sif:\n OsLoadOptions = %s\n", tmp); iso_report.uses_minint = (strstr(tmp, "/minint") != NULL); } _unlink(tmp_sif); safe_free(tmp); } StrArrayDestroy(&config_path); } else if (iso_report.has_isolinux) { safe_sprintf(path, sizeof(path), "%s\\syslinux.cfg", dest_dir); // Create a /syslinux.cfg (if none exists) that points to the existing isolinux cfg fd = fopen(path, "r"); if (fd == NULL) { fd = fopen(path, "w"); // No "/syslinux.cfg" => create a new one if (fd == NULL) { uprintf("Unable to create %s - booting from USB will not work\n", path); r = 1; } else { fprintf(fd, "DEFAULT loadconfig\n\nLABEL loadconfig\n CONFIG %s\n", iso_report.cfg_path); for (i=safe_strlen(iso_report.cfg_path); (i>0)&&(iso_report.cfg_path[i]!='/'); i--); if (i>0) { iso_report.cfg_path[i] = 0; fprintf(fd, " APPEND %s/\n", iso_report.cfg_path); iso_report.cfg_path[i] = '/'; } uprintf("Created: %s\n", path); } } if (fd != NULL) fclose(fd); } ShowWindow(hISOProgressDlg, SW_HIDE); if (p_iso != NULL) iso9660_close(p_iso); if (p_udf != NULL) udf_close(p_udf); if ((r != 0) && (FormatStatus == 0)) FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|APPERR((scan_only?ERROR_ISO_SCAN:ERROR_ISO_EXTRACT)); return (r == 0); }
int main(int argc, char **argv) { int mode; rodsServerConfig_t serverConfig; int status; rodsEnv myEnv; /* remove this call or change to LOG_NOTICE for more verbosity */ rodsLogLevel(LOG_ERROR); /* this will cause the sql to be printed, comment this out to skip it */ rodsLogSqlReq(1); mode = 0; if (strcmp(argv[1],"1")==0) mode=1; if (strcmp(argv[1],"2")==0) mode=2; if (strcmp(argv[1],"3")==0) mode=3; if (strcmp(argv[1],"4")==0) mode=4; if (strcmp(argv[1],"5")==0) mode=5; if (strcmp(argv[1],"6")==0) mode=6; memset((char *)&myEnv, 0, sizeof(myEnv)); status = getRodsEnv (&myEnv); if (status < 0) { rodsLog (LOG_ERROR, "main: getRodsEnv error. status = %d", status); exit (1); } if (strstr(myEnv.rodsDebug, "CAT") != NULL) { chlDebug(myEnv.rodsDebug); } memset(&serverConfig, 0, sizeof(serverConfig)); status = readServerConfig(&serverConfig); if ((status = chlOpen(serverConfig.DBUsername, serverConfig.DBPassword)) != 0) { rodsLog (LOG_SYS_FATAL, "chlopen Error. Status = %d", status); return (status); } if (mode==1) { status = doTest1(argv[2], argv[3], argv[4], argv[5]); if (status <0) exit(2); exit(0); } if (mode==2) { status = doTest2(argv[2], argv[3], argv[4], argv[5]); if (status <0) exit(2); exit(0); } if (mode==3) { status = doTest3(argv[2], argv[3], argv[4], argv[5]); if (status <0) exit(2); exit(0); } if (mode==4) { status = doTest4(argv[2], argv[3], argv[4], argv[5]); if (status <0) exit(2); exit(0); } if (mode==5) { status = doTest5(argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]); if (status <0) exit(2); exit(0); } if (mode==6) { status = doTest6(argv[2], argv[3], argv[4], argv[5]); if (status <0) exit(2); exit(0); } exit(0); }
bool CApoxObj::open( const char *szFileName, unsigned long flags ) { const char *p; unsigned long busspeed = 125; m_emergencyInfo = 0; char szDrvParams[ MAX_PATH ]; m_initFlag = flags; m_RxMsgState = USB_IDLE; // save parameter string and conbert to upper case strncpy( szDrvParams, szFileName, MAX_PATH ); _strupr( szDrvParams ); // Initiate statistics m_stat.cntReceiveData = 0; m_stat.cntReceiveFrames = 0; m_stat.cntTransmitData = 0; m_stat.cntTransmitFrames = 0; m_stat.cntBusOff = 0; m_stat.cntBusWarnings = 0; m_stat.cntOverruns = 0; // if open we have noting to do if ( m_bRun ) return true; // serial p = strtok( szDrvParams, ";" ); if ( NULL != p ) { strcpy( m_SerialNumber, p ); } // Bus-Speed p = strtok( NULL, ";" ); if ( NULL != p ) { if ( ( NULL != strstr( p, "0x" ) ) || ( NULL != strstr( p, "0X" ) ) ) { sscanf( p + 2, "%x", &busspeed ); } else { busspeed = atol( p ); } } // Handle busspeed uint8_t nSpeed = CAN_BAUD_1000; switch ( busspeed ) { case 125: nSpeed = CAN_BAUD_125; break; case 250: nSpeed = CAN_BAUD_250; break; case 500: nSpeed = CAN_BAUD_500; break; case 1000: nSpeed = CAN_BAUD_1000; break; default: nSpeed = CAN_BAUD_125; break; } FT_STATUS ftStatus; ftStatus = FT_OpenEx( (void *)m_SerialNumber, FT_OPEN_BY_SERIAL_NUMBER, &m_ftHandle ); if ( !FT_SUCCESS( ftStatus ) ) return false; ftStatus = FT_ResetDevice( m_ftHandle ); ftStatus = FT_Purge( m_ftHandle, FT_PURGE_RX | FT_PURGE_TX ); ftStatus = FT_SetTimeouts(m_ftHandle, 378, 128); ftStatus = FT_SetUSBParameters ( m_ftHandle, 2048, 2048 ); ftStatus = FT_SetLatencyTimer( m_ftHandle, 3 ); // Run run run ..... m_bRun = true; #ifdef WIN32 // Start write thread DWORD threadId; if ( NULL == ( m_hTreadTransmit = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE) workThreadTransmit, this, 0, &threadId ) ) ) { // Failure close(); return false; } // Start read thread if ( NULL == ( m_hTreadReceive = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE) workThreadReceive, this, 0, &threadId ) ) ) { // Failure close(); return false; } // Release the mutex UNLOCK_MUTEX( m_apoxMutex ); UNLOCK_MUTEX( m_receiveMutex ); UNLOCK_MUTEX( m_transmitMutex ); UNLOCK_MUTEX( m_responseMutex ); #else // LINUX pthread_attr_t thread_attr; pthread_attr_init( &thread_attr ); // Create the log write thread. if ( pthread_create( &m_threadId, &thread_attr, workThreadTransmit, this ) ) { syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv write thread."); rv = false; fclose( m_flog ); } // Create the log write thread. if ( pthread_create( &m_threadId, &thread_attr, workThreadReceive, this ) ) { syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv receive thread."); rv = false; fclose( m_flog ); } // We are open m_bOpen = true; // Release the mutex pthread_mutex_unlock( &m_apoxMutex ); #endif // Switch to main mode if in boot mode if ( RUNMODE_BOOT == getAdapterRunMode() ) { setAdapterRunMode( RUNMODE_MAIN ); } // Set baudrate setBaudrate( nSpeed ); // Set initial filter/mask switch( m_initFlag & 0x03 ) { case 0: case 3: m_filtermask.rx_buff1_ext = 0; m_filtermask.rx_buff2_ext = 1; break; case 1: m_filtermask.rx_buff1_ext = 0; m_filtermask.rx_buff2_ext = 0; break; case 2: m_filtermask.rx_buff1_ext = 1; m_filtermask.rx_buff2_ext = 1; break; } m_filtermask.RXM0 = 0; m_filtermask.RXM1 = 0; m_filtermask.RXF0 = 0; m_filtermask.RXF1 = 0; m_filtermask.RXF2 = 0; m_filtermask.RXF3 = 0; m_filtermask.RXF4 = 0; m_filtermask.RXF5 = 0; setAdapterFilterMask( &m_filtermask ); // Set transmission mode short trmode = ( (short)( m_initFlag & 0x0c ) >> 2 ); if ( 0 == trmode ) trmode = TRMODE_NORMAL; setTransmissionMode( trmode ); return true; }
static void dpdk_stats_resolve_cnt_type(char *cnt_type, size_t cnt_type_len, const char *cnt_name) { char *type_end; type_end = strrchr(cnt_name, '_'); if ((type_end != NULL) && (strncmp(cnt_name, "rx_", strlen("rx_")) == 0)) { if (strstr(type_end, "bytes") != NULL) { sstrncpy(cnt_type, "if_rx_octets", cnt_type_len); } else if (strstr(type_end, "error") != NULL) { sstrncpy(cnt_type, "if_rx_errors", cnt_type_len); } else if (strstr(type_end, "dropped") != NULL) { sstrncpy(cnt_type, "if_rx_dropped", cnt_type_len); } else if (strstr(type_end, "packets") != NULL) { sstrncpy(cnt_type, "if_rx_packets", cnt_type_len); } else if (strstr(type_end, "_placement") != NULL) { sstrncpy(cnt_type, "if_rx_errors", cnt_type_len); } else if (strstr(type_end, "_buff") != NULL) { sstrncpy(cnt_type, "if_rx_errors", cnt_type_len); } else { /* Does not fit obvious type: use a more generic one */ sstrncpy(cnt_type, "derive", cnt_type_len); } } else if ((type_end != NULL) && (strncmp(cnt_name, "tx_", strlen("tx_"))) == 0) { if (strstr(type_end, "bytes") != NULL) { sstrncpy(cnt_type, "if_tx_octets", cnt_type_len); } else if (strstr(type_end, "error") != NULL) { sstrncpy(cnt_type, "if_tx_errors", cnt_type_len); } else if (strstr(type_end, "dropped") != NULL) { sstrncpy(cnt_type, "if_tx_dropped", cnt_type_len); } else if (strstr(type_end, "packets") != NULL) { sstrncpy(cnt_type, "if_tx_packets", cnt_type_len); } else { /* Does not fit obvious type: use a more generic one */ sstrncpy(cnt_type, "derive", cnt_type_len); } } else if ((type_end != NULL) && (strncmp(cnt_name, "flow_", strlen("flow_"))) == 0) { if (strstr(type_end, "_filters") != NULL) { sstrncpy(cnt_type, "operations", cnt_type_len); } else if (strstr(type_end, "error") != NULL) sstrncpy(cnt_type, "errors", cnt_type_len); } else if ((type_end != NULL) && (strncmp(cnt_name, "mac_", strlen("mac_"))) == 0) { if (strstr(type_end, "error") != NULL) { sstrncpy(cnt_type, "errors", cnt_type_len); } } else { /* Does not fit obvious type, or strrchr error: * use a more generic type */ sstrncpy(cnt_type, "derive", cnt_type_len); } }
// Read server.config and fill server_properties::properties error server_properties::capture() { error result = SUCCESS(); std::string prop_name, prop_setting; // property name and setting FILE *fptr; char buf[BUF_LEN]; char *fchar; int len; char *key; char DBKey[MAX_PASSWORD_LEN], DBPassword[MAX_PASSWORD_LEN]; memset( &DBKey, '\0', MAX_PASSWORD_LEN ); memset( &DBPassword, '\0', MAX_PASSWORD_LEN ); std::string cfg_file; error ret = irods::get_full_path_for_config_file( SERVER_CONFIG_FILE, cfg_file ); if ( !ret.ok() ) { return PASS( ret ); } fptr = fopen( cfg_file.c_str(), "r" ); if ( fptr == NULL ) { rodsLog( LOG_DEBUG, "Cannot open SERVER_CONFIG_FILE file %s. errno = %d\n", cfg_file.c_str(), errno ); return ERROR( SYS_CONFIG_FILE_ERR, "server.config file error" ); } buf[BUF_LEN - 1] = '\0'; fchar = fgets( buf, BUF_LEN - 1, fptr ); for ( ; fchar != '\0'; ) { if ( buf[0] == '#' || buf[0] == '/' ) { buf[0] = '\0'; /* Comment line, ignore */ } /** * Parsing of server configuration settings */ key = strstr( buf, DB_PASSWORD_KW ); if ( key != NULL ) { len = strlen( DB_PASSWORD_KW ); // Store password in temporary string strncpy( DBPassword, findNextTokenAndTerm( key + len ), MAX_PASSWORD_LEN ); } // DB_PASSWORD_KW key = strstr( buf, DB_KEY_KW ); if ( key != NULL ) { len = strlen( DB_KEY_KW ); // Store key in temporary string strncpy( DBKey, findNextTokenAndTerm( key + len ), MAX_PASSWORD_LEN ); } // DB_KEY_KW // =-=-=-=-=-=-=- // PAM configuration - init PAM values result = properties.set<bool>( PAM_NO_EXTEND_KW, false ); result = properties.set<size_t>( PAM_PW_LEN_KW, 20 ); key = strstr( buf, DB_USERNAME_KW ); if ( key != NULL ) { len = strlen( DB_USERNAME_KW ); // Set property name and setting prop_name.assign( DB_USERNAME_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // DB_USERNAME_KW // =-=-=-=-=-=-=- // PAM configuration - init PAM values result = properties.set<bool>( PAM_NO_EXTEND_KW, false ); result = properties.set<size_t>( PAM_PW_LEN_KW, 20 ); prop_setting.assign( "121" ); result = properties.set<std::string>( PAM_PW_MIN_TIME_KW, prop_setting ); prop_setting.assign( "1209600" ); result = properties.set<std::string>( PAM_PW_MAX_TIME_KW, prop_setting ); // init PAM values key = strstr( buf, PAM_PW_LEN_KW ); if ( key != NULL ) { len = strlen( PAM_PW_LEN_KW ); // Set property name and setting prop_name.assign( PAM_PW_LEN_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<size_t>( prop_name, atoi( prop_setting.c_str() ) ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // PAM_PW_LEN_KW key = strstr( buf, PAM_NO_EXTEND_KW ); if ( key != NULL ) { len = strlen( PAM_NO_EXTEND_KW ); // Set property name and setting prop_name.assign( PAM_NO_EXTEND_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower ); if ( prop_setting == "true" ) { result = properties.set<bool>( PAM_NO_EXTEND_KW, true ); } else { result = properties.set<bool>( PAM_NO_EXTEND_KW, false ); } rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // PAM_NO_EXTEND_KW key = strstr( buf, PAM_PW_MIN_TIME_KW ); if ( key != NULL ) { len = strlen( PAM_PW_MIN_TIME_KW ); // Set property name and setting prop_name.assign( PAM_PW_MIN_TIME_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // PAM_PW_MIN_TIME_KW key = strstr( buf, PAM_PW_MAX_TIME_KW ); if ( key != NULL ) { len = strlen( PAM_PW_MAX_TIME_KW ); // Set property name and setting prop_name.assign( PAM_PW_MAX_TIME_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // PAM_PW_MAX_TIME_KW key = strstr( buf, RUN_SERVER_AS_ROOT_KW ); if ( key != NULL ) { len = strlen( RUN_SERVER_AS_ROOT_KW ); // Set property name and setting prop_name.assign( RUN_SERVER_AS_ROOT_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower ); if ( prop_setting == "true" ) { result = properties.set<bool>( RUN_SERVER_AS_ROOT_KW, true ); } else { result = properties.set<bool>( RUN_SERVER_AS_ROOT_KW, false ); } rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // RUN_SERVER_AS_ROOT_KW key = strstr( buf, DEF_DIR_MODE_KW ); if ( key != NULL ) { len = strlen( DEF_DIR_MODE_KW ); // Set property name and setting prop_name.assign( DEF_DIR_MODE_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<int>( prop_name, strtol( prop_setting.c_str(), 0, 0 ) ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // DEF_DIR_MODE_KW key = strstr( buf, DEF_FILE_MODE_KW ); if ( key != NULL ) { len = strlen( DEF_FILE_MODE_KW ); // Set property name and setting prop_name.assign( DEF_FILE_MODE_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<int>( prop_name, strtol( prop_setting.c_str(), 0, 0 ) ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // DEF_FILE_MODE_KW key = strstr( buf, CATALOG_DATABASE_TYPE_KW ); if ( key != NULL ) { len = strlen( CATALOG_DATABASE_TYPE_KW ); // Set property name and setting prop_name.assign( CATALOG_DATABASE_TYPE_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // CATALOG_DATABASE_TYPE_KW key = strstr( buf, KERBEROS_NAME_KW ); if ( key != NULL ) { len = strlen( KERBEROS_NAME_KW ); // Set property name and setting prop_name.assign( KERBEROS_NAME_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // KERBEROS_NAME_KW key = strstr( buf, KERBEROS_KEYTAB_KW ); if ( key != NULL ) { len = strlen( KERBEROS_KEYTAB_KW ); // Set property name and setting prop_name.assign( KERBEROS_KEYTAB_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); // Now set the appropriate kerberos environment variable setenv( "KRB5_KTNAME", prop_setting.c_str(), 1 ); } // KERBEROS_KEYTAB_KW key = strstr( buf, DEFAULT_HASH_SCHEME_KW ); if ( key != NULL ) { len = strlen( DEFAULT_HASH_SCHEME_KW ); // Set property name and setting prop_name.assign( DEFAULT_HASH_SCHEME_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // DEFAULT_HASH_SCHEME_KW key = strstr( buf, MATCH_HASH_POLICY_KW ); if ( key != NULL ) { len = strlen( MATCH_HASH_POLICY_KW ); // Set property name and setting prop_name.assign( MATCH_HASH_POLICY_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); std::transform( prop_setting.begin(), prop_setting.end(), prop_setting.begin(), ::tolower ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // MATCH_HASH_POLICY_KW key = strstr( buf, LOCAL_ZONE_SID_KW ); if ( key != NULL ) { len = strlen( LOCAL_ZONE_SID_KW ); // Set property name and setting prop_name.assign( LOCAL_ZONE_SID_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); } // LOCAL_ZONE_SID_KW key = strstr( buf, AGENT_KEY_KW.c_str() ); if ( key != NULL ) { len = strlen( AGENT_KEY_KW.c_str() ); // Set property name and setting prop_name.assign( AGENT_KEY_KW ); prop_setting.assign( findNextTokenAndTerm( key + len ) ); if ( 32 != prop_setting.size() ) { rodsLog( LOG_ERROR, "%s field in server.config must be 32 characters in length (currently %d characters in length).", prop_name.c_str(), prop_setting.size() ); fclose( fptr ); return ERROR( SYS_CONFIG_FILE_ERR, "server.config file error" ); } // Update properties table result = properties.set<std::string>( prop_name, prop_setting ); } // AGENT_KEY_KW fchar = fgets( buf, BUF_LEN - 1, fptr ); } // for ( ; fchar != '\0'; ) fclose( fptr ); // unscramble password if ( strlen( DBKey ) > 0 && strlen( DBPassword ) > 0 ) { char sPassword[MAX_PASSWORD_LEN + 10]; strncpy( sPassword, DBPassword, MAX_PASSWORD_LEN ); obfDecodeByKey( sPassword, DBKey, DBPassword ); memset( sPassword, 0, MAX_PASSWORD_LEN ); } // store password and key in server properties prop_name.assign( DB_PASSWORD_KW ); prop_setting.assign( DBPassword ); result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); prop_name.assign( DB_KEY_KW ); prop_setting.assign( DBKey ); result = properties.set<std::string>( prop_name, prop_setting ); rodsLog( LOG_DEBUG1, "%s=%s", prop_name.c_str(), prop_setting.c_str() ); // set the captured flag so we no its already been captured captured_ = true; return result; } // server_properties::capture()
TooN::SE3<> computeTpov_cam(int ref_img_no, int which_blur_sample) { char text_file_name[60]; sprintf(text_file_name,"../data/scene_%02d_%04d.txt",which_blur_sample,(int)ref_img_no); cout << "text_file_name = " << text_file_name << endl; ifstream cam_pars_file(text_file_name); char readlinedata[300]; float4 direction; float4 upvector; Vector<3>posvector; while(1) { cam_pars_file.getline(readlinedata,300); if ( cam_pars_file.eof()) break; istringstream iss; if ( strstr(readlinedata,"cam_dir")!= NULL) { string cam_dir_str(readlinedata); cam_dir_str = cam_dir_str.substr(cam_dir_str.find("= [")+3); cam_dir_str = cam_dir_str.substr(0,cam_dir_str.find("]")); iss.str(cam_dir_str); iss >> direction.x ; iss.ignore(1,','); iss >> direction.y ; iss.ignore(1,',') ; iss >> direction.z; iss.ignore(1,','); cout << direction.x<< ", "<< direction.y << ", "<< direction.z << endl; direction.w = 0.0f; } if ( strstr(readlinedata,"cam_up")!= NULL) { string cam_up_str(readlinedata); cam_up_str = cam_up_str.substr(cam_up_str.find("= [")+3); cam_up_str = cam_up_str.substr(0,cam_up_str.find("]")); iss.str(cam_up_str); iss >> upvector.x ; iss.ignore(1,','); iss >> upvector.y ; iss.ignore(1,','); iss >> upvector.z ; iss.ignore(1,','); upvector.w = 0.0f; }
int GetNvidiaRates(t_screenrate& screenmap) { #ifdef USING_XRANDR MythXDisplay *d = OpenMythXDisplay(); if (!d) { return -1; } Display *dpy; bool ret; int screen, display_devices, mask, major, minor, len, j; char *str, *start; int nDisplayDevice; char *pMetaModes, *pModeLines[8], *tmp, *modeString; char *modeLine, *modeName; int MetaModeLen, ModeLineLen[8]; int thisMask; int id; int twinview = 0; map<int, map<int,bool> > maprate; memset(pModeLines, 0, sizeof(pModeLines)); memset(ModeLineLen, 0, sizeof(ModeLineLen)); /* * Open a display connection, and make sure the NV-CONTROL X * extension is present on the screen we want to use. */ dpy = d->GetDisplay(); screen = d->GetScreen(); if (!XNVCTRLIsNvScreen(dpy, screen)) { LOG(VB_PLAYBACK, LOG_INFO, QString("The NV-CONTROL X extension is not available on screen %1 " "of '%2'.") .arg(screen) .arg(XDisplayName(NULL))); delete d; return -1; } ret = XNVCTRLQueryVersion(dpy, &major, &minor); if (ret != True) { LOG(VB_PLAYBACK, LOG_INFO, QString("The NV-CONTROL X extension does not exist on '%1'.") .arg(XDisplayName(NULL))); delete d; return -1; } ret = XNVCTRLQueryAttribute(dpy, screen, 0, NV_CTRL_DYNAMIC_TWINVIEW, &twinview); if (!ret) { LOG(VB_PLAYBACK, LOG_ERR, "Failed to query if Dynamic Twinview is enabled"); XCloseDisplay(dpy); return -1; } if (!twinview) { LOG(VB_PLAYBACK, LOG_ERR, "Dynamic Twinview not enabled, ignoring"); delete d; return 0; } /* * query the connected display devices on this X screen and print * basic information about each X screen */ ret = XNVCTRLQueryAttribute(dpy, screen, 0, NV_CTRL_CONNECTED_DISPLAYS, &display_devices); if (!ret) { LOG(VB_PLAYBACK, LOG_ERR, "Failed to query the enabled Display Devices."); delete d; return -1; } /* first, we query the MetaModes on this X screen */ ret = XNVCTRLQueryBinaryData(dpy, screen, 0, // n/a NV_CTRL_BINARY_DATA_METAMODES, (unsigned char **)&pMetaModes, &MetaModeLen); if (!ret) { LOG(VB_PLAYBACK, LOG_ERR, "Failed to query the metamode on selected display device."); delete d; return -1; } /* * then, we query the ModeLines for each display device on * this X screen; we'll need these later */ nDisplayDevice = 0; for (mask = 1; mask < (1 << 24); mask <<= 1) { if (!(display_devices & mask)) continue; ret = XNVCTRLQueryBinaryData(dpy, screen, mask, NV_CTRL_BINARY_DATA_MODELINES, (unsigned char **)&str, &len); if (!ret) { LOG(VB_PLAYBACK, LOG_ERR, "Unknown error. Failed to query the enabled Display Devices."); // Free Memory currently allocated for (j=0; j < nDisplayDevice; ++j) { free(pModeLines[j]); } delete d; return -1; } pModeLines[nDisplayDevice] = str; ModeLineLen[nDisplayDevice] = len; nDisplayDevice++; } /* now, parse each MetaMode */ str = start = pMetaModes; for (j = 0; j < MetaModeLen - 1; ++j) { /* * if we found the end of a line, treat the string from * start to str[j] as a MetaMode */ if ((str[j] == '\0') && (str[j+1] != '\0')) { id = extract_id_string(start); /* * the MetaMode may be preceded with "token=value" * pairs, separated by the main MetaMode with "::"; if * "::" exists in the string, skip past it */ tmp = strstr(start, "::"); if (tmp) { tmp += 2; } else { tmp = start; } /* split the MetaMode string by comma */ char *strtok_state = NULL; for (modeString = strtok_r(tmp, ",", &strtok_state); modeString; modeString = strtok_r(NULL, ",", &strtok_state)) { /* * retrieve the modeName and display device mask * for this segment of the Metamode */ parse_mode_string(modeString, &modeName, &thisMask); /* lookup the modeline that matches */ nDisplayDevice = 0; if (thisMask) { for (mask = 1; mask < (1 << 24); mask <<= 1) { if (!(display_devices & mask)) continue; if (thisMask & mask) break; nDisplayDevice++; } } modeLine = find_modeline(modeName, pModeLines[nDisplayDevice], ModeLineLen[nDisplayDevice]); if (modeLine && !modeline_is_interlaced(modeLine)) { int w, h, vfl, hfl, i, irate; double dcl, r; char *buf[256]; uint64_t key, key2; // skip name tmp = strchr(modeLine, '"'); tmp = strchr(tmp+1, '"') +1 ; while (*tmp == ' ') tmp++; i = 0; for (modeString = strtok_r(tmp, " ", &strtok_state); modeString; modeString = strtok_r(NULL, " ", &strtok_state)) { buf[i++] = modeString; } w = strtol(buf[1], NULL, 10); h = strtol(buf[5], NULL, 10); vfl = strtol(buf[8], NULL, 10); hfl = strtol(buf[4], NULL, 10); h = strtol(buf[5], NULL, 10); istringstream istr(buf[0]); istr.imbue(locale("C")); istr >> dcl; r = (dcl * 1000000.0) / (vfl * hfl); irate = (int) round(r * 1000.0); key = DisplayResScreen::CalcKey(w, h, (double) id); key2 = DisplayResScreen::CalcKey(w, h, 0.0); // We need to eliminate duplicates, giving priority to the first entries found if (maprate.find(key2) == maprate.end()) { // First time we see this resolution, create a map for it maprate[key2] = map<int, bool>(); } if ((maprate[key2].find(irate) == maprate[key2].end()) && (screenmap.find(key) == screenmap.end())) { screenmap[key] = r; maprate[key2][irate] = true; } } free(modeName); } /* move to the next MetaMode */ start = &str[j+1]; }
/* Write a data item to a character string */ int sprint_gauge_info_item( char *string, /* character string */ size_t nstring, /* string length */ char *keyword, /* keyword */ char *fmt, /* output format - must use s, d, e, f, or g */ char *src, /* address of starting data floating point data must be of type (Real) */ int count, /* number of data items if > 1 */ int stride) /* byte stride of data if count > 1 */ { int i,k,n; size_t bytes; char *data; float tt; /* Check for valid keyword */ for (i = 0; strlen(gauge_info_keyword[i]) > 0 && strcmp(gauge_info_keyword[i], keyword) != 0; i++); if (strlen(gauge_info_keyword[i]) == 0) printf("write_gauge_info_item: WARNING: keyword %s not in table\n", keyword); /* Write keyword */ bytes = 0; snprintf(string,nstring-bytes,"%s =",keyword); bytes = strlen(string); if (bytes >= nstring)return 1; /* Write count if more than one item */ if (count > 1) { snprintf(string+bytes, nstring-bytes, "[%d]",count); bytes = strlen(string); if (bytes >= nstring)return 1; } n = count; if (n == 0)n = 1; /* Write data */ for (k = 0, data = (char *)src; k < n; k++, data += stride) { snprintf(string+bytes, nstring-bytes," "); bytes = strlen(string); if (bytes >= nstring)return 1; if (strstr(fmt,"s") != NULL) { snprintf(string+bytes,nstring-bytes, fmt,data); bytes = strlen(string); if (bytes >= nstring)return 1; } else if (strstr(fmt,"d") != NULL) { snprintf(string+bytes,nstring-bytes,fmt,*(int *)data); bytes = strlen(string); if (bytes >= nstring)return 1; } else if (strstr(fmt,"lu") != NULL) { snprintf(string + bytes, nstring - bytes, fmt, *(unsigned long *)data); bytes = strlen(string); if (bytes >= nstring)return 1; } else if (strstr(fmt, "e") != NULL || strstr(fmt, "f") != NULL || strstr(fmt, "g") != NULL) { tt = *(Real *)data; snprintf(string+bytes,nstring-bytes,fmt,tt); bytes = strlen(string); if (bytes >= nstring)return 1; } else { printf("write_gauge_info_item: Unrecognized data type %s\n",fmt); return 1; } } snprintf(string + bytes, nstring - bytes, "\n"); bytes = strlen(string); if (bytes >= nstring)return 1; return 0; }
void get_block_devs(hd_data_t *hd_data) { str_list_t *sl; char *s, *t; unsigned u1, u2, u3; uint64_t ul0; hd_t *hd, *hd1; hd_dev_num_t dev_num; str_list_t *sf_class, *sf_class_e; char *sf_cdev = NULL, *sf_dev = NULL, *sf_dev_ide; char *sf_drv_name, *sf_drv, *bus_id, *bus_name, *ide_bus_id; str_list_t *sf_bus, *sf_bus_e; char *sf_block_dir; hd_data->lsscsi = free_str_list(hd_data->lsscsi); hd_data->lsscsi = read_file("|/usr/bin/lsscsi -t 2>/dev/null", 0, 0); ADD2LOG("----- lsscsi -----\n"); for(sl = hd_data->lsscsi; sl; sl = sl->next) { ADD2LOG(" %s", sl->str); } ADD2LOG("----- lsscsi end -----\n"); sf_bus = read_dir("/sys/bus/ide/devices", 'l'); if(sf_bus) { for(sf_bus_e = sf_bus; sf_bus_e; sf_bus_e = sf_bus_e->next) { sf_dev = new_str(hd_read_sysfs_link("/sys/bus/ide/devices", sf_bus_e->str)); ADD2LOG( " ide: bus_id = %s path = %s\n", sf_bus_e->str, hd_sysfs_id(sf_dev) ); free_mem(sf_dev); } } sf_block_dir = "/sys/subsystem/block"; sf_class = read_dir(sf_block_dir, 'l'); if (!sf_class) { sf_block_dir = "/sys/class/block"; sf_class = read_dir(sf_block_dir, 'l'); } if (!sf_class) { sf_block_dir = "/sys/block"; sf_class = read_dir(sf_block_dir, 'd'); } if(!sf_class) { ADD2LOG("sysfs: no such class: block\n"); return; } for(sf_class_e = sf_class; sf_class_e; sf_class_e = sf_class_e->next) { str_printf(&sf_cdev, 0, "%s/%s", sf_block_dir, sf_class_e->str); ADD2LOG( " block: name = %s, path = %s\n", sf_class_e->str, hd_sysfs_id(sf_cdev) ); memset(&dev_num, 0, sizeof dev_num); if((s = get_sysfs_attr_by_path(sf_cdev, "dev"))) { if(sscanf(s, "%u:%u", &u1, &u2) == 2) { dev_num.type = 'b'; dev_num.major = u1; dev_num.minor = u2; dev_num.range = 1; } ADD2LOG(" dev = %u:%u\n", u1, u2); } if(hd_attr_uint(get_sysfs_attr_by_path(sf_cdev, "range"), &ul0, 0)) { dev_num.range = ul0; ADD2LOG(" range = %u\n", dev_num.range); } sf_dev = new_str(hd_read_sysfs_link(sf_cdev, "device")); sf_drv_name = NULL; sf_drv = hd_read_sysfs_link(sf_dev, "driver"); if(!sf_drv) { /* maybe older kernel */ sf_drv = hd_read_sysfs_link(sf_cdev, "driver"); } if(sf_drv) { sf_drv_name = strrchr(sf_drv, '/'); if(sf_drv_name) sf_drv_name++; } sf_drv_name = new_str(sf_drv_name); bus_id = sf_dev ? strrchr(sf_dev, '/') : NULL; if(bus_id) bus_id++; bus_name = NULL; if( (s = hd_read_sysfs_link(sf_dev, "subsystem")) || (s = hd_read_sysfs_link(sf_dev, "bus")) ) { bus_name = strrchr(s, '/'); if(bus_name) bus_name++; bus_name = new_str(bus_name); } if(sf_dev) { ADD2LOG( " block device: bus = %s, bus_id = %s driver = %s\n path = %s\n", bus_name, bus_id, sf_drv_name, hd_sysfs_id(sf_dev) ); } hd = NULL; #if defined(__s390x__) || defined(__s390__) /* check if disk is DASD and has already been found by s390.c */ if(sf_drv_name && strstr(sf_drv_name,"dasd")) { char bid[9]; hd_res_t* res; //fprintf(stderr,"dn %s bi %s\n",sf_drv_name,bus_id); for(hd=hd_data->hd;hd;hd=hd->next) { //fprintf(stderr,"bcid %d\n",hd->base_class.id); if(hd->base_class.id == bc_storage_device && hd->detail && hd->detail->ccw.type == hd_detail_ccw) { for(res=hd->res;res;res=res->next) { if(res->io.type==res_io) { sprintf(bid,"%01x.%01x.%04x", hd->detail->ccw.data->lcss >> 8, hd->detail->ccw.data->lcss & 0xff, (unsigned short)res->io.base); //fprintf(stderr,"bid %s\n",bid); if (strcmp(bid,bus_id)==0) goto out; } } } } hd=NULL; out:; }
void *threadfunc() { int cnt,cnt1; char str[100]; char copy[100],tmpstr[100],tmpfinal[100]; int z;int i; char restartFile[100],rstart[100]; int pos; char processID[100],check[400],context[100]; FILE *fp; while(1) { if(read(sockdes,buff,sizeof(buff))) { puts(buff); if(!strcmp(buff,"CP")) { FILE *procs; procs = popen("ps -e -o pid,cmd","r"); fscanf(procs,"%s",processID); fgets(str,100,procs); while(!feof(procs)) { fscanf(procs,"%s",processID); fgets(str,100,procs); if(strstr(str,"a.out")!=NULL) { sprintf(str,"cr_checkpoint --save-all --kill %s",processID); strcpy(tmpstr,"/home/cse4119/context_files/bal/context."); strcat(tmpstr,processID); printf("\nHere\n"); for(cnt=0;strcmp(tmpstr,processIDs[cnt])!=0;cnt++) { // printf("\n%s --> %s",processIDs[cnt],tmpstr); } printf("\nHere\n"); for(cnt1=(cnt+1);cnt1<noOfProcess;cnt1++) strcpy(processIDs[cnt1-1],processIDs[cnt1]); noOfProcess--; strcpy(check,"\0"); fp=popen(str,"r"); fgets(check,100,fp); fclose(fp); if(strstr(check,"Checkpoint")!=NULL) { printf("\nThe selected file could not be checkpointed"); } else { printf("\nForced Checkpoint due to overload successful\n"); sprintf(context,"chmod 777 context.%s",processID); system(context); sprintf(context,"mv context.%s /home/cse4119/context_files/redist/context.%s",processID,processID); system(context); break; } } } } else if(strstr(buff,"FAIL")!=NULL) { for(z=strlen(buff);buff[z]!='/';z--); z++; pos=0; for(;z<=strlen(buff);z++) restartFile[pos++]=buff[z]; printf("\nTo be restarted: %s",restartFile); if(strstr(buff,"FAIL")!=NULL) { for(i=5;i<=strlen(buff);i++) { rstart[i-5]=buff[i]; } } // sprintf(copy,"mv %s %s",rstart,restartFile); // system(copy); // sleep(3); printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\nRESTART\n&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\n"); pthread_create(&restartThread,NULL,restartFunc,buff); pthread_create(&restartThreadRem,NULL,restartFuncDel,rstart); } else if(strstr(buff,"context")!=NULL) { sprintf(copy,"mv /home/cse4119/context_files/redist/%s %s",buff,buff); system(copy); sprintf(tmpfinal,"/home/cse4119/context_files/redist/%s",buff); // printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\nRESTART\n&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&&&&&&&&&&&&&&&&&&&\n"); pthread_create(&restartThread,NULL,restartFunc,buff); //pthread_create(&restartThreadRem,NULL,restartFuncDel,tmpfinal); } } } }
int /* O - 1 on success, 0 on error */ translate_messages(cups_array_t *cat, /* I - Message catalog */ const char *lang) /* I - Output language... */ { /* * Google provides a simple translation/language tool for translating * from one language to another. It is far from perfect, however it * can be used to get a basic translation done or update an existing * translation when no other resources are available. * * Translation requests are sent as HTTP POSTs to * "http://translate.google.com/translate_t" with the following form * variables: * * Name Description Value * -------- ---------------------------------- ---------------- * hl Help language? "en" * ie Input encoding "UTF8" * langpair Language pair "en|" + language * oe Output encoding "UTF8" * text Text to translate translation string */ int ret; /* Return value */ _cups_message_t *m; /* Current message */ int tries; /* Number of tries... */ http_t *http; /* HTTP connection */ http_status_t status; /* Status of POST request */ char *idptr, /* Pointer into msgid */ buffer[65536], /* Input/output buffer */ *bufptr, /* Pointer into buffer */ *bufend, /* Pointer to end of buffer */ length[16]; /* Content length */ int bytes; /* Number of bytes read */ /* * Connect to translate.google.com... */ puts("Connecting to translate.google.com..."); if ((http = httpConnect("translate.google.com", 80)) == NULL) { perror("Unable to connect to translate.google.com"); return (0); } /* * Scan the current messages, requesting a translation of any untranslated * messages... */ for (m = (_cups_message_t *)cupsArrayFirst(cat), ret = 1; m; m = (_cups_message_t *)cupsArrayNext(cat)) { /* * Skip messages that are already translated... */ if (m->str && m->str[0]) continue; /* * Encode the form data into the buffer... */ snprintf(buffer, sizeof(buffer), "hl=en&ie=UTF8&langpair=en|%s&oe=UTF8&text=", lang); bufptr = buffer + strlen(buffer); bufend = buffer + sizeof(buffer) - 5; for (idptr = m->id; *idptr && bufptr < bufend; idptr ++) if (*idptr == ' ') *bufptr++ = '+'; else if (*idptr < ' ' || *idptr == '%') { sprintf(bufptr, "%%%02X", *idptr & 255); bufptr += 3; } else if (*idptr != '&') *bufptr++ = *idptr; *bufptr++ = '&'; *bufptr = '\0'; sprintf(length, "%d", (int)(bufptr - buffer)); /* * Send the request... */ printf("\"%s\" = ", m->id); fflush(stdout); tries = 0; do { httpClearFields(http); httpSetField(http, HTTP_FIELD_CONTENT_TYPE, "application/x-www-form-urlencoded"); httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, length); if (httpPost(http, "/translate_t")) { httpReconnect(http); httpPost(http, "/translate_t"); } httpWrite2(http, buffer, bufptr - buffer); while ((status = httpUpdate(http)) == HTTP_CONTINUE); if (status != HTTP_OK && status != HTTP_ERROR) httpFlush(http); tries ++; } while (status == HTTP_ERROR && tries < 10); if (status == HTTP_OK) { /* * OK, read the translation back... */ bufptr = buffer; bufend = buffer + sizeof(buffer) - 1; while ((bytes = httpRead2(http, bufptr, bufend - bufptr)) > 0) bufptr += bytes; if (bytes < 0) { /* * Read error, abort! */ puts("READ ERROR!"); ret = 0; break; } *bufptr = '\0'; /* * Find the div containing translation */ if ((bufptr = strstr(buffer, "<div id=result_box")) == NULL) { /* * No textarea, abort! */ puts("NO div id=result_box!"); ret = 0; break; } if ((bufptr = strchr(bufptr, '>')) == NULL) { /* * textarea doesn't end, abort! */ puts("DIV SHORT DATA!"); ret = 0; break; } bufptr ++; if ((bufend = strstr(bufptr, "</div>")) == NULL) { /* * textarea doesn't close, abort! */ puts("/DIV SHORT DATA!"); ret = 0; break; } *bufend = '\0'; /* * Copy the translation... */ m->str = strdup(bufptr); /* * Convert character entities to regular chars... */ for (bufptr = strchr(m->str, '&'); bufptr; bufptr = strchr(bufptr + 1, '&')) { if (!strncmp(bufptr, "<", 4)) { *bufptr = '<'; _cups_strcpy(bufptr + 1, bufptr + 4); } else if (!strncmp(bufptr, ">", 4)) { *bufptr = '>'; _cups_strcpy(bufptr + 1, bufptr + 4); } else if (!strncmp(bufptr, "&", 5)) _cups_strcpy(bufptr + 1, bufptr + 5); } printf("\"%s\"\n", m->str); } else if (status == HTTP_ERROR) { printf("NETWORK ERROR (%s)!\n", strerror(httpError(http))); ret = 0; break; } else { printf("HTTP ERROR %d!\n", status); ret = 0; break; } } httpClose(http); return (ret); }
void fmtprint(const char *libname, Obj_Entry *obj, const char *fmt1, const char *fmt2) { const char *libpath = obj ? obj->path : "not found"; char libnamebuf[200]; char *libmajor = NULL; const char *fmt; char *cp; int c; if (strncmp(libname, "lib", 3) == 0 && (cp = strstr(libname, ".so")) != NULL) { int i = cp - (libname + 3); if (i >= sizeof(libnamebuf)) i = sizeof(libnamebuf) - 1; (void)memcpy(libnamebuf, libname + 3, i); libnamebuf[i] = '\0'; if (cp[3] && isdigit((unsigned char)cp[4])) libmajor = &cp[4]; libname = libnamebuf; } if (fmt1 == NULL) fmt1 = libmajor != NULL ? "\t-l%o.%m => %p\n" : "\t-l%o => %p\n"; if (fmt2 == NULL) fmt2 = "\t%o => %p\n"; fmt = libname == libnamebuf ? fmt1 : fmt2; while ((c = *fmt++) != '\0') { switch (c) { default: putchar(c); continue; case '\\': switch (c = *fmt) { case '\0': continue; case 'n': putchar('\n'); break; case 't': putchar('\t'); break; } break; case '%': switch (c = *fmt) { case '\0': continue; case '%': default: putchar(c); break; case 'A': printf("%s", main_local); break; case 'a': printf("%s", main_progname); break; case 'o': printf("%s", libname); break; case 'm': printf("%s", libmajor); break; case 'n': /* XXX: not supported for elf */ break; case 'p': printf("%s", libpath); break; case 'x': printf("%p", obj ? obj->mapbase : 0); break; } break; } ++fmt; } }
void HitProtein::loadProteinInfo(string proteinLocation) { //open protein db file, read and store protein infomation string proteinFile(proteinLocation); proteinFile += proteinName; proteinFile += ".db"; FILE* fptr = fopen((char*) proteinFile.c_str(), "r"); if (fptr == NULL) { cout << "input file: " << proteinFile << " can't open" << endl; } else { int lineLength = 5000; char line[lineLength]; while (fgets(line, lineLength, fptr) != NULL) { if ((strstr(line, ">Real Sequence Info:") != NULL)) { fgets(line, lineLength, fptr); int numberOfChars = 0; while (line[numberOfChars] != '\0') { numberOfChars++; } numberOfChars--; string _realSequenceInfo(line); setRealSequenceInfo(_realSequenceInfo); //cout << realSequenceInfo << endl; setRealSequenceLength(numberOfChars); //cout << realSequenceLength << endl; } if ((strstr(line, ">Ca XYZ:") != NULL)) { double Xs[realSequenceLength]; double Ys[realSequenceLength]; double Zs[realSequenceLength]; double temp; for (int i = 0; i < realSequenceLength; i++) { fscanf(fptr, "%lf", &temp); Xs[i] = temp; //if (i % 10 == 0) { // cout << endl; // } // cout << Xs[i] << " "; } //cout << endl; for (int i = 0; i < realSequenceLength; i++) { fscanf(fptr, "%lf", &temp); Ys[i] = temp; //if (i % 10 == 0) { // cout << endl; // } // cout << Ys[i] << " "; } //cout << endl; for (int i = 0; i < realSequenceLength; i++) { fscanf(fptr, "%lf", &temp); Zs[i] = temp; //if (i % 10 == 0) { // cout << endl; // } // cout << Zs[i] << " "; } //cout << endl; CAlpha_XYZ = (Point*) malloc( sizeof(Point) * realSequenceLength); for (int i = 0; i < realSequenceLength; i++) { Point point(Xs[i], Ys[i], Zs[i]); CAlpha_XYZ[i] = point; } } } } }
static void set_utmpx (struct utmpx *u, const char *line, const char *user, const char *host, time_t date, int addp) { static const char letters[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; memset (u, 0, sizeof (*u)); if (line) { if(strcmp(line, ":0") == 0) (void) strcpy(u->ut_line, "console"); else (void) strncpy (u->ut_line, line, sizeof (u->ut_line)); strncpy(u->ut_host, line, sizeof(u->ut_host)); #ifdef HAVE_STRUCT_UTMPX_UT_SYSLEN u->ut_syslen = strlen(line); #endif } else memset (u->ut_line, 0, sizeof (u->ut_line)); if (addp && user) (void) strncpy (u->ut_user, user, sizeof (u->ut_user)); else memset (u->ut_user, 0, sizeof (u->ut_user)); if (line) { size_t i; /* * this is a bit crufty, but * follows the apparent conventions in * the ttys file. ut_id is only 4 bytes * long, and the last 4 bytes of the line * name are written into it, left justified. */ i = strlen (line); if (i >= sizeof (u->ut_id)) i -= sizeof (u->ut_id); else i = 0; (void) strncpy (u->ut_id, line + i, sizeof (u->ut_id)); /* make sure there is no entry using identical ut_id */ if (!UtmpxIdOpen(u->ut_id) && addp) { int limit = sizeof(letters) - 1; int t = 0; u->ut_id[1] = line[i]; u->ut_id[2] = line[i+1]; u->ut_id[3] = line[i+2]; do { u->ut_id[0] = letters[t]; t++; } while (!UtmpxIdOpen(u->ut_id) && (t < limit)); } if (!addp && strstr(line, ":") != NULL) { struct utmpx *tmpu; while ( (tmpu = getutxent()) != NULL ) { if ( (strcmp(tmpu->ut_host, line) == 0 ) && tmpu->ut_type != DEAD_PROCESS ) { strncpy(u->ut_id, tmpu->ut_id, sizeof(u->ut_id)); break; } } endutxent(); } } else memset (u->ut_id, 0, sizeof (u->ut_id)); if (addp) { u->ut_pid = getppid (); u->ut_type = USER_PROCESS; } else { u->ut_pid = 0; u->ut_type = DEAD_PROCESS; } u->ut_tv.tv_sec = date; u->ut_tv.tv_usec = 0; }
/** pgn_open(): pgn_open opens a .pgn file and reads all games into the internal database. The number of games found is returned. Created 091407; last modified 091607 **/ int pgn_open(char *file_name) { char buffer[BUFSIZ]; char *c; char *b; int games; long last_offset; PGN_GAME *game; PGN_STATE state; /* Try opening the file. */ if (pgn_file != NULL) fclose(pgn_file); pgn_file = fopen(file_name, "rt"); if (pgn_file == NULL) { print("%s: file not found.\n", file_name); return -1; } /* First, quickly find the number of games. */ state = NEUTRAL; games = 0; while (fgets(buffer, BUFSIZ, pgn_file) != NULL) { switch (state) { case NEUTRAL: /* Stupid macros need an int cast... sigh */ if (isspace((int)buffer[0])) continue; state = HEADERS; case HEADERS: if (buffer[0] == '[') continue; state = MOVES; case MOVES: if (strstr(buffer, "1-0") || strstr(buffer, "0-1") || strstr(buffer, "1/2-1/2") || strstr(buffer, "*")) { games++; state = NEUTRAL; } } } /* Initialize the database. */ if (pgn_database.game != NULL) free(pgn_database.game); pgn_database.game_count = games; pgn_database.game = calloc(games, sizeof(PGN_GAME)); print("%i games loaded.\n", games); /* Read in all of the games. */ state = NEUTRAL; rewind(pgn_file); last_offset = 0; game = &pgn_database.game[0]; while (fgets(buffer, BUFSIZ, pgn_file)) { switch (state) { case NEUTRAL: /* Stupid macros need an int cast... sigh */ if (isspace((int)buffer[0])) continue; game->offset = last_offset; state = HEADERS; case HEADERS: if (buffer[0] == '[') { c = strtok(buffer, "\""); if (c == NULL) continue; c = strtok(buffer + strlen(c) + 1, "\""); if (c == NULL) continue; b = strtok(buffer + 1, " =\""); if (!strcmp(b, "Event")) strcpy(game->tag.event, c); if (!strcmp(b, "Site")) strcpy(game->tag.site, c); if (!strcmp(b, "Date")) strcpy(game->tag.date, c); if (!strcmp(b, "Round")) strcpy(game->tag.round, c); if (!strcmp(b, "White")) strcpy(game->tag.white, c); if (!strcmp(b, "Black")) strcpy(game->tag.black, c); if (!strcmp(b, "Result")) strcpy(game->tag.result, c); if (!strcmp(b, "FEN")) { strcpy(game->tag.fen, c); initialize_board(c); } continue; } state = MOVES; case MOVES: if (strstr(buffer, "1-0") || strstr(buffer, "0-1") || strstr(buffer, "1/2-1/2") || strstr(buffer, "*")) { game++; state = NEUTRAL; } } last_offset = ftell(pgn_file); } return games; }
int SearchCSVForWKT( const char *pszFileCSV, const char *pszTarget ) { const char *pszFilename = NULL; const char *pszWKT = NULL; char szTemp[1024]; int nPos = 0; const char *pszTemp = NULL; VSILFILE *fp = NULL; OGRSpatialReference oSRS; int nCode = 0; int nFound = -1; CPLDebug( "gdalsrsinfo", "SearchCSVForWKT()\nfile=%s\nWKT=%s\n", pszFileCSV, pszTarget); /* -------------------------------------------------------------------- */ /* Find and open file. */ /* -------------------------------------------------------------------- */ // pszFilename = pszFileCSV; pszFilename = CPLFindFile( "gdal", pszFileCSV ); if( pszFilename == NULL ) { CPLDebug( "gdalsrsinfo", "could not find support file %s", pszFileCSV ); // return OGRERR_UNSUPPORTED_SRS; return -1; } /* support gzipped file */ if ( strstr( pszFileCSV,".gz") != NULL ) sprintf( szTemp, "/vsigzip/%s", pszFilename); else sprintf( szTemp, "%s", pszFilename); CPLDebug( "gdalsrsinfo", "SearchCSVForWKT() using file %s", szTemp ); fp = VSIFOpenL( szTemp, "r" ); if( fp == NULL ) { CPLDebug( "gdalsrsinfo", "could not open support file %s", pszFilename ); // return OGRERR_UNSUPPORTED_SRS; return -1; } /* -------------------------------------------------------------------- */ /* Process lines. */ /* -------------------------------------------------------------------- */ const char *pszLine; while( (pszLine = CPLReadLine2L(fp,-1,NULL)) != NULL ) { // CPLDebug( "gdalsrsinfo", "read line %s", pszLine ); if( pszLine[0] == '#' ) continue; /* do nothing */; // else if( EQUALN(pszLine,"include ",8) ) // { // eErr = importFromDict( pszLine + 8, pszCode ); // if( eErr != OGRERR_UNSUPPORTED_SRS ) // break; // } // else if( strstr(pszLine,",") == NULL ) // /* do nothing */; pszTemp = strstr(pszLine,","); if (pszTemp) { nPos = pszTemp - pszLine; if ( nPos == 0 ) continue; strncpy( szTemp, pszLine, nPos ); szTemp[nPos] = '\0'; nCode = atoi(szTemp); pszWKT = (char *) pszLine + nPos +1; // CPLDebug( "gdalsrsinfo", // "code=%d\nWKT=\n[%s]\ntarget=\n[%s]\n", // nCode,pszWKT, pszTarget ); if ( EQUAL(pszTarget,pszWKT) ) { nFound = nCode; CPLDebug( "gdalsrsinfo", "found EPSG:%d\n" "current=%s\ntarget= %s\n", nCode, pszWKT, pszTarget ); break; } } } VSIFCloseL( fp ); return nFound; }
int memtest_test_linux_anonymous_maps(void) { FILE *fp = fopen("/proc/self/maps","r"); char line[1024]; size_t start_addr, end_addr, size; size_t start_vect[MEMTEST_MAX_REGIONS]; size_t size_vect[MEMTEST_MAX_REGIONS]; int regions = 0, j; uint64_t crc1 = 0, crc2 = 0, crc3 = 0; while(fgets(line,sizeof(line),fp) != NULL) { char *start, *end, *p = line; start = p; p = strchr(p,'-'); if (!p) continue; *p++ = '\0'; end = p; p = strchr(p,' '); if (!p) continue; *p++ = '\0'; if (strstr(p,"stack") || strstr(p,"vdso") || strstr(p,"vsyscall")) continue; if (!strstr(p,"00:00")) continue; if (!strstr(p,"rw")) continue; start_addr = strtoul(start,NULL,16); end_addr = strtoul(end,NULL,16); size = end_addr-start_addr; start_vect[regions] = start_addr; size_vect[regions] = size; printf("Testing %lx %lu\n", (unsigned long) start_vect[regions], (unsigned long) size_vect[regions]); regions++; } /* Test all the regions as an unique sequential region. * 1) Take the CRC64 of the memory region. */ for (j = 0; j < regions; j++) { crc1 = crc64(crc1,(void*)start_vect[j],size_vect[j]); } /* 2) Invert bits, swap adjacent words, swap again, invert bits. * This is the error amplification step. */ for (j = 0; j < regions; j++) memtest_non_destructive_invert((void*)start_vect[j],size_vect[j]); for (j = 0; j < regions; j++) memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]); for (j = 0; j < regions; j++) memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]); for (j = 0; j < regions; j++) memtest_non_destructive_invert((void*)start_vect[j],size_vect[j]); /* 3) Take the CRC64 sum again. */ for (j = 0; j < regions; j++) crc2 = crc64(crc2,(void*)start_vect[j],size_vect[j]); /* 4) Swap + Swap again */ for (j = 0; j < regions; j++) memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]); for (j = 0; j < regions; j++) memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]); /* 5) Take the CRC64 sum again. */ for (j = 0; j < regions; j++) crc3 = crc64(crc3,(void*)start_vect[j],size_vect[j]); /* NOTE: It is very important to close the file descriptor only now * because closing it before may result into unmapping of some memory * region that we are testing. */ fclose(fp); /* If the two CRC are not the same, we trapped a memory error. */ return crc1 != crc2 || crc2 != crc3; }
void CreateMcd(char *mcd) { FILE *f; struct stat buf; int s = MCD_SIZE; int i=0, j; f = fopen(mcd, "wb"); if (f == NULL) return; if(stat(mcd, &buf)!=-1) { if ((buf.st_size == MCD_SIZE + 3904) || strstr(mcd, ".gme")) { s = s + 3904; fputc('1', f); s--; fputc('2', f); s--; fputc('3', f); s--; fputc('-', f); s--; fputc('4', f); s--; fputc('5', f); s--; fputc('6', f); s--; fputc('-', f); s--; fputc('S', f); s--; fputc('T', f); s--; fputc('D', f); s--; for(i=0;i<7;i++) { fputc(0, f); s--; } fputc(1, f); s--; fputc(0, f); s--; fputc(1, f); s--; fputc('M', f); s--; fputc('Q', f); s--; for(i=0;i<14;i++) { fputc(0xa0, f); s--; } fputc(0, f); s--; fputc(0xff, f); while (s-- > (MCD_SIZE+1)) fputc(0, f); } else if ((buf.st_size == MCD_SIZE + 64) || strstr(mcd, ".mem") || strstr(mcd, ".vgs")) { s = s + 64; fputc('V', f); s--; fputc('g', f); s--; fputc('s', f); s--; fputc('M', f); s--; for(i=0;i<3;i++) { fputc(1, f); s--; fputc(0, f); s--; fputc(0, f); s--; fputc(0, f); s--; } fputc(0, f); s--; fputc(2, f); while (s-- > (MCD_SIZE+1)) fputc(0, f); } } fputc('M', f); s--; fputc('C', f); s--; while (s-- > (MCD_SIZE-127)) fputc(0, f); fputc(0xe, f); s--; for(i=0;i<15;i++) { // 15 blocks fputc(0xa0, f); s--; for(j=0;j<126;j++) { fputc(0x00, f); s--; } fputc(0xa0, f); s--; } while ((s--)>=0) fputc(0, f); fclose(f); }
/** * json_events - Read JSON event file from disk and call event callback. * @fn: File name to read or NULL for default. * @func: Callback to call for each event * @data: Abstract pointer to pass to func. * * The callback gets the data pointer, the event name, the event * in perf format and a description passed. * * Call func with each event in the json file * Return: -1 on failure, otherwise 0. */ int json_events(const char *fn, int (*func)(void *data, char *name, char *event, char *desc), void *data) { int err = -EIO; size_t size; jsmntok_t *tokens, *tok; int i, j, len; char *map; if (!fn) fn = json_default_name(); tokens = parse_json(fn, &map, &size, &len); if (!tokens) return -EIO; EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array"); tok = tokens + 1; for (i = 0; i < tokens->size; i++) { char *event = NULL, *desc = NULL, *name = NULL; struct msrmap *msr = NULL; jsmntok_t *msrval = NULL; jsmntok_t *precise = NULL; jsmntok_t *obj = tok++; EXPECT(obj->type == JSMN_OBJECT, obj, "expected object"); for (j = 0; j < obj->size; j += 2) { jsmntok_t *field, *val; int nz; field = tok + j; EXPECT(field->type == JSMN_STRING, tok + j, "Expected field name"); val = tok + j + 1; EXPECT(val->type == JSMN_STRING, tok + j + 1, "Expected string value"); nz = !json_streq(map, val, "0"); if (match_field(map, field, nz, &event, val)) { /* ok */ } else if (json_streq(map, field, "EventName")) { addfield(map, &name, "", "", val); } else if (json_streq(map, field, "BriefDescription")) { addfield(map, &desc, "", "", val); fixdesc(desc); } else if (json_streq(map, field, "PEBS") && nz && !strstr(desc, "(Precise Event)")) { precise = val; } else if (json_streq(map, field, "MSRIndex") && nz) { msr = lookup_msr(map, val); } else if (json_streq(map, field, "MSRValue")) { msrval = val; } else if (json_streq(map, field, "Errata") && !json_streq(map, val, "null")) { addfield(map, &desc, ". ", " Spec update: ", val); } else if (json_streq(map, field, "Data_LA") && nz) { addfield(map, &desc, ". ", " Supports address when precise", NULL); } /* ignore unknown fields */ } if (precise) { if (json_streq(map, precise, "2")) addfield(map, &desc, " ", "(Must be precise)", NULL); else addfield(map, &desc, " ", "(Precise event)", NULL); } if (msr != NULL) addfield(map, &event, ",", msr->pname, msrval); fixname(name); err = func(data, name, event, desc); free(event); free(desc); free(name); if (err) break; tok += j; } EXPECT(tok - tokens == len, tok, "unexpected objects at end"); err = 0; out_free: free_json(map, size, tokens); return err; }
//fpga and switch reg reload int sys_reg_load_form_yangy(void) { char buff[100]; int i,ret,j; FILE *fp; int addr_s; char *pbuf = buff; short *pdata = malloc(16*sizeof(short)); int pswitch = 0; int val; int tmp_vid; int reg; DEBUG(GLOBAL_OUT_GROUP,"%s:%d",__FUNCTION__,__LINE__); fp = fopen("/etc/fpgaconfig","r"); if(fp==NULL){ return -1; } while((strstr(buff,"[FPGA REGS]") == NULL) && !feof(fp)) fgets(buff,100,fp); // find FPGA REG CONFIG INFORMATION while(!feof(fp)){ fgets(buff,100,fp); if(buff[0]=='[') break; if((buff[0]=='\r')||(buff[0]=='\n')) continue; pbuf = buff; addr_s=0; addr_s = strtol(pbuf,NULL,16)&0xffff; //DEBUG(GLOBAL_OUT_GROUP," %04hx,",addr_s); //usleep(1); pbuf +=5; /* for(i=0;i<16;i++){ if((*pbuf=='\r') || (*pbuf == '\n') || (*pbuf == '\0')) break; reg_Val = strtol(pbuf,NULL,16); *(pdata+i)=reg_Val; sys_wr_fpga_reg(((addr_s+i)),reg_Val); //<<1 pbuf +=5; } memset(tmp_buf,0,sizeof(tmp_buf)); tmp_len=sprintf(tmp_buf,"%04hx:",addr_s&0xffff); for(i=0;i<16;i++){ tmp_len+=sprintf(tmp_buf+tmp_len,"%04hx ",(*(pdata+i))&0xffff); } DEBUG(GLOBAL_OUT_GROUP,"%s",tmp_buf); */ for(i=0;i<16;i++){ if((*pbuf=='\r') || (*pbuf == '\n') || (*pbuf == '\0')) break; *(pdata+i) = strtol(pbuf,NULL,16); pbuf +=5; } sys_wr_fpga_continue((addr_s),pdata,i*2); } free(pdata); fclose(fp); usleep(100); fp = fopen("/etc/fpgaconfig","r"); if(fp==NULL){ return -1; } memset(buff,0,100); while((strstr(buff,"[88E6161 REGS]") == NULL) && (!feof(fp)) ) fgets(buff,100,fp); addr_s=0x0; while(!feof(fp)){ //memset(buff,0,100); fgets(buff,100,fp); if(buff[0]=='[') break; if((buff[0]=='\r')||(buff[0]=='\n')) continue; pbuf = buff; for(j=0;j<6;j++){ //*(pdata+i) = strtol(pbuf,NULL,16); val = strtol(pbuf,NULL,16); if((*pbuf=='\r') || (*pbuf == '\n') || (*pbuf == '\0')) break; smiWriteReg(addr_s++,0,val); pbuf +=5; //DEBUG(GLOBAL_OUT_GROUP,"phyaddr=0x%2x,regaddr=0x%2x,value=0x%4x\n",i,j,val); } if(j>=6) break; } addr_s=0x10; while(!feof(fp)){ //memset(buff,0,100); fgets(buff,100,fp); if(buff[0]=='[') break; if((buff[0]=='\r')||(buff[0]=='\n')) continue; pbuf = buff; for(j=0;(j<16);j++){ //*(pdata+i) = strtol(pbuf,NULL,16); val = strtol(pbuf,NULL,16); if((*pbuf=='\r') || (*pbuf == '\n') || (*pbuf == '\0')) break; smiWriteReg(addr_s,j,val); pbuf +=5; //DEBUG(GLOBAL_OUT_GROUP,"phyaddr=0x%2x,regaddr=0x%2x,value=0x%4x\n",i,j,val); } addr_s++; if(addr_s>=0x16) break; } while(!feof(fp)){ memset(buff,0,100); fgets(buff,15,fp); if(buff[0]=='[') break; if((buff[0]=='\r')) continue; if(buff[0]=='\n') continue; pbuf = buff; init_read_times(); reg=0; while((reg&0x8000) && read_times_larger_than_0()) { smiReadReg(0x1b,5,®); } val = strtol(pbuf,NULL,16)&0xffff; pbuf +=5; //syslog(LOG_DAEMON,"%s:vid=%x",__FUNCTION__,val); if( ((val & 0x1000)==0) || ((val&0xfff) == 0xfff) || val==0 ) break; tmp_vid = (val&0xffff); val = strtol(pbuf,NULL,16)&0xffff; pbuf +=5; smiWriteReg(0x1b,7,val); val = strtol(pbuf,NULL,16)&0xffff; pbuf +=5; smiWriteReg(0x1b,8,val); // val = strtol(pbuf,NULL,16)&0xffff; // pbuf +=5; // smiWriteReg(0x1b,9,val); smiWriteReg(0x1b,6,(tmp_vid&0xffff)); smiWriteReg(0x1b,2,0); smiWriteReg(0x1b,5,0xb000); } fclose(fp); //if(pswitch>0) // close(pswitch); return 0; }
/* * Split an URL into components. URL syntax is: * [method:/][/[user[:pwd]@]host[:port]/][document] * This almost, but not quite, RFC1738 URL syntax. */ struct url * fetchParseURL(const char *URL) { char *doc; const char *p, *q; struct url *u; int i; /* allocate struct url */ if ((u = calloc(1, sizeof(*u))) == NULL) { fetch_syserr(); return (NULL); } /* scheme name */ if ((p = strstr(URL, ":/"))) { snprintf(u->scheme, URL_SCHEMELEN+1, "%.*s", (int)(p - URL), URL); URL = ++p; /* * Only one slash: no host, leave slash as part of document * Two slashes: host follows, strip slashes */ if (URL[1] == '/') URL = (p += 2); } else { p = URL; } if (!*URL || *URL == '/' || *URL == '.' || (u->scheme[0] == '\0' && strchr(URL, '/') == NULL && strchr(URL, ':') == NULL)) goto nohost; p = strpbrk(URL, "/@"); if (p && *p == '@') { /* username */ q = fetch_pctdecode(u->user, URL, URL_USERLEN); /* password */ if (*q == ':') q = fetch_pctdecode(u->pwd, q + 1, URL_PWDLEN); p++; } else { p = URL; } /* hostname */ #ifdef INET6 if (*p == '[' && (q = strchr(p + 1, ']')) != NULL && (*++q == '\0' || *q == '/' || *q == ':')) { if ((i = q - p - 2) > MAXHOSTNAMELEN) i = MAXHOSTNAMELEN; strncpy(u->host, ++p, i); p = q; } else #endif for (i = 0; *p && (*p != '/') && (*p != ':'); p++) if (i < MAXHOSTNAMELEN) u->host[i++] = *p; /* port */ if (*p == ':') { for (q = ++p; *q && (*q != '/'); q++) if (isdigit((unsigned char)*q)) u->port = u->port * 10 + (*q - '0'); else { /* invalid port */ url_seterr(URL_BAD_PORT); goto ouch; } p = q; } nohost: /* document */ if (!*p) p = "/"; if (strcasecmp(u->scheme, SCHEME_HTTP) == 0 || strcasecmp(u->scheme, SCHEME_HTTPS) == 0) { const char hexnums[] = "0123456789abcdef"; /* percent-escape whitespace. */ if ((doc = malloc(strlen(p) * 3 + 1)) == NULL) { fetch_syserr(); goto ouch; } u->doc = doc; while (*p != '\0') { if (!isspace((unsigned char)*p)) { *doc++ = *p++; } else { *doc++ = '%'; *doc++ = hexnums[((unsigned int)*p) >> 4]; *doc++ = hexnums[((unsigned int)*p) & 0xf]; p++; } } *doc = '\0'; } else if ((u->doc = strdup(p)) == NULL) {