Пример #1
0
static void
parse_statuses(const char *arg, struct ipt_conntrack_info *sinfo)
{
	const char *comma;

	while ((comma = strchr(arg, ',')) != NULL) {
		if (comma == arg || !parse_status(arg, comma-arg, sinfo))
			exit_error(PARAMETER_PROBLEM, "Bad ctstatus `%s'", arg);
		arg = comma+1;
	}

	if (strlen(arg) == 0 || !parse_status(arg, strlen(arg), sinfo))
		exit_error(PARAMETER_PROBLEM, "Bad ctstatus `%s'", arg);
}
Пример #2
0
static int refresh_imported_device_list(void)
{
	const char *attr_status;
	char status[MAX_STATUS_NAME+1] = "status";
	int i, ret;

	for (i = 0; i < vhci_driver->ncontrollers; i++) {
		if (i > 0)
			snprintf(status, sizeof(status), "status.%d", i);

		attr_status = udev_device_get_sysattr_value(vhci_driver->hc_device,
							    status);
		if (!attr_status) {
			err("udev_device_get_sysattr_value failed");
			return -1;
		}

		dbg("controller %d", i);

		ret = parse_status(attr_status);
		if (ret != 0)
			return ret;
	}

	return 0;
}
Пример #3
0
static void http_request_fetch_header(http_request_t * req) {
	int response_line = 1;
	sstring_t * line = NULL;
	while((line = readline(req->conn->connfd)) && !sstring_empty(line)) {
		if(response_line == 1) {
			parse_status(req, line);
		}
		if(strcmp(line->ptr, "\r") == 0) {
			break;
		}
		sstring_append(&req->res_header, line->ptr);
		//printf("header:%s\n", line->ptr);

		char name[200] = {0}, * value;
		value = parse_header(line, name);
		if(value) {
			hash_table_insert(req->ht_headers, name, value);
		}

		sstring_free(line);
		response_line ++;
	}

	//headers received
	change_state(req, STATE_HEADERS_RECEIVED);

	if(line) {
		sstring_free(line);
	}
}
Пример #4
0
int parse_statuses(xmlDocPtr *doc,xmlNode *node, statuses *tl){
    if(!tl)
        return -1;

    int nr_statuses = 0;
    struct status_node *prev = NULL;
    node = node->children;
    while(node){
        if(node->type == XML_ELEMENT_NODE && !xmlStrcmp(node->name,(const xmlChar *)"status")){
            xmlNode *attr = node->children;

            struct status_node *sn = newstatusnode(NULL);
            if(!sn)
                continue;

            // insert the tweet into the list
            sn->next = NULL;
            nr_statuses ++;
            if(nr_statuses == 1)
                tl->head = sn;
            else prev->next = sn;
            sn->prev = prev;
            parse_status(doc,node,&(sn->st));
            prev = sn;
        }
        node = node->next;
    }
    tl->count = nr_statuses;
    return nr_statuses;
}
Пример #5
0
/// Parses a results file written by an ATF test case.
///
/// \param input_name Path to the result file to parse.
/// \param [out] status Type of result.
/// \param [out] status_arg Optional integral argument to the status.
/// \param [out] reason Textual explanation of the result, if any.
/// \param reason_size Length of the reason output buffer.
///
/// \return An error if the input_name file has an invalid syntax; OK otherwise.
static kyua_error_t
read_atf_result(const char* input_name, enum atf_status* status,
                int* status_arg, char* const reason, const size_t reason_size)
{
    kyua_error_t error = kyua_error_ok();

    FILE* input = fopen(input_name, "r");
    if (input == NULL) {
        error = kyua_generic_error_new("Premature exit");
        goto out;
    }

    char line[1024];
    if (fgets(line, sizeof(line), input) == NULL) {
        if (ferror(input)) {
            error = kyua_libc_error_new(errno, "Failed to read result from "
                                        "file %s", input_name);
            goto out_input;
        } else {
            assert(feof(input));
            error = kyua_generic_error_new("Empty result file %s", input_name);
            goto out_input;
        }
    }

    if (!trim_newline(line)) {
        error = kyua_generic_error_new("Missing newline in result file");
        goto out_input;
    }

    char* reason_start = strstr(line, ": ");
    if (reason_start != NULL) {
        *reason_start = '\0';
        *(reason_start + 1) = '\0';
        reason_start += 2;
    }

    bool need_reason = false;  // Initialize to shut up gcc warning.
    error = parse_status(line, status, status_arg, &need_reason);
    if (kyua_error_is_set(error))
        goto out_input;

    if (need_reason) {
        error = read_reason(input, reason_start, reason, reason_size);
    } else {
        if (reason_start != NULL || !is_really_eof(input)) {
            error = kyua_generic_error_new("Found unexpected reason in passed "
                                           "test result");
            goto out_input;
        }
        reason[0] = '\0';
    }

out_input:
    fclose(input);
out:
    return error;
}
Пример #6
0
static gpgme_error_t
gpgsm_assuan_simple_command(assuan_context_t ctx, char *cmd,
                            engine_status_handler_t status_fnc,
                            void *status_fnc_value)
{
    gpg_error_t err;
    char *line;
    size_t linelen;

    err = assuan_write_line(ctx, cmd);
    if(err)
        return map_assuan_error(err);

    do
    {
        err = assuan_read_line(ctx, &line, &linelen);
        if(err)
            return map_assuan_error(err);

        if(*line == '#' || !linelen)
            continue;

        if(linelen >= 2
                && line[0] == 'O' && line[1] == 'K'
                && (line[2] == '\0' || line[2] == ' '))
            return 0;
        else if(linelen >= 4
                && line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
                && line[3] == ' ')
            err = map_assuan_error(atoi(&line[4]));
        else if(linelen >= 2
                && line[0] == 'S' && line[1] == ' ')
        {
            char *rest;
            gpgme_status_code_t r;

            rest = strchr(line + 2, ' ');
            if(!rest)
                rest = line + linelen; /* set to an empty string */
            else
                *(rest++) = 0;

            r = parse_status(line + 2);

            if(r >= 0 && status_fnc)
                err = status_fnc(status_fnc_value, r, rest);
            else
                err = gpg_error(GPG_ERR_GENERAL);
        }
        else
            err = gpg_error(GPG_ERR_GENERAL);
    }
    while(!err);

    return err;
}
Пример #7
0
/* ------------------------------------------------------------------------
@NAME       : bt_parse_entry_s()
@INPUT      : entry_text - string containing the entire entry to parse,
                           or NULL meaning we're done, please cleanup
              options    - standard btparse options bitmap
              line       - current line number (if that makes any sense)
                           -- passed to the parser to set zzline, so that
                           lexical and syntax errors are properly localized
@OUTPUT     : *top       - newly-allocated AST for the entry
                           (or NULL if entry_text was NULL, ie. at EOF)
@RETURNS    : 1 with *top set to AST for entry on successful read/parse
              1 with *top==NULL if entry_text was NULL, ie. at EOF
              0 if any serious errors seen in input (*top is still 
                set to the AST, but only for as much of the input as we
                were able to parse)
              (A "serious" error is a lexical or syntax error; "trivial"
              errors such as warnings and notifications count as "success"
              for the purposes of this function's return value.)
@DESCRIPTION: Parses a BibTeX entry contained in a string.
@GLOBALS    : 
@CALLS      : ANTLR
@CREATED    : 1997/01/18, GPW (from code in bt_parse_entry())
@MODIFIED   : 
-------------------------------------------------------------------------- */
AST * bt_parse_entry_s (char *    entry_text,
                        char *    filename,
                        int       line,
                        ushort    options,
                        boolean * status)
{
   AST *        entry_ast = NULL;
   static int * err_counts = NULL;

   if (options & BTO_STRINGMASK)        /* any string options set? */
   {
      usage_error ("bt_parse_entry_s: illegal options "
                   "(string options not allowed");
   }

   InputFilename = filename;
   err_counts = bt_get_error_counts (err_counts);

   if (entry_text == NULL)              /* signal to clean up */
   {
      finish_parse (&err_counts);
      if (status) *status = TRUE;
      return NULL;
   }

   zzast_sp = ZZAST_STACKSIZE;          /* workaround apparent pccts bug */
   start_parse (NULL, entry_text, line);

   entry (&entry_ast);                  /* enter the parser */
   ++zzasp;                             /* why is this done? */

   if (entry_ast == NULL)               /* can happen with very bad input */
   {
      if (status) *status = FALSE;
      return entry_ast;
   }

#if DEBUG
   dump_ast ("bt_parse_entry_s: single entry, after parsing:\n", 
             entry_ast);
#endif
   bt_postprocess_entry (entry_ast,
                         StringOptions[entry_ast->metatype] | options);
#if DEBUG
   dump_ast ("bt_parse_entry_s: single entry, after post-processing:\n",
             entry_ast);
#endif

   if (status) *status = parse_status (err_counts);
   return entry_ast;

} /* bt_parse_entry_s () */
Пример #8
0
static int refresh_imported_device_list(void)
{
	const char *attr_status;

	attr_status = udev_device_get_sysattr_value(vhci_driver->hc_device,
					       "status");
	if (!attr_status) {
		err("udev_device_get_sysattr_value failed");
		return -1;
	}

	return parse_status(attr_status);
}
Пример #9
0
/* see what the status of the UPS is and handle any changes */
static void pollups(utype_t *ups)
{
    char	status[SMALLBUF];

    /* try a reconnect here */
    if (!flag_isset(ups->status, ST_CONNECTED))
        if (try_connect(ups) != 1)
            return;

    if (upscli_ssl(&ups->conn) == 1)
        upsdebugx(2, "%s: %s [SSL]", __func__, ups->sys);
    else
        upsdebugx(2, "%s: %s", __func__, ups->sys);

    set_alarm();

    if (get_var(ups, "status", status, sizeof(status)) == 0) {
        clear_alarm();
        parse_status(ups, status);
        return;
    }

    /* fallthrough: no communications */
    clear_alarm();

    /* try to make some of these a little friendlier */

    switch (upscli_upserror(&ups->conn)) {

    case UPSCLI_ERR_UNKNOWNUPS:
        upslogx(LOG_ERR, "Poll UPS [%s] failed - [%s] "
                "does not exist on server %s",
                ups->sys, ups->upsname,	ups->hostname);

        break;
    default:
        upslogx(LOG_ERR, "Poll UPS [%s] failed - %s",
                ups->sys, upscli_strerror(&ups->conn));
        break;
    }

    /* throw COMMBAD or NOCOMM as conditions may warrant */
    ups_is_gone(ups);

    /* if upsclient lost the connection, clean up things on our side */
    if (upscli_fd(&ups->conn) == -1) {
        drop_connection(ups);
        return;
    }
}
Пример #10
0
static void cb_read(struct bufferevent *bev, void *arg)
{
	struct request_ctx *req = arg;
	char *line;
	size_t n;

	if (req->read_state == READ_NONE) {
		req->read_state = READ_STATUS;
	}

	while (req->read_state == READ_STATUS || req->read_state == READ_HEADERS) {

		line = read_line(bev, &n);
		if (line == NULL) {
			return;
		}

		if (req->read_state == READ_STATUS) {
			verbose(VERBOSE, "%s(): status line: '%s'\n", __func__, line);
			parse_status(req, line, n);
			set_read_state(req, READ_HEADERS);
		} else {
			while (line && req->read_state == READ_HEADERS) {
				if (*line == '\0') {
					set_read_state(req, READ_BODY);
				} else {
					char *key, *val;
					verbose(VERBOSE, "%s(): header line '%s'\n", __func__, line);
					header_keyval(&key, &val, line);
					handle_header(req, key, val);
					free(line);
					line = read_line(bev, &n);
				}
			}
		}

		free(line);

	}

	while (req->read_state == READ_BODY && evbuffer_get_length(bufferevent_get_input(bev)) > 0) {
		drain_body(req, bev);
	}

	if (req->read_state == READ_DONE) {
		request_done(req, bev);
	}

}
Пример #11
0
// *TODO:  Currently converts only from XML content.  A mode
// to convert using fromBinary() might be useful as well.  Mesh
// headers could use it.
bool responseToLLSD(HttpResponse * response, bool log, LLSD & out_llsd)
{
	// Convert response to LLSD
	BufferArray * body(response->getBody());
	if (! body || ! body->size())
	{
		return false;
	}

	LLCore::BufferArrayStream bas(body);
	LLSD body_llsd;
	S32 parse_status(LLSDSerialize::fromXML(body_llsd, bas, log));
	if (LLSDParser::PARSE_FAILURE == parse_status){
		return false;
	}
	out_llsd = body_llsd;
	return true;
}
Пример #12
0
status *parse_single_status(char *filename){
    xmlDocPtr doc;
    int result = 0;
    if(parse_xml_file(filename,&doc) == -1)
        return NULL;

    xmlNode *root_element = xmlDocGetRootElement(doc);
    status *st = NULL;
    if(root_element->type==XML_ELEMENT_NODE
        && strcmp(root_element->name,"status")==0){
        parse_status(&doc,root_element, &st);
    }
    /*
    else
        parse_error(doc,root_element);
        */

    xmlFreeDoc(doc);
    xmlCleanupParser();

    return st;
}
Пример #13
0
int parse_status(xmlDocPtr *doc, xmlNode *node, status **stptr){
    if(!node || !doc || !stptr)
        return -1;
    xmlNode *attr = node->children;

    status *st = *stptr;
    while(attr){ // parse status attributes
        if(!xmlStrcmp(attr->name, (const xmlChar *)"id")){ //status id
            char *id = xmlNodeListGetString(*doc, attr->xmlChildrenNode, 1);
            if(id){
                // look up status by id
                /*
                pthread_mutex_lock(&status_map_mutex);
                st = g_hash_table_lookup(status_map,id);
                pthread_mutex_unlock(&status_map_mutex);
                */
                if(!st){
                    // create new status and insert into the map
                    st = newstatus();
                    st->id = strdup(id);
                    /*
                    pthread_mutex_lock(&status_map_mutex);
                    g_hash_table_insert(status_map,st->id,st);
                    pthread_mutex_unlock(&status_map_mutex);
                    */
                }
                else
                    break;
            }
            else
                break;
        }
        else if(!xmlStrcmp(attr->name, (const xmlChar *)"text")){ //status text
            char *text = xmlNodeListGetString(*doc, attr->xmlChildrenNode, 1);
            if(text){
                st->wtext = malloc((TWEET_MAX_LEN+1)*sizeof(wchar_t));
                memset(st->wtext,'\0',(TWEET_MAX_LEN+1)*sizeof(wchar_t));
                st->length = mbstowcs(st->wtext,text,TWEET_MAX_LEN);
            }
        }
        else if(!xmlStrcmp(attr->name, (const xmlChar *)"favorited")){ 
            char *favorited = xmlNodeListGetString(*doc, attr->xmlChildrenNode, 1);
            if(favorited && strcmp(favorited,"true") == 0)
                SET_FAVORITED(st->extra_info);
        }
        else if(!xmlStrcmp(attr->name, (const xmlChar *)"user")){ //user
            parse_user(doc,attr,&(st->composer));
        }
        /*
        else if(!xmlStrcmp(attr->name, (const xmlChar *)"in_reply_to_status_id")){ 
            char *in_reply_to_status_id = xmlNodeListGetString(*doc, attr->xmlChildrenNode, 1);
            if(in_reply_to_status_id && strlen(in_reply_to_status_id) > 0){
                st->in_reply_to_status_id = strdup(in_reply_to_status_id);
            }
        }
        */
        else if(!xmlStrcmp(attr->name,(const xmlChar *)"retweeted_status")){
            parse_status(doc,attr,&(st->retweeted_status));
            /*
            for(entity *et=st->retweeted_status->entities;et;et=et->next)
                printf("%ls\n",et->text);
                */
        }
        else if(!xmlStrcmp(attr->name,(const xmlChar *)"entities")){
            parse_entities(doc,attr,st);
        }
        attr = attr->next;
    }
    split_status_entities(st);
    *stptr = st;
    return 0;
}
Пример #14
0
/***************************************************************************
 * Read in the file, one record at a time.
 ***************************************************************************/
