Exemplo n.º 1
0
URL::URL(const std::string& scheme, const std::string& host, const std::string& path, const std::string& query, const std::string& fragment)
{
    parse(scheme + "://" + host + path + "?" + query + "#" + fragment);
}
Exemplo n.º 2
0
TodoList::TodoList() {
  path = std::string(getenv("HOME")) + "/todo.txt";
  parse();
}
Exemplo n.º 3
0
int
main(int argc, char **argv)
{

    extern int found_err;	/* flag set in diag() on error */
    int     dec_ind;	/* current indentation for declarations */
    int     di_stack[20];	/* a stack of structure indentation levels */
    int     flushed_nl;	/* used when buffering up comments to remember
				 * that a newline was passed over */
    int     force_nl;	/* when true, code must be broken */
    int     hd_type;	/* used to store type of stmt for if (...),
				 * for (...), etc */
    int     i;		/* local loop counter */
    int     scase;		/* set to true when we see a case, so we will
				 * know what to do with the following colon */
    int     sp_sw;		/* when true, we are in the expressin of
				 * if(...), while(...), etc. */
    int     squest;		/* when this is positive, we have seen a ?
				 * without the matching : in a <c>?<s>:<s>
				 * construct */
    const char *t_ptr;	/* used for copying tokens */
    int	tabs_to_var = 0; /* true if using tabs to indent to var name */
    int     type_code;	/* the type of token, returned by lexi */

    int     last_else = 0;	/* true iff last keyword was an else */


    /*-----------------------------------------------*\
        |		      INITIALIZATION		      |
        \*-----------------------------------------------*/

    if (!setlocale(LC_ALL, ""))
        warnx("can't set locale.");

    hd_type = 0;
    ps.p_stack[0] = stmt;	/* this is the parser's stack */
    ps.last_nl = true;	/* this is true if the last thing scanned was
				 * a newline */
    ps.last_token = semicolon;
    combuf = (char *) malloc(bufsize);
    labbuf = (char *) malloc(bufsize);
    codebuf = (char *) malloc(bufsize);
    tokenbuf = (char *) malloc(bufsize);
    l_com = combuf + bufsize - 5;
    l_lab = labbuf + bufsize - 5;
    l_code = codebuf + bufsize - 5;
    l_token = tokenbuf + bufsize - 5;
    combuf[0] = codebuf[0] = labbuf[0] = ' ';	/* set up code, label,
							 * and comment buffers */
    combuf[1] = codebuf[1] = labbuf[1] = '\0';
    ps.else_if = 1;		/* Default else-if special processing to on */
    s_lab = e_lab = labbuf + 1;
    s_code = e_code = codebuf + 1;
    s_com = e_com = combuf + 1;
    s_token = e_token = tokenbuf + 1;

    in_buffer = (char *) malloc(10);
    in_buffer_limit = in_buffer + 8;
    buf_ptr = buf_end = in_buffer;
    line_no = 1;
    had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
    sp_sw = force_nl = false;
    ps.in_or_st = false;
    ps.bl_line = true;
    dec_ind = 0;
    di_stack[ps.dec_nest = 0] = 0;
    ps.want_blank = ps.in_stmt = ps.ind_stmt = false;


    scase = ps.pcase = false;
    squest = 0;
    sc_end = 0;
    bp_save = 0;
    be_save = 0;

    output = 0;



    /*--------------------------------------------------*\
        |   		COMMAND LINE SCAN		 |
        \*--------------------------------------------------*/

#ifdef undef
    max_col = 78;		/* -l78 */
    lineup_to_parens = 1;	/* -lp */
    ps.ljust_decl = 0;	/* -ndj */
    ps.com_ind = 33;	/* -c33 */
    star_comment_cont = 1;	/* -sc */
    ps.ind_size = 8;	/* -i8 */
    verbose = 0;
    ps.decl_indent = 16;	/* -di16 */
    ps.indent_parameters = 1;	/* -ip */
    ps.decl_com_ind = 0;	/* if this is not set to some positive value
				 * by an arg, we will set this equal to
				 * ps.com_ind */
    btype_2 = 1;		/* -br */
    cuddle_else = 1;	/* -ce */
    ps.unindent_displace = 0;	/* -d0 */
    ps.case_indent = 0;	/* -cli0 */
    format_col1_comments = 1;	/* -fc1 */
    procnames_start_line = 1;	/* -psl */
    proc_calls_space = 0;	/* -npcs */
    comment_delimiter_on_blankline = 1;	/* -cdb */
    ps.leave_comma = 1;	/* -nbc */
#endif

    for (i = 1; i < argc; ++i)
        if (strcmp(argv[i], "-npro") == 0)
            break;
    set_defaults();
    if (i >= argc)
        set_profile();

    for (i = 1; i < argc; ++i) {

        /*
         * look thru args (if any) for changes to defaults
         */
        if (argv[i][0] != '-') {	/* no flag on parameter */
            if (input == 0) {	/* we must have the input file */
                in_name = argv[i];	/* remember name of
							 * input file */
                input = fopen(in_name, "r");
                if (input == 0)	/* check for open error */
                    err(1, "%s", in_name);
                continue;
            } else if (output == 0) {
                /* we have the output
                			 * file */
                out_name = argv[i];	/* remember name of
								 * output file */
                if (strcmp(in_name, out_name) == 0) {
                    /* attempt to overwrite
                    					 * the file */
                    errx(1, "input and output files must be different");
                }
                output = fopen(out_name, "w");
                if (output == 0)	/* check for create
								 * error */
                    err(1, "%s", out_name);
                continue;
            }
            errx(1, "unknown parameter: %s", argv[i]);
        } else
            set_option(argv[i]);
    }			/* end of for */
    if (input == 0) {
        input = stdin;
    }
    if (output == 0) {
        if (troff || input == stdin)
            output = stdout;
        else {
            out_name = in_name;
            bakcopy();
        }
    }
    if (ps.com_ind <= 1)
        ps.com_ind = 2;	/* don't put normal comments before column 2 */
    if (troff) {
        if (bodyf.font[0] == 0)
            parsefont(&bodyf, "R");
        if (scomf.font[0] == 0)
            parsefont(&scomf, "I");
        if (blkcomf.font[0] == 0)
            blkcomf = scomf, blkcomf.size += 2;
        if (boxcomf.font[0] == 0)
            boxcomf = blkcomf;
        if (stringf.font[0] == 0)
            parsefont(&stringf, "L");
        if (keywordf.font[0] == 0)
            parsefont(&keywordf, "B");
        writefdef(&bodyf, 'B');
        writefdef(&scomf, 'C');
        writefdef(&blkcomf, 'L');
        writefdef(&boxcomf, 'X');
        writefdef(&stringf, 'S');
        writefdef(&keywordf, 'K');
    }
    if (block_comment_max_col <= 0)
        block_comment_max_col = max_col;
    if (ps.decl_com_ind <= 0)	/* if not specified by user, set this */
        ps.decl_com_ind = ps.ljust_decl ? (ps.com_ind <= 10 ? 2 : ps.com_ind - 8) : ps.com_ind;
    if (continuation_indent == 0)
        continuation_indent = ps.ind_size;
    fill_buffer();		/* get first batch of stuff into input buffer */

    parse(semicolon);
    {
        char   *p = buf_ptr;
        int     col = 1;

        while (1) {
            if (*p == ' ')
                col++;
            else if (*p == '\t')
                col = ((col - 1) & ~7) + 9;
            else
                break;
            p++;
        }
        if (col > ps.ind_size)
            ps.ind_level = ps.i_l_follow = col / ps.ind_size;
    }
    if (troff) {
        const char   *p = in_name, *beg = in_name;

        while (*p)
            if (*p++ == '/')
                beg = p;
        fprintf(output, ".Fn \"%s\"\n", beg);
    }
    /*
         * START OF MAIN LOOP
         */

    while (1) {
        /* this is the main loop.  it will go until we
        			 * reach eof */
        int     is_procname;

        type_code = lexi();	/* lexi reads one token.  The actual
					 * characters read are stored in
					 * "token". lexi returns a code
					 * indicating the type of token */
        is_procname = ps.procname[0];

        /*
         * The following code moves everything following an if (), while (),
         * else, etc. up to the start of the following stmt to a buffer. This
         * allows proper handling of both kinds of brace placement.
         */

        flushed_nl = false;
        while (ps.search_brace) {
            /* if we scanned an if(),
            				 * while(), etc., we might
            				 * need to copy stuff into a
            				 * buffer we must loop,
            				 * copying stuff into
            				 * save_com, until we find the
            				 * start of the stmt which
            				 * follows the if, or whatever */
            switch (type_code) {
            case newline:
                ++line_no;
                flushed_nl = true;
            case form_feed:
                break;	/* form feeds and newlines found here
					 * will be ignored */

            case lbrace:	/* this is a brace that starts the
					 * compound stmt */
                if (sc_end == 0) {
                    /* ignore buffering if a
                    			 * comment wasn't stored
                    			 * up */
                    ps.search_brace = false;
                    goto check_type;
                }
                if (btype_2) {
                    save_com[0] = '{';	/* we either want to put
								 * the brace right after
								 * the if */
                    goto sw_buffer;	/* go to common code to
							 * get out of this loop */
                }
            case comment:	/* we have a comment, so we must copy
					 * it into the buffer */
                if (!flushed_nl || sc_end != 0) {
                    if (sc_end == 0) {
                        /* if this is the first
                        			 * comment, we must set
                        			 * up the buffer */
                        save_com[0] = save_com[1] = ' ';
                        sc_end = &(save_com[2]);
                    } else {
                        *sc_end++ = '\n';	/* add newline between
									 * comments */
                        *sc_end++ = ' ';
                        --line_no;
                    }
                    *sc_end++ = '/';	/* copy in start of
								 * comment */
                    *sc_end++ = '*';

                    for (;;) {
                        /* loop until we get to
                        		 * the end of the
                        		 * comment */
                        *sc_end = *buf_ptr++;
                        if (buf_ptr >= buf_end)
                            fill_buffer();

                        if (*sc_end++ == '*' && *buf_ptr == '/')
                            break;	/* we are at end of
								 * comment */

                        if (sc_end >= &(save_com[sc_size])) {
                            /* check for temp buffer
                            					 * overflow */
                            diag(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever.");
                            fflush(output);
                            exit(1);
                        }
                    }
                    *sc_end++ = '/';	/* add ending slash */
                    if (++buf_ptr >= buf_end)	/* get past / in buffer */
                        fill_buffer();
                    break;
                }
            default:	/* it is the start of a normal
					 * statment */
                if (flushed_nl)	/* if we flushed a newline,
						 * make sure it is put back */
                    force_nl = true;
                if ((type_code == sp_paren && *token == 'i'
                        && last_else && ps.else_if) ||
                        (type_code == sp_nparen && *token == 'e'
                         && e_code != s_code && e_code[-1] == '}'))
                    force_nl = false;

                if (sc_end == 0) {
                    /* ignore buffering if
                    			 * comment wasn't saved
                    			 * up */
                    ps.search_brace = false;
                    goto check_type;
                }
                if (force_nl) {
                    /* if we should insert a nl
                    		 * here, put it into the
                    		 * buffer */
                    force_nl = false;
                    --line_no;	/* this will be
							 * re-increased when the
							 * nl is read from the
							 * buffer */
                    *sc_end++ = '\n';
                    *sc_end++ = ' ';
                    if (verbose && !flushed_nl)	/* print error msg if
									 * the line was not
									 * already broken */
                        diag(0, "Line broken");
                    flushed_nl = false;
                }
                for (t_ptr = token; *t_ptr; ++t_ptr)
                    *sc_end++ = *t_ptr;	/* copy token into temp
								 * buffer */
                ps.procname[0] = 0;

sw_buffer:
                ps.search_brace = false;	/* stop looking for
								 * start of stmt */
                bp_save = buf_ptr;	/* save current input
							 * buffer */
                be_save = buf_end;
                buf_ptr = save_com;	/* fix so that
							 * subsequent calls to
							 * lexi will take tokens
							 * out of save_com */
                *sc_end++ = ' ';	/* add trailing blank,
							 * just in case */
                buf_end = sc_end;
                sc_end = 0;
                break;
            }	/* end of switch */
            if (type_code != 0)	/* we must make this check,
						 * just in case there was an
						 * unexpected EOF */
                type_code = lexi();	/* read another token */
            /* if (ps.search_brace) ps.procname[0] = 0; */
            if ((is_procname = ps.procname[0]) && flushed_nl
                    && !procnames_start_line && ps.in_decl
                    && type_code == ident)
                flushed_nl = 0;
        }		/* end of while (search_brace) */
        last_else = 0;
check_type:
        if (type_code == 0) {	/* we got eof */
            if (s_lab != e_lab || s_code != e_code
                    || s_com != e_com)	/* must dump end of line */
                dump_line();
            if (ps.tos > 1)	/* check for balanced braces */
                diag(1, "Stuff missing from end of file.");

            if (verbose) {
                printf("There were %d output lines and %d comments\n",
                       ps.out_lines, ps.out_coms);
                printf("(Lines with comments)/(Lines with code): %6.3f\n",
                       (1.0 * ps.com_lines) / code_lines);
            }
            fflush(output);
            exit(found_err);
        }
        if (
            (type_code != comment) &&
            (type_code != newline) &&
            (type_code != preesc) &&
            (type_code != form_feed)) {
            if (force_nl &&
                    (type_code != semicolon) &&
                    (type_code != lbrace || !btype_2)) {
                /* we should force a broken line here */
                if (verbose && !flushed_nl)
                    diag(0, "Line broken");
                flushed_nl = false;
                dump_line();
                ps.want_blank = false;	/* don't insert blank at
							 * line start */
                force_nl = false;
            }
            ps.in_stmt = true;	/* turn on flag which causes
						 * an extra level of
						 * indentation. this is turned
						 * off by a ; or '}' */
            if (s_com != e_com) {
                /* the turkey has embedded a
                			 * comment in a line. fix it */
                *e_code++ = ' ';
                for (t_ptr = s_com; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;
                }
                *e_code++ = ' ';
                *e_code = '\0';	/* null terminate code sect */
                ps.want_blank = false;
                e_com = s_com;
            }
        } else if (type_code != comment)	/* preserve force_nl
							 * thru a comment */
            force_nl = false;	/* cancel forced newline
							 * after newline, form
							 * feed, etc */



        /*-----------------------------------------------------*\
        |	   do switch on type of token scanned		|
        \*-----------------------------------------------------*/
        CHECK_SIZE_CODE;
        switch (type_code) {
            /* now, decide what to do with the
            			 * token */

        case form_feed:/* found a form feed in line */
            ps.use_ff = true;	/* a form feed is treated much
						 * like a newline */
            dump_line();
            ps.want_blank = false;
            break;

        case newline:
            if (ps.last_token != comma || ps.p_l_follow > 0
                    || !ps.leave_comma || ps.block_init || !break_comma || s_com != e_com) {
                dump_line();
                ps.want_blank = false;
            }
            ++line_no;	/* keep track of input line number */
            break;

        case lparen:	/* got a '(' or '[' */
            ++ps.p_l_follow;	/* count parens to make Healy
						 * happy */
            if (ps.want_blank && *token != '[' &&
                    (ps.last_token != ident || proc_calls_space
                     || (ps.its_a_keyword && (!ps.sizeof_keyword || Bill_Shannon))))
                *e_code++ = ' ';
            if (ps.in_decl && !ps.block_init) {
                if (troff && !ps.dumped_decl_indent && !is_procname && ps.last_token == decl) {
                    ps.dumped_decl_indent = 1;
                    sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
                    e_code += strlen(e_code);
                } else {
                    while ((e_code - s_code) < dec_ind) {
                        CHECK_SIZE_CODE;
                        *e_code++ = ' ';
                    }
                    *e_code++ = token[0];
                }
            } else
                *e_code++ = token[0];
            ps.paren_indents[ps.p_l_follow - 1] = e_code - s_code;
            if (sp_sw && ps.p_l_follow == 1 && extra_expression_indent
                    && ps.paren_indents[0] < 2 * ps.ind_size)
                ps.paren_indents[0] = 2 * ps.ind_size;
            ps.want_blank = false;
            if (ps.in_or_st && *token == '(' && ps.tos <= 2) {
                /*
                 * this is a kluge to make sure that declarations will be
                 * aligned right if proc decl has an explicit type on it, i.e.
                 * "int a(x) {..."
                 */
                parse(semicolon);	/* I said this was a
							 * kluge... */
                ps.in_or_st = false;	/* turn off flag for
							 * structure decl or
							 * initialization */
            }
            if (ps.sizeof_keyword)
                ps.sizeof_mask |= 1 << ps.p_l_follow;
            break;

        case rparen:	/* got a ')' or ']' */
            rparen_count--;
            if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.sizeof_mask) {
                ps.last_u_d = true;
                ps.cast_mask &= (1 << ps.p_l_follow) - 1;
            }
            ps.sizeof_mask &= (1 << ps.p_l_follow) - 1;
            if (--ps.p_l_follow < 0) {
                ps.p_l_follow = 0;
                diag(0, "Extra %c", *token);
            }
            if (e_code == s_code)	/* if the paren starts the
						 * line */
                ps.paren_level = ps.p_l_follow;	/* then indent it */

            *e_code++ = token[0];
            ps.want_blank = true;

            if (sp_sw && (ps.p_l_follow == 0)) {
                /* check for end of if
                					 * (...), or some such */
                sp_sw = false;
                force_nl = true;	/* must force newline
							 * after if */
                ps.last_u_d = true;	/* inform lexi that a
							 * following operator is
							 * unary */
                ps.in_stmt = false;	/* don't use stmt
							 * continuation
							 * indentation */

                parse(hd_type);	/* let parser worry about if,
						 * or whatever */
            }
            ps.search_brace = btype_2;	/* this should insure
							 * that constructs such
							 * as main(){...} and
							 * int[]{...} have their
							 * braces put in the
							 * right place */
            break;

        case unary_op:	/* this could be any unary operation */
            if (ps.want_blank)
                *e_code++ = ' ';

            if (troff && !ps.dumped_decl_indent && ps.in_decl && !is_procname) {
                sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
                ps.dumped_decl_indent = 1;
                e_code += strlen(e_code);
            } else {
                const char *res = token;

                if (ps.in_decl && !ps.block_init) {
                    /* if this is a unary op
                    					 * in a declaration, we
                    					 * should indent this
                    					 * token */
                    for (i = 0; token[i]; ++i);	/* find length of token */
                    while ((e_code - s_code) < (dec_ind - i)) {
                        CHECK_SIZE_CODE;
                        *e_code++ = ' ';	/* pad it */
                    }
                }
                if (troff && token[0] == '-' && token[1] == '>')
                    res = "\\(->";
                for (t_ptr = res; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;
                }
            }
            ps.want_blank = false;
            break;

        case binary_op:/* any binary operation */
            if (ps.want_blank)
                *e_code++ = ' ';
            {
                const char *res = token;

                if (troff)
                    switch (token[0]) {
                    case '<':
                        if (token[1] == '=')
                            res = "\\(<=";
                        break;
                    case '>':
                        if (token[1] == '=')
                            res = "\\(>=";
                        break;
                    case '!':
                        if (token[1] == '=')
                            res = "\\(!=";
                        break;
                    case '|':
                        if (token[1] == '|')
                            res = "\\(br\\(br";
                        else if (token[1] == 0)
                            res = "\\(br";
                        break;
                    }
                for (t_ptr = res; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;	/* move the operator */
                }
            }
            ps.want_blank = true;
            break;

        case postop:	/* got a trailing ++ or -- */
            *e_code++ = token[0];
            *e_code++ = token[1];
            ps.want_blank = true;
            break;

        case question:	/* got a ? */
            squest++;	/* this will be used when a later
					 * colon appears so we can distinguish
					 * the <c>?<n>:<n> construct */
            if (ps.want_blank)
                *e_code++ = ' ';
            *e_code++ = '?';
            ps.want_blank = true;
            break;

        case casestmt:	/* got word 'case' or 'default' */
            scase = true;	/* so we can process the later colon
					 * properly */
            goto copy_id;

        case colon:	/* got a ':' */
            if (squest > 0) {
                /* it is part of the <c>?<n>:
                			 * <n> construct */
                --squest;
                if (ps.want_blank)
                    *e_code++ = ' ';
                *e_code++ = ':';
                ps.want_blank = true;
                break;
            }
            if (ps.in_or_st) {
                *e_code++ = ':';
                ps.want_blank = false;
                break;
            }
            ps.in_stmt = false;	/* seeing a label does not
						 * imply we are in a stmt */
            for (t_ptr = s_code; *t_ptr; ++t_ptr)
                *e_lab++ = *t_ptr;	/* turn everything so
							 * far into a label */
            e_code = s_code;
            *e_lab++ = ':';
            *e_lab++ = ' ';
            *e_lab = '\0';

            force_nl = ps.pcase = scase;	/* ps.pcase will be used
							 * by dump_line to
							 * decide how to indent
							 * the label. force_nl
							 * will force a case n:
							 * to be on a line by
							 * itself */
            scase = false;
            ps.want_blank = false;
            break;

        case semicolon:/* got a ';' */
            ps.in_or_st = false;	/* we are not in an
						 * initialization or structure
						 * declaration */
            scase = false;	/* these will only need resetting in a
					 * error */
            squest = 0;
            if (ps.last_token == rparen && rparen_count == 0)
                ps.in_parameter_declaration = 0;
            ps.cast_mask = 0;
            ps.sizeof_mask = 0;
            ps.block_init = 0;
            ps.block_init_level = 0;
            ps.just_saw_decl--;

            if (ps.in_decl && s_code == e_code && !ps.block_init)
                while ((e_code - s_code) < (dec_ind - 1)) {
                    CHECK_SIZE_CODE;
                    *e_code++ = ' ';
                }

            ps.in_decl = (ps.dec_nest > 0);	/* if we were in a first
							 * level structure
							 * declaration, we
							 * aren't any more */

            if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) {

                /*
                 * This should be true iff there were unbalanced parens in the
                 * stmt.  It is a bit complicated, because the semicolon might
                 * be in a for stmt
                 */
                diag(1, "Unbalanced parens");
                ps.p_l_follow = 0;
                if (sp_sw) {
                    /* this is a check for a if,
                    		 * while, etc. with unbalanced
                    		 * parens */
                    sp_sw = false;
                    parse(hd_type);	/* don't lose the if,
							 * or whatever */
                }
            }
            *e_code++ = ';';
            ps.want_blank = true;
            ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in
								 * the middle of a stmt */

            if (!sp_sw) {	/* if not if for (;;) */
                parse(semicolon);	/* let parser know about
							 * end of stmt */
                force_nl = true;	/* force newline after a
							 * end of stmt */
            }
            break;

        case lbrace:	/* got a '{' */
            ps.in_stmt = false;	/* don't indent the {} */
            if (!ps.block_init)
                force_nl = true;	/* force other stuff on
							 * same line as '{' onto
							 * new line */
            else if (ps.block_init_level <= 0)
                ps.block_init_level = 1;
            else
                ps.block_init_level++;

            if (s_code != e_code && !ps.block_init) {
                if (!btype_2) {
                    dump_line();
                    ps.want_blank = false;
                } else if (ps.in_parameter_declaration && !ps.in_or_st) {
                    ps.i_l_follow = 0;
                    dump_line();
                    ps.want_blank = false;
                }
            }
            if (ps.in_parameter_declaration)
                prefix_blankline_requested = 0;

            if (ps.p_l_follow > 0) {
                /* check for preceding
                				 * unbalanced parens */
                diag(1, "Unbalanced parens");
                ps.p_l_follow = 0;
                if (sp_sw) {
                    /* check for unclosed if, for,
                    		 * etc. */
                    sp_sw = false;
                    parse(hd_type);
                    ps.ind_level = ps.i_l_follow;
                }
            }
            if (s_code == e_code)
                ps.ind_stmt = false;	/* don't put extra
							 * indentation on line
							 * with '{' */
            if (ps.in_decl && ps.in_or_st) {
                /* this is either a
                					 * structure declaration
                					 * or an init */
                di_stack[ps.dec_nest++] = dec_ind;
                /* ?		dec_ind = 0; */
            } else {
                ps.decl_on_line = false;	/* we can't be in the
								 * middle of a
								 * declaration, so don't
								 * do special
								 * indentation of
								 * comments */
                if (blanklines_after_declarations_at_proctop
                        && ps.in_parameter_declaration)
                    postfix_blankline_requested = 1;
                ps.in_parameter_declaration = 0;
            }
            dec_ind = 0;
            parse(lbrace);	/* let parser know about this */
            if (ps.want_blank)	/* put a blank before '{' if
						 * '{' is not at start of line */
                *e_code++ = ' ';
            ps.want_blank = false;
            *e_code++ = '{';
            ps.just_saw_decl = 0;
            break;

        case rbrace:	/* got a '}' */
            if (ps.p_stack[ps.tos] == decl && !ps.block_init)	/* semicolons can be
										 * omitted in
										 * declarations */
                parse(semicolon);
            if (ps.p_l_follow) {
                /* check for unclosed if, for,
                			 * else. */
                diag(1, "Unbalanced parens");
                ps.p_l_follow = 0;
                sp_sw = false;
            }
            ps.just_saw_decl = 0;
            ps.block_init_level--;
            if (s_code != e_code && !ps.block_init) {
                /* '}' must be first on
                						 * line */
                if (verbose)
                    diag(0, "Line broken");
                dump_line();
            }
            *e_code++ = '}';
            ps.want_blank = true;
            ps.in_stmt = ps.ind_stmt = false;
            if (ps.dec_nest > 0) {
                /* we are in multi-level
                			 * structure declaration */
                dec_ind = di_stack[--ps.dec_nest];
                if (ps.dec_nest == 0 && !ps.in_parameter_declaration)
                    ps.just_saw_decl = 2;
                ps.in_decl = true;
            }
            prefix_blankline_requested = 0;
            parse(rbrace);	/* let parser know about this */
            ps.search_brace = cuddle_else && ps.p_stack[ps.tos] == ifhead
                              && ps.il[ps.tos] >= ps.ind_level;
            if (ps.tos <= 1 && blanklines_after_procs && ps.dec_nest <= 0)
                postfix_blankline_requested = 1;
            break;

        case swstmt:	/* got keyword "switch" */
            sp_sw = true;
            hd_type = swstmt;	/* keep this for when we have
						 * seen the expression */
            goto copy_id;	/* go move the token into buffer */

        case sp_paren:	/* token is if, while, for */
            sp_sw = true;	/* the interesting stuff is done after
					 * the expression is scanned */
            hd_type = (*token == 'i' ? ifstmt :
                       (*token == 'w' ? whilestmt : forstmt));

            /*
                 * remember the type of header for later use by parser
                 */
            goto copy_id;	/* copy the token into line */

        case sp_nparen:/* got else, do */
            ps.in_stmt = false;
            if (*token == 'e') {
                if (e_code != s_code && (!cuddle_else || e_code[-1] != '}')) {
                    if (verbose)
                        diag(0, "Line broken");
                    dump_line();	/* make sure this starts
							 * a line */
                    ps.want_blank = false;
                }
                force_nl = true;	/* also, following stuff
							 * must go onto new line */
                last_else = 1;
                parse(elselit);
            } else {
                if (e_code != s_code) {
                    /* make sure this starts
                    			 * a line */
                    if (verbose)
                        diag(0, "Line broken");
                    dump_line();
                    ps.want_blank = false;
                }
                force_nl = true;	/* also, following stuff
							 * must go onto new line */
                last_else = 0;
                parse(dolit);
            }
            goto copy_id;	/* move the token into line */

        case decl:	/* we have a declaration type (int, register,
				 * etc.) */
            parse(decl);	/* let parser worry about indentation */
            if (ps.last_token == rparen && ps.tos <= 1) {
                ps.in_parameter_declaration = 1;
                if (s_code != e_code) {
                    dump_line();
                    ps.want_blank = 0;
                }
            }
            if (ps.in_parameter_declaration && ps.indent_parameters && ps.dec_nest == 0) {
                ps.ind_level = ps.i_l_follow = 1;
                ps.ind_stmt = 0;
            }
            ps.in_or_st = true;	/* this might be a structure
						 * or initialization
						 * declaration */
            ps.in_decl = ps.decl_on_line = true;
            if ( /* !ps.in_or_st && */ ps.dec_nest <= 0)
                ps.just_saw_decl = 2;
            prefix_blankline_requested = 0;
            for (i = 0; token[i++];);	/* get length of token */

            /*
                 * dec_ind = e_code - s_code + (ps.decl_indent>i ? ps.decl_indent
                 * : i);
                 */
            dec_ind = ps.decl_indent > 0 ? ps.decl_indent : i;
            tabs_to_var = (use_tabs ? ps.decl_indent > 0 : 0);
            goto copy_id;

        case ident:	/* got an identifier or constant */
            if (ps.in_decl) {
                /* if we are in a declaration,
                			 * we must indent identifier */
                if (ps.want_blank)
                    *e_code++ = ' ';
                ps.want_blank = false;
                if (is_procname == 0 || !procnames_start_line) {
                    if (!ps.block_init) {
                        if (troff && !ps.dumped_decl_indent) {
                            sprintf(e_code, "\n.De %dp+\200p\n", dec_ind * 7);
                            ps.dumped_decl_indent = 1;
                            e_code += strlen(e_code);
                            CHECK_SIZE_CODE;
                        } else {
                            int cur_dec_ind;
                            int pos, startpos;

                            /*
                             * in order to get the tab math right for
                             * indentations that are not multiples of 8 we
                             * need to modify both startpos and dec_ind
                             * (cur_dec_ind) here by eight minus the
                             * remainder of the current starting column
                             * divided by eight. This seems to be a
                             * properly working fix
                             */
                            startpos = e_code - s_code;
                            cur_dec_ind = dec_ind;
                            pos = startpos;
                            if ((ps.ind_level * ps.ind_size) % 8 != 0) {
                                pos += (ps.ind_level * ps.ind_size) % 8;
                                cur_dec_ind += (ps.ind_level * ps.ind_size) % 8;
                            }

                            if (tabs_to_var) {
                                while ((pos & ~7) + 8 <= cur_dec_ind) {
                                    CHECK_SIZE_CODE;
                                    *e_code++ = '\t';
                                    pos = (pos & ~7) + 8;
                                }
                            }
                            while (pos < cur_dec_ind) {
                                CHECK_SIZE_CODE;
                                *e_code++ = ' ';
                                pos++;
                            }
                            if (ps.want_blank && e_code - s_code == startpos)
                                *e_code++ = ' ';
                            ps.want_blank = false;
                        }
                    }
                } else {
                    if (dec_ind && s_code != e_code)
                        dump_line();
                    dec_ind = 0;
                    ps.want_blank = false;
                }
            } else if (sp_sw && ps.p_l_follow == 0) {
                sp_sw = false;
                force_nl = true;
                ps.last_u_d = true;
                ps.in_stmt = false;
                parse(hd_type);
            }
copy_id:
            if (ps.want_blank)
                *e_code++ = ' ';
            if (troff && ps.its_a_keyword) {
                e_code = chfont(&bodyf, &keywordf, e_code);
                for (t_ptr = token; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = keywordf.allcaps
                                ? toupper((unsigned char)*t_ptr)
                                : *t_ptr;
                }
                e_code = chfont(&keywordf, &bodyf, e_code);
            } else
                for (t_ptr = token; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;
                }
            ps.want_blank = true;
            break;

        case period:	/* treat a period kind of like a binary
				 * operation */
            *e_code++ = '.';	/* move the period into line */
            ps.want_blank = false;	/* don't put a blank after a
						 * period */
            break;

        case comma:
            ps.want_blank = (s_code != e_code);	/* only put blank after
								 * comma if comma does
								 * not start the line */
            if (ps.in_decl && is_procname == 0 && !ps.block_init)
                while ((e_code - s_code) < (dec_ind - 1)) {
                    CHECK_SIZE_CODE;
                    *e_code++ = ' ';
                }

            *e_code++ = ',';
            if (ps.p_l_follow == 0) {
                if (ps.block_init_level <= 0)
                    ps.block_init = 0;
                if (break_comma && (!ps.leave_comma || compute_code_target() + (e_code - s_code) > max_col - 8))
                    force_nl = true;
            }
            break;

        case preesc:	/* got the character '#' */
            if ((s_com != e_com) ||
                    (s_lab != e_lab) ||
                    (s_code != e_code))
                dump_line();
            *e_lab++ = '#';	/* move whole line to 'label' buffer */
            {
                int     in_comment = 0;
                int     com_start = 0;
                char    quote = 0;
                int     com_end = 0;

                while (*buf_ptr == ' ' || *buf_ptr == '\t') {
                    buf_ptr++;
                    if (buf_ptr >= buf_end)
                        fill_buffer();
                }
                while (*buf_ptr != '\n' || in_comment) {
                    CHECK_SIZE_LAB;
                    *e_lab = *buf_ptr++;
                    if (buf_ptr >= buf_end)
                        fill_buffer();
                    switch (*e_lab++) {
                    case BACKSLASH:
                        if (troff)
                            *e_lab++ = BACKSLASH;
                        if (!in_comment) {
                            *e_lab++ = *buf_ptr++;
                            if (buf_ptr >= buf_end)
                                fill_buffer();
                        }
                        break;
                    case '/':
                        if (*buf_ptr == '*' && !in_comment && !quote) {
                            in_comment = 1;
                            *e_lab++ = *buf_ptr++;
                            com_start = e_lab - s_lab - 2;
                        }
                        break;
                    case '"':
                        if (quote == '"')
                            quote = 0;
                        break;
                    case '\'':
                        if (quote == '\'')
                            quote = 0;
                        break;
                    case '*':
                        if (*buf_ptr == '/' && in_comment) {
                            in_comment = 0;
                            *e_lab++ = *buf_ptr++;
                            com_end = e_lab - s_lab;
                        }
                        break;
                    }
                }

                while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
                    e_lab--;
                if (e_lab - s_lab == com_end && bp_save == 0) {
                    /* comment on
                    						 * preprocessor line */
                    if (sc_end == 0)	/* if this is the first
								 * comment, we must set
								 * up the buffer */
                        sc_end = &(save_com[0]);
                    else {
                        *sc_end++ = '\n';	/* add newline between
									 * comments */
                        *sc_end++ = ' ';
                        --line_no;
                    }
                    memmove(sc_end, s_lab + com_start, com_end - com_start);
                    sc_end += com_end - com_start;
                    if (sc_end >= &save_com[sc_size])
                        abort();
                    e_lab = s_lab + com_start;
                    while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
                        e_lab--;
                    bp_save = buf_ptr;	/* save current input
								 * buffer */
                    be_save = buf_end;
                    buf_ptr = save_com;	/* fix so that
								 * subsequent calls to
								 * lexi will take tokens
								 * out of save_com */
                    *sc_end++ = ' ';	/* add trailing blank,
								 * just in case */
                    buf_end = sc_end;
                    sc_end = 0;
                }
                *e_lab = '\0';	/* null terminate line */
                ps.pcase = false;
            }

            if (strncmp(s_lab, "#if", 3) == 0) {
                if (blanklines_around_conditional_compilation) {
                    int     c;
                    prefix_blankline_requested++;
                    while ((c = getc(input)) == '\n');
                    ungetc(c, input);
                }
                if (ifdef_level < (int)(sizeof state_stack / sizeof state_stack[0])) {
                    match_state[ifdef_level].tos = -1;
                    state_stack[ifdef_level++] = ps;
                } else
                    diag(1, "#if stack overflow");
            } else if (strncmp(s_lab, "#else", 5) == 0) {
                if (ifdef_level <= 0)
                    diag(1, "Unmatched #else");
                else {
                    match_state[ifdef_level - 1] = ps;
                    ps = state_stack[ifdef_level - 1];
                }
            } else if (strncmp(s_lab, "#endif", 6) == 0) {
                if (ifdef_level <= 0)
                    diag(1, "Unmatched #endif");
                else {
                    ifdef_level--;

#ifdef undef
                    /*
                         * This match needs to be more intelligent before the
                         * message is useful
                         */
                    if (match_state[ifdef_level].tos >= 0
                            && memcmp(&ps, &match_state[ifdef_level], sizeof ps))
                        diag(0, "Syntactically inconsistant #ifdef alternatives.");
#endif
                }
                if (blanklines_around_conditional_compilation) {
                    postfix_blankline_requested++;
                    n_real_blanklines = 0;
                }
            }
            break;	/* subsequent processing of the newline
				 * character will cause the line to be printed */

        case comment:	/* we have gotten a start comment */
            /* this is a biggie */
            if (flushed_nl) {
                /* we should force a broken
                			 * line here */
                flushed_nl = false;
                dump_line();
                ps.want_blank = false;	/* don't insert blank at
							 * line start */
                force_nl = false;
            }
            pr_comment();
            break;
        }		/* end of big switch stmt */

        *e_code = '\0';	/* make sure code section is null terminated */
        if (type_code != comment && type_code != newline && type_code != preesc)
            ps.last_token = type_code;
    }			/* end of main while (1) loop */
}
Exemplo n.º 4
0
int parse(char *g)
/* returns 0 for non-formulas, 1 for atoms, 2 for negations, 3 for binary connective fmlas, 4 for existential and 5 for universal formulas.*/
{
	//0:check for number of brackets
	int counter = 0;
	int i;
	int length = strlen(g);
	for(i = 0 ; i < length ; i++){
		if(g[i] == '('){
			counter++;
		}
		else if(g[i] == ')'){
			counter--;
		}
	}

	// case where it is an atomic formula
	if(g[0] == 'X'){
		if(g[1] == '['){
			if(g[2] == 'x' || g[2] == 'y' || g[2] == 'z'){
				if(g[3] == 'y' || g[3] == 'z' || g[3] == 'x'){
					if(g[4] == ']'){
						if(g[5] == '\0'){
							return 1;
						}
					}
				}
			}
		}

	}
	//2:case of negation
	else if(g[0] == '-'){
		if(g[1] != '\0'){
			if(parse(g+1)>0){
				return 2;
			}
		}

	}
	//4:case of Existential formula
	else if(g[0] == 'E'){
		if(g[1] == 'x' || g[1] == 'y' || g[1] == 'z'){
				if(g[2] != '\0' && parse(g+2)>0){
				return 4;
			}

		}
			
			
	}
	//5:case of Universal formula
	else if(g[0] == 'A'){
		if(g[1] == 'x' || g[1] == 'y' || g[1] == 'z'){
				if(g[2] != '\0' && parse(g+2)>0){
					return 5;
				}		
		}
	}
	//3:case of Binary connective formula
	else if(g[0] == '('){
		// puts("in binary connective");
		if(counter == 0){
			// puts("counter check passed");
			// printf("part one is: %s\n", partone(g));
			// printf("part two is: %s\n", parttwo(g));
			// printf("part one parse result: %d\n", parse(partone(g)));
			// printf("part two parse result: %d\n", parse(parttwo(g)));
			if(parse(partone(g)) > 0 && parse(parttwo(g)) > 0){
				// puts("is binary connective");
				return 3;
			}

		}
		
	}
		
	//A fail case to catch all the failures   
	return 0;
}
Exemplo n.º 5
0
inline bool compile(CompileMode compileMode, ExecState* exec, CodeBlock* codeBlock, JITCode& jitCode, MacroAssemblerCodePtr* jitCodeWithArityCheck, unsigned osrEntryBytecodeIndex)
{
    SamplingRegion samplingRegion("DFG Compilation (Driver)");
    
    numCompilations++;
    
    ASSERT(codeBlock);
    ASSERT(codeBlock->alternative());
    ASSERT(codeBlock->alternative()->getJITType() == JITCode::BaselineJIT);
    
    ASSERT(osrEntryBytecodeIndex != UINT_MAX);

    if (!Options::useDFGJIT())
        return false;
    
#if DFG_ENABLE(DEBUG_VERBOSE)
    dataLog("DFG compiling ", *codeBlock, ", number of instructions = ", codeBlock->instructionCount(), "\n");
#endif
    
    // Derive our set of must-handle values. The compilation must be at least conservative
    // enough to allow for OSR entry with these values.
    unsigned numVarsWithValues;
    if (osrEntryBytecodeIndex)
        numVarsWithValues = codeBlock->m_numVars;
    else
        numVarsWithValues = 0;
    Operands<JSValue> mustHandleValues(codeBlock->numParameters(), numVarsWithValues);
    for (size_t i = 0; i < mustHandleValues.size(); ++i) {
        int operand = mustHandleValues.operandForIndex(i);
        if (operandIsArgument(operand)
            && !operandToArgument(operand)
            && compileMode == CompileFunction
            && codeBlock->specializationKind() == CodeForConstruct) {
            // Ugh. If we're in a constructor, the 'this' argument may hold garbage. It will
            // also never be used. It doesn't matter what we put into the value for this,
            // but it has to be an actual value that can be grokked by subsequent DFG passes,
            // so we sanitize it here by turning it into Undefined.
            mustHandleValues[i] = jsUndefined();
        } else
            mustHandleValues[i] = exec->uncheckedR(operand).jsValue();
    }
    
    Graph dfg(exec->globalData(), codeBlock, osrEntryBytecodeIndex, mustHandleValues);
    if (!parse(exec, dfg))
        return false;
    
    if (compileMode == CompileFunction)
        dfg.predictArgumentTypes();
    
    // By this point the DFG bytecode parser will have potentially mutated various tables
    // in the CodeBlock. This is a good time to perform an early shrink, which is more
    // powerful than a late one. It's safe to do so because we haven't generated any code
    // that references any of the tables directly, yet.
    codeBlock->shrinkToFit(CodeBlock::EarlyShrink);

    validate(dfg);
    performPredictionPropagation(dfg);
    performFixup(dfg);
    performStructureCheckHoisting(dfg);
    unsigned cnt = 1;
    dfg.m_fixpointState = FixpointNotConverged;
    for (;; ++cnt) {
#if DFG_ENABLE(DEBUG_VERBOSE)
        dataLogF("DFG beginning optimization fixpoint iteration #%u.\n", cnt);
#endif
        bool changed = false;
        performCFA(dfg);
        changed |= performConstantFolding(dfg);
        changed |= performArgumentsSimplification(dfg);
        changed |= performCFGSimplification(dfg);
        changed |= performCSE(dfg);
        if (!changed)
            break;
        dfg.resetExitStates();
        performFixup(dfg);
    }
    dfg.m_fixpointState = FixpointConverged;
    performCSE(dfg);
#if DFG_ENABLE(DEBUG_VERBOSE)
    dataLogF("DFG optimization fixpoint converged in %u iterations.\n", cnt);
#endif
    performVirtualRegisterAllocation(dfg);

    GraphDumpMode modeForFinalValidate = DumpGraph;
#if DFG_ENABLE(DEBUG_VERBOSE)
    dataLogF("Graph after optimization:\n");
    dfg.dump();
    modeForFinalValidate = DontDumpGraph;
#endif
    validate(dfg, modeForFinalValidate);
    
    JITCompiler dataFlowJIT(dfg);
    bool result;
    if (compileMode == CompileFunction) {
        ASSERT(jitCodeWithArityCheck);
        
        result = dataFlowJIT.compileFunction(jitCode, *jitCodeWithArityCheck);
    } else {
        ASSERT(compileMode == CompileOther);
        ASSERT(!jitCodeWithArityCheck);
        
        result = dataFlowJIT.compile(jitCode);
    }
    
    return result;
}
Exemplo n.º 6
0
Foam::argList::argList
(
    int& argc,
    char**& argv,
    bool checkArgs,
    bool checkOpts,
    const bool initialise
)
:
    args_(argc),
    options_(argc)
{
    // Check if this run is a parallel run by searching for any parallel option
    // If found call runPar which might filter argv
    for (int argI = 0; argI < argc; ++argI)
    {
        if (argv[argI][0] == '-')
        {
            const char *optionName = &argv[argI][1];

            if (validParOptions.found(optionName))
            {
                parRunControl_.runPar(argc, argv);
                break;
            }
        }
    }

    // convert argv -> args_ and capture ( ... ) lists
    // for normal arguments and for options
    regroupArgv(argc, argv);

    // Get executable name
    args_[0]    = fileName(argv[0]);
    executable_ = fileName(argv[0]).name();

    // Check arguments and options, we already have argv[0]
    int nArgs = 1;
    argListStr_ = args_[0];

    for (int argI = 1; argI < args_.size(); ++argI)
    {
        argListStr_ += ' ';
        argListStr_ += args_[argI];

        if (args_[argI][0] == '-')
        {
            const char *optionName = &args_[argI][1];

            if
            (
                (
                    validOptions.found(optionName)
                 && !validOptions[optionName].empty()
                )
             || (
                    validParOptions.found(optionName)
                 && !validParOptions[optionName].empty()
                )
            )
            {
                ++argI;
                if (argI >= args_.size())
                {
                    FatalError
                        <<"Option '-" << optionName
                        << "' requires an argument" << endl;
                    printUsage();
                    FatalError.exit();
                }

                argListStr_ += ' ';
                argListStr_ += args_[argI];
                options_.insert(optionName, args_[argI]);
            }
            else
            {
                options_.insert(optionName, "");
            }
        }
        else
        {
            if (nArgs != argI)
            {
                args_[nArgs] = args_[argI];
            }
            ++nArgs;
        }
    }

    args_.setSize(nArgs);

    parse(checkArgs, checkOpts, initialise);
}
Exemplo n.º 7
0
Logical Parser::parse( const char* filepath, Character* data, Integer count )
{
  ParseReader parse_reader;
  parse_reader.init( vm, filepath, data, count );
  return parse( parse_reader );
}
Exemplo n.º 8
0
int main(){

	exception e;
	FILE *f = NULL;
	int i = 0,t,result,count=0;
 	wchar_t *tmpString;	
	
	char* filename = "./servers.xml";
	struct stat s;
	UByte *xml = NULL; // this is the buffer containing the XML content, UByte means unsigned byte
	VTDGen *vg = NULL; // This is the VTDGen that parses XML
	VTDNav *vn = NULL; // This is the VTDNav that navigates the VTD records
	AutoPilot *ap = NULL;

	// allocate a piece of buffer then reads in the document content
	// assume "c:\soap2.xml" is the name of the file
	f = fopen(filename,"r");

	stat(filename,&s);

	i = (int) s.st_size;	
	wprintf(L"size of the file is %d \n",i);
	xml = (UByte *)malloc(sizeof(UByte) *i);
	i = fread(xml,sizeof(UByte),i,f);
	Try{
		vg = createVTDGen();
		setDoc(vg,xml,i);
		parse(vg,TRUE);
		vn = getNav(vg);
		ap = createAutoPilot2();
		declareXPathNameSpace(ap,L"ns1",L"http://purl.org/dc/elements/1.1/");
		if (selectXPath(ap,L"//ns1:*")){
			bind(ap,vn);
			while((result=evalXPath(ap))!= -1){
				wprintf(L"result is %d \n",result);
				tmpString = toString(vn,result);
                		wprintf(L"Element name ==> %ls \n",tmpString);
				free(tmpString);
				t = getText(vn);
				if (t!=-1){
					tmpString = toNormalizedString(vn,t);
					wprintf(L" text ==> %ls \n",tmpString);
					free(tmpString);
				}
				wprintf(L"\n =======================\n ");
				count ++;
			}
		}
		wprintf(L"\nTotal number of elements %d \n",count);
		fclose(f);
		// remember C has no automatic garbage collector
		// needs to deallocate manually.
		freeVTDNav(vn);
		freeVTDGen(vg);
		freeAutoPilot(ap);
	}
	Catch (e) {
		if (e.et == parse_exception)
			wprintf(L"parse exception e ==> %s \n %s\n", e.msg, e.sub_msg);	
		// manual garbage collection here
		freeVTDGen(vg);
	}
  return 0;
}	
int server(char* port) {

	int completed=0;


	node *IP_list = NULL;
	int noOfConnections=0;
	int cmdNo;

	fd_set read_fds, write_fds,read_fds_copy,write_fds_copy;
	FD_ZERO(&read_fds);
	FD_ZERO(&write_fds);
	
	//int fdMax = STDIN_FILENO;
	int fdMax = 0; // 0 is file descriptor for standard input 
	int serverSocket, nSocket,selected;  
	struct sockaddr_in serverAddress,clientAddress;
	struct sockaddr_storage getPeerInfo;
	socklen_t clientAddrLen = sizeof(clientAddress);

	char msg[5000]; 
	int numBytes;

	serverSocket= socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);  

	printf("Server created \n");
	
	if(serverSocket == -1) {
		printf("Server: Socket creation failed\n");
	}

	fdMax = serverSocket;
	/* Beej: Allows other sockets to bind() to this port, unless there is an active listening socket bound to the port already. 
	This enables you to get around those "Address already in use" error messages when you try to restart your server after a crash. */
	int socketReuse = 1; 
	setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,&socketReuse,sizeof(int));


	serverAddress.sin_addr.s_addr = INADDR_ANY;
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_port = htons(atoi(port)); //network Byte order

	// bind
	if(bind(serverSocket,(struct sockaddr*)&serverAddress,sizeof(serverAddress))== -1) {
		printf("Server: Binding failed\n");
		close(serverSocket); 
	}
	printf("Server has been bound to port %d \n",atoi(port));

	//printf("Server sockets is %d \n",serverSocket);

	listen(serverSocket,10);

	FD_SET(STDIN_FILENO,&read_fds);
	FD_SET(serverSocket,&read_fds);
	
	while(1) {
		// Create copies of fd_sets because select will modify them
		read_fds_copy = read_fds;
		write_fds_copy = write_fds;
		if (select(fdMax+1, &read_fds_copy,NULL, NULL, NULL) == -1) {
			perror("Server : Select error");
			continue;
		}
		for(selected = 0;selected<=fdMax;selected++) {
			if(FD_ISSET(selected,&read_fds_copy)) {
				/* Need to handle  3 scenarios
				1. Data available from Server socket (New Client arrives)
				2. Data available from Standard Input (Commands)
				3. Data available from clients (SYNC? )
				*/
				if(selected==serverSocket){ // Scenario 1
					printf("Server : A client is trying to connect.\n");
					
					memset(&clientAddress, 0, sizeof(clientAddrLen));
					if ((nSocket = accept(serverSocket,(struct sockaddr*)&clientAddress,&clientAddrLen))==-1) {
						printf("Server: Accept failed\n");
					}
					
					if (noOfConnections >= 4) {
						close(nSocket);
						printf("Server : Connection limit exceeded!\n");
						continue;
					}

					memset(msg,0,5000);
					// receive clients listening port number
					numBytes = recv(nSocket,msg,5000,0);
					printf("New connection from %s : %d \n",inet_ntoa(clientAddress.sin_addr),atoi(msg));
					printf("Client has been registered .Yay!\n");


					setsockopt(nSocket,SOL_SOCKET,SO_REUSEADDR,&socketReuse,sizeof(int));
					push(clientAddress,nSocket,atoi(msg),&IP_list);
										noOfConnections++;

					sendAll(IP_list,noOfConnections);
					FD_SET(nSocket,&read_fds);
					
					if(nSocket > fdMax) 
						fdMax = nSocket;
				} // End Scenario 1
				if(selected==0){ // Scenario 2
					memset(msg,0,sizeof(msg)); // clear msg array
					if ((numBytes = read(selected, msg, sizeof(msg))) <= 0)
						perror("Server read error");

					cmdNo=parse(msg);
					int fd;

					switch(cmdNo){
						case 0: // HELP
						help();
						break;
						case 1:
						creator(); //CREATOR
						break;
						case 2:
						display(port,1); //DISPLAY 
						break;
						case 3: //REGISTER
						printf("REGISTER command not available for server\n");
						break;
						case 4: //CONNECT 
						printf("CONNECT command not available for server\n");
						break;
						case 5: //LIST
						displayList(IP_list); 
						break;
						case 6: //TERMINATE 
						fd=terminate(&IP_list);
                            if(fd!=-1){
                                FD_CLR(fd,&read_fds);
                                FD_CLR(fd,&write_fds);

                                fdMax = getMaxFD(IP_list);
                                noOfConnections--;
                                if(noOfConnections==0){
                                    IP_list=NULL;
                                }

                            }
                            else{
                                printf("Invalid connection ID \n");

                            }
						break;
						break;
						case 7: //QUIT
						quit(&IP_list);
						return 1;
						break;
						case 8: //GET
						printf("GET command not available for server\n");
						break;
						case 9: //PUT
						printf("PUT command not available for server\n");
						break;
						case 10: //SYNC
						printf("SYNC command not available for server\n");
						break;
					}
				} // End Scenario 2

                else { // Scenario 3

					if ((numBytes = recv(selected, msg, 5000, 0)) <= 0) {
						if (numBytes == 0)
						{

							if(getpeername(selected,(struct sockaddr*)&getPeerInfo,&clientAddrLen)<0)
							{
								perror("Server : Error\n");
								return 0;
							}

							struct sockaddr_in *s = (struct sockaddr_in *)&getPeerInfo;

							char* IPAdd = (char*)malloc(sizeof(char)*INET6_ADDRSTRLEN);
							int targetPort = ntohs(ntohs(s->sin_port));
							inet_ntop(AF_INET, &(s->sin_addr), IPAdd, INET6_ADDRSTRLEN);

							printf("Server: Connection closed by IP %s\n",IPAdd);

							
							delete(IPAdd,targetPort,&IP_list);
							FD_CLR(selected,&read_fds);
							close(selected);
							noOfConnections--;

							if(noOfConnections == 0){
								printf("All connections are closed\n");
								IP_list=NULL;}
							else
							{
								// Broad cast current peer list
								fdMax = getMaxFD(IP_list);
								sendAll(IP_list,noOfConnections);
								
							}
						}
						else
						{
							//perror("Server");
						}
					}
					else// we got some data from a client
					{


						char command1[4];
						char command2[6];
                        memcpy(command1,msg,4); // Extract first 3 characters from incoming data
                        memcpy(command2,msg,6); // Extract first 3 characters from incoming data


                        if(!(strcmp(command1,"SYNC")) || (!(strcmp(command1,"sync")))) { // Check if it is GET command


                        	printf("Triggering SYNC on all connected peers!\n");


                        	node *curr=IP_list;
                        	
							syncRelay(curr);
							memset(msg,0,5000); // reset read buffer
							curr=curr->next;
							completed++;
					



                        }


                        else if(!(strcmp(command2,"E_SYNC")) || (!(strcmp(command2,"e_sync")))) { // Check if it is GET command

                        	printf("ESYNC received\n");
                        	int i;

                        	node *curr=IP_list;


                        	if(completed!=noOfConnections){
                        		for(i=0;i<completed;i++){
                        			curr=curr->next;
                        		}
                        		syncRelay(curr);
                        		completed++;
                        	}
                        	else if(completed==noOfConnections){
                        		completed=0;
                        	}


							memset(msg,0,5000); // reset read buffer



                        }

					}
                }
			}
		}
	}
}
Exemplo n.º 10
0
bool FDPLoader::loadInput(const InputSource& input)
{
	bool bFailed = false; // assume all will go well
	// create new parser instance.
	delete m_pParser;
	m_pParser = new XercesDOMParser;
	if (m_pParser)
	{
		m_pParser->setValidationScheme(XercesDOMParser::Val_Auto);
		m_pParser->setDoNamespaces(false);
		m_pParser->setDoSchema(false);

		// skip this if you haven't written your own error reporter class.
//		DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter;
//		parser->setErrorHandler(errReporter);

		m_pParser->setCreateEntityReferenceNodes(false);
		//parser->setToCreateXMLDeclTypeNode(true);
		try
		{
			m_pParser->parse(input);
			bFailed = m_pParser->getErrorCount() != 0;
			if (bFailed)
			{
				std::cerr << "FDPLoader: Parsing error count: " << m_pParser->getErrorCount() << std::endl;
			}
		}
		catch (const DOMException& e)
		{
			std::cerr << "FDPLoader: DOM Exception parsing reports: ";
			// was message provided?
			if (e.msg)
			{
				// yes: display it as ascii.
				char *strMsg = XMLString::transcode(e.msg);
				std::cerr << strMsg << std::endl;
				XMLString::release(&strMsg);
			}
			else
				// no: just display the error code.
				std::cerr << e.code << std::endl;

			bFailed = true;
		}
		catch (const XMLException& e)
		{
			std::cerr << "FDPLoader: XML Exception parsing reports: " << e.getMessage() << std::endl;
			bFailed = true;
		}
		catch (...)
		{
			std::cerr << "FDPLoader: An exception occured while parsing." << std::endl;
			bFailed = true;
		}
		// did the input document parse okay?
		if (!bFailed)
		{
			m_pDoc = m_pParser->getDocument();
			bFailed = !parse();
		}
	}

	return !bFailed;
}
Exemplo n.º 11
0
int main()
{ parse();
  return 0;
}
Exemplo n.º 12
0
URL& URL::operator = (const char* uri)
{
    parse(std::string(uri));
    return *this;
}
Exemplo n.º 13
0
URL& URL::operator = (const std::string& uri)
{
    parse(uri);
    return *this;
}
Exemplo n.º 14
0
URL& URL::operator = (const URL& uri)
{
    if (&uri != this)
        parse(uri.str());
    return *this;
}
Exemplo n.º 15
0
/*!
    \internal
    Constructs a logging rule.
*/
QLoggingRule::QLoggingRule(const QStringRef &pattern, bool enabled) :
    messageType(-1),
    enabled(enabled)
{
    parse(pattern);
}
unsigned MPEG1or2VideoStreamParser::parseSlice() {
  // Note that we've already read the slice_start_code:
  unsigned next4Bytes = PICTURE_START_CODE|fCurrentSliceNumber;
#ifdef DEBUG_SLICE
  fprintf(stderr, "parsing slice: 0x%08x\n", next4Bytes);
#endif

  if (fSkippingCurrentPicture) {
    // Skip all bytes that we see, up until we reach a code of some sort:
    skipToNextCode(next4Bytes);
  } else {
    // Copy all bytes that we see, up until we reach a code of some sort:
    saveToNextCode(next4Bytes);
  }

  // The next thing to parse depends on the code that we just saw:
  if (isSliceStartCode(next4Bytes)) { // common case
    setParseState(PARSING_SLICE);
    fCurrentSliceNumber = next4Bytes&0xFF;
  } else {
    // Because we don't see any more slices, we are assumed to have ended
    // the current picture:
    ++fPicturesSinceLastGOP;
    ++usingSource()->fPictureCount;
    usingSource()->fPictureEndMarker = True; // HACK #####

    switch (next4Bytes) {
    case SEQUENCE_END_CODE: {
      setParseState(PARSING_VIDEO_SEQUENCE_HEADER);
      break;
    }
    case VIDEO_SEQUENCE_HEADER_START_CODE: {
      setParseState(PARSING_VIDEO_SEQUENCE_HEADER_SEEN_CODE);
      break;
    }
    case GROUP_START_CODE: {
      setParseState(PARSING_GOP_HEADER_SEEN_CODE);
      break;
    }
    case PICTURE_START_CODE: {
      setParseState(PARSING_PICTURE_HEADER);
      break;
    }
    default: {
      usingSource()->envir() << "MPEG1or2VideoStreamParser::parseSlice(): Saw unexpected code "
			    << (void*)next4Bytes << "\n";
      setParseState(PARSING_SLICE); // the safest way to recover...
      break;
    }
    }
  }

  // Compute this frame's timestamp:
  usingSource()->computePresentationTime(fCurPicTemporalReference);

  if (fSkippingCurrentPicture) {
    return parse(); // try again, until we get a non-skipped frame
  } else {
    return curFrameSize();
  }
}
Exemplo n.º 17
0
void headerField::setValue(const string& value)
{
	parse(value);
}
Exemplo n.º 18
0
void DinoSerial::setPins(char *aux) {
  int *pins = parse(aux);
  SoftwareSerial newSerial(pins[0],pins[1]);
  softSerial = newSerial;
}
Exemplo n.º 19
0
std::pair<size_t, RedisParser::ParseResult> RedisParser::parseArray(const char *ptr, size_t size)
{
    assert( !arrayStack.empty() );
    assert( !valueStack.empty() );

    long int arraySize = arrayStack.top();
    std::vector<RedisValue> arrayValue = valueStack.top().toArray();

    arrayStack.pop();
    valueStack.pop();

    size_t i = 0;

    if( arrayStack.empty() == false  )
    {
        std::pair<size_t, RedisParser::ParseResult>  pair = parseArray(ptr, size);

        if( pair.second != Completed )
        {
            valueStack.push(arrayValue);
            arrayStack.push(arraySize);

            return pair;
        }
        else
        {
            arrayValue.push_back( valueStack.top() );
            valueStack.pop();
            --arraySize;
        }

        i += pair.first;
    }

    if( i == size )
    {
        valueStack.push(arrayValue);

        if( arraySize == 0 )
        {
            return std::make_pair(i, Completed);
        }
        else
        {
            arrayStack.push(arraySize);
            return std::make_pair(i, Incompleted);
        }
    }

    long int x = 0;

    for(; x < arraySize; ++x)
    {
        std::pair<size_t, RedisParser::ParseResult>  pair = parse(ptr + i, size - i);

        i += pair.first;

        if( pair.second == Error )
        {
            return std::make_pair(i, Error);
        }
        else if( pair.second == Incompleted )
        {
            arraySize -= x;
            valueStack.push(arrayValue);
            arrayStack.push(arraySize);

            return std::make_pair(i, Incompleted);
        }
        else
        {
            assert( valueStack.empty() == false );
            arrayValue.push_back( valueStack.top() );
            valueStack.pop();
        }
    }

    assert( x == arraySize );

    valueStack.push(arrayValue);
    return std::make_pair(i, Completed);
}
Exemplo n.º 20
0
bool PfParser::parse(QByteArray source, PfOptions options) {
  QBuffer buf(&source);
  if (!buf.open(QBuffer::ReadOnly))
    return false; // unlikely to occur
  return parse(&buf, options);
}
Exemplo n.º 21
0
int eval(char *nm, int edges[no_edges][2], int size, int V[3])
/*this method takes a formula, the list of edges of a graph, the number of vertices and a variable assignment.  It then evaluates the formula and returns 1 or 0 as appropriate.  */
{
	int i, first, second;
	char bin = nm[getConnectiveIndex(nm)];
	char *before = partone(nm);
	char *after = parttwo(nm);
	switch(parse(nm))
	{   
		case(1)://Atomic formula
		first = getVariable(nm[2],V);
		second = getVariable(nm[3],V);
		if(is_edge(first,second,edges) == 1){
			return 1;
		}
		else return 0;
		break;

		case(2)://negation formula
		if(eval(nm+1,edges,size,V) == 0){
			return 1;
		}
		else return 0;
		break;

		case(3)://Binary connective formula
		switch(bin){
			case 'v' :if(eval(before,edges,size,V) == 1 || eval(after,edges,size,V) == 1){
				return 1;
			}
			else return 0;
			case '^' :if(eval(before,edges,size,V) == 1 && eval(after,edges,size,V) == 1){
				return 1;
			} 
			else return 0;
			case '>' :if(eval(before,edges,size,V) == 1){
				if(eval(after,edges,size,V) == 1){
					// puts("second part passed");
					return 1;
				}
				else return 0;
			}
			else return 1;

		}
		break;

		case(4)://Existential formula
		for(i = 0 ; i < no_nodes ; i++){
			switch(nm[1]){
				case 'x': V[0] = i; break;
				case 'y': V[1] = i; break;
				case 'z': V[2] = i; break;
				default: return -1;
			}
			if(eval(nm+2,edges,size,V) == 1){
				return 1;
			}
		}
		return 0;
		break;

		case(5)://Universal formula
		for(i = 0 ; i < no_nodes ; i++){
			switch(nm[1]){
				case 'x': V[0] = i; break;
				case 'y': V[1] = i; break;
				case 'z': V[2] = i; break;
				default: return -1;
			}
			if(eval(nm+2,edges,size,V) == 0){
				return 0;
			}

		}
		return 1;
		break;

		default: return -1;

	}

}
Exemplo n.º 22
0
/**
 * parse
 */
