inline static std::string decode(const std::string& s) { return decode(s.c_str(), s.size()); }
static int decode(FILE *in, FILE *out) { struct hexfile_decoder *hfd = NULL; struct decoder decoder = { .base = 0, .file = out, .eof = 0, .position = 0, }; char buffer[4096]; int ret; size_t nbytes; ret = hexfile_decoder_new(hfd_callback, &decoder, &hfd); if (ret < 0) { fprintf(stderr, "failed to create hexfile decoder\n"); _exit(2); } while ((nbytes = fread(buffer, 1, sizeof(buffer), in)) > 0) { ret = hexfile_decoder_feed(hfd, buffer, nbytes); if (ret < 0) { fprintf(stderr, "failed to decode hexfile\n"); _exit(2); } } ret = hexfile_decoder_close(&hfd); if (ret < 0) { fprintf(stderr, "failed to close hexfile decoder\n"); _exit(2); } if (!decoder.eof) { fprintf(stderr, "no EOF record\n"); _exit(1); } return 0; } struct mapper { unsigned base, start, end; FILE *file; int eof; }; static void map_print(const struct mapper *mapper) { if (mapper->end > mapper->start) fprintf(mapper->file, "0x%08x-0x%08x\n", mapper->start, mapper->end); } static int map_callback(void *ctx, unsigned char type, unsigned offset, unsigned char *data, size_t length) { struct mapper *mapper = (struct mapper*)ctx; (void)data; if (mapper->eof) { errno = EINVAL; return -1; } if (type == 0x00) { /* data record */ unsigned new_position, new_end; new_position = (mapper->base + offset) & ~0xf; new_end = (new_position + length) | 0xf; if (new_position < mapper->start || new_position > mapper->end + 1) { map_print(mapper); mapper->start = new_position; mapper->end = new_end; } else if (new_end > mapper->end) { mapper->end = new_end; } return 0; } else if (type == 0x01) { /* EOF record */ mapper->eof = 1; return 0; } else if (type >= 0x10) { /* switch memory bank */ unsigned new_base = (type - 0x10) * BANK_SIZE; if (mapper->end != new_base) { map_print(mapper); mapper->start = mapper->end = new_base; } mapper->base = new_base; return 0; } else { errno = ENOSYS; return -1; } } static int map(FILE *in, FILE *out) { struct hexfile_decoder *hfd = NULL; struct mapper mapper = { .base = 0, .start = 0, .end = 0, .file = out, .eof = 0, }; char buffer[4096]; int ret; size_t nbytes; ret = hexfile_decoder_new(map_callback, &mapper, &hfd); if (ret < 0) { fprintf(stderr, "failed to create hexfile decoder\n"); _exit(2); } while ((nbytes = fread(buffer, 1, sizeof(buffer), in)) > 0) { ret = hexfile_decoder_feed(hfd, buffer, nbytes); if (ret < 0) { fprintf(stderr, "failed to decode hexfile\n"); _exit(2); } } ret = hexfile_decoder_close(&hfd); if (ret < 0) { fprintf(stderr, "failed to close hexfile decoder\n"); _exit(2); } if (!mapper.eof) { fprintf(stderr, "no EOF record\n"); _exit(1); } return 0; } int main(int argc, char **argv) { struct config config; FILE *in, *out; parse_cmdline(&config, argc, argv); if (config.input_path == NULL) { in = stdin; } else { in = fopen(argv[optind], "r"); if (in == NULL) { fprintf(stderr, "failed to open '%s': %s", argv[optind], strerror(errno)); _exit(1); } } if (config.output_path == NULL) { out = stdout; } else { out = fopen(config.output_path, "w"); if (out == NULL) { fprintf(stderr, "failed to create '%s': %s\n", config.output_path, strerror(errno)); _exit(1); } } /* do it */ if (config.decode) { return decode(in, out); } else if (config.map) { return map(in, out); } else { return encode(in, out); } }
//////////////////////////////////////////////////////////////////////////////// // Attempt an FF4 parse first, using Task::parse, and in the event of an error // try a legacy parse (F3, FF2). Note that FF1 is no longer supported. // // start --> [ --> Att --> ] --> end // ^ | // +-------+ // void Task::parse (const std::string& input) { std::string copy; if (input[input.length () - 1] == '\n') copy = input.substr (0, input.length () - 1); else copy = input; try { clear (); Nibbler n (copy); std::string line; if (n.skip ('[') && n.getUntil (']', line) && n.skip (']') && n.depleted ()) { if (line.length () == 0) throw std::string (STRING_RECORD_EMPTY); Nibbler nl (line); std::string name; std::string value; while (!nl.depleted ()) { if (nl.getUntil (':', name) && nl.skip (':') && nl.getQuoted ('"', value)) { // Experimental legacy value translation of 'recur:m' --> 'recur:mo'. if (name == "recur" && digitsOnly (value.substr (0, value.length () - 1)) && value[value.length () - 1] == 'm') value += 'o'; if (name.substr (0, 11) == "annotation_") ++annotation_count; (*this)[name] = decode (json::decode (value)); } nl.skip (' '); } std::string remainder; nl.getUntilEOS (remainder); if (remainder.length ()) throw std::string (STRING_RECORD_JUNK_AT_EOL); } else throw std::string (STRING_RECORD_NOT_FF4); } catch (const std::string&) { legacyParse (copy); } recalc_urgency = true; }
default_parse_context ctx(&retval); _parse( ctx, std::istreambuf_iterator<char>(is_.rdbuf()), std::istreambuf_iterator<char>(), &error_ ); return std::move(retval); } inline std::istream& operator>>(std::istream& is_, value& x_) { set_last_error(std::string()); std::string err; x_ = decode(is_, err); if (!err.empty()) { set_last_error(err); is_.setstate(std::ios::failbit); } return is_; } } // end of json namespace } // end of reactive namespace
void ofxRemoteUIServer::updateServer(float dt){ timeCounter += dt; broadcastTime += dt; timeSinceLastReply += dt; if(readyToSend){ if (timeCounter > updateInterval){ timeCounter = 0.0f; //vector<string> changes = scanForUpdatedParamsAndSync(); //sends changed params to client //cout << "ofxRemoteUIServer: sent " << ofToString(changes.size()) << " updates to client" << endl; //sendUpdateForParamsInList(changes); } } //let everyone know I exist and which is my port, every now and then if(broadcastTime > OFXREMOTEUI_BORADCAST_INTERVAL){ if(doBroadcast){ broadcastTime = 0.0f; if (computerName.size() == 0){ #ifdef OF_AVAILABLE Poco::Environment e; computerName = e.nodeName(); char pathbuf[2048]; uint32_t bufsize = sizeof(pathbuf); #ifdef TARGET_OSX _NSGetExecutablePath(pathbuf, &bufsize); Poco::Path p = Poco::Path(pathbuf); binaryName = p[p.depth()]; #endif #ifdef TARGET_WIN32 GetModuleFileNameA( NULL, pathbuf, bufsize ); //no iea why, but GetModuleFileName() is not defined? Poco::Path p = Poco::Path(pathbuf); binaryName = p[p.depth()]; #endif #endif } ofxOscMessage m; m.addIntArg(port); //0 m.addStringArg(computerName); //1 m.addStringArg(binaryName); //2 broadcastSender.sendMessage(m); } } while( oscReceiver.hasWaitingMessages() ){// check for waiting messages from client ofxOscMessage m; oscReceiver.getNextMessage(&m); if (!readyToSend){ // if not connected, connect to our friend so we can talk back connect(m.getRemoteIp(), port + 1); } DecodedMessage dm = decode(m); RemoteUIServerCallBackArg cbArg; // to notify our "delegate" cbArg.host = m.getRemoteIp(); switch (dm.action) { case HELO_ACTION: //if client says hi, say hi back sendHELLO(); if(callBack != NULL){ cbArg.action = CLIENT_CONNECTED; callBack(cbArg); } if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " says HELLO!" << endl; onScreenNotifications.addNotification("CONNECTED (" + cbArg.host + ")!"); break; case REQUEST_ACTION:{ //send all params to client if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " sends REQU!" << endl; vector<string>paramsList = getAllParamNamesList(); syncAllParamsToPointers(); sendUpdateForParamsInList(paramsList); sendREQU(true); //once all send, confirm to close the REQU } break; case SEND_PARAM_ACTION:{ //client is sending us an updated val if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " sends SEND!" << endl; updateParamFromDecodedMessage(m, dm); if(callBack != NULL){ cbArg.action = CLIENT_UPDATED_PARAM; cbArg.paramName = dm.paramName; cbArg.param = params[dm.paramName]; //copy the updated param to the callbakc arg callBack(cbArg); } } break; case CIAO_ACTION:{ if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " says CIAO!" << endl; sendCIAO(); onScreenNotifications.addNotification("DISCONNECTED (" + cbArg.host + ")!"); if(callBack != NULL){ cbArg.action = CLIENT_DISCONNECTED; callBack(cbArg); } clearOscReceiverMsgQueue(); readyToSend = false; }break; case TEST_ACTION: // we got a request from client, lets bounce back asap. sendTEST(); //if(verbose)cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " says TEST!" << endl; break; case PRESET_LIST_ACTION: //client wants us to send a list of all available presets presetNames = getAvailablePresets(); if (presetNames.size() == 0){ presetNames.push_back(OFXREMOTEUI_NO_PRESETS); } sendPREL(presetNames); break; case SET_PRESET_ACTION:{ // client wants to set a preset //presetNames = getAvailablePresets(); string presetName = m.getArgAsString(0); vector<string> missingParams = loadFromXML(string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml"); if(verbose_) cout << "ofxRemoteUIServer: setting preset: " << presetName << endl; sendSETP(presetName); sendMISP(missingParams); if(callBack != NULL){ cbArg.action = CLIENT_DID_SET_PRESET; cbArg.msg = presetName; callBack(cbArg); } onScreenNotifications.addNotification("SET PRESET to '" + string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml'"); }break; case SAVE_PRESET_ACTION:{ //client wants to save current xml as a new preset string presetName = m.getArgAsString(0); if(verbose_) cout << "ofxRemoteUIServer: saving NEW preset: " << presetName << endl; saveToXML(string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml"); sendSAVP(presetName); onScreenNotifications.addNotification("SAVED PRESET to '" + string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml'"); if(callBack != NULL){ cbArg.action = CLIENT_SAVED_PRESET; cbArg.msg = presetName; callBack(cbArg); } }break; case DELETE_PRESET_ACTION:{ string presetName = m.getArgAsString(0); if(verbose_) cout << "ofxRemoteUIServer: DELETE preset: " << presetName << endl; deletePreset(presetName); sendDELP(presetName); onScreenNotifications.addNotification("DELETED PRESET '" + string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml'"); if(callBack != NULL){ cbArg.action = CLIENT_DELETED_PRESET; cbArg.msg = presetName; callBack(cbArg); } }break; case SAVE_CURRENT_STATE_ACTION:{ if(verbose_) cout << "ofxRemoteUIServer: SAVE CURRENT PARAMS TO DEFAULT XML: " << endl; saveToXML(OFXREMOTEUI_SETTINGS_FILENAME); onScreenNotifications.addNotification("SAVED CONFIG to default XML"); sendSAVE(true); if(callBack != NULL){ cbArg.action = CLIENT_SAVED_STATE; callBack(cbArg); } }break; case RESET_TO_XML_ACTION:{ if(verbose_) cout << "ofxRemoteUIServer: RESET TO XML: " << endl; restoreAllParamsToInitialXML(); sendRESX(true); onScreenNotifications.addNotification("RESET CONFIG TO SERVER-LAUNCH XML values"); if(callBack != NULL){ cbArg.action = CLIENT_DID_RESET_TO_XML; callBack(cbArg); } }break; case RESET_TO_DEFAULTS_ACTION:{ if(verbose_) cout << "ofxRemoteUIServer: RESET TO DEFAULTS: " << endl; restoreAllParamsToDefaultValues(); sendRESD(true); onScreenNotifications.addNotification("RESET CONFIG TO DEFAULTS (source defined values)"); if(callBack != NULL){ cbArg.action = CLIENT_DID_RESET_TO_DEFAULTS; callBack(cbArg); } }break; default: cout << "ofxRemoteUIServer::update >> ERR!" <<endl; break; } } }
unsigned short checksum() const { return decode(2, 3); }
unsigned short sequence_number() const { return decode(6, 7); }
static inline decode_t fetch_decode(cpu_t *pcpu) { return decode(fetch_checked(pcpu), pcpu); }
type_id value::type() const { return decode().type(); }
int main(int argc, char *argv[]) { int i, j; char err[256]; size_t err_len = sizeof(err); int chunkSize = 1024; int numDataUnits = 6; int numParityUnits = 3; unsigned char** dataUnits; unsigned char** parityUnits; IsalEncoder* pEncoder; int erasedIndexes[2]; unsigned char* allUnits[MMAX]; IsalDecoder* pDecoder; unsigned char* decodingOutput[2]; unsigned char** backupUnits; if (0 == build_support_erasurecode()) { printf("The native library isn't available, skipping this test\n"); return 0; // Normal, not an error } load_erasurecode_lib(err, err_len); if (strlen(err) > 0) { printf("Loading erasurecode library failed: %s\n", err); return -1; } printf("Performing erasure code test\n"); dataUnits = calloc(numDataUnits, sizeof(unsigned char*)); parityUnits = calloc(numParityUnits, sizeof(unsigned char*)); backupUnits = calloc(numParityUnits, sizeof(unsigned char*)); // Allocate and generate data units srand(135); for (i = 0; i < numDataUnits; i++) { dataUnits[i] = calloc(chunkSize, sizeof(unsigned char)); for (j = 0; j < chunkSize; j++) { dataUnits[i][j] = rand(); } } // Allocate and initialize parity units for (i = 0; i < numParityUnits; i++) { parityUnits[i] = calloc(chunkSize, sizeof(unsigned char)); for (j = 0; j < chunkSize; j++) { parityUnits[i][j] = 0; } } pEncoder = (IsalEncoder*)malloc(sizeof(IsalEncoder)); memset(pEncoder, 0, sizeof(*pEncoder)); initEncoder(pEncoder, numDataUnits, numParityUnits); encode(pEncoder, dataUnits, parityUnits, chunkSize); pDecoder = (IsalDecoder*)malloc(sizeof(IsalDecoder)); memset(pDecoder, 0, sizeof(*pDecoder)); initDecoder(pDecoder, numDataUnits, numParityUnits); memcpy(allUnits, dataUnits, numDataUnits * (sizeof (unsigned char*))); memcpy(allUnits + numDataUnits, parityUnits, numParityUnits * (sizeof (unsigned char*))); erasedIndexes[0] = 1; erasedIndexes[1] = 7; backupUnits[0] = allUnits[1]; backupUnits[1] = allUnits[7]; allUnits[0] = NULL; // Not to read allUnits[1] = NULL; allUnits[7] = NULL; decodingOutput[0] = malloc(chunkSize); decodingOutput[1] = malloc(chunkSize); decode(pDecoder, allUnits, erasedIndexes, 2, decodingOutput, chunkSize); for (i = 0; i < pDecoder->numErased; i++) { if (0 != memcmp(decodingOutput[i], backupUnits[i], chunkSize)) { fprintf(stderr, "Decoding failed\n\n"); dumpDecoder(pDecoder); return -1; } } dumpDecoder(pDecoder); fprintf(stdout, "Successfully done, passed!\n\n"); return 0; }
int RsDecode::decode(BYTE * data, int length) { return decode(data, length, false); }
Ref<Result> ByQuadrantReader::decode(Ref<BinaryBitmap> image){ return decode(image, DecodeHints::DEFAULT_HINT); }
void TestLSB() { encode(); decode(); }
int cbc_mct(char *filename, FILE *file) { char line[1024], name[64], value[1024]; uint8_t KEY[256], IV[AES_BLOCK_LEN]; uint8_t CT[AES_BLOCK_LEN], PT[AES_BLOCK_LEN]; uint8_t block[AES_BLOCK_LEN], prev[AES_BLOCK_LEN]; enum { head, params } section = head; enum { encrypt, decrypt } mode; uint32_t lineno = 0, start = 0, tests = 0, count = 0; bool done = true; struct { param key, iv, ct, pt; } expected; void (*op)(aes_key *, uint8_t *, uint8_t *, size_t, uint8_t*); aes_key aes_key; while (fgets(line, sizeof(line), file)) { lineno++; switch (line[0]) { case '#': break; case '\n': case '\r': if (!done && section == params) { tests++; if (count == 0) { memcpy(KEY, expected.key.value, expected.key.len); memcpy(IV, expected.iv.value, expected.iv.len); memcpy(PT, expected.pt.value, expected.pt.len); memcpy(CT, expected.ct.value, expected.pt.len); } aesni_set_key(&aes_key, KEY, expected.key.len); memcpy(block, IV, expected.iv.len); uint8_t *SRC, *DST; if (mode == encrypt) { op = &aesni_cbc_enc; SRC = PT; DST = CT; } else { op = &aesni_cbc_dec; SRC = CT; DST = PT; } for (int j = 0; j < 1000; j++) { memcpy(prev, DST, AES_BLOCK_LEN); op(&aes_key, DST, SRC, AES_BLOCK_LEN, block); memcpy(SRC, j == 0 ? IV : prev, AES_BLOCK_LEN); } if (count != 0) { if (memcmp(KEY, expected.key.value, expected.key.len)) { fail("FAILURE (KEY) %s @ %d\n", filename, start); } if (memcmp(IV, expected.iv.value, expected.iv.len)) { fail("FAILURE (IV) %s @ %d\n", filename, start); } param *expected_p = (mode == encrypt ? &expected.ct : &expected.pt); if (memcmp(DST, expected_p->value, expected_p->len)) { fail("FAILURE (CIPHERTEXT) %s @ %d\n", filename, start); } } uint8_t *K = KEY; int y = abs(expected.key.len - 32); for (int x = y; x < 16; x++) *K++ ^= prev[x]; for (int x = 0; x < 16; x++) *K++ ^= DST[x]; memcpy(IV, DST, AES_BLOCK_LEN); start = lineno + 1; count++; done = true; } break; case '[': if (section != head) { section = head; expected.key.len = expected.iv.len = 0; expected.pt.len = expected.ct.len = 0; count = 0; } parse_kv(line, name, value); if (!strcmp(name, "ENCRYPT")) mode = encrypt; if (!strcmp(name, "DECRYPT")) mode = decrypt; break; default: if (section != params) { section = params; start = lineno; } parse_kv(line, name, value); if (!strcmp(name, "KEY")) decode(name, value, &expected.key); if (!strcmp(name, "IV")) decode(name, value, &expected.iv); if (!strcmp(name, "PLAINTEXT")) decode(name, value, &expected.pt); if (!strcmp(name, "CIPHERTEXT")) decode(name, value, &expected.ct); if (!strcmp(name, "COUNT")) { uint32_t n = atol(value); if (count != n) { fail("INVALID MCT: expected COUNT = %d\n", count); } } done = false; } } return tests; }
int main(int argc, char *argv[]) { pid_t pid = getpid(); int str_end,hash_beg,i = 0, sm, lo, rs, dr, hash_len; char dir[200],report[1000],mdString[40]= {0}, *parcel, tmp[100], *from_str, *from_str_tmp, *hash_et, *help_ptr, *arglist_sm[100], *arglist_lo[100], *arglist_rs[100], *arglist_dr[100]; unsigned char *hash_cand = malloc(50*sizeof(char)); t_elements parsed_elements; sprintf(dir,"%s%d_log.log",LOG_DIR,pid); FILE *log = fopen(dir,"w"); if(log == NULL) exit(-4); from_str_tmp = malloc(sizeof(char)*100000); sprintf(tmp, "/tmp/%d/", pid); mkdir(tmp, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); chdir(tmp); fprintf(log, "PID: %d, dir changed\nthats what we got:\n", pid); do { from_str_tmp[i] = getc(stdin); fputc(from_str_tmp[i],log); if(from_str_tmp[i] == '-' && from_str_tmp[i-1] == '-') { str_end=i-1; hash_beg=i+1; from_str_tmp[str_end]=0; } } while(from_str_tmp[i++] != EOF); hash_et = from_str_tmp + sizeof(char)*hash_beg; hash_et[40]=0; from_str_tmp += 8*sizeof(char); from_str = curl_decode(from_str_tmp); help_ptr = from_str; from_str_tmp = decode(from_str); /*base64 conversion*/ fprintf(log,"\nAfter url_decode:%s",from_str); //\r\n from_str=from_str_tmp; fprintf(log,"\nhashed string:%s\n",help_ptr); HMAC(EVP_sha1(),SALT, strlen(SALT), (unsigned char*)help_ptr, strlen(help_ptr),hash_cand,(unsigned int*)&hash_len); for(i = 0; i < 20; i++) sprintf(&mdString[i*2], "%02x",hash_cand[i]); //FIXME leaks everywhere if(strcmp(mdString,hash_et)==0) { fprintf(log,"\nhash correct\n"); fprintf(log,"decoded string: %s\n", from_str); printf("Content-Type: text/plain;charset=us-ascii\n\n"); } else { fprintf(log, "%s\n%s\n hash incorrect\n",mdString,hash_et); printf("Content-Type: text/html\nStatus: 422 Bad Request\n\n"); free(hash_cand); free(from_str); fclose(log); exit(-1); } /*we have now string to parse*/ cJSON *root = cJSON_Parse(from_str); if (!root) { fprintf(log,"Error before: [%s]\n", cJSON_GetErrorPtr()); } fprintf(log,"exec part\n"); parse_into_elements(&parsed_elements, root, log); fflush(NULL); lo = make_arglist_for_login(arglist_lo, parsed_elements); fork_exec_with_inp_redir(arglist_lo, 1, "whatever"); sm = make_arglist_for_submit_and_run(arglist_sm, parsed_elements, arglist_lo[4]); fork_exec_with_inp_redir(arglist_sm, 1, "num.txt"); rs = make_arglist_for_run_status(arglist_rs, parsed_elements, arglist_lo[4]); int rep_num; if((rep_num=wait_for_report(5, arglist_rs, parsed_elements.status))==-1) { strcpy(parsed_elements.status,"error"); strcpy(report,"ejudge marking error"); } else { int flag=0,some; some = submit_checked(parsed_elements.status, ejudge_common); if(strcmp(parsed_elements.status,"OK")==0) { strcpy(parsed_elements.status,"ok"); flag=1; } else if(submit_checked(parsed_elements.status, ejudge_error)!=-1) { strcpy(parsed_elements.status,"error"); strcpy(report,ejudge_detailed[some]); if(some == 1) flag = 2; /*let report be when compilation error*/ } else { strcpy(parsed_elements.status, "fail"); flag=1; } if(flag) { dr = make_arglist_for_dump_report(arglist_dr, parsed_elements, arglist_lo[4]); //BACKTRACE part fork_exec_with_inp_redir(arglist_dr, 1, "return_report.xml"); /*xml parse part*/ if(flag==1){ ezxml_t trace = ezxml_parse_file("return_report.xml"); const char * points = ezxml_attr(trace, "score"); const char * tp = ezxml_attr(trace, "tests-passed"); const char * to = ezxml_attr(trace, "run-tests"); sprintf(report, "%s. Your score is = %s, %s/%s tests passed",ejudge_detailed[some], points , tp, to); ezxml_free(trace); /* parse part end */ /* BTW ezxml lib used so you have possibility to add smth to report */ } else if(flag==2) { char *iftmp; iftmp = read_string("return_report.xml"); strcat(report, iftmp); free(iftmp); } } } fprintf(log, "exec part end\n"); cJSON_AddStringToObject(root, "trace", report); cJSON_AddStringToObject(root, "status", parsed_elements.status); cJSON_DeleteItemFromObject(root,"programming_language"); cJSON_DeleteItemFromObject(root,"file_name"); cJSON_DeleteItemFromObject(root,"file_content"); parcel = cJSON_Print(root); fprintf(log,"output:%s\n",parcel); free(from_str); from_str=encode(parcel); fprintf(log,"encoded output:%s\n", from_str); parcel=curl_encode(from_str); fprintf(log,"curl_encoded output:%s\n", parcel); HMAC(EVP_sha1(),SALT, strlen(SALT), (unsigned char*)from_str, strlen(from_str),hash_cand,(unsigned int*)&hash_len); for(i = 0; i < 20; i++) sprintf(&mdString[i*2], "%02x", (unsigned int)hash_cand[i]); fprintf(log,"hash HMAC:%s\n", mdString); sprintf(from_str,"session=%s--%s",parcel,mdString); fprintf(log,"final output:%s\n", from_str); /*ready to send backparcel*/ sendJSON(parsed_elements.url, from_str); sendJSON("http://ejudge.100ege.ru/cgi-bin/a.out", from_str); //FIXME: for logging purposes //printf("%s",from_str); /*now clean part*/ fprintf(log,"\n%s\n",from_str); str_vector_free(arglist_lo, lo); str_vector_free(arglist_rs, rs); str_vector_free(arglist_sm, sm); free(root); free(from_str); free(parcel); fclose(log); chdir("/tmp/"); execl("/bin/rm", "/bin/rm", "-rf", tmp, NULL); return 0; }
// compiler is expected to optimized this function to avoid return value copy inline Unicode decode(const string& str) { Unicode unicode; unicode.reserve(str.size()); decode(str, unicode); return unicode; }
//-------------------------------------------------------------------------------- PDU_bind_type_resp::PDU_bind_type_resp(const char* b) : SMPP_PDU(b) { decode(b); }
static void module_load_event(void *drcontext, const module_data_t *mod, bool loaded) { if (strstr(dr_module_preferred_name(mod), "client.drwrap-test.appdll.") != NULL) { bool ok; instr_t inst; app_pc init_pc, pc, next_pc; load_count++; if (load_count == 2) { /* test no-frills */ drwrap_set_global_flags(DRWRAP_NO_FRILLS); } addr_replace = (app_pc) dr_get_proc_address(mod->handle, "replaceme"); CHECK(addr_replace != NULL, "cannot find lib export"); ok = drwrap_replace(addr_replace, (app_pc) replacewith, false); CHECK(ok, "replace failed"); addr_replace2 = (app_pc) dr_get_proc_address(mod->handle, "replaceme2"); CHECK(addr_replace2 != NULL, "cannot find lib export"); ok = drwrap_replace_native(addr_replace2, (app_pc) replacewith2, true/*at entry*/, 0, (void *)(ptr_int_t)DRWRAP_NATIVE_PARAM, false); CHECK(ok, "replace_native failed"); init_pc = (app_pc) dr_get_proc_address(mod->handle, "replace_callsite"); CHECK(init_pc != NULL, "cannot find lib export"); /* Find callsite: we assume we'll linearly hit a ret. We take final call * to skip any PIC call. */ instr_init(drcontext, &inst); pc = init_pc; do { instr_reset(drcontext, &inst); next_pc = decode(drcontext, pc, &inst); if (!instr_valid(&inst)) break; /* if initial jmp, follow it to handle ILT-indirection */ if (pc == init_pc && instr_is_ubr(&inst)) next_pc = opnd_get_pc(instr_get_target(&inst)); else if (instr_is_call(&inst)) addr_replace_callsite = pc; pc = next_pc; } while (instr_valid(&inst) && !instr_is_return(&inst)); CHECK(addr_replace_callsite != NULL, "cannot find lib export"); ok = drwrap_replace_native(addr_replace_callsite, (app_pc) replace_callsite, false/*!at entry*/, 0, (void *)(ptr_int_t)DRWRAP_NATIVE_PARAM, false); CHECK(ok, "replace_native failed"); instr_free(drcontext, &inst); wrap_addr(&addr_level0, "level0", mod, true, true); wrap_addr(&addr_level1, "level1", mod, true, true); wrap_addr(&addr_level2, "level2", mod, true, true); wrap_addr(&addr_tailcall, "makes_tailcall", mod, true, true); wrap_addr(&addr_skipme, "skipme", mod, true, true); wrap_addr(&addr_repeat, "repeatme", mod, true, true); wrap_addr(&addr_preonly, "preonly", mod, true, false); wrap_addr(&addr_postonly, "postonly", mod, false, true); wrap_addr(&addr_runlots, "runlots", mod, false, true); /* test longjmp */ wrap_unwindtest_addr(&addr_long0, "long0", mod); wrap_unwindtest_addr(&addr_long1, "long1", mod); wrap_unwindtest_addr(&addr_long2, "long2", mod); wrap_unwindtest_addr(&addr_long3, "long3", mod); wrap_unwindtest_addr(&addr_longdone, "longdone", mod); drmgr_set_tls_field(drcontext, tls_idx, (void *)(ptr_uint_t)0); #ifdef WINDOWS /* test SEH */ /* we can't do this test for no-frills b/c only one wrap per addr */ if (load_count == 1) { ok = drwrap_wrap_ex(addr_long0, wrap_unwindtest_seh_pre, wrap_unwindtest_seh_post, NULL, DRWRAP_UNWIND_ON_EXCEPTION); CHECK(ok, "wrap failed"); ok = drwrap_wrap_ex(addr_long1, wrap_unwindtest_seh_pre, wrap_unwindtest_seh_post, NULL, DRWRAP_UNWIND_ON_EXCEPTION); CHECK(ok, "wrap failed"); ok = drwrap_wrap_ex(addr_long2, wrap_unwindtest_seh_pre, wrap_unwindtest_seh_post, NULL, DRWRAP_UNWIND_ON_EXCEPTION); CHECK(ok, "wrap failed"); ok = drwrap_wrap_ex(addr_long3, wrap_unwindtest_seh_pre, wrap_unwindtest_seh_post, NULL, DRWRAP_UNWIND_ON_EXCEPTION); CHECK(ok, "wrap failed"); ok = drwrap_wrap_ex(addr_longdone, wrap_unwindtest_seh_pre, wrap_unwindtest_seh_post, NULL, DRWRAP_UNWIND_ON_EXCEPTION); CHECK(ok, "wrap failed"); } #endif /* test leaner wrapping */ if (load_count == 2) drwrap_set_global_flags(DRWRAP_NO_FRILLS | DRWRAP_FAST_CLEANCALLS); wrap_addr(&addr_skip_flags, "skip_flags", mod, true, false); } }
unsigned short identifier() const { return decode(4, 5); }
void initKV(uint64_t kvtarget, ::libmaus::huffman::KvInitResult & result) { result = ::libmaus::huffman::KvInitResult(); if ( ( (idda.kvec.size()!=0) && (idda.kvec[idda.kvec.size()-1] != 0) ) ) { if ( kvtarget >= idda.kvec[idda.kvec.size()-1] + idda.vvec[idda.vvec.size()-1] ) { fileptr = idda.data.size(); blockptr = 0; result.koffset = idda.kvec[idda.kvec.size()-1]; result.voffset = idda.vvec[idda.vvec.size()-1]; result.kvoffset = result.koffset + result.voffset; result.kvtarget = 0; } else { ::libmaus::huffman::FileBlockOffset const FBO = idda.findKVBlock(kvtarget); fileptr = FBO.fileptr; blockptr = FBO.blockptr; /* open file and seek to block */ openNewFile(); /* decode block in question */ bool const blockok = decodeBlock(); assert ( blockok ); /* key/symbol offset of block (sum over elements of previous blocks) */ uint64_t kvoffset = idda.data[FBO.fileptr].getKeyValueCnt(FBO.blockptr); uint64_t voffset = idda.data[FBO.fileptr].getValueCnt(FBO.blockptr); uint64_t koffset = idda.data[FBO.fileptr].getKeyCnt(FBO.blockptr); assert ( kvtarget >= kvoffset ); kvtarget -= kvoffset; // std::cerr << "fileptr=" << fileptr << " blockptr=" << blockptr << " kvtarget=" << kvtarget << std::endl; while ( kvtarget >= peek() + 1 ) { uint64_t const gi = decode(); kvoffset += (gi+1); kvtarget -= (gi+1); voffset += gi; koffset += 1; } if ( koffset + 1 == getN() && kvtarget >= peek() ) { uint64_t const gi = decode(); kvoffset += gi; kvtarget -= gi; voffset += gi; koffset += 0; } else { assert ( pc != pe ); assert ( kvtarget <= peek() ); assert ( kvtarget <= *pc ); *pc -= kvtarget; } result.koffset = koffset; result.voffset = voffset; result.kvoffset = kvoffset; result.kvtarget = kvtarget; } } }
bool Q3Url::parse( const QString& url ) { QString url_( url ); slashify( url_ ); if ( url_.isEmpty() ) { d->isValid = false; return false; } d->cleanPathDirty = true; d->isValid = true; QString oldProtocol = d->protocol; d->protocol.clear(); const int Init = 0; const int Protocol = 1; const int Separator1= 2; // : const int Separator2= 3; // :/ const int Separator3= 4; // :// or more slashes const int User = 5; const int Pass = 6; const int Host = 7; const int Path = 8; const int Ref = 9; const int Query = 10; const int Port = 11; const int Done = 12; const int InputAlpha= 1; const int InputDigit= 2; const int InputSlash= 3; const int InputColon= 4; const int InputAt = 5; const int InputHash = 6; const int InputQuery= 7; static uchar table[ 12 ][ 8 ] = { /* None InputAlpha InputDigit InputSlash InputColon InputAt InputHash InputQuery */ { 0, Protocol, 0, Path, 0, 0, 0, 0, }, // Init { 0, Protocol, Protocol, 0, Separator1, 0, 0, 0, }, // Protocol { 0, Path, Path, Separator2, 0, 0, 0, 0, }, // Separator1 { 0, Path, Path, Separator3, 0, 0, 0, 0, }, // Separator2 { 0, User, User, Separator3, Pass, Host, 0, 0, }, // Separator3 { 0, User, User, User, Pass, Host, User, User, }, // User { 0, Pass, Pass, Pass, Pass, Host, Pass, Pass, }, // Pass { 0, Host, Host, Path, Port, Host, Ref, Query, }, // Host { 0, Path, Path, Path, Path, Path, Ref, Query, }, // Path { 0, Ref, Ref, Ref, Ref, Ref, Ref, Query, }, // Ref { 0, Query, Query, Query, Query, Query, Query, Query, }, // Query { 0, 0, Port, Path, 0, 0, 0, 0, } // Port }; bool relPath = false; relPath = false; bool forceRel = false; // If ':' is at pos 1, we have only one letter // before that separator => that's a drive letter! if ( url_.length() >= 2 && url_[1] == QLatin1Char(':') ) relPath = forceRel = true; int hasNoHost = -1; int cs = url_.find( QLatin1String(":/") ); if ( cs != -1 ) // if a protocol is there, find out if there is a host or directly the path after it hasNoHost = url_.find( QLatin1String("///"), cs ); table[ 4 ][ 1 ] = User; table[ 4 ][ 2 ] = User; if ( cs == -1 || forceRel ) { // we have a relative file if ( url.find( QLatin1Char(':') ) == -1 || forceRel ) { table[ 0 ][ 1 ] = Path; // Filenames may also begin with a digit table[ 0 ][ 2 ] = Path; } else { table[ 0 ][ 1 ] = Protocol; } relPath = true; } else { // some checking table[ 0 ][ 1 ] = Protocol; // find the part between the protocol and the path as the meaning // of that part is dependent on some chars ++cs; while ( url_[ cs ] == QLatin1Char('/') ) ++cs; int slash = url_.find( QLatin1Char('/'), cs ); if ( slash == -1 ) slash = url_.length() - 1; QString tmp = url_.mid( cs, slash - cs + 1 ); if ( !tmp.isEmpty() ) { // if this part exists // look for the @ in this part int at = tmp.find( QLatin1Char('@') ); if ( at != -1 ) at += cs; // we have no @, which means host[:port], so directly // after the protocol the host starts, or if the protocol // is file or there were more than 2 slashes, it is the // path if ( at == -1 ) { if ( url_.left( 4 ) == QLatin1String("file") || hasNoHost != -1 ) table[ 4 ][ 1 ] = Path; else table[ 4 ][ 1 ] = Host; table[ 4 ][ 2 ] = table[ 4 ][ 1 ]; } } } int state = Init; // parse state int input; // input token QChar c = url_[ 0 ]; int i = 0; QString port; for ( ;; ) { switch ( c.latin1() ) { case '?': input = InputQuery; break; case '#': input = InputHash; break; case '@': input = InputAt; break; case ':': input = InputColon; break; case '/': input = InputSlash; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': input = InputDigit; break; default: input = InputAlpha; } state = table[ state ][ input ]; switch ( state ) { case Protocol: d->protocol += c; break; case User: d->user += c; break; case Pass: d->pass += c; break; case Host: d->host += c; break; case Path: d->path += c; break; case Ref: d->refEncoded += c; break; case Query: d->queryEncoded += c; break; case Port: port += c; break; default: break; } ++i; if ( i > (int)url_.length() - 1 || state == Done || state == 0 ) break; c = url_[ i ]; } if ( !port.isEmpty() ) { port.remove( (uint)0, 1 ); d->port = port.toInt(); } // error if ( i < (int)url_.length() - 1 ) { d->isValid = false; return false; } if ( d->protocol.isEmpty() ) d->protocol = oldProtocol; if ( d->path.isEmpty() ) d->path = QLatin1String("/"); // hack for windows if ( d->path.length() == 2 && d->path[ 1 ] == QLatin1Char(':') ) d->path += QLatin1Char('/'); // #### do some corrections, should be done nicer too if ( !d->pass.isEmpty() ) { if ( d->pass[ 0 ] == QLatin1Char(':') ) d->pass.remove( (uint)0, 1 ); decode( d->pass ); } if ( !d->user.isEmpty() ) { decode( d->user ); } if ( !d->path.isEmpty() ) { if ( d->path[ 0 ] == QLatin1Char('@') || d->path[ 0 ] == QLatin1Char(':') ) d->path.remove( (uint)0, 1 ); if ( d->path[ 0 ] != QLatin1Char('/') && !relPath && d->path[ 1 ] != QLatin1Char(':') ) d->path.prepend( QLatin1Char('/') ); } if ( !d->refEncoded.isEmpty() && d->refEncoded[ 0 ] == QLatin1Char('#') ) d->refEncoded.remove( (uint)0, 1 ); if ( !d->queryEncoded.isEmpty() && d->queryEncoded[ 0 ] == QLatin1Char('?') ) d->queryEncoded.remove( (uint)0, 1 ); if ( !d->host.isEmpty() && d->host[ 0 ] == QLatin1Char('@') ) d->host.remove( (uint)0, 1 ); #if defined(Q_OS_WIN32) // hack for windows file://machine/path syntax if ( d->protocol == QLatin1String("file") ) { if ( url.startsWith(QLatin1String("file://")) && d->path.length() > 1 && d->path[ 1 ] != QLatin1Char(':') ) d->path.prepend( QLatin1Char('/') ); } #endif decode( d->path ); d->cleanPathDirty = true; #if 0 qDebug( "URL: %s", url.latin1() ); qDebug( "protocol: %s", d->protocol.latin1() ); qDebug( "user: %s", d->user.latin1() ); qDebug( "pass: %s", d->pass.latin1() ); qDebug( "host: %s", d->host.latin1() ); qDebug( "path: %s", path().latin1() ); qDebug( "ref: %s", d->refEncoded.latin1() ); qDebug( "query: %s", d->queryEncoded.latin1() ); qDebug( "port: %d\n\n----------------------------\n\n", d->port ); #endif return true; }
int main(int argc, char *argv[]) { /*define local variables*/ clock_t start, end, t1, t2, t3, t4; int i,g; //counters //maxrank1; //the larger maxrank between oldpop and matepop //double tot; //sum of no. of inds in a rank in both oldpop and newpop FILE *rep_ptr, *lastit;/*File Pointers*/ if( argc == 2 ) printf("The argument supplied is %s\n", argv[1]); else if( argc > 2 ) printf("Too many arguments supplied.\n"); else printf("One argument expected.\n"); seed = (double)atof(argv[1]); if (seed<=0.0 || seed>=1.0) { printf("\n Entered seed value is wrong, seed value must be in (0,1) \n"); exit(1); } /*open files*/ rep_ptr=fopen ("output.out","w"); lastit = fopen("plot.out","w"); old_pop_ptr=&(oldpop); no_mut1=0; no_mut2=0; no_cross = 0; input(rep_ptr); /*obtain inputs*/ randomize(); /*initialize random no. generator*/ /*initialize population*/ init(old_pop_ptr); /*decode integer chromosomes*/ if (no_intevar>0) { decode(old_pop_ptr); } /*initialize the rank array having different individuals at a particular rank to zero*/ new_pop_ptr=&(newpop); for (i=0;i<popsize;i++) { old_pop_ptr->rankno[i]=0; new_pop_ptr->rankno[i]=0; old_pop_ptr->ind[i].tag=1; } /*evaluation the objective and constraint functions of the current population*/ noeval=0; //assig generation number to each ind in matepop evaluatepop(old_pop_ptr, -1); for (i=0;i<popsize;i++) { old_pop_ptr->ind[i].tag=0; } //rank the oldpop before copy it into midpop and selection if (no_cons==0) { old_pop_ptr->ind_ptr->overallcons=0.0; ranking(old_pop_ptr); } else { rankcon(old_pop_ptr); } /***********************************************************************************/ /****************************GNENRATION LOOP STARTS*********************************/ for (g=0;g<no_gener;g++) { printf("\nGeneration number = %d", g+1); start=clock(); //fprintf(rep_ptr,"Population at Generation No. -->%d\n",g+1); //fprintf(rep_ptr,"#Generation No. -->%d\n",g+1); //fprintf(rep_ptr,"#Variable_vector Fitness_vector Constraint_violation Overall_violation\n"); old_pop_ptr=&(oldpop); mid_pop_ptr=&(midpop); mate_pop_ptr=&(matepop); new_pop_ptr=&(newpop); best_pop_ptr=&(bestpop); /**********************Two-member Tournament Selection***************************/ //copy oldpop into midpop-midpop is the exact copy of oldpop copypop(old_pop_ptr, mid_pop_ptr); //shuffle midpop and select from oldpop+midpop to form matepop selectt(old_pop_ptr, mid_pop_ptr, mate_pop_ptr); /***********************************Crossover************************************/ //one-point crossover for chrom1 and SBX for chrom2 //before crossover and mutation set tag to zero for (i=0;i<popsize;i++) { new_pop_ptr->ind[i].tag=0; } crossover(new_pop_ptr, mate_pop_ptr); /***********************************Mutation************************************/ //random/adjacent mutation for chrom1 and polynomial mutation for chrom2 mutation(new_pop_ptr); /*************Decode the integer chromosome of the child population*************/ if (no_intevar>0) decode(new_pop_ptr); /*Evaluation the objective and constraint functions of the child population*/ t1=clock(); evaluatepop(new_pop_ptr, g); t2=clock(); /************************Selection keeping fronts alive************************/ //Elitism and sharing implementation t3=clock(); keepalive(old_pop_ptr, new_pop_ptr, mate_pop_ptr, g+1); t4=clock(); //select best pop if (g==0) { //for the first generation form the first bestpop from matepop copypop(mate_pop_ptr, best_pop_ptr); } else { selectbest(mate_pop_ptr, best_pop_ptr, g); } report(g, best_pop_ptr, mate_pop_ptr, lastit); // output.out, /***************************Copy the newpop to oldpop**************************/ /***Assign oldpop the value of matepop(cross, mutate, keepalive_selection, so the original oldpop is updated***/ copypop(mate_pop_ptr, old_pop_ptr); for (i=0;i<popsize;i++) { old_pop_ptr->ind[i].tag=0; } /***************Print the fitness record for the last generation***************/ /* if (g==no_gener-1) { //for the last generation old_pop_ptr=&(matepop); for (f=0;f<popsize;f++) { //printing loop old_pop_ptr->ind_ptr=&(old_pop_ptr->ind[f]); //for all feasible and non-dominating solutions if ((old_pop_ptr->ind_ptr->overallcons<=0.0) && (old_pop_ptr->ind_ptr->rank==1)) { //if solution is feasible for (l=0;l<no_obj;l++) //for each objective fprintf(end_ptr, "%f\t", old_pop_ptr->ind_ptr->fit[l]); for (l=0;l<no_cons;l++) //for each constraint fprintf(end_ptr, "%f\t", old_pop_ptr->ind_ptr->cons[l]); if (no_cons>0) fprintf(end_ptr, "%f\t", old_pop_ptr->ind_ptr->overallcons); fprintf(end_ptr, "\n"); if (no_realvar>0) { //for real variables for (l=0;l<no_realvar;l++) fprintf(g_var, "%f\t", old_pop_ptr->ind_ptr->chrom2[l]); fprintf(g_var, " "); } //loop over realvar ends if (no_intevar>0) { //for integer variables for (l=0;l<no_intevar;l++) fprintf(g_var, "%d\t", old_pop_ptr->ind_ptr->chrom1[l]); } //loop over integer var ends fprintf(g_var,"\n"); } //feasibility check ends } //loop over f ends (printing) } //end of the last generation */ end=clock(); //printf("\n The time to do evaluatepop of this generation is %f seconds", ((double) t2-t1)/CLOCKS_PER_SEC); //printf("\n The time to doNS of this generation is %f seconds", ((double) t4-t3)/CLOCKS_PER_SEC); //printf("\n The time to do this generation is %f seconds", ((double) end-start)/CLOCKS_PER_SEC); printf("\n The %d th Generation has finished. ", g+1); } /*end of the ith generation*/ /****************************GNENRATION LOOP FINISHES*********************************/ /*************************************************************************************/ fprintf(rep_ptr, "No. OF CROSSOVER = %d\n", no_cross); fprintf(rep_ptr, "NO. OF MUTATION FOR INTEGER CHROMOSOME= %d\n", no_mut1); fprintf(rep_ptr, "NO. OF MUTATION FOR REAL-CODED CHROMOSOME= %d\n", no_mut2); fprintf(rep_ptr, "-----------------------------------------------------------------------\n"); fprintf(rep_ptr, "----------------Now you can look in the ourput files-------------------\n"); //close files fclose(rep_ptr); fclose(lastit); return(0); }
int main(int argc,char **argv){ int i,j,k,l,c; unsigned long a,x,count=1; // unsigned char cc[K]={0}; unsigned char m[K],mm[T]={0}; time_t timer; FILE *fp,*fq; unsigned char g2[7]={1,0,9,0,0,6,4}; // unsigned char s[K]={0}; //{4,12,7,8,11,13}; unsigned char ee[10]={1,2,3,4,5,6,7,8,9,10}; unsigned char zz[T]={86,97,114,105,97,98,108,101,32,80,111,108,121,110,111,109}; // unsigned char zz[T]={10,97,114,105,97,98,108,101,32,80,111,108,121,110,111,109}; int y; OP f,h,r,w; vec v; unsigned char d=0; // unsigned char syn[K]={4,12,7,8,11,13}; // unsigned char g[K+1]={1,0,0,0,1,0,1}; // makegf(M); // makefg(M); // zz[0]=1; //zz[1]=2; //zz[2]=4; w=setpol(g,K+1); printpol(o2v(w)); // exit(1); /* fp=fopen(argv[1],"rb"); fq=fopen(argv[2],"wb"); while((c=fread(zz,1,T,fp))>0){ for(i=0;i<M;i++){ d=trace(w,(unsigned char)i); printf("%d,",d); if(d==0){ printf("%i bad trace 0\n",i); exit(1); } } printf("\n"); //exit(1); */ //エラーの生成 for(i=0;i<T;i++) zz[i]=i+1; det(g); for(i=0;i<K;i++){ for(j=0;j<M;j++) printf("%d,",mat[i][j]); printf("\n"); } //exit(1); // シンドローム多項式の生成 printf("zz="); for(i=0;i<K;i++){ syn[i]=0; for(j=0;j<T;j++){ printf("%u,",zz[j]); syn[i]^=gf[mlt(fg[zz[j]],fg[mat[i][j]])]; } // printf("%d,",syn[i]); } printf("\n"); // exit(1); f=setpol(syn,K); printpol(o2v(f)); // exit(1); r=decode(w,f); for(i=0;i<T;i++){ mm[i]=r.t[i].a; printf("e=%d %d\n",r.t[i].a,r.t[i].n); } /* fwrite(mm,1,T,fq); } */ // fclose(fp); // fclose(fq); // h2g(mat); // exit(1); return 0; }
/* Encrypts or decrypts a string. result should be freed with free() when done */ SECStatus doCrypto(JNIEnv* jenv, const char *path, const char *value, char** result, bool encrypt) { SECStatus rv; PK11SlotInfo *slot; if (!initialized) { LOG("Initialize crypto in %s\n", path); rv = f_NSS_Initialize(path, "", "", "secmod.db", NSS_INIT_NOROOTINIT); if (rv != SECSuccess) { throwError(jenv, "NSS_Initialize"); return rv; } initialized = true; } slot = f_PK11_GetInternalKeySlot(); if (!slot) { throwError(jenv, "PK11_GetInternalKeySlot"); return SECFailure; } if (f_PK11_NeedUserInit(slot)) { LOG("Initializing key3.db with default blank password.\n"); rv = f_PK11_InitPin(slot, nullptr, nullptr); if (rv != SECSuccess) { throwError(jenv, "PK11_InitPin"); return rv; } } SECItem request; SECItem reply; reply.data = 0; reply.len = 0; if (encrypt) { // This can print sensitive data. Uncomment if you need it. // LOG("Encrypting: %s\n", value); request.data = (unsigned char*)value; request.len = strlen(value); SECItem keyid; keyid.data = 0; keyid.len = 0; rv = f_PK11SDR_Encrypt(&keyid, &request, &reply, nullptr); if (rv != SECSuccess) { throwError(jenv, "PK11SDR_Encrypt"); goto done; } rv = encode(reply.data, reply.len, result); if (rv != SECSuccess) { throwError(jenv, "encode"); goto done; } LOG("Encrypted: %s\n", *result); } else { LOG("Decoding: %s\n", value); rv = decode(value, &request.data, (int32_t*)&request.len); if (rv != SECSuccess) { throwError(jenv, "decode"); return rv; } rv = f_PK11SDR_Decrypt(&request, &reply, nullptr); if (rv != SECSuccess) { throwError(jenv, "PK11SDR_Decrypt"); goto done; } *result = (char *)malloc(reply.len+1); strncpy(*result, (char *)reply.data, reply.len); (*result)[reply.len] = '\0'; // This can print sensitive data. Uncomment if you need it. // LOG("Decoded %i letters: %s\n", reply.len, *result); free(request.data); } done: f_SECITEM_ZfreeItem(&reply, false); return rv; }
/* @param wallclock_ts [in] the current ts in the audio buffer */ int AmRtpAudio::receive(unsigned long long system_ts) { int size; unsigned int rtp_ts; int new_payload = -1; if(!fmt.get() || (!playout_buffer.get())) { DBG("audio format not initialized\n"); return RTP_ERROR; } unsigned int wallclock_ts = scaleSystemTS(system_ts); while(true) { size = AmRtpStream::receive((unsigned char*)samples, (unsigned int)AUDIO_BUFFER_SIZE, rtp_ts, new_payload); if(size <= 0) { switch(size){ case 0: break; case RTP_DTMF: case RTP_UNKNOWN_PL: case RTP_PARSE_ERROR: continue; case RTP_TIMEOUT: //FIXME: postRequest(new SchedRequest(AmMediaProcessor::RemoveSession,s)); // post to the session (FIXME: is session always set? seems to be...) session->postEvent(new AmRtpTimeoutEvent()); return -1; case RTP_BUFFER_SIZE: default: ERROR("AmRtpStream::receive() returned %i\n",size); //FIXME: postRequest(new SchedRequest(AmMediaProcessor::ClearSession,s)); // or AmMediaProcessor::instance()->clearSession(session); return -1; break; } break; } if (// don't process if we don't need to // ignore CN COMFORT_NOISE_PAYLOAD_TYPE == new_payload || // ignore packet if payload not found setCurrentPayload(new_payload) ){ playout_buffer->clearLastTs(); continue; } size = decode(size); if(size <= 0){ ERROR("decode() returned %i\n",size); return -1; } // This only works because the possible ratio (Rate/TSRate) // is 2. Rate and TSRate are only different in case of g722. // For g722, TSRate=8000 and Rate=16000 // AmAudioRtpFormat* rtp_fmt = (AmAudioRtpFormat*)fmt.get(); unsigned long long adjusted_rtp_ts = rtp_ts; if(rtp_fmt->getRate() != rtp_fmt->getTSRate()) { adjusted_rtp_ts = (unsigned long long)rtp_ts * (unsigned long long)rtp_fmt->getRate() / (unsigned long long)rtp_fmt->getTSRate(); } playout_buffer->write(wallclock_ts, adjusted_rtp_ts, (ShortSample*)((unsigned char *)samples), PCM16_B2S(size), begin_talk); if(!active) { DBG("switching to active-mode\t(ts=%u;stream=%p)\n", rtp_ts,this); active = true; } } return size; }
void *accept_thread(void *accept_sock) { //socket descriptor for each client int acptsock; //Retrieve the socket that passed from pthread_create acptsock= (intptr_t)accept_sock; //Buffer to send&receive data// char buf[256]; //Received bytes int bytes; //Declare the structure of the sending message in order //the filemanager to communicate with the client and vice versa FILEHEADER *msg = (FILEHEADER *)malloc(sizeof(FILEHEADER)); //While the client is connect to the system you have to keep the connection while(1) { //If connection is established then start communicating // //Initialize buffer with zeros // bzero(buf, sizeof(buf)); //Waiting...to receive data from the client// if (recv(acptsock, buf, sizeof(buf), 0) < 0) { perror("Received() failed!"); close(acptsock); pthread_exit((void *) 0); } //Check if direc received a message if(strlen(buf) != 0) { //Show the message that received// printf("----------------------------------\n"); printf("accept_thread received: %s\n", buf); } else if (strlen(buf) == 0) { //printf("Unable to received messsage!\n"); close(acptsock); pthread_exit((void *) 0); } //Decode the message that receive from the client //in order to identify the type of the message// decode(buf,msg); if( strcmp(msg->type , "REQCLIENTID" )== 0) { bzero(buf,sizeof(buf)); //encode the clientID sprintf(buf,"REQCLIENTID,%ld,%ld" , registerClient(msg->username ), msg->MSGID ); if (send(acptsock, buf, sizeof(buf) , 0) < 0 ) { perror("Send:Unable to send clientID"); } //Deallocations free(msg->username); } else if( strcmp(msg->type , "REQCREATE" )== 0 ) { printf("Received Create: %s , owner:%ld\n", msg->filename, msg->owner); //Store fileid unsigned long fileid = lookUpFileID(msg->filename , msg->owner ); if(fileid == -1) { //Store the new file in the metadata //Also , retrieve the fileID for the file fileid = registerFile(msg->filename, msg->owner); } printf("REQCREATE Function return: %ld \n", fileid); bzero(buf, sizeof(buf)); //encode the clientID sprintf(buf, "REQCREATE,%ld,%ld", fileid, msg->MSGID); if (send(acptsock, buf, sizeof(buf), 0) < 0) { perror("Send:Unable to send clientID"); } //Deallocations free(msg->filename); } else if( strcmp(msg->type , "REQFILEID" )== 0 ) { printf("Received REQFILEID: %s , owner:%ld\n" , msg->filename ,msg->owner); //Store the new file in the metadata //Also , retrieve the fileID for the file unsigned long fileid = lookUpFileID(msg->filename , msg->owner ); if(fileid == -1) { //Store the new file in the metadata //Also , retrieve the fileID for the file fileid = registerFile(msg->filename, msg->owner); } printf("REQFILEID Function return: %ld \n" , fileid); bzero(buf,sizeof(buf)); //encode the clientID sprintf(buf,"REQFILEID,%ld,%ld" , fileid , msg->MSGID ); if (send(acptsock, buf, sizeof(buf) , 0) < 0 ) { perror("Send:Unable to send clientID"); } //Deallocations free(msg->filename); } else if( strcmp(msg->type , "REQFILESLIST" )== 0 ) { bzero(buf,sizeof(buf)); GString *list=NULL; list=getfilelist(list); printf("List\n"); if (send(acptsock, list->str, strlen(list->str) , 0) < 0 ) { perror("Send:Unable to send clientID"); } //Deallocate memory g_string_free(list,TRUE); } }//While }
const shared_ptr<std::string> ZLBase64EncodedImage::stringData() const { decode(); return myData; }
static BOOL clientRequest( SOCKET sock, char *host, u_short port ) { BYTE buffer[ 1024 ]; BYTE *ptr, *end; DWORD length; BOOL echo = FALSE; sprintf_s( buffer, sizeof( buffer ), REQUEST_TEMPLATE, host, port ); length = strlen( buffer ); if ( ! (length = encode( length, buffer, sizeof( buffer ) )) ) return( FALSE ); if ( verbose ) { printf( "Client Request: \n" ); hexDump( length, buffer ); } if ( ! sendBytes( sock, buffer, length ) ) return( FALSE ); do { if ( ! receiveBytes( sock, buffer, sizeof( buffer ), &length ) ) return( FALSE ); if ( ! length ) { fprintf( stderr, "No response from server\n" ); break; } if ( verbose ) { printf( "Server Response: \n" ); hexDump( length, buffer ); } if ( ! (length = decode( length, buffer, sizeof( buffer ) )) ) return( FALSE ); ptr = buffer; end = ptr + length; *end = 0; while( ptr < end ) { BYTE *eol, save; for( eol = ptr; *eol && *eol != '\n'; eol++ ) /* DO NOTHING */; eol++; save = *eol; *eol = 0; /* ** Display response between 'BEGIN' and 'END' */ if ( ! echo ) { /* Echo starts with 'BEGIN' */ if ( ! strcmp( ptr, "BEGIN\r\n" ) || ! strcmp( ptr, "BEGIN\n" ) ) echo = TRUE; } else { /* Echo finishes with 'END' */ if ( ! strcmp( ptr, "END\r\n" ) || ! strcmp( ptr, "END\n" ) ) break; printf( "%s", ptr ); } *eol = save; ptr = eol; } } while( FALSE ); return( TRUE ); }
/* returns false on failure */ static bool decode_syscall_num(void *dcontext, byte *entry, syscall_info_t *info) { /* FIXME: would like to fail gracefully rather than have a DR assertion * on non-code! => use DEBUG=0 INTERNAL=1 DR build! */ bool found_syscall = false, found_eax = false, found_edx = false, found_ecx = false; bool found_ret = false; byte *pc; int num_instr = 0; instr_t *instr; if (entry == NULL) return false; info->num_args = -1; /* if find sysnum but not args */ info->sysnum = -1; info->fixup_index = -1; instr = instr_create(dcontext); pc = entry; /* FIXME - we don't support decoding 64bit instructions in 32bit mode, but I want * this to work on 32bit machines. Hack fix based on the wrapper pattern, we skip * the first instruction (mov r10, rcx) here, the rest should decode ok. * Xref PR 236203. */ if (expect_x64 && *pc == 0x4c && *(pc+1) == 0x8b && *(pc+2) == 0xd1) pc += 3; while (true) { instr_reset(dcontext, instr); pc = decode(dcontext, pc, instr); if (verbose) dr_print_instr(dcontext, STDOUT, instr, ""); if (pc == NULL || !instr_valid(instr)) break; /* ASSUMPTION: a mov imm of 0x7ffe0300 into edx followed by an * indirect call via edx is a system call on XP and later * On XP SP1 it's call *edx, while on XP SP2 it's call *(edx) * For wow it's a call through fs. * FIXME - core exports various is_*_syscall routines (such as * instr_is_wow64_syscall()) which we could use here instead of * duplicating if they were more flexible about when they could * be called (instr_is_wow64_syscall() for ex. asserts if not * in a wow process). */ if (/* int 2e or x64 or win8 sysenter */ (instr_is_syscall(instr) && found_eax && (expect_int2e || expect_x64 || expect_sysenter)) || /* sysenter case */ (expect_sysenter && found_edx && found_eax && instr_is_call_indirect(instr) && /* XP SP{0,1}, 2003 SP0: call *edx */ ((opnd_is_reg(instr_get_target(instr)) && opnd_get_reg(instr_get_target(instr)) == REG_EDX) || /* XP SP2, 2003 SP1: call *(edx) */ (opnd_is_base_disp(instr_get_target(instr)) && opnd_get_base(instr_get_target(instr)) == REG_EDX && opnd_get_index(instr_get_target(instr)) == REG_NULL && opnd_get_disp(instr_get_target(instr)) == 0))) || /* wow case * we don't require found_ecx b/c win8 does not use ecx */ (expect_wow && found_eax && instr_is_call_indirect(instr) && opnd_is_far_base_disp(instr_get_target(instr)) && opnd_get_base(instr_get_target(instr)) == REG_NULL && opnd_get_index(instr_get_target(instr)) == REG_NULL && opnd_get_segment(instr_get_target(instr)) == SEG_FS)) { found_syscall = true; } else if (instr_is_return(instr)) { if (!found_ret) { process_ret(instr, info); found_ret = true; } break; } else if (instr_is_cti(instr)) { if (instr_get_opcode(instr) == OP_call) { /* handle win8 x86 which has sysenter callee adjacent-"inlined" * ntdll!NtYieldExecution: * 77d7422c b801000000 mov eax,1 * 77d74231 e801000000 call ntdll!NtYieldExecution+0xb (77d74237) * 77d74236 c3 ret * 77d74237 8bd4 mov edx,esp * 77d74239 0f34 sysenter * 77d7423b c3 ret */ byte *tgt; assert(opnd_is_pc(instr_get_target(instr))); tgt = opnd_get_pc(instr_get_target(instr)); /* we expect only ret or ret imm, and possibly some nops (in gdi32). * XXX: what about jmp to shared ret (seen in the past on some syscalls)? */ if (tgt > pc && tgt <= pc + 16) { bool ok = false; do { if (pc == tgt) { ok = true; break; } instr_reset(dcontext, instr); pc = decode(dcontext, pc, instr); if (verbose) dr_print_instr(dcontext, STDOUT, instr, ""); if (instr_is_return(instr)) { process_ret(instr, info); found_ret = true; } else if (!instr_is_nop(instr)) break; num_instr++; } while (num_instr <= MAX_INSTRS_BEFORE_SYSCALL); if (ok) continue; } } /* assume not a syscall wrapper if we hit a cti */ break; /* give up gracefully */ } else if ((!found_eax || !found_edx || !found_ecx) && instr_get_opcode(instr) == OP_mov_imm && opnd_is_reg(instr_get_dst(instr, 0))) { if (!found_eax && opnd_get_reg(instr_get_dst(instr, 0)) == REG_EAX) { info->sysnum = (int) opnd_get_immed_int(instr_get_src(instr, 0)); found_eax = true; } else if (!found_edx && opnd_get_reg(instr_get_dst(instr, 0)) == REG_EDX) { int imm = (int) opnd_get_immed_int(instr_get_src(instr, 0)); if (imm == 0x7ffe0300) found_edx = true; } else if (!found_ecx && opnd_get_reg(instr_get_dst(instr, 0)) == REG_ECX) { found_ecx = true; info->fixup_index = (int) opnd_get_immed_int(instr_get_src(instr, 0)); } } else if (instr_get_opcode(instr) == OP_xor && opnd_is_reg(instr_get_src(instr, 0)) && opnd_get_reg(instr_get_src(instr, 0)) == REG_ECX && opnd_is_reg(instr_get_dst(instr, 0)) && opnd_get_reg(instr_get_dst(instr, 0)) == REG_ECX) { /* xor to 0 */ found_ecx = true; info->fixup_index = 0; } num_instr++; if (num_instr > MAX_INSTRS_BEFORE_SYSCALL) /* wrappers should be short! */ break; /* avoid weird cases like NPXEMULATORTABLE */ } instr_destroy(dcontext, instr); return found_syscall; }
bool decode(ArgumentDecoder* decoder, RetainPtr<CFTypeRef>& result) { CFType type; if (!decoder->decodeEnum(type)) return false; switch (type) { case CFArray: { RetainPtr<CFArrayRef> array; if (!decode(decoder, array)) return false; result.adoptCF(array.leakRef()); return true; } case CFBoolean: { RetainPtr<CFBooleanRef> boolean; if (!decode(decoder, boolean)) return false; result.adoptCF(boolean.leakRef()); return true; } case CFData: { RetainPtr<CFDataRef> data; if (!decode(decoder, data)) return false; result.adoptCF(data.leakRef()); return true; } case CFDate: { RetainPtr<CFDateRef> date; if (!decode(decoder, date)) return false; result.adoptCF(date.leakRef()); return true; } case CFDictionary: { RetainPtr<CFDictionaryRef> dictionary; if (!decode(decoder, dictionary)) return false; result.adoptCF(dictionary.leakRef()); return true; } case CFNull: result.adoptCF(kCFNull); return true; case CFNumber: { RetainPtr<CFNumberRef> number; if (!decode(decoder, number)) return false; result.adoptCF(number.leakRef()); return true; } case CFString: { RetainPtr<CFStringRef> string; if (!decode(decoder, string)) return false; result.adoptCF(string.leakRef()); return true; } case CFURL: { RetainPtr<CFURLRef> url; if (!decode(decoder, url)) return false; result.adoptCF(url.leakRef()); return true; } #if PLATFORM(MAC) case SecCertificate: { RetainPtr<SecCertificateRef> certificate; if (!decode(decoder, certificate)) return false; result.adoptCF(certificate.leakRef()); return true; } case SecKeychainItem: { RetainPtr<SecKeychainItemRef> keychainItem; if (!decode(decoder, keychainItem)) return false; result.adoptCF(keychainItem.leakRef()); return true; } #endif case Null: result = tokenNullTypeRef(); return true; case Unknown: ASSERT_NOT_REACHED(); return false; } return false; }