int main(int argc, char* argv[]) { chash* table = chash_new(); char* text = read_entire_file(fopen(argv[1], "r")); char* token = strtok(text, " \t\n"); while (token) { char* cleaned_word = clean_word(token); if (cleaned_word != NULL) { see_word(table, cleaned_word); free(cleaned_word); } token = strtok(NULL, " \t\n"); } chash_iterator iter; chash_iterator_init(&iter, table); char *key; void *value; pair* pairs = malloc(chash_size(table) * sizeof(*pairs)); int i = 0; while (chash_iterator_next(&iter, &key, &value)) { pairs[i].key = key; pairs[i].value = value; i++; } qsort(pairs, chash_size(table), sizeof(pair), compare_by_frequency); printf("Words sorted by frequency:\n"); for (i = 0; i < chash_size(table); ++i) printf("%s: %d\n", pairs[i].key, *((int*)pairs[i].value)); chash_free(table); return 0; }
static MENU_UPDATE_FUNC(script_print) { if (!script_preview_flag || !entry->selected) { MENU_SET_NAME("Show script"); MENU_SET_VALUE(""); script_preview_flag = 0; return; } static int prev_script = -1; if (prev_script != script_selected) { int size; char* p = get_script_path(script_selected); char* f = (char*)read_entire_file(p, &size); if (f) { script_copy_window(script_preview, sizeof(script_preview), f, 0, 0, 20, 60); fio_free(f); } else { snprintf(script_preview, sizeof(script_preview), "Could not read '%s'", p); } } prev_script = script_selected; bmp_fill(40, 0, 0, 720, 430); int fnt = FONT(FONT_MED, COLOR_WHITE, 40); big_bmp_printf(fnt, 10, 10, "%s", script_preview); info->custom_drawing = CUSTOM_DRAW_THIS_MENU; }
int old(char* filename) { char * ffpath = full_path(filename,".md5"); char * tspath = full_path(COMPDIR,ffpath); free(ffpath); int ol = 1; if (file_exists(tspath) && file_exists(filename)) { FILE * f = fopen(tspath,"r"); char * inner = read_entire_file(f); fclose(f); inner[strlen(inner)-1]=0; struct stat file_stat; stat(filename,&file_stat); if(DEBUG){ fprintf(stderr,"%s:%d %s:%d\n",tspath,atoi(inner),filename,file_stat.st_mtime); fflush(stderr); } if(file_stat.st_mtime<=atoi(inner)) { ol = 0; } else { ol = 1; } free(inner); } free(tspath); return ol; }
static void unpack(const char* destination, const char* filename) { char* data = read_entire_file(filename); struct pak_header* header = (struct pak_header*)data; if (memcmp(header->signature, "PACK", 4)) { fatal("Invalid pak: %s\n", filename); } struct pak_directory* directories = (struct pak_directory*) &data[header->directory_offset]; uint32_t num_directories = header->directory_length / sizeof(struct pak_directory); for (uint32_t i = 0; i < num_directories; i++) { chdir(destination); struct pak_directory* directory = &directories[i]; printf("%s (%d bytes)\n", directory->file_name, directory->file_length); const char* file_name = create_dir_and_open(directory->file_name); FILE* output = fopen(file_name, "wb"); if (!output) fatal("Error opening [%s] %s for writing.\n", getcwd(0,0), file_name); // leakcwd fwrite(&data[directory->file_position], directory->file_length, 1, output); fclose(output); } free(data); }
std::unordered_set<std::string> get_manifest_classes(const std::string& filename) { std::string manifest = read_entire_file(filename); std::unordered_set<std::string> classes; if (manifest.size()) { classes = extract_classes_from_manifest(manifest); } else { fprintf(stderr, "Unable to read manifest file: %s\n", filename.data()); } return classes; }
std::unordered_set<std::string> get_layout_classes(const std::string& apk_directory) { std::vector<std::string> tmp = find_layout_files(apk_directory); std::unordered_set<std::string> all_classes; for (auto layout_file : tmp) { std::string contents = read_entire_file(layout_file); std::unordered_set<std::string> classes_from_layout = extract_classes_from_layout(contents); all_classes.insert(classes_from_layout.begin(), classes_from_layout.end()); } return all_classes; }
/** * Return all potential java class names located in native libraries. */ std::unordered_set<std::string> get_native_classes(const std::string& apk_directory) { std::vector<std::string> native_libs = find_native_library_files(apk_directory); std::unordered_set<std::string> all_classes; for (auto native_lib : native_libs) { std::string contents = read_entire_file(native_lib); std::unordered_set<std::string> classes_from_layout = extract_classes_from_native_lib(contents); all_classes.insert(classes_from_layout.begin(), classes_from_layout.end()); } return all_classes; }
int main(int argc, char const *argv[]) { FILE *f = fopen(argv[1], "r"); if (!f) { printf("Could not open file %s\n", argv[1]); exit(EXIT_FAILURE); } /* read entire file into memory */ char *contents = read_entire_file(f); fclose(f); /* solve all sudokus */ struct timeval before; gettimeofday (&before, NULL); int result_size = 1024; char *result = malloc(sizeof(char) * result_size); strcpy(result, ""); char *ptr = contents; int total_sudokus = strlen(contents) / (BOARD_SIZE*BOARD_SIZE); int sudokus_solved = 0; char solved[256]; do { int sudoku[BOARD_SIZE][BOARD_SIZE]; ptr = from_str(ptr, sudoku); solve(sudoku); to_str(sudoku, solved); result_size = append_str(&result, result_size, solved); load_bar(++sudokus_solved, total_sudokus, 100, 100); } while (*ptr); free(contents); struct timeval after; gettimeofday (&after, NULL); long duration = ((after.tv_sec * 1000000 + after.tv_usec) - (before.tv_sec * 1000000 + before.tv_usec)) / 1000; /* Write to file the solved sudokus */ char output_name[64]; sprintf(output_name, "solved_%s", argv[1]); FILE *output = fopen(output_name, "w"); if (!output) { printf("Could not open file %s\n", output_name); exit(EXIT_FAILURE); } fprintf(output, "%s", result); free(result); fclose(output); /* Present time result */ printf("-- Elapsed time: %d ms\n", duration); return 0; }
tabtoh::tabtoh(QString &in_file_str, QString &out_file_str, QString &mod_name_str){ qDebug()<<"(tabtoh) Input: "<<in_file_str; qDebug()<<"(tabtoh) Output: "<<out_file_str; qDebug()<<"(tabtoh) Model: "<<mod_name_str; input_file_str = in_file_str; output_file_str = out_file_str; model_name_str = mod_name_str; read_entire_file(input_file_str, input_file); }
int main( int argc, char** argv ) { FILE* infile = stdin; char* input = NULL; size_t inputlen = 0; int dec = 0; if ( argc < 2 ) { usage(); return 0; } if ( !strcmp( argv[1], "enc" ) ) dec = 0; else if ( !strcmp( argv[1], "dec" ) ) dec = 1; else { usage(); return 0; } if ( argc >= 3 ) { if ((infile = fopen(argv[2], "r")) == NULL) { warn("Cannot open input file: %s", argv[2]); exit(1); } } { size_t inputlen = 0; char* input = read_entire_file( infile, &inputlen ); { char* out = calloc( 1, 2*inputlen ); size_t len = 0; if ( dec ) len = b64_decode( input, inputlen, out ); else len = b64_encode( input, inputlen, out ); { size_t i = 0; for ( ; i < len; i++ ) fputc( out[ i ], stdout ); } free( out ); } } return 0; }
int config_parse_file(const char *filename) { char autosave_flag_file[0x80]; snprintf(autosave_flag_file, sizeof(autosave_flag_file), "%sAUTOSAVE.NEG", get_config_dir()); config_autosave = !config_flag_file_setting_load(autosave_flag_file); config_file_buf = (void*)read_entire_file(filename, &config_file_size); config_file_pos = 0; config_parse(); fio_free(config_file_buf); config_file_buf = 0; return 1; }
unsigned int module_config_load(char *filename, module_entry_t *module) { if (!module->config) return -1; config_file_buf = (void*)read_entire_file(filename, &config_file_size); if (!config_file_buf) return -1; config_file_pos = 0; module_config_parse(module); fio_free(config_file_buf); config_file_buf = 0; return 0; }
int main(int argc, char **argv) { const auto bf_program = read_entire_file("main.bf"); std::vector<std::string> asm_program; //holds each equiv instruction of the bf std::map<std::string,std::string> options = {{"data_reg","r16"}}; compile(bf_program,asm_program,options); for(auto const& instr: asm_program) { std::cout << instr; } return 0; }
/** * get_property * @brief Open a property file and read in its contents * * @param prop_path path to the property file * @param prop_name propery name * @param prop_val * @param prop_len * @return 0 on success, !0 otherwise */ static int get_property(const char *prop_path, const char *prop_name, char **prop_val, size_t * prop_len) { int fd; int rc; rc = open_prop_file(prop_path, prop_name, &fd); if (rc) return rc; rc = read_entire_file(fd, prop_val, prop_len); close(fd); return rc; }
void add_nginx_config(MultiWatch* watch, char* vhost) { char* filepath = malloc(9 + strlen(vhost) + 7 + 1); // 9:/var/www/ 7:/.nginx 1:\0 char *dirpath = malloc(9 + strlen(vhost) + 1); strcpy(dirpath, "/var/www/"); strcat(dirpath, vhost); strcpy(filepath, dirpath); strcat(filepath, "/.nginx"); printf("add vhost '%s', check for file '%s'\n", vhost, filepath); if (access(filepath, F_OK) == -1 && errno == ENOENT) { char* configFile = read_entire_file("/etc/nginx/.nginx.default"); char* last_vhost_pos = configFile; char* next_vhost_pos; FILE* outputFile = PCHECKED(fopen(filepath, "w")); while((next_vhost_pos = strstr(last_vhost_pos, "$VHOST")) != NULL) { fwrite(last_vhost_pos, sizeof(char), next_vhost_pos - last_vhost_pos, outputFile); fwrite(vhost, sizeof(char), strlen(vhost), outputFile); last_vhost_pos = next_vhost_pos + 6; } fwrite(last_vhost_pos, sizeof(char), strlen(last_vhost_pos), outputFile); struct stat dirstats; stat(dirpath, &dirstats); fchmod(fileno(outputFile), 0775); fchown(fileno(outputFile), dirstats.st_uid, dirstats.st_gid); fclose(outputFile); free(configFile); } multi_watch_add(watch, filepath, IN_CLOSE_WRITE, update_config); free(filepath); free(dirpath); }
/* ANT_DIRECTORY_ITERATOR_FILE::NEXT() ----------------------------------- */ ANT_directory_iterator_object *ANT_directory_iterator_file::next(ANT_directory_iterator_object *object) { char *document_id_start = NULL, *document_id_end = NULL; if (document_end == NULL) if (get_next_file() == NULL) return NULL; if ((document_start = strstr(document_end, "<DOC")) != NULL) { if (*(document_start + 4) == '>') { document_id_start = strstr(document_start, "<DOCNO>"); document_id_end = strstr(document_id_start += 7, "</DOCNO>"); } else { document_id_start = strstr(document_start, "id=\""); document_id_end = strchr(document_id_start += 4, '"'); if (document_id_end) document_start = strchr(document_id_end, '>') + 1; } if (document_id_end != NULL && (document_end = strstr(document_id_end, "</DOC>")) != NULL) { document_end += 6; object->filename = strnnew(document_id_start, document_id_end - document_id_start); if (get_file) read_entire_file(object); return object; } } if (get_next_file() == NULL) return NULL; else return next(object); }
/* ANT_DIRECTORY_ITERATOR_CSV::NEXT() ---------------------------------- */ ANT_directory_iterator_object *ANT_directory_iterator_csv::next(ANT_directory_iterator_object *object) { if (file == NULL) return NULL; document_start = document_end; while (ANT_isspace(*document_start)) document_start++; document_end = document_start; while (*document_end != '\n' && *document_end != '\0') document_end++; if (*document_start != '\0') { object->filename = strnnew(document_start, document_end - document_start); if (get_file) read_entire_file(object); return object; } return NULL; }
len_array read_json_file_array(char* filename) { std::string content = read_entire_file(filename); json_object * jobj = json_tokener_parse(content.c_str()); int speed_number = 0; int length = json_object_array_length(jobj); int* array = NULL; array = new int[length]; json_object * jvalue; for (int index = 0; index < length; index++){ jvalue = json_object_array_get_idx(jobj, index); /*Getting the array element at position index*/ array[index] = json_object_get_int(jvalue); } len_array result; result.array = array; result.len = length; return result; }
/** * Main function */ int main(int argc, char **argv) { /* The line read, the filename and the position in the file */ char *line = malloc(1024 * sizeof(char)); char *file_name = malloc(1024 * sizeof(char)); unsigned long long position; /* The search pattern */ char *pattern; int pattern_size; /* Read the pattern */ if(argc < 2) { printf("Usage: %s <pattern file>\n", argv[0]); return 1; } /* Read in the pattern */ pattern = read_entire_file(argv[1], &pattern_size); fgets(line, 1024, stdin); while(!feof(stdin)) { /* Read and parse */ parse_line(line, file_name, &position); verify_match(pattern, pattern_size, file_name, position); fgets(line, 1024, stdin); } parse_line(line, file_name, &position); /* Free up */ free(line); free(file_name); free(pattern); return 0; }
Map init_map(const char* file_path) { Map map = {}; char* realized_path = realize_path(file_path); size_t file_size = 0; char* map_data = read_entire_file(realized_path, &file_size); int tile_data_index = 0; for (int i = 0; i <= file_size; i++) { if (map_data[i] == '\0') { map.height += 1; break; } if (map_data[i] == '\r') { continue; } if (map_data[i] == '\n') { map.width = 0; map.height += 1; continue; } map.tile_data[tile_data_index].type = map_data[i] - '0'; map.tile_data[tile_data_index].x = map.width * TILE_SIZE; map.tile_data[tile_data_index].y = map.height * TILE_SIZE; map.width += 1; tile_data_index++; } free(map_data); return map; }
static int cse_handler(request_rec* r,const char** data){ if(!r->handler || strcmp(r->handler,"cse")) return DECLINED; char* command; if (r->method_number != M_GET) { return HTTP_METHOD_NOT_ALLOWED; } generate = old(r->filename); char* de = full_path(COMPDIR,r->filename); char* depname = full_path(de,".dep"); if(!file_exists(depname)) { generate = 1; } else { char* dee = read_entire_file(fopen(depname,"r")); dee[strlen(dee)-1]=0; int maxsz = 1; char * sub =(char*) malloc(maxsz);; int i; int len = strlen(dee); int pos = 0; for(i = 0; i < len; i++) { if(dee[i]!=',') { sub[pos++] = dee[i]; if(pos >= maxsz-1) { sub = (char*)realloc(sub,maxsz*2); maxsz*=2; } }else { sub[pos]=0; if(old(sub)) { generate = 1; } free(sub); pos = 0; maxsz=1; sub =malloc(maxsz); } } free(dee); } free(de); free(depname); if(!generate) { } if(generate) { if(r->args==NULL) { asprintf(&command,"csegen %s 2>&1",r->filename); }else { asprintf(&command,"csegen %s '\"%s\"' 2>&1",r->filename,r->args); } } else { char * t = full_path(COMPDIR,r->filename); int len = strlen(t)+ 2; t = (char *)realloc(t,len+1); t[len-2]=0; strcat(t,".e"); t[len]=0; if(r->args==NULL) { asprintf(&command,"%s 2>&1",t); }else { asprintf(&command,"%s \"%s\" 2>&1",t,r->args); } free(t); } ap_set_content_type(r , "text/html"); FILE *cmd = popen(command,"r"); char* str = read_entire_file(cmd); if(generate) ap_rputs("<!--GENERATED-->\n",r); ap_rputs(str,r); free(str); free(command); return OK; }
int main(int argn, char** args){ if(argn!=5){ print("use this format: ./Client name server_ip router_ip router_port\n"); return 0; } char* client_name = args[1]; char* client_ip=NULL; char* server_ip= args[2]; char* router_port= args[4]; char server_data [MAX_STR_SIZE]; clear_buff(server_data,MAX_STR_SIZE); int ip_input_tokens_num; char ip_input_tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE]; char ip_input_buffer[MAX_STR_SIZE]; clear_buff(ip_input_buffer, MAX_STR_SIZE); while( read(STDINFD, ip_input_buffer, MAX_STR_SIZE) > 0 ){ tokenizer(ip_input_buffer, " ", &ip_input_tokens_num, ip_input_tokens); if(mystrcmp(ip_input_tokens[0], "Set") == 0 && mystrcmp(ip_input_tokens[1], "IP") == 0 && ip_input_tokens_num == 3){ client_ip=ip_input_tokens[2]; replace_char(client_ip,'\n','\0'); break; }else{ print("You should set your IP first : Set IP 115.2.2.18\n"); } } int fd = connect_to_port(atoi(router_port)); char input_buffer[MAX_STR_SIZE]; clear_buff(input_buffer, MAX_STR_SIZE); while(read(STDINFD, input_buffer, MAX_STR_SIZE) > 0) { int input_tokens_num; char input_tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE]; replace_char(input_buffer,'\n','\0'); char iden_buff[MAX_STR_SIZE]; clear_buff(iden_buff, MAX_STR_SIZE); strcat(iden_buff, "00");//00 is for client //parsing input_buffer tokenizer(input_buffer," ", &input_tokens_num, input_tokens); char frame[MAX_STR_SIZE]; clear_buff(frame, MAX_STR_SIZE); char data[MAX_STR_SIZE]; clear_buff(data, MAX_STR_SIZE); //send command for server if( (mystrcmp(input_tokens[0], "DC") < 0) && (mystrcmp(input_tokens[0], "Logout") < 0) ) { if( strcmp(input_tokens[0],"Send")==0 && strcmp(input_tokens[1],"message")==0 && input_tokens_num==3){ strcat(data,"Sent message: "); strcat(data,input_tokens[2]); } else if(strcmp(input_tokens[0],"Send")==0 && strcmp(input_tokens[1],"file")==0 && input_tokens_num==3){ if(!file_exist(input_tokens[2])){ printf("file %s doesn't exist! You should create this file near ./Client 's directory\n", input_tokens[2]); continue; } char file_content[MAX_STR_SIZE]; clear_buff(file_content,MAX_STR_SIZE); read_entire_file(input_tokens[2],file_content); replace_char(file_content,'\n','^'); strcat(data,"Sent file "); strcat(data,input_tokens[2]); strcat(data," contain:\n"); strcat(data,file_content); } else strcat(data,input_buffer); framing(iden_buff,"0",client_ip,client_name,data,"cccc","cc",frame); printf("sent frame is: %s\n",frame ); int bytes_written = write(fd, frame, strlength(frame)); if(bytes_written < 0) write(STDOUTFD,"Error on writing\n", sizeof("Error on writing\n")); //get response from server char res_status[MAX_STR_SIZE]; clear_buff(res_status, MAX_STR_SIZE); int read_status = read(fd, res_status, MAX_STR_SIZE); //show the response to client printf("status of result of first reading ...\n"); write(STDOUTFD, res_status, strlength(res_status)); printf("\n"); char res_buff[MAX_STR_SIZE]; clear_buff(res_buff, MAX_STR_SIZE); read_status = read(fd, res_buff, MAX_STR_SIZE); process_client_command(res_buff,server_data ); printf("result is:\n%s\n",res_buff ); int input_tokens_num; char input_tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE]; tokenizer(res_buff, "&", &input_tokens_num, input_tokens); //show the response to client write(STDOUTFD, input_tokens[5], strlength(input_tokens[5])); printf("\n"); } else if(mystrcmp(input_tokens[0], "DC") == 0) { int bytes_written = write(fd, "DC", strlength("DC")); if(bytes_written < 0) write(STDOUTFD,"Error on writing\n", sizeof("Error on writing\n")); break; } else if(mystrcmp(input_tokens[0], "Logout") == 0) { int bytes_written = write(fd,"DC", strlength("DC")); if(bytes_written < 0) write(STDOUTFD,"Error on writing\n", sizeof("Error on writing\n")); close(fd); return 0; } } close(fd); return 0; }
static char* config_choose_startup_preset() { int size = 0; /* by default, work in ML/SETTINGS dir */ snprintf(config_dir, sizeof(config_dir), "ML/SETTINGS/"); /* check for a preset file selected in menu */ char* preset_name = (char*) read_entire_file(config_preset_file, &size); if (preset_name) { if (streq(preset_name, "Startup mode")) { /* will handle later */ config_preset_index = config_new_preset_index = 1; } else if (streq(preset_name, "Startup key")) { /* will handle later */ config_preset_index = config_new_preset_index = 2; } else { snprintf(config_selected_by_name, sizeof(config_selected_by_name), preset_name); char preset_dir[0x80]; snprintf(preset_dir, sizeof(preset_dir), "ML/SETTINGS/%s", preset_name); if (!is_dir(preset_dir)) { FIO_CreateDirectory(preset_dir); } if (is_dir(preset_dir)) { snprintf(config_dir, sizeof(config_dir), "%s/", preset_dir); } } fio_free(preset_name); } /* scan the preset files and populate the menu */ config_preset_scan(); /* special cases: key pressed at startup, or startup mode */ /* key pressed at startup */ if (config_preset_index == 2) { if (config_selected_by_key[0]) { char preset_dir[0x80]; snprintf(preset_dir, sizeof(preset_dir), "ML/SETTINGS/%s.KEY", config_selected_by_key); if (!is_dir(preset_dir)) { FIO_CreateDirectory(preset_dir); } if (is_dir(preset_dir)) { /* success */ snprintf(config_dir, sizeof(config_dir), "%s/", preset_dir); return config_selected_by_key; } } /* didn't work */ return 0; } else config_selected_by_key[0] = 0; /* startup shooting mode (if selected in menu) */ if (config_preset_index == 1) { snprintf(config_selected_by_mode, sizeof(config_selected_by_mode), "%s", get_shootmode_name(shooting_mode_custom)); char preset_dir[0x80]; snprintf(preset_dir, sizeof(preset_dir), "ML/SETTINGS/%s.MOD", config_selected_by_mode); if (!is_dir(preset_dir)) { FIO_CreateDirectory(preset_dir); } if (is_dir(preset_dir)) { /* success */ snprintf(config_dir, sizeof(config_dir), "%s/", preset_dir); return config_selected_by_mode; } /* didn't work */ return 0; } /* lookup the current preset in menu */ for (int i = 0; i < config_preset_num; i++) { if (streq(config_preset_choices[i], config_selected_by_name)) { config_preset_index = config_new_preset_index = i; return config_selected_by_name; } } /* using default config */ return 0; }
static int do_gbb_utility(int argc, char *argv[]) { enum do_what_now { DO_GET, DO_SET, DO_CREATE } mode = DO_GET; char *infile = NULL; char *outfile = NULL; char *opt_create = NULL; char *opt_rootkey = NULL; char *opt_bmpfv = NULL; char *opt_recoverykey = NULL; char *opt_hwid = NULL; char *opt_flags = NULL; int sel_hwid = 0; int sel_digest = 0; int sel_flags = 0; int sel_roothash = 0; uint8_t *inbuf = NULL; off_t filesize; uint8_t *outbuf = NULL; GoogleBinaryBlockHeader *gbb; uint8_t *gbb_base; int i; opterr = 0; /* quiet, you */ while ((i = getopt_long(argc, argv, short_opts, long_opts, 0)) != -1) { switch (i) { case 'g': mode = DO_GET; opt_has_arg("flags", 0); opt_has_arg("hwid", 0); break; case 's': mode = DO_SET; opt_has_arg("flags", 1); opt_has_arg("hwid", 1); break; case 'c': mode = DO_CREATE; opt_create = optarg; break; case 'o': outfile = optarg; break; case 'k': opt_rootkey = optarg; break; case 'b': opt_bmpfv = optarg; break; case 'r': opt_recoverykey = optarg; break; case OPT_HWID: /* --hwid is optional: null might be okay */ opt_hwid = optarg; sel_hwid = 1; break; case OPT_FLAGS: /* --flags is optional: null might be okay */ opt_flags = optarg; sel_flags = 1; break; case OPT_DIGEST: sel_digest = 1; break; case OPT_ROOTHASH: sel_roothash = 1; break; case OPT_HELP: print_help(argc, argv); return !!errorcnt; case '?': errorcnt++; if (optopt) fprintf(stderr, "ERROR: unrecognized option: -%c\n", optopt); else if (argv[optind - 1]) fprintf(stderr, "ERROR: unrecognized option " "(possibly \"%s\")\n", argv[optind - 1]); else fprintf(stderr, "ERROR: unrecognized option\n"); break; case ':': errorcnt++; if (argv[optind - 1]) fprintf(stderr, "ERROR: missing argument to -%c (%s)\n", optopt, argv[optind - 1]); else fprintf(stderr, "ERROR: missing argument to -%c\n", optopt); break; default: errorcnt++; fprintf(stderr, "ERROR: error while parsing options\n"); } } /* Problems? */ if (errorcnt) { print_help(argc, argv); return 1; } /* Now try to do something */ switch (mode) { case DO_GET: if (argc - optind < 1) { fprintf(stderr, "\nERROR: missing input filename\n"); print_help(argc, argv); return 1; } else { infile = argv[optind++]; } /* With no args, show the HWID */ if (!opt_rootkey && !opt_bmpfv && !opt_recoverykey && !sel_flags && !sel_digest) sel_hwid = 1; inbuf = read_entire_file(infile, &filesize); if (!inbuf) break; gbb = FindGbbHeader(inbuf, filesize); if (!gbb) { fprintf(stderr, "ERROR: No GBB found in %s\n", infile); break; } gbb_base = (uint8_t *) gbb; /* Get the stuff */ if (sel_hwid) printf("hardware_id: %s\n", gbb->hwid_size ? (char *)(gbb_base + gbb-> hwid_offset) : ""); if (sel_digest) print_hwid_digest(gbb, "digest: ", "\n"); if (sel_roothash) verify_ryu_root_header(inbuf, filesize, gbb); if (sel_flags) printf("flags: 0x%08x\n", gbb->flags); if (opt_rootkey) write_to_file(" - exported root_key to file:", opt_rootkey, gbb_base + gbb->rootkey_offset, gbb->rootkey_size); if (opt_bmpfv) write_to_file(" - exported bmp_fv to file:", opt_bmpfv, gbb_base + gbb->bmpfv_offset, gbb->bmpfv_size); if (opt_recoverykey) write_to_file(" - exported recovery_key to file:", opt_recoverykey, gbb_base + gbb->recovery_key_offset, gbb->recovery_key_size); break; case DO_SET: if (argc - optind < 1) { fprintf(stderr, "\nERROR: missing input filename\n"); print_help(argc, argv); return 1; } infile = argv[optind++]; if (!outfile) outfile = (argc - optind < 1) ? infile : argv[optind++]; if (sel_hwid && !opt_hwid) { fprintf(stderr, "\nERROR: missing new HWID value\n"); print_help(argc, argv); return 1; } if (sel_flags && (!opt_flags || !*opt_flags)) { fprintf(stderr, "\nERROR: missing new flags value\n"); print_help(argc, argv); return 1; } /* With no args, we'll either copy it unchanged or do nothing */ inbuf = read_entire_file(infile, &filesize); if (!inbuf) break; gbb = FindGbbHeader(inbuf, filesize); if (!gbb) { fprintf(stderr, "ERROR: No GBB found in %s\n", infile); break; } gbb_base = (uint8_t *) gbb; outbuf = (uint8_t *) malloc(filesize); if (!outbuf) { errorcnt++; fprintf(stderr, "ERROR: can't malloc %" PRIi64 " bytes: %s\n", filesize, strerror(errno)); break; } /* Switch pointers to outbuf */ memcpy(outbuf, inbuf, filesize); gbb = FindGbbHeader(outbuf, filesize); if (!gbb) { fprintf(stderr, "INTERNAL ERROR: No GBB found in outbuf\n"); exit(1); } gbb_base = (uint8_t *) gbb; if (opt_hwid) { if (strlen(opt_hwid) + 1 > gbb->hwid_size) { fprintf(stderr, "ERROR: null-terminated HWID" " exceeds capacity (%d)\n", gbb->hwid_size); errorcnt++; } else { /* Wipe data before writing new value. */ memset(gbb_base + gbb->hwid_offset, 0, gbb->hwid_size); strcpy((char *)(gbb_base + gbb->hwid_offset), opt_hwid); update_hwid_digest(gbb); } } if (opt_flags) { char *e = NULL; uint32_t val; val = (uint32_t) strtoul(opt_flags, &e, 0); if (e && *e) { fprintf(stderr, "ERROR: invalid flags value: %s\n", opt_flags); errorcnt++; } else { gbb->flags = val; } } if (opt_rootkey) { read_from_file("root_key", opt_rootkey, gbb_base + gbb->rootkey_offset, gbb->rootkey_size); if (fill_ryu_root_header(outbuf, filesize, gbb)) errorcnt++; } if (opt_bmpfv) read_from_file("bmp_fv", opt_bmpfv, gbb_base + gbb->bmpfv_offset, gbb->bmpfv_size); if (opt_recoverykey) read_from_file("recovery_key", opt_recoverykey, gbb_base + gbb->recovery_key_offset, gbb->recovery_key_size); /* Write it out if there are no problems. */ if (!errorcnt) write_to_file("successfully saved new image to:", outfile, outbuf, filesize); break; case DO_CREATE: if (!outfile) { if (argc - optind < 1) { fprintf(stderr, "\nERROR: missing output filename\n"); print_help(argc, argv); return 1; } outfile = argv[optind++]; } /* Parse the creation args */ outbuf = create_gbb(opt_create, &filesize); if (!outbuf) { fprintf(stderr, "\nERROR: unable to parse creation spec (%s)\n", opt_create); print_help(argc, argv); return 1; } if (!errorcnt) write_to_file("successfully created new GBB to:", outfile, outbuf, filesize); break; } if (inbuf) free(inbuf); if (outbuf) free(outbuf); return !!errorcnt; }
ip_bw* load_usage_from_file(char* in_file_path, unsigned long* num_ips, time_t* last_backup) { ip_bw* data = NULL; *num_ips = 0; *last_backup = 0; FILE* in_file = fopen(in_file_path, "r"); if(in_file != NULL) { unsigned long num_data_parts = 0; char* file_data = read_entire_file(in_file, 4086, &num_data_parts); fclose(in_file); char whitespace[] = {'\n', '\r', '\t', ' '}; char** data_parts = split_on_separators(file_data, whitespace, 4, -1, 0, &num_data_parts); free(file_data); *num_ips = (num_data_parts/2) + 1; data = (ip_bw*)malloc( (*num_ips) * sizeof(ip_bw) ); *num_ips = 0; unsigned long data_index = 0; unsigned long data_part_index = 0; while(data_part_index < num_data_parts) { ip_bw next; struct in_addr ipaddr; int valid = inet_aton(data_parts[data_part_index], &ipaddr); if(!valid) { sscanf(data_parts[data_part_index], "%ld", last_backup); //printf("last_backup = %ld\n", *last_backup); } data_part_index++; if(valid && data_index < num_data_parts) { next.ip = ipaddr.s_addr; valid = sscanf(data_parts[data_part_index], "%lld", (long long int*)&(next.bw) ); data_part_index++; } else { valid = 0; } if(valid) { //printf("next.bw = %lld\n", next.bw); //printf("next.ip = %d\n", next.ip); data[data_index] = next; data_index++; *num_ips = *num_ips + 1; } } /* cleanup by freeing data_parts */ for(data_part_index = 0; data_part_index < num_data_parts; data_part_index++) { free(data_parts[data_part_index]); } free(data_parts); } return data; }