static uint64_t
parse_file(struct Output *out, const char *filename)
{
    FILE *fp = 0;
    unsigned char *buf = 0;
    size_t bytes_read;
    uint64_t total_records = 0;
    int x;

    /* Allocate a buffer of up to one megabyte per record */
    buf = (unsigned char *)malloc(BUF_MAX);
    if (buf == NULL) {
        fprintf(stderr, "memory allocation failure\n");
        goto end;
    }

    /* Open the file */
    x = fopen_s(&fp, filename, "rb");
    if (x != 0 || fp == NULL) {
        perror(filename);
        goto end;
    }

    /* first record is pseudo-record */
    bytes_read = fread(buf, 1, 'a'+2, fp);
    if (bytes_read < 'a'+2) {
        perror(filename);
        goto end;
    }

    /* Make sure it's got the format string */
    if (memcmp(buf, "masscan/1.1", 11) != 0) {
        fprintf(stderr,
                "%s: unknown file format (expeced \"masscan/1.1\")\n",
                filename);
        goto end;
    }

    /* Now read all records */
    for (;;) {
        unsigned type;
        unsigned length;


        /* [TYPE]
         * This is one or more bytes indicating the type of type of the
         * record
         */
        bytes_read = fread(buf, 1, 1, fp);
        if (bytes_read != 1)
            break;
        type = buf[0] & 0x7F;
        while (buf[0] & 0x80) {
            bytes_read = fread(buf, 1, 1, fp);
            if (bytes_read != 1)
                break;
            type = (type << 7) | (buf[0] & 0x7F);
        }

        /* [LENGTH]
         * Is one byte for lengths smaller than 127 bytes, or two
         * bytes for lengths up to 16384.
         */
        bytes_read = fread(buf, 1, 1, fp);
        if (bytes_read != 1)
            break;
        length = buf[0] & 0x7F;
        while (buf[0] & 0x80) {
            bytes_read = fread(buf, 1, 1, fp);
            if (bytes_read != 1)
                break;
            length = (length << 7) | (buf[0] & 0x7F);
        }
        if (length > BUF_MAX) {
            fprintf(stderr, "file corrupt\n");
            goto end;
        }


        /* get the remainder fo the record */
        bytes_read = fread(buf, 1, length, fp);
        if (bytes_read < (int)length)
            break; /* eof */

        /* Depending on record type, do something different */
        switch (type) {
            case 1: /* STATUS: open */
                parse_status(out, Port_Open, buf, bytes_read);
                break;
            case 2: /* STATUS: closed */
                parse_status(out, Port_Closed, buf, bytes_read);
                break;
            case 3: /* BANNER */
                parse_banner3(out, buf, bytes_read);
                break;
            case 4:
                if (fread(buf+bytes_read,1,1,fp) != 1) {
                    fprintf(stderr, "read() error\n");
                    exit(1);
                }
                bytes_read++;
                parse_banner4(out, buf, bytes_read);
                break;
            case 5:
                parse_banner4(out, buf, bytes_read);
                break;
            case 'm': /* FILEHEADER */
                //goto end;
                break;
            default:
                fprintf(stderr, "file corrupt: unknown type %u\n", type);
                goto end;
        }
        total_records++;
        if ((total_records & 0xFFFF) == 0)
            fprintf(stderr, "%s: %8llu\r", filename, total_records);
    }

end:
    if (buf)
        free(buf);
    if (fp)
        fclose(fp);
    return total_records;
}
Пример #15
0
static void parse_cmdline(int argc, char **argp)
{
	unsigned int i = 1;

	if(argc < 2) {
		show_usage(1);
	}

	if (!strcmp(argp[i], "-h")) {
		show_usage(0);
	}
	else if (!strcmp(argp[i], "-srq")) {
		command = COM_SRQ;
		i++;	
		if(argc != 5)
			show_usage(1); 
		parse_port(argp[i++]);
		parse_q(argp[i++]);
		parse_pt(argp[i++]);
	}
	else if (!strcmp(argp[i], "-sq")) {
		command = COM_SQ;
		i++;
		if(argc != 6)
			show_usage(1); 
		parse_port(argp[i++]);
		parse_q(argp[i++]);
		parse_mac(argp[i++], mac);
	}
	else if (!strcmp(argp[i], "-srp")) {
		command = COM_SRP;
		i++;
		if(argc != 4)
			show_usage(1); 
		parse_port(argp[i++]);
		parse_policy(argp[i++]);
	}
	else if (!strcmp(argp[i], "-srqw")) {
		command = COM_SRQW;
		i++;
		if(argc != 5)
			show_usage(1); 
		parse_port(argp[i++]);
		parse_q(argp[i++]);
		parse_hex_val(argp[i++], &weight);
	}
    	else if (!strcmp(argp[i], "-stp")) {
        	command = COM_STP;
        	i++;
        	if(argc != 6)
            		show_usage(1);
		parse_port(argp[i++]);
        	parse_q(argp[i++]);
		parse_hex_val(argp[i++], &weight);
		parse_policy(argp[i++]);
    	}
    	else if (!strcmp(argp[i], "-fprs")) {
        	command = COM_IP_RULE_SET;
        	i++;
        	if(argc != 8)
            		show_usage(1);
		parse_dec_val(argp[i++], &inport);
        	parse_dec_val(argp[i++], &outport);
		parse_ip(argp[i++], &dip);
		parse_ip(argp[i++], &sip);
        	parse_mac(argp[i++], da);
		parse_mac(argp[i++], sa);
    	}
	else if (!strcmp(argp[i], "-fprd")) {
		command = COM_IP_RULE_DEL;
		i++;
		if(argc != 4)
			show_usage(1);
		parse_ip(argp[i++], &dip);
		parse_ip(argp[i++], &sip);
	}
	else if (!strcmp(argp[i], "-fp_st")) {
		command = COM_NFP_STATUS;
		if(argc != 2)
			show_usage(1);
	}
	else if (!strcmp(argp[i], "-fp_print")) {
		command = COM_NFP_PRINT;
		i++;
		if (argc != 3)
			show_usage(1);
		parse_db_name(argp[i++]);
	}
    	else if (!strcmp(argp[i], "-txdone")) {
        	command = COM_TXDONE_Q;
        	i++;
		if(argc != 3)
			show_usage(1);
        	parse_dec_val(argp[i++], &value);
    	}
    	else if (!strcmp(argp[i], "-txen")) {
                command = COM_TX_EN;
                i++;
		if(argc != 4)
			show_usage(1);
		parse_port(argp[i++]);
                parse_dec_val(argp[i++], &value);
        }
	else if (!strcmp(argp[i], "-lro")) {
		command = COM_LRO;
		i++;
		if(argc != 4)
			show_usage(1);
		parse_port(argp[i++]);
		parse_dec_val(argp[i++], &value);
	}
	else if (!strcmp(argp[i], "-lro_desc")) {
		command = COM_LRO_DESC;
		i++;
		if(argc != 4)
			show_usage(1);
		parse_port(argp[i++]);
		parse_dec_val(argp[i++], &value);
	}
        else if (!strcmp(argp[i], "-reuse")) {
                command = COM_SKB_REUSE;
                i++;
		if(argc != 3)
			show_usage(1);
                parse_dec_val(argp[i++], &value);
        }
        else if (!strcmp(argp[i], "-recycle")) {
                command = COM_SKB_RECYCLE;
                i++;
                if(argc != 3)
                        show_usage(1);
                parse_dec_val(argp[i++], &value);
        }
        else if (!strcmp(argp[i], "-nfp")) {
                command = COM_NFP;
                i++;
                if(argc != 3)
                        show_usage(1);
                parse_dec_val(argp[i++], &value);
	}
	else if (!strcmp(argp[i], "-rxcoal")) {
        	command = COM_RX_COAL;
        	i++;
		if(argc != 4)
			show_usage(1);
        	parse_port(argp[i++]);
        	parse_dec_val(argp[i++], &value);
    	}
    	else if (!strcmp(argp[i], "-txcoal")) {
        	command = COM_TX_COAL;
        	i++;
		if(argc != 4)
			show_usage(1);
        	parse_port(argp[i++]);
        	parse_dec_val(argp[i++], &value);
    	}
        else if (!strcmp(argp[i], "-ejp")) {
                command = COM_EJP_MODE;
                i++;
                if(argc != 4)
                        show_usage(1);
                parse_port(argp[i++]);
                parse_dec_val(argp[i++], &value);
	}
        else if (!strcmp(argp[i], "-tos")) {
                command = COM_TOS_MAP;
                i++;
                if(argc != 5)
                        show_usage(1);
                parse_port(argp[i++]);
		parse_q(argp[i++]);
                parse_hex_val(argp[i++], &value);
        }
		else if (!strcmp(argp[i], "-tx_noq")) {
				command = COM_TX_NOQUEUE;
				i++;
				if(argc != 4)
						show_usage(1);
				parse_port(argp[i++]);
				parse_dec_val(argp[i++], &value);
	}
    	else if (!strcmp(argp[i], "-St")) {
        	command = COM_STS;
        	i++;
		if(argc < 4)
			show_usage(1);
		parse_status(argp[i++]);
		if( status == STS_PORT_Q ) {
            		if(argc != 5)
                		show_usage(1);
               		parse_q(argp[i++]);
	    	}
            	else if(argc != 4)
                	show_usage(1);
	
		parse_port(argp[i++]);
        }	
	else {
		show_usage(i++);
	}
}
Пример #16
0
int judge(run_param * run)
{
    //run_result result;
    char * temp_dir;
    //struct passwd *nobody= getpwnam("nobody");
    int pid, null_fd;
    int ret;
    int status;
    
    uid_t nobody_uid;
    gid_t nobody_gid;
    struct passwd *nobody;
    
    int input_fd, output_fd, code_fd;

    strcpy(TEMP_DIR, TEMP_DIR_TEMPLATE);
    temp_dir = mkdtemp(TEMP_DIR);
    if (temp_dir == NULL) {
        syslog(LOG_ERR, "err creating temp dir. %s", strerror(errno));
        return -1;
    }
    syslog(LOG_DEBUG, "temp_dir made %s.", TEMP_DIR);
    
    chdir(temp_dir);
    
    prepare_files(run, &input_fd, &output_fd, &code_fd);
    if (input_fd <0 || output_fd<0 || code_fd<0)
    {
        syslog(LOG_ERR, "file prepare failed. %s", strerror(errno));
    }
    syslog(LOG_DEBUG, "input_fd : %d", input_fd);
    syslog(LOG_DEBUG, "output_fd : %d", output_fd);

    ret = (int)write(code_fd, run->code, strlen(run->code));
    if (ret < 0) {
        syslog(LOG_ERR, "code write err. %s", strerror(errno));
        return -1;
    }
    close(code_fd);
    syslog(LOG_DEBUG, "compile_cmd %ld", compile_cmd[run->lang][0]);
    if (compile_cmd[run->lang][0]!= NULL) {
        //compile code
        pid = fork();
        if (pid < 0) {
            syslog(LOG_ERR,"judge compile fork error");
            return -1;
        }
        if (pid == 0) {
            ret = execvp(compile_cmd[run->lang][0],compile_cmd[run->lang]);
            if (ret < 0){
                syslog(LOG_ERR, "exec err: %s.\n", strerror(errno));
                exit(EXIT_FAILURE);
            }
        }
        else {
            waitpid(pid, &status, WUNTRACED | WCONTINUED);
            int cs = parse_status(status);
            syslog(LOG_DEBUG, "code compile status code:%d\n",cs);
        }

    }


    null_fd = open("/dev/null", O_RDWR);
    syslog(LOG_DEBUG, "null_fd : %d", null_fd);

    nobody = getpwnam("nobody");
    if (nobody == NULL) {
        syslog(LOG_ERR, "find user nobody failed.\n");
        exit(EXIT_FAILURE);
    }
    nobody_uid = nobody->pw_uid;
    nobody_gid = nobody->pw_gid;

    //char *argv[] = {"python", "main.py", NULL};
    //ret = execv("code", argv);
    //syslog(LOG_ERR, "run code error.\n");
    //ret = execvp(run_cmd[run->lang][0], run_cmd[run->lang]);
    //ret = execvp("python", argv);
    //ret = execvp(run_cmd[run->lang][0], run_cmd[run->lang]);

    pid = fork();
    if (pid < 0) {
        syslog(LOG_ERR,"judge fork error");
        return -1;
    }
    if (pid == 0) {
        //child
        /*ret = chroot(temp_dir);
        if (ret < 0) {
            syslog(LOG_ERR, "chroot failed. %s", strerror(errno));
            exit(EXIT_FAILURE);
        }
        chdir("/");*/
        
        dup2(null_fd, STDERR_FILENO);
        dup2(input_fd, STDIN_FILENO);
        dup2(output_fd, STDOUT_FILENO);
        syslog(LOG_DEBUG, "start ptrace");
        setuid(nobody_uid);
        setgid(nobody_gid);

        ret = (int) ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        if (ret < 0){
            syslog(LOG_ERR, "Error initiating ptrace");
        }
        //char *argv[] = {NULL};
        //ret = execvp("./main", argv);
        execvp(run_cmd[run->lang][0], run_cmd[run->lang]);
        syslog(LOG_ERR, "run code error.\n");
        //ret = execvp(run_cmd[run->lang][0], run_cmd[run->lang]);
    }
    else if (pid > 0){
        //parent


        struct rusage usage;
        syslog(LOG_DEBUG, "start watching");
        while(1) { //listening
            wait4(pid, &status, WUNTRACED | WCONTINUED, &usage);
            int cs = parse_status(status);
            //int time = tv2ms(usage.ru_utime) + tv2ms(usage.ru_stime);
            //long memory_now = usage.ru_minflt * (getpagesize() >> 10);
            //if (memory_now > memory_max)
            //    memory_max = memory_now;
            /*if ((time > timeLimit) || timeout_killed) {
                printf("Time Limit Exceeded\n");
                ptrace(PTRACE_KILL, child_pid, NULL, NULL);
                return TLE;
            }
            if (memory_max > memoryLimit) {
                printf("Memory Limit Exceeded\n");
                ptrace(PTRACE_KILL, child_pid, NULL, NULL);
                return MLE;
            }*/
            if (cs == PS_EXIT_ERROR) { //exited
                //printf("%d %dms %ldKiB\n", WEXITSTATUS(status), time, memory_max);
                syslog(LOG_DEBUG, "program exited error.\n");
                return FIN;
            }
            if (cs == PS_SYSCALL) {
                ret = syscall_checker(pid);
                if (ret == SS_FORBIDDEN) {
                    syslog(LOG_INFO, "forbid syscall");
                    ptrace(PTRACE_KILL, pid, NULL, NULL);
                    return RE;
                }
            }
            if (cs == PS_EXIT_SUCCESS) {
                syslog(LOG_DEBUG, "program exited successfully.\n");
                return FIN;
            }

            ret = (int) ptrace(PTRACE_SYSCALL, pid, NULL, NULL);
            if (ret < -1) {
                syslog(LOG_ERR, "Trace again failed.\n");
                return RE;
            }
        }
    }
    
    return 0;
}
Пример #17
0
void *handle_tcp_client(void *arg) {
    printf("SERVER: client thread started\n");
    
    struct thread_arg *thread_data = (struct thread_arg *)arg;

    int client_socket = thread_data->client_socket;
    int idx = thread_data->thread_idx;
    
    free(arg); /* malloc was made before starting this thread */
    char command[RCVBUFSIZE];      /* Buffer for square string */
    char response[RCVBUFSIZE];
    int recv_msg_size;                    /* Size of received message */
    
    all_sockets[idx] = client_socket;
    int is_joined = 0;
    
    
    while (!shutdown_server) {
        
        /* Receive message from client */
        command[0] = '\0';
        recv_msg_size = recv(client_socket, command, RCVBUFSIZE - 1, 0);
        command[recv_msg_size] = '\0';
        
        if (recv_msg_size == 0) {
            /* zero indicates end of transmission */
            break;
        }
        
        printf("server recieved message: %s \n", command);
        
        if (shutdown_server) {
            break;
        }

        if (winner_established == 1) {
            say(all_sockets[idx], "END\n", 0);
            continue;
        }
        
        if(strncasecmp(command, "HELLO\n", 5) == 0)
        {
            if (is_joined) {
                //already joined, so skip this
                say(all_sockets[idx], "ALREADY JOINED DUMMY\n", 0);
                continue;
            }
            
            int field_size = size_callback();
            sprintf(response, "SIZE %i \n", field_size);
            say(all_sockets[idx], response, 0);
            
            if (join_callback() == 0) {
                
                is_joined = 1;
                say(all_sockets[idx], "START\n", 1);
                
            }else{
                say(all_sockets[idx], "NACK\n", 1);
            }
            
        }else if (strncasecmp(command, "SHUTDOWN\n", 7) == 0)
        {
            stopserver();
            break;
            
        }else if (strncasecmp(command, "TAKE", 4)== 0)
        {
            int coords[2];
            char name[1000];
            
            parse_take(command, coords, name);
            int success = take_callback(coords[0], coords[1], idx);
            if  (success == 1) {
                strcpy(all_names[idx], name);
                say(all_sockets[idx], "TAKEN \n", 1);
            }else {
                say(all_sockets[idx], "INUSE \n", 1);
            }
                        
        }else if (strncasecmp(command, "STATUS", 6)== 0)
        {
            int coords[2];
            parse_status(command, coords);
            
            int player_id = status_callback(coords[0], coords[1]);
            say(all_sockets[idx], all_names[player_id], 1);

        }
        
        command[recv_msg_size] = '\0';
   
    }
    if (all_sockets[idx] > 0) {
        close(client_socket);    /* Close client socket */
        all_sockets[idx] = 0;
    }
    
    return NULL;
}
Пример #18
0
static gpgme_error_t
status_handler(void *opaque, int fd)
{
    gpg_error_t assuan_err;
    gpgme_error_t err = 0;
    engine_gpgsm_t gpgsm = opaque;
    char *line;
    size_t linelen;

    do
    {
        assuan_err = assuan_read_line(gpgsm->assuan_ctx, &line, &linelen);
        if(assuan_err)
        {
            /* Try our best to terminate the connection friendly.  */
            /*	  assuan_write_line (gpgsm->assuan_ctx, "BYE"); */
            err = map_assuan_error(assuan_err);
            DEBUG3("fd %d: error from assuan (%d) getting status line : %s \n",
                   fd, assuan_err, gpg_strerror(err));
        }
        else if(linelen >= 3
                && line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
                && (line[3] == '\0' || line[3] == ' '))
        {
            if(line[3] == ' ')
                err = map_assuan_error(atoi(&line[4]));
            else
                err = gpg_error(GPG_ERR_GENERAL);
            DEBUG2("fd %d: ERR line - mapped to: %s\n",
                   fd, err ? gpg_strerror(err) : "ok");
        }
        else if(linelen >= 2
                && line[0] == 'O' && line[1] == 'K'
                && (line[2] == '\0' || line[2] == ' '))
        {
            if(gpgsm->status.fnc)
                err = gpgsm->status.fnc(gpgsm->status.fnc_value,
                                        GPGME_STATUS_EOF, "");

            if(!err && gpgsm->colon.fnc && gpgsm->colon.any)
            {
                /* We must tell a colon function about the EOF. We do
                   this only when we have seen any data lines.  Note
                   that this inlined use of colon data lines will
                   eventually be changed into using a regular data
                   channel. */
                gpgsm->colon.any = 0;
                err = gpgsm->colon.fnc(gpgsm->colon.fnc_value, NULL);
            }
            _gpgme_io_close(gpgsm->status_cb.fd);
            DEBUG2("fd %d: OK line - final status: %s\n",
                   fd, err ? gpg_strerror(err) : "ok");
            return err;
        }
        else if(linelen > 2
                && line[0] == 'D' && line[1] == ' '
                && gpgsm->colon.fnc)
        {
            /* We are using the colon handler even for plain inline data
                   - strange name for that function but for historic reasons
                   we keep it.  */
            /* FIXME We can't use this for binary data because we
               assume this is a string.  For the current usage of colon
               output it is correct.  */
            char *src = line + 2;
            char *end = line + linelen;
            char *dst;
            char **aline = &gpgsm->colon.attic.line;
            int *alinelen = &gpgsm->colon.attic.linelen;

            if(gpgsm->colon.attic.linesize
                    < *alinelen + linelen + 1)
            {
                char *newline = realloc(*aline, *alinelen + linelen + 1);
                if(!newline)
                    err = gpg_error_from_errno(errno);
                else
                {
                    *aline = newline;
                    gpgsm->colon.attic.linesize += linelen + 1;
                }
            }
            if(!err)
            {
                dst = *aline + *alinelen;

                while(!err && src < end)
                {
                    if(*src == '%' && src + 2 < end)
                    {
                        /* Handle escaped characters.  */
                        ++src;
                        *dst = _gpgme_hextobyte(src);
                        (*alinelen)++;
                        src += 2;
                    }
                    else
                    {
                        *dst = *src++;
                        (*alinelen)++;
                    }

                    if(*dst == '\n')
                    {
                        /* Terminate the pending line, pass it to the colon
                        handler and reset it.  */

                        gpgsm->colon.any = 1;
                        if(*alinelen > 1 && *(dst - 1) == '\r')
                            dst--;
                        *dst = '\0';

                        /* FIXME How should we handle the return code?  */
                        err = gpgsm->colon.fnc(gpgsm->colon.fnc_value, *aline);
                        if(!err)
                        {
                            dst = *aline;
                            *alinelen = 0;
                        }
                    }
                    else
                        dst++;
                }
            }
            DEBUG2("fd %d: D line; final status: %s\n",
                   fd, err ? gpg_strerror(err) : "ok");
        }
        else if(linelen > 2
                && line[0] == 'S' && line[1] == ' ')
        {
            char *rest;
            gpgme_status_code_t r;

            rest = strchr(line + 2, ' ');
            if(!rest)
                rest = line + linelen; /* set to an empty string */
            else
                *(rest++) = 0;

            r = parse_status(line + 2);

            if(r >= 0)
            {
                if(gpgsm->status.fnc)
                    err = gpgsm->status.fnc(gpgsm->status.fnc_value, r, rest);
            }
            else
                fprintf(stderr, "[UNKNOWN STATUS]%s %s", line + 2, rest);
            DEBUG3("fd %d: S line (%s) - final status: %s\n",
                   fd, line + 2, err ? gpg_strerror(err) : "ok");
        }
    }
    while(!err && assuan_pending_line(gpgsm->assuan_ctx));

    return err;
}
Пример #19
0
static bool parse_line_v1 (RuleSet* rs, const char* line)
{
	if (0 == strcmp (line, "forward-unmatched")) {
		rs->forward_unmatched = true;
		return true;
	}

	if (0 == strcmp (line, "match-all")) {
		rs->match_all = true;
		return true;
	}

	Rule r;
	clear_rule (&r);

	char *tmp, *fre, *prt;
	int i = 0;
	bool in_match = true;
	tmp = fre = strdup (line);
	for (prt = strtok (tmp, " "); prt; prt = strtok (NULL, " "), ++i) {
		bool rv;
		if (prt[0] == '#') {
			break;
		}
		if (0 == strcmp (prt, "|")) {
			if (i == 0 || !in_match) {
				i = -1;
				break;
			}
			in_match = false;
			r.len = i;
			i = -1; // continue bumps it
			continue;
		}
		if (i >= MAX_MSG) {
			i = -1;
			break;
		}

		if (in_match) {
			switch (i) {
				case 0:
					rv = parse_status (&r, prt);
					break;
				case 1:
					r.match[i] = parse_note (prt); // TODO IFF note-status..
					if (r.match[i] < 128) {
						r.mask[i] = 0x7f;
						rv = true;
						break;
					}
					// no break - fall through
				default:
					rv = parse_match (&r, i, prt);
					break;
			}
		} else {
			switch (i) {
				case 1:
					r.tx_set[i] = parse_note (prt); // TODO IFF note-status..
					if (r.tx_set[i] < 128) {
						r.tx_mask[i] = 0x00;
						rv = true;
						break;
					}
					// no break - fall through
				default:
					rv = parse_replacement (&r, i, prt);
					break;
			}
		}

		if (!rv) {
			i = -1;
			break;
		}
	}

	r.tx_len = i;

	free (fre);
	if (r.tx_len < 1 || r.tx_len > MAX_MSG || r.len < 1 || r.len > MAX_MSG || in_match) {
		return false;
	}

	add_rule (rs, &r);
	return true;
}
Пример #20
0
/* ------------------------------------------------------------------------
@NAME       : bt_parse_entry()
@INPUT      : infile  - file to read next entry from
              options - standard btparse options bitmap
@OUTPUT     : *top    - AST for the entry, or NULL if no entries left in file
@RETURNS    : same as bt_parse_entry_s()
@DESCRIPTION: Starts (or continues) parsing from a file.
@GLOBALS    : 
@CALLS      : 
@CREATED    : Jan 1997, GPW
@MODIFIED   : 
-------------------------------------------------------------------------- */
AST * bt_parse_entry (FILE *    infile,
                      char *    filename,
                      ushort    options,
                      boolean * status)
{
   AST *         entry_ast = NULL;
   static int *  err_counts = NULL;
   static FILE * prev_file = NULL;

   if (prev_file != NULL && infile != prev_file)
   {
      usage_error ("bt_parse_entry: you can't interleave calls "
                   "across different files");
   }

   if (options & BTO_STRINGMASK)        /* any string options set? */
   {
      usage_error ("bt_parse_entry: illegal options "
                   "(string options not allowed)");
   }

   InputFilename = filename;
   err_counts = bt_get_error_counts (err_counts);

   if (feof (infile))
   {
      if (prev_file != NULL)            /* haven't already done the cleanup */
      {
         prev_file = NULL;
         finish_parse (&err_counts);
      }
      else
      {
         usage_warning ("bt_parse_entry: second attempt to read past eof");
      }

      if (status) *status = TRUE;
      return NULL;
   }

   /* 
    * Here we do some nasty poking about the innards of PCCTS in order to
    * enter the parser multiple times on the same input stream.  This code
    * comes from expanding the macro invokation:
    * 
    *    ANTLR (entry (top), infile);  
    * 
    * When LL_K, ZZINF_LOOK, and DEMAND_LOOK are all undefined, this
    * ultimately expands to
    * 
    *    zzbufsize = ZZLEXBUFSIZE;
    *    {
    *       static char zztoktext[ZZLEXBUFSIZE];
    *       zzlextext = zztoktext; 
    *       zzrdstream (f);
    *       zzgettok();
    *    }
    *    entry (top);
    *    ++zzasp;
    * 
    * (I'm expanding hte zzenterANTLR, zzleaveANTLR, and zzPrimateLookAhead
    * macros, but leaving ZZLEXBUFSIZE -- a simple constant -- alone.)
    * 
    * There are two problems with this: 1) zztoktext is a statically
    * allocated buffer, and when it overflows we just ignore further
    * characters that should belong to that lexeme; and 2) zzrdstream() and
    * zzgettok() are called every time we enter the parser, which means the
    * token left over from the previous entry will be discarded when we
    * parse entries 2 .. N.
    * 
    * I handle the static buffer problem with alloc_lex_buffer() and
    * realloc_lex_buffer() (in lex_auxiliary.c), and by rewriting the ZZCOPY
    * macro to call realloc_lex_buffer() when overflow is detected.
    * 
    * I handle the extra token-read by hanging on to a static file
    * pointer, prev_file, between calls to bt_parse_entry() -- when
    * the program starts it is NULL, and we reset it to NULL on
    * finishing a file.  Thus, any call that is the first on a given
    * file will allocate the lexical buffer and read the first token;
    * thereafter, we skip those steps, and free the buffer on reaching
    * end-of-file.  Currently, this method precludes interleaving
    * calls to bt_parse_entry() on different files -- perhaps I could
    * fix this with the zz{save,restore}_{antlr,dlg}_state()
    * functions?
    */

   zzast_sp = ZZAST_STACKSIZE;          /* workaround apparent pccts bug */

#if defined(LL_K) || defined(ZZINF_LOOK) || defined(DEMAND_LOOK)
# error One of LL_K, ZZINF_LOOK, or DEMAND_LOOK was defined
#endif
   if (prev_file == NULL)               /* only read from input stream if */
   {                                    /* starting afresh with a file */
      start_parse (infile, NULL, 0);
      prev_file = infile;
   }
   assert (prev_file == infile);

   entry (&entry_ast);                  /* enter the parser */
   ++zzasp;                             /* why is this done? */

   if (entry_ast == NULL)               /* can happen with very bad input */
   {
      if (status) *status = FALSE;
      return entry_ast;
   }

#if DEBUG
   dump_ast ("bt_parse_entry(): single entry, after parsing:\n", 
             entry_ast);
#endif
   bt_postprocess_entry (entry_ast,
                         StringOptions[entry_ast->metatype] | options);
#if DEBUG
   dump_ast ("bt_parse_entry(): single entry, after post-processing:\n", 
             entry_ast);
#endif

   if (status) *status = parse_status (err_counts);
   return entry_ast;

} /* bt_parse_entry() */