Esempio n. 1
0
unsigned char* hex2bin(char *hex, unsigned char *bin, int iLen, int *oLen) {
	int bLen;
	int i;

	iLen = (iLen <= 0) ? StrLen(hex) : iLen;

	if(StrNCompare(hex, "0x", 2) == 0) {
		/* hex string has 0x prefix */
		hex = hex + 2;
		iLen -= 2;			
	}	

	if(iLen%2 != 0) {
		/* hex string is not a multiple of 2 in length */
		return NULL;
	}

	bLen = iLen / 2;
	MemSet(bin,0,bLen);
	
	for(i = 0; i < bLen; i++) {
		char hbyte = *hex++;
		char lbyte = *hex++;

		if(!is_hex(hbyte) || !is_hex(lbyte)) {
			/* invalid character */
			return NULL;
		}
		*bin++ = (unsigned char) (hex2byte(hbyte)<<4 | hex2byte(lbyte));
	}

	*oLen = i;

	return bin;
}
gboolean
mm_plugin_base_get_device_ids (MMPluginBase *self,
                               const char *subsys,
                               const char *name,
                               guint16 *vendor,
                               guint16 *product)
{
    MMPluginBasePrivate *priv;
    GUdevDevice *device = NULL;
    const char *vid, *pid;
    gboolean success = FALSE;

    g_return_val_if_fail (self != NULL, FALSE);
    g_return_val_if_fail (MM_IS_PLUGIN_BASE (self), FALSE);
    g_return_val_if_fail (subsys != NULL, FALSE);
    g_return_val_if_fail (name != NULL, FALSE);
    if (vendor)
        g_return_val_if_fail (*vendor == 0, FALSE);
    if (product)
        g_return_val_if_fail (*product == 0, FALSE);

    priv = MM_PLUGIN_BASE_GET_PRIVATE (self);

    device = g_udev_client_query_by_subsystem_and_name (priv->client, subsys, name);
    if (!device)
        goto out;

    vid = g_udev_device_get_property (device, "ID_VENDOR_ID");
    if (!vid || (strlen (vid) != 4))
        goto out;

    if (vendor) {
        *vendor = (guint16) (hex2byte (vid + 2) & 0xFF);
        *vendor |= (guint16) ((hex2byte (vid) & 0xFF) << 8);
    }

    pid = g_udev_device_get_property (device, "ID_MODEL_ID");
    if (!pid || (strlen (pid) != 4)) {
        *vendor = 0;
        goto out;
    }

    if (product) {
        *product = (guint16) (hex2byte (pid + 2) & 0xFF);
        *product |= (guint16) ((hex2byte (pid) & 0xFF) << 8);
    }

    success = TRUE;

out:
    if (device)
        g_object_unref (device);
    return success;
}
Esempio n. 3
0
static char *
get_decoded_property (GUdevDevice *device, const char *property)
{
	const char *orig, *p;
	char *unescaped, *n;
	guint len;

	p = orig = g_udev_device_get_property (device, property);
	if (!orig)
		return NULL;

	len = strlen (orig);
	n = unescaped = g_malloc0 (len + 1);
	while (*p) {
		if ((len >= 4) && (*p == '\\') && (*(p+1) == 'x')) {
			*n++ = (char) hex2byte (p + 2);
			p += 4;
			len -= 4;
		} else {
			*n++ = *p++;
			len--;
		}
	}

	return unescaped;
}
Esempio n. 4
0
static u8 * add_hex(u8 *pos, u8 *end, const char *str)
{
    const char *s;
    int val;

    s = str;
    while (*s) {
        while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n' ||
                *s == ':')
            s++;
        if (*s == '\0')
            break;
        if (*s == '#') {
            while (*s != '\0' && *s != '\r' && *s != '\n')
                s++;
            continue;
        }

        val = hex2byte(s);
        if (val < 0) {
            printf("Invalid hex encoding '%s'\n", s);
            return NULL;
        }
        if (pos == end) {
            printf("Too long frame\n");
            return NULL;
        }
        *pos++ = val;
        s += 2;
    }

    return pos;
}
/* free return value by caller */
gchar *
utils_hexstr2bin (const gchar * hex, size_t len)
{
	size_t i;
	int a;
	const gchar *ipos = hex;
	gchar *buf = NULL;
	gchar *opos;

	/* Length must be a multiple of 2 */
	if ((len % 2) != 0)
		return NULL;

	opos = buf = g_malloc0 ((len / 2) + 1);
	for (i = 0; i < len; i += 2) {
		a = hex2byte (ipos);
		if (a < 0) {
			g_free (buf);
			return NULL;
		}
		*opos++ = a;
		ipos += 2;
	}
	return buf;
}
Esempio n. 6
0
int ICACHE_FLASH_ATTR URLDecode( char * decodeinto, int maxlen, const char * buf )
{
	int i = 0;

	for( ; buf && *buf; buf++ )
	{
		char c = *buf;
		if( c == '+' )
		{
			decodeinto[i++] = ' ';
		}
		else if( c == '?' || c == '&' )
		{
			break;
		}
		else if( c == '%' )
		{
			if( *(buf+1) && *(buf+2) )
			{
				decodeinto[i++] = hex2byte( buf+1 );
				buf += 2;
			}
		}
		else
		{
			decodeinto[i++] = c;
		}
		if( i >= maxlen -1 )  break;
		
	}
	decodeinto[i] = 0;
	return i;
}
Esempio n. 7
0
/* text is 6*2 + 5 + 1 = 18 bytes long, mac is 6 bytes long */
bool TXT2MAC(unsigned char * mac, char * text)
{
   char  tmp[18];
   int   maci[6];

   /* create a temporary storage */
   strncpy(tmp, text, 17);
   tmp[17] = '\0';

   /*           1111111 */
   /* 01234567890123456 */
   /* 00-00-00-00-00-00 */

   for (int i = 0; i < 5; i++) 
   {
      if (tmp[2 + i * 3] != '-' && tmp[2 + i * 3] != ':') return false;
      tmp[2 + i * 3] = '\0';
   }

   for (int i = 0; i < 6; i++) maci[i] = hex2byte(&tmp[0 + i * 3]); 

   if (maci[0] >= 0 && maci[1] >= 0 && maci[2] >= 0 && maci[3] >= 0 && maci[4] >= 0 && maci[5] >= 0)
   {
      for (int i = 0; i < 6; i++) mac[i] = maci[i];
      return true;
   }
   else
   {
      return false;
   }
}
Esempio n. 8
0
int main() {
	DIR *dp;
	struct dirent *ep;
	unsigned char buffer[BUFTAM];

	if (chdir("letras") == -1) {
		perror("No se puede cambiar al directorio \"letras\"");
		return 1;
	}
	
	int i;
	for (i=0; i<256; i++) {
		int encontrado = 0;
		
		dp = opendir ("./");
		if (!dp) {
			perror("No se puede leerse el directorio \"letras\"");
			return 1;
		}

		while (ep = readdir (dp)) {
			char nombre[32];
	
			uint8_t num;
			num = hex2byte(ep->d_name);
			
			if (num != i)
				continue;
			
			encontrado = 1;
	
			strncpy(nombre, ep->d_name+3, 32);
			if (strlen(nombre)<4)
				continue;
			nombre[strlen(nombre)-4]=0;
			
			printf("%s\n", ep->d_name);
			
			/*printf("  case 0x%.2x:\n",num);
			printf("    temp = pgm_read_byte_near(_%s);\n", nombre);
			printf("    *alto = (temp&0x0f)+1;\n");
			printf("    *ancho = ((temp&0xf0)>>4)+1;\n");
			printf("    for (i=0; i<((*alto)*(*ancho))%%8==0?((*alto)*(*ancho)/8):((*alto)*(*ancho)/8+1); i++)\n");
			printf("      buffer[i] = pgm_read_byte_near(_%s + i + 1);\n", nombre);
			printf("    break;\n");*/
		}
		if (!encontrado)
			printf("null\n");
	
		closedir (dp);
	}

	return 0;

}
Esempio n. 9
0
void Token::sendAPDUFromFile(char *f){
	LONG lReturn;
	const DWORD  cdwRecv = 1024;
	DWORD dwRecv;
	BYTE *pbRecv;


	pbRecv = new BYTE[cdwRecv];

	ifstream fin(f);

	if (!fin.is_open()){
		cout << "[*] ERROR: Failed open '" << f <<"'" << endl;
		return;
	}

	string line;
	while (getline(fin, line)){
		if (line.find(">>> ") == 0){
			line.replace(0, 4, "");

			vector<string> sar;
			vector<BYTE> bar;
			split(line, ":", sar);
			hex2byte(sar, bar);

			//
			// Send data to card
			//
			DWORD dwRecv = cdwRecv;
			lReturn = SCardTransmit(hCardHandle,
				SCARD_PCI_T1,
				bar.data(),
				bar.size(),
				NULL,
				pbRecv,
				&dwRecv);
			if (SCARD_S_SUCCESS != lReturn)	{
				cout << "[*] ERROR: Failed SCardTransmit (" << bar << "):" << lReturn << endl;
				goto THE_END;
			}
			if (this->debug){
				cout << ">>> "; showarr(bar.data(), bar.size(), ':');
				cout << "<<< "; showarr(pbRecv, dwRecv, ':');
			}
		}
	}

	THE_END:
	fin.close();

	delete[] pbRecv;

}
Esempio n. 10
0
extern int str2mac(uint8_t *outmac /* 6 bytes */, const char *s)
{
    size_t i;

    /* break it down as one case for the first "HH", the 5 x through loop for
     * each ":HH" where HH is a two hex nibbles in ASCII. */

    *outmac = hex2byte(s);
    ++outmac;
    s += 2; /* don't skip colon yet - helps generalise loop. */

    for (i = 1; i < 6; ++i)
    {
        s += 1;
        *outmac = hex2byte(s);
        ++outmac;
        s += 2;
    }

    return 0; /* ok */
}
Esempio n. 11
0
static void test_helper_hex_single(const char* cs) {
	CU_ASSERT_EQUAL(strlen(cs), 2);
	
	char c1 = *cs;
	char c2 = *(cs+1);
	
	char val = hex2byte(c1, c2);
	
	char cookie = 42;
	char[3] buf;
	*(buf+2) = cookie;
	
	byte2hex(val, bufs);
	
	CU_ASSERT_EQUAL(toupper(*buf), toupper(c1));
	CU_ASSERT_EQUAL(toupper(*(buf+1)), toupper(c2));
	char val2 = hex2byte(*buf, *(buf+1));
	CU_ASSERT_EQUAL(val, val2);
	
	CU_ASSERT_EQUAL(*(buf+2), cookie);
}
Esempio n. 12
0
uint32_t hex2word(char *hex, char **next) {
	uint32_t w = 0;
	uint8_t b;

	while ((b = hex2byte(*hex++)) != 0xFF)
		w = (w << 4) | b;

	if (next)
		*next = hex-1;

	return w;
}
Esempio n. 13
0
static bool read_xbm_body(QIODevice *device, int w, int h, QImage *outImage)
{
    const int buflen = 300;
    char buf[buflen + 1];

    qint64 readBytes = 0;

    // scan for database
    for (;;) {
        if ((readBytes = device->readLine(buf, buflen)) <= 0) {
            // end of file
            return false;
        }

        buf[readBytes] = '\0';
        if (QByteArray::fromRawData(buf, readBytes).contains("0x"))
            break;
    }

    if (outImage->size() != QSize(w, h) || outImage->format() != QImage::Format_MonoLSB) {
        *outImage = QImage(w, h, QImage::Format_MonoLSB);
        if (outImage->isNull())
            return false;
    }

    outImage->setColorCount(2);
    outImage->setColor(0, qRgb(255,255,255));        // white
    outImage->setColor(1, qRgb(0,0,0));                // black

    int           x = 0, y = 0;
    uchar *b = outImage->scanLine(0);
    char  *p = buf + QByteArray::fromRawData(buf, readBytes).indexOf("0x");
    w = (w+7)/8;                                // byte width

    while (y < h) {                                // for all encoded bytes...
        if (p) {                                // p = "0x.."
            *b++ = hex2byte(p+2);
            p += 2;
            if (++x == w && ++y < h) {
                b = outImage->scanLine(y);
                x = 0;
            }
            p = strstr(p, "0x");
        } else {                                // read another line
            if ((readBytes = device->readLine(buf,buflen)) <= 0)        // EOF ==> truncated image
                break;
            p = buf + QByteArray::fromRawData(buf, readBytes).indexOf("0x");
        }
    }

    return true;
}
Esempio n. 14
0
/**
 * hexstr2bin - Convert ASCII hex string into binary data
 * @hex: ASCII hex string (e.g., "01ab")
 * @buf: Buffer for the binary data
 * @len: Length of the text to convert in bytes (of buf); hex will be double
 * this size
 * Returns: 0 on success, -1 on failure (invalid hex string)
 */
