Ejemplo n.º 1
0
static int
strcollsp(CHARSET_INFO *cs, const STRNNCOLL_PARAM *param)
{
  int failed= 0;
  const STRNNCOLL_PARAM *p;
  diag("%-20s %-10s %-10s %10s %10s", "Collation", "a", "b", "ExpectSign", "Actual");
  for (p= param; p->a; p++)
  {
    char ahex[64], bhex[64];
    int res= cs->coll->strnncollsp(cs, (uchar *) p->a, p->alen,
                                       (uchar *) p->b, p->blen, 0);
    str2hex(ahex, sizeof(ahex), p->a, p->alen);
    str2hex(bhex, sizeof(bhex), p->b, p->blen);
    diag("%-20s %-10s %-10s %10d %10d%s",
         cs->name, ahex, bhex, p->res, res,
         eqres(res, p->res) ? "" : " FAILED");
    if (!eqres(res, p->res))
    {
      failed++;
    }
    else
    {
      /* Test in reverse order */
      res= cs->coll->strnncollsp(cs, (uchar *) p->b, p->blen,
                                     (uchar *) p->a, p->alen, 0);
      if (!eqres(res, -p->res))
      {
        diag("Comparison in reverse order failed. Expected %d, got %d",
             -p->res, res);
        failed++;
      }
    }
  }
  return failed;
}
Ejemplo n.º 2
0
/*******************************************************************************
* Function Name  : CanHexProg request, server
* Description    : dekodira in razbije vrstice hex fila na 	pakete 8 bytov in jih
*								 : pošlje na CAN bootloader
* Input          : pointer na string, zaporedne vrstice hex fila, <cr> <lf> ali <null> niso nujni
* Output         : 
* Return         : 0 ce je checksum error sicer eof(-1). bootloader asinhrono odgovarja z ACK message
*				 				 : za vsakih 8 bytov !!!
*******************************************************************************/
int					CanHexProg(char *p) {

static int	ExtAddr=0;
int	 				n,a,i=FLASH_COMPLETE;
CanTxMsg		TxMessage;
int					*d=(int *)TxMessage.Data;

						if(!p)
							p=_Iap_string;
						if(HexChecksumError(p))
							return(0);

						TxMessage.RTR=CAN_RTR_DATA;
						TxMessage.IDE=CAN_ID_STD;

						n=str2hex(&p,2);
						a=(ExtAddr<<16)+str2hex(&p,4);
						switch(str2hex(&p,2)) {
							case 00:
								TxMessage.StdId=_ID_IAP_ADDRESS;
								d[0]=a;
								TxMessage.DLC=sizeof(int);

								if(p==_Iap_string)
									PollCAN((CanRxMsg *)&TxMessage);
								else
									while(CAN_Transmit(CAN1,&TxMessage)==CAN_NO_MB);

								TxMessage.StdId=_ID_IAP_DWORD;
								for(i=0; n--;) {
									TxMessage.Data[i++]=str2hex(&p,2);
									if(i==8 || !n) {
										TxMessage.DLC=i;
										i=0;

									if(p==_Iap_string)
										PollCAN((CanRxMsg *)&TxMessage);
									else
										while(CAN_Transmit(CAN1,&TxMessage)==CAN_NO_MB);
									}	
								}
								break;
							case 01:
								break;
							case 02:
								break;
							case 04:
							case 05:
								ExtAddr=str2hex(&p,4);
								break;
						}
						return(EOF);
}
Ejemplo n.º 3
0
/*
 * Choose root and swap devices.
 */
