Пример #1
0
void parse_ia(tRuleSystem& rsys, FILE *f) {
	char linebuf[4096];
	ruleset		*pRuleset = NULL;

	while(fgets(linebuf, sizeof linebuf, f)) {
		strtrim(linebuf);

		if (!linebuf[0] || linebuf[0] == '#')
			continue;

		puts(linebuf);

		if (linebuf[0] == '%') {			// ruleset definition
			strtrim(linebuf+1);

			ruleset r;
			r.name = linebuf+1;
			rsys.push_back(r);
			pRuleset = &rsys.back();
		} else {							// rule definition

			if (!pRuleset)
				oops("Not in ruleset:\n>%s\n", linebuf);

			rule r;

			r.rule_line = linebuf;
			r.argcount = 0;

			// Find colon

			char *colon = linebuf;

			while(*colon != ':') {
				if (!*colon)
					oops("Colon missing in rule:\n>%s\n", linebuf);

				++colon;
			}

			// Nuke colon

			*colon++ = 0;

			// Parse tokens until colon is found

			static const char whitespace[]=" \t\n\v";
			const char *token = strtok(linebuf, whitespace);

			std::vector<bool> argumentTypeStack;		// true if arg is a string

			if (token) do {
				if (*token == '*') {						// any character
					if (!r.match_stream.empty() && !r.match_stream.rbegin()->second && r.match_stream.rbegin()->first < 15)
						++r.match_stream.rbegin()->first;
					else {
						r.match_stream.push_back(std::pair<uint8, uint8>(1,0));
					}

					argumentTypeStack.push_back(false);
					++r.argcount;
				} else if (*token == '[') {
					if (!strcmp(token+1, "66]"))
						r.match_stream.push_back(std::pair<uint8, uint8>(16,0));
					else if (!strcmp(token+1, "67]"))
						r.match_stream.push_back(std::pair<uint8, uint8>(17,0));
					else if (!strcmp(token+1, "F2]"))
						r.match_stream.push_back(std::pair<uint8, uint8>(18,0));
					else if (!strcmp(token+1, "F3]"))
						r.match_stream.push_back(std::pair<uint8, uint8>(19,0));
					else if (!strcmp(token+1, "!s]"))
						r.match_stream.push_back(std::pair<uint8, uint8>(20,0));
					else if (!strcmp(token+1, "q]"))
						r.match_stream.push_back(std::pair<uint8, uint8>(21,0));
					else
						oops("unknown prefix match token '%s'\n", token);
				} else if (isxdigit((unsigned char)token[0]) && isxdigit((unsigned char)token[1])
						&& (token[2] == '-' || !token[2])) {		// match character
					int byteval, byteend;
					int c;

					c = sscanf(token, "%x-%x", &byteval, &byteend);

					if (byteval < 0 || byteval >= 256)
						oops("uint8 start value out of range\n");

					if (c<2) {
						byteend = byteval;
					} else if (byteend != byteval) {
						if (byteend < 0 || byteend >= 256)
							oops("uint8 end value out of range\n");
					}

					r.match_stream.push_back(std::pair<uint8, uint8>(byteval, ~(byteval ^ byteend)));
					argumentTypeStack.push_back(false);
					++r.argcount;

				} else {									// macro invocation
					tRuleSystem::iterator it = rsys.begin();
					tRuleSystem::iterator itEnd = rsys.end();
					int index = 128;

					if (*token == '!') {	// reuse last uint8 char
						index = 192;
						++token;
					}

					for(; it!=itEnd; ++it, ++index) {
						if (!_stricmp((*it).name.c_str(), token))
							break;
					}

					if (it == itEnd)
						oops("unknown ruleset '%s'\n", token);

					r.match_stream.push_back(std::pair<uint8, uint8>(index, 0));
					r.argcount += 2;
					argumentTypeStack.push_back(false);
					argumentTypeStack.push_back(true);
				}
			} while(token = strtok(NULL, whitespace));

			// match sequence parsed -- parse the result string.

			char *s = colon;

			for(;;) {
				while(*s && strchr(whitespace, *s))
					++s;

				if (!*s || *s == '#')
					break;

				if (*s == '"') {	// string literal
					const char *start = ++s;

					while(*s != '"') {
						if (!*s)
							oops("unterminated string constant\n");

						++s;
					}
					
					r.result.append(start, s-start);
					++s;
				} else if (*s == '$') {	// macro expansion
					++s;

					if (!_strnicmp(s, "p_cs", 4)) {
						r.result += kTarget_p_cs;
						s += 4;
					} else if (!_strnicmp(s, "p_ss", 4)) {
						r.result += kTarget_p_ss;
						s += 4;
					} else if (!_strnicmp(s, "p_ds", 4)) {
						r.result += kTarget_p_ds;
						s += 4;
					} else if (!_strnicmp(s, "p_es", 4)) {
						r.result += kTarget_p_es;
						s += 4;
					} else if (!_strnicmp(s, "p_fs", 4)) {
						r.result += kTarget_p_fs;
						s += 4;
					} else if (!_strnicmp(s, "p_gs", 4)) {
						r.result += kTarget_p_gs;
						s += 4;
					} else if (!_strnicmp(s, "p_66", 4)) {
						r.result += kTarget_p_66;
						r.is_66 = true;
						s += 4;
					} else if (!_strnicmp(s, "p_67", 4)) {
						r.result += kTarget_p_67;
						r.is_67 = true;
						s += 4;
					} else if (!_strnicmp(s, "p_F2", 4)) {
						r.result += kTarget_p_F2;
						r.is_f2 = true;
						s += 4;
					} else if (!_strnicmp(s, "p_F3", 4)) {
						r.result += kTarget_p_F3;
						r.is_f3 = true;
						s += 4;
					} else if (!_strnicmp(s, "ap", 2)) {
						r.result += kTarget_ap;
						s += 2;
					} else if (!_strnicmp(s, "p_rex", 5)) {
						r.result += kTarget_p_rex;
						s += 5;
					} else if (!_strnicmp(s, "return", 6)) {
						s += 6;
						r.is_return = true;
					} else if (!_strnicmp(s, "call", 4)) {
						s += 4;
						r.is_call = true;
					} else if (!_strnicmp(s, "jmp", 3)) {
						s += 3;
						r.is_jump = true;
					} else if (!_strnicmp(s, "jcc", 3)) {
						s += 3;
						r.is_jcc = true;
					} else if (!_strnicmp(s, "imm8", 4)) {
						s += 4;
						r.is_imm8 = true;
					} else if (!_strnicmp(s, "imm16", 5)) {
						s += 5;
						r.is_imm16 = true;
					} else if (!_strnicmp(s, "imm32", 5)) {
						s += 5;
						r.is_imm32 = true;
					} else if (!_strnicmp(s, "invalid", 7)) {
						s += 7;
						r.is_invalid = true;
					} else {
						unsigned long id = strtoul(s, &s, 10);

						if (!id || id > r.argcount)
							oops("macro argument $%lu out of range\n", id);

						if (!r.result.empty() && *r.result.rbegin() == ' ')
							*r.result.rbegin() = (char)(id + 0x80);
						else
							r.result += (char)id;

						int firstbit = 0;
						int lastbit = 7;

						if (*s == '[') {
							++s;

							firstbit = strtol(s, &s, 10);

							if (*s++ != '-')
								oops("macro argument bitfield range missing '-'\n");

							lastbit = strtol(s, &s, 10);

							if (firstbit < 0 || lastbit > 7 || firstbit > lastbit)
								oops("invalid bitfield %d-%d\n", firstbit, lastbit);

							if (*s++ != ']')
								oops("invalid bitfield\n");
						}

						if (!*s)
							oops("macro expansion missing format\n");

						char *t = s;

						while(*t && !isspace((unsigned char)*t))
							++t;

						*t = 0;

						char control_byte;
						char ext_byte = 0;

						if (!_stricmp(s, "r32")) {
							control_byte = kTarget_r32;
						} else if (!_stricmp(s, "r16")) {
							control_byte = kTarget_r16;
						} else if (!_stricmp(s, "r1632")) {
							control_byte = kTarget_r1632;
						} else if (!_stricmp(s, "r8")) {
							control_byte = kTarget_r8;
						} else if (!_stricmp(s, "rm")) {
							control_byte = kTarget_rm;
						} else if (!_stricmp(s, "rx")) {
							control_byte = kTarget_rx;
						} else if (!_stricmp(s, "rmx")) {
							control_byte = kTarget_rmx;
						} else if (!_stricmp(s, "rc")) {
							control_byte = kTarget_rc;
						} else if (!_stricmp(s, "rd")) {
							control_byte = kTarget_rd;
						} else if (!_stricmp(s, "rs")) {
							control_byte = kTarget_rs;
						} else if (!_stricmp(s, "rf")) {
							control_byte = kTarget_rf;
						} else if (!_stricmp(s, "x")) {
							control_byte = kTarget_x;
						} else if (!_stricmp(s, "hx")) {
							control_byte = kTarget_hx;
						} else if (!_stricmp(s, "lx")) {
							control_byte = kTarget_lx;
						} else if (!_stricmp(s, "o")) {
							control_byte = kTarget_o;
						} else if (!_stricmp(s, "ho")) {
							control_byte = kTarget_ho;
						} else if (!_stricmp(s, "lo")) {
							control_byte = kTarget_lo;
						} else if (!_stricmp(s, "a")) {
							control_byte = kTarget_a;
						} else if (!_stricmp(s, "ha")) {
							control_byte = kTarget_ha;
						} else if (!_stricmp(s, "la")) {
							control_byte = kTarget_la;
						} else if (!_stricmp(s, "s")) {
							control_byte = kTarget_s;
						} else if (!_stricmp(s, "r3264")) {
							control_byte = kTarget_r3264;
						} else if (!_stricmp(s, "r163264")) {
							control_byte = kTarget_r163264;
						} else if (!_stricmp(s, "r3264rexX")) {
							control_byte = kTarget_ext;
							ext_byte = kTarget_ext_r3264rexX;
						} else if (!_stricmp(s, "r3264rexB")) {
							control_byte = kTarget_ext;
							ext_byte = kTarget_ext_r3264rexB;
						} else if (!_stricmp(s, "r163264rexB")) {
							control_byte = kTarget_ext;
							ext_byte = kTarget_ext_r163264rexB;
						} else {
							oops("unknown macro expansion mode: '%s'\n", s);
						}

						if (argumentTypeStack[id-1] != (control_byte == kTarget_s))
							oops("bad argument type: $%d (not a %s)\n", id, argumentTypeStack[id-1] ? "uint8" : "string");

						if (firstbit == 0 && lastbit == 2) {
							r.result += (char)(control_byte + 0x20);
						} else if (firstbit == 3 && lastbit == 5) {
							r.result += (char)(control_byte + 0x40);
						} else if (firstbit != 0 || lastbit != 7) {
							r.result += (char)(control_byte + 0xe0);
							r.result += (char)((lastbit+1-firstbit)*16 + firstbit);
						} else {
							r.result += (char)control_byte;
						}

						if (ext_byte)
							r.result += (char)ext_byte;

						s = t+1;
					}
				} else
					oops("indecipherable result string\n");
			}

			pRuleset->rules.push_back(r);
		}
	}
}
Пример #2
0
static void
OpcDoEisaId (
    ACPI_PARSE_OBJECT       *Op)
{
    UINT32                  EisaId = 0;
    UINT32                  BigEndianId;
    char                    *InString;
    ACPI_STATUS             Status = AE_OK;
    UINT32                  i;


    InString = (char *) Op->Asl.Value.String;

    /*
     * The EISAID string must be exactly 7 characters and of the form
     * "UUUXXXX" -- 3 uppercase letters and 4 hex digits (e.g., "PNP0001")
     */
    if (ACPI_STRLEN (InString) != 7)
    {
        Status = AE_BAD_PARAMETER;
    }
    else
    {
        /* Check all 7 characters for correct format */

        for (i = 0; i < 7; i++)
        {
            /* First 3 characters must be uppercase letters */

            if (i < 3)
            {
                if (!isupper ((int) InString[i]))
                {
                    Status = AE_BAD_PARAMETER;
                }
            }

            /* Last 4 characters must be hex digits */

            else if (!isxdigit ((int) InString[i]))
            {
                Status = AE_BAD_PARAMETER;
            }
        }
    }

    if (ACPI_FAILURE (Status))
    {
        AslError (ASL_ERROR, ASL_MSG_INVALID_EISAID, Op, Op->Asl.Value.String);
    }
    else
    {
        /* Create ID big-endian first (bits are contiguous) */

        BigEndianId =
            (UINT32) ((UINT8) (InString[0] - 0x40)) << 26 |
            (UINT32) ((UINT8) (InString[1] - 0x40)) << 21 |
            (UINT32) ((UINT8) (InString[2] - 0x40)) << 16 |

            (UtHexCharToValue (InString[3])) << 12 |
            (UtHexCharToValue (InString[4])) << 8  |
            (UtHexCharToValue (InString[5])) << 4  |
             UtHexCharToValue (InString[6]);

        /* Swap to little-endian to get final ID (see function header) */

        EisaId = AcpiUtDwordByteSwap (BigEndianId);
    }

    /*
     * Morph the Op into an integer, regardless of whether there
     * was an error in the EISAID string
     */
    Op->Asl.Value.Integer = EisaId;

    Op->Asl.CompileFlags &= ~NODE_COMPILE_TIME_CONST;
    Op->Asl.ParseOpcode = PARSEOP_INTEGER;
    (void) OpcSetOptimalIntegerSize (Op);

    /* Op is now an integer */

    UtSetParseOpName (Op);
}
Пример #3
0
int iswxdigit(wint_t wc) { return isxdigit(wc); }
Пример #4
0
static int httpread_hdr_analyze(struct httpread *h)
{
	char *hbp = h->hdr;      /* pointer into h->hdr */
	int standard_first_line = 1;

	/* First line is special */
	h->hdr_type = HTTPREAD_HDR_TYPE_UNKNOWN;
	if (!isgraph(*hbp))
		goto bad;
	if (os_strncmp(hbp, "HTTP/", 5) == 0) {
		h->hdr_type = HTTPREAD_HDR_TYPE_REPLY;
		standard_first_line = 0;
		hbp += 5;
		if (hbp[0] == '1' && hbp[1] == '.' &&
		    isdigit(hbp[2]) && hbp[2] != '0')
			h->version = 1;
		while (isgraph(*hbp))
			hbp++;
		while (*hbp == ' ' || *hbp == '\t')
			hbp++;
		if (!isdigit(*hbp))
			goto bad;
		h->reply_code = atol(hbp);
	} else if (word_eq(hbp, "GET"))
		h->hdr_type = HTTPREAD_HDR_TYPE_GET;
	else if (word_eq(hbp, "HEAD"))
		h->hdr_type = HTTPREAD_HDR_TYPE_HEAD;
	else if (word_eq(hbp, "POST"))
		h->hdr_type = HTTPREAD_HDR_TYPE_POST;
	else if (word_eq(hbp, "PUT"))
		h->hdr_type = HTTPREAD_HDR_TYPE_PUT;
	else if (word_eq(hbp, "DELETE"))
		h->hdr_type = HTTPREAD_HDR_TYPE_DELETE;
	else if (word_eq(hbp, "TRACE"))
		h->hdr_type = HTTPREAD_HDR_TYPE_TRACE;
	else if (word_eq(hbp, "CONNECT"))
		h->hdr_type = HTTPREAD_HDR_TYPE_CONNECT;
	else if (word_eq(hbp, "NOTIFY"))
		h->hdr_type = HTTPREAD_HDR_TYPE_NOTIFY;
	else if (word_eq(hbp, "M-SEARCH"))
		h->hdr_type = HTTPREAD_HDR_TYPE_M_SEARCH;
	else if (word_eq(hbp, "M-POST"))
		h->hdr_type = HTTPREAD_HDR_TYPE_M_POST;
	else if (word_eq(hbp, "SUBSCRIBE"))
		h->hdr_type = HTTPREAD_HDR_TYPE_SUBSCRIBE;
	else if (word_eq(hbp, "UNSUBSCRIBE"))
		h->hdr_type = HTTPREAD_HDR_TYPE_UNSUBSCRIBE;
	else {
	}

	if (standard_first_line) {
		char *rawuri;
		char *uri;
		/* skip type */
		while (isgraph(*hbp))
			hbp++;
		while (*hbp == ' ' || *hbp == '\t')
			hbp++;
		/* parse uri.
		 * Find length, allocate memory for translated
		 * copy, then translate by changing %<hex><hex>
		 * into represented value.
		 */
		rawuri = hbp;
		while (isgraph(*hbp))
			hbp++;
		h->uri = os_malloc((hbp - rawuri) + 1);
		if (h->uri == NULL)
			goto bad;
		uri = h->uri;
		while (rawuri < hbp) {
			int c = *rawuri;
			if (c == '%' &&
			    isxdigit(rawuri[1]) && isxdigit(rawuri[2])) {
				*uri++ = (hex_value(rawuri[1]) << 4) |
					hex_value(rawuri[2]);
				rawuri += 3;
			} else {
				*uri++ = c;
				rawuri++;
			}
		}
		*uri = 0;       /* null terminate */
		while (isgraph(*hbp))
			hbp++;
		while (*hbp == ' ' || *hbp == '\t')
			hbp++;
		/* get version */
		if (0 == strncmp(hbp, "HTTP/", 5)) {
			hbp += 5;
			if (hbp[0] == '1' && hbp[1] == '.' &&
			    isdigit(hbp[2]) && hbp[2] != '0')
				h->version = 1;
		}
	}
	/* skip rest of line */
	while (*hbp)
		if (*hbp++ == '\n')
			break;

	/* Remainder of lines are options, in any order;
	 * or empty line to terminate
	 */
	for (;;) {
		/* Empty line to terminate */
		if (hbp[0] == '\n' ||
		    (hbp[0] == '\r' && hbp[1] == '\n'))
			break;
		if (!isgraph(*hbp))
			goto bad;
		if (httpread_hdr_option_analyze(h, hbp))
			goto bad;
		/* skip line */
		while (*hbp)
			if (*hbp++ == '\n')
				break;
	}

	/* chunked overrides content-length always */
	if (h->chunked)
		h->got_content_length = 0;

	/* For some types, we should not try to read a body
	 * This is in addition to the application determining
	 * that we should not read a body.
	 */
	switch (h->hdr_type) {
	case HTTPREAD_HDR_TYPE_REPLY:
		/* Some codes can have a body and some not.
		 * For now, just assume that any other than 200
		 * do not...
		 */
		if (h->reply_code != 200)
			h->max_bytes = 0;
		break;
	case HTTPREAD_HDR_TYPE_GET:
	case HTTPREAD_HDR_TYPE_HEAD:
		/* in practice it appears that it is assumed
		 * that GETs have a body length of 0... ?
		 */
		if (h->chunked == 0 && h->got_content_length == 0)
			h->max_bytes = 0;
		break;
	case HTTPREAD_HDR_TYPE_POST:
	case HTTPREAD_HDR_TYPE_PUT:
	case HTTPREAD_HDR_TYPE_DELETE:
	case HTTPREAD_HDR_TYPE_TRACE:
	case HTTPREAD_HDR_TYPE_CONNECT:
	case HTTPREAD_HDR_TYPE_NOTIFY:
	case HTTPREAD_HDR_TYPE_M_SEARCH:
	case HTTPREAD_HDR_TYPE_M_POST:
	case HTTPREAD_HDR_TYPE_SUBSCRIBE:
	case HTTPREAD_HDR_TYPE_UNSUBSCRIBE:
	default:
		break;
	}

	return 0;

bad:
	/* Error */
	return -1;
}
Пример #5
0
const unsigned char *
pcre_maketables(void)
{
unsigned char *yield, *p;
int i;

#ifndef DFTABLES
yield = (unsigned char*)(pcre_malloc)(tables_length);
#else
yield = (unsigned char*)malloc(tables_length);
#endif

if (yield == NULL) return NULL;
p = yield;

/* First comes the lower casing table */

for (i = 0; i < 256; i++) *p++ = tolower(i);

/* Next the case-flipping table */

for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i);