int hexstr2bin(const char *hex, u8 *buf, size_t len)
{
	int i, a;
	const char *ipos = hex;
	u8 *opos = buf;

	for (i = 0; i < len; i++) {
		a = hex2byte(ipos);
		if (a < 0)
			return -1;
		*opos++ = a;
		ipos += 2;
	}
	return 0;
}
Esempio n. 15
0
File: util.c Progetto: greearb/iw-ct
char *hex2bin(const char *hex, char *buf)
{
	char *result = buf;
	int d;

	while (hex[0]) {
		d = hex2byte(hex);
		if (d < 0)
			return NULL;
		buf[0] = d;
		buf++;
		hex += 2;
	}

	return result;
}
Esempio n. 16
0
void storeLine(int fo, char* line) {
	int i;
	int offset = 0;
	unsigned char buf[16];
	int size = strlen(line) / 2;

	if (size > 16) {
		size = 16;
	}

	for (i = 0; i < size; i++) {
		offset = i*2;
		buf[i] = hex2byte(line + offset);		
	}
	write(fo, buf, size);

}
Esempio n. 17
0
static int8_t
hexstr2bin(const char    *hex,
           uint8_t *buf,
           size_t   len)
{
    int i = 0;
    int16_t a = 0;
    const char *inptr = hex;
    uint8_t *outptr = buf;

    for (i = 0; i < (int)len; i++)
    {
        a = hex2byte(inptr);
        inptr +=2;
        if (a < 0) return NV_KO;
        *outptr++ = a;
    }

    return NV_OK;
}
static void createFromHex(char *buf, int maxlen, const char *str)
{
    const char *pos = str;
    int len = 0;
    int val;

    while(*pos){
        if (len == maxlen)
            break;
        val = hex2byte(pos);
    if (val < 0) {
            val = hex2num(*pos);
            if (val < 0)
                break;
            buf[len++] = val;
    } else {
            buf[len++] = val;
            pos += 2;
        }
    }
}
Esempio n. 19
0
/*
 * Get data
 *  
 *  Returns with either a data record or NULL for EOF
 */
