Example #1
0
static void safe_leave(int signo){
	csprintf("\n## wanduck.safeexit ##\n");
	FD_ZERO(&allset);
	close(http_sock);
	close(dns_sock);
	
	int i;
	for(i = 0; i < maxfd; ++i)
		close(i);
	
	sleep(1);
	
	if(rule_setup == 1){
		csprintf("\n# Disable direct rule(exit wanduck)\n");
		
		if(sw_mode == 2 )
			system("iptables-restore /tmp/fake_nat_rules");
		else
			_eval(del_command, NULL, 0, NULL);
		
		change_redirect_rules(2, 0);
	}
	
// 2007.11 James {
	char *rm_pid[] = {"rm", "-f", "/var/run/wanduck.pid", NULL};
	
	_eval(rm_pid, NULL, 0, NULL);
// 2007.11 James }
	
csprintf("\n# return(exit wanduck)\n");
	exit(0);
}
Example #2
0
void get_lan_nvram(){
	char nvram_name[16];

	current_lan_unit = nvram_get_int("lan_unit");

	memset(prefix_lan, 0, 8);
	if(current_lan_unit < 0)
		strcpy(prefix_lan, "lan_");
	else
		sprintf(prefix_lan, "lan%d_", current_lan_unit);

	memset(current_lan_ifname, 0, 16);
	strcpy(current_lan_ifname, nvram_safe_get(strcat_r(prefix_lan, "ifname", nvram_name)));

	memset(current_lan_proto, 0, 16);
	strcpy(current_lan_proto, nvram_safe_get(strcat_r(prefix_lan, "proto", nvram_name)));

	memset(current_lan_ipaddr, 0, 16);
	strcpy(current_lan_ipaddr, nvram_safe_get(strcat_r(prefix_lan, "ipaddr", nvram_name)));

	memset(current_lan_netmask, 0, 16);
	strcpy(current_lan_netmask, nvram_safe_get(strcat_r(prefix_lan, "netmask", nvram_name)));

	memset(current_lan_gateway, 0, 16);
	strcpy(current_lan_gateway, nvram_safe_get(strcat_r(prefix_lan, "gateway", nvram_name)));

	memset(current_lan_dns, 0, 256);
	strcpy(current_lan_dns, nvram_safe_get(strcat_r(prefix_lan, "dns", nvram_name)));

	memset(current_lan_subnet, 0, 11);
	strcpy(current_lan_subnet, nvram_safe_get(strcat_r(prefix_lan, "subnet", nvram_name)));

#ifdef RTCONFIG_WIRELESSREPEATER
	if(sw_mode == SW_MODE_REPEATER){
		wlc_state = nvram_get_int("wlc_state");
		got_notify = 1;
	}
#endif

	csprintf("# wanduck: Got LAN(%d) information:\n", current_lan_unit);
	if(nvram_match("wanduck_debug", "1")){
#ifdef RTCONFIG_WIRELESSREPEATER
		if(sw_mode == SW_MODE_REPEATER){
			csprintf("# wanduck:   ipaddr=%s.\n", current_lan_ipaddr);
			csprintf("# wanduck:wlc_state=%d.\n", wlc_state);
		}
		else
#endif
		{
			csprintf("# wanduck:   ifname=%s.\n", current_lan_ifname);
			csprintf("# wanduck:    proto=%s.\n", current_lan_proto);
			csprintf("# wanduck:   ipaddr=%s.\n", current_lan_ipaddr);
			csprintf("# wanduck:  netmask=%s.\n", current_lan_netmask);
			csprintf("# wanduck:  gateway=%s.\n", current_lan_gateway);
			csprintf("# wanduck:      dns=%s.\n", current_lan_dns);
			csprintf("# wanduck:   subnet=%s.\n", current_lan_subnet);
		}
	}
}
Example #3
0
projectile_data *get_projectile_data(
	const short projectile_index)
{
	struct projectile_data *projectile =  GetMemberWithBounds(projectiles,projectile_index,MAXIMUM_PROJECTILES_PER_MAP);
	
	vassert(projectile, csprintf(temporary, "projectile index #%d is out of range", projectile_index));
	vassert(SLOT_IS_USED(projectile), csprintf(temporary, "projectile index #%d (%p) is unused", projectile_index, projectile));
	
	return projectile;
}
Example #4
0
int build_socket(char *http_port, char *dns_port, int *hd, int *dd){
	if((*hd = passivesock(http_port, IPPROTO_TCP, 10)) < 0){
		csprintf("Fail to socket for httpd port: %s.\n", http_port);
		return -1;
	}
	
	if((*dd = passivesock(dns_port, IPPROTO_UDP, 10)) < 0){
		csprintf("Fail to socket for DNS port: %s.\n", dns_port);
		return -1;
	}
	
	return 0;
}
Example #5
0
void windsensor(char *firstLine, char *secondLine) {
	int windSample = 0x00;

	// get windspeed
	windSample = SAR6_wind_cGetSample();
	windSample += 30; // make unsigned int
	windSample *= 5; // to get km/h
	
	csprintf(firstLine, "Windspeed       ");
	csprintf(secondLine, "%i km/h        ", windSample);
	
	// get wind direction
	/*
	if( (PORT & PIN1) &&
		(PORT & PIN2) &&
		(PORT & PIN3) )
	{ csprintf(&secondLine[13], "NO");
	} else if( !(PORT & PIN1) &&
				(PORT & PIN2) &&
				(PORT & PIN3) )
	{ csprintf(&secondLine[13], "NE");
	}else if( !(PORT & PIN1) &&
				(PORT & PIN2) &&
				!(PORT & PIN3) )
	{ csprintf(&secondLine[13], "EA");
	}else if(  (PORT & PIN1) &&
				(PORT & PIN2) &&
				!(PORT & PIN3) )
	{ csprintf(&secondLine[13], "SE");
	}else if(  (PORT & PIN1) &&
				!(PORT & PIN2) &&
				!(PORT & PIN3) )
	{ csprintf(&secondLine[13], "SO");
	}else if( !(PORT & PIN1) &&
				!(PORT & PIN2) &&
				!(PORT & PIN3) )
	{ csprintf(&secondLine[13], "SW");
	}else if( !(PORT & PIN1) &&
				!(PORT & PIN2) &&
				(PORT & PIN3) )
	{ csprintf(&secondLine[13], "WE");
	}else if(  (PORT & PIN1) &&
				!(PORT & PIN2) &&
				(PORT & PIN3) )
	{ csprintf(&secondLine[13], "NW");
	}
	*/
}
Example #6
0
int get_packets_of_net_dev(const char *net_dev, unsigned long *rx_packets, unsigned long *tx_packets){
	FILE *fp;
	char buf[256];
	char *ifname;
	char *ptr;
	int i, got_packets = 0;

	if((fp = fopen(PROC_NET_DEV, "r")) == NULL){
csprintf("get_packets_of_net_dev: Can't open the file: %s.\n", PROC_NET_DEV);
		return got_packets;
	}

	// headers.
	for(i = 0; i < 2; ++i){
		if(fgets(buf, sizeof(buf), fp) == NULL){
csprintf("get_packets_of_net_dev: Can't read out the headers of %s.\n", PROC_NET_DEV);
			fclose(fp);
			return got_packets;
		}
	}

	while(fgets(buf, sizeof(buf), fp) != NULL){
		if((ptr = strchr(buf, ':')) == NULL)
			continue;

		*ptr = 0;
		if((ifname = strrchr(buf, ' ')) == NULL)
			ifname = buf;
		else
			++ifname;

		if(strcmp(ifname, net_dev))
			continue;

		// <rx bytes, packets, errors, dropped, fifo errors, frame errors, compressed, multicast><tx ...>
		if(sscanf(ptr+1, "%*u%lu%*u%*u%*u%*u%*u%*u%*u%lu", rx_packets, tx_packets) != 2){
csprintf("get_packets_of_net_dev: Can't read the packet's number in %s.\n", PROC_NET_DEV);
			fclose(fp);
			return got_packets;
		}

		got_packets = 1;
		break;
	}
	fclose(fp);

	return got_packets;
}
static void search_from_directory(DirectorySpecifier& BaseDir)
//	FSSpec *file)
{
    FileFinder pb;

    pb.Clear();
    pb.version= 0;
    // LP change: always recurse
    pb.flags= _ff_recurse | _ff_callback_with_catinfo;
#if 0
#ifdef FINAL
    pb.flags= _ff_recurse | _ff_callback_with_catinfo;
#else
    pb.flags= _ff_callback_with_catinfo;
#endif
#endif
    pb.search_type= _callback_only;
    pb.BaseDir = BaseDir;
    pb.Type= WILDCARD_TYPE;
    pb.buffer= NULL;
    pb.max= 32767; // maximum
    pb.callback= found_some_file_callback;
    pb.user_data= NULL;
    pb.count= 0;

    bool seek_ok= pb.Find();
    if(!seek_ok)
        vassert(seek_ok, csprintf(temporary, "Error: %d", pb.GetError()));
}
Example #8
0
// Parse a single resource
bool XML_ResourceFork::ParseResource(ResType Type, short ID)
{
    ResourceHandle = Get1Resource(Type,ID);
    if (ResourceHandle == NULL) {
        return false;
    }

    HLock(ResourceHandle);
    if (!DoParse()) {
        const char *Name = SourceName ? SourceName : "[]";
#ifdef TARGET_API_MAC_CARBON
        csprintf(
            temporary,
            "There were configuration-file parsing errors in resource %hd of object %s",
            ID,Name);
        SimpleAlert(kAlertStopAlert,temporary);
#else
        psprintf(
            ptemporary,
            "There were configuration-file parsing errors in resource %hd of object %s",
            ID,Name);
        ParamText(ptemporary,0,0,0);
        Alert(FatalErrorAlert,NULL);
#endif
        ExitToShell();
    }
    HUnlock(ResourceHandle);
    ReleaseResource(ResourceHandle);
    return true;
}
Example #9
0
void change_redirect_rules(int num, int force_link_down_up){
	return;
#if 0
	int i;
	char *clean_ip_conntrack[] = {"cat", "/proc/net/nf_conntrack", NULL};
	
	num = 1;	// tmp test
	//nvram_set("wan_state_changed", "1");
	track_set("101");
	// In experience, need to clean the ip_conntrack up in three times for a clean ip_conntrack.
	if (nvram_match("asus_mfg", "0"))
	for(i = 0; i < num; ++i){
csprintf("**** clean ip_conntrack %d time. ****\n", i+1);
		_eval(clean_ip_conntrack, ">/dev/null", 0, NULL);
		
		if(i != num-1)
			sleep(1);
	}
	
	//nvram_set("wan_state_changed", "0");
	track_set("100");
#endif
//	system("killall dproxy");
	system("rm -f /tmp/dproxy.cache");
//	system("dproxy -c /tmp/dproxy.conf &");
}
Example #10
0
char *getpstr(
	char *buffer,
	short resource_number,
	short string_number)
{
	Handle strings= GetResource('STR#', resource_number);

	assert(strings);
	if (strings)
	{
		short count;
		byte *string_address;
		
		vassert(string_number>=0&&string_number<**((short**)strings),
			csprintf(temporary, "asked for #%d/#%d in 'STR#' ID#%d", string_number, **((short**)strings), resource_number));
		
		HLock(strings);
		count= 0;
		string_address= ((byte *)*strings)+2;
		while (count++<string_number)
		{
			string_address+= *string_address+1;
		}
		pstrcpy(buffer, (const char *)string_address);
		HUnlock(strings);
	}
	else
	{
		*buffer= '\0';
	}
	
	return buffer;
}
Example #11
0
void update_action_key(
	short player_index,
	boolean triggered)
{
	short               object_index;
	short               minimum_distance= 0;
	short               target_type;
	struct player_data  *player= get_player_data(player_index);
	
	if(triggered) 
	{
		object_index= find_action_key_target(player_index, MAXIMUM_ACTIVATION_RANGE, &target_type);

		if(object_index != NONE)
		{
			switch(target_type) 
			{
				case _target_is_platform:
					player_touch_platform_state(player_index, object_index);
					break;
				case _target_is_control_panel:
					change_panel_state(player_index, object_index);
					break;

				default:
					vhalt(csprintf(temporary, "%d is not a valid target type", target_type));
					break;
			}
		}
	}
}
Example #12
0
void pause_music(
	boolean pause)
{
	if(music_playing())
	{
		boolean pause_it= FALSE;

		/* If they want us to pause, and it is not already paused. */
		if(pause)
		{
			if(!(music_state->flags & _song_paused))
			{
				music_state->flags |= _song_paused;
				pause_it= TRUE;
			}
		} else {
			if(music_state->flags & _song_paused)
			{
				music_state->flags &= ~_song_paused;
				pause_it= TRUE;
			}
		}

		/* SndPauseFilePlay is a toggle */
		if(pause_it)
		{
			OSErr error;
			
			error= SndPauseFilePlay(music_state->channel);
			vwarn(error==noErr, csprintf(temporary, "Pause error: %d;g", error));
		}
	}
}
Example #13
0
static boolean load_collection(
	short collection_index,
	boolean strip)
{
	struct collection_header *header= get_collection_header(collection_index);
	Handle collection= NULL, shading_tables= NULL;
	OSErr error= noErr;
	
	if (bit_depth==8 || header->offset16==-1)
	{
		vassert(header->offset!=-1, csprintf(temporary, "collection #%d does not exist.", collection_index));
		collection= read_handle_from_file(shapes_file_refnum, header->offset, header->length);
	}
	else
	{
		collection= read_handle_from_file(shapes_file_refnum, header->offset16, header->length16);
	}

	if (collection)
	{
		if (strip) strip_collection_handle((struct collection_definition **) collection);
		MoveHHi(collection), HLock(collection);
		header->collection= (struct collection_definition **) collection;
	
		/* allocate enough space for this collectionÕs shading tables */
		if (strip)
		{
			shading_tables= NewHandle(0);
		}
		else
		{
			struct collection_definition *definition= get_collection_definition(collection_index);
			
			shading_tables= NewHandle(get_shading_table_size(collection_index)*definition->clut_count +
				shading_table_size*NUMBER_OF_TINT_TABLES);
			if ((error= MemError())==noErr)
			{
				assert(shading_tables);
				MoveHHi(shading_tables), HLock(shading_tables);
			}
		}
		
		header->shading_tables= shading_tables;
	}
	else
	{
		error= MemError();
//		vhalt(csprintf(temporary, "couldnÕt load collection #%d (error==#%d)", collection_index, error));
	}

	/* if any errors ocurred, free whatever memory we used */
	if (error!=noErr)
	{
		if (collection) DisposeHandle(collection);
		if (shading_tables) DisposeHandle(shading_tables);
	}
	
	return error==noErr ? TRUE : FALSE;
}
Example #14
0
// LP change: moved down here to use the projectile definitions
projectile_definition *get_projectile_definition(
	short type)
{
	projectile_definition *definition = GetMemberWithBounds(projectile_definitions,type,NUMBER_OF_PROJECTILE_TYPES);
	vassert(definition, csprintf(temporary, "projectile type #%d is out of range", type));
	
	return definition;
}
Example #15
0
// 2010.09 James. {
static void rebuild_rule(int signo){
	if(rule_setup == 1){
csprintf("\n# Rebuild rules by SIGUSR2\n");
		_eval(add_command, NULL, 0, NULL);
		
		change_redirect_rules(1, 0);
	}
}
Example #16
0
static struct collection_definition *get_collection_definition(
	short collection_index)
{
	struct collection_definition **collection= get_collection_header(collection_index)->collection;

	vassert(collection, csprintf(temporary, "collection #%d isnÕt loaded", collection_index));

	return (struct collection_definition *) StripAddress(*collection);
}
Example #17
0
void free_music_channel(
	void)
{
	if (music_state && music_state->initialized && music_state->channel)
	{
		OSErr error;
		
		error= SndDisposeChannel(music_state->channel, TRUE);
		vwarn(error==noErr, csprintf(temporary, "SndDisposeChannel returned %d;g", error));
		music_state->channel= NULL;
	}
}
Example #18
0
static void notify_nvram_changed(int signo){
	int unit;

#ifdef RTCONFIG_DUALWAN
	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
		if(get_dualwan_by_unit(unit) == WANS_DUALWAN_IF_USB){
			link_wan[unit] = is_usb_modem_ready();
			break;
		}
	}

	if(unit == WAN_UNIT_MAX)
		csprintf("# wanduck: nvram changed: Don't enable the USB line!\n");
	else