/* Then the character class tables. Don't try to be clever and save effort on
exclusive ones - in some locales things may be different. Note that the table
for "space" includes everything "isspace" gives, including VT in the default
locale. This makes it work for the POSIX class [:space:]. Note also that it is
possible for a character to be alnum or alpha without being lower or upper,
such as "male and female ordinals" (\xAA and \xBA) in the fr_FR locale (at
least under Debian Linux's locales as of 12/2005). So we must test for alnum
specially. */

memset(p, 0, cbit_length);
for (i = 0; i < 256; i++)
  {
  if (isdigit(i)) p[cbit_digit  + i/8] |= 1 << (i&7);
  if (isupper(i)) p[cbit_upper  + i/8] |= 1 << (i&7);
  if (islower(i)) p[cbit_lower  + i/8] |= 1 << (i&7);
  if (isalnum(i)) p[cbit_word   + i/8] |= 1 << (i&7);
  if (i == '_')   p[cbit_word   + i/8] |= 1 << (i&7);
  if (isspace(i)) p[cbit_space  + i/8] |= 1 << (i&7);
  if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7);
  if (isgraph(i)) p[cbit_graph  + i/8] |= 1 << (i&7);
  if (isprint(i)) p[cbit_print  + i/8] |= 1 << (i&7);
  if (ispunct(i)) p[cbit_punct  + i/8] |= 1 << (i&7);
  if (iscntrl(i)) p[cbit_cntrl  + i/8] |= 1 << (i&7);
  }
p += cbit_length;

/* Finally, the character type table. In this, we exclude VT from the white
space chars, because Perl doesn't recognize it as such for \s and for comments
within regexes. */

for (i = 0; i < 256; i++)
  {
  int x = 0;
  if (i != 0x0b && isspace(i)) x += ctype_space;
  if (isalpha(i)) x += ctype_letter;
  if (isdigit(i)) x += ctype_digit;
  if (isxdigit(i)) x += ctype_xdigit;
  if (isalnum(i) || i == '_') x += ctype_word;

  /* Note: strchr includes the terminating zero in the characters it considers.
  In this instance, that is ok because we want binary zero to be flagged as a
  meta-character, which in this sense is any character that terminates a run
  of data characters. */

  if (strchr("\\*+?{^.$|()[", i) != 0) x += ctype_meta;
  *p++ = x;
  }

return yield;
}
Пример #6
0
// Similar to wcstoul, but returns a 64-bit number, and always assumes base is 0 
// static
ULONGLONG ConsoleArgs::wcstoul64( LPCWSTR nptr, LPCWSTR * endptr)
{
    unsigned __int64 val = 0; // accumulator
    unsigned __int64 maxval, maxdigval; // some limits
    const WCHAR *p = nptr;  // scanning/peek pointer
    unsigned ibase;
    unsigned digval;
    WCHAR c;                // current char
    bool fNegated = false;
    bool fHadDigits = false;
    bool fOverflow = false;

    if (endptr != NULL)
        *endptr = (WCHAR*)nptr;
	errno = 0;

    c = *p++;
    while(iswspace(c))
        c = *p++;

    if (c == L'+')
        c = *p++;
    else if (*nptr == L'-') {
        fNegated = true;
        c = *p++;
    }

    if (c == L'0') {
        if (*p == L'x' || *p == L'X') {
            // Hex
            ++p;
            c = *p++;
            ibase = 16;
            maxval = UI64(0xFFFFFFFFFFFFFFFF) / 16;
        }
        else {
            // Octal
            ibase = 8;
            maxval = UI64(0xFFFFFFFFFFFFFFFF) / 8;
        }
    }
    else {
        // Decimal
        ibase = 10;
    }

    maxval = UI64(0xFFFFFFFFFFFFFFFF) / ibase;
    maxdigval = UI64(0xFFFFFFFFFFFFFFFF) % ibase;

    for (;;) {
        if (c > 0xFF || !isxdigit((char)c) || (digval = HexValue(c)) >= ibase)
            break;

        fHadDigits = true;

        if (!fOverflow && (val < maxval || (val == maxval && digval <= maxdigval)))
            val = val * ibase + digval;
        else {
            fOverflow = true;
            if (endptr == NULL) {
                /* no need to keep on parsing if we
                   don't have to return the endptr. */
                break;
            }
        }

        c = *p++;
    }

    --p;                /* point to place that stopped scan */

    if (!fHadDigits) {
        /* no number there; return 0 and point to beginning of
           string */
        if (endptr)
            /* store beginning of string in endptr later on */
            p = nptr;
        ASSERT(val == 0);
    }
    else if ( fOverflow )
    {
        /* overflow occurred */
        errno = ERANGE;
        val = UI64(0xFFFFFFFFFFFFFFFF);
    }

    if (endptr != NULL)
        /* store pointer to char that stopped the scan */
        *endptr = (WCHAR*)p;

    if (fNegated)
        /* negate result if there was a neg sign */
        val = (unsigned __int64)(-(__int64)val);

    return val;
}
Пример #7
0
/* 
 * Check whether "cp" is a valid ascii representation
 * of an Internet address and convert to a binary address.
 * Returns 1 if the address is valid, 0 if not.
 * This replaces inet_addr, the return value from which
 * cannot distinguish between failure and a local broadcast address.
 */