pic_data *
inhx32_get(FILE *fp)
{
	char line[STRLEN];
	uint8_t bb, tt;
	uint16_t aaaa, ix, i;
	static uint16_t extended_addr = 0;
	pic_data *data;

	do {
		/* Get line */
		if (inhx32_fgets(line, fp, &bb, &aaaa, &tt, &extended_addr) == NULL)
			return NULL;	/* EOF */
		if (tt == TT_EOF)
			return NULL;	/* EOF */
	}
	while (tt != TT_DATA);		/* Not a data record */

	/* Allocate data */
	data = (pic_data *)calloc(1, sizeof(pic_data));
	if (data == NULL) {
		printf("%s: fatal error: calloc failed\n", __func__);
		io_exit(EX_OSERR); /* Panic */
	}

	/* Store address and number of bytes */
	data->address = (extended_addr << 16) | aaaa;
	data->nbytes = bb;

	/* Extract and store bytes */
	ix = HHHH;
	for (i = 0; i < bb; ++i) {
		data->bytes[i] = hex2byte(&line[ix]);
		ix += 2;
	}

	/* Return data */
	return data;
}
Esempio n. 20
0
main()
{

  int i;
  int bytes_plaintext;
  //char *plaintext="0000000000000000000000000000000000000000000000000000000000000000";
  //unsigned char *plaintext="616263";
  //unsigned char *plaintext="cc";
  unsigned char *plaintext="3a3a819c48efde2ad914fbf00e18ab6bc4f14513ab27d0c178a188b61431e7f5623cb66b23346775d386b50e982c493adbbfc54b9a3cd383382336a1a0b2150a15358f336d03ae18f666c7573d55c4fd181c29e6ccfde63ea35f0adf5885cfc0a3d84a2b2e4dd24496db789e663170cef74798aa1bbcd4574ea0bba40489d764b2f83aadc66b148b4a0cd95246c127d5871c4f11418690a5ddf01246a0c80a43c70088b6183639dcfda4125bd113a8f49ee23ed306faac576c3fb0c1e256671d817fc2534a52f5b439f72e424de376f4c565cca82307dd9ef76da5b7c4eb7e085172e328807c02d011ffbf33785378d79dc266f6a5be6bb0e4a92eceebaeb1";

  // plaintext
  memcpy(s,plaintext,strlen(plaintext)+1);
  bytes_plaintext=strlen(s)/2;
  hex2byte(s, m); // transforms from left (string) to right (bytes)
  for (i = 0;i < bytes_plaintext;++i) printf("%02x",m[i]); printf("\n"); fflush(stdout);    
  
  crypto_hash(c,m,bytes_plaintext);
  
  for (i = 0;i < 512/8;++i) printf("%02x",c[i]); printf("\n"); fflush(stdout);

  return 0;
}
Esempio n. 21
0
/*
 * returns size of binary, 0 on failure.
 */