void 
cpu_rootconf(void)
{
	struct prom_n2f *nf;
	const char *devname;
	findfunc_t find;
	char promname[4];
	char partname[4];
	const char *prompath;
	int prom_ctlr, prom_unit, prom_part;

	/* Get the PROM boot path and take it apart. */
	prompath = prom_getbootpath();
	if (prompath == NULL)
		prompath = "zz(0,0,0)";
	promname[0] = *(prompath++);
	promname[1] = *(prompath++);
	promname[2] = '\0';
	prom_ctlr = prom_unit = prom_part = 0;
	if (*prompath == '(' &&
	    *(prompath = str2hex(++prompath, &prom_ctlr)) == ',' &&
	    *(prompath = str2hex(++prompath, &prom_unit)) == ',') 
		(void)str2hex(++prompath, &prom_part);

	/* Default to "unknown" */
	booted_device = NULL;
	booted_partition = 0;
	devname = "<unknown>";
	partname[0] = '\0';
	find = NULL;

	/* Do we know anything about the PROM boot device? */
	for (nf = prom_dev_table; nf->func; nf++)
		if (!strcmp(nf->name, promname)) {
			find = nf->func;
			break;
		}
	if (find)
		booted_device = (*find)(promname, prom_ctlr, prom_unit);
	if (booted_device) {
		devname = device_xname(booted_device);
		if (device_class(booted_device) == DV_DISK) {
			booted_partition = prom_part & 7;
			partname[0] = 'a' + booted_partition;
			partname[1] = '\0';
		}
	}

	printf("boot device: %s%s\n", devname, partname);
	rootconf();
}
Ejemplo n.º 4
0
static int verify_sas(struct re_printf *pf, void *arg)
{
	const struct cmd_arg *carg = arg;
	(void)pf;

	if (str_isset(carg->prm)) {
		char rzid[ZRTP_STRING16] = "";
		zrtp_status_t s;
		zrtp_string16_t remote_zid = ZSTR_INIT_EMPTY(remote_zid);

		if (str_len(carg->prm) != 24) {
			warning("zrtp: invalid remote ZID (%s)\n", carg->prm);
			return EINVAL;
		}

		(void) str2hex(carg->prm, (int) str_len(carg->prm),
			       rzid, sizeof(rzid));
		zrtp_zstrncpyc(ZSTR_GV(remote_zid), (const char*)rzid,
			       sizeof(zrtp_zid_t));

		s = zrtp_cache_set_verified(zrtp_global->cache,
					    ZSTR_GV(remote_zid),
					    true);
		if (s == zrtp_status_ok)
			info("zrtp: SAS for peer %s verified\n", carg->prm);
		else {
			warning("zrtp: zrtp_cache_set_verified"
				" failed (status = %d)\n", s);
			return EINVAL;
		}
	}

	return 0;
}
Ejemplo n.º 5
0
zrtp_status_t zrtp_signaling_hash_set( zrtp_stream_t* ctx,
									   const char *hash_buff,
									   uint32_t hash_buff_length)
{
	if (!ctx || !hash_buff) {
		return zrtp_status_bad_param;
	}

	if (ZRTP_SIGN_ZRTP_HASH_LENGTH > hash_buff_length) {
		return zrtp_status_buffer_size;
	}

	if (ctx->state != ZRTP_STATE_ACTIVE) {
		return zrtp_status_wrong_state;
	}
	
	str2hex(hash_buff,
			ZRTP_SIGN_ZRTP_HASH_LENGTH,
			ctx->messages.signaling_hash.buffer,
			ctx->messages.signaling_hash.max_length);
	ctx->messages.signaling_hash.length = ZRTP_MESSAGE_HASH_SIZE;
	
	ZRTP_LOG(3, (_ZTU_,"SIGNALLING HAS was ADDED for the comparison. ID=%u\n", ctx->id));
	ZRTP_LOG(3, (_ZTU_,"Hash=%.*s.\n", ZRTP_SIGN_ZRTP_HASH_LENGTH, hash_buff));

	return zrtp_status_ok;
}
Ejemplo n.º 6
0
int parse_web_data(const char* s_data,logo_recv_webclient_t *d_data)
{
	char upload_s_tmp[256]={0};
	char d_tmp[256]={0};
	uint32_t j =0;
	int s_len = strlen(s_data);
	str2hex(s_data,s_len,upload_s_tmp);
	upload_s_tmp[s_len/2] = '\0';
	des_decrypt_n(KEY,upload_s_tmp,d_tmp,s_len/16);		
	UNPKG_H_UINT32(d_tmp,d_data->userid,j);
	UNPKG_H_UINT32(d_tmp,d_data->channel,j);
	UNPKG_H_UINT32(d_tmp,d_data->ip,j);
	UNPKG_H_UINT32(d_tmp,d_data->time,j);
	UNPKG_H_UINT32(d_tmp,d_data->width_limit,j);
	UNPKG_H_UINT32(d_tmp,d_data->height_limit,j);
	UNPKG_H_UINT32(d_tmp,d_data->cnt,j);
	CGI_DEBUG_LOG("UPLOAD_LOGO RECV WEB[%u %u %u %u %u %u %u]",d_data->userid,d_data->channel,d_data->ip,d_data->time,d_data->width_limit,d_data->height_limit,d_data->cnt);
	for(uint32_t i=0;i < d_data->cnt && i < CNT_MAX;i++){
		UNPKG_H_UINT32(d_tmp,d_data->thumb_arg[i].W,j);
		UNPKG_H_UINT32(d_tmp,d_data->thumb_arg[i].H,j);
		UNPKG_H_UINT32(d_tmp,d_data->thumb_arg[i].start_x,j);
		UNPKG_H_UINT32(d_tmp,d_data->thumb_arg[i].start_y,j);
		UNPKG_H_UINT32(d_tmp,d_data->thumb_arg[i].thumb_x,j);
		UNPKG_H_UINT32(d_tmp,d_data->thumb_arg[i].thumb_y,j);
		CGI_DEBUG_LOG("UPLOAD_LOGO RECV WEB[%u %u %u %u %u %u]",d_data->thumb_arg[i].W,
																d_data->thumb_arg[i].H,
																d_data->thumb_arg[i].start_x,
																d_data->thumb_arg[i].start_y,
																d_data->thumb_arg[i].thumb_x,
																d_data->thumb_arg[i].thumb_y);
	}
	return SUCC;
}
Ejemplo n.º 7
0
int Cregact::verify_active_code (uint32_t user_id, char *active_code)
{
	STRU_ACTIVE_KEY ak;
	char buf1[sizeof (STRU_ACTIVE_KEY)];

	str2hex (active_code, 2*sizeof (buf1), buf1);
	//_DES_n (ACT_KEY, buf1, (char *)&ak, sizeof (buf1)/8);
	des_decrypt_n(ACT_KEY, buf1, (char *)&ak, sizeof (buf1)/8);

	//verify here
	if (ak.user_id != user_id) {
#ifdef INNER_DEBUG
		LOG (7, "user id error [%u] [%u]", ak.user_id, user_id);
#endif
		return (-1);
	}
	if (time (NULL) - ak.now > TIME_SEP_WEEK) {
#ifdef INNER_DEBUG
		LOG (7, "time is over [%u] [%u]", ak.now, time(NULL));
#endif
		return (-1);
	}
	if ((ak.pri_key1 != FILLKEY1) || (ak.pri_key2 != FILLKEY2) || (ak.pri_key3 != FILLKEY3)) {
#ifdef INNER_DEBUG
		LOG (7, "fill key is error");
#endif
		return (-1);
	}

	return (0);
}
Ejemplo n.º 8
0
zrtp_status_t zrtp_signaling_hash_set( zrtp_stream_t* ctx,
									   const char *hash_buff,
									   uint32_t hash_buff_length)
{
	if (!ctx) {
		return zrtp_status_bad_param;
	}

	if (ZRTP_MESSAGE_HASH_SIZE*2 < hash_buff_length) {
		return zrtp_status_buffer_size;
	}

	if (ctx->state != ZRTP_STATE_ACTIVE) {
		return zrtp_status_wrong_state;
	}
	
	str2hex( hash_buff,
		     hash_buff_length,
			 ctx->messages.signaling_hash.buffer,
			 ctx->messages.signaling_hash.max_length);
	ctx->messages.signaling_hash.length = ZRTP_MESSAGE_HASH_SIZE;
	
	{
	char buff[64];
	ZRTP_LOG(3, (_ZTU_,"SIGNALLING HAS was ADDED for the comparision. ID=%u\n", ctx->id));
	ZRTP_LOG(3, (_ZTU_,"Hash=%s.\n", hex2str(hash_buff, hash_buff_length, buff, sizeof(buff))));
	}

	return zrtp_status_ok;
}
Ejemplo n.º 9
0
Archivo: main.c Proyecto: perrylau/web
/* DUAL mode, uap start at system initilize state. */
static void dual_uap_start(void)
{
	sys_config_t *pconfig = get_running_config();
	base_config_t *pbase = &pconfig->base;
	extra_config_t *pextra = &pconfig->extra;
	sys_unconfig_t *punconfig = get_un_config();
	struct wlan_network wlan_config;

	if (pbase->wifi_mode != DUAL_MODE)
		return;
	
	memset(&wlan_config, 0, sizeof(wlan_config));
	/* Set profile name */
	strcpy(wlan_config.name, "UAP");
	strcpy(wlan_config.ssid, pextra->uap_ssid);
	wlan_config.channel = 0;
	wlan_config.mode = WLAN_MODE_UAP;

	switch(pextra->uap_secmode) {
	case SEC_MODE_WEP:
	case SEC_MODE_WEP_HEX:
		wlan_config.security.type = WLAN_SECURITY_WEP_OPEN;
		break;
	case SEC_MODE_WPA_NONE:
		wlan_config.security.type = WLAN_SECURITY_NONE;
		break;
	case SEC_MODE_WPA_PSK:
		wlan_config.security.type = WLAN_SECURITY_WPA2;
		break;
	default:
		wlan_config.security.type = WLAN_SECURITY_WPA2;
		break;
	}

	if (SEC_MODE_WEP_HEX == pextra->uap_secmode) {
		wlan_config.security.psk_len = str2hex(pextra->uap_key, 
				wlan_config.security.psk, 32);
	} else {
		strcpy(wlan_config.security.psk, pextra->uap_key);
		wlan_config.security.psk_len = strlen(pextra->uap_key);
	}

	if (punconfig->pmk_invalid[0] == 0) {
		wlan_config.security.pmk_valid = 1;
		memcpy(wlan_config.security.pmk, punconfig->pmk[0], WLAN_PMK_LENGTH);
	}
	wlan_config.address.addr_type = ADDR_TYPE_STATIC;
	wlan_config.address.ip = 0x0a0a0a01;
	wlan_config.address.gw = 0x0a0a0a02;
	wlan_config.address.netmask = 0xffffff00;
	wlan_config.address.dns1 = 0x0a0a0a01;

	wlan_add_network(&wlan_config);
	wlan_start_network(wlan_config.name);
}
Ejemplo n.º 10
0
/*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*/
void get_usr_pwds(char *subkey,char *usr)
{
	long res;
	HKEY hPwdKey;
	char username[MAXSIZE]="";
	char passwdhash[MAXSIZE*2]="", passwd[MAXSIZE]="",clearpasswd[MAXSIZE]="";
	char fullname[MAXSIZE]="";
	char email[MAXSIZE]="";
	DWORD lType;
	DWORD passwdhashsz=sizeof(passwdhash)-1,fullnamesz=MAXSIZE-1,emailsz=MAXSIZE-1;

		res = RegOpenKeyEx(HKEY_LOCAL_MACHINE,subkey,0,KEY_ALL_ACCESS,&hPwdKey);
		if(res!=ERROR_SUCCESS)
		{
			printf(" Error opening key %s! Error #:%d\n",subkey,res);
			exit(1);	
			//return;
		}
	
		if(RegQueryValueEx(hPwdKey,"Password",0,&lType,(LPBYTE)passwdhash,&passwdhashsz)!= ERROR_SUCCESS)
		{
			RegCloseKey(hPwdKey);
			return;
		}
		if(RegQueryValueEx(hPwdKey,"FullName",0,&lType,(LPBYTE)fullname,&fullnamesz)!= ERROR_SUCCESS)
		{
			RegCloseKey(hPwdKey);
			return;
		}
		if(RegQueryValueEx(hPwdKey,"MailAddr",0,&lType,(LPBYTE)email,&emailsz)!=ERROR_SUCCESS)
		{
			RegCloseKey(hPwdKey);
			return;
		}
		

		str2smallcase(usr);
		strncpy(username,usr,sizeof(username)-1);
		str2hex(passwdhash,passwd);
		// adik 1234567
		// adik 12
		if(strlen(passwd)>strlen(username))
			populate(username,strlen(passwd));
		imail_decrypt(username,passwd,clearpasswd);

		printf( "------------------------------------------------------------------------\n"
				" FullName:\t %s\n"
				" Email:\t\t %s\n"
				" Username:\t %s\n"
				" Password:\t %s\n",
				fullname,email,usr,clearpasswd);
	total_accs++;
	RegCloseKey(hPwdKey);
}
Ejemplo n.º 11
0
static unsigned long
str_to_native_ulong(const char *str)
{
    unsigned long x = 0, i = 0;

    while ( *str && (i < BYTES_PER_LONG) )
    {
#ifdef __BIG_ENDIAN
        x <<= 8;
        x += str2hex(str);
#elif defined(__LITTLE_ENDIAN)
        x += (unsigned long)str2hex(str) << (i*8);
#else
# error unknown endian
#endif
        str += 2;
        i++;
    }

    return x;
}
Ejemplo n.º 12
0
/*******************************************************************************
* Function Name  : CanHexProg request, server
* Description    : dekodira in razbije vrstice hex fila na 	pakete 8 bytov in jih
*								 : pošlje na CAN bootloader
* Input          : pointer na string, zaporedne vrstice hex fila, <cr> <lf> ali <null> niso nujni
* Output         : 
* Return         : 0 ce je checksum error sicer eof(-1). bootloader asinhrono odgovarja z ACK message
*				 				 : za vsakih 8 bytov !!!
*******************************************************************************/							
int					HexrecOk(char *filename, FIL *f) {
int	 				xa=0,a,amax=0,amin=INT_MAX;
char				*p,s[64];
						if(f_open(f,filename,FA_READ)==FR_OK) {
							while(!f_eof(f)) {
								p=s;
								f_gets(p,64,f);
								if(*p != ':') {
									f_close(f);
									return 0;
								}
								if(HexChecksumError(++p)) {
									f_close(f);
									return 0;
								}
								a=(xa<<16)+str2hex(&p,4)+str2hex(&p,2);														// set address
								switch(str2hex(&p,2)) {
									case 00: 																												// data record
										if(a<amin)
											amin=a;
										if(a>amax)
											amax=a;
										break;
									case 04:
										xa=str2hex(&p,4);	
										break;
									default:
										break;
								}
							}
							if(amin == (int)__Vectors) {
								f_close(f);
								return 0;
							}
							f_lseek(f,0);
							return amin;
						}
						return NULL;
}
Ejemplo n.º 13
0
/*******************************************************************************
* Function Name  : CanHexProg request, server
* Description    : dekodira in razbije vrstice hex fila na 	pakete 8 bytov in jih
*								 : pošlje na CAN bootloader
* Input          : pointer na string, zaporedne vrstice hex fila, <cr> <lf> ali <null> niso nujni
* Output         : 
* Return         : 0 ce je checksum error sicer eof(-1). bootloader asinhrono odgovarja z ACK message
*				 				 : za vsakih 8 bytov !!!
*******************************************************************************/
int					HexrecProg(char *p) {

int	 				xa=0,amax=0,amin=INT_MAX;
int	 				i,a,n;
union				{
							int i;
							char	c[4];
						} d;

						++p;
						n=str2hex(&p,2);																												// number of bytes
						a=(xa<<16)+str2hex(&p,4);																								// set address
						switch(str2hex(&p,2)) {
							case 00:																															// data record
								for(i=0; n--;) {
									if(!i)
										d.i=*(int *)a;																									// get the programmed int value
									d.c[i++]=str2hex(&p,2);
									if(i==4 || !n) {
										if(FlashProgram32(a,d.i))
											return 0;
										i=0;
										a+=sizeof(int);
									}
								}
								if(a<amin)
									amin=a;
								if(a>amax)
									amax=a;
								break;
							case 04:
								xa=str2hex(&p,4);	
								break;
						}
						return(amin);
}
Ejemplo n.º 14
0
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
	    printf("Usage: secp256r1mult K\n");
	    exit(-1);
    }
    str2hex((void*)sk, argv[1], strlen(argv[1]));
    ecc_ec_mult(ecc_g_point_x, ecc_g_point_y, sk, pkx, pky);
    //Print256(sk);
    fieldModO(pkx, pkx, 8);
    //Print256((unsigned char *)pkx);
    Print256_nbo((unsigned char *)pkx);
    printf("\n");
    return 0;
}
Ejemplo n.º 15
0
/*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*/
void decrypt_usr_pass(char *usr,char *passwd)
{
	char username[MAX_NUM]="";
	char passwordhash[MAX_NUM]="";
	char outputbuff[250]="";

	str2smallcase(usr);
	strncpy(username,usr,sizeof(username)-1);
	str2hex(passwd,passwordhash);
	printf("------------------------------------------------------------------------\n");
	printf( " Username:\t\t %s\n"
			" Passwordhash:\t\t %s\n",usr,passwd);
	if(strlen(passwordhash)>strlen(username))
		populate(username,strlen(passwordhash));

	imail_decrypt(username,passwordhash,outputbuff);
	printf(" Decrypted passwd:\t %s\n",outputbuff);
	printf("------------------------------------------------------------------------\n");
}
Ejemplo n.º 16
0
/* Write hash list to session file */
hash_stat session_write_hashlist(FILE *sessionfile)
{
#ifdef HAVE_JSON_JSON_H

    json_object *jobj;
    json_object *jchild;
    struct hash_list_s *mylist;
    char buff[1024];

    if (get_cracked_num()==get_hashes_num()) return(hash_ok);
    if (get_hashes_num()>100000) 
    {
	hash_list_node = json_object_new_array();
	json_object_object_add(root_node,"hashlist", hash_list_node);
	return(hash_ok);
    }

    hash_list_node = json_object_new_array();
    pthread_mutex_lock(&listmutex);
    mylist = hash_list;
    while ((mylist)&&(mylist->username))
    {
	jchild = json_object_new_object();
	jobj = json_object_new_string(mylist->username);
	json_object_object_add(jchild,"username", jobj);
	str2hex(mylist->hash, buff, hash_ret_len);
	jobj = json_object_new_string(buff);
	json_object_object_add(jchild,"hash", jobj);
	jobj = json_object_new_string(mylist->salt);
	json_object_object_add(jchild,"salt", jobj);
	jobj = json_object_new_string(mylist->salt);
	json_object_object_add(jchild,"salt", jobj);
	jobj = json_object_new_string(mylist->salt2);
	json_object_object_add(jchild,"salt2", jobj);
	json_object_array_add(hash_list_node,jchild);
	mylist = mylist->next;
    }
    pthread_mutex_unlock(&listmutex);
    json_object_object_add(root_node,"hashlist", hash_list_node);
#endif
    return hash_ok;
}
Ejemplo n.º 17
0
OSStatus system_easylink_wac_start( mico_Context_t * const inContext )
{
    OSStatus err = kNoErr;
    IPStatusTypedef para;
    uint8_t major_ver, minor_ver, revision;
    
    mfi_wac_lib_version( &major_ver, &minor_ver, &revision );
    system_log( "Import MFi WAC library v%d.%d.%d", major_ver, minor_ver, revision );

    WACPlatformParameters_t* WAC_Params = NULL;
    WAC_Params = calloc(1, sizeof(WACPlatformParameters_t));
    require(WAC_Params, exit);

    micoWlanGetIPStatus(&para, Station);

    str2hex((unsigned char *)para.mac, WAC_Params->macAddress, 6);
    WAC_Params->isUnconfigured          = 1;
    WAC_Params->supportsAirPlay         = 0;
    WAC_Params->supportsAirPrint        = 0;
    WAC_Params->supports2_4GHzWiFi      = 1;
    WAC_Params->supports5GHzWiFi        = 0;
    WAC_Params->supportsWakeOnWireless  = 0;

    WAC_Params->firmwareRevision =  FIRMWARE_REVISION;
    WAC_Params->hardwareRevision =  HARDWARE_REVISION;
    WAC_Params->serialNumber =      SERIAL_NUMBER;
    WAC_Params->name =              inContext->flashContentInRam.micoSystemConfig.name;
    WAC_Params->model =             MODEL;
    WAC_Params->manufacturer =      MANUFACTURER;

    WAC_Params->numEAProtocols =    1;
    WAC_Params->eaBundleSeedID =    BUNDLE_SEED_ID;
    WAC_Params->eaProtocols =       (char **)eaProtocols;

    err = mfi_wac_start( inContext, WAC_Params, MICO_I2C_CP, 1200 );
    require_noerr(err, exit);
    
exit:
    free(WAC_Params);
    return err; 
}
Ejemplo n.º 18
0
Archivo: t.c Proyecto: dulton/solotools
int main(int argc, char *argv[])
{

    char *buf = NULL;
    size_t len_buf = 0;

    if (argc < 2)
    {
        printf("Usage: %s filename\n", argv[0]);
        return -1;
    }

    if ( ! t_read_full_file(argv[1], &buf, &len_buf, 0))
    {
        printf("read file \"%s\" failed!\n", argv[1]);
        return -1;
    }
    len_buf -= 1;
    //t_disbuf(buf, len_buf);

    if (str2hex(&buf, (u32*)&len_buf) < 0)
    {
        printf("string to hex failed!\n");
        return -1;
    }
    
    if ( ! process_keda_protocol(&buf, (u32*)&len_buf))
    {
        puts("process keda failed!");
        return -1;
    }
    free(buf);
    buf = NULL;

    return 0;
}
Ejemplo n.º 19
0
int dns_get_answer(char* argval)
{
   char *field, *saveptr1=NULL;
   char field1[512], field2[512], field3[512];
   int i, len, num_params;
   u_int16_t TYPE=1; // A
   u_int8_t *ptrTYPE;
   u_int32_t TTL=0;
   u_int8_t *ptrTTL;
   u_int16_t RDLEN;
   u_int8_t *ptrRDLEN;
   u_int8_t rdata[512];
   
   field1[0]='\0';
   field2[0]='\0';
   field3[0]='\0';

   len = strlen (argval);

   // determine number of occurences of ':'
   num_params=1;
   for (i=0; i<len; i++)
     {
	if (argval[i]==':') num_params++;
     }
   if (num_params>3) return 0; // Error!
   
   // now get the fields (type, ttl, rdata)
   field = strtok_r(argval, ":", &saveptr1);
   strncpy(field1, field, 512);
   if (num_params>1)  // 2 or 3
     {
	field = strtok_r(NULL, ":", &saveptr1);
	strncpy(field2, field, 512);
	if (num_params==3)
	  {
	     field = strtok_r(NULL, ":", &saveptr1);
	     strncpy(field3, field, 512);
	  }
     }
   
   
   // Now we have all parameters in field1, field2, and field3.
   // But field2 and/or field3 might be empty.
   
   switch (num_params)
     {
      case 1: // only RDATA specified
	strncpy(field3, field1, 512); 
	strcpy(field1, "A");
	strcpy(field2, "0");
	break;
      case 2: // TYPE and RDATA
	strncpy(field3, field2, 512);
	strcpy(field2, "0");
	break;
     }

   //CHECK:
   //printf("fields: [%s] [%s] [%s]\n",field1,field2,field3);
   
   //////////////////////////////////////////////////////////////////////
   // Now create the whole answer section: Type, Class, TTL, RDLEN, RDATA
     
   //// TYPE
   if ( (strcmp(field1,"CNAME")==0) ||
	(strcmp(field1,"cname")==0) )
     {
	TYPE=5;
	gbuf[0]=0x00;
	gbuf[1]=0x05;
     }
   else if ( (strcmp(field1,"A")==0) ||
	     (strcmp(field1,"a")==0) )
     {
	TYPE=1;
	gbuf[0]=0x00;
	gbuf[1]=0x01;
     }
   else // type must be given as number
     {
	TYPE = (u_int16_t) str2int(field1);
	ptrTYPE = (u_int8_t*) &TYPE;
	gbuf[0]=*(ptrTYPE+1);
	gbuf[1]=*(ptrTYPE);
     }
   
   
   //// CLASS = IN = 0x00 01
   gbuf[2]= 0x00; gbuf[3]=0x01;
   
   //// TTL
   TTL = (u_int32_t) str2int(field2);
   ptrTTL = (u_int8_t*) &TTL; 
   gbuf[4]= *(ptrTTL+3);
   gbuf[5]= *(ptrTTL+2); 
   gbuf[6]= *(ptrTTL+1); 
   gbuf[7]= *(ptrTTL+0); 

   
   //// RDLEN and RDATA
   if (TYPE==1)      // A
     {
	RDLEN = num2hex(field3, rdata); // should be 4 if IP address
	if (RDLEN!=4)
	  {
	     fprintf(stderr," mz/dns_get_answer: [WARNING] RDATA of A record should contain an IPv4 address (4 bytes).\n");
	  }  
     }
   else if (TYPE==5) // CNAME 
     {
	RDLEN = dns_process_label (field3, rdata);
	if (RDLEN==0)
	  {
	     fprintf(stderr," mz/dns_get_answer: [WARNING] RDATA must contain a domain name.\n");
	  }
     }
   else              // Any other type 
     {
	RDLEN = str2hex(field3, rdata, 512); // should be 4 if IP address
     }
   
   ptrRDLEN = (u_int8_t*) &RDLEN;
   gbuf[8] = *(ptrRDLEN+1);
   gbuf[9] = *(ptrRDLEN+0);

   
   // finally write rdata
   for (i=0; i<RDLEN; i++) 
     {
	gbuf[10+i] = rdata[i];
     }
   gbuf_s = 10+RDLEN;

   //////// TEST
   /*
   for (i=0; i<gbuf_s; i++) 
     {
	printf("%02x \n",gbuf[i]);
     }
   printf("i=%u\n",i);
   */

   return 1;
   
}
Ejemplo n.º 20
0
/**
	@func wmmp_readAppData 
	@brief 读取wmmp接收数据
	@param[in] flowID wmmp流通道
	@param[out] buf 输出BUFF指针
	@param[in-out] len 输入BUFF的最大长度,输出接收数据的实际长度
	@return   0-成功;	其他值-失败 
 */
