Always check status of automatic service

- Remove service-only mode (start/stop service) which has not been in
  use since we moved to running the GUI as limited user.
  Also its not very useful as it does not allow any control of
  service-started daemons

- Keep CheckServiceStatus and always check the status of
automatic service.

The status of the service will be used to toggle supporting
control of persistent connections started by the service.

Signed-off-by: Selva Nair <selva.nair@gmail.com>
pull/519/head
Selva Nair 2022-07-03 16:57:40 -04:00
parent 428ee29246
commit 8f0dbbc8a3
29 changed files with 24 additions and 367 deletions

View File

@ -264,11 +264,6 @@ silent_connection
not be shown while connecting. Warnings such as interactive service
not started or multiple config files with same name are also suppressed.
service_only
If set to "1", OpenVPN GUI's normal "Connect" and "Disconnect"
actions are changed so they start/stop the OpenVPN service instead
of launching openvpn.exe directly.
show_balloon
0: Never show any connected balloon

34
main.c
View File

@ -277,6 +277,7 @@ int WINAPI _tWinMain (HINSTANCE hThisInstance,
if (use_iservice && strtod(o.ovpn_version, NULL) > 2.3 && !o.silent_connection)
CheckIServiceStatus(TRUE);
CheckServiceStatus(); /* Check if automatic service is running or not */
BuildFileList();
if (!VerifyAutoConnections()) {
@ -538,8 +539,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM
CreatePopupMenus(); /* Create popup menus */
ShowTrayIcon();
if (o.service_only)
CheckServiceStatus(); // Check if service is running or not
/* if '--import' was specified, do it now */
if (o.action == WM_OVPN_IMPORT && o.action_arg)
@ -581,15 +580,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM
else if (LOWORD(wParam) == IDM_CLOSE) {
CloseApplication(hwnd);
}
else if (LOWORD(wParam) == IDM_SERVICE_START) {
MyStartService();
}
else if (LOWORD(wParam) == IDM_SERVICE_STOP) {
MyStopService();
}
else if (LOWORD(wParam) == IDM_SERVICE_RESTART) {
MyReStartService();
}
/* rest of the handlers require a connection id */
else {
minfo.fMask = MIM_MENUDATA;
@ -713,16 +703,14 @@ ShowSettingsDialog()
++page_number;
/* Proxy tab */
if (o.service_only == 0) {
psp[page_number].dwSize = sizeof(PROPSHEETPAGE);
psp[page_number].dwFlags = PSP_DLGINDIRECT;
psp[page_number].hInstance = o.hInstance;
psp[page_number].pResource = LocalizedDialogResource(ID_DLG_PROXY);
psp[page_number].pfnDlgProc = ProxySettingsDialogFunc;
psp[page_number].lParam = 0;
psp[page_number].pfnCallback = NULL;
++page_number;
}
psp[page_number].dwSize = sizeof(PROPSHEETPAGE);
psp[page_number].dwFlags = PSP_DLGINDIRECT;
psp[page_number].hInstance = o.hInstance;
psp[page_number].pResource = LocalizedDialogResource(ID_DLG_PROXY);
psp[page_number].pfnDlgProc = ProxySettingsDialogFunc;
psp[page_number].lParam = 0;
psp[page_number].pfnCallback = NULL;
++page_number;
/* Advanced tab */
psp[page_number].dwSize = sizeof(PROPSHEETPAGE);
@ -765,10 +753,6 @@ CloseApplication(HWND hwnd)
{
int i;
if (o.service_state == service_connected
&& ShowLocalizedMsgEx(MB_YESNO, NULL, _T("Exit OpenVPN"), IDS_NFO_SERVICE_ACTIVE_EXIT) == IDNO)
return;
/* Show a message if any non-persistent connections are active */
for (i = 0; i < o.num_configs; i++)
{

View File

@ -204,7 +204,7 @@ add_option(options_t *options, int i, TCHAR **p)
else if (streq(p[0], _T("service_only")) && p[1])
{
++i;
options->service_only = _ttoi(p[1]) ? 1 : 0;
PrintDebug (L"Deprecated option: '%ls' ignored.", p[0]);
}
else if (streq(p[0], _T("show_script_window")) && p[1])
{

View File

@ -204,7 +204,6 @@ typedef struct {
TCHAR log_viewer[MAX_PATH];
TCHAR editor[MAX_PATH];
DWORD silent_connection;
DWORD service_only;
DWORD iservice_admin;
DWORD show_balloon;
DWORD show_script_window;

View File

@ -61,7 +61,6 @@ struct regkey_int {
{L"connectscript_timeout", &o.connectscript_timeout, 30},
{L"disconnectscript_timeout", &o.disconnectscript_timeout, 10},
{L"show_script_window", &o.show_script_window, 0},
{L"service_only", &o.service_only, 0},
{L"config_menu_view", &o.config_menu_view, CONFIG_VIEW_AUTO},
{L"popup_mute_interval", &o.popup_mute_interval, 24},
{L"disable_popup_messages", &o.disable_popup_messages, 0},

View File

@ -433,7 +433,6 @@ Volby k použití explicitního nastavení namísto výchozího z registru:\n\
--allow_password\t\t: 1=Zobrazit položku Změnit heslo v menu.\n\
--allow_proxy\t\t: 1=Zobrazit nastavení proxy v menu.\n\
--show_balloon\t\t: Ukazovat upozornění: 0=Nikdy, 1=Při připojení, 2=Při připojení/obnovení spojení.\n\
--service_only\t\t: 1=Ovládat pouze službu systému.\n\
--silent_connection\t\t: 1=Nezobrazovat stav při připojování ani nekritická varování při spuštění.\n\
--show_script_window\t: 0=Nezobrazovat okno skriptu, 1=Zobrazit okno skriptu.\n\
--passphrase_attempts\t: Počet možných pokusů o zadání hesla.\n\

View File

@ -435,7 +435,6 @@ Option zum Überschreiben der Registry Einstellungen:\n\
--allow_password\t\t: 1=Zeige Passwort-ändern-Menü.\n\
--allow_proxy\t\t: 1=Zeige Proxy-Einstellungsmenü.\n\
--show_balloon\t\t: 0=Nie, 1=Beim ersten Verbinden, 2=Bei jedem Wiederverbinden.\n\
--service_only\t\t: 1=Aktiviere Service-Only-Modus.\n\
--silent_connection\t\t: 1=Unterdrücke die Anzeige des Statusdialogs beim Verbinden.\n\
--show_script_window\t: 0=Unterdrücke die Anzeige des Skriptfensters, 1=Zeige es.\n\
--passphrase_attempts\t: Anzahl der erlaubten Passphrase-Versuche.\n\

View File

@ -432,7 +432,6 @@ Parametre som vil tilsidesætte indstillinger i registreringsdatabasen:\n\
--allow_password\t\t: 1=Vise Ændre Password i menu.\n\
--allow_proxy\t\t: 1=Vise Proxy Innstillinger i menu.\n\
--show_balloon\t\t: 0=Aldrig, 1=under tilslutning, 2=Ved hver ""gen-tilslutning"".\n\
--service_only\t\t: 1=Aktivere ""Kun Service"" tilstand.\n\
--silent_connection\t\t: 1=ikke vise status-vindue ved tilslutning.\n\
--show_script_window\t: 0=Skjul script-vindue, 1=Vise script-vindue.\n\
--passphrase_attempts\t: Antal forbindelses-forsøg.\n\

View File

@ -447,7 +447,6 @@ Options to override registry settings:\n\
--allow_password\t\t: 1=Show Change Password menu item.\n\
--allow_proxy\t\t: 1=Show Proxy Settings menu.\n\
--show_balloon\t\t: 0=Never, 1=At initial connect, 2=At every reconnect.\n\
--service_only\t\t: 1=Enable Service Only mode.\n\
--silent_connection\t: 1=Do not show the status dialog while connecting or non-critical warnings at startup.\n\
--show_script_window\t: 0=Hide Script execution window, 1=Show it.\n\
--passphrase_attempts\t: Number of passphrase attempts to allow.\n\

View File

@ -429,7 +429,6 @@ Opciones para sobreescribir opciones del registro:\n\
--allow_password\t\t: 1=Mostrar el menú de Cambiar Clave.\n\
--allow_proxy\t\t: 1=Mostrar el menú de Configuración del Proxy.\n\
--show_balloon\t\t: 0=Nunca, 1=En la conexión inicial, 2=En cada reconexión.\n\
--service_only\t\t: 1=Activar el modo de Solo Servicio.\n\
--silent_connection\t\t: 1=No mostrar la ventana de estado al conectar.\n\
--show_script_window\t: 0=Oculta la ventana de ejecución de Script, 1=Mostrarla.\n\
--passphrase_attempts\t: Número de intentos permitidos para la passphrase.\n\

View File

@ -435,7 +435,6 @@ Options to override registry settings:\n\
--allow_password\t\t: 1=Show Change Password menu item.\n\
--allow_proxy\t\t: 1=Show Proxy Settings menu.\n\
--show_balloon\t\t: 0=Never, 1=At initial connect, 2=At every reconnect.\n\
--service_only\t\t: 1=Enable Service Only mode.\n\
--silent_connection\t\t: 1=Do not show the status dialog while connecting or non-critical warnings at startup.\n\
--show_script_window\t: 0=Hide Script execution window, 1=Show it.\n\
--passphrase_attempts\t: Number of passphrase attempts to allow.\n\

View File

@ -432,7 +432,6 @@ Rekisterin asetukset kumoavat valinnat:\n\
--allow_password\t\t: 1=Näytä salasanan vaihto valikossa.\n\
--allow_proxy\t\t: 1=Näytä välipalvelimen asetukset valikossa.\n\
--show_balloon\t\t: 0=Ei koskaan, 1=Ensimmäisen kerran yhdistettäessä, 2=Joka yhdistyksellä.\n\
--service_only\t\t: 1=Käynnistä palveluna.\n\
--silent_connection\t\t: 1=Älä näytä sovelluksen tilaa yhdistettäessä.\n\
--show_script_window\t: 0=Piilota komentojonoikkuna, 1=Älä piilota sitä.\n\
--passphrase_attempts\t: Salasanan syöttökertojen maksimimäärä\n\

View File

@ -432,7 +432,6 @@ Options pour corriger la configuration de registre:\n\
--allow_password\t\t: 1=Afficher le menu de Changement de Mot de passe.\n\
--allow_proxy\t\t: 1=Afficher le menu de la configuration du Proxy.\n\
--show_balloon\t\t: 0=Jamais, 1=A la connexion initiale, 2=A toutes les reconnexions.\n\
--service_only\t\t: 1=Activer le mode Service seul Enable.\n\
--silent_connection\t\t: 1=Ne pas ouvrir le dialogue de Statut à la connexion.\n\
--show_script_window\t: 0=Cacher la fenêtre d'exécution du script, 1=Afficher la fenêtre.\n\
--passphrase_attempts\t: Nombre de tentatives de Mot de passe permises.\n\

View File

@ -432,7 +432,6 @@ Opzioni per ignorare il registro di sistema:\n\
--allow_password\t\t: 1=Mostra menu modifica password.\n\
--allow_proxy\t\t: 1=Mostra menu impostazioni proxy.\n\
--show_balloon\t\t: 0=Mai, 1=Alla connessione iniziale, 2=A ogni riconnessione.\n\
--service_only\t\t: 1=Abilita la modalità solo servizio.\n\
--silent_connection\t\t: 1=Non mostrare la finestra di stato durante la connessione e avvertimenti non urgenti all'avvio.\n\
--show_script_window\t: 0=Nascondi la finestra di esecuzione dello script, 1=Mostra.\n\
--passphrase_attempts\t: Numero di tentativi permessi per la frase di sicurezza.\n\

View File

@ -433,7 +433,6 @@ OpenVPN GUIをこのまま終了しますか"
--allow_password\t\t: 1=[パスワードの変更]メニューを表示する。\n\
--allow_proxy\t\t: 1=[プロキシ設定]メニューを表示する。\n\
--show_balloon\t\t: 0=表示しない, 1=接続時, 2=接続/再接続時\n\
--service_only\t\t: 1=サービスのみのモードを有効にする。\n\
--silent_connection\t\t: 1=接続時にステータス表示ダイアログを表示しない。\n\
--show_script_window\t: 0=スクリプト実行ウィンドウを非表示にする。1=表示する。\n\
--passphrase_attempts\t: パスフレーズの入力可能回数。\n\

View File

@ -430,7 +430,6 @@ OpenVPN GUI를 이대로 종료 하겠습니까?"
--allow_password\t\t: 1=암호 변경 메뉴 표시\n\
--allow_proxy\t\t: 1=프락시 설정 메뉴 표시\n\
--show_balloon\t\t: 0=표시 안함, 1=접속 시, 2=모든 접속/재접속 시.\n\
--service_only\t\t: 1=서비스 전용 모드를 사용\n\
--silent_connection\t\t: 1=연결시 상태 표시 대화 상자를 표시하지 않습니다.\n\
--show_script_window\t: 0=스크립트 실행창 숨김, 1=보기.\n\
--passphrase_attempts\t: 암호 입력 시도 회수\n\

View File

@ -433,7 +433,6 @@ Instellingen die de registerinstellingen overschrijven:\n\
--allow_password\t\t: 1=""Wachtwoord wijzigen"" menu-item weergeven.\n\
--allow_proxy\t\t: 1=Menu ""Proxyinstellingen"" weergeven.\n\
--show_balloon\t\t: 0=Nooit, 1=Tijdens eerste verbinding, 2=Bij elke herverbinding.\n\
--service_only\t\t: 1=Service Only modus activeren.\n\
--silent_connection\t\t: 1=Het status-venster tijdens het verbinden verbergen.\n\
--show_script_window\t: 0=Het script uitvoer-venster verbergen, 1=Weergeven.\n\
--passphrase_attempts\t: Aantal wachtwoordpogingen.\n\

View File

@ -426,7 +426,6 @@ Parametere som vil overstyre innstillinger gjort i registeret:\n\
--allow_password\t\t: 1=Vis 'Endre passord' i menyen.\n\
--allow_proxy\t\t: 1=Vis 'Proxy-innstillinger' i menyen.\n\
--show_balloon\t\t: 0=Aldri, 1=under tilkobling, 2=Ved hver til- og gjenoppkobling.\n\
--service_only\t\t: 1=Kjør kun som bakgrunnstjeneste.\n\
--silent_connection\t\t: 1=Skjul statusvindu ved tilkobling.\n\
--show_script_window\t: 0=Skjul skriptvindu, 1=Vis skriptvindu.\n\
--passphrase_attempts\t: Antall tilkoblingsforsøk.\n\

View File

@ -431,7 +431,6 @@ Opcje oddalające ustawienia rejestru:\n\
--allow_password\t\t: 1=Wyświetl w menu pole Zmień Hasło.\n\
--allow_proxy\t\t: 1=Wyświetl w menu pole Pokaż Ustawienia Proxy.\n\
--show_balloon\t\t: 0=Nigdy, 1=Przy pierwszym połączeniu, 2=Przy każdym połączeniu.\n\
--service_only\t\t: 1=Aktywuj tryb Tylko Usługa (Service Only).\n\
--silent_connection\t\t: 1=Nie pokazuj okna statusu podczas łączenia.\n\
--show_script_window\t: 0=Ukryj okno wykonywania skryptu, 1=Wyświetl je.\n\
--passphrase_attempts\t: Dopuszczalna ilość prób podania hasła.\n\

View File

@ -431,7 +431,6 @@ Opções para sobrescrever opções do registro:\n\
--allow_password\t\t: 1=Mostrar menu de troca de senha.\n\
--allow_proxy\t\t: 1=Mostrar menu de configurações de Proxy.\n\
--show_balloon\t\t: 0=Nunca, 1=Ao iniciar conexão, 2=Sempre que reconectar.\n\
--service_only\t\t: 1=Habilitar modo Service Only .\n\
--silent_connection\t\t: 1=Não mostrar dialogo de status quando estiver conectando.\n\
--show_script_window\t: 0=Esconder janela de execução de script, 1=Mostrar.\n\
--passphrase_attempts\t: Número de tentativas de digitação de senha.\n\

View File

@ -432,7 +432,6 @@ Supported commands:\n\
--allow_password\t\t: 1=Отображать пункт меню «Сменить пароль».\n\
--allow_proxy\t\t: 1=Отображать пункт меню «Настройки прокси-сервера».\n\
--show_balloon\t\t: Показывать информационное всплывающее окно. 0=Никогда, 1=При первом подключении, 2=При каждом переподключении.\n\
--service_only\t\t: 1=Включить режим управления службой.\n\
--silent_connection\t\t: 1=Не показывать диалог состояния при подключении.\n\
--show_script_window\t: 0=Скрыть окно выполнения скрипта, 1=Показать его.\n\
--passphrase_attempts\t: Количество разрешённых попыток ввода пароля.\n\

View File

@ -428,7 +428,6 @@ Parametrar som ersätter inställningar gjorda i registret:\n\
--allow_password\t\t: 1=Visa Ändra Lösenord på menyn.\n\
--allow_proxy\t\t: 1=Visa Proxy Inställningar på menyn.\n\
--show_balloon\t\t: 0=Aldrig, 1=Vid anslutning, 2=Vid varje återanslutning.\n\
--service_only\t\t: 1=Aktivera ""Service Only"" läge.\n\
--silent_connection\t\t: 1=Visa inte status fönstret under anslutning.\n\
--show_script_window\t: 0=Göm skript fönster, 1=Visa skript fönster.\n\
--passphrase_attempts\t: Antal lösenordsförsök.\n\

View File

@ -431,7 +431,6 @@ Registry ayarları için:\n\
--allow_password\t\t: 1=Şifre değiştirme menü öğesini göster.\n\
--allow_proxy\t\t: 1=Proxy Ayarları menüsünü gözter.\n\
--show_balloon\t\t: 0=Hiç bir zaman, 1=Bağlantı yapılırken, 2=Bağlantı her yeniden yapıldığında.\n\
--service_only\t\t: 1=Sadece servis çalışsın, arayüz gösterilmesin.\n\
--silent_connection\t\t: 1=Bağlantı sırasında durum diyaloğu görünmesin.\n\
--show_script_window\t: 0=Betik çalıştırma penceresi görünmesin, 1=Betik çalıştırma penceresi görünsün.\n\
--passphrase_attempts\t: Kaç defa şifre giriş denemesi yapılabilir.\n\

View File

@ -431,7 +431,6 @@ BEGIN
--allow_password\t\t: 1=Відобразити пункт меню Змінити пароль.\n\
--allow_proxy\t\t: 1=Відобразити меню Налаштування проксі-сервера.\n\
--show_balloon\t\t: 0=Николи, 1=У перше підключення, 2=При кожному перепідключенні.\n\
--service_only\t\t: 1=Включити режим тільки сервіси.\n\
--silent_connection\t\t: 1=Сховати вікно статусу під час підключення.\n\
--show_script_window\t: 0=Сховати вікно виконання скрипту, 1=Відобразити це вікно.\n\
--passphrase_attempts\t: Кількість спроб вводу паролю.\n\

View File

@ -434,7 +434,6 @@ BEGIN
--allow_password\t\t: 1=显示「变更密码」选项。\n\
--allow_proxy\t\t: 1=显示「代理设置」选项。\n\
--show_balloon\t\t: 0=永不、1=首次连接时、2=每次重新连接时显示通知。\n\
--service_only\t\t: 1=启动「仅系统服务」模式。\n\
--silent_connection\t\t: 1=连接时,不显示状态窗口。\n\
--show_script_window\t: 0=隐藏脚本执行窗口、1=显示。\n\
--passphrase_attempts\t: 允许尝试输入密码次数。\n\

View File

@ -434,7 +434,6 @@ Supported commands:\n\
--allow_password\t\t: 1=顯示「變更密碼」選單。\n\
--allow_proxy\t\t: 1=顯示「Proxy 設定」選單。\n\
--show_balloon\t\t: 0=永不、1=首次連線時、2=每次重新連線時顯示通知氣球。\n\
--service_only\t\t: 1=啟動「僅有系統服務」模式。\n\
--silent_connection\t\t: 1=連線時,不顯示狀態視窗。\n\
--show_script_window\t: 0=隱藏指令碼執行視窗、1=顯示。\n\
--passphrase_attempts\t: 允許嘗試輸入密碼次數。\n\

228
service.c
View File

@ -26,11 +26,8 @@
#include <windows.h>
#include <stdio.h>
#include "tray.h"
#include "service.h"
#include "openvpn.h"
#include "options.h"
#include "scripts.h"
#include "main.h"
#include "misc.h"
#include "openvpn-gui-res.h"
@ -41,220 +38,6 @@
extern options_t o;
int MyStartService()
{
SC_HANDLE schSCManager = NULL;
SC_HANDLE schService = NULL;
SERVICE_STATUS ssStatus;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
int i;
/* Set Service Status = Connecting */
o.service_state = service_connecting;
SetServiceMenuStatus();
CheckAndSetTrayIcon();
// Open a handle to the SC Manager database.
schSCManager = OpenSCManager(
NULL, // local machine
NULL, // ServicesActive database
SC_MANAGER_CONNECT); // Connect rights
if (NULL == schSCManager) {
/* open SC manager failed */
ShowLocalizedMsg(IDS_ERR_OPEN_SCMGR);
goto failed;
}
schService = OpenService(
schSCManager, // SCM database
_T("OpenVPNService"), // service name
SERVICE_START | SERVICE_QUERY_STATUS);
if (schService == NULL) {
/* can't open VPN service */
ShowLocalizedMsg(IDS_ERR_OPEN_VPN_SERVICE);
goto failed;
}
/* Run Pre-connect script */
for (i=0; i<o.num_configs; i++)
RunPreconnectScript(&o.conn[i]);
if (!StartService(
schService, // handle to service
0, // number of arguments
NULL) ) // no arguments
{
/* can't start */
ShowLocalizedMsg(IDS_ERR_START_SERVICE);
goto failed;
}
else
{
//printf("Service start pending.\n");
}
// Check the status until the service is no longer start pending.
if (!QueryServiceStatus(
schService, // handle to service
&ssStatus) ) // address of status information structure
{
/* query failed */
ShowLocalizedMsg(IDS_ERR_QUERY_SERVICE);
goto failed;
}
// Save the tick count and initial checkpoint.
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
while (ssStatus.dwCurrentState == SERVICE_START_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one tenth the wait hint, but no less than 1 second and no
// more than 5 seconds.
dwWaitTime = ssStatus.dwWaitHint / 10;
if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 5000 )
dwWaitTime = 5000;
Sleep( dwWaitTime );
// Check the status again.
if (!QueryServiceStatus(
schService, // handle to service
&ssStatus) ) // address of structure
break;
if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// The service is making progress.
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
{
// No progress made within the wait hint
break;
}
}
}
if (ssStatus.dwCurrentState != SERVICE_RUNNING)
{
/* service hasn't started */
ShowLocalizedMsg(IDS_ERR_SERVICE_START_FAILED);
goto failed;
}
/* Run Connect script */
for (i=0; i<o.num_configs; i++)
RunConnectScript(&o.conn[i], true);
/* Set Service Status = Connected */
o.service_state = service_connected;
SetServiceMenuStatus();
CheckAndSetTrayIcon();
/* Show "OpenVPN Service Started" Tray Balloon msg */
ShowTrayBalloon(LoadLocalizedString(IDS_NFO_SERVICE_STARTED), _T(""));
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return(true);
failed:
if (schService)
CloseServiceHandle(schService);
if (schSCManager)
CloseServiceHandle(schSCManager);
/* Set Service Status = Disconnecting */
o.service_state = service_disconnected;
SetServiceMenuStatus();
CheckAndSetTrayIcon();
return(false);
}
int MyStopService()
{
SC_HANDLE schSCManager = NULL;
SC_HANDLE schService = NULL;
SERVICE_STATUS ssStatus;
int i;
BOOL ret = false;
// Open a handle to the SC Manager database.
schSCManager = OpenSCManager(
NULL, // local machine
NULL, // ServicesActive database
SC_MANAGER_CONNECT); // Connect rights
if (NULL == schSCManager) {
/* can't open SCManager */
ShowLocalizedMsg(IDS_ERR_OPEN_SCMGR, (int) GetLastError());
return(false);
}
schService = OpenService(
schSCManager, // SCM database
_T("OpenVPNService"), // service name
SERVICE_STOP);
if (schService == NULL) {
/* can't open vpn service */
ShowLocalizedMsg(IDS_ERR_OPEN_VPN_SERVICE);
goto out;
}
/* Run DisConnect script */
for (i=0; i<o.num_configs; i++)
RunDisconnectScript(&o.conn[i], true);
if (!ControlService(
schService, // handle to service
SERVICE_CONTROL_STOP, // control value to send
&ssStatus) ) // address of status info
{
/* stop failed */
ShowLocalizedMsg(IDS_ERR_STOP_SERVICE);
goto out;
}
o.service_state = service_disconnected;
SetServiceMenuStatus();
CheckAndSetTrayIcon();
ret = true;
out:
if (schService)
CloseServiceHandle(schService);
if (schSCManager)
CloseServiceHandle(schSCManager);
return ret;
}
int MyReStartService()
{
MyStopService();
Sleep(1000);
if (MyStartService()) {
return(true);
}
return(false);
}
bool
CheckIServiceStatus(BOOL warn)
{
@ -322,7 +105,6 @@ int CheckServiceStatus()
if (NULL == schSCManager) {
o.service_state = service_noaccess;
SetServiceMenuStatus();
goto out;
}
@ -332,10 +114,7 @@ int CheckServiceStatus()
SERVICE_QUERY_STATUS);
if (schService == NULL) {
/* open vpn service failed */
ShowLocalizedMsg(IDS_ERR_OPEN_VPN_SERVICE);
o.service_state = service_noaccess;
SetServiceMenuStatus();
goto out;
}
@ -344,23 +123,20 @@ int CheckServiceStatus()
&ssStatus) ) // address of status information structure
{
/* query failed */
ShowLocalizedMsg(IDS_ERR_QUERY_SERVICE);
o.service_state = service_noaccess;
MsgToEventLog(EVENTLOG_ERROR_TYPE, LoadLocalizedString(IDS_ERR_QUERY_SERVICE));
goto out;
}
if (ssStatus.dwCurrentState == SERVICE_RUNNING)
{
o.service_state = service_connected;
SetServiceMenuStatus();
SetTrayIcon(connected);
ret = true;
goto out;
}
else
{
o.service_state = service_disconnected;
SetServiceMenuStatus();
SetTrayIcon(disconnected);
goto out;
}

View File

@ -19,8 +19,5 @@
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
int MyStartService();
int MyStopService();
int MyReStartService();
int CheckServiceStatus();
BOOL CheckIServiceStatus(BOOL warn);

96
tray.c
View File

@ -30,7 +30,6 @@
#include <time.h>
#include "tray.h"
#include "service.h"
#include "main.h"
#include "options.h"
#include "openvpn.h"
@ -45,7 +44,6 @@ HMENU hMenu;
HMENU *hMenuConn;
HMENU hMenuImport;
int hmenu_size = 0; /* allocated size of hMenuConn array */
HMENU hMenuService;
HBITMAP hbmpConnecting;
@ -179,7 +177,6 @@ CreatePopupMenus()
o.groups[i].children = 0; /* we have to recount this when assigning menu position index */
}
hMenuService = CreatePopupMenu();
hMenu = o.groups[0].menu; /* the first group menu is also the root menu */
/* Set notify by position style for the top menu - gets automatically applied to sub-menus */
@ -190,19 +187,11 @@ CreatePopupMenus()
if (o.num_configs == 1) {
/* Create Main menu with actions */
if (o.service_only == 0) {
AppendMenu(hMenu, MF_STRING, IDM_CONNECTMENU, LoadLocalizedString(IDS_MENU_CONNECT));
AppendMenu(hMenu, MF_STRING, IDM_DISCONNECTMENU, LoadLocalizedString(IDS_MENU_DISCONNECT));
AppendMenu(hMenu, MF_STRING, IDM_RECONNECTMENU, LoadLocalizedString(IDS_MENU_RECONNECT));
AppendMenu(hMenu, MF_STRING, IDM_STATUSMENU, LoadLocalizedString(IDS_MENU_STATUS));
AppendMenu(hMenu, MF_SEPARATOR, 0, 0);
}
else {
AppendMenu(hMenu, MF_STRING, IDM_SERVICE_START, LoadLocalizedString(IDS_MENU_SERVICEONLY_START));
AppendMenu(hMenu, MF_STRING, IDM_SERVICE_STOP, LoadLocalizedString(IDS_MENU_SERVICEONLY_STOP));
AppendMenu(hMenu, MF_STRING, IDM_SERVICE_RESTART, LoadLocalizedString(IDS_MENU_SERVICEONLY_RESTART));
AppendMenu(hMenu, MF_SEPARATOR, 0, 0);
}
AppendMenu(hMenu, MF_STRING, IDM_CONNECTMENU, LoadLocalizedString(IDS_MENU_CONNECT));
AppendMenu(hMenu, MF_STRING, IDM_DISCONNECTMENU, LoadLocalizedString(IDS_MENU_DISCONNECT));
AppendMenu(hMenu, MF_STRING, IDM_RECONNECTMENU, LoadLocalizedString(IDS_MENU_RECONNECT));
AppendMenu(hMenu, MF_STRING, IDM_STATUSMENU, LoadLocalizedString(IDS_MENU_STATUS));
AppendMenu(hMenu, MF_SEPARATOR, 0, 0);
AppendMenu(hMenu, MF_STRING, IDM_VIEWLOGMENU, LoadLocalizedString(IDS_MENU_VIEWLOG));
@ -270,13 +259,6 @@ CreatePopupMenus()
if (o.num_configs > 0)
AppendMenu(hMenu, MF_SEPARATOR, 0, 0);
if (o.service_only) {
AppendMenu(hMenu, MF_STRING, IDM_SERVICE_START, LoadLocalizedString(IDS_MENU_SERVICEONLY_START));
AppendMenu(hMenu, MF_STRING, IDM_SERVICE_STOP, LoadLocalizedString(IDS_MENU_SERVICEONLY_STOP));
AppendMenu(hMenu, MF_STRING, IDM_SERVICE_RESTART, LoadLocalizedString(IDS_MENU_SERVICEONLY_RESTART));
AppendMenu(hMenu, MF_SEPARATOR, 0, 0);
}
hMenuImport = CreatePopupMenu();
AppendMenu(hMenu, MF_POPUP, (UINT_PTR) hMenuImport, LoadLocalizedString(IDS_MENU_IMPORT));
AppendMenu(hMenuImport, MF_STRING, IDM_IMPORT_FILE, LoadLocalizedString(IDS_MENU_IMPORT_FILE));
@ -288,13 +270,11 @@ CreatePopupMenus()
/* Create popup menus for every connection */
for (int i = 0; i < o.num_configs; i++) {
if (o.service_only == 0) {
AppendMenu(hMenuConn[i], MF_STRING, IDM_CONNECTMENU, LoadLocalizedString(IDS_MENU_CONNECT));
AppendMenu(hMenuConn[i], MF_STRING, IDM_DISCONNECTMENU, LoadLocalizedString(IDS_MENU_DISCONNECT));
AppendMenu(hMenuConn[i], MF_STRING, IDM_RECONNECTMENU, LoadLocalizedString(IDS_MENU_RECONNECT));
AppendMenu(hMenuConn[i], MF_STRING, IDM_STATUSMENU, LoadLocalizedString(IDS_MENU_STATUS));
AppendMenu(hMenuConn[i], MF_SEPARATOR, 0, 0);
}
AppendMenu(hMenuConn[i], MF_STRING, IDM_CONNECTMENU, LoadLocalizedString(IDS_MENU_CONNECT));
AppendMenu(hMenuConn[i], MF_STRING, IDM_DISCONNECTMENU, LoadLocalizedString(IDS_MENU_DISCONNECT));
AppendMenu(hMenuConn[i], MF_STRING, IDM_RECONNECTMENU, LoadLocalizedString(IDS_MENU_RECONNECT));
AppendMenu(hMenuConn[i], MF_STRING, IDM_STATUSMENU, LoadLocalizedString(IDS_MENU_STATUS));
AppendMenu(hMenuConn[i], MF_SEPARATOR, 0, 0);
AppendMenu(hMenuConn[i], MF_STRING, IDM_VIEWLOGMENU, LoadLocalizedString(IDS_MENU_VIEWLOG));
@ -309,8 +289,6 @@ CreatePopupMenus()
SetMenuStatusById(i, o.conn[i].state);
}
}
SetServiceMenuStatus();
}
@ -322,11 +300,9 @@ DestroyPopupMenus()
for (i = 0; i < o.num_configs; i++)
DestroyMenu(hMenuConn[i]);
DestroyMenu(hMenuService);
DestroyMenu(hMenuImport);
DestroyMenu(hMenu);
hMenuService = NULL;
hMenuImport = NULL;
hMenu = NULL;
}
@ -359,17 +335,7 @@ OnNotifyTray(LPARAM lParam)
break;
case WM_LBUTTONDBLCLK:
if (o.service_only) {
/* Start or stop OpenVPN service */
if (o.service_state == service_disconnected) {
MyStartService();
}
else if (o.service_state == service_connected
&& ShowLocalizedMsgEx(MB_YESNO, NULL, _T(PACKAGE_NAME), IDS_MENU_ASK_STOP_SERVICE) == IDYES) {
MyStopService();
}
}
else {
{
int disconnected_conns = CountConnState(disconnected);
RecreatePopupMenus();
@ -494,12 +460,6 @@ SetTrayIcon(conn_state_t state)
void
CheckAndSetTrayIcon()
{
if (o.service_state == service_connected)
{
SetTrayIcon(connected);
return;
}
if (CountConnState(connected) != 0)
{
SetTrayIcon(connected);
@ -507,7 +467,7 @@ CheckAndSetTrayIcon()
else
{
if (CountConnState(connecting) != 0 || CountConnState(reconnecting) != 0
|| CountConnState(resuming) != 0 || o.service_state == service_connecting)
|| CountConnState(resuming) != 0)
SetTrayIcon(connecting);
else
SetTrayIcon(disconnected);
@ -655,35 +615,3 @@ SetMenuStatusById(int i, conn_state_t state)
EnableMenuItem(hMenuConn[i], IDM_CLEARPASSMENU, MF_GRAYED);
}
}
void
SetServiceMenuStatus()
{
HMENU hMenuHandle;
if (o.service_only == 0)
return;
if (o.service_only)
hMenuHandle = hMenu;
else
hMenuHandle = hMenuService;
if (o.service_state == service_noaccess
|| o.service_state == service_connecting) {
EnableMenuItem(hMenuHandle, IDM_SERVICE_START, MF_GRAYED);
EnableMenuItem(hMenuHandle, IDM_SERVICE_STOP, MF_GRAYED);
EnableMenuItem(hMenuHandle, IDM_SERVICE_RESTART, MF_GRAYED);
}
else if (o.service_state == service_connected) {
EnableMenuItem(hMenuHandle, IDM_SERVICE_START, MF_GRAYED);
EnableMenuItem(hMenuHandle, IDM_SERVICE_STOP, MF_ENABLED);
EnableMenuItem(hMenuHandle, IDM_SERVICE_RESTART, MF_ENABLED);
}
else {
EnableMenuItem(hMenuHandle, IDM_SERVICE_START, MF_ENABLED);
EnableMenuItem(hMenuHandle, IDM_SERVICE_STOP, MF_GRAYED);
EnableMenuItem(hMenuHandle, IDM_SERVICE_RESTART, MF_GRAYED);
}
}