int
inet_aton(const char *cp, struct in_addr *addr)
{
	uint32_t val;
	int base, n;
	char c;
	unsigned int parts[4];
	unsigned int *pp = parts;

	c = *cp;
	for (;;) {
		/*
		 * Collect number up to ``.''.
		 * Values are specified as for C:
		 * 0x=hex, 0=octal, isdigit=decimal.
		 */
		if (!isdigit((int)c))
			return (0);
		val = 0; base = 10;
		if (c == '0') {
			c = *++cp;
			if (c == 'x' || c == 'X')
				base = 16, c = *++cp;
			else
				base = 8;
		}
		for (;;) {
			if (isascii((int)c) && isdigit((int)c)) {
				val = (val * base) + (c - '0');
				c = *++cp;
			} else if (base == 16 && isascii((int)c) && isxdigit((int)c)) {
				val = (val << 4) |
					(c + 10 - (islower((int)c) ? 'a' : 'A'));
				c = *++cp;
			} else
				break;
		}
		if (c == '.') {
			/*
			 * Internet format:
			 *	a.b.c.d
			 *	a.b.c	(with c treated as 16 bits)
			 *	a.b	(with b treated as 24 bits)
			 */
			if (pp >= parts + 3)
				return (0);
			*pp++ = val;
			c = *++cp;
		} else
			break;
	}
	/*
	 * Check for trailing characters.
	 */
	if (c != '\0' && (!isascii((int)c) || !isspace((int)c)))
		return (0);
	/*
	 * Concoct the address according to
	 * the number of parts specified.
	 */
	n = pp - parts + 1;
	switch (n) {

	case 0:
		return (0);		/* initial nondigit */

	case 1:				/* a -- 32 bits */
		break;

	case 2:				/* a.b -- 8.24 bits */
		if ((val > 0xffffff) || (parts[0] > 0xff))
			return (0);
		val |= parts[0] << 24;
		break;

	case 3:				/* a.b.c -- 8.8.16 bits */
		if ((val > 0xffff) || (parts[0] > 0xff) || (parts[1] > 0xff))
			return (0);
		val |= (parts[0] << 24) | (parts[1] << 16);
		break;

	case 4:				/* a.b.c.d -- 8.8.8.8 bits */
		if ((val > 0xff) || (parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff))
			return (0);
		val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
		break;
	}
	if (addr)
		addr->s_addr = htonl(val);
	return (1);
}
Пример #8
0
int
ub_ctx_hosts(struct ub_ctx* ctx, const char* fname)
{
	FILE* in;
	char buf[1024], ldata[1024];
	char* parse, *addr, *name, *ins;
	lock_basic_lock(&ctx->cfglock);
	if(ctx->finalized) {
		lock_basic_unlock(&ctx->cfglock);
		errno=EINVAL;
		return UB_AFTERFINAL;
	}
	lock_basic_unlock(&ctx->cfglock);
	if(fname == NULL) {
#if defined(UB_ON_WINDOWS) && defined(HAVE_WINDOWS_H)
		/*
		 * If this is Windows NT/XP/2K it's in
		 * %WINDIR%\system32\drivers\etc\hosts.
		 * If this is Windows 95/98/Me it's in %WINDIR%\hosts.
		 */
		name = getenv("WINDIR");
		if (name != NULL) {
			int retval=0;
			snprintf(buf, sizeof(buf), "%s%s", name, 
				"\\system32\\drivers\\etc\\hosts");
			if((retval=ub_ctx_hosts(ctx, buf)) !=0 ) {
				snprintf(buf, sizeof(buf), "%s%s", name, 
					"\\hosts");
				retval=ub_ctx_hosts(ctx, buf);
			}
			return retval;
		}
		return UB_READFILE;
#else
		fname = "/etc/hosts";
#endif /* WIN32 */
	}
	in = fopen(fname, "r");
	if(!in) {
		/* error in errno! perror(fname) */
		return UB_READFILE;
	}
	while(fgets(buf, (int)sizeof(buf), in)) {
		buf[sizeof(buf)-1] = 0;
		parse=buf;
		while(*parse == ' ' || *parse == '\t')
			parse++;
		if(*parse == '#')
			continue; /* skip comment */
		/* format: <addr> spaces <name> spaces <name> ... */
		addr = parse;
		/* skip addr */
		while(isxdigit((unsigned char)*parse) || *parse == '.' || *parse == ':')
			parse++;
		if(*parse == '\r')
			parse++;
		if(*parse == '\n' || *parse == 0)
			continue;
		if(*parse == '%') 
			continue; /* ignore macOSX fe80::1%lo0 localhost */
		if(*parse != ' ' && *parse != '\t') {
			/* must have whitespace after address */
			fclose(in);
			errno=EINVAL;
			return UB_SYNTAX;
		}
		*parse++ = 0; /* end delimiter for addr ... */
		/* go to names and add them */
		while(*parse) {
			while(*parse == ' ' || *parse == '\t' || *parse=='\n'
				|| *parse=='\r')
				parse++;
			if(*parse == 0 || *parse == '#')
				break;
			/* skip name, allows (too) many printable characters */
			name = parse;
			while('!' <= *parse && *parse <= '~')
				parse++;
			if(*parse)
				*parse++ = 0; /* end delimiter for name */
			snprintf(ldata, sizeof(ldata), "%s %s %s",
				name, str_is_ip6(addr)?"AAAA":"A", addr);
			ins = strdup(ldata);
			if(!ins) {
				/* out of memory */
				fclose(in);
				errno=ENOMEM;
				return UB_NOMEM;
			}
			lock_basic_lock(&ctx->cfglock);
			if(!cfg_strlist_insert(&ctx->env->cfg->local_data, 
				ins)) {
				lock_basic_unlock(&ctx->cfglock);
				fclose(in);
				free(ins);
				errno=ENOMEM;
				return UB_NOMEM;
			}
			lock_basic_unlock(&ctx->cfglock);
		}
	}
	fclose(in);
	return UB_NOERROR;
}
static ssize_t reg_write(struct file *file, const char __user *ubuf,
						size_t count, loff_t *ppos)
{
	struct seq_file *s = file->private_data;
	struct mcde_display_device *ddev = s->private;
	struct device *dev;
	struct mcde_chnl_state *chnl;
	char *buf;
	const char *p;
	enum dbg_cmd_type cmd;
	u8 data[MCDE_MAX_DSI_DIRECT_CMD_WRITE + 1]; /* Make room for cmd  */
	int i = 0;
	int ret;
	char tmp[TMP_BUF_SZ];

	if (!ddev || !&ddev->dev) {
		pr_err("%s: no device\n", __func__);
		ret = -ENODEV;
		goto exit;
	}
	chnl = ddev->chnl_state;
	dev = &ddev->dev;

	dev_dbg(dev, "%s\n", __func__);

	reset_res_buf();

	buf = kzalloc(sizeof(char) * count, GFP_KERNEL);
	if (!buf) {
		dev_err(dev, "%s: Failed to allocate buffer\n", __func__);
		ret = -ENOMEM;
		goto exit;
	}

	dev_dbg(dev, "%s: buf = %p, ubuf = %p, count = %d, "
				"sizeof(char) * count = %d, line = %d\n",
		__func__, buf, ubuf, count, sizeof(char) * count, __LINE__);

	if (copy_from_user(buf, ubuf, count)) {
		ret = -EFAULT;
		goto fail_free_mem;
	}

	p = buf;

	if (!strncmp(buf, "dcs", 3)) {
		dev_dbg(dev, "%s: dcs\n", __func__);
		cmd = DCS;
	} else if (!strncmp(buf, "gen", 3)) {
		dev_dbg(dev, "%s: gen\n", __func__);
		cmd = GEN;
	} else {
		update_res_buf("Write - unknown type\n");
		ret = -EFAULT;
		goto fail_free_mem;
	}

	p = p+4;

	/* Get first param, Register */
	if (sscanf(p, "%4hhx", &data[0]) != 1) {
		update_res_buf("Write - parameter error\n");
		ret = -EINVAL;
		goto fail_free_mem;
	}
	i++;

	while (isxdigit(*p) || (*p == 'x'))
		p++;

	/* Get data */
	while (true) {
		if (isspace(*p)) {
			p++;
		} else {
			if (sscanf(p, "%4hhx", &data[i]) == 1) {
				while (isxdigit(*p) || (*p == 'x'))
					p++;
			}
			i++;
		}
		if (iscntrl(*p))
			break;

		if (i > MCDE_MAX_DSI_DIRECT_CMD_WRITE) {
			update_res_buf("Write - Too many parameters\n");
			ret = -EINVAL;
			goto fail_free_mem;
		}
	}

	if (cmd == DCS) {
		if (i == 1)
			ret = mcde_dsi_dcs_write(chnl, data[0], NULL, 0);
		else
			ret = mcde_dsi_dcs_write(chnl, data[0], &data[1],
									i - 1);
	} else {
		ret = mcde_dsi_generic_write(chnl, data, i);
	}

	if (!ret) {
		print_params(cmd, data[0], i - 1, &data[1]);
	} else {
		snprintf(tmp, sizeof(tmp), "Write failed, ret = %d!\n", ret);
		update_res_buf(tmp);
	}

fail_free_mem:
	kfree(buf);
exit:
	return count;
}
Пример #10
0
SendingMessage::SendingMessage(scenario *msg_scenario, char *const_src, bool skip_sanity)
{
    char * src = strdup(const_src);
    char * osrc = src;
    char * literal;
    int    literalLen;
    char * dest;
    char * key;
    char   current_line[MAX_HEADER_LEN];
    char * line_mark = NULL;
    char * tsrc;
    int    num_cr = get_cr_number(src);

    this->msg_scenario = msg_scenario;

    dest = literal = (char *)malloc(strlen(src) + num_cr + 1);

    current_line[0] = '\0';
    *dest = 0;

    while(*src) {
        if (current_line[0] == '\0') {
            line_mark = strchr(src, '\n');
            if (line_mark) {
                int header_len =  line_mark - src;
                if (header_len > MAX_HEADER_LEN-1)
                    header_len = MAX_HEADER_LEN-1;
                memcpy(current_line, src, header_len);
                current_line[header_len] = '\0';
            }
        }

        /* This hex encoding could be done in XML parsing, allowing us to skip
         * these conditionals and branches. */
        if ((*src == '\\') && (*(src+1) == 'x')) {
            /* Allows any hex coded char like '\x5B' ([) */
            src += 2;
            if (isxdigit(*src)) {
                int val = get_decimal_from_hex(*src);
                src++;
                if (isxdigit(*src)) {
                    val = (val << 4) + get_decimal_from_hex(*src);
                }
                *dest++ = val & 0xff;
            }
            src++;
        } else if (*src == '\n') {
            *dest++ = '\r';
            *dest++ = *src++;
            current_line[0] = '\0';
        } else if (*src != '[') {
            *dest++ = *src++;
        } else {
            /* We have found a keyword, store the literal that we have been generating. */
            literalLen = dest - literal;
            if (literalLen) {
                *dest = '\0';
                literal = (char *)realloc(literal, literalLen + 1);
                if (!literal) {
                    ERROR("Out of memory!");
                }

                MessageComponent *newcomp = (MessageComponent *)calloc(1, sizeof(MessageComponent));
                if (!newcomp) {
                    ERROR("Out of memory!");
                }

                newcomp->type = E_Message_Literal;
                newcomp->literal = literal;
                newcomp->literalLen = literalLen; // length without the terminator
                messageComponents.push_back(newcomp);
            } else {
                free(literal);
            }

            dest = literal = (char *)malloc(strlen(src) + num_cr + 1);
            *dest = '\0';

            /* Now lets determine which keyword we have. */
            MessageComponent *newcomp = (MessageComponent *)calloc(1, sizeof(MessageComponent));
            if (!newcomp) {
                ERROR("Out of memory!");
            }

            char keyword [KEYWORD_SIZE+1];
            src++;

            tsrc = quoted_strchr(src, '[');
            key = quoted_strchr(src, ']');

            if ((tsrc) && (tsrc<key)) {
                memcpy(keyword, src-1,  tsrc - src + 1);
                src=tsrc+1;
                dest += sprintf(dest, "%s", keyword);
            }

            if((!key) || ((key - src) > KEYWORD_SIZE) || (!(key - src))) {
                ERROR("Syntax error or invalid [keyword] in scenario while parsing '%s'", current_line);
            }
            memcpy(keyword, src,  key - src);
            keyword[key - src] = 0;
            src = key + 1;
            // allow +/-n for numeric variables
            newcomp->offset = 0;
            if ((strncmp(keyword, "authentication", strlen("authentication")) &&
                    strncmp(keyword, "tdmmap", strlen("tdmmap"))) &&
                    ((key = strchr(keyword,'+')) || (key = strchr(keyword,'-')))) {
                if (isdigit(*(key+1))) {
                    newcomp->offset = atoi(key);
                    *key = 0;
                }
            }

            char *spc = NULL;
            char ospc;
            if ((spc = strchr(keyword, ' '))) {
                ospc = *spc;
                *spc = '\0';
            }
            kw_map::iterator it = keyword_map.find(keyword);
            if (spc) {
                *spc = ospc;
            }

            if (it != keyword_map.end()) {
                newcomp->type = E_Message_Custom;
                newcomp->comp_param.fxn = it->second;
                messageComponents.push_back(newcomp);
                continue;
            }

            bool simple_keyword = false;
            for (unsigned int i = 0; i < sizeof(SimpleKeywords)/sizeof(SimpleKeywords[0]); i++) {
                if (!strcmp(keyword, SimpleKeywords[i].keyword)) {
                    newcomp->type = SimpleKeywords[i].type;
                    simple_keyword = true;
                    break;
                }
            }

            if (simple_keyword) {
                messageComponents.push_back(newcomp);
                continue;
            }

            if(!strncmp(keyword, "field", strlen("field"))) {
                newcomp->type = E_Message_Injection;

                /* Parse out the interesting things like file and number. */
                newcomp->comp_param.field_param.field = atoi(keyword + strlen("field"));

                char fileName[KEYWORD_SIZE];
                getKeywordParam(keyword, "file=", fileName);
                if (fileName[0] == '\0') {
                    if (!default_file) {
                        ERROR("No injection file was specified!\n");
                    }
                    newcomp->comp_param.field_param.filename = strdup(default_file);
                } else {
                    newcomp->comp_param.field_param.filename = strdup(fileName);
                }
                if (inFiles.find(newcomp->comp_param.field_param.filename) == inFiles.end()) {
                    ERROR("Invalid injection file: %s\n", fileName);
                }

                char line[KEYWORD_SIZE];
                getKeywordParam(keyword, "line=", line);
                if (line[0]) {
                    /* Turn this into a new message component. */
                    newcomp->comp_param.field_param.line = new SendingMessage(msg_scenario, line, true);
                }
            } else if(!strncmp(keyword, "file", strlen("file"))) {
                newcomp->type = E_Message_File;

                /* Parse out the interesting things like file and number. */
                char fileName[KEYWORD_SIZE];
                getKeywordParam(keyword, "name=", fileName);
                if (fileName[0] == '\0') {
                    ERROR("No name specified for 'file' keyword!\n");
                }
                /* Turn this into a new message component. */
                newcomp->comp_param.filename = new SendingMessage(msg_scenario, fileName, true);
            } else if(*keyword == '$') {
                newcomp->type = E_Message_Variable;
                if (!msg_scenario) {
                    ERROR("SendingMessage with variable usage outside of scenario!");
                }
                newcomp->varId = msg_scenario->get_var(keyword + 1, "Variable keyword");
            } else if(!strncmp(keyword, "fill", strlen("fill"))) {
                newcomp->type = E_Message_Fill;
                char filltext[KEYWORD_SIZE];
                char varName[KEYWORD_SIZE];

                getKeywordParam(keyword, "text=", filltext);
                if (filltext[0] == '\0') {
                    strcpy(filltext, "X");
                }
                getKeywordParam(keyword, "variable=", varName);

                newcomp->literal = strdup(filltext);
                newcomp->literalLen = strlen(newcomp->literal);
                if (!msg_scenario) {
                    ERROR("SendingMessage with variable usage outside of scenario!");
                }
                newcomp->varId = msg_scenario->get_var(varName, "Fill Variable");
            } else if(!strncmp(keyword, "last_", strlen("last_"))) {
                newcomp->type = E_Message_Last_Header;
                newcomp->literal = strdup(keyword + strlen("last_"));
                newcomp->literalLen = strlen(newcomp->literal);
            } else if(!strncmp(keyword, "authentication", strlen("authentication"))) {
                parseAuthenticationKeyword(msg_scenario, newcomp, keyword);
            }
#ifndef PCAPPLAY
            else if(!strcmp(keyword, "auto_media_port")) {
                ERROR("The %s keyword requires PCAPPLAY.\n", keyword);
            }
#endif
            else {
                // scan for the generic parameters - must be last test

                int i = 0;
                while (generic[i]) {
                    char *msg1 = *generic[i];
                    char *msg2 = *(generic[i] + 1);
                    if(!strcmp(keyword, msg1)) {
                        newcomp->type = E_Message_Literal;
                        newcomp->literal = strdup(msg2);
                        newcomp->literalLen = strlen(newcomp->literal);
                        break;
                    }
                    ++i;
                }
                if (!generic[i]) {
                    ERROR("Unsupported keyword '%s' in xml scenario file",
                          keyword);
                }
            }

            messageComponents.push_back(newcomp);
        }
    }
    if (literal[0]) {
        *dest++ = '\0';
        literalLen = dest - literal;
        literal = (char *)realloc(literal, literalLen);
        if (!literal) {
            ERROR("Out of memory!");
        }

        MessageComponent *newcomp = (MessageComponent *)calloc(1, sizeof(MessageComponent));
        if (!newcomp) {
            ERROR("Out of memory!");
        }

        newcomp->type = E_Message_Literal;
        newcomp->literal = literal;
        newcomp->literalLen = literalLen-1;
        messageComponents.push_back(newcomp);
    } else {
        free(literal);
    }

    if (skip_sanity) {
        cancel = response = ack = false;
        method = NULL;
        free(osrc);
        return;
    }

    if (numComponents() < 1) {
        ERROR("Can not create a message that is empty!");
    }
    if (getComponent(0)->type != E_Message_Literal) {
        ERROR("You can not use a keyword for the METHOD or to generate \"SIP/2.0\" to ensure proper [cseq] operation!\n%s\n", osrc);
    }

    char *p = method = strdup(getComponent(0)->literal);
    char *q;
    while (isspace(*p)) {
        p++;
    }
    if (!(q = strchr(method, ' '))) {
        ERROR("You can not use a keyword for the METHOD or to generate \"SIP/2.0\" to ensure proper [cseq] operation!%s\n", osrc);
    }
    *q++ = '\0';
    while (isspace(*q)) {
        q++;
    }
    if (!strcmp(method, "SIP/2.0")) {
        char *endptr;
        code = strtol(q, &endptr, 10);
        if (*endptr && !isspace(*endptr)) {
            ERROR("Invalid reply code: %s\n", q);
        }
        if (code < 100 || code >= 700) {
            ERROR("Response codes must be in the range of 100-700");
        }
        response = true;
        ack = false;
        cancel = false;
        free(method);
        method = NULL;
    } else {
        if (p != method) {
            memmove(method, p, strlen(p) + 1);
        }
        method = (char *)realloc(method, strlen(method) + 1);
        if (!method) {
            ERROR("Out of memory");
        }
        ack = (!strcmp(method, "ACK"));
        cancel = (!strcmp(method, "CANCEL"));
        response = false;
    };
    free(osrc);
}
Пример #11
0
int 
ub_ctx_resolvconf(struct ub_ctx* ctx, const char* fname)
{
	FILE* in;
	int numserv = 0;
	char buf[1024];
	char* parse, *addr;
	int r;

	if(fname == NULL) {
#if !defined(UB_ON_WINDOWS) || !defined(HAVE_WINDOWS_H)
		fname = "/etc/resolv.conf";
#else
		FIXED_INFO *info;
		ULONG buflen = sizeof(*info);
		IP_ADDR_STRING *ptr;

		info = (FIXED_INFO *) malloc(sizeof (FIXED_INFO));
		if (info == NULL) 
			return UB_READFILE;

		if (GetNetworkParams(info, &buflen) == ERROR_BUFFER_OVERFLOW) {
			free(info);
			info = (FIXED_INFO *) malloc(buflen);
			if (info == NULL)
				return UB_READFILE;
		}

		if (GetNetworkParams(info, &buflen) == NO_ERROR) {
			int retval=0;
			ptr = &(info->DnsServerList);
			while (ptr) {
				numserv++;
				if((retval=ub_ctx_set_fwd(ctx, 
					ptr->IpAddress.String))!=0) {
					free(info);
					return retval;
				}
				ptr = ptr->Next;
			}
			free(info);
			if (numserv==0)
				return UB_READFILE;
			return UB_NOERROR;
		}
		free(info);
		return UB_READFILE;
#endif /* WINDOWS */
	}
	in = fopen(fname, "r");
	if(!in) {
		/* error in errno! perror(fname) */
		return UB_READFILE;
	}
	while(fgets(buf, (int)sizeof(buf), in)) {
		buf[sizeof(buf)-1] = 0;
		parse=buf;
		while(*parse == ' ' || *parse == '\t')
			parse++;
		if(strncmp(parse, "nameserver", 10) == 0) {
			numserv++;
			parse += 10; /* skip 'nameserver' */
			/* skip whitespace */
			while(*parse == ' ' || *parse == '\t')
				parse++;
			addr = parse;
			/* skip [0-9a-fA-F.:]*, i.e. IP4 and IP6 address */
			while(isxdigit((unsigned char)*parse) || *parse=='.' || *parse==':')
				parse++;
			/* terminate after the address, remove newline */
			*parse = 0;
			
			if((r = ub_ctx_set_fwd(ctx, addr)) != UB_NOERROR) {
				fclose(in);
				return r;
			}
		}
	}
	fclose(in);
	if(numserv == 0) {
		/* from resolv.conf(5) if none given, use localhost */
		return ub_ctx_set_fwd(ctx, "127.0.0.1");
	}
	return UB_NOERROR;
}
Пример #12
0
void unescape_string(const std::string &src, std::string &dest)
{
  dest="";
  dest.reserve(src.size());

  for(unsigned i=0; i<src.size(); i++)
  {
    char ch=src[i];

    if(ch=='\\')
    {
      i++;
      ch=src[i];
      switch(ch)
      {
      case '\\': dest+=ch; break;
      case 'n': dest+='\n'; break; /* NL (0x0a) */
      case 't': dest+='\t'; break; /* HT (0x09) */
      case 'v': dest+='\v'; break; /* VT (0x0b) */
      case 'b': dest+='\b'; break; /* BS (0x08) */
      case 'r': dest+='\r'; break; /* CR (0x0d) */
      case 'f': dest+='\f'; break; /* FF (0x0c) */
      case 'a': dest+='\a'; break; /* BEL (0x07) */
      
      case 'x': // hex
        i++;

        {
          std::string hex;
          while(isxdigit(src[i]))
          {
            i++;
            hex+=src[i];
          }
        
          unsigned int result;
          sscanf(hex.c_str(), "%x", &result);
          ch=result;
        }
        
        dest+=ch;
      
        break;
      
      default:
        if(isdigit(ch)) // octal
        {
          std::string octal;
          
          while(isdigit(src[i]))
          {
            octal+=src[i];
            i++;
          }
          
          unsigned int result;
          sscanf(octal.c_str(), "%o", &result);
          ch=result;
          dest+=ch;
        }
        else
        {
          dest+='\\';
          dest+=ch;
        }
      }
    }
    else
      dest+=ch;
  }
}
Пример #13
0
static int getToken()
{
    const char tab[] = "bfnrt\"\'\\";
    const char backTab[] = "\b\f\n\r\t\"\'\\";

    yyIdent.clear();
    yyComment.clear();
    yyString.clear();

    while ( yyCh != EOF ) {
        yyLineNo = yyCurLineNo;

        if ( yyCh.isLetter() || yyCh.toLatin1() == '_' ) {
            do {
                yyIdent.append(yyCh);
                yyCh = getChar();
            } while ( yyCh.isLetterOrNumber() || yyCh.toLatin1() == '_' );

            if (yyTok != Tok_Dot) {
                switch ( yyIdent.at(0).toLatin1() ) {
                    case 'r':
                        if ( yyIdent == QLatin1String("return") )
                            return Tok_return;
                        break;
                     case 'c':
                        if ( yyIdent == QLatin1String("class") )
                            return Tok_class;
                        break;
                     case 'n':
                         if ( yyIdent == QLatin1String("null") )
                             return Tok_null;
                        break;
                }
            }
            switch ( yyIdent.at(0).toLatin1() ) {
            case 'T':
                // TR() for when all else fails
                if ( yyIdent == QLatin1String("TR") )
                    return Tok_tr;
                break;
            case 'p':
                if( yyIdent == QLatin1String("package") )
                    return Tok_Package;
                break;
            case 't':
                if ( yyIdent == QLatin1String("tr") )
                    return Tok_tr;
                if ( yyIdent == QLatin1String("translate") )
                    return Tok_translate;
                }
            return Tok_Ident;
        } else {
            switch ( yyCh.toLatin1() ) {

            case '/':
                yyCh = getChar();
                if ( yyCh == QLatin1Char('/') ) {
                    do {
                        yyCh = getChar();
                        if (yyCh == EOF)
                            break;
                        yyComment.append(yyCh);
                    } while (yyCh != QLatin1Char('\n'));
                    return Tok_Comment;

                } else if ( yyCh == QLatin1Char('*') ) {
                    bool metAster = false;
                    bool metAsterSlash = false;

                    while ( !metAsterSlash ) {
                        yyCh = getChar();
                        if ( yyCh == EOF ) {
                            yyMsg() << qPrintable(LU::tr("Unterminated Java comment.\n"));
                            return Tok_Comment;
                        }

                        yyComment.append( yyCh );

                        if ( yyCh == QLatin1Char('*') )
                            metAster = true;
                        else if ( metAster && yyCh == QLatin1Char('/') )
                            metAsterSlash = true;
                        else
                            metAster = false;
                    }
                    yyComment.chop(2);
                    yyCh = getChar();

                    return Tok_Comment;
                }
                break;
            case '"':
                yyCh = getChar();

                while ( yyCh != EOF && yyCh != QLatin1Char('\n') && yyCh != QLatin1Char('"') ) {
                    if ( yyCh == QLatin1Char('\\') ) {
                        yyCh = getChar();
                        if ( yyCh == QLatin1Char('u') ) {
                            yyCh = getChar();
                            uint unicode(0);
                            for (int i = 4; i > 0; --i) {
                                unicode = unicode << 4;
                                if( yyCh.isDigit() ) {
                                    unicode += yyCh.digitValue();
                                }
                                else {
                                    int sub(yyCh.toLower().toAscii() - 87);
                                    if( sub > 15 || sub < 10) {
                                        yyMsg() << qPrintable(LU::tr("Invalid Unicode value.\n"));
                                        break;
                                    }
                                    unicode += sub;
                                }
                                yyCh = getChar();
                            }
                            yyString.append(QChar(unicode));
                        }
                        else if ( yyCh == QLatin1Char('\n') ) {
                            yyCh = getChar();
                        }
                        else {
                            yyString.append( QLatin1Char(backTab[strchr( tab, yyCh.toAscii() ) - tab]) );
                            yyCh = getChar();
                        }
                    } else {
                        yyString.append(yyCh);
                        yyCh = getChar();
                    }
                }

                if ( yyCh != QLatin1Char('"') )
                    yyMsg() << qPrintable(LU::tr("Unterminated string.\n"));

                yyCh = getChar();

                return Tok_String;

            case ':':
                yyCh = getChar();
                return Tok_Colon;
            case '\'':
                yyCh = getChar();

                if ( yyCh == QLatin1Char('\\') )
                    yyCh = getChar();
                do {
                    yyCh = getChar();
                } while ( yyCh != EOF && yyCh != QLatin1Char('\'') );
                yyCh = getChar();
                break;
            case '{':
                yyCh = getChar();
                return Tok_LeftBrace;
            case '}':
                yyCh = getChar();
                return Tok_RightBrace;
            case '(':
                if (yyParenDepth == 0)
                    yyParenLineNo = yyCurLineNo;
                yyParenDepth++;
                yyCh = getChar();
                return Tok_LeftParen;
            case ')':
                if (yyParenDepth == 0)
                    yyParenLineNo = yyCurLineNo;
                yyParenDepth--;
                yyCh = getChar();
                return Tok_RightParen;
            case ',':
                yyCh = getChar();
                return Tok_Comma;
            case '.':
                yyCh = getChar();
                return Tok_Dot;
            case ';':
                yyCh = getChar();
                return Tok_Semicolon;
            case '+':
                yyCh = getChar();
                if (yyCh == QLatin1Char('+')) {
                    yyCh = getChar();
                    return Tok_PlusPlus;
		}
                if( yyCh == QLatin1Char('=') ){
                    yyCh = getChar();
                    return Tok_PlusEq;
		}
                return Tok_Plus;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                {
                    QByteArray ba;
                    ba += yyCh.toLatin1();
                    yyCh = getChar();
                    bool hex = yyCh == QLatin1Char('x');
                    if ( hex ) {
                        ba += yyCh.toLatin1();
                        yyCh = getChar();
                    }
                    while ( hex ? isxdigit(yyCh.toLatin1()) : yyCh.isDigit() ) {
                        ba += yyCh.toLatin1();
                        yyCh = getChar();
                    }
                    bool ok;
                    yyInteger = ba.toLongLong(&ok);
                    if (ok) return Tok_Integer;
                    break;
                }
            default:
                yyCh = getChar();
            }
        }
    }
    return Tok_Eof;
}
Пример #14
0
// =====================================================================
	void handle_mm_stuff(char *mailbuf,int fromwhere)