QVariant parse(const QString& json)
{
	bool success = true;
	return parse(json, success);
}
Exemplo n.º 23
0
    bool parse(const QString& arg, HValidityCheckLevel checkLevel)
    {
        HLOG(H_AT, H_FUN);

        QString tmp(arg.simplified());

        HUdn udn;
        qint32 indx = tmp.indexOf("::");
        if (indx == 41) // the length of "uuid:UUID" is 41
        {
            udn = HUdn(tmp.left(41));
            if (!udn.isValid(checkLevel))
            {
                return false;
            }

            if (tmp.size() > 43)
            {
                tmp = tmp.mid(43);
            }
            else
            {
                m_udn = udn;
                m_type = HDiscoveryType::SpecificDevice;
                m_contents = udn.toString();
                return true;
            }
        }

        QStringList parsed = tmp.split(':');
        if (parsed.size() < 2)
        {
            HLOG_WARN(QString("Invalid resource identifier: %1").arg(arg));
            return false;
        }

        if (!udn.isValid(checkLevel))
        {
            if (parsed[0] == "ssdp" && parsed[1] == "all")
            {
                m_type = HDiscoveryType::All;
                m_contents = "ssdp:all";
                return true;
            }
        }

        if (parsed[0] == "upnp" && parsed[1] == "rootdevice")
        {
            m_udn = udn;

            if (m_udn.isValid(checkLevel))
            {
                m_type = HDiscoveryType::SpecificRootDevice;
                m_contents = QString("%1::upnp:rootdevice").arg(udn.toString());
            }
            else
            {
                m_type = HDiscoveryType::RootDevices;
                m_contents = "upnp:rootdevice";
            }
            return true;
        }
        else if (parsed[0] == "uuid")
        {
            udn = HUdn(parsed[1]);
            if (udn.isValid(checkLevel))
            {
                m_udn = udn;
                m_type = HDiscoveryType::SpecificDevice;
                m_contents = udn.toString();
                return true;
            }
        }

        HResourceType resourceType(tmp);
        if (parse(resourceType))
        {
            m_udn = udn;
            if (m_udn.isValid(checkLevel))
            {
                m_type = resourceType.isDeviceType() ?
                     HDiscoveryType::SpecificDeviceWithType :
                     HDiscoveryType::SpecificServiceWithType;

                m_contents = QString("%1::%2").arg(
                    udn.toString(), resourceType.toString());
            }
            else
            {
                m_type = resourceType.isDeviceType() ?
                     HDiscoveryType::DeviceType :
                     HDiscoveryType::ServiceType;

                m_contents = QString("%1").arg(resourceType.toString());
            }

            return true;
        }

        HLOG_WARN(QString("Invalid resource identifier: %1").arg(arg));
        return false;
    }