int wmmp_readAppData(int flowID, char *buf, int *len)
{
	int rc;
	int i;
	int tmpflowID;
	int tmplen;
	int readlen;
	int timeout;
	time_t now,last;
	int retry;

	//char testbuf[4096];
	//char *p;
	char ch;

#ifdef WMMP_READ_DEBUG
	int fp;
#endif



#ifdef WMMP_READ_DEBUG
	fp = fopen("/temp.txt","ab+");
	if(fp == -1)
	{
		DEBUG_PRINTF("open file error\n");
		exit -1;
	}
	fwrite("start", 5, 1, fp);
#endif

	//int fd_ttys2;
	//fd_ttys2 = port_open("/dev/ttyS2");

	//char recbuf[APP_RECV_PACKET_MAXLEN*2+1]="";

	DEBUG_PRINTF("wmmp read data\n");

        retry = 2;
	while(retry --)
	{
		//modem_flushInputBuffer();
		rc = wmmp_waitResponse(NULL,60);
		if(rc != 0)
		{
			DEBUG_PRINTF("WMMP get response error: %x\n",rc);
			goto ExitProcessing;
		}
//	printf("rev4 = %s\n", wmmp_rx_buf.line[0]);
//	printf("*retry = %d\n", retry);

		if(wmmp_rx_buf.enumResponseType != RESPONSE_WMMP_MSG)
		{
			DEBUG_PRINTF("unexpected response: %d\n",wmmp_rx_buf.enumResponseType);
				//rc = MODEM_ERROR_NUM(MODEM_ERROR_WMMP,ERROR_WMMP_BAD_RESPONSE);
				//goto ExitProcessing;
				continue;
		}
	

		if(sscanf(wmmp_rx_buf.line[0],"$M2MMSG: 7,%d,%d",&tmpflowID,&readlen) != 2)
		{
			DEBUG_PRINTF("expected msg not found\n");
			//rc = MODEM_ERROR_NUM(MODEM_ERROR_WMMP,ERROR_WMMP_BAD_RESPONSE);
			//goto ExitProcessing;
			continue;
		}

		/*printf("flowID = %d \nlen = %d\n",tmpflowID, readlen);*/
		if(tmpflowID != flowID)
		{
			DEBUG_PRINTF("unexpected flowID\n");
			rc = MODEM_ERROR_NUM(MODEM_ERROR_WMMP,ERROR_WMMP_BAD_RESPONSE);
			goto ExitProcessing;
		}

		if((readlen > APP_RECV_PACKET_MAXLEN) || (readlen > *len))
		{
			DEBUG_PRINTF("readlen overflow!!!readlen=%d\n",readlen);
			rc = MODEM_ERROR_NUM(MODEM_ERROR_WMMP,ERROR_WMMP_APPREAD_OVERFLOW);
			goto ExitProcessing;
		}
		break;
	}

	if( retry < 0 )
	{
		DEBUG_PRINTF("expected msg not found\n");
		rc = MODEM_ERROR_NUM(MODEM_ERROR_WMMP,ERROR_WMMP_BAD_RESPONSE);
		goto ExitProcessing;
	}

#if 0
	//wait data ?
	timeout = 5000;
	do
	{
		tmplen = modem_charsInBuffer();
		//DEBUG_PRINTF("read data len = %d\n",tmplen);
		timeout --;
	}while( (tmplen < (readlen*2)) && (timeout >0));

	if(timeout <= 0)
	{
		DEBUG_PRINTF("read data len = %d\n",tmplen);
		DEBUG_PRINTF("read data timeout\n");
//		rc = MODEM_ERROR_NUM(MODEM_ERROR_DEVICE,MODEM_DEVICE_TIMEOUT);
//		goto ExitProcessing;
	}
	//read data into wmmp_rx_buf.buf
	modem_read(wmmp_rx_buf.buf,readlen*2);
#endif

#if 0
	//DEBUG_PRINTF("init response rx buffer\n");
	sleep(3);
	wmmp_initRxBuffer();
	time(&last);
	do
	{
#if 0
		tmplen = modem_charsInBuffer();
		if(tmplen != 0)
		{
			modem_read(wmmp_rx_buf.buf_tail,tmplen);
			wmmp_rx_buf.buf_tail += tmplen;
			*(wmmp_rx_buf.buf_tail) = '\0';
			wmmp_rx_buf.rxlen += tmplen;
			DEBUG_PRINTF("read data len = %d\n",wmmp_rx_buf.rxlen);
		}
#else
		//if(modem_charsInBuffer()){
		if(modem_read( wmmp_rx_buf.buf_tail, 1) == 1)
		//if(modem_read( &ch, 1) == 1)
		{
			//fwrite(&ch, 1, 1, fp);
			//modem_read( wmmp_rx_buf.buf_tail, 1);
			//DEBUG_PRINTF("%c",*wmmp_rx_buf.buf_tail);
			//write(fd_ttys2,wmmp_rx_buf.buf_tail,1);
			fwrite(wmmp_rx_buf.buf_tail, 1, 1, fp);
			wmmp_rx_buf.buf_tail++;
//			*(wmmp_rx_buf.buf_tail) = '\0';
			wmmp_rx_buf.rxlen++;
		}
#endif
		if(wmmp_rx_buf.rxlen < readlen*2)
		{
			time(&now);
			if(now > last + 60)			//timeout 60s
			{
				DEBUG_PRINTF("read data len = %d\n",wmmp_rx_buf.rxlen);
				DEBUG_PRINTF("read data timeout\n");
				rc = MODEM_ERROR_NUM(MODEM_ERROR_DEVICE,MODEM_DEVICE_TIMEOUT);
				goto ExitProcessing;
			}
		}
		else
			break;
	}while(1);


#endif

	//20100417 for uart overrun error@115200bps
#if 1
	timeout=35000;
	int recLen = 0;

	/*printf("star receive!\n");*/	
	wmmp_initRxBuffer();
	do
	{
		recLen = modem_read( wmmp_rx_buf.buf_tail, readlen*2-wmmp_rx_buf.rxlen);
		if(recLen != 0)
		{
#ifdef WMMP_READ_DEBUG
			fwrite(wmmp_rx_buf.buf_tail, 1, recLen, fp);
#endif
			wmmp_rx_buf.buf_tail += recLen;
			//			*(wmmp_rx_buf.buf_tail) = '\0';
			wmmp_rx_buf.rxlen += recLen;
			DEBUG_PRINTF("wmmp_rx_buf.rxlen = %d\n", wmmp_rx_buf.rxlen);
		}

	}while((wmmp_rx_buf.rxlen < readlen*2) && timeout-- );

// 	printf("readlen*2 = %d\n",readlen*2);
// 	printf("wmmp_rx_buf.rxlen = %d\n",wmmp_rx_buf.rxlen);

	if(timeout <= 0)
	{
		rc = MODEM_ERROR_NUM(MODEM_ERROR_DEVICE,MODEM_DEVICE_TIMEOUT);
		goto ExitProcessing;
	}


#endif

	//Decode hex into str
	tmplen = str2hex(wmmp_rx_buf.buf,readlen*2,buf,*len);
	/*printf("%s",buf);*/
	//normal return
#ifdef WMMP_READ_DEBUG
	fwrite("end", 3, 1, fp);
	fclose(fp);
#endif
	*len = tmplen;
	return 0;
	//error process
ExitProcessing:
#ifdef WMMP_READ_DEBUG
	fwrite("end", 3, 1, fp);
	fclose(fp);
#endif
	*len = 0;
	return rc;
}
Ejemplo n.º 21
0
static void
bootpath_fake(struct bootpath *bp, const char *cp)
{
	const char *pp;
	int v0val[3];

#define BP_APPEND(BP,N,V0,V1,V2) { \
	strcpy((BP)->name, N); \
	(BP)->val[0] = (V0); \
	(BP)->val[1] = (V1); \
	(BP)->val[2] = (V2); \
	(BP)++; \
	nbootpath++; \
}

