Beispiel #1
0
int main(int argc, char *argv[])
{
	char **params = NULL;
	int op = OP_UNKNOWN;
	int i, j;
	int indx = 0;
	bool dispfp = false;
	bool skshash = false;
	bool exact = false;
	bool ishex = false;
	bool isfp = false;
	bool mrhkp = false;
	uint64_t keyid = 0;
	struct openpgp_fingerprint fingerprint;
	char *search = NULL;
	char *end = NULL;
	struct openpgp_publickey *publickey = NULL;
	struct openpgp_packet_list *packets = NULL;
	struct openpgp_packet_list *list_end = NULL;
	int result;
	struct skshash hash;
	struct onak_dbctx *dbctx;

	params = getcgivars(argc, argv);
	for (i = 0; params != NULL && params[i] != NULL; i += 2) {
		if (!strcmp(params[i], "op")) {
			if (!strcmp(params[i+1], "get")) {
				op = OP_GET;
			} else if (!strcmp(params[i+1], "hget")) {
				op = OP_HGET;
			} else if (!strcmp(params[i+1], "index")) {
				op = OP_INDEX;
			} else if (!strcmp(params[i+1], "vindex")) {
				op = OP_VINDEX;
			} else if (!strcmp(params[i+1], "photo")) {
				op = OP_PHOTO;
			}
		} else if (!strcmp(params[i], "search")) {
			search = params[i+1];
			params[i+1] = NULL;
			if (search != NULL && strlen(search) == 42 &&
					search[0] == '0' && search[1] == 'x') {
				/* v4 fingerprint */
				fingerprint.length = 20;
				for (j = 0; j < 20; j++) {
					fingerprint.fp[j] = (hex2bin(
							search[2 + j * 2])
								<< 4) +
						hex2bin(search[3 + j * 2]);
				}
				isfp = true;
			} else if (search != NULL && strlen(search) == 66 &&
					search[0] == '0' && search[1] == 'x') {
				/* v5 fingerprint */
				fingerprint.length = 32;
				for (j = 0; j < 32; j++) {
					fingerprint.fp[j] = (hex2bin(
							search[2 + j * 2])
								<< 4) +
						hex2bin(search[3 + j * 2]);
				}
				isfp = true;
			} else if (search != NULL) {
				keyid = strtoull(search, &end, 16);
				if (*search != 0 &&
						end != NULL &&
						*end == 0) {
					ishex = true;
				}
			}
		} else if (!strcmp(params[i], "idx")) {
			indx = atoi(params[i+1]);
		} else if (!strcmp(params[i], "fingerprint")) {
			if (!strcmp(params[i+1], "on")) {
				dispfp = true;
			}
		} else if (!strcmp(params[i], "hash")) {
			if (!strcmp(params[i+1], "on")) {
				skshash = true;
			}
		} else if (!strcmp(params[i], "exact")) {
			if (!strcmp(params[i+1], "on")) {
				exact = true;
			}
		} else if (!strcmp(params[i], "options")) {
			/*
			 * TODO: We should be smarter about this; options may
			 * have several entries. For now mr is the only valid
			 * one though.
			 */
			if (!strcmp(params[i+1], "mr")) {
				mrhkp = true;
			}
		}
		free(params[i]);
		params[i] = NULL;
		if (params[i+1] != NULL) {
			free(params[i+1]);
			params[i+1] = NULL;
		}
	}
	if (params != NULL) {
		free(params);
		params = NULL;
	}

	if (mrhkp) {
		puts("Content-Type: text/plain\n");
	} else if (op == OP_PHOTO) {
		puts("Content-Type: image/jpeg\n");
	} else {
		start_html("Lookup of key");
	}

	if (op == OP_UNKNOWN) {
		puts("Error: No operation supplied.");
	} else if (search == NULL) {
		puts("Error: No key to search for supplied.");
	} else {
		readconfig(NULL);
		initlogthing("lookup", config.logfile);
		catchsignals();
		dbctx = config.dbinit(config.backend, false);
		switch (op) {
		case OP_GET:
		case OP_HGET:
			if (op == OP_HGET) {
				parse_skshash(search, &hash);
				result = dbctx->fetch_key_skshash(dbctx,
					&hash, &publickey);
			} else if (ishex) {
				result = dbctx->fetch_key_id(dbctx, keyid,
					&publickey, false);
			} else if (isfp) {
				result = dbctx->fetch_key_fp(dbctx,
					&fingerprint, &publickey, false);
			} else {
				result = dbctx->fetch_key_text(dbctx,
					search,
					&publickey);
			}
			if (result) {
				logthing(LOGTHING_NOTICE, 
					"Found %d key(s) for search %s",
					result,
					search);
				puts("<pre>");
				cleankeys(&publickey, config.clean_policies);
				flatten_publickey(publickey,
							&packets,
							&list_end);
				armor_openpgp_stream(stdout_putchar,
						NULL,
						packets);
				puts("</pre>");
			} else {
				logthing(LOGTHING_NOTICE,
					"Failed to find key for search %s",
					search);
				puts("Key not found");
			}
			break;
		case OP_INDEX:
			find_keys(dbctx, search, keyid, &fingerprint,
					ishex, isfp, dispfp, skshash,
					exact, false, mrhkp);
			break;
		case OP_VINDEX:
			find_keys(dbctx, search, keyid, &fingerprint,
					ishex, isfp, dispfp, skshash,
					exact, true, mrhkp);
			break;
		case OP_PHOTO:
			if (isfp) {
				dbctx->fetch_key_fp(dbctx, &fingerprint,
					&publickey, false);
			} else {
				dbctx->fetch_key_id(dbctx, keyid,
					&publickey, false);
			}
			if (publickey != NULL) {
				unsigned char *photo = NULL;
				size_t         length = 0;

				if (getphoto(publickey, indx, &photo,
						&length) == ONAK_E_OK) {
					fwrite(photo,
							1,
							length,
							stdout);
				}
				free_publickey(publickey);
				publickey = NULL;
			}
			break;
		default:
			puts("Unknown operation!");
		}
		dbctx->cleanupdb(dbctx);
		cleanuplogthing();
		cleanupconfig();
	}
	if (!mrhkp) {
		puts("<hr>");
		puts("Produced by onak " ONAK_VERSION );
		end_html();
	}

	if (search != NULL) {
		free(search);
		search = NULL;
	}
	
	return (EXIT_SUCCESS);
}
Beispiel #2
0
static gboolean dct3trace_get_packet(FILE_T fh, struct wtap_pkthdr *phdr,
	Buffer *buf, int *err, gchar **err_info)
{
	char line[1024];
	guint8 databuf[MAX_PACKET_LEN], *bufp;
	gboolean have_data = FALSE;
	int len = 0;

	bufp = &databuf[0];
	while (file_gets(line, sizeof(line), fh) != NULL)
	{
		if( memcmp(dct3trace_magic_end, line, strlen(dct3trace_magic_end)) == 0 )
		{
			/* Return on end of file </dump> */
			*err = 0;
			return FALSE;
		}
		else if( memcmp(dct3trace_magic_record_end, line, strlen(dct3trace_magic_record_end)) == 0 )
		{
			/* Return on end of record </l1> */
			if( have_data )
			{
				/* We've got a full packet! */
				phdr->rec_type = REC_TYPE_PACKET;
				phdr->presence_flags = 0; /* no time stamp, no separate "on the wire" length */
				phdr->ts.secs = 0;
				phdr->ts.nsecs = 0;
				phdr->caplen = len;
				phdr->len = len;

				*err = 0;

				/* Make sure we have enough room for the packet */
				ws_buffer_assure_space(buf, phdr->caplen);
				memcpy( ws_buffer_start_ptr(buf), databuf, phdr->caplen );

				return TRUE;
			}
			else
			{
				/* If not got any data return error */
				*err = WTAP_ERR_BAD_FILE;
				*err_info = g_strdup("dct3trace: record without data");
				return FALSE;
			}
		}
		else if( memcmp(dct3trace_magic_record_start, line, strlen(dct3trace_magic_record_start)) == 0 )
		{
			/* Parse L1 header <l1 ...>*/
			int channel, tmp;
			char *ptr;

			phdr->pseudo_header.gsm_um.uplink = !strstr(line, "direction=\"down\"");
			if (!xml_get_int(&channel, line, "logicalchannel", err, err_info))
				return FALSE;

			/* Parse downlink only fields */
			if( !phdr->pseudo_header.gsm_um.uplink )
			{
				if (!xml_get_int(&tmp, line, "physicalchannel", err, err_info))
					return FALSE;
				phdr->pseudo_header.gsm_um.arfcn = tmp;
				if (!xml_get_int(&tmp, line, "sequence", err, err_info))
					return FALSE;
				phdr->pseudo_header.gsm_um.tdma_frame = tmp;
				if (!xml_get_int(&tmp, line, "bsic", err, err_info))
					return FALSE;
				phdr->pseudo_header.gsm_um.bsic = tmp;
				if (!xml_get_int(&tmp, line, "error", err, err_info))
					return FALSE;
				phdr->pseudo_header.gsm_um.error = tmp;
				if (!xml_get_int(&tmp, line, "timeshift", err, err_info))
					return FALSE;
				phdr->pseudo_header.gsm_um.timeshift = tmp;
			}

			switch( channel )
			{
				case 128: phdr->pseudo_header.gsm_um.channel = GSM_UM_CHANNEL_SDCCH; break;
				case 112: phdr->pseudo_header.gsm_um.channel = GSM_UM_CHANNEL_SACCH; break;
				case 176: phdr->pseudo_header.gsm_um.channel = GSM_UM_CHANNEL_FACCH; break;
				case 96: phdr->pseudo_header.gsm_um.channel = GSM_UM_CHANNEL_CCCH; break;
				case 80: phdr->pseudo_header.gsm_um.channel = GSM_UM_CHANNEL_BCCH; break;
				default: phdr->pseudo_header.gsm_um.channel = GSM_UM_CHANNEL_UNKNOWN; break;
			}

			/* Read data (if have it) into databuf */
			ptr = strstr(line, "data=\"");
			if( ptr )
			{
				have_data = TRUE; /* If has data... */
				len = hex2bin(bufp, &databuf[MAX_PACKET_LEN], ptr+6);
				if (len == -1)
				{
					*err = WTAP_ERR_BAD_FILE;
					*err_info = g_strdup_printf("dct3trace: record length %d too long", phdr->caplen);
					return FALSE;
				}
			}
		}
		else if( !have_data && memcmp(dct3trace_magic_l2_start, line, strlen(dct3trace_magic_l2_start)) == 0 )
		{
			/* For uplink packets we might not get the raw L1, so have to recreate it from the L2 */
			/* Parse L2 header if didn't get data from L1 <l2 ...> */
			int data_len;
			char *ptr = strstr(line, "data=\"");

			if( !ptr )
			{
				continue;
			}

			have_data = TRUE;

			/*
			 * We know we have no data already, so we know
			 * we have enough room for the header.
			 */
			if( phdr->pseudo_header.gsm_um.channel == GSM_UM_CHANNEL_SACCH || phdr->pseudo_header.gsm_um.channel == GSM_UM_CHANNEL_FACCH || phdr->pseudo_header.gsm_um.channel == GSM_UM_CHANNEL_SDCCH )
			{
				/* Add LAPDm B header */
				memset(bufp, 0x1, 2);
				len = 3;
			}
			else
			{
				/* Add LAPDm Bbis header */
				len = 1;
			}
			bufp += len;

			data_len = hex2bin(bufp, &databuf[MAX_PACKET_LEN], ptr+6);
			if (data_len == -1)
			{
				*err = WTAP_ERR_BAD_FILE;
				*err_info = g_strdup_printf("dct3trace: record length %d too long", phdr->caplen);
				return FALSE;
			}
			len += data_len;

			/* Add LAPDm length byte */
			*(bufp - 1) = data_len << 2 | 0x1;
		}
	}

	*err = file_error(fh, err_info);
	if (*err == 0)
	{
		*err = WTAP_ERR_SHORT_READ;
	}
	return FALSE;
}
Beispiel #3
0
static void HTTPProcess(HTTP_HANDLE h) {
	char bafs[26], r;

	BOOL lbContinue;
	static HTTP_INFO* ph;
	WORD w;
	static BYTE *p, *t;

	ph = &HCB[h];
    do {
		lbContinue = FALSE;
        if(!TCPIsConnected(ph->socket)) { 	ph->smHTTP = SM_HTTP_IDLE;  break; }

        switch(ph->smHTTP) {
        case SM_HTTP_IDLE:
			w = TCPGetArray(ph->socket, httpData, MAX_HTML_CMD_LEN);
			if(!w) {
				if(TCPGetRxFIFOFree(ph->socket) == 0) TCPDisconnect(ph->socket); // Request is too big, we can't support it.
				break;
			}
			httpData[w] = 0;
			t = p = httpData;
			while(*p)	if(*p=='%') { *t++ = hex2bin(p+1); p += 3; } else *t++ = *p++;	*t = 0;
			r = httpData[150];  httpData[150]=0;

			lbContinue = TRUE;
			ph->smHTTP = SM_HTTP_NOT_FOUND;
			if(strstrrampgm(httpData,"POST"))	ph->smHTTP = SM_HTTP_POST;
			if(strstrrampgm(httpData,"GET")) {
				ph->smHTTP = SM_HTTP_HEADER;
#ifndef _FAVICON_
				if(strstrrampgm(httpData,(ROM void*)"favicon"))		{ TCPDisconnect(ph->socket);  ph->smHTTP = SM_HTTP_IDLE; }
#else
				if(strstrrampgm(httpData,"favicon"))		ph->smHTTP = SM_ICO_HEADER;
#endif
				if(strstrrampgm(httpData, "Sw_Pool"))		AppConfig.who ^= 0x81;
				if(strstrrampgm(httpData, "Sw_Mode"))		AppConfig.sw_mode ^= 1;
				if(strstrrampgm(httpData, "Sw_Clock"))		AppConfig.CkSel ^= 1;
				if(strstrrampgm(httpData, "Sw_LEDs"))		bLEDs ^= 1;
			}
			httpData[150]=r;
			break;
            
        case SM_HTTP_POST:
			exoit(ph->socket);
			memcpypgm2ram(spwrk,rMinPool,SZ_ROMS );
			for(r=0;r<SZ_SRCH;r++) {
				BYTE *s;
				p = strstrrampgm(httpData,(ROM BYTE*)(DWORD)sComa[r]);
				if(p) {
					p+=5;
					t=strstrrampgm(p,ampa);
					if(t) {
						*t=0; s=p;
						switch(r) {
//							case C_JMAC:	Hex2Mac(p); break; //S2Mac(p);	break;
							case C_JMIP:	StringToIPAddress(p,&AppConfig.MyIPAddr); break;
							case C_JMSK:	StringToIPAddress(p,&AppConfig.MyMask); break;
							case C_JGTW:	StringToIPAddress(p,&AppConfig.MyGateway); break;
							case C_PDNS:	StringToIPAddress(p,&AppConfig.PrimaryDNSServer); break;
							case C_SDNS:	StringToIPAddress(p,&AppConfig.SecondaryDNSServer); break;
							case C_WPRT:	AppConfig.MyPort = atoi(p); break;
							case C_MPRT:	while(*p) if((*p) == ',')	{ *p=0; AppConfig.MinPort[0] = atoi(s); break; } else p++;
											AppConfig.MinPort[1] = atoi(++p); *--p = ',';
											break;
							case C_MURL:	while(*p) if((*p) == ',')	{ *p=0; strcpy(&spwrk[0],s); break; } else p++;
											strcpy(&spwrk[sizeof(rMinPool)/2],++p); *--p = ',';
											break;
							case C_USPA:	while(*p) if((*p) == ',')	{ *p=0; strcpy(&spwrk[sizeof(rMinPool)],s); break; } else p++;
											strcpy(&spwrk[sizeof(rMinPool)+sizeof(rUsrPass)/2],++p); *--p = ',';
											break;
						}
						*t='&';
					}
				}
			}
			ph->smHTTP = SM_HTTP_IDLE; 		SetUPS();
	       	break;

        case SM_HTTP_NOT_FOUND:
			if(TCPIsPutReady(ph->socket) >= sizeof(hdrErr)) {
				TCPPutROMString(ph->socket, hdrErr); TCPFlush(ph->socket);
				TCPDisconnect(ph->socket);
				ph->smHTTP = SM_HTTP_IDLE;
            }
            break;
#ifdef _FAVICON_
        case SM_ICO_HEADER:
			if ( TCPIsPutReady(ph->socket) ) {
                lbContinue = TRUE;
				if(TCPIsPutReady(ph->socket) >= sizeof(hdrICO)+198) {
                	TCPPutROMString(ph->socket, hdrICO);
					TCPPutROMArray(ph->socket, favicon,198);
					TCPFlush(ph->socket);
					TCPDisconnect(ph->socket);
                	ph->smHTTP = SM_HTTP_IDLE;
				}
			}
			break;
#endif
        case SM_HTTP_HEADER:
            if ( TCPIsPutReady(ph->socket) ) {
                lbContinue = TRUE;
				if(TCPIsPutReady(ph->socket) >= sizeof(hdrOK)) {
                	TCPPutROMString(ph->socket, hdrOK);
					TCPFlush(ph->socket);
                	ph->smHTTP = SM_HTTP_GET;
                	ph->Pos = Page;
            	}
            }
            break;

        case SM_HTTP_GET:
			TCPDiscard(ph->socket);
			if(TCPIsPutReady(ph->socket) >= 400) {
				ph->Pos = TCPPutROMString(ph->socket, ph->Pos);
				ph->Pos++;
				switch (*ph->Pos) {
					case  0: TCPDisconnect(ph->socket); ph->smHTTP = SM_HTTP_IDLE; ph->Pos = Page; break;
					case  1: DoStic(ph->socket, 1); break;
					case  2: DoStic(ph->socket, 2); break;
					case  3: DoStic(ph->socket, 3); break;
//					case  4: MAC2Hex(bafs); TCPPutString(ph->socket, bafs); break;
					case  5: IP2String(AppConfig.MyIPAddr,bafs); TCPPutString(ph->socket, bafs); break;
					case  6: IP2String(AppConfig.MyMask,bafs); TCPPutString(ph->socket, bafs); break;
					case  7: IP2String(AppConfig.MyGateway,bafs); TCPPutString(ph->socket, bafs); break;
					case  8: uitoa(AppConfig.MyPort,bafs); TCPPutString(ph->socket, bafs); break;
					case  9: IP2String(AppConfig.PrimaryDNSServer,bafs); TCPPutString(ph->socket, bafs); break;
					case 10: IP2String(AppConfig.SecondaryDNSServer,bafs); TCPPutString(ph->socket, bafs); break;
					case 11: uitoa(AppConfig.MinPort[0],bafs); TCPPutString(ph->socket, bafs); TCPPut(ph->socket,','); uitoa(AppConfig.MinPort[1],bafs); TCPPutString(ph->socket, bafs); break;
					case 12: TCPPutROMString(ph->socket, rMinPool[0]); TCPPut(ph->socket,','); TCPPutROMString(ph->socket, rMinPool[1]); break;
					case 13: TCPPutROMString(ph->socket, rUsrPass[0]); TCPPut(ph->socket,','); TCPPutROMString(ph->socket, rUsrPass[1]); break;
				}
				ph->Pos++;
			}
			TCPFlush(ph->socket);
			break;
		default:	break;
        }
    } while( lbContinue );
}
Beispiel #4
0
/* can have zero or more token= options */
static int getoptions(char *c, struct trusted_key_payload *pay,
		      struct trusted_key_options *opt)
{
	substring_t args[MAX_OPT_ARGS];
	char *p = c;
	int token;
	int res;
	unsigned long handle;
	unsigned long lock;