// =====================================================================
{
static int preflen=strlen(MM_PREFIX);
char	*p,*t;
char	name[300];
char	mmcod[MAX_PATH],mmbase[MAX_PATH];

	if (GetKeyState(VK_CONTROL) & 0x80000000)
		return;

// WAVES
// Format: 	MM_PREFIX|mmtype|whentoplay|name
	p=mailbuf;
handle_wav:
	if ((gc.sound_enabled && !gc.sound_already_done) || fromwhere==3)
	{
find_ag1:
		p=strstr(p,MM_PREFIX);
		if (p)
		{
			p+=preflen;
			switch (*p)
			{
				case 'W':
				case 'w':
					break;
				case 'B':
				case 'b':
					if ((gc.bmps_enabled && !gc.bmps_already_done) || fromwhere==3)
					{
						p-=preflen;
						goto handle_bmp;
					}
					goto find_ag1;
				case '\0':
					return;
				default:
					goto find_ag1;
			}

			p++;
			if (fromwhere!=3)
			{
				switch (*p)	// 1-Play on display , 2-Play on income
				{
					case '1':
						if (fromwhere!=1)
							goto handle_bmp;
						break;
					case '2':
						if (fromwhere!=2)
							goto handle_bmp;
						break;
					default:
						goto handle_bmp;
				}
			}
			p++;
			name[0]=0;
			sscanf(p,"%s",name);
			if (!name[0] || strlen(name)>8)
				goto handle_bmp;

			t=name;
			while (*t)
			{
				if (!isxdigit(*t))
					goto handle_bmp;
				t++;
			}
			strcpy(mmcod,"00000000");
			memcpy(mmcod+(8-strlen(name)),name,strlen(name));
//			strcpy(mmcod,name);
			strcat(mmcod,".WAV");
			make_path(mmbase,gc.MultimedPath,mmcod);
			if (access(mmbase,0))
			{
				if (gc.no_error)
					err_out("W_CNFMMXF",mmbase);
				goto handle_bmp;
			}
			gc.sound_already_done=1;
			test_sound(mmbase);
		}
		else
			return;
	}

// BITMAPS
// Format: 	MM_PREFIX|mmtype|whentoplay|name with ending NULL
handle_bmp:
	if ((gc.bmps_enabled && !gc.bmps_already_done) || fromwhere==3)
	{
find_ag2:
		p=strstr(p,MM_PREFIX);
		if (p)
		{
			p+=preflen;
			switch (*p)
			{
				case 'W':
				case 'w':
					if ((gc.sound_enabled && !gc.sound_already_done) || fromwhere==3)
					{
						p-=preflen;
						goto handle_wav;
					}
					goto find_ag2;
				case 'B':
				case 'b':
					break;
				case '\0':
					return;
				default:
					goto find_ag2;
			}
			p++;
			if (fromwhere!=3)
			{
				switch (*p)	// 1=Play on display , 2=Play on income
				{
					case '1':
						if (fromwhere!=1)
							goto handle_wav;
						break;
					case '2':
						if (fromwhere!=2)
							goto handle_wav;
						break;
					default:
						goto handle_wav;
				}
			}
			p++;
			name[0]=0;
			sscanf(p,"%s",name);
			if (!name[0] || strlen(name)>8)
				goto handle_wav;

			t=name;
			while (*t)
			{
				if (!isxdigit(*t))
					goto handle_wav;
				t++;
			}
			strcpy(mmcod,"00000000");
			memcpy(mmcod+(8-strlen(name)),name,strlen(name));
			strcpy(mmcod,name);
			strcat(mmcod,".BMP");
			make_path(mmbase,gc.MultimedPath,mmcod);
			if (access(mmbase,0))
			{
				if (gc.no_error)
					err_out("W_CNFMMXF",mmbase);
				goto handle_wav;
			}
			gc.bmps_already_done=1;
			display_bitmap(mmbase);
		}
		else
			return;
		
		goto handle_wav;
	}
}
Пример #15
0
/*
 * Number scanner
 *
 * state |      ch         | next state
 * ------+-----------------+--------------------------
 *   0   | [0]             | 1
 *   0   | [1-9]           | 4
 *   0   | .               | error (should never occur)
 *   1   | [xX]            | 2
 *   1   | [0-7]           | 3
 *   1   | [89a-wyzA-WYZ_] | error invalid digit
 *   1   | .               | return 0
 *   2   | [0-9a-fA-F]     | 2
 *   2   | [g-zG-Z_]       | error invalid hex digit
 *   2   | .               | return (hex-number) if TOS != [xX] else error
 *   3   | [0-7]           | 3
 *   3   | [89a-zA-Z_]     | error invalid octal digit
 *   3   | .               | return (octal-number)
 *   4   | [0-9]           | 4
 *   4   | [a-zA-Z_]       | error invalid decimal digit
 *   4   | .               | return (decimal-number)
 *
 * All non-identifier characters [^a-zA-Z_0-9] terminate the scan
 * and return the value. This is not entirely correct, but close
 * enough (should check punctuators as trailing context, but the
 * char_table is not adapted to that and it is questionable whether
 * it is worth the trouble).
 * All non-iso-8859-1 characters are an error.
 */