#if defined(SUN4)
	if (CPU_ISSUN4M) {
		printf("twas brillig..\n");
		return;
	}
#endif

	pp = cp + 2;
	v0val[0] = v0val[1] = v0val[2] = 0;
	if (*pp == '(' 					/* for vi: ) */
 	    && *(pp = str2hex(++pp, &v0val[0])) == ','
	    && *(pp = str2hex(++pp, &v0val[1])) == ',')
		(void)str2hex(++pp, &v0val[2]);

#if defined(SUN4)
	if (CPU_ISSUN4) {
		char tmpname[8];

		/*
		 *  xylogics VME dev: xd, xy, xt
		 *  fake looks like: /vme0/xdc0/xd@1,0
		 */
		if (cp[0] == 'x') {
			if (cp[1] == 'd') {/* xd? */
				BP_APPEND(bp, "vme", -1, 0, 0);
			} else {
				BP_APPEND(bp, "vme", -1, 0, 0);
			}
			sprintf(tmpname,"x%cc", cp[1]); /* e.g. `xdc' */
			BP_APPEND(bp, tmpname, -1, v0val[0], 0);
			sprintf(tmpname,"x%c", cp[1]); /* e.g. `xd' */
			BP_APPEND(bp, tmpname, v0val[1], v0val[2], 0);
			return;
		}

		/*
		 * ethernet: ie, le (rom supports only obio?)
		 * fake looks like: /obio0/le0
		 */
		if ((cp[0] == 'i' || cp[0] == 'l') && cp[1] == 'e')  {
			BP_APPEND(bp, "obio", -1, 0, 0);
			sprintf(tmpname,"%c%c", cp[0], cp[1]);
			BP_APPEND(bp, tmpname, -1, 0, 0);
			return;
		}

		/*
		 * scsi: sd, st, sr
		 * assume: 4/100 = sw: /obio0/sw0/sd@0,0:a
		 * 4/200 & 4/400 = si/sc: /vme0/si0/sd@0,0:a
 		 * 4/300 = esp: /obio0/esp0/sd@0,0:a
		 * (note we expect sc to mimic an si...)
		 */
		if (cp[0] == 's' &&
			(cp[1] == 'd' || cp[1] == 't' || cp[1] == 'r')) {

			int  target, lun;

			switch (cpuinfo.cpu_type) {
			case CPUTYP_4_200:
			case CPUTYP_4_400:
				BP_APPEND(bp, "vme", -1, 0, 0);
				BP_APPEND(bp, "si", -1, v0val[0], 0);
				break;
			case CPUTYP_4_100:
				BP_APPEND(bp, "obio", -1, 0, 0);
				BP_APPEND(bp, "sw", -1, v0val[0], 0);
				break;
			case CPUTYP_4_300:
				BP_APPEND(bp, "obio", -1, 0, 0);
				BP_APPEND(bp, "esp", -1, v0val[0], 0);
				break;
			default:
				panic("bootpath_fake: unknown system type %d",
				      cpuinfo.cpu_type);
			}
			/*
			 * Deal with target/lun encodings.
			 * Note: more special casing in dk_establish().
			 *
			 * We happen to know how `prom_revision' is
			 * constructed from `monID[]' on sun4 proms...
			 */
			if (prom_revision() > '1') {
				target = v0val[1] >> 3; /* new format */
				lun    = v0val[1] & 0x7;
			} else {
Ejemplo n.º 22
0
//	:020000040800F2 
//	:1000000000100020470100085501000857010008B2
//	:10001000590100085B0100085D01000800000000B4
//            .
//            .
//            .
int					HexChecksumError(char *p) {

int	 				err,n=str2hex(&p,2);			
						for(err=n;n-- > -5;err+=str2hex(&p,2));
						return(err & 0xff);
}
Ejemplo n.º 23
0
int Cregdeal::userinfo_reg_account(char* recvbuf, int rcvlen, char** sendbuf, int* sndlen)
{
	int ret;
	uint32_t userid, user_id_exist = 0;
	char  passwd[PASSWD_SIZE/2];
	char  safe_str[SAFE_STR_SIZE];
	PROTO_HEAD_PTR   hdp;
	USERINFO_REG_BODY_REQ_PTR byp;

	uint32_t pkg_len = ntohl(*(uint32_t *)recvbuf);
	if (pkg_len != (PROTO_HEAD_SIZE + USERINFO_REG_REQ_BODY_SIZE) 
		&& pkg_len != (PROTO_HEAD_SIZE + USERINFO_REG_EXT_BODY_SIZE)) {
		DEBUG_LOG("USERINFO PKG LEN ERROR\t[pkglen=%u expected len=%u or %u]",
					pkg_len, (PROTO_HEAD_SIZE + USERINFO_REG_REQ_BODY_SIZE), (PROTO_HEAD_SIZE 
						+ USERINFO_REG_EXT_BODY_SIZE));
		return REG_SIZE_ERR;
	}

	hdp = (PROTO_HEAD_PTR)recvbuf;
	byp = (USERINFO_REG_BODY_REQ_PTR)(recvbuf + PROTO_HEAD_SIZE);
	str2hex(byp->passwd, PASSWD_SIZE, passwd);

	safe_str_copy(byp->email, safe_str, EMAIL_SIZE); //safe copy


	//check the email here
	//not include `@` is error
	TRIM_INVAD_EMAIL(safe_str, EMAIL_SIZE);
	if (!strchr(safe_str, '@')) {
		DEBUG_LOG("INVALID EMAIL ADDRESS\t[%s]", safe_str);
		return INVALID_EMAIL;
	}

	// check if number of registered ids today have or haven't exceeded the max limit
	if (((client_ip & 0xFFFF) != 0XA8C0) 
			&& (client_ip != 0X7D635072)
			&& (client_ip != 0X76635072)
			&& (client_ip != 0X92635072)
			&& (client_ip != 0X9A635072)

			&& (client_ip != 0XCA635072)
			&& (client_ip != 0XCB635072)
			&& (client_ip != 0XCC635072)

			&& (!this->check_count_ip(client_ip))) {
		DEBUG_LOG("enter ip count");
		char rcv[4];
		struct ip_cnt {
			uint32_t commdid;
			uint32_t ip;
		} ip_check;
		ip_check.commdid = htonl(1);
		ip_check.ip = client_ip;
		if (net->net_io(reinterpret_cast<char*>(&ip_check), 8, rcv, 4) != 4) {
			DEBUG_LOG("ERROR OCCURRED WHILE CHECKING IP COUNT");
		} else {
			uint32_t cnt;
			memcpy(&cnt, rcv, 4);
			cnt = ntohl(cnt);
			if (cnt > MAX_REG_CNT) {
				DEBUG_LOG("NUM OF REG IDS EXCEEDED PER IP MAX LIMIT\t[ip=%u cnt=%u]", client_ip, cnt);
				return REG_CNT_ERR;
			}
		}	
	}
Label:
	//得到userid
	//ret = this->regact->create_user_id(userid);
	userid_get_userid_out ret_out;		
	ret=cpo->userid_get_userid(& ret_out );
	if (ret != SUCCESS) {
		DEBUG_LOG("FAIL TO GET A USER ID");
		return CUSER_ID_CREATE_ERR;
	}
	userid=ret_out.userid;

	//send information to db
	userinfo_register_ex_in user_db;
	memset(&user_db, 0x00, sizeof (userinfo_register_ex_in));
	memcpy(user_db.passwd, passwd, sizeof (passwd));
	// Make sure the value of `sex` is 0 or 1
	user_db.sex = !!(byp->sex);
	user_db.birthday = ntohl(byp->birthday);
	memcpy(user_db.email, safe_str, EMAIL_SIZE);
	user_db.reg_addr_type = ntohl(byp->location);
	user_db.ip = client_ip;


	if (pkg_len == (PROTO_HEAD_SIZE + USERINFO_REG_EXT_BODY_SIZE)) {
		//include extended information here
		char *extend_data = byp->data;
		uint16_t t_data;
		memcpy(user_db.mobile, extend_data, TEL_SIZE);
		extend_data += TEL_SIZE;
		memcpy(&t_data, extend_data, sizeof(t_data));
		user_db.addr_province = htons(t_data);
		extend_data += PROV_SIZE;
		memcpy(&t_data, extend_data, sizeof(t_data));
		user_db.addr_city = ntohs(t_data);
		extend_data += CITY_SIZE;
		memcpy(user_db.addr, extend_data, ADR_SIZE);
		extend_data += ADR_SIZE;
		memcpy(user_db.signature, extend_data, SIG_SIZE);
	}

	ret = cpo->userinfo_register(userid, &user_db, &user_id_exist);  
	if (ret != SUCCESS) {
		DEBUG_LOG("DB ERR\t[uid=%u ret=%d]", userid, ret);

		if (ret == 1104) { // User ID already existed
			goto Label;
		}
		//this->regact->cancel_user_id(userid);
		cpo->userid_set_noused(userid );

		return ret;
	}


	if (set_sndbuf_head(sendbuf, sndlen, (PROTO_HEAD_PTR)recvbuf, SESSION_LEN, SUCCESS) != SUCCESS) {
		//this->regact->cancel_user_id(userid);
		return REG_SYS_ERR;
	}

	uint32_t inbuf[4];
    inbuf[0] = client_ip;
    inbuf[1] = time(0);
    inbuf[2] = userid;
    inbuf[3] = inbuf[1];
    des_encrypt_n(LOGIN_DES_KEY, (char *)inbuf, (char *)(*sendbuf + PROTO_HEAD_SIZE), 2);
	((PROTO_HEAD_PTR)*sendbuf)->userid = htonl(userid);
	
	INFO_LOG("userid[%u]email[%s]sex[%c]birth[%u]", userid, safe_str, 
			 byp->sex, ntohl(byp->birthday));

	DEBUG_LOG("REG FROM CHANNEL\t[%u]", user_db.reg_addr_type);
    // stat client
    time_t   ts  = time(0);
    uint32_t tmp = 1;

    // 统计消息起始ID 0x2010101
    /*  0:51mole    1:92game    2:766
        3:QQ空间    4:7K7K      5:4399
        6:3839      7:2144      8:小游戏 
        9:唤醒      10:向导     11:QQ礼活动
        12:摩尔大使 13:QQmini   14:4399xyx
        15:cks      16:yx007    17:新浪
        18:宏梦     19:19       20:彩虹堂
        21:gameyes  22:游戏22   23:41717小游戏
        24:f1212    25:游戏82   26:翼动小游戏
        27:成都小游戏网 28:92小游戏
		29: 大玩国  30:赛尔, 31哈奇小镇, 32 61.com*/
	if (user_db.reg_addr_type > max_register_channel) {
		user_db.reg_addr_type = 0;
	}
	DEBUG_LOG("====MAX %u", max_register_channel);
    msglog(statfile, 0x06010101 + user_db.reg_addr_type, ts, &tmp, sizeof(uint32_t));

	msglog(statfile, 0x06010001, ts, &userid, 4);
//	this->regact->send_email(safe_str[0], pUtil->get_config_strval("send_mail_cmd"), userid, safe_str[1]);
	DEBUG_LOG("---------------REGISTER ACCOUNT END (SUCCESS)-------------");

	////////for mole emissary
	/*
	if (ntohl(byp->location) == MOLE_EMISSARY_LOC) {
		LOG(7, "email : [%64.64s]", byp->email);
		LOG(7, "cmd : [%s]", pUtil->get_config_strval("send_mole_mail_cmd"));
		this->regact->send_mole_emissary_email(byp->email, pUtil->get_config_strval("send_mole_mail_cmd"), userid);
	}
	*/

	return SUCCESS;
}
Ejemplo n.º 24
0
int application_start(void)
{
  OSStatus err = kNoErr;
  net_para_st para;

  Platform_Init();
  /*Read current configurations*/
  context = ( mico_Context_t *)malloc(sizeof(mico_Context_t) );
  require_action( context, exit, err = kNoMemoryErr );
  memset(context, 0x0, sizeof(mico_Context_t));
  mico_rtos_init_mutex(&context->flashContentInRam_mutex);
  mico_rtos_init_semaphore(&context->micoStatus.sys_state_change_sem, 1); 

  MICOReadConfiguration( context );

  err = MICOInitNotificationCenter  ( context );

  err = MICOAddNotification( mico_notify_READ_APP_INFO, (void *)micoNotify_ReadAppInfoHandler );
  require_noerr( err, exit );  
  
  /*wlan driver and tcpip init*/
  mxchipInit();
  getNetPara(&para, Station);
  formatMACAddr(context->micoStatus.mac, (char *)&para.mac);
  
  mico_log_trace(); 
  mico_log("%s mxchipWNet library version: %s", APP_INFO, system_lib_version());

  /*Start system monotor thread*/
  err = MICOStartSystemMonitor(context);
  require_noerr_action( err, exit, mico_log("ERROR: Unable to start the system monitor.") );
  
  err = MICORegisterSystemMonitor(&mico_monitor, APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000);
  require_noerr( err, exit );
  mico_init_timer(&_watchdog_reload_timer,APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000-100, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);
  
  if(context->flashContentInRam.micoSystemConfig.configured != allConfigured){
    mico_log("Empty configuration. Starting configuration mode...");

#ifdef CONFIG_MODE_EASYLINK
  err = startEasyLink( context );
  require_noerr( err, exit );
#endif

#ifdef CONFIG_MODE_WAC
  WACPlatformParameters_t* WAC_Params = NULL;
  WAC_Params = calloc(1, sizeof(WACPlatformParameters_t));
  require(WAC_Params, exit);

  str2hex((unsigned char *)para.mac, WAC_Params->macAddress, 6);
  WAC_Params->isUnconfigured          = 1;
  WAC_Params->supportsAirPlay         = 0;
  WAC_Params->supportsAirPrint        = 0;
  WAC_Params->supports2_4GHzWiFi      = 1;
  WAC_Params->supports5GHzWiFi        = 0;
  WAC_Params->supportsWakeOnWireless  = 0;

  WAC_Params->firmwareRevision =  FIRMWARE_REVISION;
  WAC_Params->hardwareRevision =  HARDWARE_REVISION;
  WAC_Params->serialNumber =      SERIAL_NUMBER;
  WAC_Params->name =              context->flashContentInRam.micoSystemConfig.name;
  WAC_Params->model =             MODEL;
  WAC_Params->manufacturer =      MANUFACTURER;

  WAC_Params->numEAProtocols =    1;
  WAC_Params->eaBundleSeedID =    BUNDLE_SEED_ID;
  WAC_Params->eaProtocols =       (char **)eaProtocols;;

  err = startMFiWAC( context, WAC_Params, 1200);
  free(WAC_Params);
  require_noerr( err, exit );
#endif
  }
  else{
    mico_log("Available configuration. Starting Wi-Fi connection...");
    
    /* Regisist notifications */
    err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler );
    require_noerr( err, exit ); 
    
    err = MICOAddNotification( mico_notify_WiFI_PARA_CHANGED, (void *)micoNotify_WiFIParaChangedHandler );
    require_noerr( err, exit ); 

    err = MICOAddNotification( mico_notify_DHCP_COMPLETED, (void *)micoNotify_DHCPCompleteHandler );
    require_noerr( err, exit );  
   
    if(context->flashContentInRam.micoSystemConfig.rfPowerSaveEnable == true){
      ps_enable();
    }

    if(context->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable == true){
      mico_mcu_powersave_config(true);
    }

    /*Bonjour service for searching*/
    // if(context->flashContentInRam.micoSystemConfig.bonjourEnable == true){
    //   err = MICOStartBonjourService( Station, context );
    //   require_noerr( err, exit );
    // }

    err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mDNSResponder", mDNSResponder_thread, 0x1000, (void*)context );
    require_noerr_action( err, exit, mico_log("ERROR: Unable to start mDNSResponder thread.") );

    /*Local configuration server*/
    if(context->flashContentInRam.micoSystemConfig.configServerEnable == true){
      err =  MICOStartConfigServer(context);
      require_noerr_action( err, exit, mico_log("ERROR: Unable to start the local server thread.") );
    }

    /*Start mico application*/
    err = MICOStartApplication( context );
    require_noerr( err, exit );
    
    _ConnectToAP( context );
  }


  /*System status changed*/
  while(mico_rtos_get_semaphore(&context->micoStatus.sys_state_change_sem, MICO_WAIT_FOREVER)==kNoErr){
    switch(context->micoStatus.sys_state){
      case eState_Normal:
        break;
      case eState_Software_Reset:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        PlatformSoftReboot();
        break;
      case eState_Wlan_Powerdown:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        wifi_power_down();
        break;
      case eState_Standby:
        mico_log("Enter standby mode");
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(200);
        wifi_power_down();
        Platform_Enter_STANDBY();
        break;
      default:
        break;
    }
  }
    
  require_noerr_action( err, exit, mico_log("Closing main thread with err num: %d.", err) );

exit:
  mico_rtos_delete_thread(NULL);
  return kNoErr;
}
Ejemplo n.º 25
0
int
main(int argc, char **argv)
{
    int rv;
    const char *what;
    const char *filename;
    const char *outname;

    TheImg4 *img4;
    unsigned type;
    unsigned written;
    unsigned char ivkey[16 + 32];
    unsigned char *iv = NULL, *key = NULL;
    unsigned char *output = NULL;
    unsigned outlen = 0;
    int outdup = 0;

    DERItem item;
    unsigned char *data;
    size_t size;

    if (argc < 4) {
        fprintf(stderr, "usage: %s {-image|-extra|-keybag|-ticket} input output [ivkey]\n", argv[0]);
        return 1;
    }

    what = argv[1];
    filename = argv[2];
    outname = argv[3];
    if (argc > 4) {
        rv = str2hex(sizeof(ivkey), ivkey, argv[4]);
        if (rv == sizeof(ivkey)) {
            iv = ivkey;
            key = ivkey + 16;
        }
    }

    data = read_file(filename, 0, &size);
    if (data == NULL) {
        fprintf(stderr, "[e] cannot read '%s'\n", filename);
        return -1;
    }

    img4 = parse(data, size);
    if (!img4) {
        fprintf(stderr, "[e] cannot parse '%s'\n", filename);
        free(data);
        return -1;
    }

    rv = Img4DecodeGetPayloadType(img4, &type);
    if (rv) {
        fprintf(stderr, "[e] cannot identify '%s'\n", filename);
        goto err;
    }
    printf("%c%c%c%c\n", FOURCC(type));

    if (!strncmp(what, "-i", 2) || !strncmp(what, "-e", 2)) {
        int decompress;

        rv = Img4DecodeGetPayload(img4, &item);
        if (rv) {
            fprintf(stderr, "[e] cannot extract payload from '%s'\n", filename);
            goto err;
        }
        output = item.data;
        outlen = item.length;

        if (iv && key) {
            if (outlen & 15) {
                unsigned usize = (outlen + 15) & ~15;
                unsigned char *tmp = calloc(1, usize);
                if (!tmp) {
                    fprintf(stderr, "[e] out of memory %u\n", usize);
                    goto err;
                }
                memcpy(tmp, output, outlen);
                OUTSET(tmp);
            }

            rv = Img4DecodeGetPayloadKeybag(img4, &item);
            if (rv || item.length == 0) {
                fprintf(stderr, "[w] image '%s' has no keybag\n", filename);
            }
#ifdef USE_CORECRYPTO
            cccbc_one_shot(ccaes_cbc_decrypt_mode(), 32, key, iv, (outlen + 15) / 16, output, output);
#else
            AES_KEY decryptKey;
            AES_set_decrypt_key(key, 256, &decryptKey);
            AES_cbc_encrypt(output, output, (outlen + 15) & ~15, &decryptKey, iv, AES_DECRYPT);
#endif
        }

#ifdef iOS10
        if (img4->payload.compression.data && img4->payload.compression.length) {
            DERItem tmp[2];
            uint32_t deco = 0;
            uint64_t usize = 0;
            if (DERParseSequenceContent(&img4->payload.compression, 2, DERImg4PayloadItemSpecs10c, tmp, 0) ||
                DERParseInteger(&tmp[0], &deco) || DERParseInteger64(&tmp[1], &usize)) {
                fprintf(stderr, "[e] cannot get decompression info\n");
                goto err;
            }
            if (deco == 1 && what[1] == 'i') {
                size_t asize = lzfse_decode_scratch_size();
                unsigned char *dec, *aux = malloc(asize);
                if (!aux) {
                    fprintf(stderr, "[e] out of memory %zu\n", asize);
                    goto err;
                }
                dec = malloc(usize + 1);
                if (!dec) {
                    fprintf(stderr, "[e] out of memory %llu\n", usize + 1);
                    free(aux);
                    goto err;
                }
                outlen = lzfse_decode_buffer(dec, usize + 1, output, outlen, aux);
                free(aux);
                if (outlen != usize) {
                    fprintf(stderr, "[e] decompression error\n");
                    free(dec);
                    goto err;
                }
                OUTSET(dec);
            }
        }
#endif
        decompress = (DWORD_BE(output, 0) == 'comp' && DWORD_BE(output, 4) == 'lzss');
        if (decompress && what[1] == 'i') {
            uint32_t csize = DWORD_BE(output, 16);
            uint32_t usize = DWORD_BE(output, 12);
            uint32_t adler = DWORD_BE(output, 8);
            unsigned char *dec = malloc(usize);
            if (outlen > 0x180 + csize) {
                fprintf(stderr, "[i] extra 0x%x bytes after compressed chunk\n", outlen - 0x180 - csize);
            }
            if (!dec) {
                fprintf(stderr, "[e] out of memory %u\n", usize);
                goto err;
            }
            outlen = decompress_lzss(dec, output + 0x180, csize);
            if (adler != lzadler32(dec, outlen)) {
                fprintf(stderr, "[w] adler32 mismatch\n");
            }
            OUTSET(dec);
        } else if (decompress) {
            uint32_t csize = DWORD_BE(output, 16);
            uint32_t usize = outlen - 0x180 - csize;
            if (outlen > 0x180 + csize) {
                unsigned char *dec = malloc(usize);
                if (!dec) {
                    fprintf(stderr, "[e] out of memory %u\n", usize);
                    goto err;
                }
                memcpy(dec, output + 0x180 + csize, usize);
                outlen = usize;
                OUTSET(dec);
            } else {
                OUTSET(NULL);
            }
        } else if (what[1] == 'e') {
            OUTSET(NULL);
        }
        if (!output) {
            fprintf(stderr, "[e] nothing to do\n");
            goto err;
        }
    }
    if (!strncmp(what, "-k", 2)) {
        rv = Img4DecodeGetPayloadKeybag(img4, &item);
        if (rv == 0 && item.length) {
            output = item.data;
            outlen = item.length;
        } else {
            fprintf(stderr, "[e] image '%s' has no keybag\n", filename);
            goto err;
        }
    }
    if (!strncmp(what, "-t", 2)) {
        bool exists = false;
        rv = Img4DecodeManifestExists(img4, &exists);
        if (rv == 0 && exists) {
            output = img4->manifestRaw.data;
            outlen = img4->manifestRaw.length;
        } else {
            fprintf(stderr, "[e] image '%s' has no ticket\n", filename);
            goto err;
        }
    }

    written = write_file(outname, output, outlen);
    if (written != outlen) {
        fprintf(stderr, "[e] cannot write '%s'\n", outname);
        goto err;
    }

    rv = 0;
out:
    if (outdup) {
        free(output);
    }
    free(img4);
    free(data);
    return rv;

err:
    rv = -1;
    goto out;
}
Ejemplo n.º 26
0
int application_start(void)
{
  OSStatus err = kNoErr;
  IPStatusTypedef para;
  struct tm currentTime;
  mico_rtc_time_t time;
  char wifi_ver[64];
  mico_log_trace();  
#if 1 
  /*Read current configurations*/
  context = ( mico_Context_t *)malloc(sizeof(mico_Context_t) );
  require_action( context, exit, err = kNoMemoryErr );
  memset(context, 0x0, sizeof(mico_Context_t));
  mico_rtos_init_mutex(&context->flashContentInRam_mutex);
  mico_rtos_init_semaphore(&context->micoStatus.sys_state_change_sem, 1); 

  MICOReadConfiguration( context );

  err = MICOInitNotificationCenter  ( context );

  err = MICOAddNotification( mico_notify_READ_APP_INFO, (void *)micoNotify_ReadAppInfoHandler );
  require_noerr( err, exit );  

  err = MICOAddNotification( mico_notify_WIFI_CONNECT_FAILED, (void *)micoNotify_ConnectFailedHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_WIFI_Fatal_ERROR, (void *)micoNotify_WlanFatalErrHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_Stack_Overflow_ERROR, (void *)micoNotify_StackOverflowErrHandler );
  require_noerr( err, exit ); 
#endif
  /*wlan driver and tcpip init*/
  MicoInit();
  MicoSysLed(true);
  
  /**********************add ethernet**********************/
  add_ethernet();
  //sleep(5000);
  /*********************************************************/
  
  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory) ; 

  /* Enter test mode, call a build-in test function amd output on STDIO */
  if(MicoShouldEnterMFGMode()==true)
    mico_mfg_test();

  /*Read current time from RTC.*/
  MicoRtcGetTime(&time);
  currentTime.tm_sec = time.sec;
  currentTime.tm_min = time.min;
  currentTime.tm_hour = time.hr;
  currentTime.tm_mday = time.date;
  currentTime.tm_wday = time.weekday;
  currentTime.tm_mon = time.month - 1;
  currentTime.tm_year = time.year + 100;
  mico_log("Current Time: %s",asctime(&currentTime));

  micoWlanGetIPStatus(&para, Station);
  formatMACAddr(context->micoStatus.mac, (char *)&para.mac);
  MicoGetRfVer(wifi_ver, sizeof(wifi_ver));
  mico_log("%s mxchipWNet library version: %s", APP_INFO, MicoGetVer());
  mico_log("Wi-Fi driver version %s, mac %s", wifi_ver, context->micoStatus.mac);

  /*Start system monotor thread*/
  err = MICOStartSystemMonitor(context);
  require_noerr_action( err, exit, mico_log("ERROR: Unable to start the system monitor.") );

  err = MICORegisterSystemMonitor(&mico_monitor, APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000);
  require_noerr( err, exit );
  mico_init_timer(&_watchdog_reload_timer,APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000 - 100, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);

  /* Regisist notifications */
  err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler );
  require_noerr( err, exit ); 

  
  /*************add ethernet********Why add twice?***********/
  //add_ethernet();
  
  if(context->flashContentInRam.micoSystemConfig.configured != allConfigured){
    mico_log("Empty configuration. Starting configuration mode...");

#if (MICO_CONFIG_MODE == CONFIG_MODE_EASYLINK) || (MICO_CONFIG_MODE == CONFIG_MODE_EASYLINK_WITH_SOFTAP)
  err = startEasyLink( context );
  require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_SOFT_AP)
  err = startEasyLinkSoftAP( context );
  require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_AIRKISS)
  err = startAirkiss( context );
  require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_WPS) || MICO_CONFIG_MODE == defined (CONFIG_MODE_WPS_WITH_SOFTAP)
  err = startWPS( context );
  require_noerr( err, exit );
