static int cpustr_to_cpulist_physical(bstring bcpustr, int* cpulist, int length) { topology_init(); CpuTopology_t cpuid_topology = get_cpuTopology(); affinity_init(); AffinityDomains_t affinity = get_affinityDomains(); bstring bdomain; bstring blist; int domainidx = -1; if (bstrchrp(bcpustr, ':', 0) != BSTR_ERR) { struct bstrList* strlist = bstrListCreate(); strlist = bsplit(bcpustr, ':'); bdomain = bstrcpy(strlist->entry[0]); blist = bstrcpy(strlist->entry[1]); bstrListDestroy(strlist); } else { bdomain = bformat("N"); blist = bstrcpy(bcpustr); } for (int i=0; i<affinity->numberOfAffinityDomains; i++) { if (bstrcmp(bdomain, affinity->domains[i].tag) == 0) { domainidx = i; break; } } if (domainidx < 0) { fprintf(stderr, "Cannot find domain %s\n", bdata(bdomain)); bdestroy(bdomain); bdestroy(blist); return 0; } struct bstrList* strlist = bstrListCreate(); strlist = bsplit(blist, ','); int insert = 0; for (int i=0;i< strlist->qty; i++) { if (bstrchrp(strlist->entry[i], '-', 0) != BSTR_ERR) { struct bstrList* indexlist = bstrListCreate(); indexlist = bsplit(strlist->entry[i], '-'); if (atoi(bdata(indexlist->entry[0])) <= atoi(bdata(indexlist->entry[1]))) { for (int j=atoi(bdata(indexlist->entry[0])); j<=atoi(bdata(indexlist->entry[1]));j++) { if (cpu_in_domain(domainidx, j)) { cpulist[insert] = j; insert++; if (insert == length) { bstrListDestroy(indexlist); goto physical_done; } } else { fprintf(stderr, "CPU %d not in domain %s\n", j, bdata(affinity->domains[domainidx].tag)); } } } else { for (int j=atoi(bdata(indexlist->entry[0])); j>=atoi(bdata(indexlist->entry[1]));j--) { if (cpu_in_domain(domainidx, j)) { cpulist[insert] = j; insert++; if (insert == length) { bstrListDestroy(indexlist); goto physical_done; } } else { fprintf(stderr, "CPU %d not in domain %s\n", j, bdata(affinity->domains[domainidx].tag)); } } } bstrListDestroy(indexlist); } else { int cpu = atoi(bdata(strlist->entry[i])); if (cpu_in_domain(domainidx, cpu)) { cpulist[insert] = cpu; insert++; if (insert == length) { goto physical_done; } } else { fprintf(stderr, "CPU %d not in domain %s\n", cpu, bdata(affinity->domains[domainidx].tag)); } } } physical_done: bstrListDestroy(strlist); bdestroy(bdomain); bdestroy(blist); return insert; }
void bdestroy_cb(void *value, void *ignored) { (void)ignored; bdestroy((bstring) value); }
void hashTable_finalize(int* numThreads, int* numRegions, LikwidResults** results) { int threadId = 0; uint32_t numberOfThreads = 0; uint32_t numberOfRegions = 0; GHashTable* regionLookup; regionLookup = g_hash_table_new(g_str_hash, g_str_equal); /* determine number of active threads */ for (int i=0; i<MAX_NUM_THREADS; i++) { if (threadList[i] != NULL) { numberOfThreads++; uint32_t threadNumberOfRegions = g_hash_table_size(threadList[i]->hashTable); /* Determine maximum number of regions */ if (numberOfRegions < threadNumberOfRegions) { numberOfRegions = threadNumberOfRegions; } } } /* allocate data structures */ (*results) = (LikwidResults*) malloc(numberOfRegions * sizeof(LikwidResults)); if (!(*results)) { fprintf(stderr, "Failed to allocate %lu bytes for the results\n", numberOfRegions * sizeof(LikwidResults)); } else { for ( uint32_t i=0; i < numberOfRegions; i++ ) { (*results)[i].time = (double*) malloc(numberOfThreads * sizeof(double)); if (!(*results)[i].time) { fprintf(stderr, "Failed to allocate %lu bytes for the time storage\n", numberOfThreads * sizeof(double)); break; } (*results)[i].count = (uint32_t*) malloc(numberOfThreads * sizeof(uint32_t)); if (!(*results)[i].count) { fprintf(stderr, "Failed to allocate %lu bytes for the count storage\n", numberOfThreads * sizeof(uint32_t)); break; } (*results)[i].cpulist = (int*) malloc(numberOfThreads * sizeof(int)); if (!(*results)[i].count) { fprintf(stderr, "Failed to allocate %lu bytes for the cpulist storage\n", numberOfThreads * sizeof(int)); break; } (*results)[i].counters = (double**) malloc(numberOfThreads * sizeof(double*)); if (!(*results)[i].counters) { fprintf(stderr, "Failed to allocate %lu bytes for the counter result storage\n", numberOfThreads * sizeof(double*)); break; } for ( uint32_t j=0; j < numberOfThreads; j++ ) { (*results)[i].time[j] = 0.0; (*results)[i].count[j] = 0; (*results)[i].cpulist[j] = -1; (*results)[i].counters[j] = (double*) malloc(NUM_PMC * sizeof(double)); if (!(*results)[i].counters) { fprintf(stderr, "Failed to allocate %lu bytes for the counter result storage for thread %d\n", NUM_PMC * sizeof(double), j); break; } else { for ( uint32_t k=0; k < NUM_PMC; k++ ) { (*results)[i].counters[j][k] = 0.0; } } } } } uint32_t regionIds[numberOfRegions]; uint32_t currentRegion = 0; for (int core=0; core<MAX_NUM_THREADS; core++) { ThreadList* resPtr = threadList[core]; if (resPtr != NULL) { LikwidThreadResults* threadResult = NULL; GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter, resPtr->hashTable); /* iterate over all regions in thread */ while (g_hash_table_iter_next (&iter, &key, &value)) { threadResult = (LikwidThreadResults*) value; uint32_t* regionId = (uint32_t*) g_hash_table_lookup(regionLookup, key); /* is region not yet registered */ if ( regionId == NULL ) { (*results)[currentRegion].tag = bstrcpy (threadResult->label); (*results)[currentRegion].groupID = threadResult->groupID; regionIds[currentRegion] = currentRegion; regionId = regionIds + currentRegion; g_hash_table_insert(regionLookup, g_strdup(key), (regionIds+currentRegion)); currentRegion++; } (*results)[*regionId].count[threadId] = threadResult->count; (*results)[*regionId].time[threadId] = threadResult->time; (*results)[*regionId].cpulist[threadId] = threadResult->cpuID; for ( int j=0; j < NUM_PMC; j++ ) { (*results)[*regionId].counters[threadId][j] = threadResult->PMcounters[j]; } bdestroy(threadResult->label); free(threadResult); } threadId++; g_hash_table_destroy(resPtr->hashTable); free(resPtr); threadList[core] = NULL; } } g_hash_table_destroy(regionLookup); regionLookup = NULL; (*numThreads) = numberOfThreads; (*numRegions) = numberOfRegions; }
int connection_http_to_handler(Connection *conn) { int content_len = Request_content_length(conn->req); int rc = 0; char *body = NULL; Handler *handler = Request_get_action(conn->req, handler); error_unless(handler, conn, 404, "No action for request: %s", bdata(Request_path(conn->req))); bstring expects = Request_get(conn->req, &HTTP_EXPECT); if (expects != NULL) { if (biseqcstr(expects, "100-continue")) { Response_send_status(conn, &HTTP_100); } else { Response_send_status(conn, &HTTP_417); log_info("Client requested unsupported expectation: %s.", bdata(expects)); goto error; } } // we don't need the header anymore, so commit the buffer and deal with the body check(IOBuf_read_commit(conn->iob, Request_header_length(conn->req)) != -1, "Finaly commit failed streaming the connection to http handlers."); if(is_websocket(conn)) { bstring wsKey = Request_get(conn->req, &WS_SEC_WS_KEY); bstring response= websocket_challenge(wsKey); conn->handler = handler; //Response_send_status(conn,response); bdestroy(conn->req->request_method); conn->req->request_method=bfromcstr("WEBSOCKET_HANDSHAKE"); Connection_send_to_handler(conn, handler, bdata(response), blength(response)); bdestroy(response); bdestroy(conn->req->request_method); conn->req->request_method=bfromcstr("WEBSOCKET"); return REQ_SENT; } if(content_len == 0) { body = ""; rc = Connection_send_to_handler(conn, handler, body, content_len); check_debug(rc == 0, "Failed to deliver to the handler."); } else if(content_len > MAX_CONTENT_LENGTH) { rc = Upload_file(conn, handler, content_len); check(rc == 0, "Failed to upload file."); } else { debug("READ ALL CALLED with content_len: %d, and MAX_CONTENT_LENGTH: %d", content_len, MAX_CONTENT_LENGTH); body = IOBuf_read_all(conn->iob, content_len, CLIENT_READ_RETRIES); check(body != NULL, "Client closed the connection during upload."); rc = Connection_send_to_handler(conn, handler, body, content_len); check_debug(rc == 0, "Failed to deliver to the handler."); } Log_request(conn, 200, content_len); return REQ_SENT; error: return CLOSE; }
/** * Argument: * fn - file names * Return: * An ordered file names. */ alder_seqid_file_t * alder_seqid_file_init(struct bstrList *fn) { // Test if all of the files exist. // Determine the file type (text or gzip). // Use the first line to determine file formats (FASTA or FASTQ). // Read the first sequence name of each file. // Pair files using sequence names. alder_seqid_file_t *v = malloc(sizeof(alder_seqid_file_t)); int numberOfFile = fn->qty; v->filename = bstrVectorCreate(numberOfFile); v->type = malloc(numberOfFile * sizeof(int)); v->format = malloc(numberOfFile * sizeof(int)); v->pair = malloc(numberOfFile * sizeof(int)); for (int i = 0; i < fn->qty; i++) { int s = alder_file_exist(bdata(fn->entry[i])); if (s == 0) { alder_seqid_file_free(v); return NULL; } } for (int i = 0; i < fn->qty; i++) { int s = alder_file_isgzip(bdata(fn->entry[i])); if (s == 1) { v->type[i] = 2; } else { v->type[i] = 1; } } for (int i = 0; i < fn->qty; i++) { int s = alder_file_whatformat(bdata(fn->entry[i])); if (s == 1) { v->format[i] = 1; } else if (s == 2) { v->format[i] = 2; } else { alder_seqid_file_free(v); return NULL; } } struct bstrList *bnames = bstrVectorCreate(fn->qty); for (int i = 0; i < fn->qty; i++) { bstring s = alder_file_firstline(bdata(fn->entry[i])); int posFirstSpace = bstrchrp(s, ' ', 0); bstring bword = NULL; if (posFirstSpace != BSTR_ERR) { bword = bHead(s, posFirstSpace); } else { bword = bstrcpy(s); } bdestroy(s); bstring bname = bTail(bword, bword->slen - 1); bdestroy(bword); bstrVectorAdd(bnames, bdata(bname)); bdestroy(bname); } for (int i = 0; i < fn->qty; i++) { v->pair[i] = -1; for (int j = 0; j < fn->qty; j++) { if (i == j) continue; if (!bstrcmp(bnames->entry[i], bnames->entry[j])) { v->pair[i] = j; } } } int *pairCount = malloc(numberOfFile * sizeof(int)); memset(pairCount, 0, numberOfFile*sizeof(int)); for (int i = 0; i < fn->qty; i++) { int j = v->pair[i]; pairCount[j]++; } for (int i = 0; i < fn->qty; i++) { if (pairCount[i] > 1) { free(pairCount); alder_seqid_file_free(v); return NULL; } } free(pairCount); /////////////////////////////////////////////////////////////////////////// // Order pairs. int pairI = 0; alder_vector_pair_t * pair = alder_vector_pair_t_alloc(fn->qty); for (int i = 0; i < fn->qty; i++) { if (v->pair[i] >= 0) { int alreadPaired = 0; for (int j = 0; j < pairI; j++) { if (pair->data[j].first == i || pair->data[j].second== i) { alreadPaired = 1; break; } } if (alreadPaired == 0) { if (i < v->pair[i]) { pair->data[pairI].first = i; pair->data[pairI].second= v->pair[i]; } else { pair->data[pairI].first = v->pair[i]; pair->data[pairI].second= i; } pairI++; } } } for (int i = 0; i < fn->qty; i++) { if (v->pair[i] < 0) { pair->data[pairI].first = i; pair->data[pairI].second= -1; pairI++; } } alder_seqid_file_t *v2 = malloc(sizeof(alder_seqid_file_t)); v2->filename = bstrVectorCreate(numberOfFile); v2->type = malloc(numberOfFile * sizeof(int)); v2->format = malloc(numberOfFile * sizeof(int)); v2->pair = malloc(numberOfFile * sizeof(int)); int seqidIndex = 0; for (int i = 0; i < pairI; i++) { int first = pair->data[i].first; int second = pair->data[i].second; assert(first >= 0); bstrVectorAdd(v2->filename, bdata(fn->entry[first])); v2->type[seqidIndex] = v->type[first]; v2->format[seqidIndex] = v->format[first]; if (second >= 0) { v2->pair[seqidIndex] = seqidIndex + 1; } else { v2->pair[seqidIndex] = -1; } seqidIndex++; if (second >= 0) { bstrVectorAdd(v2->filename, bdata(fn->entry[second])); v2->type[seqidIndex] = v->type[second]; v2->format[seqidIndex] = v->format[second]; v2->pair[seqidIndex] = seqidIndex - 1; seqidIndex++; } } assert(seqidIndex == numberOfFile); #if 0 for (int i = 0; i < fn->qty; i++) { int j = v->pair[i]; if (j < 0) { fprintf(stdout, "%2d %10s: %10s (%d) - no pair (%d)\n", i, bdata(fn->entry[i]), bdata(bnames->entry[i]), pairCount[i], j); } else { fprintf(stdout, "%2d %10s: %10s (%d) - pair %10s (%d)\n", i, bdata(fn->entry[i]), bdata(bnames->entry[i]), pairCount[i], bdata(fn->entry[j]), j); } } fprintf(stdout, "\n"); for (int i = 0; i < fn->qty; i++) { fprintf(stdout, "%2d %10s: format (%d), type (%d), pair (%d)\n", i, bdata(v2->filename->entry[i]), v2->format[i], v2->type[i], v2->pair[i]); } #endif alder_seqid_file_free(v); alder_vector_pair_t_free(pair); bstrVectorDelete(bnames); return v2; }
int main(int argc, char* argv[]) { CURL* curl; bstring command; bstring name; bstring modpath; int all; // Define arguments. struct arg_lit* show_help = arg_lit0("h", "help", "Show this help."); struct arg_str* cmdopt = arg_str1(NULL, NULL, "<command>", "The command; either 'search', 'install', 'uninstall', 'enable' or 'disable'."); struct arg_str* nameopt = arg_str0(NULL, NULL, "<name>", "The name of the module to search for, install, uninstall, enable or disable."); struct arg_lit* all_flag = arg_lit0("a", "all", "Apply this command to all available / installed modules."); struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity."); struct arg_lit* quiet = arg_litn("q", NULL, 0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity."); struct arg_end* end = arg_end(20); void* argtable[] = { show_help, cmdopt, all_flag, nameopt, verbose, quiet, end }; // Parse arguments. int nerrors = arg_parse(argc, argv, argtable); if (nerrors != 0 || show_help->count != 0 || (all_flag->count == 0 && nameopt->count == 0)) { if (all_flag->count == 0 && nameopt->count == 0) printd(LEVEL_ERROR, "error: must have either module name or -a."); if (show_help->count != 0) arg_print_errors(stderr, end, "mm"); fprintf(stderr, "syntax:\n dtmm"); arg_print_syntax(stderr, argtable, "\n"); fprintf(stderr, "options:\n"); arg_print_glossary(stderr, argtable, " %-25s %s\n"); arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return 1; } // Set verbosity level. debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count); // Show version information. version_print(bautofree(bfromcstr("Module Manager"))); // Set argument 0 and convert parameters. osutil_setarg0(bautofree(bfromcstr(argv[0]))); command = bfromcstr(cmdopt->sval[0]); name = bfromcstr(nameopt->sval[0]); // Initialize curl or exit. curl = curl_easy_init(); if (!curl) { printd(LEVEL_ERROR, "unable to initialize curl.\n"); return 1; } // Ensure module path exists. modpath = osutil_getmodulepath(); if (modpath == NULL) { printd(LEVEL_ERROR, "module path does not exist (searched TOOLCHAIN_MODULES and modules/).\n"); return 1; } bdestroy(modpath); // Convert all flag. all = (all_flag->count > 0); // If all is set, set the name back to "". if (all) bassigncstr(name, ""); // If the name is "all" or "*", handle this as the all // boolean flag. if (biseqcstr(name, "all") || biseqcstr(name, "*")) { bassigncstr(name, ""); all = 1; printd(LEVEL_WARNING, "treating name as -a (all) flag"); } if (biseqcstrcaseless(command, "search") || biseqcstrcaseless(command, "se")) return do_search(curl, name, all); else if (biseqcstrcaseless(command, "install") || biseqcstrcaseless(command, "in")) { if (all) return do_install_all(curl); else return do_install(curl, name); } else if (biseqcstrcaseless(command, "uninstall") || biseqcstrcaseless(command, "rm")) { if (all) return do_uninstall_all(curl); else return do_uninstall(curl, name); } else if (biseqcstrcaseless(command, "enable") || biseqcstrcaseless(command, "en")) { if (all) return do_enable_all(curl); else return do_enable(curl, name); } else if (biseqcstrcaseless(command, "disable") || biseqcstrcaseless(command, "di") || biseqcstrcaseless(command, "dis")) { if (all) return do_disable_all(curl); else return do_disable(curl, name); } else { printd(LEVEL_ERROR, "unknown command (must be search, install, uninstall, enable or disable)."); return 1; } return 0; }
void createLine(int side, bstring base, bstring content, lineData lineMap, int * highlightMask) { if (lineMap.type == INFO) { content = bfromcstr(""); lineMap.lineNo = 0; } int position = 0; int needToCloseLastHighlightBeforeEscapingHTML = FALSE; if (highlightMask != NULL) { int lastState = MASK_SAME; int advanceBy; int i; int contentLen = content->slen; // Copy this because it will change as we work. for (i = 0; i < contentLen; i++) { advanceBy = 1; // Normally advance by one char. // Escape HTML as we go. if (content->data[position] == '&') { breplace(content, position, 1, bfromcstr("&"), ' '); advanceBy += 4; } else if (content->data[position] == '<') { breplace(content, position, 1, bfromcstr("<"), ' '); advanceBy += 3; } else if (content->data[position] == '>') { breplace(content, position, 1, bfromcstr(">"), ' '); advanceBy += 3; } if (highlightMask[i] != lastState) { if (highlightMask[i] == MASK_DIFFERENT) { binsert(content, position, bfromcstr("<em>"), ' '); advanceBy += 4; } else { binsert(content, position, bfromcstr("</em>"), ' '); advanceBy += 5; } } position += advanceBy; lastState = highlightMask[i]; } } // Escape HTML. // TODO: This can't possibly be good enough. bfindreplace(content, bfromcstr("&"), bfromcstr("&"), position); bfindreplace(content, bfromcstr("<"), bfromcstr("<"), position); bfindreplace(content, bfromcstr(">"), bfromcstr(">"), position); // Put something in blank lines. if (content->slen == 0) bcatcstr(content, " "); if (needToCloseLastHighlightBeforeEscapingHTML) { bcatcstr(content, "</em>"); } // TODO: there's a lot of string manipulation going on here. It might be // good for performance to call ballocmin and boost the base string size by // a big chunk. if (lineMap.lineNo >= 0 && lineMap.type != INFO) { char * lineNo = lineNumberString(lineMap.lineNo); bcatcstr(base, "<td class='line_number "); bcatcstr(base, typeString(lineMap.type)); bcatcstr(base, " "); bcatcstr(base, (side == LEFT) ? "left" : "right"); bcatcstr(base, "' width='*'>"); bcatcstr(base, lineNo); bcatcstr(base, "</td>\n"); bcatcstr(base, "<td class='line "); free(lineNo); } else { bcatcstr(base, "<td colspan='2' class='line "); } bstring whitespace; bcatcstr(base, typeString(lineMap.type)); bcatcstr(base, " "); bcatcstr(base, (side == LEFT) ? "left" : "right"); bcatcstr(base, "' width='49%'>"); bconcat(base, whitespace = getWhitespace(lineMap.leadingSpaces)); bconcat(base, content); bcatcstr(base, "</td>\n"); bdestroy(whitespace); }
bstring get_signer_pubkey(bstring url) { CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url->data); bstring result = bfromcstr(""); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, save_incoming_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, result); bstring error = bfromcstralloc(CURL_ERROR_SIZE, ""); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, bdata(error)); CURLcode rc = curl_easy_perform(curl); if (rc != CURLE_OK) { fprintf(stderr, "Error obtaining token: %s\n", bdata(error)); exit(1); } long response_code; rc = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); if (rc != CURLE_OK) { fprintf(stderr, "Error obtaining response code\n"); return 0; } if (response_code == 403) { fprintf(stderr, "Permission denied.\n"); return 0; } if (response_code >= 300) { fprintf(stderr, "Invalid response code %ld from server\n", response_code); return 0; } // printf("rc=%d '%s'\n", rc, result->data); curl_easy_cleanup(curl); curl = 0; bdestroy(error); json_settings settings = { 0 } ; char json_error[json_error_max + 1]; json_value *ret = json_parse_ex(&settings, bdata(result), blength(result), json_error); if (ret->type != json_object) return 0; int i; bstring pubkey = 0; for (i = 0; i < ret->u.object.length; i++) { if (strcmp(ret->u.object.values[i].name, "pubkey") == 0) { json_value *t = ret->u.object.values[i].value; pubkey = bfromcstr(t->u.string.ptr); } } json_value_free(ret); bdestroy(result); return pubkey; }
static int nodeProcessorList(int node, uint32_t** list) { FILE *fp; bstring filename; int count = 0; bstring src; int i,j; struct bstrList* tokens; unsigned long val; char* endptr; int cursor=0; // int unitSize = (int) (sizeof(unsigned long)*8); int unitSize = (int) 32; /* 8 nibbles */ *list = (uint32_t*) malloc(MAX_NUM_THREADS * sizeof(uint32_t)); if (!(*list)) { return -ENOMEM; } /* the cpumap interface should be always there */ filename = bformat("/sys/devices/system/node/node%d/cpumap", node); if (NULL != (fp = fopen (bdata(filename), "r"))) { src = bread ((bNread) fread, fp); tokens = bsplit(src,','); for (i=(tokens->qty-1); i>=0 ;i--) { val = strtoul((char*) tokens->entry[i]->data, &endptr, 16); if ((errno != 0 && val == LONG_MAX ) || (errno != 0 && val == 0)) { return -EFAULT; } if (endptr == (char*) tokens->entry[i]->data) { ERROR_PLAIN_PRINT(No digits were found); return -EFAULT; } if (val != 0UL) { for (j=0; j<unitSize; j++) { if (val&(1UL<<j)) { if (count < MAX_NUM_THREADS) { (*list)[count] = (j+cursor); } else { ERROR_PRINT(Number Of threads %d too large,count); return -EFAULT; } count++; } } } cursor += unitSize; } bstrListDestroy(tokens); bdestroy(src); bdestroy(filename); fclose(fp); /* FIXME: CPU list here is not physical cores first but numerical sorted */ return count; } /* something went wrong */ return -1; }
/* ---------------------------------------------------------- * FUNCTION : parse_raw_report * DESC : This function will parse through a single * : line of the CSV file. * INPUT : 0 - Raw Line * RETURN : 0 - Sucess * :-1 - Error * ---------------------------------------------------------- */ int parse_raw_report (bstring line) { struct bstrList *list; int ret = 0; /* Temporary Storage */ struct in_addr ip_addr; //char mac_addr[MAC_ADDR_LEN]; int port; int proto; bstring service; bstring application; time_t discovered; /* Check to see if this line has something to read. */ if (line->data[0] == '\0' || line->data[0] == '#') return 0; /* Break line apart. */ if ((list = bsplit(line, ',')) == NULL) return -1; /* Check to see if this line contains the header. */ if ((biseqcstr(list->entry[0], "asset")) == 1) { if (list != NULL) bstrListDestroy(list); return -1; } /* Place data from 'list' into temporary data storage. */ if ((inet_aton(bdata(list->entry[0]), &ip_addr)) == -1) ret = -1; if ((port = htons(atoi(bdata(list->entry[1])))) == -1) ret = -1; if ((proto = atoi(bdata(list->entry[2]))) == -1) ret = -1; if ((service = bstrcpy(list->entry[3])) == NULL) ret = -1; if ((application = bstrcpy(list->entry[4])) == NULL) ret = -1; if ((discovered = atol(bdata(list->entry[5]))) == -1) ret = -1; /* Make sure that this line contains 'good' data. */ if (service->slen == 0 || application->slen == 0 || discovered <= 0) ret = -1; /* Add Asset to Data Structure */ if (proto == 0 && ret != -1) { /* ARP */ //mac2hex(bdata(application), mac_addr, MAC_ADDR_LEN); //add_arp_asset(ip_addr, mac_addr, discovered); } else { /* Everything Else */ //add_asset(ip_addr, port, proto, service, application, discovered); } // Clean Up if (list != NULL) bstrListDestroy(list); if (service != NULL) bdestroy(service); if (application != NULL) bdestroy(application); return ret; }
int validate_token(bstring token) { int i; OpenSSL_add_all_algorithms(); struct bstrList *parts = bsplit(token, '|'); dictionary *dict = dictionary_new(10); bstring sig = bfromcstr("sig"); bstring to_sign = bfromcstr(""); for (i = 0; i < parts->qty; i++) { printf("%d: %s\n", i, parts->entry[i]->data); struct bstrList *x = bsplit(parts->entry[i], '='); if (x->qty == 2) { if (bstrcmp(x->entry[0], sig) != 0) { if (blength(to_sign) > 0) bconchar(to_sign, '|'); bconcat(to_sign, parts->entry[i]); } dictionary_set(dict, bdata(x->entry[0]), bdata(x->entry[1])); } bstrListDestroy(x); } bstrListDestroy(parts); parts = 0; bdestroy(sig); dictionary_dump(dict, stdout); printf("to sign: '%s'\n", bdata(to_sign)); // Check signing subject (need to know the valid values) char *subj = dictionary_get(dict, "SigningSubject", 0); if (!subj) { fprintf(stderr, "could not get signing subject\n"); return 0; } char *sigstr = dictionary_get(dict, "sig", 0); printf("sig to verify is %s\n", sigstr); bstring binsig = bfromcstralloc(strlen(sigstr) / 2, ""); char *s, *e; for (s = sigstr, e = sigstr + strlen(sigstr); s < e; s += 2) { char n[3]; n[0] = s[0]; n[1] = s[1]; n[2] = 0; long int v = strtol(n, 0, 16); // printf("n=%s v=%ld %lx\n", n, v, v); bconchar(binsig, (char) v); } unsigned char *sha = SHA1((const unsigned char *) to_sign->data, to_sign->slen, 0); bdestroy(to_sign); bstring bsubj = bfromcstr(subj); bstring pubkey = get_signer_pubkey(bsubj); BIO *bio = BIO_new(BIO_s_mem()); BIO_puts(bio, bdata(pubkey)); RSA *rsa = PEM_read_bio_RSAPublicKey(bio, 0, 0, 0); int rc = RSA_verify(NID_sha1, sha, SHA_DIGEST_LENGTH, binsig->data, binsig->slen, rsa); printf("rc=%d\n", rc); bdestroy(bsubj); bdestroy(binsig); bdestroy(pubkey); BIO_free(bio); RSA_free(rsa); dictionary_del(dict); EVP_cleanup(); return rc; }
char *test_routing_match() { RouteMap *routes = RouteMap_create(NULL); mu_assert(routes != NULL, "Failed to make the route map."); char *route_data0 = "route0"; char *route_data1 = "route1"; char *route_data2 = "route2"; char *route_data3 = "route3"; char *route_data4 = "route4"; bstring route0 = bfromcstr("/"); bstring route1 = bfromcstr("/users/([0-9]+)"); bstring route2 = bfromcstr("/users"); bstring route3 = bfromcstr("/users/people/([0-9]+)$"); bstring route4 = bfromcstr("/cars-fast/([a-z]-)$"); Route *route = NULL; RouteMap_insert(routes, route0, route_data0); RouteMap_insert(routes, route1, route_data1); RouteMap_insert(routes, route2, route_data2); RouteMap_insert(routes, route3, route_data3); RouteMap_insert(routes, route4, route_data4); bstring path1 = bfromcstr("/users/1234/testing"); bstring path2 = bfromcstr("/users"); bstring path3 = bfromcstr("/users/people/1234"); bstring path4 = bfromcstr("/cars-fast/cadillac"); bstring path5 = bfromcstr("/users/1234"); bstring path6 = bfromcstr("/"); bstring path7 = bfromcstr("/users/people/1234/notgonnawork"); list_t *found = RouteMap_match(routes, path5); mu_assert(check_routing(found, route, 1, route_data1), "Pattern match route wrong."); list_destroy_nodes(found); list_destroy(found); found = RouteMap_match(routes, path1); mu_assert(check_routing(found, route, 1, route_data1), "Past end route wrong."); list_destroy_nodes(found); list_destroy(found); found = RouteMap_match(routes, path2); mu_assert(check_routing(found, route, 1, route_data2), "No pattern route wrong."); list_destroy_nodes(found); list_destroy(found); found = RouteMap_match(routes, path3); mu_assert(check_routing(found, route, 1, route_data3), "Wrong $ terminated route."); list_destroy_nodes(found); list_destroy(found); found = RouteMap_match(routes, path4); mu_assert(check_routing(found, route, 1, route_data4), "Wrong longer route match."); list_destroy_nodes(found); list_destroy(found); found = RouteMap_match(routes, path5); mu_assert(check_routing(found, route, 1, route_data1), "Wrong route for /users/1234"); list_destroy_nodes(found); list_destroy(found); found = RouteMap_match(routes, path6); mu_assert(check_routing(found, route, 2, route_data0), "Should get root / route."); list_destroy_nodes(found); list_destroy(found); found = RouteMap_match(routes, path7); mu_assert(check_routing(found, route, 0, NULL), "Should not match past end"); list_destroy_nodes(found); list_destroy(found); bdestroy(path1); bdestroy(path2); bdestroy(path3); bdestroy(path4); bdestroy(path5); RouteMap_destroy(routes); return NULL; }
/* ---------------------------------------------------------- * FUNCTION : parse_line * DESCRIPTION : This function will process a line of data * : from a configuration file. * INPUT : 0 - Line (bstring) * ---------------------------------------------------------- */ void parse_line (bstring line) { bstring param, value; struct bstrList *list; int i; /* Check to see if this line has something to read. */ if (line->data[0] == '\0' || line->data[0] == '#') return; /* Check to see if this line has a comment in it. */ if ((list = bsplit(line, '#')) != NULL) { if ((bassign(line, list->entry[0])) == -1) { log_message("warning: 'bassign' in function 'parse_line' failed."); } if (list != NULL) bstrListDestroy(list); } /* Seperate line into a parameter and a value. */ if ((i = bstrchr(line, ' ')) == BSTR_ERR) return; if ((param = bmidstr(line, 0, i)) == NULL) return; if ((value = bmidstr(line, i + 1, line->slen - i)) == NULL) return; /* Normalize Strings */ if ((btolower(param)) != 0) log_message("warning: 'btolower' in function 'parse_line' failed."); if ((bltrim(value)) != 0) log_message("warning: 'bltrim' in function 'parse_line' failed."); if ((brtrim(value)) != 0) log_message("warning: 'brtrim' in function 'parse_line' failed."); /* Do something based upon value. */ if ((biseqcstr(param, "daemon")) == 1) { /* DAEMON */ if (!gc.daemon_mode) { if (value->data[0] == '1') gc.daemon_mode = 1; else gc.daemon_mode = 0; } } else if ((biseqcstr(param, "pid_file")) == 1) { /* PID FILE */ gc.pid_file = bstrcpy(value); } else if ((biseqcstr(param, "sig_file")) == 1) { /* SIGNATURE FILE */ gc.sig_file = bstrcpy(value); } else if ((biseqcstr(param, "mac_file")) == 1) { /* MAC / VENDOR RESOLUTION FILE */ gc.mac_file = bstrcpy(value); } else if ((biseqcstr(param, "output")) == 1) { /* OUTPUT */ conf_module_plugin(value, &activate_output_plugin); } else if ((biseqcstr(param, "user")) == 1) { /* USER */ gc.priv_user = bstrcpy(value); } else if ((biseqcstr(param, "group")) == 1) { /* GROUP */ gc.priv_group = bstrcpy(value); } else if ((biseqcstr(param, "interface")) == 1) { /* INTERFACE */ gc.dev = bstr2cstr(value, '-'); } else if ((biseqcstr(param, "filter")) == 1) { /* FILTER */ gc.pcap_filter = bstr2cstr(value, '-'); } else if ((biseqcstr(param, "network")) == 1) { /* NETWORK */ parse_networks(bdata(value)); } verbose_message("config - PARAM: |%s| / VALUE: |%s|", bdata(param), bdata(value)); /* Clean Up */ if (param != NULL) bdestroy(param); if (value != NULL) bdestroy(value); }
int cpustr_to_cpulist(char* cpustring, int* cpulist, int length) { int insert = 0; int len = 0; int ret = 0; bstring bcpustr = bfromcstr(cpustring); struct bstrList* strlist = bstrListCreate(); bstring scattercheck = bformat("scatter"); topology_init(); CpuTopology_t cpuid_topology = get_cpuTopology(); strlist = bsplit(bcpustr, '@'); int* tmpList = (int*)malloc(length * sizeof(int)); if (tmpList == NULL) { bstrListDestroy(strlist); bdestroy(scattercheck); bdestroy(bcpustr); return -ENOMEM; } for (int i=0; i< strlist->qty; i++) { if (binstr(strlist->entry[i], 0, scattercheck) != BSTR_ERR) { ret = cpustr_to_cpulist_scatter(strlist->entry[i], tmpList, length); insert += cpulist_concat(cpulist, insert, tmpList, ret); } else if (bstrchrp(strlist->entry[i], 'E', 0) == 0) { ret = cpustr_to_cpulist_expression(strlist->entry[i], tmpList, length); insert += cpulist_concat(cpulist, insert, tmpList, ret); } else if (bstrchrp(strlist->entry[i], 'L', 0) == 0) { ret = cpustr_to_cpulist_logical(strlist->entry[i], tmpList, length); insert += cpulist_concat(cpulist, insert, tmpList, ret); } else if (cpuid_topology->activeHWThreads < cpuid_topology->numHWThreads) { fprintf(stdout, "INFO: You are running LIKWID in a cpuset with %d CPUs, only logical numbering allowed\n", cpuid_topology->activeHWThreads); if (((bstrchrp(strlist->entry[i], 'N', 0) == 0) || (bstrchrp(strlist->entry[i], 'S', 0) == 0) || (bstrchrp(strlist->entry[i], 'C', 0) == 0) || (bstrchrp(strlist->entry[i], 'M', 0) == 0)) && (bstrchrp(strlist->entry[i], ':', 0) != BSTR_ERR)) { bstring newstr = bformat("L:"); bconcat(newstr, strlist->entry[i]); ret = cpustr_to_cpulist_logical(newstr, tmpList, length); insert += cpulist_concat(cpulist, insert, tmpList, ret); bdestroy(newstr); } else { bstring newstr = bformat("L:N:"); bconcat(newstr, strlist->entry[i]); ret = cpustr_to_cpulist_logical(newstr, tmpList, length); insert += cpulist_concat(cpulist, insert, tmpList, ret); bdestroy(newstr); } } else if (((bstrchrp(strlist->entry[i], 'N', 0) == 0) || (bstrchrp(strlist->entry[i], 'S', 0) == 0) || (bstrchrp(strlist->entry[i], 'C', 0) == 0) || (bstrchrp(strlist->entry[i], 'M', 0) == 0)) && (bstrchrp(strlist->entry[i], ':', 0) != BSTR_ERR)) { bstring newstr = bformat("L:"); bconcat(newstr, strlist->entry[i]); ret = cpustr_to_cpulist_logical(newstr, tmpList, length); insert += cpulist_concat(cpulist, insert, tmpList, ret); bdestroy(newstr); } else { ret = cpustr_to_cpulist_physical(strlist->entry[i], tmpList, length); insert += cpulist_concat(cpulist, insert, tmpList, ret); } } free(tmpList); bstrListDestroy(strlist); return insert; }
bool do_install_all(CURL* curl) { // define used variables DIR* dir; FILE* fp; CURLcode res; bool printed; bool install_status; bool something_errored; bool if_something_was_installed; list_t installed; long httpcode = 0; struct dirent* entry; struct bStream* stream; bstring buffer, fname, sstr; bstring modpath = osutil_getmodulepath(); bstring ext = bfromcstr(".lua"); bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/list"); list_init(&installed); list_attributes_copy(&installed, list_meter_string, 1); list_attributes_comparator(&installed, list_comparator_string); // Attempt to open the modules directory. dir = opendir(modpath->data); if (dir == NULL) { printd(LEVEL_ERROR, "unable to query local repository.\n"); return 1; } // add the filename we wish to query to the modules folder path bcatcstr(modpath, "/.all_avail"); // Open the file and do the cURL transfer. printd(LEVEL_DEFAULT, "loading a list of all the modules...\n"); fp = fopen(modpath->data, "wb"); curl_easy_setopt(curl, CURLOPT_URL, url->data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode); if (res != 0 || httpcode != 200) { bdestroy(url); bdestroy(modpath); printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode); return 1; } fclose(fp); // create a list of already installed modules 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); list_append(&installed, sstr->data); bdestroy(sstr); bdestroy(fname); } printd(LEVEL_DEFAULT, "\n"); // Print the names of the modules, and install them through the do_install function fp = fopen(modpath->data, "r"); stream = bsopen(&read_data, fp); buffer = bfromcstr(""); printed = false; if_something_was_installed = false; something_errored = false; while (bsreadln(buffer, stream, '\n') != BSTR_ERR) { btrimws(buffer); sstr = bmidstr(buffer, 0, blength(buffer) - 4); // if the module is not already installed if (!list_contains(&installed, sstr->data)) { install_status = do_install(curl, bfromcstr(sstr->data)); if_something_was_installed = true; // check whether the installation was successful if (install_status != 0) { printd(LEVEL_DEFAULT, " %s failed to install.\n", sstr->data); something_errored = true; } printd(LEVEL_DEFAULT, "\n"); } printed = true; bdestroy(sstr); } if (!printed) printd(LEVEL_DEFAULT, " <no modules available>\n"); if (something_errored) printd(LEVEL_DEFAULT, "errors occured\n"); if (!if_something_was_installed) printd(LEVEL_DEFAULT, "no changes were made\n"); bsclose(stream); fclose(fp); // Clean up. curl_easy_cleanup(curl); return 0; }
int main(int argc, char **argv) { struct gengetopt_args_info args_info; struct hostent *host; char hostname[USERURLSIZE]; int numargs; int ret = -1; int i; options_init(); memset(&args_info, 0, sizeof(args_info)); if (cmdline_parser2(argc, argv, &args_info, 1, 1, 1) != 0) { log_err(0, "Failed to parse command line options"); goto end_processing; } if (args_info.version_given) { options_print_version(); exit(2); } if (args_info.help_given) { options_print_help(); exit(2); } if (cmdline_parser_configfile(args_info.conf_arg ? args_info.conf_arg : DEFCHILLICONF, &args_info, 0, 0, 0)) { log_err(0, "Failed to parse configuration file: %s!", args_info.conf_arg); if (!args_info.forgiving_flag) goto end_processing; } /* Get the system default DNS entries */ if (res_init()) { log_err(0, "Failed to update system DNS settings (res_init()!"); goto end_processing; } /* Handle each option */ _options.initialized = 1; if (args_info.debug_flag) _options.debug = args_info.debugfacility_arg; else _options.debug = 0; /* pass-throughs */ memset(_options.pass_throughs, 0, sizeof(_options.pass_throughs)); _options.num_pass_throughs = 0; /** simple configuration parameters **/ _options.layer3 = args_info.layer3_flag; #if(_debug_ && !defined(ENABLE_LAYER3)) if (_options.layer3) log_warn(0, "layer3 not implemented. build with --enable-layer3"); #endif _options.uid = args_info.uid_arg; _options.gid = args_info.gid_arg; _options.mtu = args_info.mtu_arg; _options.usetap = args_info.usetap_flag; _options.noarpentries = args_info.noarpentries_flag; #if(_debug_ && !defined(ENABLE_TAP)) if (_options.noarpentries) log_warn(0, "tap not implemented. build with --enable-tap"); #endif #if(_debug_ && !defined(ENABLE_TAP)) if (_options.usetap) log_warn(0, "tap not implemented. build with --enable-tap"); #endif _options.foreground = args_info.fg_flag; _options.interval = args_info.interval_arg; _options.lease = args_info.lease_arg; _options.leaseplus = args_info.leaseplus_arg; _options.dhcpstart = args_info.dhcpstart_arg; _options.dhcpend = args_info.dhcpend_arg; _options.eapolenable = args_info.eapolenable_flag; #if(_debug_ && !defined(ENABLE_EAPOL)) if (_options.eapolenable) log_warn(0, "EAPOL not implemented. build with --enable-eapol"); #endif _options.swapoctets = args_info.swapoctets_flag; _options.logfacility = args_info.logfacility_arg; _options.chillixml = args_info.chillixml_flag; _options.macauth = args_info.macauth_flag; _options.macreauth = args_info.macreauth_flag; _options.macauthdeny = args_info.macauthdeny_flag; _options.uamport = args_info.uamport_arg; #ifdef ENABLE_UAMUIPORT _options.uamuiport = args_info.uamuiport_arg; #endif _options.macallowlocal = args_info.macallowlocal_flag; _options.strictmacauth = args_info.strictmacauth_flag; _options.strictdhcp = args_info.strictdhcp_flag; _options.no_wispr1 = args_info.nowispr1_flag; _options.no_wispr2 = args_info.nowispr2_flag; _options.wpaguests = args_info.wpaguests_flag; _options.openidauth = args_info.openidauth_flag; _options.challengetimeout = args_info.challengetimeout_arg; _options.challengetimeout2 = args_info.challengetimeout2_arg; _options.defsessiontimeout = args_info.defsessiontimeout_arg; _options.definteriminterval = args_info.definteriminterval_arg; _options.defbandwidthmaxdown = args_info.defbandwidthmaxdown_arg; _options.defbandwidthmaxup = args_info.defbandwidthmaxup_arg; _options.defidletimeout = args_info.defidletimeout_arg; _options.radiusnasporttype = args_info.radiusnasporttype_arg; _options.radiusauthport = args_info.radiusauthport_arg; _options.radiusacctport = args_info.radiusacctport_arg; _options.coaport = args_info.coaport_arg; _options.coanoipcheck = args_info.coanoipcheck_flag; _options.radiustimeout = args_info.radiustimeout_arg; _options.radiusretry = args_info.radiusretry_arg; _options.radiusretrysec = args_info.radiusretrysec_arg; #ifdef ENABLE_RADPROXY _options.proxyport = args_info.proxyport_arg; _options.proxymacaccept = args_info.proxymacaccept_flag; _options.proxyonacct = args_info.proxyonacct_flag; #endif #if(_debug_ && !defined(ENABLE_RADPROXY)) if (args_info.proxyport_arg) log_err(0,"radproxy not implemented. build with --enable-radproxy"); #endif _options.txqlen = args_info.txqlen_arg; _options.ringsize = args_info.ringsize_arg; _options.sndbuf = args_info.sndbuf_arg; _options.rcvbuf = args_info.rcvbuf_arg; _options.childmax = args_info.childmax_arg; _options.postauth_proxyport = args_info.postauthproxyport_arg; _options.pap_always_ok = args_info.papalwaysok_flag; _options.mschapv2 = args_info.mschapv2_flag; _options.acct_update = args_info.acctupdate_flag; _options.dhcpradius = args_info.dhcpradius_flag; _options.dhcp_broadcast = args_info.dhcpbroadcast_flag; _options.dhcpgwport = args_info.dhcpgatewayport_arg; _options.noc2c = args_info.noc2c_flag; _options.tcpwin = args_info.tcpwin_arg; _options.tcpmss = args_info.tcpmss_arg; _options.max_clients = args_info.maxclients_arg; _options.radiusqsize = args_info.radiusqsize_arg; _options.dhcphashsize = args_info.dhcphashsize_arg; _options.uamdomain_ttl = args_info.uamdomainttl_arg; _options.seskeepalive = args_info.seskeepalive_flag; _options.uamallowpost = args_info.uamallowpost_flag; _options.redir = args_info.redir_flag; _options.redirurl = args_info.redirurl_flag; _options.statusfilesave = args_info.statusfilesave_flag; _options.dhcpnotidle = args_info.dhcpnotidle_flag; #if(_debug_ && !defined(ENABLE_CHILLIREDIR)) if (_options.redir) log_err(0, "chilli_redir not implemented. build with --enable-chilliredir"); #endif _options.redirssl = args_info.redirssl_flag; _options.uamuissl = args_info.uamuissl_flag; _options.domaindnslocal = args_info.domaindnslocal_flag; _options.framedservice = args_info.framedservice_flag; _options.radsec = args_info.radsec_flag; #if(_debug_ && !defined(ENABLE_CHILLIRADSEC)) if (_options.radsec) log_err(0, "chilli_radsec not implemented. build with --enable-chilliradsec"); #endif _options.noradallow = args_info.noradallow_flag; _options.peerid = args_info.peerid_arg; #if(_debug_ && !defined(ENABLE_CLUSTER)) if (_options.peerid) log_err(0, "clustering not implemented. build with --enable-cluster"); #endif _options.redirdnsreq = args_info.redirdnsreq_flag; #if(_debug_ && !defined(ENABLE_REDIRDNSREQ)) if (_options.redirdnsreq) log_err(0, "redirdnsreq not implemented. build with --enable-redirdnsreq"); #endif #ifdef ENABLE_IPV6 _options.ipv6 = args_info.ipv6_flag; _options.ipv6only = args_info.ipv6only_flag; #endif #ifdef ENABLE_LEAKYBUCKET _options.scalewin = args_info.scalewin_flag; _options.bwbucketupsize = args_info.bwbucketupsize_arg; _options.bwbucketdnsize = args_info.bwbucketdnsize_arg; _options.bwbucketminsize = args_info.bwbucketminsize_arg; #endif #ifdef ENABLE_PROXYVSA _options.vlanlocation = args_info.vlanlocation_flag; _options.location_stop_start = args_info.locationstopstart_flag; _options.location_copy_called = args_info.locationcopycalled_flag; _options.location_immediate_update = args_info.locationimmediateupdate_flag; _options.location_option_82 = args_info.locationopt82_flag; if (args_info.proxylocattr_given) { for (numargs = 0; numargs < args_info.proxylocattr_given && numargs < PROXYVSA_ATTR_CNT; ++numargs) { unsigned int i[2]; switch (sscanf(args_info.proxylocattr_arg[numargs], "%u,%u", &i[0], &i[1])) { case 0: log_err(0, "invalid input %s", args_info.proxylocattr_arg[numargs]); break; case 1: _options.proxy_loc[numargs].attr = i[0]; break; case 2: _options.proxy_loc[numargs].attr_vsa = i[0]; _options.proxy_loc[numargs].attr = i[1]; break; } log_dbg("Proxy location attr %d %d", (int)_options.proxy_loc[numargs].attr_vsa, (int)_options.proxy_loc[numargs].attr); } } #endif if (args_info.dhcpgateway_arg && !inet_aton(args_info.dhcpgateway_arg, &_options.dhcpgwip)) { log_err(0, "Invalid DHCP gateway IP address: %s!", args_info.dhcpgateway_arg); if (!args_info.forgiving_flag) goto end_processing; } if (args_info.dhcprelayagent_arg && !inet_aton(args_info.dhcprelayagent_arg, &_options.dhcprelayip)) { log_err(0, "Invalid DHCP gateway relay IP address: %s!", args_info.dhcprelayagent_arg); if (!args_info.forgiving_flag) goto end_processing; } _options.dhcpif = STRDUP(args_info.dhcpif_arg); #ifdef ENABLE_MULTILAN for (numargs = 0; numargs < args_info.moreif_given && numargs < MAX_MOREIF; ++numargs) { char *nif = STRDUP(args_info.moreif_arg[numargs]); char *vln = strchr(nif, '/'); _options.moreif[numargs].dhcpif = nif; if (vln) { if (strlen(vln) > 1) _options.moreif[numargs].vlan = vln + 1; *vln = 0; } else { vln = strchr(nif, '.'); if (vln && strlen(vln) > 1) _options.moreif[numargs].vlan = vln + 1; } } #endif if (!args_info.radiussecret_arg) { log_err(0, "radiussecret must be specified!"); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.nexthop_arg) { memset(_options.nexthop, 0, PKT_ETH_ALEN); _options.has_nexthop = 0; } else { unsigned int temp[PKT_ETH_ALEN]; char macstr[RADIUS_ATTR_VLEN]; int macstrlen; int i; if ((macstrlen = strlen(args_info.nexthop_arg)) >= (RADIUS_ATTR_VLEN-1)) { log_err(0, "MAC address too long"); if (!args_info.forgiving_flag) goto end_processing; } memcpy(macstr, args_info.nexthop_arg, macstrlen); macstr[macstrlen] = 0; /* Replace anything but hex with space */ for (i=0; i<macstrlen; i++) if (!isxdigit((int) macstr[i])) macstr[i] = 0x20; if (sscanf (macstr, "%2x %2x %2x %2x %2x %2x", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]) != 6) { log_err(0, "MAC conversion failed!"); return -1; } for (i = 0; i < PKT_ETH_ALEN; i++) _options.nexthop[i] = temp[i]; _options.has_nexthop = 1; } if (!args_info.dhcpmac_arg) { memset(_options.dhcpmac, 0, PKT_ETH_ALEN); _options.dhcpusemac = 0; _options.dhcpmacset = 0; } else { unsigned int temp[PKT_ETH_ALEN]; char macstr[RADIUS_ATTR_VLEN]; int macstrlen; int i; if ((macstrlen = strlen(args_info.dhcpmac_arg)) >= (RADIUS_ATTR_VLEN-1)) { log_err(0, "MAC address too long"); if (!args_info.forgiving_flag) goto end_processing; } memcpy(macstr, args_info.dhcpmac_arg, macstrlen); macstr[macstrlen] = 0; /* Replace anything but hex with space */ for (i=0; i<macstrlen; i++) if (!isxdigit((int) macstr[i])) macstr[i] = 0x20; if (sscanf (macstr, "%2x %2x %2x %2x %2x %2x", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]) != 6) { log_err(0, "MAC conversion failed!"); return -1; } for (i = 0; i < PKT_ETH_ALEN; i++) _options.dhcpmac[i] = temp[i]; _options.dhcpusemac = 1; _options.dhcpmacset = args_info.dhcpmacset_flag; } if (args_info.net_arg) { if (option_aton(&_options.net, &_options.mask, args_info.net_arg, 0)) { log_err(0, "Invalid network address: %s!", args_info.net_arg); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.uamlisten_arg) { _options.uamlisten.s_addr = htonl(ntohl(_options.net.s_addr)+1); } else if (!inet_aton(args_info.uamlisten_arg, &_options.uamlisten)) { log_err(0, "Invalid UAM IP address: %s!", args_info.uamlisten_arg); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.dhcplisten_arg) { _options.dhcplisten.s_addr = _options.uamlisten.s_addr; } else if (!inet_aton(args_info.dhcplisten_arg, &_options.dhcplisten)) { log_err(0, "Invalid DHCP IP address: %s!", args_info.dhcplisten_arg); if (!args_info.forgiving_flag) goto end_processing; } } else { log_err(0, "Network address must be specified ('net' parameter)!"); if (!args_info.forgiving_flag) goto end_processing; } log_dbg("DHCP Listen: %s", inet_ntoa(_options.dhcplisten)); log_dbg("UAM Listen: %s", inet_ntoa(_options.uamlisten)); if (!args_info.uamserver_arg) { log_err(0, "WARNING: No uamserver defiend!"); } if (args_info.uamserver_arg) { int uamserverport=80; if (_options.debug & DEBUG_CONF) { log_dbg("Uamserver: %s\n", args_info.uamserver_arg); } if (get_urlparts(args_info.uamserver_arg, hostname, USERURLSIZE, &uamserverport, 0)) { log_err(0, "Failed to parse uamserver: %s!", args_info.uamserver_arg); if (!args_info.forgiving_flag) goto end_processing; } if (!args_info.uamaliasname_arg || strncmp(args_info.uamaliasname_arg, hostname, strlen(args_info.uamaliasname_arg))) { if (!(host = gethostbyname(hostname))) { log_err(0, "Could not resolve IP address of uamserver: %s!", args_info.uamserver_arg); } else { int j = 0; pass_through pt; memset(&pt, 0, sizeof(pt)); pt.port = uamserverport; pt.mask.s_addr = ~0; while (host->h_addr_list[j] != NULL) { if (_options.debug & DEBUG_CONF) { log_dbg("Uamserver IP address #%d: %s\n", j, inet_ntoa(*(struct in_addr*) host->h_addr_list[j])); } pt.host.s_addr = ((struct in_addr*) host->h_addr_list[j++])->s_addr; if (pass_through_add(_options.pass_throughs, MAX_PASS_THROUGHS, &_options.num_pass_throughs, &pt, 0 #ifdef HAVE_PATRICIA , 0 #endif )) log_err(0, "Too many pass-throughs! skipped %s:%d", inet_ntoa(pt.host), pt.port); } } } } _options.uamanydns = args_info.uamanydns_flag; #ifdef ENABLE_UAMANYIP _options.uamanyip = args_info.uamanyip_flag; _options.uamnatanyip = args_info.uamnatanyip_flag; #endif _options.dnsparanoia = args_info.dnsparanoia_flag; _options.radiusoriginalurl = args_info.radiusoriginalurl_flag; _options.routeonetone = args_info.routeonetone_flag; #ifdef HAVE_PATRICIA _options.patricia = args_info.patricia_flag; #endif #ifdef ENABLE_GARDENACCOUNTING _options.nousergardendata = args_info.nousergardendata_flag; _options.uamgardendata = args_info.uamgardendata_flag; _options.uamotherdata = args_info.uamotherdata_flag; #endif for (numargs = 0; numargs < args_info.uamallowed_given; ++numargs) { pass_throughs_from_string(_options.pass_throughs, MAX_PASS_THROUGHS, &_options.num_pass_throughs, args_info.uamallowed_arg[numargs], 0, 0 #ifdef HAVE_PATRICIA , 0 #endif ); } #ifdef ENABLE_DHCPOPT _options.dhcp_options_len = 0; for (numargs = 0; numargs < args_info.dhcpopt_given; ++numargs) { unsigned char binopt[128]; int hex_length = strlen(args_info.dhcpopt_arg[numargs]); int bin_length = hex_length / 2; if (hex_length > 0 && (bin_length * 2) == hex_length && bin_length < sizeof(binopt)) { log_dbg("DHCP Options %s", args_info.dhcpopt_arg[numargs]); if (redir_hextochar((unsigned char *)args_info.dhcpopt_arg[numargs], hex_length, binopt, bin_length) == 0) { if (_options.dhcp_options_len + bin_length < sizeof(_options.dhcp_options)) { memcpy(_options.dhcp_options + _options.dhcp_options_len, binopt, bin_length); _options.dhcp_options_len += bin_length; } else { log_dbg("No room for DHCP option %d", (int)binopt[0]); } } else { log_dbg("Bad DHCP option hex encoding"); } } else { log_dbg("DHCP options are hex encoded binary"); } } #endif #ifdef ENABLE_MODULES memset(_options.modules, 0, sizeof(_options.modules)); for (numargs = 0; numargs < args_info.module_given; ++numargs) { if (numargs < MAX_MODULES) { char *n, *sc; int len, nlen; n = args_info.module_arg[numargs]; len = strlen(n); sc = strchr(n, ';'); if (!sc) sc = strchr(n, ':'); nlen = sc ? (sc - n) : len; safe_snprintf(_options.modules[numargs].name, sizeof(_options.modules[numargs].name), "%.*s", nlen, n); if (sc && len > (nlen + 1)) { safe_snprintf(_options.modules[numargs].conf, sizeof(_options.modules[numargs].conf), "%.*s", len - nlen - 1, sc + 1); } } } #endif #ifdef ENABLE_CHILLIREDIR /* for (numargs = 0; numargs < MAX_REGEX_PASS_THROUGHS; ++numargs) { if (_options.regex_pass_throughs[numargs].re_host.allocated) regfree(&_options.regex_pass_throughs[numargs].re_host); if (_options.regex_pass_throughs[numargs].re_path.allocated) regfree(&_options.regex_pass_throughs[numargs].re_path); if (_options.regex_pass_throughs[numargs].re_qs.allocated) regfree(&_options.regex_pass_throughs[numargs].re_qs); } */ memset(_options.regex_pass_throughs, 0, sizeof(_options.regex_pass_throughs)); _options.regex_num_pass_throughs = 0; for (numargs = 0; numargs < args_info.uamregex_given; ++numargs) { regex_pass_throughs_from_string(_options.regex_pass_throughs, MAX_REGEX_PASS_THROUGHS, &_options.regex_num_pass_throughs, args_info.uamregex_arg[numargs], 0); } #endif for (numargs = 0; numargs < MAX_UAM_DOMAINS; ++numargs) { if (_options.uamdomains[numargs]) free(_options.uamdomains[numargs]); _options.uamdomains[numargs] = 0; } if (args_info.uamdomain_given) { for (numargs = 0, i=0; numargs < args_info.uamdomain_given && i < MAX_UAM_DOMAINS; ++numargs) { char *tb = args_info.uamdomain_arg[numargs]; char *tok, *str, *ptr; for (str = tb ; i < MAX_UAM_DOMAINS; str = NULL) { tok = strtok_r(str, ",", &ptr); if (!tok) break; log_dbg("uamdomain %s", tok); _options.uamdomains[i++] = STRDUP(tok); } } } _options.allowdyn = 1; #ifdef ENABLE_UAMANYIP _options.autostatip = args_info.autostatip_arg; if (_options.autostatip) _options.uamanyip = 1; #endif if (args_info.nodynip_flag) { _options.allowdyn = 0; } else { if (!args_info.dynip_arg) { _options.dynip = STRDUP(args_info.net_arg); } else { struct in_addr addr; struct in_addr mask; _options.dynip = STRDUP(args_info.dynip_arg); if (option_aton(&addr, &mask, _options.dynip, 0)) { log_err(0, "Failed to parse dynamic IP address pool!"); if (!args_info.forgiving_flag) goto end_processing; } } } /* statip */ if (args_info.statip_arg) { struct in_addr addr; struct in_addr mask; _options.statip = STRDUP(args_info.statip_arg); if (option_aton(&addr, &mask, _options.statip, 0)) { log_err(0, "Failed to parse static IP address pool!"); return -1; } _options.allowstat = 1; } else { _options.allowstat = 0; } #ifdef ENABLE_UAMANYIP if (args_info.uamnatanyipex_arg) { if (option_aton(&_options.uamnatanyipex_addr, &_options.uamnatanyipex_mask, args_info.uamnatanyipex_arg, 0)) { log_err(0, "Failed to parse uamnatanyipex network!"); return -1; } } if (args_info.uamanyipex_arg) { if (option_aton(&_options.uamanyipex_addr, &_options.uamanyipex_mask, args_info.uamanyipex_arg, 0)) { log_err(0, "Failed to parse uamanyipex network!"); return -1; } } #endif if (args_info.dns1_arg) { if (!inet_aton(args_info.dns1_arg, &_options.dns1)) { log_err(0,"Invalid primary DNS address: %s!", args_info.dns1_arg); if (!args_info.forgiving_flag) goto end_processing; } } else if (_res.nscount >= 1) { _options.dns1 = _res.nsaddr_list[0].sin_addr; } else { _options.dns1.s_addr = 0; } if (args_info.dns2_arg) { if (!inet_aton(args_info.dns2_arg, &_options.dns2)) { log_err(0,"Invalid secondary DNS address: %s!", args_info.dns1_arg); if (!args_info.forgiving_flag) goto end_processing; } } else if (_res.nscount >= 2) { _options.dns2 = _res.nsaddr_list[1].sin_addr; } else { _options.dns2.s_addr = _options.dns1.s_addr; } /* If no listen option is specified listen to any local port */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.radiuslisten_arg) { if (!(host = gethostbyname(args_info.radiuslisten_arg))) { log_err(0, "Invalid listening address: %s! [%s]", args_info.radiuslisten_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.radiuslisten.s_addr, host->h_addr, host->h_length); } } else { _options.radiuslisten.s_addr = htonl(INADDR_ANY); } #ifdef ENABLE_NETNAT if (args_info.natip_arg) { if (!(host = gethostbyname(args_info.natip_arg))) { log_warn(0, "Invalid natip address: %s! [%s]", args_info.natip_arg, strerror(errno)); } else { memcpy(&_options.natip.s_addr, host->h_addr, host->h_length); } } #endif if (args_info.uamlogoutip_arg) { if (!(host = gethostbyname(args_info.uamlogoutip_arg))) { log_warn(0, "Invalid uamlogoutup address: %s! [%s]", args_info.uamlogoutip_arg, strerror(errno)); } else { memcpy(&_options.uamlogout.s_addr, host->h_addr, host->h_length); } } if (args_info.uamaliasip_arg) { if (!(host = gethostbyname(args_info.uamaliasip_arg))) { log_warn(0, "Invalid uamaliasip address: %s! [%s]", args_info.uamlogoutip_arg, strerror(errno)); } else { memcpy(&_options.uamalias.s_addr, host->h_addr, host->h_length); } } if (args_info.postauthproxy_arg) { if (!(host = gethostbyname(args_info.postauthproxy_arg))) { log_warn(0, "Invalid postauthproxy address: %s! [%s]", args_info.postauthproxy_arg, strerror(errno)); } else { memcpy(&_options.postauth_proxyip.s_addr, host->h_addr, host->h_length); } } /* If no option is specified terminate */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.radiusserver1_arg) { if (!(host = gethostbyname(args_info.radiusserver1_arg))) { log_err(0, "Invalid radiusserver1 address: %s! [%s]", args_info.radiusserver1_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.radiusserver1.s_addr, host->h_addr, host->h_length); } } else { log_err(0,"No radiusserver1 address given!"); if (!args_info.forgiving_flag) goto end_processing; } /* radiusserver2 */ /* If no option is specified terminate */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.radiusserver2_arg) { if (!(host = gethostbyname(args_info.radiusserver2_arg))) { log_err(0, "Invalid radiusserver2 address: %s! [%s]", args_info.radiusserver2_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.radiusserver2.s_addr, host->h_addr, host->h_length); } } else { _options.radiusserver2.s_addr = 0; } /* If no listen option is specified listen to any local port */ /* Do hostname lookup to translate hostname to IP address */ if (args_info.proxylisten_arg) { #ifdef ENABLE_RADPROXY if (!(host = gethostbyname(args_info.proxylisten_arg))) { log_err(0, "Invalid listening address: %s! [%s]", args_info.proxylisten_arg, strerror(errno)); if (!args_info.forgiving_flag) goto end_processing; } else { memcpy(&_options.proxylisten.s_addr, host->h_addr, host->h_length); } } else { _options.proxylisten.s_addr = htonl(INADDR_ANY); #elif (_debug_) log_warn(0,"radproxy not implemented. build with --enable-radproxy"); #endif } /* Store proxyclient as in_addr net and mask */ if (args_info.proxyclient_arg) { #ifdef ENABLE_RADPROXY if(option_aton(&_options.proxyaddr, &_options.proxymask, args_info.proxyclient_arg, 0)) { log_err(0,"Invalid proxy client address: %s!", args_info.proxyclient_arg); if (!args_info.forgiving_flag) goto end_processing; } } else { _options.proxyaddr.s_addr = ~0; /* Let nobody through */ _options.proxymask.s_addr = 0; #elif (_debug_) log_warn(0,"radproxy not implemented. build with --enable-radproxy"); #endif } memset(_options.macok, 0, sizeof(_options.macok)); _options.macoklen = 0; for (numargs = 0; numargs < args_info.macallowed_given; ++numargs) { char *p1 = NULL; char *p2 = NULL; char *p3 = malloc(strlen(args_info.macallowed_arg[numargs])+1); int i; unsigned int mac[6]; log_dbg("Macallowed #%d: %s", numargs, args_info.macallowed_arg[numargs]); strcpy(p3, args_info.macallowed_arg[numargs]); p1 = p3; if ((p2 = strchr(p1, ','))) { *p2 = '\0'; } while (p1) { if (_options.macoklen>=MACOK_MAX) { log_err(0,"Too many addresses in macallowed %s!", args_info.macallowed_arg); } else { /* Replace anything but hex and comma with space */ for (i=0; i<strlen(p1); i++) if (!isxdigit((int) p1[i])) p1[i] = 0x20; if (sscanf (p1, "%2x %2x %2x %2x %2x %2x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) { log_err(0, "Failed to convert macallowed option to MAC Address"); } else { log_dbg("Macallowed address #%d: %.2X-%.2X-%.2X-%.2X-%.2X-%.2X", _options.macoklen, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); for (i = 0; i < 6; i++) _options.macok[_options.macoklen][i] = (unsigned char) mac[i]; _options.macoklen++; } } if (p2) { p1 = p2+1; if ((p2 = strchr(p1, ','))) { *p2 = 0; } } else { p1 = NULL; } } free(p3); } /** string parameters **/ #ifdef HAVE_SSL _options.sslkeyfile = STRDUP(args_info.sslkeyfile_arg); _options.sslkeypass = STRDUP(args_info.sslkeypass_arg); _options.sslcertfile = STRDUP(args_info.sslcertfile_arg); _options.sslcafile = STRDUP(args_info.sslcafile_arg); #endif #ifdef USING_IPC_UNIX _options.unixipc = STRDUP(args_info.unixipc_arg); #endif #ifdef HAVE_NETFILTER_COOVA _options.kname = STRDUP(args_info.kname_arg); #endif #ifdef ENABLE_DNSLOG _options.dnslog = STRDUP(args_info.dnslog_arg); #else if (args_info.dnslog_arg) log_err(0, "option dnslog given when no support built-in"); #endif #ifdef ENABLE_IPWHITELIST _options.ipwhitelist = STRDUP(args_info.ipwhitelist_arg); #else if (args_info.ipwhitelist_arg) log_err(0, "option ipwhitelist given when no support built-in"); #endif #ifdef ENABLE_UAMDOMAINFILE _options.uamdomainfile = STRDUP(args_info.uamdomainfile_arg); #else if (args_info.uamdomainfile_arg) log_err(0, "option uamdomainfile given when no support built-in"); #endif #ifdef ENABLE_MODULES _options.moddir = STRDUP(args_info.moddir_arg); #else if (args_info.moddir_arg) log_err(0, "option moddir given when no support built-in"); #endif #ifdef ENABLE_RADPROXY if (!args_info.proxysecret_arg) { _options.proxysecret = STRDUP(args_info.radiussecret_arg); } else { _options.proxysecret = STRDUP(args_info.proxysecret_arg); } #endif #ifdef ENABLE_REDIRINJECT _options.inject = STRDUP(args_info.inject_arg); _options.inject_ext = STRDUP(args_info.injectext_arg); _options.inject_wispr = args_info.injectwispr_flag; #endif #ifdef ENABLE_EXTADMVSA if (args_info.extadmvsa_given) { for (numargs = 0; numargs < args_info.extadmvsa_given && numargs < EXTADMVSA_ATTR_CNT; ++numargs) { int len = strlen(args_info.extadmvsa_arg[numargs]); if (len > 0 && len < 256) { unsigned int i[2]; char s[256]; if (sscanf(args_info.extadmvsa_arg[numargs], "%u,%u:%s", &i[0], &i[1], s) == 3) { char *idx = strchr(s, ':'); _options.extadmvsa[numargs].attr_vsa = i[0]; _options.extadmvsa[numargs].attr = i[1]; if (idx) *idx = 0; safe_strncpy(_options.extadmvsa[numargs].script, s, sizeof(_options.extadmvsa[numargs].script)-1); if (idx) { safe_strncpy(_options.extadmvsa[numargs].data, idx + 1, sizeof(_options.extadmvsa[numargs].data)-1); } } else if (sscanf(args_info.extadmvsa_arg[numargs], "%u:%s", &i[0], s) == 2) { char *idx = strchr(s, ':'); _options.extadmvsa[numargs].attr = i[0]; if (idx) *idx = 0; safe_strncpy(_options.extadmvsa[numargs].script, s, sizeof(_options.extadmvsa[numargs].script)-1); if (idx) { safe_strncpy(_options.extadmvsa[numargs].data, idx + 1, sizeof(_options.extadmvsa[numargs].data)-1); } } else { log_err(0, "invalid input %s", args_info.extadmvsa_arg[numargs]); } } log_dbg("Extended admin-user attr (%d/%d) data=%s script=%s", (int)_options.extadmvsa[numargs].attr_vsa, (int)_options.extadmvsa[numargs].attr, _options.extadmvsa[numargs].data, _options.extadmvsa[numargs].script); } } #endif _options.peerkey = STRDUP(args_info.peerkey_arg); _options.routeif = STRDUP(args_info.routeif_arg); _options.wwwdir = STRDUP(args_info.wwwdir_arg); _options.wwwbin = STRDUP(args_info.wwwbin_arg); _options.uamui = STRDUP(args_info.uamui_arg); _options.localusers = STRDUP(args_info.localusers_arg); _options.uamurl = STRDUP(args_info.uamserver_arg); _options.uamaaaurl = STRDUP(args_info.uamaaaurl_arg); _options.uamhomepage = STRDUP(args_info.uamhomepage_arg); _options.wisprlogin = STRDUP(args_info.wisprlogin_arg); _options.uamsecret = STRDUP(args_info.uamsecret_arg); _options.macsuffix = STRDUP(args_info.macsuffix_arg); _options.macpasswd = STRDUP(args_info.macpasswd_arg); _options.adminuser = STRDUP(args_info.adminuser_arg); _options.adminpasswd = STRDUP(args_info.adminpasswd_arg); _options.adminupdatefile = STRDUP(args_info.adminupdatefile_arg); _options.rtmonfile = STRDUP(args_info.rtmonfile_arg); _options.ssid = STRDUP(args_info.ssid_arg); _options.vlan = STRDUP(args_info.vlan_arg); _options.nasmac = STRDUP(args_info.nasmac_arg); _options.nasip = STRDUP(args_info.nasip_arg); _options.tundev = STRDUP(args_info.tundev_arg); _options.radiusnasid = STRDUP(args_info.radiusnasid_arg); _options.radiuslocationid = STRDUP(args_info.radiuslocationid_arg); _options.radiuslocationname = STRDUP(args_info.radiuslocationname_arg); _options.locationname = STRDUP(args_info.locationname_arg); _options.radiussecret = STRDUP(args_info.radiussecret_arg); #ifdef ENABLE_LARGELIMITS /*_options.radiusacctsecret = STRDUP(args_info.radiusacctsecret_arg); _options.radiusadmsecret = STRDUP(args_info.radiusadmsecret_arg);*/ #endif _options.cmdsocket = STRDUP(args_info.cmdsocket_arg); _options.cmdsocketport = args_info.cmdsocketport_arg; _options.domain = STRDUP(args_info.domain_arg); _options.ipup = STRDUP(args_info.ipup_arg); _options.ipdown = STRDUP(args_info.ipdown_arg); _options.conup = STRDUP(args_info.conup_arg); _options.condown = STRDUP(args_info.condown_arg); _options.macup = STRDUP(args_info.macup_arg); _options.macdown = STRDUP(args_info.macdown_arg); _options.pidfile = STRDUP(args_info.pidfile_arg); _options.statedir = STRDUP(args_info.statedir_arg); _options.usestatusfile = STRDUP(args_info.usestatusfile_arg); _options.uamaliasname = STRDUP(args_info.uamaliasname_arg); _options.uamhostname = STRDUP(args_info.uamhostname_arg); _options.binconfig = STRDUP(args_info.bin_arg); _options.ethers = STRDUP(args_info.ethers_arg); #ifdef ENABLE_IEEE8021Q _options.ieee8021q = args_info.ieee8021q_flag; _options.ieee8021q_only = args_info.only8021q_flag; _options.vlanupdate = STRDUP(args_info.vlanupdate_arg); #endif #ifdef ENABLE_PROXYVSA _options.locationupdate = STRDUP(args_info.locationupdate_arg); #endif #ifdef EX_OPT_MAIN #include EX_OPT_MAIN #endif ret = 0; if (_options.binconfig) { /* save out the configuration */ bstring bt = bfromcstr(""); int ok = options_save(_options.binconfig, bt); if (!ok) log_err(0, "could not save configuration options!"); bdestroy(bt); } if (args_info.reload_flag) { if (execl(SBINDIR "/chilli_query", "chilli_query", args_info.cmdsocket_arg, "reload", (char *) 0) != 0) { log_err(errno, "execl() did not return 0!"); exit(2); } } end_processing: cmdline_parser_free (&args_info); return ret; }
bool do_search(CURL* curl, bstring name, bool all) { DIR* dir; bool printed; CURLcode res; FILE* fp; list_t installed; struct bStream* stream; long httpcode = 0; bstring buffer, fname, sstr; bstring ext = bfromcstr(".lua"); bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/search?q="); bstring modpath = osutil_getmodulepath(); struct dirent* entry; list_init(&installed); list_attributes_copy(&installed, list_meter_string, 1); list_attributes_comparator(&installed, list_comparator_string); // Attempt to open the modules directory. dir = opendir(modpath->data); if (dir == NULL) { printd(LEVEL_ERROR, "unable to query local repository.\n"); return 1; } // Append the temporary search file name. bcatcstr(modpath, "/.search"); bconcat(url, name); // Open the file and do the cURL transfer. printd(LEVEL_DEFAULT, "querying module repository...\n"); fp = fopen(modpath->data, "wb"); curl_easy_setopt(curl, CURLOPT_URL, url->data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode); if (res != 0 || httpcode != 200) { bdestroy(url); bdestroy(name); bdestroy(modpath); printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode); return 1; } fclose(fp); // Print the local results. if (all) printd(LEVEL_DEFAULT, "all modules:\n"); else printd(LEVEL_DEFAULT, "search results for %s:\n", name->data); while ((entry = readdir(dir)) != NULL) { fname = bfromcstr(&entry->d_name[0]); if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR) { bdestroy(fname); continue; } if (binstr(fname, 0, name) == BSTR_ERR) { bdestroy(fname); continue; } if (entry->d_type != DT_REG) { bdestroy(fname); continue; } sstr = bmidstr(fname, 0, blength(fname) - 4); printd(LEVEL_DEFAULT, " %s (installed)\n", sstr->data); list_append(&installed, sstr->data); bdestroy(sstr); bdestroy(fname); } // Print the online results. fp = fopen(modpath->data, "r"); stream = bsopen(&read_data, fp); buffer = bfromcstr(""); printed = false; while (bsreadln(buffer, stream, '\n') != BSTR_ERR) { btrimws(buffer); sstr = bmidstr(buffer, 0, blength(buffer) - 4); if (!list_contains(&installed, sstr->data)) printd(LEVEL_DEFAULT, " %s\n", sstr->data); printed = true; bdestroy(sstr); } if (!printed) printd(LEVEL_DEFAULT, " <no online results>\n"); bsclose(stream); fclose(fp); // Clean up. curl_easy_cleanup(curl); return 0; }
void likwid_markerInit(void) { int i; int verbosity; int setinit = 0; bstring bThreadStr; bstring bEventStr; struct bstrList* threadTokens; struct bstrList* eventStrings; char* modeStr = getenv("LIKWID_MODE"); char* eventStr = getenv("LIKWID_EVENTS"); char* cThreadStr = getenv("LIKWID_THREADS"); char* filepath = getenv("LIKWID_FILEPATH"); char* perfpid = getenv("LIKWID_PERF_EXECPID"); char execpid[20]; /* Dirty hack to avoid nonnull warnings */ int (*ownatoi)(const char*); ownatoi = &atoi; if ((modeStr != NULL) && (filepath != NULL) && (eventStr != NULL) && (cThreadStr != NULL) && likwid_init == 0) { setinit = 1; } else if (likwid_init == 0) { fprintf(stderr, "Running without Marker API. Activate Marker API with -m on commandline.\n"); return; } else { return; } if (!lock_check()) { fprintf(stderr,"Access to performance counters is locked.\n"); exit(EXIT_FAILURE); } topology_init(); numa_init(); affinity_init(); hashTable_init(); //#ifndef LIKWID_USE_PERFEVENT HPMmode(atoi(modeStr)); //#endif if (getenv("LIKWID_DEBUG") != NULL) { perfmon_verbosity = atoi(getenv("LIKWID_DEBUG")); verbosity = perfmon_verbosity; } bThreadStr = bfromcstr(cThreadStr); threadTokens = bsplit(bThreadStr,','); num_cpus = threadTokens->qty; for (i=0; i<num_cpus; i++) { threads2Cpu[i] = ownatoi(bdata(threadTokens->entry[i])); } bdestroy(bThreadStr); bstrListDestroy(threadTokens); if (getenv("LIKWID_PIN") != NULL) { likwid_pinThread(threads2Cpu[0]); if (getenv("OMP_NUM_THREADS") != NULL) { if (ownatoi(getenv("OMP_NUM_THREADS")) > num_cpus) { use_locks = 1; } } if (getenv("CILK_NWORKERS") != NULL) { if (ownatoi(getenv("CILK_NWORKERS")) > num_cpus) { use_locks = 1; } } } #ifdef LIKWID_USE_PERFEVENT if (perfpid != NULL) { snprintf(execpid, 19, "%d", getpid()); setenv("LIKWID_PERF_PID", execpid, 1); char* perfflags = getenv("LIKWID_PERF_FLAGS"); if (perfflags) { setenv("LIKWID_PERF_FLAGS", getenv("LIKWID_PERF_FLAGS"), 1); } } #endif i = perfmon_init(num_cpus, threads2Cpu); if (i<0) { //fprintf(stderr,"Failed to initialize LIKWID perfmon library.\n"); return; } bEventStr = bfromcstr(eventStr); eventStrings = bsplit(bEventStr,'|'); numberOfGroups = eventStrings->qty; groups = malloc(numberOfGroups * sizeof(int)); if (!groups) { fprintf(stderr,"Cannot allocate space for group handling.\n"); bstrListDestroy(eventStrings); exit(EXIT_FAILURE); } for (i=0; i<eventStrings->qty; i++) { groups[i] = perfmon_addEventSet(bdata(eventStrings->entry[i])); } bstrListDestroy(eventStrings); bdestroy(bEventStr); for (i=0; i<num_cpus; i++) { hashTable_initThread(threads2Cpu[i]); for(int j=0; j<groupSet->groups[groups[0]].numberOfEvents;j++) { groupSet->groups[groups[0]].events[j].threadCounter[i].init = TRUE; groupSet->groups[groups[0]].state = STATE_START; } } if (setinit) { likwid_init = 1; } threads2Pthread[registered_cpus] = pthread_self(); registered_cpus++; groupSet->activeGroup = 0; perfmon_setupCounters(groupSet->activeGroup); perfmon_startCounters(); }
char * getHTML() { bstring html = bfromcstr("<!DOCTYPE html>\n<html>\n"); balloc(html, style_css_len); bcatcstr(html, "<head>"); bcatcstr(html, "<title>mdr</title>"); bcatcstr(html, "<style type='text/css'>"); bcatcstr(html, (char *)style_css); bcatcstr(html, "</style>"); bcatcstr(html, "</head>"); bcatcstr(html, "<body>\n<table cellpadding='0'>\n"); // Read from stdin bstring stdinContents = bread ((bNread) fread, stdin); if (stdinContents == NULL) { return "There was an error reading from stdin."; } // Split into lines struct bstrList * inputLines; if ((inputLines = bsplit(stdinContents, '\n')) != NULL) { // We are going to build a map showing which lines in the input belong // in which lines in the output and how they should be displayed. We'll // allocate the left and right maps to be big enough to each hold all // the input data, which is more than enough. lineData * lineMapL = malloc(inputLines->qty * sizeof(lineData)); if (lineMapL == NULL) { free(lineMapL); printf("Memory allocation error.\n"); exit(-1); } lineData * lineMapR = malloc(inputLines->qty * sizeof(lineData)); if (lineMapR == NULL) { free(lineMapR); printf("Memory allocation error.\n"); exit(-1); } int lineMapPosL = 0; int lineMapPosR = 0; int useL; int useR; enum lineType type; int padding; int lineNoL = 0; int lineNoR = 0; int firstInfoLine = TRUE; int startNewFileOk = TRUE; int startOldFileOk = TRUE; // Map input lines to their output column (left, right, or both) int i; for (i = 0; i < inputLines->qty; i++) { useL = 0; useR = 0; type = SHARED; padding = 1; if (startOldFileOk && stringStartsWith(inputLines->entry[i], "---")) { type = OLD_FILE; useL = 1; padding = 4; lineNoL = -1; lineNoR = -1; startOldFileOk = FALSE; } else if (startNewFileOk && stringStartsWith(inputLines->entry[i], "+++")) { type = NEW_FILE; useR = 1; padding = 4; lineNoL = -1; lineNoR = -1; startNewFileOk = FALSE; } else if (stringStartsWith(inputLines->entry[i], "@@")) { syncLineNumbers(inputLines->entry[i], &lineNoL, &lineNoR); if (firstInfoLine) { // Don't print the info row but still increment the line // numbers normally. // TODO: Might be better to mark the row as the first and // hide it with CSS instead of just not printing it. lineNoL++; lineNoR++; } else { type = INFO; useR = 1; useL = 1; padding = 1; } firstInfoLine = FALSE; } else if (bdata(inputLines->entry[i])[0] == '-') { type = OLD; useL = 1; } else if (bdata(inputLines->entry[i])[0] == '+') { type = NEW; useR = 1; } else if (bdata(inputLines->entry[i])[0] == ' ') { type = SHARED; useL = 1; useR = 1; } else { type = HEADER; lineNoL = 0; lineNoR = 0; firstInfoLine = TRUE; startNewFileOk = TRUE; startOldFileOk = TRUE; } // Balance. if (type == HEADER || (type == SHARED && (useL || useR)) || i == inputLines->qty - 1) { int difference = lineMapPosL - lineMapPosR; int j; if (difference > 0) { for (j = 0; j < difference; j++) { lineMapR[lineMapPosR].type = EMPTY; lineMapPosR++; } } else if (difference < 0) { for (j = 0; j < (difference * -1); j++) { lineMapL[lineMapPosL].type = EMPTY; lineMapPosL++; } } } if (useL) { lineMapL[lineMapPosL].inputPos = i; lineMapL[lineMapPosL].type = type; lineMapL[lineMapPosL].padding = padding; lineMapL[lineMapPosL].lineNo = lineNoL - 1; lineMapL[lineMapPosL].leadingSpaces = 0; lineMapPosL++; lineNoL++; } if (useR) { lineMapR[lineMapPosR].inputPos = i; lineMapR[lineMapPosR].type = type; lineMapR[lineMapPosR].padding = padding; lineMapR[lineMapPosR].lineNo = lineNoR - 1; lineMapR[lineMapPosR].leadingSpaces = 0; lineMapPosR++; lineNoR++; } } // Mapping complete. Quick sanity check that both L and R cols have the // same length. if (lineMapPosL != lineMapPosR) { return "Error displaying diff (generated columns not equal in length)."; } // Now we do the formatting work based on the map. for (i = 0; i < lineMapPosL; i++) { int * highlightMaskA = NULL; int * highlightMaskB = NULL; bstring contentL; bstring contentR; int leadingSpacesL = 0; int leadingSpacesR = 0; if (lineMapL[i].type != EMPTY) { contentL = getContentFromLine( inputLines->entry[lineMapL[i].inputPos], lineMapL[i].padding, &leadingSpacesL ); lineMapL[i].leadingSpaces = leadingSpacesL; } if (lineMapR[i].type != EMPTY) { contentR = getContentFromLine( inputLines->entry[lineMapR[i].inputPos], lineMapR[i].padding, &leadingSpacesR ); lineMapR[i].leadingSpaces = leadingSpacesR; } // Compare changed lines if (lineMapL[i].type == OLD && lineMapR[i].type == NEW) { lineMapL[i].type = CHANGE; lineMapR[i].type = CHANGE; determineLineHighlighting( contentL, contentR, &highlightMaskA, &highlightMaskB ); } // Format output bcatcstr(html, "<tr>\n"); if (lineMapL[i].type == EMPTY) { createEmptyLine(html); } else { createLine(LEFT, html, contentL, lineMapL[i], highlightMaskA); bdestroy(contentL); } if (lineMapR[i].type == EMPTY) { createEmptyLine(html); } else { createLine(RIGHT, html, contentR, lineMapR[i], highlightMaskB); bdestroy(contentR); } bcatcstr(html, "</tr>\n"); free(highlightMaskA); free(highlightMaskB); } bcatcstr(html, "</table>\n</body>\n</html>\n"); free(lineMapL); free(lineMapR); } bdestroy(stdinContents); bstrListDestroy(inputLines); char * result = bstr2cstr(html, '-'); bdestroy(html); return result; // Caller should free() }
int sky_importer_process_event_data(sky_importer *importer, sky_event *event, bstring source, jsmntok_t *tokens, uint32_t *index) { int rc; check(importer != NULL, "Importer required"); check(source != NULL, "Source required"); check(tokens != NULL, "Tokens required"); check(index != NULL, "Token index required"); jsmntok_t *data_token = &tokens[*index]; (*index)++; // Process over child tokens. int32_t i; for(i=0; i<(data_token->size/2); i++) { sky_event_data *event_data = NULL; jsmntok_t *key_token = &tokens[*index]; (*index)++; jsmntok_t *value_token = &tokens[*index]; (*index)++; // Retrieve property name. sky_property *property = NULL; bstring property_name = sky_importer_token_parse_bstring(source, key_token); rc = sky_property_file_find_by_name(importer->table->property_file, property_name, &property); check(rc == 0 && property != NULL, "Unable to find property: %s", bdata(property_name)); // Reallocate event data array. event->data_count++; event->data = realloc(event->data, sizeof(*event->data) * event->data_count); check_mem(event->data); // Parse string. char ch = bdata(source)[value_token->start]; bstring value = sky_importer_token_parse_bstring(source, value_token); if(value_token->type == JSMN_STRING) { event_data = sky_event_data_create_string(property->id, value); check_mem(event_data); } // Parse primitives. else if(value_token->type == JSMN_PRIMITIVE) { // True if(ch == 't') { event_data = sky_event_data_create_boolean(property->id, true); check_mem(event_data); } // False else if(ch == 'f') { event_data = sky_event_data_create_boolean(property->id, false); check_mem(event_data); } // Numbers (or null, which evaluates to Int 0). else { bstring value = sky_importer_token_parse_bstring(source, value_token); if(biseqcstr(property->data_type, "Float") == 1) { event_data = sky_event_data_create_float(property->id, atof(bdata(value))); check_mem(event_data); } else { event_data = sky_event_data_create_int(property->id, atoll(bdata(value))); check_mem(event_data); } } } bdestroy(value); // Make sure data was generated. check(event_data != NULL, "Event data could not be parsed for: %s", bdata(property->name)); event->data[event->data_count-1] = event_data; } return 0; error: return -1; }
/*start server listening on port*/ serv *initServer(char *port, char *password){ int serverSocket; /*adress info structs to be packed*/ struct sockaddr_in serverAddr; int yes = 1; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(atoi(port)); serverAddr.sin_addr.s_addr = INADDR_ANY; if ((serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ errnoExit("ERROR: Could not find a socket to bind to"); } /*multiple sockets on the same address*/ if (setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0){ close(serverSocket); errnoExit("ERROR: Could not set socket options"); } if (bind(serverSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0){ close(serverSocket); errnoExit("ERROR: Could not bind to socket"); } if(listen(serverSocket, SERVER_BACKLOG) < 0){ close(serverSocket); errnoExit("ERROR: Fail on listen"); } printf("Listening on port %s...\n", port); serv *newServer = (serv *) allocaZam(sizeof(serv)); /*get time that server was created*/ time_t currTime = time(NULL); char *createdStr = ctime(&currTime); int len = strlen(createdStr); createdStr[len - 1] = '\0'; bstring created = safe_BfromCstr(createdStr); newServer->created = created; /*set server name*/ bstring serverName = safe_BfromCstr(""); int rc = gethostname(charBuffromBstr(serverName), 513); serverName->slen = strlen(charBuffromBstr(serverName)); if (rc != 0 || !serverName->slen){ bdestroy(serverName); serverName = safe_BfromCstr("unresolved host"); } newServer->name = serverName; /*initialize reader/writer lock to eliminate race conditions*/ /*between threads trying modify server state*/ newServer->lock = newRwlock(); /*initialize reader/writer locks to eliminate race conditions*/ /*between threads trying to write the same key to the tree*/ /*concurrently, read a key that's being changed, etc.*/ newServer->clientsLock = newRwlock(); newServer->channelsLock = newRwlock(); /*initialize client hash table* to hold server * state and hash client data by nick*/ cliTbl *clients = (cliTbl*) allocaZam(sizeof(cliTbl)); *clients = NULL; newServer->clients = clients; chnlTbl *channels = (chnlTbl*) allocaZam(sizeof(chnlTbl)); *channels = NULL; newServer->channels = channels; /*set additional server info*/ newServer->socket = serverSocket; newServer->password = safe_BfromCstr(password); newServer->info = safe_BfromCstr("chir-0.0.2"); newServer->version = safe_BfromCstr("0.0.2"); newServer->channelModes = safe_BfromCstr("mtov"); newServer->userModes = safe_BfromCstr("ao"); newServer->numClients = 0; newServer->numConnections = 0; newServer->numChannels = 0; return newServer; }
int attempt_chroot_drop(Server *srv) { int rc = 0; log_info("All loaded up, time to turn into a server."); log_info("-- Starting " VERSION ". Copyright (C) Zed A. Shaw. Licensed BSD.\n"); log_info("-- Look in %s for startup messages and errors.", bdata(srv->error_log)); int testmode = 0; if(srv->chroot != NULL) { if(Unixy_chroot(srv->chroot) == 0) { if(Setting_get_int("server.daemonize", 1)) { rc = Unixy_daemonize(1); // 1 == chdir / check(rc == 0, "Failed to daemonize, looks like you're hosed."); } else { rc = chdir("/"); check(rc == 0, "Failed to change working directory to '/'."); } } else { log_warn("Couldn't chroot to %s, assuming running in test mode.", bdata(srv->chroot)); // rewrite the access log to be in the right location bstring temp = bformat("%s%s", bdata(srv->chroot), bdata(srv->access_log)); bassign(srv->access_log, temp); bdestroy(temp); temp = bformat(".%s", bdata(srv->pid_file)); bassign(srv->pid_file, temp); bdestroy(temp); testmode = 1; } } else { if(Setting_get_int("server.daemonize", 1)) { rc = Unixy_daemonize(0); // 0 == don't chdir check(rc == 0, "Failed to daemonize, looks like you're hosed."); } } rc = Unixy_pid_file(srv->pid_file); check(rc == 0, "Failed to make the PID file %s", bdata(srv->pid_file)); if(srv->chroot != NULL && ! testmode) { rc = Unixy_drop_priv(&PRIV_DIR); check(rc == 0, "Failed to drop priv to the owner of %s", bdata(&PRIV_DIR)); } else { rc = Unixy_drop_priv(NULL); check(rc == 0, "Failed to drop priv"); } if(!testmode) { FILE *log = fopen(bdata(srv->error_log), "a+"); check(log, "Couldn't open %s log file.", bdata(srv->error_log)); setbuf(log, NULL); check(0==add_log_to_rotate_list(srv->error_log,log),"Unable to add error log to list of files to rotate."); dbg_set_log(log); } return 0; error: return -1; }
int Connection_read_wspacket(Connection *conn) { bstring payload=NULL; uint8_t *dataU=NULL; char *data = IOBuf_start(conn->iob); int avail = IOBuf_avail(conn->iob); int64_t packet_length=-1; int smaller_packet_length; int header_length; char key[4]; int i; int data_length; int tries = 0; int rc=0; int fin; int inprogFlags=0; int isControl; int flags; again: dataU=NULL; data = IOBuf_start(conn->iob); avail = IOBuf_avail(conn->iob); packet_length=-1; smaller_packet_length=0; header_length=0; i=0; data_length=0; tries = 0; rc=0; fin=0; for(tries = 0; packet_length == -1 && tries < 8*CLIENT_READ_RETRIES; tries++) { if(avail > 0) { packet_length = Websocket_packet_length((uint8_t *)data, avail); } if(packet_length == -1) { data = IOBuf_read_some(conn->iob, &avail); check_debug(!IOBuf_closed(conn->iob), "Client closed during read."); } } check(packet_length > 0,"Error receiving websocket packet header.") check_debug(packet_length <= INT_MAX,"Websocket packet longer than MAXINT."); /* TODO properly terminate WS connection */ smaller_packet_length = (int)packet_length; /* TODO check for maximum length */ header_length=Websocket_header_length((uint8_t *) data, avail); data_length=smaller_packet_length-header_length; dataU = (uint8_t *)IOBuf_read_all(conn->iob,header_length,8*CLIENT_READ_RETRIES); memcpy(key,dataU+header_length-4,4); flags=dataU[0]; if (payload==NULL) { inprogFlags=flags; } fin=(WS_fin(dataU)); isControl=(WS_is_control(dataU)); { const char *error=WS_validate_packet(dataU,payload!=NULL); check(error==NULL,"%s",error); } dataU = (uint8_t *)IOBuf_read_all(conn->iob,data_length, 8*CLIENT_READ_RETRIES); check(dataU != NULL, "Client closed the connection during websocket packet."); for(i=0;i<data_length;++i) { dataU[i]^=key[i%4]; } if(isControl) /* Control frames get sent right-away */ { Request_set(conn->req,bfromcstr("FLAGS"),bformat("0x%X",flags|0x80),1); rc = Connection_send_to_handler(conn, conn->handler, (void *)dataU,data_length); check_debug(rc == 0, "Failed to deliver to the handler."); } else { if(fin) { Request_set(conn->req,bfromcstr("FLAGS"),bformat("0x%X",inprogFlags|0x80),1); } if (payload == NULL) { if (fin) { rc = Connection_send_to_handler(conn, conn->handler, (void *)dataU,data_length); check_debug(rc == 0, "Failed to deliver to the handler."); } else { payload = blk2bstr(dataU,data_length); check(payload != NULL,"Allocation failed"); } } else { check(BSTR_OK == bcatblk(payload,dataU,data_length), "Concatenation failed"); if (fin) { rc = Connection_send_to_handler(conn, conn->handler, bdata(payload),blength(payload)); check_debug(rc == 0, "Failed to deliver to the handler."); bdestroy(payload); payload=NULL; } } } if (payload != NULL) { goto again; } return packet_length; error: bdestroy(payload); return -1; }
HLSLCC_API int HLSLCC_APIENTRY TranslateHLSLFromMem(const char* shader, unsigned int flags, GLLang language, const GlExtensions *extensions, GLSLCrossDependencyData* dependencies, GLSLShader* result) { uint32_t* tokens; Shader* psShader; char* glslcstr = NULL; int GLSLShaderType = GL_FRAGMENT_SHADER_ARB; int success = 0; uint32_t i; tokens = (uint32_t*)shader; psShader = DecodeDXBC(tokens); if(psShader) { HLSLCrossCompilerContext sContext; if(psShader->ui32MajorVersion <= 3) { flags &= ~HLSLCC_FLAG_COMBINE_TEXTURE_SAMPLERS; } sContext.psShader = psShader; sContext.flags = flags; sContext.psDependencies = dependencies; for(i=0; i<NUM_PHASES;++i) { sContext.havePostShaderCode[i] = 0; } TranslateToGLSL(&sContext, &language,extensions); switch(psShader->eShaderType) { case VERTEX_SHADER: { GLSLShaderType = GL_VERTEX_SHADER_ARB; break; } case GEOMETRY_SHADER: { GLSLShaderType = GL_GEOMETRY_SHADER; break; } case DOMAIN_SHADER: { GLSLShaderType = GL_TESS_EVALUATION_SHADER; break; } case HULL_SHADER: { GLSLShaderType = GL_TESS_CONTROL_SHADER; break; } case COMPUTE_SHADER: { GLSLShaderType = GL_COMPUTE_SHADER; break; } default: { break; } } glslcstr = bstr2cstr(sContext.glsl, '\0'); bdestroy(sContext.glsl); bdestroy(sContext.earlyMain); for(i=0; i<NUM_PHASES; ++i) { bdestroy(sContext.postShaderCode[i]); } for(i=0; i<NUM_PHASES;++i) { if(psShader->asPhase[i].ppsDecl != 0) { uint32_t k; for(k=0; k < psShader->asPhase[i].ui32InstanceCount; ++k) { hlslcc_free(psShader->asPhase[i].ppsDecl[k]); } hlslcc_free(psShader->asPhase[i].ppsDecl); } if(psShader->asPhase[i].ppsInst != 0) { uint32_t k; for(k=0; k < psShader->asPhase[i].ui32InstanceCount; ++k) { FreeSubOperands(psShader->asPhase[i].ppsInst[k], psShader->asPhase[i].pui32InstCount[k]); hlslcc_free(psShader->asPhase[i].ppsInst[k]); } hlslcc_free(psShader->asPhase[i].ppsInst); } } memcpy(&result->reflection,&psShader->sInfo,sizeof(psShader->sInfo)); result->textureSamplerInfo.ui32NumTextureSamplerPairs = psShader->textureSamplerInfo.ui32NumTextureSamplerPairs; for (i=0; i<result->textureSamplerInfo.ui32NumTextureSamplerPairs; i++) strcpy(result->textureSamplerInfo.aTextureSamplerPair[i].Name, psShader->textureSamplerInfo.aTextureSamplerPair[i].Name); hlslcc_free(psShader); success = 1; } shader = 0; tokens = 0; /* Fill in the result struct */ result->shaderType = GLSLShaderType; result->sourceCode = glslcstr; result->GLSLLanguage = language; return success; }
static int32_t config_cleanup(void) { int32_t ret; ret = bdestroy(applocate_conf.plat_ip); return ret; }
static bstring tr_eval(TextResource tr, trnode_t* node) { //internally we work with bstrings trnode_t* tmpNode; switch(node->type) { case TRNODE_TEXT: return bstrcpy(node->textData); case TRNODE_REPR: ; int match=0; if (node->condKey) { assert(node->condValue); //conditional char* condkey = bstr2cstr(node->condKey,'\0'); bstring val = ght_get(tr->parameters,strlen(condkey),condkey); bcstrfree(condkey); if (val && !bstrcmp(node->condValue, val)) { //matches match = 1; } } else { //unconditional, so go too match=1; } if (match) { return tr_evalKey(tr,node->reprKey->data); } else return bfromcstr(""); case TRNODE_STRING: //these guys have a blob of nodes that needs to be catted together smartly tmpNode = node->children_list; bstring tmpStr = bfromcstralloc(32,""); while(tmpNode) { bstring childStr = tr_eval(tr,tmpNode); bconchar(tmpStr,' '); bconcat(tmpStr,childStr); bdestroy(childStr); tmpNode = tmpNode->next; } return tmpStr; case TRNODE_SWITCH: //look through the children for matching choice ; char* switchVar = bstr2cstr(node->switchVar,'\0'); bstring val = ght_get(tr->parameters,strlen(switchVar),switchVar); bcstrfree(switchVar); tmpNode = node->children_list; while(tmpNode) { assert(tmpNode->type == TRNODE_STRING); assert(tmpNode->caseValue); if (!bstrcmp(tmpNode->caseValue,val)) { //we match, return this return tr_eval(tr,tmpNode); } //try next tmpNode = tmpNode->next; } return bfromcstr(""); default: assert(0); } assert(0); return NULL; }
const char* glswGetShader(const char* pEffectKey) { glswContext* gc = glswGetCurrentContext(); bstring effectKey = 0; glswList* closestMatch = 0; struct bstrList* tokens = 0; bstring effectName = 0; glswList* pLoadedEffect = 0; glswList* pShaderEntry = 0; bstring shaderKey = 0; if (!gc) { return 0; } // Extract the effect name from the effect key effectKey = bfromcstr(pEffectKey); tokens = bsplit(effectKey, '.'); if (!tokens || !tokens->qty) { bdestroy(gc->ErrorMessage); gc->ErrorMessage = bformat("Malformed effect key key '%s'.", pEffectKey); bstrListDestroy(tokens); bdestroy(effectKey); return 0; } effectName = tokens->entry[0]; // Check if we already loaded this effect file pLoadedEffect = gc->LoadedEffects; while (pLoadedEffect) { if (biseq(pLoadedEffect->Key, effectName) == 1) { break; } pLoadedEffect = pLoadedEffect->Next; } // If we haven't loaded this file yet, load it in if (!pLoadedEffect) { bstring effectContents = 0; struct bstrList* lines = 0; int lineNo = 0; { FILE* fp = 0; bstring effectFile = 0; // Decorate the effect name to form the fullpath effectFile = bstrcpy(effectName); binsert(effectFile, 0, gc->PathPrefix, '?'); bconcat(effectFile, gc->PathSuffix); // Attempt to open the file fp = fopen((const char*) effectFile->data, "rb"); if (!fp) { bdestroy(gc->ErrorMessage); gc->ErrorMessage = bformat("Unable to open effect file '%s'.", effectFile->data); bdestroy(effectFile); bdestroy(effectKey); bstrListDestroy(tokens); return 0; } // Add a new entry to the front of gc->LoadedEffects { glswList* temp = gc->LoadedEffects; gc->LoadedEffects = (glswList*) calloc(sizeof(glswList), 1); gc->LoadedEffects->Key = bstrcpy(effectName); gc->LoadedEffects->Next = temp; } // Read in the effect file effectContents = bread_gl((bNread) fread, fp); fclose(fp); bdestroy(effectFile); effectFile = 0; } lines = bsplit(effectContents, '\n'); bdestroy(effectContents); effectContents = 0; for (lineNo = 0; lineNo < lines->qty; lineNo++) { bstring line = lines->entry[lineNo]; // If the line starts with "--", then it marks a new section if (blength(line) >= 2 && line->data[0] == '-' && line->data[1] == '-') { // Find the first character in [A-Za-z0-9_]. int colNo = 0; for (colNo = 2; colNo < blength(line); colNo++) { char c = line->data[colNo]; if (__glsw__Alphanumeric(c)) { break; } } // If there's no alphanumeric character, // then this marks the start of a new comment block. if (colNo >= blength(line)) { bdestroy(shaderKey); shaderKey = 0; } else { // Keep reading until a non-alphanumeric character is found. int endCol = 0; for (endCol = colNo; endCol < blength(line); endCol++) { char c = line->data[endCol]; if (!__glsw__Alphanumeric(c)) { break; } } bdestroy(shaderKey); shaderKey = bmidstr(line, colNo, endCol - colNo); // Add a new entry to the shader map. { glswList* temp = gc->ShaderMap; gc->ShaderMap = (glswList*) calloc(sizeof(glswList), 1); gc->ShaderMap->Key = bstrcpy(shaderKey); gc->ShaderMap->Next = temp; gc->ShaderMap->Value = bformat("//__LINE_OFFSET_\n"); binsertch(gc->ShaderMap->Key, 0, 1, '.'); binsert(gc->ShaderMap->Key, 0, effectName, '?'); } // Check for a version mapping. if (gc->TokenMap) { tokens = bsplit(shaderKey, '.'); assert(tokens); glswList* pTokenMapping = gc->TokenMap; while (pTokenMapping) { bstring directive = 0; int tokenIndex = 0; // An empty key in the token mapping means "always prepend this directive". // The effect name itself is also checked against the token mapping. if (blength(pTokenMapping->Key) == 0 || biseq(pTokenMapping->Key, effectName) == 1) { directive = pTokenMapping->Value; binsert(gc->ShaderMap->Value, 0, directive, '?'); } // Check all tokens in the current section divider for a mapped token. for (tokenIndex = 0; tokenIndex < tokens->qty && !directive; tokenIndex++) { bstring token = tokens->entry[tokenIndex]; if (biseq(pTokenMapping->Key, token) == 1) { directive = pTokenMapping->Value; binsert(gc->ShaderMap->Value, 0, directive, '?'); } } pTokenMapping = pTokenMapping->Next; } bstrListDestroy(tokens); tokens = 0; } } continue; } if (shaderKey) { bconcat(gc->ShaderMap->Value, line); bconchar(gc->ShaderMap->Value, '\n'); } } // Cleanup bstrListDestroy(lines); lines = 0; bdestroy(shaderKey); shaderKey = 0; } // Find the longest matching shader key pShaderEntry = gc->ShaderMap; while (pShaderEntry) { if (binstr(effectKey, 0, pShaderEntry->Key) == 0 && (!closestMatch || blength(pShaderEntry->Key) > blength(closestMatch->Key))) { closestMatch = pShaderEntry; } pShaderEntry = pShaderEntry->Next; } bstrListDestroy(tokens); tokens = 0; bdestroy(effectKey); effectKey = 0; if (!closestMatch) { bdestroy(gc->ErrorMessage); gc->ErrorMessage = bformat("Could not find shader with key '%s'.", pEffectKey); return 0; } return (const char*) closestMatch->Value->data; }
/* File format * 1 numberOfThreads numberOfRegions * 2 regionID:regionTag0 * 3 regionID:regionTag1 * 4 regionID threadID countersvalues(space separated) * 5 regionID threadID countersvalues */ void likwid_markerClose(void) { FILE *file = NULL; LikwidResults* results = NULL; int numberOfThreads; int numberOfRegions; if ( ! likwid_init ) { return; } hashTable_finalize(&numberOfThreads, &numberOfRegions, &results); file = fopen(getenv("LIKWID_FILEPATH"),"w"); if (file != NULL) { fprintf(file,"%d %d\n",numberOfThreads,numberOfRegions); for (int i=0; i<numberOfRegions; i++) { fprintf(file,"%d:%s\n",i,bdata(results[i].tag)); } for (int i=0; i<numberOfRegions; i++) { for (int j=0; j<numberOfThreads; j++) { fprintf(file,"%d ",i); fprintf(file,"%d ",j); fprintf(file,"%u ",results[i].count[j]); fprintf(file,"%e ",results[i].time[j]); for (int k=0; k<NUM_PMC; k++) { fprintf(file,"%e ",results[i].counters[j][k]); } fprintf(file,"\n"); } } fclose(file); } for (int i=0;i<numberOfRegions; i++) { for (int j=0;j<numberOfThreads; j++) { free(results[i].counters[j]); } free(results[i].time); bdestroy(results[i].tag); free(results[i].count); free(results[i].counters); } if (results != NULL) { free(results); } msr_finalize(); pci_finalize(); for (int i=0; i<MAX_NUM_THREADS; i++) { accessClient_finalize(thread_socketFD[i]); thread_socketFD[i] = -1; } }
void dec_prepare_output_file (FILE *fp) { if(putHeader(input_file_header, fp)){ ERROR("putHeader"); } uint32_t k = 0, **vector = NULL, *size_vector; vector = calloc(input_file_header->numChannels, sizeof(uint32_t *)); size_vector = calloc(input_file_header->numChannels, sizeof(uint32_t)); for(curr_channel=0; curr_channel<input_file_header->numChannels; curr_channel++) { size_vector[curr_channel] = b_to_uint32(&output_buffer[curr_channel], &vector[curr_channel], input_file_header->bitsPerSample, 0); } for (k=0; k<size_vector[0]; k++){ for(curr_channel=0; curr_channel<input_file_header->numChannels; curr_channel++) { switch (input_file_header->bitsPerSample/8){ case 1: if ( write_1_byte32(fp, &vector[curr_channel][k], input_file_header->endianness)){ printf("ERROR: io chunkSize\n"); }break; case 2: if (write_2_bytes32(fp, &vector[curr_channel][k], input_file_header->endianness)) { printf("ERROR: io chunkSize\n"); }break; case 3: if (write_3_bytes(fp, &vector[curr_channel][k], input_file_header->endianness)) { printf("ERROR: io chunkSize\n"); }break; case 4: if (write_4_bytes(fp, &vector[curr_channel][k], input_file_header->endianness)) { printf("ERROR: io chunkSize\n"); } } } } for(curr_channel=0; curr_channel<input_file_header->numChannels; curr_channel++) { /*bprint(&output_buffer[curr_channel]);*/ if(output_vector[curr_channel]) free(output_vector[curr_channel]); if(data_vector[curr_channel]) free(data_vector[curr_channel]); bdestroy(&output_buffer[curr_channel]); bdestroy(&data_buffer[curr_channel]); if(frequencies && frequencies[curr_channel]) free(frequencies[curr_channel]); if(vector[curr_channel]) free(vector[curr_channel]); } free(size_vector); free(vector); if(nbits_run) free(nbits_run); if(nbits_code) free(nbits_code); if(firsts) free(firsts); if(max_bits) free(max_bits); if(frequencies) free(frequencies); free(data_buffer); free(data_vector); free(output_buffer); free(output_vector); free(input_file_header); }
struct process_parameter_results process_address(struct ast_node_address* param) { struct process_parameter_results result; struct register_mapping* registr; bstring btmp = NULL; result.v_raw = NULL; if (param->value != NULL) btmp = expr_representation(param->value); if (param->bracketed && param->added) { // This is of the form [0x1000+I]. registr = get_register_by_name_next(param->addcmpt); if (registr == NULL) { // Attempt to use a label in square brackets. Convert this // to an expression and then reinvoke ourselves with the // evaluated value. param->value = expr_new(expr_new_label(bautofree(bfromcstr(param->addcmpt))), EXPR_OP_ADD, param->value); param->addcmpt = ""; param->added = 0; param->bracketed = 0; bdestroy(btmp); return process_address(param); } else if (registr->value == VALUE_NEXT_UNSUPPORTED) { // Attempt to use a register in brackets that can't be. printd(LEVEL_VERBOSE, "\n"); dhalt(ERR_NEXTED_REGISTER_UNSUPPORTED, param->addcmpt); } printd(LEVEL_VERBOSE, "[%s+%s]", btmp->data, registr->name); result.v = registr->value; result.v_extra = param->value; result.v_extra_used = true; result.v_label = NULL; } else { // This is either the form 0x1000 or [0x1000]. if (param->bracketed) { printd(LEVEL_VERBOSE, "[%s]", btmp->data); result.v = NXT; } else { printd(LEVEL_VERBOSE, "%s", btmp->data); result.v = NXT_LIT; } result.v_extra = param->value; result.v_extra_used = true; result.v_label = NULL; } if (btmp != NULL) bdestroy(btmp); return result; }