int main(int argc, char **argv) {
    if (!ReadParameter(argc, argv)) {
        std::cout << "Bad Parameters.\n";
        return 1;
    }
    SetConfig();
    if (compress) {
        // Compress
        db_compress::Compressor compressor(outputFileName, schema, config);
        int iter_cnt = 0;
        while (1) {
            std::cout << "Iteration " << ++iter_cnt << " Starts\n";
            std::ifstream inFile(inputFileName);
            std::string str;
            int tuple_cnt = 0;
            while (std::getline(inFile,str)) {
                std::stringstream sstream(str);
                std::string item;
                db_compress::Tuple tuple(schema.attr_type.size());
                
                db_compress::IntegerAttrValue attr(++tuple_cnt);
                tuple.attr[0] = &attr; 

                size_t count = 0;
                std::vector< std::unique_ptr<ColorAttr> > vec;
                while (std::getline(sstream, item, ' ')) {
                    if (++ count > 1)
                        AppendAttr(std::stod(item), &tuple, count - 1);
                }
                // The first item is tuple id
                if (count != schema.attr_type.size()) {
                    std::cerr << "File Format Error!\n";
                }
                compressor.ReadTuple(tuple);
                if (!compressor.RequireFullPass() && 
                    tuple_cnt >= NonFullPassStopPoint) {
                    break;
                }
            }
            compressor.EndOfData();
            if (!compressor.RequireMoreIterations()) 
                break;
        }
    } else {
        // Decompress
        db_compress::Decompressor decompressor(inputFileName, schema);
        std::ofstream outFile(outputFileName);
        decompressor.Init();
        while (decompressor.HasNext()) {
            db_compress::Tuple tuple(33);
            decompressor.ReadNextTuple(&tuple);
            for (size_t i = 0; i < schema.attr_type.size(); ++i) {
                double attr = ExtractAttr(&tuple, i);
                outFile << attr << (i == schema.attr_type.size() - 1 ? '\n' : ' ');
            } 
        }
    }
    return 0;
}
示例#2
0
int WINAPI Launcher_WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
	hinst = inst ;
	WNDCLASS wndclass ;
	MSG msg;
	char buffer[4096] ;

	if( FindWindow("KiTTYLauncher","KiTTYLauncher") ) return 0 ;

	if( strstr( cmdline, "-putty" ) != NULL ) PuttyFlag=1 ;
	
	wndclass.style = 0;
	wndclass.lpfnWndProc = Launcher_WndProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = inst;
	if( strstr( cmdline, "-oldicon" ) != NULL ) { oldIconFlag = 1 ; } 
	if( oldIconFlag ) { wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_BLACKBALL) ); }
	else { wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_PUTTY_LAUNCH) ); }
	wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM) ;
	wndclass.hbrBackground = NULL;
	wndclass.lpszMenuName = NULL;
	wndclass.lpszClassName = "KiTTYLauncher";

	if( !RegisterClass(&wndclass) ) return 1 ;

	if( ReadParameter( "Launcher", "reload", buffer ) ) {
		if( !stricmp( buffer, "NO" ) ) LauncherConfReload = 0 ;
		}
	if( LauncherConfReload ) InitLauncherRegistry() ;
		
	hwnd = CreateWindowEx(0, "KiTTYLauncher", "KiTTYLauncher",
				0,//WS_OVERLAPPEDWINDOW,
				CW_USEDEFAULT, CW_USEDEFAULT,
				CW_USEDEFAULT, CW_USEDEFAULT,
				NULL, NULL, inst, NULL);
	
	//ShowWindow(hwnd, show) ; UpdateWindow(hwnd) ;

	while (GetMessage(&msg, NULL, 0, 0)) {
		//if(!TranslateAccelerator(hwnd, hAccel, &msg)){
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		//	}
		}
	return msg.wParam;
	}
示例#3
0
 int main(void)
 {
 	 char main_str[10];
	 Disp_Init(DISP_INIT_ON);//显示初始化 ,打开显示
	 if(3000 > SYS_Read_Vol())
	 {
		 DispStr_E(0,16,"电量过低",DISP_CENTER|DISP_NORMAL|DISP_CLRSCR);
		 Sys_Delay_MS(1000);
		 Sys_Power_Sleep(2);
	 }
	 ReadParameter();//参数初始化
	 Disp_Set_Color(SET_BACK_COLOR,G_BackColor);//背景设置 浅蓝 
	 Disp_Set_Color(SET_CLEAR_COLOR,G_BackColor);//G_BackColor
	 Disp_Set_Color(SET_FONT_COLOR,G_FontColor);//前景颜色
	 Disp_Set_Color(SET_SELECT_COLOR,G_ThemeColor);//主题颜色
	 Sys_Auto_Poweroff_Set((ushort)G_AutoSleep);//30秒自动关机
	 EL_Set_Timeout((ushort)G_AutoElClose);//背光灯自动关闭时间7秒 
	 //WatchDog_Set(25);	//设置看门狗 
	 if(G_KeySound)
	 {
		 KEY_Init(KEY_AUTO_EL_ON|KEY_BEEP_KEY);//按键初始化
	 }
	 else
	 {
		 KEY_Init(KEY_AUTO_EL_ON);//按键初始化
	 }
	 //WriteParameter(E_PassWordAddr,sss,3);
	 //WriteParameter(E_PassWordLenAddr,&ss,1);
	 if(KEY_Read()==KEY_F2)
	 {
		sprintf(main_str,"%s",G_PassWord);
		DispStr_CE(0,4,main_str,DISP_CENTER|DISP_NORMAL|DISP_CLRSCR);
		delay_and_wait_key (1,EXIT_KEY_F1,120);
	 }
	 if(G_PassWordStatus)
	 {
		 RunPassWord();
	 }
	 Disp_Icon_Battery_Time_Set(1,ICON_AT_TAIL);
	 CWiFi_SetMSGCallBack((WiFiMSG_CALLBACK)WiFi_MsgDisplay);//设置回调函数
	 Open_WifiModel();
	 Sys_main();
	 return 1;
 }
