// always generates an HTML reply
//
int handle_request(FILE* in, R_RSA_PUBLIC_KEY& key) {
    char buf[256];
    char file_name[256];
    int major, minor, release, retval=0;
    bool got_version = true;
    bool did_something = false;
    double start_time = dtime();

#ifdef _USING_FCGI_
    log_messages.set_indent_level(1);
#endif
    while (fgets(buf, 256, in)) {
        log_messages.printf(MSG_DEBUG, "handle_request: %s", buf);
        if (parse_int(buf, "<core_client_major_version>", major)) {
            continue;
        } else if (parse_int(buf, "<core_client_minor_version>", minor)) {
            continue;
        } else if (parse_int(buf, "<core_client_release>", release)) {
            continue;
        } else if (match_tag(buf, "<file_upload>")) {

            if (!got_version) {
                retval = return_error(ERR_PERMANENT, "Missing version");
            } else {
                retval = handle_file_upload(in, key);
            }
            did_something = true;
            break;
        } else if (parse_str(buf, "<get_file_size>", file_name, sizeof(file_name))) {
            if (strstr(file_name, "..")) {
                return return_error(ERR_PERMANENT, "Bad filename");
            }
            if (!got_version) {
                retval = return_error(ERR_PERMANENT, "Missing version");
            } else {
                retval = handle_get_file_size(file_name);
            }
            did_something = true;
            break;
        } else if (match_tag(buf, "<data_server_request>")) {
            // DO NOTHING
        } else {
            log_messages.printf(MSG_DEBUG, "handle_request: unrecognized %s\n", buf);
        }
    }
    if (!did_something) {
        log_messages.printf(MSG_CRITICAL, "handle_request: no command\n");
        return return_error(ERR_TRANSIENT, "no command");
    }

    log_messages.printf(MSG_DEBUG, "elapsed time %f seconds\n", dtime()-start_time);

    return retval;
}
Example #2
0
/**
 * set an attribute on a room.
 */
