bool get_arguments (struct arguments_definition *def, int argc, char *argv[]) { bool go_on = false; size_t i, count = 0; struct option *opts; char *optstring; assert (NULL != def); for (i = 0;NULL != def->options[i].cat;++i) if (NULL != def->options[i].long_opt) ++count; opts = (struct option *) malloc (sizeof (struct option) * (count + 1)); if (NULL == opts) { fprintf (stderr, "Could not allocate memory because: %s\n", strerror (errno)); } else { memset (opts, 0, sizeof (struct option) * (count + 1)); for (i = 0;NULL != def->options[i].cat;++i) if (isalnum (def->options[i].short_opt)) ++count; optstring = (char *) malloc ((count + 1) * 3); if (NULL == optstring) { fprintf (stderr, "Could not allocate memory because: %s\n", strerror (errno)); } else { size_t s = 0, l = 0; int opt; memset (optstring, 0, (count + 1) * 3); for (i = 0;NULL != def->options[i].cat;++i) { if (isalnum (def->options[i].short_opt)) { optstring[s++] = def->options[i].short_opt; switch (def->options[i].has_arg) { case optional_argument: optstring[s++] = ':'; case required_argument: optstring[s++] = ':'; case no_argument: break; default: assert (false); /* invalid has_arg value */ break; } } if (NULL != def->options[i].long_opt) { opts[l].name = def->options[i].long_opt; opts[l].has_arg = def->options[i].has_arg; opts[l].flag = NULL; opts[l].val = def->options[i].short_opt; ++l; } } for (go_on = true; go_on && -1 != (opt = getopt_long (argc, argv, optstring, opts, NULL));) go_on = def->process_option (def, opt, optarg, argc, argv); if (go_on && optind < argc && NULL != def->process_non_options) go_on = def->process_non_options (def, optind, argc, argv); free (optstring); } free (opts); } return go_on; }
static int x_try_array(const char *buf, int buflen, const char *want, int wantlen, int *nwords, char ***words) { const char *cmd, *cp; int cmdlen, n, i, slen; char *name, *s; struct tbl *v, *vp; *nwords = 0; *words = NULL; /* Walk back to find start of command. */ if (want == buf) return 0; for (cmd = want; cmd > buf; cmd--) { if (strchr(";|&()`", cmd[-1]) != NULL) break; } while (cmd < want && isspace((u_char)*cmd)) cmd++; cmdlen = 0; while (cmd + cmdlen < want && !isspace((u_char)cmd[cmdlen])) cmdlen++; for (i = 0; i < cmdlen; i++) { if (!isalnum((u_char)cmd[i]) && cmd[i] != '_') return 0; } /* Take a stab at argument count from here. */ n = 1; for (cp = cmd + cmdlen + 1; cp < want; cp++) { if (!isspace((u_char)cp[-1]) && isspace((u_char)*cp)) n++; } /* Try to find the array. */ if (asprintf(&name, "complete_%.*s_%d", cmdlen, cmd, n) < 0) internal_errorf("unable to allocate memory"); v = global(name); free(name); if (~v->flag & (ISSET|ARRAY)) { if (asprintf(&name, "complete_%.*s", cmdlen, cmd) < 0) internal_errorf("unable to allocate memory"); v = global(name); free(name); if (~v->flag & (ISSET|ARRAY)) return 0; } /* Walk the array and build words list. */ for (vp = v; vp; vp = vp->u.array) { if (~vp->flag & ISSET) continue; s = str_val(vp); slen = strlen(s); if (slen < wantlen) continue; if (slen > wantlen) slen = wantlen; if (slen != 0 && strncmp(s, want, slen) != 0) continue; *words = areallocarray(*words, (*nwords) + 2, sizeof **words, ATEMP); (*words)[(*nwords)++] = str_save(s, ATEMP); } if (*nwords != 0) (*words)[*nwords] = NULL; return *nwords != 0; }
int zmq::socket_base_t::connect (const char *addr_) { ENTER_MUTEX(); if (unlikely (ctx_terminated)) { errno = ETERM; EXIT_MUTEX(); return -1; } // Process pending commands, if any. int rc = process_commands (0, false); if (unlikely (rc != 0)) { EXIT_MUTEX(); return -1; } // Parse addr_ string. std::string protocol; std::string address; if (parse_uri (addr_, protocol, address) || check_protocol (protocol)) { EXIT_MUTEX(); return -1; } if (protocol == "inproc") { // TODO: inproc connect is specific with respect to creating pipes // as there's no 'reconnect' functionality implemented. Once that // is in place we should follow generic pipe creation algorithm. // Find the peer endpoint. endpoint_t peer = find_endpoint (addr_); // The total HWM for an inproc connection should be the sum of // the binder's HWM and the connector's HWM. int sndhwm = 0; if (peer.socket == NULL) sndhwm = options.sndhwm; else if (options.sndhwm != 0 && peer.options.rcvhwm != 0) sndhwm = options.sndhwm + peer.options.rcvhwm; int rcvhwm = 0; if (peer.socket == NULL) rcvhwm = options.rcvhwm; else if (options.rcvhwm != 0 && peer.options.sndhwm != 0) rcvhwm = options.rcvhwm + peer.options.sndhwm; // Create a bi-directional pipe to connect the peers. object_t *parents [2] = {this, peer.socket == NULL ? this : peer.socket}; pipe_t *new_pipes [2] = {NULL, NULL}; bool conflate = options.conflate && (options.type == ZMQ_DEALER || options.type == ZMQ_PULL || options.type == ZMQ_PUSH || options.type == ZMQ_PUB || options.type == ZMQ_SUB); int hwms [2] = {conflate? -1 : sndhwm, conflate? -1 : rcvhwm}; bool conflates [2] = {conflate, conflate}; int rc = pipepair (parents, new_pipes, hwms, conflates); if (!conflate) { new_pipes[0]->set_hwms_boost(peer.options.sndhwm, peer.options.rcvhwm); new_pipes[1]->set_hwms_boost(options.sndhwm, options.rcvhwm); } errno_assert (rc == 0); if (!peer.socket) { // The peer doesn't exist yet so we don't know whether // to send the identity message or not. To resolve this, // we always send our identity and drop it later if // the peer doesn't expect it. msg_t id; rc = id.init_size (options.identity_size); errno_assert (rc == 0); memcpy (id.data (), options.identity, options.identity_size); id.set_flags (msg_t::identity); bool written = new_pipes [0]->write (&id); zmq_assert (written); new_pipes [0]->flush (); const endpoint_t endpoint = {this, options}; pend_connection (std::string (addr_), endpoint, new_pipes); } else { // If required, send the identity of the local socket to the peer. if (peer.options.recv_identity) { msg_t id; rc = id.init_size (options.identity_size); errno_assert (rc == 0); memcpy (id.data (), options.identity, options.identity_size); id.set_flags (msg_t::identity); bool written = new_pipes [0]->write (&id); zmq_assert (written); new_pipes [0]->flush (); } // If required, send the identity of the peer to the local socket. if (options.recv_identity) { msg_t id; rc = id.init_size (peer.options.identity_size); errno_assert (rc == 0); memcpy (id.data (), peer.options.identity, peer.options.identity_size); id.set_flags (msg_t::identity); bool written = new_pipes [1]->write (&id); zmq_assert (written); new_pipes [1]->flush (); } // Attach remote end of the pipe to the peer socket. Note that peer's // seqnum was incremented in find_endpoint function. We don't need it // increased here. send_bind (peer.socket, new_pipes [1], false); } // Attach local end of the pipe to this socket object. attach_pipe (new_pipes [0]); // Save last endpoint URI last_endpoint.assign (addr_); // remember inproc connections for disconnect inprocs.insert (inprocs_t::value_type (std::string (addr_), new_pipes [0])); options.connected = true; EXIT_MUTEX(); return 0; } bool is_single_connect = (options.type == ZMQ_DEALER || options.type == ZMQ_SUB || options.type == ZMQ_REQ); if (unlikely (is_single_connect)) { const endpoints_t::iterator it = endpoints.find (addr_); if (it != endpoints.end ()) { // There is no valid use for multiple connects for SUB-PUB nor // DEALER-ROUTER nor REQ-REP. Multiple connects produces // nonsensical results. EXIT_MUTEX(); return 0; } } // Choose the I/O thread to run the session in. io_thread_t *io_thread = choose_io_thread (options.affinity); if (!io_thread) { errno = EMTHREAD; EXIT_MUTEX(); return -1; } address_t *paddr = new (std::nothrow) address_t (protocol, address); alloc_assert (paddr); // Resolve address (if needed by the protocol) if (protocol == "tcp") { // Do some basic sanity checks on tcp:// address syntax // - hostname starts with digit or letter, with embedded '-' or '.' // - IPv6 address may contain hex chars and colons. // - IPv4 address may contain decimal digits and dots. // - Address must end in ":port" where port is *, or numeric // - Address may contain two parts separated by ':' // Following code is quick and dirty check to catch obvious errors, // without trying to be fully accurate. const char *check = address.c_str (); if (isalnum (*check) || isxdigit (*check) || *check == '[') { check++; while (isalnum (*check) || isxdigit (*check) || *check == '.' || *check == '-' || *check == ':'|| *check == ';' || *check == ']') check++; } // Assume the worst, now look for success rc = -1; // Did we reach the end of the address safely? if (*check == 0) { // Do we have a valid port string? (cannot be '*' in connect check = strrchr (address.c_str (), ':'); if (check) { check++; if (*check && (isdigit (*check))) rc = 0; // Valid } } if (rc == -1) { errno = EINVAL; LIBZMQ_DELETE(paddr); EXIT_MUTEX(); return -1; } // Defer resolution until a socket is opened paddr->resolved.tcp_addr = NULL; } #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS else if (protocol == "ipc") { paddr->resolved.ipc_addr = new (std::nothrow) ipc_address_t (); alloc_assert (paddr->resolved.ipc_addr); int rc = paddr->resolved.ipc_addr->resolve (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE(paddr); EXIT_MUTEX(); return -1; } } #endif // TBD - Should we check address for ZMQ_HAVE_NORM??? #ifdef ZMQ_HAVE_OPENPGM if (protocol == "pgm" || protocol == "epgm") { struct pgm_addrinfo_t *res = NULL; uint16_t port_number = 0; int rc = pgm_socket_t::init_address(address.c_str(), &res, &port_number); if (res != NULL) pgm_freeaddrinfo (res); if (rc != 0 || port_number == 0) { EXIT_MUTEX(); return -1; } } #endif #if defined ZMQ_HAVE_TIPC else if (protocol == "tipc") { paddr->resolved.tipc_addr = new (std::nothrow) tipc_address_t (); alloc_assert (paddr->resolved.tipc_addr); int rc = paddr->resolved.tipc_addr->resolve (address.c_str()); if (rc != 0) { LIBZMQ_DELETE(paddr); EXIT_MUTEX(); return -1; } } #endif // Create session. session_base_t *session = session_base_t::create (io_thread, true, this, options, paddr); errno_assert (session); // PGM does not support subscription forwarding; ask for all data to be // sent to this pipe. (same for NORM, currently?) bool subscribe_to_all = protocol == "pgm" || protocol == "epgm" || protocol == "norm"; pipe_t *newpipe = NULL; if (options.immediate != 1 || subscribe_to_all) { // Create a bi-directional pipe. object_t *parents [2] = {this, session}; pipe_t *new_pipes [2] = {NULL, NULL}; bool conflate = options.conflate && (options.type == ZMQ_DEALER || options.type == ZMQ_PULL || options.type == ZMQ_PUSH || options.type == ZMQ_PUB || options.type == ZMQ_SUB); int hwms [2] = {conflate? -1 : options.sndhwm, conflate? -1 : options.rcvhwm}; bool conflates [2] = {conflate, conflate}; rc = pipepair (parents, new_pipes, hwms, conflates); errno_assert (rc == 0); // Attach local end of the pipe to the socket object. attach_pipe (new_pipes [0], subscribe_to_all); newpipe = new_pipes [0]; // Attach remote end of the pipe to the session object later on. session->attach_pipe (new_pipes [1]); } // Save last endpoint URI paddr->to_string (last_endpoint); add_endpoint (addr_, (own_t *) session, newpipe); EXIT_MUTEX(); return 0; }
int getRequest(int fd, request *req) { const char *headers[] = { "User-Agent", "Host", "Connection" }; const char *reqTypes[] = { "GET", "DELETE", "HEAD" }; req->keepAlive = 1; int n = BUFSIZ, newlines = 0, i = 0, readFirst = 1, lastline = 0, capacity, j, delim, info = 0; char buffer[BUFSIZ + 1]; char *token, *delp; if (fd < 0) return SOCKET_ERROR; n = read(fd, buffer, BUFSIZ); capacity = n; while (n > 0) { i = 0; newlines = 0; lastline = 0; while (i < capacity) { if (buffer[i] == '\r') { newlines++; lastline = i; } i++; } if (newlines == 0) goto err; if (lastline == 0) { //consNewLines++; //if(consNewLines==2) goto finish; } buffer[lastline] = '\0'; token = strtok(buffer, "\r"); while (token) { if ((*(token + 1)) == '\0') { //consNewLines++; //if(consNewLines==2) goto finish; } else { if (readFirst) { readFirst = 0; delp = strstr(token, " "); if (!delp) return METHOD_ERROR; for (j = 0; j < sizeof(reqTypes) / sizeof(char*); j++) { if (strncmp(token, reqTypes[j], (delp - token) / sizeof(char)) == 0) break; } if (j == sizeof(reqTypes) / sizeof(char*)) return METHOD_ERROR; req->type = j; token = delp + 1; delp = strstr(token, " "); if (!delp) return VERSION_ERROR; *delp = '\0'; if (strlen(token) >= MAX_DOCUMENT_LEN) return DOCUMENT_ERROR; strcpy(req->document, token); token = delp + 1; if (strcmp(token, "HTTP/1.1") != 0) return VERSION_ERROR; info = 1; } else { if ((*token) == '\n') token++; delim = -1; for (j = 0; j < strlen(token) && delim == -1; j++) if (token[j] == ':') delim = j; if (delim == -1) continue; for (j = 0; j < sizeof(headers) / sizeof(char*); j++) { if (strncmp(token, headers[j], strlen(headers[j])) == 0) break; } if (j == sizeof(headers) / sizeof(char*)) goto next; token += delim; while (!isalnum(*token)) token++; //printf("v=%s\n", token); switch (j) { case USER_AGENT: break; case HOST: break; case CONNECTION: if (strcmp(token, "close") == 0) req->keepAlive = 0; break; } //printf("Headers: %s %s\n", token, headers[j]); } } next: //printf("token: %s\n", token+((*token)=='\n'?1:0)); token = strtok(NULL, "\r"); } int nextValidChar = lastline + 2; for (i = nextValidChar; i < capacity; i++) { buffer[i - nextValidChar] = buffer[i]; } n = read(fd, buffer + capacity - nextValidChar, BUFSIZ - (capacity - nextValidChar)); capacity = n + capacity - nextValidChar; } finish: if (info == 0) return METHOD_ERROR; return OK; err: return -1; }
int main(int argc, char *argv[]) { if (argc < 4) { printf("[!] Usage: %s [IP] [port] [public_key] <nokey>\n", argv[0]); exit(0); } int c; int on = 0; initMessenger(); //if keyfiles exist if(argc > 4){ if(strncmp(argv[4], "nokey", 6) < 0){ //load_key(); } } else { load_key(); } m_callback_friendrequest(print_request); m_callback_friendmessage(print_message); m_callback_namechange(print_nickchange); m_callback_userstatus(print_statuschange); char idstring0[200]; char idstring1[32][5]; char idstring2[32][5]; uint32_t i; for(i = 0; i < 32; i++) { if(self_public_key[i] < 16) strcpy(idstring1[i],"0"); else strcpy(idstring1[i], ""); sprintf(idstring2[i], "%hhX",self_public_key[i]); } strcpy(idstring0,"[i] your ID: "); for (i=0; i<32; i++) { strcat(idstring0,idstring1[i]); strcat(idstring0,idstring2[i]); } initscr(); noecho(); raw(); getmaxyx(stdscr,y,x); new_lines(idstring0); new_lines("[i] commands: /f ID (to add friend), /m friendnumber message (to send message), /s status (to change status), /n nick (to change nickname), /q (to quit)"); strcpy(line, ""); IP_Port bootstrap_ip_port; bootstrap_ip_port.port = htons(atoi(argv[2])); int resolved_address = resolve_addr(argv[1]); if (resolved_address != -1) bootstrap_ip_port.ip.i = resolved_address; else exit(1); DHT_bootstrap(bootstrap_ip_port, hex_string_to_bin(argv[3])); nodelay(stdscr, TRUE); while(true) { if (on == 0 && DHT_isconnected()) { new_lines("[i] connected to DHT\n[i] define username with /n"); on = 1; } doMessenger(); c_sleep(1); do_refresh(); c = getch(); if (c == ERR || c == 27) continue; getmaxyx(stdscr, y, x); if (c == '\n') { line_eval(lines, line); strcpy(line, ""); } else if (c == 127) { line[strlen(line) - 1] = '\0'; } else if (isalnum(c) || ispunct(c) || c == ' ') { strcpy(line, appender(line, (char) c)); } } endwin(); return 0; }
/* Parse a string of the form FUNC(arg1,arg2,...) Returns the number of parameters or -1 on error. */ int parse_string(char *line, char **params, int max_params) { int pos; int param_start; char *next_param; int param_count; assert(line != NULL); assert(params != NULL); pos = 0; /* Parse off "function" name */ while((isalnum(line[pos])) || (line[pos] == '_')) { pos++; } /* If we don't have any thing else than this is just the function */ if(line[pos] == 0) { return 0; } if(line[pos] != '(') { snprintf(g_errstring, MAX_ERROR, "Invalid character %c, expected (", line[pos]); return -1; } /* Terminate */ line[pos++] = 0; param_start = pos; /* Scan parameters */ while((isalnum(line[pos])) || (line[pos] == '_') || (line[pos] == ',')) { pos++; } if(line[pos] == 0) { snprintf(g_errstring, MAX_ERROR, "Missing closing brace ')'"); return -1; } if(line[pos] != ')') { snprintf(g_errstring, MAX_ERROR, "Invalid character %c, expected ')'", line[pos]); return -1; } if(line[pos+1] != 0) { snprintf(g_errstring, MAX_ERROR, "Trailing characters after bracket close %d", line[pos+1]); return -1; } line[pos] = 0; param_count = 0; next_param = strtok(&line[param_start], ","); while(next_param != NULL) { if(param_count == max_params) { snprintf(g_errstring, MAX_ERROR, "Run out of space for parameters"); return -1; } params[param_count++] = next_param; next_param = strtok(NULL, ","); } return param_count; }
static inline int iskeychar(int c) { return isalnum(c) || c == '-'; }
/* 0 failure, 1 success */ static int regmatch(regex_t *preg, int prog) { int scan; /* Current node. */ int next; /* Next node. */ scan = prog; #ifdef DEBUG if (scan != 0 && regnarrate) fprintf(stderr, "%s(\n", regprop(scan)); #endif while (scan != 0) { int n; int c; #ifdef DEBUG if (regnarrate) { fprintf(stderr, "%3d: %s...\n", scan, regprop(OP(preg, scan))); /* Where, what. */ } #endif next = regnext(preg, scan); n = reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE)); switch (OP(preg, scan)) { case BOL: if (preg->reginput != preg->regbol) return(0); break; case EOL: if (!reg_iseol(preg, c)) { return(0); } break; case WORDA: /* Must be looking at a letter, digit, or _ */ if ((!isalnum(UCHAR(c))) && c != '_') return(0); /* Prev must be BOL or nonword */ if (preg->reginput > preg->regbol && (isalnum(UCHAR(preg->reginput[-1])) || preg->reginput[-1] == '_')) return(0); break; case WORDZ: /* Can't match at BOL */ if (preg->reginput > preg->regbol) { /* Current must be EOL or nonword */ if (reg_iseol(preg, c) || !isalnum(UCHAR(c)) || c != '_') { c = preg->reginput[-1]; /* Previous must be word */ if (isalnum(UCHAR(c)) || c == '_') { break; } } } /* No */ return(0); case ANY: if (reg_iseol(preg, c)) return 0; preg->reginput += n; break; case EXACTLY: { int opnd; int len; int slen; opnd = OPERAND(scan); len = str_int_len(preg->program + opnd); slen = prefix_cmp(preg->program + opnd, len, preg->reginput, preg->cflags & REG_ICASE); if (slen < 0) { return(0); } preg->reginput += slen; } break; case ANYOF: if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) == 0) { return(0); } preg->reginput += n; break; case ANYBUT: if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) != 0) { return(0); } preg->reginput += n; break; case NOTHING: break; case BACK: break; case BRANCH: { const char *save; if (OP(preg, next) != BRANCH) /* No choice. */ next = OPERAND(scan); /* Avoid recursion. */ else { do { save = preg->reginput; if (regmatch(preg, OPERAND(scan))) { return(1); } preg->reginput = save; scan = regnext(preg, scan); } while (scan != 0 && OP(preg, scan) == BRANCH); return(0); /* NOTREACHED */ } } break; case REP: case REPMIN: return regmatchsimplerepeat(preg, scan, OP(preg, scan) == REPMIN); case REPX: case REPXMIN: return regmatchrepeat(preg, scan, OP(preg, scan) == REPXMIN); case END: return(1); /* Success! */ break; case OPENNC: case CLOSENC: if (regmatch(preg, next)) { return 1; } return 0; default: if (OP(preg, scan) >= OPEN+1 && OP(preg, scan) < CLOSE_END) { const char *save; save = preg->reginput; if (regmatch(preg, next)) { int no; /* * Don't set startp if some later * invocation of the same parentheses * already has. */ if (OP(preg, scan) < CLOSE) { no = OP(preg, scan) - OPEN; if (no < preg->nmatch && preg->pmatch[no].rm_so == -1) { preg->pmatch[no].rm_so = save - preg->start; } } else { no = OP(preg, scan) - CLOSE; if (no < preg->nmatch && preg->pmatch[no].rm_eo == -1) { preg->pmatch[no].rm_eo = save - preg->start; } } return(1); } else return(0); } return REG_ERR_INTERNAL; } scan = next; } /* * We get here only if there's trouble -- normally "case END" is * the terminating point. */ return REG_ERR_INTERNAL; }
void AsMixedCaseToUnderscores ( char *Buffer, char *Filename) { UINT32 Length; char *SubBuffer = Buffer; char *TokenEnd; char *TokenStart = NULL; char *SubString; UINT32 LineNumber = 1; UINT32 Count; /* * Examine the entire buffer (contains the entire file) * We are only interested in these tokens: * Escape sequences - ignore entire sequence * Single-quoted constants - ignore * Quoted strings - ignore entire string * Translation escape - starts with /,*,! * Decimal and hex numeric constants - ignore entire token * Entire uppercase token - ignore, it is a macro or define * Starts with underscore, then a lowercase or digit: convert */ while (*SubBuffer) { if (*SubBuffer == '\n') { LineNumber++; SubBuffer++; continue; } /* Ignore standard escape sequences (\n, \r, etc.) Not Hex or Octal escapes */ if (*SubBuffer == '\\') { SubBuffer += 2; continue; } /* Ignore single-quoted characters */ if (*SubBuffer == '\'') { SubBuffer += 3; continue; } /* Ignore standard double-quoted strings */ if (*SubBuffer == '"') { SubBuffer++; Count = 0; while (*SubBuffer != '"') { Count++; if ((!*SubBuffer) || (Count > 8192)) { printf ("Found an unterminated quoted string!, line %u: %s\n", LineNumber, Filename); return; } /* Handle escape sequences */ if (*SubBuffer == '\\') { SubBuffer++; } SubBuffer++; } SubBuffer++; continue; } /* * Check for translation escape string. It means to ignore * blocks of code during this code conversion. */ if ((SubBuffer[0] == '/') && (SubBuffer[1] == '*') && (SubBuffer[2] == '!')) { SubBuffer = strstr (SubBuffer, "!*/"); if (!SubBuffer) { printf ("Found an unterminated translation escape!, line %u: %s\n", LineNumber, Filename); return; } continue; } /* Ignore anything that starts with a number (0-9) */ if (isdigit ((int) *SubBuffer)) { /* Ignore hex constants */ if ((SubBuffer[0] == '0') && ((SubBuffer[1] == 'x') || (SubBuffer[1] == 'X'))) { SubBuffer += 2; } /* Skip over all digits, both decimal and hex */ while (isxdigit ((int) *SubBuffer)) { SubBuffer++; } TokenStart = NULL; continue; } /* * Check for fully upper case identifiers. These are usually macros * or defines. Allow decimal digits and embedded underscores. */ if (isupper ((int) *SubBuffer)) { SubString = SubBuffer + 1; while ((isupper ((int) *SubString)) || (isdigit ((int) *SubString)) || (*SubString == '_')) { SubString++; } /* * For the next character, anything other than a lower case * means that the identifier has terminated, and contains * exclusively Uppers/Digits/Underscores. Ignore the entire * identifier. */ if (!islower ((int) *SubString)) { SubBuffer = SubString + 1; continue; } } /* * These forms may indicate an identifier that can be converted: * <UpperCase><LowerCase> (Ax) * <UpperCase><Number> (An) */ if (isupper ((int) SubBuffer[0]) && ((islower ((int) SubBuffer[1])) || isdigit ((int) SubBuffer[1]))) { TokenStart = SubBuffer; SubBuffer++; while (1) { /* Walk over the lower case letters and decimal digits */ while (islower ((int) *SubBuffer) || isdigit ((int) *SubBuffer)) { SubBuffer++; } /* Check for end of line or end of token */ if (*SubBuffer == '\n') { LineNumber++; break; } if (*SubBuffer == ' ') { /* Check for form "Axx - " in a parameter header description */ while (*SubBuffer == ' ') { SubBuffer++; } SubBuffer--; if ((SubBuffer[1] == '-') && (SubBuffer[2] == ' ')) { if (TokenStart) { *TokenStart = (char) tolower ((int) *TokenStart); } } break; } /* * Ignore these combinations: * <Letter><Digit><UpperCase> * <Digit><Digit><UpperCase> * <Underscore><Digit><UpperCase> */ if (isdigit ((int) *SubBuffer)) { if (isalnum ((int) *(SubBuffer-1)) || *(SubBuffer-1) == '_') { break; } } /* Ignore token if next character is not uppercase or digit */ if (!isupper ((int) *SubBuffer) && !isdigit ((int) *SubBuffer)) { break; } /* * Form <UpperCase><LowerCaseLetters><UpperCase> (AxxB): * Convert leading character of the token to lower case */ if (TokenStart) { *TokenStart = (char) tolower ((int) *TokenStart); TokenStart = NULL; } /* Find the end of this identifier (token) */ TokenEnd = SubBuffer - 1; while ((isalnum ((int) *TokenEnd)) || (*TokenEnd == '_')) { TokenEnd++; } SubString = TokenEnd; Length = 0; while (*SubString != '\n') { /* * If we have at least two trailing spaces, we can get rid of * one to make up for the newly inserted underscore. This will * help preserve the alignment of the text */ if ((SubString[0] == ' ') && (SubString[1] == ' ')) { Length = SubString - SubBuffer - 1; break; } SubString++; } if (!Length) { Length = strlen (&SubBuffer[0]); } /* * Within this identifier, convert this pair of letters that * matches the form: * * <LowerCase><UpperCase> * to * <LowerCase><Underscore><LowerCase> */ Gbl_MadeChanges = TRUE; /* Insert the underscore */ memmove (&SubBuffer[1], &SubBuffer[0], Length + 1); SubBuffer[0] = '_'; /* * If we have <UpperCase><UpperCase>, leave them as-is * Enables transforms like: * LocalFADT -> local_FADT */ if (isupper ((int) SubBuffer[2])) { SubBuffer += 1; break; } /* Lower case the original upper case letter */ SubBuffer[1] = (char) tolower ((int) SubBuffer[1]); SubBuffer += 2; } } SubBuffer++; } }
/* This routine will expand the pathname to account for ~ and $ * characters as described above. Returns a pointer to a newly * malloc'd string. If an error occurs, an error message is printed * via error() and NULL is returned. FILE and LINE are the filename * and linenumber to include in the error message. FILE must point * to something; LINE can be zero to indicate the line number is not * known. * * When FORMATSAFE is set, percent signs (`%') in variable contents are doubled * to prevent later expansion by format_cmdline. * * CVSROOT is used to expanding $CVSROOT. */ char * expand_path (const char *name, const char *cvsroot, bool formatsafe, const char *file, int line) { size_t s, d, p; const char *e; char *mybuf = NULL; size_t mybuf_size = 0; char *buf = NULL; size_t buf_size = 0; char inquotes = '\0'; char *result; /* Sorry this routine is so ugly; it is a head-on collision between the `traditional' unix *d++ style and the need to dynamically allocate. It would be much cleaner (and probably faster, not that this is a bottleneck for CVS) with more use of strcpy & friends, but I haven't taken the effort to rewrite it thusly. */ /* First copy from NAME to MYBUF, expanding $<foo> as we go. */ s = d = 0; expand_string (&mybuf, &mybuf_size, d + 1); while ((mybuf[d++] = name[s]) != '\0') { if (name[s] == '\\') { /* The next character is a literal. Leave the \ in the string * since it will be needed again when the string is split into * arguments. */ /* if we have a \ as the last character of the string, just leave * it there - this is where we would set the escape flag to tell * our parent we want another line if we cared. */ if (name[++s]) { expand_string (&mybuf, &mybuf_size, d + 1); mybuf[d++] = name[s++]; } } /* skip $ variable processing for text inside single quotes */ else if (inquotes == '\'') { if (name[s++] == '\'') { inquotes = '\0'; } } else if (name[s] == '\'') { s++; inquotes = '\''; } else if (name[s] == '"') { s++; if (inquotes) inquotes = '\0'; else inquotes = '"'; } else if (name[s++] == '$') { int flag = (name[s] == '{'); p = d; expand_string (&mybuf, &mybuf_size, d + 1); for (; (mybuf[d++] = name[s]); s++) { if (flag ? name[s] =='}' : !isalnum (name[s]) && name[s] != '_') break; expand_string (&mybuf, &mybuf_size, d + 1); } mybuf[--d] = '\0'; e = expand_variable (&mybuf[p+flag], cvsroot, file, line); if (e) { expand_string (&mybuf, &mybuf_size, d + 1); for (d = p - 1; (mybuf[d++] = *e++); ) { expand_string (&mybuf, &mybuf_size, d + 1); if (mybuf[d-1] == '"') { /* escape the double quotes if we're between a matched * pair of double quotes so that this sub will be * passed inside as or as part of a single argument * during the argument split later. */ if (inquotes) { mybuf[d-1] = '\\'; expand_string (&mybuf, &mybuf_size, d + 1); mybuf[d++] = '"'; } } else if (formatsafe && mybuf[d-1] == '%') { /* escape '%' to get past printf style format strings * later (in make_cmdline). */ expand_string (&mybuf, &mybuf_size, d + 1); mybuf[d] = '%'; d++; } } --d; if (flag && name[s]) s++; } else /* expand_variable has already printed an error message. */ goto error_exit; } expand_string (&mybuf, &mybuf_size, d + 1); } expand_string (&mybuf, &mybuf_size, d + 1); mybuf[d] = '\0'; /* Then copy from MYBUF to BUF, expanding ~. */ s = d = 0; /* If you don't want ~username ~/ to be expanded simply remove * This entire if statement including the else portion */ if (mybuf[s] == '~') { p = d; while (mybuf[++s] != '/' && mybuf[s] != '\0') { expand_string (&buf, &buf_size, p + 1); buf[p++] = name[s]; } expand_string (&buf, &buf_size, p + 1); buf[p] = '\0'; if (p == d) e = get_homedir (); else { #ifdef GETPWNAM_MISSING if (line) error (0, 0, "%s:%d:tilde expansion not supported on this system", file, line); else error (0, 0, "%s:tilde expansion not supported on this system", file); goto error_exit; #else struct passwd *ps; ps = getpwnam (buf + d); if (ps == NULL) { if (line) error (0, 0, "%s:%d: no such user %s", file, line, buf + d); else error (0, 0, "%s: no such user %s", file, buf + d); goto error_exit; } e = ps->pw_dir; #endif } if (!e) error (1, 0, "cannot find home directory"); p = strlen (e); expand_string (&buf, &buf_size, d + p); memcpy (buf + d, e, p); d += p; } /* Kill up to here */ p = strlen (mybuf + s) + 1; expand_string (&buf, &buf_size, d + p); memcpy (buf + d, mybuf + s, p); /* OK, buf contains the value we want to return. Clean up and return it. */ free (mybuf); /* Save a little memory with xstrdup; buf will tend to allocate more than it needs to. */ result = xstrdup (buf); free (buf); return result; error_exit: if (mybuf) free (mybuf); if (buf) free (buf); return NULL; }
static int getToken() { const char tab[] = "abfnrtv"; const char backTab[] = "\a\b\f\n\r\t\v"; uint n; yyIdentLen = 0; yyCommentLen = 0; yyStringLen = 0; while ( yyCh != EOF ) { yyLineNo = yyCurLineNo; if ( isalpha(yyCh) || yyCh == '_' ) { do { if ( yyIdentLen < sizeof(yyIdent) - 1 ) yyIdent[yyIdentLen++] = (char) yyCh; yyCh = getChar(); } while ( isalnum(yyCh) || yyCh == '_' ); yyIdent[yyIdentLen] = '\0'; switch ( yyIdent[0] ) { case 'Q': if ( strcmp(yyIdent + 1, "_OBJECT") == 0 ) { return Tok_Q_OBJECT; } else if ( strcmp(yyIdent + 1, "T_TR_NOOP") == 0 ) { return Tok_tr; } else if ( strcmp(yyIdent + 1, "T_TRANSLATE_NOOP") == 0 ) { return Tok_translate; } break; case 'T': // TR() for when all else fails if ( qstricmp(yyIdent + 1, "R") == 0 ) return Tok_tr; break; case 'c': if ( strcmp(yyIdent + 1, "lass") == 0 ) return Tok_class; break; case 'f': /* QTranslator::findMessage() has the same parameters as QApplication::translate(). */ if ( strcmp(yyIdent + 1, "indMessage") == 0 ) return Tok_translate; break; case 'n': if ( strcmp(yyIdent + 1, "amespace") == 0 ) return Tok_namespace; break; case 'r': if ( strcmp(yyIdent + 1, "eturn") == 0 ) return Tok_return; break; case 's': if ( strcmp(yyIdent + 1, "truct") == 0 ) return Tok_class; break; case 't': if ( strcmp(yyIdent + 1, "r") == 0 ) { return Tok_tr; } else if ( qstrcmp(yyIdent + 1, "rUtf8") == 0 ) { return Tok_trUtf8; } else if ( qstrcmp(yyIdent + 1, "ranslate") == 0 ) { return Tok_translate; } } return Tok_Ident; } else { switch ( yyCh ) { case '#': /* Early versions of lupdate complained about unbalanced braces in the following code: #ifdef ALPHA while ( beta ) { #else while ( gamma ) { #endif delta; } The code contains, indeed, two opening braces for one closing brace; yet there's no reason to panic. The solution is to remember yyBraceDepth as it was when #if, #ifdef or #ifndef was met, and to set yyBraceDepth to that value when meeting #elif or #else. */ do { yyCh = getChar(); } while ( isspace(yyCh) && yyCh != '\n' ); switch ( yyCh ) { case 'i': yyCh = getChar(); if ( yyCh == 'f' ) { // if, ifdef, ifndef yySavedBraceDepth.push( yyBraceDepth ); yySavedParenDepth.push( yyParenDepth ); } break; case 'e': yyCh = getChar(); if ( yyCh == 'l' ) { // elif, else if ( !yySavedBraceDepth.isEmpty() ) { yyBraceDepth = yySavedBraceDepth.top(); yyParenDepth = yySavedParenDepth.top(); } } else if ( yyCh == 'n' ) { // endif if ( !yySavedBraceDepth.isEmpty() ) { yySavedBraceDepth.pop(); yySavedParenDepth.pop(); } } } while ( isalnum(yyCh) || yyCh == '_' ) yyCh = getChar(); break; case '/': yyCh = getChar(); if ( yyCh == '/' ) { do { yyCh = getChar(); } while ( yyCh != EOF && yyCh != '\n' ); } else if ( yyCh == '*' ) { bool metAster = FALSE; bool metAsterSlash = FALSE; while ( !metAsterSlash ) { yyCh = getChar(); if ( yyCh == EOF ) { fprintf( stderr, "%s: Unterminated C++ comment starting at" " line %d\n", (const char *) yyFileName, yyLineNo ); yyComment[yyCommentLen] = '\0'; return Tok_Comment; } if ( yyCommentLen < sizeof(yyComment) - 1 ) yyComment[yyCommentLen++] = (char) yyCh; if ( yyCh == '*' ) metAster = TRUE; else if ( metAster && yyCh == '/' ) metAsterSlash = TRUE; else metAster = FALSE; } yyCh = getChar(); yyCommentLen -= 2; yyComment[yyCommentLen] = '\0'; return Tok_Comment; } break; case '"': yyCh = getChar(); while ( yyCh != EOF && yyCh != '\n' && yyCh != '"' ) { if ( yyCh == '\\' ) { yyCh = getChar(); if ( yyCh == '\n' ) { yyCh = getChar(); } else if ( yyCh == 'x' ) { QCString hex = "0"; yyCh = getChar(); while ( isxdigit(yyCh) ) { hex += (char) yyCh; yyCh = getChar(); } sscanf( hex, "%x", &n ); if ( yyStringLen < sizeof(yyString) - 1 ) yyString[yyStringLen++] = (char) n; } else if ( yyCh >= '0' && yyCh < '8' ) { QCString oct = ""; do { oct += (char) yyCh; yyCh = getChar(); } while ( yyCh >= '0' && yyCh < '8' ); sscanf( oct, "%o", &n ); if ( yyStringLen < sizeof(yyString) - 1 ) yyString[yyStringLen++] = (char) n; } else { const char *p = strchr( tab, yyCh ); if ( yyStringLen < sizeof(yyString) - 1 ) yyString[yyStringLen++] = ( p == 0 ) ? (char) yyCh : backTab[p - tab]; yyCh = getChar(); } } else { if ( yyStringLen < sizeof(yyString) - 1 ) yyString[yyStringLen++] = (char) yyCh; yyCh = getChar(); } } yyString[yyStringLen] = '\0'; if ( yyCh != '"' ) qWarning( "%s:%d: Unterminated C++ string", (const char *) yyFileName, yyLineNo ); if ( yyCh == EOF ) { return Tok_Eof; } else { yyCh = getChar(); return Tok_String; } break; case '-': yyCh = getChar(); if ( yyCh == '>' ) { yyCh = getChar(); return Tok_Arrow; } break; case ':': yyCh = getChar(); if ( yyCh == ':' ) { yyCh = getChar(); return Tok_Gulbrandsen; } return Tok_Colon; case '\'': yyCh = getChar(); if ( yyCh == '\\' ) yyCh = getChar(); do { yyCh = getChar(); } while ( yyCh != EOF && yyCh != '\'' ); yyCh = getChar(); break; case '{': if (yyBraceDepth == 0) yyBraceLineNo = yyCurLineNo; yyBraceDepth++; yyCh = getChar(); return Tok_LeftBrace; case '}': if (yyBraceDepth == 0) yyBraceLineNo = yyCurLineNo; yyBraceDepth--; 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_Semicolon; default: yyCh = getChar(); } } } return Tok_Eof; }
static char* ConsumeAttribute( const char** ppsz_subtitle, char** psz_attribute_value ) { const char* psz_subtitle = *ppsz_subtitle; char* psz_attribute_name; while (*psz_subtitle == ' ') psz_subtitle++; size_t attr_len = 0; char delimiter; while ( *psz_subtitle && isalpha( *psz_subtitle ) ) { psz_subtitle++; attr_len++; } if ( !*psz_subtitle || attr_len == 0 ) return NULL; psz_attribute_name = malloc( attr_len + 1 ); if ( unlikely( !psz_attribute_name ) ) return NULL; strncpy( psz_attribute_name, psz_subtitle - attr_len, attr_len ); psz_attribute_name[attr_len] = 0; // Skip over to the attribute value while ( *psz_subtitle && *psz_subtitle != '=' ) psz_subtitle++; // Skip the '=' sign psz_subtitle++; // Aknoledge the delimiter if any while ( *psz_subtitle && isspace( *psz_subtitle) ) psz_subtitle++; if ( *psz_subtitle == '\'' || *psz_subtitle == '"' ) { // Save the delimiter and skip it delimiter = *psz_subtitle; psz_subtitle++; } else delimiter = 0; // Skip spaces, just in case while ( *psz_subtitle && isspace( *psz_subtitle ) ) psz_subtitle++; attr_len = 0; while ( *psz_subtitle && ( ( delimiter != 0 && *psz_subtitle != delimiter ) || ( delimiter == 0 && ( isalnum( *psz_subtitle ) || *psz_subtitle == '#' ) ) ) ) { psz_subtitle++; attr_len++; } if ( unlikely( !( *psz_attribute_value = malloc( attr_len + 1 ) ) ) ) { free( psz_attribute_name ); return NULL; } strncpy( *psz_attribute_value, psz_subtitle - attr_len, attr_len ); (*psz_attribute_value)[attr_len] = 0; // Finally, skip over the final delimiter if (delimiter != 0 && *psz_subtitle) psz_subtitle++; *ppsz_subtitle = psz_subtitle; return psz_attribute_name; }
/* Parse the key and value from a memory buffer. */ char *hcfg_parse(char *buf, char **key, char **val) { char *ptr = NULL; *key = NULL; *val = NULL; /* Skip leading key whitespace. */ while (isspace(*buf) && *buf != '\n') ++buf; /* Skip empty lines and comments. */ if (*buf == '\n' || *buf == '#') goto endline; if (!isalnum(*buf) && *buf != '_') return NULL; /* Force key strings to be uppercase. */ *key = buf; while (isalnum(*buf) || *buf == '_') { *buf = toupper(*buf); ++buf; } /* Check that key string was valid. */ ptr = buf; while (isspace(*buf) && *buf != '\n') ++buf; if (*(buf++) != '=') return NULL; while (isspace(*buf) && *buf != '\n') ++buf; /* Kill whitespace and separator between key and value. */ while (ptr < buf) *(ptr++) = '\0'; /* Unquote the value string. */ *val = buf; ptr = buf; while (*buf && *buf != '\n') { if (*buf == '#') goto endline; if (*buf == '\\') ++buf; *(ptr++) = *(buf++); } endline: buf += strcspn(buf, "\n"); if (*buf == '\n') ++buf; /* Kill trailing value whitespace. */ if (ptr) { do *(ptr--) = '\0'; while (isspace(*ptr)); } return buf; }
/** * Parses makeFileName based on GNU 'make' utility. * * @param makeFileName Path to valid makefile. * @param run_targets Null-terminated list of targets as listed on command-line. * @param parsed_new_target Function pointer to callback function for new target. * @param parsed_new_dependency Function pointer to callback function for new dependency. * @param parsed_new_command Function pointer to callback function for new command. * @return Void. */ void parser_parse_makefile ( const char *makeFileName, char **run_targets, void (*parsed_new_target)(char *target), void (*parsed_new_dependency)(char *target, char *dependency), void (*parsed_new_command)(char *target, char *command) ) { boolean run_targetsMalloced = False; FILE *f = fopen(makeFileName, "r"); assert(f != NULL); queue_t *rules = malloc(sizeof(queue_t)); queue_init(rules); queue_t curRules; queue_init(&curRules); char *lineBuf = NULL; size_t bytes; size_t len; while((len = getline(&lineBuf, &bytes, f)) != -1){ if(len && lineBuf[len-1] == '\n'){ lineBuf[--len] = '\0'; if(len && lineBuf[len-1] == '\r') lineBuf[--len] = '\0'; } if(isalnum(lineBuf[0])){ char *depLine = strstr(lineBuf, ":"); assert(depLine != NULL); depLine[0] = '\0'; depLine = depLine + 1; //insert prev Rule to queue int ruleIdx; for(ruleIdx=0; ruleIdx < queue_size(&curRules); ruleIdx++){ queue_enqueue(rules, queue_at(&curRules,ruleIdx)); } queue_destroy(&curRules); queue_init(&curRules); char **targets = parse_line(lineBuf); int tarIdx; for(tarIdx=0; targets[tarIdx] != NULL; tarIdx++){ rule_t *newRule = malloc(sizeof(rule_t)); rule_init(newRule); char *target = strdup(targets[tarIdx]); newRule->target = target; queue_enqueue(&curRules, newRule); } if(run_targets == NULL || run_targets[0] == NULL){ run_targetsMalloced = True; run_targets = calloc(sizeof(char *), tarIdx + 1); int rtIdx; for(rtIdx=0; rtIdx < tarIdx; rtIdx++) run_targets[rtIdx] = strdup(targets[rtIdx]); } free(targets); char **deps = parse_line(depLine); int depIdx; for(depIdx=0; deps[depIdx] != NULL; depIdx++){ int ruleIdx; for(ruleIdx=0; ruleIdx < queue_size(&curRules); ruleIdx++){ rule_t *curRule = queue_at(&curRules, ruleIdx); char *dep = strdup(deps[depIdx]); queue_enqueue(curRule->deps, dep); } } free(deps); } else if(lineBuf[0] == '\t') { assert(queue_size(&curRules) != 0); //command without target int idx; for(idx=0; idx < queue_size(&curRules); idx++){ rule_t *curRule = queue_at(&curRules, idx); char *command = strdup(lineBuf + 1); queue_enqueue(curRule->commands, command); } }else { ;//ignore line } } int ruleIdx; for(ruleIdx=0; ruleIdx < queue_size(&curRules); ruleIdx++){ queue_enqueue(rules, queue_at(&curRules, ruleIdx)); } queue_destroy(&curRules); //No longer need curRules filterOnTargets(&rules, run_targets); //send callbacks notifyRules(rules, parsed_new_target, parsed_new_dependency, parsed_new_command); //cleanup queue_iterate(rules, rule_free_adapter, 0); queue_destroy(rules); if(run_targetsMalloced){ int tarIdx; for(tarIdx=0; run_targets[tarIdx] != NULL; tarIdx++) free(run_targets[tarIdx]); free(run_targets); } free(lineBuf); free(rules); fclose(f); }
/* detection functions */ int rule15125eval(void *p) { const uint8_t *cursor_normal = 0; SFSnortPacket *sp = (SFSnortPacket *) p; const uint8_t *end_of_payload; dpgroupcount *dpCount; DEBUG_WRAP(printf("rule15125eval enter\n")); if((sp == NULL) || (sp->stream_session_ptr == NULL)) return RULE_NOMATCH; if(sp->payload == NULL) return RULE_NOMATCH; // flow:established, to_client; if(checkFlow(p, rule15125options[0]->option_u.flowFlags) <= 0) return RULE_NOMATCH; DEBUG_WRAP(printf("rule15125eval flow match\n")); // Since "group" is in the fast pattern matcher, we want to quickly make sure // that either \dpgroup or \dpendgroup is in the packet so we can drop out // before getting into the more intense detection algorithm. // content:"|5C|dp", nocase; if(contentMatch(p, rule15125options[1]->option_u.content, &cursor_normal) > 0) { // content:"group", depth 8, nocase, relative; if(contentMatch(p, rule15125options[2]->option_u.content, &cursor_normal) <= 0) return RULE_NOMATCH; } // Get-store-initialize session data dpCount = (dpgroupcount *)getRuleData(sp, (uint32_t)rule15125.info.sigID); if(!dpCount) { dpCount = (dpgroupcount *)allocRuleData(sizeof(dpgroupcount)); if (dpCount == NULL) return RULE_NOMATCH; if(storeRuleData(sp, dpCount, rule15125.info.sigID, &freeRuleData) < 0) { freeRuleData(dpCount); return RULE_NOMATCH; } dpCount->groupTally = 0; } DEBUG_WRAP(printf("rule15125eval dpCount=0x%p\n", (void*)dpCount)); // Reset cursor to beginning of payload if(getBuffer(sp, CONTENT_BUF_NORMALIZED, &cursor_normal, &end_of_payload) <= 0) return RULE_NOMATCH; // Main matching loop for "|5C|d" while(contentMatch(p, rule15125options[5]->option_u.content, &cursor_normal) > 0) { if(cursor_normal + 2 >= end_of_payload) return RULE_NOMATCH; // If entering a /do statement, reset counter if(*cursor_normal == 'o') { if(!isalnum(*(cursor_normal+1))) { dpCount->groupTally = 0; } // Match on "pgroup" within 6 then increment count } else if(contentMatch(p, rule15125options[3]->option_u.content, &cursor_normal) > 0) { dpCount->groupTally++; // Match on "pendgroup" within 9 then decrement count; fire if count is ever negative } else if(contentMatch(p, rule15125options[4]->option_u.content, &cursor_normal) > 0) { dpCount->groupTally--; if(dpCount->groupTally < 0) return RULE_MATCH; } DEBUG_WRAP(printf("rule15125eval dpCount->groupTally=%d\n", dpCount->groupTally)); } return RULE_NOMATCH; }
void AsUppercaseTokens ( char *Buffer, char *PrefixString) { char *SubBuffer; char *TokenEnd; char *SubString; int i; UINT32 Length; SubBuffer = Buffer; while (SubBuffer) { SubBuffer = strstr (SubBuffer, PrefixString); if (SubBuffer) { TokenEnd = SubBuffer; while ((isalnum ((int) *TokenEnd)) || (*TokenEnd == '_')) { TokenEnd++; } for (i = 0; i < (TokenEnd - SubBuffer); i++) { if ((islower ((int) SubBuffer[i])) && (isupper ((int) SubBuffer[i+1]))) { SubString = TokenEnd; Length = 0; while (*SubString != '\n') { if ((SubString[0] == ' ') && (SubString[1] == ' ')) { Length = SubString - &SubBuffer[i] - 2; break; } SubString++; } if (!Length) { Length = strlen (&SubBuffer[i+1]); } memmove (&SubBuffer[i+2], &SubBuffer[i+1], (Length+1)); SubBuffer[i+1] = '_'; i +=2; TokenEnd++; } } for (i = 0; i < (TokenEnd - SubBuffer); i++) { SubBuffer[i] = (char) toupper ((int) SubBuffer[i]); } SubBuffer = TokenEnd; } } }
static int tok_get(register struct tok_state *tok, char **p_start, char **p_end) { register int c; int blankline; *p_start = *p_end = NULL; nextline: tok->start = NULL; blankline = 0; /* Get indentation level */ if (tok->atbol) { register int col = 0; register int altcol = 0; tok->atbol = 0; for (;;) { c = tok_nextc(tok); if (c == ' ') col++, altcol++; else if (c == '\t') { col = (col/tok->tabsize + 1) * tok->tabsize; altcol = (altcol/tok->alttabsize + 1) * tok->alttabsize; } else if (c == '\014') /* Control-L (formfeed) */ col = altcol = 0; /* For Emacs users */ else break; } tok_backup(tok, c); if (c == '#' || c == '\n') { /* Lines with only whitespace and/or comments shouldn't affect the indentation and are not passed to the parser as NEWLINE tokens, except *totally* empty lines in interactive mode, which signal the end of a command group. */ if (col == 0 && c == '\n' && tok->prompt != NULL) blankline = 0; /* Let it through */ else blankline = 1; /* Ignore completely */ /* We can't jump back right here since we still may need to skip to the end of a comment */ } if (!blankline && tok->level == 0) { if (col == tok->indstack[tok->indent]) { /* No change */ if (altcol != tok->altindstack[tok->indent]) { if (indenterror(tok)) return ERRORTOKEN; } } else if (col > tok->indstack[tok->indent]) { /* Indent -- always one */ if (tok->indent+1 >= MAXINDENT) { tok->done = E_TOODEEP; tok->cur = tok->inp; return ERRORTOKEN; } if (altcol <= tok->altindstack[tok->indent]) { if (indenterror(tok)) return ERRORTOKEN; } tok->pendin++; tok->indstack[++tok->indent] = col; tok->altindstack[tok->indent] = altcol; } else /* col < tok->indstack[tok->indent] */ { /* Dedent -- any number, must be consistent */ while (tok->indent > 0 && col < tok->indstack[tok->indent]) { tok->pendin--; tok->indent--; } if (col != tok->indstack[tok->indent]) { tok->done = E_DEDENT; tok->cur = tok->inp; return ERRORTOKEN; } if (altcol != tok->altindstack[tok->indent]) { if (indenterror(tok)) return ERRORTOKEN; } } } } tok->start = tok->cur; /* Return pending indents/dedents */ if (tok->pendin != 0) { if (tok->pendin < 0) { tok->pendin++; return DEDENT; } else { tok->pendin--; return INDENT; } } again: tok->start = NULL; /* Skip spaces */ do { c = tok_nextc(tok); } while (c == ' ' || c == '\t' || c == '\014'); /* Set start of current token */ tok->start = tok->cur - 1; /* Skip comment, while looking for tab-setting magic */ if (c == '#') { static char *tabforms[] = { "tab-width:", /* Emacs */ ":tabstop=", /* vim, full form */ ":ts=", /* vim, abbreviated form */ "set tabsize=", /* will vi never die? */ /* more templates can be added here to support other editors */ }; char cbuf[80]; char *tp, **cp; tp = cbuf; do { *tp++ = c = tok_nextc(tok); } while (c != EOF && c != '\n' && (size_t)(tp - cbuf + 1) < sizeof(cbuf)); *tp = '\0'; for (cp = tabforms; cp < tabforms + sizeof(tabforms)/sizeof(tabforms[0]); cp++) { if ((tp = strstr(cbuf, *cp))) { int newsize = atoi(tp + strlen(*cp)); if (newsize >= 1 && newsize <= 40) { tok->tabsize = newsize; if (Py_VerboseFlag) PySys_WriteStderr( "Tab size set to %d\n", newsize); } } } while (c != EOF && c != '\n') c = tok_nextc(tok); } /* Check for EOF and errors now */ if (c == EOF) { return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; } /* Identifier (most frequent token!) */ if (isalpha(c) || c == '_') { /* Process r"", u"" and ur"" */ switch (c) { case 'b': case 'B': c = tok_nextc(tok); if (c == 'r' || c == 'R') c = tok_nextc(tok); if (c == '"' || c == '\'') goto letter_quote; break; case 'r': case 'R': c = tok_nextc(tok); if (c == '"' || c == '\'') goto letter_quote; break; case 'u': case 'U': c = tok_nextc(tok); if (c == 'r' || c == 'R') c = tok_nextc(tok); if (c == '"' || c == '\'') goto letter_quote; break; } while (isalnum(c) || c == '_') { c = tok_nextc(tok); } tok_backup(tok, c); *p_start = tok->start; *p_end = tok->cur; return NAME; } /* Newline */ if (c == '\n') { tok->atbol = 1; if (blankline || tok->level > 0) goto nextline; *p_start = tok->start; *p_end = tok->cur - 1; /* Leave '\n' out of the string */ tok->cont_line = 0; return NEWLINE; } /* Period or number starting with period? */ if (c == '.') { c = tok_nextc(tok); if (isdigit(c)) { goto fraction; } else { tok_backup(tok, c); *p_start = tok->start; *p_end = tok->cur; return DOT; } } /* Number */ if (isdigit(c)) { if (c == '0') { /* Hex, octal or binary -- maybe. */ c = tok_nextc(tok); if (c == '.') goto fraction; #ifndef WITHOUT_COMPLEX if (c == 'j' || c == 'J') goto imaginary; #endif if (c == 'x' || c == 'X') { /* Hex */ c = tok_nextc(tok); if (!isxdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while (isxdigit(c)); } else if (c == 'o' || c == 'O') { /* Octal */ c = tok_nextc(tok); if (c < '0' || c >= '8') { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while ('0' <= c && c < '8'); } else if (c == 'b' || c == 'B') { /* Binary */ c = tok_nextc(tok); if (c != '0' && c != '1') { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while (c == '0' || c == '1'); } else { int found_decimal = 0; /* Octal; c is first char of it */ /* There's no 'isoctdigit' macro, sigh */ while ('0' <= c && c < '8') { c = tok_nextc(tok); } if (isdigit(c)) { found_decimal = 1; do { c = tok_nextc(tok); } while (isdigit(c)); } if (c == '.') goto fraction; else if (c == 'e' || c == 'E') goto exponent; #ifndef WITHOUT_COMPLEX else if (c == 'j' || c == 'J') goto imaginary; #endif else if (found_decimal) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } if (c == 'l' || c == 'L') c = tok_nextc(tok); } else { /* Decimal */ do { c = tok_nextc(tok); } while (isdigit(c)); if (c == 'l' || c == 'L') c = tok_nextc(tok); else { /* Accept floating point numbers. */ if (c == '.') { fraction: /* Fraction */ do { c = tok_nextc(tok); } while (isdigit(c)); } if (c == 'e' || c == 'E') { exponent: /* Exponent part */ c = tok_nextc(tok); if (c == '+' || c == '-') c = tok_nextc(tok); if (!isdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while (isdigit(c)); } #ifndef WITHOUT_COMPLEX if (c == 'j' || c == 'J') /* Imaginary part */ imaginary: c = tok_nextc(tok); #endif } } tok_backup(tok, c); *p_start = tok->start; *p_end = tok->cur; return NUMBER; } letter_quote: /* String */ if (c == '\'' || c == '"') { Py_ssize_t quote2 = tok->cur - tok->start + 1; int quote = c; int triple = 0; int tripcount = 0; for (;;) { c = tok_nextc(tok); if (c == '\n') { if (!triple) { tok->done = E_EOLS; tok_backup(tok, c); return ERRORTOKEN; } tripcount = 0; tok->cont_line = 1; /* multiline string. */ } else if (c == EOF) { if (triple) tok->done = E_EOFS; else tok->done = E_EOLS; tok->cur = tok->inp; return ERRORTOKEN; } else if (c == quote) { tripcount++; if (tok->cur - tok->start == quote2) { c = tok_nextc(tok); if (c == quote) { triple = 1; tripcount = 0; continue; } tok_backup(tok, c); } if (!triple || tripcount == 3) break; } else if (c == '\\') { tripcount = 0; c = tok_nextc(tok); if (c == EOF) { tok->done = E_EOLS; tok->cur = tok->inp; return ERRORTOKEN; } } else tripcount = 0; } *p_start = tok->start; *p_end = tok->cur; return STRING; } /* Line continuation */ if (c == '\\') { c = tok_nextc(tok); if (c != '\n') { tok->done = E_LINECONT; tok->cur = tok->inp; return ERRORTOKEN; } tok->cont_line = 1; goto again; /* Read next line */ } /* Check for two-character token */ { int c2 = tok_nextc(tok); int token = PyToken_TwoChars(c, c2); #ifndef PGEN if (Py_Py3kWarningFlag && token == NOTEQUAL && c == '<') { if (PyErr_WarnExplicit(PyExc_DeprecationWarning, "<> not supported in 3.x; use !=", tok->filename, tok->lineno, NULL, NULL)) { return ERRORTOKEN; } } #endif if (token != OP) { int c3 = tok_nextc(tok); int token3 = PyToken_ThreeChars(c, c2, c3); if (token3 != OP) { token = token3; } else { tok_backup(tok, c3); } *p_start = tok->start; *p_end = tok->cur; return token; } tok_backup(tok, c2); } /* Keep track of parentheses nesting level */ switch (c) { case '(': case '[': case '{': tok->level++; break; case ')': case ']': case '}': tok->level--; break; } /* Punctuation character */ *p_start = tok->start; *p_end = tok->cur; return PyToken_OneChar(c); }
void compare_term_list(FILE* listfile, long totalchar,char*textlist) { int listcontainer = text_ini; int term_len = line_ini; int shouldcount=0; int list_i=0,term_i=0; char listterm_ch; char** listterm; listterm = malloc(listcontainer*sizeof(char*)); assert(listterm); memset(listterm,0,listcontainer+1); listterm[list_i] = malloc((term_len+1)*sizeof(char)); assert(listterm[list_i]); memset(listterm[list_i],0,term_len+1); long charOffset=0,termOffset=0; int afterlen_list; int readindex = 0; int readindex_list = 0; while((listterm_ch=fgetc(listfile))!=EOF) { if (listterm_ch != '\n') { listterm[list_i][term_i] = listterm_ch; term_i++; } else if (listterm_ch == '\n') { list_i++; term_len = term_i; if ((list_i) == listcontainer -1) { listcontainer = listcontainer*2; listterm = realloc(listterm, listcontainer*sizeof(char*)); assert(listterm); afterlen_list = listcontainer/2+1; memset(listterm+afterlen_list-2,0,(afterlen_list)*sizeof(char*)); } listterm[list_i] = malloc((term_len+1)*sizeof(char)); assert(listterm[list_i]); memset(listterm[list_i],0,term_len+1); term_i = 0; } } int totalterm = list_i; while (readindex < sizeof(textlist)/sizeof(char*)) { if (isalnum(textlist[readindex]) && shouldcount == 0) { termOffset++; shouldcount = 1; } if (!isalnum(textlist[readindex])) { shouldcount = 0; } while (readindex_list < totalterm) { if (strncasecmp(textlist,listterm[readindex_list],readindex-len(listterm[readindex_list])) ==0) { charOffset = charOffset+len(listterm[readindex_list]); termOffset = readindex; fprintf(stdout,"%ld,%ld,%s\n",charOffset,termOffset,listterm[readindex_list]); } else { readindex_list++; } } readindex_list = 0; readindex++; } free(textlist); free(listterm); }
int main(int argc, char *argv[]) { int i, j, k; int sets = 0, countsets = 0, minlen = 0, maxlen = MAXLENGTH, count = 0; int set_low = 0, set_up = 0, set_no = 0, set_print = 0, set_other = 0; FILE *in = stdin, *out = stdout; char buf[MAXLENGTH + 1]; prg = argv[0]; if (argc < 2) help(); while ((i = getopt(argc, argv, "i:o:m:M:c:lunps")) >= 0) { switch (i) { case 'i': if ((in = fopen(optarg, "r")) == NULL) { fprintf(stderr, "Error: unable to open input file %s\n", optarg); exit(-1); } break; case 'o': if ((out = fopen(optarg, "w")) == NULL) { fprintf(stderr, "Error: unable to open output file %s\n", optarg); exit(-1); } break; case 'm': minlen = atoi(optarg); break; case 'M': maxlen = atoi(optarg); break; case 'c': countsets = atoi(optarg); break; case 'l': if (set_low == 0) { set_low = 1; sets++; } break; case 'u': if (set_up == 0) { set_up = 1; sets++; } break; case 'n': if (set_no == 0) { set_no = 1; sets++; } break; case 'p': if (set_print == 0) { set_print = 1; sets++; } break; case 's': if (set_other == 0) { set_other = 1; sets++; } break; default: help(); } } if (minlen > maxlen) { fprintf(stderr, "Error: -m MINLEN is greater than -M MAXLEN\n"); exit(-1); } if (countsets > sets) { fprintf(stderr, "Error: -c MINSETS is larger than the sets defined\n"); exit(-1); } if (countsets == 0) countsets = sets; while (fgets(buf, sizeof(buf), in) != NULL) { i = -1; if (buf[0] == 0) continue; if (buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = 0; if (strlen(buf) >= minlen && strlen(buf) <= maxlen) { i = 0; if (countsets > 0) { if (set_low) if (strpbrk(buf, "abcdefghijklmnopqrstuvwxyz") != NULL) i++; if (set_up) if (strpbrk(buf, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") != NULL) i++; if (set_no) if (strpbrk(buf, "0123456789") != NULL) i++; if (set_print) { j = 0; for (k = 0; k < strlen(buf); k++) if (isprint(buf[k]) && isalnum(buf[k]) == 0) j = 1; if (j) i++; } if (set_other) { j = 0; for (k = 0; k < strlen(buf); k++) if (isprint(buf[k]) == 0 && isalnum(buf[k]) == 0) j = 1; if (j) i++; } } if (i >= countsets) { fprintf(out, "%s\n", buf); count++; } } /* fprintf(stderr, "[DEBUG] i: %d minlen: %d maxlen: %d len: %d\n", i, minlen, maxlen, strlen(buf)); */ } return count; }
void convert_file(char *source_filename) { char html_filename[NAME_MAX + 1]; char *relative_filename; char *base_filename; char *ext, *p; int is_c = 0; int is_asm = 0; FILE *src; FILE *out; int line_num; char line[STRSIZE]; char filename[STRSIZE]; char token[STRSIZE]; char url[STRSIZE]; int in_comment; relative_filename = source_filename + source_prefix_len; ext = ""; base_filename = relative_filename; p = relative_filename; while (*p) { if (*p == '/') { base_filename = p + 1; ext = ""; } if (*p == '.') ext = p; p++; } strcpy(html_filename, output_dir); strcat(html_filename, "/"); strcat(html_filename, relative_filename); strcat(html_filename, ".html"); if (strcmp(ext, ".c") == 0) is_c = 1; if (strcmp(ext, ".h") == 0) is_c = 1; if (strcmp(ext, ".cpp") == 0) is_c = 1; if (strcmp(ext, ".asm") == 0) is_asm = 1; if (strcmp(ext, ".s") == 0) is_asm = 1; if (!is_c && !is_asm) return; src = fopen(source_filename, "rt"); if (!src) { perror(source_filename); return; } out = fopen(html_filename, "wb"); if (!out) { perror(html_filename); return; } fprintf(out, "<html>\r\n"); fprintf(out, "<head>\r\n"); fprintf(out, "<title>%s - %s</title>\r\n", base_filename, title); fprintf(out, "<style type='text/css'>\r\n"); fprintf(out, "a:link {text-decoration: none; color:inherit}\r\n"); fprintf(out, "a:visited {text-decoration: none; color:inherit}\r\n"); fprintf(out, "a:active {text-decoration: none; color:inherit}\r\n"); fprintf(out, "</style>\r\n"); fprintf(out, "</head>\r\n"); fprintf(out, "<body>\r\n"); if (source_index) { fprintf(out, "<p style='float: right'><a href='/sanos/source/index.html'>Goto sanos source index</a></p>"); } fprintf(out, "<pre>\r\n"); line_num = 1; in_comment = 0; while (fgets(line, sizeof line, src)) { char *p = line; char *end = line; while (*end && *end != '\r' && *end != '\n') end++; *end = 0; if (in_comment) { char *comment_start = p; fprintf(out, "<font color='green'>"); while (p < end) { if (p[0] == '*' && p[1] == '/') { p += 2; output_html(out, comment_start, p); in_comment = 0; fprintf(out, "</font>"); break; } p++; } } fprintf(out, "<a name=':%d'></a>", line_num); if (!is_c) { output_html(out, p, end); p = end; } while (p < end) { if (p[0] == '/' && p[1] == '/') { fprintf(out, "<font color='green'>"); output_html(out, p, end); fprintf(out, "</font>"); p = end; } else if (p[0] == '/' && p[1] == '*') { char *comment_start = p; fprintf(out, "<font color='green'>"); while (p < end) { if (p[0] == '*' && p[1] == '/') { p += 2; output_html(out, comment_start, p); in_comment = 0; fprintf(out, "</font>"); break; } p++; } } else if (*p == '\'' || *p == '"') { char *start = p++; while (*p && *p != *start) { if (*p == '\\' && *(p + 1)) p++; p++; } if (*p) p++; fprintf(out, "<font color='brown'>"); output_html(out, start, p); fprintf(out, "</font>"); } else if (*p == '#' || *p == '_' || isalpha(*p)) { char *start = p++; while (*p && (*p == '_' || isalnum(*p))) p++; memcpy(token, start, p - start); token[p - start] = 0; if (is_keyword(token)) { fprintf(out, "<font color='blue'>"); output_html(out, start, p); fprintf(out, "</font>"); if (strncmp(start, "#include", 8) == 0) { start = p; while (isspace(*p)) p++; output_html(out, start, p); if (*p == '"' || *p == '<') { int stdincl = *p == '<'; output_html(out, p, p + 1); start = ++p; while (*p && *p != '>' && *p != '"') p++; if (stdincl) { char *base; strcpy(filename, include_dir); strcat(filename, "/"); base = filename + strlen(filename); memcpy(base, start, p - start); base[p - start] = 0; } else { int pathlen = base_filename - relative_filename; int fnlen = p - start; memcpy(filename, relative_filename, pathlen); memcpy(filename + pathlen, start, fnlen); filename[pathlen + fnlen] = 0; } relative_url(relative_filename, filename, url); fprintf(out, "<a href='%s.html'>", url); output_html(out, start, p); fprintf(out, "</a>"); if (*p) { output_html(out, p, p + 1); p++; } } } } else { struct tag *tag = find_tag(token, relative_filename); if (tag) { int self; relative_url(relative_filename, tag->file, url); self = strcmp(url, base_filename) == 0 && tag->line == line_num; if (!self) fprintf(out, "<a href='%s.html#:%d'>", url, tag->line); output_html(out, start, p); if (!self) fprintf(out, "</a>"); } else { output_html(out, start, p); } } } else { output_html(out, p, p + 1); p++; } } if (in_comment) fprintf(out, "</font>"); fprintf(out, "\r\n", line); line_num++; } fprintf(out, "</pre>\r\n"); fprintf(out, "</body>\r\n"); fprintf(out, "</html>\r\n"); fclose(src); fclose(out); }
/* Find the next token in str and fill in the token struct. Return a pointer * to the first character after the found token or return NULL and t.token=0 * if no valid token was found. */ char *Token(char *str, struct token *t, int cmd_opt) { char c; bzero(lex, LEX_LEN); lex_ptr = 0; sstate = state = 1; str_ptr = 0; if (cmd_opt == TOKEN_COMMAND) { t->token = TOKEN_COMMAND; t->attr = CMD_NOP; } else t->token = t->attr = 0; t->attr2 = 0; t->lex = lex; if (str == NULL) return NULL; do { switch (state) { case 1: nextchar(); /* strip blanks */ if (c == ' ' || c == '\t' || c == '\n') { lex[--lex_ptr] = 0; if (c == '\n') line++; break; } t->token = t->attr = 0; if (isdigit(c)) state = 2; else state = Next(); break; case 2: nextchar(); if (isdigit(c)) break; else if (c == '.') state = 3; else state = 5; break; case 3: nextchar(); if (isdigit(c)) state = 4; else state = Next(); break; case 4: nextchar(); if (isdigit(c)) break; else state = 5; break; case 5: ungetchar(); t->token = TOKEN_NUM; t->attr = (unsigned int)atoi(lex); Return(str+str_ptr); case 6: nextchar(); if (isalpha(c)) state = 7; else state = Next(); break; case 7: nextchar(); if (isalnum(c)) break; else state = 8; break; case 8: ungetchar(); /* return TOKEN_WORD, TOKEN_COMMAND, or TOKEN_OPTION */ t->token = TOKEN_WORD; if (cmd_opt == TOKEN_COMMAND) Lookup(t, commands); else Lookup(t, options); Return(str+str_ptr); case 9: nextchar(); if (c == '#') state = 10; else state = Next(); break; case 10: nextchar(); if (c == '\n') state = 11; break; case 11: ungetchar(); t->token = TOKEN_COMMENT; Return(str+str_ptr); default: printf("internal parser error: Token() in rc.c\n"); exit(-1); } } while (1); }
bool VDScriptInterpreter::isIdentNextChar(char c) { return isalnum((unsigned char)c) || c=='_'; }
static int attrsOk(XmlBuffer * xb, const XmlElement * e, XmlAttr * r, const char *tag, int etag) { unsigned int n; char *ptr, wa[32]; char msg1[] = { "Unknown attribute in list for " }; char msg2[] = { "Bad attribute list for " }; char word[32]; for (n = 0; (e + n)->attr; n++) wa[n] = 0; xb->eTagFound = 0; for (skipWS(xb); isalpha(*xb->cur); skipWS(xb)) { // for (n=0; n < a.size(); n++) { for (n = 0; (e + n)->attr; n++) { if (wa[n] == 1) continue; if (getWord(xb, (e + n)->attr, 0)) { if (!isalnum(*xb->cur)) { skipWS(xb); if (getChar(xb, '=')) { (r + n)->attr = getValue(xb, (e + n)->attr); wa[n] = 1; goto ok; } else Throw(xb, "'=' expected in attribute list"); } } } strncpy(word, xb->cur, 10); word[10] = 0; ptr = (char *) alloca(strlen(tag) + strlen(msg1) + 8 + 20); strcpy(ptr, msg1); strcat(ptr, tag); strcat(ptr, " ("); strcat(ptr, word); strcat(ptr, ")"); Throw(xb, ptr); ok:; } if (getChars(xb, "/>")) { xb->eTagFound = 1; xb->etag = etag; return 1; } else if (getChar(xb, '>')) return 1; else if (getChars(xb, "?>") && strcmp(tag, "?xml") == 0) { xb->eTagFound = 1; xb->etag = etag; return 1; } ptr = (char *) alloca(strlen(tag) + strlen(msg2) + 96); strcpy(ptr, msg2); strcat(ptr, tag); strcat(ptr, ": "); strncpy(word, xb->cur, 30); word[30]=0; strcat(ptr, word); strcat(ptr," "); strcat(ptr, tag); Throw(xb, ptr); return -1; }
//extern "C" int iphone_main (int argc, char **argv) { int res, i, j = 0, game_index; char *playbackname = NULL; int use_cyclone=0; int use_drz80=0; extern int video_scale; extern int video_border; extern int video_aspect; extern int throttle; extern int gp2x_ram_tweaks; memset(&options,0,sizeof(options)); /* these two are not available in mame.cfg */ errorlog = 0; game_index = -1; throttle=1;//FIX Seleuco for (i = 1;i < argc;i++) /* V.V_121997 */ { if (strcasecmp(argv[i],"-log") == 0) errorlog = fopen("error.log","wa"); #if 0 if (strcasecmp(argv[i],"-cyclone") == 0) use_cyclone=1; if (strcasecmp(argv[i],"-drz80") == 0) use_drz80=1; #endif if (strcasecmp(argv[i],"-scale") == 0) video_scale=1; if (strcasecmp(argv[i],"-border") == 0) video_border=1; if (strcasecmp(argv[i],"-aspect") == 0) video_aspect=1; if (strcasecmp(argv[i],"-nothrottle") == 0) { throttle=0; } //printf("throttle %d\n",throttle); if (strcasecmp(argv[i],"-ramtweaks") == 0) gp2x_ram_tweaks=1; if (strcasecmp(argv[i],"-playback") == 0) { i++; if (i < argc) /* point to inp file name */ playbackname = argv[i]; } } /* GP2X Initialization */ //gp2x_init(1000,8,22050,16,0,60); /* check for frontend options */ // res = frontend_help (argc, argv); /* if frontend options were used, return to DOS with the error code */ /* if (res != 1234) { return 0; //gp2x_deinit(); //execl("mame.gpe", "mame.gpe", "cache", NULL); //exit (res); } */ //TODO: MIRAR POR QUE ESTO PETA REARRANCANDO VARIOS GAMES /* handle playback which is not available in mame.cfg */ // init_inpdir(); /* Init input directory for opening .inp for playback */ ///LO DEJO COMENTADO if (playbackname != NULL) options.playback = osd_fopen(playbackname,0,OSD_FILETYPE_INPUTLOG,0); /* check for game name embedded in .inp header */ if (options.playback) { INP_HEADER inp_header; /* read playback header */ osd_fread(options.playback, &inp_header, sizeof(INP_HEADER)); if (!isalnum(inp_header.name[0])) /* If first byte is not alpha-numeric */ osd_fseek(options.playback, 0, SEEK_SET); /* old .inp file - no header */ else { for (i = 0; (drivers[i] != 0); i++) /* find game and play it */ { if (strcmp(drivers[i]->name, inp_header.name) == 0) { game_index = i; printf("Playing back previously recorded game %s (%s) [press return]\n", drivers[game_index]->name,drivers[game_index]->description); getchar(); break; } } } } /* If not playing back a new .inp file */ if (game_index == -1) { /* take the first commandline argument without "-" as the game name */ for (j = 1; j < argc; j++) { if (argv[j][0] != '-') break; } /* do we have a driver for this? */ { for (i = 0; drivers[i] && (game_index == -1); i++) { if (strcasecmp(argv[j],drivers[i]->name) == 0) { game_index = i; break; } } /* educated guess on what the user wants to play */ if (game_index == -1) { int fuzz = 9999; /* best fuzz factor so far */ for (i = 0; (drivers[i] != 0); i++) { int tmp; tmp = fuzzycmp(argv[j], drivers[i]->description); /* continue if the fuzz index is worse */ if (tmp > fuzz) continue; /* on equal fuzz index, we prefer working, original games */ if (tmp == fuzz) { /* game is a clone */ if (drivers[i]->clone_of != 0 && !(drivers[i]->clone_of->flags & NOT_A_DRIVER)) { /* if the game we already found works, why bother. */ /* and broken clones aren't very helpful either */ if ((!drivers[game_index]->flags & GAME_NOT_WORKING) || (drivers[i]->flags & GAME_NOT_WORKING)) continue; } else continue; } /* we found a better match */ game_index = i; fuzz = tmp; } if (game_index != -1) printf("fuzzy name compare, running %s\n",drivers[game_index]->name); } } if (game_index == -1) { printf("Game \"%s\" not supported\n", argv[j]); return 1; } } /* parse generic (os-independent) options */ parse_cmdline (argc, argv, game_index); { /* Mish: I need sample rate initialised _before_ rom loading for optional rom regions */ extern int soundcard; if (soundcard == 0) { /* silence, this would be -1 if unknown in which case all roms are loaded */ Machine->sample_rate = 0; /* update the Machine structure to show that sound is disabled */ options.samplerate=0; } } /* handle record which is not available in mame.cfg */ for (i = 1; i < argc; i++) { if (strcasecmp(argv[i],"-record") == 0) { i++; if (i < argc) options.record = osd_fopen(argv[i],0,OSD_FILETYPE_INPUTLOG,1); } } if (options.record) { INP_HEADER inp_header; memset(&inp_header, '\0', sizeof(INP_HEADER)); strcpy(inp_header.name, drivers[game_index]->name); /* MAME32 stores the MAME version numbers at bytes 9 - 11 * MAME DOS keeps this information in a string, the * Windows code defines them in the Makefile. */ /* inp_header.version[0] = 0; inp_header.version[1] = VERSION; inp_header.version[2] = BETA_VERSION; */ osd_fwrite(options.record, &inp_header, sizeof(INP_HEADER)); } #if 0 /* Replace M68000 by CYCLONE */ if (use_cyclone) { for (i=0;i<MAX_CPU;i++) { int *type=(int*)&(drivers[game_index]->drv->cpu[i].cpu_type); #ifdef NEOMAME if (((*type)&0xff)==CPU_M68000) #else if (((*type)&0xff)==CPU_M68000 || ((*type)&0xff)==CPU_M68010 ) #endif { *type=((*type)&(~0xff))|CPU_CYCLONE; } } } /* Replace Z80 by DRZ80 */ if (use_drz80) { for (i=0;i<MAX_CPU;i++) { int *type=(int*)&(drivers[game_index]->drv->cpu[i].cpu_type); if (((*type)&0xff)==CPU_Z80) { *type=((*type)&(~0xff))|CPU_DRZ80; } } } #endif // Remove the mouse usage for certain games if ( (strcasecmp(drivers[game_index]->name,"hbarrel")==0) || (strcasecmp(drivers[game_index]->name,"hbarrelw")==0) || (strcasecmp(drivers[game_index]->name,"midres")==0) || (strcasecmp(drivers[game_index]->name,"midresu")==0) || (strcasecmp(drivers[game_index]->name,"midresj")==0) || (strcasecmp(drivers[game_index]->name,"tnk3")==0) || (strcasecmp(drivers[game_index]->name,"tnk3j")==0) || (strcasecmp(drivers[game_index]->name,"ikari")==0) || (strcasecmp(drivers[game_index]->name,"ikarijp")==0) || (strcasecmp(drivers[game_index]->name,"ikarijpb")==0) || (strcasecmp(drivers[game_index]->name,"victroad")==0) || (strcasecmp(drivers[game_index]->name,"dogosoke")==0) || (strcasecmp(drivers[game_index]->name,"gwar")==0) || (strcasecmp(drivers[game_index]->name,"gwarj")==0) || (strcasecmp(drivers[game_index]->name,"gwara")==0) || (strcasecmp(drivers[game_index]->name,"gwarb")==0) || (strcasecmp(drivers[game_index]->name,"bermudat")==0) || (strcasecmp(drivers[game_index]->name,"bermudaj")==0) || (strcasecmp(drivers[game_index]->name,"bermudaa")==0) || (strcasecmp(drivers[game_index]->name,"mplanets")==0) || (strcasecmp(drivers[game_index]->name,"forgottn")==0) || (strcasecmp(drivers[game_index]->name,"lostwrld")==0) || (strcasecmp(drivers[game_index]->name,"gondo")==0) || (strcasecmp(drivers[game_index]->name,"makyosen")==0) || (strcasecmp(drivers[game_index]->name,"topgunr")==0) || (strcasecmp(drivers[game_index]->name,"topgunbl")==0) || (strcasecmp(drivers[game_index]->name,"tron")==0) || (strcasecmp(drivers[game_index]->name,"tron2")==0) || (strcasecmp(drivers[game_index]->name,"kroozr")==0) ||(strcasecmp(drivers[game_index]->name,"crater")==0) || (strcasecmp(drivers[game_index]->name,"dotron")==0) || (strcasecmp(drivers[game_index]->name,"dotrone")==0) || (strcasecmp(drivers[game_index]->name,"zwackery")==0) || (strcasecmp(drivers[game_index]->name,"ikari3")==0) || (strcasecmp(drivers[game_index]->name,"searchar")==0) || (strcasecmp(drivers[game_index]->name,"sercharu")==0) || (strcasecmp(drivers[game_index]->name,"timesold")==0) || (strcasecmp(drivers[game_index]->name,"timesol1")==0) || (strcasecmp(drivers[game_index]->name,"btlfield")==0) || (strcasecmp(drivers[game_index]->name,"aztarac")==0)) { extern int use_mouse; use_mouse=0; } /* go for it */ printf ("%s (%s)...\n",drivers[game_index]->description,drivers[game_index]->name); res = run_game (game_index); /* close open files */ if (errorlog) fclose (errorlog); if (options.playback) osd_fclose (options.playback); if (options.record) osd_fclose (options.record); if (options.language_file) osd_fclose (options.language_file); if (res!=0) { /* wait a key press */ gp2x_video_flip_single(); gp2x_joystick_press(0); } //gp2x_deinit(); //execl("mame.gpe", "mame.gpe", "cache", NULL); //exit (res); }
static int name_mangle(String *r) { char *c; int special; special = 0; Replaceall(r, "::", "_"); c = Char(r); while (*c) { if (!isalnum((int) *c) && (*c != '_')) { special = 1; switch (*c) { case '+': *c = 'a'; break; case '-': *c = 's'; break; case '*': *c = 'm'; break; case '/': *c = 'd'; break; case '<': *c = 'l'; break; case '>': *c = 'g'; break; case '=': *c = 'e'; break; case ',': *c = 'c'; break; case '(': *c = 'p'; break; case ')': *c = 'P'; break; case '[': *c = 'b'; break; case ']': *c = 'B'; break; case '^': *c = 'x'; break; case '&': *c = 'A'; break; case '|': *c = 'o'; break; case '~': *c = 'n'; break; case '!': *c = 'N'; break; case '%': *c = 'M'; break; case '.': *c = 'f'; break; case '?': *c = 'q'; break; default: *c = '_'; break; } } c++; } if (special) Append(r, "___"); return special; }
static cell AMX_NATIVE_CALL is_alnum(AMX *amx, cell *params) { return isalnum(params[1]); }
bool dIsalnum(const char c) { return isalnum(c); }
xml_token_type_t xml_get_token_tag(xml_reader_t *xr, string_t *res) { int cc, oc; xml_skip_space(xr, NULL); cc = xml_getc(xr); if (cc == EOF) { xml_parse_error(xr, "Unexpected EOF while parsing tag"); return None; } string_putc(res, cc); switch (cc) { case '<': goto error; case '?': if ((cc = xml_getc(xr)) != '>') goto error; string_putc(res, cc); xr->state = Initial; return RightAngleQ; case '>': xr->state = Initial; return RightAngle; case '/': if ((cc = xml_getc(xr)) != '>') goto error; string_putc(res, cc); xr->state = Initial; return RightAngleSlash; case '=': return Equals; case 'a' ... 'z': case 'A' ... 'Z': case '_': case '!': while ((cc = xml_getc(xr)) != EOF) { if (!isalnum(cc) && cc != '_' && cc != '!' && cc != ':' && cc != '-') { xml_ungetc(xr, cc); break; } string_putc(res, cc); } return Identifier; case '\'': case '"': string_destroy(res); oc = cc; while (1) { cc = xml_getc(xr); if (cc == EOF) goto unexpected_eof; if (cc == '\\' && oc == '"') { cc = xml_getc(xr); if (cc == EOF) goto unexpected_eof; } else if (cc == oc) break; string_putc(res, cc); } return QuotedString; default: break; } error: xml_parse_error(xr, "Unexpected character %c in XML document", cc); return None; unexpected_eof: xml_parse_error(xr, "Unexpected EOF while parsing quoted string"); return None; }
static boolean isIdentifierCharacter (int c) { return (boolean) (isalnum (c) || c == '_'); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A C H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMPCImage() reads an Magick Persistent Cache 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 ReadMPCImage method is: % % Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) % % Decompression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register long i; size_t length; ssize_t count; StringInfo *profile; unsigned long depth, quantum_depth; /* 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=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); quantum_depth=MAGICKCORE_QUANTUM_DEPTH; image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ p=keyword; do { if (isspace((int) ((unsigned char) c)) != 0) break; if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); *p++=(char) c; c=ReadBlobByte(image); if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,MaxTextExtent); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { long storage_class; storage_class=ParseMagickOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=(unsigned long) atol(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { long colorspace; colorspace=ParseMagickOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { long compression; compression=ParseMagickOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=(unsigned long) atol(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=(unsigned long) atol(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=(unsigned long) atol(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { long dispose; dispose=ParseMagickOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { long endian; endian=ParseMagickOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=atof(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=atof(options); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=(unsigned long) atol(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"matte") == 0) { long matte; matte=ParseMagickOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=atof(options); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=atof(options); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { long matte; matte=ParseMagickOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { long orientation; orientation=ParseMagickOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=AcquireStringInfo((size_t) atol(options)); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=(unsigned long) atol(options); break; } if (LocaleCompare(keyword,"quantum-depth") == 0) { quantum_depth=(unsigned long) atol(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { long rendering_intent; rendering_intent=ParseMagickOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=(unsigned long) atol(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=(unsigned long) atol(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(long) atol(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { long type; type=ParseMagickOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { long units; units=ParseMagickOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (quantum_depth != MAGICKCORE_QUANTUM_DEPTH) ThrowReaderException(CacheError,"InconsistentPersistentCacheDepth"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=colormap; switch (depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (long) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (long) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned long pixel; for (i=0; i < (long) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); }