示例#4
0
int wmain(int argc, wchar_t* argv[])
{
//Windows XP with SP3 support
	#if (defined(PLATFORM_WIN32) && !defined(PLATFORM_WIN64))
		GetFunctionPointer(FUNCTION_GETTICKCOUNT64);
		GetFunctionPointer(FUNCTION_INET_NTOP);
	#endif
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
int main(int argc, char *argv[])
{
#endif

//Get commands.
	if (argc > 0)
	{
		if (!ReadCommand(argc, argv))
			return EXIT_SUCCESS;
	}
	else {
		return EXIT_FAILURE;
	}

//Read configuration file and WinPcap or LibPcap initialization.
	if (!ReadParameter())
	{
		WSACleanup();
		return EXIT_FAILURE;
	}

//Mark Local DNS address to PTR Records.
	std::thread NetworkInformationMonitorThread(NetworkInformationMonitor);
	NetworkInformationMonitorThread.detach();

//Read IPFilter and Hosts.
	if (Parameter.OperationMode == LISTEN_MODE_CUSTOM || Parameter.BlacklistCheck || Parameter.LocalRouting)
	{
		std::thread IPFilterThread(ReadIPFilter);
		IPFilterThread.detach();
	}

	std::thread HostsThread(ReadHosts);
	HostsThread.detach();

//DNSCurve initialization
#if defined(ENABLE_LIBSODIUM)
	if (Parameter.DNSCurve && DNSCurveParameter.IsEncryption)
	{
		randombytes_set_implementation(&randombytes_salsa20_implementation);
		randombytes_stir();
		DNSCurveInit();
	}
#endif

#if defined(PLATFORM_WIN)
//Service initialization and start service.
	SERVICE_TABLE_ENTRYW ServiceTable[] = {{DEFAULT_LOCAL_SERVICE_NAME, (LPSERVICE_MAIN_FUNCTIONW)ServiceMain}, {nullptr, nullptr}};
	if (!StartServiceCtrlDispatcherW(ServiceTable))
	{
		Parameter.Console = true;
		wprintf_s(L"System Error: Service start error, error code is %lu.\n", GetLastError());
		wprintf_s(L"System Error: Program will continue to run in console mode.\n");
		wprintf_s(L"Please ignore those error messages if you want to run in console mode.\n");

	//Handle the system signal and start all monitors.
		SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
		MonitorInit();
	}

#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	MonitorInit();
#endif

	WSACleanup();
	return EXIT_SUCCESS;
}

//Read commands from main program
#if defined(PLATFORM_WIN)
bool __fastcall ReadCommand(int argc, wchar_t* argv[])
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
bool ReadCommand(int argc, char *argv[])
#endif
{
//Path initialization
#if defined(PLATFORM_WIN)
	if (!FileNameInit(argv[0]))
		return false;
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	std::shared_ptr<char> FileName(new char[PATH_MAX + 1U]());
	memset(FileName.get(), 0, PATH_MAX + 1U);
	if (getcwd(FileName.get(), PATH_MAX) == nullptr)
	{
		wprintf(L"Path initialization error.\n");
		return false;
	}
	if (!FileNameInit(FileName.get()))
		return false;
	FileName.reset();
#endif

#if defined(PLATFORM_WIN)
//Winsock initialization
	std::shared_ptr<WSAData> WSAInitialization(new WSAData());
	if (WSAStartup(MAKEWORD(WINSOCK_VERSION_HIGH, WINSOCK_VERSION_LOW), WSAInitialization.get()) != 0 ||
		LOBYTE(WSAInitialization->wVersion) != WINSOCK_VERSION_LOW || HIBYTE(WSAInitialization->wVersion) != WINSOCK_VERSION_HIGH)
	{
		wprintf_s(L"Winsock initialization error, error code is %d.\n", WSAGetLastError());
		PrintError(LOG_ERROR_NETWORK, L"Winsock initialization error", WSAGetLastError(), nullptr, 0);

		WSACleanup();
		return false;
	}

//Read commands.
	std::wstring Commands;
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	std::string Commands;
#endif
	for (size_t Index = 1U;(SSIZE_T)Index < argc;++Index)
	{
		Commands = argv[Index];

	//Flush DNS Cache from user.
		if (Commands == COMMAND_FLUSH_DNS)
		{
		#if defined(PLATFORM_WIN)
			FlushDNSMailSlotSender();
		#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
			FlushDNSFIFOSender();
		#endif

			WSACleanup();
			return false;
		}
	//Windows Firewall Test in first start.
	#if defined(PLATFORM_WIN)
		else if (Commands == COMMAND_FIREWALL_TEST)
		{
			if (!FirewallTest(AF_INET6) && !FirewallTest(AF_INET))
			{
				wprintf_s(L"Windows Firewall Test error.\n");
				PrintError(LOG_ERROR_NETWORK, L"Windows Firewall Test error", WSAGetLastError(), nullptr, 0);
			}

			WSACleanup();
			return false;
		}
	#endif
	//Set system daemon.
	#if defined(PLATFORM_LINUX)
		else if (Commands == COMMAND_DISABLE_DAEMON)
		{
			Parameter.Daemon = false;
		}
	#endif
	//Print current version.
		else if (Commands == COMMAND_LONG_PRINT_VERSION || Commands == COMMAND_SHORT_PRINT_VERSION)
		{
			wprintf_s(L"Pcap_DNSProxy ");
			wprintf_s(FULL_VERSION);
			wprintf_s(L"\n");

			WSACleanup();
			return false;
		}
	//Print help messages.
		else if (Commands == COMMAND_LONG_HELP || Commands == COMMAND_SHORT_HELP)
		{
			wprintf_s(L"Usage: Please see ReadMe... files in Documents folder.\n");

			WSACleanup();
			return false;
		}
	//Set working directory from commands.
		else if (Commands == COMMAND_LONG_SET_PATH || Commands == COMMAND_SHORT_SET_PATH)
		{
		//Commands check
			if ((SSIZE_T)Index + 1 >= argc)
			{
				wprintf_s(L"Commands error.\n");
				PrintError(LOG_ERROR_SYSTEM, L"Commands error", 0, nullptr, 0);

				WSACleanup();
				return false;
			}
			else {
				++Index;
				Commands = argv[Index];

			//Path check.
				if (Commands.length() > MAX_PATH)
				{
					wprintf_s(L"Commands error.\n");
					PrintError(LOG_ERROR_SYSTEM, L"Commands error", 0, nullptr, 0);

					WSACleanup();
					return false;
				}
				else {
					if (!FileNameInit(Commands.c_str()))
						return false;
				}
			}
		}
	}

//Set system daemon.
#if defined(PLATFORM_LINUX)
	if (Parameter.Daemon && daemon(0, 0) == RETURN_ERROR)
	{
		PrintError(LOG_ERROR_SYSTEM, L"Set system daemon error", 0, nullptr, 0);
		return false;
	}
#endif

	return true;
}

//Get path of program from the main function parameter and Winsock initialization
#if defined(PLATFORM_WIN)
bool __fastcall FileNameInit(const wchar_t *OriginalPath)
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
bool FileNameInit(const char *OriginalPath)
#endif
{
//Path process
#if defined(PLATFORM_WIN)
	Parameter.Path_Global->clear();
	Parameter.Path_Global->push_back(OriginalPath);
	Parameter.Path_Global->front().erase(Parameter.Path_Global->front().rfind(L"\\") + 1U);
	for (size_t Index = 0;Index < Parameter.Path_Global->front().length();++Index)
	{
		if ((Parameter.Path_Global->front()).at(Index) == L'\\')
		{
			Parameter.Path_Global->front().insert(Index, L"\\");
			++Index;
		}
	}
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	Parameter.sPath_Global->clear();
	Parameter.sPath_Global->push_back(OriginalPath);
	Parameter.sPath_Global->front().append("/");
	std::wstring StringTemp;
	MBSToWCSString(StringTemp, OriginalPath);
	StringTemp.append(L"/");
	Parameter.Path_Global->clear();
	Parameter.Path_Global->push_back(StringTemp);
	StringTemp.clear();
#endif

//Get path of error/running status log file and mark start time.
	Parameter.Path_ErrorLog->clear();
	*Parameter.Path_ErrorLog = Parameter.Path_Global->front();
	Parameter.Path_ErrorLog->append(L"Error.log");
#if (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	Parameter.sPath_ErrorLog->clear();
	*Parameter.sPath_ErrorLog = Parameter.sPath_Global->front();
	Parameter.sPath_ErrorLog->append("Error.log");
#endif
	Parameter.PrintError = true;
	time(&StartTime);

	return true;
}
示例#5
0
文件: main.c 项目: KipK/SbusToPPM
int main(void)
{
#if PPM_OUTPUT == TRUE
	isr_channel_pw[0] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[1] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[2] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[3] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[4] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[5] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[6] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[7] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
#if PPMCH == 12
	isr_channel_pw[8] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[9] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[10] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
	isr_channel_pw[11] = ((((F_CPU/1000) * 1500)/1000)/TIMER1_PRESCALER);
#endif

								
	TCCR1A = (1<<COM1B1) | (0<<COM1B0) | (1<<WGM11) | (1<<WGM10);
	TCCR1B = (1<<WGM13)|(1<<WGM12);
	OCR1A = RC_RESET_PW_TIMER_VAL;
	OCR1B  = RC_PPM_SYNC_PW_VAL;
	TIMSK1 |= (1<<OCIE1B)|(1<<TOIE1);
	TCNT1 = 0; 

	isr_channel_number = 1;		
#endif

	// timer0 with prescaler 8, and interrupt, Int freq: 9433khz , ~0.0001s 
	TCCR0B |= (1<<CS01);
	TIMSK0 |= (1<<TOIE0);


	DDRB |= (1<<PORTB2); //ppm out

#ifdef version1
	DDRC |= (1<<PORTC5); //inv uart out

	PCMSK2 |= (1<<PCINT18);
	PCICR |= (1<<PCIE2);
#endif

	// led
#if ENABLE_LED == TRUE
	DDRC |= (1<<PORTC4); //led out
	PORTC |= (1<<PORTC4);
	DDRB |= (1<<PORTB1); //led out
	PORTB |= (1<<PORTB1);
#endif

#if RSSI_OUTPUT == TRUE
	//timer2 fuer RSSI
	DDRB |= (1<<PORTB3);
	TCCR2A |= (1<<COM2A1) | (1<<WGM20)| (1<<WGM21);
	TCCR2B |= (1<<CS21);
	OCR2A = 0;
#endif	

	USART_Init();
	sei();

	uint8_t data = 0;
		
	uint8_t current_bit_in_ch = 0;
	uint8_t current_bit_in_byte = 0;
	uint8_t current_byte = 0;
	uint8_t current_ch = 0;
	uint8_t i = 0;
	uint8_t sbus_bytes[25];
	int16_t channels[12];
	int16_t channels_old[12];
	int16_t channels_vold[12];


	uint8_t curr_byte = 0;
	uint8_t ready = 0;
#if SPEKTRUM_OUTPUT == TRUE
	uint8_t spektrum_frame = 1;
	uint8_t send_sp = 0;
#endif

	

#if FORCE_FAILSAFE == FALSE
	uint8_t first = 0;  
	ReadParameter();
	if((MODE != 1)&&(MODE != 2)) MODE = 1;
#endif
#if FORCE_FAILSAFE == TRUE
	MODE = 1;
#endif
	
					
	while(1)
	{
		if(timeout == 0)
		{
			curr_byte = 0;
			timeout = 60; // 6ms
		}
			
		if(uart_getc_nb(&data))
		{
			timeout = 60; //6ms
			if(curr_byte == 0)
			{
				if(data != 0x0F)
				{
					curr_byte = 30;
				}
			}
			
			if( curr_byte == 24)
			{
				if(data != 0)
				{
					curr_byte = 30;
				}
			}
			if(curr_byte < 25)
			{
				sbus_bytes[curr_byte]=data;
				curr_byte++;
			}
			
			if(curr_byte == 25)
			{
				curr_byte = 0;
				current_bit_in_byte = 0;
				current_bit_in_ch = 0;
				current_ch = 0;
				current_byte = 1;

				for(i=0;i<12;i++)
				{
					channels[i] = 0;
				}
				
				for(i=0;i<132;i++)
				{
					if(sbus_bytes[current_byte] & (1<<current_bit_in_byte))
					{
						channels[current_ch] |= (1<<current_bit_in_ch);
					}
					
					current_bit_in_byte++;
					current_bit_in_ch++;
					
					if(current_bit_in_byte == 8)
					{
						current_bit_in_byte =0;
						current_byte++;
					}
					if(current_bit_in_ch == 11)
					{
						current_bit_in_ch =0;
						current_ch++;
					}
					
					
				}

#if FORCE_FAILSAFE == FALSE
				if(first < 110)
				{
					first++;
				}


				if(first < 100)
				{
					if(channels[0] < 800)
					{
						MODE = 1;
						WriteParameter();
					}
					if(channels[0] > 1250)
					{
						MODE = 2;
						WriteParameter();
					}
				}
#endif				

				for(i=0;i<12;i++)
				{
					if(channels_vold[i] == channels_old[i])
					{
						if(channels_old[i] != channels[i])
						{
							channels_old[i] = channels[i];
							if(channels_vold[i] != 0)
							{
								channels[i] = channels_vold[i];
							}
						}
					};
				}

#if PPM_OUTPUT == TRUE						
				unsigned int temp_isr_channel_pw[(PPMCH +1)];
				uint8_t i=0;

				/*
				 * Floating point math is slow, so perform computations before
				 * disabling interrupts.
				 */
				for(i=0;i<PPMCH;i++)
				{
					/*
					 * From linear regression of 7 PWM samples from
					 * 1100..1940us. R^2 = 0.999999.
					 * See https://gist.github.com/prattmic/8857047
					 */
					uint16_t pw = 0.624731*channels[i] + 880.561511;
					temp_isr_channel_pw[i] = ((((F_CPU/1000) * pw)/1000)/TIMER1_PRESCALER);
				}

				cli();
				for (i = 0; i < PPMCH; i++) {
					isr_channel_pw[i] = temp_isr_channel_pw[i];
				}
				sei();
#endif

				//wenn kein failsafe dann output senden
				if((sbus_bytes[23] & 8) == 0)
				{
					if(ready == 0)
					{
						ready = 1;
#if ENABLE_LED == TRUE
						ledpause = 0x2FFF;
						ledcycle = 0;
						PORTC |= (1<<PORTC4);
						PORTB |= (1<<PORTB1);
						if(MODE == 1) ledmode =1;
						if(MODE == 2) ledmode =2;
#endif
#if PPM_OUTPUT == TRUE						
						TCCR1B |= TIMER1_PRESCALER_BITS;
#endif						
#if SPEKTRUM_OUTPUT == TRUE
						send_sp = 1;
#endif
					}
				}
				else
				{
#if RSSI_OUTPUT == TRUE				
					OCR2A=0;
#endif					
					if(ready == 1)
					{
						ready = 0;
#if ENABLE_LED == TRUE
						ledpause = 0x2FFF;
						ledcycle = 0;
						PORTC |= (1<<PORTC4);
						PORTB |= (1<<PORTB1);
						if(MODE == 1) ledmode =3;
#endif						
						if(MODE == 2)
						{ 
#if SPEKTRUM_OUTPUT == TRUE
							send_sp = 0;
#endif
#if ENABLE_LED == TRUE
							ledmode =4;
#endif
#if PPM_OUTPUT == TRUE						
							TCCR1B &= (~(1<<CS12)) & (~(1<<CS11)) & (~(1<<CS10));
#endif						
						}
					}
				}
				
#if SPEKTRUM_OUTPUT == TRUE
				
				if(send_sp == 1)
				{
					//115200
					uint16_t ubrr = (uint16_t) ((uint32_t) F_CPU/(8 * 115200) - 1);
					UBRRH = (uint8_t)(ubrr>>8);
					UBRRL = (uint8_t)ubrr;
					UCSRA |= (1 << U2X);
					//8N1
					UCSRC &= ~(1 << UPM1);
					UCSRC &= ~(1 << UPM0);
					UCSRC &= ~(1 << USBS);
					UCSRB &= ~(1 << UCSZ2);
					UCSRC |=  (1 << UCSZ1);
					UCSRC |=  (1 << UCSZ0);

					_delay_ms(2);


					if(spektrum_frame == 0)
					{
						spektrum_frame=1;

						USART_putc(0);
						USART_putc(0);
#if SPEKTRUM_TYPE == SPEKTRUM_NORMAL
						USART_putc( ((uint8_t)((channels[0] >> 9)&0x03)) + (0 << 2)  );
						USART_putc(  ((uint8_t)(channels[0] >> 1)) );
						USART_putc( ((uint8_t)((channels[1] >> 9)&0x03)) + (1 << 2)  );
						USART_putc(  ((uint8_t)(channels[1] >> 1)) );
						USART_putc( ((uint8_t)((channels[2] >> 9)&0x03)) + (2 << 2)  );
						USART_putc(  ((uint8_t)(channels[2] >> 1)) );
						USART_putc( ((uint8_t)((channels[3] >> 9)&0x03)) + (3 << 2)  );
						USART_putc(  ((uint8_t)(channels[3] >> 1)) );
						USART_putc( ((uint8_t)((channels[4] >> 9)&0x03)) + (4 << 2)  );
						USART_putc(  ((uint8_t)(channels[4] >> 1)) );
						USART_putc( ((uint8_t)((channels[5] >> 9)&0x03)) + (5 << 2)  );
						USART_putc(  ((uint8_t)(channels[5] >> 1)) );
						USART_putc( ((uint8_t)((channels[6] >> 9)&0x03)) + (6 << 2)  );
						USART_putc(  ((uint8_t)(channels[6] >> 1)) );
#endif    	                
#if SPEKTRUM_TYPE == SPEKTRUM_HIRES
						USART_putc( ((uint8_t)((channels[0] >> 8)&0x07)) + (0 << 3)  );
						USART_putc(  ((uint8_t)(channels[0])) );
						USART_putc( ((uint8_t)((channels[1] >> 8)&0x07)) + (1 << 3)  );
						USART_putc(  ((uint8_t)(channels[1])) );
						USART_putc( ((uint8_t)((channels[2] >> 8)&0x07)) + (2 << 3)  );
						USART_putc(  ((uint8_t)(channels[2])) );
						USART_putc( ((uint8_t)((channels[3] >> 8)&0x07)) + (3 << 3)  );
						USART_putc(  ((uint8_t)(channels[3])) );
						USART_putc( ((uint8_t)((channels[4] >> 8)&0x07)) + (4 << 3)  );
						USART_putc(  ((uint8_t)(channels[4])) );
						USART_putc( ((uint8_t)((channels[5] >> 8)&0x07)) + (5 << 3)  );
						USART_putc(  ((uint8_t)(channels[5])) );
						USART_putc( ((uint8_t)((channels[6] >> 8)&0x07)) + (6 << 3)  );
						USART_putc(  ((uint8_t)(channels[6])) );
#endif    	                
					}
					else
					{
示例#6
0
int wmain(
	int argc, 
	wchar_t* argv[])
{
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
int main(
	int argc, 
	char *argv[])
{
#endif

//Get commands.
	if (argc > 0)
	{
		if (!ReadCommand(argc, argv))
			return EXIT_SUCCESS;
	}
	else {
		return EXIT_FAILURE;
	}

//Read configuration file.
	if (!ReadParameter(true))
		return EXIT_FAILURE;

//DNSCurve initialization
#if defined(ENABLE_LIBSODIUM)
	if (Parameter.DNSCurve)
	{
		DNSCurveParameterModificating.SetToMonitorItem();

	//Encryption mode initialization
		if (DNSCurveParameter.IsEncryption)
			DNSCurveInit();
	}
#endif

//Mark Local DNS address to PTR Records, read Parameter(Monitor mode), IPFilter and Hosts.
	ParameterModificating.SetToMonitorItem();
	std::thread NetworkInformationMonitorThread(std::bind(NetworkInformationMonitor));
	NetworkInformationMonitorThread.detach();
	std::thread ReadParameterThread(std::bind(ReadParameter, false));
	ReadParameterThread.detach();
	std::thread ReadHostsThread(std::bind(ReadHosts));
	ReadHostsThread.detach();
	if (Parameter.OperationMode == LISTEN_MODE_CUSTOM || Parameter.DataCheck_Blacklist || Parameter.LocalRouting)
	{
		std::thread ReadIPFilterThread(std::bind(ReadIPFilter));
		ReadIPFilterThread.detach();
	}

#if defined(PLATFORM_WIN)
//Service initialization and start service.
	SERVICE_TABLE_ENTRYW ServiceTable[]{{SYSTEM_SERVICE_NAME, (LPSERVICE_MAIN_FUNCTIONW)ServiceMain}, {nullptr, nullptr}};
	if (!StartServiceCtrlDispatcherW(ServiceTable))
	{
		GlobalRunningStatus.Console = true;
		auto ErrorCode = GetLastError();
		
	//Print to screen.
		std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
		fwprintf_s(stderr, L"System Error: Service start error, error code is %lu.\n", ErrorCode);
		fwprintf_s(stderr, L"System Error: Program will continue to run in console mode.\n");
		fwprintf_s(stderr, L"Please ignore these error messages if you want to run in console mode.\n\n");
		ScreenMutex.unlock();

	//Handle the system signal and start all monitors.
		SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
		MonitorInit();
	}
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	MonitorInit();
#endif

	return EXIT_SUCCESS;
}

//Read commands from main program
#if defined(PLATFORM_WIN)
bool __fastcall ReadCommand(
	int argc, 
	wchar_t *argv[])
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
bool ReadCommand(
	int argc, 
	char *argv[])
#endif
{
//Path initialization
#if defined(PLATFORM_WIN)
	if (!FileNameInit(argv[0]))
		return false;
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	char FileName[PATH_MAX + 1U] = {0};
	if (getcwd(FileName, PATH_MAX) == nullptr)
	{
		std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
		fwprintf(stderr, L"Path initialization error.\n");

		return false;
	}
	if (!FileNameInit(FileName))
		return false;
#endif

//Screen output buffer setting
	if (setvbuf(stderr, NULL, _IONBF, 0) != 0)
	{
		auto ErrorCode = errno;
		std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
		fwprintf_s(stderr, L"Screen output buffer setting error, error code is %d.\n", ErrorCode);
		ScreenLock.unlock();
		PrintError(LOG_LEVEL_2, LOG_ERROR_NETWORK, L"Screen output buffer setting error", ErrorCode, nullptr, 0);

		return false;
	}

//Winsock initialization
#if defined(PLATFORM_WIN)
	WSAData WSAInitialization = {0};
	if (WSAStartup(MAKEWORD(WINSOCK_VERSION_HIGH, WINSOCK_VERSION_LOW), &WSAInitialization) != 0 || 
		LOBYTE(WSAInitialization.wVersion) != WINSOCK_VERSION_LOW || HIBYTE(WSAInitialization.wVersion) != WINSOCK_VERSION_HIGH)
	{
		auto ErrorCode = WSAGetLastError();
		std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
		fwprintf_s(stderr, L"Winsock initialization error, error code is %d.\n", ErrorCode);
		ScreenLock.unlock();
		PrintError(LOG_LEVEL_1, LOG_ERROR_NETWORK, L"Winsock initialization error", ErrorCode, nullptr, 0);

		return false;
	}
	else {
		GlobalRunningStatus.Initialization_WinSock = true;
	}

//Read commands.
	std::wstring Commands;
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	std::string Commands;
#endif
	for (size_t Index = 1U;(SSIZE_T)Index < argc;++Index)
	{
		Commands = argv[Index];

	//Flush DNS Cache from user.
		if (Commands == COMMAND_FLUSH_DNS)
		{
		#if defined(PLATFORM_WIN)
			FlushDNSMailSlotSender();
		#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
			FlushDNSFIFOSender();
		#endif

			return false;
		}
	//Windows Firewall Test in first start.
	#if defined(PLATFORM_WIN)
		else if (Commands == COMMAND_FIREWALL_TEST)
		{
			if (!FirewallTest(AF_INET6) && !FirewallTest(AF_INET))
			{
				auto ErrorCode = WSAGetLastError();
				std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
				fwprintf_s(stderr, L"Windows Firewall Test error, error code is %d.\n", ErrorCode);
				ScreenMutex.unlock();
				PrintError(LOG_LEVEL_2, LOG_ERROR_NETWORK, L"Windows Firewall Test error", ErrorCode, nullptr, 0);
			}

			return false;
		}
	#endif
	//Set system daemon.
	#if defined(PLATFORM_LINUX)
		else if (Commands == COMMAND_DISABLE_DAEMON)
		{
			GlobalRunningStatus.Daemon = false;
		}
	#endif
	//Print current version.
		else if (Commands == COMMAND_LONG_PRINT_VERSION || Commands == COMMAND_SHORT_PRINT_VERSION)
		{
			std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
			fwprintf_s(stderr, L"Pcap_DNSProxy ");
			fwprintf_s(stderr, FULL_VERSION);
			fwprintf_s(stderr, L"\n");

			return false;
		}
	//Print library version.
		else if (Commands == COMMAND_LIB_VERSION)
		{
			std::unique_lock<std::mutex> ScreenMutex(ScreenLock);

		#if (defined(ENABLE_LIBSODIUM) || defined(ENABLE_PCAP))
			std::wstring LibVersion;

			//LibSodium version
			#if defined(ENABLE_LIBSODIUM)
				if (MBSToWCSString(SODIUM_VERSION_STRING, strlen(SODIUM_VERSION_STRING), LibVersion))
					fwprintf_s(stderr, L"LibSodium version %ls\n", LibVersion.c_str());
			#endif

			//WinPcap or LibPcap version
			#if defined(ENABLE_PCAP)
				if (MBSToWCSString(pcap_lib_version(), strlen(pcap_lib_version()), LibVersion))
					fwprintf_s(stderr, L"%ls\n", LibVersion.c_str());
			#endif
		#else
			fwprintf(stderr, L"No any available libraries.\n");
		#endif

			return false;
		}
	//Print help messages.
		else if (Commands == COMMAND_LONG_HELP || Commands == COMMAND_SHORT_HELP)
		{
			std::unique_lock<std::mutex> ScreenMutex(ScreenLock);

			fwprintf_s(stderr, L"Pcap_DNSProxy ");
			fwprintf_s(stderr, FULL_VERSION);
		#if defined(PLATFORM_WIN)
			fwprintf_s(stderr, L"(Windows)\n");
		#elif defined(PLATFORM_OPENWRT)
			fwprintf(stderr, L"(OpenWrt)\n");
		#elif defined(PLATFORM_LINUX)
			fwprintf(stderr, L"(Linux)\n");
		#elif defined(PLATFORM_MACX)
			fwprintf(stderr, L"(Mac)\n");
		#endif
			fwprintf_s(stderr, COPYRIGHT_MESSAGE);
			fwprintf_s(stderr, L"\nUsage: Please visit ReadMe... files in Documents folder.\n");
			fwprintf_s(stderr, L"   -v/--version:          Print current version on screen.\n");
			fwprintf_s(stderr, L"   --lib-version:         Print current version of libraries on screen.\n");
			fwprintf_s(stderr, L"   -h/--help:             Print help messages on screen.\n");
			fwprintf_s(stderr, L"   --flush-dns:           Flush all DNS cache in program and system immediately.\n");
		#if defined(PLATFORM_WIN)
			fwprintf_s(stderr, L"   --first-setup:         Test local firewall.\n");
		#endif
			fwprintf_s(stderr, L"   -c/--config-file Path: Set path of configuration file.\n");
		#if defined(PLATFORM_LINUX)
			fwprintf(stderr, L"   --disable-daemon:      Disable daemon mode.\n");
		#endif

			return false;
		}
	//Set working directory from commands.
		else if (Commands == COMMAND_LONG_SET_PATH || Commands == COMMAND_SHORT_SET_PATH)
		{
		//Commands check
			if ((SSIZE_T)Index + 1 >= argc)
			{
				std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
				fwprintf(stderr, L"Commands error.\n");
				ScreenMutex.unlock();
				PrintError(LOG_LEVEL_1, LOG_ERROR_SYSTEM, L"Commands error", 0, nullptr, 0);

				return false;
			}
			else {
				++Index;
				Commands = argv[Index];

			//Path check.
				if (Commands.length() > MAX_PATH)
				{
					std::unique_lock<std::mutex> ScreenMutex(ScreenLock);
					fwprintf_s(stderr, L"Commands error.\n");
					ScreenLock.unlock();
					PrintError(LOG_LEVEL_1, LOG_ERROR_SYSTEM, L"Commands error", 0, nullptr, 0);

					return false;
				}
				else {
					if (!FileNameInit(Commands.c_str()))
						return false;
				}
			}
		}
	}

//Set system daemon.
#if defined(PLATFORM_LINUX)
	if (GlobalRunningStatus.Daemon && daemon(0, 0) == RETURN_ERROR)
	{
		PrintError(LOG_LEVEL_2, LOG_ERROR_SYSTEM, L"Set system daemon error", 0, nullptr, 0);
		return false;
	}
#endif

	return true;
}

//Get path of program from the main function parameter and Winsock initialization
#if defined(PLATFORM_WIN)
bool __fastcall FileNameInit(
	const wchar_t *OriginalPath)
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
bool FileNameInit(
	const char *OriginalPath)
#endif
{
//Path process
#if defined(PLATFORM_WIN)
	GlobalRunningStatus.Path_Global->clear();
	GlobalRunningStatus.Path_Global->push_back(OriginalPath);
	GlobalRunningStatus.Path_Global->front().erase(GlobalRunningStatus.Path_Global->front().rfind(L"\\") + 1U);
	for (size_t Index = 0;Index < GlobalRunningStatus.Path_Global->front().length();++Index)
	{
		if ((GlobalRunningStatus.Path_Global->front()).at(Index) == L'\\')
		{
			GlobalRunningStatus.Path_Global->front().insert(Index, L"\\");
			++Index;
		}
	}
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	GlobalRunningStatus.sPath_Global->clear();
	GlobalRunningStatus.sPath_Global->push_back(OriginalPath);
	GlobalRunningStatus.sPath_Global->front().append("/");
	std::wstring StringTemp;
	if (!MBSToWCSString(OriginalPath, PATH_MAX + 1U, StringTemp))
		return false;
	StringTemp.append(L"/");
	GlobalRunningStatus.Path_Global->clear();
	GlobalRunningStatus.Path_Global->push_back(StringTemp);
	StringTemp.clear();
#endif

//Get path of error/running status log file and mark start time.
	GlobalRunningStatus.Path_ErrorLog->clear();
	*GlobalRunningStatus.Path_ErrorLog = GlobalRunningStatus.Path_Global->front();
	GlobalRunningStatus.Path_ErrorLog->append(L"Error.log");
#if (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	GlobalRunningStatus.sPath_ErrorLog->clear();
	*GlobalRunningStatus.sPath_ErrorLog = GlobalRunningStatus.sPath_Global->front();
	GlobalRunningStatus.sPath_ErrorLog->append("Error.log");
#endif
	Parameter.PrintLogLevel = DEFAULT_LOG_LEVEL;
	GlobalRunningStatus.StartupTime = time(nullptr);

	return true;
}
int main(int argc, char **argv) {
    if (argc == 1)
        PrintHelpInfo();
    else {
        if (!ReadParameter(argc, argv)) {
            std::cerr << "Bad Parameters.\n";
            return 1;
        }
        ReadConfig(configFileName);
        if (compress) {
            // Compress
            db_compress::Compressor compressor(outputFileName, schema, config);
            int iter_cnt = 0;
            while (1) {
                std::cout << "Iteration " << ++iter_cnt << " Starts\n";
                std::ifstream inFile(inputFileName);
                std::string str;
                int tuple_cnt = 0;
                while (std::getline(inFile,str)) {
                    std::stringstream sstream(str);
                    std::string item;
                    db_compress::Tuple tuple(schema.attr_type.size());

                    size_t count = 0;
                    while (std::getline(sstream, item, ',')) {
                        AppendAttr(&tuple, item, attr_type[count], count);
                        ++ count;
                    }
                    // The last item might be empty string
                    if (str[str.length() - 1] == ',') {
                        AppendAttr(&tuple, "", attr_type[count], count);
                        ++ count;
                    }
                    if (count != attr_type.size()) {
                        std::cerr << "File Format Error!\n";
                    }
                    compressor.ReadTuple(tuple);
                    if (!compressor.RequireFullPass() && 
                        ++ tuple_cnt >= NonFullPassStopPoint) {
                        break;
                    }
                }
                compressor.EndOfData();
                if (!compressor.RequireMoreIterations()) 
                    break;
            }
        } else {
            // Decompress
            db_compress::Decompressor decompressor(inputFileName, schema);
            std::ofstream outFile(outputFileName);
            decompressor.Init();
            while (decompressor.HasNext()) {
                db_compress::Tuple tuple(attr_type.size());
                decompressor.ReadNextTuple(&tuple);
                for (size_t i = 0; i < attr_type.size(); ++i) {
                    std::string str = ExtractAttr(tuple, attr_type[i], i);
                    outFile << str << (i == attr_type.size() - 1 ? '\n' : ',');
                } 
            }
        }
    }
    return 0;
}