#elif ( MICO_CONFIG_MODE == CONFIG_MODE_WAC)
  WACPlatformParameters_t* WAC_Params = NULL;
  WAC_Params = calloc(1, sizeof(WACPlatformParameters_t));
  require(WAC_Params, exit);

  str2hex((unsigned char *)para.mac, WAC_Params->macAddress, 6);
  WAC_Params->isUnconfigured          = 1;
  WAC_Params->supportsAirPlay         = 0;
  WAC_Params->supportsAirPrint        = 0;
  WAC_Params->supports2_4GHzWiFi      = 1;
  WAC_Params->supports5GHzWiFi        = 0;
  WAC_Params->supportsWakeOnWireless  = 0;

  WAC_Params->firmwareRevision =  FIRMWARE_REVISION;
  WAC_Params->hardwareRevision =  HARDWARE_REVISION;
  WAC_Params->serialNumber =      SERIAL_NUMBER;
  WAC_Params->name =              context->flashContentInRam.micoSystemConfig.name;
  WAC_Params->model =             MODEL;
  WAC_Params->manufacturer =      MANUFACTURER;

  WAC_Params->numEAProtocols =    1;
  WAC_Params->eaBundleSeedID =    BUNDLE_SEED_ID;
  WAC_Params->eaProtocols =       (char **)eaProtocols;

  err = startMFiWAC( context, WAC_Params, 1200);
  free(WAC_Params);
  require_noerr( err, exit );