static int scan_number(int ch)
{
	int state = 0;
	int base = 10;
	empty_char_stack();

	while(1)
	{
		if(!isisochar(ch))
			xyyerror("Invalid digit\n");

		switch(state)
		{
		case 0:
			if(isdigit(ch))
			{
				push_char(ch);
				if(ch == '0')
					state = 1;
				else
					state = 4;
			}
			else
				internal_error(__FILE__, __LINE__, "Non-digit in first number-scanner state\n");
			break;
		case 1:
			if(ch == 'x' || ch == 'X')
			{
				push_char(ch);
				state = 2;
			}
			else if(ch >= '0' && ch <= '7')
			{
				push_char(ch);
				state = 3;
			}
			else if(isalpha(ch) || ch == '_')
				xyyerror("Invalid number digit\n");
			else
			{
				unget_unichar(ch);
				mcy_lval.num = 0;
				return tNUMBER;
			}
			break;
		case 2:
			if(isxdigit(ch))
				push_char(ch);
			else if(isalpha(ch) || ch == '_' || !isxdigit(tos_char_stack()))
				xyyerror("Invalid hex digit\n");
			else
			{
				base = 16;
				goto finish;
			}
			break;
		case 3:
			if(ch >= '0' && ch <= '7')
				push_char(ch);
			else if(isalnum(ch) || ch == '_')
				xyyerror("Invalid octal digit\n");
			else
			{
				base = 8;
				goto finish;
			}
			break;
		case 4:
			if(isdigit(ch))
				push_char(ch);
			else if(isalnum(ch) || ch == '_')
				xyyerror("Invalid decimal digit\n");
			else
			{
				base = 10;
				goto finish;
			}
			break;
		default:
			internal_error(__FILE__, __LINE__, "Invalid state in number-scanner\n");
		}
		ch = get_unichar();
	}
finish:
	unget_unichar(ch);
	push_char(0);
	mcy_lval.num = strtoul(get_char_stack(), NULL, base);
	return tNUMBER;
}
Пример #16
0
xbool_t ctype_iswxdigit(xwchar_t c)
{
    return c < 0x100 ? isxdigit((char)c) : XFALSE;
}
Пример #17
0
inline int  HexValue (WCHAR c) { ASSERT (c < 0xFF && isxdigit((char)c)); return (c >= '0' && c <= '9') ? c - '0' : (c & 0xdf) - 'A' + 10; }
Пример #18
0
ILboolean XpmGetColour(ILubyte *Buffer, ILint Size, int Len, XpmPixel* Colours)
#endif
{
	ILint		i = 0, j, strLen = 0;
	ILubyte		ColBuff[3];
	char		Buff[1024];

	XpmPixel	Colour;
	ILubyte		Name[XPM_MAX_CHAR_PER_PIXEL];

	for ( ; i < Size; i++) {
		if (Buffer[i] == '\"')
			break;
	}
	i++;  // Skip the quotes.

	if (i >= Size)
		return IL_FALSE;

	// Get the characters.
	for (j = 0; j < Len; ++j) {
		Name[j] = Buffer[i++];
	}

	// Skip to the colour definition.
	for ( ; i < Size; i++) {
		if (Buffer[i] == 'c')
			break;
	}
	i++;  // Skip the 'c'.

	if (i >= Size || Buffer[i] != ' ') { // no 'c' found...assume black
#ifndef XPM_DONT_USE_HASHTABLE
		memset(Colour, 0, sizeof(Colour));
		Colour[3] = 255;
		XpmInsertEntry(Table, Name, Len, Colour);
#else
		memset(Colours[Name[0]], 0, sizeof(Colour));
		Colours[Name[0]][3] = 255;
#endif
		return IL_TRUE;
	}

	for ( ; i < Size; i++) {
		if (Buffer[i] != ' ')
			break;
	}

	if (i >= Size)
		return IL_FALSE;

	if (Buffer[i] == '#') {
		// colour string may 4 digits/color or 1 digit/color
		// (added 20040218) TODO: is isxdigit() ANSI???
		++i;
		while (i + strLen < Size && isxdigit(Buffer[i + strLen]))
			++strLen;

		for (j = 0; j < 3; j++) {
			if (strLen >= 10) { // 4 digits
				ColBuff[0] = Buffer[i + j*4];
				ColBuff[1] = Buffer[i + j*4 + 1];
			}
			else if (strLen >= 8) { // 3 digits
				ColBuff[0] = Buffer[i + j*3];
				ColBuff[1] = Buffer[i + j*3 + 1];
			}
			else if (strLen >= 6) { // 2 digits
				ColBuff[0] = Buffer[i + j*2];
				ColBuff[1] = Buffer[i + j*2 + 1];
			}
			else if(j < strLen) { // 1 digit, strLen >= 1
				ColBuff[0] = Buffer[i + j];
				ColBuff[1] = 0;
			}

			ColBuff[2] = 0; // add terminating '\0' char
			Colour[j] = (ILubyte)strtol((char*)ColBuff, NULL, 16);
		}
		Colour[3] = 255;  // Full alpha.
	}
	else {
		for (j = 0; i < Size; i++) {
			if (!isalnum(Buffer[i]))
				break;
			Buff[j++] = Buffer[i];
		}
		Buff[j] = 0;

		if (i >= Size)
			return IL_FALSE;

		if (!XpmPredefCol(Buff, &Colour))

			return IL_FALSE;
	}


#ifndef XPM_DONT_USE_HASHTABLE
	XpmInsertEntry(Table, Name, Len, Colour);
#else
	memcpy(Colours[Name[0]], Colour, sizeof(Colour));
#endif
	return IL_TRUE;
}
Пример #19
0
static void
parse_hex_string(const char *s, struct xt_string_info *info)
{
	int i=0, slen, sindex=0, schar;
	short hex_f = 0, literal_f = 0;
	char hextmp[3];

	slen = strlen(s);

	if (slen == 0) {
		xtables_error(PARAMETER_PROBLEM,
			"STRING must contain at least one char");
	}

	while (i < slen) {
		if (sindex >= XT_STRING_MAX_PATTERN_SIZE)
			xtables_error(PARAMETER_PROBLEM,
				      "STRING too long \"%s\"", s);
		if (s[i] == '\\' && !hex_f) {
			literal_f = 1;
		} else if (s[i] == '\\') {
			xtables_error(PARAMETER_PROBLEM,
				"Cannot include literals in hex data");
		} else if (s[i] == '|') {
			if (hex_f)
				hex_f = 0;
			else {
				hex_f = 1;
				/* get past any initial whitespace just after the '|' */
				while (s[i+1] == ' ')
					i++;
			}
			if (i+1 >= slen)
				break;
			else
				i++;  /* advance to the next character */
		}

		if (literal_f) {
			if (i+1 >= slen) {
				xtables_error(PARAMETER_PROBLEM,
					"Bad literal placement at end of string");
			}
			info->pattern[sindex] = s[i+1];
			i += 2;  /* skip over literal char */
			literal_f = 0;
		} else if (hex_f) {
			if (i+1 >= slen) {
				xtables_error(PARAMETER_PROBLEM,
					"Odd number of hex digits");
			}
			if (i+2 >= slen) {
				/* must end with a "|" */
				xtables_error(PARAMETER_PROBLEM, "Invalid hex block");
			}
			if (! isxdigit(s[i])) /* check for valid hex char */
				xtables_error(PARAMETER_PROBLEM, "Invalid hex char '%c'", s[i]);
			if (! isxdigit(s[i+1])) /* check for valid hex char */
				xtables_error(PARAMETER_PROBLEM, "Invalid hex char '%c'", s[i+1]);
			hextmp[0] = s[i];
			hextmp[1] = s[i+1];
			hextmp[2] = '\0';
			if (! sscanf(hextmp, "%x", &schar))
				xtables_error(PARAMETER_PROBLEM,
					"Invalid hex char `%c'", s[i]);
			info->pattern[sindex] = (char) schar;
			if (s[i+2] == ' ')
				i += 3;  /* spaces included in the hex block */
			else
				i += 2;
		} else {  /* the char is not part of hex data, so just copy */
			info->pattern[sindex] = s[i];
			i++;
		}
		sindex++;
	}
	info->patlen = sindex;
}
Пример #20
0
int main() {
  if (!isxdigit('a')) {
    abort();
  }
  if (!isxdigit('d')) {
    abort();
  }
  if (!isxdigit('f')) {
    abort();
  }
  if (isxdigit('z')) {
    abort();
  }
  if (!isxdigit('A')) {
    abort();
  }
  if (!isxdigit('D')) {
    abort();
  }
  if (!isxdigit('F')) {
    abort();
  }
  if (isxdigit('Z')) {
    abort();
  }
  if (isxdigit(' ')) {
    abort();
  }
  if (!isxdigit('0')) {
    abort();
  }
  if (!isxdigit('5')) {
    abort();
  }
  if (!isxdigit('9')) {
    abort();
  }
  if (isxdigit('!')) {
    abort();
  }
  if (isxdigit('@')) {
    abort();
  }
  if (isxdigit('[')) {
    abort();
  }
}
Пример #21
0
/*
 * unvis - decode characters previously encoded by vis
 */
