int do_gzip(const char* strGZ, const char* strInput) { // take an input file (strInput) and turn it into a compressed file (strGZ) // get rid of the input file after FILE* fIn = boinc_fopen(strInput, "rb"); if (!fIn) return 1; //error gzFile fOut = gzopen(strGZ, "wb"); if (!fOut) return 1; //error fseek(fIn, 0, SEEK_SET); // go to the top of the files gzseek(fOut, 0, SEEK_SET); unsigned char buf[1024]; long lRead = 0, lWrite = 0; while (!feof(fIn)) { // read 1KB at a time until end of file memset(buf, 0x00, 1024); lRead = 0; lRead = fread(buf, 1, 1024, fIn); lWrite = gzwrite(fOut, buf, lRead); if (lRead != lWrite) break; } gzclose(fOut); fclose(fIn); if (lRead != lWrite) return 1; //error -- read bytes != written bytes // if we made it here, it compressed OK, can erase strInput and leave boinc_delete_file(strInput); return 0; }
void DC_checkpointMade(const char *filename) { FILE *f; if (!filename) { /* No file name - reset the checkpoint logic */ if (active_ckpt[0]) unlink(active_ckpt); active_ckpt[0] = '\0'; if (last_complete_ckpt) { unlink(last_complete_ckpt); free(last_complete_ckpt); last_complete_ckpt = NULL; } boinc_checkpoint_completed(); return; } if (strcmp(filename, active_ckpt)) { DC_log(LOG_ERR, "DC_checkpointMade: bad checkpoint file %s " "(expected %s)", filename, active_ckpt); boinc_checkpoint_completed(); return; } DC_log(LOG_INFO, "Completed checkpoint %s", filename); /* Remember which was the last completed checkpoint */ f = boinc_fopen(LAST_CKPT_FILE, "w"); if (f) { fprintf(f, "%s", filename); fclose(f); } if (last_complete_ckpt) { unlink(last_complete_ckpt); free(last_complete_ckpt); } last_complete_ckpt = strdup(filename); /* Reset the active checkpoint */ active_ckpt[0] = '\0'; boinc_checkpoint_completed(); if (client_state == STATE_SUSPEND) client_state = STATE_FINISH; }
void printdata(const char* filename, int x, int y, unsigned char* data) { FILE* bmpfile = boinc_fopen(filename,"w"); fprintf(bmpfile,"%i,%i\n",x,y); for(int i=0;i<y;i++) { for(int c=0;c<8;c++) { fprintf(bmpfile,"%d ",data[x*i+c]); } fprintf(bmpfile,"\n"); } fclose(bmpfile); }
static int make_soft_link(const PROJECT* project, const char* link_path, const char* rel_file_path) { FILE *fp = boinc_fopen(link_path, "w"); if (!fp) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't create link file %s", link_path ); return ERR_FOPEN; } fprintf(fp, "<soft_link>%s</soft_link>\n", rel_file_path); fclose(fp); return 0; }
int convert_file(char* in, char* out) { char input_path[1024], output_path[1024]; char buf[256]; boinc_resolve_filename(in, input_path, sizeof(input_path)); FILE* infile = boinc_fopen(input_path, "r"); if (!infile) { fprintf(stderr, "%s Couldn't find input file, resolved name %s.\n", boinc_msg_prefix(buf, sizeof(buf)), input_path ); return -1; } boinc_resolve_filename(out, output_path, sizeof(output_path)); FILE* outfile = boinc_fopen(output_path, "w"); if (!outfile) { fprintf(stderr, "%s Couldn't find output file, resolved name %s.\n", boinc_msg_prefix(buf, sizeof(buf)), output_path ); fclose(infile); return -1; } while (1) { char c = fgetc(infile); if (c == EOF) break; c = toupper(c); fputc(c, outfile); } fclose(infile); fclose(outfile); return 0; }
int make_soft_link(PROJECT* project, char* link_path, char* rel_file_path) { FILE *fp = boinc_fopen(link_path, "w"); if (!fp) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't create link file %s", link_path ); return ERR_FOPEN; } fprintf(fp, "<soft_link>%s</soft_link>\n", rel_file_path); fclose(fp); if (log_flags.slot_debug) { msg_printf(project, MSG_INFO, "[slot] linked %s to %s", rel_file_path, link_path ); } return 0; }
inline int open_input_file() { string resolved_name; int ret_val = boinc_resolve_filename_s("part_input.txt", resolved_name); if (ret_val != 0) return RESOLVE_FILENAME_FAIL; FILE * f = boinc_fopen(resolved_name.c_str(), "rb"); if (f == NULL) return OPEN_INPUT_FILE_FAIL; //get the max_n int ret = fscanf(f, "%d", &max_n); if (ret == NULL) { fclose(f); return READ_N_FROM_INPUT_FAIL; } //get the k_reg ret = fscanf(f, "%d", &k_reg); if (ret == NULL) { fclose(f); return READ_K_FROM_INPUT_FAIL; } //get the m ret = fscanf(f, "%d", &m); if (ret == NULL) { fclose(f); return READ_M_FROM_INPUT_FAIL; } fclose(f); return OK; }
//DJZ there are my crappy functions to try to diagnose file type bool GarliReader::FileIsNexus(const char *name) const{ if (!FileExists(name)) { throw ErrorException("could not open file: %s!", name); } bool nexus = false; FILE *inf; #ifdef BOINC inf = boinc_fopen(name, "r"); #else inf = fopen(name, "r"); #endif char buf[1024]; GetToken(inf, buf, 1024); if(!(_stricmp(buf, "#NEXUS"))) nexus = true; fclose(inf); return nexus; }
bool GarliReader::FileIsFasta(const char *name) const{ if (!FileExists(name)) { throw ErrorException("could not open file: %s!", name); } bool fasta = false; FILE *inf; #ifdef BOINC inf = boinc_fopen(name, "r"); #else inf = fopen(name, "r"); #endif char buf[1024]; GetToken(inf, buf, 1024); if(buf[0] == '>') fasta = true; fclose(inf); return fasta; }
// benchmark a single CPU // int cpu_benchmarks(BENCHMARK_DESC* bdp) { HOST_INFO host_info; int retval; double vax_mips, int_loops=0, int_time=0, fp_time; bdp->error_str[0] = '\0'; host_info.clear_host_info(); retval = whetstone(host_info.p_fpops, fp_time, MIN_CPU_TIME); if (retval) { bdp->error = true; sprintf(bdp->error_str, "FP benchmark ran only %f sec; ignoring", fp_time); return 0; } #ifdef _WIN32 // Windows: do integer benchmark only on CPU zero. // There's a mysterious bug/problem that gives wildly // differing benchmarks on multi-CPU and multi-core machines, // if you use all the CPUs at once. // if (bdp->ordinal == 0) { #endif retval = dhrystone(vax_mips, int_loops, int_time, MIN_CPU_TIME); if (retval) { bdp->error = true; sprintf(bdp->error_str, "Integer benchmark ran only %f sec; ignoring", int_time); return 0; } host_info.p_iops = vax_mips*1e6; host_info.p_membw = 1e9; #ifdef _WIN32 } bdp->host_info = host_info; bdp->int_loops = int_loops; bdp->int_time = int_time; #else FILE* finfo; finfo = boinc_fopen(bdp->filename, "w"); if (!finfo) return ERR_FOPEN; host_info.write_cpu_benchmarks(finfo); fclose(finfo); #endif return 0; }
void CScreensaver::GetDefaultDisplayPeriods(struct ss_periods &periods) { char* default_data_dir_path = NULL; char buf[1024]; FILE* f; MIOFILE mf; periods.GFXDefaultPeriod = GFX_DEFAULT_PERIOD; periods.GFXSciencePeriod = GFX_SCIENCE_PERIOD; periods.GFXChangePeriod = GFX_CHANGE_PERIOD; periods.Show_default_ss_first = false; #ifdef __APPLE__ default_data_dir_path = "/Library/Application Support/BOINC Data"; #else default_data_dir_path = (char*)m_strBOINCDataDirectory.c_str(); #endif strlcpy(buf, default_data_dir_path, sizeof(buf)); strlcat(buf, PATH_SEPARATOR, sizeof(buf)); strlcat(buf, THE_SS_CONFIG_FILE, sizeof(buf)); f = boinc_fopen(buf, "r"); if (!f) return; mf.init_file(f); XML_PARSER xp(&mf); while (!xp.get_tag()) { if (xp.parse_bool("default_ss_first", periods.Show_default_ss_first)) continue; if (xp.parse_double("default_gfx_duration", periods.GFXDefaultPeriod)) continue; if (xp.parse_double("science_gfx_duration", periods.GFXSciencePeriod)) continue; if (xp.parse_double("science_gfx_change_interval", periods.GFXChangePeriod)) continue; } fclose(f); BOINCTRACE( _T("CScreensaver::GetDefaultDisplayPeriods: m_bShow_default_ss_first=%d, m_fGFXDefaultPeriod=%f, m_fGFXSciencePeriod=%f, m_fGFXChangePeriod=%f\n"), (int)periods.Show_default_ss_first, periods.GFXDefaultPeriod, periods.GFXSciencePeriod, periods.GFXChangePeriod ); }
static VOID CALLBACK timer_handler(HWND, UINT, UINT, DWORD) { RECT rt; int width, height; static int size_changed = 0; GetWindowRect(window, &rt); width = rt.right-rt.left; height = rt.bottom-rt.top; if (throttled_app_render(width, height, dtime())) { SwapBuffers(win_dc); if (!fullscreen) { // If user has changed window size, wait until it stops // changing and then write the new dimensions to file // if ((rt.left != rect.left) || (rt.top != rect.top) || (rt.right != rect.right) || (rt.bottom != rect.bottom) ) { if (IsZoomed(window)) return; if ((rt.left < 0) && (rt.right < 0)) return; if ((rt.top < 0) && (rt.bottom < 0)) return; size_changed = 1; rect.left = rt.left; rect.top = rt.top; rect.right = rt.right; rect.bottom = rt.bottom; } else { if (size_changed && (++size_changed > 10)) { size_changed = 0; FILE *f = boinc_fopen("gfx_info", "w"); if (f) { // ToDo: change this to XML fprintf(f, "%d %d %d %d\n", rect.left, rect.top, rect.right, rect.bottom ); fclose(f); } } } // End if (new size != previous size) else } } }
// check for app_config.xml files, and parse them. // Called at startup and on read_cc_config() RPC // void check_app_config() { char path[MAXPATHLEN]; FILE* f; for (unsigned int i=0; i<gstate.projects.size(); i++) { PROJECT* p = gstate.projects[i]; sprintf(path, "%s/%s", p->project_dir(), APP_CONFIG_FILE_NAME); f = boinc_fopen(path, "r"); if (!f) { clear_app_config(p); continue; } msg_printf(p, MSG_INFO, "Found %s", APP_CONFIG_FILE_NAME); int retval = p->app_configs.parse_file(f, p); if (!retval) { p->app_configs.config_app_versions(p, true); } fclose(f); } }
static PyObject *boinc_boinc_fopen(PyObject *self, PyObject *args) { char *name; char *mode; if (!PyArg_ParseTuple(args, "ss", &name, &mode)) return NULL; FILE *fp; PyObject *object; fp = boinc_fopen(name, mode); object = PyFile_FromFile(fp, name, mode, fclose); Py_INCREF(object); return object; }
void GET_CURRENT_VERSION_OP::handle_reply(int http_op_retval) { char buf[256], new_version[256]; if (http_op_retval) { error_num = http_op_retval; return; } gstate.new_version_check_time = gstate.now; FILE* f = boinc_fopen(GET_CURRENT_VERSION_FILENAME, "r"); if (!f) return; while (fgets(buf, 256, f)) { if (match_tag(buf, "<version>")) { if (parse_version(f, new_version)) { show_newer_version_msg(); gstate.newer_version = string(new_version); break; } } } fclose(f); }
int TEXTURE_DESC::load_image_file(const char* filename) { int retval; FILE* f; f = boinc_fopen(filename, "r"); if (!f) goto done; fclose(f); // for now, just try all the image types in turn present = true; retval = CreateTextureJPG(filename); if (!retval) { fprintf(stderr, "Successfully loaded '%s'.\n", filename); return 0; } done: present = false; fprintf(stderr, "Failed to load '%s'.\n", filename); return -1; }
static bool valid_state_file(const char* fname) { char buf[256]; FILE* f = boinc_fopen(fname, "r"); if (!f) return false; if (!fgets(buf, 256, f)) { fclose(f); return false; } if (!match_tag(buf, "<client_state>")) { fclose(f); return false; } while (fgets(buf, 256, f)) { if (match_tag(buf, "</client_state>")) { fclose(f); return true; } } fclose(f); return false; }
char *check_validity( const char *certPath, const char *origFile, unsigned char *signature, char* caPath ) { MD5_CTX md5CTX; int rbytes; unsigned char md5_md[MD5_DIGEST_LENGTH], rbuf[2048]; SSL_load_error_strings(); SSL_library_init(); if (!is_file(origFile)) { return NULL; } FILE* of = boinc_fopen(origFile, "r"); if (!of) return NULL; MD5_Init(&md5CTX); while (0 != (rbytes = (int)fread(rbuf, 1, sizeof(rbuf), of))) { MD5_Update(&md5CTX, rbuf, rbytes); } MD5_Final(md5_md, &md5CTX); fclose(of); DIRREF dir = dir_open(certPath); char file[MAXPATHLEN]; while (!dir_scan(file, dir, sizeof(file))) { char fpath[MAXPATHLEN]; snprintf(fpath, sizeof(fpath), "%s/%s", certPath, file); // TODO : replace '128' if (check_validity_of_cert(fpath, md5_md, signature, 128, caPath)) { dir_close(dir); return strdup(fpath); } } dir_close(dir); return NULL; }
int parse_job_file() { MIOFILE mf; char tag[1024], buf[256], buf2[256]; bool is_tag; boinc_resolve_filename(JOB_FILENAME, buf, 1024); FILE* f = boinc_fopen(buf, "r"); if (!f) { fprintf(stderr, "%s can't open job file %s\n", boinc_msg_prefix(buf2, sizeof(buf2)), buf ); return ERR_FOPEN; } mf.init_file(f); XML_PARSER xp(&mf); if (!xp.parse_start("job_desc")) return ERR_XML_PARSE; while (!xp.get(tag, sizeof(tag), is_tag)) { if (!is_tag) { fprintf(stderr, "%s SCHED_CONFIG::parse(): unexpected text %s\n", boinc_msg_prefix(buf2, sizeof(buf2)), tag ); continue; } if (!strcmp(tag, "/job_desc")) { fclose(f); return 0; } if (!strcmp(tag, "vm")) { vm.parse(xp); } } fclose(f); return ERR_XML_PARSE; }
int seti_analyze (ANALYSIS_STATE& state) { sah_complex* DataIn = state.savedWUData; int NumDataPoints = state.npoints; sah_complex* ChirpedData = NULL; sah_complex* WorkData = NULL; float* PowerSpectrum = NULL; float* tPowerSpectrum; // Transposed power spectra if used. float* AutoCorrelation = NULL; use_transposed_pot= (!notranspose_flag) && ((app_init_data.host_info.m_nbytes != 0) && (app_init_data.host_info.m_nbytes >= (double)(96*1024*1024))); int num_cfft = 0; float chirprate; int last_chirp_ind = - 1 << 20, chirprateind; double progress_diff, progress_in_cfft, cputime0=0; int retval=0; if (swi.analysis_cfg.credit_rate != 0) LOAD_STORE_ADJUSTMENT=swi.analysis_cfg.credit_rate; #ifndef DEBUG int icfft; #endif int NumFfts, ifft, fftlen; int CurrentSub; int FftNum, need_transpose; unsigned long bitfield=swi.analysis_cfg.analysis_fft_lengths; unsigned long FftLen; unsigned long ac_fft_len=swi.analysis_cfg.autocorr_fftlen; #ifdef USE_IPP IppsFFTSpec_C_32fc* FftSpec[MAX_NUM_FFTS]; int BufSize; ippStaticInit(); // initialization of IPP library #elif defined(USE_FFTWF) // plan space for fftw fftwf_plan analysis_plans[MAX_NUM_FFTS]; fftwf_plan autocorr_plan; #else // fields need by the ooura fft logic int * BitRevTab[MAX_NUM_FFTS]; float * CoeffTab[MAX_NUM_FFTS]; #endif // Allocate data array and work area arrays. ChirpedData = state.data; PowerSpectrum = (float*) calloc_a(NumDataPoints, sizeof(float), MEM_ALIGN); if (PowerSpectrum == NULL) SETIERROR(MALLOC_FAILED, "PowerSpectrum == NULL"); if (use_transposed_pot) { tPowerSpectrum = (float*) calloc_a(NumDataPoints, sizeof(float), MEM_ALIGN); if (tPowerSpectrum == NULL) SETIERROR(MALLOC_FAILED, "tPowerSpectrum == NULL"); } else { tPowerSpectrum=PowerSpectrum; } AutoCorrelation = (float*)calloc_a(ac_fft_len, sizeof(float), MEM_ALIGN); if (AutoCorrelation == NULL) SETIERROR(MALLOC_FAILED, "AutoCorrelation == NULL"); // boinc_worker_timer(); FftNum=0; FftLen=1; #ifdef USE_FFTWF double sz; FILE *wisdom; if ((wisdom=boinc_fopen("wisdom.sah","r"))) { char *wiz=(char *)calloc_a(1024,64,MEM_ALIGN); int n=0; while (wiz && n<64*1024 && !feof(wisdom)) { n+=fread(wiz+n,1,80,wisdom); } fftwf_import_wisdom_from_string(wiz); free_a(wiz); fclose(wisdom); } #endif #ifdef BOINC_APP_GRAPHICS if (sah_graphics) strcpy(sah_graphics->status, "Generating FFT Coefficients"); #endif while (bitfield != 0) { if (bitfield & 1) { swi.analysis_fft_lengths[FftNum]=FftLen; #ifdef USE_IPP int order = 0; for (int tmp = FftLen; !(tmp & 1); order++) tmp >>= 1; if (ippsFFTInitAlloc_C_32fc(&FftSpec[FftNum], order, IPP_FFT_NODIV_BY_ANY, ippAlgHintFast)) { SETIERROR (MALLOC_FAILED, "ippsFFTInitAlloc failed"); } #elif !defined(USE_FFTWF) // See docs in fft8g.C for sizing guidelines for BitRevTab and CoeffTab. BitRevTab[FftNum] = (int*) calloc_a(3+(int)sqrt((float)swi.analysis_fft_lengths[FftNum]), sizeof(int), MEM_ALIGN); if (BitRevTab[FftNum] == NULL) SETIERROR(MALLOC_FAILED, "BitRevTab[FftNum] == NULL"); BitRevTab[FftNum][0] = 0; #else WorkData = (sah_complex *)malloc_a(FftLen * sizeof(sah_complex),MEM_ALIGN); sah_complex *scratch=(sah_complex *)malloc_a(FftLen*sizeof(sah_complex),MEM_ALIGN); if ((WorkData == NULL) || (scratch==NULL)) { SETIERROR(MALLOC_FAILED, "WorkData == NULL || scratch == NULL"); } // TODO: Deallocate these at the end of the function analysis_plans[FftNum] = fftwf_plan_dft_1d(FftLen, scratch, WorkData, FFTW_BACKWARD, FFTW_MEASURE|FFTW_PRESERVE_INPUT); #endif FftNum++; #ifdef USE_FFTWF free_a(scratch); free_a(WorkData); #endif /* USE_FFTWF */ } FftLen*=2; bitfield>>=1; }
void worker() { int nchars = 0; int retval; char input_path[512]; char output_path[512]; FILE* outfile; FILE *infile; boinc_resolve_filename(INPUT_FILE, input_path, sizeof(input_path)); #ifdef _WIN32 infile = boinc_fopen(input_path, "rb"); #else infile = boinc_fopen(input_path, "r"); #endif if (!infile) { fprintf(stderr, "Couldn't find input file, resolved name %s.\n", input_path ); exit(-1); } // Dance Dance Revolution dfio_load_file(infile); SBMatrix* matrix = new SBMatrix(); retval = dfio_read_matrix(matrix); if (retval) { fprintf(stderr, "APP: bdance parse input file failed:\n"); fprintf(stderr, "error code %d\n", retval); dfio_cleanup(); exit(1); } dfio_cleanup(); fclose(infile); // Solve dlx_solve(matrix); uxlong solutions = dlx_count_solutions(); delete matrix; // Write results. boinc_resolve_filename(OUTPUT_FILE, output_path, sizeof(output_path)); outfile = boinc_fopen(output_path, "w"); if (!outfile) { fprintf(stderr, "Couldn't find output file, resolved name %s.\n", output_path ); exit(-1); } dfio_new_file(outfile, DFIO_TYPE_RESULT); // if (dfio_get_prop(DFIO_PROP_NO_SOLUTION_DATA)) { dfio_set_prop(DFIO_PROP_RESULTS_NUM, solutions); dfio_write_headers(); // } dfio_cleanup(); fclose(outfile); boinc_finish(0); }
int main(int argc, char **argv) { int retval; double fd; char output_path[512]; //, chkpt_path[512]; //FILE* state; retval = boinc_init(); if (retval) { fprintf(stderr, "boinc_init returned %d\n", retval); exit(retval); } // extract a --device option std::vector<char*> argVec; int cudaDevice = -1; for(int ii = 0; ii < argc; ii++) { if(cudaDevice < 0 && strcmp(argv[ii], "--device") == 0 && ii + 1 < argc) cudaDevice = atoi(argv[++ii]); else argVec.push_back(argv[ii]); } argc = (int)argVec.size(); argv = &argVec[0]; if(cudaDevice < 0) cudaDevice = 0; boinc_begin_critical_section(); // set the cuda device if ( rcuda::SetCudaDevice(cudaDevice) != 0 ) { fprintf(stderr, "Error setting device %u. Temporary exiting for 60 secs\n", cudaDevice); boinc_temporary_exitHack(); } cudaDeviceProp deviceProp; if(cudaGetDeviceProperties(&deviceProp, cudaDevice) == cudaErrorInvalidDevice) { fprintf(stderr, "Error querying device %u. Temporary exiting for 60 secs\n", cudaDevice); boinc_temporary_exitHack(); } #ifdef WIN32 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); #endif int buffCount = 0x2000; int chainSize = 100; if(deviceProp.major == 1) { /* buffCount = deviceProp.multiProcessorCount * 8;// 8 blocks per multiprocessor buffCount *= deviceProp.maxThreadsPerBlock / 64; // (BLOCK_X_SIZE) // buffCount *= 24; if(deviceProp.minor <= 1) buffCount *= 24; // 24 warps per multiprocessor for compute 1.0 and 1.1 else buffCount *= 32; // 32 warps per multiprocessor for compute 1.2 and 1.3 */ buffCount = 0x2000; } else if(deviceProp.major == 2) { chainSize = 200; /* buffCount = deviceProp.multiProcessorCount * 8;// 8 blocks per multiprocessor buffCount *= deviceProp.maxThreadsPerBlock / 64; //(BLOCK_X_SIZE) buffCount *= 32; // 48 warps per multiprocessor for compute 2.x /* if(deviceProp.minor == 1) { buffCount *= 2; } */ buffCount = 0x4000; } if(cudaDevice > 0) { chainSize = 1000; } if(argc < 10) { fprintf(stderr, "Not enough parameters"); return -1; } std::string sHashRoutineName, sCharsetName, sSalt, sCheckPoints; uint32 nRainbowChainCount, nPlainLenMin, nPlainLenMax, nRainbowTableIndex, nRainbowChainLen; uint64 nChainStart; sHashRoutineName = argv[1]; sCharsetName = argv[2]; nPlainLenMin = atoi(argv[3]); nPlainLenMax = atoi(argv[4]); nRainbowTableIndex = atoi(argv[5]); nRainbowChainLen = atoi(argv[6]); nRainbowChainCount = atoi(argv[7]); #ifdef _WIN32 nChainStart = _atoi64(argv[8]); #else nChainStart = atoll(argv[8]); #endif sCheckPoints = argv[9]; std::vector<int> vCPPositions; char *cp = strtok((char *)sCheckPoints.c_str(), ","); while(cp != NULL) { vCPPositions.push_back(atoi(cp)); cp = strtok(NULL, ","); } if(argc == 11) { sSalt = argv[10]; } //std::cout << "Starting ChainGenerator" << std::endl; // Setup CChainWalkContext //std::cout << "ChainGenerator started." << std::endl; if (!CChainWalkContext::SetHashRoutine(sHashRoutineName)) { fprintf(stderr, "hash routine %s not supported\n", sHashRoutineName.c_str()); return 1; } //std::cout << "Hash routine validated" << std::endl; if (!CChainWalkContext::SetPlainCharset(sCharsetName, nPlainLenMin, nPlainLenMax)) { std::cerr << "charset " << sCharsetName << " not supported" << std::endl; return 2; } //std::cout << "Plain charset validated" << std::endl; if (!CChainWalkContext::SetRainbowTableIndex(nRainbowTableIndex)) { std::cerr << "invalid rainbow table index " << nRainbowTableIndex << std::endl; return 3; } //std::cout << "Rainbowtable index validated" << std::endl; if(sHashRoutineName == "mscache")// || sHashRoutineName == "lmchall" || sHashRoutineName == "halflmchall") { // Convert username to unicode const char *szSalt = sSalt.c_str(); int salt_length = strlen(szSalt); unsigned char cur_salt[256]; for (int i=0; i<salt_length; i++) { cur_salt[i*2] = szSalt[i]; cur_salt[i*2+1] = 0x00; } CChainWalkContext::SetSalt(cur_salt, salt_length*2); } else if(sHashRoutineName == "halflmchall") { // The salt is hardcoded into the hash routine // CChainWalkContext::SetSalt((unsigned char*)&salt, 8); } else if(sHashRoutineName == "oracle") { CChainWalkContext::SetSalt((unsigned char *)sSalt.c_str(), sSalt.length()); } //std::cout << "Opening chain file" << std::endl; // Open file boinc_resolve_filename("result", output_path, sizeof(output_path)); fclose(boinc_fopen(output_path, "a")); FILE *outfile = boinc_fopen(output_path, "r+b"); if (outfile == NULL) { std::cerr << "failed to create " << output_path << std::endl; return 4; } // Check existing chains unsigned int nDataLen = (unsigned int)GetFileLen(outfile); // Round to boundary nDataLen = nDataLen / 10 * 10; if (nDataLen == nRainbowChainCount * 10) { std::cerr << "precomputation of this rainbow table already finished" << std::endl; fclose(outfile); return 0; } fseek(outfile, nDataLen, SEEK_SET); //XXX size_t isn't 32/64 clean size_t nReturn; CChainWalkContext cwc; uint64 nIndex[2]; //time_t tStart = time(NULL); // std::cout << "Starting to generate chains" << std::endl; int maxCalcBuffSize = rcuda::GetChainsBufferSize( buffCount ); std::cerr << "maxCalcBuffSize - estimated: " << buffCount << ". Chosen: " << maxCalcBuffSize << std::endl; uint64 *calcBuff = new uint64[2*maxCalcBuffSize]; int ii; CudaCWCExtender ex(&cwc); rcuda::RCudaTask cuTask; ex.Init(); for(int nCurrentCalculatedChains = nDataLen / 10, calcSize; nCurrentCalculatedChains < nRainbowChainCount; ) { fd = (double)nCurrentCalculatedChains / (double)nRainbowChainCount; boinc_fraction_done(fd); cuTask.hash = ex.GetHash(); cuTask.startIdx = nChainStart + nCurrentCalculatedChains; cuTask.idxCount = std::min<int>(nRainbowChainCount - nCurrentCalculatedChains, maxCalcBuffSize); cuTask.dimVec = ex.GetPlainDimVec(); cuTask.dimVecSize = ex.GetPlainDimVecSize()/2; cuTask.charSet = ex.GetCharSet(); cuTask.charSetSize = ex.GetCharSetSize(); cuTask.cpPositions = &vCPPositions[0]; cuTask.cpPosSize = vCPPositions.size(); cuTask.reduceOffset = ex.GetReduceOffset(); cuTask.plainSpaceTotal = ex.GetPlainSpaceTotal(); cuTask.rainbowChainLen = nRainbowChainLen; cuTask.kernChainSize = chainSize; for(ii = 0; ii < cuTask.idxCount; ii++) { calcBuff[2*ii] = cuTask.startIdx + ii; calcBuff[2*ii+1] = 0; } calcSize = rcuda::CalcChainsOnCUDA(&cuTask, calcBuff); BOINC_STATUS boinc_status; boinc_get_status(&boinc_status); if (boinc_status.quit_request || boinc_status.abort_request) { boinc_end_critical_section(); while (1) boinc_sleep(1); } if(calcSize > 0) { nCurrentCalculatedChains += calcSize; for(ii = 0; ii < cuTask.idxCount; ii++) { nIndex[0] = cuTask.startIdx + ii; // nReturn = fwrite(nIndex, 1, 8, outfile); nReturn = fwrite(calcBuff+(2*ii), 1, 8, outfile); nReturn += fwrite(calcBuff+(2*ii+1), 1, 2, outfile); if(nReturn != 10) { std::cerr << "disk write fail" << std::endl; fclose(outfile); return 9; } } } else { std::cerr << "Calculations on CUDA failed!" << std::endl; fclose(outfile); return -1; } } delete [] calcBuff; #ifdef _DEBUG std::cout << "Generation completed" << std::endl; #endif fclose(outfile); boinc_fraction_done(1); boinc_finish(0); }
void CSimpleFrame::OnConnect(CFrameEvent& WXUNUSED(event)) { wxLogTrace(wxT("Function Start/End"), wxT("CSimpleFrame::OnConnect - Function Begin")); CMainDocument* pDoc = wxGetApp().GetDocument(); CWizardAttach* pWizard = NULL; wxString strComputer = wxEmptyString; wxString strName = wxEmptyString; wxString strURL = wxEmptyString; wxString strTeamName = wxEmptyString; std::string strProjectName; std::string strProjectURL; std::string strProjectAuthenticator; std::string strProjectInstitution; std::string strProjectDescription; std::string strProjectKnown; bool bCachedCredentials = false; ACCT_MGR_INFO ami; PROJECT_INIT_STATUS pis; CC_STATUS status; int wasShown = 0; int wasVisible = 0; wxASSERT(pDoc); wxASSERT(wxDynamicCast(pDoc, CMainDocument)); pDoc->ForceCacheUpdate(); pDoc->GetCoreClientStatus(status, true); // If we are connected to the localhost, run a really quick screensaver // test to trigger a firewall popup. pDoc->GetConnectedComputerName(strComputer); if (pDoc->IsComputerNameLocal(strComputer)) { wxGetApp().StartBOINCScreensaverTest(); wxGetApp().StartBOINCDefaultScreensaverTest(); } pDoc->rpc.get_project_init_status(pis); pDoc->rpc.acct_mgr_info(ami); if (detect_simple_account_credentials( strProjectName, strProjectURL, strProjectAuthenticator, strProjectInstitution, strProjectDescription, strProjectKnown ) ){ if (!pDoc->project((char*)strProjectURL.c_str())) { wasShown = IsShown(); Show(); wasVisible = wxGetApp().IsApplicationVisible(); if (!wasVisible) { wxGetApp().ShowApplication(true); } pWizard = new CWizardAttach(this); pWizard->RunSimpleProjectAttach( wxURI::Unescape(strProjectName), wxURI::Unescape(strProjectURL), wxURI::Unescape(strProjectAuthenticator), wxURI::Unescape(strProjectInstitution), wxURI::Unescape(strProjectDescription), wxURI::Unescape(strProjectKnown) ); } } else if (ami.acct_mgr_url.size() && ami.have_credentials) { // Fall through // // There isn't a need to bring up the attach wizard, the account manager will // take care of ataching to projects when it completes the RPCs // } else if (ami.acct_mgr_url.size() && !ami.have_credentials) { wasShown = IsShown(); Show(); wasVisible = wxGetApp().IsApplicationVisible(); if (!wasVisible) { wxGetApp().ShowApplication(true); } pWizard = new CWizardAttach(this); if (pWizard->SyncToAccountManager()) { // _GRIDREPUBLIC, _PROGRESSTHRUPROCESSORS and _CHARITYENGINE // are defined for those branded builds on Windows only #if defined(_GRIDREPUBLIC) || defined(_PROGRESSTHRUPROCESSORS) || defined(_CHARITYENGINE) || defined(__WXMAC__) #ifdef __WXMAC__ // For GridRepublic, Charity Engine or ProgressThruProcessors, // the Mac installer put a branding file in our data directory long iBrandID = 0; // 0 is unbranded (default) BOINC FILE *f = boinc_fopen("/Library/Application Support/BOINC Data/Branding", "r"); if (f) { fscanf(f, "BrandId=%ld\n", &iBrandID); fclose(f); } if ((iBrandID > 0) && (iBrandID < 4)) #endif { // If successful, hide the main window if we showed it if (!wasVisible) { wxGetApp().ShowApplication(false); } #ifndef __WXMAC__ // See comment in CBOINCGUIApp::OnFinishInit() if (!wasShown) { Hide(); } #endif } #endif } } else if ((pis.url.size() || (0 >= pDoc->GetSimpleProjectCount())) && !status.disallow_attach) { Show(); wxGetApp().ShowApplication(true); strURL = wxString(pis.url.c_str(), wxConvUTF8); bCachedCredentials = pis.url.length() && pis.has_account_key; pWizard = new CWizardAttach(this); pWizard->Run(strURL, bCachedCredentials); } if (pWizard) { pWizard->Destroy(); m_pBackgroundPanel->UpdateProjectView(); } wxLogTrace(wxT("Function Start/End"), wxT("CSimpleFrame::OnConnect - Function End")); }
// do an account manager RPC; // if URL is null, detach from current account manager // int ACCT_MGR_OP::do_rpc( std::string _url, std::string name, std::string password_hash, bool _via_gui ) { int retval; unsigned int i; char url[256], password[256], buf[256]; FILE *pwdf; strlcpy(url, _url.c_str(), sizeof(url)); error_num = ERR_IN_PROGRESS; via_gui = _via_gui; if (global_prefs_xml) { free(global_prefs_xml); global_prefs_xml = 0; } // if null URL, detach from current AMS // if (!strlen(url) && strlen(gstate.acct_mgr_info.acct_mgr_url)) { msg_printf(NULL, MSG_INFO, "Removing account manager info"); gstate.acct_mgr_info.clear(); boinc_delete_file(ACCT_MGR_URL_FILENAME); boinc_delete_file(ACCT_MGR_LOGIN_FILENAME); error_num = 0; for (i=0; i<gstate.projects.size(); i++) { PROJECT* p = gstate.projects[i]; p->attached_via_acct_mgr = false; p->ams_resource_share = -1; } return 0; } canonicalize_master_url(url); if (!valid_master_url(url)) { error_num = ERR_INVALID_URL; return 0; } strlcpy(ami.acct_mgr_url, url, sizeof(ami.acct_mgr_url)); strlcpy(ami.acct_mgr_name, "", sizeof(ami.acct_mgr_name)); strlcpy(ami.login_name, name.c_str(), sizeof(ami.login_name)); strlcpy(ami.password_hash, password_hash.c_str(), sizeof(ami.password_hash)); FILE* f = boinc_fopen(ACCT_MGR_REQUEST_FILENAME, "w"); if (!f) return ERR_FOPEN; fprintf(f, "<acct_mgr_request>\n" " <name>%s</name>\n" " <password_hash>%s</password_hash>\n" " <host_cpid>%s</host_cpid>\n" " <domain_name>%s</domain_name>\n" " <client_version>%d.%d.%d</client_version>\n" " <run_mode>%s</run_mode>\n", name.c_str(), password_hash.c_str(), gstate.host_info.host_cpid, gstate.host_info.domain_name, gstate.core_client_version.major, gstate.core_client_version.minor, gstate.core_client_version.release, run_mode_name[gstate.run_mode.get_perm()] ); if (strlen(gstate.acct_mgr_info.previous_host_cpid)) { fprintf(f, " <previous_host_cpid>%s</previous_host_cpid>\n", gstate.acct_mgr_info.previous_host_cpid ); } // If the AMS requested it, send GUI RPC port and password hash. // This is for the "farm" account manager so it // can know where to send GUI RPC requests to // without having to configure each host // if (gstate.acct_mgr_info.send_gui_rpc_info) { if (gstate.cmdline_gui_rpc_port) { fprintf(f," <gui_rpc_port>%d</gui_rpc_port>\n", gstate.cmdline_gui_rpc_port); } else { fprintf(f," <gui_rpc_port>%d</gui_rpc_port>\n", GUI_RPC_PORT); } if (boinc_file_exists(GUI_RPC_PASSWD_FILE)) { strcpy(password, ""); pwdf = fopen(GUI_RPC_PASSWD_FILE, "r"); if (pwdf) { if (fgets(password, 256, pwdf)) { strip_whitespace(password); } fclose(pwdf); } fprintf(f," <gui_rpc_password>%s</gui_rpc_password>\n", password); } } for (i=0; i<gstate.projects.size(); i++) { PROJECT* p = gstate.projects[i]; fprintf(f, " <project>\n" " <url>%s</url>\n" " <project_name>%s</project_name>\n" " <suspended_via_gui>%d</suspended_via_gui>\n" " <account_key>%s</account_key>\n" " <hostid>%d</hostid>\n" "%s" " </project>\n", p->master_url, p->project_name, p->suspended_via_gui, p->authenticator, p->hostid, p->attached_via_acct_mgr?" <attached_via_acct_mgr/>\n":"" ); } if (boinc_file_exists(GLOBAL_PREFS_FILE_NAME)) { FILE* fprefs = fopen(GLOBAL_PREFS_FILE_NAME, "r"); if (fprefs) { copy_stream(fprefs, f); fclose(fprefs); } } if (strlen(gstate.acct_mgr_info.opaque)) { fprintf(f, " <opaque>\n%s\n" " </opaque>\n", gstate.acct_mgr_info.opaque ); } fprintf(f, "</acct_mgr_request>\n"); fclose(f); sprintf(buf, "%srpc.php", url); retval = gstate.gui_http.do_rpc_post( this, buf, ACCT_MGR_REQUEST_FILENAME, ACCT_MGR_REPLY_FILENAME ); if (retval) { error_num = retval; return retval; } msg_printf(NULL, MSG_INFO, "Contacting account manager at %s", url); return 0; }
static void make_benchmark_file(int which) { FILE* f = boinc_fopen(file_names[which], "w"); fclose(f); }
/// Read the mach-o headers to determine the architectures /// supported by executable file. /// Returns 1 if application can run natively on i386 / x86_64 Macs, else returns 0. int ACTIVE_TASK::is_native_i386_app(const char* exec_path) const { FILE *f; int result = 0; headeru myHeader; fat_arch fatHeader; uint32_t n, i, len; uint32_t theMagic; integer_t theType; f = boinc_fopen(exec_path, "rb"); if (!f) { return result; // Should never happen } myHeader.fat.magic = 0; myHeader.fat.nfat_arch = 0; fread(&myHeader, 1, sizeof(fat_header), f); theMagic = myHeader.mach.magic; switch (theMagic) { case MH_CIGAM: case MH_MAGIC: case MH_MAGIC_64: case MH_CIGAM_64: theType = myHeader.mach.cputype; if ((theMagic == MH_CIGAM) || (theMagic == MH_CIGAM_64)) { theType = OSSwapInt32(theType); } if ((theType == CPU_TYPE_I386) || (theType == CPU_TYPE_X86_64)) { result = 1; // Single-architecture i386or x86_64 file } break; case FAT_MAGIC: case FAT_CIGAM: n = myHeader.fat.nfat_arch; if (theMagic == FAT_CIGAM) { n = OSSwapInt32(myHeader.fat.nfat_arch); } // Multiple architecture (fat) file for (i=0; i<n; i++) { len = fread(&fatHeader, 1, sizeof(fat_arch), f); if (len < sizeof(fat_arch)) { break; // Should never happen } theType = fatHeader.cputype; if (theMagic == FAT_CIGAM) { theType = OSSwapInt32(theType); } if ((theType == CPU_TYPE_I386) || (theType == CPU_TYPE_X86_64)) { result = 1; break; } } break; default: break; } fclose (f); return result; }
int main(int argc, char **argv) { int retval; double fd; char output_path[512]; //, chkpt_path[512]; //FILE* state; retval = boinc_init(); if (retval) { fprintf(stderr, "boinc_init returned %d\n", retval); exit(retval); } // get size of input file (used to compute fraction done) // //file_size(input_path, fsize); // See if there's a valid checkpoint file. // If so seek input file and truncate output file // if(argc < 10) { fprintf(stderr, "Not enough parameters"); return -1; } std::string sHashRoutineName, sCharsetName, sSalt, sCheckPoints; uint32 nRainbowChainCount, nPlainLenMin, nPlainLenMax, nRainbowTableIndex, nRainbowChainLen; uint64 nChainStart; sHashRoutineName = argv[1]; sCharsetName = argv[2]; nPlainLenMin = atoi(argv[3]); nPlainLenMax = atoi(argv[4]); nRainbowTableIndex = atoi(argv[5]); nRainbowChainLen = atoi(argv[6]); nRainbowChainCount = atoi(argv[7]); #ifdef _WIN32 nChainStart = _atoi64(argv[8]); #else nChainStart = atoll(argv[8]); #endif sCheckPoints = argv[9]; std::vector<uint32> vCPPositions; char *cp = strtok((char *)sCheckPoints.c_str(), ","); while(cp != NULL) { vCPPositions.push_back(atoi(cp)); cp = strtok(NULL, ","); } if(argc == 11) { sSalt = argv[10]; } //std::cout << "Starting ChainGenerator" << std::endl; // Setup CChainWalkContext //std::cout << "ChainGenerator started." << std::endl; if (!CChainWalkContext::SetHashRoutine(sHashRoutineName)) { fprintf(stderr, "hash routine %s not supported\n", sHashRoutineName.c_str()); return 1; } //std::cout << "Hash routine validated" << std::endl; if (!CChainWalkContext::SetPlainCharset(sCharsetName, nPlainLenMin, nPlainLenMax)) { std::cerr << "charset " << sCharsetName << " not supported" << std::endl; return 2; } //std::cout << "Plain charset validated" << std::endl; if (!CChainWalkContext::SetRainbowTableIndex(nRainbowTableIndex)) { std::cerr << "invalid rainbow table index " << nRainbowTableIndex << std::endl; return 3; } //std::cout << "Rainbowtable index validated" << std::endl; if(sHashRoutineName == "mscache")// || sHashRoutineName == "lmchall" || sHashRoutineName == "halflmchall") { // Convert username to unicode const char *szSalt = sSalt.c_str(); int salt_length = strlen(szSalt); unsigned char cur_salt[256]; for (int i=0; i<salt_length; i++) { cur_salt[i*2] = szSalt[i]; cur_salt[i*2+1] = 0x00; } CChainWalkContext::SetSalt(cur_salt, salt_length*2); } else if(sHashRoutineName == "halflmchall") { // The salt is hardcoded into the hash routine // CChainWalkContext::SetSalt((unsigned char*)&salt, 8); } else if(sHashRoutineName == "oracle") { CChainWalkContext::SetSalt((unsigned char *)sSalt.c_str(), sSalt.length()); } //std::cout << "Opening chain file" << std::endl; // Open file boinc_resolve_filename("result", output_path, sizeof(output_path)); fclose(boinc_fopen(output_path, "a")); FILE *outfile = boinc_fopen(output_path, "r+b"); if (outfile == NULL) { std::cerr << "failed to create " << output_path << std::endl; return 4; } // Check existing chains unsigned int nDataLen = (unsigned int)GetFileLen(outfile); // Round to boundary nDataLen = nDataLen / 10 * 10; if (nDataLen == nRainbowChainCount * 10) { std::cerr << "precomputation of this rainbow table already finished" << std::endl; fclose(outfile); return 0; } nChainStart += (nDataLen / 10); fseek(outfile, nDataLen, SEEK_SET); //XXX size_t isn't 32/64 clean size_t nReturn; CChainWalkContext cwc; uint64 nIndex[2]; //time_t tStart = time(NULL); // std::cout << "Starting to generate chains" << std::endl; for(uint32 nCurrentCalculatedChains = nDataLen / 10; nCurrentCalculatedChains < nRainbowChainCount; nCurrentCalculatedChains++) { uint32 cpcheck = 0; unsigned short checkpoint = 0; fd = (double)nCurrentCalculatedChains / (double)nRainbowChainCount; boinc_fraction_done(fd); cwc.SetIndex(nChainStart++); // use a given index now! nIndex[0] = cwc.GetIndex(); for (uint32 nPos = 0; nPos < nRainbowChainLen - 1; nPos++) { // std::cout << "IndexToPlain()" << std::endl; cwc.IndexToPlain(); // std::cout << "PlainToHash()" << std::endl; cwc.PlainToHash(); // std::cout << "HashToIndex()" << std::endl; cwc.HashToIndex(nPos); if(cpcheck < vCPPositions.size() && nPos == vCPPositions[cpcheck]) { checkpoint |= (1 << cpcheck) & (unsigned short)cwc.GetIndex() << cpcheck; cpcheck++; } } //std::cout << "GetIndex()" << std::endl; nIndex[1] = cwc.GetIndex(); // Write chain to disk if ((nReturn = fwrite(&nIndex[1], 1, 8, outfile)) != 8) { std::cerr << "disk write fail" << std::endl; fclose(outfile); return 9; } if((nReturn = fwrite(&checkpoint, 1, 2, outfile)) != 2) { std::cerr << "disk write fail" << std::endl; fclose(outfile); return 9; } } //std::cout << "Generation completed" << std::endl; fclose(outfile); boinc_fraction_done(1); boinc_finish(0); }
static void make_window(const char* title) { RECT WindowRect = {0,0,0,0}; int width, height; DWORD dwExStyle; DWORD dwStyle; if (fullscreen) { HDC screenDC=GetDC(NULL); WindowRect.left = WindowRect.top = 0; WindowRect.right=GetDeviceCaps(screenDC, HORZRES); WindowRect.bottom=GetDeviceCaps(screenDC, VERTRES); ReleaseDC(NULL, screenDC); dwExStyle=WS_EX_TOPMOST; dwStyle=WS_POPUP; while(ShowCursor(false) >= 0); } else { // Version 5 screensaver logic kills all MODE_WINDOW graphics before starting one // in fullscreen mode, then restarts the ones it killed when screensaver stops. // To be compatible with V5, we remember and restore the MODE_WINDOW dimensions. FILE *f = boinc_fopen("gfx_info", "r"); if (f) { // ToDo: change this to XML parsing fscanf(f, "%d %d %d %d\n", &rect.left, &rect.top, &rect.right, &rect.bottom); fclose(f); } WindowRect = rect; dwExStyle=WS_EX_APPWINDOW|WS_EX_WINDOWEDGE; dwStyle=WS_OVERLAPPEDWINDOW; while(ShowCursor(true) < 0); } char window_title[256]; if (title) { strcpy(window_title, title); } else { APP_INIT_DATA aid; boinc_get_init_data(aid); if (!strlen(aid.app_name)) strcpy(aid.app_name, "BOINC Application"); get_window_title(window_title, 256); } //fprintf(stderr, "Setting window title to '%s'.\n", window_title); hWnd = CreateWindowEx(dwExStyle, BOINC_WINDOW_CLASS_NAME, window_title, dwStyle|WS_CLIPSIBLINGS|WS_CLIPCHILDREN, WindowRect.left, WindowRect.top, WindowRect.right-WindowRect.left,WindowRect.bottom-WindowRect.top, NULL, NULL, hInstance, NULL ); if (!SetForegroundWindow(hWnd)) { fprintf(stderr, "%s ERROR: Unable to set foreground window (0x%x).\n", boinc_msg_prefix(), GetLastError() ); } if (!GetCursorPos(&mousePos)) { fprintf(stderr, "%s ERROR: Unable to get mouse cursor position (0x%x).\n", boinc_msg_prefix(), GetLastError() ); } hDC = GetDC(hWnd); if (!hDC) { fprintf(stderr, "%s ERROR: Couldn't get a device context for the window (0x%x).\n", boinc_msg_prefix(), GetLastError() ); } SetupPixelFormat(hDC); hRC = wglCreateContext(hDC); if (!hRC) { fprintf(stderr, "%s ERROR: Unable to create OpenGL context (0x%x).\n", boinc_msg_prefix(), GetLastError() ); ReleaseDC(hWnd, hDC); return; } if(!wglMakeCurrent(hDC, hRC)) { fprintf(stderr, "%s ERROR: Unable to make OpenGL context current (0x%x).\n", boinc_msg_prefix(), GetLastError() ); ReleaseDC(hWnd, hDC); wglDeleteContext(hRC); return; } // use client area for resize when not fullscreen if (current_graphics_mode != MODE_FULLSCREEN) { GetClientRect(hWnd, &WindowRect); } width = WindowRect.right-WindowRect.left; height = WindowRect.bottom-WindowRect.top; ShowWindow(hWnd, SW_SHOW); SetFocus(hWnd); app_graphics_init(); app_graphics_resize(width, height); window_ready=true; }
int cert_verify_file( CERT_SIGS* signatures, const char* origFile, const char* trustLocation ) { MD5_CTX md5CTX; int rbytes; unsigned char md5_md[MD5_DIGEST_LENGTH], rbuf[2048]; char buf[256]; char fbuf[MAXPATHLEN]; int verified = false; int file_counter = 0; DATA_BLOCK sig_db; BIO *bio; X509 *cert; X509_NAME *subj; if (signatures->signatures.size() == 0) { printf("No signatures available for file ('%s').\n", origFile); fflush(stdout); return false; } SSL_library_init(); if (!is_file(origFile)) return false; FILE* of = boinc_fopen(origFile, "r"); if (!of) return false; MD5_Init(&md5CTX); while (0 != (rbytes = (int)fread(rbuf, 1, sizeof(rbuf), of))) { MD5_Update(&md5CTX, rbuf, rbytes); } MD5_Final(md5_md, &md5CTX); fclose(of); for(unsigned int i=0;i < signatures->signatures.size(); i++) { sig_db.data = (unsigned char*)calloc(128, sizeof(char)); if (sig_db.data == NULL) { printf("Cannot allocate 128 bytes for signature buffer\n"); return false; } sig_db.len=128; sscan_hex_data(signatures->signatures.at(i).signature, sig_db); file_counter = 0; while (1) { snprintf(fbuf, MAXPATHLEN, "%s/%s.%d", trustLocation, signatures->signatures.at(i).hash, file_counter); #ifndef _USING_FCGI_ FILE *f = fopen(fbuf, "r"); #else FCGI_FILE *f = FCGI::fopen(fbuf, "r"); #endif if (f==NULL) break; fclose(f); bio = BIO_new(BIO_s_file()); BIO_read_filename(bio, fbuf); if (NULL == (cert = PEM_read_bio_X509(bio, NULL, 0, NULL))) { BIO_vfree(bio); printf("Cannot read certificate ('%s')\n", fbuf); file_counter++; continue; } fflush(stdout); subj = X509_get_subject_name(cert); X509_NAME_oneline(subj, buf, 256); // ??? //X509_NAME_free(subj); X509_free(cert); BIO_vfree(bio); if (strcmp(buf, signatures->signatures.at(i).subject)) { printf("Subject does not match ('%s' <-> '%s')\n", buf, signatures->signatures.at(i).subject); file_counter++; continue; } verified = check_validity_of_cert(fbuf, md5_md, sig_db.data, 128, trustLocation); if (verified) break; file_counter++; } free(sig_db.data); if (!verified) return false; } return verified; }
void qcnTrickleUp(const char* strTrickle, const int iVariety, const char* strWU) { // probably not thread safe, but within a same proc/thread (i.e. main.cpp) we should not have trickles/triggers sent within a second because BOINC // can't handle them that fast (i.e. writes out a trickle file name with a timestamp to the nearest second, and trickles within a second // write over each other static double dTimeLastTrickle = 0.0; // set time trickle sent so we can pause if necessary #ifdef QCNLIVE return; // no trickles on gui! #else // just a "sanity check" to make sure we haven't sent too many trickles in a row (i.e. > 1 sec) //trickleup::qcnCheckTrickleSleep(); double dCurTime = dtime(); if ((dCurTime - dTimeLastTrickle) < 1.0) { // last trickle sent less than a second ago, which would be bad for boinc, so sleep a bit) boinc_sleep((dCurTime - dTimeLastTrickle) + .10); } char strVariety[32]; memset(strVariety, 0x00, 32); strcpy(strVariety, "trigger"); switch (iVariety) { case TRIGGER_VARIETY_FINALSTATS: strcpy(strVariety, "finalstats"); break; case TRIGGER_VARIETY_QUAKELIST: strcpy(strVariety, "quakelist"); break; case TRIGGER_VARIETY_NORMAL: strcpy(strVariety, "trigger"); break; case TRIGGER_VARIETY_PING: strcpy(strVariety, "ping"); break; case TRIGGER_VARIETY_CONTINUAL: strcpy(strVariety, "continual"); break; } // BOINC adds the appropriate workunit/resultid etc and posts to trickle_up table in MySQL static bool bInHere = false; if (bInHere) return; bInHere = true; // CMC let's print out trickles in standalone mode so I can see something! if (boinc_is_standalone()) { char szTFile[32]; static unsigned long iNum = 0L; iNum++; sprintf(szTFile, "trickle_%09lu_%s.xml", (unsigned long) iNum, strVariety); FILE* fTrickle = boinc_fopen(szTFile, "w"); if (fTrickle) { fwrite(strTrickle, 1, strlen(strTrickle), fTrickle); fclose(fTrickle); } } else { boinc_send_trickle_up((char*) strVariety, (char*) strTrickle); } bInHere = false; #endif dTimeLastTrickle = dtime(); // set time trickle sent so we can pause if necessary }