static
int espprint_decode_hex(netdissect_options *ndo,
			u_char *binbuf, unsigned int binbuf_len,
			char *hex)
{
	unsigned int len;
	int i;

	len = strlen(hex) / 2;
		
	if (len > binbuf_len) {
		(*ndo->ndo_warning)(ndo, "secret is too big: %d\n", len);
		return 0;
	}
		
	i = 0;
	while (hex[0] != '\0' && hex[1]!='\0') {
		binbuf[i] = hex2byte(ndo, hex);
		hex += 2;
		i++;
	}

	return i;
}
Esempio n. 22
0
// 客户端解析服务器响应的协商包,从协商包中解析出临时密钥,并使用自己的私钥进行解密
// 服务器端解析客户端发来的协商包,并填充服务器包解析器
int pkg_talk_parse(packet_parser_t *pkg, const char* xml)
{
	iks *x, *e, *c;
	int result=0;
	int dest_len;

	if(NULL==xml) return NULL_ERROR;

	x =	iks_tree (xml, 0, &result);
	if(!x) return NULL_ERROR;
	if(result != IKS_OK)
	{
		iks_delete(x);
		return IKS_BADXML;
	}

	if(0 == iks_strcmp("connection",iks_name(x)))
	{
		char* tmp = NULL;
		char *tempkey;
		char *output;

		tmp = iks_find_attrib(x, "type");
		if(NULL != tmp){
			if(strcmp(tmp, "create")==0)
				set_talk_type(1, pkg); //说明为服务端
			else
				set_talk_type(0, pkg); //说明为客户端
		}

		if(1 == pkg->talk_type)
		{
			//说明本端为服务端
			tmp = iks_find_cdata(x, "client-id");
			set_client_id(tmp, pkg);

			tmp = iks_find_cdata(x, "public-key");
			if(SUCCESS != set_talk_crt_public_key(tmp, pkg))
				return SET_TALK_CRT_KEY_ERROR;

			tmp = iks_find_attrib(iks_find(x,"public-key"), "type");
			if(SUCCESS != set_talk_crt_type(tmp, pkg))
				return SET_TALK_CRT_TYPE_ERROR;

			e = iks_find(x,"encryption");
			while( e ){
				tmp = iks_find_cdata(e, "allow");
				if(SUCCESS == set_transfer_crt_type(tmp, pkg)) break;
				e = iks_next(e);
			}
			// 服务器端设置传输数据使用的临时密钥
			set_transfer_crt_key(TRANSFERKEY, pkg);

			c = iks_find(x,"compression");
			while( c ){
				tmp = iks_find_cdata(c, "allow");
				if(SUCCESS == set_cps_type(tmp, pkg)) break;
				c = iks_next(c);
			}
		}
		else if(0 == pkg->talk_type)
		{
			// 说明本端为客户端
			tempkey = iks_find_cdata(x,"encryption");
			output = (char *)calloc(strlen(tempkey)/2+1, 1);
			hex2byte(tempkey, strlen(tempkey), (unsigned char *)output);
			if (pkg->asym_encrypt_hook == NULL)
			{
				tempkey = (char *)rsa_encrypt((unsigned char *)output, strlen(tempkey)/2, &dest_len, pkg->curr_ert.ert_keys[1], CRYPT_TYPE_DECRYPT);
			}
			else
			{
				tempkey = (char *)pkg->asym_encrypt_hook((unsigned char *)output, strlen(tempkey)/2, &dest_len, pkg->curr_ert.ert_keys[1], CRYPT_TYPE_DECRYPT);
			}
			free(output);
			// 比较服务器端响应的压缩加密方式与客户端请求的是否相同
			if( SUCCESS != set_transfer_crt_key(tempkey, pkg))
				return SET_TRANSFER_ERT_KEY_ERROR;
			free(tempkey);
			if( SUCCESS != cmp_transfer_crt_type(iks_find_attrib(iks_find(x, "encryption"), "type"), pkg) )
				return CMP_TRANSFER_CRT_TYPE_ERROR;
			if( SUCCESS != cmp_cps_type(iks_find_cdata(x, "compression"), pkg) )
				return CMP_CPS_TYPE_ERROR;
			set_heatbeat("client", iks_find_attrib(iks_find(x, "heartbeat"), "seconds"), pkg);
		}	
	} 
	
	//iks_parser_delete (p);
	iks_delete(x);
	return SUCCESS;
}
Esempio n. 23
0
void TSampler::process_signal(char* pSignal) {
  if (    (pSignal[0] == 'F')
       && (pSignal[1] == 'I')
       && (pSignal[2] == 'L')
       && (pSignal[3] == 'I') ) {
    char filename[cStringLength];
    strcpy(filename, pSignal + 4);
    open_file(filename);
  }
  if (    (pSignal[0] == 'F')
       && (pSignal[1] == 'I')
       && (pSignal[2] == 'L')
       && (pSignal[3] == 'O') ) {
        char filename[cStringLength];
    int length;
    length = (unsigned int)(pSignal[ 4]-48)*1000000000
           + (unsigned int)(pSignal[ 5]-48)*100000000
           + (unsigned int)(pSignal[ 6]-48)*10000000
           + (unsigned int)(pSignal[ 7]-48)*1000000
           + (unsigned int)(pSignal[ 8]-48)*100000
           + (unsigned int)(pSignal[ 9]-48)*10000
           + (unsigned int)(pSignal[10]-48)*1000
           + (unsigned int)(pSignal[11]-48)*100
           + (unsigned int)(pSignal[12]-48)*10
           + (unsigned int)(pSignal[13]-48);
    strcpy(filename, pSignal + 14);
    write_history_to_file(length, filename);
  }
  if (    (pSignal[0] == 'N')
       && (pSignal[1] == 'O')
       && (pSignal[2] == 'T')
       && (pSignal[3] == 'E') ) {
    int polych = (unsigned int)(pSignal[4] - 48);
      // polych is the Poly-Channel, i.e. the index
      // of the channel which shall play/stop the note.
    if ((polych >= 0) && (polych < cPolyNum))
    {
      if (pSignal[5] == '1') {
        StkFloat speedfactor =
          (pSignal[6]  - 48) * 10 +
          (pSignal[7]  - 48)     +
          (pSignal[8]  - 48) * 0.1 +
          (pSignal[9]  - 48) * 0.01 +
          (pSignal[10]  - 48) * 0.001 +
          (pSignal[11] - 48) * 0.0001 +
          (pSignal[12] - 48) * 0.00001 +
          (pSignal[13] - 48) * 0.000001;
        StkFloat velocity = StkFloat(hex2byte(
          pSignal[14], pSignal[15]
        )) / 127.0;
        noteon(polych, speedfactor, velocity);
      }
      else if (pSignal[5] == '0') {
        noteoff(polych);
      }
    }
    else
    {
      std::cout << "Error: The master says the slave "
                << "to play the poly-channel with index " 
                << polych << ". This index is not valid "
                << "Please check, whether master and slave "
                << "use the same number of poly-channels. "
                << "You can find this in the"
                << "constant-declarations" << std::endl; 
    }

  }
  if (    (pSignal[0] == 'V')
       && (pSignal[1] == 'O')
       && (pSignal[2] == 'L')
       && (pSignal[3] == 'I') ) {
    VolumeInc();
  }
  if (    (pSignal[0] == 'V')
       && (pSignal[1] == 'O')
       && (pSignal[2] == 'L')
       && (pSignal[3] == 'D') ) {
    VolumeDec();
  }
  if (    (pSignal[0] == 'A')
       && (pSignal[1] == 'D')
       && (pSignal[2] == 'S')
       && (pSignal[3] == 'R') ) {
    if (pSignal[4] == 'a') {
      if (pSignal[5] == '+') {
        zADSR_A += cADSRaStep;
      }
      else if (pSignal[5] == '-') {
        zADSR_A -= cADSRaStep;
        if (zADSR_A <= 0) {
          zADSR_A = cADSRaStep;
        }
      }
    }
    else if (pSignal[4] == 'd') {
      if (pSignal[5] == '+') {
        zADSR_D += cADSRdStep;
      }
      else if (pSignal[5] == '-') {
        zADSR_D -= cADSRdStep;
        if (zADSR_D <= 0) {
          zADSR_D = cADSRdStep;
        }
      }
    }
    else if (pSignal[4] == 's') {
      if (pSignal[5] == '+') {
        zADSR_S += cADSRsStep;
        if (zADSR_S > 1) {
          zADSR_S = 1;
        }
        if (zADSR_S < 0) {
          zADSR_S = 0;
        }
      }
      else if (pSignal[5] == '-') {
        zADSR_S -= cADSRsStep;
      }
    }
    else if (pSignal[4] == 'r') {
      if (pSignal[5] == '+') {
        zADSR_R += cADSRrStep;
      }
      else if (pSignal[5] == '-') {
        zADSR_R -= cADSRrStep;
        if (zADSR_R <= 0) {
          zADSR_R = cADSRrStep;
        }
      }
    }
    else if (pSignal[4] == '0')
    {
      zADSRon = 0;
    }
    else if (pSignal[4] == '1')
    {
      zADSRon = 1;
    }
    refreshADSR();
  }
  if (    (pSignal[0] == 'S')
       && (pSignal[1] == 'H')
       && (pSignal[2] == 'O')
       && (pSignal[3] == 'W')
       && (pSignal[4] == 'A'))
  {
      printADSR();
  }
  if (    (pSignal[0] == 'T')
       && (pSignal[1] == 'I')
       && (pSignal[2] == 'M')
       && (pSignal[3] == 'E') )
  {
    int numOfFrames = 
      (unsigned int)(pSignal[5] - 48) * 100000 +
      (unsigned int)(pSignal[6] - 48) * 10000 +
      (unsigned int)(pSignal[7] - 48) * 1000 +
      (unsigned int)(pSignal[8] - 48) * 100 +
      (unsigned int)(pSignal[9] - 48) * 10 +
      (unsigned int)(pSignal[10] - 48);
    if (pSignal[4] == '-')
    {
      numOfFrames *= -1;
    }
    TimeShift(numOfFrames);
  }
}
Esempio n. 24
0
/*
 * Get line
 *
 * Reads input line and updates the byte count and address fields.
 *
 * The record type field (*tt) is also returned as:
 *
 *	TT_EOF		EOF record
 *	TT_DATA		Data record
 *	~TT_DATA	Not a data record (255)
 */
