ini_t read_ini(const std::string& filename) { ini_t ini; std::ifstream istr(filename.c_str()); if(!istr) return ini; std::vector<std::string> lines; std::string temp; while(true) { if(!std::getline(istr,temp)) { if(istr.eof()) break; else throw std::runtime_error("Error while reading \""+filename+"\"."); } else { lines.push_back(temp); } } istr.close(); for(size_t ii=0;ii<lines.size();++ii) { if(lines.size()>0&&lines[ii][0]=='#') continue; std::string key; for(size_t jj=0;jj<lines[ii].size();++jj) { if(lines[ii][jj]=='=') break; else key+=lines[ii][jj]; } std::string value; for(size_t jj=key.size()+1;jj<lines[ii].size();++jj) value+=lines[ii][jj]; key=to_lower(strip_whitespace(key)); value=to_lower(strip_whitespace(value)); if(value.size()>0) ini[key]=value; } return ini; }
// parse name value pairs based on INI file rules. // bool parse_name_value_pair(char* buf, std::string& name, std::string& value) { std::basic_string<char>::size_type i; std::string s; s = std::string(buf); i = s.find("=", 0); if ( i < s.npos ) { name = s.substr(0, i); value = s.substr(i + 1); strip_whitespace(name); strip_whitespace(value); return true; } return false; }
dav_error * dav_repos_patch_exec(const dav_resource *resource, const apr_xml_elem *elem, int operation, void *context, dav_liveprop_rollback **rollback_ctx) { dav_repos_resource *db_r = resource->info->db_r; const dav_liveprop_spec *spec = (const dav_liveprop_spec *)context; const char *data; apr_size_t size; apr_xml_to_text(db_r->p, elem, APR_XML_X2T_INNER, NULL, NULL, &data, &size); switch (spec->propid) { case DAV_PROPID_displayname: db_r->displayname = data; break; case DAV_PROPID_getcontentlanguage: db_r->getcontentlanguage = data; break; case DAV_PROPID_getcontenttype: db_r->getcontenttype = strip_whitespace((char*)data); break; } return NULL; }
bool read_config(FILE *file, bool is_active) { struct sway_config *temp_config = malloc(sizeof(struct sway_config)); config_defaults(temp_config); if (is_active) { sway_log(L_DEBUG, "Performing configuration file reload"); temp_config->reloading = true; temp_config->active = true; } bool success = true; int temp_depth = 0; // Temporary: skip all config sections with depth while (!feof(file)) { int _; char *line = read_line(file); line = strip_whitespace(line, &_); line = strip_comments(line); if (!line[0]) { goto _continue; } if (temp_depth && line[0] == '}') { temp_depth--; goto _continue; } // Any command which would require wlc to be initialized // should be queued for later execution list_t *args = split_string(line, " "); if (!is_active && ( strcmp("exec", args->items[0]) == 0 || strcmp("exec_always", args->items[0]) == 0 )) { sway_log(L_DEBUG, "Deferring command %s", line); char *cmd = malloc(strlen(line) + 1); strcpy(cmd, line); list_add(temp_config->cmd_queue, cmd); } else if (!temp_depth && !handle_command(temp_config, line)) { sway_log(L_DEBUG, "Config load failed for line %s", line); success = false; temp_config->failed = true; } list_free(args); _continue: if (line && line[strlen(line) - 1] == '{') { temp_depth++; } free(line); } if (is_active) { temp_config->reloading = false; container_map(&root_container, reset_gaps, NULL); arrange_windows(&root_container, -1, -1); } config = temp_config; return success; }
// copy everything up to (but not including) the given end tag. // The copied text may include XML tags. // strips whitespace. // int XML_PARSER::element_contents(const wxChar* end_tag, wxChar* buf, int buflen) { int n=0; int retval=0; while (1) { if (n == buflen-1) { retval = -112; break; } wxChar c = f->_getc(); if ((char)c == EOF) { retval = -112; break; } buf[n++] = c; buf[n] = 0; wxChar* p = _tcsstr(buf, end_tag); if (p) { *p = 0; break; } } buf[n] = 0; strip_whitespace(buf); return retval; }
Eina_Bool set_clip_content(char **content, char* text, int mode) { Eina_Bool ret = EINA_TRUE; char *temp, *trim; /* Sanity check */ if (!text) { WRN("ERROR: Text is NULL\n"); text = ""; } if (content) { switch (mode) { case 0: /* Don't trim */ temp = strdup(text); break; case 1: /* Trim new lines */ trim = strip_whitespace(text, TRIM_NEWLINES); temp = strdup(trim); break; case 2: /* Trim all white Space * since white space includes new lines * drop thru here */ case 3: /* Trim white space and new lines */ trim = strip_whitespace(text, TRIM_SPACES); temp = strdup(trim); break; default : /* Error Don't trim */ WRN("ERROR: Invalid strip_mode %d\n", mode); temp = strdup(text); break; } if (!temp) { /* This is bad, leave it to calling function */ CRI("ERROR: Memory allocation Failed!!"); ret = EINA_FALSE; } *content = temp; } else ERR("Error: Clip content pointer is Null!!"); return ret; }
void write_ini(const std::string& filename,const ini_t& ini) { std::ofstream ostr(filename.c_str()); if(!ostr) throw std::runtime_error("Could not open \""+filename+"\" for writing."); std::vector<std::string> lines; for(ini_t::const_iterator iter=ini.begin();iter!=ini.end();++iter) lines.push_back(strip_whitespace(iter->first)+"="+strip_whitespace(iter->second)); for(size_t ii=0;ii<lines.size();++ii) if(!(ostr<<lines[ii]<<std::endl)) throw std::runtime_error("Error while writing \""+filename+"\"."); ostr.close(); }
// remove trailing blanks and tabs from each line of input // delete entirely blank lines int main() { int len; // current line length char line[MAX_LINE]; // current input line while ((len = getlinelen(line, MAX_LINE)) > 0) { strip_whitespace(line, len); printf("%s\n", line); } return 0; }
void parse_sysctl_output(const std::vector<std::string>& lines, std::string& ostype, std::string& osrelease) { char buf[256], ostype_found[256], osrelease_found[256]; ostype = ""; osrelease = ""; for (size_t i = 0; i < lines.size(); ++i) { safe_strcpy(buf, lines[i].c_str()); strip_whitespace(buf); if (strstr(buf, "kernel.ostype =")) { safe_strcpy(ostype_found, strchr(buf, '=') + 1); ostype = ostype_found; strip_whitespace(ostype); continue; } if (strstr(buf, "kernel.osrelease =")) { safe_strcpy(osrelease_found, strchr(buf, '=') + 1); osrelease = osrelease_found; strip_whitespace(osrelease); } } }
float notenum_from_notetext(char *notetext){ int chroma, octave, sharp; char *stripped = strip_whitespace(notetext); char *notename; int comma_pos = string_charpos(stripped, ','); if (comma_pos != -1) notename = substring(stripped,0,comma_pos); else notename = stripped; printf("stripped: -%s-, notename: -%s-\n",stripped,notename); if(strlen(notename)==2){ chroma = get_chroma(notename[0]); sharp = 0; octave = get_octave(notename[1]); } else if(strlen(notename)==3){ chroma = get_chroma(notename[0]); sharp = get_sharp(notename[1]); octave = get_octave(notename[2]); } else return -1; if(chroma==-1 || sharp==-2 || octave==-1) return -1; float decimals = 0.0f; if (comma_pos != -1) { char *decimaltext = stripped + comma_pos + 1; #ifdef TEST_NOTES decimals = atof(decimaltext) / 100.0f; #else decimals = OS_get_double_from_string(decimaltext) / 100.0f; #endif printf("decimaltext: -%s-, dec: %f\n",decimaltext,decimals); } float notenum = octave*12 + chroma + sharp + decimals; if(notenum<=0 || notenum>127.99) return -1; else return notenum; }
/***********************************************************************//** * @brief Load effective area from performance table * * @param[in] filename Performance table file name. * * @exception GCTAExceptionHandler::file_open_error * File could not be opened for read access. * * This method loads the effective area information from an ASCII * performance table. ***************************************************************************/ void GCTAAeffPerfTable::load(const std::string& filename) { // Clear arrays m_logE.clear(); m_aeff.clear(); // Allocate line buffer const int n = 1000; char line[n]; // Open performance table readonly FILE* fptr = std::fopen(filename.c_str(), "r"); if (fptr == NULL) { throw GCTAException::file_open_error(G_LOAD, filename); } // Read lines while (std::fgets(line, n, fptr) != NULL) { // Split line in elements. Strip empty elements from vector. std::vector<std::string> elements = split(line, " "); for (int i = elements.size()-1; i >= 0; i--) { if (strip_whitespace(elements[i]).length() == 0) { elements.erase(elements.begin()+i); } } // Skip header if (elements[0].find("log(E)") != std::string::npos) { continue; } // Break loop if end of data table has been reached if (elements[0].find("----------") != std::string::npos) { break; } // Push elements in node array and vector m_logE.append(todouble(elements[0])); m_aeff.push_back(todouble(elements[1])*10000.0); } // endwhile: looped over lines // Close file std::fclose(fptr); // Store filename m_filename = filename; // Return return; }
// macro-substitute a result template: // - replace OUTFILE_x with base_filename_x, etc. // - add signatures for file uploads // - strip enclosing <output_template> tags // // This is called only from the transitioner, // to create a new result for a WU // int process_result_template( char* result_template, R_RSA_PRIVATE_KEY& key, char* base_filename, SCHED_CONFIG& config_loc ) { char* p,*q; char temp[BLOB_SIZE], buf[256]; int retval; while (1) { p = strstr(result_template, OUTFILE_MACRO); if (p) { q = p+strlen(OUTFILE_MACRO); char* endptr = strstr(q, "/>"); if (!endptr) return ERR_XML_PARSE; if (strchr(q, '>') != endptr+1) return ERR_XML_PARSE; *endptr = 0; strcpy(buf, q); strcpy(temp, endptr+2); strcpy(p, base_filename); strcat(p, buf); strcat(p, temp); continue; } p = strstr(result_template, UPLOAD_URL_MACRO); if (p) { strcpy(temp, p+strlen(UPLOAD_URL_MACRO)); strcpy(p, config_loc.upload_url); strcat(p, temp); continue; } break; } if (!config_loc.dont_generate_upload_certificates) { retval = add_signatures(result_template, key); if (retval) return retval; } // strip enclosing <output_template> tags, if any // p = strstr(result_template, "<output_template>"); if (p) { strcpy(temp, result_template+strlen("<output_template>")); q = strstr(temp, "</output_template>"); if (q) *q = 0; strcpy(result_template, temp); } strip_whitespace(result_template); return 0; }
int mk_cheetah_cmd(char *raw_cmd) { char *cmd = strip_whitespace(raw_cmd); if (strcmp(cmd, MK_CHEETAH_CONFIG) == 0 || strcmp(cmd, MK_CHEETAH_CONFIG_SC) == 0) { mk_cheetah_cmd_config(); } else if (strcmp(cmd, MK_CHEETAH_STATUS) == 0 || strcmp(cmd, MK_CHEETAH_STATUS_SC) == 0) { mk_cheetah_cmd_status(); } else if (strcmp(cmd, MK_CHEETAH_CLEAR) == 0 || strcmp(cmd, MK_CHEETAH_CLEAR_SC) == 0) { mk_cheetah_cmd_clear(); } else if (strcmp(cmd, MK_CHEETAH_UPTIME) == 0 || strcmp(cmd, MK_CHEETAH_UPTIME_SC) == 0) { mk_cheetah_cmd_uptime(); } else if (strcmp(cmd, MK_CHEETAH_PLUGINS) == 0 || strcmp(cmd, MK_CHEETAH_PLUGINS_SC) == 0) { mk_cheetah_cmd_plugins(); } else if (strcmp(cmd, MK_CHEETAH_WORKERS) == 0 || strcmp(cmd, MK_CHEETAH_WORKERS_SC) == 0) { mk_cheetah_cmd_workers(); } else if (strcmp(cmd, MK_CHEETAH_VHOSTS) == 0 || strcmp(cmd, MK_CHEETAH_VHOSTS_SC) == 0) { mk_cheetah_cmd_vhosts(); } else if (strcmp(cmd, MK_CHEETAH_HELP) == 0 || strcmp(cmd, MK_CHEETAH_HELP_SC) == 0 || strcmp(cmd, MK_CHEETAH_SHELP) == 0 || strcmp(cmd, MK_CHEETAH_SHELP_SC) == 0) { mk_cheetah_cmd_help(); } else if (strcmp(cmd, MK_CHEETAH_QUIT) == 0 || strcmp(cmd, MK_CHEETAH_QUIT_SC) == 0) { return mk_cheetah_cmd_quit(); } else if (strlen(cmd) == 0) { return 0; } else { CHEETAH_WRITE("Invalid command, type 'help' for a list of available commands\n"); } CHEETAH_FLUSH(); return 0; }
static dav_error * dav_repos_patch_validate(const dav_resource * resource, const apr_xml_elem * elem, int operation, void **context, int *defer_to_dead) { apr_pool_t *pool = resource->pool; dav_elem_private *priv = elem->priv; dav_repos_resource *db_r = resource->info->db_r; dav_repos_db *db = resource->info->db; char *path; const char *data; apr_size_t size; if (operation == DAV_PROP_OP_DELETE) return dav_new_error(pool, HTTP_CONFLICT, 0, "This property cannot be removed"); *context = (void *)get_livepropspec_from_id(dav_repos_props, priv->propid); switch(priv->propid) { case DAV_PROPID_displayname: if (elem->first_cdata.first && (elem->first_cdata.first->text == NULL || strlen(elem->first_cdata.first->text) > DAV_DISPLAYNAME_LIMIT)) return dav_new_error(pool, HTTP_CONFLICT, 0, "Invalid value specified"); break; case DAV_PROPID_getcontentlanguage: if (validate_language_tag(pool, elem->first_cdata.first->text)) return dav_new_error(pool, HTTP_CONFLICT, 0, "Invalid value specified"); break; case DAV_PROPID_getcontenttype: apr_xml_to_text(pool, elem, APR_XML_X2T_INNER, NULL, NULL, &data, &size); data = strip_whitespace((char*)data); sabridge_get_resource_file(db, db_r, &path); if (!is_content_type_good(path, data)) return dav_new_error(pool, HTTP_CONFLICT, 0, "Couldn't pass filter"); break; default: return dav_new_error(pool, HTTP_FORBIDDEN, 0, "Cannot be modified"); } return NULL; }
SvnLogEntry * svn_log_entry_new (gchar *author, gchar *date, glong revision, gchar *log) { SvnLogEntry *self; gchar *log_filtered; /* No leading whitespace */ gchar *first_newline; size_t first_newline_pos; gchar *first_log_line; gchar *short_log; self = g_object_new (SVN_TYPE_LOG_ENTRY, NULL); self->priv->author = g_strdup (author); self->priv->date = g_strdup (date); self->priv->revision = revision; self->priv->log = g_strdup (log); /* Now create the "short log", or a one-line summary of a log. * This is just the first line of a commit log message. If there is more * than one line to a message, take the first line and put an ellipsis * after it to create the short log. Otherwise, the short log is just a * copy of the log messge. */ log_filtered = strip_whitespace (log); first_newline = strchr (log_filtered, '\n'); if (first_newline) { first_newline_pos = first_newline - log_filtered; if (first_newline_pos < (strlen (log_filtered) - 1)) { first_log_line = g_strndup (log_filtered, first_newline_pos); short_log = g_strconcat (first_log_line, " ...", NULL); g_free (first_log_line); } else /* There could be a newline and nothing after it... */ short_log = g_strndup (log_filtered, first_newline_pos); } else short_log = g_strdup (log_filtered); self->priv->short_log = g_strdup (short_log); g_free (short_log); return self; }
bool config_read(FILE *file) { int line_number = 0; char *line; while (!feof(file)) { line = read_line(file); line_number++; line = strip_whitespace(line); if (line[0] == '#' || strlen(line) < 1) { free(line); continue; } cmd_eval(NULL, line); free(line); } cmd_flush(); return 1; }
char * _sanitize_ln(char *text, const unsigned int n, const int mode) { EINA_SAFETY_ON_NULL_RETURN_VAL(text, NULL); char *ret = calloc(n + 1, sizeof(char)); char *temp = ret; unsigned int chr, k, i = 0; if (!ret) return NULL; if (mode) text = strip_whitespace(text, TRIM_SPACES); while (1) { chr = *text; if (chr == 0) break; if ((chr < 32)) { /* is it a tab */ if (chr == 9){ // default tab for (k=0; k<4; k++, i++){ if (i == n) break; *temp++ = ' '; } text++; } else { text++; } } else { /* assume char is ok and add to temp buffer */ *temp++ = *text++; i++; } if (i == n) break; } *temp = 0; return ret; }
static int colcheck(const char *check, const char *in) { while (1) { switch (check[0]) { case '\n': case '\r': case '\t': case ' ': in = strip_whitespace(in); ++check; break; case '\0': return 1; default: if (check[0] != in[0] || in[0] == '\0') return 0; ++check; ++in; } } return 0; }
// Scan something, either tag or text. // Strip whitespace at start and end. // Return true iff reached EOF // int XML_PARSER::get_aux(wxChar* buf, int len, wxChar* attr_buf, int attr_len) { bool eof; wxChar c, retval; while (1) { eof = scan_nonws(c); if (eof) return XML_PARSE_EOF; if (c == wxT('<')) { retval = scan_tag(buf, len, attr_buf, attr_len); if (retval == XML_PARSE_EOF) return retval; if (retval == XML_PARSE_COMMENT) continue; } else { buf[0] = c; eof = copy_until_tag(buf+1, len-1); if (eof) return XML_PARSE_EOF; retval = XML_PARSE_DATA; } strip_whitespace(buf); return retval; } return false; }
struct sway_config *read_config(FILE *file) { struct sway_config *config = malloc(sizeof(struct sway_config)); config_defaults(config); bool success = true; int temp_depth = 0; // Temporary: skip all config sections with depth while (!feof(file)) { int _; char *line = read_line(file); line = strip_whitespace(line, &_); line = strip_comments(line); if (!line[0]) { goto _continue; } if (temp_depth && line[0] == '}') { temp_depth--; goto _continue; } if (!temp_depth && handle_command(config, line) != 0) { success = false; } _continue: if (line && line[strlen(line) - 1] == '{') { temp_depth++; } free(line); } if (!success) { exit(1); } return config; }
//----------------------------------------------------------------- void IniFile::load(const std::string filename) { _sections.clear(); if (filename.empty()) { return; } FILE* file = fopen(filename.c_str(), "rb"); if (!file) { return; } static ArrayPtr<char> s_Buffer; static int s_BufferSize = 0; if (s_BufferSize == 0) { // one-time initialization try { s_Buffer.reset(new char[1024]); s_BufferSize = 1024; } catch (const std::bad_alloc&) { return; } } int num_keys_read = 0; std::string section; std::string key; std::string value; char* ptr; int avail; int state = 'A'; int input; int chr; fetch: // fill buffer with data from the stream int num_fetched = fread(s_Buffer.get(), 1, s_BufferSize, file); if (num_fetched == 0) { goto finish; } else { avail = num_fetched; ptr = s_Buffer.get(); } parse: // parse the data in the buffer chr = *ptr; if (chr == '\n' || chr == '\r') { input = 'n'; } else if (chr == '[') { input = 'l'; } else if (chr == ']') { input = 'r'; } else if (chr == '=') { input = 'z'; } else if (chr == ' ') { input = 's'; } else if (chr > 31 && chr < 127) { input = 'g'; } else { input = 'u'; } switch (state) { case 'A': switch (input) { case 'n': case 's': break; case 'l': state = 'B'; break; case 'r': case 'z': case 'g': case 'u': state = 'C'; break; } break; case 'B': switch (input) { case 'n': state = 'A'; break; case 'g': state = 'D'; section = chr; break; case 's': break; case 'l': case 'r': case 'z': case 'u': state = 'C'; break; } break; case 'C': switch (input) { case 'n': state = 'A'; break; case 'l': case 'r': case 'z': case 's': case 'g': case 'u': break; } break; case 'D': switch (input) { case 'n': state = 'A'; break; case 's': case 'g': section += chr; break; case 'r': state = 'E'; break; case 'l': case 'z': case 'u': state = 'C'; break; } break; case 'E': switch (input) { case 'n': state = 'F'; break; case 'l': case 'r': case 'z': case 's': case 'g': case 'u': break; } break; case 'F': switch (input) { case 'n': case 's': break; case 'g': state = 'G'; key = chr; break; case 'l': state = 'B'; break; case 'r': case 'z': case 'u': state = 'H'; break; } break; case 'G': switch (input) { case 'n': state = 'F'; break; case 's': case 'g': key += chr; break; case 'z': state = 'I'; break; case 'l': case 'r': case 'u': state = 'H'; break; } break; case 'H': switch (input) { case 'n': state = 'F'; break; case 'l': case 'r': case 'z': case 's': case 'g': case 'u': break; } break; case 'I': switch (input) { case 'n': state = 'F'; break; case 's': break; case 'l': case 'r': case 'g': state = 'J'; value = chr; break; case 'z': case 'u': state = 'H'; break; } break; case 'J': switch (input) { case 'n': state = 'F'; _sections[strip_whitespace(section)]._keys[strip_whitespace(key)] = strip_whitespace(value); num_keys_read++; break; case 'l': case 'r': case 's': case 'g': value += chr; break; case 'z': case 'u': state = 'H'; _sections[strip_whitespace(section)]._keys[strip_whitespace(key)] = strip_whitespace(value); num_keys_read++; break; } break; } --avail; ++ptr; if (avail > 0) { goto parse; } else { goto fetch; } finish: if (state == 'J') { // we still have a valid key-value pair _sections[strip_whitespace(section)]._keys[strip_whitespace(key)] = strip_whitespace(value); num_keys_read++; } return; }
// parse project fields from client_state.xml // int PROJECT::parse_state(XML_PARSER& xp) { char buf[256]; std::string sched_url, stemp; string str1, str2; int retval, rt; double x; bool btemp; init(); while (!xp.get_tag()) { if (xp.match_tag("/project")) { if (cpid_time == 0) { cpid_time = user_create_time; } if (dont_use_dcf) { duration_correction_factor = 1; } return 0; } if (xp.parse_string("scheduler_url", sched_url)) { scheduler_urls.push_back(sched_url); continue; } if (xp.parse_str("master_url", master_url, sizeof(master_url))) continue; if (xp.parse_str("project_name", project_name, sizeof(project_name))) continue; if (xp.parse_str("symstore", symstore, sizeof(symstore))) continue; if (xp.parse_str("user_name", user_name, sizeof(user_name))) continue; if (xp.parse_str("team_name", team_name, sizeof(team_name))) continue; if (xp.parse_str("host_venue", host_venue, sizeof(host_venue))) continue; if (xp.parse_str("email_hash", email_hash, sizeof(email_hash))) continue; if (xp.parse_str("cross_project_id", cross_project_id, sizeof(cross_project_id))) continue; if (xp.parse_str("external_cpid", external_cpid, sizeof(external_cpid))) continue; if (xp.parse_double("cpid_time", cpid_time)) continue; if (xp.parse_double("user_total_credit", user_total_credit)) continue; if (xp.parse_double("user_expavg_credit", user_expavg_credit)) continue; if (xp.parse_double("user_create_time", user_create_time)) continue; if (xp.parse_int("rpc_seqno", rpc_seqno)) continue; if (xp.parse_int("userid", userid)) continue; if (xp.parse_int("teamid", teamid)) continue; if (xp.parse_int("hostid", hostid)) continue; if (xp.parse_double("host_total_credit", host_total_credit)) continue; if (xp.parse_double("host_expavg_credit", host_expavg_credit)) continue; if (xp.parse_double("host_create_time", host_create_time)) continue; if (xp.match_tag("code_sign_key")) { retval = copy_element_contents( xp.f->f, "</code_sign_key>", code_sign_key, sizeof(code_sign_key) ); if (retval) return retval; strip_whitespace(code_sign_key); continue; } if (xp.parse_int("nrpc_failures", nrpc_failures)) continue; if (xp.parse_int("master_fetch_failures", master_fetch_failures)) continue; if (xp.parse_double("min_rpc_time", x)) continue; if (xp.parse_bool("master_url_fetch_pending", master_url_fetch_pending)) continue; if (xp.parse_int("sched_rpc_pending", sched_rpc_pending)) continue; if (xp.parse_double("next_rpc_time", next_rpc_time)) continue; if (xp.parse_bool("trickle_up_pending", trickle_up_pending)) continue; if (xp.parse_int("send_time_stats_log", send_time_stats_log)) continue; if (xp.parse_int("send_job_log", send_job_log)) continue; if (xp.parse_bool("send_full_workload", send_full_workload)) continue; if (xp.parse_bool("dont_use_dcf", dont_use_dcf)) continue; if (xp.parse_bool("non_cpu_intensive", non_cpu_intensive)) continue; if (xp.parse_bool("verify_files_on_app_start", verify_files_on_app_start)) continue; if (xp.parse_bool("suspended_via_gui", suspended_via_gui)) continue; if (xp.parse_bool("dont_request_more_work", dont_request_more_work)) continue; if (xp.parse_bool("detach_when_done", detach_when_done)) continue; if (xp.parse_bool("ended", ended)) continue; if (xp.parse_double("rec", pwf.rec)) continue; if (xp.parse_double("rec_time", pwf.rec_time)) continue; if (xp.parse_double("cpu_backoff_interval", rsc_pwf[0].backoff_interval)) continue; if (xp.parse_double("cpu_backoff_time", rsc_pwf[0].backoff_time)) { if (rsc_pwf[0].backoff_time > gstate.now + 28*SECONDS_PER_DAY) { rsc_pwf[0].backoff_time = gstate.now + 28*SECONDS_PER_DAY; } continue; } if (xp.match_tag("rsc_backoff_interval")) { if (parse_rsc_param(xp, "/rsc_backoff_interval", rt, x)) { rsc_pwf[rt].backoff_interval = x; } continue; } if (xp.match_tag("rsc_backoff_time")) { if (parse_rsc_param(xp, "/rsc_backoff_time", rt, x)) { rsc_pwf[rt].backoff_time = x; } continue; } if (xp.parse_double("resource_share", resource_share)) continue; // not authoritative if (xp.parse_double("duration_correction_factor", duration_correction_factor)) continue; if (xp.parse_bool("attached_via_acct_mgr", attached_via_acct_mgr)) continue; if (xp.parse_bool("no_cpu_apps", btemp)) { if (btemp) handle_no_rsc_apps(this, "CPU"); continue; } // deprecated if (xp.parse_bool("no_cuda_apps", btemp)) { if (btemp) handle_no_rsc_apps(this, GPU_TYPE_NVIDIA); continue; } if (xp.parse_bool("no_ati_apps", btemp)) { if (btemp) handle_no_rsc_apps(this, GPU_TYPE_ATI); continue; } if (xp.parse_str("no_rsc_apps", buf, sizeof(buf))) { handle_no_rsc_apps(this, buf); continue; } if (xp.parse_bool("no_cpu_ams", btemp)) { if (btemp) handle_no_rsc_ams(this, "CPU"); continue; } if (xp.parse_bool("no_cuda_ams", btemp)) { if (btemp) handle_no_rsc_ams(this, GPU_TYPE_NVIDIA); continue; } if (xp.parse_bool("no_ati_ams", btemp)) { if (btemp) handle_no_rsc_ams(this, GPU_TYPE_ATI); continue; } if (xp.parse_bool("no_intel_gpu_ams", btemp)) { if (btemp) handle_no_rsc_ams(this, GPU_TYPE_INTEL); continue; } if (xp.parse_str("no_rsc_ams", buf, sizeof(buf))) { handle_no_rsc_ams(this, buf); continue; } if (xp.parse_str("no_rsc_pref", buf, sizeof(buf))) { handle_no_rsc_pref(this, buf); continue; } // backwards compat - old state files had ams_resource_share = 0 if (xp.parse_double("ams_resource_share_new", ams_resource_share)) continue; if (xp.parse_double("ams_resource_share", x)) { if (x > 0) ams_resource_share = x; continue; } if (xp.parse_bool("scheduler_rpc_in_progress", btemp)) continue; if (xp.parse_bool("use_symlinks", use_symlinks)) continue; if (xp.parse_bool("anonymous_platform", btemp)) continue; if (xp.parse_string("trickle_up_url", stemp)) { trickle_up_ops.push_back(new TRICKLE_UP_OP(stemp)); continue; } if (xp.parse_double("desired_disk_usage", desired_disk_usage)) continue; if (xp.parse_int("njobs_success", njobs_success)) continue; if (xp.parse_int("njobs_error", njobs_error)) continue; if (xp.parse_double("elapsed_time", elapsed_time)) continue; if (xp.parse_double("last_rpc_time", last_rpc_time)) continue; #ifdef SIM if (xp.match_tag("available")) { available.parse(xp, "/available"); continue; } #endif if (log_flags.unparsed_xml) { msg_printf(0, MSG_INFO, "[unparsed_xml] PROJECT::parse_state(): unrecognized: %s", xp.parsed_tag ); } xp.skip_unexpected(); } return ERR_XML_PARSE; }
int main(int argc, char** argv) { #ifndef _USING_FCGI_ FILE* fin, *fout; #else FCGI_FILE *fin, *fout; #endif int i, retval; char req_path[MAXPATHLEN], reply_path[MAXPATHLEN]; char log_path[MAXPATHLEN], path[MAXPATHLEN]; unsigned int counter=0; char* code_sign_key; int length = -1; log_messages.pid = getpid(); bool debug_log = false; for (i=1; i<argc; i++) { if (!strcmp(argv[i], "--batch")) { batch = true; continue; } else if (!strcmp(argv[i], "--mark_jobs_done")) { mark_jobs_done = true; } else if (!strcmp(argv[i], "--debug_log")) { debug_log = true; #ifdef GCL_SIMULATOR } else if (!strcmp(argv[i], "--simulator")) { if(!argv[++i]) { log_messages.printf(MSG_CRITICAL, "%s requires an argument\n\n", argv[--i]); usage(argv[0]); exit(1); } simtime = atof(argv[i]); #endif } else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { usage(argv[0]); exit(0); } else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) { printf("%s\n", SVN_VERSION); exit(0); } else if (strlen(argv[i])){ log_messages.printf(MSG_CRITICAL, "unknown command line argument: %s\n\n", argv[i]); usage(argv[0]); exit(1); } } // install a signal handler that catches SIGTERMS sent by Apache if the CGI // times out. // signal(SIGTERM, sigterm_handler); if (debug_log) { if (!freopen("debug_log", "w", stderr)) { fprintf(stderr, "Can't redirect stderr\n"); exit(1); } } else { char *stderr_buffer; get_log_path(path, "scheduler.log"); #ifndef _USING_FCGI_ char buf[256]; if (!freopen(path, "a", stderr)) { fprintf(stderr, "Can't redirect stderr\n"); sprintf(buf, "Server can't open log file (%s)", path); send_message(buf, 3600); exit(1); } #else FCGI_FILE* f = FCGI::fopen(path, "a"); if (f) { log_messages.redirect(f); } else { char buf[256]; fprintf(stderr, "Can't redirect FCGI log messages\n"); sprintf(buf, "Server can't open log file for FCGI (%s)", path); send_message(buf, 3600); exit(1); } #endif // install a larger buffer for stderr. This ensures that // log information from different scheduler requests running // in parallel aren't intermingled in the log file. // if (config.scheduler_log_buffer) { stderr_buffer = (char*)malloc(config.scheduler_log_buffer); if (!stderr_buffer) { log_messages.printf(MSG_CRITICAL, "Unable to allocate stderr buffer\n" ); } else { #ifdef _USING_FCGI_ retval = setvbuf( f->stdio_stream, stderr_buffer, _IOFBF, config.scheduler_log_buffer ); #else retval = setvbuf( stderr, stderr_buffer, _IOFBF, config.scheduler_log_buffer ); #endif if (retval) { log_messages.printf(MSG_CRITICAL, "Unable to change stderr buffering\n" ); } } } } srand(time(0)+getpid()); log_messages.set_debug_level(DEBUG_LEVEL); #if DUMP_CORE_ON_SEGV set_core_dump_size_limit(); #endif retval = config.parse_file(); if (retval) { log_messages.printf(MSG_CRITICAL, "Can't parse config.xml: %s\n", boincerror(retval) ); send_message("Server can't parse configuration file", 3600); exit(0); } log_messages.set_debug_level(config.sched_debug_level); if (config.sched_debug_level == 4) g_print_queries = true; gui_urls.init(); project_files.init(); init_file_delete_regex(); sprintf(path, "%s/code_sign_public", config.key_dir); retval = read_file_malloc(path, code_sign_key); if (retval) { log_messages.printf(MSG_CRITICAL, "Can't read code sign key file (%s)\n", path ); send_message("Server can't find key file", 3600); exit(0); } strip_whitespace(code_sign_key); g_pid = getpid(); #ifdef _USING_FCGI_ //while(FCGI_Accept() >= 0 && counter < MAX_FCGI_COUNT) { while(FCGI_Accept() >= 0) { counter++; log_messages.set_indent_level(0); #endif if (config.debug_request_headers) { log_request_headers(length); } if (!debug_log && check_stop_sched()) { send_message("Project is temporarily shut down for maintenance", 3600); goto done; } if (!ssp) { attach_to_feeder_shmem(); } if (!ssp) { send_message("Server error: can't attach shared memory", 3600); goto done; } if (strlen(config.debug_req_reply_dir)) { struct stat statbuf; // the code below is convoluted because, // instead of going from stdin to stdout directly, // we go via a pair of disk files // (this makes it easy to save the input, // and to know the length of the output). // NOTE: to use this, you must create group-writeable dirs // boinc_req and boinc_reply in the project dir // sprintf(req_path, "%s/%d_%u_sched_request.xml", config.debug_req_reply_dir, g_pid, counter); sprintf(reply_path, "%s/%d_%u_sched_reply.xml", config.debug_req_reply_dir, g_pid, counter); // keep an own 'log' per PID in case general logging fails // this allows to associate at leas the scheduler request with the client // IP address (as shown in httpd error log) in case of a crash sprintf(log_path, "%s/%d_%u_sched.log", config.debug_req_reply_dir, g_pid, counter); #ifndef _USING_FCGI_ fout = fopen(log_path, "a"); #else fout = FCGI::fopen(log_path,"a"); #endif fprintf(fout, "PID: %d Client IP: %s\n", g_pid, get_remote_addr()); fclose(fout); log_messages.printf(MSG_DEBUG, "keeping sched_request in %s, sched_reply in %s, custom log in %s\n", req_path, reply_path, log_path ); #ifndef _USING_FCGI_ fout = fopen(req_path, "w"); #else fout = FCGI::fopen(req_path,"w"); #endif if (!fout) { log_messages.printf(MSG_CRITICAL, "can't write request file\n" ); exit(1); } copy_stream(stdin, fout); fclose(fout); stat(req_path, &statbuf); if (length>=0 && (statbuf.st_size != length)) { log_messages.printf(MSG_CRITICAL, "Request length %d != CONTENT_LENGTH %d\n", (int)statbuf.st_size, length ); } #ifndef _USING_FCGI_ fin = fopen(req_path, "r"); #else fin = FCGI::fopen(req_path,"r"); #endif if (!fin) { log_messages.printf(MSG_CRITICAL, "can't read request file\n" ); exit(1); } #ifndef _USING_FCGI_ fout = fopen(reply_path, "w"); #else fout = FCGI::fopen(reply_path, "w"); #endif if (!fout) { log_messages.printf(MSG_CRITICAL, "can't write reply file\n" ); exit(1); } handle_request(fin, fout, code_sign_key); fclose(fin); fclose(fout); #ifndef _USING_FCGI_ fin = fopen(reply_path, "r"); #else fin = FCGI::fopen(reply_path, "r"); #endif if (!fin) { log_messages.printf(MSG_CRITICAL, "can't read reply file\n" ); exit(1); } copy_stream(fin, stdout); fclose(fin); // if not contacted from a client, don't keep the log files /* not sure what lead to the assumption of a client setting CONTENT_LENGTH, but it's wrong at least on our current project / Apache / Client configuration. Commented out. if (getenv("CONTENT_LENGTH")) { unlink(req_path); unlink(reply_path); } */ #ifndef _USING_FCGI_ } else if (batch) { while (!feof(stdin)) { handle_request(stdin, stdout, code_sign_key); fflush(stdout); } #endif } else { handle_request(stdin, stdout, code_sign_key); fflush(stderr); } done: #ifdef _USING_FCGI_ if (config.debug_fcgi) { log_messages.printf(MSG_NORMAL, "FCGI: counter: %d\n", counter ); log_messages.flush(); } } // do() if (counter == MAX_FCGI_COUNT) { fprintf(stderr, "FCGI: counter passed MAX_FCGI_COUNT - exiting..\n"); } else { fprintf(stderr, "FCGI: FCGI_Accept failed - exiting..\n"); } // when exiting, write headers back to apache so it won't complain // about "incomplete headers" fprintf(stdout,"Content-type: text/plain\n\n"); #endif if (db_opened) { boinc_db.close(); } }
bool read_config(FILE *file, struct sway_config *config) { bool success = true; enum cmd_status block = CMD_BLOCK_END; int line_number = 0; char *line; while (!feof(file)) { line = read_line(file); if (!line) { continue; } line_number++; line = strip_whitespace(line); if (line[0] == '#') { free(line); continue; } struct cmd_results *res; if (block == CMD_BLOCK_COMMANDS) { // Special case res = config_commands_command(line); } else { res = config_command(line, block); } switch(res->status) { case CMD_FAILURE: case CMD_INVALID: sway_log(L_ERROR, "Error on line %i '%s': %s (%s)", line_number, line, res->error, config->current_config); success = false; break; case CMD_DEFER: sway_log(L_DEBUG, "Defferring command `%s'", line); list_add(config->cmd_queue, strdup(line)); break; case CMD_BLOCK_MODE: if (block == CMD_BLOCK_END) { block = CMD_BLOCK_MODE; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_INPUT: if (block == CMD_BLOCK_END) { block = CMD_BLOCK_INPUT; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_BAR: if (block == CMD_BLOCK_END) { block = CMD_BLOCK_BAR; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_BAR_COLORS: if (block == CMD_BLOCK_BAR) { block = CMD_BLOCK_BAR_COLORS; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_COMMANDS: if (block == CMD_BLOCK_END) { block = CMD_BLOCK_COMMANDS; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_IPC: if (block == CMD_BLOCK_END) { block = CMD_BLOCK_IPC; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_IPC_EVENTS: if (block == CMD_BLOCK_IPC) { block = CMD_BLOCK_IPC_EVENTS; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_END: switch(block) { case CMD_BLOCK_MODE: sway_log(L_DEBUG, "End of mode block"); config->current_mode = config->modes->items[0]; block = CMD_BLOCK_END; break; case CMD_BLOCK_INPUT: sway_log(L_DEBUG, "End of input block"); current_input_config = NULL; block = CMD_BLOCK_END; break; case CMD_BLOCK_BAR: sway_log(L_DEBUG, "End of bar block"); config->current_bar = NULL; block = CMD_BLOCK_END; break; case CMD_BLOCK_BAR_COLORS: sway_log(L_DEBUG, "End of bar colors block"); block = CMD_BLOCK_BAR; break; case CMD_BLOCK_COMMANDS: sway_log(L_DEBUG, "End of commands block"); block = CMD_BLOCK_END; break; case CMD_BLOCK_IPC: sway_log(L_DEBUG, "End of IPC block"); block = CMD_BLOCK_END; break; case CMD_BLOCK_IPC_EVENTS: sway_log(L_DEBUG, "End of IPC events block"); block = CMD_BLOCK_IPC; break; case CMD_BLOCK_END: sway_log(L_ERROR, "Unmatched }"); break; default:; } default:; } free(line); free_cmd_results(res); } return success; }
bool read_config(FILE *file, bool is_active) { struct sway_config *old_config = config; config = calloc(1, sizeof(struct sway_config)); config_defaults(config); config->reading = true; if (is_active) { sway_log(L_DEBUG, "Performing configuration file reload"); config->reloading = true; config->active = true; } bool success = true; enum cmd_status block = CMD_BLOCK_END; int line_number = 0; char *line; while (!feof(file)) { line = read_line(file); line_number++; line = strip_whitespace(line); if (line[0] == '#') { continue; } struct cmd_results *res = config_command(line, block); switch(res->status) { case CMD_FAILURE: case CMD_INVALID: sway_log(L_ERROR, "Error on line %i '%s': %s", line_number, line, res->error); success = false; break; case CMD_DEFER: sway_log(L_DEBUG, "Defferring command `%s'", line); list_add(config->cmd_queue, strdup(line)); break; case CMD_BLOCK_MODE: if (block == CMD_BLOCK_END) { block = CMD_BLOCK_MODE; } else { sway_log(L_ERROR, "Invalid block '%s'", line); } break; case CMD_BLOCK_END: switch(block) { case CMD_BLOCK_MODE: sway_log(L_DEBUG, "End of mode block"); config->current_mode = config->modes->items[0]; break; case CMD_BLOCK_END: sway_log(L_ERROR, "Unmatched }"); break; default:; } default:; } free(line); free(res); } if (is_active) { config->reloading = false; arrange_windows(&root_container, -1, -1); } if (old_config) { free_config(old_config); } config->reading = false; return success; }
// return an error message or NULL // const char* SCHEDULER_REQUEST::parse(FILE* fin) { char buf[256]; RESULT result; int retval; strcpy(authenticator, ""); strcpy(platform.name, ""); strcpy(cross_project_id, ""); hostid = 0; core_client_major_version = 0; core_client_minor_version = 0; core_client_release = 0; rpc_seqno = 0; work_req_seconds = 0; cpu_req_secs = 0; cpu_req_instances = 0; resource_share_fraction = 1.0; rrs_fraction = 1.0; prrs_fraction = 1.0; cpu_estimated_delay = 0; strcpy(global_prefs_xml, ""); strcpy(working_global_prefs_xml, ""); strcpy(code_sign_key, ""); memset(&global_prefs, 0, sizeof(global_prefs)); memset(&host, 0, sizeof(host)); have_other_results_list = false; have_ip_results_list = false; have_time_stats_log = false; client_cap_plan_class = false; sandbox = -1; coproc_cuda = 0; coproc_ati = 0; fgets(buf, sizeof(buf), fin); if (!match_tag(buf, "<scheduler_request>")) return "no start tag"; while (fgets(buf, sizeof(buf), fin)) { // If a line is too long, ignore it. // This can happen e.g. if the client has bad global_prefs.xml // This won't be necessary if we rewrite this using XML_PARSER // if (!strchr(buf, '\n')) { while (fgets(buf, sizeof(buf), fin)) { if (strchr(buf, '\n')) break; } continue; } if (match_tag(buf, "</scheduler_request>")) { core_client_version = 10000*core_client_major_version + 100*core_client_minor_version + core_client_release; return NULL; } if (parse_str(buf, "<authenticator>", authenticator, sizeof(authenticator))) { remove_quotes(authenticator); continue; } if (parse_str(buf, "<cross_project_id>", cross_project_id, sizeof(cross_project_id))) continue; if (parse_int(buf, "<hostid>", hostid)) continue; if (parse_int(buf, "<rpc_seqno>", rpc_seqno)) continue; if (parse_str(buf, "<platform_name>", platform.name, sizeof(platform.name))) continue; if (match_tag(buf, "<alt_platform>")) { CLIENT_PLATFORM cp; retval = cp.parse(fin); if (!retval) { alt_platforms.push_back(cp); } continue; } if (match_tag(buf, "<app_versions>")) { while (fgets(buf, sizeof(buf), fin)) { if (match_tag(buf, "</app_versions>")) break; if (match_tag(buf, "<app_version>")) { CLIENT_APP_VERSION cav; retval = cav.parse(fin); if (retval) { g_reply->insert_message( "Invalid app version description", "high" ); } else { client_app_versions.push_back(cav); } } } continue; } if (parse_int(buf, "<core_client_major_version>", core_client_major_version)) continue; if (parse_int(buf, "<core_client_minor_version>", core_client_minor_version)) continue; if (parse_int(buf, "<core_client_release>", core_client_release)) continue; if (parse_double(buf, "<work_req_seconds>", work_req_seconds)) continue; if (parse_double(buf, "<cpu_req_secs>", cpu_req_secs)) continue; if (parse_double(buf, "<cpu_req_instances>", cpu_req_instances)) continue; if (parse_double(buf, "<resource_share_fraction>", resource_share_fraction)) continue; if (parse_double(buf, "<rrs_fraction>", rrs_fraction)) continue; if (parse_double(buf, "<prrs_fraction>", prrs_fraction)) continue; if (parse_double(buf, "<estimated_delay>", cpu_estimated_delay)) continue; if (parse_double(buf, "<duration_correction_factor>", host.duration_correction_factor)) continue; if (match_tag(buf, "<global_preferences>")) { strcpy(global_prefs_xml, "<global_preferences>\n"); while (fgets(buf, sizeof(buf), fin)) { if (strstr(buf, "</global_preferences>")) break; safe_strcat(global_prefs_xml, buf); } safe_strcat(global_prefs_xml, "</global_preferences>\n"); continue; } if (match_tag(buf, "<working_global_preferences>")) { while (fgets(buf, sizeof(buf), fin)) { if (strstr(buf, "</working_global_preferences>")) break; safe_strcat(working_global_prefs_xml, buf); } continue; } if (parse_str(buf, "<global_prefs_source_email_hash>", global_prefs_source_email_hash, sizeof(global_prefs_source_email_hash))) continue; if (match_tag(buf, "<host_info>")) { host.parse(fin); continue; } if (match_tag(buf, "<time_stats>")) { host.parse_time_stats(fin); continue; } if (match_tag(buf, "<time_stats_log>")) { handle_time_stats_log(fin); have_time_stats_log = true; continue; } if (match_tag(buf, "<net_stats>")) { host.parse_net_stats(fin); continue; } if (match_tag(buf, "<disk_usage>")) { host.parse_disk_usage(fin); continue; } if (match_tag(buf, "<result>")) { result.parse_from_client(fin); static int max_results = 200; --max_results; if (max_results >= 0) results.push_back(result); continue; } if (match_tag(buf, "<code_sign_key>")) { copy_element_contents(fin, "</code_sign_key>", code_sign_key, sizeof(code_sign_key)); continue; } if (match_tag(buf, "<msg_from_host>")) { MSG_FROM_HOST_DESC md; retval = md.parse(fin); if (!retval) { msgs_from_host.push_back(md); } continue; } if (match_tag(buf, "<file_info>")) { FILE_INFO fi; retval = fi.parse(fin); if (!retval) { file_infos.push_back(fi); } continue; } if (match_tag(buf, "<host_venue>")) { continue; } if (match_tag(buf, "<other_results>")) { have_other_results_list = true; while (fgets(buf, sizeof(buf), fin)) { if (match_tag(buf, "</other_results>")) break; if (match_tag(buf, "<other_result>")) { OTHER_RESULT o_r; retval = o_r.parse(fin); if (!retval) { other_results.push_back(o_r); } } } continue; } if (match_tag(buf, "<in_progress_results>")) { have_ip_results_list = true; int i = 0; double now = time(0); while (fgets(buf, sizeof(buf), fin)) { if (match_tag(buf, "</in_progress_results>")) break; if (match_tag(buf, "<ip_result>")) { IP_RESULT ir; retval = ir.parse(fin); if (!retval) { if (!strlen(ir.name)) { sprintf(ir.name, "ip%d", i++); } ir.report_deadline -= now; ip_results.push_back(ir); } } } continue; } if (match_tag(buf, "coprocs")) { MIOFILE mf; mf.init_file(fin); coprocs.parse(mf); coproc_cuda = (COPROC_CUDA*)coprocs.lookup("CUDA"); coproc_ati = (COPROC_ATI*)coprocs.lookup("ATI"); continue; } if (parse_bool(buf, "client_cap_plan_class", client_cap_plan_class)) continue; if (parse_int(buf, "<sandbox>", sandbox)) continue; if (match_tag(buf, "<active_task_set>")) continue; if (match_tag(buf, "<app>")) continue; if (match_tag(buf, "<app_version>")) continue; if (match_tag(buf, "<duration_variability>")) continue; if (match_tag(buf, "<new_version_check_time>")) continue; if (match_tag(buf, "<newer_version>")) continue; if (match_tag(buf, "<project>")) continue; if (match_tag(buf, "<project_files>")) continue; if (match_tag(buf, "<proxy_info>")) continue; if (match_tag(buf, "<user_network_request>")) continue; if (match_tag(buf, "<user_run_request>")) continue; if (match_tag(buf, "<master_url>")) continue; if (match_tag(buf, "<project_name>")) continue; if (match_tag(buf, "<user_name>")) continue; if (match_tag(buf, "<team_name>")) continue; if (match_tag(buf, "<email_hash>")) continue; if (match_tag(buf, "<user_total_credit>")) continue; if (match_tag(buf, "<user_expavg_credit>")) continue; if (match_tag(buf, "<user_create_time>")) continue; if (match_tag(buf, "<host_total_credit>")) continue; if (match_tag(buf, "<host_expavg_credit>")) continue; if (match_tag(buf, "<host_create_time>")) continue; if (match_tag(buf, "<nrpc_failures>")) continue; if (match_tag(buf, "<master_fetch_failures>")) continue; if (match_tag(buf, "<min_rpc_time>")) continue; if (match_tag(buf, "<short_term_debt>")) continue; if (match_tag(buf, "<long_term_debt>")) continue; if (match_tag(buf, "<resource_share>")) continue; if (match_tag(buf, "<scheduler_url>")) continue; if (match_tag(buf, "</project>")) continue; if (match_tag(buf, "<?xml")) continue; strip_whitespace(buf); if (!strlen(buf)) continue; log_messages.printf(MSG_NORMAL, "SCHEDULER_REQUEST::parse(): unrecognized: %s\n", buf ); MIOFILE mf; mf.init_file(fin); retval = skip_unrecognized(buf, mf); if (retval) return "unterminated unrecognized XML"; } return "no end tag"; }
int process_file(FILE *ifp) { char *ibuf, *config = NULL; byte **rom = NULL; /* pointers to ROM images */ byte *data = NULL; /* data accumulators */ int line = 0, first = 1, nroms = 0, abits = 0, length = 0, res = 0; int ix; /* Allocate space to read strings into */ if((ibuf = calloc(MAXLINE + 1, sizeof(char))) == NULL) { fprintf(stderr, "Insufficient memory to process file\n"); return 1; /* out of memory */ } /* Read strings from the input file */ while(read_line(ifp, ibuf, MAXLINE)) { ++line; strip_comment(ibuf); /* Blank lines are skipped in all cases */ if(is_blank(ibuf)) continue; strip_whitespace(ibuf); /* When we see the first line, we need to accumulate some other info we're going to need later. This includes the number of address bits (abits), and the number of ROMs (nroms). We also need to save a copy of the configuration line for later, since ibuf will be overwritten with each line that is consumed. We also range-check the values of abits and nroms, and allocate memory for the ROM images we will build during the reading of the rest of the file. We save the length of the configuration line (length) so that we can syntax check subsequent lines in an efficent manner. */ if(first) { /* Check structural validity of configuration line */ if(!valid_string(ibuf, "0123456789Aa")) { fprintf(stderr, "Line %d: invalid character in configuration\n", line); res = 1; goto CLEANUP; } /* Count number of ROM cells and address (state) bits */ nroms = count_roms(ibuf); abits = count_addr(ibuf); /* Complain if we didn't get at least 1 ROM, or if we got too many */ if(nroms < 1) { fprintf(stderr, "Line %d: must specify at least 1 ROM number\n", line); res = 2; goto CLEANUP; } else if(nroms > NUM_ROMS) { fprintf(stderr, "Line %d: cannot specify more than %d ROMs\n", line, NUM_ROMS); res = 2; goto CLEANUP; } /* Complain if we got no address bits, or more than MAXBITS */ if(abits < 1 || abits > MAXBITS) { fprintf(stderr, "Line %d: must have between 1-%d state bits\n", line, MAXBITS); res = 3; goto CLEANUP; } /* Okay, the config is alright, save it for later ... */ if((config = copy_string(ibuf)) == NULL) { fprintf(stderr, "Insufficient memory to process file\n"); res = 1; goto CLEANUP; } /* Hang onto the length, we'll need it later */ length = strlen(config); /* Allocate space for the ROMs and their accumulators */ if(!alloc_roms(&rom, nroms, config, abits)) { fprintf(stderr, "Insufficient memory to process file\n"); res = 1; goto CLEANUP; } if((data = calloc(nroms, sizeof(byte))) == NULL) { fprintf(stderr, "Insufficient memory to process file\n"); res = 1; goto CLEANUP; } first = 0; continue; } /* end if(first) */ /* Translate output "don't care" values to regular bits */ translate(ibuf, OUTPUT_DC, g_odcv); /* Anything bad left in the string? */ if(!valid_string(ibuf, "01Xx")) { fprintf(stderr, "Line %d: invalid character in data\n", line); res = 1; goto CLEANUP; } /* Make sure we got enough fields to satisfy the template */ if(strlen(ibuf) != length) { fprintf(stderr, "Line %d: wrong number of fields (wanted %u, got %u)\n", line, (unsigned) length, (unsigned) strlen(ibuf)); res = 4; goto CLEANUP; } /* Grab all the data out of the line, escaping on error */ if(!parse_data(ibuf, line, config, abits, data)) { res = 5; goto CLEANUP; } /* Write the data into the ROM images. We know which ROMs to use by checking the pointers in the ROM image array, and the accumulator is already set to go */ for(ix = 0; ix < nroms; ix++) { if(rom[ix]) { write_range(rom[ix], ibuf, abits, data[ix]); } } /* Clear out accumulators for the next round */ memset(data, 0, nroms); } /* end while(read_line(...)) */ /* If we didn't get a first line at all, the file was logically empty (i.e., not even a configuration!) */ if(first) { fprintf(stderr, "No configuration line was found\n"); res = 7; } else { /* Having accumulated all the data into the ROM images, we now will dump them out into the appropriate files */ if(!dump_roms(rom, nroms, abits, g_fmt)) res = 6; } CLEANUP: free(ibuf); if(config) free(config); if(rom) { free_roms(rom, nroms); free(rom); } if(data) free(data); return res; } /* end process_file() */
enum nss_status _nss_netgroup_parseline (char **cursor, struct __netgrent *result, char *buffer, size_t buflen, int *errnop) { enum nss_status status; const char *host, *user, *domain; char *cp = *cursor; /* Some sanity checks. */ if (cp == NULL) return NSS_STATUS_NOTFOUND; /* First skip leading spaces. */ while (isspace (*cp)) ++cp; if (*cp != '(') { /* We have a list of other netgroups. */ char *name = cp; while (*cp != '\0' && ! isspace (*cp)) ++cp; if (name != cp) { /* It is another netgroup name. */ int last = *cp == '\0'; result->type = group_val; result->val.group = name; *cp = '\0'; if (! last) ++cp; *cursor = cp; result->first = 0; return NSS_STATUS_SUCCESS; } return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; } /* Match host name. */ host = ++cp; while (*cp != ',') if (*cp++ == '\0') return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; /* Match user name. */ user = ++cp; while (*cp != ',') if (*cp++ == '\0') return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; /* Match domain name. */ domain = ++cp; while (*cp != ')') if (*cp++ == '\0') return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; ++cp; /* When we got here we have found an entry. Before we can copy it to the private buffer we have to make sure it is big enough. */ if (cp - host > buflen) { *errnop = ERANGE; status = NSS_STATUS_UNAVAIL; } else { memcpy (buffer, host, cp - host); result->type = triple_val; buffer[(user - host) - 1] = '\0'; /* Replace ',' with '\0'. */ result->val.triple.host = strip_whitespace (buffer); buffer[(domain - host) - 1] = '\0'; /* Replace ',' with '\0'. */ result->val.triple.user = strip_whitespace (buffer + (user - host)); buffer[(cp - host) - 1] = '\0'; /* Replace ')' with '\0'. */ result->val.triple.domain = strip_whitespace (buffer + (domain - host)); status = NSS_STATUS_SUCCESS; /* Remember where we stopped reading. */ *cursor = cp; result->first = 0; } return status; }
m64p_error ConfigInit(const char *ConfigDirOverride, const char *DataDirOverride) { m64p_error rval; const char *configpath = NULL; char *filepath; long filelen, pathlen; FILE *fPtr; char *configtext; config_section *current_section = NULL; char *line, *end, *lastcomment; if (l_ConfigInit) return M64ERR_ALREADY_INIT; l_ConfigInit = 1; /* if a data directory was specified, make a copy of it */ if (DataDirOverride != NULL) { l_DataDirOverride = (char *) malloc(strlen(DataDirOverride) + 1); if (l_DataDirOverride == NULL) return M64ERR_NO_MEMORY; strcpy(l_DataDirOverride, DataDirOverride); } /* if a config directory was specified, make a copy of it */ if (ConfigDirOverride != NULL) { l_ConfigDirOverride = (char *) malloc(strlen(ConfigDirOverride) + 1); if (l_ConfigDirOverride == NULL) return M64ERR_NO_MEMORY; strcpy(l_ConfigDirOverride, ConfigDirOverride); } /* get the full pathname to the config file and try to open it */ configpath = ConfigGetUserConfigPath(); if (configpath == NULL) return M64ERR_FILES; filepath = (char *) malloc(strlen(configpath) + 32); if (filepath == NULL) return M64ERR_NO_MEMORY; strcpy(filepath, configpath); pathlen = strlen(filepath); if (filepath[pathlen - 1] != OSAL_DIR_SEPARATOR) { filepath[pathlen] = OSAL_DIR_SEPARATOR; filepath[pathlen + 1] = 0; } strcat(filepath, MUPEN64PLUS_CFG_NAME); fPtr = fopen(filepath, "rb"); if (fPtr == NULL) { DebugMessage(M64MSG_INFO, "Couldn't open configuration file '%s'. Using defaults.", filepath); free(filepath); l_SaveConfigOnExit = 1; /* auto-save the config file so that the defaults will be saved to disk */ return M64ERR_SUCCESS; } free(filepath); /* read the entire config file */ fseek(fPtr, 0L, SEEK_END); filelen = ftell(fPtr); fseek(fPtr, 0L, SEEK_SET); configtext = (char *) malloc(filelen + 16); if (configtext == NULL) { fclose(fPtr); return M64ERR_NO_MEMORY; } if (fread(configtext, 1, filelen, fPtr) != filelen) { free(configtext); fclose(fPtr); return M64ERR_FILES; } fclose(fPtr); /* parse the file data */ current_section = NULL; line = configtext; end = configtext + filelen; lastcomment = NULL; *end = 0; while (line < end) { char *pivot, *varname, *varvalue; /* get the pointer to the next line, and null-terminate this line */ char *nextline = strchr(line, '\n'); if (nextline == NULL) nextline = end; *nextline++ = 0; /* strip the whitespace and handle comment */ strip_whitespace(line); if (strlen(line) < 1) { line = nextline; continue; } if (line[0] == '#') { line++; strip_whitespace(line); lastcomment = line; line = nextline; continue; } /* handle section definition line */ if (strlen(line) > 2 && line[0] == '[' && line[strlen(line)-1] == ']') { line++; line[strlen(line)-1] = 0; rval = ConfigOpenSection(line, (m64p_handle *) ¤t_section); if (rval != M64ERR_SUCCESS) { free(configtext); return rval; } lastcomment = NULL; line = nextline; continue; } /* handle variable definition */ pivot = strchr(line, '='); if (current_section == NULL || pivot == NULL) { line = nextline; continue; } varname = line; varvalue = pivot + 1; *pivot = 0; strip_whitespace(varname); strip_whitespace(varvalue); if (varvalue[0] == '"' && varvalue[strlen(varvalue)-1] == '"') { varvalue++; varvalue[strlen(varvalue)-1] = 0; ConfigSetDefaultString((m64p_handle) current_section, varname, varvalue, lastcomment); } else if (osal_insensitive_strcmp(varvalue, "false") == 0) { ConfigSetDefaultBool((m64p_handle) current_section, varname, 0, lastcomment); } else if (osal_insensitive_strcmp(varvalue, "true") == 0) { ConfigSetDefaultBool((m64p_handle) current_section, varname, 1, lastcomment); } else if (is_numeric(varvalue)) { int val_int = (int) strtol(varvalue, NULL, 10); float val_float = (float) strtod(varvalue, NULL); if ((val_float - val_int) != 0.0) ConfigSetDefaultFloat((m64p_handle) current_section, varname, val_float, lastcomment); else ConfigSetDefaultInt((m64p_handle) current_section, varname, val_int, lastcomment); } else { /* assume that it's a string */ ConfigSetDefaultString((m64p_handle) current_section, varname, varvalue, lastcomment); } lastcomment = NULL; line = nextline; } /* release memory used for config file text */ free(configtext); /* duplicate the entire config data list, to store a copy of the list which represents the state of the file on disk */ copy_configlist_active_to_saved(); return M64ERR_SUCCESS; }
/* * Convert a binary number (string) to a series of characters */ int number_to_string( char *string ) { int sLen = strlen( string ); // Length of original string int ch = 0; // Integer to receive character value int stringMoved = 0; // Number of times string was incremeneted int counter; // Generic counter /* Create our bin string */ char *binStr = malloc( (BIN_STR_LENGTH) ); if( binStr == NULL ) { mem_error("In: number_to_string"); return(1); } /* A mutable copy of the original string */ char fromStringStack[ sLen ]; char *fromString = fromStringStack; /* Null out strings */ memset( binStr, '\0', (BIN_STR_LENGTH) ); memset( fromString, '\0', ( sLen + 1 )); /* Strip whitespace */ strip_whitespace( fromString, string ); /* * Go through the string, grabbing 8-bit (or fewer) chunks of it and * converting said 'chunks' to ASCII character values, printing each * along the way. */ while( 1 ) { /* Check if we're only working with one character */ if( sLen <= (BIN_STR_LENGTH) + 1) { ch = (int)binary_to_decimal( fromString ); if( ch != 0 ) { text_mode_printer( ch, fromString ); if( lineSpacing == 1 && totalConversions < 2 ) printf("\n"); } break; } else { for( counter = 0; counter <= (BIN_STR_LENGTH) ; ++counter ) { binStr[counter] = fromString[counter]; } fromString += counter; stringMoved += counter; sLen -= counter; ch = (int)binary_to_decimal( binStr ); text_mode_printer( ch, binStr ); memset( binStr, '\0', (BIN_STR_LENGTH) ); if( lineSpacing == 1 ) printf("\n"); else if( verbose == 1 ) printf("\t"); } } if( lineSpacing == 0 ) printf("\n"); /* Reset the original string */ fromString -= stringMoved; /* Free / null binStr */ free( binStr ); binStr = NULL; return(0); }