static int room_attr_set(struct room *r, const char *name, const char *value) {
	int res;

	assert(r != NULL);
	assert(name != NULL);
	assert(value != NULL);

	if(!r) return 0;

	if(!strcasecmp("id", name))
		res=parse_uint(name, value, &r->id);
	else if(!strcasecmp("name.short", name))
		res=parse_str(name, value, &r->name.short_str);
	else if(!strcasecmp("name.long", name))
		res=parse_str(name, value, &r->name.long_str);
	else if(!strcasecmp("desc.short", name))
		res=parse_str(name, value, &r->desc.short_str);
	else if(!strcasecmp("desc.long", name))
		res=parse_str(name, value, &r->desc.long_str);
	else if(!strcasecmp("creator", name))
		res=parse_str(name, value, &r->creator);
	else if(!strcasecmp("owner", name))
		res=parse_str(name, value, &r->owner);
	else
		res=parse_attr(name, value, &r->extra_values);

	if(res)
		r->dirty_fl=1;
	return res;
}
Example #3
0
int APP_CONFIG::parse(char* buf) {

    memset(this, 0, sizeof(APP_CONFIG));
    parse_str(buf, "<scidb_name>", scidb_name, sizeof(scidb_name));
    parse_int(buf, "<max_wus_ondisk>", max_wus_ondisk);
    parse_int(buf, "<min_quorum>", min_quorum );
    parse_int(buf, "<target_nresults>", target_nresults);
    parse_int(buf, "<max_error_results>", max_error_results);
    parse_int(buf, "<max_success_results>", max_success_results);
    parse_int(buf, "<max_total_results>", max_total_results);
    if (match_tag(buf, "</config>")) return 0;
    return ERR_XML_PARSE;
}
Example #4
0
int FILE_INFO::parse(FILE* f) {
    char buf[256];

    memset(this, 0, sizeof(FILE_INFO));
    while (fgets(buf, sizeof(buf), f)) {
        if (match_tag(buf, "</file_info>")) {
            if (!strlen(name)) return ERR_XML_PARSE;
            return 0;
        }
        if (parse_str(buf, "<name>", name, 256)) continue;
    }
    return ERR_XML_PARSE;
}
Example #5
0
int IP_RESULT::parse(FILE* f) {
    char buf[256];

    report_deadline = 0;
    cpu_time_remaining = 0;
    strcpy(name, "");
    while (fgets(buf, sizeof(buf), f)) {
        if (match_tag(buf, "</ip_result>")) return 0;
        if (parse_str(buf, "<name>", name, sizeof(name))) continue;
        if (parse_double(buf, "<report_deadline>", report_deadline)) continue;
        if (parse_double(buf, "<cpu_time_remaining>", cpu_time_remaining)) continue;
    }
    return ERR_XML_PARSE;
}
Example #6
0
int CSkinIcon::Parse(MIOFILE& in) {
    char buf[256];
    std::string strBuffer;

    while (in.fgets(buf, 256)) {
        if (match_tag(buf, "</image>")) break;
        else if (parse_str(buf, "<imagesrc>", strBuffer)) {
            if (strBuffer.length()) {
                m_strDesiredIcon = wxString(
                    wxGetApp().GetSkinManager()->ConstructSkinPath() +
                    wxString(strBuffer.c_str(), wxConvUTF8)
                );
            }
            continue;
        } else if (parse_str(buf, "<transparency_mask>", strBuffer)) {
            if (strBuffer.length()) {
                m_strDesiredTransparencyMask = wxString(strBuffer.c_str(), wxConvUTF8);
            }
            continue;
        }
    }

    return BOINC_SUCCESS;
}
Example #7
0
static void
start_list(Visitor *v, const char *name, Error **errp)
{
    StringInputVisitor *siv = to_siv(v);

    parse_str(siv, errp);

    siv->cur_range = g_list_first(siv->ranges);
    if (siv->cur_range) {
        Range *r = siv->cur_range->data;
        if (r) {
            siv->cur = r->begin;
        }
    }
}
Example #8
0
int CSkinImage::Parse(MIOFILE& in) {
    char buf[256];
    std::string strBuffer;

    while (in.fgets(buf, 256)) {
        if (match_tag(buf, "</image>")) break;
        else if (parse_str(buf, "<imagesrc>", strBuffer)) {
            if (strBuffer.length()) {
                m_strDesiredBitmap = wxString(
                    wxGetApp().GetSkinManager()->ConstructSkinPath() +
                    wxString(strBuffer.c_str(), wxConvUTF8)
                );
            }
            continue;
        } else if (parse_str(buf, "<background_color>", strBuffer)) {
            if (strBuffer.length()) {
                m_strDesiredBackgroundColor = wxString(strBuffer.c_str(), wxConvUTF8);
            }
            continue;
        } else if (match_tag(buf, "<anchor_horizontal_left>")) {
            m_iAnchorHorizontal = BKGD_ANCHOR_HORIZ_LEFT;
        } else if (match_tag(buf, "<anchor_horizontal_center>")) {
            m_iAnchorHorizontal = BKGD_ANCHOR_HORIZ_CENTER;
        } else if (match_tag(buf, "<anchor_horizontal_right>")) {
            m_iAnchorHorizontal = BKGD_ANCHOR_HORIZ_RIGHT;
        } else if (match_tag(buf, "<anchor_vertical_top>")) {
            m_iAnchorVertical = BKGD_ANCHOR_VERT_TOP;;
        } else if (match_tag(buf, "<anchor_vertical_center>")) {
            m_iAnchorVertical = BKGD_ANCHOR_VERT_CENTER;;
        } else if (match_tag(buf, "<anchor_vertical_bottom>")) {
            m_iAnchorVertical = BKGD_ANCHOR_VERT_BOTTOM;;
        }
    }

    return BOINC_SUCCESS;
}
Example #9
0
int CSkinImage::Parse(MIOFILE& in) {
    char buf[256];
    std::string strBuffer;

    while (in.fgets(buf, 256)) {
        if (match_tag(buf, "</image>")) break;
        else if (parse_str(buf, "<imagesrc>", strBuffer)) {
            if (strBuffer.length()) {
                m_strDesiredBitmap = wxString(
                    wxGetApp().GetSkinManager()->ConstructSkinPath() +
                    wxString(strBuffer.c_str(), wxConvUTF8)
                );
            }
            continue;
        } else if (parse_str(buf, "<background_color>", strBuffer)) {
            if (strBuffer.length()) {
                m_strDesiredBackgroundColor = wxString(strBuffer.c_str(), wxConvUTF8);
            }
            continue;
        }
    }

    return BOINC_SUCCESS;
}
Example #10
0
int CSkinWizardATAM::Parse(MIOFILE& in) {
    char buf[256];
    std::string strBuffer;

    while (in.fgets(buf, 256)) {
        if (match_tag(buf, "</attach_to_account_manager>")) break;
        else if (parse_str(buf, "<account_info_message>", strBuffer)) {
            m_strAccountInfoMessage = wxString(strBuffer.c_str(), wxConvUTF8);
            continue;
        }
    }

    InitializeDelayedValidation();

    return 0;
}
Example #11
0
int CSkinWizardATP::Parse(MIOFILE& in) {
    char buf[256];
    std::string strBuffer;

    while (in.fgets(buf, 256)) {
        if (match_tag(buf, "</attach_to_project>")) break;
        else if (parse_str(buf, "<title>", strBuffer)) {
            m_strTitle = wxString(strBuffer.c_str(), wxConvUTF8);
            continue;
        }
    }

    InitializeDelayedValidation();

    return 0;
}
Example #12
0
char *v4l_guess(char *str, int *fd) {
	char *dev = NULL, *settings = NULL, *atparms = NULL;

	parse_str(str, &dev, &settings, &atparms);

	init_freqs();

	v4l1_cap = -1;
	v4l2_cap = -1;
	*fd = -1;

	if (dev == NULL) {
		rfbLog("v4l_guess: could not find device in: %s\n", str);
		return NULL;
	}

	if (settings) {
		apply_settings(dev, settings, fd);
	}

	if (atparms) {
		/* use user's parameters. */
		char *t = (char *) malloc(5+strlen(dev)+1+strlen(atparms)+1);
		sprintf(t, "snap:%s@%s", dev, atparms);
		return t;
	}

	/* try to query the device for parameters. */
	atparms = guess_via_v4l(dev, fd);
	if (atparms == NULL) {
		/* try again with v4l-info(1) */
		atparms = guess_via_v4l_info(dev, fd);
	}

	if (atparms == NULL) {
		/* bad news */
		if (*fd >= 0) {
			close(*fd);
		}
		*fd = -1;
		return NULL;
	} else {
		char *t = (char *) malloc(5+strlen(dev)+1+strlen(atparms)+1);
		sprintf(t, "snap:%s@%s", dev, atparms);
		return t;
	}
}
int HOST_INFO::parse(MIOFILE& in, bool benchmarks_only) {
    char buf[1024];

    while (in.fgets(buf, sizeof(buf))) {
        if (match_tag(buf, "</host_info>")) return 0;
        else if (parse_double(buf, "<p_fpops>", p_fpops)) {
            // fix foolishness that could result in negative value here
            //
            if (p_fpops < 0) p_fpops = -p_fpops;
            continue;
        }
        else if (parse_double(buf, "<p_iops>", p_iops)) {
            if (p_iops < 0) p_iops = -p_iops;
            continue;
        }
        else if (parse_double(buf, "<p_membw>", p_membw)) {
            if (p_membw < 0) p_membw = -p_membw;
            continue;
        }
        else if (parse_double(buf, "<p_calculated>", p_calculated)) continue;

        if (benchmarks_only) continue;

        if (parse_int(buf, "<timezone>", timezone)) continue;
        else if (parse_str(buf, "<domain_name>", domain_name, sizeof(domain_name))) continue;
        else if (parse_str(buf, "<ip_addr>", ip_addr, sizeof(ip_addr))) continue;
        else if (parse_str(buf, "<host_cpid>", host_cpid, sizeof(host_cpid))) continue;
        else if (parse_int(buf, "<p_ncpus>", p_ncpus)) continue;
        else if (parse_str(buf, "<p_vendor>", p_vendor, sizeof(p_vendor))) continue;
        else if (parse_str(buf, "<p_model>", p_model, sizeof(p_model))) continue;
        else if (parse_str(buf, "<p_features>", p_features, sizeof(p_features))) continue;
        else if (parse_double(buf, "<m_nbytes>", m_nbytes)) continue;
        else if (parse_double(buf, "<m_cache>", m_cache)) continue;
        else if (parse_double(buf, "<m_swap>", m_swap)) continue;
        else if (parse_double(buf, "<d_total>", d_total)) continue;
        else if (parse_double(buf, "<d_free>", d_free)) continue;
        else if (parse_str(buf, "<os_name>", os_name, sizeof(os_name))) continue;
        else if (parse_str(buf, "<os_version>", os_version, sizeof(os_version))) continue;
        else if (match_tag(buf, "<coprocs>")) {
            coprocs.parse(in);
        }
    }
    return ERR_XML_PARSE;
}
// Add a signature at the end of every <file_info> element,
//
int add_signatures(char* xml, R_RSA_PRIVATE_KEY& key) {
    char* p = xml, *q1, *q2, buf[BLOB_SIZE], buf2[BLOB_SIZE];
    char signature_hex[BLOB_SIZE];
    char signature_xml[BLOB_SIZE];
    char signed_xml[1024];
    int retval, len;

    while (1) {
        q1 = strstr(p, "<file_info>\n");
        if (!q1) break;
        q2 = strstr(q1, "</file_info>");
        if (!q2) {
            fprintf(stderr, "add_signatures: malformed XML: %s\n", xml);
            return ERR_XML_PARSE;
        }

        q1 += strlen("<file_info>\n");
        len = q2 - q1;
        memcpy(buf, q1, len);
        buf[len] = 0;
        char name[1024];
        if (!parse_str(buf, "<name>", name, sizeof(name))) {
            fprintf(stderr, "add_signatures: missing name: %s", buf);
            return ERR_XML_PARSE;
        }
        double max_nbytes;
        if (!parse_double(buf, "<max_nbytes>", max_nbytes)) {
            fprintf(stderr, "add_signatures: missing max_nbytes: %s", buf);
            return ERR_XML_PARSE;
        }
        sprintf(signed_xml, "<name>%s</name><max_nbytes>%.0f</max_nbytes>",
            name, max_nbytes
        );
        retval = generate_signature(signed_xml, signature_hex, key);
        sprintf(signature_xml,
            "<xml_signature>\n%s</xml_signature>\n", signature_hex
        );
        if (retval) return retval;
        strcpy(buf2, q2);
        strcpy(q1, buf);
        strcat(q1, signature_xml);
        strcat(q1, buf2);
        p = q1;
    }
    return 0;
}
Example #15
0
t_obj		*my_spot(t_obj *obj, int fd, int *cmp)
{
  t_tmp		*tmp;
  char		*s;

  tmp = new_tmp();
  tmp->name = "spot";
  while ((s = get_next_line(fd)) && my_strcmp(s, "</SPOT>"))
    {
      if (s[0] && s[0] != COMMENT_CHAR)
        tmp = parse_str(tmp, s, cmp);
      (*cmp)++;
      free(s);
    }
  obj = append_obj(obj, tmp);
  free(s);
  free(tmp);
  return (obj);
}
Example #16
0
static void parse_type_int64(Visitor *v, const char *name, int64_t *obj,
                             Error **errp)
{
    StringInputVisitor *siv = to_siv(v);

    if (!siv->string) {
        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",
                   "integer");
        return;
    }

    if (parse_str(siv, name, errp) < 0) {
        return;
    }

    if (!siv->ranges) {
        goto error;
    }

    if (!siv->cur_range) {
        Range *r;

        siv->cur_range = g_list_first(siv->ranges);
        if (!siv->cur_range) {
            goto error;
        }

        r = siv->cur_range->data;
        if (!r) {
            goto error;
        }

        siv->cur = r->begin;
    }

    *obj = siv->cur;
    siv->cur++;
    return;