int
unvis(char *cp, int c, int *astate, int flag)
{
	unsigned char uc = (unsigned char)c;
	unsigned char st, ia, is, lc;

/*
 * Bottom 8 bits of astate hold the state machine state.
 * Top 8 bits hold the current character in the http 1866 nv string decoding
 */
#define GS(a)		((a) & 0xff)
#define SS(a, b)	(((uint32_t)(a) << 24) | (b))
#define GI(a)		((uint32_t)(a) >> 24)

	_DIAGASSERT(cp != NULL);
	_DIAGASSERT(astate != NULL);
	st = GS(*astate);

	if (flag & UNVIS_END) {
		switch (st) {
		case S_OCTAL2:
		case S_OCTAL3:
		case S_HEX2:
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case S_GROUND:
			return UNVIS_NOCHAR;
		default:
			return UNVIS_SYNBAD;
		}
	}

	switch (st) {

	case S_GROUND:
		*cp = 0;
		if ((flag & VIS_NOESCAPE) == 0 && c == '\\') {
			*astate = SS(0, S_START);
			return UNVIS_NOCHAR;
		}
		if ((flag & VIS_HTTP1808) && c == '%') {
			*astate = SS(0, S_HEX1);
			return UNVIS_NOCHAR;
		}
		if ((flag & VIS_HTTP1866) && c == '&') {
			*astate = SS(0, S_AMP);
			return UNVIS_NOCHAR;
		}
		if ((flag & VIS_MIMESTYLE) && c == '=') {
			*astate = SS(0, S_MIME1);
			return UNVIS_NOCHAR;
		}
		*cp = c;
		return UNVIS_VALID;

	case S_START:
		switch(c) {
		case '\\':
			*cp = c;
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case '0': case '1': case '2': case '3':
		case '4': case '5': case '6': case '7':
			*cp = (c - '0');
			*astate = SS(0, S_OCTAL2);
			return UNVIS_NOCHAR;
		case 'M':
			*cp = (char)0200;
			*astate = SS(0, S_META);
			return UNVIS_NOCHAR;
		case '^':
			*astate = SS(0, S_CTRL);
			return UNVIS_NOCHAR;
		case 'n':
			*cp = '\n';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 'r':
			*cp = '\r';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 'b':
			*cp = '\b';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 'a':
			*cp = '\007';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 'v':
			*cp = '\v';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 't':
			*cp = '\t';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 'f':
			*cp = '\f';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 's':
			*cp = ' ';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 'E':
			*cp = '\033';
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		case 'x':
			*astate = SS(0, S_HEX);
			return UNVIS_NOCHAR;
		case '\n':
			/*
			 * hidden newline
			 */
			*astate = SS(0, S_GROUND);
			return UNVIS_NOCHAR;
		case '$':
			/*
			 * hidden marker
			 */
			*astate = SS(0, S_GROUND);
			return UNVIS_NOCHAR;
		}
		goto bad;

	case S_META:
		if (c == '-')
			*astate = SS(0, S_META1);
		else if (c == '^')
			*astate = SS(0, S_CTRL);
		else 
			goto bad;
		return UNVIS_NOCHAR;

	case S_META1:
		*astate = SS(0, S_GROUND);
		*cp |= c;
		return UNVIS_VALID;

	case S_CTRL:
		if (c == '?')
			*cp |= 0177;
		else
			*cp |= c & 037;
		*astate = SS(0, S_GROUND);
		return UNVIS_VALID;

	case S_OCTAL2:	/* second possible octal digit */
		if (isoctal(uc)) {
			/*
			 * yes - and maybe a third
			 */
			*cp = (*cp << 3) + (c - '0');
			*astate = SS(0, S_OCTAL3);
			return UNVIS_NOCHAR;
		}
		/*
		 * no - done with current sequence, push back passed char
		 */
		*astate = SS(0, S_GROUND);
		return UNVIS_VALIDPUSH;

	case S_OCTAL3:	/* third possible octal digit */
		*astate = SS(0, S_GROUND);
		if (isoctal(uc)) {
			*cp = (*cp << 3) + (c - '0');
			return UNVIS_VALID;
		}
		/*
		 * we were done, push back passed char
		 */
		return UNVIS_VALIDPUSH;

	case S_HEX:
		if (!isxdigit(uc))
			goto bad;
		/*FALLTHROUGH*/
	case S_HEX1:
		if (isxdigit(uc)) {
			*cp = xtod(uc);
			*astate = SS(0, S_HEX2);
			return UNVIS_NOCHAR;
		}
		/*
		 * no - done with current sequence, push back passed char
		 */
		*astate = SS(0, S_GROUND);
		return UNVIS_VALIDPUSH;

	case S_HEX2:
		*astate = S_GROUND;
		if (isxdigit(uc)) {
			*cp = xtod(uc) | (*cp << 4);
			return UNVIS_VALID;
		}
		return UNVIS_VALIDPUSH;

	case S_MIME1:
		if (uc == '\n' || uc == '\r') {
			*astate = SS(0, S_EATCRNL);
			return UNVIS_NOCHAR;
		}
		if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) {
			*cp = XTOD(uc);
			*astate = SS(0, S_MIME2);
			return UNVIS_NOCHAR;
		}
		goto bad;

	case S_MIME2:
		if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) {
			*astate = SS(0, S_GROUND);
			*cp = XTOD(uc) | (*cp << 4);
			return UNVIS_VALID;
		}
		goto bad;

	case S_EATCRNL:
		switch (uc) {
		case '\r':
		case '\n':
			return UNVIS_NOCHAR;
		case '=':
			*astate = SS(0, S_MIME1);
			return UNVIS_NOCHAR;
		default:
			*cp = uc;
			*astate = SS(0, S_GROUND);
			return UNVIS_VALID;
		}

	case S_AMP:
		*cp = 0;
		if (uc == '#') {
			*astate = SS(0, S_NUMBER);
			return UNVIS_NOCHAR;
		}
		*astate = SS(0, S_STRING);
		/*FALLTHROUGH*/

	case S_STRING:
		ia = *cp;		/* index in the array */
		is = GI(*astate);	/* index in the string */
		lc = is == 0 ? 0 : nv[ia].name[is - 1];	/* last character */

		if (uc == ';')
			uc = '\0';

		for (; ia < __arraycount(nv); ia++) {
			if (is != 0 && nv[ia].name[is - 1] != lc)
				goto bad;
			if (nv[ia].name[is] == uc)
				break;
		}

		if (ia == __arraycount(nv))
			goto bad;

		if (uc != 0) {
			*cp = ia;
			*astate = SS(is + 1, S_STRING);
			return UNVIS_NOCHAR;
		}

		*cp = nv[ia].value;
		*astate = SS(0, S_GROUND);
		return UNVIS_VALID;

	case S_NUMBER:
		if (uc == ';')
			return UNVIS_VALID;
		if (!isdigit(uc))
			goto bad;
		*cp += (*cp * 10) + uc - '0';
		return UNVIS_NOCHAR;

	default:
	bad:
		/*
		 * decoder in unknown state - (probably uninitialized)
		 */
		*astate = SS(0, S_GROUND);
		return UNVIS_SYNBAD;
	}
}
Пример #22
0
Файл: string.c Проект: Exim/exim
int
string_is_ip_address(const uschar *s, int *maskptr)
{
    int i;
    int yield = 4;

    /* If an optional mask is permitted, check for it. If found, pass back the
    offset. */

    if (maskptr != NULL)
    {
        const uschar *ss = s + Ustrlen(s);
        *maskptr = 0;
        if (s != ss && isdigit(*(--ss)))
        {
            while (ss > s && isdigit(ss[-1])) ss--;
            if (ss > s && *(--ss) == '/') *maskptr = ss - s;
        }
    }

    /* A colon anywhere in the string => IPv6 address */

    if (Ustrchr(s, ':') != NULL)
    {
        BOOL had_double_colon = FALSE;
        BOOL v4end = FALSE;
        int count = 0;

        yield = 6;

        /* An IPv6 address must start with hex digit or double colon. A single
        colon is invalid. */

        if (*s == ':' && *(++s) != ':') return 0;

        /* Now read up to 8 components consisting of up to 4 hex digits each. There
        may be one and only one appearance of double colon, which implies any number
        of binary zero bits. The number of preceding components is held in count. */

        for (count = 0; count < 8; count++)
        {
            /* If the end of the string is reached before reading 8 components, the
            address is valid provided a double colon has been read. This also applies
            if we hit the / that introduces a mask or the % that introduces the
            interface specifier (scope id) of a link-local address. */

            if (*s == 0 || *s == '%' || *s == '/') return had_double_colon? yield : 0;

            /* If a component starts with an additional colon, we have hit a double
            colon. This is permitted to appear once only, and counts as at least
            one component. The final component may be of this form. */

            if (*s == ':')
            {
                if (had_double_colon) return 0;
                had_double_colon = TRUE;
                s++;
                continue;
            }

            /* If the remainder of the string contains a dot but no colons, we
            can expect a trailing IPv4 address. This is valid if either there has
            been no double-colon and this is the 7th component (with the IPv4 address
            being the 7th & 8th components), OR if there has been a double-colon
            and fewer than 6 components. */

            if (Ustrchr(s, ':') == NULL && Ustrchr(s, '.') != NULL)
            {
                if ((!had_double_colon && count != 6) ||
                        (had_double_colon && count > 6)) return 0;
                v4end = TRUE;
                yield = 6;
                break;
            }

            /* Check for at least one and not more than 4 hex digits for this
            component. */

            if (!isxdigit(*s++)) return 0;
            if (isxdigit(*s) && isxdigit(*(++s)) && isxdigit(*(++s))) s++;

            /* If the component is terminated by colon and there is more to
            follow, skip over the colon. If there is no more to follow the address is
            invalid. */

            if (*s == ':' && *(++s) == 0) return 0;
        }

        /* If about to handle a trailing IPv4 address, drop through. Otherwise
        all is well if we are at the end of the string or at the mask or at a percent
        sign, which introduces the interface specifier (scope id) of a link local
        address. */

        if (!v4end)
            return (*s == 0 || *s == '%' ||
                    (*s == '/' && maskptr != NULL && *maskptr != 0))? yield : 0;
    }

    /* Test for IPv4 address, which may be the tail-end of an IPv6 address. */

    for (i = 0; i < 4; i++)
    {
        if (i != 0 && *s++ != '.') return 0;
        if (!isdigit(*s++)) return 0;
        if (isdigit(*s) && isdigit(*(++s))) s++;
    }

    return (*s == 0 || (*s == '/' && maskptr != NULL && *maskptr != 0))?
           yield : 0;
}
Пример #23
0
/* httpread_read_handler -- called when socket ready to read
 *
 * Note: any extra data we read past end of transmitted file is ignored;
 * if we were to support keeping connections open for multiple files then
 * this would have to be addressed.
 */
