int main(char *argc, char *argv[]) { char l[1025], c = 0; int fd = 0, left = 0, n = 0, eof = 0; struct stat fs; write(2, "*****************\n\r", 19); write(2, "*** grep time ***\r\n", 19); write(2, "*****************\n\r", 19); reset(l, 1025); //getc(); if(argc == 2) { fstat(0, &fs); if((fs.st_mode & 0010000)) //FIFO (it's a pipe!) { while(n = readLine(l, 256, 0, &eof)) { if(l[0] == '~') {exit(0);} if(grep(l, argv[1])) { write(1, l, n); putc('\r'); } reset(l, 1025); if(eof) {putc(0); break;} } } else { while(gets(l)) { if(l[0] == '~') {exit(0);} if(grep(l, argv[1])) { printf("%s\n", l); } reset(l, 256); } } } else { fd = open(argv[2], O_RDONLY); if(fd < 0) { return -1; } fstat(fd, &fs); left = fs.st_size; while(left > 0) { if(left >= 1024) { n = readLine(l, 1024, fd, &eof); } else { n = readLine(l, left, fd, &eof); } l[n+1] = 0; if(grep(l, argv[1])) { write(1, l, n); putc('\r'); } reset(l, 1025); left -= n; } putc(0); close(fd); } //printf("\n"); exit(1); }
// usage: smp <IP address to connect to> int main( int argc, char** argv ) { if ( argc != 2 ) /* argc should be 2 for correct execution */ { printf( "usage:\n\tsmp <ipaddress>\n\tsmp server\n" ); return EXIT_FAILURE; } int bServerMode = strstr( "server", argv[ 1 ] ) != 0; setup(); unsigned char holder[ BUFFER_SIZE ]; memset( holder, 0x00, BUFFER_SIZE ); if ( !bServerMode ) { // we are talking to the server at ip address argv[ 1 ] char input_string[ 256 ]; printf( "Enter a shared secret: " ); readLine( input_string, 256 ); // TESTCODE: strcpy( input_string, "testme" ); secret = binEncode( input_string, strlen( input_string ) ); /*****************************************************/ /*****************************************************/ /* Do Step 1 and send to other side */ /*****************************************************/ /*****************************************************/ int len = step1( holder, BUFFER_SIZE ); int serverfd = connect_to_server( argv[ 1 ] ); if ( serverfd == 1 ) return EXIT_FAILURE; write_to_server( serverfd, holder, len ); // dumpBuff( holder, len ); /*****************************************************/ /*****************************************************/ /* Get results from other side. */ /* Other side performed Step 2. */ /*****************************************************/ /*****************************************************/ memset( holder, 0x00, BUFFER_SIZE ); len = revc_from_server( serverfd, holder, BUFFER_SIZE ); // dumpBuff( holder, len ); /*****************************************************/ /*****************************************************/ /* Do Step 3 and send to the other side */ /*****************************************************/ /*****************************************************/ step3( holder, BUFFER_SIZE ); write_to_server( serverfd, holder, len ); /*****************************************************/ /*****************************************************/ /* Get bytes from other side and do Step 5 */ /*****************************************************/ /*****************************************************/ memset( holder, 0x00, BUFFER_SIZE ); len = revc_from_server( serverfd, holder, BUFFER_SIZE ); // dumpBuff( holder, len ); step5( holder, len ); disconnect_from_server( serverfd ); } else // we are in server mode, other side will send us data first { int listenfd = listen_server(); /*if ( listenfd == 1 ) return EXIT_FAILURE; TODO: error checking */ char input_string[ 256 ]; printf( "Enter a shared secret: " ); readLine( input_string, 256 ); // TESTCODE: strcpy( input_string, "testme" ); secret = binEncode( input_string, strlen( input_string ) ); int len = revc_from_server( listenfd, holder, BUFFER_SIZE ); // dumpBuff( holder, BUFFER_SIZE); /*****************************************************/ /*****************************************************/ /* Do Step 2 and send to other side */ /*****************************************************/ /*****************************************************/ len = step2( holder, BUFFER_SIZE ); write_to_server( listenfd, holder, len ); len = revc_from_server( listenfd, holder, BUFFER_SIZE ); // dumpBuff( holder, len ); /*****************************************************/ /*****************************************************/ /* Do Step 4 and send to other side */ /*****************************************************/ /*****************************************************/ len = step4( holder, BUFFER_SIZE ); write_to_server( listenfd, holder, len ); disconnect_from_server( listenfd ); } if ( match == 1 ) printf( "Secrets match\n" ); else printf( "Secrets do not match\n"); cleanup(); return EXIT_SUCCESS; }
void rlSpawn::printAll() { const char *cptr; while((cptr=readLine()) != NULL) ::printf("%s",cptr); }
static int processMultiBulkItem(redisReader *r) { redisReadTask *cur = &(r->rstack[r->ridx]); void *obj; char *p; long elements; int root = 0; /* Set error for nested multi bulks with depth > 1 */ if (r->ridx == 2) { __redisReaderSetError(r,REDIS_ERR_PROTOCOL, "No support for nested multi bulk replies with depth > 1"); return REDIS_ERR; } if ((p = readLine(r,NULL)) != NULL) { elements = readLongLong(p); root = (r->ridx == 0); if (elements == -1) { if (r->fn && r->fn->createNil) obj = r->fn->createNil(cur); else obj = (void*)REDIS_REPLY_NIL; if (obj == NULL) { __redisReaderSetErrorOOM(r); return REDIS_ERR; } moveToNextTask(r); } else { if (r->fn && r->fn->createArray) obj = r->fn->createArray(cur,elements); else obj = (void*)REDIS_REPLY_ARRAY; if (obj == NULL) { __redisReaderSetErrorOOM(r); return REDIS_ERR; } /* Modify task stack when there are more than 0 elements. */ if (elements > 0) { cur->elements = elements; cur->obj = obj; r->ridx++; r->rstack[r->ridx].type = -1; r->rstack[r->ridx].elements = -1; r->rstack[r->ridx].idx = 0; r->rstack[r->ridx].obj = NULL; r->rstack[r->ridx].parent = cur; r->rstack[r->ridx].privdata = r->privdata; } else { moveToNextTask(r); } } /* Set reply if this is the root object. */ if (root) r->reply = obj; return REDIS_OK; } return REDIS_ERR; }
void computeVariedScaleFactors(const string& dataEfficienciesFileName, const string& MCEfficienciesFileName, const string& outputFile, const unsigned int numSigPars, const float nominalScaleFactor) { //open data and MC efficiency text files ifstream dataEfficienciesFile(dataEfficienciesFileName.c_str()); ifstream MCEfficienciesFile(MCEfficienciesFileName.c_str()); if (!dataEfficienciesFile.is_open() || !MCEfficienciesFile.is_open()) { cerr << "Error opening file " << dataEfficienciesFileName << " and/or "; cerr << MCEfficienciesFileName << ".\n"; return; } //quantities to be calculated and printed vector<float> scaleFactor; vector<float> error; vector<float> deviationFromNominal; //quantities to be read and re-printed vector<float> alphaPass; vector<float> nPass; vector<float> alphaFail; vector<float> nFail; vector<string> bkgShape; vector<float> dataEfficiency; vector<float> dataEfficiencyErrorHigh; vector<float> dataEfficiencyErrorLow; vector<float> dataEfficiencyError; vector<float> MCEfficiency; vector<float> MCEfficiencyErrorHigh; vector<float> MCEfficiencyErrorLow; vector<float> MCEfficiencyError; //read each file unsigned int lineNum = 0; unsigned int dataFail = 0; unsigned int MCFail = 0; while (!dataEfficienciesFile.eof() && !MCEfficienciesFile.eof()) { //check each line of the file to see if it is a comment string dataLine, MCLine; getline(dataEfficienciesFile, dataLine); getline(MCEfficienciesFile, MCLine); ++lineNum; if ((dataLine.find('#') == string::npos) && (dataLine.length() != 0) && (MCLine.find('#') == string::npos) && (MCLine.length() != 0)) { /*grab all words and check that signal and background shape parameters are equal for data and MC*/ vector<float> dataFloatPars, MCFloatPars; string dataBkgPar, MCBkgPar; readLine(dataFloatPars, dataBkgPar, dataLine); readLine(MCFloatPars, MCBkgPar, MCLine); if ((dataFloatPars.size() == MCFloatPars.size()) && (dataBkgPar == MCBkgPar)) { bool equal = true; unsigned int iFloatPar = 0; while ((iFloatPar < numSigPars) && equal) { equal = equal && (dataFloatPars[iFloatPar] == MCFloatPars[iFloatPar]); ++iFloatPar; } if (equal) { /*if the error isn't -1, compute the scale factor, error, and deviation of scale factor from nominal*/ if (dataFloatPars[dataFloatPars.size() - 1] != -1.0) ++dataFail; if (MCFloatPars[MCFloatPars.size() - 1] != -1.0) ++MCFail; if ((dataFloatPars[dataFloatPars.size() - 1] != -1.0) && (MCFloatPars[MCFloatPars.size() - 1] != -1.0)) { const unsigned int efficiencyIndex = numSigPars; const unsigned int errorIndex = dataFloatPars.size() - 1; scaleFactor.push_back(dataFloatPars[efficiencyIndex]/MCFloatPars[efficiencyIndex]); error.push_back(scaleFactor[scaleFactor.size() - 1]* sqrt(((dataFloatPars[errorIndex]*dataFloatPars[errorIndex])/ (dataFloatPars[efficiencyIndex]*dataFloatPars[efficiencyIndex])) + ((MCFloatPars[errorIndex]*MCFloatPars[errorIndex])/ (MCFloatPars[efficiencyIndex]*MCFloatPars[efficiencyIndex])))); deviationFromNominal.push_back(scaleFactor[scaleFactor.size() - 1] - nominalScaleFactor); //save other information alphaPass.push_back(dataFloatPars[0]); nPass.push_back(dataFloatPars[1]); alphaFail.push_back(dataFloatPars[2]); nFail.push_back(dataFloatPars[3]); bkgShape.push_back(dataBkgPar); dataEfficiency.push_back(dataFloatPars[4]); dataEfficiencyErrorHigh.push_back(dataFloatPars[5]); dataEfficiencyErrorLow.push_back(dataFloatPars[6]); dataEfficiencyError.push_back(dataFloatPars[7]); MCEfficiency.push_back(MCFloatPars[4]); MCEfficiencyErrorHigh.push_back(MCFloatPars[5]); MCEfficiencyErrorLow.push_back(MCFloatPars[6]); MCEfficiencyError.push_back(MCFloatPars[7]); } } } else { cerr << "Error processing " << dataEfficienciesFileName << " and "; cerr << MCEfficienciesFileName << " at line " << lineNum << ".\n"; } } } //close files dataEfficienciesFile.close(); MCEfficienciesFile.close(); //open file for dumping scale factors, errors, and deviations from nominal ofstream out(outputFile.c_str()); if (!out.is_open()) { cerr << "Error opening file " << outputFile << ".\n"; return; } out << "#alphaPass nPass alphaFail nFail bkgShape dataEfficiency dataEfficiencyErrorHigh "; out << "dataEfficiencyErrorLow dataEfficiencyError MCEfficiency MCEfficiencyErrorHigh "; out << "MCEfficiencyErrorLow MCEfficiencyError scaleFactor scaleFactorError "; out << "scaleFactorDeviationFromNominal\n"; vector<float> deviationFromNominalCopy; deviationFromNominalCopy.resize(deviationFromNominal.size()); copy(deviationFromNominal.begin(), deviationFromNominal.end(), deviationFromNominalCopy.begin()); sort(deviationFromNominal.begin(), deviationFromNominal.end()); for (vector<float>::const_iterator iDeviation = deviationFromNominal.begin(); iDeviation != deviationFromNominal.end(); ++iDeviation) { vector<float>::const_iterator p = find(deviationFromNominalCopy.begin(), deviationFromNominalCopy.end(), *iDeviation); const unsigned int index = p - deviationFromNominalCopy.begin(); out << alphaPass[index] << " " << nPass[index] << " " << alphaFail[index] << " "; out << nFail[index] << " " << bkgShape[index] << " " << dataEfficiency[index] << " "; out << dataEfficiencyErrorHigh[index] << " " << dataEfficiencyErrorLow[index] << " "; out << dataEfficiencyError[index] << " " << MCEfficiency[index] << " "; out << MCEfficiencyErrorHigh[index] << " " << MCEfficiencyErrorLow[index] << " "; out << MCEfficiencyError[index] << " " << scaleFactor[index] << " " << error[index] << " "; out << *iDeviation << endl; } out.close(); }
void spider(void *pack,char *line,char * pathtable) { struct MemoryStruct chunk; FILE *fp=NULL; bool match_string=false,save_response=false,test_tamper=false; long status=0,length=0; int old=0,res=0,counter=0,counter_cookie=0,counter_agent=0,POST=0,timeout=0,debug_host=3; char *make=NULL,*make_cookie=NULL,*make_agent=NULL,*tamper=NULL,*responsetemplate=NULL,*tmp_response=NULL,*tmp_make=NULL,*tmp_make_cookie=NULL,*tmp_make_agent=NULL,*tmp_line=NULL,*tmp_line2=NULL; char **pack_ptr=(char **)pack,**arg = pack_ptr; char randname[16],line2[1024],log[2048],tabledata[4086],pathsource[1024]; if(arg[12]!=NULL) save_response=true; if(arg[8]!=NULL) timeout=atoi(arg[8]); // payload tamper if(arg[20]!=NULL) { tamper=arg[20]; if(strstr(tamper,"encode64")) { line=encode64(line,strlen(line)-1); test_tamper=true; } if(strstr(tamper,"randcase")) { line=rand_case(line); test_tamper=true; } if(strstr(tamper,"urlencode")) { line=urlencode(line); test_tamper=true; } if(strstr(tamper,"double_urlencode")) { line=double_urlencode(line); test_tamper=true; } if(strstr(tamper,"spaces2comment")) { line=spaces2comment(line); test_tamper=true; } if(strstr(tamper,"unmagicquote")) { line=unmagicquote(line); test_tamper=true; } if(strstr(tamper,"apostrophe2nullencode")) { line=apostrophe2nullencode(line); test_tamper=true; } if(strstr(tamper,"rand_comment")) { line=rand_comment(line); test_tamper=true; } if(strstr(tamper,"rand_space")) { line=rand_space(line); test_tamper=true; } if(test_tamper==false) { DEBUG("error at tamper argument\n"); exit(0); } } memset(pathsource,0,sizeof(char)*1023); if(save_response==false) { strcat(pathsource,"0"); } // brute POST/GET/COOKIES/UserAgent if(arg[21]==NULL) { POST=(arg[4]==NULL)?0:1; counter=char_type_counter(POST?arg[4]:arg[0],'^'); counter_cookie=char_type_counter(arg[13]!=NULL?arg[13]:"",'^'); counter_agent=char_type_counter(arg[19]!=NULL?arg[19]:"",'^'); old=counter; } else { char *file_request=readLine(arg[21]); counter=char_type_counter(file_request,'^'); old=counter; xfree((void**)&file_request); } chomp(line); // goto to fix signal stop if user do ctrl+c try_again: while ( old > 0 || counter_cookie > 0 || counter_agent > 0 ) { CURL *curl; // curl_global_init(CURL_GLOBAL_ALL); chunk.memory=NULL; chunk.size = 0; curl_socket_t sockfd; /* socket */ long sockextr; size_t iolen; curl = curl_easy_init(); // DEBUG("counts ^ : %d \n",old); if(arg[21]==NULL) { make=payload_injector( (POST?arg[4]:arg[0]),line,old); if(arg[13]!=NULL) make_cookie=payload_injector( arg[13],line,counter_cookie); if(arg[19]!=NULL) make_agent=payload_injector( arg[19],line,counter_agent); curl_easy_setopt(curl, CURLOPT_URL, POST?arg[0]:make); } else { // if is custom request char *request_file=readLine(arg[21]); make=payload_injector( request_file,line,old); curl_easy_setopt(curl, CURLOPT_URL, arg[0]); xfree((void**)&request_file); } if ( POST ) curl_easy_setopt(curl, CURLOPT_POSTFIELDS, make); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); // load user agent if ( arg[6]!=NULL ) { curl_easy_setopt(curl, CURLOPT_USERAGENT, arg[6]); } else { curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (0d1n v0.1) "); } // json headers to use JSON if(arg[14]!=NULL) { struct curl_slist *headers = NULL; curl_slist_append(headers, arg[14]); if(arg[16]!=NULL) { curl_slist_append(headers, "Accept: application/json"); curl_slist_append(headers, "Content-Type: application/json"); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_slist_free_all(headers); } else { if(arg[16] != NULL) { struct curl_slist *headers = NULL; curl_slist_append(headers, "Accept: application/json"); curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_slist_free_all(headers); } } //use custom method PUT,DELETE... if(arg[15]!=NULL) { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, arg[15]); } curl_easy_setopt(curl, CURLOPT_ENCODING,"gzip,deflate"); // load cookie jar if ( arg[3] != NULL ) { curl_easy_setopt(curl,CURLOPT_COOKIEFILE,arg[3]); curl_easy_setopt(curl,CURLOPT_COOKIEJAR,arg[3]); } else { curl_easy_setopt(curl,CURLOPT_COOKIEJAR,"odin_cookiejar.txt"); } // LOAD cookie fuzz if(arg[13]!=NULL) { curl_easy_setopt(curl,CURLOPT_COOKIE,make_cookie); } // LOAD UserAgent FUZZ if(arg[19]!=NULL) { curl_easy_setopt(curl,CURLOPT_USERAGENT,make_agent); } curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1); // Load cacert if ( arg[7] != NULL ) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2); curl_easy_setopt(curl, CURLOPT_CAINFO, arg[7]); } else { curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0L); curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L); } if(timeout) curl_easy_setopt(curl,CURLOPT_TIMEOUT,timeout); // load single proxy if(arg[17] != NULL) { curl_easy_setopt(curl, CURLOPT_PROXY, arg[17]); // curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1); } // load random proxy in list if(arg[18] != NULL) { char *randproxy=Random_linefile(arg[18]); // printf("PROXY LOAD: %s\n",randproxy); curl_easy_setopt(curl, CURLOPT_PROXY, randproxy); // curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1); } if ( arg[9] != NULL ) curl_easy_setopt(curl,CURLOPT_SSLVERSION,(long)atoi(arg[9])); curl_easy_setopt(curl,CURLOPT_VERBOSE,0); curl_easy_setopt(curl,CURLOPT_HEADER,1); if(arg[21]!=NULL) { curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L); } res=curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,&status); // custom http request if(arg[21]!=NULL) { curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, &sockextr); sockfd = sockextr; if(!wait_on_socket(sockfd, 0, 60000L)) { DEBUG("error in socket at custom http request"); } res=curl_easy_send(curl, make, strlen(make), &iolen); // recv data while(1) { wait_on_socket(sockfd, 1, 60000L); chunk.memory=xmalloc(sizeof(char)*3024); res = curl_easy_recv(curl, chunk.memory, 3023, &iolen); chunk.size=strlen(chunk.memory); if(strlen(chunk.memory) > 8) break; if(CURLE_OK != res) break; } status=(long)parse_http_status(chunk.memory); //status=404; } // length of response if(chunk.size<=0) length=0.0; else length=chunk.size; if(status==0) { debug_host--; DEBUG("Problem in Host: \n %s",chunk.memory); if(debug_host<0) exit(0); goto try_again; } // arg[10] list to find with regex , arg[2] list without regex if( (arg[2]) || (arg[10]) ) { if(save_response==true) { memset(pathsource,0,sizeof(char)*1023); } fp = fopen((arg[2]!=NULL)?arg[2]:arg[10], "r"); if ( !fp ) { DEBUG("error to open response list"); exit(1); } while ( fgets(line2,1023,fp) != NULL) { chomp(line2); // find a string in response if(status != 0) { if ( arg[2] != NULL ) match_string=strstr(chunk.memory,line2)?true:false; if ( arg[10] != NULL ) match_string=strstr_regex(chunk.memory,line2)?true:false; } if(chunk.memory && (match_string == true) ) { if(make_cookie!=NULL) { fprintf(stdout,"%s [ %s %ld %s ] Payload: %s %s %s Grep: %s %s %s Params: %s \nCookie: %s %s\n",YELLOW,CYAN,status,YELLOW,GREEN,line,YELLOW,CYAN,line2,YELLOW,make,make_cookie,LAST); } if(make_agent!=NULL) { fprintf(stdout,"%s [ %s %ld %s ] Payload: %s %s %s Grep: %s %s %s Params: %s \nCookie: %s %s\n",YELLOW,CYAN,status,YELLOW,GREEN,line,YELLOW,CYAN,line2,YELLOW,make,make_agent,LAST); } else { fprintf(stdout,"%s [ %s %ld %s ] Payload: %s %s %s Grep: %s %s %s Params: %s %s\n",YELLOW,CYAN,status,YELLOW,GREEN,line,YELLOW,CYAN,line2,YELLOW,make,LAST); } if(save_response==true) { // create responses path memset(pathsource,0,sizeof(char)*1023); strncat(pathsource,"response_sources/",18); strncat(pathsource,arg[5], 15); mkdir(pathsource,S_IRWXU|S_IRWXG|S_IRWXO); snprintf(pathsource,986,"response_sources/%s/%s.html",arg[5],rand_str(randname, sizeof randname)); } // write log file snprintf(log,2047,"[ %ld ] Payload: %s Grep: %s Params: %s cookie: %s UserAgent: %s \n Path Response Source: %s\n",status,line,line2,make,(make_cookie!=NULL)?make_cookie:" ",(make_agent!=NULL)?make_agent:" ",pathsource); WriteFile(arg[5],log); memset(log,0,2047); if(save_response==true) { // write highlights response responsetemplate=NULL; responsetemplate=readLine(TEMPLATE); WriteFile(pathsource,responsetemplate); memset(responsetemplate,0,strlen(responsetemplate)-1); tmp_response=NULL; tmp_response=html_entities(chunk.memory); WriteFile(pathsource,tmp_response); memset(tmp_response,0,strlen(tmp_response)-1); WriteFile(pathsource,"</pre></html>"); } // create datatables tmp_make=html_entities(make); tmp_line2=html_entities(line2); tmp_line=html_entities(line); if(make_cookie!=NULL) { tmp_make_cookie=html_entities(make_cookie); snprintf(tabledata,4085,"[\"<a class=\\\"fancybox fancybox.iframe\\\" href=\\\"../%s\\\">%ld </a>\",\"%ld\",\"%s cookie: %s\",\"%s\",\"%s\"],\n",pathsource,status,length,tmp_make,tmp_make_cookie,tmp_line2,tmp_line); memset(tmp_make_cookie,0,strlen(tmp_make_cookie)-1); } if(make_agent!=NULL) { tmp_make_agent=html_entities(make_agent); snprintf(tabledata,4085,"[\"<a class=\\\"fancybox fancybox.iframe\\\" href=\\\"../%s\\\">%ld </a>\",\"%ld\",\"%s UserAgent: %s\",\"%s\",\"%s\"],\n",pathsource,status,length,tmp_make,tmp_make_agent,tmp_line2,tmp_line); memset(tmp_make_agent,0,strlen(tmp_make_agent)-1); } else { snprintf(tabledata,4085,"[\"<a class=\\\"fancybox fancybox.iframe\\\" href=\\\"../%s\\\">%ld </a>\",\"%ld\",\"%s\",\"%s\",\"%s\"],\n",pathsource,status,length,tmp_make,tmp_line2,tmp_line); } WriteFile(pathtable,tabledata); // memset(tmp_make,0,strlen(tmp_make)-1); // memset(tmp_make_cookie,0,strlen(tmp_make_cookie)-1); // memset(tmp_make_agent,0,strlen(tmp_make_agent)-1); memset(tmp_line,0,strlen(tmp_line)-1); memset(tmp_line2,0,strlen(tmp_line2)-1); memset(tabledata,0,4085); memset(pathsource,0,strlen(pathsource)-1); } } if( fclose(fp) == EOF ) { DEBUG("Error in close()"); exit(1); } fp=NULL; } else { if(counter_cookie) { fprintf(stdout,"%s [ %s %ld %s ] Payload: %s %s %s Params: %s %s\n Cookie: %s %s\n",YELLOW,CYAN,status,YELLOW,GREEN,line,YELLOW,CYAN,make,make_cookie,LAST); } if(counter_agent) { fprintf(stdout,"%s [ %s %ld %s ] Payload: %s %s %s Params: %s %s\n UserAgent: %s %s\n",YELLOW,CYAN,status,YELLOW,GREEN,line,YELLOW,CYAN,make,make_agent,LAST); } else { fprintf(stdout,"%s [ %s %ld %s ] Payload: %s %s %s Params: %s %s %s\n",YELLOW,CYAN,status,YELLOW,GREEN,line,YELLOW,CYAN,make,LAST); } if(save_response==true) { // memset(pathsource,0,sizeof(char)*1023); strncat(pathsource,"response_sources/",18); strncat(pathsource,arg[5], 15); mkdir(pathsource,S_IRWXU|S_IRWXG|S_IRWXO); snprintf(pathsource,986,"response_sources/%s/%s.html",arg[5],rand_str(randname, sizeof randname)); } //write logs snprintf(log,2047,"[%ld Payload: %s Params: %s Cookie: %s UserAgent: %s \n Path Response Source: %s\n",status,line,make,(make_cookie!=NULL)?make_cookie:" ",(make_agent!=NULL)?make_agent:" ",pathsource); WriteFile(arg[5],log); memset(log,0,2047); if(save_response==true) { // write response source with highlights responsetemplate=readLine(TEMPLATE); WriteFile(pathsource,responsetemplate); //memset(responsetemplate,0,strlen(responsetemplate)-1); tmp_response=html_entities(chunk.memory); WriteFile(pathsource,tmp_response); //memset(tmp_response,0,strlen(tmp_response)-1); WriteFile(pathsource,"</pre></html>"); } // create datatables tmp_make=html_entities(make); tmp_line=html_entities(line); if(counter_cookie) { tmp_make_cookie=html_entities(make_cookie); snprintf(tabledata,4085,"[\"<a class=\\\"fancybox fancybox.iframe\\\" href=\\\"../%s\\\">%ld </a>\",\"%ld\",\"%s cookie: %s\",\"\",\"%s\"],\n",pathsource,status,length,tmp_make,tmp_make_cookie,tmp_line); // memset(tmp_make_cookie,0,strlen(tmp_make_cookie)-1); } if(counter_agent) { tmp_make_agent=html_entities(make_agent); snprintf(tabledata,4085,"[\"<a class=\\\"fancybox fancybox.iframe\\\" href=\\\"../%s\\\">%ld </a>\",\"%ld\",\"%s UserAgent: %s\",\"\",\"%s\"],\n",pathsource,status,length,tmp_make,tmp_make_agent,tmp_line); } else { snprintf(tabledata,4047,"[\"<a class=\\\"fancybox fancybox.iframe\\\" href=\\\"../%s\\\">%ld </a>\",\"%ld\",\"%s\",\"\",\"%s\"],\n",pathsource,status,length,tmp_make,tmp_line); } WriteFile(pathtable,tabledata); memset(tmp_make,0,strlen(tmp_make)-1); memset(tmp_line,0,strlen(tmp_line)-1); memset(tabledata,0,4085); memset(pathsource,0,strlen(pathsource)-1); //DEBUG("part B"); } //DEBUG("END PARTS"); // memset(make,0,strlen(make)-1); // memset(make_cookie,0,strlen(make_cookie)-1); // memset(make_agent,0,strlen(make_agent)-1); // memset(pathsource,0,strlen(pathsource)-1); xfree((void **)&chunk.memory); // curl_easy_cleanup(curl); // curl_global_cleanup(); if(old>0) old--; if(counter_cookie > 0) counter_cookie--; if(counter_agent > 0) counter_agent--; debug_host=3; } xfree((void **)&make_agent); xfree((void **)&make_cookie); xfree((void **)&make); xfree((void **)&tmp_make); xfree((void **)&tmp_make_cookie); xfree((void **)&tmp_make_agent); xfree((void **)&tmp_line); xfree((void **)&tmp_line2); xfree((void **)&responsetemplate); xfree((void **)&tmp_response); if(arg[20] != NULL) xfree((void **)&line); // DEBUG("GOOO3"); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { char *fileName; int fileNameLen; FILE *filePtr; char *line = NULL; int lineBufLength = 4; char *tok; char delims[] = " \t\n\r\f\v"; double *vertices; int vi = 0; int vertBufSize = 3*10000; mxArray *vsArray; double *faces; int fi = 0; int faceBufSize = 3*10000; mxArray *trisArray; if (!mxIsChar(prhs[0])) mexErrMsgTxt("The first argument must be a character array."); fileNameLen = mxGetM(prhs[0])*mxGetN(prhs[0]) + 1; fileName = mxMalloc(fileNameLen*sizeof(char)); mxGetString(prhs[0], fileName, fileNameLen); filePtr = fopen(fileName, "r"); mxFree(fileName); if (filePtr == NULL) { mexErrMsgTxt("Couldn't open input file for reading. Note that " "tilde expansions are not supported."); } if (!readLine(&line, &lineBufLength, filePtr)) mexErrMsgTxt("Empty file."); vertices = mxMalloc(vertBufSize*sizeof(double)); faces = mxMalloc(faceBufSize*sizeof(double)); do { int i; if ((tok = strtok(line, delims)) == NULL) continue; if (!strcmp(tok, "v")) { if (vi >= vertBufSize - 3) { vertBufSize += vertBufSize; vertices = mxRealloc(vertices, vertBufSize*sizeof(double)); } for (i = 0; i < 3; ++i) { tok = strtok(NULL, delims); vertices[vi++] = atof(tok); } } else if (!strcmp(tok, "f")) { if (fi >= faceBufSize - 6) { faceBufSize += faceBufSize; faces = mxRealloc(faces, faceBufSize*sizeof(double)); } // Read in a triangle for (i = 0; i < 3; ++i) { tok = strtok(NULL, delims); faces[fi++] = atof(tok); } // Check if it was actually a quad, and if so add another triangle if ((tok = strtok(NULL, delims)) != NULL) { faces[fi] = faces[fi - 3]; faces[fi + 1] = faces[fi - 1]; faces[fi + 2] = atof(tok); fi += 3; } } } while (readLine(&line, &lineBufLength, filePtr)); fclose(filePtr); mxFree(line); vsArray = mxCreateDoubleMatrix(3, vi/3, mxREAL); trisArray = mxCreateDoubleMatrix(3, fi/3, mxREAL); mxFree(mxGetPr(vsArray)); mxFree(mxGetPr(trisArray)); mxSetPr(vsArray, vertices); mxSetPr(trisArray, faces); mexCallMATLAB(1, plhs, 1, &vsArray, "transpose"); mexCallMATLAB(1, plhs + 1, 1, &trisArray, "transpose"); }
std::vector<std::string>* getNext() { assert(hasNext()); splitLine(); readLine(); return _cells.get(); }
ssize_t Socket::readData(void *Target, size_t Size, char Separator, timeout_t timeout) { if ((Separator == 0x0D) || (Separator == 0x0A)) return (readLine ((char *) Target, Size, timeout)); if (Size < 1) return (0); ssize_t nstat; if (Separator == 0) { // Flat-out read for a number of bytes. if (timeout) { if (!isPending (pendingInput, timeout)) { error(errTimeout); return (-1); } } nstat =::recv (so, (char *)Target, _IOLEN64 Size, 0); if (nstat < 0) { error (errInput); return (-1); } return (nstat); } ///////////////////////////////////////////////////////////// // Otherwise, we have a special char separator to use ///////////////////////////////////////////////////////////// bool found = false; size_t nleft = Size; int c; char *str = (char *) Target; memset (str, 0, Size); while (nleft && !found) { if (timeout) { if (!isPending (pendingInput, timeout)) { error(errTimeout); return (-1); } } nstat =::recv (so, str, _IOLEN64 nleft, MSG_PEEK); if (nstat <= 0) { error (errInput); return (-1); } for (c = 0; (c < nstat) && !found; ++c) { if (str[c] == Separator) found = true; } memset (str, 0, nleft); nstat =::recv (so, str, c, 0); if (nstat < 0) break; str += nstat; nleft -= nstat; } return (ssize_t)(Size - (ssize_t) nleft); }
/* Process a specific test case. File name is provided. * Needs to return 0 if all is OK, something else otherwise. */ int processTestFile(int fd, char *pszFileName) { FILE *fp; char *testdata = NULL; char *expected = NULL; int ret = 0; size_t lenLn; char buf[4096]; if((fp = fopen((char*)pszFileName, "r")) == NULL) { perror((char*)pszFileName); return(2); } /* skip comments at start of file */ while(!feof(fp)) { getline(&testdata, &lenLn, fp); while(!feof(fp)) { if(*testdata == '#') getline(&testdata, &lenLn, fp); else break; /* first non-comment */ } /* this is not perfect, but works ;) */ if(feof(fp)) break; ++iTests; /* increment test count, we now do one! */ testdata[strlen(testdata)-1] = '\0'; /* remove \n */ /* now we have the test data to send (we could use function pointers here...) */ unescapeTestdata(testdata); if(inputMode == inputUDP) { if(udpSend(testdata, strlen(testdata)) != 0) return(2); } else { if(tcpSend(testdata, strlen(testdata)) != 0) return(2); } /* next line is expected output * we do not care about EOF here, this will lead to a failure and thus * draw enough attention. -- rgerhards, 2009-03-31 */ getline(&expected, &lenLn, fp); expected[strlen(expected)-1] = '\0'; /* remove \n */ /* pull response from server and then check if it meets our expectation */ readLine(fd, buf); if(strcmp(expected, buf)) { ++iFailed; printf("\nExpected Response:\n'%s'\nActual Response:\n'%s'\n", expected, buf); ret = 1; } /* we need to free buffers, as we have potentially modified them! */ free(testdata); testdata = NULL; free(expected); expected = NULL; } free(expected); fclose(fp); return(ret); }
/* Run the test suite. This must be called with exactly one parameter, the * name of the test suite. For details, see file header comment at the top * of this file. * rgerhards, 2009-04-03 */ int main(int argc, char *argv[]) { int fd; int opt; int ret = 0; FILE *fp; char buf[4096]; char testcases[4096]; while((opt = getopt(argc, argv, "dc:i:p:t:v")) != EOF) { switch((char)opt) { case 'c': pszCustomConf = optarg; break; case 'd': useDebugEnv = 1; break; case 'i': if(!strcmp(optarg, "udp")) inputMode = inputUDP; else if(!strcmp(optarg, "tcp")) inputMode = inputTCP; else { printf("error: unsupported input mode '%s'\n", optarg); exit(1); } break; case 'p': iPort = atoi(optarg); break; case 't': testSuite = optarg; break; case 'v': verbose = 1; break; default:printf("Invalid call of nettester, invalid option '%c'.\n", opt); printf("Usage: nettester -d -ttestsuite-name -iudp|tcp [-pport] [-ccustomConfFile] \n"); exit(1); } } if(testSuite == NULL) { printf("error: no testsuite given, need to specify -t testsuite!\n"); exit(1); } atexit(doAtExit); if((srcdir = getenv("srcdir")) == NULL) srcdir = "."; if(verbose) printf("Start of nettester run ($srcdir=%s, testsuite=%s, input=%s/%d)\n", srcdir, testSuite, inputMode2Str(inputMode), iPort); /* create input config file */ if((fp = fopen(NETTEST_INPUT_CONF_FILE, "w")) == NULL) { perror(NETTEST_INPUT_CONF_FILE); printf("error opening input configuration file\n"); exit(1); } if(inputMode == inputUDP) { fputs("$ModLoad ../plugins/imudp/.libs/imudp\n", fp); fprintf(fp, "$UDPServerRun %d\n", iPort); } else { fputs("$ModLoad ../plugins/imtcp/.libs/imtcp\n", fp); fprintf(fp, "$InputTCPServerRun %d\n", iPort); } fclose(fp); /* start to be tested rsyslogd */ openPipe(testSuite, &rsyslogdPid, &fd); readLine(fd, buf); /* generate filename */ sprintf(testcases, "%s/testsuites/*.%s", srcdir, testSuite); if(doTests(fd, testcases) != 0) ret = 1; if(verbose) printf("End of nettester run (%d).\n", ret); exit(ret); }
void AndroidRetracer::run() { m_androidUtils.reloadAdb(); QString errorStr; bool setupRet; QMetaObject::invokeMethod(this, "setup", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, setupRet), Q_ARG(QString *, &errorStr)); if (!setupRet) { emit finished(errorStr); return; } if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("am") << _("start") << _("-n") << packageName + activityName)) { emit finished(tr("Can't start apitrace application")); return; } QByteArray which; if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("readlink") << _("$(which ps)") , &which)) { emit finished(tr("Can't start adb")); return; } bool isBusyBox = which.startsWith("busybox"); QStringList psArgs; psArgs << _("shell") << _("ps"); if (isBusyBox) psArgs << _("-w"); qint64 processPID; bool wasStarted = false; QTime startTime; startTime.start(); QTcpSocket stdoutSocket; QTcpSocket stderrSocket; ImageHash thumbnails; QVariantMap parsedJson; trace::Profile* profile = isProfiling() ? new trace::Profile() : NULL; QList<ApiTraceError> errors; QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$"); QString msg = QLatin1String("Replay finished!"); QByteArray ubjsonBuffer; QByteArray outputBuffer; bool keepGoing = true; while(keepGoing) { if (!wasStarted || startTime.elapsed() > 1000) { QByteArray psOut; m_androidUtils.runAdb(psArgs, &psOut); processPID = extractPid(psOut); if (wasStarted) startTime.restart(); } if (processPID == -1) { if (wasStarted) { break; } else { if (startTime.elapsed() > 3000) { // wait 3 seconds to start emit finished(tr("Unable to start retrace on device.")); return; } } msleep(100); continue; } // we have a valid pid, it means the application started if (!wasStarted) { // connect the sockets int tries = 0; do { stdoutSocket.connectToHost(QHostAddress::LocalHost, m_stdoutPort); } while (!stdoutSocket.waitForConnected(100) && ++tries < 10); if (stdoutSocket.state() != QAbstractSocket::ConnectedState) { emit finished(tr("Can't connect to stdout socket.")); return; } // Android doesn't suport GPU and PPD profiling (at leats not on my devices) //setProfiling(false, isProfilingCpu(), false); QString args = (retraceArguments() << m_androdiFileName).join(" ") + _("\n"); stdoutSocket.write(args.toUtf8()); if (!stdoutSocket.waitForBytesWritten()) { emit finished(tr("Can't send params.")); return; } stderrSocket.connectToHost(QHostAddress::LocalHost, m_stderrPort); stderrSocket.waitForConnected(100); if (stderrSocket.state() != QAbstractSocket::ConnectedState) { emit finished(tr("Can't connect to stderr socket.")); return; } wasStarted = true; } // We are going to read both channels at the same time // read stdout channel if (stdoutSocket.waitForReadyRead(100)) { if (captureState()) ubjsonBuffer.append(stdoutSocket.readAll()); else if (captureThumbnails()) { // read one image image::PNMInfo info; QByteArray header; int headerLines = 3; // assume no optional comment line for (int headerLine = 0; headerLine < headerLines; ++headerLine) { QByteArray line = readLine(stdoutSocket); if (line.isEmpty()) { keepGoing = false; break; } header += line; // if header actually contains optional comment line, ... if (headerLine == 1 && line[0] == '#') { ++headerLines; } } const char *headerEnd = image::readPNMHeader(header.constData(), header.size(), info); // if invalid PNM header was encountered, ... if (headerEnd == NULL || info.channelType != image::TYPE_UNORM8) { qDebug() << "error: invalid snapshot stream encountered"; keepGoing = false; break; } unsigned channels = info.channels; unsigned width = info.width; unsigned height = info.height; // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height"; QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888); int rowBytes = channels * width; for (int y = 0; y < height; ++y) { unsigned char *scanLine = snapshot.scanLine(y); if (!read(stdoutSocket, (char *) scanLine, rowBytes)) { keepGoing = false; break; } } QImage thumb = thumbnail(snapshot); thumbnails.insert(info.commentNumber, thumb); } else if (isProfiling()) { QByteArray line = readLine(stdoutSocket); if (line.isEmpty()) { keepGoing = false; break; } line.append('\0'); trace::Profiler::parseLine(line.constData(), profile); } else { outputBuffer.append(stdoutSocket.readAll()); } } // read stderr channel if (stderrSocket.waitForReadyRead(5) && stderrSocket.canReadLine()) { QString line = stderrSocket.readLine(); if (regexp.indexIn(line) != -1) { ApiTraceError error; error.callIndex = regexp.cap(1).toInt(); error.type = regexp.cap(2); error.message = regexp.cap(3); errors.append(error); } else if (!errors.isEmpty()) { // Probably a multiligne message ApiTraceError &previous = errors.last(); if (line.endsWith("\n")) { line.chop(1); } previous.message.append('\n'); previous.message.append(line); } } } if (outputBuffer.size() < 80) msg = outputBuffer; if (captureState()) { QBuffer io(&ubjsonBuffer); io.open(QIODevice::ReadOnly); parsedJson = decodeUBJSONObject(&io).toMap(); ApiTraceState *state = new ApiTraceState(parsedJson); emit foundState(state); } if (captureThumbnails() && !thumbnails.isEmpty()) { emit foundThumbnails(thumbnails); } if (isProfiling() && profile) { emit foundProfile(profile); } if (!errors.isEmpty()) { emit retraceErrors(errors); } emit finished(msg); }
int parseDescription(Spec spec) /*@globals name, lang @*/ /*@modifies name, lang @*/ { rpmParseState nextPart = (rpmParseState) RPMRC_FAIL; /* assume error */ rpmiob iob = NULL; int flag = PART_SUBNAME; Package pkg; int rc, argc; int arg; const char **argv = NULL; poptContext optCon = NULL; spectag t = NULL; { char * se = strchr(spec->line, '#'); if (se) { *se = '\0'; while (--se >= spec->line && strchr(" \t\n\r", *se) != NULL) *se = '\0'; } } if ((rc = poptParseArgvString(spec->line, &argc, &argv))) { rpmlog(RPMLOG_ERR, _("line %d: Error parsing %%description: %s\n"), spec->lineNum, poptStrerror(rc)); goto exit; } name = NULL; lang = RPMBUILD_DEFAULT_LANG; optCon = poptGetContext(NULL, argc, argv, optionsTable, 0); while ((arg = poptGetNextOpt(optCon)) > 0) {;} if (name != NULL) flag = PART_NAME; if (arg < -1) { rpmlog(RPMLOG_ERR, _("line %d: Bad option %s: %s\n"), spec->lineNum, poptBadOption(optCon, POPT_BADOPTION_NOALIAS), spec->line); goto exit; } if (poptPeekArg(optCon)) { if (name == NULL) name = poptGetArg(optCon); if (poptPeekArg(optCon)) { rpmlog(RPMLOG_ERR, _("line %d: Too many names: %s\n"), spec->lineNum, spec->line); goto exit; } } if (lookupPackage(spec, name, flag, &pkg) != RPMRC_OK) { rpmlog(RPMLOG_ERR, _("line %d: Package does not exist: %s\n"), spec->lineNum, spec->line); goto exit; } /* Lose the inheirited %description (if present). */ if (spec->packages->header != pkg->header) { HE_t he = memset(alloca(sizeof(*he)), 0, sizeof(*he)); int xx; he->tag = RPMTAG_DESCRIPTION; xx = headerGet(pkg->header, he, 0); he->p.ptr = _free(he->p.ptr); if (xx && he->t == RPM_STRING_TYPE) xx = headerDel(pkg->header, he, 0); } t = stashSt(spec, pkg->header, RPMTAG_DESCRIPTION, lang); iob = rpmiobNew(0); if ((rc = readLine(spec, STRIP_TRAILINGSPACE | STRIP_COMMENTS)) > 0) { nextPart = PART_NONE; goto exit; } if (rc < 0) { nextPart = (rpmParseState) RPMRC_FAIL; goto exit; } while ((nextPart = isPart(spec)) == PART_NONE) { iob = rpmiobAppend(iob, spec->line, 1); if (t) t->t_nlines++; if ((rc = readLine(spec, STRIP_TRAILINGSPACE | STRIP_COMMENTS)) > 0) { nextPart = PART_NONE; break; } if (rc) { nextPart = (rpmParseState) RPMRC_FAIL; goto exit; } } iob = rpmiobRTrim(iob); if (!(noLang && strcmp(lang, RPMBUILD_DEFAULT_LANG))) { const char * s = rpmiobStr(iob); (void) headerAddI18NString(pkg->header, RPMTAG_DESCRIPTION, s, lang); } exit: iob = rpmiobFree(iob); argv = _free(argv); optCon = poptFreeContext(optCon); return nextPart; }
int main(int argc, char* argv[]) { #ifdef Q_OS_WIN _setmode(1, _O_BINARY); _setmode(2, _O_BINARY); #endif #ifdef Q_WS_X11 FcInit(); WebCore::DumpRenderTree::initializeFonts(); #endif QApplication::setGraphicsSystem("raster"); QApplication::setStyle(new QWindowsStyle); QFont f("Sans Serif"); f.setPointSize(9); f.setWeight(QFont::Normal); f.setStyle(QFont::StyleNormal); QApplication::setFont(f); QApplication app(argc, argv); #ifdef Q_WS_X11 QX11Info::setAppDpiY(0, 96); QX11Info::setAppDpiX(0, 96); #endif #if HAVE(SIGNAL_H) signal(SIGILL, crashHandler); /* 4: illegal instruction (not reset when caught) */ signal(SIGTRAP, crashHandler); /* 5: trace trap (not reset when caught) */ signal(SIGFPE, crashHandler); /* 8: floating point exception */ signal(SIGBUS, crashHandler); /* 10: bus error */ signal(SIGSEGV, crashHandler); /* 11: segmentation violation */ signal(SIGSYS, crashHandler); /* 12: bad argument to system call */ signal(SIGPIPE, crashHandler); /* 13: write on a pipe with no reader */ signal(SIGXCPU, crashHandler); /* 24: exceeded CPU time limit */ signal(SIGXFSZ, crashHandler); /* 25: exceeded file size limit */ #endif QStringList args = app.arguments(); if (args.count() < 2) { qDebug() << "Usage: DumpRenderTree [-v|--pixel-tests] filename [filename2..n]"; qDebug() << "Or folder containing test files: DumpRenderTree [-v|--pixel-tests] dirpath"; exit(0); } // Suppress debug output from Qt if not started with -v if (!args.contains(QLatin1String("-v"))) qInstallMsgHandler(messageHandler); WebCore::DumpRenderTree dumper; if (args.contains(QLatin1String("--pixel-tests"))) dumper.setDumpPixels(true); QWebDatabase::removeAllDatabases(); if (args.contains(QLatin1String("-"))) { QObject::connect(&dumper, SIGNAL(ready()), &dumper, SLOT(readLine()), Qt::QueuedConnection); QTimer::singleShot(0, &dumper, SLOT(readLine())); } else dumper.processArgsLine(args); return app.exec(); #ifdef Q_WS_X11 FcConfigSetCurrent(0); #endif }
char* MWiFi::readDataLn(uint8_t sk) { return readLine(sk); }
int eHttpStream::openUrl(const std::string &url, std::string &newurl) { int port; std::string hostname; std::string uri = url; std::string request; size_t buflen = 1024; char *linebuf = NULL; int result; char proto[100]; int statuscode = 0; char statusmsg[100]; bool playlist = false; bool contenttypeparsed = false; close(); int pathindex = uri.find("/", 7); if (pathindex > 0) { hostname = uri.substr(7, pathindex - 7); uri = uri.substr(pathindex, uri.length() - pathindex); } else { hostname = uri.substr(7, uri.length() - 7); uri = "/"; } int authenticationindex = hostname.find("@"); if (authenticationindex > 0) { authorizationData = base64encode(hostname.substr(0, authenticationindex)); hostname = hostname.substr(authenticationindex + 1); } int customportindex = hostname.find(":"); if (customportindex > 0) { port = atoi(hostname.substr(customportindex + 1, hostname.length() - customportindex - 1).c_str()); hostname = hostname.substr(0, customportindex); } else if (customportindex == 0) { port = atoi(hostname.substr(1, hostname.length() - 1).c_str()); hostname = "localhost"; } else { port = 80; } std::string extra_headers = ""; size_t pos = uri.find('#'); if (pos != std::string::npos) { extra_headers = uri.substr(pos + 1); uri = uri.substr(0, pos); } streamSocket = Connect(hostname.c_str(), port, 10); if (streamSocket < 0) goto error; request = "GET "; request.append(uri).append(" HTTP/1.1\r\n"); request.append("Host: ").append(hostname).append("\r\n"); request.append("User-Agent: ").append("Enigma2").append("\r\n"); if (authorizationData != "") { request.append("Authorization: Basic ").append(authorizationData).append("\r\n"); } pos = 0; while (pos != std::string::npos && !extra_headers.empty()) { std::string name, value; size_t start = pos; size_t len = std::string::npos; pos = extra_headers.find('=', pos); if (pos != std::string::npos) { len = pos - start; pos++; name = extra_headers.substr(start, len); start = pos; len = std::string::npos; pos = extra_headers.find('&', pos); if (pos != std::string::npos) { len = pos - start; pos++; } value = extra_headers.substr(start, len); } if (!name.empty() && !value.empty()) { eDebug("[eHttpStream] setting extra-header '%s:%s'", name.c_str(), value.c_str()); request.append(name).append(": ").append(value).append("\r\n"); } else { eDebug("[eHttpStream] Invalid header format %s", extra_headers.c_str()); break; } } request.append("Accept: */*\r\n"); request.append("Connection: close\r\n"); request.append("\r\n"); writeAll(streamSocket, request.c_str(), request.length()); linebuf = (char*)malloc(buflen); result = readLine(streamSocket, &linebuf, &buflen); if (result <= 0) goto error; result = sscanf(linebuf, "%99s %d %99s", proto, &statuscode, statusmsg); if (result != 3 || (statuscode != 200 && statuscode != 206 && statuscode != 302)) { eDebug("[eHttpStream] %s: wrong http response code: %d", __func__, statuscode); goto error; } while (1) { result = readLine(streamSocket, &linebuf, &buflen); if (!contenttypeparsed) { char contenttype[33]; if (sscanf(linebuf, "Content-Type: %32s", contenttype) == 1) { contenttypeparsed = true; if (!strcasecmp(contenttype, "application/text") || !strcasecmp(contenttype, "audio/x-mpegurl") || !strcasecmp(contenttype, "audio/mpegurl") || !strcasecmp(contenttype, "application/m3u")) { /* assume we'll get a playlist, some text file containing a stream url */ playlist = true; } continue; } } if (playlist && !strncasecmp(linebuf, "http://", 7)) { newurl = linebuf; eDebug("[eHttpStream] %s: playlist entry: %s", __func__, newurl.c_str()); break; } if (((statuscode == 301) || (statuscode == 302) || (statuscode == 303) || (statuscode == 307) || (statuscode == 308)) && strncasecmp(linebuf, "location: ", 10) == 0) { newurl = &linebuf[10]; eDebug("[eHttpStream] %s: redirecting to: %s", __func__, newurl.c_str()); break; } if (((statuscode == 200) || (statuscode == 206)) && !strncasecmp(linebuf, "transfer-encoding: chunked", strlen("transfer-encoding: chunked"))) { isChunked = true; } if (!playlist && result == 0) break; if (result < 0) break; } free(linebuf); return 0; error: eDebug("[eHttpStream] %s failed", __func__); free(linebuf); close(); return -1; }
void scan(void *arguments) { FILE *fp=NULL; int num1=0,num2=0; char **arg = (char **)arguments; char *pathtable=NULL,*pathhammer=NULL,*view=NULL,*template2=NULL,*template3=NULL; char line[2048]; pid_t pid; if(arg[11]!=NULL) threadss=atoi(arg[11]); int old_thread=threadss; int status=-1; int timeout=3; if(arg[8]!=NULL) timeout=atoi(arg[8]); pathtable=xmalloc(sizeof(char)*64); memset(pathtable,0, sizeof(char)*63); strncat(pathtable,"tables/",8); strncat(pathtable,arg[5],16); strncat(pathtable,".txt",5); fp = fopen(arg[1], "r"); if ( !fp ) { DEBUG("error to open Payload list"); exit(1); } num1=FileSize(TEMPLATE2); num2=FileSize(TEMPLATE3); view=xmalloc(sizeof(char)*(num1+num2+42)); memset(view,0,sizeof(char)*(num1+num2+1)); // template2=xmalloc(sizeof(char)*num1+1); template2=readLine(TEMPLATE2); strncat(view,template2,num1+1); strncat(view,"\"sAjaxSource\": \"",23); strncat(view,arg[5],16); strncat(view,".txt\" \n",9); // template3=xmalloc(sizeof(char)*num2+1); template3=readLine(TEMPLATE3); strncat(view,template3,num2); pathhammer=xmalloc(sizeof(char)*64); memset(pathhammer,0,sizeof(char)*63); strncat(pathhammer,"tables/hammer_",15); strncat(pathhammer,arg[5],16); strncat(pathhammer,".html",6); WriteFile(pathhammer,view); WriteFile(pathtable,"{ \"aaData\": [ \n"); puts("start..."); // TODO add my thread pool library while ( fgets(line,2047,fp) != NULL ) { curl_global_cleanup(); pid=fork(); curl_global_init(CURL_GLOBAL_ALL); if(pid==-1) { DEBUG("error in fork()"); exit(1); } if(!pid) { // curl_global_init(CURL_GLOBAL_ALL); threadss--; spider(arguments,line,pathtable); // curl_global_cleanup(); exit(0); } if(threadss<=0) { while(1) { pid=wait(&status); if (errno == ECHILD) { break; } } threadss=old_thread; } } threadss=0; while(1) { pid=wait(&status); if (errno == ECHILD) { break; } } sleep(timeout); WriteFile(pathtable," [\"\",\"\",\"\",\"\",\"\"] \n ] }"); puts(RED); fprintf(stdout,"end scan \n look the file %s\n \n",pathhammer); puts(LAST); memset(pathtable,0,sizeof(char)*strlen(pathtable)-1); xfree((void **)&pathtable); memset(pathhammer,0,sizeof(char)*strlen(pathhammer)-1); xfree((void **)&pathhammer); memset(view,0,sizeof(char)*strlen(view)-1); xfree((void **)&view); xfree((void **)&template2); xfree((void **)&template3); if( fclose(fp) == EOF ) { DEBUG("Error in close()"); exit(1); } fp=NULL; exit(0); }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int32_t VtkStructuredPointsReader:: readFile() { int32_t err = 0; DataContainer::Pointer volDc = getDataContainerArray()->getDataContainer(getVolumeDataContainerName()); AttributeMatrix::Pointer volAm = volDc->getAttributeMatrix(getCellAttributeMatrixName()); DataContainer::Pointer vertDc = getDataContainerArray()->getDataContainer(getVertexDataContainerName()); AttributeMatrix::Pointer vertAm = vertDc->getAttributeMatrix(getVertexAttributeMatrixName()); std::ifstream in(getInputFile().toLatin1().constData(), std::ios_base::in | std::ios_base::binary); if (!in.is_open()) { QString msg = QObject::tr("Error opening output file '%1'").arg(getInputFile()); setErrorCondition(-61003); notifyErrorMessage(getHumanLabel(), msg, getErrorCondition()); return -100; } QByteArray buf(kBufferSize, '\0'); char* buffer = buf.data(); err = readLine(in, buffer, kBufferSize); // Read Line 1 - VTK Version Info err = readLine(in, buffer, kBufferSize); // Read Line 2 - User Comment setComment(QString(buf)); err = readLine(in, buffer, kBufferSize); // Read Line 3 - BINARY or ASCII QString fileType(buf); if (fileType.startsWith("BINARY") == true) { setFileIsBinary(true); } else if (fileType.startsWith("ASCII") == true) { setFileIsBinary(false); } else { QString ss = QObject::tr("The file type of the VTK legacy file could not be determined. It should be 'ASCII' or 'BINARY' and should appear on line 3 of the file"); setErrorCondition(-61004); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return getErrorCondition(); } // Read Line 4 - Type of Dataset err = readLine(in, buffer, kBufferSize); QList<QByteArray> words = buf.split(' '); if (words.size() != 2) { QString ss = QObject::tr("Error reading the type of data set. Was expecting 2 words but got %1").arg(QString(buf)); setErrorCondition(-61005); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return getErrorCondition(); } QString dataset(words.at(1)); dataset = dataset.trimmed(); setDatasetType(dataset); // Should be STRUCTURED_POINTS bool ok = false; err = readLine(in, buffer, kBufferSize); // Read Line 5 which is the Dimension values // But we need the 'extents' which is one less in all directions (unless dim=1) QVector<size_t> dims(3, 0); QList<QByteArray> tokens = buf.split(' '); dims[0] = tokens[1].toInt(&ok, 10); dims[1] = tokens[2].toInt(&ok, 10); dims[2] = tokens[3].toInt(&ok, 10); QVector<size_t> tDims(3, 0); tDims[0] = dims[0]; tDims[1] = dims[1]; tDims[2] = dims[2]; vertAm->setTupleDimensions(tDims); vertDc->getGeometryAs<ImageGeom>()->setDimensions(dims.data()); tDims[0] = dims[0] - 1; tDims[1] = dims[1] - 1; tDims[2] = dims[2] - 1; volAm->setTupleDimensions(tDims); volDc->getGeometryAs<ImageGeom>()->setDimensions(tDims.data()); err = readLine(in, buffer, kBufferSize); // Read Line 7 which is the Scaling values tokens = buf.split(' '); float resolution[3]; resolution[0] = tokens[1].toFloat(&ok); resolution[1] = tokens[2].toFloat(&ok); resolution[2] = tokens[3].toFloat(&ok); volDc->getGeometryAs<ImageGeom>()->setResolution(resolution); vertDc->getGeometryAs<ImageGeom>()->setResolution(resolution); err = readLine(in, buffer, kBufferSize); // Read Line 6 which is the Origin values tokens = buf.split(' '); float origin[3]; origin[0] = tokens[1].toFloat(&ok); origin[1] = tokens[2].toFloat(&ok); origin[2] = tokens[3].toFloat(&ok); volDc->getGeometryAs<ImageGeom>()->setOrigin(origin); vertDc->getGeometryAs<ImageGeom>()->setOrigin(origin); // Read the first key word which should be POINT_DATA or CELL_DATA err = readLine(in, buffer, kBufferSize); // Read Line 6 which is the first type of data we are going to read tokens = buf.split(' '); QString word = QString(tokens[0]); int32_t npts = 0, ncells = 0; int32_t numPts = 0; if ( word.startsWith("CELL_DATA") ) { DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getVolumeDataContainerName()); m_CurrentAttrMat = m->getAttributeMatrix(getCellAttributeMatrixName()); ncells = tokens[1].toInt(&ok); if (m_CurrentAttrMat->getNumTuples() != ncells) { setErrorCondition(-61006); notifyErrorMessage(getHumanLabel(), QString("Number of cells does not match number of tuples in the Attribute Matrix"), getErrorCondition()); return getErrorCondition(); } this->readDataTypeSection(in, ncells, "point_data"); } else if ( word.startsWith("POINT_DATA") ) { DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getVertexDataContainerName()); m_CurrentAttrMat = m->getAttributeMatrix(getVertexAttributeMatrixName()); npts = tokens[1].toInt(&ok); if (m_CurrentAttrMat->getNumTuples() != npts) { setErrorCondition(-61007); notifyErrorMessage(getHumanLabel(), QString("Number of points does not match number of tuples in the Attribute Matrix"), getErrorCondition()); return getErrorCondition(); } this->readDataTypeSection(in, numPts, "cell_data"); } // Close the file since we are done with it. in.close(); return err; }
void processSonicOSRule(char *line, struct nipperConfig *nipper) { // Variables... fpos_t filePosition; struct ciscoCommand command; struct filterListConfig *filterListPointer = 0; struct filterConfig *filterPointer = 0; struct filterConfig *filterSearchPointer = 0; struct filterObjectConfig *servicePointer = 0; struct filterObjectConfig *sourcePointer = 0; struct filterObjectConfig *destinationPointer = 0; int stopReading = false; int initialSetup = false; char sourceNet[32]; // Loop through the rule lines fgetpos(nipper->input, &filePosition); while ((feof(nipper->input) == 0) && (stopReading == false)) { // Debug output if (nipper->debugMode == true) printf("Rules Line: %s\n", line); // Init command = splitLine(line); // If filter does not yet exist... if (filterPointer == 0) { filterPointer = malloc(sizeof(struct filterConfig)); memset(filterPointer, 0, sizeof(struct filterConfig)); filterPointer->enabled = true; filterPointer->log = false; } // Rule Action... if (strncmp(command.part[0], "prefs_ruleAction_", 17) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 17); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 17)) { if (strcasecmp(command.part[1], "allow") == 0) filterPointer->action = filter_action_accept; else if (strcasecmp(command.part[1], "deny") == 0) filterPointer->action = filter_action_reject; else filterPointer->action = filter_action_drop; } else stopReading = true; } // Service ID else if (strncmp(command.part[0], "prefs_ruleSvcID_", 16) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 16); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 16)) { servicePointer = getFilterMember(filterPointer, command.part[1], object_filter_service); servicePointer->type = object_type_object; servicePointer->serviceOp = service_oper_eq; } else stopReading = true; } // Source Ethernet else if (strncmp(command.part[0], "prefs_ruleSrcEnet_", 18) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 18); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 18)) strncpy(sourceNet, command.part[1], sizeof(sourceNet) - 1); else stopReading = true; } // Destination Ethernet else if (strncmp(command.part[0], "prefs_ruleDstEnet_", 18) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 18); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 18)) { filterListPointer = getFilterList(nipper, sourceNet, command.part[1], false); filterListPointer->type = access_std; // If no filters yet... if (filterListPointer->filter == 0) filterListPointer->filter = filterPointer; else { filterSearchPointer = filterListPointer->filter; while (filterSearchPointer->next != 0) filterSearchPointer = filterSearchPointer->next; filterSearchPointer->next = filterPointer; } } else stopReading = true; } // Source Begin else if (strncmp(command.part[0], "prefs_ruleSrcBegin_", 19) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 19); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 19)) sourcePointer = getFilterMember(filterPointer, command.part[1], object_filter_source); else stopReading = true; } // Source End else if (strncmp(command.part[0], "prefs_ruleSrcEnd_", 17) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 17); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 17)) { strncpy(sourcePointer->netMask, command.part[1], sizeof(sourcePointer->netMask) - 1); if (strcmp(sourcePointer->name, "0.0.0.0") == 0) sourcePointer->type = object_type_any; else if (strcmp(sourcePointer->name, sourcePointer->netMask) != 0) sourcePointer->type = object_type_network; else sourcePointer->type = object_type_host; } else stopReading = true; } // Destination Begin else if (strncmp(command.part[0], "prefs_ruleDstBegin_", 19) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 19); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 19)) destinationPointer = getFilterMember(filterPointer, command.part[1], object_filter_destination); else stopReading = true; } // Destination End else if (strncmp(command.part[0], "prefs_ruleDstEnd_", 17) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 17); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 17)) { strncpy(destinationPointer->netMask, command.part[1], sizeof(destinationPointer->netMask) - 1); if (strcmp(destinationPointer->name, "0.0.0.0") == 0) destinationPointer->type = object_type_any; else if (strcmp(destinationPointer->name, destinationPointer->netMask) != 0) destinationPointer->type = object_type_network; else destinationPointer->type = object_type_host; } else stopReading = true; } // Rule Enabled else if (strncmp(command.part[0], "prefs_ruleEnabled_", 18) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 18); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 18)) { if (strcmp(command.part[1], "1") == 0) filterPointer->enabled = true; else filterPointer->enabled = false; } else stopReading = true; } // Fragmentation else if (strncmp(command.part[0], "prefs_ruleAllowFrags_", 21) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 21); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 21)) { if (strcmp(command.part[1], "off") == 0) filterPointer->fragments = false; else filterPointer->fragments = true; } else stopReading = true; } // Comments else if (strncmp(command.part[0], "ruleComment_", 12) == 0) { if (initialSetup == false) { filterPointer->id = atoi(command.part[0] + 12); initialSetup = true; } if (filterPointer->id == atoi(command.part[0] + 12)) strncpy(filterPointer->remark, line + strlen(command.part[0]) + 1, sizeof(filterPointer->remark) -1); else stopReading = true; } else if ((strncmp(command.part[0], "serviceNameInRule_", 18) != 0) || (strncmp(command.part[0], "prefs_rule", 10) == 0)) stopReading = true; if (stopReading == false) { // Get next line fgetpos(nipper->input, &filePosition); readLine(nipper->input, line, nipper->maxSize); } } // Set file position back fsetpos(nipper->input, &filePosition); // If the filter was not added to the list... if ((filterListPointer == 0) && (filterPointer != 0)) { if (sourcePointer != 0) free(sourcePointer); if (destinationPointer != 0) free(destinationPointer); if (servicePointer != 0) free (servicePointer); free(filterPointer); } }
QStringList CSV::parseLine(){ return parseLine(readLine()); }
int main(int argc, char* argv[]) { #ifdef Q_OS_WIN _setmode(1, _O_BINARY); _setmode(2, _O_BINARY); #endif // Suppress debug output from Qt if not started with -v bool suppressQtDebugOutput = true; for (int i = 1; i < argc; ++i) { if (!qstrcmp(argv[i], "-v")) { suppressQtDebugOutput = false; break; } } // Has to be done before QApplication is constructed in case // QApplication itself produces debug output. if (suppressQtDebugOutput) qInstallMsgHandler(messageHandler); WebKit::initializeTestFonts(); QApplication::setGraphicsSystem("raster"); QApplication::setStyle(new QWindowsStyle); QApplication app(argc, argv); app.setQuitOnLastWindowClosed(false); #if HAVE(QT5) QCoreApplication::setAttribute(Qt::AA_Use96Dpi, true); #else #ifdef Q_WS_X11 QX11Info::setAppDpiY(0, 96); QX11Info::setAppDpiX(0, 96); #endif /* * QApplication will initialize the default application font based * on the application DPI at construction time, which might be * different from the DPI we explicitly set using QX11Info above. * See: https://bugreports.qt.nokia.com/browse/QTBUG-21603 * * To ensure that the application font DPI matches the application * DPI, we override the application font using the font we get from * a QWidget, which has already been resolved against the existing * default font, but with the correct paint-device DPI. */ QApplication::setFont(QWidget().font()); #endif WTFInstallReportBacktraceOnCrashHook(); QStringList args = app.arguments(); if (args.count() < (!suppressQtDebugOutput ? 3 : 2)) { printUsage(); exit(1); } // Remove the first arguments, it is application name itself args.removeAt(0); WebCore::DumpRenderTree dumper; int index = args.indexOf(QLatin1String("--stdout")); if (index != -1) { QString fileName = takeOptionValue(args, index); dumper.setRedirectOutputFileName(fileName); if (fileName.isEmpty() || !freopen(qPrintable(fileName), "w", stdout)) { fprintf(stderr, "STDOUT redirection failed."); exit(1); } } index = args.indexOf(QLatin1String("--stderr")); if (index != -1) { QString fileName = takeOptionValue(args, index); dumper.setRedirectErrorFileName(fileName); if (!freopen(qPrintable(fileName), "w", stderr)) { fprintf(stderr, "STDERR redirection failed."); exit(1); } } QWebDatabase::removeAllDatabases(); index = args.indexOf(QLatin1String("--timeout")); if (index != -1) { int timeout = takeOptionValue(args, index).toInt(); dumper.setTimeout(timeout); } index = args.indexOf(QLatin1String("--no-timeout")); if (index != -1) { dumper.setShouldTimeout(false); args.removeAt(index); } index = args.indexOf(QLatin1String("-")); if (index != -1) { args.removeAt(index); // Continue waiting in STDIN for more test case after process one test case QObject::connect(&dumper, SIGNAL(ready()), &dumper, SLOT(readLine()), Qt::QueuedConnection); // Read and only read the first test case, ignore the others if (args.size() > 0) { // Process the argument first dumper.processLine(args[0]); } else QTimer::singleShot(0, &dumper, SLOT(readLine())); } else { // Go into standalone mode // Standalone mode need at least one test case if (args.count() < 1) { printUsage(); exit(1); } dumper.processArgsLine(args); } return app.exec(); }
void TifReader::readLine(char *buffer, int x0, int x1, int shrink) { if (this->m_info.m_bitsPerSample == 16 && this->m_info.m_samplePerPixel >= 3) { std::vector<short> app(4 * (m_info.m_lx)); readLine(&app[0], x0, x1, shrink); TPixel64 *pixin = (TPixel64 *)&app[0]; TPixel32 *pixout = (TPixel32 *)buffer; for (int j = 0; j < x0; j++) { pixout++; pixin++; } for (int i = 0; i < (x1 - x0) + 1; i++) *pixout++ = PixelConverter<TPixel32>::from(*pixin++); return; } assert(shrink > 0); const int pixelSize = 4; int stripRowSize = m_rowLength * pixelSize; if (m_row < m_info.m_y0 || m_row > m_info.m_y1) { memset(buffer, 0, (x1 - x0 + 1) * pixelSize); m_row++; return; } int stripIndex = m_row / m_rowsPerStrip; if (m_stripIndex != stripIndex) { m_stripIndex = stripIndex; if (TIFFIsTiled(m_tiff)) { uint32 tileWidth = 0, tileHeight = 0; TIFFGetField(m_tiff, TIFFTAG_TILEWIDTH, &tileWidth); TIFFGetField(m_tiff, TIFFTAG_TILELENGTH, &tileHeight); assert(tileWidth > 0 && tileHeight > 0); int tileSize = tileWidth * tileHeight; std::unique_ptr<uint32[]> tile(new uint32[tileSize]); int x = 0; int y = tileHeight * m_stripIndex; int lastTy = std::min((int)tileHeight, m_info.m_ly - y); while (x < m_info.m_lx) { int ret = TIFFReadRGBATile(m_tiff, x, y, tile.get()); assert(ret); int tileRowSize = std::min((int)tileWidth, (int)(m_info.m_lx - x)) * pixelSize; for (int ty = 0; ty < lastTy; ++ty) { memcpy( m_stripBuffer + (ty * m_rowLength + x) * pixelSize, (UCHAR *)tile.get() + ty * tileWidth * pixelSize, tileRowSize); } x += tileWidth; } } else { int y = m_rowsPerStrip * m_stripIndex; int ok = TIFFReadRGBAStrip(m_tiff, y, (uint32 *)m_stripBuffer); assert(ok); } } uint16 orient = ORIENTATION_TOPLEFT; TIFFGetField(m_tiff, TIFFTAG_ORIENTATION, &orient); int r = m_rowsPerStrip - 1 - (m_row % m_rowsPerStrip); switch (orient) // Pretty weak check for top/bottom orientation { case ORIENTATION_TOPLEFT: case ORIENTATION_TOPRIGHT: case ORIENTATION_LEFTTOP: case ORIENTATION_RIGHTTOP: // We have to invert the fixed BOTTOM-UP returned by TIFF functions - since this function is // supposed to ignore orientation issues (which are managed outside). // The last tiles row will actually start at the END OF THE IMAGE (not necessarily at // m_rowsPerStrip multiples). So, we must adjust for that. r = std::min(m_rowsPerStrip, m_info.m_ly - m_rowsPerStrip * m_stripIndex) - 1 - (m_row % m_rowsPerStrip); break; case ORIENTATION_BOTRIGHT: case ORIENTATION_BOTLEFT: case ORIENTATION_RIGHTBOT: case ORIENTATION_LEFTBOT: r = m_row % m_rowsPerStrip; break; } TPixel32 *pix = (TPixel32 *)buffer; uint32 *v = (uint32 *)(m_stripBuffer + r * stripRowSize); pix += x0; v += x0; int width = (x1 < x0) ? (m_info.m_lx - 1) / shrink + 1 : (x1 - x0) / shrink + 1; for (int i = 0; i < width; i++) { uint32 c = *v; pix->r = (UCHAR)TIFFGetR(c); pix->g = (UCHAR)TIFFGetG(c); pix->b = (UCHAR)TIFFGetB(c); pix->m = (UCHAR)TIFFGetA(c); v += shrink; pix += shrink; } m_row++; }
void reads::readReads(char *filename) { FILE *readF; char *line; int colNum = 0; int strandPos = 0; int i, pos; bool firstLine = true; readF = mustOpen(filename, "r"); //int chrNo; //chromosome number, without "chr" char *chr; char **cols; //save temp columns int bufsize = 64; while ((line=readLine(readF)) != NULL) { readsCnt ++; if (line[0] == '/' || line[0] == '#') { continue; } if (firstLine) { colNum = bedColNum(line); } cols = new char*[colNum]; for (i=0; i<colNum; i++) cols[i] = new char[bufsize]; chopLine(line, colNum, cols); if (firstLine) { firstLine = false; for (i=3; i<colNum; i++) { if (isStrand(cols[i])) { strandPos = i; break; } } #ifdef DEBUG_R printf("strand is col: %d\n", i); #endif } // deal with the first col in bed file: chromosome chr = cols[0]; int chrInd = -1; map_iter = chrIdxMap.find(chr); if (map_iter == chrIdxMap.end()) // new chromosome { chrInd = chrIdxMap.size(); chrIdxMap[chr] = chrInd; fpos.push_back(vector<int>()); rpos.push_back(vector<int>()); chrName.push_back(chr); #ifdef DEBUG_R printf("%d: %s\n", chrInd, chr); #endif } else chrInd = map_iter->second; if (cols[strandPos][0] == '+') //forward strand, save start point to fpos { fwdReadsCnt ++; pos = atoi(cols[1]); (fpos[chrInd]).push_back(pos); #ifdef DEBUG_R printf("\t%s\t%d\t+\n", chr, pos); #endif } else //reverse strand, save end point to rpos { rvsReadsCnt ++; pos = atoi(cols[2]); (rpos[chrInd]).push_back(pos); #ifdef DEBUG_R printf("\t%s\t%d\t-\n", chr, pos); #endif } for (i=0; i<colNum; i++) delete[] cols[i]; delete[] cols; if (line != NULL) free(line); // print the reading progress if (param.VERBOSE && readsCnt % 1000 == 0) fprintf(stderr, " %d reads done...\r", readsCnt); } totalChr = chrIdxMap.size(); //lambda_bg_f = param.bandwidth * fwdReadsCnt / param.genomeSize; //lambda_bg_r = param.bandwidth * rvsReadsCnt / param.genomeSize; }
/** * @brief Read header of y4m stream and make a compatible video_format_t * @return 1 if successful, <=0 on error */ static int readY4mHeader(const filter_t* intf, video_format_t* fmt, int fd) { char header[256] = { 0 }; if (0 >= readLine(header, sizeof(header)-1, fd)) { msg_Err(intf, "readY4mHeader: failed to read header: errno=%d %s", errno, strerror(errno)); return -1; } if (strncmp(header, "YUV4MPEG2", 9) != 0) { msg_Err(intf, "readY4mHeader: input is not a y4m stream"); return -2; } int width, height, fpsNum, fpsDen, sarNum, sarDen; width = height = fpsNum = sarNum = 0; fpsDen = sarDen = 1; char y4mChroma[32] = { 0 }; char* ptr = header; while (*ptr) { if (*ptr++ == ' ') { char field = *ptr++; switch (field) { case 'W': sscanf(ptr, "%d", &width); break; case 'H': sscanf(ptr, "%d", &height); break; case 'F': sscanf(ptr, "%d:%d", &fpsNum, &fpsDen); break; case 'A': sscanf(ptr, "%d:%d", &sarNum, &sarDen); break; case 'C': sscanf(ptr, "%31s", y4mChroma); break; case 'I': break; } } } vlc_fourcc_t chroma = 0; int i = 0; while (sChromaTable[i].name) { if (0 == strcmp(y4mChroma, sChromaTable[i].name)) { chroma = sChromaTable[i].fourcc; break; } i++; } if (chroma == 0) { msg_Err(intf, "readY4mHeader: unsupported Y4M chroma: %s", y4mChroma); return -3; } // vspipe is giving aspect 0:0, (maybe a bug), assume 1:1 // fixme: keep same as the input sar if (sarNum == 0 || sarDen == 0) { msg_Info(intf, "readY4mHeader: assume sar 1:1"); sarNum = 1; sarDen = 1; } msg_Info(intf, "readY4mHeader: %s", header); msg_Info(intf, "readY4mHeader: w=%d h=%d fps=%d:%d sar=%d:%d chroma=%s", width, height, fpsNum, fpsDen, sarNum, sarDen, y4mChroma); video_format_Setup(fmt, chroma, width, height, width, height, sarNum, sarDen); fmt->i_frame_rate = fpsNum; fmt->i_frame_rate_base = fpsDen; return 1; }
void Font::readTextureGlyphsNew(const char *file) { G_FILE *fis = g_fopen(file, "rt"); if (!fis) throw GiderosException(GStatus(6000, file)); // Error #6000: %s: No such file or directory. std::string line; while (readLine(fis, &line)) { if (startsWith(line, "common")) { if (!getArg(line, "lineHeight", &fontInfo_.height)) goto error; if (!getArg(line, "base", &fontInfo_.ascender)) goto error; fontInfo_.isSetTextColorAvailable = false; int alphaChnl, redChnl, greenChnl, blueChnl; if (getArg(line, "alphaChnl", &alphaChnl) && getArg(line, "redChnl", &redChnl) && getArg(line, "greenChnl", &greenChnl) && getArg(line, "blueChnl", &blueChnl)) { if (alphaChnl == 0 && redChnl == 4 && greenChnl == 4 && blueChnl == 4) { fontInfo_.isSetTextColorAvailable = true; } } } else if (startsWith(line, "char")) { TextureGlyph textureGlyph; if (!getArg(line, "id", &textureGlyph.chr)) goto error; if (!getArg(line, "x", &textureGlyph.x)) goto error; if (!getArg(line, "y", &textureGlyph.y)) goto error; if (!getArg(line, "width", &textureGlyph.width)) goto error; if (!getArg(line, "height", &textureGlyph.height)) goto error; if (!getArg(line, "xoffset", &textureGlyph.left)) goto error; if (!getArg(line, "yoffset", &textureGlyph.top)) goto error; if (!getArg(line, "xadvance", &textureGlyph.advancex)) goto error; textureGlyph.top = fontInfo_.ascender - textureGlyph.top; textureGlyph.advancex <<= 6; fontInfo_.textureGlyphs[textureGlyph.chr] = textureGlyph; } else if (startsWith(line, "kerning")) { wchar32_t first, second; int amount; if (!getArg(line, "first", &first)) goto error; if (!getArg(line, "second", &second)) goto error; if (!getArg(line, "amount", &amount)) goto error; amount <<= 6; fontInfo_.kernings[std::make_pair(first, second)] = amount; } } g_fclose(fis); return; error: g_fclose(fis); throw GiderosException(GStatus(6016, file)); // Error #6016: %s: Error while reading FNT file. }
/**************************************************************************** Desc: Read the ini file and parse its contents ****************************************************************************/ RCODE FTKAPI F_IniFile::read( const char * pszFileName) { RCODE rc = NE_FLM_OK; FLMBOOL bMore = FALSE; FLMBOOL bEOF = FALSE; #define INITIAL_READ_BUF_SIZE 100 FLMUINT uiReadBufSize = 0; FLMUINT uiBytesAvail = 0; FLMUINT uiBytesInLine = 0; char * pszReadBuf = NULL; FLMUINT uiLineNum = 0; IF_FileSystem * pFileSystem = f_getFileSysPtr(); f_assert( m_bReady); f_assert( !m_pFileHdl); // Open the file if (RC_BAD( rc = f_alloc( f_strlen( pszFileName) + 1, &m_pszFileName))) { goto Exit; } f_strcpy( m_pszFileName, pszFileName); // It's not an error if the file doesn't exist. If it does exist, // we'll read in its data. if( RC_BAD( pFileSystem->openFile( pszFileName, FLM_IO_RDONLY, &m_pFileHdl))) { goto Exit; } m_uiFileOffset = 0; // Read in and parse the file uiReadBufSize = INITIAL_READ_BUF_SIZE; if (RC_BAD( rc = f_alloc( uiReadBufSize, &pszReadBuf))) { goto Exit; } // Read in and parse each line in the file... while (!bEOF) { uiLineNum++; uiBytesAvail = uiReadBufSize; if( RC_BAD( rc = readLine( pszReadBuf, &uiBytesAvail, &bMore)) && rc != NE_FLM_IO_END_OF_FILE) { goto Exit; } if (rc == NE_FLM_IO_END_OF_FILE) { bEOF = TRUE; } // While there are more bytes in the line, re-alloc the buffer, and do // another read. uiBytesInLine = uiBytesAvail; while( bMore) { uiBytesAvail = uiReadBufSize; uiReadBufSize *= 2; if (RC_BAD( rc = f_realloc( uiReadBufSize, &pszReadBuf))) { goto Exit; } if (RC_BAD( rc = readLine( pszReadBuf+uiBytesAvail, &uiBytesAvail, &bMore)) && (rc != NE_FLM_IO_END_OF_FILE) ) { goto Exit; } if( rc == NE_FLM_IO_END_OF_FILE) { bEOF = TRUE; } uiBytesInLine += uiBytesAvail; } if ( (RC_OK( rc) || (rc == NE_FLM_IO_END_OF_FILE)) && (uiBytesInLine > 0) ) { // NumBytes will be 0 if the line was blank. No need // to call parseBuffer in this case if (RC_BAD( rc = parseBuffer( pszReadBuf, uiBytesInLine))) { if (rc == NE_FLM_SYNTAX) { rc = NE_FLM_OK; } else { goto Exit; } } } } Exit: // Close the file if( m_pFileHdl) { m_pFileHdl->closeFile(); m_pFileHdl->Release(); m_pFileHdl = NULL; } // Free the buffer if (pszReadBuf) { f_free( &pszReadBuf); } if (rc == NE_FLM_IO_END_OF_FILE) { rc = NE_FLM_OK; } return rc; }
int parseScript(rpmSpec spec, int parsePart) { /* There are a few options to scripts: */ /* <pkg> */ /* -n <pkg> */ /* -p <sh> */ /* -p "<sh> <args>..." */ /* -f <file> */ const char *p; const char **progArgv = NULL; int progArgc; const char *partname = NULL; rpmTagVal reqtag = 0; rpmTagVal tag = 0; rpmsenseFlags tagflags = 0; rpmTagVal progtag = 0; rpmTagVal flagtag = 0; rpmscriptFlags scriptFlags = 0; int flag = PART_SUBNAME; Package pkg; StringBuf sb = NULL; int nextPart; int index; char * reqargs = NULL; int res = PART_ERROR; /* assume failure */ int rc, argc; int arg; const char **argv = NULL; poptContext optCon = NULL; const char *name = NULL; const char *prog = "/bin/sh"; const char *file = NULL; int priority = 1000000; struct poptOption optionsTable[] = { { NULL, 'p', POPT_ARG_STRING, &prog, 'p', NULL, NULL}, { NULL, 'n', POPT_ARG_STRING, &name, 'n', NULL, NULL}, { NULL, 'f', POPT_ARG_STRING, &file, 'f', NULL, NULL}, { NULL, 'e', POPT_BIT_SET, &scriptFlags, RPMSCRIPT_FLAG_EXPAND, NULL, NULL}, { NULL, 'q', POPT_BIT_SET, &scriptFlags, RPMSCRIPT_FLAG_QFORMAT, NULL, NULL}, { NULL, 'c', POPT_BIT_SET, &scriptFlags, RPMSCRIPT_FLAG_CRITICAL, NULL, NULL}, { NULL, 'P', POPT_ARG_INT, &priority, 'P', NULL, NULL}, { 0, 0, 0, 0, 0, NULL, NULL} }; switch (parsePart) { case PART_PRE: tag = RPMTAG_PREIN; tagflags = RPMSENSE_SCRIPT_PRE; progtag = RPMTAG_PREINPROG; flagtag = RPMTAG_PREINFLAGS; partname = "%pre"; break; case PART_POST: tag = RPMTAG_POSTIN; tagflags = RPMSENSE_SCRIPT_POST; progtag = RPMTAG_POSTINPROG; flagtag = RPMTAG_POSTINFLAGS; partname = "%post"; break; case PART_PREUN: tag = RPMTAG_PREUN; tagflags = RPMSENSE_SCRIPT_PREUN; progtag = RPMTAG_PREUNPROG; flagtag = RPMTAG_PREUNFLAGS; partname = "%preun"; break; case PART_POSTUN: tag = RPMTAG_POSTUN; tagflags = RPMSENSE_SCRIPT_POSTUN; progtag = RPMTAG_POSTUNPROG; flagtag = RPMTAG_POSTUNFLAGS; partname = "%postun"; break; case PART_PRETRANS: tag = RPMTAG_PRETRANS; tagflags = RPMSENSE_PRETRANS; progtag = RPMTAG_PRETRANSPROG; flagtag = RPMTAG_PRETRANSFLAGS; partname = "%pretrans"; break; case PART_POSTTRANS: tag = RPMTAG_POSTTRANS; tagflags = RPMSENSE_POSTTRANS; progtag = RPMTAG_POSTTRANSPROG; flagtag = RPMTAG_POSTTRANSFLAGS; partname = "%posttrans"; break; case PART_VERIFYSCRIPT: tag = RPMTAG_VERIFYSCRIPT; tagflags = RPMSENSE_SCRIPT_VERIFY; progtag = RPMTAG_VERIFYSCRIPTPROG; flagtag = RPMTAG_VERIFYSCRIPTFLAGS; partname = "%verifyscript"; break; case PART_TRIGGERPREIN: tag = RPMTAG_TRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_TRIGGERPREIN; progtag = RPMTAG_TRIGGERSCRIPTPROG; flagtag = RPMTAG_TRIGGERSCRIPTFLAGS; partname = "%triggerprein"; break; case PART_TRIGGERIN: tag = RPMTAG_TRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_TRIGGERIN; progtag = RPMTAG_TRIGGERSCRIPTPROG; flagtag = RPMTAG_TRIGGERSCRIPTFLAGS; partname = "%triggerin"; break; case PART_TRIGGERUN: tag = RPMTAG_TRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_TRIGGERUN; progtag = RPMTAG_TRIGGERSCRIPTPROG; flagtag = RPMTAG_TRIGGERSCRIPTFLAGS; partname = "%triggerun"; break; case PART_TRIGGERPOSTUN: tag = RPMTAG_TRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_TRIGGERPOSTUN; progtag = RPMTAG_TRIGGERSCRIPTPROG; flagtag = RPMTAG_TRIGGERSCRIPTFLAGS; partname = "%triggerpostun"; break; case PART_FILETRIGGERIN: tag = RPMTAG_FILETRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_FILETRIGGERIN; progtag = RPMTAG_FILETRIGGERSCRIPTPROG; flagtag = RPMTAG_FILETRIGGERSCRIPTFLAGS; partname = "%filetriggerin"; break; case PART_FILETRIGGERUN: tag = RPMTAG_FILETRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_FILETRIGGERUN; progtag = RPMTAG_FILETRIGGERSCRIPTPROG; flagtag = RPMTAG_FILETRIGGERSCRIPTFLAGS; partname = "%filetriggerun"; break; case PART_FILETRIGGERPOSTUN: tag = RPMTAG_FILETRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_FILETRIGGERPOSTUN; progtag = RPMTAG_FILETRIGGERSCRIPTPROG; flagtag = RPMTAG_FILETRIGGERSCRIPTFLAGS; partname = "%filetriggerpostun"; break; case PART_TRANSFILETRIGGERIN: tag = RPMTAG_TRANSFILETRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_TRANSFILETRIGGERIN; progtag = RPMTAG_TRANSFILETRIGGERSCRIPTPROG; flagtag = RPMTAG_TRANSFILETRIGGERSCRIPTFLAGS; partname = "%transfiletriggerin"; break; case PART_TRANSFILETRIGGERUN: tag = RPMTAG_TRANSFILETRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_TRANSFILETRIGGERUN; progtag = RPMTAG_TRANSFILETRIGGERSCRIPTPROG; flagtag = RPMTAG_TRANSFILETRIGGERSCRIPTFLAGS; partname = "%transfiletriggerun"; break; case PART_TRANSFILETRIGGERPOSTUN: tag = RPMTAG_TRANSFILETRIGGERSCRIPTS; tagflags = 0; reqtag = RPMTAG_TRANSFILETRIGGERPOSTUN; progtag = RPMTAG_TRANSFILETRIGGERSCRIPTPROG; flagtag = RPMTAG_TRANSFILETRIGGERSCRIPTFLAGS; partname = "%transfiletriggerpostun"; break; } if (tag == RPMTAG_TRIGGERSCRIPTS || tag == RPMTAG_FILETRIGGERSCRIPTS || tag == RPMTAG_TRANSFILETRIGGERSCRIPTS) { /* break line into two at the -- separator */ char *sep, *s = spec->line; while ((s = strstr(s, "--")) != NULL) { s += 2; if (risblank(*(s-3)) && risblank(*s)) break; } if (s == NULL) { rpmlog(RPMLOG_ERR, _("line %d: triggers must have --: %s\n"), spec->lineNum, spec->line); goto exit; } sep = s; SKIPSPACE(s); if (*s == '\0') { rpmlog(RPMLOG_ERR, _("line %d: missing trigger condition: %s\n"), spec->lineNum, spec->line); goto exit; } *sep = '\0'; reqargs = xstrdup(s); } if ((rc = poptParseArgvString(spec->line, &argc, &argv))) { rpmlog(RPMLOG_ERR, _("line %d: Error parsing %s: %s\n"), spec->lineNum, partname, poptStrerror(rc)); goto exit; } optCon = poptGetContext(NULL, argc, argv, optionsTable, 0); while ((arg = poptGetNextOpt(optCon)) > 0) { switch (arg) { case 'p': if (prog[0] == '<') { if (prog[strlen(prog)-1] != '>') { rpmlog(RPMLOG_ERR, _("line %d: internal script must end " "with \'>\': %s\n"), spec->lineNum, prog); goto exit; } } else if (prog[0] != '/') { rpmlog(RPMLOG_ERR, _("line %d: script program must begin " "with \'/\': %s\n"), spec->lineNum, prog); goto exit; } break; case 'n': flag = PART_NAME; break; case 'P': if (tag != RPMTAG_TRIGGERSCRIPTS && tag != RPMTAG_FILETRIGGERSCRIPTS && tag != RPMTAG_TRANSFILETRIGGERSCRIPTS) { rpmlog(RPMLOG_ERR, _("line %d: Priorities are allowed only for file " "triggers : %s\n"), spec->lineNum, prog); goto exit; } } } if (arg < -1) { rpmlog(RPMLOG_ERR, _("line %d: Bad option %s: %s\n"), spec->lineNum, poptBadOption(optCon, POPT_BADOPTION_NOALIAS), spec->line); goto exit; } if (poptPeekArg(optCon)) { if (name == NULL) name = poptGetArg(optCon); if (poptPeekArg(optCon)) { rpmlog(RPMLOG_ERR, _("line %d: Too many names: %s\n"), spec->lineNum, spec->line); goto exit; } } if (lookupPackage(spec, name, flag, &pkg)) goto exit; if (tag != RPMTAG_TRIGGERSCRIPTS) { if (headerIsEntry(pkg->header, progtag)) { rpmlog(RPMLOG_ERR, _("line %d: Second %s\n"), spec->lineNum, partname); goto exit; } } if ((rc = poptParseArgvString(prog, &progArgc, &progArgv))) { rpmlog(RPMLOG_ERR, _("line %d: Error parsing %s: %s\n"), spec->lineNum, partname, poptStrerror(rc)); goto exit; } sb = newStringBuf(); if ((rc = readLine(spec, STRIP_NOTHING)) > 0) { nextPart = PART_NONE; } else if (rc < 0) { goto exit; } else { while (! (nextPart = isPart(spec->line))) { appendStringBuf(sb, spec->line); if ((rc = readLine(spec, STRIP_NOTHING)) > 0) { nextPart = PART_NONE; break; } else if (rc < 0) { goto exit; } } } stripTrailingBlanksStringBuf(sb); p = getStringBuf(sb); #ifdef WITH_LUA if (rstreq(progArgv[0], "<lua>")) { rpmlua lua = NULL; /* Global state. */ if (rpmluaCheckScript(lua, p, partname) != RPMRC_OK) { goto exit; } (void) rpmlibNeedsFeature(pkg, "BuiltinLuaScripts", "4.2.2-1"); } else #endif if (progArgv[0][0] == '<') { rpmlog(RPMLOG_ERR, _("line %d: unsupported internal script: %s\n"), spec->lineNum, progArgv[0]); goto exit; } else { (void) addReqProv(pkg, RPMTAG_REQUIRENAME, progArgv[0], NULL, (tagflags | RPMSENSE_INTERP), 0); } if (scriptFlags) { rpmlibNeedsFeature(pkg, "ScriptletExpansion", "4.9.0-1"); } /* Trigger script insertion is always delayed in order to */ /* get the index right. */ if (tag == RPMTAG_TRIGGERSCRIPTS || tag == RPMTAG_FILETRIGGERSCRIPTS || tag == RPMTAG_TRANSFILETRIGGERSCRIPTS) { if (tag != RPMTAG_TRIGGERSCRIPTS && *reqargs != '/') { rpmlog(RPMLOG_ERR, _("line %d: file trigger condition must begin with '/': %s"), spec->lineNum, reqargs); goto exit; } if (progArgc > 1) { rpmlog(RPMLOG_ERR, _("line %d: interpreter arguments not allowed in triggers: %s\n"), spec->lineNum, prog); goto exit; } /* Add file/index/prog triple to the trigger file list */ index = addTriggerIndex(pkg, file, p, progArgv[0], scriptFlags, tag, priority); /* Generate the trigger tags */ if (parseRCPOT(spec, pkg, reqargs, reqtag, index, tagflags, addReqProvPkg, NULL)) goto exit; } else { struct rpmtd_s td; /* * XXX Ancient rpm uses STRING, not STRING_ARRAY type here. Construct * the td manually and preserve legacy compat for now... */ rpmtdReset(&td); td.tag = progtag; td.count = progArgc; if (progArgc == 1) { td.data = (void *) *progArgv; td.type = RPM_STRING_TYPE; } else { (void) rpmlibNeedsFeature(pkg, "ScriptletInterpreterArgs", "4.0.3-1"); td.data = progArgv; td.type = RPM_STRING_ARRAY_TYPE; } headerPut(pkg->header, &td, HEADERPUT_DEFAULT); if (*p != '\0') { headerPutString(pkg->header, tag, p); } if (scriptFlags) { headerPutUint32(pkg->header, flagtag, &scriptFlags, 1); } if (file) { switch (parsePart) { case PART_PRE: pkg->preInFile = xstrdup(file); break; case PART_POST: pkg->postInFile = xstrdup(file); break; case PART_PREUN: pkg->preUnFile = xstrdup(file); break; case PART_POSTUN: pkg->postUnFile = xstrdup(file); break; case PART_PRETRANS: pkg->preTransFile = xstrdup(file); break; case PART_POSTTRANS: pkg->postTransFile = xstrdup(file); break; case PART_VERIFYSCRIPT: pkg->verifyFile = xstrdup(file); break; } } } res = nextPart; exit: free(reqargs); freeStringBuf(sb); free(progArgv); free(argv); poptFreeContext(optCon); return res; }
int main(int argc, char *argv[]) { if (argc != 3) { writeErr("Error: Use ./server directory PORT"); return -1; } strcpy(MY_PATH, argv[1]); SERVER_PORT = atoi(argv[2]); int i, len, rc; int desc_ready, end_server = FALSE; int close_conn; char buffer[BUFFER_SIZE]; fd_set master_set, working_set; int max_sd, new_sd; int listen_sd = init(); if (listen_sd == -1) return -1; println("list"); FD_ZERO(&master_set); FD_SET(STDIN, &master_set); println("listening"); max_sd = listen_sd; FD_SET(listen_sd, &master_set); do { memcpy(&working_set, &master_set, sizeof(master_set)); // println("waiting for listen..."); rc = select(max_sd + 1, &working_set, NULL, NULL, NULL ); if (isRCValid(rc) <= 0) break; desc_ready = rc; for (i = 0; i <= max_sd && desc_ready > 0; ++i) { if (FD_ISSET(i, &working_set)) { desc_ready--; if (i == listen_sd) { print(" Listening socket is readable\n"); //DO_ACCEPT /**********************/ new_sd = accept(listen_sd, NULL, NULL ); if (new_sd < 0) { if (errno != EWOULDBLOCK) { writeErr(" accept() failed"); end_server = TRUE; } break; } print(" New incoming connection: %d\n", new_sd); rc = recv(new_sd, buffer, sizeof(buffer), 0); int q = 0; int flag = 0; for (; q < clientCount; q++) { if (clients[q].fd == -1) { flag = 1; clients[q].fd = new_sd; strcpy(clients[q].name, buffer); clients[q].id = q; println("cli#%d:%s", q, buffer); break; } } if (flag == 0) { q = clientCount; clients[q].fd = new_sd; strcpy(clients[q].name, buffer); clients[q].id = q; println("cli#%d:%s", q, buffer); clientCount++; } len = convertIntToString(q, buffer); rc = send(new_sd, buffer, len + 1, 0); println("It has been sent"); /**********************/ //END DO_ACCEPT FD_SET(new_sd, &master_set); if (new_sd > max_sd) max_sd = new_sd; } else if (i == STDIN) { memset(buffer, 0, BUFFER_SIZE); readLine(buffer); int index = 0; char next[BUFFER_SIZE]; memset(next, 0, BUFFER_SIZE); index = nextToken(buffer, next, index); if (strcmp("kick", next) == 0) { strcpy(buffer, buffer + 9); char tmpInt[BUFFER_SIZE] = ""; index = nextToken(buffer, tmpInt, 0); int q = atoi(tmpInt); int i = clients[q].fd; int j = 0; for (; j < clients[q].fileCount; j++) { char fileName[BUFFER_SIZE] = ""; strcpy(fileName, MY_PATH); strcat(fileName, clients[q].fileNames[j]); unlink(fileName); } resetClient(&clients[q]); close(i); FD_CLR(i, &master_set); if (i == max_sd) { while (FD_ISSET(max_sd, &master_set) == FALSE) max_sd -= 1; } } } else { // print(" Descriptor %d is readable\n", i); close_conn = FALSE; rc = recv(i, buffer, sizeof(buffer), 0); if (rc < 0) writeErr(" recv() failed"); if (rc == 0) { print(" Connection closed\n"); close_conn = TRUE; } len = rc; do_command(buffer, len, getNum(i)); if (close_conn) { int q = 0; int flag = 0; for (; q < clientCount; q++) { if (clients[q].fd == i) { int j = 0; for (; j < clients[q].fileCount; j++) { char fileName[BUFFER_SIZE] = ""; strcpy(fileName, MY_PATH); strcat(fileName, clients[q].fileNames[j]); unlink(fileName); } resetClient(&clients[q]); break; } } close(i); FD_CLR(i, &master_set); if (i == max_sd) { while (FD_ISSET(max_sd, &master_set) == FALSE) max_sd -= 1; } } } } } } while (end_server == FALSE); for (i = 0; i <= max_sd; ++i) { if (FD_ISSET(i, &master_set)) close(i); } }
void BaseAtlas::load (const char *current, const char *end) { if (!current) throw invalid_argument("current cannot be null."); if (!end) throw invalid_argument("end cannot be null."); string value; string tuple[4]; BaseAtlasPage *page; while (current != end) { readLine(current, end, value); trim(value); if (value.length() == 0) { page = 0; } else if (!page) { page = newAtlasPage(value); pages.push_back(page); page->name = value; page->format = static_cast<Format>(indexOf(formatNames, 7, readValue(current, end, value))); readTuple(current, end, value, tuple); page->minFilter = static_cast<TextureFilter>(indexOf(textureFilterNames, 7, tuple[0])); page->magFilter = static_cast<TextureFilter>(indexOf(textureFilterNames, 7, tuple[1])); readValue(current, end, value); if (value == "x") { page->uWrap = repeat; page->vWrap = clampToEdge; } else if (value == "y") { page->uWrap = clampToEdge; page->vWrap = repeat; } else if (value == "xy") { page->uWrap = repeat; page->vWrap = repeat; } } else { BaseAtlasRegion *region = newAtlasRegion(page); regions.push_back(region); region->name = value; region->rotate = readValue(current, end, value) == "true"; readTuple(current, end, value, tuple); region->x = atoi(tuple[0].c_str()); region->y = atoi(tuple[1].c_str()); readTuple(current, end, value, tuple); region->width = atoi(tuple[0].c_str()); region->height = atoi(tuple[1].c_str()); if (readTuple(current, end, value, tuple) == 4) { // split is optional region->splits = new int[4]; region->splits[0] = atoi(tuple[0].c_str()); region->splits[1] = atoi(tuple[1].c_str()); region->splits[2] = atoi(tuple[2].c_str()); region->splits[3] = atoi(tuple[3].c_str()); if (readTuple(current, end, value, tuple) == 4) { // pad is optional, but only present with splits region->pads = new int[4]; region->pads[0] = atoi(tuple[0].c_str()); region->pads[1] = atoi(tuple[1].c_str()); region->pads[2] = atoi(tuple[2].c_str()); region->pads[3] = atoi(tuple[3].c_str()); readTuple(current, end, value, tuple); } } region->originalWidth = atoi(tuple[0].c_str()); region->originalHeight = atoi(tuple[1].c_str()); readTuple(current, end, value, tuple); region->offsetX = atoi(tuple[0].c_str()); region->offsetY = atoi(tuple[1].c_str()); region->index = atoi(readValue(current, end, value).c_str()); } } }
bool Client::getReadNext(char **key, size_t *cbKey, char **data, size_t *cbData, int *_flags, UINT64 *_cas, bool *bError) { *bError = false; if (!readLine()) { *bError = true; return false; } if (m_reader.readBytes(6) == NULL) { // "END\r\n" was recieved m_reader.skip(); return false; } *key = (char *) m_reader.readUntil(cbKey, ' '); if (*key == NULL) { *bError = true; return false; } *(*key + *cbKey) = '\0'; if (m_reader.readBytes(1) == NULL) { *bError = true; return false; } UINT64 flags; UINT64 bytes; if (!m_reader.readNumeric(&flags)) { *bError = true; return false; } *_flags = (int) flags; if (m_reader.readBytes(1) == NULL) { *bError = true; return false; } if (!m_reader.readNumeric(&bytes)) { *bError = true; return false; } if (m_reader.getBytesLeft () > 2) { UINT64 cas; if (m_reader.readBytes(1) == NULL) { *bError = true; return false; } if (!m_reader.readNumeric(&cas)) { *bError = true; return false; } *_cas = cas; } m_reader.skip(); size_t cbExpect = bytes + 2; while (m_reader.getWritePtr() - m_reader.getReadPtr() < cbExpect) { size_t bytesToRead = cbExpect - (m_reader.getWritePtr() - m_reader.getReadPtr()); if (bytesToRead > 65536) { bytesToRead = 65536; } int result = m_sock->recv(m_sock, m_reader.getWritePtr(), bytesToRead); if (result < 1) { *bError = true; disconnect(NULL); return false; } m_reader.push(result); } m_reader.setEndPtr(m_reader.getReadPtr() + bytes + 2); *data = (char *) m_reader.readBytes(bytes); *cbData = bytes; *((*data) + *cbData) = '\0'; m_reader.skip(); return true; }