Ejemplo n.º 1
0
int parse_rfpi(const char * str_rfpi, uint8_t * rfpi)
{
    int i = 0;

    // Skip initial whitespace:
    while (isspace(*str_rfpi))
        str_rfpi++;

    for (;;)
    {
        int highnibble, lownibble;
        highnibble = hexvalue(str_rfpi[0]);
        // Need to check for validity of the first character before
        // continuing with the next, in case the first one was \0:
        if (highnibble == -1)
            return -1;
        lownibble = hexvalue(str_rfpi[1]);
        if (lownibble == -1)
            return -1;
        rfpi[i] = (highnibble << 4) | lownibble;

        if (i == 4)
            break;
        i++;
        str_rfpi += 2;

        // Accept space or colon as byte separator. None at all is ok too.
        if (*str_rfpi == ' ' || *str_rfpi == ':')
            str_rfpi++;
    }

    return 0;
}
Ejemplo n.º 2
0
Archivo: args.c Proyecto: xach/wfcomp
u8 hexhex(char *string)
{
    if (string[0] && string[1]) {
        return (hexvalue(string[0]) << 4) + hexvalue(string[1]);
    }

    fail("bad hexhex");
}
Ejemplo n.º 3
0
/* Convert nbinary*2 ASCII hex characters [0-9A-Fa-f] to nbinary bytes of data.  Can be used to
   perform the conversion in-place, eg, fromhex(buf, (char*)buf, n);  Returns -1 if a non-hex-digit
   character is encountered, otherwise returns the number of binary bytes produced (= nbinary).
   @author Andrew Bettison <*****@*****.**>
 */
size_t fromhex(unsigned char *dstBinary, const char *srcHex, size_t nbinary)
{
  size_t count = 0;
  while (count != nbinary) {
    unsigned char high = hexvalue(*srcHex++);
    if (high & 0xf0) return -1;
    unsigned char low = hexvalue(*srcHex++);
    if (low & 0xf0) return -1;
    dstBinary[count++] = (high << 4) + low;
  }
  return count;
}
Ejemplo n.º 4
0
void make_hex(int decimal[3],char hex[7]){

	int countd,counth;
	
	hex[0] = '#';
	
	for(counth = 1,countd = 0;counth < strlen(hex);countd++,counth += 2 ){
	
		hex[counth + 1] =  hexvalue(decimal[countd]%16);
		decimal[countd]/= 16;
		hex[counth] = hexvalue(decimal[countd]%16);
		
	}


}
Ejemplo n.º 5
0
void WebServerClass::urlDecode(char *decoded, const char *encoded, size_t n) {
  const char *p = encoded;
  char *q = decoded;
  while (*p != '\0') {
    // Check length limit first, make sure it's zero-terminated
    if ((q - decoded >= n) && (n > 0)) {
      q[-1] = '\0';
      return;
    }
    if (*p == '+') {
      *q = ' ';
    } else if (*p == '%' && isxdigit(p[1]) && isxdigit(p[2])) {
      *q = (char)(hexvalue(p[1])*16 + hexvalue(p[2]));
      p += 2;  // Additional chars to skip
    } else {
      *q = *p;
    }
    ++p; ++q;
  }
  *q = '\0';
}
Ejemplo n.º 6
0
static void
URL_decode(char *URL)
{
    char *in, *out;

    in = out = URL;

    while (*in != '\0') {
        if (in[0] == '%' && in[1] != '\0' && in[2] != '\0') {
            /* URL-decode character */
            if (hexvalue(in[1]) != -1 && hexvalue(in[2]) != -1) {
                *out++ = hexvalue(in[1])*16+hexvalue(in[2]);
            }
            /* skip invalid encoded signs too */
            in += 3;
        }
        else
            *out++ = *in++;
    }

    *out = '\0';

    return;
}
Ejemplo n.º 7
0
/*
 * Convert a URL with "%XX" hexadecimal escaped style bytes into normal form.
 * Result length will always be <= source length.
 */
