/* * Converts ascii lat/lon to unsigned encoded 32-bit number */ static DWORD latlon2ul (char **latlonstrptr, int *which) { DWORD retval; char *cp = *latlonstrptr; int deg = 0; int min = 0; int secs = 0; int secsfrac = 0; while (isdigit(*cp)) deg = deg * 10 + (*cp++ - '0'); while (isspace(*cp)) cp++; if (!(isdigit(*cp))) goto fndhemi; while (isdigit(*cp)) min = min * 10 + (*cp++ - '0'); while (isspace(*cp)) cp++; if (!(isdigit(*cp))) goto fndhemi; while (isdigit(*cp)) secs = secs * 10 + (*cp++ - '0'); if (*cp == '.') /* decimal seconds */ { cp++; if (isdigit(*cp)) { secsfrac = (*cp++ - '0') * 100; if (isdigit(*cp)) { secsfrac += (*cp++ - '0') * 10; if (isdigit(*cp)) secsfrac += (*cp++ - '0'); } } } while (!isspace(*cp)) /* if any trailing garbage */ cp++; while (isspace(*cp)) cp++; fndhemi: switch (toupper(*cp)) { case 'N': case 'E': retval = (1UL << 31UL) + (((((deg * 60UL) + min) * 60UL) + secs) * 1000UL) + secsfrac; break; case 'S': case 'W': retval = (1UL << 31UL) - (((((deg * 60UL) + min) * 60UL) + secs) * 1000UL) - secsfrac; break; default: retval = 0; /* invalid value -- indicates error */ break; } switch (toupper(*cp)) { case 'N': case 'S': *which = 1; /* latitude */ break; case 'E': case 'W': *which = 2; /* longitude */ break; default: *which = 0; /* error */ break; } cp++; /* skip the hemisphere */ while (!isspace(*cp)) /* if any trailing garbage */ cp++; while (isspace(*cp)) /* move to next field */ cp++; *latlonstrptr = cp; return (retval); }
static int skipWhite (int c) { while (isspace (c)) c = vGetc (); return c; }
t_token nextToken(void){ tokenString = ""; hasTokenSecundario = false; // loop do estado inicial para pular os separadores while(isspace(nextChar)){ nextChar = readChar(); } if(nextChar == EOF){ token = ENDFILE; return token; } if( isalpha(nextChar) ){ do { tokenString = tokenString + nextChar; nextChar = readChar(); } while( isalnum(nextChar) || nextChar == '_' ); token = searchKeyWord(tokenString); //std::cout << "Read:" << text << ", Token: " << token; if(token == IDT){ tokenSecundario = searchName(tokenString); hasTokenSecundario = true; //std::cout << ", Token Secundario IDT " << tokenSecundario << std::endl; } else{ //std::cout << std::endl; } } else if( isdigit(nextChar) ){ char numeral[MAX_NUM_LEN+1]; int i = 0; //std::cout << "Read: "; do{ tokenString = tokenString + nextChar; numeral[i++] = nextChar; //std::cout << nextChar; nextChar = readChar(); }while( isdigit(nextChar) ); numeral[i] = '\0'; token = NUMERAL; //std::cout << ", Token: " << token; tokenSecundario = addIntConst(atoi(numeral)); hasTokenSecundario = true; //std::cout << ", Token Secundario Const: " << tokenSecundario << std::endl; } else if( nextChar == '"' ){ tokenString = ""; nextChar = readChar(); while(nextChar != '"'){ tokenString += nextChar; nextChar = readChar(); } token = STRINGVAL; char* cstr = new char[tokenString.size()+1]; memcpy(cstr, tokenString.c_str(), tokenString.size()+1); tokenSecundario = addStringConst(cstr); hasTokenSecundario = true; nextChar = readChar(); //std::cout << "Read: " << tokenString << ", Token: " << token << ", Token Secundario Const: " << tokenSecundario << std::endl; }else if( nextChar == '\''){ nextChar = readChar(); tokenString = nextChar; token = CHARACTER; tokenSecundario = addCharConst(nextChar); hasTokenSecundario = true; //std::cout << "Read: " << '\'' << nextChar << '\'' << ", Token: " << token << ", Token Secundario Const: " << tokenSecundario << std::endl; nextChar = readChar(); //pular o ' nextChar = readChar(); } else{ //SIMBOLOS //std::cout << "Read: " << nextChar; tokenString = nextChar; switch(nextChar){ case ':': nextChar = readChar(); token = COLON; break; case ';': nextChar = readChar(); token = SEMI_COLON; break; case ',': nextChar = readChar(); token = COMMA; break; case '[': nextChar = readChar(); token = LEFT_SQUARE; break; case ']': nextChar = readChar(); token = RIGHT_SQUARE; break; case '{': nextChar = readChar(); token = LEFT_BRACES; break; case '}': nextChar = readChar(); token = RIGHT_BRACES; break; case '(': nextChar = readChar(); token = LEFT_PARENTHESIS; break; case ')': nextChar = readChar(); token = RIGHT_PARENTHESIS; break; case '&': nextChar = readChar(); if(nextChar == '&'){ tokenString += nextChar; token = AND; nextChar = readChar(); } else{ token = UNKNOWN; } break; case '|': nextChar = readChar(); if(nextChar == '|'){ tokenString += nextChar; token = OR; nextChar = readChar(); } else{ token = UNKNOWN; } break; case '=': nextChar = readChar(); if( nextChar == '=' ) { tokenString += nextChar; token = EQUAL_EQUAL; nextChar = readChar(); } else { token = EQUALS; } break; case '<': nextChar = readChar(); if( nextChar == '=' ) { tokenString += nextChar; token = LESS_OR_EQUAL; nextChar = readChar(); } else { token = LESS_THAN; } break; case '>': nextChar = readChar(); if( nextChar == '=' ) { tokenString += nextChar; token = GREATER_OR_EQUAL; nextChar = readChar(); } else { token = GREATER_THAN; } break; case '!': nextChar = readChar(); if( nextChar == '=' ) { tokenString += nextChar; token = NOT_EQUAL; nextChar = readChar(); } else { token = NOT; } break; case '+': nextChar = readChar(); if( nextChar == '+' ) { tokenString += nextChar; token = PLUS_PLUS; nextChar = readChar(); } else { token = PLUS; } break; case '-': nextChar = readChar(); if( nextChar == '-' ) { tokenString += nextChar; token = MINUS_MINUS; nextChar = readChar(); } else { token = MINUS; } break; case '*': nextChar = readChar(); token = TIMES; break; case '/': nextChar = readChar(); token = DIVIDE; break; case '.': nextChar = readChar(); token = DOT; break; default: token = UNKNOWN; } //std::cout << ", Token: " << token << std::endl; } return token; }
char * skip_whitespace (const char *p) { while (isspace((unsigned char)*p)) p++; return (char *)p; }
int tokenize (Basrec_type *node, char *text, int casemode, int colmode) { int tex = 0, j, k, eol, len, found, quantity, curr_list = 0, search; char casetext [MAXLINE]; unsigned char byte; static unsigned int prev_line = 0, line_num = 0; static int cont = FALSE, comment = FALSE, quote = FALSE; static int tok = 0; Keyword_type *kw; if (node == BASREC_NULL) { prev_line = 0; tok = 0; quote = FALSE; comment = FALSE; return FALSE; } eol = strlen (text); if (colmode) if (isdigit (text [0])) { cont = FALSE; if (quote) fprintf (stderr, "\n%s: missing close quote on line %u\n", program, line_num); } else { cont = TRUE; if (tex < eol) tex ++; if (text [0] && ! isspace (text [0])) fprintf (stderr, "\n%s: invalid char in col 1 on line %u\n", program, line_num); } if (cont) { cont = FALSE; if (colmode && tok < MAXTOKENLINE - 1) node -> tokenline [tok ++] = ' '; } else { if (sscanf (text, "%d", &line_num) != 1) return FALSE; if (prev_line && line_num <= prev_line) { fprintf (stderr, "\n%s: line numbers not sorted.", program); fprintf (stderr, " Previous = %u, Current = %u.\n", prev_line, line_num); fprintf (stderr, "Do you need the \"%s\" or the \"%s\" option?\n", cmds [MULT].command, cmds [COL].command); exit (EXITBAD); } tok = 0; quote = FALSE; comment = FALSE; prev_line = line_num; node -> line_num.whole_addy = line_num; while (tex < eol && isspace (text [tex])) tex ++; while (tex < eol && isdigit (text [tex])) tex ++; } if (colmode) cont = TRUE; if (text [eol - 1] == '\\') { cont = TRUE; eol --; } while (tex < eol && isspace (text [tex])) tex ++; for (j = tex; j < eol; j++) casetext [j] = tolower (text [j]); casetext [j] = 0; while (tex < eol && tok < MAXTOKENLINE - 1) { if (comment) { if (! casemode && isupper (text [tex])) node -> tokenline [tok] = text [tex]; else if (islower (text [tex])) node -> tokenline [tok] = toupper (text [tex]); else if (isupper (text [tex])) node -> tokenline [tok] = tolower (text [tex]); else node -> tokenline [tok] = text [tex]; tex ++; } else /* not comment mode */ { curr_list = 0; if (quote) kw = special; /* display code replacement */ else kw = kw_list [curr_list]; /* basic keywords */ k = 0; found = FALSE; quantity = FALSE; search = TRUE; while (search) /* search thru lists of keyword lists */ { /* search thru current keyword list */ while (! found && kw [k].keyword [0]) if (eol - tex + 1 >= (len = strlen (kw [k].keyword)) && ! strncmp (&(casetext [tex]), kw [k].keyword, len)) found = TRUE; else k ++; if (quote || found || kw_list [curr_list + 1] == KW_NULL) search = FALSE; else { curr_list ++; kw = kw_list [curr_list]; } } if (quote && ! found) { k = 0; /* look for partial keywords that may be followed by quantity */ while (! quantity && kw [k].keyword [0]) if (eol - tex + 1 >= (len = strlen (kw [k].keyword) - 1) && ! strncmp (& (casetext [tex]), kw [k].keyword, len)) quantity = TRUE; else k ++; } if (found) { if (! strcmp (kw [k].keyword, COMT_WORD)) comment = TRUE; node -> tokenline [tok] = kw [k].token; tex += len; } else if (quantity) { if (! tok_quantity (kw [k].token, text, &tex, len, node -> tokenline, &tok)) exit_illeg_subs (line_num, tex); tex ++; } else /* keyword not found */ { if (text [tex] == '\"') quote = (quote ? FALSE : TRUE); if (quote) { if (! casemode && isupper (text [tex])) node -> tokenline [tok] = text [tex]; else if (islower (text [tex])) node -> tokenline [tok] = toupper (text [tex]); else if (isupper (text [tex])) node -> tokenline [tok] = tolower (text [tex]); else if (text [tex] == '{') { byte = get_deci_byte (text, tex + 1, MAXLINE - 1); if (! byte || ! tok_quantity (byte, text, &tex, MAXDECIM, node -> tokenline, &tok)) exit_illeg_subs (line_num, tex); } else node -> tokenline [tok] = text [tex]; } else /* not quote mode */ { if (islower (text [tex])) node -> tokenline [tok] = toupper (text [tex]); else node -> tokenline [tok] = text [tex]; } tex ++; } } /* end not comment mode */ tok++; } /* end while not eol */ if (tok < MAXTOKENLINE) node -> tokenline [tok] = 0; else { node -> tokenline [MAXTOKENLINE - 1] = 0; fprintf (stderr, "\n%s: line %u is too long.\n", program, line_num); } if (cont) return FALSE; else if (quote) { fprintf (stderr, "\n%s: missing close quote on line %u\n", program, node -> line_num.whole_addy); return FALSE; } else return TRUE; } /* end tokenize */
/********************************************************************** * %FUNCTION: parse_config_file * %ARGUMENTS: * es -- event selector * fname -- filename to parse * %RETURNS: * -1 on error, 0 if all is OK * %DESCRIPTION: * Parses configuration file. ***********************************************************************/ int l2tp_parse_config_file(EventSelector *es, char const *fname) { char buf[512]; char name[512]; char value[512]; int r = 0; size_t l; char *line; FILE *fp; /* Defaults */ Settings.listen_port = 1701; if (!fname || !*fname) return 0; fp = fopen(fname, "r"); if (!fp) { l2tp_set_errmsg("Could not open '%s' for reading: %s", fname, strerror(errno)); return -1; } /* Start in global context */ option_context_fn = NULL; while (fgets(buf, sizeof(buf), fp) != NULL) { l = strlen(buf); if (l && (buf[l] == '\n')) { buf[l--] = 0; } /* Skip leading whitespace */ line = buf; while(*line && isspace(*line)) line++; /* Ignore blank lines and comments */ if (!*line || *line == '#') { continue; } /* Split line into two words */ split_line_into_words(line, name, value); /* Check for context switch */ if (!strcasecmp(name, "global") || !strcasecmp(name, "section")) { r = parser_switch_context(es, name, value); if (r < 0) break; continue; } r = handle_option(es, name, value); if (r < 0) break; } fclose(fp); if (r >= 0) { if (option_context_fn) { r = option_context_fn(es, "*end*", "*end*"); option_context_fn = NULL; } } return r; }
bool isNumber(string s) { if (s.empty()) return false; int i = 0; while(isspace(s[i])) { i++; } if (s[i] == '+' || s[i] == '-') { i++; } bool eAppear = false; bool dotAppear = false; bool firstPart = false; bool secondPart = false; bool spaceAppear = false; while(s[i] != '\0') { if (s[i] == '.') { if (dotAppear || eAppear || spaceAppear) { return false; } else { dotAppear = true; } } else if (s[i] == 'e' || s[i] == 'E') { if (eAppear || !firstPart || spaceAppear) { return false; } else { eAppear = true; } } else if (isdigit(s[i])) { if (spaceAppear) { return false; } if (!eAppear) { firstPart = true; } else { secondPart = true; } } else if (s[i] == '+' || s[i] == '-') { if (spaceAppear) { return false; } if (!eAppear || !(s[i - 1] == 'e' || s[i - 1] == 'E')) { return false; } } else if (isspace(s[i])) { spaceAppear = true; } else { return false; } i++; } if (!firstPart) { return false; } else if (eAppear && !secondPart) { return false; } else { return true; } }
/* This function has to be reachable by res_data.c but not publically. */ int __res_vinit(res_state statp, int preinit) { register FILE *fp; register char *cp, **pp; register int n; char buf[BUFSIZ]; int nserv = 0; /* number of nameserver records read from file */ #ifdef _LIBC int nservall = 0; /* number of NS records read, nserv IPv4 only */ #endif int haveenv = 0; int havesearch = 0; #ifdef RESOLVSORT int nsort = 0; char *net; #endif #ifndef RFC1535 int dots; #endif if (!preinit) { statp->retrans = RES_TIMEOUT; statp->retry = RES_DFLRETRY; statp->options = RES_DEFAULT; statp->id = res_randomid(); } #ifdef USELOOPBACK statp->nsaddr.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1); #else statp->nsaddr.sin_addr.s_addr = INADDR_ANY; #endif statp->nsaddr.sin_family = AF_INET; statp->nsaddr.sin_port = htons(NAMESERVER_PORT); statp->nscount = 1; statp->ndots = 1; statp->pfcode = 0; statp->_vcsock = -1; statp->_flags = 0; statp->qhook = NULL; statp->rhook = NULL; statp->_u._ext.nsinit = 0; statp->_u._ext.nscount = 0; #ifdef _LIBC statp->_u._ext.nscount6 = 0; for (n = 0; n < MAXNS; n++) statp->_u._ext.nsaddrs[n] = NULL; #endif /* Allow user to override the local domain definition */ if ((cp = getenv("LOCALDOMAIN")) != NULL) { (void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1); statp->defdname[sizeof(statp->defdname) - 1] = '\0'; haveenv++; /* * Set search list to be blank-separated strings * from rest of env value. Permits users of LOCALDOMAIN * to still have a search list, and anyone to set the * one that they want to use as an individual (even more * important now that the rfc1535 stuff restricts searches) */ cp = statp->defdname; pp = statp->dnsrch; *pp++ = cp; for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) { if (*cp == '\n') /* silly backwards compat */ break; else if (*cp == ' ' || *cp == '\t') { *cp = 0; n = 1; } else if (n) { *pp++ = cp; n = 0; havesearch = 1; } } /* null terminate last domain if there are excess */ while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n') cp++; *cp = '\0'; *pp++ = 0; } #define MATCH(line, name) \ (!strncmp(line, name, sizeof(name) - 1) && \ (line[sizeof(name) - 1] == ' ' || \ line[sizeof(name) - 1] == '\t')) if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) { /* No threads use this stream. */ __fsetlocking (fp, FSETLOCKING_BYCALLER); /* read the config file */ while (fgets_unlocked(buf, sizeof(buf), fp) != NULL) { /* skip comments */ if (*buf == ';' || *buf == '#') continue; /* read default domain name */ if (MATCH(buf, "domain")) { if (haveenv) /* skip if have from environ */ continue; cp = buf + sizeof("domain") - 1; while (*cp == ' ' || *cp == '\t') cp++; if ((*cp == '\0') || (*cp == '\n')) continue; strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1); statp->defdname[sizeof(statp->defdname) - 1] = '\0'; if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL) *cp = '\0'; havesearch = 0; continue; } /* set search list */ if (MATCH(buf, "search")) { if (haveenv) /* skip if have from environ */ continue; cp = buf + sizeof("search") - 1; while (*cp == ' ' || *cp == '\t') cp++; if ((*cp == '\0') || (*cp == '\n')) continue; strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1); statp->defdname[sizeof(statp->defdname) - 1] = '\0'; if ((cp = strchr(statp->defdname, '\n')) != NULL) *cp = '\0'; /* * Set search list to be blank-separated strings * on rest of line. */ cp = statp->defdname; pp = statp->dnsrch; *pp++ = cp; for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) { if (*cp == ' ' || *cp == '\t') { *cp = 0; n = 1; } else if (n) { *pp++ = cp; n = 0; } } /* null terminate last domain if there are excess */ while (*cp != '\0' && *cp != ' ' && *cp != '\t') cp++; *cp = '\0'; *pp++ = 0; havesearch = 1; continue; } /* read nameservers to query */ #ifdef _LIBC if (MATCH(buf, "nameserver") && nservall < MAXNS) { #else if (MATCH(buf, "nameserver") && nserv < MAXNS) { #endif struct in_addr a; cp = buf + sizeof("nameserver") - 1; while (*cp == ' ' || *cp == '\t') cp++; if ((*cp != '\0') && (*cp != '\n') && __inet_aton(cp, &a)) { statp->nsaddr_list[nserv].sin_addr = a; statp->nsaddr_list[nserv].sin_family = AF_INET; statp->nsaddr_list[nserv].sin_port = htons(NAMESERVER_PORT); nserv++; #ifdef _LIBC nservall++; } else { struct in6_addr a6; char *el; if ((el = strchr(cp, '\n')) != NULL) *el = '\0'; if ((*cp != '\0') && (inet_pton(AF_INET6, cp, &a6) > 0)) { struct sockaddr_in6 *sa6; sa6 = malloc(sizeof(*sa6)); if (sa6 != NULL) { sa6->sin6_addr = a6; sa6->sin6_family = AF_INET6; sa6->sin6_port = htons(NAMESERVER_PORT); statp->_u._ext.nsaddrs[nservall] = sa6; statp->_u._ext.nstimes[nservall] = RES_MAXTIME; statp->_u._ext.nssocks[nservall] = -1; nservall++; } } #endif } continue; } #ifdef RESOLVSORT if (MATCH(buf, "sortlist")) { struct in_addr a; cp = buf + sizeof("sortlist") - 1; while (nsort < MAXRESOLVSORT) { while (*cp == ' ' || *cp == '\t') cp++; if (*cp == '\0' || *cp == '\n' || *cp == ';') break; net = cp; while (*cp && !ISSORTMASK(*cp) && *cp != ';' && isascii(*cp) && !isspace(*cp)) cp++; n = *cp; *cp = 0; if (__inet_aton(net, &a)) { statp->sort_list[nsort].addr = a; if (ISSORTMASK(n)) { *cp++ = n; net = cp; while (*cp && *cp != ';' && isascii(*cp) && !isspace(*cp)) cp++; n = *cp; *cp = 0; if (__inet_aton(net, &a)) { statp->sort_list[nsort].mask = a.s_addr; } else { statp->sort_list[nsort].mask = net_mask(statp->sort_list[nsort].addr); } } else { statp->sort_list[nsort].mask = net_mask(statp->sort_list[nsort].addr); } nsort++; } *cp = n; } continue; } #endif if (MATCH(buf, "options")) { res_setoptions(statp, buf + sizeof("options") - 1, "conf"); continue; } } if (nserv > 1) statp->nscount = nserv; #ifdef _LIBC if (nservall - nserv > 0) statp->_u._ext.nscount6 = nservall - nserv; #endif #ifdef RESOLVSORT statp->nsort = nsort; #endif (void) fclose(fp); } if (statp->defdname[0] == 0 && __gethostname(buf, sizeof(statp->defdname) - 1) == 0 && (cp = strchr(buf, '.')) != NULL) strcpy(statp->defdname, cp + 1); /* find components of local domain that might be searched */ if (havesearch == 0) { pp = statp->dnsrch; *pp++ = statp->defdname; *pp = NULL; #ifndef RFC1535 dots = 0; for (cp = statp->defdname; *cp; cp++) dots += (*cp == '.'); cp = statp->defdname; while (pp < statp->dnsrch + MAXDFLSRCH) { if (dots < LOCALDOMAINPARTS) break; cp = __rawmemchr(cp, '.') + 1; /* we know there is one */ *pp++ = cp; dots--; } *pp = NULL; #ifdef DEBUG if (statp->options & RES_DEBUG) { printf(";; res_init()... default dnsrch list:\n"); for (pp = statp->dnsrch; *pp; pp++) printf(";;\t%s\n", *pp); printf(";;\t..END..\n"); } #endif #endif /* !RFC1535 */ } if ((cp = getenv("RES_OPTIONS")) != NULL) res_setoptions(statp, cp, "env"); statp->options |= RES_INIT; return (0); } static void internal_function res_setoptions(res_state statp, const char *options, const char *source) { const char *cp = options; int i; #ifdef DEBUG if (statp->options & RES_DEBUG) printf(";; res_setoptions(\"%s\", \"%s\")...\n", options, source); #endif while (*cp) { /* skip leading and inner runs of spaces */ while (*cp == ' ' || *cp == '\t') cp++; /* search for and process individual options */ if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) { i = atoi(cp + sizeof("ndots:") - 1); if (i <= RES_MAXNDOTS) statp->ndots = i; else statp->ndots = RES_MAXNDOTS; #ifdef DEBUG if (statp->options & RES_DEBUG) printf(";;\tndots=%d\n", statp->ndots); #endif } else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) { i = atoi(cp + sizeof("timeout:") - 1); if (i <= RES_MAXRETRANS) statp->retrans = i; else statp->retrans = RES_MAXRETRANS; } else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){ i = atoi(cp + sizeof("attempts:") - 1); if (i <= RES_MAXRETRY) statp->retry = i; else statp->retry = RES_MAXRETRY; } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) { #ifdef DEBUG if (!(statp->options & RES_DEBUG)) { printf(";; res_setoptions(\"%s\", \"%s\")..\n", options, source); statp->options |= RES_DEBUG; } printf(";;\tdebug\n"); #endif } else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) { statp->options |= RES_USE_INET6; } else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) { statp->options |= RES_ROTATE; } else if (!strncmp(cp, "no-check-names", sizeof("no-check-names") - 1)) { statp->options |= RES_NOCHECKNAME; } else { /* XXX - print a warning here? */ } /* skip to next run of spaces */ while (*cp && *cp != ' ' && *cp != '\t') cp++; } } #ifdef RESOLVSORT /* XXX - should really support CIDR which means explicit masks always. */ static u_int32_t net_mask(in) /* XXX - should really use system's version of this */ struct in_addr in; { register u_int32_t i = ntohl(in.s_addr); if (IN_CLASSA(i)) return (htonl(IN_CLASSA_NET)); else if (IN_CLASSB(i)) return (htonl(IN_CLASSB_NET)); return (htonl(IN_CLASSC_NET)); } #endif u_int res_randomid(void) { struct timeval now; __gettimeofday(&now, NULL); return (0xffff & (now.tv_sec ^ now.tv_usec ^ __getpid())); } /* * This routine is for closing the socket if a virtual circuit is used and * the program wants to close it. This provides support for endhostent() * which expects to close the socket. * * This routine is not expected to be user visible. */ void res_nclose(res_state statp) { int ns; if (statp->_vcsock >= 0) { (void) __close(statp->_vcsock); statp->_vcsock = -1; statp->_flags &= ~(RES_F_VC | RES_F_CONN); } #ifdef _LIBC for (ns = 0; ns < statp->_u._ext.nscount + statp->_u._ext.nscount6; ns++) #else for (ns = 0; ns < statp->_u._ext.nscount; ns++) #endif { if (statp->_u._ext.nssocks[ns] != -1) { (void) __close(statp->_u._ext.nssocks[ns]); statp->_u._ext.nssocks[ns] = -1; } } statp->_u._ext.nsinit = 0; }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d V I C A R I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadVICARImage() reads a VICAR image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadVICARImage method is: % % Image *ReadVICARImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadVICARImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: The image info. % % o exception: return any errors or warnings in this structure. % % */ static Image *ReadVICARImage(const ImageInfo *image_info, ExceptionInfo *exception) { char keyword[MaxTextExtent], value[MaxTextExtent]; Image *image; int c; long y; MagickBooleanType status, value_expected; QuantumInfo quantum_info; register PixelPacket *q; ssize_t count; ssize_t length; unsigned char *scanline; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AllocateImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ c=ReadBlobByte(image); count=1; if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } length=0; image->columns=0; image->rows=0; while (isgraph(c) && ((image->columns == 0) || (image->rows == 0))) { if (isalnum(c) == MagickFalse) { c=ReadBlobByte(image); count++; } else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent/2)) *p++=c; c=ReadBlobByte(image); count++; } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); count++; } if (value_expected == MagickFalse) continue; p=value; while (isalnum(c)) { if ((size_t) (p-value) < (MaxTextExtent/2)) *p++=c; c=ReadBlobByte(image); count++; } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"Label_RECORDS") == 0) length=(ssize_t) atol(value); if (LocaleCompare(keyword,"LBLSIZE") == 0) length=(ssize_t) atol(value); if (LocaleCompare(keyword,"RECORD_BYTES") == 0) image->columns=1UL*atol(value); if (LocaleCompare(keyword,"NS") == 0) image->columns=1UL*atol(value); if (LocaleCompare(keyword,"LINES") == 0) image->rows=1UL*atol(value); if (LocaleCompare(keyword,"NL") == 0) image->rows=1UL*atol(value); } while (isspace((int) ((unsigned char) c)) != 0) { c=ReadBlobByte(image); count++; } } while (count < (ssize_t) length) { c=ReadBlobByte(image); count++; } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); image->depth=8; if (AllocateImageColormap(image,256) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { CloseBlob(image); return(GetFirstImageInList(image)); } /* Read VICAR pixels. */ if (SetImageExtent(image,0,0) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } GetQuantumInfo(image_info,&quantum_info); scanline=(unsigned char *) AcquireQuantumMemory(image->columns, sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (long) image->rows; y++) { q=SetImagePixels(image,0,y,image->columns,1); if (q == (PixelPacket *) NULL) break; count=ReadBlob(image,image->columns,scanline); (void) ExportQuantumPixels(image,&quantum_info,GrayQuantum,scanline); if (SyncImagePixels(image) == MagickFalse) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (QuantumTick(y,image->rows) != MagickFalse)) { status=image->progress_monitor(LoadImageTag,y,image->rows, image->client_data); if (status == MagickFalse) break; } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); CloseBlob(image); return(GetFirstImageInList(image)); }
/** pgn_load(): pgn_load loads a specific game from the opened pgn database. The board position is set to the last position in the game. Created 091407; last modified 111208 **/ void pgn_load(int game_number, POS_FUNC pos_func, void *pos_arg) { char buffer[BUFSIZ]; char move_buf[8]; char flag_buf[8]; int consumed; int braces; int x; POS_DATA pos_data; PGN_GAME *game; PGN_STATE state; NOTATION old_notation; if (pgn_database.game_count == 0) { print("No database loaded.\n"); return; } if (game_number < 1 || game_number > pgn_database.game_count) { print("Invalid game number: %i. Valid numbers are 1-%i\n", game_number, pgn_database.game_count); return; } /* Copy the PGN tags. */ game = &pgn_database.game[game_number - 1]; strcpy(pgn_game.tag.event, game->tag.event); strcpy(pgn_game.tag.site, game->tag.site); strcpy(pgn_game.tag.date, game->tag.date); strcpy(pgn_game.tag.round, game->tag.round); strcpy(pgn_game.tag.white, game->tag.white); strcpy(pgn_game.tag.black, game->tag.black); strcpy(pgn_game.tag.result, game->tag.result); strcpy(pgn_game.tag.fen, game->tag.fen); /* Initialize. */ if (strcmp(pgn_game.tag.fen, "") != 0) initialize_board(pgn_game.tag.fen); else initialize_board(NULL); /* Set the engine to force mode. */ zct->zct_side = EMPTY; old_notation = zct->notation; /* PGN uses SAN, of course... */ zct->notation = SAN; braces = 0; state = NEUTRAL; pos_data.type = POS_PGN; pos_data.pgn = game; /* Find the game in the PGN file and start reading. */ fseek(pgn_file, game->offset, SEEK_SET); while (fgets(buffer, sizeof(buffer), pgn_file)) { switch (state) { case NEUTRAL: /* Stupid macros need an int cast... sigh */ if (isspace((int)buffer[0])) continue; state = HEADERS; case HEADERS: if (buffer[0] == '[') continue; state = MOVES; case MOVES: /* Read the next line of input. Strip out all of the unneeded characters. */ set_cmd_input(buffer); cmd_parse(" \t.+#\r\n"); for (x = 0; x < cmd_input.arg_count; x++) { if (strchr(cmd_input.arg[x], '{')) braces++; if (strchr(cmd_input.arg[x], '}')) braces--; else if (braces == 0) { /* Pull out any flags in the move string and separate them. */ consumed = sscanf(cmd_input.arg[x], "%8[^?!=]%8[?!=]", move_buf, flag_buf); if (consumed == 2) strcpy(pos_data.flags, flag_buf); else strcpy(pos_data.flags, ""); /* Check if we have a valid move. If so, make it and call pos_func. */ if (input_move(move_buf, INPUT_CHECK_MOVE)) { input_move(move_buf, INPUT_USER_MOVE); /* Now execute the pos_func, which does any processing for this move, for example the book making routine which collects statistics. */ if (pos_func != NULL) if (pos_func(pos_arg, &pos_data)) goto end; } /* Check for end-of-game. */ else if (!strcmp(cmd_input.arg[x], "1-0") || !strcmp(cmd_input.arg[x], "0-1") || !strcmp(cmd_input.arg[x], "1/2-1/2") || !strcmp(cmd_input.arg[x], "*")) goto end; } } } } /* Look at the spaghetti code! How unreadable! ;) */ end: zct->notation = old_notation; }
/** pgn_open(): pgn_open opens a .pgn file and reads all games into the internal database. The number of games found is returned. Created 091407; last modified 091607 **/ int pgn_open(char *file_name) { char buffer[BUFSIZ]; char *c; char *b; int games; long last_offset; PGN_GAME *game; PGN_STATE state; /* Try opening the file. */ if (pgn_file != NULL) fclose(pgn_file); pgn_file = fopen(file_name, "rt"); if (pgn_file == NULL) { print("%s: file not found.\n", file_name); return -1; } /* First, quickly find the number of games. */ state = NEUTRAL; games = 0; while (fgets(buffer, BUFSIZ, pgn_file) != NULL) { switch (state) { case NEUTRAL: /* Stupid macros need an int cast... sigh */ if (isspace((int)buffer[0])) continue; state = HEADERS; case HEADERS: if (buffer[0] == '[') continue; state = MOVES; case MOVES: if (strstr(buffer, "1-0") || strstr(buffer, "0-1") || strstr(buffer, "1/2-1/2") || strstr(buffer, "*")) { games++; state = NEUTRAL; } } } /* Initialize the database. */ if (pgn_database.game != NULL) free(pgn_database.game); pgn_database.game_count = games; pgn_database.game = calloc(games, sizeof(PGN_GAME)); print("%i games loaded.\n", games); /* Read in all of the games. */ state = NEUTRAL; rewind(pgn_file); last_offset = 0; game = &pgn_database.game[0]; while (fgets(buffer, BUFSIZ, pgn_file)) { switch (state) { case NEUTRAL: /* Stupid macros need an int cast... sigh */ if (isspace((int)buffer[0])) continue; game->offset = last_offset; state = HEADERS; case HEADERS: if (buffer[0] == '[') { c = strtok(buffer, "\""); if (c == NULL) continue; c = strtok(buffer + strlen(c) + 1, "\""); if (c == NULL) continue; b = strtok(buffer + 1, " =\""); if (!strcmp(b, "Event")) strcpy(game->tag.event, c); if (!strcmp(b, "Site")) strcpy(game->tag.site, c); if (!strcmp(b, "Date")) strcpy(game->tag.date, c); if (!strcmp(b, "Round")) strcpy(game->tag.round, c); if (!strcmp(b, "White")) strcpy(game->tag.white, c); if (!strcmp(b, "Black")) strcpy(game->tag.black, c); if (!strcmp(b, "Result")) strcpy(game->tag.result, c); if (!strcmp(b, "FEN")) { strcpy(game->tag.fen, c); initialize_board(c); } continue; } state = MOVES; case MOVES: if (strstr(buffer, "1-0") || strstr(buffer, "0-1") || strstr(buffer, "1/2-1/2") || strstr(buffer, "*")) { game++; state = NEUTRAL; } } last_offset = ftell(pgn_file); } return games; }
struct cnfnode *parse_route(struct cnfmodule *cm, FILE *fptr) { struct cnfnode *cn_root, *cn_top, *cn; struct confline *cl, *cl_root; cl_root = read_conflines(fptr); cn_root = create_cnfnode("(root)"); for(cl = cl_root; cl; cl = cl->next){ const char *p = cl->line; char buf[256], *q; char target[256], netmask[256]; int i; while(*p && isspace(*p)) p++; if(*p){ if((strncmp("route", p, 5) == 0) || (strncmp("/sbin/route", p, 11) == 0)) { cn_top = create_cnfnode("route"); append_node(cn_root, cn_top); if (*p == '/') { p += 11; } else { p += 5; } while(*p && isspace(*p)) p++; if(!*p) continue; p = parse_route_options(cn_top, p); if(!*p) continue; if(strncmp(p, "add", 3) == 0){ cn = create_cnfnode("add"); append_node(cn_top, cn); p += 3; }else if(strncmp(p, "del", 3) == 0){ cn = create_cnfnode("del"); append_node(cn_top, cn); p += 3; } while(*p && isspace(*p)) p++; if(!*p) continue; if(strncmp(p, "-net", 4) == 0){ cn = create_cnfnode("-net"); append_node(cn_top, cn); p += 4; }else if(strncmp(p, "-host", 5) == 0){ cn = create_cnfnode("-host"); append_node(cn_top, cn); p += 5; } while(*p && isspace(*p)) p++; if(!*p) continue; /* get target */ q = target; while(*p && !isspace(*p) && (q < target+255)) *q++ = *p++; *q = 0; while(*p && isspace(*p)) p++; if(!*p) continue; cn = create_cnfnode("target"); append_node(cn_top, cn); cnfnode_setval(cn, target); netmask[0] = 0; if(strncmp(p, "netmask", 7) == 0){ p += 7; while(*p && isspace(*p)) p++; if(!*p) continue; q = netmask; while(*p && !isspace(*p) && (q < netmask+255)) *q++ = *p++; *q = 0; while(*p && isspace(*p)) p++; if(!*p) continue; } cn = create_cnfnode("netmask"); append_node(cn_top, cn); cnfnode_setval(cn, netmask); //if(netmask[0]) // snprintf(buf, 256, "%s/%s", target, netmask); //else // snprintf(buf, 256, "%s", target); // //cnfnode_setname(cn_top, buf); for(i = 0; i < sizeof(route_options)/sizeof(struct route_options); i++){ if(strncmp(p, route_options[i].name, strlen(route_options[i].name)) == 0){ int j; cn = create_cnfnode(route_options[i].name); append_node(cn_top, cn); p += strlen(route_options[i].name); while(*p && isspace(*p)) p++; if(!*p) break; for(j = 0; j < route_options[i].nparams; j++){ q = buf; while(*p && !isspace(*p) && (q < buf+255)) *q++ = *p++; *q = 0; cnfnode_setval(cn, buf); while(*p && isspace(*p)) p++; if(!*p) break; } if(!*p) break; } } if(!*p) continue; while(*p && isspace(*p)) p++; if(!*p) continue; q = buf; while(*p && !isspace(*p) && (q < buf+255)) *q++ = *p++; *q = 0; cn = create_cnfnode("dev"); append_node(cn_top, cn); cnfnode_setval(cn, buf); }else if(*p == '#'){ cn = create_cnfnode(".comment"); cnfnode_setval(cn, dup_next_line_b(&p, buf, 255)); append_node(cn_root, cn); } }else{ cn = create_cnfnode(".empty"); cnfnode_setval(cn, ""); append_node(cn_root, cn); } } destroy_confline_list(cl_root); return cn_root; }
bool isWhitespace() const { return isspace((int)_ch) > 0; }
/* * Converts a zone file representation in a string to an RDATA * on-the-wire representation. */ int loc_aton (const char *ascii, u_char *binary) { char *cp, *maxcp; BYTE *bcp; DWORD latit = 0, longit = 0, alt = 0; DWORD lltemp1 = 0, lltemp2 = 0; int altmeters = 0; int altfrac = 0; int altsign = 1; BYTE hp = 0x16; /* default = 1e6 cm = 10000.00m = 10km */ BYTE vp = 0x13; /* default = 1e3 cm = 10.00m */ BYTE siz = 0x12; /* default = 1e2 cm = 1.00m */ int which1 = 0; int which2 = 0; cp = (char*)ascii; maxcp = cp + strlen (ascii); lltemp1 = latlon2ul (&cp, &which1); lltemp2 = latlon2ul (&cp, &which2); switch (which1 + which2) { case 3: /* 1 + 2, the only valid combination */ if (which1 == 1 && which2 == 2) /* normal case */ { latit = lltemp1; longit = lltemp2; } else if (which1 == 2 && which2 == 1) /* reversed */ { longit = lltemp1; latit = lltemp2; } else /* some kind of brokenness */ return (0); break; default: /* we didn't get one of each */ return (0); } /* altitude */ if (*cp == '-') { altsign = -1; cp++; } if (*cp == '+') ++cp; while (isdigit(*cp)) altmeters = altmeters * 10 + (*cp++ - '0'); if (*cp == '.') /* decimal meters */ { cp++; if (isdigit(*cp)) { altfrac = (*cp++ - '0') * 10; if (isdigit(*cp)) altfrac += (*cp++ - '0'); } } alt = (10000000 + (altsign * (altmeters * 100 + altfrac))); while (!isspace(*cp) && (cp < maxcp)) cp++; /* if trailing garbage or m */ while (isspace(*cp) && (cp < maxcp)) cp++; if (cp >= maxcp) goto defaults; siz = precsize_aton (&cp); while (!isspace(*cp) && (cp < maxcp)) /* if trailing garbage or m */ cp++; while (isspace(*cp) && (cp < maxcp)) cp++; if (cp >= maxcp) goto defaults; hp = precsize_aton (&cp); while (!isspace(*cp) && (cp < maxcp)) /* if trailing garbage or m */ cp++; while (isspace(*cp) && (cp < maxcp)) cp++; if (cp >= maxcp) goto defaults; vp = precsize_aton(&cp); defaults: bcp = binary; *bcp++ = (BYTE) 0; /* version byte */ *bcp++ = siz; *bcp++ = hp; *bcp++ = vp; PUTLONG (latit,bcp); PUTLONG (longit,bcp); PUTLONG (alt,bcp); return (16); /* size of RR in octets */ }
void zpcgetvector(struct zpctoken *token, const char *str, char **retstr) { char *ptr = (char *)str; struct zpctoken **toktab; struct zpctoken *token1; long ndx = 0; long type = 0; char *cp; long sign = 0; toktab = malloc(DEFAULTDIM * sizeof(struct zpctoken *)); ptr++; /* skip the '<' */ while ((*ptr) && *ptr != '>') { while (isspace(*ptr)) { ptr++; } if (*ptr) { token1 = calloc(1, sizeof(struct zpctoken)); if (*ptr == '-') { sign = 1; ptr++; }; cp = index(ptr, '.'); if (cp) { type = ZPCDOUBLE; zpcgetdouble(token1, ptr, &ptr); } else { if (strstr(ptr, "uU")) { if (sign) { fprintf(stderr, "sign on unsigned number\n"); return; } } if (!type) { if (sign) { #if (SMARTTYPES) token1->sign = ZPCUSERSIGNED; #endif type = ZPCINT64; } else { type = ZPCUINT64; } } #if (SMARTTYPES) if (type == ZPCUINT64) { zpcgetuint64(token1, ptr, &ptr); } else { zpcgetint64(token1, ptr, &ptr); } if (ZPCUSERSIGNED || token1->data.ui64.u64 <= INT64_MAX) { token1->type = ZPCINT64; } else if (!sign) { token1->type = ZPCUINT64; } #else token1->type = type; #endif } toktab[ndx++] = token1; } if (*ptr == ',') { ptr++; } } token->type = ZPCVECTOR; token->data.vector.ndim = ndx; token->data.vector.toktab = toktab; *retstr = ptr; return; };
int str2args(const char *line, char ***argv_ret) { int line_i, arg_i; /* Index into line and current argument */ int argv_size = 10; /* Initial # of allocated args */ int arg_size; /* Allocated size of the curr arg */ char **argv; int argc; enum str2args_parse_state state = PARSE_STATE_IN_SPACE; const size_t line_len = strlen(line); argc = arg_i = 0; argv = (char **)malloc(argv_size * sizeof(char *)); if (!argv) { return -1; } zero_argvs(0, argv_size - 1, argv); arg_size = 0; line_i = 0; while ((size_t)line_i < line_len && state != PARSE_STATE_ERROR) { switch (state) { case PARSE_STATE_IN_SPACE: /* Found the start of the next argument */ if (!isspace(line[line_i])) { state = PARSE_STATE_START_ARG; } else { /* Gobble up space */ line_i++; } break; case PARSE_STATE_START_ARG: /* Increase size of argv, if needed */ if (argc >= argv_size) { void *tmp; argv_size = argv_size + argv_size / 2; tmp = realloc(argv, argv_size); if (tmp) { argv = (char **)tmp; zero_argvs(argc, argv_size - 1, argv); } else { state = PARSE_STATE_ERROR; } } /* Record start of word (unless we failed to realloc() */ if (state != PARSE_STATE_ERROR) { /* Reset per-arg variables */ arg_i = 0; arg_size = 32; /* Allocate this argument. This will be * realloc'd as necessary by append_char() */ argv[argc] = (char *)calloc(arg_size, 1); if (!argv[argc]) { state = PARSE_STATE_ERROR; break; } if (line[line_i] == '"') { /* Gobble up quote */ state = PARSE_STATE_IN_QUOTE; } else { /* Append this character to the argument begin * fetching up a word */ if (append_char(&argv[argc], &arg_size, &arg_i, line[line_i])) { state = PARSE_STATE_ERROR; } else { state = PARSE_STATE_IN_ARG; } } argc++; line_i++; } break; case PARSE_STATE_IN_ARG: if (isspace(line[line_i])) { state = PARSE_STATE_IN_SPACE; } else if (line[line_i] == '"') { state = PARSE_STATE_IN_QUOTE; } else { /* Append this character to the argument and remain in * PARSE_STATE_IN_ARG state */ if (append_char(&argv[argc - 1], &arg_size, &arg_i, line[line_i])) { state = PARSE_STATE_ERROR; } } line_i++; break; case PARSE_STATE_IN_QUOTE: if (line[line_i] == '"') { /* Return to looking for more of the word */ state = PARSE_STATE_IN_ARG; } else { /* Append this character to the argumen */ if (append_char(&argv[argc - 1], &arg_size, &arg_i, line[line_i])) { state = PARSE_STATE_ERROR; } } line_i++; break; case PARSE_STATE_ERROR: break; } } /* Print PARSE_STATE_ERROR message if hit the EOL in an invalid state */ switch (state) { case PARSE_STATE_IN_SPACE: case PARSE_STATE_IN_ARG: *argv_ret = argv; break; /* Unterminated quote or unexpexted state to end on */ case PARSE_STATE_IN_QUOTE: default: state = PARSE_STATE_ERROR; break; } if (state == PARSE_STATE_ERROR) { free_args(argc, argv); return -1; } else { return argc; } }
struct zpctoken * zpcgettoken(const char *str, char **retstr) { char *ptr = (char *)str; struct zpctoken *token = NULL; char *dec; long sign = 0; long radix; if (!*str) { return NULL; } while (isspace(*ptr)) { ptr++; } token = calloc(1, sizeof(struct zpctoken)); if (*ptr == '-' && !isspace(ptr[1])) { #if (SMARTTYPES) sign = ZPCUSERSIGNED; #else sign = 1; #endif ptr++; } if (isdigit(*ptr)) { #if 0 if (*ptr == '0') { if (ptr[1] == 'x' || ptr[1] == 'X') { token->radix = 16; } else if (ptr[1] == 'b' || ptr[1] == 'B') { token->radix = 2; } else { token->radix = 8; } } else { token->radix = 10; } #endif token->str = calloc(1, TOKENSTRLEN); token->slen = TOKENSTRLEN; dec = index(ptr, '.'); if(strstr(ptr, "uU")) { #if (SMARTTYPES) if (sign == ZPCUSERSIGNED) { fprintf(stderr, "sign on unsigned number\n"); return NULL; } sign = ZPCUSERUNSIGNED; #else if (sign) { fprintf(stderr, "sign on unsigned number\n"); return NULL; } #endif } if (dec) { // token->type = ZPCDOUBLE; zpcgetdouble(token, ptr, &ptr); if (sign) { token->data.f64 = -token->data.f64; token->sign = sign; } sprintf(token->str, "%e", token->data.f64); } else if (!sign) { token->sign = 0; zpcgetuint64(token, ptr, &ptr); #if (SMARTTYPES) if (sign == ZPCUSERSIGNED || token->data.ui64.u64 <= INT64_MAX) { token->type = ZPCINT64; token->sign = sign; } else { token->sign = ZPCUNSIGNED; token->type = ZPCUINT64; } #else // token->type = ZPCUINT64; #endif radix = token->radix; #if 0 if (!radix) { radix = zpcradix; } #endif switch (radix) { case 2: zpcconvbinuint64(token->data.ui64.u64, token->str, TOKENSTRLEN); break; case 8: sprintf(token->str, "0%llo", (long long)token->data.ui64.u64); break; case 10: sprintf(token->str, "%llu", (long long)token->data.ui64.u64); break; case 16: default: sprintf(token->str, "0x%llx", (long long)token->data.ui64.u64); break; } } else { // token->type = ZPCINT64; zpcgetint64(token, ptr, &ptr); token->data.ui64.i64 = -token->data.ui64.i64; #if (SMARTTYPES) token->sign = ZPCUSERSIGNED; #else token->sign = 1; #endif radix = token->radix; if (!radix) { radix = zpcradix; } switch (radix) { case 2: #if 0 zpcconvbinint64(token->data.ui64.i64, token->str, TOKENSTRLEN); #endif zpcconvbinint64(token->data.ui64.i64, token->str, TOKENSTRLEN); break; case 8: sprintf(token->str, "0%llo", (long long)token->data.ui64.i64); break; case 10: sprintf(token->str, "%lld", (long long)token->data.ui64.i64); break; case 16: default: sprintf(token->str, "0x%llx", (long long)token->data.ui64.i64); break; } } } else if (*ptr == '"') { zpcgetstr(token, ptr, &ptr); token->type = ZPCSTRING; } else if (*ptr == '<' && isxdigit(ptr[1])) { zpcgetvector(token, ptr, &ptr); // } else if (*ptr == '(' && isxdigit(ptr[1])) { // zpcgetcomplex(token, ptr, &ptr); } else if (zpcisoperchar(*ptr)) { zpcgetoper(token, ptr, &ptr); } else if (*ptr == '(') { token->type = ZPCLEFTPAREN; token->str = calloc(1, TOKENSTRLEN); token->slen = TOKENSTRLEN; *token->str = '('; token->str[1] = '\0'; token->len = 1; ptr++; } else if (*ptr == ')') { token->type = ZPCRIGHTPAREN; token->str = calloc(1, TOKENSTRLEN); token->slen = TOKENSTRLEN; *token->str = ')'; token->str[1] = '\0'; token->len = 1; ptr++; } else { free(token); token = NULL; } if (token) { *retstr = (char *)ptr; } return token; }
int main() { FILE *fp; int init, *FS, **FA, i, j, col, row, fs, r, c; char *str, temp[50]; fp = FA = FS = str = NULL; if(!(fp = fopen("input", "r"))) { printf("Error opening file!!!\n"); return -1; } fscanf(fp, "%d", &init); fgets(temp, sizeof(char)*50, fp); fgets(temp, sizeof(char)*50, fp); #ifdef DEBUG printf("FS String: %s", temp); #endif str = temp; i = 0; while(*str != '\0') { FS = (int *) realloc(FS, sizeof(int)*(i+1)); sscanf(str, "%d", &FS[i++]); #ifdef DEBUG printf("Here, i = %d, *str = %c\n", i, *str); #endif str++; while(isdigit(*str)) { #ifdef DEBUG printf("He1"); #endif str++; } while(isspace(*str)) str++; } fs = i; fgets(temp, sizeof(char)*50, fp); str = temp; i= 0; #ifdef DEBUG printf("0FA scanned: %s\n", temp); #endif FA = (int **) malloc(sizeof(int *)*1); FA[0] = NULL; while(*str != '\0') { FA[0] = (int *)realloc(FA[0], sizeof(int)*(i+1)); sscanf(str, "%d", &FA[0][i++]); #ifdef DEBUG printf("Here1, i = %d, *str = %c, FA[0][%d] = %d\n", i, *str, i-1, FA[0][i-1]); #endif str++; while(isdigit(*str)) str++; while(isspace(*str)) str++; } row = 1; col = i; while(!feof(fp)) { FA = (int **) realloc(FA, sizeof(int *)*(row+1)); FA[row] = NULL; fgets(temp, sizeof(char)*50, fp); #ifdef DEBUG printf("1FA scanned: %s\n", temp); #endif str = temp; i= 0; while(*str != '\0') { FA[row] = (int *)realloc(FA[row], sizeof(int)*(i+1)); sscanf(str, "%d", &FA[row][i++]); #ifdef DEBUG printf("Here1, i = %d, *str = %c, FA[%d][%d] = %d\n", i, *str, row, i-1, FA[row][i-1]); #endif str++; while(isdigit(*str)) str++; while(isspace(*str)) str++; } row++; } printf("Initial State: %d\n", init); printf("Final states: "); for(i = 0; i < fs; i++) printf("%d ", FS[i]); printf("\nInput Table:\n"); for(i = 0; i < row; i++) { for(j = 0; j < col; j++) { printf("%d\t", FA[i][j]); } printf("\n"); } while(1) { printf("Enter the string to be validated using the Finite Automata (\"!end\" to quit): "); scanf("%s", temp); if(strcmp(temp, "!end") == 0) break; str = temp; r = 0; while(*str != '\0') { c = tolower(*str) - 97; //Column of FA to be matched for the current input symbol if((c >= col) || (c < 0)) { printf("Error! Invalid input symbol!\n"); c = -1; break; } if(FA[r][c] != -1) { r = FA[r][c]; str++; } else { printf("Error! Input symbol unexpected!\n"); c = -1; break; } } if(c == -1) continue; for(i = 0; i < fs; i++) if(r == FS[i]) { printf("String validated.\n"); break; } if(i == fs) printf("String ending at a non-final state.\n"); }; return 0; }
/* * Get from "/proc/net/dev" all interfaces listed there; if they're * already in the list of interfaces we have, that won't add another * instance, but if they're not, that'll add them. * * We don't bother getting any addresses for them; it appears you can't * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and, * although some other types of addresses can be fetched with SIOCGIFADDR, * we don't bother with them for now. * * We also don't fail if we couldn't open "/proc/net/dev"; we just leave * the list of interfaces as is. */ static int scan_proc_net_dev(pcap_if_t **devlistp, int fd, char *errbuf) { FILE *proc_net_f; char linebuf[512]; int linenum; unsigned char *p; char name[512]; /* XXX - pick a size */ char *q, *saveq; struct ifreq ifrflags; int ret = 0; proc_net_f = fopen("/proc/net/dev", "r"); if (proc_net_f == NULL) return (0); for (linenum = 1; fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) { /* * Skip the first two lines - they're headers. */ if (linenum <= 2) continue; p = &linebuf[0]; /* * Skip leading white space. */ while (*p != '\0' && isspace(*p)) p++; if (*p == '\0' || *p == '\n') continue; /* blank line */ /* * Get the interface name. */ q = &name[0]; while (*p != '\0' && !isspace(*p)) { if (*p == ':') { /* * This could be the separator between a * name and an alias number, or it could be * the separator between a name with no * alias number and the next field. * * If there's a colon after digits, it * separates the name and the alias number, * otherwise it separates the name and the * next field. */ saveq = q; while (isdigit(*p)) *q++ = *p++; if (*p != ':') { /* * That was the next field, * not the alias number. */ q = saveq; } break; } else *q++ = *p++; } *q = '\0'; /* * Get the flags for this interface, and skip it if * it's not up. */ strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name)); if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) { if (errno == ENXIO) continue; (void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFFLAGS: %.*s: %s", (int)sizeof(ifrflags.ifr_name), ifrflags.ifr_name, pcap_strerror(errno)); ret = -1; break; } if (!(ifrflags.ifr_flags & IFF_UP)) continue; /* * Add an entry for this interface, with no addresses. */ if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL, errbuf) == -1) { /* * Failure. */ ret = -1; break; } } if (ret != -1) { /* * Well, we didn't fail for any other reason; did we * fail due to an error reading the file? */ if (ferror(proc_net_f)) { (void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading /proc/net/dev: %s", pcap_strerror(errno)); ret = -1; } } (void)fclose(proc_net_f); return (ret); }
/* receive one JSON object from the server. * Returns: - NULL after a network error OR * - an empty JSON object if there is a parsing error OR * - the parsed response from the server */ static json_t *receive_json_msg(void) { char *rbuf, *bp; int datalen, ret, rbufsize; json_t *recv_msg; json_error_t err; fd_set rfds; struct timeval tv; FD_ZERO(&rfds); FD_SET(sockfd, &rfds); rbufsize = 1024 * 1024; /* initial size: 1MB */ rbuf = malloc(rbufsize); memset(rbuf, 0, rbufsize); recv_msg = NULL; datalen = 0; while (!recv_msg) { /* select before reading so that we get a timeout. Otherwise the * program might hang indefinitely in read if the connection has failed */ tv.tv_sec = 10; /* 10s * 3 retries results in a long wait on failed connections... */ tv.tv_usec = 0; ret = select(sockfd + 1, &rfds, NULL, NULL, &tv); if (ret <= 0) { /* we aren't expecting any signals, so it seems ok to abort even if * ret == -1 && errno == EINTR */ free(rbuf); return NULL; } /* leave the last byte in the buffer free for the '\0' */ ret = recv(sockfd, &rbuf[datalen], rbufsize - datalen - 1, 0); if (ret == -1 && errno == EINTR) continue; else if (ret <= 0) { free(rbuf); return NULL; } datalen += ret; rbuf[datalen] = '\0'; /* terminate the string */ bp = &rbuf[datalen - 1]; while (isspace(*bp)) bp--; recv_msg = NULL; if (*bp == '}') { /* possibly the end of the json object */ recv_msg = json_loads(rbuf, JSON_REJECT_DUPLICATES, &err); if (!recv_msg && err.position < datalen) { print_error("Broken response received from server."); free(rbuf); return json_object(); } } /* allow the receive buffer to grow to 16MB. Growing larger than 1MB is * extremely unlikely (I can't imagine how it would happen); 16MB or * more is clearly an error. */ if (!recv_msg && datalen >= rbufsize - 1) { if (datalen < 16 * 1024 * 1024) { rbufsize *= 2; rbuf = realloc(rbuf, rbufsize); } else { print_error("Too much incoming data. Server error?"); free(rbuf); return json_object(); } } } free(rbuf); return recv_msg; }
static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf, size_t len, CURLcode *err) { ldapconninfo *li = conn->proto.generic; struct SessionHandle *data=conn->data; ldapreqinfo *lr = data->state.proto.generic; int rc, ret; LDAPMessage *result = NULL; LDAPMessage *ent; BerElement *ber = NULL; struct timeval tv = {0,1}; (void)len; (void)buf; (void)sockindex; rc = ldap_result(li->ld, lr->msgid, LDAP_MSG_RECEIVED, &tv, &result); if (rc < 0) { failf(data, "LDAP local: search ldap_result %s", ldap_err2string(rc)); *err = CURLE_RECV_ERROR; return -1; } *err = CURLE_AGAIN; ret = -1; /* timed out */ if (result == NULL) return ret; for (ent = ldap_first_message(li->ld, result); ent; ent = ldap_next_message(li->ld, ent)) { struct berval bv, *bvals, **bvp = &bvals; int binary = 0, msgtype; msgtype = ldap_msgtype(ent); if (msgtype == LDAP_RES_SEARCH_RESULT) { int code; char *info = NULL; rc = ldap_parse_result(li->ld, ent, &code, NULL, &info, NULL, NULL, 0); if (rc) { failf(data, "LDAP local: search ldap_parse_result %s", ldap_err2string(rc)); *err = CURLE_LDAP_SEARCH_FAILED; } else if (code && code != LDAP_SIZELIMIT_EXCEEDED) { failf(data, "LDAP remote: search failed %s %s", ldap_err2string(rc), info ? info : ""); *err = CURLE_LDAP_SEARCH_FAILED; } else { /* successful */ if (code == LDAP_SIZELIMIT_EXCEEDED) infof(data, "There are more than %d entries\n", lr->nument); data->req.size = data->req.bytecount; *err = CURLE_OK; ret = 0; } lr->msgid = 0; ldap_memfree(info); break; } else if (msgtype != LDAP_RES_SEARCH_ENTRY) { continue; } lr->nument++; rc = ldap_get_dn_ber(li->ld, ent, &ber, &bv); Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4); Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, bv.bv_len); Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); data->req.bytecount += bv.bv_len + 5; for (rc = ldap_get_attribute_ber(li->ld, ent, ber, &bv, bvp); rc == LDAP_SUCCESS; rc = ldap_get_attribute_ber(li->ld, ent, ber, &bv, bvp)) { int i; if (bv.bv_val == NULL) break; if (bv.bv_len > 7 && !strncmp(bv.bv_val + bv.bv_len - 7, ";binary", 7)) binary = 1; for (i=0; bvals[i].bv_val != NULL; i++) { int binval = 0; Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1); Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, bv.bv_len); Curl_client_write(conn, CLIENTWRITE_BODY, (char *)":", 1); data->req.bytecount += bv.bv_len + 2; if (!binary) { /* check for leading or trailing whitespace */ if (isspace(bvals[i].bv_val[0]) || isspace(bvals[i].bv_val[bvals[i].bv_len-1])) { binval = 1; } else { /* check for unprintable characters */ unsigned int j; for (j=0; j<bvals[i].bv_len; j++) if (!isprint(bvals[i].bv_val[j])) { binval = 1; break; } } } if (binary || binval) { char *val_b64; /* Binary value, encode to base64. */ size_t val_b64_sz = Curl_base64_encode(data, bvals[i].bv_val, bvals[i].bv_len, &val_b64); Curl_client_write(conn, CLIENTWRITE_BODY, (char *)": ", 2); data->req.bytecount += 2; if(val_b64_sz > 0) { Curl_client_write(conn, CLIENTWRITE_BODY, val_b64, val_b64_sz); free(val_b64); data->req.bytecount += val_b64_sz; } } else { Curl_client_write(conn, CLIENTWRITE_BODY, (char *)" ", 1); Curl_client_write(conn, CLIENTWRITE_BODY, bvals[i].bv_val, bvals[i].bv_len); data->req.bytecount += bvals[i].bv_len + 1; } Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); data->req.bytecount++; } ber_memfree(bvals); Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); data->req.bytecount++; } Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); data->req.bytecount++; ber_free(ber, 0); } ldap_msgfree(result); return ret; }
// returns the last port from the trace file uint16_t openInputTraceFile(const char *name) { FILE *in = fopen(name, "r"); TraceRecord *previous = NULL; uint16_t i; if (in == NULL) { fprintf(stderr, "Open \"%s\" failed.\n", name); exit(-1); } emReadingTrace = true; int result = 0; while (true) { int tag = fgetc(in); unsigned int length; TraceRecord *traceRecord = {0}; int port; uint8_t addressFromFile[100] = {0}; if (tag == EOF) { break; } else if (isspace(tag)) { continue; } if (fscanf(in, " %d", &port) != 1) { fprintf(stderr, "Failed to read port"); exit(-1); } ASSERT(port <= 0xFFFF); if (fscanf(in, " %s", addressFromFile) != 1) { fprintf(stderr, "Failed to read address"); exit(-1); } if (fscanf(in, " %u", &length) != 1) { fprintf(stderr, "Failed to read trace length."); exit(-1); } traceRecord = (TraceRecord *) malloc(sizeof(TraceRecord) + length); if (traceRecord == NULL) { fprintf(stderr, "Failed to allocate TraceRecord."); exit(-1); } traceRecord->tag = tag; traceRecord->previous = previous; traceRecord->next = NULL; traceRecord->length = length; traceRecord->port = port; result = traceRecord->port; // i don't like having an #ifdef here, but it's easier than // pulling in ip-address.c to the tls and pana tests #ifdef UNIX_SCRIPTED_HOST stringToIpAddress(addressFromFile, strlen(addressFromFile), traceRecord->address); #endif if (previous == NULL) { theTrace = traceRecord; } else { previous->next = traceRecord; } previous = traceRecord; for (i = 0; i < length; i++) { unsigned int n; if (fscanf(in, " %2X", &n) != 1) { fprintf(stderr, "Failed to read trace value."); exit(-1); } traceRecord->contents[i] = n; } } fprintf(stderr, "[Running \"%s\" ", name); return result; }
char * skip_token (const char *p) { while (isspace((unsigned char)*p)) p++; while (*p && !isspace((unsigned char)*p)) p++; return (char *)p; }
UINT32 strtoul ( const char *String, char **Terminator, UINT32 Base) { UINT32 converted = 0; UINT32 index; UINT32 sign; const char *StringStart; UINT32 ReturnValue = 0; ACPI_STATUS Status = AE_OK; /* * Save the value of the pointer to the buffer's first * character, save the current errno value, and then * skip over any white space in the buffer: */ StringStart = String; while (isspace (*String) || *String == '\t') { ++String; } /* * The buffer may contain an optional plus or minus sign. * If it does, then skip over it but remember what is was: */ if (*String == '-') { sign = ACPI_SIGN_NEGATIVE; ++String; } else if (*String == '+') { ++String; sign = ACPI_SIGN_POSITIVE; } else { sign = ACPI_SIGN_POSITIVE; } /* * If the input parameter Base is zero, then we need to * determine if it is octal, decimal, or hexadecimal: */ if (Base == 0) { if (*String == '0') { if (tolower (*(++String)) == 'x') { Base = 16; ++String; } else { Base = 8; } } else { Base = 10; } } else if (Base < 2 || Base > 36) { /* * The specified Base parameter is not in the domain of * this function: */ goto done; } /* * For octal and hexadecimal bases, skip over the leading * 0 or 0x, if they are present. */ if (Base == 8 && *String == '0') { String++; } if (Base == 16 && *String == '0' && tolower (*(++String)) == 'x') { String++; } /* * Main loop: convert the string to an unsigned long: */ while (*String) { if (isdigit (*String)) { index = (UINT32) ((UINT8) *String - '0'); } else { index = (UINT32) toupper (*String); if (isupper (index)) { index = index - 'A' + 10; } else { goto done; } } if (index >= Base) { goto done; } /* * Check to see if value is out of range: */ if (ReturnValue > ((ACPI_UINT32_MAX - (UINT32) index) / (UINT32) Base)) { Status = AE_ERROR; ReturnValue = 0; /* reset */ } else { ReturnValue *= Base; ReturnValue += index; converted = 1; } ++String; } done: /* * If appropriate, update the caller's pointer to the next * unconverted character in the buffer. */ if (Terminator) { if (converted == 0 && ReturnValue == 0 && String != NULL) { *Terminator = (char *) StringStart; } else { *Terminator = (char *) String; } } if (Status == AE_ERROR) { ReturnValue = ACPI_UINT32_MAX; } /* * If a minus sign was present, then "the conversion is negated": */ if (sign == ACPI_SIGN_NEGATIVE) { ReturnValue = (ACPI_UINT32_MAX - ReturnValue) + 1; } return (ReturnValue); }
void process_mult (FILE *in, int overwrite, int casemode, int colmode) { Basrec_type rec; int processing = FALSE, i, j, eol, len; char file_out [MAXPATH], casetext [MAXLINE], fext [MAXEXT]; FILE *out; while (getline (line, MAXLINE, in) != EOF) { i = 0; eol = strlen (line); while (i < eol && isspace (line [i])) i ++; for (j = i; j < eol; j++) casetext [j] = tolower (line [j]); casetext [j] = 0; len = strlen (START_PROC); if (! strncmp (& (casetext [i]), START_PROC, len)) { if (processing) { end_prg (out); fclose (out); processing = FALSE; fprintf (stderr, " done.\n"); } i += len; if (sscanf (& (line [i]), "%s", file_out) == 1) { if (! extension (file_out, fext, MAXEXT -1)) strncat (file_out, PRG_EXT, MAXPATH - 1); else if (! strcmp (fext, TXT_EXT)) { fclose (in); fprintf (stderr, "%s: not expecting \"%s\" as output.\n", program, file_out); exit (EXITBAD); } if (! exit_exists (overwrite, in, file_out)) if ((out = fopen (file_out, "wb")) == NULL) { fprintf (stderr, "%s: Can't open %s for output\n", program, file_out); fclose (in); exit (EXITBAD); } else { fprintf (stderr, "==> %s ...", file_out); processing = TRUE; set_addy (BASREC_NULL); tokenize (BASREC_NULL, CH_NULL, TRUE, TRUE); start_prg (out); } } else { fprintf (stderr, "%s: no output filename given\n", program); fclose (in); exit (EXITBAD); } } else if (! strncmp (& (casetext [i]), STOP_PROC, strlen (STOP_PROC))) { if (processing) { end_prg (out); fclose (out); processing = FALSE; fprintf (stderr, " done.\n"); } } else if (processing) { if (tokenize (&rec, line, casemode, colmode)) { set_addy (&rec); outprg (out, &rec); } } } return; }
static NEOERR* _hdf_read_string (HDF *hdf, const char **str, STRING *line, const char *path, int *lineno, int include_handle, int expect_end_brace) { NEOERR *err; HDF *lower; char *s; char *name, *value; HDF_ATTR *attr = NULL; while (**str != '\0') { /* Reset string length, but don't free the reserved buffer */ line->len = 0; err = _copy_line_advance(str, line); if (err) return nerr_pass(err); attr = NULL; (*lineno)++; s = line->buf; SKIPWS(s); if ((!strncmp(s, "#include ", 9) || !strncmp(s, "-include ", 9)) && include_handle != INCLUDE_IGNORE) { int required = !strncmp(s, "#include ", 9); if (include_handle == INCLUDE_ERROR) { return nerr_raise (NERR_PARSE, "[%d]: #include not supported in string parse", *lineno); } else if (include_handle < INCLUDE_MAX_DEPTH) { int l; s += 9; name = neos_strip(s); l = strlen(name); if (name[0] == '"' && name[l-1] == '"') { name[l-1] = '\0'; name++; } char fullpath[PATH_MAX]; if (name[0] != '/') { memset(fullpath, 0, PATH_MAX); char *p = strrchr(path, '/'); if (p == NULL) { char pwd[PATH_MAX]; memset(pwd, 0, PATH_MAX); getcwd(pwd, PATH_MAX); snprintf(fullpath, PATH_MAX, "%s/%s", pwd, name); } else { int dir_len = p - path + 1; snprintf(fullpath, PATH_MAX, "%s", path); snprintf(fullpath + dir_len, PATH_MAX - dir_len, "%s", name); } name = fullpath; } err = hdf_read_file_internal(hdf, name, include_handle + 1); if (err != STATUS_OK && required) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else { return nerr_raise (NERR_MAX_RECURSION, "[%d]: Too many recursion levels.", *lineno ); } } else if (s[0] == '#') { /* comment: pass */ } else if (s[0] == '}') /* up */ { s = neos_strip(s); if (strcmp(s, "}")) { err = nerr_raise(NERR_PARSE, "[%s:%d] Trailing garbage on line following }: %s", path, *lineno, line->buf); return err; } return STATUS_OK; } else if (s[0]) { /* Valid hdf name is [0-9a-zA-Z_.]+ */ int splice = *s == '@'; if (splice) s++; name = s; while (*s && (isalnum(*s) || *s == '_' || *s == '.' || *s == '*')) s++; SKIPWS(s); char num[16]; static int counter = 0; if (*name == '*') { snprintf(num, sizeof(num), "%d", counter++); name = num; } if (s[0] == '[') /* attributes */ { *s = '\0'; name = neos_strip(name); s++; err = parse_attr(&s, &attr); if (err) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } SKIPWS(s); } if (splice) { name = neos_strip(name); HDF *h = hdf_get_obj(hdf->top, name); if (h) { HDF *c = hdf_obj_child(h); while (c) { err = hdf_copy (hdf, hdf_obj_name(c), c); if (err != STATUS_OK) break; c = hdf_obj_next(c); } } if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == '=') /* assignment */ { *s = '\0'; name = neos_strip(name); s++; value = neos_strip(s); err = _set_value (hdf, name, value, 1, 1, 0, attr, NULL); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == ':' && s[1] == '=') /* copy */ { *s = '\0'; name = neos_strip(name); s+=2; value = neos_strip(s); HDF *h = hdf_get_obj(hdf->top, value); if (!h) { err = nerr_raise(NERR_PARSE, "[%s:%d] Failed to copy a node that is not loaded " "yet: %s", path, *lineno, value); return err; } err = hdf_copy(hdf, name, h); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == '!' && s[1] == '=') /* exec */ { *s = '\0'; name = neos_strip(name); s+=2; value = neos_strip(s); FILE *f = popen(value, "r"); if (f == NULL) { err = nerr_raise(NERR_PARSE, "[%s:%d] Failed to exec specified command: %s", path, *lineno, line->buf); return err; } char *content = _read_file(f); fclose(f); int len = strlen(content); if (len > 0 && content[len - 1] == '\n') { content[len - 1] = '\0'; // remove \n artifact } err = _set_value (hdf, name, content, 1, 1, 0, attr, NULL); free(content); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == ':') /* link */ { *s = '\0'; name = neos_strip(name); s++; value = neos_strip(s); err = _set_value (hdf, name, value, 1, 1, 1, attr, NULL); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == '{') /* deeper */ { *s = '\0'; name = neos_strip(name); lower = hdf_get_obj (hdf, name); if (lower == NULL) { err = _set_value (hdf, name, NULL, 1, 1, 0, attr, &lower); } else { err = _set_value (lower, NULL, lower->value, 1, 1, 0, attr, NULL); } if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } err = _hdf_read_string (lower, str, line, path, lineno, include_handle, 1); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == '<' && s[1] == '<') /* multi-line assignment */ { char *m; int msize = 0; int mmax = 128; int l; *s = '\0'; name = neos_strip(name); s+=2; value = neos_strip(s); l = strlen(value); if (l == 0) { err = nerr_raise(NERR_PARSE, "[%s:%d] No multi-assignment terminator given: %s", path, *lineno, line->buf); return err; } m = (char *) malloc (mmax * sizeof(char)); if (m == NULL) { return nerr_raise(NERR_NOMEM, "[%s:%d] Unable to allocate memory for multi-line assignment to %s", path, *lineno, name); } while (_copy_line (str, m+msize, mmax-msize) != 0) { (*lineno)++; if (!strncmp(value, m+msize, l) && isspace(m[msize+l])) { m[msize] = '\0'; break; } msize += strlen(m+msize); if (msize + l + 10 > mmax) { void *new_ptr; mmax += 128; new_ptr = realloc (m, mmax * sizeof(char)); if (new_ptr == NULL) { free(m); return nerr_raise(NERR_NOMEM, "[%s:%d] Unable to allocate memory for multi-line assignment to %s: size=%d", path, *lineno, name, mmax); } m = (char *) new_ptr; } } err = _set_value (hdf, name, m, 0, 1, 0, attr, NULL); if (err != STATUS_OK) { free (m); return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else { err = nerr_raise(NERR_PARSE, "[%s:%d] Unable to parse line %s", path, *lineno, line->buf); return err; } } } if (expect_end_brace) { err = nerr_raise(NERR_PARSE, "[%s:%d] Missing matching }", path, *lineno); return err; } return STATUS_OK; }
/** * skip_spaces - Removes leading whitespace from @str. * @str: The string to be stripped. * * Returns a pointer to the first non-whitespace character in @str. */ char __attribute__((weak)) *skip_spaces(const char *str) { while (isspace(*str)) ++str; return (char *)str; }
bool TMXLoader::Private::processLayer(XMLElement &e) { const char *l_name; float l_opacity = 1.f; int l_visible = 1; if ((!(l_name = e.Attribute("name")))) { MMWARNING("Layer element is missing one or more required attributes."); return(false); } MMIGNORE e.QueryFloatAttribute("opacity", &l_opacity); MMIGNORE e.QueryIntAttribute("visible", &l_visible); XMLElement *l_data = e.FirstChildElement(TMXLAYER_DATA_NODE); if (!l_data) { MMWARNING("Layer element is missing data element."); return(false); } const char *l_data_encoding; const char *l_data_compression; if (!(l_data_encoding = l_data->Attribute("encoding")) || !(l_data_compression = l_data->Attribute("compression"))) { MMWARNING("Layer data element is missing one or more required attributes."); return(false); } const char *l_data_raw = XMLUtil::SkipWhiteSpace(l_data->GetText()); size_t l_data_raw_len = strlen(l_data_raw); /* right-side data trim */ while (l_data_raw_len > 0 && isspace(l_data_raw[l_data_raw_len - 1])) --l_data_raw_len; if (!l_data_raw_len) { MMWARNING("Zero size layer data encountered."); return(false); } char *l_data_array = 0; #define TMXDATA_ENCODING_BASE64 "base64" if (0 == strcmp(l_data_encoding, TMXDATA_ENCODING_BASE64)) { char *l_decoded_data; size_t l_decoded_data_size = Core::Base64::Decode(l_data_raw, l_data_raw_len, &l_decoded_data); #define TMXDATA_COMPRESSION_ZLIB "zlib" if (0 == strcmp(l_data_compression, TMXDATA_COMPRESSION_ZLIB)) { char *l_inflated_data; if (0 < Core::Zlib::Inflate(l_decoded_data, l_decoded_data_size, static_cast<size_t>(map_size.width * map_size.height * 4), &l_inflated_data)) l_data_array = l_inflated_data; } #define TMXDATA_COMPRESSION_GZIP "gzip" else if (0 == strcmp(l_data_compression, TMXDATA_COMPRESSION_GZIP)) { char *l_inflated_data; if (0 < Core::Gzip::Inflate(l_decoded_data, l_decoded_data_size, static_cast<size_t>(map_size.width * map_size.height * 4), &l_inflated_data)) l_data_array = l_inflated_data; } delete[] l_decoded_data; } #define TMXDATA_ENCODING_CSV "csv" else if (0 == strcmp(l_data_encoding, TMXDATA_ENCODING_CSV)) { // TODO(gamaral) assert(0 && "CSV data encoding is currently unimplemented"); return(false); } if (!l_data_array) return(false); Game::TilemapSceneLayer *l_layer = new Game::TilemapSceneLayer(l_name, scene); l_layer->setData(reinterpret_cast<uint32_t *>(l_data_array)); l_layer->setOpacity(l_opacity); l_layer->setSize(map_size); l_layer->setTileSize(tile_size); l_layer->setScale(scale); l_layer->setVisibility(1 == l_visible); /* process properties */ XMLElement *l_properties = e.FirstChildElement(TMXPROPERTIES_NODE); XMLElement *l_property = l_properties ? l_properties->FirstChildElement(TMXPROPERTIES_PROPERTY_NODE) : 0; if (l_property) do { const char *l_pname = l_property->Attribute("name"); const char *l_value = l_property->Attribute("value"); if (!l_pname) continue; /* scale property */ if (0 == strcmp(l_pname, "scale")) { if (!l_value) { MMWARNING("Skipping incomplete scale property."); continue; } Math::Size2f l_scale = l_layer->scale(); if (0 == MMSTRCASECMP(l_value, "screen")) { const Math::Size2f &l_vsize = Graphics::Viewport::Size(); const Math::Size2i &l_wsize = Graphics::Viewport::WindowSize(); /* * calculate pixels per viewport coordinate ratio * scale ratio = vSize (vcoord)) / wSize (pixels) */ l_scale = l_vsize / l_wsize.cast<float>(); l_layer->setScale(l_scale); continue; } else if (2 == sscanf(l_value, "%fx%f", &l_scale.width, &l_scale.height)) { l_layer->setScale(l_scale); continue; } else if (1 == sscanf(l_value, "%f", &l_scale.width)) { l_scale.height = l_scale.width; l_layer->setScale(l_scale); continue; } MMERROR("Invalid scale value encountered."); continue; } else l_layer->setProperty(l_name, l_value ? l_value : std::string()); } while ((l_property = l_property->NextSiblingElement(TMXPROPERTIES_PROPERTY_NODE))); /* attach tilesets */ TilesetCollection::iterator l_tileset_i; for (l_tileset_i = tilesets.begin(); l_tileset_i != tilesets.end(); ++l_tileset_i) l_layer->attachTileset(l_tileset_i->first, l_tileset_i->second); layers.push_back(l_layer); return(true); }
static int getstructure(char *tag, int structure) { /* int len; *//* not used - 2/22/00 */ char oldChar = 0; char *endOfTag = NULL; char *pos; pos = tag; while (*pos) { if (isspace((int) ((unsigned char) *pos))) { endOfTag = pos; /* remember where we are... */ oldChar = *pos; /* ...and what we saw */ *pos = '\0'; /* truncate string, for now */ } else pos++; } /* Store Word Context ** Modified DLN 1999-10-24 - Comments and Cleaning ** TODO: Make sure that these allow for HTML attributes * */ /* HEAD */ if (strcasecmp(tag, "/head") == 0) structure &= ~IN_HEAD; /* Out */ else if (strcasecmp(tag, "head") == 0) structure |= IN_HEAD; /* In */ /* TITLE */ else if (strcasecmp(tag, "/title") == 0) structure &= ~IN_TITLE; else if (strcasecmp(tag, "title") == 0) structure |= IN_TITLE; /* BODY */ else if (strcasecmp(tag, "/body") == 0) structure &= ~IN_BODY; /* In */ else if (strcasecmp(tag, "body") == 0) structure |= IN_BODY; /* Out */ /* H1, H2, H3, H4, H5, H6 */ else if (tag[0] == '/' && tolower((int)((unsigned char)tag[1])) == 'h' && isdigit((int)((unsigned char)tag[2]))) /* cast to int - 2/22/00 */ structure &= ~IN_HEADER; /* In */ else if (tolower((int)((unsigned char)tag[0])) == 'h' && isdigit((int)(unsigned char)tag[1])) /* cast to int - 2/22/00 */ structure |= IN_HEADER; /* Out */ /* EM, STRONG */ else if ((strcasecmp(tag, "/em") == 0) || (strcasecmp(tag, "/strong") == 0)) structure &= ~IN_EMPHASIZED; /* Out */ else if ((strcasecmp(tag, "em") == 0) || (strcasecmp(tag, "strong") == 0)) structure |= IN_EMPHASIZED; /* In */ /* B, I are seperate for semantics */ else if ((strcasecmp(tag, "/b") == 0) || (strcasecmp(tag, "/i") == 0)) structure &= ~IN_EMPHASIZED; /* Out */ else if ((strcasecmp(tag, "b") == 0) || (strcasecmp(tag, "i") == 0)) structure |= IN_EMPHASIZED; /* In */ /* The End */ if (endOfTag != NULL) { *endOfTag = oldChar; } return structure; }
fm_s32 cfg_parser(fm_s8 *buffer, CFG_HANDLER handler, fm_cust_cfg *cfg) { fm_s32 ret = 0; fm_s8 *p = buffer; fm_s8 *group_start = NULL; fm_s8 *key_start = NULL; fm_s8 *value_start = NULL; enum fm_cfg_parser_state state = FM_CFG_STAT_NONE; FMR_ASSERT(p); for (p = buffer; *p != '\0'; p++) { switch (state) { case FM_CFG_STAT_NONE: { if (*p == '[') { /* if we get char '[' in none state, it means a new group name start */ state = FM_CFG_STAT_GROUP; group_start = p + 1; } else if (*p == COMMENT_CHAR) { /* if we get char '#' in none state, it means a new comment start */ state = FM_CFG_STAT_COMMENT; } else if (!isspace(*p) && (*p != '\n') && (*p != '\r')) { /* if we get an nonspace char in none state, it means a new key start */ state = FM_CFG_STAT_KEY; key_start = p; } break; } case FM_CFG_STAT_GROUP: { if (*p == ']') { /* if we get char ']' in group state, it means a group name complete */ *p = '\0'; /* FIX_ME */ /* record group name */ state = FM_CFG_STAT_NONE; trim_string(&group_start); /* WCN_DBG(FM_NTC|MAIN, "g=%s\n", group_start); */ } break; } case FM_CFG_STAT_COMMENT: { if (*p == '\n') { /* if we get char '\n' in comment state, it means new line start */ state = FM_CFG_STAT_NONE; group_start = p + 1; } break; } case FM_CFG_STAT_KEY: { if (*p == DELIMIT_CHAR) { /* if we get char '=' in key state, it means a key name complete */ *p = '\0'; /* FIX_ME */ /* record key name */ state = FM_CFG_STAT_VALUE; value_start = p + 1; trim_string(&key_start); /* WCN_DBG(FM_NTC|MAIN, "k=%s\n", key_start); */ } break; } case FM_CFG_STAT_VALUE: { if (*p == '\n' || *p == '\r') { /* if we get char '\n' or '\r' in value state, it means a value complete */ *p = '\0'; /* record value */ trim_string(&value_start); /* WCN_DBG(FM_NTC|MAIN, "v=%s\n", value_start); */ if (handler) { ret = handler(group_start, key_start, value_start, cfg); } state = FM_CFG_STAT_NONE; } break; } default: break; } } return ret; }