#else
  #error "Wi-Fi configuration mode is not defined"?
#endif
  }
  else{
    mico_log("Available configuration. Starting Wi-Fi connection...");
    
    err = MICOAddNotification( mico_notify_WiFI_PARA_CHANGED, (void *)micoNotify_WiFIParaChangedHandler );
    require_noerr( err, exit ); 

    err = MICOAddNotification( mico_notify_DHCP_COMPLETED, (void *)micoNotify_DHCPCompleteHandler );
    require_noerr( err, exit );  
   
    if(context->flashContentInRam.micoSystemConfig.rfPowerSaveEnable == true){
      micoWlanEnablePowerSave();
    }

    if(context->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable == true){
      MicoMcuPowerSaveConfig(true);
    }

    /*Local configuration server*/
    if(context->flashContentInRam.micoSystemConfig.configServerEnable == true){
      err =  MICOStartConfigServer(context);
      require_noerr_action( err, exit, mico_log("ERROR: Unable to start the local server thread.") );
    }

    err =  MICOStartNTPClient(context);
    require_noerr_action( err, exit, mico_log("ERROR: Unable to start the NTP client thread.") );

    /*Start mico application*/
    err = MICOStartApplication( context );
    require_noerr( err, exit );

    _ConnectToAP( context );
  }

  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory) ; 
  
  /*System status changed*/
  while(mico_rtos_get_semaphore(&context->micoStatus.sys_state_change_sem, MICO_WAIT_FOREVER)==kNoErr){
    switch(context->micoStatus.sys_state){
      case eState_Normal:
        break;
      case eState_Software_Reset:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        MicoSystemReboot();
        break;
      case eState_Wlan_Powerdown:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        micoWlanPowerOff();
        break;
      case eState_Standby:
        mico_log("Enter standby mode");
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(200);
        micoWlanPowerOff();
        MicoSystemStandBy(MICO_WAIT_FOREVER);
        break;
      default:
        break;
    }
  }
    
  require_noerr_action( err, exit, mico_log("Closing main thread with err num: %d.", err) );