char *
inhx32_fgets(char *line, FILE *fp,
	uint8_t *bb, uint16_t *aaaa, uint8_t *tt, uint16_t *extended_addr)
{
	size_t len;
	uint8_t cc, _tt;
	uint16_t i;

	*bb = 0;
	*aaaa = 0;
	*tt = ~TT_DATA; /* Not a data record (255) */

	/* Get line */
	if (fgets(line, STRLEN, fp) == NULL)
		return NULL; /* EOF */

	/* Validate line prefix */
	if (line[0] != ':')
		return line;

	/* Remove CRLF */
	rmcrlf(line, STRLEN);

	/* Validate line length */
	len = strlen(line);
	if ((len & 1) == 0 || len < 11)
		return line;

	/* Validate checksum */
	cc = 0;
	for (i = 1; line[i]; i += 2)
		cc += hex2byte(&line[i]); 
	if (cc != 0)
		return line;

	/* Determine number of bytes in this line */
	*bb = hex2byte(&line[BB]);
#if 0
	/* Validate number of bytes */
	if (*bb > PIC_BYTLEN)
		return line;
#endif
	/* Validate line length */
	if (len != (2 * *bb + 11))
		return line;

	/* Determine address for this line */
	*aaaa = (hex2byte(&line[AAAA]) << 8) |
		hex2byte(&line[AAAA + 2]);

	/* Determine record type */
	_tt = hex2byte(&line[TT]);

	/* Process data record */
	if (_tt == TT_DATA) {
		/* Validate line length */
		if (*bb == 0)
			return line;	/* Not a data record */

		/* Validate alignment */
		if (p.pic && (*bb % p.pic->align)) {
#if 0
			printf("%s: information: unaligned input ignored\n", __func__);
#endif
			return line;	/* Not a data record */
		}
	}
	/* Process extended address record */
	else if (_tt == TT_EXTENDED_LINEAR_ADDRESS) {
		/* Validate extended address */
		if (*aaaa != 0 || *bb != 2)
			return line;	/* Not a data record */

		/* Determine extended address */
		*extended_addr = (hex2byte(&line[HHHH]) << 8) |
				hex2byte(&line[HHHH + 2]);
		return line;		/* Not a data record */
	}
	/* Ignore other records */
	else {
		return line;		/* Not a data record */
	}

	/* Return data record */
	*tt = TT_DATA;

	return line;
}
Esempio n. 25
0
int
main(int argc, char *argv[])
{
	struct stat st;
	int ch, rc, errs, am_readlink;
	int lsF, fmtchar, usestat, nfs_handle, fn, nonl, quiet;
	const char *statfmt, *options, *synopsis;
	char dname[sizeof _PATH_DEV + MNAMELEN] = _PATH_DEV;
	fhandle_t fhnd;
	const char *file;

	am_readlink = 0;
	lsF = 0;
	fmtchar = '\0';
	usestat = 0;
	nfs_handle = 0;
	nonl = 0;
	quiet = 0;
	linkfail = 0;
	statfmt = NULL;
	timefmt = NULL;

	if (strcmp(getprogname(), "readlink") == 0) {
		am_readlink = 1;
		options = "fn";
		synopsis = "[-fn] [file ...]";
		statfmt = "%Y";
		fmtchar = 'f';
		quiet = 1;
	} else {
		options = "f:FHlLnqrst:x";
		synopsis = "[-FLnq] [-f format | -l | -r | -s | -x] "
		    "[-t timefmt] [file|handle ...]";
	}

	while ((ch = getopt(argc, argv, options)) != -1)
		switch (ch) {
		case 'F':
			lsF = 1;
			break;
                case 'H':
			nfs_handle = 1;
			break;
		case 'L':
			usestat = 1;
			break;
		case 'n':
			nonl = 1;
			break;
		case 'q':
			quiet = 1;
			break;
		case 'f':
			if (am_readlink) {
				statfmt = "%R";
				break;
			}
			statfmt = optarg;
			/* FALLTHROUGH */
		case 'l':
		case 'r':
		case 's':
		case 'x':
			if (fmtchar != 0)
				errx(1, "can't use format '%c' with '%c'",
				    fmtchar, ch);
			fmtchar = ch;
			break;
		case 't':
			timefmt = optarg;
			break;
		default:
			usage(synopsis);
		}

	argc -= optind;
	argv += optind;
	fn = 1;

	if (fmtchar == '\0') {
		if (lsF)
			fmtchar = 'l';
		else {
			fmtchar = 'f';
			statfmt = DEF_FORMAT;
		}
	}

	if (lsF && fmtchar != 'l')
		errx(1, "can't use format '%c' with -F", fmtchar);

	switch (fmtchar) {
	case 'f':
		/* statfmt already set */
		break;
	case 'l':
		statfmt = lsF ? LSF_FORMAT : LS_FORMAT;
		break;
	case 'r':
		statfmt = RAW_FORMAT;
		break;
	case 's':
		statfmt = SHELL_FORMAT;
		break;
	case 'x':
		statfmt = LINUX_FORMAT;
		if (timefmt == NULL)
			timefmt = "%c";
		break;
	default:
		usage(synopsis);
		/*NOTREACHED*/
	}

	if (timefmt == NULL)
		timefmt = TIME_FORMAT;

	errs = 0;
	do {
		if (argc == 0) {
			if (fdevname_r(STDIN_FILENO, dname +
			    sizeof _PATH_DEV - 1, MNAMELEN) == 0)
				file = dname;
			else
				file = "(stdin)";
			rc = fstat(STDIN_FILENO, &st);
		} else {
			int j;

			file = argv[0];
			if (nfs_handle) {
				rc = 0;
				bzero(&fhnd, sizeof(fhnd));
				j = MIN(2 * sizeof(fhnd), strlen(file));
				if ((j & 1) != 0) {
					rc = -1;
				} else {
					while (j) {
						rc = hex2byte(&file[j - 2]);
						if (rc == -1)
							break;
						((char*) &fhnd)[j / 2 - 1] = rc;
						j -= 2;
					}
				}
				if (rc == -1)
					errno = EINVAL;
				else
					rc = fhstat(&fhnd, &st);

			} else if (usestat) {
				/*
				 * Try stat() and if it fails, fall back to
				 * lstat() just in case we're examining a
				 * broken symlink.
				 */
				if ((rc = stat(file, &st)) == -1 &&
				    errno == ENOENT &&
				    (rc = lstat(file, &st)) == -1)
					errno = ENOENT;
			}
			else
				rc = lstat(file, &st);
		}

		if (rc == -1) {
			errs = 1;
			linkfail = 1;
			if (!quiet)
				warn("%s: stat", file);
		}
		else
			output(&st, file, statfmt, fn, nonl);

		argv++;
		argc--;
		fn++;
	} while (argc > 0);

	return (am_readlink ? linkfail : errs);
}
/* parse SSID string encoded from wpa_supplicant to normal string  */
static size_t ssid_decode(char *buf, size_t maxlen, const char *str)
{
    const char *pos = str;
    size_t len = 0;
    int val;

    while (*pos) {
        if (len == maxlen)
            break;
        switch (*pos) {
        case '\\':
            pos++;
            switch (*pos) {
            case '\\':
                buf[len++] = '\\';
                pos++;
                break;
            case '"':
                buf[len++] = '"';
                pos++;
                break;
            case 'n':
                buf[len++] = '\n';
                pos++;
                break;
            case 'r':
                buf[len++] = '\r';
                pos++;
                break;
            case 't':
                buf[len++] = '\t';
                pos++;
                break;
            case 'e':
                buf[len++] = '\e';
                pos++;
                break;
            case 'x':
                pos++;
                val = hex2byte(pos);
                if (val < 0) {
                    val = hex2num(*pos);
                    if (val < 0)
                        break;
                    buf[len++] = val;
                    pos++;
                } else {
                    buf[len++] = val;
                    pos += 2;
                }
                break;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
                val = *pos++ - '0';
                if (*pos >= '0' && *pos <= '7')
                    val = val * 8 + (*pos++ - '0');
                if (*pos >= '0' && *pos <= '7')
                    val = val * 8 + (*pos++ - '0');
                buf[len++] = val;
                break;
            default:
                break;
            }
            break;
        default:
            buf[len++] = *pos++;
            break;
        }
    }

    return len;
}
Esempio n. 27
0
void generarbitmap(FILE *fp, char* _nombre) {
	char nombre[32];
	uint8_t pos;
	
	pos = hex2byte(_nombre);
	
	strncpy(nombre, _nombre+3, 32);
	if (strlen(nombre)<4)
		return;
	nombre[strlen(nombre)-4]=0;

	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL);
	if (!png_ptr)
		return;

	png_infop info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr) {
		png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
		return;
	}

	png_infop end_info = png_create_info_struct(png_ptr);
	if (!end_info) {
		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
		return;
	}
	
	png_set_sig_bytes(png_ptr, 8);
	png_init_io(png_ptr, fp);
	
	png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_STRIP_ALPHA | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_GRAY_TO_RGB, NULL);

	// Obtengo información básica
	png_uint_32 width, height, color_type, bit_depth;
	color_type = png_get_color_type(png_ptr, info_ptr);
	bit_depth = png_get_bit_depth(png_ptr, info_ptr);
	width = png_get_image_width(png_ptr, info_ptr);
	height = png_get_image_height(png_ptr, info_ptr);
	
	// Guardo la posición del bitmap en el fichero
	cabecera.punteros[pos] = htonl(tam + sizeof(struct cabecerabmf));
	
	// Escribo el ancho
	uint8_t ancho = width;
	fwrite(&ancho, 1, 1, bmf);
	tam++;
	
	// Empiezo a generar el bitmap
	uint8_t bitmap = 0;
	int bit = 7;
	
	// Obtengo los pixels
	png_bytep *row_pointers = png_get_rows(png_ptr, info_ptr);
	int i,j;
	// Genero bits en blanco superiores
	for (i=0; i<((height==10||height==12)?4:0);i++) {
		for (j=0; j<width; j++) {
			bit--;
			if (bit < 0) {
				fwrite(&bitmap, 1, 1, bmf);
				bit = 7;
				tam++;
			}
		}
	}
	for (i=0; i<height; i++) {
		for (j=0; j<width; j++) {
			bitmap |= (row_pointers[i][j*3]==0)<<bit;
			bit--;
			if (bit < 0) {
				fwrite(&bitmap, 1, 1, bmf);
				bitmap = 0;
				bit = 7;
				tam++;
			}
		}
	}
	// Genero bits en blanco inferiores
	for (i=0; i<((height==10||height==14)?2:0);i++) {
		for (j=0; j<width; j++) {
			bit--;
			if (bit < 0) {
				fwrite(&bitmap, 1, 1, bmf);
				bitmap = 0;
				bit = 7;
				tam++;
			}
		}
	}
	if (bit!=7) {
		fwrite(&bitmap, 1, 1, bmf);
		tam++;
	}
	
	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
}
Esempio n. 28
0
/*
 * decode the form:    SPINUM@IP <tab> ALGONAME:0xsecret
 *
 * special form: file /name
 * causes us to go read from this file instead.
 *
 */