	while ((p = strsep(&c, " \t"))) {
		if (*p == '\0' || *p == ' ' || *p == '\t')
			continue;
		token = match_token(p, key_tokens, args);

		switch (token) {
		case Opt_pcrinfo:
			opt->pcrinfo_len = strlen(args[0].from) / 2;
			if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
				return -EINVAL;
			res = hex2bin(opt->pcrinfo, args[0].from,
				      opt->pcrinfo_len);
			if (res < 0)
				return -EINVAL;
			break;
		case Opt_keyhandle:
			res = kstrtoul(args[0].from, 16, &handle);
			if (res < 0)
				return -EINVAL;
			opt->keytype = SEAL_keytype;
			opt->keyhandle = handle;
			break;
		case Opt_keyauth:
			if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
				return -EINVAL;
			res = hex2bin(opt->keyauth, args[0].from,
				      SHA1_DIGEST_SIZE);
			if (res < 0)
				return -EINVAL;
			break;
		case Opt_blobauth:
			if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
				return -EINVAL;
			res = hex2bin(opt->blobauth, args[0].from,
				      SHA1_DIGEST_SIZE);
			if (res < 0)
				return -EINVAL;
			break;
		case Opt_migratable:
			if (*args[0].from == '0')
				pay->migratable = 0;
			else
				return -EINVAL;
			break;
		case Opt_pcrlock:
			res = kstrtoul(args[0].from, 10, &lock);
			if (res < 0)
				return -EINVAL;
			opt->pcrlock = lock;
			break;
		default:
			return -EINVAL;
		}
	}
	return 0;
}
Beispiel #5
0
void process_linkwan_at(void)
{
    bool ret = false;
    int value;
    MibRequestConfirm_t mibReq;
    LoRaMacStatus_t status;
    uint8_t length;
    uint8_t buf[16];

    if (atcmd_index == 0 || atcmd[atcmd_index] != '\0') {
        return;
    }
    if (strncmp(atcmd, LORA_AT_HELP, strlen(LORA_AT_HELP)) == 0) {
        snprintf(atcmd, ATCMD_SIZE, "\r\n%s\r\n", LORA_AT_HELP);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_RM);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_APPEUI);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_APPKEY);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_DEUI);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_DR);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_ADR);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_CLASS);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_SCANMASK);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_CFM);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_CFMTRIALS);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_JOIN);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_TX);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_RX);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_DCS);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_TXSIZE);
        linkwan_serial_output(atcmd, strlen(atcmd));
        snprintf(atcmd, ATCMD_SIZE, "%s\r\n", LORA_AT_LINKCHK);
        linkwan_serial_output(atcmd, strlen(atcmd));
        return;
    } else if (strncmp(atcmd, LORA_AT_APPEUI, strlen(LORA_AT_APPEUI)) == 0) {
        if (atcmd_index == strlen(LORA_AT_APPEUI)) {
            uint8_t *eui = get_lora_app_eui();
            ret = true;
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s %02x%02x%02x%02x%02x%02x%02x%02x\r\n", \
                     LORA_AT_APPEUI, eui[0], eui[1], eui[2], eui[3], eui[4], eui[5], eui[6], eui[7]);
        } else if (atcmd_index == (strlen(LORA_AT_APPEUI) + 16)) {
            length = hex2bin(&atcmd[strlen(LORA_AT_APPEUI)], buf, 8);
            if (length == 8) {
                ret = set_lora_app_eui(buf);
                if (ret == true) {
                    snprintf(atcmd, ATCMD_SIZE, "\r\n%s %02x%02x%02x%02x%02x%02x%02x%02x\r\n", \
                             LORA_AT_APPEUI, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
                }
            }
        }
        if (ret == false) {
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s ERROR\r\n", LORA_AT_APPEUI);
        }
    } else if (strncmp(atcmd, LORA_AT_APPKEY, strlen(LORA_AT_APPKEY)) == 0) {
        if (atcmd_index == strlen(LORA_AT_APPKEY)) {
            uint8_t *key = get_lora_app_key();
            ret = true;
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\r\n", \
                     LORA_AT_APPKEY, key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7],
                     key[8], key[9], key[10], key[11], key[12], key[13], key[14], key[15]);
        } else if (atcmd_index == (strlen(LORA_AT_APPKEY) + 32)) {
            length = hex2bin(&atcmd[strlen(LORA_AT_APPKEY)], buf, 16);
            if (length == 16) {
                ret = set_lora_app_key(buf);
                if (ret == true) {
                    snprintf(atcmd, ATCMD_SIZE, "\r\n%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\r\n", \
                             LORA_AT_APPKEY, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
                             buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]);
                }
            }
        }
        if (ret == false) {
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s ERROR\r\n", LORA_AT_APPKEY);
        }
    } else if (strncmp(atcmd, LORA_AT_DEUI, strlen(LORA_AT_DEUI)) == 0) {
        if (atcmd_index == strlen(LORA_AT_DEUI)) {
            uint8_t *eui = get_lora_dev_eui();
            ret = true;
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s %02x%02x%02x%02x%02x%02x%02x%02x\r\n", \
                     LORA_AT_DEUI, eui[0], eui[1], eui[2], eui[3], eui[4], eui[5], eui[6], eui[7]);
        } else if (atcmd_index == (strlen(LORA_AT_DEUI) + 16)) {
            length = hex2bin(&atcmd[strlen(LORA_AT_DEUI)], buf, 8);
            if (length == 8) {
                ret = set_lora_dev_eui(buf);
                if (ret == true) {
                    snprintf(atcmd, ATCMD_SIZE, "\r\n%s %02x%02x%02x%02x%02x%02x%02x%02x\r\n", \
                             LORA_AT_DEUI, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
                }
            }
        }
        if (ret == false) {
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s ERROR\r\n", LORA_AT_DEUI);
        }
    } else if (strncmp(atcmd, LORA_AT_RM, strlen(LORA_AT_RM)) == 0) {
        aos_kv_del("lora");
        aos_kv_del("lora_dev");
        ret = true;
        snprintf(atcmd, ATCMD_SIZE, "\r\n%s OK\r\n", LORA_AT_RM);
    } else if (strncmp(atcmd, LORA_AT_DR, strlen(LORA_AT_DR)) == 0) {
        int8_t datarate;
        if (atcmd_index == strlen(LORA_AT_DR)) {
            ret = true;
            datarate = get_lora_tx_datarate();
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s %d\r\n", LORA_AT_DR, datarate);
        } else if (atcmd_index == (strlen(LORA_AT_DR) + 1)) {
            datarate = strtol(atcmd + strlen(LORA_AT_DR), NULL, 0);
            ret = set_lora_tx_datarate(datarate);
            if (ret == true) {
                snprintf(atcmd, ATCMD_SIZE, "\r\n%s %d\r\n", LORA_AT_DR, datarate);
            }
        }
        if (ret == false) {
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s ERROR\r\n", LORA_AT_DR);
        }
    } else if (strncmp(atcmd, LORA_AT_ADR, strlen(LORA_AT_ADR)) == 0) {
        int adr;
        if (atcmd_index == strlen(LORA_AT_ADR)) {
            ret = true;
            adr = get_lora_adr();
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s %d\r\n", LORA_AT_ADR, adr);
        } else if (atcmd_index == (strlen(LORA_AT_ADR) + 1)) {
            adr = strtol(atcmd + strlen(LORA_AT_ADR), NULL, 0);
            ret = set_lora_adr(adr);
            if (ret == true) {
                snprintf(atcmd, ATCMD_SIZE, "\r\n%s %d\r\n", LORA_AT_ADR, adr);
            }
        }
        if (ret == false) {
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s ERROR\r\n", LORA_AT_ADR);
        }
    } else if (strncmp(atcmd, LORA_AT_CLASS, strlen(LORA_AT_CLASS)) == 0) {
        int8_t class;
        if (atcmd_index == strlen(LORA_AT_CLASS)) {
            ret = true;
            class = get_lora_class();
            snprintf(atcmd, ATCMD_SIZE, "\r\n%s %d\r\n", LORA_AT_CLASS, class);
        } else if (atcmd_index == (strlen(LORA_AT_CLASS) + 1)) {
Beispiel #6
0
/* can have zero or more token= options */
static int getoptions(char *c, struct trusted_key_payload *pay,
		      struct trusted_key_options *opt)
{
	substring_t args[MAX_OPT_ARGS];
	char *p = c;
	int token;
	int res;
	unsigned long handle;
	unsigned long lock;
	unsigned long token_mask = 0;
	unsigned int digest_len;
	int i;
	int tpm2;

	tpm2 = tpm_is_tpm2(TPM_ANY_NUM);
	if (tpm2 < 0)
		return tpm2;

	opt->hash = tpm2 ? HASH_ALGO_SHA256 : HASH_ALGO_SHA1;

	while ((p = strsep(&c, " \t"))) {
		if (*p == '\0' || *p == ' ' || *p == '\t')
			continue;
		token = match_token(p, key_tokens, args);
		if (test_and_set_bit(token, &token_mask))
			return -EINVAL;

		switch (token) {
		case Opt_pcrinfo:
			opt->pcrinfo_len = strlen(args[0].from) / 2;
			if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
				return -EINVAL;
			res = hex2bin(opt->pcrinfo, args[0].from,
				      opt->pcrinfo_len);
			if (res < 0)
				return -EINVAL;
			break;
		case Opt_keyhandle:
			res = kstrtoul(args[0].from, 16, &handle);
			if (res < 0)
				return -EINVAL;
			opt->keytype = SEAL_keytype;
			opt->keyhandle = handle;
			break;
		case Opt_keyauth:
			if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
				return -EINVAL;
			res = hex2bin(opt->keyauth, args[0].from,
				      SHA1_DIGEST_SIZE);
			if (res < 0)
				return -EINVAL;
			break;
		case Opt_blobauth:
			if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
				return -EINVAL;
			res = hex2bin(opt->blobauth, args[0].from,
				      SHA1_DIGEST_SIZE);
			if (res < 0)
				return -EINVAL;
			break;
		case Opt_migratable:
			if (*args[0].from == '0')
				pay->migratable = 0;
			else
				return -EINVAL;
			break;
		case Opt_pcrlock:
			res = kstrtoul(args[0].from, 10, &lock);
			if (res < 0)
				return -EINVAL;
			opt->pcrlock = lock;
			break;
		case Opt_hash:
			if (test_bit(Opt_policydigest, &token_mask))
				return -EINVAL;
			for (i = 0; i < HASH_ALGO__LAST; i++) {
				if (!strcmp(args[0].from, hash_algo_name[i])) {
					opt->hash = i;
					break;
				}
			}
			if (i == HASH_ALGO__LAST)
				return -EINVAL;
			if  (!tpm2 && i != HASH_ALGO_SHA1) {
				pr_info("trusted_key: TPM 1.x only supports SHA-1.\n");
				return -EINVAL;
			}
			break;
		case Opt_policydigest:
			digest_len = hash_digest_size[opt->hash];
			if (!tpm2 || strlen(args[0].from) != (2 * digest_len))
				return -EINVAL;
			res = hex2bin(opt->policydigest, args[0].from,
				      digest_len);
			if (res < 0)
				return -EINVAL;
			opt->policydigest_len = digest_len;
			break;
		case Opt_policyhandle:
			if (!tpm2)
				return -EINVAL;
			res = kstrtoul(args[0].from, 16, &handle);
			if (res < 0)
				return -EINVAL;
			opt->policyhandle = handle;
			break;
		default:
			return -EINVAL;
		}
	}
	return 0;
}
Beispiel #7
0
/* a serial connection, and instUnknown not serial. */
static instType ser_inst_type(
	icoms *p, 
	int port		/* Enumerated port number, 1..n */
) {
	instType rv = instUnknown;
	char buf[100];
	baud_rate brt[] = { baud_9600, baud_19200, baud_4800, baud_2400,
	                     baud_1200, baud_38400, baud_57600, baud_115200,
	                     baud_600, baud_300, baud_110, baud_nc };
	long etime;
	int bi, i;
	int se, len;
	int xrite = 0;
	int ss = 0;
	int so = 0;
	
	if (p->paths == NULL)
		p->get_paths(p);

	if (port <= 0 || port > p->npaths)
		return instUnknown;

#ifdef ENABLE_USB
	if (p->paths[port-1]->dev != NULL
	 || p->paths[port-1]->hev != NULL)
		return instUnknown;
#endif /* ENABLE_USB */

	if (p->debug) fprintf(stderr,"instType: About to init Serial I/O\n");

	bi = 0;

	/* The tick to give up on */
	etime = msec_time() + (long)(1000.0 * 20.0 + 0.5);

	if (p->debug) fprintf(stderr,"instType: Trying different baud rates (%lu msec to go)\n",etime - msec_time());

	/* Until we time out, find the correct baud rate */
	for (i = bi; msec_time() < etime; i++) {
		if (brt[i] == baud_nc)
			i = 0;
		p->set_ser_port(p, port, fc_none, brt[i], parity_none, stop_1, length_8);

//printf("~1 brt = %d\n",brt[i]);
		if ((se = p->write_read(p, ";D024\r\n", buf, 100, '\r', 1, 0.5)) != 0) {
			if ((se & ICOM_USERM) == ICOM_USER) {
				if (p->debug) fprintf(stderr,"instType: User aborted\n");
				return instUnknown;
			}
		}
		len = strlen(buf);

//printf("~1 len = %d\n",len);
		if (len < 4)
			continue;

		/* Is this an X-Rite error value such as "<01>" ? */
		if (buf[0] == '<' && isdigit(buf[1]) && isdigit(buf[2]) && buf[3] == '>') {
//printf("~1 xrite\n");
			xrite = 1;
			break;
		}

		/* Is this a Spectrolino error resonse ? */
		if (len >= 5 && strncmp(buf, ":26", 3) == 0) {
//printf("~1 spectrolino\n");
			so = 1;
			break;
		}
		/* Is this a SpectroScan response ? */
		if (len >= 7 && strncmp(buf, ":D183", 5) == 0) {
//printf("~1 spectroscan\n");
			ss = 1;
			break;
		}
	}

	if (msec_time() >= etime) {		/* We haven't established comms */
		if (p->debug) fprintf(stderr,"instType: Failed to establish coms\n");
		return instUnknown;
	}

	if (p->debug) fprintf(stderr,"instType: Got coms with instrument\n");

	/* Spectrolino */
	if (so) {
		rv = instSpectrolino;
	}

	/* SpectroScan */
	if (ss) {
		rv = instSpectroScan;
		if ((se = p->write_read(p, ";D030\r\n", buf, 100, '\n', 1, 1.5)) == 0)  {
			if (strlen(buf) >= 41) {
				hex2bin(&buf[5], 12);
//printf("~1 type = '%s'\n",buf);
				if (strncmp(buf, ":D190SpectroScanT", 17) == 0)
					rv = instSpectroScanT;
			}
		}
	}
	if (xrite) {

		/* Get the X-Rite model and version number */
		if ((se = p->write_read(p, "SV\r\n", buf, 100, '>', 1, 2.5)) != 0)
			return instUnknown;
	
		if (strlen(buf) >= 12) {
		    if (strncmp(buf,"X-Rite DTP22",12) == 0)
				rv = instDTP22;
		    if (strncmp(buf,"X-Rite DTP41",12) == 0)
				rv = instDTP41;
		    if (strncmp(buf,"X-Rite DTP42",12) == 0)
				rv = instDTP41;
		    if (strncmp(buf,"X-Rite DTP51",12) == 0)
				rv = instDTP51;
		    if (strncmp(buf,"X-Rite DTP52",12) == 0)
				rv = instDTP51;
		    if (strncmp(buf,"X-Rite DTP92",12) == 0)
				rv = instDTP92;
		    if (strncmp(buf,"X-Rite DTP94",12) == 0)
				rv = instDTP94;
		}
	}

	if (p->debug) fprintf(stderr,"instType: Instrument type is '%s'\n", inst_name(rv));

	return rv;
}
static bool gridseed_detect_one(libusb_device *dev, struct usb_find_devices *found)
{
	struct cgpu_info *gridseed;
	GRIDSEED_INFO *info;
	int err, wrote, def_freq_inx;
	unsigned char rbuf[GRIDSEED_READ_SIZE];
#if 0
	const char detect_cmd[] =
		"55aa0f01"
		"4a548fe471fa3a9a1371144556c3f64d"
		"2500b4826008fe4bbf7698c94eba7946"
		"ce22a72f4f6726141a0b3287eeeeeeee";
	unsigned char detect_data[52];
#else
	const char detect_cmd[] = "55aac000909090900000000001000000";
	unsigned char detect_data[16];
#endif

	gridseed = usb_alloc_cgpu(&gridseed_drv, GRIDSEED_MINER_THREADS);
	if (!usb_init(gridseed, dev, found))
		goto shin;

	libusb_reset_device(gridseed->usbdev->handle);

	info = (GRIDSEED_INFO*)calloc(sizeof(GRIDSEED_INFO), 1);
	if (unlikely(!info))
		quit(1, "Failed to calloc gridseed_info data");
	gridseed->device_data = (void *)info;

	info->baud = GRIDSEED_DEFAULT_BAUD;
	info->freq = GRIDSEED_DEFAULT_FREQUENCY;
	def_freq_inx = gc3355_find_freq_index(GRIDSEED_DEFAULT_FREQUENCY);
	memcpy(info->freq_cmd, bin_frequency[def_freq_inx], 8);
	info->chips = GRIDSEED_DEFAULT_CHIPS;
	info->voltage = 0;
	info->per_chip_stats = 0;
	info->serial = strdup(gridseed->usbdev->serial_string);
	memset(info->nonce_count, 0, sizeof(info->nonce_count));
	memset(info->error_count, 0, sizeof(info->error_count));

	get_options(info, opt_gridseed_options);
	get_freq(info, opt_gridseed_freq);

	update_usb_stats(gridseed);

	gridseed->usbdev->usb_type = USB_TYPE_STD;
	gridseed_initialise(gridseed, info);

	/* get MCU firmware version */
	hex2bin(detect_data, detect_cmd, sizeof(detect_data));
	if (gc3355_write_data(gridseed, detect_data, sizeof(detect_data))) {
		applog(LOG_DEBUG, "Failed to write work data to %i, err %d",
			gridseed->device_id, err);
		goto unshin;
	}

	/* waiting for return */
	if (gc3355_get_data(gridseed, rbuf, GRIDSEED_READ_SIZE)) {
		applog(LOG_DEBUG, "No response from %i", gridseed->device_id);
		goto unshin;
	}

	if (memcmp(rbuf, "\x55\xaa\xc0\x00\x90\x90\x90\x90", GRIDSEED_READ_SIZE-4) != 0) {
		applog(LOG_DEBUG, "Bad response from %i",
			gridseed->device_id);
		goto unshin;
	}

	info->fw_version = le32toh(*(uint32_t *)(rbuf+8));
	applog(LOG_NOTICE, "Device found, firmware version %08X, driver version %s",
		info->fw_version, gridseed_version);

	gc3355_init(gridseed, info);

	if (!add_cgpu(gridseed))
		goto unshin;

	return true;

unshin:
	usb_uninit(gridseed);
	free(gridseed->device_data);
	gridseed->device_data = NULL;

shin:
	gridseed = usb_free_cgpu(gridseed);
	return false;
}
Beispiel #9
0
/* Convert sequence \uXXXX */
static inline bool
deunicodify(char **pp, int avail, int *eat)
{
    uint32_t codepoint;
    bool     utf32;
    char    *p = *pp;
    char    *rep = p;

    p++; /* Remove '\' */
    utf32 = (*p == 'U');
    p++, (*eat)++, avail--; /* Remove 'u' */
    if (avail >= 1) {
        if (!isxdigit(*p))
            return false;
        codepoint = hex2bin(*p++);
        (*eat)++, avail--;
    } else {
        return false;
    }
    if (avail >= 1 && isxdigit(*p)) {
        codepoint <<= 4;
        codepoint |= hex2bin(*p++);
        (*eat)++, avail--;
    }
    if (avail >= 1 && isxdigit(*p)) {
        codepoint <<= 4;
        codepoint |= hex2bin(*p++);
        (*eat)++, avail--;
    }
    if (avail >= 1 && isxdigit(*p)) {
        codepoint <<= 4;
        codepoint |= hex2bin(*p++);
        (*eat)++, avail--;
    }
    if (utf32) {
        if (avail >= 1 && isxdigit(*p)) {
            codepoint <<= 4;
            codepoint |= hex2bin(*p++);
            (*eat)++, avail--;
        }
        if (avail >= 1 && isxdigit(*p)) {
            codepoint <<= 4;
            codepoint |= hex2bin(*p++);
            (*eat)++, avail--;
        }
        if (avail >= 1 && isxdigit(*p)) {
            codepoint <<= 4;
            codepoint |= hex2bin(*p++);
            (*eat)++, avail--;
        }
        if (avail >= 1 && isxdigit(*p)) {
            codepoint <<= 4;
            codepoint |= hex2bin(*p++);
            (*eat)++, avail--;
        }
    }

    if (codepoint >= 0x110000)
        codepoint = 0xfffe;

    if (codepoint <= 0x7f)
        *rep = codepoint;
    else if (codepoint <= 0x7ff) {
        *rep++ = 0xc0 | (codepoint >> 6);
        *rep++ = 0x80 | (codepoint & 0x3f);
        (*eat) -= 2;
    } else if (codepoint <= 0xffff) {
Beispiel #10
0
int proc_file(char *rqfile)
    {
    char afn[256], rfn[256];
    FILE *afp = NULL, *rfp = NULL;
    char ibuf[2048];
    int ilen, len, ret = 0;
    char algo[8] = "";
    char amode[8] = "";
    char atest[8] = "";
    int akeysz = 0;
    unsigned char iVec[20], aKey[40];
    int dir = -1, err = 0, step = 0;
    unsigned char plaintext[2048];
    unsigned char ciphertext[2048];
    char *rp;
    EVP_CIPHER_CTX ctx;

    if (!rqfile || !(*rqfile))
	{
	printf("No req file\n");
	return -1;
	}
    strcpy(afn, rqfile);

    if ((afp = fopen(afn, "r")) == NULL)
	{
	printf("Cannot open file: %s, %s\n", 
	       afn, strerror(errno));
	return -1;
	}
    strcpy(rfn,afn);
    rp=strstr(rfn,"req/");
    assert(rp);
    memcpy(rp,"rsp",3);
    rp = strstr(rfn, ".req");
    memcpy(rp, ".rsp", 4);
    if ((rfp = fopen(rfn, "w")) == NULL)
	{
	printf("Cannot open file: %s, %s\n", 
	       rfn, strerror(errno));
	fclose(afp);
	afp = NULL;
	return -1;
	}
    while (!err && (fgets(ibuf, sizeof(ibuf), afp)) != NULL)
	{
	ilen = strlen(ibuf);
	/*      printf("step=%d ibuf=%s",step,ibuf); */
	switch (step)
	    {
	case 0:  /* read preamble */
	    if (ibuf[0] == '\n')
		{ /* end of preamble */
		if ((*algo == '\0') ||
		    (*amode == '\0') ||
		    (akeysz == 0))
		    {
		    printf("Missing Algorithm, Mode or KeySize (%s/%s/%d)\n",
			   algo,amode,akeysz);
		    err = 1;
		    }
		else
		    {
		    fputs(ibuf, rfp);
		    ++ step;
		    }
		}
	    else if (ibuf[0] != '#')
		{
		printf("Invalid preamble item: %s\n", ibuf);
		err = 1;
		}
	    else
		{ /* process preamble */
		char *xp, *pp = ibuf+2;
		int n;
		if (akeysz)
		    { /* insert current time & date */
		    time_t rtim = time(0);
		    fprintf(rfp, "# %s", ctime(&rtim));
		    }
		else
		    {
		    fputs(ibuf, rfp);
		    if (strncmp(pp, "AESVS ", 6) == 0)
			{
			strcpy(algo, "AES");
			/* get test type */
			pp += 6;
			xp = strchr(pp, ' ');
			n = xp-pp;
			strncpy(atest, pp, n);
			atest[n] = '\0';
			/* get mode */
			xp = strrchr(pp, ' '); /* get mode" */
			n = strlen(xp+1)-1;
			strncpy(amode, xp+1, n);
			amode[n] = '\0';
			/* amode[3] = '\0'; */
			printf("Test = %s, Mode = %s\n", atest, amode);
			}
		    else if (strncasecmp(pp, "Key Length : ", 13) == 0)
			{
			akeysz = atoi(pp+13);
			printf("Key size = %d\n", akeysz);
			}
		    }
		}
	    break;

	case 1:  /* [ENCRYPT] | [DECRYPT] */
	    if (ibuf[0] == '[')
		{
		fputs(ibuf, rfp);
		++step;
		if (strncasecmp(ibuf, "[ENCRYPT]", 9) == 0)
		    dir = 1;
		else if (strncasecmp(ibuf, "[DECRYPT]", 9) == 0)
		    dir = 0;
		else
		    {
		    printf("Invalid keyword: %s\n", ibuf);
		    err = 1;
		    }
		break;
		}
	    else if (dir == -1)
		{
		err = 1;
		printf("Missing ENCRYPT/DECRYPT keyword\n");
		break;
		}
	    else 
		step = 2;

	case 2: /* KEY = xxxx */
	    fputs(ibuf, rfp);
	    if(*ibuf == '\n')
		break;
	    if(!strncasecmp(ibuf,"COUNT = ",8))
		break;

	    if (strncasecmp(ibuf, "KEY = ", 6) != 0)
		{
		printf("Missing KEY\n");
		err = 1;
		}
	    else
		{
		len = hex2bin((char*)ibuf+6, strlen(ibuf+6)-1, aKey);
		if (len < 0)
		    {
		    printf("Invalid KEY\n");
		    err =1;
		    break;
		    }
		PrintValue("KEY", aKey, len);
		if (strcmp(amode, "ECB") == 0)
		    {
		    memset(iVec, 0, sizeof(iVec));
		    step = (dir)? 4: 5;  /* no ivec for ECB */
		    }
		else
		    ++step;
		}
	    break;

	case 3: /* IV = xxxx */
	    fputs(ibuf, rfp);
	    if (strncasecmp(ibuf, "IV = ", 5) != 0)
		{
		printf("Missing IV\n");
		err = 1;
		}
	    else
		{
		len = hex2bin((char*)ibuf+5, strlen(ibuf+5)-1, iVec);
		if (len < 0)
		    {
		    printf("Invalid IV\n");
		    err =1;
		    break;
		    }
		PrintValue("IV", iVec, len);
		step = (dir)? 4: 5;
		}
	    break;

	case 4: /* PLAINTEXT = xxxx */
	    fputs(ibuf, rfp);
	    if (strncasecmp(ibuf, "PLAINTEXT = ", 12) != 0)
		{
		printf("Missing PLAINTEXT\n");
		err = 1;
		}
	    else
		{
		int nn = strlen(ibuf+12);
		if(!strcmp(amode,"CFB1"))
		    len=bint2bin(ibuf+12,nn-1,plaintext);
		else
		    len=hex2bin(ibuf+12, nn-1,plaintext);
		if (len < 0)
		    {
		    printf("Invalid PLAINTEXT: %s", ibuf+12);
		    err =1;
		    break;
		    }
		if (len >= sizeof(plaintext))
		    {
		    printf("Buffer overflow\n");
		    }
		PrintValue("PLAINTEXT", (unsigned char*)plaintext, len);
		if (strcmp(atest, "MCT") == 0)  /* Monte Carlo Test */
		    {
		    if(do_mct(amode, akeysz, aKey, iVec, 
			      dir, (unsigned char*)plaintext, len, 
			      rfp) < 0)
			EXIT(1);
		    }
		else
		    {
		    ret = AESTest(&ctx, amode, akeysz, aKey, iVec, 
				  dir,  /* 0 = decrypt, 1 = encrypt */
				  plaintext, ciphertext, len);
		    OutputValue("CIPHERTEXT",ciphertext,len,rfp,
				!strcmp(amode,"CFB1"));
		    }
		step = 6;
		}
	    break;

	case 5: /* CIPHERTEXT = xxxx */
	    fputs(ibuf, rfp);
	    if (strncasecmp(ibuf, "CIPHERTEXT = ", 13) != 0)
		{
		printf("Missing KEY\n");
		err = 1;
		}
	    else
		{
		if(!strcmp(amode,"CFB1"))
		    len=bint2bin(ibuf+13,strlen(ibuf+13)-1,ciphertext);
		else
		    len = hex2bin(ibuf+13,strlen(ibuf+13)-1,ciphertext);
		if (len < 0)
		    {
		    printf("Invalid CIPHERTEXT\n");
		    err =1;
		    break;
		    }

		PrintValue("CIPHERTEXT", ciphertext, len);
		if (strcmp(atest, "MCT") == 0)  /* Monte Carlo Test */
		    {
		    do_mct(amode, akeysz, aKey, iVec, 
			   dir, ciphertext, len, rfp);
		    }
		else
		    {
		    ret = AESTest(&ctx, amode, akeysz, aKey, iVec, 
				  dir,  /* 0 = decrypt, 1 = encrypt */
				  plaintext, ciphertext, len);
		    OutputValue("PLAINTEXT",(unsigned char *)plaintext,len,rfp,
				!strcmp(amode,"CFB1"));
		    }
		step = 6;
		}
	    break;

	case 6:
	    if (ibuf[0] != '\n')
		{
		err = 1;
		printf("Missing terminator\n");
		}
	    else if (strcmp(atest, "MCT") != 0)
		{ /* MCT already added terminating nl */
		fputs(ibuf, rfp);
		}
	    step = 1;
	    break;
	    }
	}
    if (rfp)
	fclose(rfp);
    if (afp)
	fclose(afp);
    return err;
    }
Beispiel #11
0
int main (int argc, char *argv[])
{
  uint64_t p, q, g, t, x, y, k, r, s=0, kinv, xr, H;
  uint64_t v, w, u1, u2;
  char *m;

  puts ("\n  Digital Signature Algorithm example");
  
  if (argc != 2) {
    printf ("\n  usage: dsa <message>\n");
    return 0;
  }
  m=argv[1];
  printf ("\n  Generating p...");
  p=safe_prime(RP);
  printf ("%llX\n  Generating g...", p);
  
  // find g
  q=(p-1)/2;
  for (g=1; g == 1;) {
    // g = t ^ (p-1)/q % p
    t=rand_range (q);            // normally, t would be a hash of q bits
    g=powmod (t, (p-1)/q, p);
  }
  printf ("%llX\n", g);
  
  /** 
  generated by modified openssl gen_params
  
  p=hex2bin("5E6DDA8BC9B2B5A9");
  q=hex2bin("D549");
  g=hex2bin("22729DB49EE21F4B");
  
  powmod
  invmod
  
  */
  printf ("\np=%llX\nq=%llX\ng=%llX", p, q, g);
  
  // generate random x in range of q
  x=rand_range(q);
  // y = g ^ x % p
  y=powmod (g, x, p);
  
  y = 0x7632D; x = 0x628A5;
  printf ("\n\npublic key = %llX\nPrivate key = %llX", y, x);
  
  H=hex2bin(m);
  
  // sign message
  do {
    // generate k in range of q
    k=rand_range(q);
    // k ^ -1 % q
    kinv=invmod (k, q);
    // r = (g ^ k % p) % q
    r=modulo (powmod (g, k, p), q);
    if (r == 0)
      continue;      
    // s = (kinv * (H + x*r)) % q
    xr=multiply (x, r);
    s=add (xr, H);
    s=mulmod (s, kinv, q);
  } while (s == 0);
    
  printf ("\n\n(k=%llX, r=%llX, s=%llX)", k, r, s);
  
  // now verify
  
  // w = s invmod q
  w=invmod (s, q);
  // u1 = (H * w) % q
  u1=mulmod(H, w, q);
  // u2 = (r * w) % q
  u2=mulmod(r, w, q);
  // v = ((g^u1 * y^u2) % p) % q
  u1=powmod (g, u1, p);
  u2=powmod (y, u2, p);
  
  v=mulmod(u1, u2, p);
  v=modulo(v, q);
  
  printf ("\nv = %llX", v);
  printf ("\n  signature is %s", v==r ? "valid" : "invalid");
  
  return 0;
}
void decodeCode() {	
	FILE *fptr;
	if ((fptr=fopen("output.txt","w"))==NULL){
    	printf("Error! opening file");
		exit(1);        
	}	
	
	int i,j;	
	char* isa;
	char* temp2;
	temp2 = filterCode();
	if(temp2 == NULL)
		return;
	isa = readFile("isa.txt");
	char* token = strtok(temp2, ",");	//spliting the string to read each token
	int programCounter = 0; 
    while (token != NULL) {
    	int length = strlen(token);		
		char * result = strstr(isa,token);
		int position = result - isa;

		
		int	detectMemAdd = 0; // stores 1 if token is memory address
		for(i=0;i<length-1;i++){
			if(((isdigit(*(token+i)) || (*(token+i)>='a'&& *(token+i)<='f') || (*(token+i)>='A' && *(token+i)<='F'))))
				detectMemAdd = -1;
			else{
				detectMemAdd = 0;
				break;					
			}	
		}
		char * h;char * mem;
		long ret;
		
		int isAllDigit=0;
		
		for(i=0;i<length;i++){	//checking if token is all digits
			if(isdigit(token[i]))
				isAllDigit =1;
			else
				{
					isAllDigit =0;
					break;
				}
		}
		
		if(isAllDigit ==1){ //if token is all digits then printing the opcode
			ret = strtol(token,&h,10);
			if(ret>15){
				printf("\nError! Memory Overflow\n");
				printf("\nView Help in the Menu to correct your code in code.txt file\n");
			}
			else if (ret>0 && ret<10){
				char buff [2];
				int n=sprintf (buff, "%lu", ret);			
				printf(" %s",hex2bin(*buff));
				fprintf(fptr," %s",hex2bin(*buff));
			}
			else if (ret>9 && ret<16){
				char t = (char) ('a'+ret-10);
				printf(" %s",hex2bin(t));
				fprintf(fptr," %s",hex2bin(t));
			}
		}
		
		if(detectMemAdd == -1 && tolower(*(token+length-1)) == 'h'){ //checking if token is memory address
			detectMemAdd = 1;
			mem = (char*)malloc(4);
			memcpy(mem,token,3);
			mem[4] = '\0';
			ret = strtol(token,&h,10);
		}
		else
			detectMemAdd = 0;
			
		if( length >3 && isAllDigit !=1 && detectMemAdd == 1 && (isalpha(*mem) || isalpha(*(mem+1))) ) {  //checking if token is memory address and is more than 00FH.
			printf("\nError! Memory Overflow\n");
			printf("\nView Help in the Menu to correct your code in code.txt file\n");
			break;
		}
		
		if (length == 2 && detectMemAdd ==1 && isAllDigit !=1){ //if token is a memory address of length is 2 like AH,5H,etc
			printf(" %s",hex2bin(token[0]));
			fprintf(fptr," %s",hex2bin(token[0]));
		}

		//checking if token is memory address and is more than 00FH.			
		if (length >2  && isAllDigit !=1 && detectMemAdd == 1 && ((ret>9 && tolower(*h)=='h') || (ret ==0 && ((tolower(*h)>'f' && tolower(*h)<'a'))) || (ret > 0 && ((tolower(*h)<='f' && tolower(*h)>='a'))))){
			printf("\nError! Memory Overflow\n");
			printf("\nView Help in the Menu to correct your code in code.txt file\n");
			break;
		}
		//if token is a memory address of length more than 2 like 0AH, 05H, 00CH, etc
		else if (length >2  && isAllDigit !=1 && detectMemAdd == 1 && ((ret<=9 && tolower(*h)=='h') || (ret ==0 && ((tolower(*h)<='f' && tolower(*h)>='a'))))){
			if(ret!=0){
				char buffer [2];
				int n=sprintf (buffer, "%lu", ret);			
				printf(" %s",hex2bin(*buffer));
				fprintf(fptr," %s",hex2bin(*buffer));				
			}
			else{
				printf(" %s",hex2bin(*h));
				fprintf(fptr," %s",hex2bin(*h));
				}
		}

		if (result == '\0' && detectMemAdd !=1 && isAllDigit !=1) {	//checking if instruction is not found in the ISA	
			printf("\nError! \"%s\" not found in ISA | Exiting\n",token);
			printf("\nView Help in the Menu to correct your code in code.txt file\n");
			break;
		}
		int lineCounter=1;
		for(i=0; i<isasize;i++){	//getting the line number of each instruction
			char* to = (char*) malloc(length+1);
			memset(to,'\0',length+1);				
  			strncpy(to, isa+i, length);
  			if (strcmp(to,token)==0)  			
  				break;
  			else if (*(isa+i)=='\n')  	
  				lineCounter++;  			

  		}
  		
  		int numOp;
  		if (lineCounter<14)
  			numOp=3;
  		else if(lineCounter>13 && lineCounter<26)
  			numOp=2;
  		else if(lineCounter>25 && lineCounter<31)
		    numOp=1;
		else if (lineCounter>30 && lineCounter<41)
			numOp=0;
		else if (lineCounter>40)
			numOp=-1;
	
		if(numOp>=0 && programCounter >0  && isAllDigit !=1){ 
			putchar('\n');
			programCounter++;
			fputc('\n', fptr);
		} else if(numOp==-1){
			putchar(' ');
			fputc(' ', fptr);			
		}
		if(detectMemAdd !=1 && isAllDigit !=1){
		    for(i=position+length+1;*(isa+i)!='\n';i++){
				putchar(*(isa+i));
				fputc(*(isa+i), fptr);
			}
		}
		if(programCounter == 0)
			programCounter++;	
			
		if(strcmp(token,"HLT")==0){
			printf("\nHALT FOUND | EXITING\n");
			break;			
		}
	//	programCounter++;	

		token = strtok(NULL, ",");
	}
	fclose(fptr);
}
Beispiel #13
0
void fcgi_create_file(void) {
    const struct jparse_actions acts = {
	JPACTS_INT64(
		     JPACT(cb_newfile_size, JPKEY("fileSize"))
		     ),
	JPACTS_STRING(
		      JPACT(cb_newfile_block, JPKEY("fileData"), JPANYITM),
		      JPACT(cb_newfile_addmeta, JPKEY("fileMeta"), JPANYKEY)
		      ),
	JPACTS_NULL(
		    JPACT(cb_newfile_delmeta, JPKEY("fileMeta"), JPANYKEY)
		    )
    };
    struct cb_newfile_ctx yctx;
    jparse_t *J;
    int len;
    rc_ty s;
    sx_hash_t revid;

    quit_unless_has(PRIV_CLUSTER); /* Just in case */

    if(!has_arg("rev") || !has_arg("revid") || strlen(get_arg("revid")) != SXI_SHA1_TEXT_LEN)
	quit_errmsg(500, "File revision missing");
    if(hex2bin(get_arg("revid"), SXI_SHA1_TEXT_LEN, revid.b, sizeof(revid.b)))
        quit_errmsg(400, "Failed to parse revision ID");

    s = sx_hashfs_createfile_begin(hashfs);
    switch (s) {
    case OK:
	break;
    case ENOENT:
	quit_errnum(404);
    case EINVAL:
	quit_errnum(400);
    default:
	WARN("sx_hashfs_createfile_begin failed: %d", s);
	quit_errmsg(rc2http(s), "Cannot initialize file upload");
    }

    yctx.filesize = -1;
    yctx.rc = EINVAL;

    J = sxi_jparse_create(&acts, &yctx, 0);
    if(!J) {
	sx_hashfs_createfile_end(hashfs);
	quit_errmsg(503, "Cannot create JSON parser");
    }

    while((len = get_body_chunk(hashbuf, sizeof(hashbuf))) > 0)
	if(sxi_jparse_digest(J, hashbuf, len))
	    break;

    if(len || sxi_jparse_done(J)) {
	send_error(rc2http(yctx.rc), sxi_jparse_geterr(J));
	sx_hashfs_createfile_end(hashfs);
	sxi_jparse_destroy(J);
	return;
    }
    sxi_jparse_destroy(J);

    auth_complete();
    quit_unless_authed();

    s = sx_hashfs_createfile_commit(hashfs, volume, path, get_arg("rev"), &revid, yctx.filesize, 0);
    if(s != OK)
	quit_errmsg(rc2http(s), msg_get_reason());

    CGI_PUTS("\r\n");
}
int roadmap_nmea_decode (void *user_context,
                         void *decoder_context, char *sentence, int length) {

   RoadMapNmeaAccount account = (RoadMapNmeaAccount) decoder_context;

   int i;
   char *p = sentence;

   int   count;
   char *field[80];

   unsigned char checksum = 0;


   /* We skip any leftover from previous transmission problems,
    * check that the '$' is really here, compute the checksum
    * and then decode the "csv" format.
    */
   while ((*p != '$') && (*p >= ' ')) ++p;

   if (*p != '$') return 0; /* Ignore this ill-formed sentence. */

   sentence = p++;
   roadmap_log (ROADMAP_ERROR, "NMEA: '%s'", sentence);
   while ((*p != '*') && (*p >= ' ')) {
      checksum ^= *p;
      p += 1;
   }

   if (*p == '*') {

      unsigned char mnea_checksum = hex2bin(p[1]) * 16 + hex2bin(p[2]);

      if (mnea_checksum != checksum) {
         roadmap_log (ROADMAP_ERROR,
               "mnea checksum error for '%s' (nmea=%02x, calculated=%02x)",
               sentence,
               mnea_checksum,
               checksum);

         return 0;
      }
   }
   *p = 0;

   for (i = 0, p = sentence; p != NULL && *p != 0; ++i, p = strchr (p, ',')) {
      *p = 0;
      field[i] = ++p;
   }
   count = i;


   /* Now that we have separated each argument of the sentence, retrieve
    * the right decoder & listener functions and call them.
    */
   if (*(field[0]) == 'P') {

      /* This is a proprietary sentence. */

      for (i = 0; RoadMapNmeaPhrase[i].decoder != NULL; ++i) {

         /* Skip standard sentences. */
         if (RoadMapNmeaPhrase[i].vendor == NULL) continue;

         if ((strncmp(RoadMapNmeaPhrase[i].vendor, field[0]+1, 3) == 0) &&
             (strcmp(RoadMapNmeaPhrase[i].sentence, field[0]+4) == 0)) {

            return roadmap_nmea_call (user_context, account, i, count, field);
         }
      }
   } else {

      /* This is a standard sentence. */

      for (i = 0; RoadMapNmeaPhrase[i].decoder != NULL; ++i) {

         /* Skip proprietary sentences. */
         if (RoadMapNmeaPhrase[i].vendor != NULL) continue;

         if (strcmp (RoadMapNmeaPhrase[i].sentence, field[0]+2) == 0) {

            return roadmap_nmea_call (user_context, account, i, count, field);
         }
      }
   }

   roadmap_log (ROADMAP_DEBUG, "unknown nmea sentence %s", field[0]);

   return 0; /* Could not decode it. */
}
Beispiel #15
0
static void sigver(FILE *in, FILE *out)
    {
    DSA *dsa=NULL;
    char buf[1024];
    char lbuf[1024];
    unsigned char msg[1024];
    char *keyword, *value;
    int n=0;
    int dsa2, L, N;
    const EVP_MD *md = NULL;
    DSA_SIG sg, *sig = &sg;

    sig->r = NULL;
    sig->s = NULL;

    while(fgets(buf,sizeof buf,in) != NULL)
	{
	if (!parse_line(&keyword, &value, lbuf, buf))
		{
		fputs(buf,out);
		continue;
		}
	fputs(buf,out);
	if(!strcmp(keyword,"[mod"))
	    {
	    if (!parse_mod(value, &dsa2, &L, &N, &md))
		{
		fprintf(stderr, "Mod Parse Error\n");
		exit (1);
		}
	    if (dsa)
		FIPS_dsa_free(dsa);
	    dsa = FIPS_dsa_new();
	    }
	else if(!strcmp(keyword,"P"))
	    dsa->p=hex2bn(value);
	else if(!strcmp(keyword,"Q"))
	    dsa->q=hex2bn(value);
	else if(!strcmp(keyword,"G"))
	    dsa->g=hex2bn(value);
	else if(!strcmp(keyword,"Msg"))
	    n=hex2bin(value,msg);
	else if(!strcmp(keyword,"Y"))
	    dsa->pub_key=hex2bn(value);
	else if(!strcmp(keyword,"R"))
	    sig->r=hex2bn(value);
	else if(!strcmp(keyword,"S"))
	    {
	    EVP_MD_CTX mctx;
	    int r;
	    FIPS_md_ctx_init(&mctx);
	    sig->s=hex2bn(value);

	    FIPS_digestinit(&mctx, md);
	    FIPS_digestupdate(&mctx, msg, n);
	    no_err = 1;
	    r = FIPS_dsa_verify_ctx(dsa, &mctx, sig);
	    no_err = 0;
	    FIPS_md_ctx_cleanup(&mctx);
	
	    fprintf(out, "Result = %c\n\n", r == 1 ? 'P' : 'F');
	    }
	}
    }
Beispiel #16
0
bool ans_key_h(connection_t *c) {
	char from_name[MAX_STRING_SIZE];
	char to_name[MAX_STRING_SIZE];
	char key[MAX_STRING_SIZE];
	char address[MAX_STRING_SIZE] = "";
	char port[MAX_STRING_SIZE] = "";
	int cipher, digest, maclength, compression;
	node_t *from, *to;

	if(sscanf(c->buffer, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING" %d %d %d %d "MAX_STRING" "MAX_STRING,
		from_name, to_name, key, &cipher, &digest, &maclength,
		&compression, address, port) < 7) {
		logger(LOG_ERR, "Got bad %s from %s (%s)", "ANS_KEY", c->name,
			   c->hostname);
		return false;
	}

	if(!check_id(from_name) || !check_id(to_name)) {
		logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ANS_KEY", c->name, c->hostname, "invalid name");
		return false;
	}

	from = lookup_node(from_name);

	if(!from) {
		logger(LOG_ERR, "Got %s from %s (%s) origin %s which does not exist in our connection list",
			   "ANS_KEY", c->name, c->hostname, from_name);
		return true;
	}

	to = lookup_node(to_name);

	if(!to) {
		logger(LOG_ERR, "Got %s from %s (%s) destination %s which does not exist in our connection list",
			   "ANS_KEY", c->name, c->hostname, to_name);
		return true;
	}

	/* Forward it if necessary */

	if(to != myself) {
		if(tunnelserver)
			return true;

		if(!to->status.reachable) {
			logger(LOG_WARNING, "Got %s from %s (%s) destination %s which is not reachable",
				"ANS_KEY", c->name, c->hostname, to_name);
			return true;
		}

		if(!*address && from->address.sa.sa_family != AF_UNSPEC && to->minmtu) {
			char *address, *port;
			ifdebug(PROTOCOL) logger(LOG_DEBUG, "Appending reflexive UDP address to ANS_KEY from %s to %s", from->name, to->name);
			sockaddr2str(&from->address, &address, &port);
			send_request(to->nexthop->connection, "%s %s %s", c->buffer, address, port);
			free(address);
			free(port);
			return true;
		}

		return send_request(to->nexthop->connection, "%s", c->buffer);
	}

	/* Don't use key material until every check has passed. */
	from->status.validkey = false;

	/* Update our copy of the origin's packet key */
	from->outkey = xrealloc(from->outkey, strlen(key) / 2);
	from->outkeylength = strlen(key) / 2;
	if(!hex2bin(key, from->outkey, from->outkeylength)) {
		logger(LOG_ERR, "Got bad %s from %s(%s): %s", "ANS_KEY", from->name, from->hostname, "invalid key");
		return true;
	}

	/* Check and lookup cipher and digest algorithms */

	if(cipher) {
		from->outcipher = EVP_get_cipherbynid(cipher);

		if(!from->outcipher) {
			logger(LOG_ERR, "Node %s (%s) uses unknown cipher!", from->name,
				   from->hostname);
			return true;
		}

		if(from->outkeylength != from->outcipher->key_len + from->outcipher->iv_len) {
			logger(LOG_ERR, "Node %s (%s) uses wrong keylength!", from->name,
				   from->hostname);
			return true;
		}
	} else {
		from->outcipher = NULL;
	}

	from->outmaclength = maclength;

	if(digest) {
		from->outdigest = EVP_get_digestbynid(digest);

		if(!from->outdigest) {
			logger(LOG_ERR, "Node %s (%s) uses unknown digest!", from->name,
				   from->hostname);
			return true;
		}

		if(from->outmaclength > from->outdigest->md_size || from->outmaclength < 0) {
			logger(LOG_ERR, "Node %s (%s) uses bogus MAC length!",
				   from->name, from->hostname);
			return true;
		}
	} else {
		from->outdigest = NULL;
	}

	if(compression < 0 || compression > 11) {
		logger(LOG_ERR, "Node %s (%s) uses bogus compression level!", from->name, from->hostname);
		return true;
	}
	
	from->outcompression = compression;

	if(from->outcipher)
		if(!EVP_EncryptInit_ex(&from->outctx, from->outcipher, NULL, (unsigned char *)from->outkey, (unsigned char *)from->outkey + from->outcipher->key_len)) {
			logger(LOG_ERR, "Error during initialisation of key from %s (%s): %s",
					from->name, from->hostname, ERR_error_string(ERR_get_error(), NULL));
			return true;
		}

	from->status.validkey = true;
	from->sent_seqno = 0;

	if(*address && *port) {
		ifdebug(PROTOCOL) logger(LOG_DEBUG, "Using reflexive UDP address from %s: %s port %s", from->name, address, port);
		sockaddr_t sa = str2sockaddr(address, port);
		update_node_udp(from, &sa);
	}

	if(from->options & OPTION_PMTU_DISCOVERY && !from->mtuevent)
		send_mtu_probe(from);

	return true;
}
Beispiel #17
0
static void mc2_config(dev_link_t *link)
{
  client_handle_t handle = link->handle;
  local_info_t *dev = link->priv;
  tuple_t tuple;
  cisparse_t parse;
  int last_fn, last_ret;
  u_char buf[64];
  config_info_t conf;
  win_req_t req;
  memreq_t map;
  cistpl_cftable_entry_t dflt = { 0 };
  char *dev_name = NULL; /* get the device name from wl24n_card_init() */
  int nw_len; /* length of networkname */


  DEBUG(0, "mc2_config(0x%p)\n", link);

  /*
    This reads the card's CONFIG tuple to find its configuration
    registers.
  */
  tuple.DesiredTuple = CISTPL_CONFIG;
  tuple.Attributes = 0;
  tuple.TupleData = buf;
  tuple.TupleDataMax = sizeof(buf);
  tuple.TupleOffset = 0;
  CS_CHECK(GetFirstTuple, handle, &tuple);
  CS_CHECK(GetTupleData, handle, &tuple);
  CS_CHECK(ParseTuple, handle, &tuple, &parse);
  link->conf.ConfigBase = parse.config.base;
  link->conf.Present = parse.config.rmask[0];
    
  /* Configure card */
  link->state |= DEV_CONFIG;

  /* Look up the current Vcc */
  CS_CHECK(GetConfigurationInfo, handle, &conf);
  link->conf.Vcc = conf.Vcc;

  /*
    In this loop, we scan the CIS for configuration table entries,
    each of which describes a valid card configuration, including
    voltage, IO window, memory window, and interrupt settings.

    We make no assumptions about the card to be configured: we use
    just the information available in the CIS.  In an ideal world,
    this would work for any PCMCIA card, but it requires a complete
    and accurate CIS.  In practice, a driver usually "knows" most of
    these things without consulting the CIS, and most client drivers
    will only use the CIS to fill in implementation-defined details.
  */
  tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
  CS_CHECK(GetFirstTuple, handle, &tuple);
  while (1) {
    cistpl_cftable_entry_t *cfg = &(parse.cftable_entry);
    CFG_CHECK(GetTupleData, handle, &tuple);
    CFG_CHECK(ParseTuple, handle, &tuple, &parse);

    if (cfg->flags & CISTPL_CFTABLE_DEFAULT) dflt = *cfg;
    if (cfg->index == 0) goto next_entry;
    link->conf.ConfigIndex = cfg->index;
        
    /* Use power settings for Vcc and Vpp if present */
    /*  Note that the CIS values need to be rescaled */
    if (cfg->vcc.present & (1<<CISTPL_POWER_VNOM)) {
      if (conf.Vcc != cfg->vcc.param[CISTPL_POWER_VNOM]/10000)
        goto next_entry;
    } else if (dflt.vcc.present & (1<<CISTPL_POWER_VNOM)) {
      if (conf.Vcc != dflt.vcc.param[CISTPL_POWER_VNOM]/10000)
        goto next_entry;
    }
            
    if (cfg->vpp1.present & (1<<CISTPL_POWER_VNOM))
      link->conf.Vpp1 = link->conf.Vpp2 =
        cfg->vpp1.param[CISTPL_POWER_VNOM]/10000;
    else if (dflt.vpp1.present & (1<<CISTPL_POWER_VNOM))
      link->conf.Vpp1 = link->conf.Vpp2 =
        dflt.vpp1.param[CISTPL_POWER_VNOM]/10000;
        
    /* Do we need to allocate an interrupt? */
    if (cfg->irq.IRQInfo1 || dflt.irq.IRQInfo1)
      link->conf.Attributes |= CONF_ENABLE_IRQ;
        
    /* IO window settings */
    link->io.NumPorts1 = link->io.NumPorts2 = 0;
    if ((cfg->io.nwin > 0) || (dflt.io.nwin > 0)) {
      cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt.io;
      link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO;
      if (!(io->flags & CISTPL_IO_8BIT))
        link->io.Attributes1 = IO_DATA_PATH_WIDTH_16;
      if (!(io->flags & CISTPL_IO_16BIT))
        link->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
      link->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK;
      link->io.BasePort1 = io->win[0].base;
      link->io.NumPorts1 = io->win[0].len;
      if (io->nwin > 1) {
        link->io.Attributes2 = link->io.Attributes1;
        link->io.BasePort2 = io->win[1].base;
        link->io.NumPorts2 = io->win[1].len;
      }
      /* This reserves IO space but doesn't actually enable it */
      CFG_CHECK(RequestIO, link->handle, &link->io);
    }

    /*
      Now set up a common memory window, if needed.  There is room
      in the dev_link_t structure for one memory window handle,
      but if the base addresses need to be saved, or if multiple
      windows are needed, the info should go in the private data
      structure for this device.

      Note that the memory window base is a physical address, and
      needs to be mapped to virtual space with ioremap() before it
      is used.
    */
    if ((cfg->mem.nwin > 0) || (dflt.mem.nwin > 0)) {
      cistpl_mem_t *mem =
        (cfg->mem.nwin) ? &cfg->mem : &dflt.mem;
      req.Attributes = WIN_DATA_WIDTH_16|WIN_MEMORY_TYPE_CM;
      req.Attributes |= WIN_ENABLE;
      req.Base = mem->win[0].host_addr;
      req.Size = mem->win[0].len;
      if (req.Size < 0x1000)
        req.Size = 0x1000;
      req.AccessSpeed = 0;
      link->win = (window_handle_t)link->handle;
      CFG_CHECK(RequestWindow, &link->win, &req);
      map.Page = 0; map.CardOffset = mem->win[0].card_addr;
      CFG_CHECK(MapMemPage, link->win, &map);
    }
    /* If we got this far, we're cool! */
    break;
        
  next_entry:
    if (link->io.NumPorts1)
      CardServices(ReleaseIO, link->handle, &link->io);
    CS_CHECK(GetNextTuple, handle, &tuple);
  }

  /* init the card after we got the io addresses etc. 
     Please note, that the irq value is set to 0, which is false,
     but who evaluates the dev->irq (but ifconfig ?) 
     But we need the mc2_priv for the RequestIRQ call below, so we must
     call it before. On the other hand the RequestIRQ returns the
     correct AssignedIRQ to us ... */
  link->open = 0;
  if (nwn_is_hex) 
    /* condense the hex string into a binary one */
    nw_len = hex2bin(networkname,networkname);
  else
    nw_len = strlen(networkname);

  if ((dev->mc2_priv=wl24n_card_init(dbg_mask, msg_to_dbg_mask,
                                     msg_from_dbg_mask,
                                     link->io.BasePort1,
                                     0, /* was: link->irq.AssignedIRQ */
                                     LLCType, networktype, networkname,
                                     nw_len, Channel, &link->open, 
                                     &dev_name, trace_mask)) == NULL) {
    printk(KERN_DEBUG "wl24_card_init failed\n");
    mc2_release((u_long)link);
    return;
  } 

  /*
    Allocate an interrupt line.  Note that this does not assign a
    handler to the interrupt, unless the 'Handler' member of the
    irq structure is initialized.
  */

  if (link->conf.Attributes & CONF_ENABLE_IRQ) {

    /* if we use the wrapper wl24n_cs_interrupt, we must
       pass dev here ! */
    //link->irq.Instance = dev->mc2_priv;
    link->irq.Instance = dev;

    CS_CHECK(RequestIRQ, link->handle, &link->irq);
    printk(KERN_DEBUG "%s: request irq %d at card service\n",
           dev_name, link->irq.AssignedIRQ);
  }

  /*
    This actually configures the PCMCIA socket -- setting up
    the I/O windows and the interrupt mapping, and putting the
    card and host interface into "Memory and IO" mode.
  */
  CS_CHECK(RequestConfiguration, link->handle, &link->conf);

  /* this will read the MAC addr etc. and enter it into the netdevice struct.
     -> we must do it _after_ the RequestConfiguration ! */
  {
    int i;
    for (i=0; i < 10; i++)
      if (wl24n_card_reset(dev->mc2_priv))
        break;
    if (i >= 10) {
      printk(KERN_WARNING "%s: cannot reset card - giving up\n", dev_name);
      mc2_detach(link); /* calls mc2_release((u_long)link), too */
      return;
    }
  }

  /*
    We can release the IO port allocations here, if some other
    driver for the card is going to loaded, and will expect the
    ports to be available.
  */
  if (free_ports) {
    if (link->io.BasePort1)
      release_region(link->io.BasePort1, link->io.NumPorts1);
    if (link->io.BasePort2)
      release_region(link->io.BasePort2, link->io.NumPorts2);
  }

  /*
    At this point, the dev_node_t structure(s) need to be
    initialized and arranged in a linked list at link->dev.
  */
  dev->node.major = dev->node.minor = 0;
  dev->node.next = NULL; /* only one elem in list at link->dev*/
  strcpy(dev->node.dev_name, dev_name);

  link->dev = &dev->node;

  /* Finally, report what we've done */
  printk(KERN_INFO "%s: %s, version " WL24_VERSION 
         ", $Id: wl24n_cs.c,v 1.6 2003/02/01 13:43:59 jal2 Exp $, compiled "
         __DATE__ " " __TIME__ "\n", 
         dev->node.dev_name, __FILE__);
  printk(KERN_INFO "%s: index 0x%02x: Vcc %d.%d",
         dev->node.dev_name, link->conf.ConfigIndex,
         link->conf.Vcc/10, link->conf.Vcc%10);
  if (link->conf.Vpp1)
    printk(", Vpp %d.%d", link->conf.Vpp1/10, link->conf.Vpp1%10);
  if (link->conf.Attributes & CONF_ENABLE_IRQ)
    printk(", irq %d", link->irq.AssignedIRQ);
  if (link->io.NumPorts1)
    printk(", io 0x%04x-0x%04x  %d lines %s", link->io.BasePort1,
           link->io.BasePort1+link->io.NumPorts1-1,
           link->io.IOAddrLines,
           link->io.Attributes1 == IO_DATA_PATH_WIDTH_AUTO ? "AUTO" :
           link->io.Attributes1 == IO_DATA_PATH_WIDTH_16 ? "16BIT" :
           "8BIT");
  if (link->io.NumPorts2)
    printk(" & 0x%04x-0x%04x", link->io.BasePort2,
           link->io.BasePort2+link->io.NumPorts2-1);
  if (link->win)
    printk(", mem 0x%06lx-0x%06lx", req.Base,
           req.Base+req.Size-1);
  printk("\n");
    
  link->state &= ~DEV_CONFIG_PENDING;
  return;

 cs_failed:
  cs_error(link->handle, last_fn, last_ret);
  mc2_release((u_long)link);

} /* mc2_config */
Beispiel #18
0
int cmd_handle(int UNUSED(sd), char *line)
{
    int argc, func;
    char *argv[10];
    dev_info_t *pdev;

    argc = make_argv(line, ARRAY_SIZE(argv), argv);
    if (argc <= 0)
        return ERROR;

    DBG_OUT("argc is %d", argc);
    
	func = get_cmdid(argv[0]);
	if (func < 0) {
		printf("unknown command: %s\r\n", argv[0]);
		return ERROR;
	}

	switch (func) {
	case SERV_REQ_KICKCLI:
	case SERV_REQ_REBOOT:
	case SERV_REQ_FACTORY:
    {
        PMIFI_PACKET p;
        int i, datalen, packetlen;
        u8 sum;

        i = 0;
        datalen = 0;
        packetlen =  sizeof(MIFI_PACKET ) + datalen;

		p = (PMIFI_PACKET)malloc(packetlen + 1);

        if (argc == 2) {
            devid_t devid;
            hex2bin((u8 *)argv[1], (u8 *)&devid, sizeof(devid_t));
            i = find_device_by_id(&devid);
            if (i < 0) {
                printf("cannot find device: %s\r\n", argv[1]);
                break;
            }
        }

		pdev = get_device(i);
		build_packet_header(p, pdev, func);
		p->datalen = htons(datalen);
		sum = get_checksum((u8 *)p, packetlen);
		*(((u8 *)p) + packetlen) = sum;

		push_data(pdev->sd, (u8 *)p, packetlen + 1);

        free(p);
    }
	break;

	case SERV_REQ_UPGRADE:
	{
		PMIFI_PACKET p;
		char *url = "http://url.cn/QyCLQu";
		int i, url_len, datalen, packetlen;
		u8 sum;

		i = 0;
		url_len = strlen(url);
		datalen = url_len + 2;
		packetlen =  sizeof(MIFI_PACKET ) + datalen;

		p = (PMIFI_PACKET)malloc(packetlen + 1);

		pdev = get_device(i);
		build_packet_header(p, pdev, func);
		p->datalen = htons(datalen);
		p->data[0] = ((u8*)&url_len)[1];
		p->data[1] = ((u8*)&url_len)[0];
		memcpy(p->data + 2, url, datalen);
		sum = get_checksum((u8 *)p, packetlen);
		*(((u8 *)p) + packetlen) = sum;

		push_data(pdev->sd, (u8 *)p, packetlen + 1);

		free(p);
	}
	break;

	case SERV_REQ_KICKUSR:
	{
		PMIFI_PACKET p;
		int i, datalen, packetlen;
		u8 sum;

		i = 0;
		datalen = sizeof(macadr_t);
		packetlen =  sizeof(MIFI_PACKET ) + datalen;

		p = (PMIFI_PACKET)malloc(packetlen + 1);

        if (argc == 3) {
            devid_t devid;
            hex2bin((u8 *)argv[2], (u8 *)&devid, sizeof(devid_t));
            i = find_device_by_id(&devid);
            if (i < 0) {
                printf("cannot find device: %s\r\n", argv[2]);
                break;
            }
        }

		pdev = get_device(i);
        build_packet_header(p, pdev, func);
		p->datalen = htons(datalen);
        if (argc == 1) {
            i = find_first_valid_user(pdev);
        } else {
            macadr_t user;
            hex2bin((u8 *)argv[1], (u8 *)&user, sizeof(macadr_t));
            i = find_user(pdev, &user);
            if (i < 0) {
                printf("cannot find user: %s\r\n", argv[1]);
                break;
            }
        }
		memcpy(p->data, pdev->users[i], datalen);
        clean_user(&pdev->users[i]);  // should be clean after got the response from client
		sum = get_checksum((u8 *)p, packetlen);
		*(((u8 *)p) + packetlen) = sum;

		push_data(pdev->sd, (u8 *)p, packetlen + 1);

		free(p);
	}
	break;
    
    case MIFI_CMD_LDEV:
	{
		int i = 0;
		devid_t freedev = {0};
		for (i = 0; i < ARRAY_SIZE(dev_map); i++)
		{
			if (dev_map[i].valid && (memcmp(&dev_map[i].devid, &freedev, sizeof(devid_t)) != 0))
			{
				printf("DevID: ");
				dump_data((u8 *)&dev_map[i].devid, sizeof(devid_t), 0);
				printf("IMSI:  ");
				dump_data((u8 *)&dev_map[i].imsi, sizeof(imsi_t), 0);
				printf("\r\n");
			}
		}
	}
	break;
	
    case MIFI_CMD_LUSER:
    {
        int i = 0;
        macadr_t freeuser = {0};
        
        if (argc == 2) {
            devid_t devid;
            hex2bin((u8 *)argv[1], (u8 *)&devid, sizeof(devid_t));
            i = find_device_by_id(&devid);
            if (i < 0) {
                printf("cannot find device: %s\r\n", argv[1]);
                break;
            }
        }
        
        pdev = get_device(i);
        for (i = 0; i < ARRAY_SIZE(pdev->users); i++)
        {
            if (memcmp(&pdev->users[i], &freeuser, sizeof(macadr_t)) != 0)
            {
                dump_data((u8 *)&pdev->users[i], sizeof(macadr_t), 0);
            }
        }
    }
    break;

	default:
		DBG_OUT("func isn't impletement: %d", func);
		return ERROR;
    }
    return 0;
}
Beispiel #19
0
static int64_t bitforce_get_result(struct thr_info *thr, struct work *work)
{
	struct cgpu_info *bitforce = thr->cgpu;
	int fdDev = bitforce->device_fd;
	unsigned int delay_time_ms;
	struct timeval elapsed;
	struct timeval now;
	char pdevbuf[0x100];
	char *pnoncebuf;
	uint32_t nonce;

	if (!fdDev)
		return -1;

	while (1) {
		if (unlikely(thr->work_restart))
			return 0;

		mutex_lock(&bitforce->device_mutex);
		BFwrite(fdDev, "ZFX", 3);
		pdevbuf[0] = '\0';
		BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
		mutex_unlock(&bitforce->device_mutex);

		gettimeofday(&now, NULL);
		timersub(&now, &bitforce->work_start_tv, &elapsed);

		if (elapsed.tv_sec >= BITFORCE_LONG_TIMEOUT_S) {
			applog(LOG_ERR, "BFL%i: took %dms - longer than %dms", bitforce->device_id,
				tv_to_ms(elapsed), BITFORCE_LONG_TIMEOUT_MS);
			return 0;
		}

		if (pdevbuf[0] && strncasecmp(pdevbuf, "B", 1)) /* BFL does not respond during throttling */
			break;

		/* if BFL is throttling, no point checking so quickly */
		delay_time_ms = (pdevbuf[0] ? BITFORCE_CHECK_INTERVAL_MS : 2 * WORK_CHECK_INTERVAL_MS);
		nmsleep(delay_time_ms);
		bitforce->wait_ms += delay_time_ms;
	}

	if (elapsed.tv_sec > BITFORCE_TIMEOUT_S) {
		applog(LOG_ERR, "BFL%i: took %dms - longer than %dms", bitforce->device_id,
			tv_to_ms(elapsed), BITFORCE_TIMEOUT_MS);
		bitforce->device_last_not_well = time(NULL);
		bitforce->device_not_well_reason = REASON_DEV_OVER_HEAT;
		bitforce->dev_over_heat_count++;

		if (!pdevbuf[0])	/* Only return if we got nothing after timeout - there still may be results */
			return 0;
	} else if (!strncasecmp(pdevbuf, "N", 1)) {/* Hashing complete (NONCE-FOUND or NO-NONCE) */
		/* Simple timing adjustment. Allow a few polls to cope with
		 * OS timer delays being variably reliable. wait_ms will
		 * always equal sleep_ms when we've waited greater than or
		 * equal to the result return time.*/
		delay_time_ms = bitforce->sleep_ms;

		if (bitforce->wait_ms > bitforce->sleep_ms + (WORK_CHECK_INTERVAL_MS * 2))
			bitforce->sleep_ms += (bitforce->wait_ms - bitforce->sleep_ms) / 2;
		else if (bitforce->wait_ms == bitforce->sleep_ms) {
			if (bitforce->sleep_ms > WORK_CHECK_INTERVAL_MS)
				bitforce->sleep_ms -= WORK_CHECK_INTERVAL_MS;
			else if (bitforce->sleep_ms > BITFORCE_CHECK_INTERVAL_MS)
				bitforce->sleep_ms -= BITFORCE_CHECK_INTERVAL_MS;
		}

		if (delay_time_ms != bitforce->sleep_ms)
			  applog(LOG_DEBUG, "BFL%i: Wait time changed to: %d, waited %u", bitforce->device_id, bitforce->sleep_ms, bitforce->wait_ms);

		/* Work out the average time taken. Float for calculation, uint for display */
		bitforce->avg_wait_f += (tv_to_ms(elapsed) - bitforce->avg_wait_f) / TIME_AVG_CONSTANT;
		bitforce->avg_wait_d = (unsigned int) (bitforce->avg_wait_f + 0.5);
	}

	applog(LOG_DEBUG, "BFL%i: waited %dms until %s", bitforce->device_id, bitforce->wait_ms, pdevbuf);
	if (!strncasecmp(&pdevbuf[2], "-", 1))
		return bitforce->nonces;   /* No valid nonce found */
	else if (!strncasecmp(pdevbuf, "I", 1))
		return 0;	/* Device idle */
	else if (strncasecmp(pdevbuf, "NONCE-FOUND", 11)) {
		bitforce->hw_errors++;
		applog(LOG_WARNING, "BFL%i: Error: Get result reports: %s", bitforce->device_id, pdevbuf);
		bitforce_clear_buffer(bitforce);
		return 0;
	}

	pnoncebuf = &pdevbuf[12];

	while (1) {
		hex2bin((void*)&nonce, pnoncebuf, 4);
#ifndef __BIG_ENDIAN__
		nonce = swab32(nonce);
#endif
		if (unlikely(bitforce->nonce_range && (nonce >= work->blk.nonce ||
			(work->blk.nonce > 0 && nonce < work->blk.nonce - bitforce->nonces - 1)))) {
				applog(LOG_WARNING, "BFL%i: Disabling broken nonce range support", bitforce->device_id);
				bitforce->nonce_range = false;
				work->blk.nonce = 0xffffffff;
				bitforce->sleep_ms *= 5;
				bitforce->kname = KNAME_WORK;
		}
			
		submit_nonce(thr, work, nonce);
		if (strncmp(&pnoncebuf[8], ",", 1))
			break;
		pnoncebuf += 9;
	}

	return bitforce->nonces;
}
Beispiel #20
0
// Return values: true (option parsing ok)
//                false (option not parsed/invalid)
int
ParseOption(char opt, char *arg, RTMP_REQUEST * req)
{
    switch (opt)
    {
#ifdef CRYPTO
    case 'w':
    {
        int res = hex2bin(arg, &req->swfHash.av_val);
        if (!res || res != RTMP_SWF_HASHLEN)
        {
            req->swfHash.av_val = NULL;
            RTMP_Log(RTMP_LOGWARNING,
                     "Couldn't parse swf hash hex string, not hexstring or not %d bytes, ignoring!", RTMP_SWF_HASHLEN);
        }
        req->swfHash.av_len = RTMP_SWF_HASHLEN;
        break;
    }
    case 'x':
    {
        int size = atoi(arg);
        if (size <= 0)
        {
            RTMP_Log(RTMP_LOGERROR, "SWF Size must be at least 1, ignoring\n");
        }
        else
        {
            req->swfSize = size;
        }
        break;
    }
    case 'W':
    {
        STR2AVAL(req->swfUrl, arg);
        req->swfVfy = 1;
    }
    break;
    case 'X':
    {
        int num = atoi(arg);
        if (num < 0)
        {
            RTMP_Log(RTMP_LOGERROR, "SWF Age must be non-negative, ignoring\n");
        }
        else
        {
            req->swfAge = num;
        }
        break;
    }
#endif
    case 'b':
    {
        int32_t bt = atol(arg);
        if (bt < 0)
        {
            RTMP_Log(RTMP_LOGERROR,
                     "Buffer time must be greater than zero, ignoring the specified value %d!",
                     bt);
        }
        else
        {
            req->bufferTime = bt;
        }
        break;
    }
    case 'v':
        req->bLiveStream = TRUE;  // no seeking or resuming possible!
        break;
    case 'd':
        STR2AVAL(req->subscribepath, arg);
        break;
    case 'n':
        STR2AVAL(req->hostname, arg);
        break;
    case 'c':
        req->rtmpport = atoi(arg);
        break;
    case 'l':
    {
        int protocol = atoi(arg);
        if (protocol < RTMP_PROTOCOL_RTMP || protocol > RTMP_PROTOCOL_RTMPTS)
        {
            RTMP_Log(RTMP_LOGERROR, "Unknown protocol specified: %d, using default",
                     protocol);
            return FALSE;
        }
        else
        {
            req->protocol = protocol;
        }
        break;
    }
    case 'y':
        STR2AVAL(req->playpath, arg);
        break;
    case 'r':
    {
        req->rtmpurl = arg;

        AVal parsedHost, parsedPlaypath, parsedApp;
        unsigned int parsedPort = 0;
        int parsedProtocol = RTMP_PROTOCOL_UNDEFINED;

        if (!RTMP_ParseURL
                (req->rtmpurl, &parsedProtocol, &parsedHost, &parsedPort,
                 &parsedPlaypath, &parsedApp))
        {
            RTMP_Log(RTMP_LOGWARNING, "Couldn't parse the specified url (%s)!", arg);
        }
        else
        {
            if (!req->hostname.av_len)
                req->hostname = parsedHost;
            if (req->rtmpport == -1)
                req->rtmpport = parsedPort;
            if (req->playpath.av_len == 0 && parsedPlaypath.av_len)
            {
                req->playpath = parsedPlaypath;
            }
            if (req->protocol == RTMP_PROTOCOL_UNDEFINED)
                req->protocol = parsedProtocol;
            if (req->app.av_len == 0 && parsedApp.av_len)
            {
                req->app = parsedApp;
            }
        }
        break;
    }
    case 'i':
        STR2AVAL(req->fullUrl, arg);
        break;
    case 's':
        STR2AVAL(req->swfUrl, arg);
        break;
    case 't':
        STR2AVAL(req->tcUrl, arg);
        break;
    case 'p':
        STR2AVAL(req->pageUrl, arg);
        break;
    case 'a':
        STR2AVAL(req->app, arg);
        break;
    case 'f':
        STR2AVAL(req->flashVer, arg);
        break;
    case 'u':
        STR2AVAL(req->auth, arg);
        break;
    case 'C':
        parseAMF(&req->extras, arg, &req->edepth);
        break;
    case 'm':
        req->timeout = atoi(arg);
        break;
    case 'A':
        req->dStartOffset = (int)(atof(arg) * 1000.0);
        //printf("dStartOffset = %d\n", dStartOffset);
        break;
    case 'B':
        req->dStopOffset = (int)(atof(arg) * 1000.0);
        //printf("dStartOffset = %d\n", dStartOffset);
        break;
    case 'T':
        STR2AVAL(req->token, arg);
        break;
    case 'S':
        STR2AVAL(req->sockshost, arg);
    case 'q':
        RTMP_debuglevel = RTMP_LOGCRIT;
        break;
    case 'V':
        RTMP_debuglevel = RTMP_LOGDEBUG;
        break;
    case 'z':
        RTMP_debuglevel = RTMP_LOGALL;
        break;
    case 'j':
        STR2AVAL(req->usherToken, arg);
        break;
    default:
        RTMP_LogPrintf("unknown option: %c, arg: %s\n", opt, arg);
        return FALSE;
    }
    return TRUE;
}
Beispiel #21
0
void RRCERT::fromStringContents(const std::vector<std::string>& tokens)
{
	rdata.append("\x01\x00\x00\x00\x00", 5);
	for (unsigned int i = 0; i < tokens[0].length(); i += 2)
		rdata += hex2bin(tokens[0].substr(i, 2));
}
Beispiel #22
0
bool stratum_subscribe(struct stratum_ctx *sctx)
{
	char *s, *sret = NULL;
	const char *sid, *xnonce1;
	int xn2_size;
	json_t *val = NULL, *res_val, *err_val;
	json_error_t err;
	bool ret = false, retry = false;

start:
	s = (char*)malloc(128 + (sctx->session_id ? strlen(sctx->session_id) : 0));
	if (retry)
		sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}");
	else if (sctx->session_id)
		sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": [\"" USER_AGENT "\", \"%s\"]}", sctx->session_id);
	else
		sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": [\"" USER_AGENT "\"]}");

	if (!stratum_send_line(sctx, s))
		goto out;

	if (!socket_full(sctx->sock, 30)) {
		applog(LOG_ERR, "stratum_subscribe timed out");
		goto out;
	}

	sret = stratum_recv_line(sctx);
	if (!sret)
		goto out;

	val = JSON_LOADS(sret, &err);
	free(sret);
	if (!val) {
		applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
		goto out;
	}

	res_val = json_object_get(val, "result");
	err_val = json_object_get(val, "error");

	if (!res_val || json_is_null(res_val) ||
	    (err_val && !json_is_null(err_val))) {
		if (opt_debug || retry) {
			free(s);
			if (err_val)
				s = json_dumps(err_val, JSON_INDENT(3));
			else
				s = strdup("(unknown reason)");
			applog(LOG_ERR, "JSON-RPC call failed: %s", s);
		}
		goto out;
	}

	sid = get_stratum_session_id(res_val);
	if (opt_debug && !sid)
		applog(LOG_DEBUG, "Failed to get Stratum session id");
	xnonce1 = json_string_value(json_array_get(res_val, 1));
	if (!xnonce1) {
		applog(LOG_ERR, "Failed to get extranonce1");
		goto out;
	}
	xn2_size = json_integer_value(json_array_get(res_val, 2));
	if (!xn2_size) {
		applog(LOG_ERR, "Failed to get extranonce2_size");
		goto out;
	}

	pthread_mutex_lock(&sctx->work_lock);
	free(sctx->session_id);
	free(sctx->xnonce1);
	sctx->session_id = sid ? strdup(sid) : NULL;
	sctx->xnonce1_size = strlen(xnonce1) / 2;
	sctx->xnonce1 = (unsigned char*)malloc(sctx->xnonce1_size);
	hex2bin(sctx->xnonce1, xnonce1, sctx->xnonce1_size);
	sctx->xnonce2_size = xn2_size;
	sctx->next_diff = 1.0;
	pthread_mutex_unlock(&sctx->work_lock);

	if (opt_debug && sid)
		applog(LOG_DEBUG, "Stratum session id: %s", sctx->session_id);

	ret = true;

out:
	free(s);
	if (val)
		json_decref(val);

	if (!ret) {
		if (sret && !retry) {
			retry = true;
			goto start;
		}
	}

	return ret;
}
int main(int argc, char **argv)
{
    enum { BINARY, DEFAULT, HEX } outputmode = DEFAULT;
    char *inhex = NULL;
    unsigned char *data;
    int datalen;
    int decode = -1;
    int doing_opts = TRUE;

    while (--argc > 0) {
	char *p = *++argv;

	if (doing_opts && *p == '-') {
	    if (!strcmp(p, "--")) {
		doing_opts = 0;
		continue;
	    }
	    p++;
	    while (*p) {
		switch (*p) {
		  case 'e':
		    decode = 0;
		    break;
		  case 'd':
		    decode = 1;
		    break;
		  case 'b':
		    outputmode = BINARY;
		    break;
		  case 'h':
		    outputmode = HEX;
		    break;
		  default:
		    return 1;
		}
		p++;
	    }
	} else {
	    if (!inhex) {
		inhex = p;
	    } else {
		return 1;
	    }
	}
    }

    if (decode < 0) {
	return 0;
    }

    if (outputmode == DEFAULT)
	outputmode = (decode ? BINARY : HEX);

    if (inhex) {
	datalen = strlen(inhex) / 2;
	data = hex2bin(inhex, datalen);
    } else {
	int datasize = 4096;
	datalen = 0;
	data = snewn(datasize, unsigned char);
	while (1) {
	    int ret = fread(data + datalen, 1, datasize - datalen, stdin);
	    if (ret < 0) {
		fprintf(stderr, "obfusc: read: %s\n", strerror(errno));
		return 1;
	    } else if (ret == 0) {
		break;
	    } else {
		datalen += ret;
		if (datasize - datalen < 4096) {
		    datasize = datalen * 5 / 4 + 4096;
		    data = sresize(data, datasize, unsigned char);
		}
	    }
	}
    }
Beispiel #24
0
static bool stratum_notify(struct stratum_ctx *sctx, json_t *params)
{
	const char *job_id, *prevhash, *coinb1, *coinb2, *version, *nbits, *ntime, *nreward;
	size_t coinb1_size, coinb2_size;
	bool clean, ret = false;
	int merkle_count, i;
	json_t *merkle_arr;
	unsigned char **merkle;

	job_id = json_string_value(json_array_get(params, 0));
	prevhash = json_string_value(json_array_get(params, 1));
	coinb1 = json_string_value(json_array_get(params, 2));
	coinb2 = json_string_value(json_array_get(params, 3));
	merkle_arr = json_array_get(params, 4);
	if (!merkle_arr || !json_is_array(merkle_arr))
		goto out;
	merkle_count = json_array_size(merkle_arr);
	version = json_string_value(json_array_get(params, 5));
	nbits = json_string_value(json_array_get(params, 6));
	ntime = json_string_value(json_array_get(params, 7));
	clean = json_is_true(json_array_get(params, 8));
	nreward = json_string_value(json_array_get(params, 9));

	if (!job_id || !prevhash || !coinb1 || !coinb2 || !version || !nbits || !ntime ||
	    strlen(prevhash) != 64 || strlen(version) != 8 ||
	    strlen(nbits) != 8 || strlen(ntime) != 8) {
		applog(LOG_ERR, "Stratum notify: invalid parameters");
		goto out;
	}
	merkle = (unsigned char**)malloc(merkle_count * sizeof(char *));
	for (i = 0; i < merkle_count; i++) {
		const char *s = json_string_value(json_array_get(merkle_arr, i));
		if (!s || strlen(s) != 64) {
			while (i--)
				free(merkle[i]);
			free(merkle);
			applog(LOG_ERR, "Stratum notify: invalid Merkle branch");
			goto out;
		}
		merkle[i] = (unsigned char*)malloc(32);
		hex2bin(merkle[i], s, 32);
	}

	pthread_mutex_lock(&sctx->work_lock);

	coinb1_size = strlen(coinb1) / 2;
	coinb2_size = strlen(coinb2) / 2;
	sctx->job.coinbase_size = coinb1_size + sctx->xnonce1_size +
	                          sctx->xnonce2_size + coinb2_size;
	sctx->job.coinbase = (unsigned char*)realloc(sctx->job.coinbase, sctx->job.coinbase_size);
	sctx->job.xnonce2 = sctx->job.coinbase + coinb1_size + sctx->xnonce1_size;
	hex2bin(sctx->job.coinbase, coinb1, coinb1_size);
	memcpy(sctx->job.coinbase + coinb1_size, sctx->xnonce1, sctx->xnonce1_size);
	if (!sctx->job.job_id || strcmp(sctx->job.job_id, job_id))
		memset(sctx->job.xnonce2, 0, sctx->xnonce2_size);
	hex2bin(sctx->job.xnonce2 + sctx->xnonce2_size, coinb2, coinb2_size);

	free(sctx->job.job_id);
	sctx->job.job_id = strdup(job_id);
	hex2bin(sctx->job.prevhash, prevhash, 32);

	for (i = 0; i < sctx->job.merkle_count; i++)
		free(sctx->job.merkle[i]);
	free(sctx->job.merkle);
	sctx->job.merkle = merkle;
	sctx->job.merkle_count = merkle_count;

	hex2bin(sctx->job.version, version, 4);
	hex2bin(sctx->job.nbits, nbits, 4);
	hex2bin(sctx->job.ntime, ntime, 4);
	if(nreward != NULL)
	{
		if(strlen(nreward) == 4)
			hex2bin(sctx->job.nreward, nreward, 2);
	}
	sctx->job.clean = clean;

	sctx->job.diff = sctx->next_diff;

	pthread_mutex_unlock(&sctx->work_lock);

	ret = true;

out:
	return ret;
}
Beispiel #25
0
int esc( const tchar * * s)
{
     /* Map escape sequences into their equivalent symbols. Return
      * the equivalent ASCII character. *s is advanced past the
      * escape sequence. If no escape sequence is present, the
      * current character is returned and the string is advanced by
      * one. The following are recognized:
      *
      *  \b     backspace
      *  \f     formfeed
      *  \n     newline
      *  \r     carriage return
      *  \s     space
      *  \t     tab
      *  \e     ASCII ESC character ('\033')
      *  \DDD   number formed of 1-3 octal digits
      *  \xDDD  number formed of 1-3 hex digits
      *  \^C    C = any letter. Control code
      */

     int rval;

     if( **s != _T('\\') )
          rval = *( (*s)++ );
     else {
          ++(*s);                                 /* Skip the \ */
          switch( toupper(**s) ) {
            case _T('\0'):  rval = _T('\\');             break;
            case _T('B'):   rval = _T('\b') ;            break;
            case _T('F'):   rval = _T('\f') ;            break;
            case _T('N'):   rval = _T('\n') ;            break;
            case _T('R'):   rval = _T('\r') ;            break;
            case _T('S'):   rval = _T(' ')  ;            break;
            case _T('T'):   rval = _T('\t') ;            break;
            case _T('E'):   rval = _T('\033');           break;

            case _T('^'):
              rval = *++(*s) ;
              rval = _toupper(rval) - _T('@') ;
              break;

            case _T('X'):
              rval = 0;
              ++(*s);
              if( ISHEXDIGIT(**s) ) {
                   rval  = hex2bin( *(*s)++ );
              }
              if( ISHEXDIGIT(**s) ) {
                   rval <<= 4;
                   rval  |= hex2bin( *(*s)++ );
              }
              if( ISHEXDIGIT(**s) ) {
                   rval <<= 4;
                   rval  |= hex2bin( *(*s)++ );
              }
              --(*s);
              break;

            default:
              if( !ISOCTDIGIT(**s) )
                   rval = **s;
              else {
                   ++(*s);
                   rval = oct2bin( *(*s)++ );
                   if( ISOCTDIGIT(**s) ) {
                        rval <<= 3;
                        rval  |= oct2bin( *(*s)++ );
                   }
                   if( ISOCTDIGIT(**s) ) {
                        rval <<= 3;
                        rval  |= oct2bin( *(*s)++ );
                   }
                   --(*s);
              }
              break;
          }
          ++(*s);
     }
     return rval;
}
Beispiel #26
0
static void pqgver(FILE *in, FILE *out)
    {
    char buf[1024];
    char lbuf[1024];
    char *keyword, *value;
    BIGNUM *p = NULL, *q = NULL, *g = NULL;
    int counter=-1, counter2;
    unsigned long h=-1, h2;
    DSA *dsa=NULL;
    int dsa2, L, N, part_test = 0;
    const EVP_MD *md = NULL;
    int seedlen=-1;
    unsigned char seed[1024];

    while(fgets(buf,sizeof buf,in) != NULL)
	{
	if (!parse_line(&keyword, &value, lbuf, buf))
		{
		if (p && q)
			{
			part_test = 1;
			goto partial;
			}
		fputs(buf,out);
		continue;
		}
	fputs(buf, out);
	if(!strcmp(keyword,"[mod"))
	    {
	    if (!parse_mod(value, &dsa2, &L, &N, &md))
		{
		fprintf(stderr, "Mod Parse Error\n");
		exit (1);
		}
	    }
	else if(!strcmp(keyword,"P"))
	    p=hex2bn(value);
	else if(!strcmp(keyword,"Q"))
	    q=hex2bn(value);
	else if(!strcmp(keyword,"G"))
	    g=hex2bn(value);
	else if(!strcmp(keyword,"Seed"))
	    {
	    seedlen = hex2bin(value, seed);
	    if (!dsa2 && seedlen != 20)
		{
		fprintf(stderr, "Seed parse length error\n");
		exit (1);
		}
	    }
	else if(!strcmp(keyword,"c"))
	    counter =atoi(buf+4);
	partial:
	if(!strcmp(keyword,"H") || part_test)
	    {
	    if (!part_test)
	    	h = atoi(value);
	    if (!p || !q || (!g && !part_test))
		{
		fprintf(stderr, "Parse Error\n");
		exit (1);
		}
	    dsa = FIPS_dsa_new();
	    if (!dsa2 && !dsa_builtin_paramgen(dsa, L, N, md,
					seed, seedlen, NULL,
					&counter2, &h2, NULL))
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
	    if (dsa2 && dsa_builtin_paramgen2(dsa, L, N, md,
					seed, seedlen, NULL,
					&counter2, &h2, NULL) < 0)
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
            if (BN_cmp(dsa->p, p) || BN_cmp(dsa->q, q) || 
		(!part_test &&
		((BN_cmp(dsa->g, g) || (counter != counter2) || (h != h2)))))
	    	fprintf(out, "Result = F\n");
	    else
	    	fprintf(out, "Result = P\n");
	    BN_free(p);
	    BN_free(q);
	    BN_free(g);
	    p = NULL;
	    q = NULL;
	    g = NULL;
	    FIPS_dsa_free(dsa);
	    dsa = NULL;
	    if (part_test)
		{
		fputs(buf,out);
		part_test = 0;
		}
	    }
	}
    }
Beispiel #27
0
int main(int argc, char **argv) {
LOGV("Main()");
extern char *optarg;
extern int optind;
//reset optind counter
optind=1;

int nStatus = RD_SUCCESS;
double percent = 0;
double duration = 0.0;

int nSkipKeyFrames = DEF_SKIPFRM;// skip this number of keyframes when resuming

int bOverrideBufferTime = FALSE;// if the user specifies a buffer time override this is true
int bStdoutMode = TRUE;	// if true print the stream directly to stdout, messages go to stderr
int bResume = FALSE;		// true in resume mode
uint32_t dSeek = 0;		// seek position in resume mode, 0 otherwise
uint32_t bufferTime = DEF_BUFTIME;

// meta header and initial frame for the resume mode (they are read from the file and compared with
// the stream we are trying to continue
char *metaHeader = 0;
uint32_t nMetaHeaderSize = 0;

// video keyframe for matching
char *initialFrame = 0;
uint32_t nInitialFrameSize = 0;
int initialFrameType = 0;	// tye: audio or video

AVal hostname = { 0, 0 };
AVal playpath = { 0, 0 };
AVal subscribepath = { 0, 0 };
AVal usherToken = { 0, 0 }; //Justin.tv auth token
int port = -1;
int protocol = RTMP_PROTOCOL_UNDEFINED;
int retries = 0;
int bLiveStream = FALSE;	// is it a live stream? then we can't seek/resume
int bRealtimeStream = FALSE;  // If true, disable the BUFX hack (be patient)
int bHashes = FALSE;		// display byte counters not hashes by default

long int timeout = DEF_TIMEOUT;	// timeout connection after 120 seconds
uint32_t dStartOffset = 0;	// seek position in non-live mode
uint32_t dStopOffset = 0;
RTMP rtmp = { 0 };

AVal swfUrl = { 0, 0 };
AVal tcUrl = { 0, 0 };
AVal pageUrl = { 0, 0 };
AVal app = { 0, 0 };
AVal auth = { 0, 0 };
AVal swfHash = { 0, 0 };
uint32_t swfSize = 0;
AVal flashVer = { 0, 0 };
AVal sockshost = { 0, 0 };

#ifdef CRYPTO
int swfAge = 30; /* 30 days for SWF cache by default */
int swfVfy = 0;
unsigned char hash[RTMP_SWF_HASHLEN];
#endif

char *flvFile = 0;

signal(SIGINT, sigIntHandler);
signal(SIGTERM, sigIntHandler);
#ifndef WIN32
signal(SIGHUP, sigIntHandler);
signal(SIGPIPE, sigIntHandler);
signal(SIGQUIT, sigIntHandler);
#endif

RTMP_debuglevel = RTMP_LOGINFO;

// Check for --quiet option before printing any output
int index = 0;
while (index < argc) {
	if (strcmp(argv[index], "--quiet") == 0 || strcmp(argv[index], "-q") == 0)
		RTMP_debuglevel = RTMP_LOGCRIT;
	index++;
}

RTMP_LogPrintf("RTMPDump %s\n", RTMPDUMP_VERSION);
RTMP_LogPrintf(
		"(c) 2010 Andrej Stepanchuk, Howard Chu, The Flvstreamer Team; license: GPL\n");

if (!InitSockets()) {
	RTMP_Log(RTMP_LOGERROR,
			"Couldn't load sockets support on your platform, exiting!");
	return RD_FAILED;
}

/* sleep(30); */

RTMP_Init(&rtmp);

int opt;
struct option longopts[] = { { "help", 0, NULL, 'h' }, { "host", 1, NULL, 'n' },
		{ "port", 1, NULL, 'c' }, { "socks", 1, NULL, 'S' }, { "protocol", 1,
				NULL, 'l' }, { "playpath", 1, NULL, 'y' }, { "playlist", 0,
				NULL, 'Y' }, { "rtmp", 1, NULL, 'r' },
		{ "swfUrl", 1, NULL, 's' }, { "tcUrl", 1, NULL, 't' }, { "pageUrl", 1,
				NULL, 'p' }, { "app", 1, NULL, 'a' }, { "auth", 1, NULL, 'u' },
		{ "conn", 1, NULL, 'C' },
#ifdef CRYPTO
		{ "swfhash", 1, NULL, 'w' }, { "swfsize", 1, NULL, 'x' }, { "swfVfy", 1,
				NULL, 'W' }, { "swfAge", 1, NULL, 'X' },
#endif
		{ "flashVer", 1, NULL, 'f' }, { "live", 0, NULL, 'v' }, { "realtime", 0,
				NULL, 'R' }, { "flv", 1, NULL, 'o' },
		{ "resume", 0, NULL, 'e' }, { "timeout", 1, NULL, 'm' }, { "buffer", 1,
				NULL, 'b' }, { "skip", 1, NULL, 'k' }, { "subscribe", 1, NULL,
				'd' }, { "start", 1, NULL, 'A' }, { "stop", 1, NULL, 'B' }, {
				"token", 1, NULL, 'T' }, { "hashes", 0, NULL, '#' }, { "debug",
				0, NULL, 'z' }, { "quiet", 0, NULL, 'q' }, { "verbose", 0, NULL,
				'V' }, { "jtv", 1, NULL, 'j' }, { 0, 0, 0, 0 } };

while ((opt = getopt_long(argc, argv,
		"hVveqzRr:s:t:p:a:b:f:o:u:C:n:c:l:y:Ym:k:d:A:B:T:w:x:W:X:S:#j:",
		longopts, NULL)) != -1) {
	switch (opt) {
	case 'h':
		usage(argv[0]);
		return RD_SUCCESS;
#ifdef CRYPTO
	case 'w': {
		int res = hex2bin(optarg, &swfHash.av_val);
		if (res != RTMP_SWF_HASHLEN) {
			swfHash.av_val = NULL;
			RTMP_Log(RTMP_LOGWARNING,
					"Couldn't parse swf hash hex string, not hexstring or not %d bytes, ignoring!",
					RTMP_SWF_HASHLEN);
		}
		swfHash.av_len = RTMP_SWF_HASHLEN;
		break;
	}
	case 'x': {
		int size = atoi(optarg);
		if (size <= 0) {
			RTMP_Log(RTMP_LOGERROR, "SWF Size must be at least 1, ignoring\n");
		} else {
			swfSize = size;
		}
		break;
	}
	case 'W':
		STR2AVAL(swfUrl, optarg);
		swfVfy = 1;
		break;
	case 'X': {
		int num = atoi(optarg);
		if (num < 0) {
			RTMP_Log(RTMP_LOGERROR, "SWF Age must be non-negative, ignoring\n");
		} else {
			swfAge = num;
		}
	}
		break;
#endif
	case 'k':
		nSkipKeyFrames = atoi(optarg);
		if (nSkipKeyFrames < 0) {
			RTMP_Log(RTMP_LOGERROR,
					"Number of keyframes skipped must be greater or equal zero, using zero!");
			nSkipKeyFrames = 0;
		} else {
			RTMP_Log(RTMP_LOGDEBUG,
					"Number of skipped key frames for resume: %d",
					nSkipKeyFrames);
		}
		break;
	case 'b': {
		int32_t bt = atol(optarg);
		if (bt < 0) {
			RTMP_Log(RTMP_LOGERROR,
					"Buffer time must be greater than zero, ignoring the specified value %d!",
					bt);
		} else {
			bufferTime = bt;
			bOverrideBufferTime = TRUE;
		}
		break;
	}
	case 'v':
		bLiveStream = TRUE;	// no seeking or resuming possible!
		break;
	case 'R':
		bRealtimeStream = TRUE; // seeking and resuming is still possible
		break;
	case 'd':
		STR2AVAL(subscribepath, optarg);
		break;
	case 'n':
		STR2AVAL(hostname, optarg);
		break;
	case 'c':
		port = atoi(optarg);
		break;
	case 'l':
		protocol = atoi(optarg);
		if (protocol < RTMP_PROTOCOL_RTMP || protocol > RTMP_PROTOCOL_RTMPTS) {
			RTMP_Log(RTMP_LOGERROR, "Unknown protocol specified: %d", protocol);
			return RD_FAILED;
		}
		break;
	case 'y':
		STR2AVAL(playpath, optarg);
		break;
	case 'Y':
		RTMP_SetOpt(&rtmp, &av_playlist, (AVal *) &av_true);
		break;
	case 'r': {
		AVal parsedHost, parsedApp, parsedPlaypath;
		unsigned int parsedPort = 0;
		int parsedProtocol = RTMP_PROTOCOL_UNDEFINED;

		if (!RTMP_ParseURL(optarg, &parsedProtocol, &parsedHost, &parsedPort,
				&parsedPlaypath, &parsedApp)) {
			RTMP_Log(RTMP_LOGWARNING, "Couldn't parse the specified url (%s)!",
					optarg);
		} else {
			if (!hostname.av_len)
				hostname = parsedHost;
			if (port == -1)
				port = parsedPort;
			if (playpath.av_len == 0 && parsedPlaypath.av_len) {
				playpath = parsedPlaypath;
			}
			if (protocol == RTMP_PROTOCOL_UNDEFINED)
				protocol = parsedProtocol;
			if (app.av_len == 0 && parsedApp.av_len) {
				app = parsedApp;
			}
		}
		break;
	}
	case 's':
		STR2AVAL(swfUrl, optarg);
		break;
	case 't':
		STR2AVAL(tcUrl, optarg);
		break;
	case 'p':
		STR2AVAL(pageUrl, optarg);
		break;
	case 'a':
		STR2AVAL(app, optarg);
		break;
	case 'f':
		STR2AVAL(flashVer, optarg);
		break;
	case 'o':
		flvFile = optarg;
		if (strcmp(flvFile, "-"))
			bStdoutMode = FALSE;

		break;
	case 'e':
		bResume = TRUE;
		break;
	case 'u':
		STR2AVAL(auth, optarg);
		break;
	case 'C': {
		AVal av;
		STR2AVAL(av, optarg);
		if (!RTMP_SetOpt(&rtmp, &av_conn, &av)) {
			RTMP_Log(RTMP_LOGERROR, "Invalid AMF parameter: %s", optarg);
			return RD_FAILED;
		}
	}
		break;
	case 'm':
		timeout = atoi(optarg);
		break;
	case 'A':
		dStartOffset = (int) (atof(optarg) * 1000.0);
		break;
	case 'B':
		dStopOffset = (int) (atof(optarg) * 1000.0);
		break;
	case 'T': {
		AVal token;
		STR2AVAL(token, optarg);
		RTMP_SetOpt(&rtmp, &av_token, &token);
	}
		break;
	case '#':
		bHashes = TRUE;
		break;
	case 'q':
		RTMP_debuglevel = RTMP_LOGCRIT;
		break;
	case 'V':
		RTMP_debuglevel = RTMP_LOGDEBUG;
		break;
	case 'z':
		RTMP_debuglevel = RTMP_LOGALL;
		break;
	case 'S':
		STR2AVAL(sockshost, optarg);
		break;
	case 'j':
		STR2AVAL(usherToken, optarg);
		break;
	default:
		RTMP_LogPrintf("unknown option: %c\n", opt);
		usage(argv[0]);
		return RD_FAILED;
		break;
	}
}

if (!hostname.av_len) {
	RTMP_Log(RTMP_LOGERROR,
			"You must specify a hostname (--host) or url (-r \"rtmp://host[:port]/playpath\") containing a hostname");
	return RD_FAILED;
}
if (playpath.av_len == 0) {
	RTMP_Log(RTMP_LOGERROR,
			"You must specify a playpath (--playpath) or url (-r \"rtmp://host[:port]/playpath\") containing a playpath");
	return RD_FAILED;
}

if (protocol == RTMP_PROTOCOL_UNDEFINED) {
	RTMP_Log(RTMP_LOGWARNING,
			"You haven't specified a protocol (--protocol) or rtmp url (-r), using default protocol RTMP");
	protocol = RTMP_PROTOCOL_RTMP;
}
if (port == -1) {
	RTMP_Log(RTMP_LOGWARNING,
			"You haven't specified a port (--port) or rtmp url (-r), using default port 1935");
	port = 0;
}
if (port == 0) {
	if (protocol & RTMP_FEATURE_SSL)
		port = 443;
	else if (protocol & RTMP_FEATURE_HTTP)
		port = 80;
	else
		port = 1935;
}

if (flvFile == 0) {
	RTMP_Log(RTMP_LOGWARNING,
			"You haven't specified an output file (-o filename), using stdout");
	bStdoutMode = TRUE;
}

if (bStdoutMode && bResume) {
	RTMP_Log(RTMP_LOGWARNING,
			"Can't resume in stdout mode, ignoring --resume option");
	bResume = FALSE;
}

if (bLiveStream && bResume) {
	RTMP_Log(RTMP_LOGWARNING,
			"Can't resume live stream, ignoring --resume option");
	bResume = FALSE;
}

#ifdef CRYPTO
if (swfVfy) {
	if (RTMP_HashSWF(swfUrl.av_val, &swfSize, hash, swfAge) == 0) {
		swfHash.av_val = (char *) hash;
		swfHash.av_len = RTMP_SWF_HASHLEN;
	}
}

if (swfHash.av_len == 0 && swfSize > 0) {
	RTMP_Log(RTMP_LOGWARNING,
			"Ignoring SWF size, supply also the hash with --swfhash");
	swfSize = 0;
}

if (swfHash.av_len != 0 && swfSize == 0) {
	RTMP_Log(RTMP_LOGWARNING,
			"Ignoring SWF hash, supply also the swf size  with --swfsize");
	swfHash.av_len = 0;
	swfHash.av_val = NULL;
}
#endif

if (tcUrl.av_len == 0) {
	tcUrl.av_len = strlen(RTMPProtocolStringsLower[protocol]) + hostname.av_len
			+ app.av_len + sizeof("://:65535/");
	tcUrl.av_val = (char *) malloc(tcUrl.av_len);
	if (!tcUrl.av_val)
		return RD_FAILED;
	tcUrl.av_len = snprintf(tcUrl.av_val, tcUrl.av_len, "%s://%.*s:%d/%.*s",
			RTMPProtocolStringsLower[protocol], hostname.av_len,
			hostname.av_val, port, app.av_len, app.av_val);
}

int first = 1;

// User defined seek offset
if (dStartOffset > 0) {
	// Live stream
	if (bLiveStream) {
		RTMP_Log(RTMP_LOGWARNING,
				"Can't seek in a live stream, ignoring --start option");
		dStartOffset = 0;
	}
}

RTMP_SetupStream(&rtmp, protocol, &hostname, port, &sockshost, &playpath,
		&tcUrl, &swfUrl, &pageUrl, &app, &auth, &swfHash, swfSize, &flashVer,
		&subscribepath, &usherToken, dSeek, dStopOffset, bLiveStream, timeout);

/* Try to keep the stream moving if it pauses on us */
if (!bLiveStream && !bRealtimeStream && !(protocol & RTMP_FEATURE_HTTP))
	rtmp.Link.lFlags |= RTMP_LF_BUFX;

off_t size = 0;

// ok, we have to get the timestamp of the last keyframe (only keyframes are seekable) / last audio frame (audio only streams)
if (bResume) {
	nStatus = OpenResumeFile(flvFile, &file, &size, &metaHeader,
			&nMetaHeaderSize, &duration);
	if (nStatus == RD_FAILED)
		goto clean;

	if (!file) {
		// file does not exist, so go back into normal mode
		bResume = FALSE; // we are back in fresh file mode (otherwise finalizing file won't be done)
	} else {
		nStatus = GetLastKeyframe(file, nSkipKeyFrames, &dSeek, &initialFrame,
				&initialFrameType, &nInitialFrameSize);
		if (nStatus == RD_FAILED) {
			RTMP_Log(RTMP_LOGDEBUG, "Failed to get last keyframe.");
			goto clean;
		}

		if (dSeek == 0) {
			RTMP_Log(RTMP_LOGDEBUG,
					"Last keyframe is first frame in stream, switching from resume to normal mode!");
			bResume = FALSE;
		}
	}
}

if (!file) {
	if (bStdoutMode) {
		file = stdout;
		SET_BINMODE(file);
	} else {
		file = fopen(flvFile, "w+b");
		if (file == 0) {
			RTMP_LogPrintf("Failed to open file! %s\n", flvFile);
			return RD_FAILED;
		}
	}
}

#ifdef _DEBUG
netstackdump = fopen("netstackdump", "wb");
netstackdump_read = fopen("netstackdump_read", "wb");
#endif

while (!RTMP_ctrlC) {
	RTMP_Log(RTMP_LOGDEBUG, "Setting buffer time to: %dms", bufferTime);
	RTMP_SetBufferMS(&rtmp, bufferTime);

	if (first) {
		first = 0;
		RTMP_LogPrintf("Connecting ...\n");

		if (!RTMP_Connect(&rtmp, NULL)) {
			nStatus = RD_NO_CONNECT;
			break;
		}

		RTMP_Log(RTMP_LOGINFO, "Connected...");

		// User defined seek offset
		if (dStartOffset > 0) {
			// Don't need the start offset if resuming an existing file
			if (bResume) {
				RTMP_Log(RTMP_LOGWARNING,
						"Can't seek a resumed stream, ignoring --start option");
				dStartOffset = 0;
			} else {
				dSeek = dStartOffset;
			}
		}

		// Calculate the length of the stream to still play
		if (dStopOffset > 0) {
			// Quit if start seek is past required stop offset
			if (dStopOffset <= dSeek) {
				RTMP_LogPrintf("Already Completed\n");
				nStatus = RD_SUCCESS;
				break;
			}
		}

		if (!RTMP_ConnectStream(&rtmp, dSeek)) {
			nStatus = RD_FAILED;
			break;
		}
	} else {
		nInitialFrameSize = 0;

		if (retries) {
			RTMP_Log(RTMP_LOGERROR, "Failed to resume the stream\n\n");
			if (!RTMP_IsTimedout(&rtmp))
				nStatus = RD_FAILED;
			else
				nStatus = RD_INCOMPLETE;
			break;
		}
		RTMP_Log(RTMP_LOGINFO, "Connection timed out, trying to resume.\n\n");
		/* Did we already try pausing, and it still didn't work? */
		if (rtmp.m_pausing == 3) {
			/* Only one try at reconnecting... */
			retries = 1;
			dSeek = rtmp.m_pauseStamp;
			if (dStopOffset > 0) {
				if (dStopOffset <= dSeek) {
					RTMP_LogPrintf("Already Completed\n");
					nStatus = RD_SUCCESS;
					break;
				}
			}
			if (!RTMP_ReconnectStream(&rtmp, dSeek)) {
				RTMP_Log(RTMP_LOGERROR, "Failed to resume the stream\n\n");
				if (!RTMP_IsTimedout(&rtmp))
					nStatus = RD_FAILED;
				else
					nStatus = RD_INCOMPLETE;
				break;
			}
		} else if (!RTMP_ToggleStream(&rtmp)) {
			RTMP_Log(RTMP_LOGERROR, "Failed to resume the stream\n\n");
			if (!RTMP_IsTimedout(&rtmp))
				nStatus = RD_FAILED;
			else
				nStatus = RD_INCOMPLETE;
			break;
		}
		bResume = TRUE;
	}

	nStatus = Download(&rtmp, file, dSeek, dStopOffset, duration, bResume,
			metaHeader, nMetaHeaderSize, initialFrame, initialFrameType,
			nInitialFrameSize, nSkipKeyFrames, bStdoutMode, bLiveStream,
			bRealtimeStream, bHashes, bOverrideBufferTime, bufferTime,
			&percent);
	free(initialFrame);
	initialFrame = NULL;

	/* If we succeeded, we're done.
	 */
	if (nStatus != RD_INCOMPLETE || !RTMP_IsTimedout(&rtmp) || bLiveStream)
		break;
}

if (nStatus == RD_SUCCESS) {
	RTMP_LogPrintf("Download complete\n");
} else if (nStatus == RD_INCOMPLETE) {
	RTMP_LogPrintf(
			"Download may be incomplete (downloaded about %.2f%%), try resuming\n",
			percent);
}

clean: RTMP_Log(RTMP_LOGDEBUG, "Closing connection.\n");
RTMP_Close(&rtmp);

if (file != 0){
	fclose(file);
	file = 0;
}

CleanupSockets();

#ifdef _DEBUG
if (netstackdump != 0)
fclose(netstackdump);
if (netstackdump_read != 0)
fclose(netstackdump_read);
#endif
return nStatus;
}
Beispiel #28
0
static void siggen(FILE *in, FILE *out)
    {
    char buf[1024];
    char lbuf[1024];
    char *keyword, *value;
    int dsa2, L, N;
    const EVP_MD *md = NULL;
    DSA *dsa=NULL;

    while(fgets(buf,sizeof buf,in) != NULL)
	{
	if (!parse_line(&keyword, &value, lbuf, buf))
		{
		fputs(buf,out);
		continue;
		}
	fputs(buf,out);
	if(!strcmp(keyword,"[mod"))
	    {
	    if (!parse_mod(value, &dsa2, &L, &N, &md))
		{
		fprintf(stderr, "Mod Parse Error\n");
		exit (1);
		}
	    if (dsa)
		FIPS_dsa_free(dsa);
	    dsa = FIPS_dsa_new();
	    if (!dsa2 && !dsa_builtin_paramgen(dsa, L, N, md, NULL, 0,
						NULL, NULL, NULL, NULL))
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
	    if (dsa2 && dsa_builtin_paramgen2(dsa, L, N, md, NULL, 0,
						NULL, NULL, NULL, NULL) <= 0)
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
	    do_bn_print_name(out, "P",dsa->p);
	    do_bn_print_name(out, "Q",dsa->q);
	    do_bn_print_name(out, "G",dsa->g);
	    fputs("\n", out);
	    }
	else if(!strcmp(keyword,"Msg"))
	    {
	    unsigned char msg[1024];
	    int n;
	    EVP_MD_CTX mctx;
	    DSA_SIG *sig;
	    FIPS_md_ctx_init(&mctx);

	    n=hex2bin(value,msg);

	    if (!DSA_generate_key(dsa))
		exit(1);
	    do_bn_print_name(out, "Y",dsa->pub_key);

	    FIPS_digestinit(&mctx, md);
	    FIPS_digestupdate(&mctx, msg, n);
	    sig = FIPS_dsa_sign_ctx(dsa, &mctx);

	    do_bn_print_name(out, "R",sig->r);
	    do_bn_print_name(out, "S",sig->s);
	    fputs("\n", out);
	    FIPS_dsa_sig_free(sig);
	    FIPS_md_ctx_cleanup(&mctx);
	    }
	}
	if (dsa)
		FIPS_dsa_free(dsa);
    }
Beispiel #29
0
static int64_t bitforce_get_result(struct thr_info *thr, struct work *work)
{
	struct cgpu_info *bitforce = thr->cgpu;
	unsigned int delay_time_ms;
	struct timeval elapsed;
	struct timeval now;
	char buf[BITFORCE_BUFSIZ+1];
	int amount;
	char *pnoncebuf;
	uint32_t nonce;

	while (1) {
		if (unlikely(thr->work_restart))
			return 0;

		mutex_lock(&bitforce->device_mutex);
		usb_write(bitforce, BITFORCE_WORKSTATUS, BITFORCE_WORKSTATUS_LEN, &amount, C_REQUESTWORKSTATUS);
		usb_read_nl(bitforce, buf, sizeof(buf)-1, &amount, C_GETWORKSTATUS);
		mutex_unlock(&bitforce->device_mutex);

		cgtime(&now);
		timersub(&now, &bitforce->work_start_tv, &elapsed);

		if (elapsed.tv_sec >= BITFORCE_LONG_TIMEOUT_S) {
			applog(LOG_ERR, "%s%i: took %ldms - longer than %dms",
				bitforce->drv->name, bitforce->device_id,
				tv_to_ms(elapsed), BITFORCE_LONG_TIMEOUT_MS);
			return 0;
		}

		if (amount > 0 && buf[0] && strncasecmp(buf, "B", 1)) /* BFL does not respond during throttling */
			break;

		/* if BFL is throttling, no point checking so quickly */
		delay_time_ms = (buf[0] ? BITFORCE_CHECK_INTERVAL_MS : 2 * WORK_CHECK_INTERVAL_MS);
		cgsleep_ms(delay_time_ms);
		bitforce->wait_ms += delay_time_ms;
	}

	if (elapsed.tv_sec > BITFORCE_TIMEOUT_S) {
		applog(LOG_ERR, "%s%i: took %ldms - longer than %dms",
			bitforce->drv->name, bitforce->device_id,
			tv_to_ms(elapsed), BITFORCE_TIMEOUT_MS);
		dev_error(bitforce, REASON_DEV_OVER_HEAT);

		/* Only return if we got nothing after timeout - there still may be results */
		if (amount == 0)
			return 0;
	} else if (!strncasecmp(buf, BITFORCE_EITHER, BITFORCE_EITHER_LEN)) {
		/* Simple timing adjustment. Allow a few polls to cope with
		 * OS timer delays being variably reliable. wait_ms will
		 * always equal sleep_ms when we've waited greater than or
		 * equal to the result return time.*/
		delay_time_ms = bitforce->sleep_ms;

		if (bitforce->wait_ms > bitforce->sleep_ms + (WORK_CHECK_INTERVAL_MS * 2))
			bitforce->sleep_ms += (bitforce->wait_ms - bitforce->sleep_ms) / 2;
		else if (bitforce->wait_ms == bitforce->sleep_ms) {
			if (bitforce->sleep_ms > WORK_CHECK_INTERVAL_MS)
				bitforce->sleep_ms -= WORK_CHECK_INTERVAL_MS;
			else if (bitforce->sleep_ms > BITFORCE_CHECK_INTERVAL_MS)
				bitforce->sleep_ms -= BITFORCE_CHECK_INTERVAL_MS;
		}

		if (delay_time_ms != bitforce->sleep_ms)
			  applog(LOG_DEBUG, "%s%i: Wait time changed to: %d, waited %u",
					bitforce->drv->name, bitforce->device_id,
					bitforce->sleep_ms, bitforce->wait_ms);

		/* Work out the average time taken. Float for calculation, uint for display */
		bitforce->avg_wait_f += (tv_to_ms(elapsed) - bitforce->avg_wait_f) / TIME_AVG_CONSTANT;
		bitforce->avg_wait_d = (unsigned int) (bitforce->avg_wait_f + 0.5);
	}

	applog(LOG_DEBUG, "%s%i: waited %dms until %s",
			bitforce->drv->name, bitforce->device_id,
			bitforce->wait_ms, buf);
	if (!strncasecmp(buf, BITFORCE_NO_NONCE, BITFORCE_NO_NONCE_MATCH))
		return bitforce->nonces;   /* No valid nonce found */
	else if (!strncasecmp(buf, BITFORCE_IDLE, BITFORCE_IDLE_MATCH))
		return 0;	/* Device idle */
	else if (strncasecmp(buf, BITFORCE_NONCE, BITFORCE_NONCE_LEN)) {
		bitforce->hw_errors++;
		applog(LOG_WARNING, "%s%i: Error: Get result reports: %s",
			bitforce->drv->name, bitforce->device_id, buf);
		bitforce_initialise(bitforce, true);
		return 0;
	}

	pnoncebuf = &buf[12];

	while (1) {
		hex2bin((void*)&nonce, pnoncebuf, 4);
#ifndef __BIG_ENDIAN__
		nonce = swab32(nonce);
#endif
		if (unlikely(bitforce->nonce_range && (nonce >= work->blk.nonce ||
			(work->blk.nonce > 0 && nonce < work->blk.nonce - bitforce->nonces - 1)))) {
				applog(LOG_WARNING, "%s%i: Disabling broken nonce range support",
					bitforce->drv->name, bitforce->device_id);
				bitforce->nonce_range = false;
				work->blk.nonce = 0xffffffff;
				bitforce->sleep_ms *= 5;
				bitforce->kname = KNAME_WORK;
		}
			
		submit_nonce(thr, work, nonce);
		if (strncmp(&pnoncebuf[8], ",", 1))
			break;
		pnoncebuf += 9;
	}

	return bitforce->nonces;
}
Beispiel #30
0
/**
 * In: RIL_REQUEST_SEND_SMS
 *   Send an SMS message.
 *
 * Out: TAPI_NETTEXT_SEND
 */
void ril_request_send_sms(RIL_Token t, void *data, size_t length)
{
	tapiNettextInfo* mess;
	char *pdu, *a, *message;
	unsigned char *smsc, *pdu_hex, *p, *message_tmp;
	int smsc_length, pdu_length, pdu_hex_length, i, numberLen, send_msg_type;

	if (data == NULL || length < 2 * sizeof(char *))
		return;

	pdu = ((char **) data)[1];
	pdu_length = 0;

	if (pdu != NULL) {
		pdu_length = strlen(pdu) + 1;
		pdu = strdup(pdu);
	}

	/* We first need to get SMS SVC before sending the message */

	smsc_length = strlen((char *) ril_data.smsc_number);
	smsc = (unsigned char *) strdup((char *) ril_data.smsc_number);

	if (pdu == NULL || pdu_length <= 0 || smsc == NULL || smsc_length <= 0) {
		LOGE("Provided PDU or SMSC is invalid! Aborting");
		ril_request_complete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
		return;
	}

	if ((pdu_length / 2 + smsc_length) > 0xfe) {
		LOGE("PDU or SMSC too large, aborting");
		ril_request_complete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
		return;
	}

	pdu_hex_length = pdu_length % 2 == 0 ? pdu_length / 2 :	(pdu_length ^ 1) / 2;

	pdu_hex = calloc(1, pdu_hex_length);

	hex2bin(pdu, pdu_length, pdu_hex);

	send_msg_type = 0;

	/* PDU operations */

	int pdu_tp_da_index = 2;

	unsigned char pdu_tp_da_len = pdu_hex[pdu_tp_da_index];

	if (pdu_tp_da_len > 0xff / 2) {

		LOGE("PDU TP-DA Len failed (0x%x)\n", pdu_tp_da_len);

		goto pdu_end;

	}

	LOGD("PDU TP-DA Len is 0x%x\n", pdu_tp_da_len);

	int pdu_tp_udh_index = pdu_tp_da_index + pdu_tp_da_len / 2 + 5;

	if (pdu_tp_da_len % 2 > 0)
		pdu_tp_udh_index += 1;
		

	unsigned char pdu_tp_udh_len = pdu_hex[pdu_tp_udh_index];

	if (pdu_tp_udh_len > 0xff / 2 || pdu_tp_udh_len < 5) {

		LOGE("PDU TP-UDH Len failed (0x%x)\n", pdu_tp_udh_len);

		goto pdu_end;

	}

	LOGD("PDU TP-UDH Len is 0x%x\n", pdu_tp_udh_len);

	int pdu_tp_udh_num_index = pdu_tp_udh_index + 4;

	unsigned char pdu_tp_udh_num = pdu_hex[pdu_tp_udh_num_index];

	if (pdu_tp_udh_num > 0xf) {

		LOGE("PDU TP-UDH Num failed (0x%x)\n", pdu_tp_udh_num);

		goto pdu_end;

	}

	int pdu_tp_udh_seq_index = pdu_tp_udh_index + 5;

	unsigned char pdu_tp_udh_seq = pdu_hex[pdu_tp_udh_seq_index];

	if (pdu_tp_udh_seq > 0xf || pdu_tp_udh_seq > pdu_tp_udh_num) {

		LOGE("PDU TP-UDH Seq failed (0x%x)\n", pdu_tp_udh_seq);

		goto pdu_end;

	}

	LOGD("We are sending message %d on %d\n", pdu_tp_udh_seq, pdu_tp_udh_num);

	if (pdu_tp_udh_num > 1) {

		LOGD("We are sending a multi-part message!");

		send_msg_type = 1; //multi-part

	}


	pdu_end:

	DEBUG_I("%s : pdu : %s", __func__, pdu);

	numberLen = (uint8_t)pdu_tp_da_len;	

	mess = (tapiNettextInfo *)malloc(sizeof(tapiNettextInfo));
	memset(mess, 0, sizeof(tapiNettextInfo));

	mess->NPI_ToNumber= 0x01; // 01

	if (pdu_hex[pdu_tp_da_index + 1] == 0x91)
		mess->TON_ToNumber= 0x01; // 01 - international
	else
		mess->TON_ToNumber= 0x00; // 00 - national

	mess->lengthToNumber = numberLen;

	if (numberLen % 2 > 0)
		numberLen = numberLen + 1;
		
	i = 0;
	
	while (i < numberLen)
	{
		mess->szToNumber[i] = pdu[i + 9];
		if ( pdu[i + 8] != 'f')
		mess->szToNumber[i+1] =pdu[i + 8]; 	
		i = i + 2;		
	}


	mess->scTime = time(NULL);

	mess->NPI_SMSC = 0x01;

	if (smsc[2] == 0x39 && smsc [3] == 0x31)
		mess->TON_SMSC = 0x01; // 01 - international
	else
		mess->TON_SMSC= 0x00; // 00 - national

	if (smsc[smsc_length - 2] == 'f' || smsc[smsc_length - 2] == 'F')
		mess->lengthSMSC = smsc_length - 5;
	else
		mess->lengthSMSC = smsc_length - 4;

	i = 4;

	while (i < smsc_length)
	{
		mess->SMSC[i - 4] = smsc[i + 1];
		if ( smsc[i] != 'f')
		mess->SMSC[i - 3] =smsc[i]; 	
		i = i + 2;		
	}

	if (pdu_hex[0] == 0x21 || pdu_hex[0] == 0x61)
		mess->bSRR = 0x01;

	mess->validityValue = 0xFF; //FF

	mess->classType = 0x04; //04	

	if (send_msg_type == 1)
	{
		mess->nUDH = 0x01; //multipart SMS
		mess->bUDHI = 0x01;
		mess->messageLength = pdu_hex[(numberLen / 2) + 6] - 1;
	}
	else
		mess->messageLength = pdu_hex[(numberLen / 2) + 6];
	
	if (pdu_hex[(numberLen / 2) + 5] == 8)
	{
		DEBUG_I("%s : DCS - Unicode", __func__);
		mess->alphabetType = 0x03; //Unicode
		if (send_msg_type == 0)
		{
			int k = (numberLen / 2) + 7;
			for (i = 0; i < pdu_hex[(numberLen / 2) + 6]; i++)
				mess->messageBody[i] = pdu_hex[i + k];
		}
		else 
		{
			int k = (numberLen / 2) + 8;
			for (i = 0; i < pdu_hex[(numberLen / 2) + 6] - 1; i++)
				mess->messageBody[i] = pdu_hex[i + k];
		}	
	} else {
		DEBUG_I("%s : DCS - GSM7", __func__);
		mess->alphabetType = 0x00; //GSM7
		int k = (numberLen / 2) + 7;

		message_tmp = malloc(((pdu_hex[(numberLen / 2) + 6]) * 2) + 1);
		memset(message_tmp, 0, ((pdu_hex[(numberLen / 2) + 6]) * 2) + 1);
			for (i = 0; i < pdu_hex[(numberLen / 2) + 6]; i++)
				message_tmp[i] = pdu_hex[i + k];

		gsm72ascii(message_tmp, &message, pdu_hex[(numberLen / 2) + 6]);
		
		if (send_msg_type == 0)
		{

			for (i = 0; i < pdu_hex[(numberLen / 2) + 6]; i++)
				mess->messageBody[i] = message[i];
		}
		else
		{
			mess->messageLength = mess->messageLength - 1;
			for (i = 0; i < pdu_hex[(numberLen / 2) + 6] - 2; i++)
				mess->messageBody[i] = message[i + 2];
			for (i = 0; i < 5; i++)
				mess->messageBody[i] = pdu_hex[(numberLen / 2) + 8 + i];

		}

		free(message_tmp);

	}

	tapi_nettext_set_net_burst(0);
	tapi_nettext_send((uint8_t *)mess);
	
	ril_data.tokens.outgoing_sms = t;

	if (pdu != NULL)
		free(pdu);

	if (smsc != NULL)
		free(smsc);

	if (mess != NULL)	
		free(mess);

	if (pdu_hex != NULL)
		free(pdu_hex);
}