Exemplo n.º 24
0
int m_alias(aClient *cptr, aClient *sptr, int parc, char *parv[], char *cmd)
{
ConfigItem_alias *alias;
aClient *acptr;
int ret;

	if (!(alias = Find_alias(cmd))) 
	{
		sendto_one(sptr, ":%s %d %s %s :Unknown command",
			me.name, ERR_UNKNOWNCOMMAND, parv[0], cmd);
		return 0;
	}
	
	/* If it isn't an ALIAS_COMMAND, we require a paramter ... We check ALIAS_COMMAND LATER */
	if (alias->type != ALIAS_COMMAND && (parc < 2 || *parv[1] == '\0'))
	{
		sendto_one(sptr, err_str(ERR_NOTEXTTOSEND), me.name, parv[0]);
		return -1;
	}

	if (alias->type == ALIAS_SERVICES) 
	{
		if (SERVICES_NAME && (acptr = find_person(alias->nick, NULL)))
		{
			if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_USERMSG, alias->nick, 0, NULL)) < 0)
				return ret;
			sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
				IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
				alias->nick, SERVICES_NAME, parv[1]);
		}
		else
			sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
				parv[0], alias->nick);
	}
	else if (alias->type == ALIAS_STATS) 
	{
		if (STATS_SERVER && (acptr = find_person(alias->nick, NULL)))
		{
			if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_USERMSG, alias->nick, 0, NULL)) < 0)
				return ret;
			sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
				IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
				alias->nick, STATS_SERVER, parv[1]);
		}
		else
			sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
				parv[0], alias->nick);
	}
	else if (alias->type == ALIAS_NORMAL) 
	{
		if ((acptr = find_person(alias->nick, NULL))) 
		{
			if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_USERMSG, alias->nick, 0, NULL)) < 0)
				return ret;
			if (MyClient(acptr))
				sendto_one(acptr, ":%s!%s@%s PRIVMSG %s :%s", parv[0], 
					sptr->user->username, GetHost(sptr),
					alias->nick, parv[1]);
			else
				sendto_one(acptr, ":%s %s %s :%s", parv[0],
					IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
					alias->nick, parv[1]);
		}
		else
			sendto_one(sptr, err_str(ERR_NOSUCHNICK), me.name,
				parv[0], alias->nick);
	}
	else if (alias->type == ALIAS_CHANNEL)
	{
		aChannel *chptr;
		if ((chptr = find_channel(alias->nick, NULL)))
		{
			if (!can_send(sptr, chptr, parv[1], 0))
			{
				if (alias->spamfilter && (ret = dospamfilter(sptr, parv[1], SPAMF_CHANMSG, chptr->chname, 0, NULL)) < 0)
					return ret;
				sendto_channelprefix_butone_tok(sptr,
				    sptr, chptr,
				    PREFIX_ALL,
				    MSG_PRIVATE,
				    TOK_PRIVATE,
				    chptr->chname, parv[1], 0);
				return 0;
			}
		}
		sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name, parv[0],
				cmd, "You may not use this command at this time");
	}
	else if (alias->type == ALIAS_COMMAND) 
	{
		ConfigItem_alias_format *format;
		char *ptr = "";
		if (!(parc < 2 || *parv[1] == '\0'))
			ptr = parv[1]; 
		for (format = alias->format; format; format = (ConfigItem_alias_format *)format->next) 
		{
			if (regexec(&format->expr, ptr, 0, NULL, 0) == 0) 
			{
				/* Parse the parameters */
				int i = 0, j = 0, k = 1;
				char output[1024], current[1024];
				char nums[4];

				bzero(current, sizeof current);
				bzero(output, sizeof output);

				while(format->parameters[i] && j < 500) 
				{
					k = 0;
					if (format->parameters[i] == '%') 
					{
						i++;
						if (format->parameters[i] == '%') 
							output[j++] = '%';
						else if (isdigit(format->parameters[i])) 
						{
							for(; isdigit(format->parameters[i]) && k < 2; i++, k++) {
								nums[k] = format->parameters[i];
							}
							nums[k] = 0;
							i--;
							if (format->parameters[i+1] == '-') {
								strrangetok(ptr, current, ' ', atoi(nums),0);
								i++;
							}
							else 
								strrangetok(ptr, current, ' ', atoi(nums), atoi(nums));
							if (!*current)
								continue;
							if (j + strlen(current)+1 >= 500)
								break;
							strlcat(output, current, sizeof output);
							j += strlen(current);
							
						}
						else if (format->parameters[i] == 'n' ||
							 format->parameters[i] == 'N')
						{
							strlcat(output, parv[0], sizeof output);
							j += strlen(parv[0]);
						}
						else 
						{
							output[j++] = '%';
							output[j++] = format->parameters[i];
						}
						i++;
						continue;
					}
					output[j++] = format->parameters[i++];
				}
				output[j] = 0;
				/* Now check to make sure we have something to send */
				if (strlen(output) == 0)
				{
					sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS), me.name, sptr->name, cmd);
					return -1;
				}
				
				if (format->type == ALIAS_SERVICES) 
				{
					if (SERVICES_NAME && (acptr = find_person(format->nick, NULL)))
					{
						if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_USERMSG, format->nick, 0, NULL)) < 0)
							return ret;
						sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
						IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
						format->nick, SERVICES_NAME, output);
					} else
						sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
							parv[0], format->nick);
				}
				else if (format->type == ALIAS_STATS) 
				{
					if (STATS_SERVER && (acptr = find_person(format->nick, NULL)))
					{
						if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_USERMSG, format->nick, 0, NULL)) < 0)
							return ret;
						sendto_one(acptr, ":%s %s %s@%s :%s", parv[0],
							IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
							format->nick, STATS_SERVER, output);
					} else
						sendto_one(sptr, err_str(ERR_SERVICESDOWN), me.name,
							parv[0], format->nick);
				}
				else if (format->type == ALIAS_NORMAL) 
				{
					if ((acptr = find_person(format->nick, NULL))) 
					{
						if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_USERMSG, format->nick, 0, NULL)) < 0)
							return ret;
						if (MyClient(acptr))
							sendto_one(acptr, ":%s!%s@%s PRIVMSG %s :%s", parv[0], 
							sptr->user->username, IsHidden(sptr) ? sptr->user->virthost : sptr->user->realhost,
							format->nick, output);
						else
							sendto_one(acptr, ":%s %s %s :%s", parv[0],
								IsToken(acptr->from) ? TOK_PRIVATE : MSG_PRIVATE, 
								format->nick, output);
					}
					else
						sendto_one(sptr, err_str(ERR_NOSUCHNICK), me.name,
							parv[0], format->nick);
				}
				else if (format->type == ALIAS_CHANNEL)
				{
					aChannel *chptr;
					if ((chptr = find_channel(format->nick, NULL)))
					{
						if (!can_send(sptr, chptr, output, 0))
						{
							if (alias->spamfilter && (ret = dospamfilter(sptr, output, SPAMF_CHANMSG, chptr->chname, 0, NULL)) < 0)
								return ret;
							sendto_channelprefix_butone_tok(sptr,
							    sptr, chptr,
							    PREFIX_ALL, MSG_PRIVATE,
							    TOK_PRIVATE, chptr->chname,
							    output, 0);
							return 0;
						}
					}
					sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name,
						 parv[0], cmd, 
						"You may not use this command at this time");
				}
				else if (format->type == ALIAS_REAL)
				{
					int ret;
					char mybuf[500];
					
					snprintf(mybuf, sizeof(mybuf), "%s %s", format->nick, output);

					if (recursive_alias)
					{
						sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name, parv[0], cmd, "You may not use this command at this time -- recursion");
						return -1;
					}

					recursive_alias = 1;
					ret = parse(sptr, mybuf, mybuf+strlen(mybuf));
					recursive_alias = 0;

					return ret;
				}
				break;
			}
		}
		return 0;
	}
	return 0;
}
Exemplo n.º 25
0
//
//  read in the mailbox and parse into messages.
//
static char*
_readmbox(Mailbox *mb, int doplumb, Mlock *lk)
{
	int fd, n;
	String *tmp;
	Dir *d;
	static char err[Errlen];
	Message *m, **l;
	Inbuf *inb;
	char *x;

	l = &mb->root->part;

	/*
	 *  open the mailbox.  If it doesn't exist, try the temporary one.
	 */
	n = 0;
retry:
	fd = open(mb->path, OREAD);
	if(fd < 0){
		rerrstr(err, sizeof(err));
		if(strstr(err, "exclusive lock") != 0 && n++ < 20){
			sleep(500);	/* wait for lock to go away */
			goto retry;
		}
		if(strstr(err, "exist") != 0){
			tmp = s_copy(mb->path);
			s_append(tmp, ".tmp");
			if(sysrename(s_to_c(tmp), mb->path) == 0){
				s_free(tmp);
				goto retry;
			}
			s_free(tmp);
		}
		return err;
	}

	/*
	 *  a new qid.path means reread the mailbox, while
	 *  a new qid.vers means read any new messages
	 */
	d = dirfstat(fd);
	if(d == nil){
		close(fd);
		errstr(err, sizeof(err));
		return err;
	}
	if(mb->d != nil){
		if(d->qid.path == mb->d->qid.path && d->qid.vers == mb->d->qid.vers){
			close(fd);
			free(d);
			return nil;
		}
		if(d->qid.path == mb->d->qid.path){
			while(*l != nil)
				l = &(*l)->next;
			seek(fd, mb->d->length, 0);
		}
		free(mb->d);
	}
	mb->d = d;
	mb->vers++;
	henter(PATH(0, Qtop), mb->name,
		(Qid){PATH(mb->id, Qmbox), mb->vers, QTDIR}, nil, mb);

	inb = emalloc(sizeof(Inbuf));
	inb->rptr = inb->wptr = inb->data;
	inb->fd = fd;

	//  read new messages
	snprint(err, sizeof err, "reading '%s'", mb->path);
	logmsg(err, nil);
	for(;;){
		if(lk != nil)
			syslockrefresh(lk);
		m = newmessage(mb->root);
		m->mallocd = 1;
		m->inmbox = 1;
		if(readmessage(m, inb) < 0){
			delmessage(mb, m);
			mb->root->subname--;
			break;
		}

		// merge mailbox versions
		while(*l != nil){
			if(memcmp((*l)->digest, m->digest, SHA1dlen) == 0){
				// matches mail we already read, discard
				logmsg("duplicate", *l);
				delmessage(mb, m);
				mb->root->subname--;
				m = nil;
				l = &(*l)->next;
				break;
			} else {
				// old mail no longer in box, mark deleted
				logmsg("disappeared", *l);
				if(doplumb)
					mailplumb(mb, *l, 1);
				(*l)->inmbox = 0;
				(*l)->deleted = 1;
				l = &(*l)->next;
			}
		}
		if(m == nil)
			continue;

		x = strchr(m->start, '\n');
		if(x == nil)
			m->header = m->end;
		else
			m->header = x + 1;
		m->mheader = m->mhend = m->header;
		parseunix(m);
		parse(m, 0, mb, 0);
		logmsg("new", m);

		/* chain in */
		*l = m;
		l = &m->next;
		if(doplumb)
			mailplumb(mb, m, 0);

	}
	logmsg("mbox read", nil);

	// whatever is left has been removed from the mbox, mark deleted
	while(*l != nil){
		if(doplumb)
			mailplumb(mb, *l, 1);
		(*l)->inmbox = 0;
		(*l)->deleted = 1;
		l = &(*l)->next;
	}

	close(fd);
	free(inb);
	return nil;
}
Exemplo n.º 26
0
int main(
    int argc,
    char *argv[])
{
    char     *buffer;
    long      i;
    long      filter = 0;
    struct option long_options[] = {
        {"filter", no_argument, 0, 'f'},
        {0, 0, 0, 0}
    };

#ifdef MUST_DISABLE_SIGFPE
    signal(SIGFPE, SIG_IGN);
#endif
#ifdef MUST_DISABLE_FPMASK
    fpsetmask(0);
#endif
    optind = 0;
    opterr = 0;         /* initialize getopt */

    /* what do we get for cmdline arguments?
       for (i=0;i<argc;i++)
       printf("%d-'%s'\n",i,argv[i]); */
    while (1) {
        int       option_index = 0;
        int       opt;

        opt = getopt_long(argc, argv, "f", long_options, &option_index);
        if (opt == EOF) {
            break;
        }

        switch (opt) {
        case 'f':
            filter = 1;
            break;
        case '?':
            printf("unknown commandline option '%s'\n", argv[optind - 1]);
            return -1;
        }
    }

    if (!filter) {
        rrdcgiDebug(0, 0);
        rrdcgiArg = rrdcgiInit();
    }

    /* make sure we have one extra argument, 
       if there are others, we do not care Apache gives several */

    /* if ( (optind != argc-2 
       && strstr( getenv("SERVER_SOFTWARE"),"Apache/2") != NULL) 
       && optind != argc-1) { */

    if (optind >= argc) {
        fprintf(stderr, "ERROR: expected a filename\n");
        exit(1);
    } else {
        readfile(argv[optind], &buffer, 1);
    }

    if (rrd_test_error()) {
        fprintf(stderr, "ERROR: %s\n", rrd_get_error());
        exit(1);
    }

    /* initialize variable heap */
    initvar();

#ifdef DEBUG_PARSER
    /* some fake header for testing */
    printf("Content-Type: text/html\nContent-Length: 10000000\n\n\n");
#endif


    /* expand rrd directives in buffer recursivly */
    for (i = 0; buffer[i]; i++) {
        if (buffer[i] != '<')
            continue;
        if (!filter) {
            parse(&buffer, i, "<RRD::CV", cgiget);
            parse(&buffer, i, "<RRD::CV::PATH", cgigetqp);
            parse(&buffer, i, "<RRD::CV::QUOTE", cgigetq);
            parse(&buffer, i, "<RRD::GETENV", rrdgetenv);
        }
        parse(&buffer, i, "<RRD::GETVAR", rrdgetvar);
        parse(&buffer, i, "<RRD::GOODFOR", rrdgoodfor);
        parse(&buffer, i, "<RRD::GRAPH", drawgraph);
        parse(&buffer, i, "<RRD::INCLUDE", includefile);
        parse(&buffer, i, "<RRD::PRINT", drawprint);
        parse(&buffer, i, "<RRD::SETCONSTVAR", rrdsetvarconst);
        parse(&buffer, i, "<RRD::SETENV", rrdsetenv);
        parse(&buffer, i, "<RRD::SETVAR", rrdsetvar);
        parse(&buffer, i, "<RRD::TIME::LAST", printtimelast);
        parse(&buffer, i, "<RRD::TIME::NOW", printtimenow);
        parse(&buffer, i, "<RRD::TIME::STRFTIME", printstrftime);
        parse(&buffer, i, "<RRD::INTERNAL", rrdgetinternal);
    }

    if (!filter) {
        printf("Content-Type: text/html\n"
               "Content-Length: %zd\n", strlen(buffer));

        if (labs(goodfor) > 0) {
            time_t    now;

            now = time(NULL);
            printf("Last-Modified: %s\n", http_time(&now));
            now += labs(goodfor);
            printf("Expires: %s\n", http_time(&now));
            if (goodfor < 0) {
                printf("Refresh: %ld\n", labs(goodfor));
            }
        }
        printf("\n");
    }

    /* output result */
    printf("%s", buffer);

    /* cleanup */
    calfree();
    if (buffer) {
        free(buffer);
    }
    donevar();
    exit(0);
}
Exemplo n.º 27
0
void read_line(lcontext_t *ctx)
{
	int isFirstLine = 1, isSyntaxError = 0;
	char *line, *pos;
	int size = 0;

	while(1) {
		if(ctx->fp) {
			line = (char *)malloc(MAX_LINE_LEN);
			if(!fgets(line, MAX_LINE_LEN, ctx->fp))
			{
				free(line);
				free_rootContext(ctx);
				exit(0);
			}
		}
		else {
			if(isFirstLine) {
				line = readline(">>> ");
				isFirstLine = 0;
			}
			else line = readline("    ");
		}

		pos = line;

		if((*(pos = skip_space(pos))) != '(' && ctx->bracketsCounter == -1) {
			lstrerr(SYNTAX_ERROR);
			free(line);
			line = NULL;
			isFirstLine = 1;
			init_rootContext(ctx);
			continue;
		}

		while((*pos != '\0') && (*pos != '\n')) {
			if(!ctx->bracketsCounter) {
				isSyntaxError = 1;
				break;
			}
			size = tokenize(pos);
			if(size == END_OF_LINE) {
				parse(ctx, pos, strlen(pos));
				break;
			}
			else if(size == QUIT) {
				free(line);
				free_rootContext(ctx);
				exit(0);
			}
			parse(ctx, pos, size);
			pos += size;
			pos = skip_space(pos);
		}

		free(line);
		line = NULL;
		if(isSyntaxError) {
			lstrerr(SYNTAX_ERROR);
			isSyntaxError = 0;
			isFirstLine = 1;
			init_rootContext(ctx);
			continue;
		}

		if(!ctx->bracketsCounter) break;
	}
	return;
}
Exemplo n.º 28
0
bool LLLoginHandler::handle(const LLSD& tokens,
							const LLSD& query_map,
							LLMediaCtrl* web)
{
	// do nothing if we are already logged in
	if (LLLoginInstance::getInstance()->authSuccess())
	{
		LL_WARNS_ONCE("SLURL") << "Already logged in! Ignoring login SLapp." << LL_ENDL;
		return true;
	}

	if (tokens.size() == 1
		&& tokens[0].asString() == "show")
	{
		// We're using reg-in-client, so show the XUI login widgets
		LLPanelLogin::showLoginWidgets();
		return true;
	}

	if (tokens.size() == 1
		&& tokens[0].asString() == "reg")
	{
		LLWindow* window = gViewerWindow->getWindow();
		window->incBusyCount();
		window->setCursor(UI_CURSOR_ARROW);

		// Do this first, as it may be slow and we want to keep something
		// on the user's screen as long as possible
		LLWeb::loadURLExternal( "http://join.eniac15.lindenlab.com/" );

		window->decBusyCount();
		window->setCursor(UI_CURSOR_ARROW);

		// Then hide the window
		window->minimize();
		return true;
	}

	// Make sure window is visible
	LLWindow* window = gViewerWindow->getWindow();
	if (window->getMinimized())
	{
		window->restore();
	}

	parse(query_map);
	
	//if we haven't initialized stuff yet, this is 
	//coming in from the GURL handler, just parse
	if (STATE_FIRST == LLStartUp::getStartupState())
	{
		return true;
	}
	
	if  (LLStartUp::getStartupState() < STATE_LOGIN_CLEANUP)  //on splash page         
	{
	  // as the login page may change from grid to grid, as well as
	  // things like username/password/etc, we simply refresh the
	  // login page to make sure everything is set up correctly
	  LLPanelLogin::loadLoginPage();
	  LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
	}
	return true;
}
Exemplo n.º 29
0
struct expression_s *
parse (FILE *input)
{
  int ch;
  do {
    ch = getc (input);
    if ( ch == '#' )
      while ( ch != '\n' && ch != EOF )
	ch = getc (input);
  } while ( ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' );
  if ( ch == '`' )
    {
      struct expression_s *rator = parse (input);
      struct expression_s *rand = parse (input);
      struct expression_s *expr = new_expression ();

      expr->t = EXPRESSION_APPLICATION;
      init_ptr (&expr->d.expression_application_v.rator, rator);
      init_ptr (&expr->d.expression_application_v.rand, rand);
#if 0  /* Harmless but not necessary */
      free_expression (rator);
      free_expression (rand);
#endif
      return expr;
    }
  else if ( ch == 'i' || ch == 'I' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_I;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'k' || ch == 'K' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_K;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 's' || ch == 'S' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_S;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'v' || ch == 'V' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_V;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'd' || ch == 'D' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_D;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'e' || ch == 'E' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_E;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'p' || ch == 'P' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_P;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'f' || ch == 'F' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_F;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'r' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_DOT;
      fun->d.function_dot_v = '\n';
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '.' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();
      int ch2;

      fun->t = FUNCTION_DOT;
      ch2 = getc (input);
      if ( ch2 == EOF )
	goto ueof;
      fun->d.function_dot_v = ch2;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '@' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_AT;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '?' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();
      int ch2;

      fun->t = FUNCTION_QUES;
      ch2 = getc (input);
      if ( ch2 == EOF )
	goto ueof;
      fun->d.function_ques_v = ch2;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '|' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_PIPE;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == EOF )
    {
    ueof:
      fprintf (stderr, "Unexpected end of file\n");
      exit (1);
    }
  else
    {
      fprintf (stderr, "Character not recognized: %c\n", ch);
      exit (1);
    }
  return NULL;
}
Exemplo n.º 30
0
URL::URL(const std::string& scheme, const std::string& host, const std::string& pathEtc)
{
    parse(scheme + "://" + host + pathEtc);
}