static void esp_print_decode_onesecret(netdissect_options *ndo, char *line)
{
	struct sa_list sa1;
	int sa_def;

	char *spikey;
	char *decode;

	spikey = strsep(&line, " \t");
	sa_def = 0;
	memset(&sa1, 0, sizeof(struct sa_list));

	/* if there is only one token, then it is an algo:key token */
	if (line == NULL) {
		decode = spikey;
		spikey = NULL;
		/* memset(&sa1.daddr, 0, sizeof(sa1.daddr)); */
		/* sa1.spi = 0; */
		sa_def    = 1;
	} else
		decode = line;

	if (spikey && strcasecmp(spikey, "file") == 0) {
		/* open file and read it */
		FILE *secretfile;
		char  fileline[1024];
		char  *nl;

		secretfile = fopen(line, FOPEN_READ_TXT);
		if (secretfile == NULL) {
			perror(line);
			exit(3);
		}

		while (fgets(fileline, sizeof(fileline)-1, secretfile) != NULL) {
			/* remove newline from the line */
			nl = strchr(fileline, '\n');
			if (nl)
				*nl = '\0';
			if (fileline[0] == '#') continue;
			if (fileline[0] == '\0') continue;

			esp_print_decode_onesecret(ndo, fileline);
		}
		fclose(secretfile);

		return;
	}

	if (spikey) {
		char *spistr, *foo;
		u_int32_t spino;
		struct sockaddr_in *sin;
#ifdef INET6
		struct sockaddr_in6 *sin6;
#endif

		spistr = strsep(&spikey, "@");

		spino = strtoul(spistr, &foo, 0);
		if (spistr == foo || !spikey) {
			(*ndo->ndo_warning)(ndo, "print_esp: failed to decode spi# %s\n", foo);
			return;
		}

		sa1.spi = spino;

		sin = (struct sockaddr_in *)&sa1.daddr;
#ifdef INET6
		sin6 = (struct sockaddr_in6 *)&sa1.daddr;
		if (inet_pton(AF_INET6, spikey, &sin6->sin6_addr) == 1) {
#ifdef HAVE_SOCKADDR_SA_LEN
			sin6->sin6_len = sizeof(struct sockaddr_in6);
#endif
			sin6->sin6_family = AF_INET6;
		} else
#endif
		if (inet_pton(AF_INET, spikey, &sin->sin_addr) == 1) {
#ifdef HAVE_SOCKADDR_SA_LEN
			sin->sin_len = sizeof(struct sockaddr_in);
#endif
			sin->sin_family = AF_INET;
		} else {
			(*ndo->ndo_warning)(ndo, "print_esp: can not decode IP# %s\n", spikey);
			return;
		}
	}

	if (decode) {
		char *colon, *p;
		u_char espsecret_key[256];
		int len;
		size_t i;
		const EVP_CIPHER *evp;
		int authlen = 0;

		/* skip any blank spaces */
		while (isspace((unsigned char)*decode))
			decode++;

		colon = strchr(decode, ':');
		if (colon == NULL) {
			(*ndo->ndo_warning)(ndo, "failed to decode espsecret: %s\n", decode);
			return;
		}
		*colon = '\0';

		len = colon - decode;
		if (strlen(decode) > strlen("-hmac96") &&
		    !strcmp(decode + strlen(decode) - strlen("-hmac96"),
		    "-hmac96")) {
			p = strstr(decode, "-hmac96");
			*p = '\0';
			authlen = 12;
		}
		if (strlen(decode) > strlen("-cbc") &&
		    !strcmp(decode + strlen(decode) - strlen("-cbc"), "-cbc")) {
			p = strstr(decode, "-cbc");
			*p = '\0';
		}
		evp = EVP_get_cipherbyname(decode);
		if (!evp) {
			(*ndo->ndo_warning)(ndo, "failed to find cipher algo %s\n", decode);
			sa1.evp = NULL;
			sa1.authlen = 0;
			sa1.ivlen = 0;
			return;
		}

		sa1.evp = evp;
		sa1.authlen = authlen;
		sa1.ivlen = EVP_CIPHER_iv_length(evp);

		colon++;
		if (colon[0] == '0' && colon[1] == 'x') {
			/* decode some hex! */
			colon += 2;
			len = strlen(colon) / 2;

			if (len > 256) {
				(*ndo->ndo_warning)(ndo, "secret is too big: %d\n", len);
				return;
			}

			i = 0;
			while (colon[0] != '\0' && colon[1]!='\0') {
				espsecret_key[i] = hex2byte(ndo, colon);
				colon += 2;
				i++;
			}

			memcpy(sa1.secret, espsecret_key, i);
			sa1.secretlen = i;
		} else {
			i = strlen(colon);

			if (i < sizeof(sa1.secret)) {
				memcpy(sa1.secret, colon, i);
				sa1.secretlen = i;
			} else {
				memcpy(sa1.secret, colon, sizeof(sa1.secret));
				sa1.secretlen = sizeof(sa1.secret);
			}
		}
	}

	esp_print_addsa(ndo, &sa1, sa_def);
}
Esempio n. 29
0
static int _lua_json_parse_string(jsontok_t * tok, const char quote)
{
	char c;
	int ps =tok->pos,s =lt_string;
	if(0 == quote)
		return _lua_json_parser_key(tok);
	while(tok->pos < tok->size){
		c = tok->jstr[tok->pos];
		switch(s){
		case lt_string:
			switch(c){
				case '\n': tok->pos++; JSONTOK_NEWLINE(tok); break;	// new line.
				case '\\': tok->pos++; s=lt_string_escape;break;	// switch to escape string.
				case '\'':case '"':
					if(c != quote){
						tok->pos++;automem_append_byte(&tok->mem,c);break;
					}
					//TODO: finish the string.
					lua_pushlstring(tok->L, (char *)tok->mem.pdata,tok->mem.size);
					tok->mem.size=0;
					tok->pos++;
					return 0;
				default:
					tok->pos++;
					automem_append_byte(&tok->mem, c);
					break;
			}
			break;
		case lt_string_escape:
			switch(c){
			case 'b': automem_append_byte(&tok->mem, '\b');tok->pos++;s=lt_string;break;
			case 'n': automem_append_byte(&tok->mem, '\n');tok->pos++;s=lt_string;break;
			case 'r': automem_append_byte(&tok->mem, '\r');tok->pos++;s=lt_string;break;
			case 't': automem_append_byte(&tok->mem, '\t');tok->pos++;s=lt_string;break;
			case 'f': automem_append_byte(&tok->mem, '\f');tok->pos++;s=lt_string;break;
			case '\\': automem_append_byte(&tok->mem, '\\');tok->pos++;s=lt_string;break;
			case '/': automem_append_byte(&tok->mem, '/');tok->pos++;s=lt_string;break;
			case 'u':
				s=lt_string_escape_unicode;
				tok->pos++;
				break;
			default:
				automem_append_byte(&tok->mem,'\\');automem_append_byte(&tok->mem,c);tok->pos++;s=lt_string;break;
			}
			break;
		case lt_string_escape_unicode:
			{	//--处理 4个字节的UNICODE
				char * pt=&tok->jstr[tok->pos];
				if(ch_is_hex(pt[0]) && ch_is_hex(pt[1]) && ch_is_hex(pt[2]) && ch_is_hex(pt[3])){
					//是正确的 UNICODE.
					unsigned short uni = (hex2byte((unsigned char *)&pt[0]) << 8) | hex2byte((unsigned char *)&pt[2]);
					if(0x80 > uni){ //1 bytes
						automem_append_byte(&tok->mem, uni & 0x7F);
					}else if(0x800 > uni){ //2 bytes
						automem_append_byte(&tok->mem, (0xC0 | ((uni >> 6) & 0x3F)));
						automem_append_byte(&tok->mem, 0x80 | (0x3F & uni));
					}else if(0x10000 > uni){ //3 bytes
						automem_append_byte(&tok->mem, (0xE0 | ((uni >> 12))));
						automem_append_byte(&tok->mem, (0xC0 | ((uni >> 6) & 0x3F)));
						automem_append_byte(&tok->mem, 0x80 | (0x3F & uni));
					}
					else if(0x110000 > uni){ // 4 bytes.
Esempio n. 30
0
static int httpread_hdr_analyze(struct httpread *h)
{
	char *hbp = h->hdr;      /* pointer into h->hdr */
	int standard_first_line = 1;

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

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

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

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

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

	return 0;

bad:
	/* Error */
	return -1;
}