char *urlunescape(char *url)
{
	static char *result = NULL;
	char *pin, *pout;

	pin = url;
	if (result) xfree(result);
	pout = result = (char *) malloc(strlen(url) + 1);
	while (*pin) {
		if (*pin == '+') {
			*pout = ' ';
			pin++;
		}
		else if (*pin == '%') {
			pin++;
			if ((strlen(pin) >= 2) && isxdigit((int)*pin) && isxdigit((int)*(pin+1))) {
				*pout = 16*hexvalue(*pin) + hexvalue(*(pin+1));
				pin += 2;
			}
			else {
				*pout = '%';
				pin++;
			}
		}
		else {
			*pout = *pin;
			pin++;
		}

		pout++;
	}

	*pout = '\0';

	return result;
}
Ejemplo n.º 8
0
static int hex2str( const char *src, char *dest )
{
	if ( src == NULL ) {
		dest[0] = 0 ;
		return 0;
	}

	int pos = 0 ;
	int i   = 0 ;
	int len = (int) strlen(src) ;
	// 转换实际数据
	unsigned char c = 0 ;
	for ( i = 0; i < len; ++i ) {
		if ( i % 2 == 0 ) {
			c = hexvalue( src[i] ) & 0xff ;
		}  else  {
			c = c << 4 ;
			c |= hexvalue( src[i] ) ;
			dest[pos++] = (char) c ;
		}
	}
	dest[pos] = 0 ;
	return pos ;
}
Ejemplo n.º 9
0
static inline isc_result_t
fromtext_in_nsap(ARGS_FROMTEXT) {
	isc_token_t token;
	isc_textregion_t *sr;
	int n;
	int digits;
	unsigned char c = 0;

	REQUIRE(type == 22);
	REQUIRE(rdclass == 1);

	UNUSED(type);
	UNUSED(origin);
	UNUSED(options);
	UNUSED(rdclass);
	UNUSED(callbacks);

	/* 0x<hex.string.with.periods> */
	RETERR(isc_lex_getmastertoken(lexer, &token, isc_tokentype_string,
				      ISC_FALSE));
	sr = &token.value.as_textregion;
	if (sr->length < 2)
		RETTOK(ISC_R_UNEXPECTEDEND);
	if (sr->base[0] != '0' || (sr->base[1] != 'x' && sr->base[1] != 'X'))
		RETTOK(DNS_R_SYNTAX);
	isc_textregion_consume(sr, 2);
	digits = 0;
	n = 0;
	while (sr->length > 0) {
		if (sr->base[0] == '.') {
			isc_textregion_consume(sr, 1);
			continue;
		}
		if ((n = hexvalue(sr->base[0])) == -1)
			RETTOK(DNS_R_SYNTAX);
		c <<= 4;
		c += n;
		if (++digits == 2) {
			RETERR(mem_tobuffer(target, &c, 1));
			digits = 0;
		}
		isc_textregion_consume(sr, 1);
	}
	if (digits)
		RETTOK(ISC_R_UNEXPECTEDEND);
	return (ISC_R_SUCCESS);
}
Ejemplo n.º 10
0
void read_reference(FILE *trace_file, memory_reference *reference)
{
    int c;
    /* we have the first character; it defined the
       memory access type.  Skip any blanks, get the
       hexadecimal address, skip the comma and get the length */

    /* skip any leading blanks */
    c = skip_blanks(trace_file);
    
    memory_address a = 0;
    while (ishex(c))
        {
            a = (a << 4) | hexvalue(c);
            c = getc(trace_file);
        }
    if (c != ',')
        {
            fprintf(stderr, "bad trace file input at line %d: %c\n", trace_line_number, c);
            exit(-1);
        }
  
    /* skip the comma */
    /* and get the length */
    int n = 0;
    c = getc(trace_file);    
    while (isdigit(c))
        {
            n = n * 10 + decvalue(c);
            c = getc(trace_file);
        }

    /* skip to end of line */
    while ((c != '\n') && (c != EOF)) c = getc(trace_file);

    /* define reference fields */
    reference->address = a;
    reference->length = n;
}
Ejemplo n.º 11
0
int tcp_http_data_callback(unsigned char *buf, unsigned int len, void *priv)
{
	/*
	 * This callback receives data from HTTP servers.
	 * While doing that, it splits out the data into a
	 * buffer for the HTTP headers, and a buffer for the
	 * HTTP content-data.
	 * Return 1 if data is complete, 0 if more data wanted.
	 */

	http_data_t *item = (http_data_t *) priv;

	if (item->gotheaders) {
		unsigned int len1chunk = 0;
		int i;

		/*
		 * We already have the headers, so just stash away the data
		 */


		while (len > 0) {
			dbgprintf("HDC IN : state=%d, leftinchunk=%d, len=%d\n", item->chunkstate, item->leftinchunk, len);
			switch (item->chunkstate) {
			  case CHUNK_NOTCHUNKED:
				len1chunk = len;
				if ((item->contlen > 0) && (item->contlen >= len)) item->contlen -= len;
				break;

			  case CHUNK_INIT:
				/* We're about to pick up a chunk length */
				item->leftinchunk = 0;
				item->chunkstate = CHUNK_GETLEN;
				len1chunk = 0;
				break;

			  case CHUNK_GETLEN:
				/* We are collecting the length of the chunk */
				i = hexvalue(*buf);
				if (i == -1) {
					item->chunkstate = CHUNK_SKIPLENCR;
				}
				else {
					item->leftinchunk = item->leftinchunk*16 + i;
					buf++; len--;
				}
				len1chunk = 0;
				break;
				
			  case CHUNK_SKIPLENCR:
				/* We've got the length, now skip to the next LF */
				if (*buf == '\n') {
					buf++; len--; 
					item->chunkstate = ((item->leftinchunk > 0) ? CHUNK_DATA : CHUNK_NOMORE);
				}
				else if ((*buf == '\r') || (*buf == ' ')) {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk len. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				len1chunk = 0;
				break;

			  case CHUNK_DATA:
				/* Passing off the data */
				if (len > item->leftinchunk) len1chunk = item->leftinchunk;
				else len1chunk = len;
				item->leftinchunk -= len1chunk;
				if (item->leftinchunk == 0) item->chunkstate = CHUNK_SKIPENDCR;
				break;

			  case CHUNK_SKIPENDCR:
				/* Skip CR/LF after a chunk */
				if (*buf == '\n') {
					buf++; len--; item->chunkstate = CHUNK_DONE;
				}
				else if (*buf == '\r') {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk data. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				len1chunk = 0;
				break;

			  case CHUNK_DONE:
				/* One chunk is done, continue with the next */
				len1chunk = 0;
				item->chunkstate = CHUNK_GETLEN;
				break;

			  case CHUNK_NOMORE:
				/* All chunks done. Skip the rest (trailers) */
				len1chunk = 0;
				len = 0;
			}

			if (len1chunk > 0) {
				switch (item->contentcheck) {
				  case CONTENTCHECK_NONE:
				  case CONTENTCHECK_CONTENTTYPE:
					/* No need to save output - just drop it */
					break;

				  case CONTENTCHECK_REGEX:
				  case CONTENTCHECK_NOREGEX:
					/* Save the full data */
					if ((item->output == NULL) || (item->outlen == 0)) {
						item->output = (unsigned char *)malloc(len1chunk+1);
					}
					else {
						item->output = (unsigned char *)realloc(item->output, item->outlen+len1chunk+1);
					}

					memcpy(item->output+item->outlen, buf, len1chunk);
					item->outlen += len1chunk;
					*(item->output + item->outlen) = '\0'; /* Just in case ... */
					break;

				  case CONTENTCHECK_DIGEST:
					/* Run the data through our digest routine, but discard the raw data */
					if ((item->digestctx == NULL) || (digest_data(item->digestctx, buf, len1chunk) != 0)) {
						errprintf("Failed to hash data for digest\n");
					}
					break;
				}

				buf += len1chunk;
				len -= len1chunk;
				dbgprintf("HDC OUT: state=%d, leftinchunk=%d, len=%d\n", item->chunkstate, item->leftinchunk, len);
			}
		}
	}
	else {
		/*
		 * Havent seen the end of headers yet.
		 */
		unsigned char *p;

		/* First, add this to the header-buffer */
		if (item->headers == NULL) {
			item->headers = (unsigned char *) malloc(len+1);
		}
		else {
			item->headers = (unsigned char *) realloc(item->headers, item->hdrlen+len+1);
		}

		memcpy(item->headers+item->hdrlen, buf, len);
		item->hdrlen += len;
		*(item->headers + item->hdrlen) = '\0';

check_for_endofheaders:
		/* 
		 * Now see if we have the end-of-headers delimiter.
		 * This SHOULD be <cr><lf><cr><lf>, but RFC 2616 says
		 * you SHOULD recognize just plain <lf><lf>.
		 * So try the second form, if the first one is not there.
		 */
		p=strstr(item->headers, "\r\n\r\n");
		if (p) {
			p += 4;
		}
		else {
			p = strstr(item->headers, "\n\n");
			if (p) p += 2;
		}

		if (p) {
			int http1subver, httpstatus;
			unsigned int bytesindata;
			char *p1, *xferencoding;
			int contlen;

			/* We have an end-of-header delimiter, but it could be just a "100 Continue" response */
			sscanf(item->headers, "HTTP/1.%d %d", &http1subver, &httpstatus);
			if (httpstatus == 100) {
				/* 
				 * It's a "100"  continue-status.
				 * Just drop this set of headers, and move on.
				 */
				item->hdrlen -= (p - item->headers);
				if (item->hdrlen > 0) {
					memmove(item->headers, p, item->hdrlen);
					*(item->headers + item->hdrlen) = '\0';
					goto check_for_endofheaders;
				}
				else {
					xfree(item->headers);
					item->headers = NULL;
					item->hdrlen = 0;
					return 0;
				}

				/* Should never go here ... */
			}


			/* We did find the end-of-header delimiter, and it is not a "100" status. */
			item->gotheaders = 1;

			/* p points at the first byte of DATA. So the header ends 1 or 2 bytes before. */
			*(p-1) = '\0';
			if (*(p-2) == '\r') { *(p-2) = '\0'; } /* NULL-terminate the headers. */

			/* See if the transfer uses chunks */
			p1 = item->headers; xferencoding = NULL; contlen = 0;
			do {
				if (strncasecmp(p1, "Transfer-encoding:", 18) == 0) {
					p1 += 18; while (isspace((int)*p1)) p1++;
					xferencoding = p1;
				}
				else if (strncasecmp(p1, "Content-Length:", 15) == 0) {
					p1 += 15; while (isspace((int)*p1)) p1++;
					contlen = atoi(p1);
				}
				else {
					p1 = strchr(p1, '\n'); if (p1) p1++;
				}
			} while (p1 && (xferencoding == NULL));

			if (xferencoding && (strncasecmp(xferencoding, "chunked", 7) == 0)) {
				item->chunkstate = CHUNK_INIT;
			}
			item->contlen = (contlen ? contlen : -1);

			bytesindata = item->hdrlen - (p - item->headers);
			item->hdrlen = strlen(item->headers);
			if (*p) {
				/* 
				 * We received some content data together with the
				 * headers. Save these to the content-data area.
				 */
				tcp_http_data_callback(p, bytesindata, priv);
			}
		}
	}

	if (item->chunkstate == CHUNK_NOTCHUNKED) 
		/* Not chunked - we're done if contlen reaches 0 */
		return (item->contlen == 0);
	else 
		/* Chunked - we're done if we reach state NOMORE*/
		return (item->chunkstate == CHUNK_NOMORE);
}
Ejemplo n.º 12
0
static PyObject *feed_avr(modesreader *self, Py_buffer *buffer, int max_messages)
{
    PyObject *rv = NULL;
    uint8_t *buffer_start, *p, *eod;
    int message_count = 0;
    PyObject *message_tuple = NULL;
    PyObject **messages = NULL;
    int error_pending = 0;

    buffer_start = buffer->buf;

    if (max_messages <= 0) {
        /* allocate the maximum size we might need, given a minimal encoding of:
         *   '*' <2 bytes message> ';' LF
         */
        max_messages = buffer->len / 5 + 1;
    }

    messages = calloc(max_messages, sizeof(PyObject*));
    if (!messages) {
        PyErr_NoMemory();
        goto out;
    }

    p = buffer_start;
    eod = buffer_start + buffer->len;
    while (p+17 <= eod && message_count+1 < max_messages) {
        int message_len = -1;
        uint64_t timestamp;
        uint8_t data[14];
        uint8_t message_format;
        int i;
        uint8_t *m;
        PyObject *message;

        message_format = p[0];
        if (message_format != '@' &&
            message_format != '%' &&
            message_format != '<' &&
            message_format != '*' &&
            message_format != ':') {
            error_pending = 1;
            if (message_count > 0)
                goto nomoredata;
            PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected '@'/'%%'/'<'/'*'/':' at offset %d but found 0x%02x instead",
                         (int) (p - buffer_start), (int)p[0]);
            goto out;
        }

        m = p + 1;
        if (message_format == '@' ||
            message_format == '%' ||
            message_format == '<') {
            /* read 6 bytes of timestamp */
            timestamp = 0;
            for (i = 0; i < 12; ++i, ++m) {
                int c;

                if (m >= eod) {
                    goto nomoredata;
                }

                timestamp <<= 4;
                c = hexvalue(*m);
                if (c >= 0) {
                    timestamp |= c;
                } else {
                    error_pending = 1;
                    if (message_count > 0)
                        goto nomoredata;
                    PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead",
                                 (int) (m - buffer_start), (int)*m);
                    goto out;
                }
            }
        } else {
            /* AVR format with no timestamp */
            timestamp = 0;
        }

        if (message_format == '<') {
            /* in format '<', skip 1 byte of signal */
            m += 2;
            if (m >= eod)
                goto nomoredata;
        }

        /* read 2-14 bytes of data */
        message_len = 0;
        while (message_len < 14) {
            int c0, c1;

            if (m+1 >= eod) {
                goto nomoredata;
            }

            if (m[0] == ';') {
                break; /* end of message marker */
            } else {
                c0 = hexvalue(m[0]);
                if (c0 < 0) {
                    error_pending = 1;
                    if (message_count > 0)
                        goto nomoredata;

                    PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead",
                                 (int) (m - buffer_start), (int)m[0]);
                    goto out;
                }
            }

            c1 = hexvalue(m[1]);
            if (c1 < 0) {
                error_pending = 1;
                if (message_count > 0)
                    goto nomoredata;

                PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead",
                             (int) (m - buffer_start), (int)m[1]);
                goto out;
            }

            if (message_len < 14) {
                data[message_len] = (c0 << 4) | c1;
            }
            ++message_len;
            m += 2;
        }

        /* consume ';' */
        if (m >= eod)
            goto nomoredata;
        if (*m != ';') {
            error_pending = 1;
            if (message_count > 0)
                goto nomoredata;

            PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected ';' at offset %d but found 0x%02x instead",
                         (int) (m - buffer_start), (int)*m);
            goto out;
        }

        /* CR LF, LF CR, LF all seen! ugh. */

        /* skip until CR or LF */
        while (m < eod && *m != '\r' && *m != '\n')
            ++m;

        /* consume however many CRs and LFs */
        while (m < eod && (*m == '\r' || *m == '\n'))
            ++m;

        /* check length */
        if (message_len != 2 && message_len != 7 && message_len != 14) {
            error_pending = 1;
            if (message_count > 0)
                goto nomoredata;

            PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected %d-byte message starting at offset %d",
                         message_len, (int) (p - buffer_start));
            goto out;
        }

        /* check for very out of range value
         * (dump1090 can hold messages for up to 60 seconds! so be conservative here)
         * also work around dump1090-mutability issue #47 which can send very stale Mode A/C messages
         */
        if (self->want_events && message_len != 2 && !timestamp_check(self, timestamp)) {
            if (! (messages[message_count++] = make_timestamp_jump_event(self, timestamp)))
                goto out;
        }

        timestamp_update(self, timestamp);

        /* decode it */
        if (! (message = modesmessage_from_buffer(timestamp, 0, data, message_len)))
            goto out;

        /* apply filters, update seen-set */
        ++self->received_messages;
        int wanted = filter_message(self, message);
        if (wanted < 0)
            goto out;
        else if (wanted)
            messages[message_count++] = message;
        else {
            ++self->suppressed_messages;
            Py_DECREF(message);
        }

        /* next message */
        p = m;
    }

 nomoredata:
    if (! (message_tuple = PyTuple_New(message_count)))
        goto out;

    while (--message_count >= 0) {
        PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */
    }

    rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending));

 out:
    while (--message_count >= 0) {
        Py_XDECREF(messages[message_count]);
    }
    free(messages);
    return rv;
}
Ejemplo n.º 13
0
static int http_datahandler(myconn_t *rec, int iobytes, int startoffset, int *advancestep)
{
	char *endofhdrs;
	int httpmajorver, httpminorver;
	char *xferencoding;
	int len = iobytes;
	char *bol, *buf;
	int hdrbytes, bodybytes = 0, bodyoffset, initialhdrbuflen, n;

	*advancestep = 0;

	switch (rec->httpdatastate) {
	  case HTTPDATA_HEADERS:
		initialhdrbuflen = STRBUFLEN(rec->httpheaders);
		addtobufferraw(rec->httpheaders, rec->readbuf+startoffset, (iobytes - startoffset));

check_for_endofheaders:
		/* 
		 * Now see if we have the end-of-headers delimiter.
		 * This SHOULD be <cr><lf><cr><lf>, but RFC 2616 says
		 * you SHOULD recognize just plain <lf><lf>.
		 * So try the second form, if the first one is not there.
		 */
		endofhdrs = strstr(STRBUF(rec->httpheaders), "\r\n\r\n");
		if (endofhdrs) {
			endofhdrs += 4;
		}
		else {
			endofhdrs = strstr(STRBUF(rec->httpheaders), "\n\n");
			if (endofhdrs) {
				endofhdrs += 2;
			}
		}

		if (!endofhdrs) {
			/* No more to do for now, but pass the databyte-count back to the caller for further processing. */
			return iobytes;
		}
		else {
			/* Chop the non-header section of data from the headers */
			strbufferchop(rec->httpheaders, strlen(endofhdrs));
		}


		/* We have an end-of-header delimiter, but it could be just a "100 Continue" response */
		sscanf(STRBUF(rec->httpheaders), "HTTP/%d.%d %d", &httpmajorver, &httpminorver, &rec->httpstatus);
		if (rec->httpstatus == 100) {
			/* 
			 * It's a "100"  continue-status.
			 * Just drop this set of headers, and re-do the end-of-headers check.
			 */
			strbuffer_t *newhdrbuf = newstrbuffer(0);
			addtobuffer(newhdrbuf, endofhdrs);
			freestrbuffer(rec->httpheaders);
			rec->httpheaders = newhdrbuf;
			goto check_for_endofheaders;
		}

		/* Have all the http headers now */
		rec->httpdatastate = HTTPDATA_BODY;


		/* 
		 * Find the "Transfer-encoding: " header (if there is one) to see if the transfer uses chunks,
		 * and grab "Content-Length:" to get the length of the body.
		 */
		xferencoding = NULL;
		bol = STRBUF(rec->httpheaders);
		while (bol && !xferencoding && !rec->httpcontentleft) {
			if (strncasecmp(bol, "Transfer-encoding:", 18) == 0) {
				bol += 18; bol += strspn(bol, " ");
				xferencoding = bol;
			}
			else if (strncasecmp(bol, "Content-Length:", 15) == 0) {
				bol += 15; bol += strspn(bol, " ");
				rec->httpcontentleft = atoi(bol);
			}
			else {
				bol = strchr(bol, '\n'); if (bol) bol++;
			}
		}

		if (xferencoding && (strncasecmp(xferencoding, "chunked", 7) == 0)) 
			rec->httpchunkstate = HTTP_CHUNK_INIT;
		else {
			rec->httpchunkstate = (rec->httpcontentleft > 0) ? HTTP_CHUNK_NOTCHUNKED : HTTP_CHUNK_NOTCHUNKED_NOCLEN;
		}

		/* Done with all the http header processing. Call ourselves to handle any remaining data we got after the headers */

		/* 
		 * To figure out how this works, here is the layout of rec->httpheaders. The first 
		 * (initialhdrbuflen) part is what we had before this call to http_datahandler, the 
		 * last (iobytes) part has been copied over from the current rec->buf. 
		 * endofhdrs points into rec->httpheaders. bodyoffset and bodybytes are relative,
		 * so even though the body data is in rec->buf and NOT in rec->httpheaders, we can
		 * calculate the offset and length of the body data.
		 *
		 *                                         endofhdrs
		 *                                              !
		 * !-----------------------------!----------------------------!
		 *
		 * <......initialhdrbuflen.......>
		 *                               <.........iobytes............>
		 * <...............hdrbytes.....................>
		 *                               <..bodyoffset..>
		 *                                              <..bodybytes..>
		 */
		hdrbytes = (endofhdrs - STRBUF(rec->httpheaders));
		bodyoffset = hdrbytes - initialhdrbuflen;
		bodybytes = iobytes - bodyoffset;
		http_datahandler(rec, bodybytes, bodyoffset, advancestep); 
		break;


	  case HTTPDATA_BODY:
		buf = rec->readbuf+startoffset;
		while (len > 0) {
			bodybytes = 0;

			switch (rec->httpchunkstate) {
			  case HTTP_CHUNK_NOTCHUNKED:
			  case HTTP_CHUNK_NOTCHUNKED_NOCLEN:
				bodybytes = len;
				break;

			  case HTTP_CHUNK_INIT:
				/* We're about to pick up a chunk length */
				rec->httpleftinchunk = 0;
				rec->httpchunkstate = HTTP_CHUNK_GETLEN;
				break;

			  case HTTP_CHUNK_GETLEN:
				/* We are collecting the length of the chunk */
				n = hexvalue(*buf);
				if (n == -1) {
					rec->httpchunkstate = HTTP_CHUNK_SKIPLENCR;
				}
				else {
					rec->httpleftinchunk = rec->httpleftinchunk*16 + n;
					buf++; len--;
				}
				break;
				
			  case HTTP_CHUNK_SKIPLENCR:
				/* We've got the length, now skip to the next LF */
				if (*buf == '\n') {
					buf++; len--; 
					rec->httpchunkstate = ((rec->httpleftinchunk > 0) ? HTTP_CHUNK_DATA : HTTP_CHUNK_NOMORE);
				}
				else if ((*buf == '\r') || (*buf == ' ')) {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk len. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				break;

			  case HTTP_CHUNK_DATA:
				/* Passing off the data */
				bodybytes = (len > rec->httpleftinchunk) ? rec->httpleftinchunk : len;
				rec->httpleftinchunk -= bodybytes;
				if (rec->httpleftinchunk == 0) rec->httpchunkstate = HTTP_CHUNK_SKIPENDCR;
				break;

			  case HTTP_CHUNK_SKIPENDCR:
				/* Skip CR/LF after a chunk */
				if (*buf == '\n') {
					buf++; len--; rec->httpchunkstate = HTTP_CHUNK_DONE;
				}
				else if (*buf == '\r') {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk data. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				break;

			  case HTTP_CHUNK_DONE:
				/* One chunk is done, continue with the next */
				rec->httpchunkstate = HTTP_CHUNK_GETLEN;
				break;

			  case HTTP_CHUNK_NOMORE:
				/* All chunks done. Skip the rest (trailers) */
				len = 0;
				break;
			}

			/* bodybytes holds the number of bytes data from buf that should go to userspace */
			if (bodybytes > 0) {
				addtobufferraw(rec->httpbody, buf, bodybytes);
				buf += bodybytes;
				len -= bodybytes;
				if ((rec->httpcontentleft > 0) && (rec->httpcontentleft >= bodybytes)) rec->httpcontentleft -= bodybytes;
				dbgprintf("HTTP bodybytes %d, %d bytes left\n", bodybytes, rec->httpcontentleft);
			}
		}

		/* Done processing body content. Now see if we have all of it - if we do, then proceed to next step. */
		dbgprintf("http chunkstate: %d\n",rec->httpchunkstate);
		switch (rec->httpchunkstate) {
		  case HTTP_CHUNK_NOTCHUNKED:
			if (rec->httpcontentleft <= 0) *advancestep = 1;
			break;

		  case HTTP_CHUNK_NOTCHUNKED_NOCLEN:
			/* We have no content-length: header, so keep going until we do two NULL-reads */
			if ((rec->httplastbodyread == 0) && (bodybytes == 0))
				*advancestep = 1;
			else
				rec->httplastbodyread = bodybytes;
			break;

		  case HTTP_CHUNK_NOMORE:
			*advancestep = 1;
			break;

		  default:
			break;
		}

		break;
	}


	return iobytes;
}
Ejemplo n.º 14
0
void pass2( char a[50],char b[10],int d[60],FILE *fp1,FILE *fp2,FILE *f)
 {
 	  char c,temp2[10],temp1[10],reg[10],A;
      int byte,locctr,assign,n,count=0,checker=0,length,i=1,e,l,x,y,ta=0,j,disp=0,pc,p,opcode,f1,r,zero,f2,f3,hexadecimalval = 0,k=1,remainder,hex[50],temp;
      FILE *fp3;
      fp1 = fopen("sym.txt", "r");
      f = fopen("int.txt", "r");
      fp2 = fopen("object.txt", "w");   
      fscanf(f,"%s",b);
      printf("%s",b);
      fprintf(fp2,"%s",b);
      fprintf(fp2,"%c",' ');
      fscanf(f,"%s",b);
      printf("%s",b);
      fprintf(fp2,"%s",b);
      fscanf(f,"%x",&locctr);
      printf("%x",locctr);
      fprintf(fp2,"%c",' ');
      fprintf(fp2,"%04x",locctr);
      fprintf(fp2,"%c",'\n');
      int hello=0,word=0,resw=0,byte1=0,tc=0;
      while(fscanf(f,"%s",a)!=EOF)
       {     
         count=0;
         FILE *fp = fopen("optab1.txt", "r");
    	 while(fscanf(fp,"%s",b)!=EOF)
    	 {
    		if(strcmp(a,b)==0)
    		{    
    		     count++;
    			 fprintf(fp2,"%c",' ');
    			  fprintf(fp2,"%s",a);
    			  fprintf(fp2,"%c",' ');
    			  fscanf(fp,"%x",&byte);
    			  if(byte==3)
    			  {
    			  	e=1;
    			  	l=1;
    		       }
    			  else if(byte==2)
    			  {
    			  	e=0;
    			  	l=1;
    			  	
    			  }
    			  else if (byte==1)
    			  {
    			  	e=0;
    			  	l=0;
    			  }
    			  fscanf(fp,"%x",&opcode);
    			  if (e==0&&l==0||strcmp(a,"RSUB")==0)
    			  {
    			  	i++;
    			  	if(strcmp(a,"RSUB")==0)
    			  	{
    			  		fscanf(f,"%x",&locctr);
                     fprintf(fp2,"%04x",locctr);
                     fprintf(fp2,"%c",' ');
    			  	   fprintf(fp2,"%02x",opcode);
    			  	   fprintf(fp2,"%s","000000");
    			  	    fprintf(fp2,"%c",'\n');
    			  	   
					  }
					  else
					  {
					  
    			  	    fscanf(f,"%x",&locctr);
                        fprintf(fp2,"%04x",locctr);
                        fprintf(fp2,"%c",' ');
    			  	    fprintf(fp2,"%x",opcode);
					    fprintf(fp2,"%s","000000");
					    fprintf(fp2,"%c",'\n');
				      }
					   
				  }
				  else if(e==0&l==1)
				  {
				  	 i++;
				  	 fscanf(f,"%s",a);
				  	 fprintf(fp2,"%s",a);
				  	 fprintf(fp2,"%c",' ');
    			  	 fscanf(f,"%s",reg);
    			     fprintf(fp2,"%s",reg);
    			  	 fprintf(fp2,"%c",' ');
    			  	 fscanf(f,"%x",&locctr);
                     fprintf(fp2,"%04x",locctr);
                     fprintf(fp2,"%c",' ');
                     fprintf(fp2,"%02x",opcode);
                     if(strcmp(a,"$")!=0)
                     {
                     fprintf(fp2,"%d",a[0]);
                     assign=0;
                    }
                    else
                    {
                    	
                    	assign=1;
                    }
                    fprintf(fp2,"%d",reg[0]);
                      if(assign==1)
                     {
                     	
                     	fprintf(fp2,"%d",'A');
                     }
                     
                     fprintf(fp2,"%s","00");
                     fprintf(fp2,"%c",'\n');
				  	
				  }
    			  else
    			  {
    			     fscanf(f,"%s",a);
    			     fprintf(fp2,"%s",a);
    			      if(strcmp(a,"@")==0)
    			      {
    			      	x=0;
    			      	y=0;
    			      	p=1;
    			      	f1=0;
    			      	f2=0;
    			      	f3=0;
    			      	fscanf(f,"%s",a);
    			      	fprintf(fp2,"%c", ' ');
    			      	 fprintf(fp2,"%s",a);
    			      	 fprintf(fp2,"%c",' ');
    			      	 fp1=fopen("sym.txt","r");
    			      	while(fscanf(fp1,"%s",b)!=EOF)
    			      	   {
    			      	       if(strcmp(a,b)==0)
						       {
						       	tc++;
						       	fscanf(fp1,"%x",&ta);
						       	printf(" \n\nta =%x",ta);
						     	pc=d[i];
							  	i++;
							  	break;
							    }
    			      		
    			      	    }
    			      	       fclose(fp1);
    			      	       disp=ta-pc;
							if(disp<0)
    			      	    {
	                                   sprintf(temp2,"%x",disp);
	                                   strncpy(temp1,temp2+4,4);
	                                  sscanf(temp1,"%x",&disp);
                                    	printf("\n%x",x);
							}
							    fscanf(f,"%x",&locctr);
                                fprintf(fp2,"%04x",locctr);
                                fprintf(fp2,"%c",' ');
							    fprintf(fp2,"%02x",opcode);
							    hexadecimalval=hexvalue(x,y,p,e,l);
							     fprintf(fp2,"%lX", hexadecimalval);         
							     fprintf(fp2,"%04x",disp);
							     fprintf(fp2,"%c",'\n');
                           
					  }	
    			      else if(strcmp(a,"#")==0)
    			      {
    			      	x=0;
    			      	y=1;
    			      	p=0;
    			      	f1=0;
    			      	f2=0;
    			      	f3=0;
    			      	fprintf(fp2,"%c",' ');
    			      	fscanf(f,"%d",&disp);
    			      	fprintf(fp2,"%d",disp);
    			      	fp3 = fopen("io.txt", "w");
    		            fprintf(fp3,"%x",disp);
    		            fclose(fp3);
    		            fp3 = fopen("io.txt", "r");
    		            fscanf(fp3,"%x",&disp);
    		            fclose(fp3);
    			      	fprintf(fp2,"%c",' ');
    			      	fscanf(f,"%x",&locctr);
                        fprintf(fp2,"%04x",locctr);
                        fprintf(fp2,"%c",' ');
    			      	fprintf(fp2,"%02x",opcode);
    			      	hexadecimalval=hexvalue(x,y,p,e,l);
							             fprintf(fp2,"%lX", hexadecimalval);
						                 fprintf(fp2,"%04x",disp);
						                  fprintf(fp2,"%c",'\n');
    			      	                   i++;
    			      }
    			      else if(strcmp(a,"*")==0)
    			      {
    			      	x=1;
    			      	y=1;
						p=1;
						f1=0;
						f2=0;
						f3=0;
    			      	fscanf(f,"%s",a);
    			      	fprintf(fp2,"%c", ' ');
    			      	 fprintf(fp2,"%s",a);
    			      	 fprintf(fp2,"%c",' ');
    			      	   fp1=fopen("sym.txt","r");
    			      	while(fscanf(fp1,"%s",b)!=EOF)
    			      	 {
    			      		if(strcmp(a,b)==0)
							  {
							  	fscanf(fp1,"%x",&ta);
							  	pc=d[i];
							  	i++;
							  	break;
							  }
    			      		
    			      	 }
    			      	 fclose(fp1);
    			      	 disp=ta-pc;
    			      	 int m;
    			      	 m=0;
    			      	    if(disp<0)
    			      	    {
    			      	                sprintf(temp2,"%x",disp);
	                                   strncpy(temp1,temp2+4,4);
	                                  sscanf(temp1,"%x",&disp);
                                    	printf("\n%x",x);
                                    	m++;
							}
							    fscanf(f,"%x",&locctr);
                                fprintf(fp2,"%04x",locctr);
                                fprintf(fp2,"%c",' ');
							    fprintf(fp2,"%02x",opcode);
							    hexadecimalval=hexvalue(x,y,p,e,l);
							    fprintf(fp2,"%lX", hexadecimalval);
							     fprintf(fp2,"%04x",disp);
							     fprintf(fp2,"%c",'\n');
    

    		      }
		         }
		    break;
		    }
		 }
		 fclose(fp);
             
    		     if(strcmp(a,"WORD")==0&&count==0)
    		   {     
    		         word++;
    		     	count++;
    			    fprintf(fp2,"%c",' ');
    			    fprintf(fp2,"%s",a);
    		        fprintf(fp2,"%c",' ');
    		        fscanf(f,"%d",&byte);
    		        fprintf(fp2,"%d",byte);
    		        fprintf(fp2,"%c",' ');
    		        fp3 = fopen("io.txt", "w");
    		        fprintf(fp3,"%x",byte);
    		        fclose(fp3);
    		        fp3 = fopen("io.txt", "r");
    		        fscanf(fp3,"%x",&byte);
    		        fclose(fp3);
    		        fscanf(f,"%x",&locctr);
                    fprintf(fp2,"%04x",locctr);
                    fprintf(fp2,"%c",' ');
							 fprintf(fp2,"%06x",byte);
							 fprintf(fp2,"%c",'\n');   
							 i++;
 
    	   	    }
    	
    		    else if(strcmp(a,"BYTE")==0&&count==0)
    		   {
    		   	byte1++;
    			count++;
    			fprintf(fp2,"%c",' ');
    			fprintf(fp2,"%s",a);
    		    fprintf(fp2,"%c",' ');
    			fscanf(f,"%c",&c);
    			fscanf(f,"%c",&c);
                fprintf(fp2,"%c",c); 	
    			fscanf(f,"%s",a);
    			fprintf(fp2,"%s",a);
    		    fprintf(fp2,"%c",' ');
    		    fscanf(f,"%x",&locctr);
                fprintf(fp2,"%04x",locctr);
                fprintf(fp2,"%c",' ');
    		   int k=0;
    			if(c=='C')
    			{
    				while(a[k]!='\0')
                 	{
                 	
		              c=a[k];
		              k++;
		              fprintf(fp2,"%x",c);
	                }
    			
    				
    			}
    			else if(c=='X')
    			{
    				fprintf(fp2,"%c",' ');
    				fprintf(fp2,"%s",a);
    				
    			}
    				fprintf(fp2,"%c",'\n');
    				i++;
    			
    	       }
    	        		  
         		if(count==0)
    		{
    		 
    		
    		 if(strcmp(a,"RESB")==0||strcmp(a,"RESW")==0)
    		 {
    		 	fprintf(fp2,"%c",' ');
    		 	i++;
    		 	
			 }
			 fprintf(fp2,"%s",a);
			 fprintf(fp2,"%c",' ');
			  if(strcmp(a,"RESB")==0||strcmp(a,"RESW")==0)
    		 {
    		 	resw++;
    		 	fscanf(f,"%s",a);
    		 	fprintf(fp2,"%c",' ');
    		 	fprintf(fp2,"%s",a);
    		 	fscanf(f,"%s",a);
    		 	fprintf(fp2,"%c",' ');
    		 	fprintf(fp2,"%s",a);
    		 	fprintf(fp2,"%c",'\n');
    		 	
    		 	
	
			 }
    		}
        }
       fclose(f);
       fclose(fp2);
}
Ejemplo n.º 15
0
static int rhizome_server_sql_query_fill_buffer(rhizome_http_request *r, char *table, char *column)
{
  unsigned char blob_value[r->source_record_size*2+1];

  if (debug & DEBUG_RHIZOME_TX)
    DEBUGF("populating with sql rows at offset %d",r->buffer_length);
  if (r->source_index>=r->source_count)
    {
      /* All done */
      return 0;
    }

  int record_count=(r->buffer_size-r->buffer_length)/r->source_record_size;
  if (record_count<1) {
    if (debug & DEBUG_RHIZOME_TX)
      DEBUGF("r->buffer_size=%d, r->buffer_length=%d, r->source_record_size=%d",
	   r->buffer_size, r->buffer_length, r->source_record_size);
    return WHY("Not enough space to fit any records");
  }

  sqlite3_stmt *statement = sqlite_prepare("%s LIMIT %lld,%d", r->source, r->source_index, record_count);
  if (!statement)
    return -1;
  if (debug & DEBUG_RHIZOME_TX)
    DEBUG(sqlite3_sql(statement));
  sqlite_retry_state retry = SQLITE_RETRY_STATE_DEFAULT;
  while(  r->buffer_length + r->source_record_size < r->buffer_size
      &&  sqlite_step_retry(&retry, statement) == SQLITE_ROW
  ) {
    r->source_index++;
    if (sqlite3_column_count(statement)!=2) {
      sqlite3_finalize(statement);
      return WHY("sqlite3 returned multiple columns for a single column query");
    }
    sqlite3_blob *blob;
    const unsigned char *value;
    int column_type=sqlite3_column_type(statement, 0);
    switch(column_type) {
    case SQLITE_TEXT:	value=sqlite3_column_text(statement, 0); break;
    case SQLITE_BLOB:
      if (debug & DEBUG_RHIZOME_TX)
	DEBUGF("table='%s',col='%s',rowid=%lld", table, column, sqlite3_column_int64(statement,1));

      int ret;
      int64_t rowid = sqlite3_column_int64(statement, 1);
      do ret = sqlite3_blob_open(rhizome_db, "main", table, column, rowid, 0 /* read only */, &blob);
	while (sqlite_code_busy(ret) && sqlite_retry(&retry, "sqlite3_blob_open"));
      if (!sqlite_code_ok(ret)) {
	WHYF("sqlite3_blob_open() failed, %s", sqlite3_errmsg(rhizome_db));
	continue;
      }
      sqlite_retry_done(&retry, "sqlite3_blob_open");
      if (sqlite3_blob_read(blob,&blob_value[0],
			/* copy number of bytes based on whether we need to
			    de-hex the string or not */
			    r->source_record_size*(1+(r->source_flags&1)),0)
	  !=SQLITE_OK) {
	WHYF("sqlite3_blob_read() failed, %s", sqlite3_errmsg(rhizome_db));
	sqlite3_blob_close(blob);
	continue;
      }
      value = blob_value;
      sqlite3_blob_close(blob);
      break;
    default:
      /* improper column type, so don't include in report */
      WHYF("Bad column type %d", column_type);
      continue;
    }
    if (r->source_flags&1) {
      /* hex string to be converted */
      int i;
      for(i=0;i<r->source_record_size;i++)
	/* convert the two nybls and make a byte */
	r->buffer[r->buffer_length+i]
	  =(hexvalue(value[i<<1])<<4)|hexvalue(value[(i<<1)+1]);
    } else
      /* direct binary value */
      bcopy(value,&r->buffer[r->buffer_length],r->source_record_size);
    r->buffer_length+=r->source_record_size;
    
  }
  sqlite3_finalize(statement);
  return 0;
}