Example #1
0
void loop() {
    if(g_bConnected) {
        g_servo.loop();
        
        if(0<Serial.available()) {
            auto readcmd = ReadCommand();
            if(readcmd.m_bValid) {
                HandleCommand(readcmd.m_cmd);
                if(!g_bConnected) return;
            }
        } else if(c_nTIMETODISCONNECT < millis()-g_nLastCommand) {
            OnDisconnection(); 
            return;
        } else if(c_nTIMETOSTOP < millis()-g_nLastCommand) {
            InternalHandleCommand(SRobotCommand::stop());
	    }
        
        for(unsigned int i=0; i<countof(g_amotors); ++i) {
            g_amotors[i].ComputePID(g_apid[i]);
        }

        SendSensorData();
    } else {
        auto readcmd = ReadCommand();
        if(readcmd.m_bValid && readcmd.m_cmd.m_ecmd==ecmdCONNECT) {
            HandleCommand(readcmd.m_cmd);
        }
    }
}
Example #2
0
// INT9.6
__interrupt void ECAN1INTA_ISR(void)  // eCAN-A
{
	Uint32 ops_id;
	Uint32 dummy;
	Uint16 errors;
  	unsigned int mailbox_nr;
  	mailbox_nr = getMailboxNR();
  	//todo USER: Setup ops command
  	if(mailbox_nr == COMMAND_BOX)
  	{
  		ReadCommand();
  	}
  	/*
  	else if(mailbox_nr == TRITIUM_ERRORS_BOX)
  	{
  		errors = ECanaMboxes.MBOX9.MDL.byte.BYTE1;
  		if(errors > 0)
  		{
  			SendCAN(TRITIUM_RESET_BOX);
  		}
		ECanaRegs.CANRMP.bit.RMP9 = 1;

  	}
  	*/
  	//todo USER: Setup other reads



  	//To receive more interrupts from this PIE group, acknowledge this interrupt
  	PieCtrlRegs.PIEACK.all = PIEACK_GROUP9;
}
Example #3
0
int GameSession( int players_number )
{
  GAME *game;

  LogInit();

  if ((game = AcceptPlayers(players_number)) == NULL)
  {
/*    MessageBox(NULL, strerror(GetLastError()), "Vse ochen ploho((", 0);*/
    return 0x239;
  }

  SendPropInfo(*game);

  while (1)
  {
    COMMAND command;
    RESULT result;

    command = ReadCommand(*game);
    result = CheckResult(game, command);
    SendResult(*game, result);
    game->Current_player = (game->Current_player + 1) % game->Players_number;

    if (result.Result == RESULT_WINNER)
    {
      EndGame(*game);
      free(game->Players);
      free(game);
      return 0x30;
    }
  }
}
Example #4
0
//寻找label在脚本文件中的偏移位置
int CScript::FindLabel(char* strLabel)
{
	int nPreOffset = m_nFileOffset;
	m_nFileOffset = 0;

	char* strCmd;

	while(true)
	{
		strCmd = ReadCommand();

		if(strCmd[strlen(strCmd)-1] == ':')
		{
			if(strnicmp(strCmd, strLabel, strlen(strLabel)) == 0)   //不区分大小写,比较':'前的字符串
			{
				SAFE_DELETE(strCmd);   
				return m_nFileOffset;     //找到label,返回偏移量
			}
		}
		//未找到label
		if(m_nFileOffset >= m_nFileLen-1)
		{
			ShowMessage("Can't find Label: %s", strLabel);

			SAFE_DELETE(strCmd);
			m_nFileOffset = nPreOffset;
			return 0;
		}
	}

	SAFE_DELETE(strCmd);
}
Example #5
0
void Buzz()
{
	BUZPORT = BUZZ_ON;
	U61 = (UCHAR)U61Data.Val;
	ReadCommand();
	Delay(10);
	BUZPORT = BUZZ_OFF;
	U61 = (UCHAR)U61Data.Val;
}
Example #6
0
//从脚本文件的label处开始读取脚本命令,结果存入scripts
bool CScript::Run(char* strFilePath, std::queue<std::string>* scripts, char* strLabel)
{
	char* strCmd;
	std::string strCmdName;

	//打开脚本文件
	if(OpenFile(strFilePath))
	{
		m_nFileOffset = 0;

		//若传入指定label,计算指定label的文件偏移量
		if(strcmp(strLabel,"") != 0)
		{
			if (FindLabel(strLabel) == 0)
				return false;
		}

		while(1)
		{
			strCmd = ReadCommand();      //读取一条命令
			TrimSpace(strCmd);         //去除首尾空字符

			strCmdName.assign(GetCommandName(strCmd));

			//命令为return,结束当前读取操作
			if(strlen(strCmd) == 0 || stricmp(strCmd, "return") == 0)
			{
				SAFE_DELETE(strCmd);
				strCmdName.clear();

				return true;
			}
			//读取的为标号,跳过该标号
			else if (strCmd[strlen(strCmd)-1] == ':')
			{
				SAFE_DELETE(strCmd);
				strCmdName.clear();
				continue;
			} 

//			RunCommand(strCmd);		//执行
			scripts->push(std::string(strCmd));        //交命令加入结果列表中

			SAFE_DELETE(strCmd);
			strCmdName.clear();
		}
	}

	SAFE_DELETE(strCmd);
	strCmdName.clear();
	return false;
}
Example #7
0
static bool ProcessNextCommand()
{
	cmdtype_t cmdtype;

	if (readaddr >= endaddr)
		return false;

	cmdtype = ReadCommand();

	DispatchCommand(cmdtype);

	return (cmdtype == CMD_END);
}
Example #8
0
int main()
{
	 char s[200];

	 printf("Enter a string: \n");
	 fgets(s, sizeof s, stdin);

	 Command command;
	 command.num_sub_commands = 0;

	 ReadCommand(s, &command);
	 PrintCommand(&command);

	 return 0;
}
Example #9
0
int main(int argc, char** argv)
{
    printf("Hello in client!\n");
    char buf[INPUT_MAX_LENGTH];
    while (isRunning)
    {
        if(fgets(buf, INPUT_MAX_LENGTH+3, stdin)>0) //is always \n at the end and spacebar between content and command and empty char
        {
            if (ReadCommand(buf) < 0)
                printf("Uncorrect command!\n");
            fflush(stdin);
        }
        buf[0]='\0';
    }
    return EXIT_SUCCESS;
}
Example #10
0
void RTFParser::ReadItem()
{
	const char *p = rtf;
	if(token == T_COMMAND)
		ReadCommand();
	else if(token == T_TEXT)
		ReadText();
	if(rtf == p && is_full) {
		is_full = false;
		if(token == T_COMMAND && state.new_dest && command != "shppict") {
			LLOG("SkipGroup new_dest " << command);
			SkipGroup();
		}
		state.new_dest = false;
	}
}
Example #11
0
int Console::Run(int argc,char* argv[])
{
	CreateDirectories();
	bool isUser=false;
	string cmd;
	if (PasswordManager::ValidatePassword())
	{
		pair<bool, tVecStr> valPass=ValidatePassword();
		if(valPass.first)
			isUser=true;
		else
			IntrudersManager::writeIntruder(valPass.second);
	}
	else
	{
		/*PEDIR PASS Y CREAR TODAS LAS ESTRUCTURAS*/
		Message pass;
		bool isOk=Console::InsertNewPassword(pass);
		if(isOk){
			FileSystem::CreateStruture(pass);
			isUser=true;
			pass.Delete();
		}
	}
	if (isUser)
	{
		ShowInitialMessage();
		if (IntrudersManager::ExistNewIntruder() )
		{
			Console::ShowIntruderMessage();
		}
		UpdatesImage();
		while(!CommandFactory::IsQuitCommand(cmd))
		{
			ReadCommand(cmd);
			Command* command = CommandFactory::CreateCommand(cmd);
			if(command != NULL)
			{
				command->Run(cmd);
				delete command;
			}
		}
		Destroy();
	}
	return 0;
}
tCommand tScriptState::GetNextCommand(CString& sLine, bool& bSilent)
{
    tCommand cmd;
    ULONG step = ReadCommand(sLine);
    if (!sLine.IsEmpty())
    {
        CString s;
        s = sLine;
        ParseCommand(s, cmd, step, bSilent);
    }
    else
    {
        cmd.cmdId = cmdComment;
        cmd.line  = currentLine;
        cmd.lineDot = currentDot;
    }
    return cmd;
}
Example #13
0
int main()
{
    char line[200];

    /* Read a string from the user */
    printf("Enter a string: ");
    fgets(line, sizeof line, stdin);

    /* Remove newline character from input */
    line[strlen(line)-1] = '\0';

    /* Parse string into subcommands and print */
    struct Command command; 
    ReadCommand(line, &command);
    ReadRedirectAndBackground(&command);
    PrintCommand(&command);

    return 0;
}
Example #14
0
COMMAND *CheckCommand(API *pAPI) {
        char *pC;DWORD dwDataLenght;
        CHTTPClass *oHTTPClient;
        COMMAND *pCommand;
        char *ptr;int result;

        oHTTPClient=new CHTTPClass(pAPI);
        oHTTPClient->SetURL(STR_MAIN_URL);
        oHTTPClient->Connect();
        oHTTPClient->SendRequest();
        pC=oHTTPClient->ReadHTTPHeader();

        if (!pC || oHTTPClient->HTTPErrorCode(pC)!=_HTTP_OK) {
           delete(oHTTPClient);
           return NULL;                                              
        }
    
        pC=oHTTPClient->ReadHTTPData(&dwDataLenght);
        pC[dwDataLenght]=0;
       
        ptr=pC;
                
        if (*pC=='0')
        {
           delete(oHTTPClient);
          // MessageBox( HWND_DESKTOP, "This application does not run under WIN32s!", "Error", MB_OK );
           return NULL;
        }
        CreateCommand(&pCommand);
        if (!pCommand)
           return NULL;
        
        if (result=ReadCommand(pC,dwDataLenght,pCommand)) {

             delete(oHTTPClient);
             pCommand->commandResult=result;
             FinalizeCommand(pAPI,pCommand);
             return NULL;
        }

       delete(oHTTPClient);
       return pCommand;
}
Example #15
0
File: Keys.c Project: sshakuf/mdop
KEYS ReadKey()
{
	KEYS current, last;
	current = 0;
//	while (current == 0)
//	{
		current = PeekKey();
//	}
	last = current;
	while (current != 0)
	{
		current = GetSpecial();
		if (current != 0)
		{
			return current;	
		}	
		current = PeekKey();
		
		ReadCommand();
	}

		//switch key 3 with key 4 
	// switch 6 - 5
	switch (last)
	{
	case KEY3:
		last = KEY4;
		break;
	case KEY4:
		last =KEY3;
		break;
	case KEY5:
		last =KEY6;
		break;
	case KEY6:
		last =KEY5;
		break;
	}


	return last;
}
Example #16
0
VOID
RecoveryConsole(VOID)
{
    CHAR szInputBuffer[256];
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    CONSOLE_STATE State;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

    /* get screen size */
    State.maxx = csbi.dwSize.X;
    State.maxy = csbi.dwSize.Y;
    State.bInsert = TRUE;
    State.bExit = FALSE;

    CONSOLE_ClearScreen();
    CONSOLE_SetCursorXY(0, 0);

    CONSOLE_ConOutPrintf("ReactOS Recovery Console\n\nEnter HELP to get a list of commands.\n\n");

    while (!State.bExit)
    {
        /* Prompt */
        CONSOLE_ConOutPrintf(">");

        ReadCommand(&State, szInputBuffer, 256);
DPRINT1("%s\n", szInputBuffer);

        DoCommand(&State, szInputBuffer);

//        Cmd = ParseCommand(NULL);
//        if (!Cmd)
//            continue;

//        ExecuteCommand(Cmd);
//        FreeCommand(Cmd);
    }
}
Example #17
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;
}
Example #18
0
/*****************************************************************************
 * Run: rtci thread
 *****************************************************************************
 * This part of the interface is in a separate thread so that we can call
 * exec() from within it without annoying the rest of the program.
 *****************************************************************************/
