static int read_one_token(gss_name_t service, const char *ccname, int negotiate) { gss_cred_id_t cred = NULL; gss_cred_id_t deleg_creds = NULL; gss_name_t client; gss_OID mech_oid; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc in, out, dname; krb5_context kctx = NULL; krb5_ccache ccache = NULL; krb5_error_code kret; OM_uint32 maj, min; char *inbuf = NULL; char *tmp; char buf[65536]; int ret = 0; if (service) { maj = gss_acquire_cred(&min, service, 0, NULL, GSS_C_ACCEPT, &cred, NULL, NULL); GBAIL("gss_acquire_cred", maj, min); } inbuf = read_buffer(stdin); if (!inbuf) /* Just a couple of \n's in a row or EOF, not an error. */ return 0; tmp = inbuf; if (negotiate) { if (strncasecmp("Negotiate ", inbuf, 10)) { fprintf(stderr, "Token doesn't begin with " "\"Negotiate \"\n"); return -1; } tmp += 10; } in.length = base64_decode((uint8_t *)tmp, strlen(tmp), (uint8_t *)buf, sizeof(buf)); in.value = buf; out.length = 0; out.value = 0; maj = gss_accept_sec_context(&min, &ctx, cred, &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL, NULL, &deleg_creds); GBAIL("gss_accept_sec_context", maj, min); /* * XXXrcd: not bothering to clean up because we're about to exit. * Probably should fix this in case the code is used as * an example by someone. */ maj = gss_display_name(&min, client, &dname, NULL); GBAIL("gss_display_name", maj, min); if (!nflag) printf("Authenticated: %.*s\n", (int)dname.length, (char *)dname.value); if (ccname) { #ifdef HAVE_GSS_STORE_CRED_INTO gss_key_value_set_desc store; gss_key_value_element_desc elem; int overwrite_cred = 1; int default_cred = 0; elem.key = "ccache"; elem.value = ccname; store.count = 1; store.elements = &elem; maj = gss_store_cred_into(&min, deleg_creds, GSS_C_INITIATE, GSS_C_NO_OID, overwrite_cred, default_cred, &store, NULL, NULL); GBAIL("gss_store_cred_into", maj, min); #else K5BAIL(krb5_init_context(&kctx)); K5BAIL(krb5_cc_resolve(kctx, ccname, &ccache)); maj = gss_krb5_copy_ccache(&min, deleg_creds, ccache); GBAIL("gss_krb5_copy_ccache", maj, min); #endif } bail: if (kctx) krb5_free_context(kctx); if (ccache) krb5_cc_close(kctx, ccache); if (cred) gss_release_cred(&min, &cred); if (deleg_creds) gss_release_cred(&min, &deleg_creds); free(inbuf); return ret; }
bool confupdate_h(connection_t *c) { char updname[MAX_STRING_SIZE]; char rawconf[MAX_STRING_SIZE], b64conf[MAX_STRING_SIZE]; char rawdgst[MAX_STRING_SIZE], b64dgst[MAX_STRING_SIZE]; node_t *n; char *fname, *tname; FILE *fp; int x; size_t slen, dlen, rlen; RSA *updkey; /* Guard ourselves against updates */ if (ignorenetupdates() || ignoreconfupdates()) return true; if (sscanf(c->buffer, "%*d " MAX_STRING " " MAX_STRING " %zd %zd " MAX_STRING, updname, b64conf, &slen, &dlen, b64dgst) != 5) { logger(LOG_ERR, "Got bad %s from %s (%s)", "CONFUPDATE", c->name, c->hostname); return false; } if (dontverifyupdatepermission()) goto _next; if(!getconf_bool_node_offline(updname, "ConfFileMaster")) { ifdebug(PROTOCOL) logger(LOG_WARNING, "Ignoring config update request originating from %s [which came from %s (%s)]", updname, c->name, c->hostname); return true; } _next: if (!isvalidfname(updname)) { logger(LOG_ERR, "Got bogus updater name \"%s\" from %s (%s) (from: %s)", updname, c->name, c->hostname, updname); return false; } if (slen >= MAX_STRING_SIZE || dlen >= MAX_STRING_SIZE) { logger(LOG_ERR, "CONFUPDATE string sizes are bigger than buffer can fit (%zd, %zd)", slen, dlen); return false; } if (dontverifyupdatesignature()) goto _out; if (!read_rsa_public_key_offline(updname, &updkey)) { logger(LOG_ERR, "Could not find public key for %s", updname); return true; } base64_decode(b64dgst, rawdgst, sizeof(rawdgst)-1); snprintf(rawconf, sizeof(rawconf), "%s %s %zd %zd", updname, b64conf, slen, dlen); rlen = strlen(rawconf); if (!EVP_verify(updkey, rawdgst, dlen, rawconf, rlen)) { logger(LOG_WARNING, "Ignoring config update request with bad signature" " from %s [which came from %s (%s)]", updname, c->name, c->hostname); RSA_free(updkey); return true; } RSA_free(updkey); _out: if (!strcmp(updname, myself->name)) return true; if (!dontforwardconfupdates()) { exceptmasters = true; forward_request(c); } if (!strcmp(b64conf, "START")) { run_script("confupdate-before"); return true; } else if (!strcmp(b64conf, "END")) { run_script("confupdate-after"); schedulereload(); return true; } xasprintf(&fname, "%s/tinc.conf", confbase); fp = fopen(fname, "w"); if (!fp) { logger(LOG_ERR, "Could not update %s: %s", fname, strerror(errno)); free(fname); return true; } /* Save variables which are sensitive */ for (x = 0; confvarstopreserve[x]; x++) { if(get_config_string(lookup_config(config_tree, confvarstopreserve[x]), &tname)) { fprintf(fp, "%s = %s\n", confvarstopreserve[x], tname); free(tname); } } /* Decode and append our template */ base64_decode(b64conf, rawconf, sizeof(rawconf)-1); fwrite(rawconf, slen, 1, fp); fclose(fp); free(fname); return true; }
void Map::LoadLayer(const unsigned char* bLayer, int layerID) { //Décompression base64 size_t out = 0; unsigned char* data = base64_decode(bLayer, strlen((const char*)bLayer), &out); int cptx, cpty; cptx = 0; cpty = 0; int gid, tx, ty; int max = 0; for(int i = 0; i < out; i += 4) { gid = data[i] | data[i + 1] << 8 | data[i + 2] << 16 | data[i + 3] << 24; if(layerID == 0) { gid -= 1; ty = (gid)>>4; tx = (gid)%16; //tx = gid-(tx<<4); //Vérification de tiles spécial entités if(tx == 1 && ty == 0) { //Gemme worldMan->LoadEntity("gemme", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 0, 0, 0); tx = ty = 0; } else if(tx == 2 && ty == 0) { //Gemme worldMan->LoadEntity("fullstar", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 0, 0, 0); tx = ty = 0; } else if(tx == 3 && ty == 0) { //Peaks vers le haut worldMan->LoadEntity("peaks", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 0, 0, 0); tx = ty = 0; } if(tx == 4 && ty == 0) { //Gemme worldMan->LoadEntity("dbloc", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 0, 0, 0); tx = ty = 0; } else if(tx == 6 && ty == 0) { //Gemme worldMan->LoadEntity("womie", (cptx*16), (cpty*16), 16, 16, 0, 0, 0); tx = ty = 0; } else if(tx == 7 && ty == 0) { //Gemme worldMan->LoadEntity("wopic", (cptx*16), (cpty*16), 16, 16, 0, 0, 0); tx = ty = 0; } else if(tx == 8 && ty == 0) { //Gemme worldMan->LoadEntity("extralife", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 0, 0, 0); tx = ty = 0; } else if(tx == 9 && ty == 0) { //Peaks vers le bas worldMan->LoadEntity("peaks", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 1, 0, 0); tx = ty = 0; } else if(tx == 10 && ty == 0) { //Peaks vers le bas worldMan->LoadEntity("peaks", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 2, 0, 0); tx = ty = 0; } else if(tx == 11 && ty == 0) { //Peaks vers le bas worldMan->LoadEntity("peaks", (cptx*16)<<8, (cpty*16)<<8, 16, 16, 3, 0, 0); tx = ty = 0; } } if(layerID == 3) { gid -= 257; ty = (gid)/8; tx = (gid)%8; } /*if(layerID == 3) { if(gid != 0) { ulDebug("gid : %d - tx : %d , ty : %d\n", gid, tx, ty); } }*/ sMapArray[layerID * (mMapWidthHeight) + (cptx * mMapHeight) + cpty] = MakeTile(tx, ty, 0, 0, 0); if(max < layerID * (mMapWidthHeight) + (cptx * mMapHeight) + cpty) max = layerID * (mMapWidthHeight) + (cptx * mMapHeight) + cpty; cptx++; if(cptx > mMapWidth-1) { cptx = 0; cpty++; } }
/* AUTH LOGIN method base64-encodes both prompts and credentials. For example: AUTH LOGIN + VXNlcm5hbWU6 (Username:) Zm9v (foo) + UGFzc3dvcmQ6 (Password:) YmFy (bar) */ int sendAuthLOGIN(int hSocket, _MODULE_DATA* _psSessionData, char* szLogin, char* szPassword) { unsigned char* bufReceive = NULL; unsigned char* bufSend = NULL; unsigned char* szPrompt = NULL; unsigned char* szTmpBuf = NULL; int nSendBufferSize = 0; int nReceiveBufferSize = 0; int nRet = SUCCESS; writeError(ERR_DEBUG_MODULE, "[%s] Initiating LOGIN Authentication Attempt.", MODULE_NAME); /* --- Send initial AUTH LOGIN command --- */ bufSend = malloc(12 + 1); memset(bufSend, 0, 12 + 1); sprintf(bufSend, "AUTH LOGIN\r\n"); if (medusaSend(hSocket, bufSend, strlen(bufSend), 0) < 0) { writeError(ERR_ERROR, "[%s] Failed: medusaSend was not successful", MODULE_NAME); } FREE(bufSend); /* Server should respond with a base64-encoded username prompt */ nReceiveBufferSize = 0; if ((medusaReceiveRegex(hSocket, &bufReceive, &nReceiveBufferSize, "\\+ .*\r\n|-ERR.*\r\n") == FAILURE) || (bufReceive == NULL)) { writeError(ERR_ERROR, "[%s] POP3 server did not respond with \"+ \" to AUTH LOGIN request.", MODULE_NAME); return FAILURE; } else if (strstr(bufReceive,"-ERR The specified authentication package is not supported.") != NULL) { writeError(ERR_ERROR, "[%s] Server response: The specified authentication package is not supported.", MODULE_NAME); return FAILURE; } szTmpBuf = ((char*)index(bufReceive, '\r')); szTmpBuf[0] = '\0'; szPrompt = malloc(strlen(bufReceive + 2) + 1); memset(szPrompt, 0, strlen(bufReceive + 2) + 1); base64_decode(bufReceive + 2, szPrompt); FREE(bufReceive); writeError(ERR_DEBUG_MODULE, "[%s] POP3 server sent the following prompt: %s", MODULE_NAME, szPrompt); FREE(szPrompt); /* --- Send username --- */ /* Base64 encoded value can be up to 2x+2 original text. Leave additional space for "\r\n" and NULL */ bufSend = malloc((2 * strlen(szLogin) + 2) + 2 + 1); memset(bufSend, 0, (2 * strlen(szLogin) + 2) + 2 + 1); base64_encode(szLogin, strlen(szLogin), bufSend); strncat(bufSend, "\r\n", 2); if (medusaSend(hSocket, bufSend, strlen(bufSend), 0) < 0) { writeError(ERR_ERROR, "[%s] Failed: medusaSend was not successful", MODULE_NAME); } /* Server should respond with a base64-encoded password prompt */ nReceiveBufferSize = 0; if ((medusaReceiveRegex(hSocket, &bufReceive, &nReceiveBufferSize, "\\+ .*\r\n") == FAILURE) || (bufReceive == NULL)) { writeError(ERR_ERROR, "[%s] POP3 server did not respond with \"+ \" to AUTH LOGIN request.", MODULE_NAME); return FAILURE; } szTmpBuf = ((char*)index(bufReceive, '\r')); szTmpBuf[0] = '\0'; szPrompt = malloc(strlen(bufReceive + 2) + 1); memset(szPrompt, 0, strlen(bufReceive + 2) + 1); base64_decode(bufReceive + 2, szPrompt); FREE(bufReceive); writeError(ERR_DEBUG_MODULE, "[%s] POP3 server sent the following prompt: %s", MODULE_NAME, szPrompt); FREE(szPrompt); /* --- Send password --- */ /* Base64 encoded value can be up to 2x+2 original text. Leave additional space for "\r\n" and NULL */ bufSend = malloc((2 * strlen(szPassword) + 2) + 2 + 1); memset(bufSend, 0, (2 * strlen(szPassword) + 2) + 2 + 1); base64_encode(szPassword, strlen(szPassword), bufSend); strncat(bufSend, "\r\n", 2); if (medusaSend(hSocket, bufSend, strlen(bufSend), 0) < 0) { writeError(ERR_ERROR, "[%s] Failed: medusaSend was not successful", MODULE_NAME); } return SUCCESS; }
void MementoAppServerTsx::on_in_dialog_request(pjsip_msg* req) { TRC_DEBUG("Mememto processing an in_dialog_request"); // Get the dialog id. It has the format: // <YYYYMMDDHHMMSS>_<unique_id>_<base64 encoded impu> std::string dialogid = dialog_id(); // Pull out the timestamp, id and IMPU. std::vector<std::string> dialog_values; Utils::split_string(dialogid, '_', dialog_values, 3, false); if (dialog_values.size() != 3) { // LCOV_EXCL_START TRC_WARNING("Invalid dialog ID (%s)", dialogid.c_str()); send_request(req); return; // LCOV_EXCL_STOP } std::string timestamp = dialog_values[0]; _unique_id = dialog_values[1]; _impu = base64_decode(dialog_values[2]); // Create the XML. XML should be of the form: // <end-time><current time></end-time> // Get the current time time_t currenttime; time(¤ttime); tm* ct = localtime(¤ttime); // Create the XML rapidxml::xml_document<> doc; std::string end_timestamp = create_formatted_timestamp(ct, XML_PATTERN); rapidxml::xml_node<>* root = doc.allocate_node( rapidxml::node_element, MementoXML::END_TIME, doc.allocate_string(end_timestamp.c_str())); doc.append_node(root); char contents[MAX_CALL_ENTRY_LENGTH] = {0}; char* end = rapidxml::print(contents, doc); *end = 0; // Write the call list entry to the call list store. SAS::Event event(trail(), SASEvent::CALL_LIST_END_FRAGMENT, 0); SAS::report_event(event); _call_list_store_processor->write_call_list_entry( _impu, timestamp, _unique_id, CallListStore::CallFragment::Type::END, contents, trail()); send_request(req); }
void sendNicks(int sd, char *buff) { char email[GP_EMAIL_LEN]; char pass[GP_PASSWORD_LEN]; char query[1024]; char gamename[32]; bool sendUnique = false; if(!find_param("email", buff, email, sizeof(email))) { sendError(sd,"Error recieving request"); return; } if(find_param("gamename", buff, gamename, sizeof(gamename))) { sendUnique = true;//just assume you want it sent } if(!find_param("pass", buff, pass, sizeof(pass))) { if(!find_param("passenc",buff,pass,sizeof(pass))) { sendError(sd,"Error recieving request"); return; } else { char *dpass; int passlen = strlen(pass); dpass = (char *)base64_decode((uint8_t *)pass, &passlen); passlen = gspassenc((uint8_t *)dpass); strcpy(pass,dpass); free(dpass); } } mysql_real_escape_string(conn,email,email,strlen(email)); mysql_real_escape_string(conn,pass,pass,strlen(pass)); sprintf_s(query,sizeof(query),"SELECT `nick`,`uniquenick` FROM `GameTracker`.`users` INNER JOIN `GameTracker`.`profiles` ON `GameTracker`.`profiles`.`userid` = `GameTracker`.`users`.`userid` WHERE `GameTracker`.`users`.`email` = '%s' AND `password` = '%s'",email,pass); if (mysql_query(conn, query)) { fprintf(stderr, "%s\n", mysql_error(conn)); return; } res = mysql_store_result(conn); char *sendmsg; char namestr[256]; int num_rows = mysql_num_rows(res); if(num_rows == 0) { formatSend(sd,true,0,"\\nr\\\\ndone\\"); return; } int len = 1024; sendmsg = (char *)malloc(len); memset((void *)sendmsg,0,len); sprintf_s(sendmsg,len,"\\nr\\%d",num_rows); while ((row = mysql_fetch_row(res)) != NULL) { sprintf_s(namestr,sizeof(namestr),"\\nick\\%s",row[0]); strncat(sendmsg,namestr,strlen(namestr)%len); if(sendUnique) { sprintf_s(namestr,sizeof(namestr),"\\uniquenick\\%s",row[1]); strncat(sendmsg,namestr,strlen(namestr)%len); } if(strlen(sendmsg)>(len/2)) { len *= 2; sendmsg = (char *)realloc(sendmsg,len); } } strcat(sendmsg,"\\ndone\\"); formatSend(sd,true,0,"%s",sendmsg); mysql_free_result(res); free((void *)sendmsg); }
/* * variable_set() * * ustawia warto¶æ podanej zmiennej. je¶li to zmienna liczbowa lub boolowska, * zmienia ci±g na liczbê. w przypadku boolowskich, rozumie zwroty typu `on', * `off', `yes', `no' itp. je¶li dana zmienna jest bitmap±, akceptuje warto¶æ * w postaci listy flag oraz konstrukcje `+flaga' i `-flaga'. * * - name - nazwa zmiennej, * - value - nowa warto¶æ, * - allow_foreign - czy ma pozwalaæ dopisywaæ obce zmienne. */ int variable_set(const char *name, const char *value, int allow_foreign) { struct variable *v = variable_find(name); if (!v && allow_foreign) { variable_add(name, "##", VAR_FOREIGN, 2, xstrdup(value), NULL, NULL, NULL); return -1; } if (!v && !allow_foreign) return -1; switch (v->type) { case VAR_INT: case VAR_MAP: { const char *p = value; int hex, tmp; if (!value) return -2; if (v->map && v->type == VAR_INT && !xisdigit(*p)) { int i; for (i = 0; v->map[i].label; i++) if (!strcasecmp(v->map[i].label, value)) value = itoa(v->map[i].value); } if (v->map && v->type == VAR_MAP && !xisdigit(*p)) { int i, k = *(int*)(v->ptr); int mode = 0; /* 0 set, 1 add, 2 remove */ char **args; if (*p == '+') { mode = 1; p++; } else if (*p == '-') { mode = 2; p++; } if (!mode) k = 0; args = array_make(p, ",", 0, 1, 0); for (i = 0; args[i]; i++) { int j, found = 0; for (j = 0; v->map[j].label; j++) { if (!strcasecmp(args[i], v->map[j].label)) { found = 1; if (mode == 2) k &= ~(v->map[j].value); if (mode == 1) k &= ~(v->map[j].conflicts); if (mode == 1 || !mode) k |= v->map[j].value; } } if (!found) { array_free(args); return -2; } } array_free(args); value = itoa(k); } p = value; if ((hex = !strncasecmp(p, "0x", 2))) p += 2; while (*p && *p != ' ') { if (hex && !xisxdigit(*p)) return -2; if (!hex && !xisdigit(*p)) return -2; p++; } tmp = strtol(value, NULL, 0); if (v->map) { int i; for (i = 0; v->map[i].label; i++) { if ((tmp & v->map[i].value) && (tmp & v->map[i].conflicts)) return -2; } } *(int*)(v->ptr) = tmp; if (v->notify) (v->notify)(v->name); if (ui_event) ui_event("variable_changed", v->name); return 0; } case VAR_BOOL: { int tmp; if (!value) return -2; if ((tmp = on_off(value)) == -1) return -2; *(int*)(v->ptr) = tmp; if (v->notify) (v->notify)(v->name); if (ui_event) ui_event("variable_changed", v->name); return 0; } case VAR_STR: { char **tmp = (char**)(v->ptr); xfree(*tmp); if (value) { if (*value == 1) *tmp = base64_decode(value + 1); else *tmp = xstrdup(value); } else *tmp = NULL; if (v->notify) (v->notify)(v->name); if (ui_event) ui_event("variable_changed", v->name); return 0; } } return -1; }
int main () { int nbytes; char * rawstr = "Once upon a midnight dreary as I pondered weak and weary I heard a rapping tap tap tapping at my parlor door."; char * codedstr = "T25jZSB1cG9uIGEgbWlkbmlnaHQgZHJlYXJ5IGFzIEkgcG9uZGVyZWQgd2VhayBhbmQgd2Vhcnkg\r\nSSBoZWFyZCBhIHJhcHBpbmcgdGFwIHRhcCB0YXBwaW5nIGF0IG15IHBhcmxvciBkb29yLg=="; unsigned char * resultstr; struct session mysession; char source[] = "*****@*****.**"; char dest[256]; unsigned char *foo, *bar; int i; mysession.malloc = malloc; mysession.free = free; printf("encode test: "); resultstr = base64_encode(&mysession, rawstr, strlen(rawstr)); if (resultstr && !bcmp(resultstr, codedstr, strlen(codedstr))) { free(resultstr); printf("passed\n"); } else { printf("FAILED'\n"); } printf("decode test: "); nbytes = base64_decode(&mysession, codedstr, &resultstr); if (nbytes > 0 && !bcmp(resultstr, rawstr, strlen(rawstr))) { free(resultstr); printf("passed\n"); } else { printf("FAILED'\n"); } printf("detect length error: "); nbytes = base64_decode(&mysession, "AA", &resultstr); if (-2 == nbytes) { printf("passed\n"); } else { printf("FAILED\n"); } printf("detect coding error: "); nbytes = base64_decode(&mysession, "A}}A", &resultstr); if (-2 == nbytes) { printf("passed\n"); } else { printf("FAILED\n"); } printf("detect trailers error: "); nbytes = base64_decode(&mysession, "A===", &resultstr); if (-2 == nbytes) { printf("passed\n"); } else { printf("FAILED\n"); } resultstr = "aa=="; nbytes = 1; printf("base64_dsize: of '%s' should be %d: actually %d\n", resultstr, nbytes, base64_dsize(resultstr)); resultstr = "aaa="; nbytes = 2; printf("base64_dsize: of '%s' should be %d: actually %d\n", resultstr, nbytes, base64_dsize(resultstr)); resultstr = "aaaa"; nbytes = 3; printf("base64_dsize: of '%s' should be %d: actually %d\n", resultstr, nbytes, base64_dsize(resultstr)); nbytes = 1; printf("base64_esize: of %d should be %d: actually %d\n", nbytes, 4, base64_esize(nbytes)); nbytes = 2; printf("base64_esize: of %d should be %d: actually %d\n", nbytes, 4, base64_esize(nbytes)); nbytes = 3; printf("base64_esize: of %d should be %d: actually %d\n", nbytes, 4, base64_esize(nbytes)); /* * incremental test and print. */ memset(dest, 0, 256); for (i = 0; i < 10; i++) { dest[i] = source[i]; foo = base64_encode(&mysession, dest, i+1); base64_decode(&mysession, foo, &bar); printf("\tinput=`%s` encoded=`%s` decoded=`%s`\n", dest, foo, bar); free(foo); free(bar); } foo = base64_encode(&mysession, rawstr, strlen(rawstr)); base64_decode(&mysession, foo, &bar); printf("\tinput=`%s` encoded=`%s` decoded=`%s`\n", dest, foo, bar); free(foo); free(bar); /* * done-zies */ exit(0); }
static bool fetch_data_process(struct fetch_data_context *c) { fetch_msg msg; char *params; char *comma; char *unescaped; int templen; /* format of a data: URL is: * data:[<mimetype>][;base64],<data> * The mimetype is optional. If it is missing, the , before the * data must still be there. */ LOG(("url: %.140s", c->url)); if (strlen(c->url) < 6) { /* 6 is the minimum possible length (data:,) */ msg.type = FETCH_ERROR; msg.data.error = "Malformed data: URL"; fetch_data_send_callback(&msg, c); return false; } /* skip the data: part */ params = c->url + SLEN("data:"); /* find the comma */ if ( (comma = strchr(params, ',')) == NULL) { msg.type = FETCH_ERROR; msg.data.error = "Malformed data: URL"; fetch_data_send_callback(&msg, c); return false; } if (params[0] == ',') { /* there is no mimetype here, assume text/plain */ c->mimetype = strdup("text/plain;charset=US-ASCII"); } else { /* make a copy of everything between data: and the comma */ c->mimetype = strndup(params, comma - params); } if (c->mimetype == NULL) { msg.type = FETCH_ERROR; msg.data.error = "Unable to allocate memory for mimetype in data: URL"; fetch_data_send_callback(&msg, c); return false; } if (strcmp(c->mimetype + strlen(c->mimetype) - 7, ";base64") == 0) { c->base64 = true; c->mimetype[strlen(c->mimetype) - 7] = '\0'; } else { c->base64 = false; } /* we URL unescape the data first, just incase some insane page * decides to nest URL and base64 encoding. Like, say, Acid2. */ templen = c->datalen; unescaped = curl_easy_unescape(curl, comma + 1, 0, &templen); c->datalen = templen; if (unescaped == NULL) { msg.type = FETCH_ERROR; msg.data.error = "Unable to URL decode data: URL"; fetch_data_send_callback(&msg, c); return false; } if (c->base64) { c->data = malloc(c->datalen); /* safe: always gets smaller */ if (base64_decode(unescaped, c->datalen, c->data, &(c->datalen)) == false) { msg.type = FETCH_ERROR; msg.data.error = "Unable to Base64 decode data: URL"; fetch_data_send_callback(&msg, c); curl_free(unescaped); return false; } } else { c->data = malloc(c->datalen); if (c->data == NULL) { msg.type = FETCH_ERROR; msg.data.error = "Unable to allocate memory for data: URL"; fetch_data_send_callback(&msg, c); curl_free(unescaped); return false; } memcpy(c->data, unescaped, c->datalen); } curl_free(unescaped); return true; }
bool game::opening_screen() { std::map<std::string, WORLDPTR> worlds; if (world_generator) { world_generator->set_active_world(NULL); worlds = world_generator->get_all_worlds(); } WINDOW *w_background = newwin(TERMY, TERMX, 0, 0); werase(w_background); wrefresh(w_background); // main window should also expand to use available display space. // expanding to evenly use up half of extra space, for now. int extra_w = ((TERMX - FULL_SCREEN_WIDTH) / 2) - 1; int extra_h = ((TERMY - FULL_SCREEN_HEIGHT) / 2) - 1; extra_w = (extra_w > 0 ? extra_w : 0); extra_h = (extra_h > 0 ? extra_h : 0); const int total_w = FULL_SCREEN_WIDTH + extra_w; const int total_h = FULL_SCREEN_HEIGHT + extra_h; // position of window within main display const int x0 = (TERMX - total_w) / 2; const int y0 = (TERMY - total_h) / 2; WINDOW *w_open = newwin(total_h, total_w, y0, x0); const int iMenuOffsetX = 2; int iMenuOffsetY = total_h - 3; std::vector<std::string> vSubItems; vSubItems.push_back(pgettext("Main Menu|New Game", "<C>ustom Character")); vSubItems.push_back(pgettext("Main Menu|New Game", "<P>reset Character")); vSubItems.push_back(pgettext("Main Menu|New Game", "<R>andom Character")); vSubItems.push_back(pgettext("Main Menu|New Game", "Play <N>ow!")); std::vector<std::string> vWorldSubItems; vWorldSubItems.push_back(pgettext("Main Menu|World", "<C>reate World")); vWorldSubItems.push_back(pgettext("Main Menu|World", "<D>elete World")); vWorldSubItems.push_back(pgettext("Main Menu|World", "<R>eset World")); print_menu(w_open, 0, iMenuOffsetX, iMenuOffsetY); std::vector<std::string> savegames, templates; dirent *dp; DIR *dir; dir = opendir("save"); if (!dir){ #if (defined _WIN32 || defined __WIN32__) mkdir("save"); #else mkdir("save", 0777); #endif dir = opendir("save"); } if (!dir) { dbg(D_ERROR) << "game:opening_screen: Unable to make save directory."; debugmsg("Could not make './save' directory"); endwin(); exit(1); } closedir(dir); dir = opendir("data"); while ((dp = readdir(dir))) { std::string tmp = dp->d_name; if (tmp.find(".template") != std::string::npos) { templates.push_back(tmp.substr(0, tmp.find(".template"))); } } closedir(dir); int sel1 = 1, sel2 = 1, sel3 = 1, layer = 1; InputEvent input; int chInput; bool start = false; // Load MOTD and store it in a string // Only load it once, it shouldn't change for the duration of the application being open static std::vector<std::string> motd; if (motd.empty()) { std::ifstream motd_file; motd_file.open("data/motd"); if (!motd_file.is_open()) { motd.push_back(_("No message today.")); } else { while (!motd_file.eof()) { std::string tmp; getline(motd_file, tmp); if (!tmp.length() || tmp[0] != '#') { motd.push_back(tmp); } } } } // Load Credits and store it in a string // Only load it once, it shouldn't change for the duration of the application being open static std::vector<std::string> credits; if (credits.empty()) { std::ifstream credits_file; credits_file.open("data/credits"); if (!credits_file.is_open()) { credits.push_back(_("No message today.")); } else { while (!credits_file.eof()) { std::string tmp; getline(credits_file, tmp); if (!tmp.length() || tmp[0] != '#') { credits.push_back(tmp); } } } } u = player(); while(!start) { if (layer == 1) { print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY, (sel1 == 0 || sel1 == 7) ? false : true); if (sel1 == 0) { // Print the MOTD. for (int i = 0; i < motd.size() && i < 16; i++) { mvwprintz(w_open, i + 6, 8 + extra_w / 2, c_ltred, motd[i].c_str()); } wrefresh(w_open); refresh(); } else if (sel1 == 7) { // Print the Credits. for (int i = 0; i < credits.size() && i < 16; i++) { mvwprintz(w_open, i + 6, 8 + extra_w / 2, c_ltred, credits[i].c_str()); } wrefresh(w_open); refresh(); } chInput = getch(); if (chInput == 'm' || chInput == 'M') { // MOTD sel1 = 0; chInput = '\n'; } else if (chInput == 'n' || chInput == 'N') { // New Game sel1 = 1; chInput = '\n'; } else if (chInput == 'a' || chInput == 'A') { // Load Game sel1 = 2; chInput = '\n'; } else if (chInput == 'w' || chInput == 'W') { // World sel1 = 3; chInput = '\n'; } else if (chInput == 's' || chInput == 'S') { // Special Game sel1 = 4; chInput = '\n'; } else if (chInput == 'o' || chInput == 'O') { // Options sel1 = 5; chInput = '\n'; } else if (chInput == 'e' || chInput == 'E' || chInput == '?') { // Help sel1 = 6; chInput = '\n'; } else if (chInput == 'c' || chInput == 'C') { // Credits sel1 = 7; chInput = '\n'; } else if (chInput == 'q' || chInput == 'Q' || chInput == KEY_ESCAPE) { // Quit sel1 = 8; chInput = '\n'; } if (chInput == KEY_LEFT || chInput == 'h') { if (sel1 > 0) { sel1--; } else { sel1 = 8; } } else if (chInput == KEY_RIGHT || chInput == 'l') { if (sel1 < 8) { sel1++; } else { sel1 = 0; } } else if ((chInput == KEY_UP || chInput == 'k' || chInput == '\n') && sel1 > 0 && sel1 != 7) { if (sel1 == 5) { show_options(); } else if (sel1 == 6) { display_help(); } else if (sel1 == 8) { uquit = QUIT_MENU; delwin(w_open); delwin(w_background); return false; } else { sel2 = 0; layer = 2; print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY, (sel1 == 0 || sel1 == 7) ? false : true); } } } else if (layer == 2) { if (sel1 == 1) { // New Character print_menu_items(w_open, vSubItems, sel2, iMenuOffsetY - 2, iMenuOffsetX); wrefresh(w_open); refresh(); chInput = getch(); if (chInput == 'c' || chInput == 'C') { sel2 = 0; chInput = '\n' ; } else if (chInput == 'p' || chInput == 'P') { sel2 = 1; chInput = '\n'; } else if (chInput == 'r' || chInput == 'R') { sel2 = 2; chInput = '\n'; } else if (chInput == 'n' || chInput == 'N') { sel2 = 3; chInput = '\n'; } if (chInput == KEY_LEFT || chInput == 'h') { sel2--; if (sel2 < 0) { sel2 = vSubItems.size() - 1; } } if (chInput == KEY_RIGHT || chInput == 'l') { sel2++; if (sel2 >= vSubItems.size()) { sel2 = 0; } } else if (chInput == KEY_DOWN || chInput == 'j' || chInput == KEY_ESCAPE) { layer = 1; sel1 = 1; } if (chInput == KEY_UP || chInput == 'k' || chInput == '\n') { if (sel2 == 0 || sel2 == 2 || sel2 == 3) { setup(); if (!u.create((sel2 == 0) ? PLTYPE_CUSTOM : ((sel2 == 2) ? PLTYPE_RANDOM : PLTYPE_NOW))) { u = player(); delwin(w_open); return (opening_screen()); } // Pick a world, supressing prompts if it's "play now" mode. WORLDPTR world = world_generator->pick_world( sel2 != 3 ); if (!world) { u = player(); delwin(w_open); return opening_screen(); } else { world_generator->set_active_world(world); } werase(w_background); wrefresh(w_background); load_artifacts(world->world_path + "/artifacts.gsav", itypes); MAPBUFFER.load(world->world_name); start_game(world->world_name); start = true; } else if (sel2 == 1) { layer = 3; sel3 = 0; } } } else if (sel1 == 2) { // Load Character if (world_generator->all_worldnames.empty()) { mvwprintz(w_open, iMenuOffsetY - 2, 15 + iMenuOffsetX + extra_w / 2, c_red, _("No Worlds found!")); } else { for (int i = 0; i < world_generator->all_worldnames.size(); ++i) { int line = iMenuOffsetY - 2 - i; std::string world_name = world_generator->all_worldnames[i]; int savegames_count = world_generator->all_worlds[world_name]->world_saves.size(); mvwprintz(w_open, line, 15 + iMenuOffsetX + extra_w / 2, (sel2 == i ? h_white : c_white), "%s (%d)", world_name.c_str(), savegames_count); } } wrefresh(w_open); refresh(); input = get_input(); if (world_generator->all_worldnames.empty() && (input == DirectionS || input == Confirm)) { layer = 1; } else if (input == DirectionS) { if (sel2 > 0) { sel2--; } else { sel2 = world_generator->all_worldnames.size() - 1; } } else if (input == DirectionN) { if (sel2 < world_generator->all_worldnames.size() - 1) { sel2++; } else { sel2 = 0; } } else if (input == DirectionW || input == Cancel) { layer = 1; } if (input == DirectionE || input == Confirm) { if (sel2 >= 0 && sel2 < world_generator->all_worldnames.size()) { layer = 3; sel3 = 0; } } } else if (sel1 == 3) { // World Menu // Show options for Create, Destroy, Reset worlds. // Create world goes directly to Make World screen. // Reset and Destroy ask for world to modify. // Reset empties world of everything but options, then makes new world within it. // Destroy asks for confirmation, then destroys everything in world and then removes world folder. // only show reset / destroy world if there is at least one valid world existing! int world_subs_to_display = (world_generator->all_worldnames.size() > 0)? vWorldSubItems.size(): 1; std::vector<std::string> world_subs; int xoffset = 25 + iMenuOffsetX + extra_w / 2; int yoffset = iMenuOffsetY - 2; int xlen = 0; for (int i = 0; i < world_subs_to_display; ++i) { world_subs.push_back(vWorldSubItems[i]); xlen += vWorldSubItems[i].size() + 2; // Open and close brackets added } xlen += world_subs.size() - 1; if (world_subs.size() > 1) { xoffset -= 6; } print_menu_items(w_open, world_subs, sel2, yoffset, xoffset - (xlen / 4)); wrefresh(w_open); refresh(); input = get_input(); if (input == DirectionW) { if (sel2 > 0) { --sel2; } else { sel2 = world_subs_to_display - 1; } } else if (input == DirectionE) { if (sel2 < world_subs_to_display - 1) { ++sel2; } else { sel2 = 0; } } else if (input == DirectionS || input == Cancel) { layer = 1; } if (input == DirectionN || input == Confirm) { if (sel2 == 0) { // Create world // Open up world creation screen! if (world_generator->make_new_world()) { return opening_screen(); } else { layer = 1; } } else if (sel2 == 1 || sel2 == 2) { // Delete World | Reset World layer = 3; sel3 = 0; } } } else if (sel1 == 4) { // Special game std::vector<std::string> special_names; int xoffset = 32 + iMenuOffsetX + extra_w / 2; int yoffset = iMenuOffsetY - 2; int xlen = 0; for (int i = 1; i < NUM_SPECIAL_GAMES; i++) { std::string spec_name = special_game_name(special_game_id(i)); special_names.push_back(spec_name); xlen += spec_name.size() + 2; } xlen += special_names.size() - 1; print_menu_items(w_open, special_names, sel2, yoffset, xoffset - (xlen / 4)); wrefresh(w_open); refresh(); input = get_input(); if (input == DirectionW) { if (sel2 > 0) { sel2--; } else { sel2 = NUM_SPECIAL_GAMES - 2; } } else if (input == DirectionE) { if (sel2 < NUM_SPECIAL_GAMES - 2) { sel2++; } else { sel2 = 0; } } else if (input == DirectionS || input == Cancel) { layer = 1; } if (input == DirectionN || input == Confirm) { if (sel2 >= 0 && sel2 < NUM_SPECIAL_GAMES - 1) { delete gamemode; gamemode = get_special_game( special_game_id(sel2 + 1) ); // check world WORLDPTR world = world_generator->make_new_world(special_game_id(sel2 + 1)); if (world) { world_generator->set_active_world(world); setup(); } if (world == NULL || !gamemode->init()) { delete gamemode; gamemode = new special_game; u = player(); delwin(w_open); return (opening_screen()); } load_artifacts(world->world_path + "/artifacts.gsav", itypes); start = true; } } } } else if (layer == 3) { if (sel1 == 2) { // Load Game savegames = world_generator->all_worlds[world_generator->all_worldnames[sel2]]->world_saves; if (savegames.empty()) { mvwprintz(w_open, iMenuOffsetY - 2, 19 + 19 + iMenuOffsetX + extra_w / 2, c_red, _("No save games found!")); } else { for (int i = 0; i < savegames.size(); i++) { int line = iMenuOffsetY - 2 - i; mvwprintz(w_open, line, 19 + 19 + iMenuOffsetX + extra_w / 2, (sel3 == i ? h_white : c_white), base64_decode(savegames[i]).c_str()); } } wrefresh(w_open); refresh(); input = get_input(); if (savegames.size() == 0 && (input == DirectionS || input == Confirm)) { layer = 2; } else if (input == DirectionS) { if (sel3 > 0) { sel3--; } else { sel3 = savegames.size() - 1; } } else if (input == DirectionN) { if (sel3 < savegames.size() - 1) { sel3++; } else { sel3 = 0; } } else if (input == DirectionW || input == Cancel) { layer = 2; sel3 = 0; print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY); } if (input == DirectionE || input == Confirm) { if (sel3 >= 0 && sel3 < savegames.size()) { werase(w_background); wrefresh(w_background); WORLDPTR world = world_generator->all_worlds[world_generator->all_worldnames[sel2]]; world_generator->set_active_world(world); load_artifacts(world->world_path + "/artifacts.gsav", itypes); MAPBUFFER.load(world->world_name); setup(); load(world->world_name, savegames[sel3]); start = true; } } } else if (sel1 == 3) { // Show world names int i = 0; for (std::vector<std::string>::iterator it = world_generator->all_worldnames.begin(); it != world_generator->all_worldnames.end(); ++it) { int savegames_count = world_generator->all_worlds[*it]->world_saves.size(); int line = iMenuOffsetY - 4 - i; mvwprintz(w_open, line, 26 + iMenuOffsetX + extra_w / 2, (sel3 == i ? h_white : c_white), "%s (%d)", (*it).c_str(), savegames_count); ++i; } wrefresh(w_open); refresh(); input = get_input(); if (input == DirectionS) { if (sel3 > 0) { --sel3; } else { sel3 = world_generator->all_worldnames.size() - 1; } } else if (input == DirectionN) { if (sel3 < world_generator->all_worldnames.size() - 1) { ++sel3; } else { sel3 = 0; } } else if (input == DirectionW || input == Cancel) { layer = 2; print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY); } if (input == DirectionE || input == Confirm) { if (sel3 >= 0 && sel3 < world_generator->all_worldnames.size()) { bool query_yes = false; bool do_delete = false; if (sel2 == 1) { // Delete World if (query_yn(_("Delete the world and all saves?"))) { query_yes = true; do_delete = true; } } else if (sel2 == 2) { // Reset World if (query_yn(_("Remove all saves and regenerate world?"))) { query_yes = true; do_delete = false; } } if (query_yes) { delete_world(world_generator->all_worldnames[sel3], do_delete); savegames.clear(); MAPBUFFER.reset(); MAPBUFFER.make_volatile(); overmap_buffer.clear(); layer = 2; if (do_delete) { // delete world and all contents world_generator->remove_world(world_generator->all_worldnames[sel3]); } else { // clear out everything but worldoptions from this world world_generator->all_worlds[world_generator->all_worldnames[sel3]]->world_saves.clear(); } if (world_generator->all_worldnames.size() == 0) { sel2 = 0; // reset to create world selection } } else { // hacky resolution to the issue of persisting world names on the screen return opening_screen(); } } print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY); } } else { // Character Templates if (templates.size() == 0) { mvwprintz(w_open, iMenuOffsetY - 4, iMenuOffsetX + 20 + extra_w / 2, c_red, _("No templates found!")); } else { for (int i = 0; i < templates.size(); i++) { int line = iMenuOffsetY - 4 - i; mvwprintz(w_open, line, 20 + iMenuOffsetX + extra_w / 2, (sel3 == i ? h_white : c_white), templates[i].c_str()); } } wrefresh(w_open); refresh(); input = get_input(); if (input == DirectionS) { if (sel3 > 0) { sel3--; } else { sel3 = templates.size() - 1; } } else if (templates.size() == 0 && (input == DirectionN || input == Confirm)) { sel1 = 1; layer = 2; print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY); } else if (input == DirectionN) { if (sel3 < templates.size() - 1) { sel3++; } else { sel3 = 0; } } else if (input == DirectionW || input == Cancel || templates.size() == 0) { sel1 = 1; layer = 2; print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY); } else if (input == DirectionE || input == Confirm) { setup(); if (!u.create(PLTYPE_TEMPLATE, templates[sel3])) { u = player(); delwin(w_open); return (opening_screen()); } // check world WORLDPTR world = world_generator->pick_world(); if (!world) { u = player(); delwin(w_open); return (opening_screen()); } else { world_generator->set_active_world(world); } werase(w_background); wrefresh(w_background); std::string artfilename = world_generator->active_world->world_path + "/artifacts.gsav"; load_artifacts(artfilename, itypes); MAPBUFFER.load(world_generator->active_world->world_name); start_game(world_generator->active_world->world_name); start = true; } } } } delwin(w_open); delwin(w_background); if (start == false) { uquit = QUIT_MENU; } else { refresh_all(); draw(); } return start; }
/* * Process a multipart body-part: * MIME-part-headers [ line-end *OCTET ] * line-end dashed-boundary transport-padding line-end * * If applicable, call a media subdissector. * * Return the offset to the start of the next body-part. */ static gint process_body_part(proto_tree *tree, tvbuff_t *tvb, const guint8 *boundary, gint boundary_len, packet_info *pinfo, gint start, gboolean *last_boundary) { proto_tree *subtree = NULL; proto_item *ti = NULL; gint offset = start, next_offset = 0; char *parameters = NULL; gint body_start, boundary_start, boundary_line_len; char *content_type_str = NULL; char *content_encoding_str = NULL; char *filename = NULL; char *mimetypename = NULL; int len = 0; gboolean last_field = FALSE; if (tree) { ti = proto_tree_add_item(tree, hf_multipart_part, tvb, start, 0, ENC_ASCII|ENC_NA); subtree = proto_item_add_subtree(ti, ett_multipart_body); } /* * Process the MIME-part-headers */ while (!last_field) { gint colon_offset; char *hdr_str; char *header_str; /* Look for the end of the header (denoted by cr) * 3:d argument to imf_find_field_end() maxlen; must be last offset in the tvb. */ next_offset = imf_find_field_end(tvb, offset, tvb_length_remaining(tvb, offset)+offset, &last_field); /* If cr not found, won't have advanced - get out to avoid infinite loop! */ if (next_offset == offset) { break; } hdr_str = tvb_get_string(wmem_packet_scope(), tvb, offset, next_offset - offset); header_str = unfold_and_compact_mime_header(hdr_str, &colon_offset); if (colon_offset <= 0) { if (tree) { proto_tree_add_text(subtree, tvb, offset, next_offset - offset, "%s", tvb_format_text(tvb, offset, next_offset - offset)); } } else { gint hf_index; /* Split header name from header value */ header_str[colon_offset] = '\0'; hf_index = is_known_multipart_header(header_str, colon_offset); if (hf_index == -1) { if (tree) { proto_tree_add_text(subtree, tvb, offset, next_offset - offset, "%s", tvb_format_text(tvb, offset, next_offset - offset)); } } else { char *value_str = header_str + colon_offset + 1; if (tree) { proto_tree_add_string_format(subtree, hf_header_array[hf_index], tvb, offset, next_offset - offset, (const char *)value_str, "%s", tvb_format_text(tvb, offset, next_offset - offset)); } switch (hf_index) { case POS_CONTENT_TYPE: { /* The Content-Type starts at colon_offset + 1 */ gint semicolon_offset = index_of_char( value_str, ';'); if (semicolon_offset > 0) { value_str[semicolon_offset] = '\0'; parameters = wmem_strdup(wmem_packet_scope(), value_str + semicolon_offset + 1); } else { parameters = NULL; } content_type_str = g_ascii_strdown(value_str, -1); /* Show content-type in root 'part' label */ proto_item_append_text(ti, " (%s)", content_type_str); /* find the "name" parameter in case we don't find a content disposition "filename" */ if((mimetypename = find_parameter(parameters, "name=", &len)) != NULL) { mimetypename = g_strndup(mimetypename, len); } } break; case POS_CONTENT_TRANSFER_ENCODING: { /* The Content-Transfeing starts at colon_offset + 1 */ gint cr_offset = index_of_char(value_str, '\r'); if (cr_offset > 0) { value_str[cr_offset] = '\0'; } content_encoding_str = g_ascii_strdown(value_str, -1); } break; case POS_CONTENT_DISPOSITION: { /* find the "filename" parameter */ if((filename = find_parameter(value_str, "filename=", &len)) != NULL) { filename = g_strndup(filename, len); } } break; default: break; } } } offset = next_offset; } body_start = next_offset; /* * Process the body */ boundary_start = find_next_boundary(tvb, body_start, boundary, boundary_len, &boundary_line_len, last_boundary); if (boundary_start > 0) { gint body_len = boundary_start - body_start; tvbuff_t *tmp_tvb = tvb_new_subset(tvb, body_start, body_len, body_len); if (content_type_str) { /* * subdissection */ void *save_private_data = pinfo->private_data; gboolean dissected; /* * Try and remove any content transfer encoding so that each sub-dissector * doesn't have to do it itself * */ if(content_encoding_str && remove_base64_encoding) { if(!g_ascii_strncasecmp(content_encoding_str, "base64", 6)) tmp_tvb = base64_decode(pinfo, tmp_tvb, filename ? filename : (mimetypename ? mimetypename : content_type_str)); } pinfo->private_data = parameters; /* * First try the dedicated multipart dissector table */ dissected = dissector_try_string(multipart_media_subdissector_table, content_type_str, tmp_tvb, pinfo, subtree, NULL); if (! dissected) { /* * Fall back to the default media dissector table */ dissected = dissector_try_string(media_type_dissector_table, content_type_str, tmp_tvb, pinfo, subtree, NULL); } if (! dissected) { const char *save_match_string = pinfo->match_string; pinfo->match_string = content_type_str; call_dissector(media_handle, tmp_tvb, pinfo, subtree); pinfo->match_string = save_match_string; } pinfo->private_data = save_private_data; g_free(content_type_str); content_type_str = NULL; parameters = NULL; /* Shares same memory as content_type_str */ } else { call_dissector(data_handle, tmp_tvb, pinfo, subtree); } if (tree) { proto_item_set_len(ti, boundary_start - start); if (*last_boundary == TRUE) { proto_tree_add_text(tree, tvb, boundary_start, boundary_line_len, "Last boundary: %s", tvb_format_text(tvb, boundary_start, boundary_line_len)); } else { proto_tree_add_text(tree, tvb, boundary_start, boundary_line_len, "Boundary: %s", tvb_format_text(tvb, boundary_start, boundary_line_len)); } } g_free(filename); g_free(mimetypename); return boundary_start + boundary_line_len; } g_free(filename); g_free(mimetypename); return -1; }
void LevelParser::parseTileLayer (TiXmlElement *pTileElement, vector<ILayer *> *pLayers, vector<TileLayer*>* pCollisionLayers,vector<Tileset> *pTilesets){ TileLayer* pTileLayer = new TileLayer(m_tileSize, m_width, m_height, *pTilesets); //Check for layer properties bool collidable(false); for (TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){ //cout << "Checking " << e->Value() << "\n"; if (e->Value() == string("properties")){ for (TiXmlElement* p = e->FirstChildElement(); p != NULL; p = p->NextSiblingElement()){ if (p->Value() == string("property")){ cout << "Now checking " << p->Value() << "\n"; string currentProperty = p->Attribute("name"); if (currentProperty == string("collidable")){ if (p->Attribute("value") == string("true")){ collidable = true; } else { collidable = false; } if (collidable){ cout << "Found collidable layer\n"; } } } } } } //Find data node then store it //pDataNode = findElement("data", pTileElement->FirstChildElement()); bool isBase64 = false ; bool isZlibCompressed = false; TiXmlElement* pDataNode= 0; for (TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){ if (e->Value() == string("data")){ pDataNode = e; //Check if encoded/compressed if (e->Attribute("encoding")){ if (e->Attribute("encoding") == string("base64")){ isBase64 = true; } } if (e->Attribute("compression")){ if (e->Attribute("compression") == string("zlib")){ isZlibCompressed = true; } } } } //Decode data and store string decodedIDs; if (pDataNode && isBase64){ for (TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()){ TiXmlText* text = e ->ToText(); string t = text->Value(); decodedIDs = base64_decode(t); } } //Placeholder for data vector<vector<int>> data; //Calculate number of GIDS present uLongf numGids = m_width * m_height * sizeof(int); vector<unsigned> gids(numGids); //Horizontal register for vector vector<int> layerRow(m_width); //Build empty data vector to fill for(int j = 0 ; j < m_height; j++){ data.push_back(layerRow); } //Compressed data assignment if (isZlibCompressed){ uncompress ((Bytef*)&gids[0], &numGids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size()); for (int rows = 0 ; rows <m_height; rows++){ for (int cols = 0; cols < m_width; cols++){ data[rows][cols] = gids[rows * m_width + cols]; } } } else { //Uncompressed data assignment int index = 0; int tileID = 0; //Find all tiles, assign GID to proper data vector place for (TiXmlElement* e = pDataNode->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){ e->Attribute("gid",&tileID); data[index / m_width][index % m_width] = tileID; index++; } } //Set Tile Layer properties pTileLayer->setTileIDs(data); pTileLayer->setNumColumns(m_width); pTileLayer->setNumRows(m_height); //Save new tile layer to Level cout << "Added new layer\n"; pLayers->push_back(pTileLayer); //Add collision tiles to collision layer if (collidable){ pCollisionLayers->push_back(pTileLayer); cout << "Added new collision layer\n"; } }
int module_hash_decode (MAYBE_UNUSED const hashconfig_t *hashconfig, MAYBE_UNUSED void *digest_buf, MAYBE_UNUSED salt_t *salt, MAYBE_UNUSED void *esalt_buf, MAYBE_UNUSED void *hook_salt_buf, MAYBE_UNUSED hashinfo_t *hash_info, const char *line_buf, MAYBE_UNUSED const int line_len) { u32 *digest = (u32 *) digest_buf; token_t token; token.token_cnt = 4; token.len[0] = 1; token.attr[0] = TOKEN_ATTR_FIXED_LENGTH; token.len[1] = 1; token.attr[1] = TOKEN_ATTR_FIXED_LENGTH; token.len[2] = 48; token.attr[2] = TOKEN_ATTR_FIXED_LENGTH | TOKEN_ATTR_VERIFY_BASE64A; token.len[3] = 1; token.attr[3] = TOKEN_ATTR_FIXED_LENGTH; const int rc_tokenizer = input_tokenizer ((const u8 *) line_buf, line_len, &token); if (rc_tokenizer != PARSER_OK) return (rc_tokenizer); if (token.buf[0][0] != '(') return (PARSER_SIGNATURE_UNMATCHED); if (token.buf[1][0] != 'H') return (PARSER_SIGNATURE_UNMATCHED); if (token.buf[3][0] != ')') return (PARSER_SIGNATURE_UNMATCHED); // decode const u8 *hash_pos = token.buf[2]; const int hash_len = token.len[2]; u8 tmp_buf[120] = { 0 }; base64_decode (lotus64_to_int, hash_pos, hash_len, tmp_buf); tmp_buf[3] += -4; // dont ask! // salt memcpy (salt->salt_buf, tmp_buf, 16); salt->salt_len = 16; // Attention: in theory we have 2 salt_len, one for the -m 8700 part (len: 8), 2nd for the 9100 part (len: 16) // iteration char tmp_iter_buf[11] = { 0 }; memcpy (tmp_iter_buf, tmp_buf + 16, 10); tmp_iter_buf[10] = 0; salt->salt_iter = hc_strtoul ((const char *) tmp_iter_buf, NULL, 10); if (salt->salt_iter < 1) // well, the limit hopefully is much higher { return (PARSER_SALT_ITERATION); } salt->salt_iter--; // first round in init // 2 additional bytes for display only salt->salt_buf_pc[0] = tmp_buf[26]; salt->salt_buf_pc[1] = tmp_buf[27]; // digest memcpy (digest, tmp_buf + 28, 8); digest[0] = byte_swap_32 (digest[0]); digest[1] = byte_swap_32 (digest[1]); digest[2] = 0; digest[3] = 0; return (PARSER_OK); }
static int imap_hibernate_client_parse_input(const char *const *args, pool_t pool, struct imap_client_state *state_r, const char **error_r) { const char *key, *value; unsigned int peer_dev_major = 0, peer_dev_minor = 0; memset(state_r, 0, sizeof(*state_r)); if (args[0] == NULL) { *error_r = "Missing username in input"; return -1; } state_r->username = args[0]; args++; if (args[0] == NULL) { *error_r = "Missing mail_log_prefix in input"; return -1; } state_r->mail_log_prefix = args[0]; args++; for (; *args != NULL; args++) { value = strchr(*args, '='); if (value != NULL) key = t_strdup_until(*args, value++); else { key = *args; value = ""; } if (strcmp(key, "lip") == 0) { if (net_addr2ip(value, &state_r->local_ip) < 0) { *error_r = t_strdup_printf( "Invalid lip value: %s", value); return -1; } } else if (strcmp(key, "rip") == 0) { if (net_addr2ip(value, &state_r->remote_ip) < 0) { *error_r = t_strdup_printf( "Invalid rip value: %s", value); return -1; } } else if (strcmp(key, "peer_dev_major") == 0) { if (str_to_uint(value, &peer_dev_major) < 0) { *error_r = t_strdup_printf( "Invalid peer_dev_major value: %s", value); return -1; } } else if (strcmp(key, "peer_dev_minor") == 0) { if (str_to_uint(value, &peer_dev_minor) < 0) { *error_r = t_strdup_printf( "Invalid peer_dev_minor value: %s", value); return -1; } } else if (strcmp(key, "peer_ino") == 0) { if (str_to_ino(value, &state_r->peer_ino) < 0) { *error_r = t_strdup_printf( "Invalid peer_ino value: %s", value); return -1; } } else if (strcmp(key, "uid") == 0) { if (str_to_uid(value, &state_r->uid) < 0) { *error_r = t_strdup_printf( "Invalid uid value: %s", value); return -1; } } else if (strcmp(key, "gid") == 0) { if (str_to_gid(value, &state_r->gid) < 0) { *error_r = t_strdup_printf( "Invalid gid value: %s", value); return -1; } } else if (strcmp(key, "stats") == 0) { state_r->stats = value; } else if (strcmp(key, "idle-cmd") == 0) { state_r->idle_cmd = TRUE; } else if (strcmp(key, "session") == 0) { state_r->session_id = value; } else if (strcmp(key, "session_created") == 0) { if (str_to_time(value, &state_r->session_created) < 0) { *error_r = t_strdup_printf( "Invalid session_created value: %s", value); return -1; } } else if (strcmp(key, "userdb_fields") == 0) { state_r->userdb_fields = value; } else if (strcmp(key, "notify_fd") == 0) { state_r->have_notify_fd = TRUE; } else if (strcmp(key, "idle_notify_interval") == 0) { if (str_to_uint(value, &state_r->imap_idle_notify_interval) < 0) { *error_r = t_strdup_printf( "Invalid idle_notify_interval value: %s", value); return -1; } } else if (strcmp(key, "tag") == 0) { state_r->tag = i_strdup(value); } else if (strcmp(key, "state") == 0) { buffer_t *state_buf; state_buf = buffer_create_dynamic(pool, 1024); if (base64_decode(value, strlen(value), NULL, state_buf) < 0) { *error_r = t_strdup_printf( "Invalid state base64 value: %s", value); return -1; } state_r->state = state_buf->data; state_r->state_size = state_buf->used; } } if (state_r->tag == NULL) { *error_r = "Missing tag"; return -1; } if (peer_dev_major != 0 || peer_dev_minor != 0) state_r->peer_dev = makedev(peer_dev_major, peer_dev_minor); return 0; }
int password_decode(const char *password, const char *scheme, const unsigned char **raw_password_r, size_t *size_r, const char **error_r) { const struct password_scheme *s; enum password_encoding encoding; buffer_t *buf; size_t len; bool guessed_encoding; *error_r = NULL; s = password_scheme_lookup(scheme, &encoding); if (s == NULL) { *error_r = "Unknown scheme"; return 0; } len = strlen(password); if (encoding != PW_ENCODING_NONE && s->raw_password_len != 0 && strchr(scheme, '.') == NULL) { /* encoding not specified. we can guess quite well between base64 and hex encodings. the only problem is distinguishing 2 character strings, but there shouldn't be any that short raw_password_lens. */ encoding = len == s->raw_password_len * 2 ? PW_ENCODING_HEX : PW_ENCODING_BASE64; guessed_encoding = TRUE; } else { guessed_encoding = FALSE; } switch (encoding) { case PW_ENCODING_NONE: *raw_password_r = (const unsigned char *)password; *size_r = len; break; case PW_ENCODING_HEX: buf = t_buffer_create(len / 2 + 1); if (hex_to_binary(password, buf) == 0) { *raw_password_r = buf->data; *size_r = buf->used; break; } if (!guessed_encoding) { *error_r = "Input isn't valid HEX encoded data"; return -1; } /* check if it's base64-encoded after all. some input lengths produce matching hex and base64 encoded lengths. */ /* fall through */ case PW_ENCODING_BASE64: buf = t_buffer_create(MAX_BASE64_DECODED_SIZE(len)); if (base64_decode(password, len, NULL, buf) < 0) { *error_r = "Input isn't valid base64 encoded data"; return -1; } *raw_password_r = buf->data; *size_r = buf->used; break; } if (s->raw_password_len != *size_r && s->raw_password_len != 0) { /* password has invalid length */ *error_r = t_strdup_printf( "Input length isn't valid (%u instead of %u)", (unsigned int)*size_r, s->raw_password_len); return -1; } return 1; }
// send data bool Socket::send(string sData) { // variables int iResult; int iDataLength = sData.length(); // if encryption is enabled, encrypt data to send if(bEncryption) { // encrypt data bXOR(sData); } // prevent sending more data than buffer can contain if(bBase64 == false && iDataLength > 1492) { #ifdef DEBUG cout << "Socket::send() error: You are trying to send " << iDataLength << " bytes, where limit is 1492 bytes!" << endl; #endif // return false return false; } else if(bBase64 == true && iDataLength > 1024) { #ifdef DEBUG cout << "Socket::send() error: You are trying to send " << iDataLength << " bytes, where limit is 1024 bytes using Base64!" << endl; #endif // return false return false; } // if base64 is enabled, encode sent data if(bBase64) { sData = base64_encode(sData); } // send data from sData iResult = ::send(SocketFD, sData.c_str(), sData.length(), 0); // return false if something failed if(iResult == -1) { #ifdef DEBUG cout << "Socket::send() error: '::send' return value == -1" << endl; cout << "Socket::send() error: errno == " << errno << endl; #endif // return false return false; } // // // create buffer char table (without content - clean) char chBuffer[BUFFER_SIZE + 1] = {}; // receive data to buffer iResult = ::recv(SocketFD, chBuffer, BUFFER_SIZE, 0); #ifdef DEBUG string sTemp = chBuffer; sTemp = sXOR(base64_decode(sTemp)); stringstream ssTemp; ssTemp << sData.length(); if(sTemp == ssTemp.str()) { cout << "Socket::send(): Good! " << endl; } else { cout << "Socket::send(): Bad! " << endl; } #endif // #ifdef DEBUG cout << "Socket::send(): Sent " << sData.length() << " bytes" << endl; #endif // return true return true; }
void newUser(int sd, char *buff) { //TODO: add uniquenick support char sendbuff[512]; char nick[GP_NICK_LEN],email[GP_EMAIL_LEN],pass[GP_PASSWORD_LEN],uniquenick[GP_NICK_LEN]; int userid,profileid; find_param("uniquenick",buff,uniquenick,sizeof(uniquenick)); if(!find_param("nick", buff, nick, sizeof(nick))) { sendError(sd,"Error recieving request"); return; } mysql_real_escape_string(conn,nick,nick,strlen(nick)); if(!find_param("email", buff, email, sizeof(email))) { sendError(sd,"Error recieving request"); return; } mysql_real_escape_string(conn,email,email,strlen(email)); if(!find_param("pass", buff, pass, sizeof(pass))) { if(!find_param("passenc",buff,pass,sizeof(pass))) { sendError(sd,"Error recieving request"); return; } else { char *dpass; int passlen = strlen(pass); dpass = (char *)base64_decode((uint8_t *)pass, &passlen); passlen = gspassenc((uint8_t *)dpass); strcpy(pass,dpass); free(dpass); } } mysql_real_escape_string(conn,pass,pass,strlen(pass)); userid = getUserIDFromEmail(conn,email); if(userid == 0 || !tryPassword(conn,userid,pass)) { formatSend(sd,true,0,"\\nur\\%d",GP_NEWUSER_BAD_PASSWORD); return; } profileid = getProfileIDFromNickEmail(conn, nick, email); if(profileid != 0) { formatSend(sd,true,0,"\\nur\\%d\\pid\\%d",GP_NEWUSER_BAD_NICK,profileid); return; } if(!nameValid(nick,false)) { formatSend(sd,true,0,"\\nur\\%d",GP_NEWUSER_BAD_NICK); return; } if(uniquenick[0] != 0) { profileid = getProfileIDFromUniquenick(conn,uniquenick); if(profileid != 0) { formatSend(sd,true,0,"\\nur\\%d",GP_NEWUSER_UNIQUENICK_INUSE); return; } if(!nameValid(uniquenick,false)) { formatSend(sd,true,0,"\\nur\\%d",GP_NEWUSER_UNIQUENICK_INVALID); return; } } if(uniquenick[0] != 0) { profileid = makeNewProfileWithUniquenick(conn,nick,uniquenick,userid); } else { profileid = makeNewProfile(conn,nick,userid); } if(profileid != 0) { formatSend(sd,true,0,"\\nur\\0\\pid\\%d",profileid); return; } }
int udf_cask_info_put(char *name, char * params, cf_dyn_buf * out) { cf_debug(AS_INFO, "UDF CASK INFO PUT"); int rc = 0; char filename[128] = {0}; int filename_len = sizeof(filename); // Content_len from the client and its expected size char content_len[32] = {0}; int clen = sizeof(content_len); // Udf content from the client and its expected length char *udf_content = NULL; int udf_content_len = 0; // Udf type from the client and its expected size char type[8] = {0}; int type_len = sizeof(type); // get (required) script filename char *tmp_char; if ( as_info_parameter_get(params, "filename", filename, &filename_len) || !(tmp_char = strchr(filename, '.')) // No extension in filename || tmp_char == filename // '.' at the begining of filename || strlen (tmp_char) <= 1) { // '.' in filename, but no extnsion e.g. "abc." cf_info(AS_INFO, "invalid or missing filename"); cf_dyn_buf_append_string(out, "error=invalid_filename"); return 0; } if ( as_info_parameter_get(params, "content-len", content_len, &(clen)) ) { cf_info(AS_INFO, "invalid or missing content-len"); cf_dyn_buf_append_string(out, "error=invalid_content_len"); return 0; } if ( as_info_parameter_get(params, "udf-type", type, &type_len) ) { // Replace with DEFAULT IS LUA strcpy(type, as_udf_type_name[0]); } // check type field if (-1 == udf_type_getid(type)) { cf_info(AS_INFO, "invalid or missing udf-type : %s not valid", type); cf_dyn_buf_append_string(out, "error=invalid_udf_type"); return 0; } // get b64 encoded script udf_content_len = atoi(content_len) + 1; udf_content = (char *) cf_malloc(udf_content_len); if ( udf_content == NULL ) { cf_info(AS_UDF, "internal allocation error"); cf_dyn_buf_append_string(out, "error=internal_error"); // As memory is not allocated. // It should not continue. return 0; } // cf_info(AS_UDF, "content_len = %s", content_len); // cf_info(AS_UDF, "udf_content_len = %d", udf_content_len); // get (required) script content - base64 encoded here. if ( as_info_parameter_get(params, "content", udf_content, &(udf_content_len)) ) { cf_info(AS_UDF, "invalid content"); cf_dyn_buf_append_string(out, "error=invalid_content"); cf_free(udf_content); return 0; } // base 64 decode it int decoded_len = strlen(udf_content); char * decoded_str = cf_malloc(decoded_len); rc = base64_decode((uint8_t *)udf_content, (uint8_t *)decoded_str, &decoded_len, true); if ( rc ) { cf_info(AS_UDF, "invalid base64 content %s", filename); cf_dyn_buf_append_string(out, "error=invalid_base64_content"); cf_free(decoded_str); return 0; } decoded_str[decoded_len] = '\0'; as_module_error err; rc = as_module_validate(&mod_lua, NULL, filename, decoded_str, decoded_len, &err); cf_free(decoded_str); decoded_str = NULL; decoded_len = 0; if ( rc ) { cf_warning(AS_UDF, "udf-put: compile error: [%s:%d] %s", err.file, err.line, err.message); cf_dyn_buf_append_string(out, "error=compile_error"); cf_dyn_buf_append_string(out, ";file="); cf_dyn_buf_append_string(out, err.file); cf_dyn_buf_append_string(out, ";line="); cf_dyn_buf_append_uint32(out, err.line); int message_len = strlen(err.message); char message[base64_encode_maxlen(message_len)]; base64_encode((uint8_t *) err.message, (uint8_t *) message, &message_len); cf_dyn_buf_append_string(out, ";message="); cf_dyn_buf_append_buf(out, (uint8_t *) message, message_len); cf_free(udf_content); return 0; } // Create an empty JSON object json_t *udf_obj = 0; if (!(udf_obj = json_object())) { cf_warning(AS_UDF, "failed to create JSON array for receiving UDF"); if (udf_content) cf_free(udf_content); return -1; } int e = 0; e += json_object_set_new(udf_obj, "content64", json_string(udf_content)); e += json_object_set_new(udf_obj, "type", json_string(type)); e += json_object_set_new(udf_obj, "name", json_string(filename)); if (e) { cf_warning(AS_UDF, "could not encode UDF object, error %d", e); json_decref(udf_obj); if (udf_content) cf_free(udf_content); return(-1); } // make it into a string, yet another buffer copy char *udf_obj_str = json_dumps(udf_obj, 0/*flags*/); json_decref(udf_obj); udf_obj = 0; cf_debug(AS_UDF, "created json object %s", udf_obj_str); // how do I know whether to call create or add? e = as_smd_set_metadata(udf_smd_module_name, filename, udf_obj_str); if (e) { cf_warning(AS_UDF, "could not add UDF metadata, error %d", e); cf_free(udf_obj_str); if (udf_content) cf_free(udf_content); return(-1); } // free the metadata cf_free(udf_obj_str); udf_obj_str = 0; if (udf_content) cf_free(udf_content); return 0; }
json_t* authRequest(Parameters& params, std::string url, std::string request, std::string options) { // create nonce and POST data struct timeval tv; gettimeofday(&tv, NULL); unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5; std::string post_data = ""; if (options.empty()) { post_data = "nonce=" + patch::to_string(nonce); } else { post_data = "nonce=" + patch::to_string(nonce) + "&" + options; } // Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) // and base64 decoded secret API key std::string payload_for_signature = patch::to_string(nonce) + post_data; unsigned char digest[SHA256_DIGEST_LENGTH]; SHA256((unsigned char*)payload_for_signature.c_str(), strlen(payload_for_signature.c_str()), (unsigned char*)&digest); int signature_data_length = request.length() + SHA256_DIGEST_LENGTH; unsigned char signature_data[signature_data_length]; std::copy(request.begin(), request.end(), &signature_data[0]); memcpy(&signature_data[request.length()], &digest, SHA256_DIGEST_LENGTH); std::string decoded_key = base64_decode(params.krakenSecret); unsigned char* hmac_digest; hmac_digest = HMAC(EVP_sha512(), decoded_key.c_str(), decoded_key.length(), (unsigned char*)&signature_data, signature_data_length, NULL, NULL); std::string api_sign_header = base64_encode(reinterpret_cast<const unsigned char*>(hmac_digest), SHA512_DIGEST_LENGTH); // cURL header struct curl_slist* headers = NULL; std::string api = "API-KEY:" + std::string(params.krakenApi); std::string api_sig = "API-Sign:" + api_sign_header; headers = curl_slist_append(headers, api.c_str()); headers = curl_slist_append(headers, api_sig.c_str()); // cURL request CURLcode resCurl; if (params.curl) { std::string readBuffer; curl_easy_setopt(params.curl, CURLOPT_POST, 1L); curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, post_data.c_str()); curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(params.curl, CURLOPT_URL, (url+request).c_str()); curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L); resCurl = curl_easy_perform(params.curl); json_t* root; json_error_t error; while (resCurl != CURLE_OK) { *params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); while (!root) { *params.logFile << "<Kraken> Error with JSON:\n" << error.text << ". Retrying..." << std::endl; readBuffer = ""; resCurl = curl_easy_perform(params.curl); while (resCurl != CURLE_OK) { *params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); } curl_slist_free_all(headers); curl_easy_reset(params.curl); return root; } else { *params.logFile << "<Kraken> Error with cURL init." << std::endl; return NULL; } return NULL; }
int udf_cask_smd_accept_fn(char *module, as_smd_item_list_t *items, void *udata, uint32_t accept_opt) { if (accept_opt & AS_SMD_ACCEPT_OPT_CREATE) { cf_debug(AS_UDF, "(doing nothing in UDF accept cb for module creation)"); return 0; } cf_debug(AS_UDF, "UDF CASK accept fn : n items %d", items->num_items); // For each item in the list, see if the current version // is different from the curretly stored version // and if the new item is new, write to the storage directory for (int i = 0; i < items->num_items ; i++) { as_smd_item_t *item = items->item[i]; if (item->action == AS_SMD_ACTION_SET) { json_error_t json_err; json_t *item_obj = json_loads(item->value, 0 /*flags*/, &json_err); /*item->key is name */ json_t *content64_obj = json_object_get(item_obj, "content64"); const char *content64_str = json_string_value(content64_obj); // base 64 decode it int content_len = strlen(content64_str); char *content_str = cf_malloc(content_len); // base64_decode function does not add '\0' at the end , if input string is of length%3 = 0 // content_len is greater than required size. // It leads adding junk characters at the end of LUA file. // Zeroing out the string, so that it will have '\0' at end in all cases. memset (content_str, 0, content_len); int e = base64_decode((uint8_t *)content64_str, (uint8_t *)content_str, &content_len, true); if (e) { cf_info(AS_UDF, "invalid script on accept, will not register %s", item->key); cf_free(content_str); json_decref(content64_obj); json_decref(item_obj); continue; } cf_debug(AS_UDF, "pushing to %s, %d bytes [%s]", item->key, content_len, content_str); mod_lua_wrlock(&mod_lua); // content_gen is actually a hash. Not sure if it's filled out or what. unsigned char content_gen[256] = {0}; e = file_write(item->key, (uint8_t *) content_str, content_len, content_gen); cf_free(content_str); json_decref(content64_obj); json_decref(item_obj); if ( e ) { mod_lua_unlock(&mod_lua); cf_info(AS_UDF, "invalid script on accept, will not register %s", item->key); continue; } // Update the cache as_module_event ame = { .type = AS_MODULE_EVENT_FILE_ADD, .data.filename = item->key }; as_module_update(&mod_lua, &ame); mod_lua_unlock(&mod_lua); } else if (item->action == AS_SMD_ACTION_DELETE) { cf_debug(AS_UDF, "received DELETE SMD action %d key %s", item->action, item->key); mod_lua_wrlock(&mod_lua); file_remove(item->key); // fixes potential cache issues as_module_event e = { .type = AS_MODULE_EVENT_FILE_REMOVE, .data.filename = item->key }; as_module_update(&mod_lua, &e); mod_lua_unlock(&mod_lua); } else {
/* * variable_undigest() * * rozszyfrowuje skrót zmiennych z listy kontaktów i ustawia wszystko, * co trzeba. * * - digest - ci±g znaków. * * 0/-1 */ int variable_undigest(const char *digest) { const char *p = digest; if (!digest) return -1; while (*p) { struct variable *v; list_t l; for (v = NULL, l = variables; l; l = l->next) { struct variable *w = l->data; if (!strncmp(p, w->short_name, 2)) { v = w; break; } } if (!v) { gg_debug(GG_DEBUG_MISC, "// unknown short \"%c%c\"\n", p[0], p[1]); return -1; } p += 2; if (v->type == VAR_INT || v->type == VAR_BOOL || v->type == VAR_MAP) { char *end; int val; val = strtol(p, &end, 10); variable_set(v->name, itoa(val), 0); p = end; } if (v->type == VAR_STR) { char *val = NULL; if (*p == '-') { val = NULL; p++; } else { const char *q; char *tmp; int len = 0, base64 = 0; if (*p == '+') { base64 = 1; p++; } for (q = p; *q && *q != ':'; q++, len++) ; tmp = xstrmid(p, 0, len); gg_debug(GG_DEBUG_MISC, "// got string variable \"%s\"\n", tmp); if (base64) { val = base64_decode(tmp); xfree(tmp); } else val = tmp; p += len + 1; } gg_debug(GG_DEBUG_MISC, "// setting variable %s = \"%s\"\n", v->name, ((val) ? val : "(null)")); variable_set(v->name, val, 0); xfree(val); } } return 0; }
void kauth(int argc, char **argv) { int ret; char buf[1024]; des_cblock key; des_key_schedule schedule; KTEXT_ST tkt, tktcopy; char *name; char *p; int overbose; char passwd[100]; int tmp; int save; if(argc > 2){ printf("usage: %s [principal]\n", argv[0]); code = -1; return; } if(argc == 2) name = argv[1]; else name = username; overbose = verbose; verbose = 0; save = set_command_prot(prot_private); ret = command("SITE KAUTH %s", name); if(ret != CONTINUE){ verbose = overbose; set_command_prot(save); code = -1; return; } verbose = overbose; p = strstr(reply_string, "T="); if(!p){ printf("Bad reply from server.\n"); set_command_prot(save); code = -1; return; } p += 2; tmp = base64_decode(p, &tkt.dat); if(tmp < 0){ printf("Failed to decode base64 in reply.\n"); set_command_prot(save); code = -1; return; } tkt.length = tmp; tktcopy.length = tkt.length; p = strstr(reply_string, "P="); if(!p){ printf("Bad reply from server.\n"); verbose = overbose; set_command_prot(save); code = -1; return; } name = p + 2; for(; *p && *p != ' ' && *p != '\r' && *p != '\n'; p++); *p = 0; snprintf(buf, sizeof(buf), "Password for %s:", name); if (des_read_pw_string (passwd, sizeof(passwd)-1, buf, 0)) *passwd = '\0'; des_string_to_key (passwd, &key); des_key_sched(&key, schedule); des_pcbc_encrypt((des_cblock*)tkt.dat, (des_cblock*)tktcopy.dat, tkt.length, schedule, &key, DES_DECRYPT); if (strcmp ((char*)tktcopy.dat + 8, KRB_TICKET_GRANTING_TICKET) != 0) { afs_string_to_key (passwd, krb_realmofhost(hostname), &key); des_key_sched (&key, schedule); des_pcbc_encrypt((des_cblock*)tkt.dat, (des_cblock*)tktcopy.dat, tkt.length, schedule, &key, DES_DECRYPT); } memset(key, 0, sizeof(key)); memset(schedule, 0, sizeof(schedule)); memset(passwd, 0, sizeof(passwd)); if(base64_encode(tktcopy.dat, tktcopy.length, &p) < 0) { printf("Out of memory base64-encoding.\n"); set_command_prot(save); code = -1; return; } memset (tktcopy.dat, 0, tktcopy.length); ret = command("SITE KAUTH %s %s", name, p); free(p); set_command_prot(save); if(ret != COMPLETE){ code = -1; return; } code = 0; }
/* NTLM POP3 Authentication Based on: http://curl.haxx.se/rfc/ntlm.html#ntlmPop3Authentication http://src.opensolaris.org/source/xref/sfw/usr/src/cmd/fetchmail/fetchmail-6.3.8/README.NTLM */ int sendAuthNTLM(int hSocket, _MODULE_DATA* _psSessionData, char* szLogin, char* szPassword) { unsigned char* bufSend = NULL; unsigned char* bufReceive = NULL; int nReceiveBufferSize = 0; int nSendBufferSize = 0; tSmbNtlmAuthRequest sTmpReq; tSmbNtlmAuthChallenge sTmpChall; tSmbNtlmAuthResponse sTmpResp; unsigned char* szTmpBuf = NULL; unsigned char* szTmpBuf64 = NULL; writeError(ERR_DEBUG_MODULE, "[%s] Initiating NTLM Authentication Attempt.", MODULE_NAME); /* --- Send initial AUTHENTICATE NTLM command --- */ bufSend = malloc(11 + 1); memset(bufSend, 0, 11 + 1); sprintf(bufSend, "AUTH NTLM\r\n"); if (medusaSend(hSocket, bufSend, strlen(bufSend), 0) < 0) { writeError(ERR_ERROR, "%s failed: medusaSend was not successful", MODULE_NAME); } FREE(bufSend); /* Server should respond with an empty challenge, consisting simply of a "+" */ nReceiveBufferSize = 0; if ((medusaReceiveRegex(hSocket, &bufReceive, &nReceiveBufferSize, "\\+ *OK.*\r\n") == FAILURE) || (bufReceive == NULL)) { writeError(ERR_ERROR, "[%s] POP3 server did not respond with \"+ OK\" to AUTH NTLM request.", MODULE_NAME); return FAILURE; } FREE(bufReceive); /* --- Send Base-64 encoded Type-1 message --- */ buildAuthRequest(&sTmpReq, 0, NULL, NULL); szTmpBuf64 = malloc(2 * SmbLength(&sTmpReq) + 2); memset(szTmpBuf64, 0, 2 * SmbLength(&sTmpReq) + 2); base64_encode((char *)&sTmpReq, SmbLength(&sTmpReq), szTmpBuf64); writeError(ERR_DEBUG_MODULE, "[%s] Sending initial challenge (B64 Encoded): %s", MODULE_NAME, szTmpBuf64); nSendBufferSize = strlen(szTmpBuf64) + 2; bufSend = malloc(nSendBufferSize + 1); memset(bufSend, 0, nSendBufferSize + 1); sprintf(bufSend, "%s\r\n", szTmpBuf64); FREE(szTmpBuf64); if (medusaSend(hSocket, bufSend, strlen(bufSend), 0) < 0) { writeError(ERR_ERROR, "[%s] failed: medusaSend was not successful", MODULE_NAME); return FAILURE; } FREE(bufSend); /* Server should respond with a Base-64 encoded Type-2 challenge message. The challenge response format is specified by RFC 1730 ("+", followed by a space, followed by the challenge message). */ nReceiveBufferSize = 0; if ((medusaReceiveRegex(hSocket, &bufReceive, &nReceiveBufferSize, "\\+ .*\r\n") == FAILURE) || (bufReceive == NULL)) { writeError(ERR_ERROR, "[%s] Server did not send valid Type-2 challenge response.", MODULE_NAME); return FAILURE; } szTmpBuf = ((char*)index(bufReceive, '\r')); szTmpBuf[0] = '\0'; writeError(ERR_DEBUG_MODULE, "[%s] NTLM Challenge (B64 Encoded): %s", MODULE_NAME, bufReceive + 2); base64_decode(bufReceive + 2, (char *)&sTmpChall); FREE(bufReceive); /* --- Calculate and send Base-64 encoded Type 3 response --- */ buildAuthResponse(&sTmpChall, &sTmpResp, 0, szLogin, szPassword, _psSessionData->szDomain, NULL); szTmpBuf64 = malloc(2 * SmbLength(&sTmpResp) + 2); memset(szTmpBuf64, 0, 2 * SmbLength(&sTmpResp) + 2); base64_encode((char *)&sTmpResp, SmbLength(&sTmpResp), szTmpBuf64); writeError(ERR_DEBUG_MODULE, "[%s] NTLM Response (B64 Encoded): %s", MODULE_NAME, szTmpBuf64); nSendBufferSize = strlen(szTmpBuf64) + 2; bufSend = malloc(nSendBufferSize + 1); memset(bufSend, 0, nSendBufferSize + 1); sprintf(bufSend, "%s\r\n", szTmpBuf64); if (medusaSend(hSocket, bufSend, nSendBufferSize, 0) < 0) { writeError(ERR_ERROR, "[%s] failed: medusaSend was not successful", MODULE_NAME); return FAILURE; } FREE(szTmpBuf64); FREE(bufSend); /* Server should validate the response and indicate the result of authentication. e.g. +OK User successfully logged on */ return SUCCESS; }
void Toolbox::DecodeBase64(std::string& result, const std::string& data) { result = base64_decode(data); }
bool hostupdate_h(connection_t *c) { /* FIXME: Whoah! Even more!! */ char rawfile[MAX_STRING_SIZE]; char rawhost[MAX_STRING_SIZE], b64host[MAX_STRING_SIZE]; char rawdgst[MAX_STRING_SIZE], b64dgst[MAX_STRING_SIZE]; char updname[MAX_STRING_SIZE], hosttoupd[MAX_STRING_SIZE]; char *fname; FILE *fp; size_t slen, dlen, rlen; RSA *updkey; /* We ignore host files updates, maybe for reason */ if (ignorenetupdates() || ignorehostsupdates()) return true; /* handle received host data, check sign, (over)write on disk */ if (sscanf(c->buffer, "%*d " MAX_STRING " " MAX_STRING " " MAX_STRING " %zd %zd " MAX_STRING, updname, hosttoupd, b64host, &slen, &dlen, b64dgst) != 6) { logger(LOG_ERR, "Got bad %s from %s (%s)", "HOSTUPDATE", c->name, c->hostname); return false; } /* verify the originating node is permitted to send updates */ if (dontverifyupdatepermission()) goto _next; if(!getconf_bool_node_offline(updname, "HostsFilesMaster")) { ifdebug(PROTOCOL) logger(LOG_WARNING, "Ignoring hosts update request originating from %s [which came from %s (%s)]", updname, c->name, c->hostname); return true; } /* some other sanity checks */ _next: if (!isvalidfname(updname)) { logger(LOG_ERR, "Got bogus updater name \"%s\" from %s (%s) (from: %s)", updname, c->name, c->hostname, updname); return false; } if (!isvalidfname(hosttoupd)) { logger(LOG_ERR, "Got bogus update name \"%s\" from %s (%s) (from: %s)", hosttoupd, c->name, c->hostname, updname); return false; } if (slen >= MAX_STRING_SIZE || dlen >= MAX_STRING_SIZE) { logger(LOG_ERR, "HOSTUPDATE string sizes for %s are bigger than buffer can fit (%zd, %zd)", hosttoupd, slen, dlen); return false; } /* verify it */ if (dontverifyupdatesignature()) goto _out; if (!read_rsa_public_key_offline(updname, &updkey)) { logger(LOG_ERR, "Could not find public key for %s", updname); return true; } base64_decode(b64dgst, rawdgst, sizeof(rawdgst)-1); snprintf(rawhost, sizeof(rawhost), "%s %s %s %zd %zd", updname, hosttoupd, b64host, slen, dlen); rlen = strlen(rawhost); if (!EVP_verify(updkey, rawdgst, dlen, rawhost, rlen)) { logger(LOG_WARNING, "Ignoring hosts update request with bad signature from %s for %s" " [which came from %s (%s)]", updname, hosttoupd, c->name, c->hostname); RSA_free(updkey); return true; } RSA_free(updkey); /* neighbours return us our own packets */ _out: if (!strcmp(updname, myself->name)) return true; /* All right, let's start updating */ xasprintf(&fname, "%s/hosts/%s", confbase, hosttoupd); /* Tell others if needed */ if (!dontforwardhostsupdates()) { exceptmasters = true; forward_request(c); } /* Check if it's a START marker */ if (!strcmp(updname, hosttoupd) && !strcmp(b64host, "START")) { /* Run pre-update script (embedded devices do remount,rw fs for example) We really need to run this once, so that's why there are START and END markers */ run_script("hostsupdate-before"); /* That's it folks! Waiting for files to arrive */ free(fname); return true; } /* Check if it's a END marker */ else if (!strcmp(updname, hosttoupd) && !strcmp(b64host, "END")) { /* Run post-update script (embedded devices do remount,ro fs for example) */ run_script("hostsupdate-after"); /* Schedule config/host reload */ schedulereload(); /* That's it folks! */ free(fname); return true; } /* Remove unneeded hosts */ else if (!strcmp(b64host, "DEAD")) { unlink(fname); /* That's it, waiting for other next request */ free(fname); return true; } /* We need this early for next test */ base64_decode(b64host, rawhost, sizeof(rawhost)-1); /* * Via broadcasting host files one hosts file master can become config file master. * Reject such a claims even if they're authentic. */ if (dontverifyupdatepermission()) goto _write; if(!getconf_bool_node_offline(updname, "ConfFileMaster") && strcasestr_local(rawhost, "ConfFileMaster")) { logger(LOG_WARNING, "Ignoring %s which tried to raise privileges for %s to ConfFileMaster!", updname, hosttoupd); goto _end; } /* Finally write it to disk */ _write: fp = fopen(fname, "w"); if (!fp) { logger(LOG_ERR, "Unable to write new host file: %s (%s)", fname, strerror(errno)); free(fname); return true; } #ifdef HAVE_FCHMOD fchmod(fileno(fp), 0640); #endif fwrite(rawhost, slen, 1, fp); fclose(fp); _end: free(fname); return true; }
/** * Take a base64 blob of data and decrypt it (using AES) into its * proper ASN.1 form. */ static int pem_decrypt(const char *where, const char *end, const char *password, SSLObjLoader *ssl_obj) { int ret = -1; int is_aes_256 = 0; char *start = NULL; uint8_t iv[IV_SIZE]; int i, pem_size; MD5_CTX md5_ctx; AES_CTX aes_ctx; uint8_t key[32]; /* AES256 size */ if (password == NULL || strlen(password) == 0) { #ifdef CONFIG_SSL_FULL_MODE printf("Error: Need a password for this PEM file\n"); TTY_FLUSH(); #endif goto error; } if ((start = strstr((const char *)where, aes_str[0]))) /* AES128? */ { start += strlen(aes_str[0]); } else if ((start = strstr((const char *)where, aes_str[1]))) /* AES256? */ { is_aes_256 = 1; start += strlen(aes_str[1]); } else { #ifdef CONFIG_SSL_FULL_MODE printf("Error: Unsupported password cipher\n"); TTY_FLUSH(); #endif goto error; } /* convert from hex to binary - assumes uppercase hex */ for (i = 0; i < IV_SIZE; i++) { char c = *start++ - '0'; iv[i] = (c > 9 ? c + '0' - 'A' + 10 : c) << 4; c = *start++ - '0'; iv[i] += (c > 9 ? c + '0' - 'A' + 10 : c); } while (*start == '\r' || *start == '\n') start++; /* turn base64 into binary */ pem_size = (int)(end-start); if (base64_decode(start, pem_size, ssl_obj->buf, &ssl_obj->len) != 0) goto error; /* work out the key */ MD5_Init(&md5_ctx); MD5_Update(&md5_ctx, (const uint8_t *)password, (int)strlen(password)); /* GBG */ MD5_Update(&md5_ctx, iv, SALT_SIZE); MD5_Final(key, &md5_ctx); if (is_aes_256) { MD5_Init(&md5_ctx); MD5_Update(&md5_ctx, key, MD5_SIZE); MD5_Update(&md5_ctx, (const uint8_t *)password, (int)strlen(password)); /* GBG */ MD5_Update(&md5_ctx, iv, SALT_SIZE); MD5_Final(&key[MD5_SIZE], &md5_ctx); } /* decrypt using the key/iv */ AES_set_key(&aes_ctx, key, iv, is_aes_256 ? AES_MODE_256 : AES_MODE_128); AES_convert_key(&aes_ctx); AES_cbc_decrypt(&aes_ctx, ssl_obj->buf, ssl_obj->buf, ssl_obj->len); ret = 0; error: return ret; }
void LevelParser::parseTileLayer(TiXmlElement * pTileElement, std::vector<Layer*>* pLayers, const std::vector<Tileset>* pTilesets, std::vector<TileLayer*>* pCollisionLayers) { bool collidable = false; //crar un nuevo tileLayer TileLayer* pTileLayer = new TileLayer(m_tileSize, *pTilesets); // tile data std::vector<std::vector<int>> data; std::string decodedIDs; TiXmlElement* pDataNode = NULL; //////// for (TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Value() == std::string("properties")) { for (TiXmlElement* property = e->FirstChildElement(); property != NULL; property = property->NextSiblingElement()) { if (property->Value() == std::string("property")) { if (property->Attribute("name") == std::string("coli") && property->Attribute("value") == std::string("True")) { collidable = true; } } } } if (e->Value() == std::string("data")) { pDataNode = e; } } ///////// for (TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()) { TiXmlText* text = e->ToText(); std::string t = text->Value(); decodedIDs = base64_decode(t); } // uncompress zlib compression uLongf numGids = m_width * m_height * sizeof(int); std::vector<unsigned> gids(numGids); uncompress((Bytef*)&gids[0], &numGids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size()); std::vector<int> layerRow(m_width); for (int j = 0; j < m_height; j++) { data.push_back(layerRow); } for (int rows = 0; rows < m_height; rows++) { for (int cols = 0; cols < m_width; cols++) { data[rows][cols] = gids[rows * m_width + cols]; } } pTileLayer->setTileIDs(data); if (collidable) { pCollisionLayers->push_back(pTileLayer); } pLayers->push_back(pTileLayer); }
/** * Take a base64 blob of data and turn it into its proper ASN.1 form. */ static int new_pem_obj(SSL_CTX *ssl_ctx, int is_cacert, char *where, int remain, const char *password) { int ret = SSL_ERROR_BAD_CERTIFICATE; SSLObjLoader *ssl_obj = NULL; while (remain > 0) { int i, pem_size, obj_type; char *start = NULL, *end = NULL; for (i = 0; i < NUM_PEM_TYPES; i++) { if ((start = strstr(where, begins[i])) && (end = strstr(where, ends[i]))) { remain -= (int)(end-where); start += strlen(begins[i]); pem_size = (int)(end-start); ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader)); /* 4/3 bigger than what we need but so what */ ssl_obj->buf = (uint8_t *)calloc(1, pem_size); ssl_obj->len = pem_size; if (i == IS_RSA_PRIVATE_KEY && strstr(start, "Proc-Type:") && strstr(start, "4,ENCRYPTED")) { /* check for encrypted PEM file */ if (pem_decrypt(start, end, password, ssl_obj) < 0) { ret = SSL_ERROR_BAD_CERTIFICATE; goto error; } } else { ssl_obj->len = pem_size; if (base64_decode(start, pem_size, ssl_obj->buf, &ssl_obj->len) != 0) { ret = SSL_ERROR_BAD_CERTIFICATE; goto error; } } switch (i) { case IS_RSA_PRIVATE_KEY: obj_type = SSL_OBJ_RSA_KEY; break; case IS_ENCRYPTED_PRIVATE_KEY: case IS_PRIVATE_KEY: obj_type = SSL_OBJ_PKCS8; break; case IS_CERTIFICATE: obj_type = is_cacert ? SSL_OBJ_X509_CACERT : SSL_OBJ_X509_CERT; break; default: ret = SSL_ERROR_BAD_CERTIFICATE; goto error; } /* In a format we can now understand - so process it */ if ((ret = do_obj(ssl_ctx, obj_type, ssl_obj, password))) goto error; end += strlen(ends[i]); remain -= strlen(ends[i]); while (remain > 0 && (*end == '\r' || *end == '\n')) { end++; remain--; } where = end; break; } } ssl_obj_free(ssl_obj); ssl_obj = NULL; if (start == NULL) break; } error: ssl_obj_free(ssl_obj); return ret; }
std::string b64String::decode() { return base64_decode(this->str); }
static bool message_decode_body(struct message_decoder_context *ctx, struct message_block *input, struct message_block *output) { const unsigned char *data = NULL; size_t pos = 0, size = 0; const char *error; int ret; if (ctx->encoding_buf->used != 0) buffer_append(ctx->encoding_buf, input->data, input->size); switch (ctx->message_cte) { case MESSAGE_CTE_UNKNOWN: /* just skip this body */ return FALSE; case MESSAGE_CTE_78BIT: case MESSAGE_CTE_BINARY: i_assert(ctx->encoding_buf->used == 0); data = input->data; size = pos = input->size; break; case MESSAGE_CTE_QP: { i_assert(ctx->encoding_buf->used == 0); buffer_set_used_size(ctx->buf, 0); if (ctx->qp == NULL) ctx->qp = qp_decoder_init(ctx->buf); (void)qp_decoder_more(ctx->qp, input->data, input->size, &pos, &error); data = ctx->buf->data; size = ctx->buf->used; /* eat away all input. qp-decoder buffers it internally. */ pos = input->size; break; } case MESSAGE_CTE_BASE64: buffer_set_used_size(ctx->buf, 0); if (ctx->encoding_buf->used != 0) { ret = base64_decode(ctx->encoding_buf->data, ctx->encoding_buf->used, &pos, ctx->buf); } else { ret = base64_decode(input->data, input->size, &pos, ctx->buf); } if (ret < 0) { /* corrupted base64 data, don't bother with the rest of it */ return FALSE; } if (ret == 0) { /* end of base64 input */ pos = input->size; buffer_set_used_size(ctx->encoding_buf, 0); } data = ctx->buf->data; size = ctx->buf->used; break; } if (ctx->encoding_buf->used != 0) buffer_delete(ctx->encoding_buf, 0, pos); else if (pos != input->size) { buffer_append(ctx->encoding_buf, input->data + pos, input->size - pos); } if (ctx->binary_input) { output->data = data; output->size = size; } else { buffer_set_used_size(ctx->buf2, 0); if (ctx->translation_size != 0) translation_buf_decode(ctx, &data, &size); pos = size; (void)charset_to_utf8(ctx->charset_trans, data, &pos, ctx->buf2); if (pos != size) { ctx->translation_size = size - pos; i_assert(ctx->translation_size <= sizeof(ctx->translation_buf)); memcpy(ctx->translation_buf, data + pos, ctx->translation_size); } output->data = ctx->buf2->data; output->size = ctx->buf2->used; } output->hdr = NULL; return TRUE; }