error:
    error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name ? name : "null",
               "an int64 value or range");
}
Example #17
0
static svn_error_t *
try_explicit_length(const char *data, apr_size_t len, apr_size_t check_len,
                    apr_pool_t *pool)
{
  int i;
  svn_stringbuf_t *str = get_empty_string(pool);
  svn_skel_t *skel;

  /* Try it with every possible separator character.  */
  for (i = 0; i < 256; i++)
    if (skel_is_space( (apr_byte_t)i))
      {
        svn_stringbuf_setempty(str);
        put_explicit_length(str, data, len,  (apr_byte_t)i);
        skel = parse_str(str, pool);
        if (! check_explicit_length(skel, data, check_len))
          return fail(pool, "failed to reparse explicit-length atom");
      }

  return SVN_NO_ERROR;
}
Example #18
0
/**
 * parse_arg_x - parse QPF-VARPTR style commands
 */
static unsigned int parse_arg_x(const char *origptr)
{
	const char *ptr = origptr, *var_begin, *var_end = NULL, *data;
	char var_name[64] = {};
	size_t var_size;

	++ptr;
	while (HX_isspace(*ptr))
		++ptr;
	if (*ptr != '(') {
		fprintf(stderr, "** Syntax error, no '(' following 'X'\n");
		return ptr - origptr;
	}

	++ptr;
	while (HX_isspace(*ptr))
		++ptr;
	var_begin = ptr;
	while (!HX_isspace(*ptr) && *ptr != '\0' && *ptr != ')')
		var_end = ++ptr;
	while (HX_isspace(*ptr))
		++ptr;
	if (*ptr != ')') {
		fprintf(stderr, "** Syntax error, no ')' after 'X'\n");
		return ptr - origptr;
	}

	++ptr;
	var_size = var_end - var_begin;
	strncpy(var_name, var_begin, (var_size + 1 > sizeof(var_name)) ?
	        sizeof(var_name) : var_size);

	if ((data = HXmap_get(varmap, var_name)) == NULL) {
		fprintf(stderr, "** Variable \"%s\" not found\n", var_name);
		return ptr - origptr;
	}

	parse_str(data);
	return ptr - origptr;
}
Example #19
0
/**
 * @brief Check if a message is addressed to an ad bot
 * @return 0=no, 1=yes
 */
int adCheck(UserList *nl_from, char *nm_target, char *args[], int numargs)
{
	int k = 0;
	char txt_message[IRCBUF];

	if (MassServ == NULL)
		return 0;

	if (nl_from == 0 || args == 0 || numargs < 1 || args[0]==0 || nm_target == 0)
		return 0;
	parse_str(args, numargs, 0, txt_message, IRCBUF);

	for(k = 0; k < 2; k++)
	{
		if (massAdClones[k] && strcasecmp(nm_target, massAdClones[k]) == 0)
		{
			detect_mass(nl_from, txt_message, k);
			return 1;
		}
	}
	return 0;
}
Example #20
0
/**
 * Reads the NMEA sentence into the specified structure.
 *
 * @param[out] nmea Structure to hold the parsed data.
 * @param[in] s Start of the string to parse (inclusive).
 * @param[in] e End of the string to parse (exclusive).
 * @retval -1 Parameter failure, parsing error.
 * @retval  0 Success
 */
