Beispiel #1
0
// Parse string text to words
// Seperator by punctuation, space
StringArray parse_words(const simple::string& text)
{
    const unsigned char *p = (const unsigned char *) text.c_str();
    StringArray arr(text.length() / 4);
    
    size_t i = 0;
    while (i < text.length())
    {
        // Skip all spaces
        while (p[i] && isspace(p[i]))
            i++;

        if (!p[i])
            // End of parse
            break;

        // Lead by _ or alphabet
        size_t b = i;
        if (isalpha(p[i]) || p[i] == '_')
        {
            while (p[i] && (isalnum(p[i]) || p[i] == '_'))
                i++;
            arr.push_back(simple::string((const char *)p + b, i - b));
            continue;
        }

        // Lead by number, looking number.number
        if (isdigit(p[i]))
        {
            bool has_dot = false;
            while (isdigit(p[i]) || (p[i] == '.' && !has_dot))
            {
                if (p[i] == '.')
                    has_dot = true;
                i++;
            }
            arr.push_back(simple::string((const char *)p + b, i - b));
            continue;
        }

        // Lead by .
        if (p[i] == '.')
        {
            if (p[i + 1] == '.' && p[i + 2] == '.')
            {
                // Got ...
                arr.push_back("...");
                i += 3;
                continue;
            }

            if (p[i + 1] == '.')
            {
                // Got ..
                arr.push_back("..");
                i += 2;
                continue;
            }

            if (isdigit(p[i]))
            {
                // Got .number
                while (isdigit(p[i]))
                    i++;
                arr.push_back(simple::string((const char *)p + b, i - b));
                continue;
            }

            // Got .
            arr.push_back(".");
            i++;
            continue;
        }

        // Got single char
        arr.push_back(simple::string((const char *)p + i, 1));
        i++;
    }
    return arr;
}
Beispiel #2
0
int str_match(const char *str, const char *format) {

    const char *s   = str;
    const char *fmt = format;
    unsigned int flag = 0;
    int width = 0;

    bit_t bit;
    char c;
    const char *s0;

    while (*fmt) {
        if (*fmt == '%') {
            fmt++;

            while (*fmt >= '0' && *fmt <= '9') 
                width = width * 10 + *fmt++ - '0';

            switch(*fmt) {
                case 'd':
                    if (width) {
                        while (*s && isdigit(*s) && width-- > 0)
                            s++;
                    } else {
                        while (*s && isdigit(*s))
                            s++;
                    }
                    fmt++;
                    break;

                case '[':
                    fmt++;
                    bit_zero(&bit);

                    if (*fmt == '^') {
                        fmt++;
                        flag |= STATUS_CARET;
                    }

                    while (*fmt && *fmt != ']') {
                        if (fmt[1] == '-') {
                            for (c = *fmt; c < fmt[2]; c++) {
                                bit_set(&bit, c);
                            }
                            if (c == fmt[2])
                                fmt += 2;
                        } else {
                            bit_set(&bit, *fmt);
                            fmt++;
                        }
                    }

                    if (flag & STATUS_CARET) {
                        bit_rev(&bit);
                        /* clear STATUS_CARET */
                        flag &= ~STATUS_CARET;
                    }

                    if (width) {
                        while (*s && bit_isset(&bit, *s) && width-- > 0) {
                            s++;
                        }
                    } else {
                        while (*s && bit_isset(&bit, *s)) {
                            s++;
                        }
                    }

                    if (*fmt == ']')
                        fmt++;
                    break;

                case 'f':

                    if (width) {
                        while (*s && isdigit(*s) && width > 0)
                            s++, width--;

                        if (*s == '.' && width > 0)
                            s++, width--;

                        while (*s && isdigit(*s) && width > 0)
                            s++, width--;
                    } else {
                        while (*s && isdigit(*s))
                            s++;

                        if (*s == '.')
                            s++;

                        while (*s && isdigit(*s))
                            s++;
                    }

                    fmt++;
                    break;

                case '{':
                    fmt++;

                    flag &= ~STATUS_OR;
                    while(*fmt && *fmt != '|' && *fmt != '}') {
                        s0 = s;

                        /* match */
                        while (*fmt && *fmt != '|' && *fmt != '}' && (*s0 == *fmt))
                            s0++, fmt++;

                        /* match ok*/
                        if (*fmt == '|' || *fmt == '}') {
                            flag |= STATUS_OR;
                            while (*fmt && *fmt != '}')
                                fmt++;
                            s = s0;
                        } else {
                            /* match no*/
                            while (*fmt && *fmt != '|' && *fmt != '}')
                                fmt++;
                            if (*fmt == '|' || *fmt == '}')
                                fmt++;
                        }
                    }

                    if (!(flag & STATUS_OR))
                        return 0;

                    if (*fmt == '}')
                        fmt++;
                    break;

                default:
                    fmt++;
                    break;
            }

            width = 0;
        } else {

            /*printf("%d:%d:%c:%c\n", *fmt, *s, *fmt, *s);*/
            if (!*fmt && !*s)
                return 1;

            if (*fmt != *s) {
                /* %?*/
                if (*fmt && fmt[1] == '%' && fmt[2] == '?') {
                    fmt++;
                    continue;
                }
                else
                    return 0;
            }

            fmt++;
            s++;
        }
    }

    return !*fmt && !*s;
}
Beispiel #3
0
bool NumericToken::Start(const std::string &line)
{
    return isdigit(line[0]) || (line[0] == '.' && isdigit(line[1]));
}
int
http_stream_read(char *buf,
                 int len,
                 int *err)
{    
    struct _stream *s = &http_stream;
    int total = 0;
    int cnt, code;

    if (!s->open) {
        return -1;  // Shouldn't happen, but...
    }
    while (len) {
        while (s->avail == 0) {
            // Need to wait for some data to arrive
            __tcp_poll();
            if (s->sock.state != _ESTABLISHED) {
                if (s->sock.state == _CLOSE_WAIT) {
                    // This connection is breaking
                    if (s->sock.data_bytes == 0 && s->sock.rxcnt == 0) {
                        __tcp_close(&s->sock);
                        return total;
                    }  
                } else if (s->sock.state == _CLOSED) {
                    	// The connection is gone
                    	s->open = false;
                    	return -1;
                } else {	
                    *err = HTTP_IO;
                    return -1;
		}
            }
            s->actual_len = __tcp_read(&s->sock, s->data, sizeof(s->data));
            if (s->actual_len > 0) {
                s->bufp = s->data;
                s->avail = s->actual_len;
                if (s->pos == 0) {
                    // First data - need to scan HTTP response header
                    if (strncmp(s->bufp, "HTTP/", 5) == 0) {
                        // Should look like "HTTP/1.1 200 OK"
                        s->bufp += 5;
                        s->avail -= 5;
                        // Find first space
                        while ((s->avail > 0) && (*s->bufp != ' ')) {
                            s->bufp++;  
                            s->avail--;
                        }
                        // Now the integer response
                        code = 0;
                        while ((s->avail > 0) && (*s->bufp == ' ')) {
                            s->bufp++;  
                            s->avail--;
                        }
                        while ((s->avail > 0) && isdigit(*s->bufp)) {
                            code = (code * 10) + (*s->bufp - '0');
                            s->bufp++;  
                            s->avail--;
                        }
                        // Make sure it says OK
                        while ((s->avail > 0) && (*s->bufp == ' ')) {
                            s->bufp++;  
                            s->avail--;
                        }
                        if (strncmp(s->bufp, "OK", 2)) {
                            *err = HTTP_BADHDR;
                            return -1;
                        }
                        // Find \r\n\r\n - end of HTTP preamble
                        while (s->avail > 4) {
                            // This could be done faster, but not simpler
                            if (strncmp(s->bufp, "\r\n\r\n", 4) == 0) {
                                s->bufp += 4;
                                s->avail -= 4;
#if 0 // DEBUG - show header
                                *(s->bufp-2) = '\0';
                                diag_printf(s->data);
#endif
                                break;
                            }
                            s->avail--;
                            s->bufp++;
                        }
                        s->pos++;
                    } else {
                        // Unrecognized response
                        *err = HTTP_BADHDR;
                        return -1;
                    }
                }
            } else if (s->actual_len < 0) {
                *err = HTTP_IO;
                return -1;
            }
        }
        cnt = min(len, s->avail);
        memcpy(buf, s->bufp, cnt);
        s->avail -= cnt;
        s->bufp += cnt;
        buf += cnt;
        total += cnt;
        len -= cnt;
    }
    return total;
}
static int find_prev_reset(rlm_sqlcounter_t *inst, time_t timeval)
{
	int ret = 0;
	size_t len;
	unsigned int num = 1;
	char last = '\0';
	struct tm *tm, s_tm;
	char sCurrentTime[40], sPrevTime[40];

	tm = localtime_r(&timeval, &s_tm);
	len = strftime(sCurrentTime, sizeof(sCurrentTime), "%Y-%m-%d %H:%M:%S", tm);
	if (len == 0) *sCurrentTime = '\0';
	tm->tm_sec = tm->tm_min = 0;

	rad_assert(inst->reset != NULL);

	if (isdigit((int) inst->reset[0])){
		len = strlen(inst->reset);
		if (len == 0)
			return -1;
		last = inst->reset[len - 1];
		if (!isalpha((int) last))
			last = 'd';
		num = atoi(inst->reset);
		DEBUG("rlm_sqlcounter: num=%d, last=%c",num,last);
	}
	if (strcmp(inst->reset, "hourly") == 0 || last == 'h') {
		/*
		 *  Round down to the prev nearest hour.
		 */
		tm->tm_hour -= num - 1;
		inst->last_reset = mktime(tm);
	} else if (strcmp(inst->reset, "daily") == 0 || last == 'd') {
		/*
		 *  Round down to the prev nearest day.
		 */
		tm->tm_hour = 0;
		tm->tm_mday -= num - 1;
		inst->last_reset = mktime(tm);
	} else if (strcmp(inst->reset, "weekly") == 0 || last == 'w') {
		/*
		 *  Round down to the prev nearest week.
		 */
		tm->tm_hour = 0;
		tm->tm_mday -= (7 - tm->tm_wday) +(7*(num-1));
		inst->last_reset = mktime(tm);
	} else if (strcmp(inst->reset, "monthly") == 0 || last == 'm') {
		tm->tm_hour = 0;
		tm->tm_mday = 1;
		tm->tm_mon -= num - 1;
		inst->last_reset = mktime(tm);
	} else if (strcmp(inst->reset, "never") == 0) {
		inst->reset_time = 0;
	} else {
		return -1;
	}
	len = strftime(sPrevTime, sizeof(sPrevTime), "%Y-%m-%d %H:%M:%S", tm);
	if (len == 0) *sPrevTime = '\0';
	DEBUG2("rlm_sqlcounter: Current Time: %" PRId64 " [%s], Prev reset %" PRId64 " [%s]",
	       (int64_t) timeval, sCurrentTime, (int64_t) inst->last_reset, sPrevTime);

	return ret;
}
Beispiel #6
0
long inputfile::ReadNumber(int CallLevel, truth PreserveTerminator)
{
  long Value = 0;
  static festring Word;
  truth NumberCorrect = false;

  for(;;)
  {
    ReadWord(Word);
    char First = Word[0];

    if(isdigit(First))
    {
      Value = atoi(Word.CStr());
      NumberCorrect = true;
      continue;
    }

    if(Word.GetSize() == 1)
    {
      if(First == ';' || First == ',' || First == ':')
      {
	if(CallLevel != HIGHEST || PreserveTerminator)
	  ungetc(First, Buffer);

	return Value;
      }

      if(First == ')')
      {
	if((CallLevel != HIGHEST && CallLevel != 4) || PreserveTerminator)
	  ungetc(')', Buffer);

	return Value;
      }

      if(First == '~')
      {
	Value = ~ReadNumber(4);
	NumberCorrect = true;
	continue;
      }

      /* Convert this into an inline function! */

#define CHECK_OP(op, cl)\
	  if(First == #op[0])\
	    if(cl < CallLevel)\
	      {\
		Value op##= ReadNumber(cl);\
		NumberCorrect = true;\
		continue;\
	      }\
	    else\
	      {\
		ungetc(#op[0], Buffer);\
		return Value;\
	      }

      CHECK_OP(&, 1); CHECK_OP(|, 1); CHECK_OP(^, 1);
      CHECK_OP(*, 2); CHECK_OP(/, 2); CHECK_OP(%, 2);
      CHECK_OP(+, 3); CHECK_OP(-, 3);

      if(First == '<')
      {
	char Next = Get();

	if(Next == '<')
	  if(1 < CallLevel)
	  {
	    Value <<= ReadNumber(1);
	    NumberCorrect = true;
	    continue;
	  }
	  else
	  {
	    ungetc('<', Buffer);
	    ungetc('<', Buffer);
	    return Value;
	  }
	else
	  ungetc(Next, Buffer);
      }

      if(First == '>')
      {
	char Next = Get();

	if(Next == '>')
	  if(1 < CallLevel)
	  {
	    Value >>= ReadNumber(1);
	    NumberCorrect = true;
	    continue;
	  }
	  else
	  {
	    ungetc('>', Buffer);
	    ungetc('>', Buffer);
	    return Value;
	  }
	else
Beispiel #7
0
int state_init_from_fen(state_t *state, char *fen)
{
    /* Sets the board according to Forsyth-Edwards Notation.
     * See http://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation for more information.
     *
     * Returns the number of used characters from fen */

    int piece_idx = 8 * 7; /* Starting on the A8. */
    int i = 0;
    int color, piece;
    char num[16];
    int res;

    memset(state, 0, sizeof(state_t));
    memset(state->square, 7, 64 * sizeof(int));

    /* Set up the position. */
    while (fen[i] && fen[i] != ' ')
    {
        char c = fen[i];

        if (c == '/')
        {
            piece_idx -= 2 * 8;
        }
        else if (isdigit(c))
        {
            piece_idx += (int)(c - '0');
        }
        else
        {
            int piece = util_char_to_piece(c);
            int color = util_char_to_color(c);
            state->pieces[color][piece] |= (1ull << piece_idx);
            state->square[piece_idx] = piece;
            if (piece == KING)
            {
                state->king_idx[color] = piece_idx;
            }

            piece_idx += 1;
        }

        ++i;
    }

    ++i;

    /* Update state->occupied with the occupied squares in state->pieces. */
    for (color = 0; color < 2; ++color)
    {
        for (piece = 0; piece < 6; ++piece)
        {
            state->occupied[color] |= state->pieces[color][piece];
            state->occupied_both |= state->pieces[color][piece];
        }
    }

    /* Set active color. */
    if (tolower(fen[i++]) == 'w')
    {
        state->turn = WHITE;
    }
    else
    {
        state->turn = BLACK;
    }

    ++i;

    while (fen[i] && fen[i] != ' ')
    {
        switch (fen[i++])
        {
            case 'Q':
                state->castling |= A1;
                break;
            case 'K':
                state->castling |= H1;
                break;
            case 'q':
                state->castling |= A8;
                break;
            case 'k':
                state->castling |= H8;
                break;
        }
    }

    ++i;

    /* Set en passant. */
    if (fen[i] != '-')
    {
        uint64_t square_idx = util_chars_to_square(&fen[i]);
        state->en_passant = (1ull << square_idx);

        i += 2;
    }
    else
    {
        ++i;
    }

    ++i;

    /* TODO: Halfmove and Fullmove numbers from FEN. */
    /* Halfmove */

    res = sscanf(&fen[i], "%s", num);
    if (1 == res && num[0] != '-')
    {
        //int halfmove = atoi(num);
        i += strlen(num);
    }
    else
    {
        ++i;
    }

    ++i;

    /* Fullmove */
    res = sscanf(&fen[i], "%s", num);
    if (1 == res && num[0] != '-')
    {
        //int fullmove = atoi(num);
        i += strlen(num);
    }
    else
    {
        ++i;
    }

    state->zobrist = hash_make_zobrist(state);
    return i;
}
Beispiel #8
0
void
conv(register FILE *fp)
{
	register int c, k;
	int m, n, n1, m1;
	char str[4096], buf[4096];

	while ((c = getc(fp)) != EOF) {
		switch (c) {
		case '\n':	/* when input is text */
		case ' ':
		case 0:		/* occasional noise creeps in */
			break;
		case '{':	/* push down current environment */
			t_push();
			break;
		case '}':
			t_pop();
			break;
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			/* two motion digits plus a character */
			hmot((c-'0')*10 + getc(fp)-'0');
			put1(getc(fp));
			break;
		case 'c':	/* single ascii character */
			put1(getc(fp));
			break;
		case 'C':
			sget(str, sizeof str, fp);
			put1s(str);
			break;
		case 't':	/* straight text */
			fgets(buf, sizeof(buf), fp);
			t_text(buf);
			break;
		case 'D':	/* draw function */
			fgets(buf, sizeof(buf), fp);
			switch (buf[0]) {
			case 'l':	/* draw a line */
				sscanf(buf+1, "%d %d", &n, &m);
				drawline(n, m, ".");
				break;
			case 'c':	/* circle */
				sscanf(buf+1, "%d", &n);
				drawcirc(n);
				break;
			case 'e':	/* ellipse */
				sscanf(buf+1, "%d %d", &m, &n);
				drawellip(m, n);
				break;
			case 'a':	/* arc */
				sscanf(buf+1, "%d %d %d %d", &n, &m, &n1, &m1);
				drawarc(n, m, n1, m1);
				break;
			case '~':	/* wiggly line */
				drawwig(buf+1);
				break;
			default:
				error(FATAL, "unknown drawing function %s\n", buf);
				break;
			}
			break;
		case 's':
			fscanf(fp, "%d", &n);
			if (n == -23) {
				float	f;
				fscanf(fp, "%f", &f);
				setsize(f);
			} else
				setsize(t_size(n));/* ignore fractional sizes */
			break;
		case 'f':
			sget(str, sizeof str, fp);
			setfont(t_font(str));
			break;
		case 'H':	/* absolute horizontal motion */
			/* fscanf(fp, "%d", &n); */
			while ((c = getc(fp)) == ' ')
				;
			k = 0;
			do {
				k = 10 * k + c - '0';
			} while (isdigit(c = getc(fp)));
			ungetc(c, fp);
			hgoto(k);
			break;
		case 'h':	/* relative horizontal motion */
			/* fscanf(fp, "%d", &n); */
			while ((c = getc(fp)) == ' ')
				;
			k = 0;
			do {
				k = 10 * k + c - '0';
			} while (isdigit(c = getc(fp)));
			ungetc(c, fp);
			hmot(k);
			break;
		case 'w':	/* word space */
			putc(' ', stdout);
			break;
		case 'V':
			fscanf(fp, "%d", &n);
			vgoto(n);
			break;
		case 'v':
			fscanf(fp, "%d", &n);
			vmot(n);
			break;
		case 'p':	/* new page */
			fscanf(fp, "%d", &n);
			t_page(n);
			break;
		case 'n':	/* end of line */
			while (getc(fp) != '\n')
				;
			t_newline();
			break;
		case '#':	/* comment */
			while (getc(fp) != '\n')
				;
			break;
		case 'x':	/* device control */
			devcntrl(fp);
			break;
		default:
			error(!FATAL, "unknown input character %o %c\n", c, c);
			done();
		}
	}
}
Beispiel #9
0
/*
 * Convert a string to an intmax_t
 *
 * Ignores `locale' stuff.  Assumes that the upper and lower case
 * alphabets and digits are each contiguous.
 */
intmax_t
strtoimax(const char *nptr, char **endptr, int base)
{
	const char *s;
	intmax_t acc, cutoff;
	int c;
	int neg, any, cutlim;

	/*
	 * Skip white space and pick up leading +/- sign if any.
	 * If base is 0, allow 0x for hex and 0 for octal, else
	 * assume decimal; if base is already 16, allow 0x.
	 */
	s = nptr;
	do {
		c = (unsigned char) *s++;
	} while (isspace(c));
	if (c == '-') {
		neg = 1;
		c = *s++;
	} else {
		neg = 0;
		if (c == '+')
			c = *s++;
	}
	if ((base == 0 || base == 16) &&
	    c == '0' && (*s == 'x' || *s == 'X')) {
		c = s[1];
		s += 2;
		base = 16;
	}
	if (base == 0)
		base = c == '0' ? 8 : 10;

	/*
	 * Compute the cutoff value between legal numbers and illegal
	 * numbers.  That is the largest legal value, divided by the
	 * base.  An input number that is greater than this value, if
	 * followed by a legal input character, is too big.  One that
	 * is equal to this value may be valid or not; the limit
	 * between valid and invalid numbers is then based on the last
	 * digit.  For instance, if the range for intmax_t is
	 * [-9223372036854775808..9223372036854775807] and the input base
	 * is 10, cutoff will be set to 922337203685477580 and cutlim to
	 * either 7 (neg==0) or 8 (neg==1), meaning that if we have
	 * accumulated a value > 922337203685477580, or equal but the
	 * next digit is > 7 (or 8), the number is too big, and we will
	 * return a range error.
	 *
	 * Set any if any `digits' consumed; make it negative to indicate
	 * overflow.
	 */

	/* BIONIC: avoid division and module for common cases */
#define  CASE_BASE(x) \
            case x:  \
	        if (neg) { \
                    cutlim = INTMAX_MIN % x; \
		    cutoff = INTMAX_MIN / x; \
	        } else { \
		    cutlim = INTMAX_MAX % x; \
		    cutoff = INTMAX_MAX / x; \
		 }; \
		 break

	switch (base) {
            case 4:
                if (neg) {
                    cutlim = (int)(INTMAX_MIN % 4);
                    cutoff = INTMAX_MIN / 4;
                } else {
                    cutlim = (int)(INTMAX_MAX % 4);
                    cutoff = INTMAX_MAX / 4;
                }
                break;

	    CASE_BASE(8);
	    CASE_BASE(10);
	    CASE_BASE(16);
	    default:
	              cutoff  = neg ? INTMAX_MIN : INTMAX_MAX;
		      cutlim  = cutoff % base;
	              cutoff /= base;
	}
#undef CASE_BASE

	if (neg) {
		if (cutlim > 0) {
			cutlim -= base;
			cutoff += 1;
		}
		cutlim = -cutlim;
	}
	for (acc = 0, any = 0;; c = (unsigned char) *s++) {
		if (isdigit(c))
			c -= '0';
		else if (isalpha(c))
			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
		else
			break;
		if (c >= base)
			break;
		if (any < 0)
			continue;
		if (neg) {
			if (acc < cutoff || (acc == cutoff && c > cutlim)) {
				any = -1;
				acc = INTMAX_MIN;
				errno = ERANGE;
			} else {
				any = 1;
				acc *= base;
				acc -= c;
			}
		} else {
			if (acc > cutoff || (acc == cutoff && c > cutlim)) {
				any = -1;
				acc = INTMAX_MAX;
				errno = ERANGE;
			} else {
				any = 1;
				acc *= base;
				acc += c;
			}
		}
	}
	if (endptr != 0)
		*endptr = (char *) (any ? s - 1 : nptr);
	return (acc);
}
Beispiel #10
0
int parse(lcontext_t *ctx, char *pos, int size)
{
	char c = *pos;
	char str[MAX_LINE_LEN];
	char *e;
	int ival;

	if(c == ')') {
		TREE_HEAD->cdr = NULL;
		pop_startBracketCellPtr(TREE_HEAD);
		ctx->bracketsCounter--;
		return T;
	}

	if(size == 1) {
		switch(c) {
			case '(':
				if(!TREE_HEAD) {
					TREE_ROOT = new_consCell(ctx);
					TREE_HEAD = TREE_ROOT;
				}
				else {
					TREE_HEAD->cdr = new_consCell(ctx);
					TREE_HEAD = TREE_HEAD->cdr;
				}
				TREE_HEAD->otype = O_START_BRACKET;
				TREE_HEAD->car = NULL;
				TREE_HEAD->cdr = NULL;
				push_startBracketCellPtr(TREE_HEAD);
				if(ctx->bracketsCounter == -1) ctx->bracketsCounter += 2;
				else ctx->bracketsCounter++;
				return T;
			case '+':
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_ADD;
				return T;
			case '-':
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_SUB;
				return T;
			case '*':
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_MUL;
				return T;
			case '/':
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_DIV;
				return T;
			case '<':
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_LT;
				return T;
			case '>':
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_GT;
				return T;
			case '=':
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_EQ;
				return T;
			default:
				break;
		}
	}

	memcpy(str, pos, size);
	str[size] = '\0';

	switch(c) {
		case '-':
			ival = (int)strtol(str, &e, 10);
			if(*e != '\0') return NIL;
			TREE_HEAD->cdr = new_consCell(ctx);
			TREE_HEAD = TREE_HEAD->cdr;
			TREE_HEAD->otype = O_NUM;
			TREE_HEAD->ivalue = ival;
			return T;
		default:
			if(isdigit(c)) {
				ival = (int)strtol(str, &e, 10);
				if(*e != '\0') return NIL;
				TREE_HEAD->cdr = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->cdr;
				TREE_HEAD->otype = O_NUM;
				TREE_HEAD->ivalue = ival;
				return T;
			}
			else if(size == 2 && !strncmp(str, "<=", 2)) {
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_LE;
				return T;
			}
			else if(size == 2 && !strncmp(str, ">=", 2)) {
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_GE;
				return T;
			}
			else if(size == 2 && !strncmp(str, "if", 2)) {
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_IF;
				return T;
			}
			else if(size == 4 && !strncmp(str, "setq", 4)) {
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_SETQ;
				return T;
			}
			else if(size == 5 && !strncmp(str, "defun", 5)) {
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
				TREE_HEAD->otype = O_DEFUN;
				return T;
			}
			if((TREE_HEAD->otype == O_START_BRACKET) && !TREE_HEAD->car) {
				TREE_HEAD->car = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->car;
			}
			else {
				TREE_HEAD->cdr = new_consCell(ctx);
				TREE_HEAD = TREE_HEAD->cdr;
			}
			TREE_HEAD->otype = O_STRING;
			TREE_HEAD->svalue = (char *)malloc(size + 1);
			memcpy(TREE_HEAD->svalue, pos, size);
			TREE_HEAD->svalue[size] = '\0';
			return T;
	}
}
Beispiel #11
0
void rpn_calculator()
{
	int num = 0, x = 0, prev_num = 0;
	char y = ' ';
	int line_count = 0;

	init();

	while ((x = getchar()) != EOF) {

		if (isdigit(x)) {
			num = num*10 + x - '0';

		} else {

			if (num || (isdigit(y) && num == 0)) {
				push(num);
				prev_num = num; // Save previous number
				num = 0;
			}

			if (size() > MAX_SIZE) {
				while ( getchar() != '\n' ); // flush input
				init();
				printf("line %d: error at %d\n",++line_count,prev_num);
			} else {

			int a = 0;
			int p = peek();
			int s = size();

			switch (x) {

				case '+':
					push(pop()+pop());
					break;

				case '-':
					a = pop();
					push(pop() - a);
					break;

				case '*':
					push(pop()*pop());
					break;

				case '/':
					if (peek() == 0) {
						printf("line %d: error at /\n",++line_count);
						init();

					} else {
						a = pop();
						push(pop() / a);
					}
					break;

				case '\n':
					/* Mostly error finding here */

					/* No operator */
					if (isdigit(y)) {
						printf("line %d: error at \\n\n",++line_count);
						init();
						break;
					}

					/* Single operand and operator */
					else if (p && s < 1 && (y == '+' || y == '-' || y == '*' || y == '/')) {
						printf("line %d: error at %c\n",++line_count,y);
						init();
						break;

					}
					else if (y == x) { /* Empty line case */
						printf("line %d: error at \\n\n",++line_count);
						y = ' ';
						init();
						break;
					}

					/* Pop result from stack */
					else if (size() > 0) {
						printf("line %d: %d\n",++line_count,pop());
						init();
						break;
					}

					init();
					break;

				default:
					/* Illegal char */
					if (x != ' ') {
						printf("line %d: error at %c\n",++line_count,x);
						init();
					}
					break;
				}
			}
		}
		y = x; //save previous char
	}
}
Beispiel #12
0
int
main(int argc, char *argv[])
{
    char *p, *cls = NULL;
    char *cleanenv[1];
    struct passwd * pwd = NULL;
    int rcswhich, shelltype;
    int i, num_limits = 0;
    int ch, doeval = 0, doall = 0;
    login_cap_t * lc = NULL;
    enum { ANY=0, SOFT=1, HARD=2, BOTH=3, DISPLAYONLY=4 } type = ANY;
    enum { RCSUNKNOWN=0, RCSSET=1, RCSSEL=2 } todo = RCSUNKNOWN;
    int which_limits[RLIM_NLIMITS];
    rlim_t set_limits[RLIM_NLIMITS];
    struct rlimit limits[RLIM_NLIMITS];

    /* init resource tables */
    for (i = 0; i < RLIM_NLIMITS; i++) {
	which_limits[i] = 0; /* Don't set/display any */
	set_limits[i] = RLIM_INFINITY;
	/* Get current resource values */
	if (getrlimit(i, &limits[i]) < 0) {
		limits[i].rlim_cur = -1;
		limits[i].rlim_max = -1;
	}
    }

    optarg = NULL;
    while ((ch = getopt(argc, argv, ":EeC:U:BSHabc:d:f:k:l:m:n:s:t:u:v:")) != -1) {
	switch(ch) {
	case 'a':
	    doall = 1;
	    break;
	case 'E':
	    environ = cleanenv;
	    cleanenv[0] = NULL;
	    break;
	case 'e':
	    doeval = 1;
	    break;
	case 'C':
	    cls = optarg;
	    break;
	case 'U':
	    if ((pwd = getpwnam(optarg)) == NULL) {
		if (!isdigit(*optarg) ||
		    (pwd = getpwuid(atoi(optarg))) == NULL) {
		    warnx("invalid user `%s'", optarg);
		    usage();
		}
	    }
	    break;
	case 'H':
	    type = HARD;
	    break;
	case 'S':
	    type = SOFT;
	    break;
	case 'B':
	    type = SOFT|HARD;
	    break;
	default:
	case ':': /* Without arg */
	    if ((p = strchr(rcs_string, optopt)) != NULL) {
		rcswhich = p - rcs_string;

		/*
		 * Backwards compatibility with earlier kernel which might
		 * support fewer resources.
		 */
		if (rcswhich >= RLIM_NLIMITS) {
		    usage();
		    break;
		}
		if (optarg && *optarg == '-') { /* 'arg' is actually a switch */
		    --optind;		/* back one arg, and make arg NULL */
		    optarg = NULL;
		}
		todo = optarg == NULL ? RCSSEL : RCSSET;
		if (type == ANY)
		    type = BOTH;
		which_limits[rcswhich] = optarg ? type : DISPLAYONLY;
		set_limits[rcswhich] = resource_num(rcswhich, optopt, optarg);
		num_limits++;
		break;
	    }
	    /* FALLTHRU */
	case '?':
	    usage();
	}
	optarg = NULL;
    }

    /* If user was specified, get class from that */
    if (pwd != NULL)
	lc = login_getpwclass(pwd);
    else if (cls != NULL && *cls != '\0') {
	lc = login_getclassbyname(cls, NULL);
	if (lc == NULL || strcmp(cls, lc->lc_class) != 0)
	    fprintf(stderr, "login class '%s' non-existent, using %s\n",
		    cls, lc?lc->lc_class:"current settings");
    }

    /* If we have a login class, update resource table from that */
    if (lc != NULL) {
	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
	    char str[40];
	    rlim_t val;

	    /* current value overridden by resourcename or resourcename-cur */
	    sprintf(str, "%s-cur", resources[rcswhich].cap);
	    val = resources[rcswhich].func(lc, resources[rcswhich].cap, limits[rcswhich].rlim_cur, limits[rcswhich].rlim_cur);
	    limits[rcswhich].rlim_cur = resources[rcswhich].func(lc, str, val, val);
	    /* maximum value overridden by resourcename or resourcename-max */
	    sprintf(str, "%s-max", resources[rcswhich].cap);
	    val = resources[rcswhich].func(lc, resources[rcswhich].cap, limits[rcswhich].rlim_max, limits[rcswhich].rlim_max);
	    limits[rcswhich].rlim_max = resources[rcswhich].func(lc, str, val, val);
	}
    }

    /* now, let's determine what we wish to do with all this */

    argv += optind;

    /* If we're setting limits or doing an eval (ie. we're not just
     * displaying), then check that hard limits are not lower than
     * soft limits, and force rasing the hard limit if we need to if
     * we are raising the soft limit, or lower the soft limit if we
     * are lowering the hard limit.
     */
    if ((*argv || doeval) && getuid() == 0) {

	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
	    if (limits[rcswhich].rlim_max != RLIM_INFINITY) {
		if (limits[rcswhich].rlim_cur == RLIM_INFINITY) {
		    limits[rcswhich].rlim_max = RLIM_INFINITY;
		    which_limits[rcswhich] |= HARD;
		} else if (limits[rcswhich].rlim_cur > limits[rcswhich].rlim_max) {
		    if (which_limits[rcswhich] == SOFT) {
			limits[rcswhich].rlim_max = limits[rcswhich].rlim_cur;
			which_limits[rcswhich] |= HARD;
		    }  else if (which_limits[rcswhich] == HARD) {
			limits[rcswhich].rlim_cur = limits[rcswhich].rlim_max;
			which_limits[rcswhich] |= SOFT;
		    } else {
			/* else.. if we're specifically setting both to
			 * silly values, then let it error out.
			 */
		    }
		}
	    }
	}
    }

    /* See if we've overridden anything specific on the command line */
    if (num_limits && todo == RCSSET) {
	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
	    if (which_limits[rcswhich] & HARD)
		limits[rcswhich].rlim_max = set_limits[rcswhich];
	    if (which_limits[rcswhich] & SOFT)
		limits[rcswhich].rlim_cur = set_limits[rcswhich];
	}
    }

    /* If *argv is not NULL, then we are being asked to
     * (perhaps) set environment variables and run a program
     */
    if (*argv) {
	if (doeval) {
	    warnx("-e cannot be used with `cmd' option");
	    usage();
	}

	login_close(lc);

	/* set leading environment variables, like eval(1) */
	while (*argv && (p = strchr(*argv, '='))) {
	    *p = '\0';
	    if (setenv(*argv++, p + 1, 1) == -1)
		err(1, "setenv: cannot set %s=%s", *argv, p + 1);
	    *p = '=';
	}

	/* Set limits */
	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
	    if (doall || num_limits == 0 || which_limits[rcswhich] != 0)
		if (setrlimit(rcswhich, &limits[rcswhich]) == -1)
		    err(1, "setrlimit %s", resources[rcswhich].cap);
	}

	if (*argv == NULL)
	    usage();

	execvp(*argv, argv);
	err(1, "%s", *argv);
    }

    shelltype = doeval ? getshelltype() : SH_NONE;

    if (type == ANY) /* Default to soft limits */
	type = SOFT;

    /* Display limits */
    printf(shellparm[shelltype].cmd,
	   lc ? " for class " : " (current)",
	   lc ? lc->lc_class : "");

    for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
	if (doall || num_limits == 0 || which_limits[rcswhich] != 0) {
	    if (which_limits[rcswhich] == ANY)
		which_limits[rcswhich] = type;
	    if (shellparm[shelltype].lprm[rcswhich].pfx) {
		if (shellparm[shelltype].both && limits[rcswhich].rlim_cur == limits[rcswhich].rlim_max) {
		    print_limit(limits[rcswhich].rlim_max,
				shellparm[shelltype].lprm[rcswhich].divisor,
				shellparm[shelltype].inf,
				shellparm[shelltype].lprm[rcswhich].pfx,
				shellparm[shelltype].lprm[rcswhich].sfx,
				shellparm[shelltype].both);
		} else {
		    if (which_limits[rcswhich] & HARD) {
			print_limit(limits[rcswhich].rlim_max,
				    shellparm[shelltype].lprm[rcswhich].divisor,
				    shellparm[shelltype].inf,
				    shellparm[shelltype].lprm[rcswhich].pfx,
				    shellparm[shelltype].lprm[rcswhich].sfx,
				    shellparm[shelltype].hard);
		    }
		    if (which_limits[rcswhich] & SOFT) {
			print_limit(limits[rcswhich].rlim_cur,
				    shellparm[shelltype].lprm[rcswhich].divisor,
				    shellparm[shelltype].inf,
				    shellparm[shelltype].lprm[rcswhich].pfx,
				    shellparm[shelltype].lprm[rcswhich].sfx,
				    shellparm[shelltype].soft);
		    }
		}
	    }
	}
    }

    login_close(lc);
    exit(EXIT_SUCCESS);
}
Beispiel #13
0
Datei: epd.c Projekt: gcp/sjeng
void setup_epd_line(char* inbuff)
{
  int i = 0;
  int rankp = 0;   // a8
  int rankoffset = 0;
  int fileoffset = 0;
  int j;

  /* 0 : FEN data */
  /* 1 : Active color */
  /* 2 : Castling status */
  /* 3 : EP info */
  /* 4 : 50 move */
  /* 5 : movenumber */
  /* 6 : EPD data */
  int stage = 0;

  static int rankoffsets[] = {110, 98, 86, 74, 62, 50, 38, 26};
 
  /* conversion from algebraic to sjeng internal for ep squares */
  int converterf = (int) 'a';
  int converterr = (int) '1';
  int ep_file, ep_rank, norm_file, norm_rank;
  
  memset(board, frame, sizeof(board));
  
  white_castled = no_castle;
  black_castled = no_castle;

  book_ply = 50;

  rankoffset = rankoffsets[0];

  while (inbuff[i] == ' ') {i++;};

  while((inbuff[i] != '\n') && (inbuff[i] != '\0'))
    {
      if(stage == 0 && isdigit(inbuff[i]))
	{
	  for (j = 0; j < atoi(&inbuff[i]); j++)
	    board[rankoffset + j + fileoffset] = npiece;
	  
	  fileoffset += atoi(&inbuff[i]);
	}
      else if (stage == 0 && inbuff[i] == '/')
	{
	  rankp++;
	  rankoffset = rankoffsets[rankp];	
	  fileoffset = 0;
	}
      else if (stage == 0 && isalpha(inbuff[i]))
	{
	  switch (inbuff[i])
	    {
	    case 'p' : board[rankoffset + fileoffset] = bpawn; break;
	    case 'P' : board[rankoffset + fileoffset] = wpawn; break;	
	    case 'n' : board[rankoffset + fileoffset] = bknight; break;
	    case 'N' : board[rankoffset + fileoffset] = wknight; break;	
	    case 'b' : board[rankoffset + fileoffset] = bbishop; break;
	    case 'B' : board[rankoffset + fileoffset] = wbishop; break;	
	    case 'r' : board[rankoffset + fileoffset] = brook; break;
	    case 'R' : board[rankoffset + fileoffset] = wrook; break;	
	    case 'q' : board[rankoffset + fileoffset] = bqueen; break;
	    case 'Q' : board[rankoffset + fileoffset] = wqueen; break;	
	    case 'k' : 
	      bking_loc = rankoffset + fileoffset;
	      board[bking_loc] = bking; 
	      break;
	    case 'K' :
	      wking_loc = rankoffset + fileoffset;
	      board[wking_loc] = wking; 
	      break;	
	    }
	  fileoffset++;
	}
      else if (inbuff[i] == ' ')
	{
	  stage++;

	  if (stage == 1)
	    {
	      /* skip spaces */
	      while (inbuff[i] == ' ') i++;
	      
	      if (inbuff[i] == 'w') 
		white_to_move = 1;
	      else
		white_to_move = 0;
	    }
	  else if (stage == 2)
	    {
	      /* assume no castling at all */
	      moved[26] = moved[33] = moved[30] = 1;
	      moved[110] = moved[114] = moved[117] = 1;

	      while(inbuff[i] == ' ') i++;
	     
	      while (inbuff[i] != ' ')
		{
		  switch (inbuff[i])
		    {
		    case '-' :
		      break;
		    case 'K' :
		      moved[30] = moved[33] = 0;
		      break;
		    case 'Q' :
		      moved[30] = moved[26] = 0;
		      break;
		    case 'k' :
		      moved[114] = moved[117] = 0;
		      break;
		    case 'q' :
		      moved[114] = moved[110] = 0;
		      break;
		    }
		  i++;
		}
	      i--; /* go back to space so we move to next stage */
	      
	    }
	  else if (stage == 3)
	    {
	      /* skip spaces */
	      while (inbuff[i] == ' ') i++;
	      
	      if (inbuff[i] == '-')
		{
		  ep_square = 0;
		}
	      else
		{
		  ep_file = inbuff[i++];
		  ep_rank = inbuff[i++];
		  
		  norm_file = ep_file - converterf;
		  norm_rank = ep_rank - converterr;
		  
		  ep_square = ((norm_rank * 12) + 26) + (norm_file);		  
		}
	    }
	  else if (stage == 4)
	    {
	      /* ignore this for now */
	    }
	  else if (stage == 5)
	    {
	      /* ignore this for now */
	    }
	  else if (stage == 6)
	    {
	      /* ignore this for now */
	    }	  
	};
      
      i++;
    }

  reset_piece_square();
  initialize_hash();

}
Beispiel #14
0
static inline const char *
parse_format(const char *s, char *format, int *len)
{
    grub_bool done = FALSE;
    grub_bool allowminus = FALSE;
    grub_bool dot = FALSE;
    grub_bool err = FALSE;
    char *fmt = format;
    int prec = 0;
    int width = 0;
    int value = 0;

    *len = 0;
    *format++ = '%';
    while (*s != '\0' && !done) {
	switch (*s) {
	case 'c':		/* FALLTHRU */
	case 'd':		/* FALLTHRU */
	case 'o':		/* FALLTHRU */
	case 'x':		/* FALLTHRU */
	case 'X':		/* FALLTHRU */
	case 's':
	    *format++ = *s;
	    done = TRUE;
	    break;
	case '.':
	    *format++ = *s++;
	    if (dot) {
		err = TRUE;
	    } else {
		dot = TRUE;
		prec = value;
	    }
	    value = 0;
	    break;
	case '#':
	    *format++ = *s++;
	    break;
	case ' ':
	    *format++ = *s++;
	    break;
	case ':':
	    s++;
	    allowminus = TRUE;
	    break;
	case '-':
	    if (allowminus) {
		*format++ = *s++;
	    } else {
		done = TRUE;
	    }
	    break;
	default:
	    if (isdigit(*s)) {
		value = (value * 10) + (*s - '0');
		if (value > 10000)
		    err = TRUE;
		*format++ = *s++;
	    } else {
		done = TRUE;
	    }
	}
    }

    /*
     * If we found an error, ignore (and remove) the flags.
     */
    if (err) {
	prec = width = value = 0;
	format = fmt;
	*format++ = '%';
	*format++ = *s;
    }

    if (dot)
	width = value;
    else
	prec = value;

    *format = '\0';
    /* return maximum string length in print */
    *len = (prec > width) ? prec : width;
    return s;
}
Beispiel #15
0
unsigned long long _str2num(const char *string, unsigned base, int sign)
{
	unsigned long long result = 0;
	int length = 0;
	int negative = 0;
	int count = 0;

	if (!string)
	{
		errno = ERR_NULLPARAMETER;
		return (0);
	}

	// Get the length of the string
	length = strlen(string);

	if (sign && (string[0] == '-'))
	{
		negative = 1;
		count += 1;
	}

	// Do a loop to iteratively add to the value of 'result'.
	for ( ; count < length; count ++)
	{
		switch (base)
		{
			case 10:
				if (!isdigit(string[count]))
				{
					errno = ERR_INVALID;
					goto out;
				}
				result *= base;
				result += (string[count] - '0');
				break;

			case 16:
				if (!isxdigit(string[count]))
				{
					errno = ERR_INVALID;
					goto out;
				}
				result *= base;
				if ((string[count] >= '0') && (string[count] <= '9'))
					result += (string[count] - '0');
				else if ((string[count] >= 'a') && (string[count] <= 'f'))
					result += ((string[count] - 'a') + 10);
				else
					result += ((string[count] - 'A') + 10);
				break;

			default:
				errno = ERR_NOTIMPLEMENTED;
				goto out;
		}
	}

out:
	if (negative)
		result = ((long long) result * -1);

	return (result);
}
Beispiel #16
0
int G__oldsite_get(FILE * ptr, Site * s, int fmt)

/*-
 * Reads ptr and returns 0 on success,
 *                      -1 on EOF,
 *                      -2 on other fatal error or insufficient data,
 *                       1 on format mismatch (extra data)
 */
{
    char sbuf[MAX_SITE_LEN], *buf, *last, *p1, *p2;
    char ebuf[128], nbuf[128];
    int n = 0, d = 0, c = 0, dim = 0, err = 0, tmp;

    buf = sbuf;

    if ((buf = fgets(sbuf, 1024, ptr)) == (char *)NULL)
	return EOF;

    while ((*buf == '#' || !isdigit(*buf)) && *buf != '-' && *buf != '+')
	if ((buf = fgets(sbuf, 1024, ptr)) == (char *)NULL)
	    return EOF;

    if (buf[strlen(buf) - 1] == '\n')
	buf[strlen(buf) - 1] = '\0';

    if (sscanf(buf, "%[^|]|%[^|]|%*[^\n]", ebuf, nbuf) < 2) {
	fprintf(stderr, "ERROR: ebuf %s nbuf %s\n", ebuf, nbuf);
	return -2;
    }

    if (!G_scan_northing(nbuf, &(s->north), fmt) ||
	!G_scan_easting(ebuf, &(s->east), fmt)) {
	fprintf(stderr, "ERROR: ebuf %s nbuf %s\n", ebuf, nbuf);
	return -2;
    }

    /* move pointer past easting and northing fields */
    if (NULL == (buf = strchr(buf, PIPE)))
	return -2;
    if (NULL == (buf = strchr(buf + 1, PIPE)))
	return -2;

    /* check for remaining dimensional fields */
    do {
	buf++;
	if (isnull(*buf))
	    return (FOUND_ALL(s, n, dim, c, d) ? 0 : -2);
	last = buf;
	if (dim < s->dim_alloc) {	/* should be more dims to read */
	    if (sscanf(buf, "%lf|", &(s->dim[dim++])) < 1)
		return -2;	/* no more dims, though expected */
	}
	else if (NULL != (p1 = strchr(buf, PIPE))) {
	    if (NULL == (p2 = strchr(buf, DQUOTE)))
		err = 1;	/* more dims, though none expected */
	    else if (strlen(p1) > strlen(p2))
		err = 1;	/* more dims, though none expected */
	}
    } while ((buf = strchr(buf, PIPE)) != NULL);
    buf = last;

    /* no more dimensions-now we parse attribute fields */
    while (!isnull(*buf)) {
	switch (*buf) {
	case '#':		/* category field */
	    if (n == 0) {
		switch (s->cattype) {
		case CELL_TYPE:
		    if (sscanf(buf, "#%d", &s->ccat) == 1)
			n++;
		    break;
		case FCELL_TYPE:
		    if (sscanf(buf, "#%f", &s->fcat) == 1)
			n++;
		    break;
		case DCELL_TYPE:
		    if (sscanf(buf, "#%lf", &s->dcat) == 1)
			n++;
		    break;
		default:
		    err = 1;	/* has cat, none expected */
		    break;
		}
	    }
	    else {
		err = 1;	/* extra cat */
	    }

	    /* move to beginning of next attribute */
	    if ((buf = next_att(buf)) == (char *)NULL)
		return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    break;

	case '%':		/* decimal attribute */
	    if (d < s->dbl_alloc) {
		p1 = ++buf;
		errno = 0;
		s->dbl_att[d++] = strtod(buf, &p1);
		if (p1 == buf || errno == ERANGE) {
		    /* replace with:
		     * s->dbl_att[d - 1] = NAN
		     * when we add NULL attribute support
		     */
		    return -2;
		}
		/* err = 0; Make sure this is zeroed */
	    }
	    else {
		err = 1;	/* extra decimal */
	    }

	    if ((buf = next_att(buf)) == (char *)NULL) {
		return (FOUND_ALL(s, n, dim, c, d)) ? err : -2;
	    }
	    break;
	case '@':		/* string attribute */
	    if (isnull(*buf) || isnull(*(buf + 1)))
		return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    else
		buf++;
	default:		/* defaults to string attribute */
	    /* allow both prefixed and unprefixed strings */
	    if (c < s->str_alloc) {
		if ((tmp = cleanse_string(buf)) > 0) {
		    strncpy(s->str_att[c++], buf, tmp);
		    buf += tmp;
		}
		else
		    return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    }
	    if ((buf = next_att(buf)) == (char *)NULL) {
		return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
	    }
	    break;
	}
    }

    return (FOUND_ALL(s, n, dim, c, d) ? err : -2);
}
Beispiel #17
0
char inputfile::ReadLetter(truth AbortOnEOF)
{
  for(int Char = fgetc(Buffer); !feof(Buffer); Char = fgetc(Buffer))
  {
    if(isalpha(Char) || isdigit(Char))
      return Char;

    if(ispunct(Char))
    {
      if(Char == '/')
      {
	if(!feof(Buffer))
	{
	  Char = fgetc(Buffer);

	  if(Char == '*')
	  {
	    long StartPos = TellPos();
	    int OldChar = 0, CommentLevel = 1;

	    for(;;)
	    {
	      if(feof(Buffer))
		ABORT("Unterminated comment in file %s, "
		      "beginning at line %ld!",
		      FileName.CStr(), TellLineOfPos(StartPos));

	      Char = fgetc(Buffer);

	      if(OldChar != '*' || Char != '/')
	      {
		if(OldChar != '/' || Char != '*')
		  OldChar = Char;
		else
		{
		  ++CommentLevel;
		  OldChar = 0;
		}
	      }
	      else
	      {
		if(!--CommentLevel)
		  break;
		else
		  OldChar = 0;
	      }
	    }

	    continue;
	  }
	  else
	    ungetc(Char, Buffer);
	}

	return '/';
      }

      return Char;
    }
  }

  if(AbortOnEOF)
    ABORT("Unexpected end of file %s!", FileName.CStr());

  return 0;
}
Beispiel #18
0
int G_oldsite_describe(FILE * ptr, int *dims, int *cat, int *strs, int *dbls)

/*-
 * Tries to guess the format of a sites list (the dimensionality,
 * the presence/type of a category, and the number of string and decimal
 * attributes) by reading the first record in the file.
 * Reads ptr and returns 0 on success,
 *                      -1 on EOF,
 *                      -2 for other error.
 */
{
    char sbuf[MAX_SITE_LEN], *buf;
    char ebuf[128], nbuf[128];
    int err;
    int itmp;
    float ftmp;

    if (G_ftell(ptr) != 0L) {
	fprintf(stderr,
		"\nPROGRAMMER ERROR: G_oldsite_describe() must be called\n");
	fprintf(stderr, "        immediately after G_fopen_sites_old()\n");
	return -2;
    }

    *dims = *strs = *dbls = 0;
    *cat = -1;
    buf = sbuf;

    if ((buf = fgets(sbuf, 1024, ptr)) == (char *)NULL) {
	rewind(ptr);
	return EOF;
    }
    /* skip over comment & header lines */
    while ((*buf == '#' || !isdigit(*buf)) && *buf != '-' && *buf != '+')
	if ((buf = fgets(sbuf, 1024, ptr)) == (char *)NULL) {
	    rewind(ptr);
	    return EOF;
	}

    if (buf[strlen(buf) - 1] == '\n')
	buf[strlen(buf) - 1] = '\0';

    if ((err = sscanf(buf, "%[^|]|%[^|]|%*[^\n]", ebuf, nbuf)) < 2) {
	fprintf(stderr, "ERROR: ebuf %s nbuf %s\n", ebuf, nbuf);
	rewind(ptr);
	return -2;
    }
    *dims = 2;

    /* move pointer past easting and northing fields */
    while (!ispipe(*buf) && !isnull(*buf))
	buf++;
    if (!isnull(*buf) && !isnull(*(buf + 1)))
	buf++;
    else {
	rewind(ptr);
	return -2;
    }
    while (!ispipe(*buf) && !isnull(*buf))
	buf++;
    if (!isnull(*buf) && !isnull(*(buf + 1)))
	buf++;
    else {
	rewind(ptr);
	return 0;
    }

    /* check for remaining dimensional fields */
    while (strchr(buf, PIPE) != (char *)NULL) {
	(*dims)++;
	while (!ispipe(*buf) && !isnull(*buf))
	    buf++;
	if (isnull(*buf) || isnull(*(buf + 1))) {
	    rewind(ptr);
	    return 0;
	}
	if (!isnull(*(buf + 1)))
	    buf++;
	else {
	    rewind(ptr);
	    return -2;
	}
    }

    /* no more dimensions-now we parse attribute fields */
    while (!isnull(*buf)) {
	switch (*buf) {
	case '#':		/* category field */
	    sscanf(buf, "#%s ", ebuf);
	    if (strstr(ebuf, ".") == NULL && sscanf(ebuf, "%d", &itmp) == 1)
		*cat = CELL_TYPE;
	    else if (strstr(ebuf, ".") != NULL &&
		     sscanf(ebuf, "%f", &ftmp) == 1)
		*cat = FCELL_TYPE;
	    else
		*cat = -1;

	    /* move to beginning of next attribute */
	    while (!isspace(*buf) && !isnull(*buf))
		buf++;
	    if (isnull(*buf) || isnull(*(buf + 1))) {
		rewind(ptr);
		return 0;
	    }
	    else
		buf++;
	    break;
	case '%':		/* decimal attribute */
	    (*dbls)++;
	    /* move to beginning of next attribute */
	    while (!isspace(*buf) && !isnull(*buf))
		buf++;
	    if (isnull(*buf) || isnull(*(buf + 1))) {
		rewind(ptr);
		return 0;
	    }
	    else
		buf++;
	    break;
	case '@':		/* string attribute */
	    if (isnull(*buf) || isnull(*(buf + 1))) {
		rewind(ptr);
		return 0;
	    }
	    else
		buf++;
	default:		/* defaults to string attribute */
	    /* allow both prefixed and unprefixed strings */
	    if ((err = cleanse_string(buf)) > 0) {
		(*strs)++;
		buf += err;
	    }

	    /* move to beginning of next attribute */
	    while (!isspace(*buf) && !isnull(*buf))
		buf++;
	    if (isnull(*buf) || isnull(*(buf + 1))) {
		rewind(ptr);
		return 0;
	    }
	    else
		buf++;
	    break;
	}
    }

    rewind(ptr);
    return 0;
}
Beispiel #19
0
void
sink(int argc, char **argv)
{
	static BUF buffer;
	struct stat stb;
	enum {
		YES, NO, DISPLAYED
	} wrerr;
	BUF *bp;
	off_t i;
	size_t j, count;
	int amt, exists, first, ofd;
	mode_t mode, omode, mask;
	off_t size, statbytes;
	int setimes, targisdir, wrerrno = 0;
	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
	struct timeval tv[2];

#define	atime	tv[0]
#define	mtime	tv[1]
#define	SCREWUP(str)	{ why = str; goto screwup; }

	setimes = targisdir = 0;
	mask = umask(0);
	if (!pflag)
		(void) umask(mask);
	if (argc != 1) {
		run_err("ambiguous target");
		exit(1);
	}
	targ = *argv;
	if (targetshouldbedirectory)
		verifydir(targ);

	(void) atomicio(vwrite, remout, "", 1);
	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
		targisdir = 1;
	for (first = 1;; first = 0) {
		cp = buf;
		if (atomicio(read, remin, cp, 1) != 1)
			return;
		if (*cp++ == '\n')
			SCREWUP("unexpected <newline>");
		do {
			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
				SCREWUP("lost connection");
			*cp++ = ch;
		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
		*cp = 0;
		if (verbose_mode)
			fprintf(stderr, "Sink: %s", buf);

		if (buf[0] == '\01' || buf[0] == '\02') {
			if (iamremote == 0)
				(void) atomicio(vwrite, STDERR_FILENO,
				    buf + 1, strlen(buf + 1));
			if (buf[0] == '\02')
				exit(1);
			++errs;
			continue;
		}
		if (buf[0] == 'E') {
			(void) atomicio(vwrite, remout, "", 1);
			return;
		}
		if (ch == '\n')
			*--cp = 0;

		cp = buf;
		if (*cp == 'T') {
			setimes++;
			cp++;
			mtime.tv_sec = strtol(cp, &cp, 10);
			if (!cp || *cp++ != ' ')
				SCREWUP("mtime.sec not delimited");
			mtime.tv_usec = strtol(cp, &cp, 10);
			if (!cp || *cp++ != ' ')
				SCREWUP("mtime.usec not delimited");
			atime.tv_sec = strtol(cp, &cp, 10);
			if (!cp || *cp++ != ' ')
				SCREWUP("atime.sec not delimited");
			atime.tv_usec = strtol(cp, &cp, 10);
			if (!cp || *cp++ != '\0')
				SCREWUP("atime.usec not delimited");
			(void) atomicio(vwrite, remout, "", 1);
			continue;
		}
		if (*cp != 'C' && *cp != 'D') {
			/*
			 * Check for the case "rcp remote:foo\* local:bar".
			 * In this case, the line "No match." can be returned
			 * by the shell before the rcp command on the remote is
			 * executed so the ^Aerror_message convention isn't
			 * followed.
			 */
			if (first) {
				run_err("%s", cp);
				exit(1);
			}
			SCREWUP("expected control record");
		}
		mode = 0;
		for (++cp; cp < buf + 5; cp++) {
			if (*cp < '0' || *cp > '7')
				SCREWUP("bad mode");
			mode = (mode << 3) | (*cp - '0');
		}
		if (*cp++ != ' ')
			SCREWUP("mode not delimited");

		for (size = 0; isdigit(*cp);)
			size = size * 10 + (*cp++ - '0');
		if (*cp++ != ' ')
			SCREWUP("size not delimited");
		if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
			run_err("error: unexpected filename: %s", cp);
			exit(1);
		}
		if (targisdir) {
			static char *namebuf;
			static size_t cursize;
			size_t need;

			need = strlen(targ) + strlen(cp) + 250;
			if (need > cursize) {
				free(namebuf);
				namebuf = xmalloc(need);
				cursize = need;
			}
			(void) snprintf(namebuf, need, "%s%s%s", targ,
			    strcmp(targ, "/") ? "/" : "", cp);
			np = namebuf;
		} else
			np = targ;
		curfile = cp;
		exists = stat(np, &stb) == 0;
		if (buf[0] == 'D') {
			int mod_flag = pflag;
			if (!iamrecursive)
				SCREWUP("received directory without -r");
			if (exists) {
				if (!S_ISDIR(stb.st_mode)) {
					errno = ENOTDIR;
					goto bad;
				}
				if (pflag)
					(void) chmod(np, mode);
			} else {
				/* Handle copying from a read-only
				   directory */
				mod_flag = 1;
				if (mkdir(np, mode | S_IRWXU) < 0)
					goto bad;
			}
			vect[0] = xstrdup(np);
			sink(1, vect);
			if (setimes) {
				setimes = 0;
				if (utimes(vect[0], tv) < 0)
					run_err("%s: set times: %s",
					    vect[0], strerror(errno));
			}
			if (mod_flag)
				(void) chmod(vect[0], mode);
			free(vect[0]);
			continue;
		}
		omode = mode;
		mode |= S_IWUSR;
		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
bad:			run_err("%s: %s", np, strerror(errno));
			continue;
		}
		(void) atomicio(vwrite, remout, "", 1);
		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
			(void) close(ofd);
			continue;
		}
		cp = bp->buf;
		wrerr = NO;

		statbytes = 0;
		if (showprogress)
			start_progress_meter(curfile, size, &statbytes);
		set_nonblock(remin);
		for (count = i = 0; i < size; i += bp->cnt) {
			amt = bp->cnt;
			if (i + amt > size)
				amt = size - i;
			count += amt;
			do {
				j = atomicio6(read, remin, cp, amt,
				    scpio, &statbytes);
				if (j == 0) {
					run_err("%s", j != EPIPE ?
					    strerror(errno) :
					    "dropped connection");
					exit(1);
				}
				amt -= j;
				cp += j;
			} while (amt > 0);

			if (count == bp->cnt) {
				/* Keep reading so we stay sync'd up. */
				if (wrerr == NO) {
					if (atomicio(vwrite, ofd, bp->buf,
					    count) != count) {
						wrerr = YES;
						wrerrno = errno;
					}
				}
				count = 0;
				cp = bp->buf;
			}
		}
		unset_nonblock(remin);
		if (showprogress)
			stop_progress_meter();
		if (count != 0 && wrerr == NO &&
		    atomicio(vwrite, ofd, bp->buf, count) != count) {
			wrerr = YES;
			wrerrno = errno;
		}
		if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
		    ftruncate(ofd, size) != 0) {
			run_err("%s: truncate: %s", np, strerror(errno));
			wrerr = DISPLAYED;
		}
		if (pflag) {
			if (exists || omode != mode)
#ifdef HAVE_FCHMOD
				if (fchmod(ofd, omode)) {
#else /* HAVE_FCHMOD */
				if (chmod(np, omode)) {
#endif /* HAVE_FCHMOD */
					run_err("%s: set mode: %s",
					    np, strerror(errno));
					wrerr = DISPLAYED;
				}
		} else {
			if (!exists && omode != mode)
#ifdef HAVE_FCHMOD
				if (fchmod(ofd, omode & ~mask)) {
#else /* HAVE_FCHMOD */
				if (chmod(np, omode & ~mask)) {
#endif /* HAVE_FCHMOD */
					run_err("%s: set mode: %s",
					    np, strerror(errno));
					wrerr = DISPLAYED;
				}
		}
		if (close(ofd) == -1) {
			wrerr = YES;
			wrerrno = errno;
		}
		(void) response();
		if (setimes && wrerr == NO) {
			setimes = 0;
			if (utimes(np, tv) < 0) {
				run_err("%s: set times: %s",
				    np, strerror(errno));
				wrerr = DISPLAYED;
			}
		}
		switch (wrerr) {
		case YES:
			run_err("%s: %s", np, strerror(wrerrno));
			break;
		case NO:
			(void) atomicio(vwrite, remout, "", 1);
			break;
		case DISPLAYED:
			break;
		}
	}
screwup:
	run_err("protocol error: %s", why);
	exit(1);
}