exit:
  mico_rtos_delete_thread(NULL);
  return kNoErr;
}
Ejemplo n.º 27
0
int send_eth()
{
   // Tasks:
   // 1. Check 'eth_src_txt' and 'eth_dst_txt' which contain either a MAC address or a keyword
   //    'eth_dst' can be set without having 'eth_src_txt' specified (the next 6 bytes of the
   //    'arg_string' will be used). But if 'eth_src_txt' is given then also 'eth_dst_txt' 
   //    should have been specified, otherwise a default (ff-ff-ff-ff-ff-ff) will be used.
   // 2. Check whether 'arg_string' contains a hex-string. If YES then convert it into an
   //    'eth_payload' and extract eth_type.
   // 3. Apply 'padding' if specified
   // 4. Check if frame has at least minimum length (14 Bytes).
   // 5. Send frame 'count' times and
   // 6. Apply 'delay' (make precautions for better delay functions)
   
   int 
     src,                 // flag telling whether user has specified a source address
     dst,                 // flag telling whether user has specified a destination address
     src_random=0, 
     dst_random=0, 
     byte_ptr=1,
     bytestring_s=0,
     min_size=15,
     pad=0,
     repeat, loop, update,
     i=0,
     j=0;
   char 
     err_buf[LIBNET_ERRBUF_SIZE],
     message[MAX_PAYLOAD_SIZE*3];
     
   u_int8_t       bytestring[MAX_PAYLOAD_SIZE];
   libnet_ptag_t  t;
   libnet_t       *l;

   
	
   if (tx.dot1Q)
     {
	fprintf(stderr," Note: raw layer 2 mode does not support 802.1Q builder.\n"
		       " If you want to create VLAN tags then you must do it by hand.\n");
	exit(1);
     }
   
   if (tx.mpls)
     {
	fprintf(stderr," Note: raw layer 2 mode does not support MPLS builder.\n"
		       " If you want to create MPLS labels then you must do it by hand.\n");
	exit(1);
     }
   
	

   
   // So other functions can use this function for sending Ethernet frames
   // These other functions must set dst, src, type and payload!
   if (tx.eth_params_already_set) goto ALL_SPECIFIED;
   
   
   if ((tx.padding) && (tx.padding<15)) // Note: ignored if padding==0
     { 
	     tx.padding=15;
	     if (mz_port)    {
		     cli_print(gcli, "Note: Set padding to 15 bytes (total length)\n");
	     } else
		     fprintf(stderr, " mz/send_eth: [Note] adjusted minimum frame size to 15 bytes.\n");
     }
   
   // Create a temporal, local bytestring:
   //
   for (i=0; i<MAX_PAYLOAD_SIZE; i++) bytestring[i]=0x00;
   bytestring_s = str2hex (tx.arg_string, bytestring, MAX_PAYLOAD_SIZE);
   
   // Set the flags to shorten subsequent decisions:
   src = strlen(tx.eth_src_txt);
   dst = strlen(tx.eth_dst_txt);
   
   
   // IN ANY CASE if src has been specified:
   // 
   if (src) 
     {
	// Evaluate Ethernet CLI options (-a and -b)
	if (check_eth_mac_txt(ETH_SRC))  // if true then problem!
	  {
	     // use own (already set in init.c)
	  }
	src_random = tx.eth_src_rand; // local vars are faster
     }

   // IN ANY CASE if dst has been specified:
   // 
   if (dst) 
     {
	// Evaluate Ethernet CLI options (-a and -b)
	if (check_eth_mac_txt(ETH_DST))  // if true then problem!
	  {
	     str2hex("ff:ff:ff:ff:ff:ff",tx.eth_dst, 6); // the default 
	  }
	dst_random = tx.eth_dst_rand; // local vars are faster
     }

   
   // Catch errors with too short bytestrings:
   // 
   if (src)
     {
	// bytestring only needs to contain eth_type
	min_size-=12; 
     }
   else if (dst)
     {
	// bytstring must contain src and type
	min_size-=6;
     }
   if (bytestring_s < min_size)
     {
	     j = min_size - bytestring_s; // this is what's missing
	     bytestring_s += j; // note that bytestring has been filled up with 0x00, so we can do that
     }

	
   // ADDENDUM: If src specified, dst missing:
   // 
   if ( (!dst) && (src) ) 
     {
	str2hex_mac ("ff:ff:ff:ff:ff:ff", tx.eth_dst);
     }
   
   
   
   // ADDENDUM: If dst specified, src missing:
   // 
   if ((dst) && (!src))
     {
	// Get eth_src from bytestring:
	if (bytestring_s>=6) {
		(void) getbytes (bytestring, tx.eth_src, byte_ptr, byte_ptr+5);
		byte_ptr=7; // now points to eth_type within bytestring
	}
     }
   
   // FINALLY: If both dst and src have NOT been specified:
   // 
   if ((!dst) && (!src))
     {
	     if (bytestring_s>=6) {
		     (void) getbytes (bytestring, tx.eth_dst, byte_ptr, byte_ptr+5);
		     byte_ptr=7;
	     }

	     if (bytestring_s>=12) {
		     (void) getbytes (bytestring, tx.eth_src, byte_ptr, byte_ptr+5);
		     byte_ptr=13; // points to eth_type
	     }
     }
   
   // Set eth_type:
   // 
   if (bytestring_s>=2) {
	   tx.eth_type = 256 * bytestring[byte_ptr-1] + bytestring[byte_ptr]; // don't forget: byte_ptr counts from 1 not 0
	   byte_ptr+=2; // points to first payload byte (if available)
   }


   // Get remaining payload:
   // 
   if ( (tx.eth_payload_s = bytestring_s - byte_ptr +1) > 0 ) // if there are any remaining bytes
     {
	(void) getbytes (bytestring, tx.eth_payload, byte_ptr, bytestring_s);
     }
   

	
   // Add padding if desired. 
   // Note: padding means 'extend to given length' (not 'add these number of bytes')
   if (tx.padding) 
     {
	pad = tx.padding - (14 + tx.eth_payload_s); // number of additonal pad bytes required
	for (i=0; i<pad; i++)
	  {  
	    // tx.eth_payload[i+tx.eth_payload_s] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
	    tx.eth_payload[i+tx.eth_payload_s] = 0x00;
	  }
	tx.eth_payload_s += pad;
     }
   
   
	
   ALL_SPECIFIED:
   // *** All Ethernet parameters have been determined !
   // *** Now let's send the frame!
   
   l = libnet_init (LIBNET_LINK_ADV, tx.device, err_buf ); 
   
   if (l == NULL)
     {
	fprintf(stderr, " mz/send_eth: libnet_init() failed (%s)", err_buf);
	return -1;
     }
   
   repeat=1;
   
   if (tx.count == 0) 
     {
	loop = 1000000;
	if (!quiet) 
	  fprintf(stderr, " mz: !!! Infinite mode! Will send frames until you stop Mausezahn!!!\n");
     }
   else
     loop = tx.count;

   if ( (!quiet) && (!tx.delay) && (tx.count==0) )
	fprintf(stderr, " mz: !!! Will send at maximum frame rate without feedback!!!\n");
   
   t=0;
   update=1;

   // this is for the statistics:
   mz_start = clock();
   total_d = tx.count;
   
   while (repeat)
     {
	if (tx.count!=0) repeat=0; // count=0 means repeat ad inifinitum 
	
	for (i=0; i<loop; i++)
	  {
	     if (src_random)
	       {
		  tx.eth_src[0] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256) & 0xFE;
		  tx.eth_src[1] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_src[2] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_src[3] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_src[4] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_src[5] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  update=1;
	       }
	     
	     if (dst_random)
	       {
		  tx.eth_dst[0] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_dst[1] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_dst[2] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_dst[3] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_dst[4] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  tx.eth_dst[5] = (u_int8_t) ( ((float) rand()/RAND_MAX)*256);
		  update=1;
	       }
	     
	     if (update) // new frame parameters
	       {
		  t = libnet_build_ethernet (tx.eth_dst,
					     tx.eth_src,
					     tx.eth_type,
					     tx.eth_payload,
					     tx.eth_payload_s,
					     l,
					     t); 
	     
		  if (t == -1)
		    {
		       fprintf(stderr, " mz/send_eth: %s", libnet_geterror(l));
		       return -1;
		    }
		  
		  if (verbose) 
		    {
		       bs2str (tx.eth_dst, message, 6);                     // DA
		       fprintf(stderr, " mz: send %s",message);
		       
		       bs2str (tx.eth_src, message, 6);                     // SA
		       fprintf(stderr, " %s",message);
		       
		       type2str(tx.eth_type, message);
		       fprintf(stderr, " %s",message);                      // Type
		       
		       bs2str (tx.eth_payload, message, tx.eth_payload_s);   // Payload
		       fprintf(stderr, " %s\n",message);
		    }
		  update=0;
		  if (verbose==2) 
		    {
		        fprintf(stderr, "\n");
		       	fprintf(stderr, "*** NOTE: Simulation only! Nothing has been sent! ***\n");
		       libnet_destroy(l);
		       return 0;
		    }
		  
		    
	       }
	     
	     libnet_write(l);

	     if (tx.delay) 
	       {
		  SLEEP (tx.delay);
		  if ( (verbose) && (!src_random) && (!dst_random)  ) 
		    {
		       fprintf(stderr, ".");
		    }
	       }
	     
	  } // end for
	
     } // end while
   
   if (verbose)
     {
	if ((tx.delay) || (tx.count==0))
	  {
	     fprintf(stderr,"\n");
	  }
	
	fprintf(stderr, " mz: sent %u frames.\n",loop);
     }
   
   
   
   libnet_destroy(l);

   
   return 0;
}
Ejemplo n.º 28
0
int application_start(void)
{
  OSStatus err = kNoErr;
  IPStatusTypedef para;
  struct tm currentTime;
  mico_rtc_time_t time;
  char wifi_ver[64] = {0};
  mico_log_trace(); 


  /*Read current configurations*/
  context = ( mico_Context_t *)malloc(sizeof(mico_Context_t) );
  require_action( context, exit, err = kNoMemoryErr );
  memset(context, 0x0, sizeof(mico_Context_t));
  mico_rtos_init_mutex(&context->flashContentInRam_mutex);//ram互斥初始化
  mico_rtos_init_semaphore(&context->micoStatus.sys_state_change_sem, 1);//系统状态信号量 
  mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY, "sys", _sys_state_thread, 800, NULL );

  MICOReadConfiguration( context );//读flash数据

  err = MICOInitNotificationCenter  ( context );

  err = MICOAddNotification( mico_notify_READ_APP_INFO, (void *)micoNotify_ReadAppInfoHandler );
  require_noerr( err, exit );  

  err = MICOAddNotification( mico_notify_WIFI_CONNECT_FAILED, (void *)micoNotify_ConnectFailedHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_WIFI_Fatal_ERROR, (void *)micoNotify_WlanFatalErrHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_Stack_Overflow_ERROR, (void *)micoNotify_StackOverflowErrHandler );
  require_noerr( err, exit ); 

  /*wlan driver and tcpip init*/
  mico_log( "MiCO starting..." );
  MicoInit();
#ifdef MICO_CLI_ENABLE
  MicoCliInit();
#endif
  MicoSysLed(true);
  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory); 
  micoWlanGetIPStatus(&para, Station);
  formatMACAddr(context->micoStatus.mac, (char *)para.mac);
  MicoGetRfVer(wifi_ver, sizeof(wifi_ver));
  mico_log("ip = %s,mac=%s",para.ip,para.mac);
  mico_log("%s mxchipWNet library version: %s", APP_INFO, MicoGetVer());
  mico_log("Wi-Fi driver version %s, mac %s", wifi_ver, context->micoStatus.mac);
 
  /*Start system monotor thread*/
  //err = MICOStartSystemMonitor(context);
  require_noerr_action( err, exit, mico_log("ERROR: Unable to start the system monitor.") );

  err = MICORegisterSystemMonitor(&mico_monitor, APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000);
  require_noerr( err, exit );
  mico_init_timer(&_watchdog_reload_timer,APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000/2, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);

  /* Enter test mode, call a build-in test function amd output on MFG UART */
  if(MicoShouldEnterMFGMode()==true){
    mico_log( "Enter MFG mode by MFG button" );
    mico_mfg_test(context);
  }
  
  /*Read current time from RTC.*/
  if( MicoRtcGetTime(&time) == kNoErr ){
    currentTime.tm_sec = time.sec;
    currentTime.tm_min = time.min;
    currentTime.tm_hour = time.hr;
    currentTime.tm_mday = time.date;
    currentTime.tm_wday = time.weekday;
    currentTime.tm_mon = time.month - 1;
    currentTime.tm_year = time.year + 100;
    mico_log("Current Time: %s",asctime(&currentTime));
  }else
    mico_log("RTC function unsupported");
  
  /* Regisist notifications */
  err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler );
  require_noerr( err, exit ); 

  if( context->flashContentInRam.micoSystemConfig.configured == wLanUnConfigured ||
      context->flashContentInRam.micoSystemConfig.configured == unConfigured){
    mico_log("Empty configuration. Starting configuration mode...");
//HERE TO config network
#if (MICO_CONFIG_MODE == CONFIG_MODE_EASYLINK) || (MICO_CONFIG_MODE == CONFIG_MODE_EASYLINK_WITH_SOFTAP)
    err = startEasyLink( context );
    require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_SOFT_AP)
    err = startEasyLinkSoftAP( context );
    require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_AIRKISS)
    err = startAirkiss( context );
    require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_WPS) || MICO_CONFIG_MODE == defined (CONFIG_MODE_WPS_WITH_SOFTAP)
    err = startWPS( context );
    require_noerr( err, exit );
#elif ( MICO_CONFIG_MODE == CONFIG_MODE_WAC)
    WACPlatformParameters_t* WAC_Params = NULL;
    WAC_Params = calloc(1, sizeof(WACPlatformParameters_t));
    require(WAC_Params, exit);

    str2hex((unsigned char *)para.mac, WAC_Params->macAddress, 6);
    WAC_Params->isUnconfigured          = 1;
    WAC_Params->supportsAirPlay         = 0;
    WAC_Params->supportsAirPrint        = 0;
    WAC_Params->supports2_4GHzWiFi      = 1;
    WAC_Params->supports5GHzWiFi        = 0;
    WAC_Params->supportsWakeOnWireless  = 0;

    WAC_Params->firmwareRevision =  FIRMWARE_REVISION;
    WAC_Params->hardwareRevision =  HARDWARE_REVISION;
    WAC_Params->serialNumber =      SERIAL_NUMBER;
    WAC_Params->name =              context->flashContentInRam.micoSystemConfig.name;
    WAC_Params->model =             MODEL;
    WAC_Params->manufacturer =      MANUFACTURER;

    WAC_Params->numEAProtocols =    1;
    WAC_Params->eaBundleSeedID =    BUNDLE_SEED_ID;
    WAC_Params->eaProtocols =       (char **)eaProtocols;

    err = startMFiWAC( context, WAC_Params, MICO_I2C_CP, 1200 );
    free(WAC_Params);
    require_noerr( err, exit );