static void httpread_read_handler(int sd, void *eloop_ctx, void *sock_ctx)
{
	struct httpread *h = sock_ctx;
	int nread;
	char *rbp;      /* pointer into read buffer */
	char *hbp;      /* pointer into header buffer */
	char *bbp;      /* pointer into body buffer */
	char readbuf[HTTPREAD_READBUF_SIZE];  /* temp use to read into */

	if (httpread_debug >= 20)
		wpa_printf(MSG_DEBUG, "ENTER httpread_read_handler(%p)", h);

	/* read some at a time, then search for the interal
	 * boundaries between header and data and etc.
	 */
	nread = read(h->sd, readbuf, sizeof(readbuf));
	if (nread < 0)
		goto bad;
	if (nread == 0) {
		/* end of transmission... this may be normal
		 * or may be an error... in some cases we can't
		 * tell which so we must assume it is normal then.
		 */
		if (!h->got_hdr) {
			/* Must at least have completed header */
			wpa_printf(MSG_DEBUG, "httpread premature eof(%p)", h);
			goto bad;
		}
		if (h->chunked || h->got_content_length) {
			/* Premature EOF; e.g. dropped connection */
			wpa_printf(MSG_DEBUG,
				   "httpread premature eof(%p) %d/%d",
				   h, h->body_nbytes,
				   h->content_length);
			goto bad;
		}
		/* No explicit length, hopefully we have all the data
		 * although dropped connections can cause false
		 * end
		 */
		if (httpread_debug >= 10)
			wpa_printf(MSG_DEBUG, "httpread ok eof(%p)", h);
			h->got_body = 1;
			goto got_file;
	}
	rbp = readbuf;

	/* Header consists of text lines (terminated by both CR and LF)
	 * and an empty line (CR LF only).
	 */
	if (!h->got_hdr) {
		hbp = h->hdr + h->hdr_nbytes;
		/* add to headers until:
		 *      -- we run out of data in read buffer
		 *      -- or, we run out of header buffer room
		 *      -- or, we get double CRLF in headers
		 */
		for (;;) {
			if (nread == 0)
				goto get_more;
			if (h->hdr_nbytes == HTTPREAD_HEADER_MAX_SIZE) {
				goto bad;
			}
			*hbp++ = *rbp++;
			nread--;
			h->hdr_nbytes++;
			if (h->hdr_nbytes >= 4 &&
			    hbp[-1] == '\n' &&
			    hbp[-2] == '\r' &&
			    hbp[-3] == '\n' &&
			    hbp[-4] == '\r' ) {
				h->got_hdr = 1;
				*hbp = 0;       /* null terminate */
				break;
			}
		}
		/* here we've just finished reading the header */
		if (httpread_hdr_analyze(h)) {
			wpa_printf(MSG_DEBUG, "httpread bad hdr(%p)", h);
			goto bad;
		}
		if (h->max_bytes == 0) {
			if (httpread_debug >= 10)
				wpa_printf(MSG_DEBUG,
					   "httpread no body hdr end(%p)", h);
			goto got_file;
		}
		if (h->got_content_length && h->content_length == 0) {
			if (httpread_debug >= 10)
				wpa_printf(MSG_DEBUG,
					   "httpread zero content length(%p)",
					   h);
			goto got_file;
		}
	}

	/* Certain types of requests never have data and so
	 * must be specially recognized.
	 */
	if (!os_strncasecmp(h->hdr, "SUBSCRIBE", 9) ||
	    !os_strncasecmp(h->hdr, "UNSUBSCRIBE", 11) ||
	    !os_strncasecmp(h->hdr, "HEAD", 4) ||
	    !os_strncasecmp(h->hdr, "GET", 3)) {
		if (!h->got_body) {
			if (httpread_debug >= 10)
				wpa_printf(MSG_DEBUG,
					   "httpread NO BODY for sp. type");
		}
		h->got_body = 1;
		goto got_file;
	}

	/* Data can be just plain binary data, or if "chunked"
	 * consists of chunks each with a header, ending with
	 * an ending header.
	 */
	if (nread == 0)
		goto get_more;
	if (!h->got_body) {
		/* Here to get (more of) body */
		/* ensure we have enough room for worst case for body
		 * plus a null termination character
		 */
		if (h->body_alloc_nbytes < (h->body_nbytes + nread + 1)) {
			char *new_body;
			int new_alloc_nbytes;

			if (h->body_nbytes >= h->max_bytes)
				goto bad;
			new_alloc_nbytes = h->body_alloc_nbytes +
				HTTPREAD_BODYBUF_DELTA;
			/* For content-length case, the first time
			 * through we allocate the whole amount
			 * we need.
			 */
			if (h->got_content_length &&
			    new_alloc_nbytes < (h->content_length + 1))
				new_alloc_nbytes = h->content_length + 1;
			if ((new_body = os_realloc(h->body, new_alloc_nbytes))
			    == NULL)
				goto bad;

			h->body = new_body;
			h->body_alloc_nbytes = new_alloc_nbytes;
		}
		/* add bytes */
		bbp = h->body + h->body_nbytes;
		for (;;) {
			int ncopy;
			/* See if we need to stop */
			if (h->chunked && h->in_chunk_data == 0) {
				/* in chunk header */
				char *cbp = h->body + h->chunk_start;
				if (bbp-cbp >= 2 && bbp[-2] == '\r' &&
				    bbp[-1] == '\n') {
					/* end of chunk hdr line */
					/* hdr line consists solely
					 * of a hex numeral and CFLF
					 */
					if (!isxdigit(*cbp))
						goto bad;
					h->chunk_size = strtoul(cbp, NULL, 16);
					/* throw away chunk header
					 * so we have only real data
					 */
					h->body_nbytes = h->chunk_start;
					bbp = cbp;
					if (h->chunk_size == 0) {
						/* end of chunking */
						/* trailer follows */
						h->in_trailer = 1;
						if (httpread_debug >= 20)
							wpa_printf(
								MSG_DEBUG,
								"httpread end chunks(%p)", h);
						break;
					}
					h->in_chunk_data = 1;
					/* leave chunk_start alone */
				}
			} else if (h->chunked) {
				/* in chunk data */
				if ((h->body_nbytes - h->chunk_start) ==
				    (h->chunk_size + 2)) {
					/* end of chunk reached,
					 * new chunk starts
					 */
					/* check chunk ended w/ CRLF
					 * which we'll throw away
					 */
					if (bbp[-1] == '\n' &&
					    bbp[-2] == '\r') {
					} else
						goto bad;
					h->body_nbytes -= 2;
					bbp -= 2;
					h->chunk_start = h->body_nbytes;
					h->in_chunk_data = 0;
					h->chunk_size = 0; /* just in case */
				}
			} else if (h->got_content_length &&
				   h->body_nbytes >= h->content_length) {
				h->got_body = 1;
				if (httpread_debug >= 10)
					wpa_printf(
						MSG_DEBUG,
						"httpread got content(%p)", h);
				goto got_file;
			}
			if (nread <= 0)
				break;
			/* Now transfer. Optimize using memcpy where we can. */
			if (h->chunked && h->in_chunk_data) {
				/* copy up to remainder of chunk data
				 * plus the required CR+LF at end
				 */
				ncopy = (h->chunk_start + h->chunk_size + 2) -
					h->body_nbytes;
			} else if (h->chunked) {
				/*in chunk header -- don't optimize */
				*bbp++ = *rbp++;
				nread--;
				h->body_nbytes++;
				continue;
			} else if (h->got_content_length) {
				ncopy = h->content_length - h->body_nbytes;
			} else {
				ncopy = nread;
			}
			/* Note: should never be 0 */
			if (ncopy > nread)
				ncopy = nread;
			os_memcpy(bbp, rbp, ncopy);
			bbp += ncopy;
			h->body_nbytes += ncopy;
			rbp += ncopy;
			nread -= ncopy;
		}       /* body copy loop */
	}       /* !got_body */
	if (h->chunked && h->in_trailer) {
		/* If "chunked" then there is always a trailer,
		 * consisting of zero or more non-empty lines
		 * ending with CR LF and then an empty line w/ CR LF.
		 * We do NOT support trailers except to skip them --
		 * this is supported (generally) by the http spec.
		 */
		bbp = h->body + h->body_nbytes;
		for (;;) {
			int c;
			if (nread <= 0)
				break;
			c = *rbp++;
			nread--;
			switch (h->trailer_state) {
			case trailer_line_begin:
				if (c == '\r')
					h->trailer_state = trailer_empty_cr;
				else
					h->trailer_state = trailer_nonempty;
				break;
			case trailer_empty_cr:
				/* end empty line */
				if (c == '\n') {
					h->trailer_state = trailer_line_begin;
					h->in_trailer = 0;
					if (httpread_debug >= 10)
						wpa_printf(
							MSG_DEBUG,
							"httpread got content(%p)", h);
					h->got_body = 1;
					goto got_file;
				}
				h->trailer_state = trailer_nonempty;
				break;
			case trailer_nonempty:
				if (c == '\r')
					h->trailer_state = trailer_nonempty_cr;
				break;
			case trailer_nonempty_cr:
				if (c == '\n')
					h->trailer_state = trailer_line_begin;
				else
					h->trailer_state = trailer_nonempty;
				break;
			}
		}
	}
	goto get_more;

bad:
	/* Error */
	wpa_printf(MSG_DEBUG, "httpread read/parse failure (%p)", h);
	(*h->cb)(h, h->cookie, HTTPREAD_EVENT_ERROR);
	return;

get_more:
	return;

got_file:
	if (httpread_debug >= 10)
		wpa_printf(MSG_DEBUG,
			   "httpread got file %d bytes type %d",
			   h->body_nbytes, h->hdr_type);
	/* Null terminate for convenience of some applications */
	if (h->body)
		h->body[h->body_nbytes] = 0; /* null terminate */
	h->got_file = 1;
	/* Assume that we do NOT support keeping connection alive,
	 * and just in case somehow we don't get destroyed right away,
	 * unregister now.
	 */
	if (h->sd_registered)
		eloop_unregister_sock(h->sd, EVENT_TYPE_READ);
	h->sd_registered = 0;
	/* The application can destroy us whenever they feel like...
	 * cancel timeout.
	 */
	if (h->to_registered)
		eloop_cancel_timeout(httpread_timeout_handler, NULL, h);
	h->to_registered = 0;
	(*h->cb)(h, h->cookie, HTTPREAD_EVENT_FILE_READY);
}
Пример #24
0
s32_t uip_ipaton(const u8_t *cp,struct in_addr *addr)
{
	u32_t val;
	u8_t c;
	u32_t parts[4];
	u32_t *pp = parts;
	int base,n;

	c = *cp;
	for(;;) {
		if(!isdigit(c)) return 0;
		
		val = 0; base = 10;
		if(c=='0') {
			c = *++cp;
			if(c=='x' || c=='X')
				base = 16, c = *++cp;
			else
				base = 8;
		}
		for(;;) {
			if(isdigit(c)) {
				val = (val*base)+(int)(c-'0');
				c = *++cp;
			} else if(base==16 && isxdigit(c)) {
				val = (val<<4)|(int)(c+10-(islower(c)?'a':'A'));
				c = *++cp;
			} else 
				break;
		}
		if(c=='.') {
			if(pp>=parts+3) return 0;
			*pp++ = val;
			c = *++cp;
		} else
			break;
	}

	if(c!='\0' && (!isascii(c) || isspace(c))) return 0;

	n = pp-parts+1;
	switch(n) {
		case 0:
			return 0;
		case 1:
			break;
		case 2:
			if(val>0x00ffffff) return 0;

			val |= (parts[0]<<24);
			break;
		case 3:
			if(val>0x0000ffff) return 0;

			val |= (parts[0]<<24)|(parts[1]<<16);
			break;
		case 4:
			if(val>0x000000ff) return 0;

			val |= (parts[0]<<24)|(parts[1]<<16)|(parts[2]<<8);
			break;
	}
	if(addr)
		addr->s_addr = htonl(val);

	return 1;
}
Пример #25
0
static void
odoffset(int argc, char ***argvp)
{
	char *p, *num, *end;
	int base;

	/*
	 * The offset syntax of od(1) was genuinely bizarre.  First, if
	 * it started with a plus it had to be an offset.  Otherwise, if
	 * there were at least two arguments, a number or lower-case 'x'
	 * followed by a number makes it an offset.  By default it was
	 * octal; if it started with 'x' or '0x' it was hex.  If it ended
	 * in a '.', it was decimal.  If a 'b' or 'B' was appended, it
	 * multiplied the number by 512 or 1024 byte units.  There was
	 * no way to assign a block count to a hex offset.
	 *
	 * We assume it's a file if the offset is bad.
	 */
	p = argc == 1 ? (*argvp)[0] : (*argvp)[1];

	if (*p != '+' && (argc < 2 ||
	    (!isdigit(p[0]) && (p[0] != 'x' || !isxdigit(p[1])))))
		return;

	base = 0;
	/*
	 * skip over leading '+', 'x[0-9a-fA-f]' or '0x', and
	 * set base.
	 */
	if (p[0] == '+')
		++p;
	if (p[0] == 'x' && isxdigit(p[1])) {
		++p;
		base = 16;
	} else if (p[0] == '0' && p[1] == 'x') {
		p += 2;
		base = 16;
	}

	/* skip over the number */
	if (base == 16)
		for (num = p; isxdigit(*p); ++p);
	else
		for (num = p; isdigit(*p); ++p);

	/* check for no number */
	if (num == p)
		return;

	/* if terminates with a '.', base is decimal */
	if (*p == '.') {
		if (base)
			return;
		base = 10;
	}

	skip = strtoll(num, &end, base ? base : 8);

	/* if end isn't the same as p, we got a non-octal digit */
	if (end != p) {
		skip = 0;
		return;
	}

	if (*p) {
		if (*p == 'B') {
			skip *= 1024;
			++p;
		} else if (*p == 'b') {
			skip *= 512;
			++p;
		}
	}

	if (*p) {
		skip = 0;
		return;
	}

	/*
	 * If the offset uses a non-octal base, the base of the offset
	 * is changed as well.  This isn't pretty, but it's easy.
	 */
	if (base == 16) {
		fshead->nextfu->fmt[TYPE_OFFSET] = 'x';
		fshead->nextfs->nextfu->fmt[TYPE_OFFSET] = 'x';
	} else if (base == 10) {
		fshead->nextfu->fmt[TYPE_OFFSET] = 'd';
		fshead->nextfs->nextfu->fmt[TYPE_OFFSET] = 'd';
	}

	/* Terminate file list. */
	(*argvp)[1] = NULL;
}
Пример #26
0
/* airspeed_otf_parse */
void airspeed_otf_parse(char c)
{
  static unsigned char otf_status = OTF_UNINIT, otf_idx = 0, otf_crs_idx;
  static char otf_inp[64];
  static unsigned int counter;
  static short course[3];
  static unsigned int altitude;
  static unsigned char checksum;

  switch (otf_status) {

  case OTF_WAIT_START:
    if (c == OTF_START) {
      otf_status++;
      otf_idx = 0;
    } else {
      otf_status = OTF_UNINIT;
    }
    break;

  case OTF_WAIT_COUNTER:
    if (isdigit((int)c)) {
      if (otf_idx == 0) {
//FIXME        otf_timestamp = getclock();
      }
      otf_inp[otf_idx++] = c;
    } else {
      if ((otf_idx == 5) && (c == OTF_LIMITER)) {
        otf_inp[otf_idx] = 0;
        counter = atoi(otf_inp);
        otf_idx = 0;
        otf_crs_idx = 0;
        otf_status++;
      } else {
        otf_status = OTF_UNINIT;
      }
    }
    break;

  case OTF_WAIT_ANGLES:
    if (isdigit((int)c) || (c == '-') || (c == '.')) {
      otf_inp[otf_idx++] = c;
    } else {
      if ((otf_idx > 1) && (otf_idx < 9) && (c == OTF_LIMITER)) {
        otf_inp[otf_idx] = 0;
        course[otf_crs_idx] = (int16_t) (100. * atof(otf_inp));
        otf_idx = 0;
        if (otf_crs_idx++ == 2) {
          otf_status++;
        }
      } else {
        otf_status = OTF_UNINIT;
      }
    }
    break;

  case OTF_WAIT_ALTITUDE:
    if (isdigit((int)c) || (c == '-') || (c == '.')) {
      otf_inp[otf_idx++] = c;
    } else {
      if ((otf_idx > 1) && (otf_idx < 9) && (c == OTF_LIMITER)) {
        otf_inp[otf_idx] = 0;
        altitude = (int32_t) (100. * atof(otf_inp));
        otf_idx = 0;
        otf_status++;
      } else {
        otf_status = OTF_UNINIT;
      }
    }
    break;

  case OTF_WAIT_CHECKSUM:
    if (isxdigit((int)c)) {
      otf_inp[otf_idx++] = c;
    } else {
      if ((otf_idx == 2) && (c == OTF_END)) {
        otf_inp[otf_idx] = 0;
        checksum = strtol(otf_inp, NULL, 16);
        otf_idx = 0;
        DOWNLINK_SEND_FLOW_AP_OTF(DefaultChannel, DefaultDevice, &counter, &course[0], &course[1], &course[2], &altitude, &checksum);
      }
      otf_status = OTF_UNINIT;
    }
    break;

  default:
    otf_status = OTF_UNINIT;
    break;
  }
}
Пример #27
0
u_long xatoi(const char *cp)
{
	u_long val;
	char base;
	char c;

	/*
	 * 0x=hex
	 * 0=octal
	 * isdigit=decimal
	 */
	c = *cp;
	if (!isdigit(c))
		return 0;
	val = 0;
	base = 10;
	if (c == '0') {
		c = *++cp;
		if (c == 'x' || c == 'X') {
			base = 16;
			c = *++cp;
		} else
			base = 8;
	}
	for (;;) {
#if 0
		if (isascii(c) && isdigit(c)) {
#else
		if (isdigit(c)) {
#endif
			val = (val * base) + (c - '0');
			c = *++cp;
#if 0
		} else if (base == 16 && isascii(c) && isxdigit(c)) {
#else
		} else if (base == 16 && isxdigit(c)) {
#endif
			val = (val << 4) | (c + 10 - (islower(c) ? 'a' : 'A'));
			c = *++cp;
		} else
			break;
	}
	return val;
}

void MemDump(void *mem, u_long len, u_char wordAccess)
{
	u_long memaddr = (u_long)mem;
	u_long addr;
	u_long i = 0;
	u_char line[17];	/* character display buffer */
	u_char j, k, l;
	u_char even = 1;
	u_short w = 0;
	SYS_DECL_LOCK;

	if (wordAccess) {
		memaddr &= ~0x1;	/* make even */
		len <<= 1;	/* make double */
	}

	memset(line, 0, sizeof(line));
	l = 0;
	addr = memaddr & ~0x0f;
	if (len <= 0)
		return;

	SYS_LOCK(); /* not non-reentrant code but for clean display */
	do {
		if ((addr & 0x0f) == 0)
			printf("%08lx  ", addr);
		if (addr < memaddr) {
			printf("  ");
			line[l++] = ' ';
		} else {
			u_char b;
			if (wordAccess) {
				if (even) {
					w = *((u_short *)addr);
					b = (u_char)((w >> 8) & 0xff);
					even = 0;
				} else {
					b = (u_char)(w & 0xff);
					even = 1;
				}
			} else
				b = *((u_char *)addr);
			printf("%02x", (int)b);
			i++;
			//line[l++] =isspace(b) ? ' ' : (isprint(b) ? b : '.');
			line[l++] =  (b >= 0x20 && b <= 0x7e) ? b : '.';

		}
Пример #28
0
/**
 * Check whether "cp" is a valid ascii representation
 * of an Internet address and convert to a binary address.
 * Returns 1 if the address is valid, 0 if not.
 * This replaces inet_addr, the return value from which
 * cannot distinguish between failure and a local broadcast address.
 *
 * @param cp IP address in ascii represenation (e.g. "127.0.0.1")
 * @param addr pointer to which to save the ip address in network order
 * @return 1 if cp could be converted to addr, 0 on failure
 */
int
ipaddr_aton(const char *cp, ip_addr_t *addr)
{
    u32_t val;
    u8_t base;
    char c;
    u32_t parts[4];
    u32_t *pp = parts;

    c = *cp;
    for (;;) {
        /*
         * Collect number up to ``.''.
         * Values are specified as for C:
         * 0x=hex, 0=octal, 1-9=decimal.
         */
        if (!isdigit(c))
            return (0);
        val = 0;
        base = 10;
        if (c == '0') {
            c = *++cp;
            if (c == 'x' || c == 'X') {
                base = 16;
                c = *++cp;
            } else
                base = 8;
        }
        for (;;) {
            if (isdigit(c)) {
                val = (val * base) + (int)(c - '0');
                c = *++cp;
            } else if (base == 16 && isxdigit(c)) {
                val = (val << 4) | (int)(c + 10 - (islower(c) ? 'a' : 'A'));
                c = *++cp;
            } else
                break;
        }
        if (c == '.') {
            /*
             * Internet format:
             *  a.b.c.d
             *  a.b.c   (with c treated as 16 bits)
             *  a.b (with b treated as 24 bits)
             */
            if (pp >= parts + 3) {
                return (0);
            }
            *pp++ = val;
            c = *++cp;
        } else
            break;
    }
    /*
     * Check for trailing characters.
     */
    if (c != '\0' && !isspace(c)) {
        return (0);
    }
    /*
     * Concoct the address according to
     * the number of parts specified.
     */
    switch (pp - parts + 1) {

        case 0:
            return (0);       /* initial nondigit */

        case 1:             /* a -- 32 bits */
            break;

        case 2:             /* a.b -- 8.24 bits */
            if (val > 0xffffffUL) {
                return (0);
            }
            val |= parts[0] << 24;
            break;

        case 3:             /* a.b.c -- 8.8.16 bits */
            if (val > 0xffff) {
                return (0);
            }
            val |= (parts[0] << 24) | (parts[1] << 16);
            break;

        case 4:             /* a.b.c.d -- 8.8.8.8 bits */
            if (val > 0xff) {
                return (0);
            }
            val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
            break;
        default:
            LWIP_ASSERT("unhandled", 0);
            break;
    }
    if (addr) {
        ip4_addr_set_u32(addr, htonl(val));
    }
    return (1);
}
Пример #29
0
CStringUTF8 CHTMLHelper::HTMLDecode(const string& str, EEncoding encoding,
                                    THTMLDecodeFlags* result_flags)
{
    CStringUTF8 ustr;
    THTMLDecodeFlags result = 0;
    if (encoding == eEncoding_Unknown) {
        encoding = CStringUTF8::GuessEncoding(str);
        if (encoding == eEncoding_Unknown) {
            NCBI_THROW2(CStringException, eBadArgs,
                "Unable to guess the source string encoding", 0);
        }
    }
    // wild guess...
    ustr.reserve(str.size());

    string::const_iterator i, e = str.end();
    char ch;
    TUnicodeSymbol uch;

    for (i = str.begin(); i != e;) {
        ch = *(i++);
        //check for HTML entities and character references
        if (i != e && ch == '&') {
            string::const_iterator itmp, end_of_entity, start_of_entity;
            itmp = end_of_entity = start_of_entity = i;
            bool ent, dec, hex, parsed=false;
            ent = isalpha((unsigned char)(*itmp)) != 0;
            dec = !ent && *itmp == '#' && ++itmp != e &&
                  isdigit((unsigned char)(*itmp)) != 0;
            hex = !dec && itmp != e &&
                  (*itmp == 'x' || *itmp == 'X') && ++itmp != e &&
                  isxdigit((unsigned char)(*itmp)) != 0;
            start_of_entity = itmp;
            if (itmp != e && (ent || dec || hex)) {
                // do not look too far
                for (int len=0; len<16 && itmp != e; ++len, ++itmp) {
                    if (*itmp == '&' || *itmp == '#') {
                        break;
                    }
                    if (*itmp == ';') {
                        end_of_entity = itmp;
                        break;
                    }
                    ent = ent && isalnum( (unsigned char)(*itmp)) != 0;
                    dec = dec && isdigit( (unsigned char)(*itmp)) != 0;
                    hex = hex && isxdigit((unsigned char)(*itmp)) != 0;
                }
                if (end_of_entity != i && (ent || dec || hex)) {
                    uch = 0;
                    if (ent) {
                        string entity(start_of_entity,end_of_entity);
                        const struct tag_HtmlEntities* p = s_HtmlEntities;
                        for ( ; p->u != 0; ++p) {
                            if (entity.compare(p->s) == 0) {
                                uch = p->u;
                                parsed = true;
                                result |= fCharRef_Entity;
                                break;
                            }
                        }
                    } else {
                        parsed = true;
                        result |= fCharRef_Numeric;
                        for (itmp = start_of_entity;
                             itmp != end_of_entity; ++itmp) {
                            TUnicodeSymbol ud = *itmp;
                            if (dec) {
                                uch = 10 * uch + (ud - '0');
                            } else if (hex) {
                                if (ud >='0' && ud <= '9') {
                                    ud -= '0';
                                } else if (ud >='a' && ud <= 'f') {
                                    ud -= 'a';
                                    ud += 10;
                                } else if (ud >='A' && ud <= 'F') {
                                    ud -= 'A';
                                    ud += 10;
                                }
                                uch = 16 * uch + ud;
                            }
                        }
                    }
                    if (parsed) {
                        ustr.Append(uch);
                        i = ++end_of_entity;
                        continue;
                    }
                }
            }
        }
// no entity - append as is
        if (encoding == eEncoding_UTF8 || encoding == eEncoding_Ascii) {
            ustr.append( 1, ch );
        } else {
            result |= fEncoding;
            ustr.Append(CStringUTF8::CharToSymbol( ch, encoding ));
        }
    }
    if (result_flags) {
        *result_flags = result;
    }
    return ustr;
}
Пример #30
0
unsigned function (char const * oldname, char const * newname)

{
	unsigned count = 0;
	signed c = getc (stdin);
	while (c != EOF)
	{
		if (isspace (c))
		{
			do 
			{
				putc (c, stdout);
				c = getc (stdin);
			}
			while (isspace (c));
			continue;
		}
		if (isalpha (c) || (c == '_'))
		{
			char string [255];
			char * sp = string;
			do 
			{
				* sp++ = (char) (c);
				c = getc (stdin);
			}
			while (isalnum (c) || (c == '_'));
			* sp = (char) (0);
			if (! strcmp (string, oldname))
			{
				count++;
				fputs (newname, stdout);
				continue;
			}
			fputs (string, stdout);
			continue;
		}
		if (isdigit (c))
		{
			do 
			{
				putc (c, stdout);
				c = getc (stdin);
			}
			while (isdigit (c) || (c == '.'));
			if ((c == 'x') || (c == 'X'))
			{
				do 
				{
					putc (c, stdout);
					c = getc (stdin);
				}
				while (isxdigit (c));
			}
			if ((c == 'e') || (c == 'E'))
			{
				putc (c, stdout);
				c = getc (stdin);
				if ((c == '+') || (c == '-'))
				{
					putc (c, stdout);
					c = getc (stdin);
				}
				while (isdigit (c))
				{
					putc (c, stdout);
					c = getc (stdin);
				}
			}
			continue;
		}
		if (isquote (c))
		{
			signed o;
			putc (c, stdout);
			o = getc (stdin);
			while (nomatch (o, c))
			{
				if ((char) (o) == '\\')
				{
					putc (o, stdout);
					o = getc (stdin);
				}
				putc (o, stdout);
				o = getc (stdin);
			}
			putc (c, stdout);
			c = getc (stdin);
			continue;
		}
		if (c == '/')
		{
			putc (c, stdout);
			c = getc (stdin);
			if (c == '/')
			{
				while (nobreak (c))
				{
					putc (c, stdout);
					c = getc (stdin);
				}
				putc ('\n', stdout);
				c = getc (stdin);
				continue;
			}
			if (c == '*')
			{
				while (nomatch (c, '/'))
				{
					while (nomatch (c, '*'))
					{
						putc (c, stdout);
						c = getc (stdin);
					}
					putc (c, stdout);
					c = getc (stdin);
				}
				putc ('/', stdout);
				c = getc (stdin);
				continue;
			}
			continue;
		}
		putc (c, stdout);
		c = getc (stdin);
	}
	return (count);
}