#else
	unit = WAN_UNIT_SECOND;

	link_wan[unit] = is_usb_modem_ready();
#endif
		csprintf("# wanduck: nvram changed: x_Setting=%d, link_modem=%d.\n", !isFirstUse, link_wan[unit]);
}
Example #19
0
// Reports a read error
void XML_ResourceFork::ReportReadError()
{
    const char *Name = SourceName ? SourceName : "[]";
#ifdef TARGET_API_MAC_CARBON
    csprintf(temporary,
             "Error in reading resource fork of object %s",Name);
    SimpleAlert(kAlertStopAlert,temporary);
#else
    psprintf(ptemporary,
             "Error in reading resource fork of object %s",Name);
    ParamText(ptemporary,0,0,0);
    Alert(FatalErrorAlert,NULL);
#endif
    ExitToShell();
}
Example #20
0
void stop_music(
	void)
{
	if (music_state && music_state->initialized && music_state->state != _no_song_playing)
	{
		OSErr error;
		
		error= SndStopFilePlay(music_state->channel, TRUE);
		vwarn(error==noErr, csprintf(temporary, "StopFilePlay returned %d;g", error));
		music_state->state= _no_song_playing;
		
		free(music_state->sound_buffer);
		music_state->sound_buffer= NULL;
	}
}
Example #21
0
static Handle read_handle_from_file(
	short refNum,
	long offset,
	long length)
{
	OSErr error= noErr;
	Handle data= NULL;
	
	if (refNum!=-1)
	{
		if (data= NewHandle(length))
		{
			ParamBlockRec param;
			
			HLock(data);
			
			param.ioParam.ioCompletion= (IOCompletionUPP) NULL;
			param.ioParam.ioRefNum= refNum;
			param.ioParam.ioBuffer= *data;
			param.ioParam.ioReqCount= length;
			param.ioParam.ioPosMode= fsFromStart;
			param.ioParam.ioPosOffset= offset;
			
			error= PBReadSync(&param);
			if (error==noErr)
			{
				HUnlock(data);
			}
			else
			{
				DisposeHandle(data);
				
				data= NULL;
			}
		}
		else
		{
			error= MemError();
		}
	}
	
	vwarn(error==noErr, csprintf(temporary, "read_handle_from_file() got error #%d", error));
	
	return data;
}
Example #22
0
// Reports an XML parsing error
void XML_ResourceFork::ReportParseError(const char *ErrorString, int LineNumber)
{
    const char *Name = SourceName ? SourceName : "[]";
#ifdef TARGET_API_MAC_CARBON
    csprintf(temporary,
             "XML parsing error: %s at line %d in object %s",ErrorString,
             LineNumber,
             Name);
    SimpleAlert(kAlertStopAlert,temporary);
#else
    psprintf(ptemporary,"XML parsing error: %s at line %d in object %s",
             ErrorString,LineNumber,
             Name);
    ParamText(ptemporary,0,0,0);
    Alert(FatalErrorAlert,NULL);
#endif
    ExitToShell();
}
Example #23
0
int wanduck_main(int argc, char **argv){
	char *http_servport, *dns_servport;
	socklen_t clilen;
	struct sockaddr_in cliaddr;
	struct timeval  tval;
	int nready, maxi, sockfd, conn_state;
#ifdef RTCONFIG_USB_MODEM
	int modem_ready_count = MODEM_IDLE;
#endif
	/*int pid;
	
	// daemonize
	if((pid = fork()) != 0)
		exit(0);
	
	umask(0);
	
	setsid();
	
	chdir("/");
	
	close(STDIN_FILENO);
	//close(STDOUT_FILENO);
	//close(STDERR_FILENO);
	
	struct stat fstatus;
	int fd;
	int max_tbl_sz = getdtablesize();
	for(fd = (STDERR_FILENO+1); fd <= max_tbl_sz; ++fd){
		if(fstat(fd, &fstatus) == 0){
			fprintf(stdout, "The inherited fd(%d) is closed.\n", fd);
			close(fd);
		}
	}//*/
	
	signal(SIGHUP, SIG_IGN);
	signal(SIGTERM, safe_leave);
	signal(SIGUSR1, get_related_nvram2); // 2010.09 James.
	signal(SIGUSR2, rebuild_rule); // 2010.09 James.
	
	if(argc < 3){
		http_servport = DFL_HTTP_SERV_PORT;
		dns_servport = DFL_DNS_SERV_PORT;
	}
	else{
// 2007.10 James {
		if(atoi(argv[1]) <= 0)
			http_servport = DFL_HTTP_SERV_PORT;
		else
			http_servport = argv[1];
		
		if(atoi(argv[2]) <= 0)
			dns_servport = DFL_DNS_SERV_PORT;
		else
			dns_servport = argv[2];
// 2007.10 James }
	}
	
// 2007.10 James {
	if(build_socket(http_servport, dns_servport, &http_sock, &dns_sock) < 0){
		csprintf("\n*** Fail to build socket! ***\n");
		exit(0);
	}
	
	FILE *fp = fopen("/var/run/wanduck.pid", "w");
	
	if(fp != NULL){
		fprintf(fp, "%d", getpid());
		fclose(fp);
	}
// 2007.10 James }
	
	maxfd = (http_sock > dns_sock)?http_sock:dns_sock;
	maxi = -1;
	
	FD_ZERO(&allset);
	FD_SET(http_sock, &allset);
	FD_SET(dns_sock, &allset);
	
	for(fd_i = 0; fd_i < MAX_USER; ++fd_i){
		client[fd_i].sfd = -1;
		client[fd_i].type = 0;
	}
	
	rule_setup = 0;
	disconn_case = 0;
	clilen = sizeof(cliaddr);
	
	sleep(3);
	
// 2008.03 James. {
	if(nvram_match("x_Setting", "1"))
		isFirstUse = FALSE;
	else
		isFirstUse = TRUE;
	
	get_related_nvram();
	
	if(!strcmp(nvram_safe_get("wan_ready"), "1")){
		wan_ready = 1;

		get_related_nvram2();
	}
// 2008.03 James. }
	
	err_state = if_wan_phyconnected();
	
	record_conn_status();	// 2008.02 James.
	
	if(err_state == DISCONN){
		if(nat_enable == 1 || (fer < HAD_SET)){
csprintf("\n# Enable direct rule\n");
			rule_setup = 1;
			
			_eval(add_command, NULL, 0, NULL);
			
			change_redirect_rules(2, 0);
		}
	}
	else if(err_state == CONNED && isFirstUse){
		if((nat_enable == 1) || (fer < HAD_SET)){
csprintf("\n#CONNED : Enable direct rule\n");
			rule_setup = 1;
			
			_eval(add_command, NULL, 0, NULL);
			
			change_redirect_rules(2, 0);
		}
	}
	
	for(;;){
		rset = allset;
		tval.tv_sec = SCAN_INTERVAL;
		tval.tv_usec = 0;

// 2008.03 James. {
		if(nvram_match("x_Setting", "1"))
			isFirstUse = FALSE;
		else
			isFirstUse = TRUE;

		if(wan_ready == 0 && !strcmp(nvram_safe_get("wan_ready"), "1")){
			wan_ready = 1;

			get_related_nvram2();

			if(isFirstUse == TRUE)	// 0608 add
			{
csprintf("\n# Rebuild rules\n");
				_eval(add_command, NULL, 0, NULL);
				change_redirect_rules(1, 0);
			}
		}
// 2008.03 James. }

		if((nat_enable == 1) || (fer < HAD_SET)){
			conn_state = if_wan_phyconnected();
			
			if(conn_state == CONNED){
				if(err_state == DISCONN)
					err_state = D2C;
				else
					err_state = CONNED;
					
#ifdef RTCONFIG_USB_MODEM
				modem_ready_count = MODEM_IDLE;
#endif
			}
			else if(conn_state == DISCONN){
				if(err_state == CONNED)
					err_state = C2D;
				else
					err_state = DISCONN;

#ifdef RTCONFIG_USB_MODEM
			if(disconn_case == CASE_THESAMESUBNET)
				modem_ready_count = MODEM_IDLE;
			else if(!strcmp(nvram_safe_get("manually_disconnect_wan"), "1"))
				modem_ready_count = MODEM_IDLE;
			else if(!link_modem)
				modem_ready_count = MODEM_IDLE;
			else if(modem_ready_count == MODEM_IDLE)
				modem_ready_count = MODEM_READY;
#endif
			}

#ifdef RTCONFIG_USB_MODEM
		if(modem_ready_count != MODEM_IDLE){
			if(modem_ready_count < MAX_WAIT_COUNT){
				++modem_ready_count;
csprintf("# wanduck: wait time for switching: %d/%d.\n", modem_ready_count*SCAN_INTERVAL, MAX_WAIT_TIME_OF_MODEM);
			}
			else{
				modem_ready_count = MODEM_READY;
			}
		}
#endif

			record_conn_status();	// 2008.02 James.
			
			if(err_state == C2D || (err_state == CONNED && isFirstUse)){
				if(rule_setup == 0){	// 2007.10 James
csprintf("\n# Enable direct rule(C2D)\n");
					rule_setup = 1;
					
					_eval(add_command, NULL, 0, NULL);
					
					change_redirect_rules(2, 1);
					update_wan(0);

#ifdef RTCONFIG_USB_MODEM
					if(err_state == C2D && !link_modem && modem_running){ // plug-off the Modem.
csprintf("\n# wanduck(C2D): Try to Switch the WAN line.(link_modem=%d).\n", link_modem);
						switch_usb_modem(link_modem);
					}
#endif
				}
			}
			else if(err_state == D2C || err_state == CONNED){
				if(rule_setup == 1 && !isFirstUse){
csprintf("\n#w Disable direct rule(D2C)\n");
					rule_setup = 0;
					
                			if(sw_mode == 2 )
                        			system("iptables-restore /tmp/fake_nat_rules");
                			else
					{
						_eval(del_command, NULL, 0, NULL);
					}
					change_redirect_rules(2, 0);
					update_wan(1);
				}
			}
#ifdef RTCONFIG_USB_MODEM
			// After boot, wait the WAN port to connect.
			else if(err_state == DISCONN){
				if((link_modem && modem_ready_count >= MAX_WAIT_COUNT)
						|| (!link_modem && modem_running)
						)
				{
if(modem_running)
	csprintf("# Switching the connect to WAN port...\n");
else
	csprintf("# Switching the connect to USB Modem...\n");
					switch_usb_modem(!modem_running);
				}
			}
#endif
		}
		else{	// ap mode
			nat_enable = 0;
			
			if(rule_setup == 1){
csprintf("\n#AP Disable direct rule(D2C)\n");
				rule_setup = 0;
				
                		if(sw_mode == 2 )
                        		system("iptables-restore /tmp/fake_nat_rules");
                		else
				{
					_eval(del_command, NULL, 0, NULL);
				}

				change_redirect_rules(2, 0);
				update_wan(1);
			}
		}
		
		if((nready = select(maxfd+1, &rset, NULL, NULL, &tval)) <= 0)
			continue;
		
		if(FD_ISSET(dns_sock, &rset)){
			//printf("# run fake dns service\n");	// tmp test
			run_dns_serv(dns_sock);
			if(--nready <= 0)
				continue;
		}
		else if(FD_ISSET(http_sock, &rset)){
			//printf("# run fake httpd service\n");	// tmp test
			if((connfd = accept(http_sock, (struct sockaddr *)&cliaddr, &clilen)) <= 0){
				perror("http accept");
				continue;
			}
			cur_sockfd = connfd;
			
			for(fd_i = 0; fd_i < MAX_USER; ++fd_i){
				if(client[fd_i].sfd < 0){
					client[fd_i].sfd = cur_sockfd;
					client[fd_i].type = T_HTTP;
					break;
				}
			}
			
			if(fd_i == MAX_USER){
csprintf("wanduck servs full\n");
				close(cur_sockfd);
				
				continue;
			}
			
			FD_SET(cur_sockfd, &allset);
			if(cur_sockfd > maxfd)
				maxfd = cur_sockfd;
			if(fd_i > maxi)
				maxi = fd_i;
			
			if(--nready <= 0)
				continue;	// no more readable descriptors
		}
		
		// polling
		for(fd_i = 0; fd_i <= maxi; ++fd_i){
			if((sockfd = client[fd_i].sfd) < 0)
				continue;
			
			if(FD_ISSET(sockfd, &rset)){
// 2007.10 James {
				int nread;
				ioctl(sockfd, FIONREAD, &nread);
				if(nread == 0){
					close_socket(sockfd, T_HTTP);
					continue;
				}
// 2007.10 James }
				
				cur_sockfd = sockfd;
				
				run_http_serv(sockfd);
				
				if(--nready <= 0)
					break;
			}
		}
	}
	
csprintf("wanduck exit error\n");
	exit(1);
}
bool ImageDescriptor::LoadFromFile(FileSpecifier& File, int ImgMode, int flags, int actual_width, int actual_height, int maxSize)
{
	if (flags & ImageLoader_ImageIsAlreadyPremultiplied)
		PremultipliedAlpha = true;

	// Don't load opacity if there is no color component:
	switch(ImgMode) {
		case ImageLoader_Colors:
			if (LoadDDSFromFile(File, flags, actual_width, actual_height, maxSize)) return true;
			break;
		
		case ImageLoader_Opacity:
			if (!IsPresent())
				return false;
			break;
		
		default:
			vassert(false, csprintf(temporary,"Bad image mode for loader: %d",ImgMode));
	}

	// Load image to surface
#ifndef SDL_RFORK_HACK
#ifdef HAVE_SDL_IMAGE
	SDL_Surface *s = IMG_Load(File.GetPath());
#else
	SDL_Surface *s = SDL_LoadBMP(File.GetPath());
#endif
#else
SDL_Surface *s = NULL;
#endif
	if (s == NULL)
		return false;

	// Get image dimensions and set its size
	int Width = s->w, Height = s->h;
	int OriginalWidth = (actual_width) ? actual_width : Width;
	int OriginalHeight = (actual_height) ? actual_height : Height;
	if (flags & ImageLoader_ResizeToPowersOfTwo) {
		Width = NextPowerOfTwo(Width);
		Height = NextPowerOfTwo(Height);
	}
	switch (ImgMode) {
		case ImageLoader_Colors:
			Resize(Width, Height);
			VScale = ((double) OriginalWidth / (double) Width);
			UScale = ((double) OriginalHeight / (double) Height);
			MipMapCount = 0;
			break;

		case ImageLoader_Opacity:
			// If the wrong size, then bug out
			if (Width != this->Width || Height != this->Height || ((double) OriginalWidth / Width != VScale || ((double) OriginalHeight / Height != UScale))) {
				SDL_FreeSurface(s);
				return false;
			}
			break;
	}

	// Convert to 32-bit OpenGL-friendly RGBA surface
#ifdef ALEPHONE_LITTLE_ENDIAN
	SDL_Surface *rgba = SDL_CreateRGBSurface(SDL_SWSURFACE, Width, Height, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
#else
	SDL_Surface *rgba = SDL_CreateRGBSurface(SDL_SWSURFACE, Width, Height, 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
#endif
	if (rgba == NULL) {
		SDL_FreeSurface(s);
		return false;
	}

	SDL_SetAlpha(s, 0, 0xff); // disable SDL_SRCALPHA
	SDL_BlitSurface(s, NULL, rgba, NULL);
	SDL_FreeSurface(s);

	// Convert surface to RGBA texture
	switch (ImgMode) {
		case ImageLoader_Colors:
			memcpy(GetPixelBasePtr(), rgba->pixels, Width * Height * 4);
			break;

		case ImageLoader_Opacity: {
			uint8 *p = (uint8 *)rgba->pixels;
			uint8 *q = (uint8 *)GetPixelBasePtr();
			for (int h=0; h<Height; h++) {
				for (int w=0; w<Width; w++) {
					// RGB to greyscale value, and then to the opacity
					float Red = float(*p++);
					float Green = float(*p++);
					float Blue = float(*p++);
					p++;
					float Opacity = (Red + Green + Blue) / 3.0F;
					q[3] = PIN(int(Opacity + 0.5), 0, 255);
					q += 4;
				}
			}
			break;
		}
	}

	SDL_FreeSurface(rgba);
	return true;
}
Example #25
0
void _alephone_warn(const char *file, int32 line, const char *what)
{
	vpause(csprintf(assert_text, "%s:%d: %s", file, line, what));
}
Example #26
0
void _alephone_assert(const char *file, int32 line, const char *what)
{
	vhalt(csprintf(assert_text, "%s:%d: %s", file, line, what));
}
Example #27
0
int main(int argc, char *argv[]) {
	disk_info_t *follow_disk, *disks_info = read_disk_data();
	partition_info_t *follow_partition;
	
	for (follow_disk = disks_info; follow_disk != NULL; follow_disk = follow_disk->next) {
		csprintf("	      tag: %s.\n", follow_disk->tag);
		csprintf("	   vendor: %s.\n", follow_disk->vendor);
		csprintf("	    model: %s.\n", follow_disk->model);
		csprintf("	   device: %s.\n", follow_disk->device);
		csprintf("	    major: %u.\n", follow_disk->major);
		csprintf("	    minor: %u.\n", follow_disk->minor);
		csprintf("   mounted_number: %u.\n", follow_disk->mounted_number);
		csprintf("     device_order: %u.\n", follow_disk->device_order);
		csprintf("size_in_kilobytes: %llu.\n", follow_disk->size_in_kilobytes);
		if (follow_disk->partitions == NULL) {
			csprintf("\n");
			continue;
		}
		
		for (follow_partition = follow_disk->partitions; follow_partition != NULL; follow_partition = follow_partition->next) {
			csprintf("     Partition %u:\n", follow_partition->partition_number);
			csprintf("parent disk's tag: %s.\n", follow_partition->disk->tag);
			csprintf("	   device: %s.\n", follow_partition->device);
			csprintf("      mount_point: %s.\n", follow_partition->mount_point);
			csprintf("      file_system: %s.\n", follow_partition->file_system);
			csprintf("size_in_kilobytes: %llu.\n", follow_partition->size_in_kilobytes);
			csprintf("   used_kilobytes: %llu.\n", follow_partition->used_kilobytes);
		}
		
		csprintf("\n");
	}//*/
	
	free_disk_data(&disks_info);
	
	return 0;
}
Example #28
0
/* can be called at interrupt time */
void queue_network_speaker_data(
  byte *buffer,
  short count)
{
  if (speaker) {
    switch (speaker->state)
    {
    case _speaker_is_off:
      /* we were off but now weÕre getting data; fill one double buffer with static and
              change our state to _turning_on (weÕll wait until we receive another full
              double buffer worth of data before beginning to replay) */

//				ZZZ: CarbonSndPlayDB emulation layer specifically warns against calling
//				SndDoImmediate() with a quietCmd at interrupt time - which is what
//				quiet_network_speaker() would do.  So instead here we try resetting
//				the speaker (which ought to be safe I think) now, but delay issuing the
//				quiet commands until just before we start playing again.
#if defined(TARGET_API_MAC_CARBON)
      reset_network_speaker();
#else
      quiet_network_speaker();                           /* we could be playing trailing static */
#endif
      speaker->state= _speaker_is_turning_on;
      fill_network_speaker_buffer(speaker->header->dbhBufferPtr[0]);
      break;

    case _speaker_is_on:
    case _speaker_is_turning_on:
      speaker->connection_status= 0;
      break;

    default:
      vhalt(csprintf(temporary, "what the hell is #%d!?", speaker->state));
    }

    /* move incoming data into queue, NULL buffer means static */
    if (speaker->queue_size+count<=MAXIMUM_QUEUE_SIZE) {
      if (buffer) {
        BlockMove(buffer, speaker->queue+speaker->queue_size, count);
      }
      else
      {
        fill_buffer_with_static((byte *)speaker->queue+speaker->queue_size,
                                count);
      }

      speaker->queue_size+= count;
    }
    else
    {
      // This really shouldn't log in the non-main thread yet...
      logAnomaly3("queue_net_speaker_data() is ignoring data: #%d+#%d>#%d",
                  speaker->queue_size, count,
                  MAXIMUM_QUEUE_SIZE);
    }

#ifdef SNDPLAYDOUBLEBUFFER_DOESNT_SUCK
    switch (speaker->state)
    {
    case _speaker_is_turning_on:
      /* check and see if we have enough data to turn on */
      if (speaker->queue_size>=speaker->block_size) {
        OSErr error;

        error= SndPlayDoubleBuffer(speaker->channel, speaker->header);
        vwarn(error==noErr,
              csprintf(temporary, "SndPlayDoubleBuffer(%p,%p)==#%d",
                       speaker->channel,
                       speaker->header, error));

        speaker->state= _speaker_is_on;
      }
      break;
    }
#endif
  }
}
Example #29
0
void main(void)
{	
	M8C_EnableGInt ; // Uncomment this line to enable Global Interrupts
	
	// Start the UART(with no parity), and Counter16
	UART_Start(UART_PARITY_NONE);
	// clock for moving serial
	Counter16_Start();
	
	// Start I2CHW
	I2CHW_Start();
	I2CHW_EnableMstr();
	I2CHW_EnableInt();
	
	// This is the command usage string
	UART_CPutString("########################## I2C External SRAM ########################\r\n\
#	W # XX T [Data]\r\n\
#		W    - Write command\r\n\
#		#    - Group Address (0 - 7)\r\n\
#		XX   - Memory Location in hex (00 - FF)\r\n\
#		T    - Data Type, either A for ASCII or H for Hexadecimal\r\n\
#		Data - Either ASCII string or Hexadecimal separates by spaces\r\n\
#\t\t\tA - Mary had a little lamb\r\n\
#\t\t\tH - 01 FF A0 0F D8 C3\r\n\
#\r\n\
#	R # XX T NN\r\n\
#		R    - Read command\r\n\
#		#    - Group Address (0 - 7)\r\n\
#		XX   - Memory Location in hex (00 - FF)\r\n\
#		T    - Data Type, either A for ASCII or H for Hexadecimal\r\n\
#		NN	 - Number of bytes to read in hexadecimal\r\n\
#####################################################################\r\n");
	while (1)
	{
		char *cmd;
		char *params;
		char slaveAddress = 0x50;		// 010100000 R/W shifted to front
		
		GetLine(buf, 79); // Retrieves a line with a maximum length of 70 characters and put it in buf.
		
		memset(data, 0x00, 256);	// Initialize all the set {data} to NULL bytes
		cmd = Lowercase(cstrtok(buf, " ")); // Get the first word from the entered string and lowercase it.
		if (strlen(cmd) == 1 && cmd[0] == 'w') // If the command is one letter and it is w, then write command
		{	
			int groupAddress; // only 1 and 2 actually go to SRAM
			int memLoc;
			char dataType;
			
			int len;

			params = cstrtok(0x00, " ");  // 0x00 indicates it will continue from last cstrtok command and get next word. This gets the next parameter
			
			// csscanf if used to parse the string into values such as hexadecimal or integers
			// It returns the number of parameters it parsed which should be one
			// If the length of the params is not right or it does not parse the right amount, it returns an error
			// %d gets an integer, this is the groupAddress
			if (strlen(params) != 1 || csscanf(params, "%d", &groupAddress) != 1) goto error;
			
			// %x gets a hexadecimal value, this can read capital or lowercase letters, this is the memory location
			params = cstrtok(0x00, " ");
			if (strlen(params) != 2 || csscanf(params, "%x", &memLoc) != 1) goto error;
			
			// %c gets a character, the data type character
			params = cstrtok(0x00, " ");
			if (strlen(params) != 1 || csscanf(params, "%c", &dataType) != 1) goto error;
			
			// This reads the rest of the string and stores it in params. 
			// If the length is zero or if cstrtok returns 0, this means that there was no valid string/hex entered
			params = cstrtok(0x00, "\0");
			if (strlen(params) == 0 || params == 0x00) goto error;	// They did all the params but didn't write anything
			
			dataType = tolower(dataType); // Lowercase the data type
			if (groupAddress < 0 || groupAddress > 7)
				goto error; // groupAddress was not in range
			
			data[0] = memLoc;	// First byte needs to be the memory location according to PCF8570 datasheet
			slaveAddress |= groupAddress;	// ORs the group 2 address to the group 1 address to get slaveAddress
			
			if (dataType == 'a') // If the data type is ASCII
			{
				strcpy((data + 1), params); // Copy the string from params and put it right after the data[0] byte
				len = strlen((data + 1)) + 1; // len is the number of bytes to write, it is the length of the string and then +1 because of the memLoc byte
				// Cant just do strlen(data) because data[0] could be 0x00 and it would return 0 as the string length
			}
			else if (dataType == 'h') // If the data type is hex
			{
				// Take ASCII encoded hex data params and put it after data[0], returns number of bytes converted
				if ((len = HexConversion(params, (data + 1))) == -1)
					goto error;
				len++; // Add one to the length because of the memLoc byte at data[0]
			}
			else
				goto error;
			
			I2CHW_bWriteBytes(slaveAddress, data, len, I2CHW_CompleteXfer); // Write len bytes from data 
			while (!(I2CHW_bReadI2CStatus() & I2CHW_WR_COMPLETE)); // Wait while it is writing
			I2CHW_ClrWrStatus(); // Clear the write bit

			csprintf(data, "%x bytes were written", len); // csprintf takes the string and substitutes %x for len, puts into data str
			UART_PutString(data); // Print the string to UART
			UART_PutCRLF();
		}
		else if (strlen(cmd) == 1 && cmd[0] == 'r') // If the command is one letter and it is r, then read command
		{
			int groupAddress;
			int memLoc;
			char dataType;
			int numBytes;
			
			char hexStr[4];
			int i;

			// csscanf if used to parse the string into values such as hexadecimal or integers
			// It returns the number of parameters it parsed which should be one
			// If the length of the params is not right or it does not parse the right amount, it returns an error
			// %d gets an integer, this is the groupAddress
			params = cstrtok(0x00, " ");
			if (strlen(params) != 1 || csscanf(params, "%d", &groupAddress) != 1) goto error;
	
			// %x gets a hexadecimal value, this can read capital or lowercase letters, this is the memory location
			params = cstrtok(0x00, " ");
			if (strlen(params) != 2 || csscanf(params, "%x", &memLoc) != 1) goto error;
			
			// %c gets a character, the data type character
			params = cstrtok(0x00, " ");
			if (strlen(params) != 1 || csscanf(params, "%c", &dataType) != 1) goto error;
			
			// %x gets a hexadecimal value, number of bytes to read
			params = cstrtok(0x00, " ");
			if (strlen(params) != 2 || csscanf(params, "%x", &numBytes) != 1) goto error;
			
			// If there is any data after the number of bytes, then the format is invalid and it should return an error
			if (cstrtok(0x00, " ") != 0x00) goto error;
			
			dataType = tolower(dataType); // Lowercase the data type
			if (groupAddress < 0 || groupAddress > 7)
				goto error; // groupAddress was not in range
			
			data[0] = memLoc;	// First byte needs to be the memory location according to PCF8570 datasheet
			slaveAddress |= groupAddress;	// ORs the group 2 address to the group 1 address to get slaveAddress
			
			I2CHW_bWriteBytes(slaveAddress, data, 1, I2CHW_NoStop); // Write one byte to the RAM, the slaveAddress so it knows who were talking to
			while (!(I2CHW_bReadI2CStatus() & I2CHW_WR_COMPLETE)); // Wait while it is writing
			I2CHW_ClrWrStatus(); // Clear the write bit
			
			I2CHW_fReadBytes(slaveAddress, data, numBytes, I2CHW_CompleteXfer); // Read numBytes from the RAM, put it in data
			while(!(I2CHW_bReadI2CStatus() & I2CHW_RD_COMPLETE)); // Wait while it is reading
			I2CHW_ClrRdStatus(); // Clear the read bit
			
			if (dataType == 'a') // If the data type is ASCII
			{
				for (i = 0; i < numBytes; ++i) // Loop through each byte
					UART_PutChar(data[i]); // Put the character in PuTTy
				UART_PutCRLF();
			}
			else if (dataType == 'h') // If the data type is Hex
			{
				for (i = 0; i < numBytes; ++i) // Loop through each byte
				{
					csprintf(hexStr, "%X ", data[i]); // csprintf prints into hexStr a hexadecimal with a space
					UART_PutString(hexStr); // Print hexStr
				}
				UART_PutCRLF();
			}
			else
				goto error;
		}
		else 
			goto error;
		
		continue; // This is so that the error is skipped when everything goes right
		error: // This outputs an invalid format message and continues on to read another line
			UART_CPutString("Invalid format entered. Valid formats are:\r\n\tW [GroupAddress] [MemoryLocation] [h|a] Hex/ASCII\r\n\tR [GroupAddress] [MemoryLocation] [h|a] [NumBytes]\r\n");
	}
}
Example #30
0
void music_idle_proc(
	void)
{
	if(music_state && music_state->initialized && music_state->state != _no_song_playing)
	{
		short ticks_elapsed= TickCount()-music_state->ticks_at_last_update;

		switch(music_state->state)
		{
			case _delaying_for_loop:
				if((music_state->phase-=ticks_elapsed)<=0)
				{
					/* Start playing.. */
					OSErr error;

					music_state->sound_buffer_size= kDefaultSoundBufferSize;
					music_state->sound_buffer= (Ptr)malloc(music_state->sound_buffer_size);
					if (music_state->sound_buffer)
					{
						assert(music_state->channel);					
	
						error= SndStartFilePlay(music_state->channel, // channel
							music_state->song_file_refnum, // Not from an AIFF file.
							0, // our resource id.
							music_state->sound_buffer_size, // Buffer size
							music_state->sound_buffer, // Let it allocate a buffer for us.
							NULL, // Audio selection ptr.
							music_state->completion_proc, // Completion proc
							TRUE); // Async.
						vwarn(error==noErr, csprintf(temporary, "SndStartFilePlay returned %d;g", error));
						if (!error) 
						{
							music_state->state= _playing_introduction;
						}
						else
						{
							music_state->state= _no_song_playing;
						}
					}
				}
				break;

			case _music_fading:
				if (ticks_elapsed>0)
				{
					if((music_state->phase-=ticks_elapsed)<=0 || (music_state->flags & _song_completed))
					{
						/* oops. we are done.. */
						stop_music();
						music_state->state= _no_song_playing;
						if(music_state->song_index != NONE)
						{
							/* Start the new song playing.. */
							queue_song(music_state->song_index);
						}
					} else {
						if(--music_state->fade_interval_ticks<=0)
						{
							short new_volume;
							SndCommand command;
							OSErr error;
							
							/* Only do this a few times.. */
							music_state->fade_interval_ticks= music_state->fade_interval_duration;
	
							/* Set the sound volume */
							new_volume= (0x100*music_state->phase)/music_state->fade_duration;

							/* set the sound volume */
							command.cmd= volumeCmd;
							command.param1= 0;
							command.param2= BUILD_STEREO_VOLUME(new_volume, new_volume);
							error= SndDoImmediate(music_state->channel, &command);
							vwarn(error==noErr, csprintf(temporary, "SndDoImmediate returned %d;g", error));
						}
					}
				}
				break;
			
			default:
				/* Don't change states until song_completed flag is set. */
				if(music_state->flags & _song_completed)
				{
					struct song_definition *song= get_song_definition(music_state->song_index);
					
					if(song->flags & _song_automatically_loops)
					{
						music_state->state= _delaying_for_loop;
						music_state->phase= song->restart_delay;
					} else {
						music_state->state= _no_song_playing;
					}
					music_state->flags &= ~_song_completed;
				}
				break;
		}
		music_state->ticks_at_last_update= TickCount();
	}

	return;
}