static int read(struct nmea_t * nmea, const char * s, const char * e)
{
	struct nmea_rte_t * v;
	int state = 0;
	const char * p;

	if (nmea == NULL || s == NULL || e == NULL) return -1;
	nmea->type = NMEA_RTE;
	v = &nmea->sentence.rte;
	p = find_token_end(s);
	for (state = -1; state < 13 && s < e; ++state) {
		switch (state) {
			case  0: if (parse_int(s, p, &v->n_messages) != p) return -1; break;
			case  1: if (parse_int(s, p, &v->message_number) != p) return -1; break;
			case  2: v->message_mode = (s == p) ? NMEA_COMPLETE_ROUTE : *s; break;
			case  3:
			case  4:
			case  5:
			case  6:
			case  7:
			case  8:
			case  9:
			case 10:
			case 11:
			case 12:
				if ((unsigned int)(p-s+1) < sizeof(v->waypoint_id[state-3])
					&& parse_str(s, p, v->waypoint_id[state-3]) != p)
					return -1;
				break;
			default: break;
		}
		s = p + 1;
		p = find_token_end(s);
	}
	return 0;
}
Example #21
0
// ALWAYS generates an HTML reply
//
int handle_file_upload(FILE* in, R_RSA_PUBLIC_KEY& key) {
    char buf[256], path[MAXPATHLEN], signed_xml[1024];
    char name[256], stemp[256];
    double max_nbytes=-1;
    char xml_signature[1024];
    int retval;
    double offset=0, nbytes = -1;
    bool is_valid, btemp;

    strcpy(name, "");
    strcpy(xml_signature, "");
    bool found_data = false;
    while (fgets(buf, 256, in)) {
#if 1
        log_messages.printf(MSG_NORMAL, "got:%s\n", buf);
#endif
        if (match_tag(buf, "<file_info>")) continue;
        if (match_tag(buf, "</file_info>")) continue;
        if (match_tag(buf, "<signed_xml>")) continue;
        if (match_tag(buf, "</signed_xml>")) continue;
        if (parse_bool(buf, "generated_locally", btemp)) continue;
        if (parse_bool(buf, "upload_when_present", btemp)) continue;
        if (parse_str(buf, "<url>", stemp, sizeof(stemp))) continue;
        if (parse_str(buf, "<md5_cksum>", stemp, sizeof(stemp))) continue;
        if (match_tag(buf, "<xml_signature>")) {
            copy_element_contents(
                in, "</xml_signature>", xml_signature, sizeof(xml_signature)
            );
            continue;
        }
        if (parse_str(buf, "<name>", name, sizeof(name))) {
            strcpy(this_filename, name);
            continue;
        }
        if (parse_double(buf, "<max_nbytes>", max_nbytes)) continue;
        if (parse_double(buf, "<offset>", offset)) continue;
        if (parse_double(buf, "<nbytes>", nbytes)) continue;
        if (match_tag(buf, "<data>")) {
            found_data = true;
            break;
        }
        log_messages.printf(MSG_CRITICAL, "unrecognized: %s", buf);
    }
    if (strlen(name) == 0) {
        return return_error(ERR_PERMANENT, "Missing name");
    }
    if (!found_data) {
        return return_error(ERR_PERMANENT, "Missing <data> tag");
    }
    if (!config.ignore_upload_certificates) {
        if (strlen(xml_signature) == 0) {
            return return_error(ERR_PERMANENT, "missing signature");
        }
        if (max_nbytes < 0) {
            return return_error(ERR_PERMANENT, "missing max_nbytes");
        }
        sprintf(signed_xml,
            "<name>%s</name><max_nbytes>%.0f</max_nbytes>",
            name, max_nbytes
        );
        retval = check_string_signature(
            signed_xml, xml_signature, key, is_valid
        );
        if (retval || !is_valid) {
            log_messages.printf(MSG_CRITICAL,
                "check_string_signature() [%s] [%s] retval %d, is_valid = %d\n",
                signed_xml, xml_signature,
                retval, is_valid
            );
            log_messages.printf(MSG_NORMAL,
                "signed xml: %s\n", signed_xml
            );
            log_messages.printf(MSG_NORMAL,
                "signature: %s\n", xml_signature
            );
            return return_error(ERR_PERMANENT, "invalid signature");
        }
    }
    if (nbytes < 0) {
        return return_error(ERR_PERMANENT, "nbytes missing or negative");
    }

    // enforce limits in signed XML
    //
    if (!config.ignore_upload_certificates) {
        if (nbytes > max_nbytes) {
            sprintf(buf,
                "file size (%d KB) exceeds limit (%d KB)",
                (int)(nbytes/1024), (int)(max_nbytes/1024)
            );
            copy_socket_to_null(in);
            return return_error(ERR_PERMANENT, buf);
        }
    }

    // make sure filename is legit
    //
    if (strstr(name, "..")) {
        return return_error(ERR_PERMANENT,
            "file_upload_handler: .. found in filename: %s",
            name
        );
    }

    if (strlen(name) == 0) {
        return return_error(ERR_PERMANENT,
            "file_upload_handler: no filename; nbytes %f", nbytes
        );
    }

    retval = dir_hier_path(
        name, config.upload_dir, config.uldl_dir_fanout,
        path, true
    );
    if (retval) {
        log_messages.printf(MSG_CRITICAL,
            "Failed to find/create directory for file '%s' in '%s'\n",
            name, config.upload_dir
        );
        return return_error(ERR_TRANSIENT, "can't open file");
    }
    log_messages.printf(MSG_NORMAL,
        "Starting upload of %s from %s [offset=%.0f, nbytes=%.0f]\n",
        name,
        get_remote_addr(),
        offset, nbytes
    );
#ifndef _USING_FCGI_
    fflush(stderr);
#endif
    if (offset >= nbytes) {
        log_messages.printf(MSG_CRITICAL,
            "ERROR: offset >= nbytes!!\n"
        );
        return return_success(0);
    }
    retval = copy_socket_to_file(in, path, offset, nbytes);
    log_messages.printf(MSG_NORMAL,
        "Ended upload of %s from %s; retval %d\n",
        name,
        get_remote_addr(),
        retval
    );
#ifndef _USING_FCGI_
    fflush(stderr);
#endif
    return retval;
}
int result_delete_files(RESULT& result) {
    char* p;
    char filename[256], pathname[256], buf[BLOB_SIZE];
    bool no_delete=false;
    int count_deleted = 0, retval, mthd_retval = 0;

    safe_strcpy(buf, result.xml_doc_in);
    p = strtok(buf,"\n");
    while (p) {
        if (parse_str(p, "<name>", filename, sizeof(filename))) {
        } else if (match_tag(p, "<file_info>")) {
            no_delete = false;
            strcpy(filename, "");
        } else if (match_tag(p, "<no_delete/>")) {
            no_delete = true;
        } else if (match_tag(p, "</file_info>")) {
            if (!no_delete) {
                retval = get_file_path(
                             filename, config.upload_dir, config.uldl_dir_fanout,
                             pathname
                         );
                if (retval == ERR_OPENDIR) {
                    mthd_retval = ERR_OPENDIR;
                    log_messages.printf(MSG_CRITICAL,
                                        "[RESULT#%d] missing dir for %s\n",
                                        result.id, pathname
                                       );
                } else if (retval) {
                    // the fact that no result files were found is a critical
                    // error if this was a successful result, but is to be
                    // expected if the result outcome was failure, since in
                    // that case there may well be no output file produced.
                    //
                    int debug_or_crit;
                    if (RESULT_OUTCOME_SUCCESS == result.outcome) {
                        debug_or_crit=MSG_CRITICAL;
                    } else {
                        debug_or_crit=MSG_DEBUG;
                    }
                    log_messages.printf(debug_or_crit,
                                        "[RESULT#%d] outcome=%d client_state=%d No file %s to delete\n",
                                        result.id, result.outcome, result.client_state, filename
                                       );
                } else {
                    retval = unlink(pathname);
                    if (retval) {
                        mthd_retval = ERR_UNLINK;
                        log_messages.printf(MSG_CRITICAL,
                                            "[RESULT#%d] unlink %s error: %s %s\n",
                                            result.id, pathname, boincerror(retval),
                                            (retval && errno)?strerror(errno):""
                                           );
                    } else {
                        count_deleted++;
                        log_messages.printf(MSG_NORMAL,
                                            "[RESULT#%d] unlinked %s\n", result.id, pathname
                                           );
                    }
                }
            }
        }
        p = strtok(0, "\n");
    }

    log_messages.printf(MSG_DEBUG,
                        "[RESULT#%d] deleted %d file(s)\n", result.id, count_deleted
                       );
    return mthd_retval;
}
int wu_delete_files(WORKUNIT& wu) {
    char* p;
    char filename[256], pathname[256], buf[BLOB_SIZE];
    bool no_delete=false;
    int count_deleted = 0, retval, mthd_retval = 0;

    if (strstr(wu.name, "nodelete")) return 0;

    safe_strcpy(buf, wu.xml_doc);

    p = strtok(buf, "\n");
    strcpy(filename, "");
    while (p) {
        if (parse_str(p, "<name>", filename, sizeof(filename))) {
        } else if (match_tag(p, "<file_info>")) {
            no_delete = false;
            strcpy(filename, "");
        } else if (match_tag(p, "<no_delete/>")) {
            no_delete = true;
        } else if (match_tag(p, "</file_info>")) {
            if (!no_delete) {
                retval = get_file_path(
                             filename, config.download_dir, config.uldl_dir_fanout,
                             pathname
                         );
                if (retval == ERR_OPENDIR) {
                    log_messages.printf(MSG_CRITICAL,
                                        "[WU#%d] missing dir for %s\n",
                                        wu.id, filename
                                       );
                    mthd_retval = ERR_UNLINK;
                } else if (retval) {
                    log_messages.printf(MSG_CRITICAL,
                                        "[WU#%d] get_file_path: %s: %s\n",
                                        wu.id, filename, boincerror(retval)
                                       );
                } else {
                    log_messages.printf(MSG_NORMAL,
                                        "[WU#%d] deleting %s\n", wu.id, filename
                                       );
                    retval = unlink(pathname);
                    if (retval) {
                        log_messages.printf(MSG_CRITICAL,
                                            "[WU#%d] unlink %s failed: %s\n",
                                            wu.id, filename, boincerror(retval)
                                           );
                        mthd_retval = ERR_UNLINK;
                    } else {
                        count_deleted++;
                    }
                    // delete the cached MD5 file if needed
                    //
                    if (config.cache_md5_info) {
                        strcat(pathname,".md5");
                        log_messages.printf(MSG_NORMAL,
                                            "[WU#%d] deleting %s\n", wu.id, filename
                                           );
                        retval = unlink(pathname);
                        if (retval) {
                            log_messages.printf(MSG_CRITICAL,
                                                "[WU#%d] unlink %s failed: %s\n",
                                                wu.id, filename, boincerror(retval)
                                               );
                        }
                    }
                }
            }
        }
        p = strtok(0, "\n");
    }
    log_messages.printf(MSG_DEBUG,
                        "[WU#%d] deleted %d file(s)\n", wu.id, count_deleted
                       );
    return mthd_retval;
}
Example #24
0
// initialize the diagnostics environment.
//
int diagnostics_init(
    int _flags, const char* stdout_prefix, const char* stderr_prefix
) {
    // Check to see if we have already been called
    //
    if (diagnostics_initialized) {
        return ERR_INVALID_PARAM;
    }
    diagnostics_initialized = true;

    // Setup initial values
    //
    flags = _flags;
    strcpy(stdout_log, "");
    strcpy(stdout_archive, "");
    strcpy(stderr_log, "");
    strcpy(stderr_archive, "");
    strcpy(boinc_dir, "");
    strcpy(boinc_install_dir, "");
    boinc_proxy_enabled = 0;
    strcpy(boinc_proxy, "");
    strcpy(symstore, "");

    
    // Check for invalid parameter combinations
    //
    if ((flags & BOINC_DIAG_REDIRECTSTDERR) && (flags & BOINC_DIAG_REDIRECTSTDERROVERWRITE)) {
        return ERR_INVALID_PARAM;
    }

    if ((flags & BOINC_DIAG_REDIRECTSTDOUT) && (flags & BOINC_DIAG_REDIRECTSTDOUTOVERWRITE)) {
        return ERR_INVALID_PARAM;
    }


    // Determine where the log files are to be stored
    //
    if (flags & BOINC_DIAG_PERUSERLOGFILES) {
        char user_dir[MAXPATHLEN];

#if   defined(_WIN32)
        snprintf(user_dir, sizeof(user_dir), "%s", getenv("APPDATA"));
        strncat(user_dir, "/BOINC", sizeof(user_dir) - strlen(user_dir)-1);
#elif defined(__APPLE__)
        snprintf(user_dir, sizeof(user_dir), "%s", getenv("HOME"));
        strncat(user_dir, "/Library/Application Support/BOINC", sizeof(user_dir) - strlen(user_dir)-1);
#else
        snprintf(user_dir, sizeof(user_dir), "%s", getenv("HOME"));
        strncat(user_dir, "/.BOINC", sizeof(user_dir) - strlen(user_dir)-1);
#endif

        // Check to see if the directory exists
        if (!is_dir(user_dir)) {
            boinc_mkdir(user_dir);
        }

        snprintf(stdout_log, sizeof(stdout_log), "%s/%s.txt", user_dir, stdout_prefix);
        snprintf(stdout_archive, sizeof(stdout_archive), "%s/%s.old", user_dir, stdout_prefix);
        snprintf(stderr_log, sizeof(stderr_log), "%s/%s.txt", user_dir, stderr_prefix);
        snprintf(stderr_archive, sizeof(stderr_archive), "%s/%s.old", user_dir, stderr_prefix);

    } else {

        snprintf(stdout_log, sizeof(stdout_log), "%s.txt", stdout_prefix);
        snprintf(stdout_archive, sizeof(stdout_archive), "%s.old", stdout_prefix);
        snprintf(stderr_log, sizeof(stderr_log), "%s.txt", stderr_prefix);
        snprintf(stderr_archive, sizeof(stderr_archive), "%s.old", stderr_prefix);

    }

    // Archive any old stderr.txt and stdout.txt files, if requested
    //
    if (flags & BOINC_DIAG_ARCHIVESTDERR) {
        boinc_copy(stderr_log, stderr_archive);
    }

    if (flags & BOINC_DIAG_ARCHIVESTDOUT) {
        boinc_copy(stdout_log, stdout_archive);
    }

    // Redirect stderr and/or stdout, if requested
    //
    if (flags & BOINC_DIAG_REDIRECTSTDERR) {
        file_size(stderr_log, stderr_file_size);
        stderr_file = freopen(stderr_log, "a", stderr);
        if (!stderr_file) {
            return ERR_FOPEN;
        }
        setbuf(stderr_file, 0);
    }

    if (flags & BOINC_DIAG_REDIRECTSTDERROVERWRITE) {
        stderr_file = freopen(stderr_log, "w", stderr);
        if (!stderr_file) {
            return ERR_FOPEN;
        }
        setbuf(stderr_file, 0);
    }

    if (flags & BOINC_DIAG_REDIRECTSTDOUT) {
        file_size(stdout_log, stdout_file_size);
        stdout_file = freopen(stdout_log, "a", stdout);
        if (!stdout_file) {
            return ERR_FOPEN;
        }
    }

    if (flags & BOINC_DIAG_REDIRECTSTDOUTOVERWRITE) {
        stdout_file = freopen(stdout_log, "w", stdout);
        if (!stdout_file) {
            return ERR_FOPEN;
        }
    }


#if defined(_WIN32)

#if defined(_DEBUG)

    _CrtSetReportHook(boinc_message_reporting);

    if (flags & BOINC_DIAG_MEMORYLEAKCHECKENABLED) {
        SET_CRT_DEBUG_FIELD(_CRTDBG_LEAK_CHECK_DF);
    }

    if (flags & BOINC_DIAG_HEAPCHECKENABLED) {
        if (flags & BOINC_DIAG_HEAPCHECKEVERYALLOC) {
            SET_CRT_DEBUG_FIELD(_CRTDBG_CHECK_ALWAYS_DF);
        } else {
            SET_CRT_DEBUG_FIELD(_CRTDBG_CHECK_EVERY_1024_DF);
        }
    }

    if (flags & BOINC_DIAG_BOINCAPPLICATION) {
        if (flags & BOINC_DIAG_MEMORYLEAKCHECKENABLED) {
            _CrtMemCheckpoint(&start_snapshot); 
        }
    }

#endif // defined(_DEBUG)

    // Initialize the thread list structure
    //   The data for this structure should be set by
    //   boinc_init or boinc_init_graphics.
    diagnostics_init_thread_list();

    diagnostics_init_unhandled_exception_monitor();

    diagnostics_init_message_monitor();

#endif // defined(_WIN32)

#ifdef ANDROID
#define resolve_func(l,x) \
  x=(x##_t)dlsym(l,#x); \
  if (!x) {\
    fprintf(stderr,"Unable to resolve function %s\n",#x); \
    unwind_backtrace_signal_arch=NULL; \
  }

    if ((libhandle=dlopen("libcorkscrew.so",RTLD_NOW|RTLD_GLOBAL))) {
        resolve_func(libhandle,unwind_backtrace_signal_arch);
        resolve_func(libhandle,acquire_my_map_info_list);
        resolve_func(libhandle,release_my_map_info_list);
        resolve_func(libhandle,get_backtrace_symbols);
        resolve_func(libhandle,free_backtrace_symbols);
        resolve_func(libhandle,format_backtrace_line);
        resolve_func(libhandle,load_symbol_table);
        resolve_func(libhandle,free_symbol_table);
        resolve_func(libhandle,find_symbol);
    } else {
        fprintf(stderr,"stackdumps unavailable\n");
    }
#endif // ANDROID

    // Install unhandled exception filters and signal traps.
    if (BOINC_SUCCESS != boinc_install_signal_handlers()) {
        return ERR_SIGNAL_OP;
    }


    // Store various pieces of inforation for future use.
    if (flags & BOINC_DIAG_BOINCAPPLICATION) {
        char    buf[256];
        char    proxy_address[256];
        int     proxy_port;
        MIOFILE mf;
        FILE*   p;
#ifdef _WIN32
        LONG    lReturnValue;
        HKEY    hkSetupHive;
        DWORD   dwSize = 0;
#endif

        strcpy(buf, "");
        strcpy(proxy_address, "");
        proxy_port = 0;

#ifndef _USING_FCGI_
        p = fopen(INIT_DATA_FILE, "r");
#else
        p = FCGI::fopen(INIT_DATA_FILE, "r");
#endif
 
		if (p) {
			mf.init_file(p);
			while(mf.fgets(buf, sizeof(buf))) {
				if (match_tag(buf, "</app_init_data>")) break;
				else if (parse_str(buf, "<boinc_dir>", boinc_dir, sizeof(boinc_dir))) continue;
				else if (parse_str(buf, "<symstore>", symstore, sizeof(symstore))) ;
				else if (match_tag(buf, "<use_http_proxy/>")) {
					boinc_proxy_enabled = true;
					continue;
				}
				else if (parse_str(buf, "<http_server_name>", proxy_address, sizeof(proxy_address))) continue;
				else if (parse_int(buf, "<http_server_port>", proxy_port)) continue;
			}
			fclose(p);
		}

        if (boinc_proxy_enabled) {
            int buffer_used = snprintf(boinc_proxy, sizeof(boinc_proxy), "%s:%d", proxy_address, proxy_port);
            if ((sizeof(boinc_proxy) == buffer_used) || (-1 == buffer_used)) { 
                boinc_proxy[sizeof(boinc_proxy)-1] = '\0';
            }
        }

#ifdef _WIN32
        // Lookup the location of where BOINC was installed to and store
        //   that for future use.
        lReturnValue = RegOpenKeyEx(
            HKEY_LOCAL_MACHINE, 
            _T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Setup"),  
	        0, 
            KEY_READ,
            &hkSetupHive
        );
        if (lReturnValue == ERROR_SUCCESS) {
            // How large does our buffer need to be?
            dwSize = sizeof(boinc_install_dir);

            lReturnValue = RegQueryValueEx(
                hkSetupHive,
                _T("INSTALLDIR"),
                NULL,
                NULL,
                (LPBYTE)&boinc_install_dir,
                &dwSize
            );
        }

        if (hkSetupHive) RegCloseKey(hkSetupHive);
#endif
    }

    return BOINC_SUCCESS;
}
Example #25
0
int wu_delete_files(WORKUNIT& wu) {
    char* p;
    char filename[256], path[MAXPATHLEN], buf[BLOB_SIZE];
    char path_gz[MAXPATHLEN], path_md5[MAXPATHLEN];
    bool no_delete=false;
    int count_deleted = 0, retval, mthd_retval = 0;

    if (strstr(wu.name, "nodelete")) return 0;

    safe_strcpy(buf, wu.xml_doc);

    p = strtok(buf, "\n");
    strcpy(filename, "");

    // TODO: use the XML parser.  Yuck!
    //
    while (p) {
        if (parse_str(p, "<name>", filename, sizeof(filename))) {
        } else if (match_tag(p, "<file_info>")) {
            no_delete = false;
            strcpy(filename, "");
        } else if (match_tag(p, "<no_delete/>")) {
            no_delete = true;
        } else if (match_tag(p, "</file_info>")) {
            if (!no_delete) {
                retval = get_file_path(
                    filename, download_dir, config.uldl_dir_fanout,
                    path
                );
                if (retval == ERR_OPENDIR) {
                    log_messages.printf(MSG_CRITICAL,
                        "[WU#%lu] missing dir for %s\n",
                        wu.id, filename
                    );
                    mthd_retval = ERR_UNLINK;
                } else if (retval) {
                    log_messages.printf(MSG_CRITICAL,
                        "[WU#%lu] get_file_path: %s: %s\n",
                        wu.id, filename, boincerror(retval)
                    );
                } else {
                    log_messages.printf(MSG_NORMAL,
                        "[WU#%lu] deleting %s\n", wu.id, filename
                    );
                    retval = unlink(path);
                    if (retval) {
                        log_messages.printf(MSG_CRITICAL,
                            "[WU#%lu] unlink %s failed: %s\n",
                            wu.id, filename, boincerror(retval)
                        );
                        mthd_retval = ERR_UNLINK;
                    } else {
                        count_deleted++;
                    }

                    // delete the gzipped version of the file
                    //
                    sprintf(path_gz, "%s.gz", path);
                    retval = unlink(path_gz);
                    if (!retval) {
                        log_messages.printf(MSG_NORMAL,
                            "[WU#%lu] deleted %s.gz\n", wu.id, filename
                        );
                    }

                    // delete the cached MD5 file if needed
                    //
                    if (config.cache_md5_info) {
                        sprintf(path_md5, "%s.md5", path);
                        log_messages.printf(MSG_NORMAL,
                            "[WU#%lu] deleting %s.md5\n", wu.id, filename
                        );
                        retval = unlink(path_md5);
                        if (retval) {
                            log_messages.printf(MSG_CRITICAL,
                                "[WU#%lu] unlink %s.md5 failed: %s\n",
                                wu.id, filename, boincerror(retval)
                            );
                        }
                    }
                }
            }
        }
        p = strtok(0, "\n");
    }
    log_messages.printf(MSG_DEBUG,
        "[WU#%lu] deleted %d file(s)\n", wu.id, count_deleted
    );
    return mthd_retval;
}
Example #26
0
// 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";
}
Example #27
0
/**
 * \brief Try to parse all options in str and fail if it was not possible.
 *
 * \param str Pointer to the zero terminated string to be parsed.
 * \param opts Pointer to a options array. The array must be terminated
 *             with an element having set name to NULL in its opt_t structure.
 *
 * \return The return value is zero if the string could be parsed
 *         else a non-zero value is returned.
 *
 */
int subopt_parse( char const * const str, const opt_t * opts )
{
    int parse_err = 0, idx;
    unsigned int parse_pos = 0;

    if ( str )
    {
        while ( str[parse_pos] && !parse_err )
        {
            int next = 0;

            idx = 0; // reset index for the below loop
            while ( opts[idx].name )
            {
                int opt_len;
                int substr_len;

                // get length of the option we test against */
                opt_len = strlen( opts[idx].name );

                // get length of the current substring of str */
                {
                    char * delim, * arg_delim;

                    /* search nearest delimiter ( option or argument delimiter ) */
                    delim = strchr( &str[parse_pos], ':' );
                    arg_delim = strchr( &str[parse_pos], '=' );

                    if ( ( delim && arg_delim && delim > arg_delim ) ||
                            delim == NULL )
                    {
                        delim = strchr( &str[parse_pos], '=' );
                    }

                    substr_len = delim ? // is a delim present
                                 delim - &str[parse_pos] : // yes
                                 strlen( &str[parse_pos] ); // no, end of string
                }

                //printf( "substr_len=%d, opt_len=%d\n", substr_len, opt_len );

                /* Check if the length of the current option matches the *
                 * length of the option we want to test again.           */
                if ( substr_len == opt_len )
                {
                    /* check if option was activated/deactivated */
                    if( strncmp( &str[parse_pos], opts[idx].name, opt_len ) == 0 )
                    {
                        /* option was found */
                        next = 1;

                        assert( opts[idx].valp && "Need a pointer to store the arg!" );

                        /* type specific code */
                        if ( opts[idx].type == OPT_ARG_BOOL )
                        {
                            /* Handle OPT_ARG_BOOL separately so *
                             * the others can share code.        */

                            /* set option to true */
                            *((int *)(opts[idx].valp)) = 1;

                            /* increment position */
                            parse_pos += opt_len;
                        }
                        else
                        {
                            /* Type is not OPT_ARG_BOOL, means we have to parse *
                             * for the arg delimiter character and eventually   *
                             * call a test function.                            */
                            char const * last;

                            /* increment position to check for arg */
                            parse_pos += opt_len;

                            if ( str[parse_pos] != '=' )
                            {
                                parse_err = 1;
                                break;
                            }

                            /* '=' char was there, so let's move after it */
                            ++parse_pos;

                            switch ( opts[idx].type )
                            {
                            case OPT_ARG_INT:
                                last = parse_int( &str[parse_pos],
                                                  (int *)opts[idx].valp );

                                break;
                            case OPT_ARG_STR:
                                last = parse_str( &str[parse_pos],
                                                  (strarg_t *)opts[idx].valp );
                                break;
                            case OPT_ARG_MSTRZ:
                            {
                                char **valp = opts[idx].valp;
                                strarg_t tmp;
                                tmp.str = NULL;
                                tmp.len = 0;
                                last = parse_str( &str[parse_pos], &tmp );
                                free(*valp);
                                *valp = NULL;
                                if (tmp.str && tmp.len > 0) {
                                    *valp = malloc(tmp.len + 1);
                                    memcpy(*valp, tmp.str, tmp.len);
                                    (*valp)[tmp.len] = 0;
                                }
                                break;
                            }
                            case OPT_ARG_FLOAT:
                                last = parse_float( &str[parse_pos],
                                                    (float *)opts[idx].valp );
                                break;
                            default:
                                assert( 0 && "Arg type of suboption doesn't exist!" );
                                last = NULL; // break parsing!
                            }

                            /* was the conversion succesful? */
                            if ( !last )
                            {
                                parse_err = 1;
                                break;
                            }

                            /* make test if supplied */
                            if ( opts[idx].test && !opts[idx].test( opts[idx].valp ) )
                            {
                                parse_err = 1;
                                break;
                            }

                            /* we succeded, set position */
                            parse_pos = last - str;
                        }
                    }
                }
                else if ( substr_len == opt_len+2 )
                {
                    if ( opts[idx].type == OPT_ARG_BOOL && // check for no<opt>
                            strncmp( &str[parse_pos], "no", 2 ) == 0 &&
                            strncmp( &str[parse_pos+2], opts[idx].name, opt_len ) == 0 )
                    {
                        /* option was found but negated */
                        next = 1;

                        /* set arg to false */
                        *((int *)(opts[idx].valp)) = 0;

                        /* increment position */
                        parse_pos += opt_len+2;
                    }
                }

                ++idx; // test against next option

                /* break out of the loop, if this subopt is processed */
                if ( next ) {
                    break;
                }
            }

            /* if we had a valid suboption the current pos should *
             * equal the delimiter char, which should be ':' for  *
             * suboptions.                                        */
            if ( !parse_err && str[parse_pos] == ':' ) {
                ++parse_pos;
            }
            else if ( str[parse_pos] ) {
                parse_err = 1;
            }
        }
    }

    /* if an error was encountered */
    if (parse_err)
    {
        unsigned int i;
        mp_msg( MSGT_VO, MSGL_FATAL, "Could not parse arguments at the position indicated below:\n%s\n", str );
        for ( i = 0; i < parse_pos; ++i )
        {
            mp_msg(MSGT_VO, MSGL_FATAL, " ");
        }
        mp_msg(MSGT_VO, MSGL_FATAL, "^\n");

        return -1;
    }

    /* we could parse everything */
    return 0;
}
Example #28
0
int main(void) {

  printf("<!-- hello.c -->\n");
  char name[MAX] = "henry";
  printf("hello %s!\n",name);

  printf("\n<!-- declare4Types.c -->\n");
  char c='A';
  int i = 1;
  float f = 12.0;
  double d = 12.12;
  printf("%c, %d, %f, %f\n",c,i,f,d);

  printf("\n<!-- circle.c -->\n");
  const float PI = 3.14159;
  int radius = 10;
  float area = PI * radius * radius;
  float circumference = 2 * PI * radius;
  printf("%f, %f\n", area, circumference );

  printf("\n<!-- operators.c -->\n");
  int a=17,b=5;
  printf("%d  %d  %d  %d\n", a+b, a-b, a*b, a/b);

  printf("\n<!-- inputName.c -->\n");
  char myName[MAX];
  int myAge;
  scanf("%s",myName);
  scanf("%d",&myAge);
  printf("%s is %d years old.\n", myName, myAge );

  printf("\n<!-- circle2.c -->\n");
  scanf("%d", &radius);
  printf("%f, %f\n", PI * radius * radius, 2 * PI * radius );

  printf("\n<!-- evenNum.c -->\n");
  int num[5];
  scanf("%d %d %d %d %d",&num[0],&num[1],&num[2],&num[3],&num[4]);
  printf("even number: %d-%d-%d\n",num[0],num[2],num[4]);

  printf("\n<!-- string.c -->\n");
  char line1[MAX];
  char line2[MAX];
  char line3[MAX];
  scanf("%s",line1);
  scanf("%s",line2);
  scanf("%s",line3);
  printf("%s\n%s\n%s\n", line1,line2,line3);

  printf("\n<!-- charOfString.c -->\n");
  char charOfString[5];
  scanf("%s", charOfString);
  for (int i=0;i<5;i++){
    printf("%c-->", charOfString[i] );
  }
  printf("\n");

  printf("\n<!-- sumOfArray.c -->\n");
  int sumOfArray[2][3] = {{1,2,3},{4,5,6}};

  int result;
  for(int i=0;i<2;i++){
    result=0;
    for(int j=0;j<3;j++){
      result+=sumOfArray[i][j];
    }
    printf("%d\n", result);
  }
  int col[3]={0,0,0};
  for(int i=0;i<2;i++){
    for(int j=0;j<3;j++){
      col[j]+=sumOfArray[i][j];
    }
  }
  printf("%d %d %d\n",col[0],col[1],col[2]);

  printf("\n<!-- structScanf.c -->\n");
  struct person{
    char name[10];
    int age;
    float salary;
  };
  struct person teacher;
  scanf("%s",teacher.name);
  scanf("%d", &teacher.age);
  scanf("%f", &teacher.salary);
  printf("%s is %d years old. %f\n", teacher.name, teacher.age, teacher.salary);

  printf("\n<!-- unionScanf.c -->\n");
  union money{
    int student;
    double teacher;
  };

  union money henry;
  scanf("%d", &henry.student);
  scanf("%lf", &henry.teacher);
  printf("%d\n", henry.student);
  printf("%10.2lf\n", henry.teacher);

  printf("\n<!-- enumShow.c -->\n");
  enum color {
    white=100,
    red,
    blue,
    green,
    black
  };
  enum color ball;
  ball=white;
  printf("white: %d\n",ball);
  ball=green;
  printf("green: %d\n",ball);

  printf("\n<!-- structTypedefInput.c -->\n");
  // typedef struct {
  //     char name[10];
  //     int age;
  //     float salary;
  // } Person;
  Person teacher_lin;
  scanf("%s",teacher_lin.name);
  scanf("%d", &teacher_lin.age);
  scanf("%f", &teacher_lin.salary);
  printf("%s is %d years old. %f\n", teacher_lin.name, teacher_lin.age, teacher_lin.salary);

  printf("\n<!-- defineCircle.c -->\n");
  scanf("%d", &radius);
  printf("%f, %f\n", DEFINE_PI * radius * radius, 2 * DEFINE_PI * radius );

  printf("\n<!-- defineTypedef.c -->\n");
  printf("please see structTypedefInput.c\n");

  printf("\n<!-- triangle.c -->\n");
  triangle1();
  printf("\n");
  triangle2();
  printf("\n");
  triangle3();
  printf("\n");
  triangle4();

  printf("\n<!-- rectangle.c -->\n");
  int rectN,rectM,rectD;
  scanf("%d %d %d", &rectN, &rectM, &rectD );
  for (int i=1;i<=rectD;i++){
    for (int j=1;j<=rectN;j++){
      printf("%c", '*');
    }
    printf("\n");
  }
  for (int i=1;i<=rectM-rectD*2;i++){
    for (int j=1;j<=rectD;j++){
      printf("%c", '*');
    }
    for (int j=1;j<=rectN-rectD*2;j++){
      printf("%c", ' ');
    }
    for (int j=1;j<=rectD;j++){
      printf("%c", '*');
    }
    printf("\n");
  }
  for (int i=1;i<=rectD;i++){
    for (int j=1;j<=rectN;j++){
      printf("%c", '*');
    }
    printf("\n");
  }

  printf("\n<!-- rectangle_star.c -->\n");
  int rect_star_num=20;
  int rect_star_mod=0;
  while (rect_star_mod==0){
    printf("input odd:");
    scanf("%d",&rect_star_num);
    rect_star_mod=rect_star_num%2;
  }
  a=(rect_star_num+1)/2;
	for(int b=1;b<=a;b++)
	{
		for(int d=a-b;d>0;d--)
		{
		printf(" ");
		}
		for(int e=1;e<=2*b-1;e++)
		{
			printf("*");
		}
		printf("\n");
	}
	for(int b=a-1;b>0;b--)
	{
		for(int d=a-b;d>0;d--)
		{
			printf(" ");
		}
		for(int e=1;e<=2*b-1;e++)
		{
			printf("*");
		}
		printf("\n");//換行
	}

  printf("\n<!-- id.c -->\n");
  int isOK = parse_str("11111115");
  if (isOK) {
    printf("%s\n", "OK");
  } else {
    printf("%s\n", "nOK");
  }
  isOK = parse_int(22222220);
  if (isOK) {
    printf("%s\n", "OK");
  } else {
    printf("%s\n", "nOK");
  }


}
// returns zero on success, non-zero to indicate an error
//
int add_download_servers(char *old_xml, char *new_xml, int tz) {
    char *p, *q, *r;
    int total_free = BLOB_SIZE - strlen(old_xml);

    p = (r = old_xml);

    // search for next URL to do surgery on
    while ((q=strstr(p, "<url>"))) {
        // p is at current position
        // q is at beginning of next "<url>" tag

        char *s;
        char path[MAXPATHLEN];
        int  len = q-p;

        // copy everything from p to q to new_xml
        //
        strncpy(new_xml, p, len);
        new_xml += len;

        // locate next instance of </url>
        //
        if (!(r = strstr(q, "</url>"))) {
            return 1;
        }
        r += strlen("</url>");

        // r points to the end of the whole "<url>...</url>" tag
        // parse out the URL into 'path'
        //
        if (!parse_str(q, "<url>", path, 1024)) {
            return 1;
        }

        // check if path contains the string specified in config.xml
        //
        if (!(s = strstr(path,config.replace_download_url_by_timezone))) {
            // if it doesn't, just copy the whole tag as it is
            strncpy(new_xml, q, r-q);
            new_xml += r-q;
            p=r;
        } else {
            // calculate free space available for URL replaces
            int lim = total_free - (len - (p - old_xml));

            // find end of the specified replace string,
            // i.e. start of the 'path'
            s += strlen(config.replace_download_url_by_timezone);

            // insert new download list in place of the original single URL
            len = make_download_list(new_xml, s, lim, tz);
            if (len == 0) {
                // if the replacement would exceed the maximum XML length,
                // just keep the original URL
                len = r-q;
                strncpy(new_xml, q, len);
            } else if (len < 0) {
                return 1;
            }
            new_xml += len;
            // advance pointer to start looking for next <url> tag.
            //
            p=r;
        }
    }

    strcpy(new_xml, r);
    return 0;
}
Example #30
0
void test1()
{
  const char* str = "1+2+3+4+5-4-3-2-1";

  parse_str(str, strlen(str));
}