int
response(void)
{
	char ch, *cp, resp, rbuf[2048];

	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
		lostconn(0);

	cp = rbuf;
	switch (resp) {
	case 0:		/* ok */
		return (0);
	default:
		*cp++ = resp;
		/* FALLTHROUGH */
	case 1:		/* error, followed by error msg */
	case 2:		/* fatal error, "" */
		do {
			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
				lostconn(0);
			*cp++ = ch;
		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');

		if (!iamremote)
			(void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
		++errs;
		if (resp == 1)
			return (-1);
		exit(1);
	}
	/* NOTREACHED */
}

void
usage(void)
{
	(void) fprintf(stderr,
	    "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
	    "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
	    "           [[[email protected]]host1:]file1 ... [[[email protected]]host2:]file2\n");
	exit(1);
}
Beispiel #20
0
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
int ExtractWmo(const std::vector<std::string>& pArchiveNames)
{

    char* szListFile = "";
    char   szLocalFile[MAX_PATH] = "";
    HANDLE hMpq = "";
    BOOL bResult = FALSE;

    //const char* ParsArchiveNames[] = {"patch-2.MPQ", "patch.MPQ", "common.MPQ", "expansion.MPQ"};

    int nError = ERROR_SUCCESS;
    if(szListFile == NULL || *szListFile == 0)
        szListFile = NULL;
    //char tmp[1024];
    //for (size_t i=0; i<4; i++)
    for (size_t i=0; i<pArchiveNames.size(); i++)
    {

        //sprintf(tmp,"%s\\%s", input_path, ParsArchiveNames[i]);
        //if(!SFileOpenArchive(tmp, 0, 0, &hMpq))
        if(!SFileOpenArchive(pArchiveNames[i].c_str(), 0, 0, &hMpq))
            printf("NOT open!!! %s\n",pArchiveNames[i].c_str());

        // Copy files from archive
        if(nError == ERROR_SUCCESS)
        {
            SFILE_FIND_DATA wf;
            HANDLE hFind = SFileFindFirstFile(hMpq,"*.wmo*", &wf, szListFile);
            bResult = TRUE;

            while(hFind != NULL && bResult == TRUE)
            {
                ShowProcessedFile(wf.cFileName);
                SFileSetLocale(wf.lcLocale);
                sprintf(szLocalFile, "%s\\%s", szWorkDirWmo, GetPlainName(wf.cFileName));
                fixnamen(szLocalFile,strlen(szLocalFile));
                FILE * n;
                if ((n = fopen(szLocalFile, "rb"))== NULL)
                {
                    int p = 0;
                    //Select root wmo files
                    const char * rchr = strrchr(GetPlainName(wf.cFileName),0x5f);
                    if(rchr != NULL)
                    {
                        char cpy[4];
                        strncpy((char*)cpy,rchr,4);
                        for (int i=0;i<4;i++)
                        {
                            int m = cpy[i];
                            if(isdigit(m))
                                p++;
                        }
                    }
                    if(p != 3)
                    {
                        //printf("RootWmo!\n");
                        string s = wf.cFileName;
                        WMORoot * froot = new WMORoot(s);
                        if(!froot->open())
                        {
                            printf("Not open RootWmo!!!\n");
                            bResult = SFileFindNextFile(hFind, &wf);
                            continue;
                        }
                         FILE *output=fopen(szLocalFile,"wb");
                        froot->ConvertToVMAPRootWmo(output);
                        int Wmo_nVertices = 0;
                        if(froot->nGroups !=0)
                        {
                            for (int i=0; i<froot->nGroups; i++)
                            {
                                char temp[512];
                                strcpy(temp, wf.cFileName);
                                temp[strlen(wf.cFileName)-4] = 0;
                                char groupFileName[512];
                                sprintf(groupFileName,"%s_%03d.wmo",temp, i);
                                printf("%s\n",groupFileName);
                                //printf("GroupWmo!\n");
                                string s = groupFileName;
                                WMOGroup * fgroup = new WMOGroup(s);
                                if(!fgroup->open())
                                {
                                    printf("Not all open Group file for: %s\n",GetPlainName(wf.cFileName));
                                    bResult = SFileFindNextFile(hFind, &wf);
                                    break;
                                }
                                Wmo_nVertices += fgroup->ConvertToVMAPGroupWmo(output, preciseVectorData);
                            }
                        }
                        fseek(output, 8, SEEK_SET); // store the correct no of vertices
                        fwrite(&Wmo_nVertices,sizeof(int),1,output);
                        fclose(output);
                    }
                } else {
                    fclose(n);
                }
                wf.dwFileFlags &= ~MPQ_FILE_HAS_EXTRA;
                wf.dwFileFlags &= ~MPQ_FILE_EXISTS;
                // Find the next file
                bResult = SFileFindNextFile(hFind, &wf);
            }
            // Delete the extracted file in the case of an error
            if(nError != ERROR_SUCCESS)
                DeleteFile(szLocalFile);
            // Close the search handle
            if(hFind != NULL)
                SFileFindClose(hFind);

        }
    }
    // Close both archives
    if(hMpq != NULL)
        //SFileCloseArchive(hMpq);
        if(nError == ERROR_SUCCESS)
            printf("\nExtract wmo complete (No errors)\n");

    return nError;

}
Beispiel #21
0
static size_t dopr(char *buffer, size_t maxlen, const char *format,
	va_list args)
{
	char ch;
	LLONG value;
	LDOUBLE fvalue;
	char *strvalue;
	int min;
	int max;
	int state;
	int flags;
	int cflags;
	size_t currlen;

	state = DP_S_DEFAULT;
	currlen = flags = cflags = min = 0;
	max = -1;
	ch = *format++;

	while (state != DP_S_DONE) {
		if (ch == '\0')
			state = DP_S_DONE;

		switch(state) {
		case DP_S_DEFAULT:
			if (ch == '%')
				state = DP_S_FLAGS;
			else
				dopr_outch (buffer, &currlen, maxlen, ch);
			ch = *format++;
			break;
		case DP_S_FLAGS:
			switch (ch) {
			case '-':
				flags |= DP_F_MINUS;
				ch = *format++;
				break;
			case '+':
				flags |= DP_F_PLUS;
				ch = *format++;
				break;
			case ' ':
				flags |= DP_F_SPACE;
				ch = *format++;
				break;
			case '#':
				flags |= DP_F_NUM;
				ch = *format++;
				break;
			case '0':
				flags |= DP_F_ZERO;
				ch = *format++;
				break;
			default:
				state = DP_S_MIN;
				break;
			}
			break;
		case DP_S_MIN:
			if (isdigit((unsigned char)ch)) {
				min = 10*min + char_to_int (ch);
				ch = *format++;
			} else if (ch == '*') {
				min = va_arg (args, int);
				ch = *format++;
				state = DP_S_DOT;
			} else {
				state = DP_S_DOT;
			}
			break;
		case DP_S_DOT:
			if (ch == '.') {
				state = DP_S_MAX;
				ch = *format++;
			} else {
				state = DP_S_MOD;
			}
			break;
		case DP_S_MAX:
			if (isdigit((unsigned char)ch)) {
				if (max < 0)
					max = 0;
				max = 10*max + char_to_int (ch);
				ch = *format++;
			} else if (ch == '*') {
				max = va_arg (args, int);
				ch = *format++;
				state = DP_S_MOD;
			} else {
Beispiel #22
0
DWORD
CTGetPidOfCmdLine(
    PCSTR programName,
    PCSTR programFilename,
    PCSTR cmdLine,
    uid_t owner,
    pid_t *pid,
    size_t *count
    )
{
    DWORD ceError = ERROR_NOT_SUPPORTED;
    size_t fillCount = 0;
    size_t foundCount = 0;
    struct stat findStat;
#if HAVE_DECL_PSTAT_GETPROC
    //HPUX should have this
    struct pst_status mystatus;
    struct pst_status status[10];
    int inBuffer;
    int i;
#endif
#ifdef HAVE_STRUCT_PSINFO
    //Solaris and AIX should have this
    DIR *dir = NULL;
    struct dirent *dirEntry = NULL;
    PSTR filePath = NULL;
    struct psinfo infoStruct;
    FILE *infoFile = NULL;
    struct stat compareStat;
    BOOLEAN bFileExists;
#endif
#if defined(HAVE_KVM_GETPROCS) && HAVE_DECL_KERN_PROC_PATHNAME
    //FreeBSD has this
    char pathBuffer[MAXPATHLEN];
    size_t len;
    int unfilteredCount;
    kvm_t *kd = NULL;
    struct kinfo_proc *procs;
    int i;
    struct kinfo_proc *pos;
    int sysctlName[4] = {
        CTL_KERN,
        KERN_PROC,
        KERN_PROC_PATHNAME,
        0 };
#endif

    if(count)
    {
        fillCount = *count;
        *count = 0;
    }
    else if(pid != NULL)
        fillCount = 1;

    if(programFilename != NULL)
    {
        while(stat(programFilename, &findStat) < 0)
        {
            if(errno == EINTR)
                continue;
            GCE(ceError = LwMapErrnoToLwError(errno));
        }
    }
    
#if HAVE_DECL_PSTAT_GETPROC
    //First get the process info for this process
    inBuffer = pstat_getproc(&mystatus, sizeof(mystatus), 0,
            getpid());
    if(inBuffer != 1)
        GCE(ceError = LwMapErrnoToLwError(errno));

    //Now look at all processes
    inBuffer = pstat_getproc(status, sizeof(status[0]),
            sizeof(status)/sizeof(status[0]), 0);
    if(inBuffer < 0)
        GCE(ceError = LwMapErrnoToLwError(errno));
    while(inBuffer > 0)
    {
        for(i = 0; i < inBuffer; i++)
        {
            if(memcmp(&mystatus.pst_rdir, &status[i].pst_rdir,
                        sizeof(mystatus.pst_rdir)))
            {
                /* This process has a different root directory (it is being run
                   via a chroot). Let's not count this process as a match. */
                continue;
            }
            if (owner != (uid_t)-1 && owner != status[i].pst_euid)
            {
                continue;
            }
            if (programName != NULL && strcmp(status[i].pst_ucomm, programName))
            {
                continue;
            }
            if (cmdLine != NULL && strcmp(status[i].pst_cmd, cmdLine))
            {
                continue;
            }
            if(programFilename != NULL && (
                    status[i].pst_text.psf_fileid != findStat.st_ino ||
                    status[i].pst_text.psf_fsid.psfs_id != findStat.st_dev ||
                    status[i].pst_text.psf_fsid.psfs_type != findStat.st_fstype
                    ))
            {
                continue;
            }
 
            //This is a match
            if(foundCount < fillCount)
                pid[foundCount] = status[i].pst_pid;
            foundCount++;
        }
        //Continue looking at the process list where we left off
        inBuffer = pstat_getproc(status, sizeof(status[0]),
                sizeof(status)/sizeof(status[0]),
                status[inBuffer - 1].pst_idx + 1);
        if(inBuffer < 0)
            GCE(ceError = LwMapErrnoToLwError(errno));
    }
    ceError = ERROR_SUCCESS;
#endif

#ifdef HAVE_STRUCT_PSINFO
    if ((dir = opendir("/proc")) == NULL) {
        GCE(ceError = LwMapErrnoToLwError(errno));
    }

    while(1)
    {
        errno = 0;
        dirEntry = readdir(dir);
        if(dirEntry == NULL)
        {
            if(errno != 0)
                GCE(ceError = LwMapErrnoToLwError(errno));
            else
            {
                //No error here. We simply read the last entry
                break;
            }
        }
        if(dirEntry->d_name[0] == '.')
            continue;
        // On AIX, there is a /proc/sys which does not contain a psinfo
        if(!isdigit((int)dirEntry->d_name[0]))
            continue;
        CT_SAFE_FREE_STRING(filePath);
        GCE(ceError = CTAllocateStringPrintf(&filePath, "/proc/%s/psinfo",
                    dirEntry->d_name));
        GCE(ceError = CTCheckFileOrLinkExists(filePath, &bFileExists));
        if(!bFileExists)
        {
            // On AIX 6.1, a defunct process can lack a psinfo file.
            continue;
        }
        GCE(ceError = CTSafeCloseFile(&infoFile));
        GCE(ceError = CTOpenFile(filePath, "r", &infoFile));
        if(fread(&infoStruct, sizeof(infoStruct), 1, infoFile) != 1)
        {
            GCE(ceError = LwMapErrnoToLwError(errno));
        }

        if (owner != (uid_t)-1 && owner != infoStruct.pr_euid)
        {
            continue;
        }
        if (programName != NULL && strcmp(infoStruct.pr_fname, programName))
        {
            continue;
        }
        if (cmdLine != NULL && strcmp(infoStruct.pr_psargs, cmdLine))
        {
            continue;
        }
        if(programFilename != NULL)
        {
            CT_SAFE_FREE_STRING(filePath);
            GCE(ceError = CTAllocateStringPrintf(&filePath,
                        "/proc/%s/object/a.out",
                        dirEntry->d_name));

            while(stat(filePath, &compareStat) < 0)
            {
                if(errno == EINTR)
                    continue;
                if(errno == ENOENT || errno == ENOTDIR)
                {
                    //This process wasn't executed from a file?
                    goto not_match;
                }
                GCE(ceError = LwMapErrnoToLwError(errno));
            }
            if(findStat.st_ino != compareStat.st_ino)
                continue;
            if(findStat.st_dev != compareStat.st_dev)
                continue;
            if(findStat.st_rdev != compareStat.st_rdev)
                continue;
        }
 
        //This is a match
        if(foundCount < fillCount)
            pid[foundCount] = infoStruct.pr_pid;
        foundCount++;
not_match:
        ;
    }
#endif

#if defined(HAVE_KVM_GETPROCS) && HAVE_DECL_KERN_PROC_PATHNAME
    kd = kvm_open(NULL, "/dev/null", NULL, O_RDONLY, NULL);
    if (kd == NULL)
        GCE(ceError = DWORD_ACCESS_DENIED);

    procs = kvm_getprocs(kd, KERN_PROC_PROC, 0, &unfilteredCount);
    if (procs == NULL)
        GCE(ceError = DWORD_ACCESS_DENIED);

    pos = procs;
    for(i = 0; i < unfilteredCount; i++,
        pos = (struct kinfo_proc *)((char *)pos + pos->ki_structsize))
    {
        if (owner != (uid_t)-1 && owner != pos->ki_uid)
        {
            continue;
        }
        if (programName != NULL && strcmp(pos->ki_comm, programName))
        {
            continue;
        }
        if (cmdLine != NULL)
        {
            char **args = kvm_getargv(kd, pos, 0);
            char **argPos = args;
            PCSTR cmdLinePos = cmdLine;

            while (*cmdLinePos != '\0')
            {
                if (argPos == NULL || *argPos == NULL)
                    break;

                if (strncmp(cmdLinePos, *argPos, strlen(*argPos)))
                    break;

                cmdLinePos += strlen(*argPos);
                argPos++;

                if(cmdLinePos[0] == ' ')
                    cmdLinePos++;
            }

            if(*cmdLinePos != '\0' || (argPos != NULL && *argPos != NULL))
            {
                //not a match
                continue;
            }
        }
        if (programFilename != NULL)
        {
            pathBuffer[0] = '\0';
            if (pos->ki_textvp != NULL)
            {
                sysctlName[3] = pos->ki_pid;
                len = sizeof(pathBuffer);
                if( sysctl(sysctlName, 4, pathBuffer, &len, NULL, 0) < 0)
                {
		    /* If the executable path does not exist
		       (e.g. because the file was deleted after
		       the program started), move on */
		    if (errno == ENOENT)
			continue;
                    GCE(ceError = LwMapErrnoToLwError(errno));
                }
            }
            if(strcmp(programFilename, pathBuffer))
                continue;
        }

        //This is a match
        if(foundCount < fillCount)
            pid[foundCount] = pos->ki_pid;
        foundCount++;
    }
    ceError = ERROR_SUCCESS;
#endif

    if(count)
        *count = foundCount;
    else if(!ceError && foundCount == 0)
        ceError = ERROR_PROC_NOT_FOUND;

cleanup:
#ifdef HAVE_STRUCT_PSINFO
    if(dir != NULL)
        closedir(dir);
    CT_SAFE_FREE_STRING(filePath);
    CTSafeCloseFile(&infoFile);
#endif
#if defined(HAVE_KVM_GETPROCS) && HAVE_DECL_KERN_PROC_PATHNAME
    if(kd != NULL)
    {
        kvm_close(kd);
    }
#endif

    return ceError;
}
Beispiel #23
0
static tix_token get_tix_token( char *buff )
/******************************************/
{
    int         c;
    char        *p;
    char        *end;
    unsigned    num;
    char        endc;

    for( ;; ) {
        c = getc( in_file );
        if( c == EOF )
            return( TT_EOF );
        if( c == '#' ) {
            /* eat a comment */
            for( ;; ) {
                c = getc( in_file );
                if( c == EOF )
                    return( TT_EOF );
                if( c == '\n' ) {
                    break;
                }
            }
        }
        if( !isspace( c ) ) {
            break;
        }
    }
    p = buff;
    if( c == '\'' || c == '\"' ) {
        /* collect a string */
        endc = c;
        for( ;; ) {
            c = getc( in_file );
            if( c == EOF )
                break;
            if( c == '\r' )
                break;
            if( c == '\n' )
                break;
            if( c == endc )
                break;
            if( c == '\\' ) {
                c = getc( in_file );
                if( c == EOF )
                    break;
                switch( c ) {
                case 'a':
                    c = '\a';
                    break;
                case 'b':
                    c = '\b';
                    break;
                case 'e':
                    c = '\x1b';
                    break;
                case 'f':
                    c = '\f';
                    break;
                case 'n':
                    c = '\n';
                    break;
                case 'r':
                    c = '\r';
                    break;
                case 't':
                    c = '\t';
                    break;
                case 'v':
                    c = '\b';
                    break;
                case 'x':
                    num = 0;
                    for( ;; ) {
                        c = getc( in_file );
                        if( c == EOF )
                            break;
                        if( isdigit( c ) ) {
                            c = c - '0';
                        } else if( c >= 'A' && c <= 'F' ) {
                            c = c - 'A' + 10;
                        } else if( c >= 'a' && c <= 'f' ) {
                            c = c - 'a' + 10;
                        } else {
                            ungetc( c, in_file );
                        }
                        num = (num << 8) + c;
                    }
                    c = num;
                    break;
                }
            }
            *p++ = c;
        }
        *p = '\0';
        return( TT_CODE );
    } else {
        /* collect a string or number */
        for( ;; ) {
            *p++ = c;
            c = getc( in_file );
            if( c == EOF )
                break;
            if( isspace( c ) )
                break;
            if( c == '#' ) {
                ungetc( c, in_file );
                break;
            }
        }
        *p = '\0';
        num = strtoul( buff, &end, 0 );
        if( end != p )
            return( TT_STRING );
        buff[0] = num & 0xff;
        buff[1] = num >> 8;
        return( TT_CODE );
    }
}
Beispiel #24
0
Lexeme Scanner::get_lex() {
	int number, j;
	current_state = START;
	type_of_lex tmp;
	do {
		switch(current_state) {
			case START:	
				if(next == ' ' || next == '\n' || next == '\t') {
					if(next == '\n') line++;
					get_next();
				} else if(isalpha(next)) {
					current_state = IDENT;
					clear_buffer();
					add_next_to_buffer();
					get_next();
				} else if(isdigit(next)) {
					current_state = NUMB;
					number = next - '0';
					get_next();
				} else if(next == '\'') {
					current_state = STRI1;
					clear_buffer();
					get_next();
				} else if(next == '\"') {
					current_state = STRI2;
					clear_buffer();
					get_next();
				} else if(next == '>' || next == '<' || next == '=' || next == '&' || next == '|' || next == '!' || next == '/' || next == '-' || next == '+') {
					current_state = DELIM2;
					clear_buffer();
					add_next_to_buffer();
					get_next();
				} else if(next == -1) {
					return Lexeme(LEX_FIN);
				} else {
					current_state = DELIM;
					clear_buffer();
					add_next_to_buffer();
				}
				break;

			case IDENT:
				if(isalpha(next) || isdigit(next)) {
					add_next_to_buffer();
					get_next();
				} else if(MJSWords.find(scan_buffer) != MJSWords.end()) {
					tmp = MJSWords[scan_buffer];
					if(tmp == LEX_TRUE) {
						return Lexeme(LEX_BOOL, true);
					} else if(tmp == LEX_FALSE) {
						return Lexeme(LEX_BOOL, false);
					} else {
						return Lexeme(tmp);
					}
				} else if(find(MJSFields.begin(), MJSFields.end(), scan_buffer) != MJSFields.end()) {
					return Lexeme(LEX_FIELDS, string(scan_buffer));
				} else if(find(MJSMethods.begin(), MJSMethods.end(), scan_buffer) != MJSMethods.end()) {
					return Lexeme(LEX_METHODS, string(scan_buffer));
				} else {
					return Lexeme(LEX_ID, TOI.put(scan_buffer));
				}
				break;

			case NUMB:
				if(isdigit(next)) {
					number = number * 10 + (next - '0');
					get_next();
				} else {
					return Lexeme(LEX_NUM, number);
				}
				break;

			case STRI1:
				if(next == '\'') {
					get_next();
					return Lexeme(LEX_STR, string(scan_buffer));
				} else if(next == -1) {
					throw lexical_exception(next, line, "Unexpected EOF in LEX_STR");
				} else if(next == '\\') {
					get_next();
					if(next == 'n') 
						add_to_buffer('\n');
					get_next();
				} else {
					add_next_to_buffer();
					get_next();
				}
				break;

			case STRI2:
				if(next == '\"') {
					get_next();
					return Lexeme(LEX_STR, string(scan_buffer));
				} else if(next == -1) {
					throw lexical_exception(next, line, "Unexpected EOF in LEX_STR");
				} else if(next == '\\') {
					get_next();
					if(next == 'n') {
						add_to_buffer('\n');
					} else {
						add_next_to_buffer();
					}
					get_next();
				} else {
					add_next_to_buffer();
					get_next();
				}
				break;

			case DELIM:
				if(MJSDelims.find(scan_buffer) != MJSDelims.end()) {
					get_next();
					return Lexeme(MJSDelims[scan_buffer]);
				} else {
					throw lexical_exception(next, line, "Forbidden symbol");
				}
				break;

			case DELIM2:
				add_next_to_buffer();
				if(scan_buffer[0] == '=' && next == '=') {
					current_state = DELIM3;
					get_next();
				} else if(MJSDelims.find(scan_buffer) != MJSDelims.end()) {
					get_next();
					if(MJSDelims[scan_buffer] == LEX_COMM) {
						current_state = COMM;
					} else {
						return Lexeme(MJSDelims[scan_buffer]);
					}
				} else {
					scan_buffer[1] = '\0';
					if(MJSDelims.find(scan_buffer) != MJSDelims.end()) {
						return Lexeme(MJSDelims[scan_buffer]);
					} else {
						throw lexical_exception(next, line, "Forbidden symbol");
					}
				}
				break;

			case DELIM3:
				if(next == '=') {
					get_next();
					return Lexeme(LEX_IDENT);
				} else {
					return Lexeme(LEX_EQ);
				}
				break;

			case COMM:
				if(next == '\n' || next == -1) {
					line++;
					current_state = START;
					clear_buffer();
					get_next();
				} else {
					get_next();
				}

			default:
				break;
		}
	} while(true);
}
Beispiel #25
0
static
DWORD
LocalCfgSetHomedirUmask(
    PLOCAL_CONFIG pConfig,
    PCSTR          pszName,
    PCSTR          pszValue
    )
{
    DWORD dwError = 0;
    PCSTR cp = NULL;
    DWORD dwOct = 0;
    DWORD dwVal = 0;
    DWORD dwCnt = 0;
    char  cp2[2];
    PSTR pszUmask = NULL;

    // Convert the umask octal string to a decimal number

    cp2[1] = 0;

    for (cp = pszValue, dwCnt = 0; isdigit((int)*cp); cp++, dwCnt++)
    {
        dwOct *= 8;

        cp2[0] = *cp;
        dwVal = atoi(cp2);

        if (dwVal > 7)
        {
            dwError = LW_ERROR_INVALID_PARAMETER;
        }
        BAIL_ON_UP_ERROR(dwError);

        dwOct += dwVal;
    }

    if (dwCnt > 4)
    {
        dwError = LW_ERROR_INVALID_PARAMETER;
    }
    BAIL_ON_UP_ERROR(dwError);

    // Disallow 07xx since the user should always have
    // access to his home directory.
    if ((dwOct & 0700) == 0700)
    {
        dwError = LW_ERROR_INVALID_PARAMETER;
    }
    BAIL_ON_UP_ERROR(dwError);

    dwError = LwAllocateString(pszValue, &pszUmask);
    BAIL_ON_UP_ERROR(dwError);

    LW_SAFE_FREE_STRING(pConfig->pszUmask);
    pConfig->pszUmask = pszUmask;
    pszUmask = NULL;

cleanup:

    LW_SAFE_FREE_STRING(pszUmask);

    return dwError;

error:

    goto cleanup;
}
Beispiel #26
0
static void
transform_string (STRING_T * t, STRING_T * s)
{
  int c, state = 0, accum = 0;
  size_t ip = 0, i;
  static int fsm[] = {
    0, '\\', FSM_SUPPRESS, 1,
    0, FSM_ANY, FSM_OUTPUT, 0,
    1, 'b', '\b', 0,
    1, 'e', '\033', 0,
    1, 'f', '\f', 0,
    1, 'n', '\n', 0,
    1, 'r', '\r', 0,
    1, 't', '\t', 0,
    1, 'v', '\v', 0,
    1, '\\', '\\', 0,
    1, 'd', FSM_SUPPRESS, 2,
    1, FSM_ODIGIT, FSM_BASE8, 3,
    1, 'x', FSM_SUPPRESS, 4,
    1, FSM_ANY, FSM_OUTPUT, 0,
    2, FSM_DIGIT, FSM_BASE10, 21,
    2, FSM_ANY, FSM_RETAIN, 0,
    3, FSM_ODIGIT, FSM_BASE8, 31,
    3, FSM_ANY, FSM_RETAIN, 0,
    4, FSM_XDIGIT, FSM_BASE16, 4,
    4, FSM_ANY, FSM_RETAIN, 0,
    21, FSM_DIGIT, FSM_BASE10, 22,
    21, FSM_ANY, FSM_RETAIN, 0,
    22, FSM_DIGIT, FSM_BASE10_OUTPUT, 0,
    22, FSM_ANY, FSM_RETAIN, 0,
    31, FSM_ODIGIT, FSM_BASE8_OUTPUT, 0,
    31, FSM_ANY, FSM_RETAIN, 0,
    -1, -1, -1, -1
  };
  static char hexits[] =
    { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
    'e', 'f', '\0'
  };

  DSresize (t, 0, 0);
  while (ip < DSlength (s) && (c = DSget_at (s, ip)) != '\0')
    {
      for (i = 0;
	   !(fsm[i] == state
	     && (fsm[i + 1] == c
		 || fsm[i + 1] == FSM_ANY
		 || (fsm[i + 1] == FSM_DIGIT && isdigit (c))
		 || (fsm[i + 1] == FSM_ODIGIT && strchr ("01234567", c) != 0)
		 || (fsm[i + 1] == FSM_XDIGIT && isxdigit (c)))); i += 4);
      switch (fsm[i + 2])
	{
	case FSM_OUTPUT:
	  DSappendchar (t, c, 1);
	  ip++;
	  break;
	case FSM_SUPPRESS:
	  accum = 0;
	  ip++;
	  break;
	case FSM_BASE10:
	  accum = (accum * 10) + (c - '0');
	  ip++;
	  break;
	case FSM_BASE8:
	  accum = (accum << 3) + (c - '0');
	  ip++;
	  break;
	case FSM_BASE16:
	  accum = (accum << 4) + (strchr (hexits, tolower (c)) - hexits);
	  ip++;
	  break;
	case FSM_BASE10_OUTPUT:
	  accum = (accum * 10) + (c - '0');
	  DSappendchar (t, accum, 1);
	  accum = 0;
	  ip++;
	  break;
	case FSM_BASE8_OUTPUT:
	  accum = (accum << 3) + (c - '0');
	  DSappendchar (t, accum, 1);
	  accum = 0;
	  ip++;
	  break;
	case FSM_RETAIN:
	  DSappendchar (t, accum, 1);
	  accum = 0;
	  break;
	default:
	  DSappendchar (t, fsm[i + 2], 1);
	  ip++;
	  break;
	}
      state = fsm[i + 3];
    }
}
Beispiel #27
0
int CharacterToken::QuotedChar(int bytes, const char **source)
{
    register int i=*(*source)++, j;
    if (**source == '\n')
        return INT_MIN;
    if (i != '\\')
    {
        return (unsigned char)i;
    }
    i = *(*source); /* get an escaped character */
    if (isdigit(i) && i < '8')
    {
        for (i = 0, j = 0; j < 3; ++j)
        {
            if (*(*source) <= '7' && *(*source) >= '0')
                i = (i << 3) + *(*source) - '0';
            else
                break;
            (*source)++;
        }
        return i;
    }
    (*source)++;
    switch (i)
    {
        case 'a':
            return '\a';
        case 'b':
            return '\b';
        case 'f':
            return '\f';
        case 'n':
            return '\n';
        case 'r':
            return '\r';
        case 'v':
            return '\v';
        case 't':
            return '\t';
        case '\'':
            return '\'';
        case '\"':
            return '\"';
        case '\\':
            return '\\';
        case '?':
            return '?';
        case 'U':
            bytes = 4;
        case 'u':
            if (i == 'u')
                bytes = 2;
        case 'x':
            {
                int n = 0;
                while (isxdigit(*(*source)))
                {
                    int v = **source;
                    if (v >= 0x60)
                        v &= 0xdf;
                    v -= 0x30;

                    if (v > 10)
                        v -= 7;
                    n *= 16;
                    n += v;
                    (*source)++;
                }
                /* hexadecimal escape sequences are only terminated by a non hex char */
                /* we sign extend or truncate */
                if (bytes == 1)
                    if (unsignedchar)
                        n = (int)(unsigned char)n;
                    else
                        n = (int)(char)n;
                if (bytes == 2 && i == 'x')
                        n = (int)(wchar_t)n;
//				if (i != 'x')
//				{
//					if (n <= 0x20 || n >= 0x7f && n <= 0x9f ||
//						n >=0xd800 && n<= 0xdfff)
//						Errors::Error("Invalid character constant");
//				}
                return n;
            }
        default:
            return (char)i;
    }
}
Beispiel #28
0
/* catread - read a catalogue file */
static _CAT_CATALOG_T *
catread (const char *name)
{
  FILE *f;
  STRING_T *s = DScreate (), *t = DScreate ();
  _CAT_CATALOG_T *cat = 0;
  size_t z;
  _CAT_MESSAGE_T catmsg = { 0, 0, 0 };
  int c;

  /* Open the catfile */
  f = fopen (name, "r");
  if (f == 0)
    return 0;			/* could not open file */
  setvbuf (f, 0, _IOFBF, 16384);
  while (DSlength (s = append_from_file (f, s)) > 0)
    {
      DSresize (s, DSlength (s) - 1, 0);
      /* We have a full line */
      if (DSlength (s) > 0)
	{
	  z = DSfind_first_not_of (s, " \t\f\v\r", 0, NPOS);
	  DSremove (s, 0, z);
	  z = DSfind_last_not_of (s, " \t\f\v\r", NPOS, NPOS);
	  DSresize (s, z + 1, 0);
	}
      if (DSlength (s) > 0 && DSget_at (s, DSlength (s) - 1) == '\\')
	{
	  /* continuation */
	  DSresize (s, DSlength (s) - 1, 0);
	}
      else
	{
	  if (DSlength (s) > 0 && isdigit (DSget_at (s, 0)))
	    {
	      /* if it starts with a digit, assume it's a catalog line */
	      for (z = 0, catmsg.set_id = 0;
		   isdigit (c = DSget_at (s, z));
		   catmsg.set_id = catmsg.set_id * 10 + (c - '0'), z++);
	      z++;
	      for (catmsg.msg_id = 0;
		   isdigit (c = DSget_at (s, z));
		   catmsg.msg_id = catmsg.msg_id * 10 + (c - '0'), z++);
	      z++;
	      DSremove (s, 0, z);
	      transform_string (t, s);
	      if (catmsg.msg == 0)
		catmsg.msg = DScreate ();
	      DSassign (catmsg.msg, t, 0, NPOS);
	      if (cat == 0)
		{
		  cat = malloc (sizeof (_CAT_CATALOG_T));
		  if (cat == 0)
		    Nomemory ();
		  cat->is_opened = 0;
		  cat->msgs = _CATMSG_create ();
		}
	      _CATMSG_append (cat->msgs, &catmsg, 1, 0);
	    }
	  DSresize (s, 0, 0);
	}
    }
  fclose (f);
  qsort (_CATMSG_base (cat->msgs), _CATMSG_length (cat->msgs),
	 sizeof (_CAT_MESSAGE_T), catmsg_cmp);
  return cat;
}
Beispiel #29
0
int NumericToken::GetNumber(const char **ptr)
{
    char buf[256];
    char  *p = buf ;
    int radix = 10;
    int floatradix = 0;
    bool hasdot = false;
    bool floating = false;
    if (!isdigit(**ptr) && **ptr != '.')
        return  INT_MIN;
    if (**ptr == '.' && !isdigit(*(*ptr + 1)))
        return INT_MIN;
    if (**ptr == '0')
    {
        (*ptr)++;
        if (**ptr == 'x' || **ptr == 'X')
        {
            (*ptr)++;
            radix = 16;
        }
        else
            radix = 8;
    }
    else if (**ptr == '$')
    {
        radix = 16;
        (*ptr)++;
    }
    while (Radix36(**ptr) < radix || Radix36(**ptr) < 16)
    {
        *p++ = **ptr;
        (*ptr)++;
    }
    if (**ptr == '.')
    {
        hasdot = true;
        if (radix == 8)
            radix = 10;
        *p++ = **ptr;
        (*ptr)++;
        while (Radix36(**ptr) < radix)
        {
            *p++ = **ptr;
            (*ptr)++;
        }
    }
    if ((**ptr == 'e' || **ptr == 'E') && radix != 16)
        radix = floatradix = 10;
    else if ((**ptr == 'p' || **ptr == 'P') && radix == 16)
    {
           floatradix = 2;
    } 
    else if (radix == 16 && hasdot)
    {
        Errors::Error("Invalid floating point constant");
    }

    if (floatradix)
    {
        *p++ = **ptr;
        (*ptr)++;
        if (**ptr == '-' || **ptr == '+')
        {
            *p++ = **ptr;
            (*ptr)++;
        }
        while (Radix36(**ptr) < 10)
        {
            *p++ = **ptr;
            (*ptr)++;
        }
    }

    *p = 0;
    if (!floatradix && radix != 16)
    {
        char *q = buf;
        if (**ptr == 'H' || **ptr == 'h')
        {
            radix = 16;
            (*ptr)++;
            while (*q)
                if (Radix36(*q++) >= 16)
                    return INT_MIN;
        }
    }
    p = buf;
    /* at this point the next char is any qualifier after the number*/

    if (hasdot || floatradix)
    {
        if (floatradix == 0)
            floatradix = radix;
        GetFloating(floatValue, floatradix, &p);
        floating = true;
    }
    else
    {
        if (Radix36(*p) < radix)
            intValue = GetBase(radix, &p);
        else
        {
               intValue = 0;
        }
    }
    if (!floating)
    {
        type = t_int;
        if (**ptr == 'i')
        {
            if (!ansi &&  (*ptr)[1] == '6' && (*ptr)[2] == '4')
            {
                (*ptr)++;
                (*ptr)++;
                (*ptr)++;
                type = t_longlongint;
            }
        }
        else if (**ptr == 'U' || **ptr == 'u')
        {
            (*ptr)++;
            type = t_unsignedint;
            if (**ptr == 'i')
            {
                if (!ansi &&  (*ptr)[1] == '6' && (*ptr)[2] == '4')
                {
                    (*ptr)++;
                    (*ptr)++;
                    (*ptr)++;
                    type = t_unsignedlonglongint;
                }
            }
            else if (**ptr == 'L' || **ptr == 'l')
            {
                (*ptr)++;
                type = t_unsignedlongint;
                if (c99 && (**ptr == 'L' || **ptr == 'l'))
                {
                    type = t_unsignedlonglongint;
                    (*ptr)++;
                }
            }
        }
        else if (**ptr == 'L' || **ptr == 'l')
        {
            type = t_longint;
            (*ptr)++;
            if (c99 && (**ptr == 'L' || **ptr == 'l'))
            {
                type = t_longlongint;
                (*ptr)++;
                if (**ptr == 'U' || **ptr == 'u')
                {
                    type = t_unsignedlonglongint;
                    (*ptr)++;
                }
            }

            else if (**ptr == 'U' || **ptr == 'u')
            {
                type = t_unsignedlongint;
                (*ptr)++;
            }
        }
        if (type == t_int) /* no qualifiers */
        {
            if (intValue > INT_MAX)
            {
                type = t_unsignedint;
                if (radix == 10 || (L_UINT)intValue > UINT_MAX)
                {
                    type = t_longint;
                    if (intValue > LONG_MAX)
                    {
                        type = t_unsignedlongint;
                        if (radix == 10 || (L_UINT)intValue > ULONG_MAX)
                        {
                            if (radix == 10)
                            {
                                type = t_longlongint;
                            }
                            else
                                type = t_unsignedlonglongint;
                        }
                    }
                }
            }
        }
    }
    else
    {
        if (**ptr == 'F' || **ptr == 'f')
        {
            type = t_float;
            (*ptr)++;
            floatValue.Truncate(FLT_MANT_DIG, FLT_MAX_EXP, FLT_MIN_EXP);
        }
        else if (**ptr == 'L' || **ptr == 'l')
        {
            type = t_longdouble;
            (*ptr)++;
            floatValue.Truncate(LDBL_MANT_DIG, LDBL_MAX_EXP, LDBL_MIN_EXP);
        } else
        {
            type = t_double;
            floatValue.Truncate(DBL_MANT_DIG, DBL_MAX_EXP, DBL_MIN_EXP);
        }
        parsedAsFloat = true;
    }
    if (IsSymbolChar(*ptr))
    {
        Errors::Error("Invalid constant value");
        while (**ptr && IsSymbolChar(*ptr))
        {
            int n = UTF8::CharSpan(*ptr);
            for (int i=0; i < n && **ptr; i++)
                (*ptr++);
        }
    }
    return type;
}
Beispiel #30
0
int main(int argc, char **argv)
{
    extern int opterr, optind;
    extern char *optarg;
    int c, fd;
    char *fn;

    setlocale(LC_ALL, "");
    opterr = 0;

    /*
     * try to get a buffer _twice_ the size mandated by the standard as in
     * later processing we may be paging through the file in _half_ buffer
     * increments; this way we guarentee POSIX buffer size conformance
     */
    bufsize = sysconf(_SC_LINE_MAX) * 20;   /* POSIX says [{LINE_MAX)*10] */
    bufsize = bufsize < 4096 ? 4096 : bufsize;

    if ((buf = malloc(bufsize)) == NULL)
        fatal(APPERR, NOMALLOC);

    while ((c = getopt(argc, argv, "fc:n:")) != -1)
        switch (c)
        {
        case 'f':   /* follow file */
            optf = 1;
            break;

        case 'c':   /* offset in bytes */
            optc = 1;
            offset = 0;
            if (*optarg && isdecint(optarg))
            {
                offset = atol(optarg);
                offset = isdigit(*optarg) ? -offset : offset;
            }

            if (offset == 0)
                fatal(APPERR, BADBYTES);
            else
                break;

        case 'n':   /* offset in lines */
            optn = 1;
            if (*optarg && isdecint(optarg))
            {
                offset = atol(optarg);
                offset = isdigit(*optarg) ? -offset : offset;

                /* the standard says [-n 0] is OK, but [-n +0] isn't &_& */
                if (offset != 0 || (offset == 0 && *optarg != '+'))
                    break;
            }
            fatal(APPERR, BADLINES);

        default:
            fprintf(stderr, USAGE);
            exit(1);
        }

    if (! optc && ! optn)   /* if none, set the default options */
    {
        optn = 1;
        offset = -10;
    }

    if (optc && optn)
        fatal(APPERR, CNMUTEXCL);

    if (optind >= argc)
        tailfile(STDIN_FILENO, "stdin");
    else
    {
        fn = argv[optind++];

        if (strcmp(fn, "-") == 0)
            tailfile(STDIN_FILENO, "stdin");
        else
            if ((fd = open(fn, O_RDONLY)) == -1)
                fatal(SYSERR, fn);
            else
            {
                tailfile(fd, fn);
                if (close(fd) == -1)
                    fatal(SYSERR, fn);
            }
    }

    return(0);
}