static void _doc_process_var(doc_ptr doc, cptr name) { if (strcmp(name, "version") == 0) { string_ptr s = string_alloc_format("%d.%d.%d", VER_MAJOR, VER_MINOR, VER_PATCH); doc_insert(doc, string_buffer(s)); string_free(s); } else if (strlen(name) > 3 && strncmp(name, "FF_", 3) == 0) { char buf[100]; int f_idx; sprintf(buf, "%s", name + 3); f_idx = f_tag_to_index(buf); if (0 <= f_idx && f_idx < max_f_idx) { string_ptr s = string_alloc(); feature_type *feat = &f_info[f_idx]; string_printf(s, "<color:%c>%c</color>", attr_to_attr_char(feat->d_attr[F_LIT_STANDARD]), feat->d_char[F_LIT_STANDARD]); doc_insert(doc, string_buffer(s)); string_free(s); } } }
std::string GetLineWithSize(std::size_t const size, std::ifstream& stream) { std::unique_ptr<char[]> buffer(new char[size]); if (!stream.getline(&buffer[0], size).eof() && stream.fail()) { stream.clear(); std::string string_buffer(buffer.get()); string_buffer += GetLineWithSize(2 * size, stream); return std::move(string_buffer); } else { std::string string_buffer(buffer.get()); return std::move(string_buffer); } }
static STSStatus compute_signature(char* buffer, uint32_t bufferSize, char* paramsArray[], const uint32_t paramsCount, const char* accessKeySecret) { ////////////////////////////////////////////////////////////////////////// // sign uint32_t canonLen = 0; char canonicalizedQueryString[2048 * 3]; compose_canonicalized_query_string(canonicalizedQueryString, 2048 * 3, &canonLen, paramsArray, paramsCount); string_buffer(strToSign, 2048 * 3); string_buffer_initialize(strToSign); int fit; string_buffer_append(strToSign, "POST&%2F&", 9, fit); if (!fit) { return STSStatusUriTooLong; } string_buffer(percentTwice, 2048 * 3); string_buffer_initialize(percentTwice); percentEncode(percentTwice, canonicalizedQueryString, canonLen); string_buffer_append(strToSign, percentTwice, strlen(percentTwice), fit); //fprintf(stdout, "strToSign(%lu): %s\n", strlen(strToSign), strToSign); // Generate an HMAC-SHA-1 of the strToSign size_t akSecretLen = strlen(accessKeySecret); char newAccessKeySecret[akSecretLen + 1]; snprintf(newAccessKeySecret, akSecretLen+2, "%s&", accessKeySecret); unsigned char hmac[20]; STS_HMAC_SHA1(hmac, (unsigned char *) newAccessKeySecret, strlen(newAccessKeySecret), (unsigned char *) strToSign, strlen(strToSign)); // Now base-64 encode the results char b64[((20 + 1) * 4) / 3]; int b64Len = base64Encode(hmac, 20, b64); char b64Encoded[256]; if (!urlEncode(b64Encoded, b64, b64Len)) { return STSStatusUriTooLong; } snprintf(buffer, strlen(b64Encoded)+1, "%s", b64Encoded); return STSStatusOK; }
int msg_get_plain_text(int age, char *buffer, int max) { int ct = 0, i; doc_token_t token; msg_ptr msg = msg_get(age); cptr pos = string_buffer(msg->msg); bool done = FALSE; while (!done) { pos = doc_lex(pos, &token); if (token.type == DOC_TOKEN_EOF) break; if (token.type == DOC_TOKEN_TAG) continue; /* assume only color tags */ for (i = 0; i < token.size; i++) { if (ct >= max - 4) { buffer[ct++] = '.'; buffer[ct++] = '.'; buffer[ct++] = '.'; done = TRUE; break; } buffer[ct++] = token.pos[i]; } } buffer[ct] = '\0'; return ct; }
char port_read_char(port_t *port) { char res = EOF; assert(port_is_input(port)); if (port_is_input(port)) { switch (port->tag) { case _PORT_STRING: if (port->data.string_port.pos < string_length(port->data.string_port.buf)) res = string_buffer(port->data.string_port.buf)[port->data.string_port.pos++]; break; case _PORT_FILE: case _PORT_FILE_STD: res = port->data.file_port.peek_buf; if (res == EOF) res = fgetc(port->data.file_port.file); else port->data.file_port.peek_buf = EOF; break; } } if (res == '\n') port->line++; return res; }
char port_peek_char(port_t *port) { char res = EOF; assert(port_is_input(port)); if (port_is_input(port)) { switch (port->tag) { case _PORT_STRING: if (port->data.string_port.pos < string_length(port->data.string_port.buf)) res = string_buffer(port->data.string_port.buf)[port->data.string_port.pos]; break; case _PORT_FILE: case _PORT_FILE_STD: res = port->data.file_port.peek_buf; if (res == EOF) { res = fgetc(port->data.file_port.file); port->data.file_port.peek_buf = res; } break; } } return res; }
doc_pos_t doc_read_file(doc_ptr doc, FILE *fp) { string_ptr s = string_read_file(fp); doc_insert(doc, string_buffer(s)); string_free(s); return doc->cursor; }
vector<string> getMxStringArray(const mxArray *string_array_ptr) { /* result */ vector<string> string_vector; /* allocate and store chars in buffer */ const size_t char_buffer_len = mxGetNumberOfElements(string_array_ptr) + 1; boost::scoped_array<char> char_buffer(new char[char_buffer_len]); /* fill char buffer */ if (mxGetString(string_array_ptr, char_buffer.get(), (mwSize)char_buffer_len) != 0) return string_vector; /* Get the shape of the input mxArray. */ const size_t max_length = mxGetN(string_array_ptr); /* max length of strings */ const size_t count = mxGetM(string_array_ptr); /* number of strings */ boost::scoped_array<char> string_buffer(new char[max_length+1]); /* terminate string, other elements will be set in folling for loop */ string_buffer[max_length] = '\0'; for (size_t n=0; n<count; n++) { /* for each string get the column-major elements from char buffer */ for (size_t index=n, pos=0; index<char_buffer_len-1; index+=count) string_buffer[pos++] = char_buffer[index]; /* now string_buffer holds the nth element (and possibly multiple terminating symbols) */ string_vector.push_back(string(string_buffer.get())); } return string_vector; }
doc_pos_t doc_find_bookmark(doc_ptr doc, cptr name) { int i; for (i = 0; i < vec_length(doc->bookmarks); i++) { doc_bookmark_ptr mark = vec_get(doc->bookmarks, i); if (strcmp(name, string_buffer(mark->name)) == 0) return mark->pos; } return doc_pos_invalid(); }
doc_pos_t doc_cprintf(doc_ptr doc, byte a, const char *fmt, ...) { string_ptr s = string_alloc(); va_list vp; va_start(vp, fmt); string_vprintf(s, fmt, vp); va_end(vp); doc_insert_text(doc, a, string_buffer(s)); string_free(s); return doc->cursor; }
cptr port_name(port_t *port) { switch (port->tag) { case _PORT_STRING: return "MEMORY"; case _PORT_FILE: case _PORT_FILE_STD: return string_buffer(port->data.file_port.name); } return ""; }
app_action_t application_function_flash_checksum(string_t *src, string_t *dst) { unsigned int address, current, length, done; SHA_CTX sha_context; unsigned char sha_result[SHA_DIGEST_LENGTH]; string_new(, sha_string, SHA_DIGEST_LENGTH * 2 + 2); if(parse_uint(1, src, &address, 0, ' ') != parse_ok) { string_append(dst, "ERROR flash-checksum: address required\n"); return(app_action_error); } if(parse_uint(2, src, &length, 0, ' ') != parse_ok) { string_append(dst, "ERROR flash-checksum: length required\n"); return(app_action_error); } if((address % SPI_FLASH_SEC_SIZE) != 0) { string_append(dst, "ERROR: flash_checksum: address should be divisible by flash sector size"); return(app_action_error); } if((length % SPI_FLASH_SEC_SIZE) != 0) { string_append(dst, "ERROR: flash_checksum: length should be divisible by flash sector size"); return(app_action_error); } SHA1Init(&sha_context); for(current = address, done = 0; done < length; current += SPI_FLASH_SEC_SIZE, done += SPI_FLASH_SEC_SIZE) { spi_flash_read(current, string_buffer_nonconst(dst), SPI_FLASH_SEC_SIZE); SHA1Update(&sha_context, string_buffer(dst), SPI_FLASH_SEC_SIZE); } SHA1Final(sha_result, &sha_context); string_bin_to_hex(&sha_string, sha_result, SHA_DIGEST_LENGTH); string_clear(dst); string_format(dst, "OK flash-checksum: checksummed bytes: %u, from address: %u, checksum: ", done, address); string_append_string(dst, &sha_string); string_append(dst, "\n"); return(app_action_normal); }
app_action_t application_function_flash_read(string_t *src, string_t *dst) { unsigned int address, sector; SHA_CTX sha_context; unsigned char sha_result[SHA_DIGEST_LENGTH]; string_new(, sha_string, SHA_DIGEST_LENGTH * 2 + 2); if(string_size(&flash_sector_buffer) < SPI_FLASH_SEC_SIZE) { string_format(dst, "ERROR flash-read: flash sector buffer too small: %d\n", string_size(&flash_sector_buffer)); return(app_action_error); } if(parse_uint(1, src, &address, 0, ' ') != parse_ok) { string_append(dst, "ERROR flash-read: address required\n"); return(app_action_error); } if((address % SPI_FLASH_SEC_SIZE) != 0) { string_append(dst, "ERROR flash-read: address should be divisible by flash sector size"); return(app_action_error); } if((flash_sector_buffer_use != fsb_free) && (flash_sector_buffer_use != fsb_config_cache)) { string_format(dst, "ERROR: flash-read: sector buffer in use: %u\n", flash_sector_buffer_use); return(app_action_error); } flash_sector_buffer_use = fsb_ota; sector = address / SPI_FLASH_SEC_SIZE; spi_flash_read(sector * SPI_FLASH_SEC_SIZE, string_buffer_nonconst(&flash_sector_buffer), SPI_FLASH_SEC_SIZE); string_setlength(&flash_sector_buffer, SPI_FLASH_SEC_SIZE); SHA1Init(&sha_context); SHA1Update(&sha_context, string_buffer(&flash_sector_buffer), SPI_FLASH_SEC_SIZE); SHA1Final(sha_result, &sha_context); string_bin_to_hex(&sha_string, sha_result, SHA_DIGEST_LENGTH); string_format(dst, "OK flash-read: read bytes: %d, from address: %u (%u), checksum: ", SPI_FLASH_SEC_SIZE, address, sector); string_append_string(dst, &sha_string); string_append(dst, "\n"); return(app_action_normal); }
int doc_display_help_aux(cptr file_name, cptr topic, rect_t display) { int rc = _OK; FILE *fp = NULL; char path[1024]; char caption[1024]; doc_ptr doc = NULL; int top = 0; /* Check for file_name#topic from a lazy client */ if (!topic) { cptr pos = strchr(file_name, '#'); if (pos) { string_ptr name = string_copy_sn(file_name, pos - file_name); int result = doc_display_help_aux(string_buffer(name), pos + 1, display); string_free(name); return result; } } sprintf(caption, "Help file '%s'", file_name); path_build(path, sizeof(path), ANGBAND_DIR_HELP, file_name); fp = my_fopen(path, "r"); if (!fp) { cmsg_format(TERM_VIOLET, "Cannot open '%s'.", file_name); msg_print(NULL); return _OK; } doc = doc_alloc(MIN(80, display.cx)); doc_read_file(doc, fp); my_fclose(fp); if (topic) { doc_pos_t pos = doc_find_bookmark(doc, topic); if (doc_pos_is_valid(pos)) top = pos.y; } rc = doc_display_aux(doc, caption, top, display); doc_free(doc); return rc; }
void msg_on_save(savefile_ptr file) { int i; int count = msg_count(); if (compress_savefile && count > 40) count = 40; savefile_write_u16b(file, count); for (i = count - 1; i >= 0; i--) { msg_ptr m = msg_get(i); savefile_write_cptr(file, string_buffer(m->msg)); savefile_write_s32b(file, m->turn); savefile_write_s32b(file, m->count); savefile_write_byte(file, m->color); } }
std::string StringUtilities::ToString(const std::wstring& input) { // Assumption: The byte count of the resulting narrow string will be at most // four times the character count of the input wstring. Allocate the buffer // with that many char items (bytes) so that the first WideCharToMultiByte // call will succeed most of the time as an optimization. std::string output = ""; int wide_string_length = static_cast<int>(input.size()) + 1; int output_string_byte_count = wide_string_length * 4; std::vector<char> string_buffer(output_string_byte_count); bool convert_failed = (0 == ::WideCharToMultiByte(CP_UTF8, 0, input.c_str(), wide_string_length, &string_buffer[0], output_string_byte_count, NULL, NULL)); if (convert_failed) { if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // Buffer wasn't big enough. Call WideCharToMultiByte again with // NULL values to determine how big the buffer should be. output_string_byte_count = ::WideCharToMultiByte(CP_UTF8, 0, input.c_str(), wide_string_length, NULL, 0, NULL, NULL); string_buffer.resize(output_string_byte_count); convert_failed = (0 == ::WideCharToMultiByte(CP_UTF8, 0, input.c_str(), wide_string_length, &string_buffer[0], output_string_byte_count, NULL, NULL)); if (!convert_failed) { output = &string_buffer[0]; } } } else { output = &string_buffer[0]; } return output; }
doc_pos_t doc_next_bookmark_char(doc_ptr doc, doc_pos_t pos, int c) { int i; for (i = 0; i < vec_length(doc->bookmarks); i++) { doc_bookmark_ptr mark = vec_get(doc->bookmarks, i); cptr name; assert(mark->name); name = string_buffer(mark->name); if ( doc_pos_compare(pos, mark->pos) <= 0 /* Subtle: So I can wrap and start at (0,0) *and* pick up an initial topic */ && string_length(mark->name) > 0 && tolower(name[0]) == tolower(c) ) { return mark->pos; } } return doc_pos_invalid(); }
void msg_on_load(savefile_ptr file) { int i; int count = savefile_read_s16b(file); for (i = 0; i < count; i++) { s32b turn = 0; s32b count = 0; byte color = TERM_WHITE; string_ptr msg = 0; msg = savefile_read_string(file); turn = savefile_read_s32b(file); count = savefile_read_s32b(file); color = savefile_read_byte(file); _cmsg_add_aux(color, string_buffer(msg), turn, count); string_free(msg); } }
void _cmsg_add_aux(byte color, cptr str, int turn, int count) { msg_ptr m; /* Repeat last message? */ if (_msg_count) { m = msg_get(0); if (strcmp(string_buffer(m->msg), str) == 0) { m->count += count; m->turn = turn; m->color = color; return; } } m = _msgs[_msg_head]; if (!m) { m = _msg_alloc(NULL); _msgs[_msg_head] = m; _msg_count++; } else { string_clear(m->msg); string_shrink(m->msg, 128); } string_append_s(m->msg, str); m->turn = turn; m->count = count; m->color = color; _msg_head = (_msg_head + 1) % _msg_max; }
void gray_mage_gain_spell(void) { int item; if (p_ptr->blind || no_lite()) { msg_print("You cannot see!"); return; } if (p_ptr->confused) { msg_print("You are too confused!"); return; } if (!p_ptr->new_spells) { msg_print("You cannot learn any new spells!"); return; } item_tester_hook = _spell_book_p; if (get_item(&item, "Study which book?", "You have no books that you can read.", USE_INVEN)) { object_type *o_ptr = &inventory[item]; int spell_idx; _slot_info_ptr slot_ptr; /* Pick a spell to learn */ spell_idx = _choose_spell_to_gain(o_ptr); if (spell_idx == -1) return; /* Pick a slot for storage (possibly replacing an already learned spell) */ slot_ptr = _choose("Replace", _ALLOW_EMPTY | _SHOW_INFO); if (!slot_ptr) return; if (slot_ptr->realm != REALM_NONE) { string_ptr prompt = string_alloc_format( "Really replace %s? <color:y>[y/N]</color>", do_spell(slot_ptr->realm, slot_ptr->spell, SPELL_NAME)); if (msg_prompt(string_buffer(prompt), "ny", PROMPT_DEFAULT) == 'n') { string_free(prompt); return; } string_free(prompt); } /* Learn the spell: Note, we don't bother with spell_learned# and spell_order[], since these are hard coded for 2 spell realms. Hopefully, ticking up learned_spells is enough? */ p_ptr->learned_spells++; slot_ptr->realm = tval2realm(o_ptr->tval); slot_ptr->spell = spell_idx; msg_format("You have learned the spell '%s'.", do_spell(slot_ptr->realm, slot_ptr->spell, SPELL_NAME)); p_ptr->update |= PU_SPELLS; p_ptr->redraw |= PR_EFFECTS; energy_use = 100; } }
static void _doc_process_tag(doc_ptr doc, doc_tag_ptr tag) { if ( tag->type == DOC_TAG_CLOSE_COLOR || tag->type == DOC_TAG_CLOSE_STYLE || tag->type == DOC_TAG_CLOSE_INDENT ) { doc_pop_style(doc); } else if (tag->type == DOC_TAG_COLOR) { assert(tag->arg); if (tag->arg_size == 1) { if (tag->arg[0] == '*') doc_pop_style(doc); else { doc_style_t style = *doc_current_style(doc); /* copy */ switch (tag->arg[0]) { case 'd': style.color = TERM_DARK; break; case 'w': style.color = TERM_WHITE; break; case 's': style.color = TERM_SLATE; break; case 'o': style.color = TERM_ORANGE; break; case 'r': style.color = TERM_RED; break; case 'g': style.color = TERM_GREEN; break; case 'b': style.color = TERM_BLUE; break; case 'u': style.color = TERM_UMBER; break; case 'D': style.color = TERM_L_DARK; break; case 'W': style.color = TERM_L_WHITE; break; case 'v': style.color = TERM_VIOLET; break; case 'y': style.color = TERM_YELLOW; break; case 'R': style.color = TERM_L_RED; break; case 'G': style.color = TERM_L_GREEN; break; case 'B': style.color = TERM_L_BLUE; break; case 'U': style.color = TERM_L_UMBER; break; } doc_push_style(doc, &style); } } else { string_ptr arg = string_copy_sn(tag->arg, tag->arg_size); doc_style_t style = *doc_current_style(doc); /* copy */ doc_style_f f = _get_doc_style_f(doc, string_buffer(arg)); if (f) f(&style); {/* We don't copy the named style, just its color. */ /* Also, we damn well better push a style or we'll be upset when the good little user pops! */ doc_style_t copy = *doc_current_style(doc); copy.color = style.color; doc_push_style(doc, ©); } string_free(arg); } } else if (tag->type == DOC_TAG_INDENT) { doc_style_t style = *doc_current_style(doc); style.left = doc->cursor.x; doc_push_style(doc, &style); } else { string_ptr arg = string_copy_sn(tag->arg, tag->arg_size); switch (tag->type) { case DOC_TAG_STYLE: if (tag->arg_size == 1 && tag->arg[0] == '*') doc_pop_style(doc); else {/* Better silently add one if name doesn't exist ... */ doc_style_t copy = *doc_current_style(doc); doc_style_f f = _get_doc_style_f(doc, string_buffer(arg)); if (f) f(©); doc_push_style(doc, ©); } break; case DOC_TAG_VAR: _doc_process_var(doc, string_buffer(arg)); break; case DOC_TAG_TAB: { int pos = atoi(string_buffer(arg)) + doc_current_style(doc)->left; if (pos > doc->cursor.x) doc_insert_space(doc, pos - doc->cursor.x); else doc_rollback(doc, doc_pos_create(pos, doc->cursor.y)); break; } case DOC_TAG_TOPIC: { doc_bookmark_ptr mark = malloc(sizeof(doc_bookmark_t)); mark->name = arg; /* steal ownership */ arg = NULL; mark->pos = doc->cursor; vec_add(doc->bookmarks, mark); break; } case DOC_TAG_LINK: { doc_link_ptr link = malloc(sizeof(doc_link_t)); int split = string_chr(arg, 0, '#'); int ch = 'a' + int_map_count(doc->links); if (split >= 0) { substring_t left = string_left(arg, split); substring_t right = string_right(arg, string_length(arg) - split - 1); link->file = substring_copy(&left); link->topic = substring_copy(&right); } else { link->file = arg; /* steal ownership */ arg = NULL; link->topic = NULL; } link->location.start = doc->cursor; int_map_add(doc->links, ch, link); { /* TODO: This is flawed. Here's a real world example: "(see below <link:birth.txt#PrimaryStats>)." Can you see the problem? We might line break after "[a]" right before ").". Instead, "[a])." should be treated as the current word. To fix this, we'll need a parser with a token queue that we can push onto, but this raises storage issues. */ string_ptr s = string_alloc_format("<style:link>[%c]</style>", ch); doc_insert(doc, string_buffer(s)); string_free(s); link->location.stop = doc->cursor; } break; } } string_free(arg); } }
std::string StringUtilities::ToString(long input) { std::vector<char> string_buffer(MAX_DIGITS_OF_NUMBER); _i64toa_s(input, &string_buffer[0], MAX_DIGITS_OF_NUMBER, BASE_TEN_BASE); std::string string_value = &string_buffer[0]; return string_value; }
void S3_list_bucket(const S3BucketContext *bucketContext, const char *prefix, const char *marker, const char *delimiter, int maxkeys, S3RequestContext *requestContext, const S3ListBucketHandler *handler, void *callbackData) { // Compose the query params string_buffer(queryParams, 4096); string_buffer_initialize(queryParams); #define safe_append(name, value) \ do { \ int fit; \ if (amp) { \ string_buffer_append(queryParams, "&", 1, fit); \ if (!fit) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ } \ string_buffer_append(queryParams, name "=", \ sizeof(name "=") - 1, fit); \ if (!fit) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ amp = 1; \ char encoded[3 * 1024]; \ if (!urlEncode(encoded, value, 1024)) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ string_buffer_append(queryParams, encoded, strlen(encoded), \ fit); \ if (!fit) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ } while (0) int amp = 0; if (prefix) { safe_append("prefix", prefix); } if (marker) { safe_append("marker", marker); } if (delimiter) { safe_append("delimiter", delimiter); } if (maxkeys) { char maxKeysString[64]; snprintf(maxKeysString, sizeof(maxKeysString), "%d", maxkeys); safe_append("max-keys", maxKeysString); } ListBucketData *lbData = (ListBucketData *) malloc(sizeof(ListBucketData)); if (!lbData) { (*(handler->responseHandler.completeCallback)) (S3StatusOutOfMemory, 0, callbackData); return; } simplexml_initialize(&(lbData->simpleXml), &listBucketXmlCallback, lbData); lbData->responsePropertiesCallback = handler->responseHandler.propertiesCallback; lbData->listBucketCallback = handler->listBucketCallback; lbData->responseCompleteCallback = handler->responseHandler.completeCallback; lbData->callbackData = callbackData; string_buffer_initialize(lbData->isTruncated); string_buffer_initialize(lbData->nextMarker); initialize_list_bucket_data(lbData); // Set up the RequestParams RequestParams params = { HttpRequestTypeGET, // httpRequestType { bucketContext->hostName, // hostName bucketContext->bucketName, // bucketName bucketContext->protocol, // protocol bucketContext->uriStyle, // uriStyle bucketContext->accessKeyId, // accessKeyId bucketContext->secretAccessKey, // secretAccessKey bucketContext->securityToken }, // securityToken 0, // key queryParams[0] ? queryParams : 0, // queryParams 0, // subResource 0, // copySourceBucketName 0, // copySourceKey 0, // getConditions 0, // startByte 0, // byteCount 0, // putProperties &listBucketPropertiesCallback, // propertiesCallback 0, // toS3Callback 0, // toS3CallbackTotalSize &listBucketDataCallback, // fromS3Callback &listBucketCompleteCallback, // completeCallback lbData // callbackData }; // Perform the request request_perform(¶ms, requestContext); }
static STSStatus compose_post_data(char* buffer, uint32_t bufferSize, CommonRequestContext* commonContext, AssumeRoleRequestContext* assumeRoleContext) { string_buffer(queryParams, 2048*3); string_buffer_initialize(queryParams); char* queryParamsArray[32]; int paramsCount = 0; int len = 0; int start = 0; int amp = 0; #define safe_append(isNewParam, name, value) \ do { \ int fit; \ start = len; \ if (amp) { start++; } \ if (isNewParam) { \ queryParamsArray[paramsCount++] = &(queryParams[start]); \ } \ if (amp) { \ string_buffer_append(queryParams, "&", 1, fit); \ if (!fit) { \ return STSStatusUriTooLong; \ } \ len++; \ } \ string_buffer_append(queryParams, name "=", \ sizeof(name "=") - 1, fit); \ if (!fit) { \ return STSStatusUriTooLong; \ } \ len += strlen(name) + 1; \ amp = 1; \ string_buffer_append(queryParams, value, strlen(value), fit); \ len += strlen(value); \ } while (0) time_t now = time(NULL); char timebuf[256]; strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&now)); STSUUID uuid; char* uuidString; uuid_create(&uuid); uuid_to_string(&uuid, &uuidString); char durationSeconds[10]; snprintf(durationSeconds, 10, "%d", assumeRoleContext->durationSeconds); safe_append(1, "Format", "JSON"); safe_append(1, "Version", "2015-04-01"); safe_append(1, "SignatureVersion", "1.0"); safe_append(1, "SignatureMethod", "HMAC-SHA1"); safe_append(1, "SignatureNonce", uuidString); safe_append(1, "Timestamp", timebuf); safe_append(1, "Action", commonContext->action); safe_append(1, "AccessKeyId", commonContext->accessKeyId); safe_append(1, "RoleArn", assumeRoleContext->RoleArn); safe_append(1, "RoleSessionName", assumeRoleContext->RoleSessionName); safe_append(1, "Policy", assumeRoleContext->policy); safe_append(1, "DurationSeconds", durationSeconds); params_array_sort(queryParamsArray, paramsCount); string_buffer(signature, 256); string_buffer_initialize(signature); compute_signature(signature, 256, queryParamsArray, paramsCount, commonContext->accessKeySecret); compose_url_encoded_post_data(buffer, bufferSize, queryParams, strlen(queryParams), signature); free(uuidString); return STSStatusOK; }
STSStatus STS_assume_role(const char* roleArn, const char* roleSessionName, const char* policy, const uint32_t durationSeconds, const char* accessKeyId, const char* accessKeySecret, STSData* assumeRoleData, char* errorMessage) { int status; int httpResponseCode; CommonRequestContext commonContext = {STSProtocolHTTPS, STS_DEFAULT_HOSTNAME, accessKeyId, accessKeySecret, "AssumeRole"}; AssumeRoleRequestContext assumeRoleContext = {roleArn, roleSessionName, policy, durationSeconds}; string_buffer(response, MAX_RESPONSE_SIZE); string_buffer_initialize(response); string_buffer(postData, 2048*3); string_buffer_initialize(postData); compose_post_data(postData, 2048*3, &commonContext, &assumeRoleContext); RequestParams params = { HttpRequestTypePOST, // httpRequestType commonContext, // commonContext assumeRoleContext, // assumeRoleContext postData // postData }; status = request_perform(¶ms, &httpResponseCode, response); if (200 == httpResponseCode) { parse_sts_result(strlen(response), response, assumeRoleData); } else if( 0 != httpResponseCode) { if (400 == httpResponseCode) { status = STSStatusInvalidParameter; } else if (403 == httpResponseCode) { status = STSStatusNoPermission; } else if (500 == httpResponseCode) { status = STSStatusInternalError; } else if (404 == httpResponseCode) { status = STSStatusInvalidAcccessKeyId; } snprintf(errorMessage, strlen(response)+1, "%s", response); } else if (0 == httpResponseCode) { switch (status) { case STSStatusOutOfMemory: snprintf(errorMessage, 256, "%s.", "Out of memory"); break; case STSStatusNameLookupError: snprintf(errorMessage, 256, "%s %s.", "Failed to lookup STS server:", commonContext.hostname); break; case STSStatusFailedToConnect: snprintf(errorMessage, 256, "%s %s.", "Failed to connect to STS server:", commonContext.hostname); break; case STSStatusConnectionFailed: snprintf(errorMessage, 256, "%s.", "Write Error or Operation Timeout"); break; case STSStatusServerFailedVerification: snprintf(errorMessage, 256, "%s.", "SSL verification failed"); break; case STSStatusInternalError: snprintf(errorMessage, 256, "%s.", "Internal Error"); break; default: break; } } return status; }
static void _doc_write_html_file(doc_ptr doc, FILE *fp) { doc_pos_t pos; doc_char_ptr cell; byte old_a = _INVALID_COLOR; int bookmark_idx = 0; doc_bookmark_ptr next_bookmark = NULL; vec_ptr links = doc_get_links(doc); int link_idx = 0; doc_link_ptr next_link = NULL; if (bookmark_idx < vec_length(doc->bookmarks)) next_bookmark = vec_get(doc->bookmarks, bookmark_idx); if (link_idx < vec_length(links)) next_link = vec_get(links, link_idx); fprintf(fp, "<!DOCTYPE html>\n<html>\n"); if (string_length(doc->html_header)) fprintf(fp, "%s\n", string_buffer(doc->html_header)); fprintf(fp, "<body text=\"#ffffff\" bgcolor=\"#000000\"><pre>\n"); for (pos.y = 0; pos.y <= doc->cursor.y; pos.y++) { int cx = doc->width; pos.x = 0; if (pos.y == doc->cursor.y) cx = doc->cursor.x; cell = doc_char(doc, pos); if (next_bookmark && pos.y == next_bookmark->pos.y) { fprintf(fp, "<a name=\"%s\"></a>", string_buffer(next_bookmark->name)); bookmark_idx++; if (bookmark_idx < vec_length(doc->bookmarks)) next_bookmark = vec_get(doc->bookmarks, bookmark_idx); else next_bookmark = NULL; } for (; pos.x < cx; pos.x++) { char c = cell->c; byte a = cell->a & 0x0F; if (next_link) { if (doc_pos_compare(next_link->location.start, pos) == 0) { string_ptr s; int pos = string_last_chr(next_link->file, '.'); if (pos >= 0) { s = string_copy_sn(string_buffer(next_link->file), pos + 1); string_append_s(s, "html"); } else s = string_copy(next_link->file); fprintf(fp, "<a href=\"%s", string_buffer(s)); if (next_link->topic) fprintf(fp, "#%s", string_buffer(next_link->topic)); fprintf(fp, "\">"); string_free(s); } if (doc_pos_compare(next_link->location.stop, pos) == 0) { fprintf(fp, "</a>"); link_idx++; if (link_idx < vec_length(links)) next_link = vec_get(links, link_idx); else next_link = NULL; } } if (!c) break; if (a != old_a && c != ' ') { if (old_a != _INVALID_COLOR) fprintf(fp, "</font>"); fprintf(fp, "<font color=\"#%02x%02x%02x\">", angband_color_table[a][1], angband_color_table[a][2], angband_color_table[a][3] ); old_a = a; } switch (c) { case '&': fprintf(fp, "&"); break; case '<': fprintf(fp, "<"); break; case '>': fprintf(fp, ">"); break; default: fprintf(fp, "%c", c); break; } cell++; } fputc('\n', fp); } fprintf(fp, "</font>"); fprintf(fp, "</pre></body></html>\n"); vec_free(links); }
int doc_display_aux(doc_ptr doc, cptr caption, int top, rect_t display) { int rc = _OK; int i; char finder_str[81]; char back_str[81]; int page_size; bool done = FALSE; strcpy(finder_str, ""); page_size = display.cy - 4; if (top < 0) top = 0; if (top > doc->cursor.y - page_size) top = MAX(0, doc->cursor.y - page_size); for (i = 0; i < display.cy; i++) Term_erase(display.x, display.y + i, display.cx); while (!done) { int cmd; Term_erase(display.x, display.y, display.cx); put_str(format("[%s, Line %d/%d]", caption, top, doc->cursor.y), display.y, display.x); doc_sync_term(doc, doc_region_create(0, top, doc->width, top + page_size - 1), doc_pos_create(display.x, display.y + 2)); Term_erase(display.x, display.y + display.cy - 1, display.cx); put_str("[Press ESC to exit. Press ? for help]", display.y + display.cy - 1, display.x); cmd = inkey_special(TRUE); if ('a' <= cmd && cmd <= 'z') { doc_link_ptr link = int_map_find(doc->links, cmd); if (link) { rc = doc_display_help_aux(string_buffer(link->file), string_buffer(link->topic), display); if (rc == _UNWIND) done = TRUE; continue; } } switch (cmd) { case '?': if (!strstr(caption, "helpinfo.txt")) { rc = doc_display_help_aux("helpinfo.txt", NULL, display); if (rc == _UNWIND) done = TRUE; } break; case ESCAPE: done = TRUE; break; case 'q': done = TRUE; rc = _UNWIND; break; case SKEY_TOP: case '7': top = 0; break; case SKEY_BOTTOM: case '1': top = MAX(0, doc->cursor.y - page_size); break; case SKEY_PGUP: case '9': top -= page_size; if (top < 0) top = 0; break; case SKEY_PGDOWN: case '3': top += page_size; if (top > doc->cursor.y - page_size) top = MAX(0, doc->cursor.y - page_size); break; case SKEY_UP: case '8': top--; if (top < 0) top = 0; break; case SKEY_DOWN: case '2': top++; if (top > doc->cursor.y - page_size) top = MAX(0, doc->cursor.y - page_size); break; case '>': { doc_pos_t pos = doc_next_bookmark(doc, doc_pos_create(doc->width - 1, top)); if (doc_pos_is_valid(pos)) { top = pos.y; if (top > doc->cursor.y - page_size) top = MAX(0, doc->cursor.y - page_size); } break; } case '<': { doc_pos_t pos = doc_prev_bookmark(doc, doc_pos_create(0, top)); if (doc_pos_is_valid(pos)) top = pos.y; else top = 0; break; } case '|': { FILE *fp2; char buf[1024]; char name[82]; int cb; int format = DOC_FORMAT_TEXT; strcpy(name, string_buffer(doc->name)); if (!get_string("File name: ", name, 80)) break; path_build(buf, sizeof(buf), ANGBAND_DIR_USER, name); fp2 = my_fopen(buf, "w"); if (!fp2) { msg_format("Failed to open file: %s", buf); break; } cb = strlen(buf); if (cb > 5 && strcmp(buf + cb - 5, ".html") == 0) format = DOC_FORMAT_HTML; else if (cb > 4 && strcmp(buf + cb - 4, ".htm") == 0) format = DOC_FORMAT_HTML; doc_write_file(doc, fp2, format); my_fclose(fp2); msg_format("Created file: %s", buf); msg_print(NULL); break; } case '/': Term_erase(display.x, display.y + display.cy - 1, display.cx); put_str("Find: ", display.y + display.cy - 1, display.x); strcpy(back_str, finder_str); if (askfor(finder_str, 80)) { if (finder_str[0]) { doc_pos_t pos = doc->selection.stop; if (!doc_pos_is_valid(pos)) pos = doc_pos_create(0, top); pos = doc_find_next(doc, finder_str, pos); if (doc_pos_is_valid(pos)) { top = pos.y; if (top > doc->cursor.y - page_size) top = MAX(0, doc->cursor.y - page_size); } } } else strcpy(finder_str, back_str); break; case '\\': Term_erase(display.x, display.y + display.cy - 1, display.cx); put_str("Find: ", display.y + display.cy - 1, display.x); strcpy(back_str, finder_str); if (askfor(finder_str, 80)) { if (finder_str[0]) { doc_pos_t pos = doc->selection.start; if (!doc_pos_is_valid(pos)) pos = doc_pos_create(doc->width, top + page_size); pos = doc_find_prev(doc, finder_str, pos); if (doc_pos_is_valid(pos)) { top = pos.y; if (top > doc->cursor.y - page_size) top = MAX(0, doc->cursor.y - page_size); } } } else strcpy(finder_str, back_str); break; default: { /* BETA: Any unhandled keystroke will navigate to the next topic based upon a comparison of the first letter. This is nice, say, for viewing the Character Sheet and navigating to the various sections */ doc_pos_t pos = doc_next_bookmark_char(doc, doc_pos_create(1, top), cmd); if (!doc_pos_is_valid(pos)) /* wrap */ pos = doc_next_bookmark_char(doc, doc_pos_create(0, 0), cmd); if (doc_pos_is_valid(pos)) { top = pos.y; if (top > doc->cursor.y - page_size) top = MAX(0, doc->cursor.y - page_size); } } } } return rc; }
void port_write_string(port_t *port, string_t *s) { port_write_cptr(port, string_buffer(s)); }
void S3_list_parts(S3BucketContext *bucketContext, const char *key, const char *partnumbermarker, const char *uploadid, const char *encodingtype, int maxparts, S3RequestContext *requestContext, const S3ListPartsHandler *handler, void *callbackData) { // Compose the query params string_buffer(queryParams, 4096); string_buffer_initialize(queryParams); #define safe_append(name, value) \ do { \ int fit; \ if (amp) { \ string_buffer_append(queryParams, "&", 1, fit); \ if (!fit) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ } \ string_buffer_append(queryParams, name "=", \ sizeof(name "=") - 1, fit); \ if (!fit) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ amp = 1; \ char encoded[3 * 1024]; \ if (!urlEncode(encoded, value, 1024)) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ string_buffer_append(queryParams, encoded, strlen(encoded), \ fit); \ if (!fit) { \ (*(handler->responseHandler.completeCallback)) \ (S3StatusQueryParamsTooLong, 0, callbackData); \ return; \ } \ } while (0) char subResource[512]; snprintf(subResource, 512, "uploadId=%s", uploadid); int amp = 0; if (partnumbermarker && *partnumbermarker) { safe_append("part-number-marker", partnumbermarker); } if (encodingtype && *encodingtype) { safe_append("encoding-type", encodingtype); } if (maxparts) { char maxPartsString[64]; snprintf(maxPartsString, sizeof(maxPartsString), "%d", maxparts); safe_append("max-parts", maxPartsString); } ListPartsData *lpData = (ListPartsData *) malloc(sizeof(ListPartsData)); if (!lpData) { (*(handler->responseHandler.completeCallback)) (S3StatusOutOfMemory, 0, callbackData); return; } simplexml_initialize(&(lpData->simpleXml), &listPartsXmlCallback, lpData); lpData->responsePropertiesCallback = handler->responseHandler.propertiesCallback; lpData->listPartsCallback = handler->responseXmlCallback; lpData->responseCompleteCallback = handler->responseHandler.completeCallback; lpData->callbackData = callbackData; string_buffer_initialize(lpData->isTruncated); string_buffer_initialize(lpData->nextPartNumberMarker); string_buffer_initialize(lpData->initiatorId); string_buffer_initialize(lpData->initiatorDisplayName); string_buffer_initialize(lpData->ownerId); string_buffer_initialize(lpData->ownerDisplayName); string_buffer_initialize(lpData->storageClass); initialize_list_parts_data(lpData); lpData->handlePartsStart = 0; // Set up the RequestParams RequestParams params = { HttpRequestTypeGET, // httpRequestType { bucketContext->hostName, // hostName bucketContext->bucketName, // bucketName bucketContext->protocol, // protocol bucketContext->uriStyle, // uriStyle bucketContext->accessKeyId, // accessKeyId bucketContext->secretAccessKey, // secretAccessKey bucketContext->securityToken }, // securityToken key, // key queryParams[0] ? queryParams : 0, // queryParams subResource, // subResource 0, // copySourceBucketName 0, // copySourceKey 0, // getConditions 0, // startByte 0, // byteCount 0, // putProperties &listPartsPropertiesCallback, // propertiesCallback 0, // toS3Callback 0, // toS3CallbackTotalSize &listPartsDataCallback, // fromS3Callback &listPartsCompleteCallback, // completeCallback lpData // callbackData }; // Perform the request request_perform(¶ms, requestContext); }
int jass_call_closure(lua_State* L) { lua::jassbind* lj = (lua::jassbind*)L; if (!is_gaming()) { lj->pushnil(); return 1; } native_function::native_function* nf = (native_function::native_function*)lj->tounsigned(lua_upvalueindex(1)); size_t param = nf->get_param().size(); if ((int)param > lj->gettop()) { lj->pushnil(); return 1; } std::unique_ptr<uintptr_t[]> buffer(new uintptr_t[param]); std::vector<jass::jreal_t> real_buffer(param); std::vector<std::unique_ptr<jass::string_fake>> string_buffer(param); for (size_t i = 0; i < param; ++i) { native_function::variable_type vt = nf->get_param()[i]; switch (vt) { case native_function::TYPE_BOOLEAN: buffer[i] = lj->read_boolean(i+1); break; case native_function::TYPE_CODE: buffer[i] = (jass::jcode_t)util::singleton_nonthreadsafe<jump_func>::instance().create(lua::callback(lj, i+1), 'YDWE'); break; case native_function::TYPE_HANDLE: buffer[i] = lj->read_handle(i+1); break; case native_function::TYPE_INTEGER: buffer[i] = lj->read_integer(i+1); break; case native_function::TYPE_REAL: real_buffer[i] = lj->read_real(i+1); buffer[i] = (uintptr_t)&real_buffer[i]; break; case native_function::TYPE_STRING: string_buffer[i].reset(new jass::string_fake(lj->tostring(i+1))); buffer[i] = (jass::jstring_t)*string_buffer[i]; break; default: assert(false); buffer[i] = 0; break; } } uintptr_t retval = nf->call(buffer.get()); switch (nf->get_return()) { case native_function::TYPE_NOTHING: return 0; case native_function::TYPE_BOOLEAN: lj->push_boolean(retval); return 1; case native_function::TYPE_CODE: lj->push_code(retval); return 1; case native_function::TYPE_HANDLE: lj->push_handle(retval); return 1; case native_function::TYPE_INTEGER: lj->push_integer(retval); return 1; case native_function::TYPE_REAL: lj->push_real(retval); return 1; case native_function::TYPE_STRING: lj->push_string(retval); return 1; default: assert(false); break; } return 0; }