int String_find(bstring in, bstring what) { const unsigned char *found = NULL; const unsigned char *haystack = (const unsigned char *)bdata(in); ssize_t hlen = blength(in); const unsigned char *needle = (const unsigned char *)bdata(what); ssize_t nlen = blength(what); size_t skip_chars[UCHAR_MAX + 1] = { 0 }; String_setup_skip_chars(skip_chars, needle, nlen); found = String_base_search(haystack, hlen, needle, nlen, skip_chars); return found != NULL ? found - haystack : -1; }
static inline void StringScanner_set_needle(StringScanner * scan, bstring tofind) { scan->needle = (const unsigned char *)bdata(tofind); scan->nlen = blength(tofind); String_setup_skip_chars(scan->skip_chars, scan->needle, scan->nlen); }
int test2 (void) { struct tagbstring t = bsStatic ("Hello world"); bstring b; int ret = 0, reto; printf ("TEST: bSetChar function.\n"); ret += 0 <= bSetChar (&t, 4, ','); ret += 0 > bSetChar (b = bstrcpy (&t), 4, ','); ret += 0 >= biseqcstr (b, "Hell, world"); ret += 0 <= bSetChar (b, -1, 'x'); b->slen = 2; ret += 0 > bSetChar (b, 1, 'i'); ret += 0 >= biseqcstr (b, "Hi"); ret += 0 > bSetChar (b, 2, 's'); ret += 0 >= biseqcstr (b, "His"); ret += 0 > bSetChar (b, 1, '\0'); ret += blength (b) != 3; ret += bchare (b, 0, '?') != 'H'; ret += bchare (b, 1, '?') != '\0'; ret += bchare (b, 2, '?') != 's'; bdestroy (b); printf ("\t# failures: %d\n", ret); reto = ret; ret = 0; printf ("TEST: bSetCstrChar function.\n"); ret += 0 <= bSetCstrChar (&t, 4, ','); ret += 0 > bSetCstrChar (b = bstrcpy (&t), 4, ','); ret += 0 >= biseqcstr (b, "Hell, world"); ret += 0 <= bSetCstrChar (b, -1, 'x'); b->slen = 2; ret += 0 > bSetCstrChar (b, 1, 'i'); ret += 0 >= biseqcstr (b, "Hi"); ret += 0 > bSetCstrChar (b, 2, 's'); ret += 0 >= biseqcstr (b, "His"); ret += 0 > bSetCstrChar (b, 1, '\0'); ret += blength (b) != 1; ret += bchare (b, 0, '?') != 'H'; bdestroy (b); printf ("\t# failures: %d\n", ret); return reto + ret; }
static inline void handler_cap_payload(bstring payload) { if(payload->data[payload->slen - 1] == '\0') { btrunc(payload, blength(payload)-1); } else if(payload->data[payload->slen] != '\0') { bconchar(payload, '\0'); } }
//////////////////////////////////////////////////////////// /// Skip until the end of line //////////////////////////////////////////////////////////// UInt32 LexerNextLine(struct Lexer * LexPtr) { UInt32 Result = LEXER_EOF; // Skip separators if (!LexerOff(LexPtr)) { LexerSkip(LexPtr, LEXER_SEPARATOR); } // Skip the garbage if (!LexerOff(LexPtr)) { LexerNextTo(LexPtr, "\n"); if (!LexerOff(LexPtr)) { // Garbage found if (blength(LexerItemGet(LexPtr)) > 0) { Result = LEXER_ERROR; } bdestroy(LexerItemGet(LexPtr)); } } if (!LexerOff(LexPtr)) { LexerNextChar(LexPtr, "\n"); if (!LexerOff(LexPtr)) { if (blength(LexerItemGet(LexPtr)) > 0 && Result != LEXER_ERROR) { // '\n' found Result = LEXER_OK; } bdestroy(LexerItemGet(LexPtr)); } } return Result; }
int Dir_serve_file(Dir *dir, Request *req, Connection *conn) { FileRecord *file = NULL; bstring resp = NULL; bstring path = Request_path(req); bstring pattern = req->pattern; int rc = 0; int is_get = biseq(req->request_method, &HTTP_GET); int is_head = is_get ? 0 : biseq(req->request_method, &HTTP_HEAD); check(path, "Request had not path. That's weird."); req->response_size = 0; if(!(is_get || is_head)) { req->status_code = 405; rc = Response_send_status(conn, &HTTP_405); check_debug(rc == blength(&HTTP_405), "Failed to send 405 to client."); return -1; } else { file = Dir_resolve_file(dir, pattern, path); resp = Dir_calculate_response(req, file); if(resp) { rc = Response_send_status(conn, resp); check_debug(rc == blength(resp), "Failed to send error response on file serving."); } else if(is_get) { rc = Dir_stream_file(file, conn); req->response_size = rc; check_debug(rc == file->sb.st_size, "Didn't send all of the file, sent %d of %s.", rc, bdata(path)); } else if(is_head) { rc = Dir_send_header(file, conn); check_debug(rc, "Failed to write header to socket."); } else { sentinel("How the hell did you get to here. Tell Zed."); } FileRecord_release(file); return 0; } sentinel("Invalid code branch, Tell Zed you have magic."); error: FileRecord_release(file); return -1; }
bool do_uninstall_all(CURL* curl) { // define used variables DIR* dir; bool something_was_removed; struct dirent* entry; bstring fname, sstr; bstring ext = bfromcstr(".lua"); bstring modpath = osutil_getmodulepath(); // Attempt to open the modules directory. dir = opendir(modpath->data); if (dir == NULL) { printd(LEVEL_ERROR, "unable to query local repository.\n"); return 1; } bdestroy(modpath); // iterate through the installed modules something_was_removed = false; while ((entry = readdir(dir)) != NULL) { fname = bfromcstr(&entry->d_name[0]); if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR) { bdestroy(fname); continue; } if (entry->d_type != DT_REG) { bdestroy(fname); continue; } sstr = bmidstr(fname, 0, blength(fname) - 4); do_uninstall(curl, bfromcstr(sstr->data)); something_was_removed = true; bdestroy(sstr); bdestroy(fname); } if (!something_was_removed) printd(LEVEL_DEFAULT, "No changes were made.\n"); return 0; }
// Calculates the total number of bytes needed to store the property. // // property - The property. // // Returns the number of bytes required to store the property. size_t sky_property_sizeof(sky_property *property) { size_t sz = 0; sz += minipack_sizeof_map(2); sz += minipack_sizeof_raw(strlen("id")) + strlen("id"); sz += minipack_sizeof_int(property->id); sz += minipack_sizeof_raw(strlen("type")) + strlen("type"); sz += minipack_sizeof_uint(property->type); sz += minipack_sizeof_raw(strlen("dataType")) + strlen("dataType"); bstring data_type_str = sky_data_type_to_str(property->data_type); sz += blength(data_type_str); bdestroy(data_type_str); sz += minipack_sizeof_raw(strlen("name")) + strlen("name"); sz += blength(property->name); return sz; }
void irc_write(bstring message) { int n; n = write(sockfd, bdata(bformat("%s\r\n", bdata(message))), blength(message)+2); if (n < 0) perror("ERROR writing to socket"); printf("%s\n", bdata(message)); }
static int parse_bind_address(allium_ptcfg *cfg, const char *addrs) { struct bstrList *l; struct tagbstring str; int i, j; assert(NULL != cfg); if (NULL == addrs) { fprintf(stdout, "ENV-ERROR No Bind Addresses\n"); return (-1); } btfromcstr(str, addrs); if (0 == btlength(str)) { fprintf(stdout, "ENV-ERROR Empty Bind Address\n"); return (-1); } l = bsplit(&str, ','); if (NULL == l) { fprintf(stdout, "ENV-ERROR OOM parsing Bind Addresses\n"); return (-1); } if (l->qty != cfg->nr_methods) { fprintf(stdout, "ENV-ERROR Malformed Bind Addresses\n"); bstrListDestroy(l); return (-1); } for (i = 0; i < l->qty; i++) { /* * Per pt-spec.txt, the order is identical to the transport * list. I have no idea what is supposed to happen when * the transport list is wildcarded, so this routine will * currently fail gracefully. */ j = bstrrchr(l->entry[i], '-'); if ((j != blength(cfg->methods[i].name)) || bstrncmp(l->entry[i], cfg->methods[i].name, j - 1)) { fprintf(stdout, "ENV-ERROR Unexpected method in Bind Address\n"); bstrListDestroy(l); return (-1); } cfg->methods[i].bind_addr_len = sizeof(cfg->methods[i].bind_addr); if (parse_addr(bdataofs(l->entry[i], j + 1), (struct sockaddr *)&cfg->methods[i].bind_addr, &cfg->methods[i].bind_addr_len)) { fprintf(stdout, "ENV-ERROR Invalid address in Bind Address (%s)\n", bdata(l->entry[i])); bstrListDestroy(l); return (-1); } cfg->methods[i].has_bind_addr = 1; } bstrListDestroy(l); return (0); }
int mongrel2_ws_reply(mongrel2_socket *pub_socket, mongrel2_request *req, bstring data){ size_t req_len = blength(data); uint8_t *req_data = (uint8_t*)bdata(data); size_t payload_len = 0; uint8_t *payload_data = NULL; // Simplest code but seems to be unsafe with chrome 14? int retval = mongrel2_ws_frame_create(0,req_len,&payload_len,&payload_data); if(retval != 0){ fprintf(stderr,"mongrel2_ws_reply failed with errno %d\n",retval); return -1; } mongrel2_ws_frame_set_payload(payload_len,payload_data,req_len,req_data); mongrel2_ws_frame_set_opcode(payload_len,payload_data,OP_TEXT); mongrel2_ws_frame_set_fin(payload_len,payload_data); // Instead, let's chunk it to a bunch of small messages // int fullchunks = req_len % WEBSOCKET_SMALL_MAX; // int leftoverbytes = req_len / WEBSOCKET_SMALL_MAX; // bstring chunk; // for(int i=0; i<fullchunks; i++){ // uint8_t chunk_payload[WEBSOCKET_SMALL_MAX]; // chunk = bmidstr(data,i*WEBSOCKET_SMALL_MAX,i*WEBSOCKET_SMALL_MAX+WEBSOCKET_SMALL_MAX-1); // fullchunks--; // } #ifndef NDEBUG mongrel2_ws_frame_debug(payload_len,payload_data); #endif bstring outgoing = blk2bstr(payload_data,payload_len); assert(blength(outgoing) == payload_len); mongrel2_reply(pub_socket,req,outgoing); free(payload_data); bdestroy(outgoing); return 0; }
int Command_access_logs(Command *cmd) { bstring log_filename = option(cmd, "log", "logs/access.log"); check(log_filename, "Invalid log file given."); FILE *log_file = fopen(bdata(log_filename), "r"); check(log_file != NULL, "Failed to open log file: %s", bdata(log_filename)); int line_number = 0; bstring line; while ((line = bgets((bNgetc) fgetc, log_file, '\n')) != NULL) { line_number++; tns_value_t *log_item = tns_parse(bdata(line), blength(line), NULL); if (log_item == NULL || tns_get_type(log_item) != tns_tag_list || darray_end(log_item->value.list) < 9 ) { log_warn("Malformed log line: %d.", line_number); continue; } darray_t *entries = log_item->value.list; bstring hostname = darray_get_as(entries, 0, string); bstring remote_addr = darray_get_as(entries, 1, string); long remote_port = darray_get_as(entries, 2, number); long timestamp = darray_get_as(entries, 3, number); bstring request_method = darray_get_as(entries, 4, string); bstring request_path = darray_get_as(entries, 5, string); bstring version = darray_get_as(entries, 6, string); long status = darray_get_as(entries, 7, number); long size = darray_get_as(entries, 8, number); printf("[%ld] %s:%ld %s \"%s %s %s\" %ld %ld\n", timestamp, bdata(remote_addr), remote_port, bdata(hostname), bdata(request_method), bdata(request_path), bdata(version), status, size); tns_value_destroy(log_item); } return 0; error: return -1; }
char *test_search_exact() { void *res = TSTree_search(node, bdata(&test1), blength(&test1)); mu_assert(res == valueA, "got the wrong value back, should get A not B."); res = TSTree_search(node, "TESTNO", strlen("TESTNO")); mu_assert(res == NULL, "Should not find anything."); return NULL; }
static inline int deliver_payload(int raw, int fd, Connection *conn, bstring payload) { int rc = 0; if(raw) { debug("Sending raw message to %d length %d", fd, blength(payload)); rc = Connection_deliver_raw(conn, payload); check(rc != -1, "Error sending raw message to HTTP listener on FD %d, closing them.", fd); } else { debug("Sending BASE64 message to %d length %d", fd, blength(payload)); handler_cap_payload(payload); rc = Connection_deliver(conn, payload); check(rc != -1, "Error sending to MSG listener on FD %d, closing them.", fd); } return 0; error: return -1; }
// Calculates the total number of bytes needed to store the action. // // action - The action. // // Returns the number of bytes required to store the action. size_t sky_action_sizeof(sky_action *action) { size_t sz = 0; sz += minipack_sizeof_map(SKY_ACTION_KEY_COUNT); sz += minipack_sizeof_raw((&SKY_ACTION_ID_STR)->slen) + (&SKY_ACTION_ID_STR)->slen; sz += minipack_sizeof_uint(action->id); sz += minipack_sizeof_raw((&SKY_ACTION_NAME_STR)->slen) + (&SKY_ACTION_NAME_STR)->slen; sz += blength(action->name); return sz; }
static int test13_fgetc (void * ctx) { struct vfgetc * vctx = (struct vfgetc *) ctx; int c; if (NULL == vctx || NULL == vctx->base) return EOF; if (vctx->ofs >= blength (vctx->base)) return EOF; c = bchare (vctx->base, vctx->ofs, EOF); vctx->ofs++; return c; }
Request *fake_req(const char *method, const char *path) { int rc = 0; size_t nparsed = 0; Request *req = Request_create(); Request_start(req); bstring p = bfromcstr(path); bstring rp = bformat(REQ_PATTERN, method, bdata(p)); rc = Request_parse(req, bdata(rp), blength(rp), &nparsed); check(rc != 0, "Failed to parse request."); check(nparsed == blength(rp), "Failed to parse all of request."); return req; error: return NULL; }
char *test_gets() { bstring rbs1 = NULL; rbs1 = RingBuffer_gets(buffer, blength(bss1)); mu_assert(rbs1 != NULL, "Error getting first bstring from ringbuffer."); mu_assert(bstrcmp(rbs1, bss1) == 0, "The returned bstring should be equal to bstring1."); return NULL; }
int Setting_add(const char *key, const char *value) { bstring key_str = bfromcstr(key); bstring value_str = bfromcstr(value); check(!tst_search(SETTINGS_MAP, bdata(key_str), blength(value_str)), "Setting key %s already exists, can't add %s:%s", key, key, value); SETTINGS_MAP = tst_insert(SETTINGS_MAP, bdata(key_str), blength(key_str), value_str); bdestroy(key_str); return 0; error: bdestroy(key_str); bdestroy(value_str); return -1; }
uint32_t Hashmap_djb_hash(void* data) { bstring s = (bstring)data; uint32_t hash = 5381; int i = 0; for(i = 0; i < blength(s); i++) { hash = ((hash << 5) + hash) + bchare(s, i, 0); // hash * 33 + c } return hash; }
void Node_catbstr(bstring str, Node *d, char sep, int follow_sibs) { int rc = 0; assert_not(str, NULL); if(d == NULL) return; if(d->sibling != NULL && follow_sibs) { Node_catbstr(str, d->sibling, sep, follow_sibs); } if(d->type == TYPE_GROUP) { rc = bformata(str, "[%c", sep); assert(rc == BSTR_OK); } if(d->child != NULL) { // we always follow siblings on the children Node_catbstr(str, d->child, sep, 1); } switch(d->type) { case TYPE_BLOB: bformata(str, "'%zu:" , blength(d->value.string)); bconcat(str, d->value.string); bformata(str, "\'%c", sep); break; case TYPE_STRING: bformata(str, "\"%s\"%c" , bdata(d->value.string), sep); break; case TYPE_NUMBER: bformata(str, "%llu%c", d->value.number, sep); break; case TYPE_FLOAT: bformata(str, "%f%c", d->value.floating, sep); break; case TYPE_GROUP: if(!d->name || bchar(d->name, 0) == '@') { rc = bformata(str, "]%c", sep); assert(rc == BSTR_OK); } break; case TYPE_INVALID: // fallthrough default: assert(!"invalid type for node"); break; } if(d->name != NULL) { rc = bformata(str, "%s%c", bdata(d->name), sep); assert(rc == BSTR_OK); } }
int mongrel2_ws_reply(mongrel2_socket *pub_socket, mongrel2_request *req, bstring data){ bstring payload = bstrcpy(data); // ! and # are the fill characters. You should not see these if the data is correct bInsertChrs(payload, blength(payload), 1, TERM_CHAR, '!'); bInsertChrs(payload, 0, 1, START_CHAR, '#'); mongrel2_reply(pub_socket,req,payload); // mongrel2_ws_debug(payload); bdestroy(payload); return 0; }
static void nodeMeminfo(int node, uint64_t* totalMemory, uint64_t* freeMemory) { FILE *fp; bstring filename; bstring totalString = bformat("MemTotal:"); bstring freeString = bformat("MemFree:"); int i; filename = bformat("/sys/devices/system/node/node%d/meminfo", node); if (NULL != (fp = fopen (bdata(filename), "r"))) { bstring src = bread ((bNread) fread, fp); struct bstrList* tokens = bsplit(src,(char) '\n'); for (i=0;i<tokens->qty;i++) { if (binstr(tokens->entry[i],0,totalString) != BSTR_ERR) { bstring tmp = bmidstr (tokens->entry[i], 18, blength(tokens->entry[i])-18 ); bltrimws(tmp); struct bstrList* subtokens = bsplit(tmp,(char) ' '); *totalMemory = str2int(bdata(subtokens->entry[0])); } else if (binstr(tokens->entry[i],0,freeString) != BSTR_ERR) { bstring tmp = bmidstr (tokens->entry[i], 18, blength(tokens->entry[i])-18 ); bltrimws(tmp); struct bstrList* subtokens = bsplit(tmp,(char) ' '); *freeMemory = str2int(bdata(subtokens->entry[0])); } } } else { ERROR; } fclose(fp); }
static bstring genrandmsg(){ unsigned int len = WEBSOCKET_MEDIUM_MAX - 1000; printf("genrandmsg of len %u\n",len); int range = 'Z' - 'A'; bstring randchars = bfromcstr(""); for(int i=0; i<len; i++){ char randchar = 'A' + rand()%range; bcatblk(randchars,&randchar,1); } bstring retval = bformat("Len: %d Data: %.*s",len,blength(randchars),bdata(randchars)); return retval; }
int write_some(RingBuffer *buffer, int fd, int is_socket) { int rc = 0; bstring data = RingBuffer_get_all(buffer); check(data != NULL, "Failed to get data from the buffer."); check(bfindreplace(data, &NL, &CRLF, 0) == BSTR_OK, "Failed to replace NL."); if(is_socket) { rc = send(fd, bdata(data), blength(data), 0); } else { rc = write(fd, bdata(data), blength(data)); } check(rc == blength(data), "failed to write everything to fd: %d", fd); bdestroy(data); return rc; error: return -1; }
char *test_bassignblk() { char * blk = malloc(1000); memset(blk, 1, 1000); bstring bstr = bfromcstr(""); bassignblk(bstr, blk, 10); mu_assert(blength(bstr) == 10, "bassignblk failed"); bdestroy(bstr); free(blk); return NULL; }
int test_parse(const char *test, int target_count) { HandlerParser *parser = HandlerParser_create(128); bstring T1 = bfromcstr(test); int rc = HandlerParser_execute(parser, bdata(T1), blength(T1)); bdestroy(T1); return rc == 1 && target_count == (int)parser->target_count; }
uint32_t Hashmap_my_hash( void *data) { bstring s = (bstring)data; uint32_t hash = 0; int i = 0; for( i = 0 ; i < blength(s); i++) { hash += bchare(s , i , 0 ); } return hash; }
uint32_t Hashmap_adler32_hash(void* data) { bstring s = (bstring)data; uint32_t a = 1, b = 0; int i = 0; for(i = 0; i < blength(s); i++) { a = (a + bchare(s, i, 0)) % MOD_ADLER; b = (b + a) % MOD_ADLER; } return (b << 16) | a; }
uint32_t Hashmap_fnvla_hash(void* data) { bstring s = (bstring)data; uint32_t hash = FNV_OFFSET_BIAS; int i = 0; for(i = 0; i < blength(s); i++) { hash ^= bchare(s, i, 0); hash *= FNV_PRIME; } return hash; }