#else
    #error "Wi-Fi configuration mode is not defined"
#endif
  }
  else{
    mico_log("Available configuration. Starting Wi-Fi connection...");
    _ConnectToAP( context );
  }


#ifdef MFG_MODE_AUTO
  if( context->flashContentInRam.micoSystemConfig.configured == mfgConfigured ){
    mico_log( "Enter MFG mode automatically" );
    mico_mfg_test(context);
    mico_thread_sleep(MICO_NEVER_TIMEOUT);
  }
#endif
  
  err = MICOAddNotification( mico_notify_WiFI_PARA_CHANGED, (void *)micoNotify_WiFIParaChangedHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_DHCP_COMPLETED, (void *)micoNotify_DHCPCompleteHandler );
  require_noerr( err, exit );  
 
  if(context->flashContentInRam.micoSystemConfig.rfPowerSaveEnable == true){
    micoWlanEnablePowerSave();
  }

  if(context->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable == true){
    MicoMcuPowerSaveConfig(true);
  }
 
  /*Local configuration server*/
  if(context->flashContentInRam.micoSystemConfig.configServerEnable == true){
    err =  MICOStartConfigServer(context);
    require_noerr_action( err, exit, mico_log("ERROR: Unable to start the local server thread.") );
  }

  err =  MICOStartNTPClient(context);
  require_noerr_action( err, exit, mico_log("ERROR: Unable to start the NTP client thread.") );

  /*Start mico application*/
  err = MICOStartApplication( context );
  require_noerr( err, exit );
  
  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory) ; 
  
  require_noerr_action( err, exit, mico_log("Closing main thread with err num: %d.", err) );

exit:
  mico_rtos_delete_thread(NULL);
  return kNoErr;
}
Ejemplo n.º 29
0
int main(int argc, char *argv[])
{
	char *line = NULL;
	int len = 0, num = 0, n, rlen, type;
	unsigned char am, al, checksum;
	unsigned int addr;

	int flash_size = 0;

	int ch, option_index;
	static struct option long_options[] = {
		{"flash-size",	1, 0, 'S'},
		{"help",	0, 0, 'h'},
		{"version",	0, 0, 'v'},
		{ 0,		0, 0,  0 }
	};

	unsigned char *ptr;

	int ret;

	/* Process command line arguments */
	while (1) {
		ch = getopt_long(argc, argv, "S:hv",
			long_options, &option_index);
    
		if (ch == -1)
			break;
    
		switch (ch) {
		case 'S' :	/* flash-size */
			ret = sscanf(optarg, "%d", &flash_size);
			if (ret !=1) {
				PERR("set-control: Invalid value");
				exit(EXIT_FAILURE);
			}
			break;

		case 'h' :		/* help */
			print_help();
			exit(EXIT_SUCCESS);
			break;

		case 'v' :		/* version */
			print_version();
			exit(EXIT_SUCCESS);
			break;

		default :
			print_help();
			exit(EXIT_FAILURE);
		}
	}

	/* Sanity checks */
	if (flash_size == 0) {
		PERR("flash size unknow");
		exit(EXIT_FAILURE);
	}

	/* Build the flash image */
	ptr = (unsigned char *) malloc(flash_size);
	if (!ptr) {
		PERR("unable to allocate memory for flash image");
		exit(EXIT_FAILURE);
	}
	memset(ptr, 0xff, flash_size);

	/* Do the job */
	while (1) {
		/* Read ASCII strings from stdin */
		n = getline(&line, &len, stdin);
		if (n < 0) {
			if (feof(stdin))
				break;   /* EOF */

			PERR("error reading input data file");
			return -1;
		}
		n = strlen(line)-1;
		if (n >= 0)
			line[n] = '\0';
		num++;

		PDEBUG("[%05d]> %s", num, line);

		if (line[0] != ':') {
			PDEBUG("no data line, skipped");
			continue;
		}

		rlen = str2hex(line[1], line[2]);
		if (rlen > 16) {
			PERR("record too long at line %d", num);
			return -1;
		}
		am = str2hex(line[3], line[4]);
		al = str2hex(line[5], line[6]);
		addr = (am<<8)+al;
		if (addr >= flash_size) {
			PERR("invalid addres \"%x\"", addr);
			exit(EXIT_FAILURE);
		}
		type = str2hex(line[7], line[8]);
		checksum = str2hex(line[9+rlen*2], line[10+rlen*2]);

		PDEBUG("len %d - addr %04x - type %s - checksum %02x",
			rlen, addr, type == 0 ? "data" : "end", checksum);

		if (type == 1) {
			PDEBUG("end");
			break;
		}

		/* Save the data */
		for (n = 0; n < rlen; n++)
			ptr[addr+n] = str2hex(line[9+n*2], line[10+n*2]);

#if 0
		/* FIXME: should check checksum??? */
		checksum = compute_checksum(&wbuf[2], rlen+5);
#endif

#ifndef DEBUG
		fprintf(stderr, ".");
		fflush(stdout);
#endif
	}
#ifndef DEBUG
		fprintf(stderr, "\n");
#endif

	/* Write the flash image to the stdout */
	ret = fwrite(ptr, flash_size, 1, stdout);
	if (ret < 0) {
	   PERR("cannot write flash image");
	   return -1;
	}

	return 0;
}
Ejemplo n.º 30
0
/* Print to stdout detailed session summary */
hash_stat print_session_detailed(char *sessionname)
{
#ifdef HAVE_JSON_JSON_H
    FILE *sesfile;
    struct passwd *pwd;
    char sesname[1024];
    int cnt=0;
    char username[HASHFILE_MAX_LINE_LENGTH];
    char hash[HASHFILE_MAX_LINE_LENGTH];
    char rawhash[HASHFILE_MAX_LINE_LENGTH];
    char rawhash2[HASHFILE_MAX_LINE_LENGTH*2];
    char plugin_used[HASHFILE_MAX_LINE_LENGTH*2];
    char salt[HASHFILE_MAX_LINE_LENGTH];
    int flag = 0;
    json_object *jobj;
    
    printf("\nDetailed information about session: %s\n"
	    "-----------------------------------------------\n",sessionname);
    pwd = getpwuid(getuid());
    snprintf(sesname, 1024, "%s/.hashkill/sessions/%s.session", pwd->pw_dir, sessionname);
    /* Parse the <session>..</session> info */
    sesfile = fopen(sesname, "r");
    if (!sesfile)
    {
        elog("Cannot open session file : %s\n",sesname);
        return hash_err;
    }
    printf("Session file: \t%s\n",sesname);

    fclose(sesfile);
    root_node = json_object_from_file(sesname);
    main_header_node = json_object_object_get(root_node,"main");
    switch (json_object_get_int(json_object_object_get(main_header_node,"attacktype")))
    {
	case attack_method_simple_bruteforce:
	    printf("Attack type: \tBruteforce\n");
	    break;
	case attack_method_markov:
	    printf("Attack type: \tMarkov\n");
	    break;
	case attack_method_rule:
	    printf("Attack type: \tRule-based\n");
	    break;
	default:
	    printf("Attack type: \tUNKNOWN!\n");
	    break;
    }
    attack_method=json_object_get_int(json_object_object_get(main_header_node,"attacktype"));
    printf("Plugin: \t%s\n",json_object_get_string(json_object_object_get(main_header_node,"plugin")));
    printf("Progress: \t%d%%\n",json_object_get_int(json_object_object_get(main_header_node,"progress")));
    printf("Session ends: \t%s",json_object_get_string(json_object_object_get(main_header_node,"timestamp")));
    printf("Hashlist file: \t%s\n",json_object_get_string(json_object_object_get(main_header_node,"hashlistfile")));
    printf("Command line: \t%s\n",json_object_get_string(json_object_object_get(main_header_node,"commandline")));

    switch (attack_method)
    {
	case attack_method_simple_bruteforce:
	    attack_header_node = json_object_object_get(root_node,"bruteforce");
	    printf("\nBruteforce attack parameters:\n"
	             "-----------------------------\n");
	    printf("Start length: \t%d\n",json_object_get_int(json_object_object_get(attack_header_node,"start")));
	    printf("End length: \t%d\n",json_object_get_int(json_object_object_get(attack_header_node,"end")));
	    printf("Charset: \t%s\n",json_object_get_string(json_object_object_get(attack_header_node,"charset")));
	    printf("Current str: \t%s\n",json_object_get_string(json_object_object_get(attack_header_node,"currentstr")));
	break;
	case attack_method_markov:
	    attack_header_node = json_object_object_get(root_node,"markov");
	    printf("\nMarkov attack parameters:\n"
	             "-------------------------\n");
	    printf("Statfile: \t%s\n",json_object_get_string(json_object_object_get(attack_header_node,"statfile")));
	    printf("Threshold: \t%d\n",json_object_get_int(json_object_object_get(attack_header_node,"threshold")));
	    printf("End length: \t%d\n",json_object_get_int(json_object_object_get(attack_header_node,"maxlen")));
	    printf("Current str: \t%s\n",json_object_get_string(json_object_object_get(attack_header_node,"currentstr")));
	break;
	case attack_method_rule:
	    attack_header_node = json_object_object_get(root_node,"rule");
	    printf("\nRule attack parameters:\n"
	             "-----------------------\n");
	    printf("Rule file: \t%s\n",json_object_get_string(json_object_object_get(attack_header_node,"rulefile")));
	break;

    }
    printf("\nHashes list (username:hash:salt):\n---------------------------------\n");
    hash_list_node = json_object_object_get(root_node,"hashlist");
    flag = json_object_array_length(hash_list_node);
    for (cnt=0;cnt<flag;cnt++)
    {
	jobj = json_object_array_get_idx(hash_list_node, cnt);
	strcpy(username, json_object_get_string(json_object_object_get(jobj,"username")));
	strcpy(hash, json_object_get_string(json_object_object_get(jobj,"hash")));
	strcpy(salt, json_object_get_string(json_object_object_get(jobj,"salt")));
	// This is idiotic I know
	if ((strncmp(plugin_used,"md5unix",8)==0) || (strncmp(plugin_used,"sha512unix",10)==0) ||(strncmp(plugin_used,"phpbb3",6)==0) || (strncmp(plugin_used,"wordpress",9)==0) || (strncmp(plugin_used,"apr1",4)==0))
	{
	    b64_pton(hash,(unsigned char *)rawhash,512);
	    printf("%s:%s%s\n", username, salt, rawhash);
	}
	else if (  (strncmp(plugin_used,"desunix",7)==0)
		 || (strncmp(plugin_used,"ldap-sha",8)==0) || (strncmp(plugin_used,"ldap-ssha",9)==0))
	{
	    b64_pton(hash,(unsigned char *)rawhash,512);
	    printf("%s:%s:%s\n", username, rawhash, salt);
	}
	else
	{
	    str2hex(rawhash,rawhash2, (strlen(hash)*100)/147);
	    printf("%s:%s:%s\n", username, rawhash2, salt);
	}
    }
    cracked_list_node = json_object_object_get(root_node,"crackedlist");
    if (cracked_list_node)
    {
	cnt = json_object_array_length(cracked_list_node);
    }
    else
    {
	cnt=0;
    }
    printf("\n%d passwords cracked.\n",cnt);
    printf("\n");
    hlog("Session %s dumped successfully\n\n", sessionname);
    return hash_ok;
#else
    wlog("This build does not support sessions. Please reconfigure with --with-json and rebuild%s\n","");
    return hash_err;
#endif
}