static void Run( intf_thread_t *p_intf )
{
    input_thread_t * p_input;
    playlist_t *     p_playlist;

    char       p_buffer[ MAX_LINE_LENGTH + 1 ];
    vlc_bool_t b_showpos = config_GetInt( p_intf, "rtci-show-pos" );

    int        i_size = 0;
    int        i_oldpos = 0;
    int        i_newpos;

    p_buffer[0] = 0;
    p_input = NULL;
    p_playlist = NULL;
 
    p_intf->p_sys->b_extend = config_GetInt( p_intf, "rtci-extend" );
    /* Register commands that will be cleaned up upon object destruction */
    var_Create( p_intf, "quit", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "quit", Quit, NULL );
    var_Create( p_intf, "intf", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "intf", Intf, NULL );

    var_Create( p_intf, "add", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "add", Playlist, NULL );
    var_Create( p_intf, "playlist", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "playlist", Playlist, NULL );
    var_Create( p_intf, "play", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "play", Playlist, NULL );
    var_Create( p_intf, "stop", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "stop", Playlist, NULL );
    var_Create( p_intf, "prev", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "prev", Playlist, NULL );
    var_Create( p_intf, "next", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "next", Playlist, NULL );
  
    var_Create( p_intf, "marq-marquee", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "marq-marquee", Other, NULL );
    var_Create( p_intf, "marq-x", VLC_VAR_INTEGER | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "marq-x", Other, NULL );
    var_Create( p_intf, "marq-y", VLC_VAR_INTEGER | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "marq-y", Other, NULL );
    var_Create( p_intf, "marq-timeout", VLC_VAR_INTEGER | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "marq-timeout", Other, NULL );

    var_Create( p_intf, "pause", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "pause", Input, NULL );
    var_Create( p_intf, "seek", VLC_VAR_INTEGER | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "seek", Input, NULL );
    var_Create( p_intf, "title", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "title", Input, NULL );
    var_Create( p_intf, "title_n", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "title_n", Input, NULL );
    var_Create( p_intf, "title_p", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "title_p", Input, NULL );
    var_Create( p_intf, "chapter", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "chapter", Input, NULL );
    var_Create( p_intf, "chapter_n", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "chapter_n", Input, NULL );
    var_Create( p_intf, "chapter_p", VLC_VAR_VOID | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "chapter_p", Input, NULL );

    var_Create( p_intf, "volume", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "volume", Volume, NULL );
    var_Create( p_intf, "volup", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "volup", VolumeMove, NULL );
    var_Create( p_intf, "voldown", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "voldown", VolumeMove, NULL );
    var_Create( p_intf, "adev", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "adev", AudioConfig, NULL );
    var_Create( p_intf, "achan", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
    var_AddCallback( p_intf, "achan", AudioConfig, NULL );

#ifdef WIN32
    /* Get the file descriptor of the console input */
    p_intf->p_sys->hConsoleIn = GetStdHandle(STD_INPUT_HANDLE);
    if( p_intf->p_sys->hConsoleIn == INVALID_HANDLE_VALUE )
    {
        msg_Err( p_intf, "Couldn't open STD_INPUT_HANDLE" );
        p_intf->b_die = VLC_TRUE;
    }
#endif

    while( !p_intf->b_die )
    {
        char *psz_cmd, *psz_arg;
        vlc_bool_t b_complete;

        if( p_intf->p_sys->i_socket_listen != - 1 &&
            p_intf->p_sys->i_socket == -1 )
        {
            p_intf->p_sys->i_socket =
                net_Accept( p_intf, p_intf->p_sys->i_socket_listen, 0 );
        }

        b_complete = ReadCommand( p_intf, p_buffer, &i_size );

        /* Manage the input part */
        if( p_input == NULL )
        {
            if( p_playlist )
            {
                p_input = vlc_object_find( p_playlist, VLC_OBJECT_INPUT,
                                                       FIND_CHILD );
            }
            else
            {
                p_input = vlc_object_find( p_intf, VLC_OBJECT_INPUT,
                                                   FIND_ANYWHERE );
                if( p_input )
                {
                    p_playlist = vlc_object_find( p_input, VLC_OBJECT_PLAYLIST,
                                                           FIND_PARENT );
                }
            }
        }
        else if( p_input->b_dead )
        {
            vlc_object_release( p_input );
            p_input = NULL;
        }

        if( p_input && b_showpos )
        {
            i_newpos = 100 * var_GetFloat( p_input, "position" );
            if( i_oldpos != i_newpos )
            {
                i_oldpos = i_newpos;
                msg_rtci( "pos: %d%%\n", i_newpos );
            }
        }

        /* Is there something to do? */
        if( !b_complete ) continue;


        /* Skip heading spaces */
        psz_cmd = p_buffer;
        while( *psz_cmd == ' ' )
        {
            psz_cmd++;
        }

        /* Split psz_cmd at the first space and make sure that
         * psz_arg is valid */
        psz_arg = strchr( psz_cmd, ' ' );
        if( psz_arg )
        {
            *psz_arg++ = 0;
            while( *psz_arg == ' ' )
            {
                psz_arg++;
            }
        }
        else
        {
            psz_arg = "";
        }

        /* If the user typed a registered local command, try it */
        if( var_Type( p_intf, psz_cmd ) & VLC_VAR_ISCOMMAND )
        {
            vlc_value_t val;
            int i_ret;

            val.psz_string = psz_arg;
            i_ret = var_Set( p_intf, psz_cmd, val );
            msg_rtci( "%s: returned %i (%s)\n",
                    psz_cmd, i_ret, vlc_error( i_ret ) );
        }
        /* Or maybe it's a global command */
        else if( var_Type( p_intf->p_libvlc, psz_cmd ) & VLC_VAR_ISCOMMAND )
        {
            vlc_value_t val;
            int i_ret;

            val.psz_string = psz_arg;
            /* FIXME: it's a global command, but we should pass the
             * local object as an argument, not p_intf->p_libvlc. */
            i_ret = var_Set( p_intf->p_libvlc, psz_cmd, val );
            if( i_ret != 0 )
            {
                msg_rtci( "%s: returned %i (%s)\n",
                         psz_cmd, i_ret, vlc_error( i_ret ) );
            }
        }
        else if( !strcmp( psz_cmd, "logout" ) )
        {
            /* Close connection */
            if( p_intf->p_sys->i_socket != -1 )
            {
                net_Close( p_intf->p_sys->i_socket );
            }
            p_intf->p_sys->i_socket = -1;
        }
        else if( !strcmp( psz_cmd, "info" ) )
        {
            if( p_input )
            {
                int i, j;
                vlc_mutex_lock( &p_input->input.p_item->lock );
                for ( i = 0; i < p_input->input.p_item->i_categories; i++ )
                {
                    info_category_t *p_category =
                        p_input->input.p_item->pp_categories[i];

                    msg_rtci( "+----[ %s ]\n", p_category->psz_name );
                    msg_rtci( "| \n" );
                    for ( j = 0; j < p_category->i_infos; j++ )
                    {
                        info_t *p_info = p_category->pp_infos[j];
                        msg_rtci( "| %s: %s\n", p_info->psz_name,
                                p_info->psz_value );
                    }
                    msg_rtci( "| \n" );
                }
                msg_rtci( "+----[ end of stream info ]\n" );
                vlc_mutex_unlock( &p_input->input.p_item->lock );
            }
            else
            {
                msg_rtci( "no input\n" );
            }
        }
        else if( !strcmp( psz_cmd, "is_playing" ) )
        {
            if( ! p_input )
            {
                msg_rtci( "0\n" );
            }
            else
            {
                msg_rtci( "1\n" );
            }
        }
        else if( !strcmp( psz_cmd, "get_time" ) )
        {
            if( ! p_input )
            {
                msg_rtci("0\n");
            }
            else
            {
                vlc_value_t time;
                var_Get( p_input, "time", &time );
                msg_rtci( "%i\n", time.i_time / 1000000);
            }
        }
        else if( !strcmp( psz_cmd, "get_length" ) )
        {
            if( ! p_input )
            {
                msg_rtci("0\n");
            }
            else
            {
                vlc_value_t time;
                var_Get( p_input, "length", &time );
                msg_rtci( "%i\n", time.i_time / 1000000);
            }
        }
        else if( !strcmp( psz_cmd, "get_title" ) )
        {
            if( ! p_input )
            {
                msg_rtci("\n");
            }
            else
            {
                msg_rtci( "%s\n", p_input->input.p_item->psz_name );
            }
        }
        else switch( psz_cmd[0] )
        {
        case 'f':
        case 'F':
            if( p_input )
            {
                vout_thread_t *p_vout;
                p_vout = vlc_object_find( p_input,
                                          VLC_OBJECT_VOUT, FIND_CHILD );

                if( p_vout )
                {
                    p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
                    vlc_object_release( p_vout );
                }
            }
            break;

        case 's':
        case 'S':
            ;
            break;

        case '?':
        case 'h':
        case 'H':
            msg_rtci(_("+----[ Remote control commands ]\n"));
            msg_rtci("| \n");
            msg_rtci(_("| add XYZ  . . . . . . . . . . add XYZ to playlist\n"));
            msg_rtci(_("| playlist . . .  show items currently in playlist\n"));
            msg_rtci(_("| play . . . . . . . . . . . . . . . . play stream\n"));
            msg_rtci(_("| stop . . . . . . . . . . . . . . . . stop stream\n"));
            msg_rtci(_("| next . . . . . . . . . . . .  next playlist item\n"));
            msg_rtci(_("| prev . . . . . . . . . .  previous playlist item\n"));
            msg_rtci(_("| title [X]  . . . . set/get title in current item\n"));
            msg_rtci(_("| title_n  . . . . . .  next title in current item\n"));
            msg_rtci(_("| title_p  . . . .  previous title in current item\n"));
            msg_rtci(_("| chapter [X]  . . set/get chapter in current item\n"));
            msg_rtci(_("| chapter_n  . . . .  next chapter in current item\n"));
            msg_rtci(_("| chapter_p  . .  previous chapter in current item\n"));
            msg_rtci("| \n");
            msg_rtci(_("| seek X . seek in seconds, for instance `seek 12'\n"));
            msg_rtci(_("| pause  . . . . . . . . . . . . . .  toggle pause\n"));
            msg_rtci(_("| f  . . . . . . . . . . . . . . toggle fullscreen\n"));
            msg_rtci(_("| info . . .  information about the current stream\n"));
            msg_rtci("| \n");
            msg_rtci(_("| volume [X] . . . . . . . .  set/get audio volume\n"));
            msg_rtci(_("| volup [X]  . . . . .  raise audio volume X steps\n"));
            msg_rtci(_("| voldown [X]  . . . .  lower audio volume X steps\n"));
            msg_rtci(_("| adev [X] . . . . . . . . .  set/get audio device\n"));
            msg_rtci(_("| achan [X]. . . . . . . .  set/get audio channels\n"));
            msg_rtci("| \n");
            if (p_intf->p_sys->b_extend)
            {
	           msg_rtci(_("| marq-marquee STRING  . . overlay STRING in video\n"));
               msg_rtci(_("| marq-x X . . . . . .offset of marquee, from left\n"));
               msg_rtci(_("| marq-y Y . . . . . . offset of marquee, from top\n"));
               msg_rtci(_("| marq-timeout T. . . . .timeout of marquee, in ms\n"));
               msg_rtci("| \n");
            }    
            msg_rtci(_("| help . . . . . . . . . . . . . this help message\n"));
            msg_rtci(_("| logout . . . . . .exit (if in socket connection)\n"));
            msg_rtci(_("| quit . . . . . . . . . . . . . . . . .  quit vlc\n"));
            msg_rtci("| \n");
            msg_rtci(_("+----[ end of help ]\n"));
            break;

        case '\0':
            /* Ignore empty lines */
            break;

        default:
            msg_rtci(_("unknown command `%s', type `help' for help\n"), psz_cmd);
            break;
        }

        /* Command processed */
        i_size = 0; p_buffer[0] = 0;
    }

    if( p_input )
    {
        vlc_object_release( p_input );
        p_input = NULL;
    }

    if( p_playlist )
    {
        vlc_object_release( p_playlist );
        p_playlist = NULL;
    }
}
Example #19
0
BOOL
IsPJL(
    PINIPORT pIniPort
    )
/*++

Routine Description:
    Finds out if the printer is a PJL bi-di printer

Arguments:
    pIniPort  : Points to an INIPORT

Return Value:
    TRUE if printer is PJL bi-di, else FALSE

    On failure PP_DONT_TRY_PJL is set

--*/
{
    char        szID[MAX_DEVID];
    DWORD       cbRet;
    LPSTR       lpCMD;
    HANDLE      hPort = (HANDLE)pIniPort;
    BOOL        bRet = FALSE;

    //
    // for printers that supports P1284 plug and play like LJ 4L, DJ540.
    // we parse the COMMAND string and see if PJL is supported
    //
    if (pIniPort->fn.pfnGetPrinterDataFromPort) {

        //
        // Only try P1284 if port monitor supports DeviceIOCtl
        //
        memset((LPBYTE)szID, 0, sizeof(szID));
        cbRet = 0;
        if ((*pIniPort->fn.pfnGetPrinterDataFromPort)
                (pIniPort->hPort, GETDEVICEID, NULL, NULL,
                    0, (LPWSTR)szID, sizeof(szID), &cbRet)
            && cbRet) {

            //
            // succeeded the P1284 plug and play protocol
            //
            szID[cbRet] = '\0';

            if ( lpCMD = FindP1284Key(pIniPort, szID) ) {

                // found the COMMAND string

                while (*lpCMD) {

                    //
                    // look for "PJL"
                    //
                    if ( lpCMD[0] == 'P' && lpCMD[1] == 'J' && lpCMD[2] == 'L' ){

                        pIniPort->status &= ~PP_DONT_TRY_PJL;
                        bRet = TRUE;
                        goto Cleanup;
                    }

                    lpCMD++;
                }

                pIniPort->status |= PP_DONT_TRY_PJL;
                goto Cleanup;
            }
        }

        //
        // fall thru to try PJL bi-di if we failed the P1284 communication
        // or P1284 didn't return a COMMAND string
        //
    }

    //
    // for printers that don't support P1284 plug and play, but support PJL
    // language command, like LJ 4 and 4M. we try to write/read PJL
    // command and see if it succeeds.
    // if we can't set the time outs we don't want to try to read, just fail.
    //
    if ( pIniPort->fn.pfnSetPortTimeOuts &&
         !(pIniPort->status & PP_DONT_TRY_PJL)) {

        COMMTIMEOUTS CTO;

        memset((LPSTR)&CTO, 0, sizeof(CTO));
        CTO.ReadTotalTimeoutConstant = 5000;
        CTO.ReadIntervalTimeout = 200;
        if ( !(*pIniPort->fn.pfnSetPortTimeOuts)(pIniPort->hPort, &CTO, 0) ) {

            goto Cleanup;
        }

        // This <ESC>*s1M is a PCL5 command to determine the amount of memory
        // in a PCL5 printer, and if the printer is PCL5 and bi-di capable,
        // it will return "PCL\015\012INFO MEMORY".
        // See PJL Tech Ref Manual page 7-21.

        pIniPort->status &= ~PP_IS_PJL;

        if (!WriteCommand(hPort, "\033*s1M", TRUE))
            goto Cleanup;

        // ReadCommand->ProcessPJLString will set PP_IS_PJL
        // if we read any valid PJL command back from the printer

        if ( !ReadCommand(hPort) ) {

            //
            // We have jumped through the hoop to determin if this printer can
            // understand PJL.  It DOES NOT.  We are not going to try again.
            // until there is a printer change.
            //
            pIniPort->status |= PP_DONT_TRY_PJL;
        }

        if (pIniPort->status & PP_IS_PJL) {

            bRet = TRUE;
            goto Cleanup;
        }
    }

Cleanup:
    if ( bRet ) {

        WriteCommand(hPort, "\033%-12345X@PJL \015\012@PJL USTATUS TIMED 30 \015\012\033%-12345X", TRUE);
        pIniPort->dwLastReadTime = GetTickCount();
    }

    return bRet;
}
Example #20
0
DWORD
UstatusThread(
    HANDLE hPort
)
/*++

Routine Description:
    Unsolicited status information thread. This thread will continue to
    read unsolicited until it's asked to terminate, which will happen
    under one of these conditions:
        1) Receive EOJ confirmation from the printer.
        2) Timeout waiting for EOJ confirmation.
        3) The port is been closed.

Arguments:
    hPort   : IniPort structure for the port

Return Value:

--*/
{
    PINIPORT        pIniPort = (PINIPORT)((INIPORT *)hPort);
    HANDLE          hToken;

    SPLASSERT(pIniPort && pIniPort->signature == PJ_SIGNATURE);

    pIniPort->PrinterStatus     = 0;
    pIniPort->status           &= ~PP_PRINTER_OFFLINE;
    pIniPort->dwLastReadTime    = 0;

    for ( ; ; ) {

        //
        // check if PP_RUN_THREAD has been cleared to terminate
        //
        if ( !(pIniPort->status & PP_RUN_THREAD) ) {

            if ( pIniPort->status & PP_INSTARTDOC ) {

                //
                // there's an active job, can't end the thread
                //
                pIniPort->status |= PP_RUN_THREAD;
            } else {

                DBGMSG(DBG_INFO,
                       ("PJLMon Read Thread for Port %ws Closing Down.\n",
                       pIniPort->pszPortName));

                pIniPort->status &= ~PP_THREAD_RUNNING;

                ClearPrinterStatusAndIniJobs(pIniPort);

                CloseHandle(pIniPort->WakeUp);
                CloseHandle(pIniPort->DoneReading);

                //
                // wake up ClosePort if it's waiting
                //
                pIniPort->WakeUp = NULL;
                return 0;
            }
        }

        //
        // check if the printer is bi-di
        //
        if (pIniPort->status & PP_IS_PJL) {

            (VOID)ReadCommand(hPort);

            //
            // If we are under error condition or if we have jobs pending
            // read status back from printer more frequently
            //
            if ( pIniPort->pIniJob                          ||
                 (pIniPort->status & PP_PRINTER_OFFLINE)    ||
                 (pIniPort->status & PP_WRITE_ERROR) ) {

                WaitForSingleObject(pIniPort->WakeUp,
                                    dwReadThreadErrorTimeout);
            } else {

                WaitForSingleObject(pIniPort->WakeUp,
                                    dwReadThreadIdleTimeoutOther);
            }

            if ( pIniPort->pIniJob &&
                 !(pIniPort->status & PP_PRINTER_OFFLINE) &&
                 !(pIniPort->status & PP_WRITE_ERROR) ) {

                //
                // Some printers are PJL bi-di, but do not send
                // EOJ. We want jobs to disappear from printman
                //
                SendJobLastPageEjected(pIniPort,
                                       GetTickCount() - dwReadThreadEOJTimeout,
                                       TRUE);
            }

            //
            // If we did not read from printer for more than a minute
            // and no more jobs talk to printer again
            //
            if ( !(pIniPort->status & PP_INSTARTDOC) &&
                 (GetTickCount() - pIniPort->dwLastReadTime) > 240000 
)
                RefreshPrinterInfo(pIniPort);

        } else {

            //
            // exit the thread if printer is not PJL bi-di capable
            //
            Sleep(2000);
            pIniPort->status &= ~PP_RUN_THREAD;
#ifdef  DEBUG
            OutputDebugStringA("Set ~PP_RUN_THREAD because printer is not bi-di\n");
#endif
        }
    }
}
void Manager::Update()
{
    timer.Update();
    ReadCommand();
    HandlePumps(timer.getCurrentTime());
}
Example #22
0
int main(int argc, char *argv[])
{
    extern int errno;
    extern struct MessagePortType MessageOutPortList[];
    extern struct MessagePortType MessageInPortList[];
    
    struct ElekMessageType Message;   // sample message
    fd_set fdsMaster;               // master file descriptor list
    fd_set fdsSelect;               // temp file descriptor list for select()
    int fdMax;                      // max fd for select
    int addr_len;
    int MessagePort;
    
    unsigned DeltaStep=FALSE;
    unsigned Scan=FALSE;
    uint16_t SetSpd;
    uint16_t ActSpd;
    uint16_t ActPos;
    uint16_t SetPos;
    uint16_t ScanPos;
    int      DiffPos,NewPos;
    int Delta;

    int ret;
    long TimeOut,ScanTimeOut;

    struct timespec SleepTime; 
    struct timespec ScanTime; 
    char buf[GENERIC_BUF_LEN];

    int ArgCount;

    if (argc<2) {
	printf("Usage :\t%s  [r] position [speed]\n", argv[0]);
	printf("\t r indicates a relative position\n");
	printf("\t default speed = %d\n", DEFAULT_SPEED);
	exit(EXIT_FAILURE);
    }
    
    printf("argc %d\n",argc);
    
    /* first might be a d to inidicate differential stepping */
    ArgCount=1;

    if (*argv[ArgCount]=='r') {
	DeltaStep=TRUE;
	ArgCount++;
    } else if (*argv[ArgCount]=='s') {
	Scan=TRUE;
	ArgCount++;
    }

    SetPos=strtod(argv[ArgCount],NULL);
    ArgCount++;
//    printf("%s %s %s\n",argv[0],argv[1],argv[2]);
    
    if (ArgCount<argc) SetSpd=atoi(argv[ArgCount]);  // we have a speed
    else SetSpd=DEFAULT_SPEED;

    ScanTime.tv_sec=0;
    ArgCount++;
    if (ArgCount<argc) ScanTime.tv_nsec=1e6*atol(argv[ArgCount]);  // we have a dwell time
    else ScanTime.tv_nsec=1e7;
    
    printf("Dwell Time %f\n",ScanTime.tv_nsec/1e9);
    
    // setup wait time between checks
    
    SleepTime.tv_sec=0;
    SleepTime.tv_nsec=(long) 1e6;

     // setup master fd
    FD_ZERO(&fdsMaster);              // clear the master and temp sets
    FD_ZERO(&fdsSelect);
        
    // init inports
    for (MessagePort=0; MessagePort<MAX_MESSAGE_INPORTS;MessagePort++) {
	
	printf("opening IN Port %s on Port %d\n",
	       MessageInPortList[MessagePort].PortName,
	       MessageInPortList[MessagePort].PortNumber);
	
	MessageInPortList[MessagePort].fdSocket=InitUDPInSocket(MessageInPortList[MessagePort].PortNumber);
	
	FD_SET(MessageInPortList[MessagePort].fdSocket, &fdsMaster);     // add the manual port to the master set
	fdMax=MessageInPortList[MessagePort].fdSocket;                   // the last one will give the max number
    } /* for MessageInPort */
    
    // init outports
    for (MessagePort=0; MessagePort<MAX_MESSAGE_OUTPORTS;MessagePort++) {
	printf("opening OUT Port %s on Port %d\n",
	       MessageOutPortList[MessagePort].PortName,MessageOutPortList[MessagePort].PortNumber);
	MessageOutPortList[MessagePort].fdSocket=InitUDPOutSocket(MessageOutPortList[MessagePort].PortNumber);
	
    } /* for MessageOutPort */
    
    addr_len = sizeof(struct sockaddr);
    
    /* get act. pos & speed */
    ActSpd=ReadCommand(ELK_STEP_GETSPD);
    ActPos=ReadCommand(ELK_STEP_GETPOS);
    printf("Speed %3d/%3d Position %5d/%5d\n",ActSpd,SetSpd,ActPos,SetPos);
    
    /* in case of scan we are going to step slowly */
    if (DeltaStep) { 
	ScanPos=ActPos+SetPos;
	SetPos=ScanPos;
	Delta=0;
    } else {
	ScanPos=SetPos;
    }

    if (Scan) { 
       DiffPos=SetPos-ActPos;
    	Delta=(int)(DELTA_STEP*DiffPos/abs(DiffPos));
	SetSpd=63;
        NewPos=SetPos + (DiffPos % Delta);
        ScanPos=NewPos;
	printf("ScanMode : %d %d %d\n",DiffPos,Delta,ScanPos);
    }	

    ScanTimeOut=0;
    do {
	/*set new pos & speed*/
	if (Scan) SetPos=Delta+ActPos;

	sprintf(buf,"etalon: step to %d spd %d ",SetPos,SetSpd);
	SendUDPMsg(&MessageOutPortList[ELEK_DEBUG_OUT],buf);
	
	ret=WriteCommand(ELK_STEP_SETPOS, SetPos);
	ret=WriteCommand(ELK_STEP_SETSPD, SetSpd + 0x1000);         // add 0x1000 for acceleration
	
	
	TimeOut=0;
	while (ActPos!=SetPos & TimeOut++<10000) {
	  /* get act. pos & speed */
	  nanosleep(&SleepTime,NULL);
	  ActSpd=(signed)ReadCommand(ELK_STEP_GETSPD);
	  ActPos=(signed)ReadCommand(ELK_STEP_GETPOS);
	} /*endwhile*/
        printf("%4ld Speed %3d/%3d Position %5d/%5d\n",TimeOut,ActSpd,SetSpd,ActPos,ScanPos);
	
	nanosleep(&ScanTime,NULL);
    } while (ActPos!=ScanPos & ScanTimeOut++<0xfffff); 

    /* get act. pos & speed */
    ActSpd=(signed)ReadCommand(ELK_STEP_GETSPD);
    ActPos=(signed)ReadCommand(ELK_STEP_GETPOS);
    printf("Speed %3hhd Position %5d\n",ActSpd,ActPos);


// close all in bound sockets
    for (MessagePort=0; MessagePort<MAX_MESSAGE_INPORTS;MessagePort++) {	
	close(MessageInPortList[MessagePort].fdSocket);
    } /*for MessagePort */ 
    
// close all out bound sockets
    for (MessagePort=0; MessagePort<MAX_MESSAGE_OUTPORTS;MessagePort++) {	
	close(MessageOutPortList[MessagePort].fdSocket);
    } /*for MessagePort */
    
    exit(EXIT_SUCCESS);

}
Example #23
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;
}