diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..823b4979b --- /dev/null +++ b/.clang-format @@ -0,0 +1,44 @@ +--- +BasedOnStyle: Mozilla +AccessModifierOffset: '-4' +AlignAfterOpenBracket: Align +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: true + AcrossComments: true +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: + Kind: Always + OverEmptyLines: 1 +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeBraces: Allman +BreakBeforeTernaryOperators: true +BreakStringLiterals: false +ColumnLimit: '100' +ContinuationIndentWidth: '4' +DerivePointerAlignment: false +IndentCaseLabels: true +IndentGotoLabels: false +IndentWidth: '4' +IndentWrappedFunctionNames: false +KeepEmptyLinesAtTheStartOfBlocks: false +Language: Cpp +MaxEmptyLinesToKeep: '2' +PointerAlignment: Right +ReflowComments: true +SortIncludes: false +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpacesBeforeTrailingComments: '2' +SpacesInParens: Never +TabWidth: '4' +UseTab: Never diff --git a/.github/workflows/msbuild.yml b/.github/workflows/msbuild.yml index 0133431e2..8bd1c2960 100644 --- a/.github/workflows/msbuild.yml +++ b/.github/workflows/msbuild.yml @@ -3,29 +3,26 @@ name: Build on: [push, pull_request] jobs: - checkuncrustify: - name: "Check code style with Uncrustify" - # Ubuntu 22.04 has uncrustify 0.72_f - runs-on: ubuntu-22.04 + checkformat: + name: "Check code style with clang-format" + runs-on: ubuntu-24.04 steps: - - name: Install dependencies - run: sudo apt update && sudo apt install -y uncrustify + - name: Install pre-commit + run: pip3 install pre-commit - name: Checkout OpenVPN-GUI uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 - - name: Show uncrustify version - run: uncrustify --version - - name: Run uncrustify - run: ./dev-tools/reformat-all.sh + - name: Run pre-commit + run: pre-commit run -a || true - name: Check for changes - run: git diff --output=uncrustify-changes.patch + run: git diff --output=cf-changes.patch - name: Show changes on standard output run: git diff - uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4 with: - name: uncrustify-changes.patch - path: uncrustify-changes.patch + name: cf-changes.patch + path: cf-changes.patch - name: Set job status - run: test ! -s uncrustify-changes.patch + run: test ! -s cf-changes.patch msvc: strategy: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..340121641 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,6 @@ +repos: + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: 'v19.1.4' + hooks: + - id: clang-format + files: \.[ch]$ diff --git a/access.c b/access.c index 69e2460d0..103425e79 100644 --- a/access.c +++ b/access.c @@ -70,8 +70,7 @@ GetBuiltinAdminGroupName(WCHAR *name, DWORD nlen) return FALSE; } - b = CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, - &sid_size); + b = CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size); if (b) { b = LookupAccountSidW(NULL, admin_sid, name, &nlen, domain, &dlen, &su); @@ -127,22 +126,22 @@ AddUserToGroup(const WCHAR *group) size = _countof(syspath); if (GetSystemDirectory(syspath, size)) { - syspath[size-1] = L'\0'; + syspath[size - 1] = L'\0'; size = _countof(cmd); _snwprintf(cmd, size, L"%ls\\%ls", syspath, L"cmd.exe"); - cmd[size-1] = L'\0'; + cmd[size - 1] = L'\0'; size = _countof(netcmd); _snwprintf(netcmd, size, L"%ls\\%ls", syspath, L"net.exe"); - netcmd[size-1] = L'\0'; + netcmd[size - 1] = L'\0'; } - size = (wcslen(fmt) + wcslen(username) + 2*wcslen(group) + 2*wcslen(netcmd)+ 1); - if ((params = malloc(size*sizeof(WCHAR))) == NULL) + size = (wcslen(fmt) + wcslen(username) + 2 * wcslen(group) + 2 * wcslen(netcmd) + 1); + if ((params = malloc(size * sizeof(WCHAR))) == NULL) { return retval; } _snwprintf(params, size, fmt, netcmd, group, netcmd, group, username); - params[size-1] = L'\0'; + params[size - 1] = L'\0'; status = RunAsAdmin(cmd, params); if (status == 0) @@ -151,15 +150,16 @@ AddUserToGroup(const WCHAR *group) } #ifdef DEBUG - if (status == (DWORD) -1) + if (status == (DWORD)-1) { PrintDebug(L"RunAsAdmin: failed to execute the command [%ls %ls] : error = 0x%x", - cmd, params, GetLastError()); + cmd, + params, + GetLastError()); } else if (status) { - PrintDebug(L"RunAsAdmin: command [%ls %ls] returned exit_code = %lu", - cmd, params, status); + PrintDebug(L"RunAsAdmin: command [%ls %ls] returned exit_code = %lu", cmd, params, status); } #endif @@ -206,7 +206,7 @@ AuthorizeConfig(const connection_t *c) WCHAR sysadmin_group[MAX_NAME]; BYTE sid_buf[SECURITY_MAX_SID_SIZE]; DWORD sid_size = SECURITY_MAX_SID_SIZE; - PSID sid = (PSID) sid_buf; + PSID sid = (PSID)sid_buf; PTOKEN_GROUPS groups = NULL; if (GetBuiltinAdminGroupName(sysadmin_group, _countof(sysadmin_group))) @@ -229,13 +229,12 @@ AuthorizeConfig(const connection_t *c) { if (!o.silent_connection) { - MessageBoxW(NULL, L"Failed to determine process owner SID", L""PACKAGE_NAME, MB_OK); + MessageBoxW(NULL, L"Failed to determine process owner SID", L"" PACKAGE_NAME, MB_OK); } return FALSE; } groups = GetProcessTokenGroups(); - if (IsUserInGroup(sid, groups, admin_group) - || IsUserInGroup(sid, groups, o.ovpn_admin_group)) + if (IsUserInGroup(sid, groups, admin_group) || IsUserInGroup(sid, groups, o.ovpn_admin_group)) { free(groups); return TRUE; @@ -243,8 +242,7 @@ AuthorizeConfig(const connection_t *c) free(groups); /* do not attempt to add user to sysadmin_group or a no-name group */ - if (wcscmp(admin_group, o.ovpn_admin_group) == 0 - || wcslen(o.ovpn_admin_group) == 0 + if (wcscmp(admin_group, o.ovpn_admin_group) == 0 || wcslen(o.ovpn_admin_group) == 0 || !o.netcmd_semaphore) { ShowLocalizedMsg(IDS_ERR_CONFIG_NOT_AUTHORIZED, c->config_name, o.ovpn_admin_group); @@ -258,8 +256,11 @@ AuthorizeConfig(const connection_t *c) return FALSE; } /* semaphore locked -- relase before return */ - res = ShowLocalizedMsgEx(MB_YESNO|MB_ICONWARNING, NULL, TEXT(PACKAGE_NAME), - IDS_ERR_CONFIG_TRY_AUTHORIZE, c->config_name, + res = ShowLocalizedMsgEx(MB_YESNO | MB_ICONWARNING, + NULL, + TEXT(PACKAGE_NAME), + IDS_ERR_CONFIG_TRY_AUTHORIZE, + c->config_name, o.ovpn_admin_group); if (res == IDYES) { @@ -364,11 +365,11 @@ IsUserInGroup(PSID sid, const PTOKEN_GROUPS token_groups, const WCHAR *group_nam int nloop = 0; /* a counter used to not get stuck in the do .. while() */ /* first check in the token groups */ - if (token_groups && LookupSID(group_name, (PSID) grp_sid, _countof(grp_sid))) + if (token_groups && LookupSID(group_name, (PSID)grp_sid, _countof(grp_sid))) { for (DWORD i = 0; i < token_groups->GroupCount; ++i) { - if (EqualSid((PSID) grp_sid, token_groups->Groups[i].Sid)) + if (EqualSid((PSID)grp_sid, token_groups->Groups[i].Sid)) { PrintDebug(L"Found group in token at position %lu", i); return TRUE; @@ -385,8 +386,8 @@ IsUserInGroup(PSID sid, const PTOKEN_GROUPS token_groups, const WCHAR *group_nam { DWORD nread, nmax; LOCALGROUP_MEMBERS_INFO_0 *members = NULL; - err = NetLocalGroupGetMembers(NULL, group_name, 0, (LPBYTE *) &members, - MAX_PREFERRED_LENGTH, &nread, &nmax, &resume); + err = NetLocalGroupGetMembers( + NULL, group_name, 0, (LPBYTE *)&members, MAX_PREFERRED_LENGTH, &nread, &nmax, &resume); if (err != NERR_Success && err != ERROR_MORE_DATA) { break; diff --git a/as.c b/as.c index a87595e32..48327b7ba 100644 --- a/as.c +++ b/as.c @@ -32,11 +32,11 @@ #include "openvpn-gui-res.h" #include "save_pass.h" -#define URL_LEN 1024 -#define PROFILE_NAME_LEN 128 -#define READ_CHUNK_LEN 65536 +#define URL_LEN 1024 +#define PROFILE_NAME_LEN 128 +#define READ_CHUNK_LEN 65536 -#define PROFILE_NAME_TOKEN L"# OVPN_ACCESS_SERVER_PROFILE=" +#define PROFILE_NAME_TOKEN L"# OVPN_ACCESS_SERVER_PROFILE=" #define FRIENDLY_NAME_TOKEN L"# OVPN_ACCESS_SERVER_FRIENDLY_NAME=" /** Replace characters not allowed in Windows filenames with '_' */ @@ -69,7 +69,10 @@ SanitizeFilename(wchar_t *fname) * @param out_name_length max length of out_name char array */ void -ExtractProfileName(const WCHAR *profile, const WCHAR *default_name, WCHAR *out_name, size_t out_name_length) +ExtractProfileName(const WCHAR *profile, + const WCHAR *default_name, + WCHAR *out_name, + size_t out_name_length) { WCHAR friendly_name[PROFILE_NAME_LEN] = { 0 }; WCHAR profile_name[PROFILE_NAME_LEN] = { 0 }; @@ -123,9 +126,15 @@ void ShowWinInetError(HANDLE hWnd) { WCHAR err[256] = { 0 }; - FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM, GetModuleHandleW(L"wininet.dll"), - GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err, _countof(err), NULL); - ShowLocalizedMsgEx(MB_OK, hWnd, _T(PACKAGE_NAME), IDS_ERR_URL_IMPORT_PROFILE, GetLastError(), err); + FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM, + GetModuleHandleW(L"wininet.dll"), + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + err, + _countof(err), + NULL); + ShowLocalizedMsgEx( + MB_OK, hWnd, _T(PACKAGE_NAME), IDS_ERR_URL_IMPORT_PROFILE, GetLastError(), err); } struct UrlComponents @@ -185,7 +194,8 @@ ParseUrl(const WCHAR *url, struct UrlComponents *comps) * * @param hWnd handle of window which initiated download * @param hRequest WinInet request handle - * @param pbuf pointer to a buffer, will be allocated by this function. Caller must free it after use. + * @param pbuf pointer to a buffer, will be allocated by this function. Caller must free it after + * use. * @param psize pointer to a profile size, assigned by this function */ BOOL @@ -272,8 +282,8 @@ CRDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) /* disable OK button by default - not disabled in resources */ EnableWindow(GetDlgItem(hwndDlg, IDOK), FALSE); - ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); + ResetPasswordReveal( + GetDlgItem(hwndDlg, ID_EDT_RESPONSE), GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); break; case WM_COMMAND: @@ -285,7 +295,8 @@ CRDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) if (!(param->flags & FLAG_CR_ECHO)) { ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); } if (HIWORD(wParam) == EN_UPDATE) { @@ -295,7 +306,8 @@ CRDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) } break; - case IDOK: { + case IDOK: + { int len = 0; GetDlgItemTextUtf8(hwndDlg, ID_EDT_RESPONSE, ¶m->cr_response, &len); EndDialog(hwndDlg, LOWORD(wParam)); @@ -308,7 +320,8 @@ CRDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) case ID_PASSWORD_REVEAL: /* password reveal symbol clicked */ ChangePasswordVisibility(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); return TRUE; } break; @@ -335,10 +348,12 @@ CRDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) static void GetASUrl(const WCHAR *host, bool autologin, struct UrlComponents *comps) { - ParseUrl(host, comps); - swprintf(comps->path, URL_LEN, L"/rest/%ls?tls-cryptv2=1&action=import", autologin ? L"GetAutologin" : L"GetUserlogin"); + swprintf(comps->path, + URL_LEN, + L"/rest/%ls?tls-cryptv2=1&action=import", + autologin ? L"GetAutologin" : L"GetUserlogin"); comps->path[URL_LEN - 1] = L'\0'; } @@ -368,8 +383,7 @@ ExtractFilenameFromHeader(HINTERNET hRequest, wchar_t *name, size_t len) /* try again with more space */ free(buf); buf = malloc(buflen); - if (!buf - || !HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_DISPOSITION, buf, &buflen, &index)) + if (!buf || !HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_DISPOSITION, buf, &buflen, &index)) { goto done; } @@ -378,7 +392,7 @@ ExtractFilenameFromHeader(HINTERNET hRequest, wchar_t *name, size_t len) /* look for filename= */ char *p = strtok(buf, ";"); char *fn = NULL; - for ( ; p; p = strtok(NULL, ";")) + for (; p; p = strtok(NULL, ";")) { if ((fn = strstr(p, "filename=")) != NULL) { @@ -427,8 +441,12 @@ ExtractFilenameFromHeader(HINTERNET hRequest, wchar_t *name, size_t len) * with the url hostname as a fallback. */ static BOOL -DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *username, - const char *password_orig, WCHAR *out_path, size_t out_path_size) +DownloadProfile(HANDLE hWnd, + const struct UrlComponents *comps, + const char *username, + const char *password_orig, + WCHAR *out_path, + size_t out_path_size) { HANDLE hInternet = NULL; HANDLE hConnect = NULL; @@ -461,7 +479,8 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user /* wait cursor will be automatically reverted later */ SetCursor(LoadCursorW(0, IDC_WAIT)); - hConnect = InternetConnectW(hInternet, comps->host, comps->port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); + hConnect = InternetConnectW( + hInternet, comps->host, comps->port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (!hConnect) { ShowWinInetError(hWnd); @@ -487,8 +506,10 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user /* turns out that *A WinAPI function must be used with UTF-8 encoded parameters to get * correct Base64 encoding (used by Basic HTTP auth) for non-ASCII characters */ - InternetSetOptionA(hRequest, INTERNET_OPTION_USERNAME, (LPVOID)username, (DWORD)strlen(username)); - InternetSetOptionA(hRequest, INTERNET_OPTION_PASSWORD, (LPVOID)password, (DWORD)strlen(password)); + InternetSetOptionA( + hRequest, INTERNET_OPTION_USERNAME, (LPVOID)username, (DWORD)strlen(username)); + InternetSetOptionA( + hRequest, INTERNET_OPTION_PASSWORD, (LPVOID)password, (DWORD)strlen(password)); /* handle cert errors */ /* https://www.betaarchive.com/wiki/index.php/Microsoft_KB_Archive/182888 */ @@ -496,32 +517,34 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user { #ifdef DEBUG DWORD err = GetLastError(); - if ((err == ERROR_INTERNET_INVALID_CA) - || (err == ERROR_INTERNET_SEC_CERT_CN_INVALID) + if ((err == ERROR_INTERNET_INVALID_CA) || (err == ERROR_INTERNET_SEC_CERT_CN_INVALID) || (err == ERROR_INTERNET_SEC_CERT_DATE_INVALID) || (err == ERROR_INTERNET_SEC_CERT_REV_FAILED)) { - /* ask user what to do and modify options if needed */ - DWORD dlg_result = InternetErrorDlg(hWnd, hRequest, + DWORD dlg_result = InternetErrorDlg(hWnd, + hRequest, err, FLAGS_ERROR_UI_FILTER_FOR_ERRORS - |FLAGS_ERROR_UI_FLAGS_GENERATE_DATA - |FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, + | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA + | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); if (dlg_result == ERROR_SUCCESS) { - /* for unknown reasons InternetErrorDlg() doesn't change options for ERROR_INTERNET_SEC_CERT_REV_FAILED, - * despite user is willing to continue, so we have to do it manually */ + /* for unknown reasons InternetErrorDlg() doesn't change options for + * ERROR_INTERNET_SEC_CERT_REV_FAILED, despite user is willing to continue, so we + * have to do it manually */ if (err == ERROR_INTERNET_SEC_CERT_REV_FAILED) { DWORD flags; DWORD len = sizeof(flags); - InternetQueryOptionW(hRequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&flags, &len); + InternetQueryOptionW( + hRequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&flags, &len); flags |= SECURITY_FLAG_IGNORE_REVOCATION; - InternetSetOptionW(hRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, sizeof(flags)); + InternetSetOptionW( + hRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, sizeof(flags)); goto again; } @@ -541,7 +564,8 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user /* get http status code */ DWORD status_code = 0; DWORD length = sizeof(DWORD); - HttpQueryInfoW(hRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &status_code, &length, NULL); + HttpQueryInfoW( + hRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &status_code, &length, NULL); size_t size = 0; @@ -567,7 +591,8 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user if (parse_dynamic_cr(msg_begin + 14, param)) { /* prompt user for dynamic challenge */ - INT_PTR res = LocalizedDialogBoxParam(ID_DLG_CHALLENGE_RESPONSE, CRDialogFunc, (LPARAM)param); + INT_PTR res = + LocalizedDialogBoxParam(ID_DLG_CHALLENGE_RESPONSE, CRDialogFunc, (LPARAM)param); if (res == IDOK) { _snprintf_0(password, "CRV1::%s::%s", param->id, param->cr_response); @@ -589,7 +614,8 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user if (status_code != 200) { - ShowLocalizedMsgEx(MB_OK, hWnd, _T(PACKAGE_NAME), IDS_ERR_URL_IMPORT_PROFILE, status_code, L"HTTP error"); + ShowLocalizedMsgEx( + MB_OK, hWnd, _T(PACKAGE_NAME), IDS_ERR_URL_IMPORT_PROFILE, status_code, L"HTTP error"); goto done; } @@ -601,13 +627,17 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user BOOL res = HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_TYPE, tmp, &len, NULL); if (!res || stricmp(comps->content_type, tmp)) { - ShowLocalizedMsgEx(MB_OK, hWnd, _T(PACKAGE_NAME), IDS_ERR_URL_IMPORT_PROFILE, 0, + ShowLocalizedMsgEx(MB_OK, + hWnd, + _T(PACKAGE_NAME), + IDS_ERR_URL_IMPORT_PROFILE, + 0, L"HTTP content-type mismatch"); goto done; } } - WCHAR name[MAX_PATH] = {0}; + WCHAR name[MAX_PATH] = { 0 }; /* read filename from header or from the profile metadata */ if (strlen(comps->content_type) == 0 /* AS profile */ || !ExtractFilenameFromHeader(hRequest, name, MAX_PATH)) @@ -615,7 +645,8 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user WCHAR *wbuf = Widen(buf); if (!wbuf) { - MessageBoxW(hWnd, L"Failed to convert profile content to wchar", _T(PACKAGE_NAME), MB_OK); + MessageBoxW( + hWnd, L"Failed to convert profile content to wchar", _T(PACKAGE_NAME), MB_OK); goto done; } ExtractProfileName(wbuf, comps->host, name, MAX_PATH); @@ -669,7 +700,8 @@ DownloadProfile(HANDLE hWnd, const struct UrlComponents *comps, const char *user return result; } -typedef enum { +typedef enum +{ server_as = 1, server_generic = 2 } server_type_t; @@ -677,14 +709,14 @@ typedef enum { INT_PTR CALLBACK ImportProfileFromURLDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { - WCHAR url[URL_LEN] = {0}; + WCHAR url[URL_LEN] = { 0 }; BOOL autologin = FALSE; server_type_t type; switch (msg) { case WM_INITDIALOG: - type = (server_type_t) lParam; + type = (server_type_t)lParam; TRY_SETPROP(hwndDlg, cfgProp, (HANDLE)lParam); SetStatusWinIcon(hwndDlg, ID_ICO_APP); @@ -696,17 +728,18 @@ ImportProfileFromURLDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa } /* disable OK button until required data is filled in */ EnableWindow(GetDlgItem(hwndDlg, IDOK), FALSE); - ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); + ResetPasswordReveal( + GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); break; case WM_COMMAND: - type = (server_type_t) GetProp(hwndDlg, cfgProp); + type = (server_type_t)GetProp(hwndDlg, cfgProp); switch (LOWORD(wParam)) { case ID_EDT_AUTH_PASS: ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); /* fall through */ case ID_EDT_AUTH_USER: @@ -714,8 +747,9 @@ ImportProfileFromURLDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa if (HIWORD(wParam) == EN_UPDATE) { /* enable OK button only if url and username are filled */ - BOOL enableOK = GetWindowTextLengthW(GetDlgItem(hwndDlg, ID_EDT_URL)) - && GetWindowTextLengthW(GetDlgItem(hwndDlg, ID_EDT_AUTH_USER)); + BOOL enableOK = + GetWindowTextLengthW(GetDlgItem(hwndDlg, ID_EDT_URL)) + && GetWindowTextLengthW(GetDlgItem(hwndDlg, ID_EDT_AUTH_USER)); EnableWindow(GetDlgItem(hwndDlg, IDOK), enableOK); } break; @@ -733,20 +767,22 @@ ImportProfileFromURLDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa GetDlgItemTextUtf8(hwndDlg, ID_EDT_AUTH_PASS, &password, &password_len); WCHAR path[MAX_PATH + 1] = { 0 }; - struct UrlComponents comps = {0}; + struct UrlComponents comps = { 0 }; if (type == server_as) { - autologin = IsDlgButtonChecked(hwndDlg, ID_CHK_AUTOLOGIN) == BST_CHECKED; GetASUrl(url, autologin, &comps); } else { ParseUrl(url, &comps); - strncpy_s(comps.content_type, _countof(comps.content_type), - "application/x-openvpn-profile", _TRUNCATE); + strncpy_s(comps.content_type, + _countof(comps.content_type), + "application/x-openvpn-profile", + _TRUNCATE); } - BOOL downloaded = DownloadProfile(hwndDlg, &comps, username, password, path, _countof(path)); + BOOL downloaded = + DownloadProfile(hwndDlg, &comps, username, password, path, _countof(path)); if (username_len > 0) { @@ -774,7 +810,8 @@ ImportProfileFromURLDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa case ID_PASSWORD_REVEAL: /* password reveal symbol clicked */ ChangePasswordVisibility(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); return TRUE; } break; @@ -795,11 +832,13 @@ ImportProfileFromURLDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa void ImportConfigFromAS() { - LocalizedDialogBoxParam(ID_DLG_URL_PROFILE_IMPORT, ImportProfileFromURLDialogFunc, (LPARAM) server_as); + LocalizedDialogBoxParam( + ID_DLG_URL_PROFILE_IMPORT, ImportProfileFromURLDialogFunc, (LPARAM)server_as); } void ImportConfigFromURL() { - LocalizedDialogBoxParam(ID_DLG_URL_PROFILE_IMPORT, ImportProfileFromURLDialogFunc, (LPARAM) server_generic); + LocalizedDialogBoxParam( + ID_DLG_URL_PROFILE_IMPORT, ImportProfileFromURLDialogFunc, (LPARAM)server_generic); } diff --git a/chartable.h b/chartable.h index 9b780c2b8..17fe1d054 100644 --- a/chartable.h +++ b/chartable.h @@ -20,260 +20,26 @@ */ WCHAR unicode_to_ascii[256] = { - 0x0000, - 0x0001, - 0x0002, - 0x0003, - 0x0004, - 0x0005, - 0x0006, - 0x0007, - 0x0008, - 0x0009, - 0x000a, - 0x000b, - 0x000c, - 0x000d, - 0x000e, - 0x000f, - 0x0010, - 0x0011, - 0x0012, - 0x0013, - 0x0014, - 0x0015, - 0x0016, - 0x0017, - 0x0018, - 0x0019, - 0x001a, - 0x001b, - 0x001c, - 0x001d, - 0x001e, - 0x001f, - 0x0020, - 0x0021, - 0x0022, - 0x0023, - 0x0024, - 0x0025, - 0x0026, - 0x0027, - 0x0028, - 0x0029, - 0x002a, - 0x002b, - 0x002c, - 0x002d, - 0x002e, - 0x002f, - 0x0030, - 0x0031, - 0x0032, - 0x0033, - 0x0034, - 0x0035, - 0x0036, - 0x0037, - 0x0038, - 0x0039, - 0x003a, - 0x003b, - 0x003c, - 0x003d, - 0x003e, - 0x003f, - 0x0040, - 0x0041, - 0x0042, - 0x0043, - 0x0044, - 0x0045, - 0x0046, - 0x0047, - 0x0048, - 0x0049, - 0x004a, - 0x004b, - 0x004c, - 0x004d, - 0x004e, - 0x004f, - 0x0050, - 0x0051, - 0x0052, - 0x0053, - 0x0054, - 0x0055, - 0x0056, - 0x0057, - 0x0058, - 0x0059, - 0x005a, - 0x005b, - 0x005c, - 0x005d, - 0x005e, - 0x005f, - 0x0060, - 0x0061, - 0x0062, - 0x0063, - 0x0064, - 0x0065, - 0x0066, - 0x0067, - 0x0068, - 0x0069, - 0x006a, - 0x006b, - 0x006c, - 0x006d, - 0x006e, - 0x006f, - 0x0070, - 0x0071, - 0x0072, - 0x0073, - 0x0074, - 0x0075, - 0x0076, - 0x0077, - 0x0078, - 0x0079, - 0x007a, - 0x007b, - 0x007c, - 0x007d, - 0x007e, - 0x007f, - 0x00c7, - 0x00fc, - 0x00e9, - 0x00e2, - 0x00e4, - 0x00e0, - 0x00e5, - 0x00e7, - 0x00ea, - 0x00eb, - 0x00e8, - 0x00ef, - 0x00ee, - 0x00ec, - 0x00c4, - 0x00c5, - 0x00c9, - 0x00e6, - 0x00c6, - 0x00f4, - 0x00f6, - 0x00f2, - 0x00fb, - 0x00f9, - 0x00ff, - 0x00d6, - 0x00dc, - 0x00f8, - 0x00a3, - 0x00d8, - 0x00d7, - 0x0192, - 0x00e1, - 0x00ed, - 0x00f3, - 0x00fa, - 0x00f1, - 0x00d1, - 0x00aa, - 0x00ba, - 0x00bf, - 0x00ae, - 0x00ac, - 0x00bd, - 0x00bc, - 0x00a1, - 0x00ab, - 0x00bb, - 0x2591, - 0x2592, - 0x2593, - 0x2502, - 0x2524, - 0x00c1, - 0x00c2, - 0x00c0, - 0x00a9, - 0x2563, - 0x2551, - 0x2557, - 0x255d, - 0x00a2, - 0x00a5, - 0x2510, - 0x2514, - 0x2534, - 0x252c, - 0x251c, - 0x2500, - 0x253c, - 0x00e3, - 0x00c3, - 0x255a, - 0x2554, - 0x2569, - 0x2566, - 0x2560, - 0x2550, - 0x256c, - 0x00a4, - 0x00f0, - 0x00d0, - 0x00ca, - 0x00cb, - 0x00c8, - 0x0131, - 0x00cd, - 0x00ce, - 0x00cf, - 0x2518, - 0x250c, - 0x2588, - 0x2584, - 0x00a6, - 0x00cc, - 0x2580, - 0x00d3, - 0x00df, - 0x00d4, - 0x00d2, - 0x00f5, - 0x00d5, - 0x00b5, - 0x00fe, - 0x00de, - 0x00da, - 0x00db, - 0x00d9, - 0x00fd, - 0x00dd, - 0x00af, - 0x00b4, - 0x00ad, - 0x00b1, - 0x2017, - 0x00be, - 0x00b6, - 0x00a7, - 0x00f7, - 0x00b8, - 0x00b0, - 0x00a8, - 0x00b7, - 0x00b9, - 0x00b3, - 0x00b2, - 0x25a0, - 0x00a0 + 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, + 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, + 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, + 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, + 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, + 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, + 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, + 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, + 0x006c, 0x006d, 0x006e, 0x006f, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, + 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, 0x00c7, 0x00fc, 0x00e9, 0x00e2, + 0x00e4, 0x00e0, 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5, + 0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, 0x00ff, 0x00d6, 0x00dc, 0x00f8, + 0x00a3, 0x00d8, 0x00d7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba, + 0x00bf, 0x00ae, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, 0x2591, 0x2592, 0x2593, 0x2502, + 0x2524, 0x00c1, 0x00c2, 0x00c0, 0x00a9, 0x2563, 0x2551, 0x2557, 0x255d, 0x00a2, 0x00a5, 0x2510, + 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x00e3, 0x00c3, 0x255a, 0x2554, 0x2569, 0x2566, + 0x2560, 0x2550, 0x256c, 0x00a4, 0x00f0, 0x00d0, 0x00ca, 0x00cb, 0x00c8, 0x0131, 0x00cd, 0x00ce, + 0x00cf, 0x2518, 0x250c, 0x2588, 0x2584, 0x00a6, 0x00cc, 0x2580, 0x00d3, 0x00df, 0x00d4, 0x00d2, + 0x00f5, 0x00d5, 0x00b5, 0x00fe, 0x00de, 0x00da, 0x00db, 0x00d9, 0x00fd, 0x00dd, 0x00af, 0x00b4, + 0x00ad, 0x00b1, 0x2017, 0x00be, 0x00b6, 0x00a7, 0x00f7, 0x00b8, 0x00b0, 0x00a8, 0x00b7, 0x00b9, + 0x00b3, 0x00b2, 0x25a0, 0x00a0 }; diff --git a/config_parser.c b/config_parser.c index 9b854f011..a1bad7384 100644 --- a/config_parser.c +++ b/config_parser.c @@ -49,9 +49,9 @@ copy_token(wchar_t **dest, wchar_t **src, wchar_t *delim) wchar_t *s = *dest; /* copy src to dest until delim character with escaped chars converted */ - for ( ; *p != L'\0' && wcschr(delim, *p) == NULL; p++, s++) + for (; *p != L'\0' && wcschr(delim, *p) == NULL; p++, s++) { - if (*p == L'\\' && legal_escape(*(p+1))) + if (*p == L'\\' && legal_escape(*(p + 1))) { *s = *(++p); } @@ -81,7 +81,7 @@ tokenize(config_entry_t *ce) unsigned int i = 0; int status = 0; - for ( ; *p != L'\0'; p++, s++) + for (; *p != L'\0'; p++, s++) { if (*p == L' ' || *p == L'\t') { @@ -140,7 +140,7 @@ config_readline(FILE *fd, int first) char tmp[MAX_LINE_LENGTH]; int offset = 0; - if (fgets(tmp, _countof(tmp)-1, fd) == NULL) + if (fgets(tmp, _countof(tmp) - 1, fd) == NULL) { return NULL; } @@ -157,7 +157,7 @@ config_readline(FILE *fd, int first) return NULL; } - mbstowcs(ce->line, &tmp[offset], _countof(ce->line)-1); + mbstowcs(ce->line, &tmp[offset], _countof(ce->line) - 1); len = wcscspn(ce->line, L"\n\r"); ce->line[len] = L'\0'; diff --git a/config_parser.h b/config_parser.h index c369fe915..0b65a0609 100644 --- a/config_parser.h +++ b/config_parser.h @@ -26,7 +26,8 @@ typedef struct config_entry config_entry_t; -struct config_entry { +struct config_entry +{ wchar_t line[MAX_LINE_LENGTH]; wchar_t sline[MAX_LINE_LENGTH]; wchar_t *tokens[16]; diff --git a/dev-tools/git-pre-commit-uncrustify.sh b/dev-tools/git-pre-commit-uncrustify.sh deleted file mode 100755 index 9851c212f..000000000 --- a/dev-tools/git-pre-commit-uncrustify.sh +++ /dev/null @@ -1,161 +0,0 @@ -#!/bin/sh - -# Copyright (c) 2015, David Martin -# 2022, Heiko Hund -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -# git pre-commit hook that runs an Uncrustify stylecheck. -# Features: -# - abort commit when commit does not comply with the style guidelines -# - create a patch of the proposed style changes -# -# More info on Uncrustify: http://uncrustify.sourceforge.net/ - -# This file was taken from a set of unofficial pre-commit hooks available -# at https://github.com/ddddavidmartin/Pre-commit-hooks and modified to -# fit the openvpn project's needs - -# exit on error -set -e - - -# If called so, install this script as pre-commit hook -if [ "$1" = "install" ] ; then - TARGET="$(git rev-parse --git-path hooks)/pre-commit" - - if [ -e "$TARGET" ] ; then - printf "$TARGET file exists. Won't overwrite.\n" - printf "Aborting installation.\n" - exit 1 - fi - - read -p "Install as $TARGET? [y/N] " INPUT - [ "$INPUT" = "y" ] || exit 0 - cp "$0" "$TARGET" - chmod +x $TARGET - exit 0 -fi - -# check whether the given file matches any of the set extensions -matches_extension() { - local filename="$(basename -- "$1")" - local extension=".${filename##*.}" - local ext - - for ext in .c .h ; do [ "$ext" = "$extension" ] && return 0; done - - return 1 -} - -# necessary check for initial commit -if git rev-parse --verify HEAD >/dev/null 2>&1 ; then - against=HEAD -else - # Initial commit: diff against an empty tree object - against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 -fi - -UNCRUSTIFY=$(command -v uncrustify) -UNCRUST_CONFIG="$(git rev-parse --show-toplevel)/dev-tools/uncrustify.conf" - -# make sure the config file and executable are correctly set -if [ ! -f "$UNCRUST_CONFIG" ] ; then - printf "Error: uncrustify config file not found.\n" - printf "Expected to find it at $UNCRUST_CONFIG.\n" - printf "Aborting commit.\n" - exit 1 -fi - -if [ -z "$UNCRUSTIFY" ] ; then - printf "Error: uncrustify executable not found.\n" - printf "Is it installed and in your \$PATH?\n" - printf "Aborting commit.\n" - exit 1 -fi - -# create a filename to store our generated patch -patch=$(mktemp /tmp/ovpn-fmt-XXXXXX) -tmpout=$(mktemp /tmp/uncrustify-XXXXXX) - -# create one patch containing all changes to the files -# sed to remove quotes around the filename, if inserted by the system -# (done sometimes, if the filename contains special characters, like the quote itself) -git diff-index --cached --diff-filter=ACMR --name-only $against -- | \ -sed -e 's/^"\(.*\)"$/\1/' | \ -while read file -do - # ignore file if we do check for file extensions and the file - # does not match the extensions .c or .h - if ! matches_extension "$file"; then - continue; - fi - - # escape special characters in the target filename: - # phase 1 (characters escaped in the output diff): - # - '\': backslash needs to be escaped in the output diff - # - '"': quote needs to be escaped in the output diff if present inside - # of the filename, as it used to bracket the entire filename part - # phase 2 (characters escaped in the match replacement): - # - '\': backslash needs to be escaped again for sed itself - # (i.e. double escaping after phase 1) - # - '&': would expand to matched string - # - '|': used as sed split char instead of '/' - # printf %s particularly important if the filename contains the % character - file_escaped_target=$(printf "%s" "$file" | sed -e 's/[\"]/\\&/g' -e 's/[\&|]/\\&/g') - - # uncrustify our sourcefile, create a patch with diff and append it to our $patch - # The sed call is necessary to transform the patch from - # --- - timestamp - # +++ $tmpout timestamp - # to both lines working on the same file and having a a/ and b/ prefix. - # Else it can not be applied with 'git apply'. - git show ":$file" | "$UNCRUSTIFY" -q -l C -c "$UNCRUST_CONFIG" -o "$tmpout" - git show ":$file" | diff -u -- - "$tmpout" | \ - sed -e "1s|--- -|--- \"b/$file_escaped_target\"|" -e "2s|+++ $tmpout|+++ \"a/$file_escaped_target\"|" >> "$patch" -done - -rm -f "$tmpout" - -# if no patch has been generated all is ok, clean up the file stub and exit -if [ ! -s "$patch" ] ; then - rm -f "$patch" - exit 0 -fi - -# a patch has been created, notify the user and exit -printf "Formatting of some code does not follow the project guidelines.\n" - -if [ $(wc -l < $patch) -gt 80 ] ; then - printf "The file $patch contains the necessary fixes.\n" -else - printf "Here's the patch that fixes the formatting:\n\n" - cat $patch -fi - -printf "\nYou can apply these changes with:\n git apply $patch\n" -printf "(from the root directory of the repository) and then commit again.\n" -printf "\nAborting commit.\n" - -exit 1 diff --git a/dev-tools/reformat-all.sh b/dev-tools/reformat-all.sh deleted file mode 100755 index ed472289d..000000000 --- a/dev-tools/reformat-all.sh +++ /dev/null @@ -1,136 +0,0 @@ -#!/bin/sh -# reformat-all.sh - Reformat all git files in the checked out -# git branch using uncrustify. -# -# Copyright (C) 2016-2023 - David Sommerseth -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# - -tstamp="$(date +%Y%m%d-%H%M%S)" -files="$(pwd)/reformat-all_files-$tstamp.lst" -log="$(pwd)/reformat-all_log-$tstamp.txt" - -srcroot="$(git rev-parse --show-toplevel)" -cfg="$srcroot/dev-tools/uncrustify.conf" -specialfiles="$srcroot/dev-tools/special-files.lst" - -export gitfiles=0 -export procfiles=0 - -# Go to the root of the source tree -cd "$srcroot" - -{ - echo -n "** Starting $0: " - date - - # Find all C source/header files - git ls-files | grep -E ".*\.[ch](\.in$|$)" > "${files}.git" - - # Manage files which needs special treatment - awk -F\# '{gsub("\n| ", "", $1); print $1}' "$specialfiles" > "${files}.sp" - while read srcfile - do - res=$(grep "$srcfile" "${files}.sp" 2>/dev/null) - if [ $? -ne 0 ]; then - # If grep didn't find the file among special files, - # process it normally - echo "$srcfile" >> "$files" - else - mode=$(echo "$res" | cut -d: -f1) - case "$mode" in - E) - echo "** INFO ** Excluding '$srcfile'" - ;; - P) - echo "** INFO ** Pre-patching '$srcfile'" - patchfile="${srcroot}"/dev-tools/reformat-patches/before_$(echo "$srcfile" | tr "/" "_").patch - if [ -r "$patchfile" ]; then - git apply "$patchfile" - if [ $? -ne 0 ]; then - echo "** ERROR ** Failed to apply pre-patch file: $patchfile" - exit 2 - fi - else - echo "** WARN ** Pre-patch file for $srcfile is missing: $patchfile" - fi - echo "$srcfile" >> "${files}.postpatch" - echo "$srcfile" >> "$files" - ;; - *) - echo "** WARN ** Unknown mode '$mode' for file '$srcfile'" - ;; - esac - fi - done < "${files}.git" - rm -f "${files}.git" "${files}.sp" - - # Kick off uncrustify - echo - echo "** INFO ** Running: uncrustify -c $cfg --no-backup -l C -F $files" - uncrustify -c "$cfg" --no-backup -l C -F "$files" 2>&1 - res=$? - echo "** INFO ** Uncrustify completed (exit code $res)" -} | tee "${log}-1" # Log needs to be closed here, to be processed in next block - -{ - # Check the results - gitfiles=$(wc -l "$files" | cut -d\ -f1) - procfiles=$(grep "Parsing: " "${log}-1" | wc -l) - echo - echo "C source/header files checked into git: $gitfiles" - echo "Files processed by uncrustify: $procfiles" - echo - - # Post-Patch files modified after we uncrustify have adjusted them - if [ -r "${files}.postpatch" ]; then - while read srcfile; - do - patchfile="${srcroot}"/dev-tools/reformat-patches/after_$(echo "$srcfile" | tr "/" "_").patch - if [ -r "$patchfile" ]; then - echo "** INFO ** Post-patching '$srcfile'" - git apply "$patchfile" - if [ $? -ne 0 ]; then - echo "** WARN ** Failed to apply $patchfile" - fi - else - echo "** WARN ** Post-patch file for $srcfile is missing: $patchfile" - fi - done < "${files}.postpatch" - rm -f "${files}.postpatch" - fi -} | tee "${log}-2" # Log needs to be closed here, to be processed in next block - -cat "${log}-1" "${log}-2" > "$log" - -{ - ec=1 - echo - if [ "$gitfiles" -eq "$procfiles" ]; then - echo "Reformatting completed successfully" - ec=0 - else - last=$(tail -n1 "${log}-1") - echo "** ERROR ** Reformating failed to process all files." - echo " uncrustify exit code: $res" - echo " Last log line: $last" - echo - fi - rm -f "${log}-1" "${log}-2" -} | tee -a "$log" -rm -f "${files}" - -exit $ec diff --git a/dev-tools/special-files.lst b/dev-tools/special-files.lst deleted file mode 100644 index e69de29bb..000000000 diff --git a/dev-tools/uncrustify.conf b/dev-tools/uncrustify.conf deleted file mode 100644 index 325f3108c..000000000 --- a/dev-tools/uncrustify.conf +++ /dev/null @@ -1,79 +0,0 @@ -# Use Allman-style -indent_columns=4 -indent_braces=false -indent_else_if=false -indent_switch_case=4 -indent_label=1 -nl_if_brace=add -nl_brace_else=add -nl_elseif_brace=add -nl_else_brace=add -nl_else_if=remove -nl_for_brace=add -nl_while_brace=add -nl_switch_brace=add -nl_fdef_brace=add -nl_do_brace=add -sp_func_proto_paren=Remove -sp_func_def_paren=Remove -sp_func_call_paren=Remove -sp_sizeof_paren=Remove - -# No tabs, spaces only -indent_with_tabs=0 -align_with_tabs=false -cmt_convert_tab_to_spaces=true - -# Do not put spaces between the # and preprocessor statements -pp_space=remove - -# Various whitespace fiddling -sp_assign=add -sp_before_sparen=add -sp_inside_sparen=remove -sp_cond_colon=add -sp_cond_question=add -sp_bool=add -sp_else_brace=add -sp_brace_else=add -sp_after_comma=add -pos_arith=Lead -pos_bool=Lead -nl_func_type_name=add -nl_before_case=true -nl_assign_leave_one_liners=true -nl_enum_leave_one_liners=true -nl_brace_fparen=add -nl_max=4 -nl_after_func_proto=2 -nl_end_of_file_min=1 -nl_end_of_file=force - -# Always use scoping braces for conditionals -mod_full_brace_if=add -mod_full_brace_if_chain=false -mod_full_brace_while=add -mod_full_brace_for=add -mod_full_brace_do=add - -# Annotate #else and #endif statements -mod_add_long_ifdef_endif_comment=20 -mod_add_long_ifdef_else_comment=5 - -# Misc cleanup -mod_remove_extra_semicolon=true - -# leave blank at end of empty for() statements -sp_after_semi_for_empty=Add - -# Use C-style comments (/* .. */) -cmt_c_nl_end=true -cmt_star_cont=true -cmt_cpp_to_c=true - -# Use "char **a"-style pointer stars/dereferences -sp_before_ptr_star=Add -sp_between_ptr_star=Remove -sp_after_ptr_star=Remove -sp_before_byref=Add -sp_after_byref=Remove diff --git a/echo.c b/echo.c index a51ac18d3..093931b24 100644 --- a/echo.c +++ b/echo.c @@ -43,9 +43,10 @@ extern options_t o; #define ECHO_MSG_NOTIFY (2) /* Old text in the window is deleted when content grows beyond this many lines */ -#define MAX_MSG_LINES 1000 +#define MAX_MSG_LINES 1000 -struct echo_msg_history { +struct echo_msg_history +{ struct echo_msg_fp fp; struct echo_msg_history *next; }; @@ -55,16 +56,17 @@ struct echo_msg_history { static HWND echo_msg_window; /* Forward declarations */ -static void -AddMessageBoxText(HWND hwnd, const wchar_t *text, const wchar_t *title, const wchar_t *from); +static void AddMessageBoxText(HWND hwnd, + const wchar_t *text, + const wchar_t *title, + const wchar_t *from); -static INT_PTR CALLBACK -MessageDialogFunc(HWND hwnd, UINT msg, UNUSED WPARAM wParam, LPARAM lParam); +static INT_PTR CALLBACK MessageDialogFunc(HWND hwnd, UINT msg, UNUSED WPARAM wParam, LPARAM lParam); void echo_msg_init(void) { - echo_msg_window = CreateLocalizedDialogParam(ID_DLG_MESSAGE, MessageDialogFunc, (LPARAM) 0); + echo_msg_window = CreateLocalizedDialogParam(ID_DLG_MESSAGE, MessageDialogFunc, (LPARAM)0); if (!echo_msg_window) { @@ -83,8 +85,8 @@ echo_msg_add_fp(struct echo_msg *msg, time_t timestamp) { return; } - md_update(&ctx, (BYTE *) msg->text, msg->txtlen*sizeof(msg->text[0])); - md_update(&ctx, (BYTE *) msg->title, wcslen(msg->title)*sizeof(msg->title[0])); + md_update(&ctx, (BYTE *)msg->text, msg->txtlen * sizeof(msg->text[0])); + md_update(&ctx, (BYTE *)msg->title, wcslen(msg->title) * sizeof(msg->title[0])); md_final(&ctx, msg->fp.digest); return; } @@ -126,7 +128,7 @@ echo_msg_save(struct echo_msg *msg) { hist->fp.timestamp = msg->fp.timestamp; } - else /* add */ + else /* add */ { msg->history = echo_msg_history_add(msg->history, &msg->fp); } @@ -144,7 +146,7 @@ echo_msg_persist(connection_t *c) len++; if (len > 99) { - break; /* max 100 history items persisted */ + break; /* max 100 history items persisted */ } } if (len == 0) @@ -152,7 +154,7 @@ echo_msg_persist(connection_t *c) return; } - size_t size = len*sizeof(struct echo_msg_fp); + size_t size = len * sizeof(struct echo_msg_fp); struct echo_msg_fp *data = malloc(size); if (data == NULL) { @@ -165,9 +167,10 @@ echo_msg_persist(connection_t *c) { data[i++] = hist->fp; } - if (!SetConfigRegistryValueBinary(c->config_name, L"echo_msg_history", (BYTE *) data, size)) + if (!SetConfigRegistryValueBinary(c->config_name, L"echo_msg_history", (BYTE *)data, size)) { - WriteStatusLog(c, L"GUI> ", L"Failed to persist echo msg history: error writing to registry", false); + WriteStatusLog( + c, L"GUI> ", L"Failed to persist echo msg history: error writing to registry", false); } free(data); @@ -186,19 +189,19 @@ echo_msg_load(connection_t *c) { return; /* no history in registry */ } - else if (size%item_len != 0) + else if (size % item_len != 0) { WriteStatusLog(c, L"GUI> ", L"echo msg history in registry has invalid size", false); return; } data = malloc(size); - if (!data || !GetConfigRegistryValue(c->config_name, L"echo_msg_history", (BYTE *) data, size)) + if (!data || !GetConfigRegistryValue(c->config_name, L"echo_msg_history", (BYTE *)data, size)) { goto out; } - size_t len = size/item_len; + size_t len = size / item_len; for (size_t i = 0; i < len; i++) { c->echo_msg.history = echo_msg_history_add(c->echo_msg.history, &data[i]); @@ -215,7 +218,7 @@ echo_msg_repeated(const struct echo_msg *msg) const struct echo_msg_history *hist; hist = echo_msg_recall(msg->fp.digest, msg->history); - return (hist && (hist->fp.timestamp + o.popup_mute_interval*3600 > msg->fp.timestamp)); + return (hist && (hist->fp.timestamp + o.popup_mute_interval * 3600 > msg->fp.timestamp)); } /* Append a line of echo msg */ @@ -231,21 +234,21 @@ echo_msg_append(connection_t *c, time_t UNUSED timestamp, const char *msg, BOOL goto out; } - size_t len = c->echo_msg.txtlen + wcslen(wmsg) + 1; /* including null terminator */ + size_t len = c->echo_msg.txtlen + wcslen(wmsg) + 1; /* including null terminator */ if (addnl) { eol = L"\r\n"; len += 2; } - WCHAR *s = realloc(c->echo_msg.text, len*sizeof(WCHAR)); + WCHAR *s = realloc(c->echo_msg.text, len * sizeof(WCHAR)); if (!s) { WriteStatusLog(c, L"GUI> ", L"Error: out of memory while processing echo msg", false); goto out; } - swprintf(s + c->echo_msg.txtlen, len - c->echo_msg.txtlen, L"%ls%ls", wmsg, eol); + swprintf(s + c->echo_msg.txtlen, len - c->echo_msg.txtlen, L"%ls%ls", wmsg, eol); - s[len-1] = L'\0'; + s[len - 1] = L'\0'; c->echo_msg.text = s; c->echo_msg.txtlen = len - 1; /* exclude null terminator */ @@ -266,7 +269,8 @@ echo_msg_display(connection_t *c, time_t timestamp, const char *title, int type) } else { - WriteStatusLog(c, L"GUI> ", L"Error: out of memory converting echo message title to widechar", false); + WriteStatusLog( + c, L"GUI> ", L"Error: out of memory converting echo message title to widechar", false); c->echo_msg.title = L"Message from server"; } echo_msg_add_fp(&c->echo_msg, timestamp); /* add fingerprint: digest+timestamp */ @@ -281,7 +285,9 @@ echo_msg_display(connection_t *c, time_t timestamp, const char *title, int type) DWORD_PTR res; UINT timeout = 5000; /* msec */ if (echo_msg_window - && SendMessageTimeout(echo_msg_window, WM_OVPN_ECHOMSG, 0, (LPARAM) c, SMTO_BLOCK, timeout, &res) == 0) + && SendMessageTimeout( + echo_msg_window, WM_OVPN_ECHOMSG, 0, (LPARAM)c, SMTO_BLOCK, timeout, &res) + == 0) { WriteStatusLog(c, L"GUI> Failed to display echo message: ", c->echo_msg.title, false); } @@ -312,7 +318,7 @@ echo_msg_process(connection_t *c, time_t timestamp, const char *s) } else if (streq(msg, "msg")) /* empty msg is treated as a new line */ { - echo_msg_append(c, timestamp, msg+3, true); + echo_msg_append(c, timestamp, msg + 3, true); } else if (strbegins(msg, "msg-n ")) { @@ -377,11 +383,11 @@ get_text_in_range(HWND h, CHARRANGE chrg) } size_t len = chrg.cpMax - chrg.cpMin; - wchar_t *txt = malloc((len + 1)*sizeof(wchar_t)); + wchar_t *txt = malloc((len + 1) * sizeof(wchar_t)); if (txt) { - TEXTRANGEW txtrg = {chrg, txt}; + TEXTRANGEW txtrg = { chrg, txt }; if (SendMessage(h, EM_GETTEXTRANGE, 0, (LPARAM)&txtrg) <= 0) { txt[0] = '\0'; @@ -428,7 +434,7 @@ static void AddMessageBoxText(HWND hwnd, const wchar_t *text, const wchar_t *title, const wchar_t *from) { HWND hmsg = GetDlgItem(hwnd, ID_TXT_MESSAGE); - DWORD align[2] = {PFA_LEFT, PFA_RIGHT}; /* default alignments for text and title */ + DWORD align[2] = { PFA_LEFT, PFA_RIGHT }; /* default alignments for text and title */ if (LangFlowDirection() == 1) { @@ -439,57 +445,57 @@ AddMessageBoxText(HWND hwnd, const wchar_t *text, const wchar_t *title, const wc /* Start adding new message at the top */ SendMessage(hmsg, EM_SETSEL, 0, 0); - CHARFORMATW cfm = {.cbSize = sizeof(CHARFORMATW) }; + CHARFORMATW cfm = { .cbSize = sizeof(CHARFORMATW) }; /* save current alignment */ - PARAFORMAT pf = {.cbSize = sizeof(PARAFORMAT) }; - SendMessage(hmsg, EM_GETPARAFORMAT, 0, (LPARAM) &pf); + PARAFORMAT pf = { .cbSize = sizeof(PARAFORMAT) }; + SendMessage(hmsg, EM_GETPARAFORMAT, 0, (LPARAM)&pf); WORD pf_align_saved = pf.dwMask & PFM_ALIGNMENT ? pf.wAlignment : align[0]; pf.dwMask |= PFM_ALIGNMENT; if (from && wcslen(from)) { /* Change font to italics */ - SendMessage(hmsg, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &cfm); + SendMessage(hmsg, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cfm); cfm.dwMask |= CFM_ITALIC; cfm.dwEffects |= CFE_ITALIC; - SendMessage(hmsg, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cfm); + SendMessage(hmsg, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cfm); /* Align to right */ pf.wAlignment = align[1]; - SendMessage(hmsg, EM_SETPARAFORMAT, 0, (LPARAM) &pf); - SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM) from); - SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM) L"\n"); + SendMessage(hmsg, EM_SETPARAFORMAT, 0, (LPARAM)&pf); + SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM)from); + SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM)L"\n"); } pf.wAlignment = align[0]; - SendMessage(hmsg, EM_SETPARAFORMAT, 0, (LPARAM) &pf); + SendMessage(hmsg, EM_SETPARAFORMAT, 0, (LPARAM)&pf); if (title && wcslen(title)) { /* Increase font size and set font color for title of the message */ - SendMessage(hmsg, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &cfm); - cfm.dwMask |= CFM_SIZE|CFM_COLOR; + SendMessage(hmsg, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cfm); + cfm.dwMask |= CFM_SIZE | CFM_COLOR; cfm.yHeight = MulDiv(cfm.yHeight, 4, 3); /* scale up by 1.33: 12 pt if default is 9 pt */ cfm.crTextColor = RGB(0, 0x33, 0x99); cfm.dwEffects = 0; - SendMessage(hmsg, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cfm); - SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM) title); - SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM) L"\n"); + SendMessage(hmsg, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cfm); + SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM)title); + SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM)L"\n"); } /* Revert to default font and set the text */ - SendMessage(hmsg, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &cfm); - SendMessage(hmsg, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cfm); + SendMessage(hmsg, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cfm); + SendMessage(hmsg, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cfm); if (text) { - SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM) text); - SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM) L"\n"); + SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM)text); + SendMessage(hmsg, EM_REPLACESEL, FALSE, (LPARAM)L"\n"); } /* revert alignment */ pf.wAlignment = pf_align_saved; - SendMessage(hmsg, EM_SETPARAFORMAT, 0, (LPARAM) &pf); + SendMessage(hmsg, EM_SETPARAFORMAT, 0, (LPARAM)&pf); /* Remove lines from the window if it is getting full * We allow the window to grow by upto 50 lines beyond a @@ -528,12 +534,14 @@ MessageDialogFunc(HWND hwnd, UINT msg, UNUSED WPARAM wParam, LPARAM lParam) hIcon = LoadLocalizedIcon(ID_ICO_APP); if (hIcon) { - SendMessage(hwnd, WM_SETICON, (WPARAM) (ICON_SMALL), (LPARAM) (hIcon)); - SendMessage(hwnd, WM_SETICON, (WPARAM) (ICON_BIG), (LPARAM) (hIcon)); + SendMessage(hwnd, WM_SETICON, (WPARAM)(ICON_SMALL), (LPARAM)(hIcon)); + SendMessage(hwnd, WM_SETICON, (WPARAM)(ICON_BIG), (LPARAM)(hIcon)); } hmsg = GetDlgItem(hwnd, ID_TXT_MESSAGE); SetWindowText(hwnd, L"OpenVPN Messages"); - SendMessage(hmsg, EM_SETMARGINS, EC_LEFTMARGIN|EC_RIGHTMARGIN, + SendMessage(hmsg, + EM_SETMARGINS, + EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELPARAM(side_margin, side_margin)); if (LangFlowDirection() == 1) { @@ -550,8 +558,8 @@ MessageDialogFunc(HWND hwnd, UINT msg, UNUSED WPARAM wParam, LPARAM lParam) GetWindowRect(hwnd, &rc); OffsetRect(&rc, -rc.left, -rc.top); int ox = GetSystemMetrics(SM_CXSCREEN); /* screen size along x */ - ox -= rc.right + DPI_SCALE(rand()%50 + 25); - int oy = DPI_SCALE(rand()%50 + 25); + ox -= rc.right + DPI_SCALE(rand() % 50 + 25); + int oy = DPI_SCALE(rand() % 50 + 25); SetWindowPos(hwnd, HWND_TOP, ox > 0 ? ox : 0, oy, 0, 0, SWP_NOSIZE); return TRUE; @@ -559,14 +567,14 @@ MessageDialogFunc(HWND hwnd, UINT msg, UNUSED WPARAM wParam, LPARAM lParam) case WM_SIZE: hmsg = GetDlgItem(hwnd, ID_TXT_MESSAGE); /* leave some space as top margin */ - SetWindowPos(hmsg, NULL, 0, top_margin, LOWORD(lParam), HIWORD(lParam)-top_margin, 0); + SetWindowPos(hmsg, NULL, 0, top_margin, LOWORD(lParam), HIWORD(lParam) - top_margin, 0); InvalidateRect(hwnd, NULL, TRUE); break; /* set the whole client area background to white */ case WM_CTLCOLORDLG: case WM_CTLCOLORSTATIC: - return (INT_PTR) GetStockObject(WHITE_BRUSH); + return (INT_PTR)GetStockObject(WHITE_BRUSH); break; case WM_COMMAND: @@ -589,14 +597,15 @@ MessageDialogFunc(HWND hwnd, UINT msg, UNUSED WPARAM wParam, LPARAM lParam) */ case WM_OVPN_ECHOMSG: { - connection_t *c = (connection_t *) lParam; + connection_t *c = (connection_t *)lParam; wchar_t from[256]; - _sntprintf_0(from, L"From: %ls %ls", c->config_name, _wctime(&c->echo_msg.fp.timestamp)); + _sntprintf_0( + from, L"From: %ls %ls", c->config_name, _wctime(&c->echo_msg.fp.timestamp)); /* strip \n added by _wctime */ if (wcslen(from) > 0) { - from[wcslen(from)-1] = L'\0'; + from[wcslen(from) - 1] = L'\0'; } AddMessageBoxText(hwnd, c->echo_msg.text, c->echo_msg.title, from); @@ -606,7 +615,7 @@ MessageDialogFunc(HWND hwnd, UINT msg, UNUSED WPARAM wParam, LPARAM lParam) break; case WM_NOTIFY: - nmh = (NMHDR *) lParam; + nmh = (NMHDR *)lParam; /* We handle only EN_LINK messages */ if (nmh->idFrom == ID_TXT_MESSAGE && nmh->code == EN_LINK) { diff --git a/echo.h b/echo.h index bb443a165..cc838a977 100644 --- a/echo.h +++ b/echo.h @@ -28,12 +28,14 @@ #define HASHLEN 20 /* message finger print consists of a SHA1 hash and a timestamp */ -struct echo_msg_fp { +struct echo_msg_fp +{ BYTE digest[HASHLEN]; time_t timestamp; }; struct echo_msg_history; -struct echo_msg { +struct echo_msg +{ struct echo_msg_fp fp; /* keep this as the first element */ wchar_t *title; wchar_t *text; diff --git a/env_set.c b/env_set.c index ba2f76969..5fb46b5c8 100644 --- a/env_set.c +++ b/env_set.c @@ -31,7 +31,8 @@ #include "openvpn.h" #include "env_set.h" -struct env_item { +struct env_item +{ wchar_t *nameval; struct env_item *next; }; @@ -170,7 +171,7 @@ void env_item_del_all(struct env_item *head) { struct env_item *next; - for ( ; head; head = next) + for (; head; head = next) { next = head->next; env_item_free(head); @@ -258,7 +259,7 @@ merge_env_block(const struct env_item *es) return NULL; } - for (pe = e; *pe; pe += wcslen(pe)+1) + for (pe = e; *pe; pe += wcslen(pe) + 1) { } len = (pe + 1 - e); /* including the extra '\0' at the end */ @@ -268,7 +269,7 @@ merge_env_block(const struct env_item *es) len += wcslen(item->nameval) + 1; } - wchar_t *env = malloc(sizeof(wchar_t)*len); + wchar_t *env = malloc(sizeof(wchar_t) * len); if (!env) { /* no memory -- return NULL */ @@ -294,7 +295,7 @@ merge_env_block(const struct env_item *es) p += wcslen(item->nameval) + 1; item = item->next; } - else /* add entry from process env */ + else /* add entry from process env */ { wcscpy(p, pe); p += len; @@ -311,12 +312,12 @@ merge_env_block(const struct env_item *es) /* Add any remaining entries -- either item or *pe is NULL at this point. * So only one of the two following loops will run. */ - for ( ; item; item = item->next) + for (; item; item = item->next) { wcscpy(p, item->nameval); p += wcslen(item->nameval) + 1; } - for ( ; *pe; pe += len, p += len) + for (; *pe; pe += len, p += len) { wcscpy(p, pe); len = wcslen(pe) + 1; @@ -344,8 +345,8 @@ process_setenv(connection_t *c, UNUSED time_t timestamp, const char *msg) return; } - msg += strlen("setenv "); /* character following "setenv" */ - msg += strspn(msg, " \t"); /* skip leading space */ + msg += strlen("setenv "); /* character following "setenv" */ + msg += strspn(msg, " \t"); /* skip leading space */ if (msg[0] == '\0') { WriteStatusLog(c, L"GUI> ", L"Error: Name empty in echo setenv", false); diff --git a/localization.c b/localization.c index bb90576ae..f218e12d9 100644 --- a/localization.c +++ b/localization.c @@ -110,7 +110,7 @@ GetGUILanguage(void) RegCloseKey(regkey); } - gui_language = ( value != 0 ? value : GetUserDefaultUILanguage() ); + gui_language = (value != 0 ? value : GetUserDefaultUILanguage()); InitMUILanguage(gui_language); return gui_language; } @@ -120,8 +120,9 @@ static void SetGUILanguage(LANGID langId) { HKEY regkey; - if (RegCreateKeyEx(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, 0, NULL, 0, - KEY_WRITE, NULL, ®key, NULL) != ERROR_SUCCESS) + if (RegCreateKeyEx( + HKEY_CURRENT_USER, GUI_REGKEY_HKCU, 0, NULL, 0, KEY_WRITE, NULL, ®key, NULL) + != ERROR_SUCCESS) { ShowLocalizedMsg(IDS_ERR_CREATE_REG_HKCU_KEY, GUI_REGKEY_HKCU); } @@ -144,12 +145,11 @@ LocalizedSystemTime(const SYSTEMTIME *st, wchar_t *buf, size_t size) return date_size + time_size; } - date_size = GetDateFormat(locale, DATE_SHORTDATE, st, NULL, - buf, size); - if (size > (size_t) date_size) + date_size = GetDateFormat(locale, DATE_SHORTDATE, st, NULL, buf, size); + if (size > (size_t)date_size) { - time_size = GetTimeFormat(locale, TIME_NOSECONDS, st, NULL, - buf + date_size, size - date_size); + time_size = + GetTimeFormat(locale, TIME_NOSECONDS, st, NULL, buf + date_size, size - date_size); } if (date_size > 0 && time_size > 0) { @@ -174,7 +174,7 @@ LocalizedFileTime(const FILETIME *ft) int size = LocalizedSystemTime(&st, NULL, 0); if (size > 0) { - buf = calloc(1, size*sizeof(wchar_t)); + buf = calloc(1, size * sizeof(wchar_t)); if (buf) { LocalizedSystemTime(&st, buf, size); @@ -190,7 +190,7 @@ LocalizedTime(const time_t t, LPTSTR buf, size_t size) FILETIME lft; SYSTEMTIME st; LONGLONG tmp = (t * 10000000LL) + 116444736000000000LL; - FILETIME ft = { .dwLowDateTime = (DWORD) tmp, .dwHighDateTime = tmp >> 32}; + FILETIME ft = { .dwLowDateTime = (DWORD)tmp, .dwHighDateTime = tmp >> 32 }; FileTimeToLocalFileTime(&ft, &lft); FileTimeToSystemTime(&lft, &st); @@ -212,7 +212,7 @@ LoadStringLang(UINT stringId, LANGID langId, PTSTR buffer, int bufferSize, va_li } /* get pointer to first entry in resource block */ - entry = (PWCH) LoadResource(o.hInstance, res); + entry = (PWCH)LoadResource(o.hInstance, res); if (entry == NULL) { goto err; @@ -235,7 +235,7 @@ LoadStringLang(UINT stringId, LANGID langId, PTSTR buffer, int bufferSize, va_li } /* string found, copy it */ - PTSTR formatStr = (PTSTR) malloc((*entry + 1) * sizeof(TCHAR)); + PTSTR formatStr = (PTSTR)malloc((*entry + 1) * sizeof(TCHAR)); if (formatStr == NULL) { break; @@ -293,10 +293,14 @@ LoadLocalizedStringBuf(PTSTR buffer, int bufferSize, const UINT stringId, ...) static int -__ShowLocalizedMsgEx(const UINT type, HANDLE parent, LPCTSTR caption, const UINT stringId, va_list args) +__ShowLocalizedMsgEx( + const UINT type, HANDLE parent, LPCTSTR caption, const UINT stringId, va_list args) { - return MessageBoxEx(parent, __LoadLocalizedString(stringId, args), caption, - type | MB_SETFOREGROUND | MBOX_RTL_FLAGS, GetGUILanguage()); + return MessageBoxEx(parent, + __LoadLocalizedString(stringId, args), + caption, + type | MB_SETFOREGROUND | MBOX_RTL_FLAGS, + GetGUILanguage()); } int @@ -324,9 +328,12 @@ LoadLocalizedIconEx(const UINT iconId, int cxDesired, int cyDesired) { LANGID langId = GetGUILanguage(); - HICON hIcon = - (HICON) LoadImage(o.hInstance, MAKEINTRESOURCE(iconId), - IMAGE_ICON, cxDesired, cyDesired, LR_DEFAULTSIZE|LR_SHARED); + HICON hIcon = (HICON)LoadImage(o.hInstance, + MAKEINTRESOURCE(iconId), + IMAGE_ICON, + cxDesired, + cyDesired, + LR_DEFAULTSIZE | LR_SHARED); if (hIcon) { return hIcon; @@ -378,8 +385,8 @@ LoadLocalizedIconEx(const UINT iconId, int cxDesired, int cyDesired) } /* Note: this uses the first icon in the resource and scales it */ - hIcon = CreateIconFromResourceEx(resInfo, resSize, TRUE, 0x30000, - cxDesired, cyDesired, LR_DEFAULTSIZE|LR_SHARED); + hIcon = CreateIconFromResourceEx( + resInfo, resSize, TRUE, 0x30000, cxDesired, cyDesired, LR_DEFAULTSIZE | LR_SHARED); return hIcon; } @@ -473,24 +480,26 @@ LangListEntry(const UINT stringId, const LANGID langId, ...) } -typedef struct { +typedef struct +{ HWND languages; LANGID language; } langProcData; static BOOL -FillLangListProc(UNUSED HANDLE module, UNUSED PTSTR type, UNUSED PTSTR stringId, WORD langId, LONG_PTR lParam) +FillLangListProc( + UNUSED HANDLE module, UNUSED PTSTR type, UNUSED PTSTR stringId, WORD langId, LONG_PTR lParam) { - langProcData *data = (langProcData *) lParam; + langProcData *data = (langProcData *)lParam; int index = ComboBox_AddString(data->languages, LangListEntry(IDS_LANGUAGE_NAME, langId)); ComboBox_SetItemData(data->languages, index, langId); /* Select this item if it is the currently displayed language */ if (langId == data->language - || (PRIMARYLANGID(langId) == PRIMARYLANGID(data->language) - && ComboBox_GetCurSel(data->languages) == CB_ERR) ) + || (PRIMARYLANGID(langId) == PRIMARYLANGID(data->language) + && ComboBox_GetCurSel(data->languages) == CB_ERR)) { ComboBox_SetCurSel(data->languages, index); } @@ -501,14 +510,17 @@ FillLangListProc(UNUSED HANDLE module, UNUSED PTSTR type, UNUSED PTSTR stringId, static BOOL GetLaunchOnStartup() { - WCHAR regPath[MAX_PATH], exePath[MAX_PATH]; BOOL result = FALSE; HKEY regkey; - if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, ®key) == ERROR_SUCCESS) + if (RegOpenKeyExW(HKEY_CURRENT_USER, + L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", + 0, + KEY_READ, + ®key) + == ERROR_SUCCESS) { - if (GetRegistryValue(regkey, L"OpenVPN-GUI", regPath, MAX_PATH) && GetModuleFileNameW(NULL, exePath, MAX_PATH)) { @@ -519,23 +531,24 @@ GetLaunchOnStartup() } RegCloseKey(regkey); - } return result; - } static void SetLaunchOnStartup(BOOL value) { - WCHAR exePath[MAX_PATH]; HKEY regkey; - if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, ®key) == ERROR_SUCCESS) + if (RegOpenKeyExW(HKEY_CURRENT_USER, + L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", + 0, + KEY_WRITE, + ®key) + == ERROR_SUCCESS) { - if (value) { if (GetModuleFileNameW(NULL, exePath, MAX_PATH)) @@ -549,33 +562,31 @@ SetLaunchOnStartup(BOOL value) } RegCloseKey(regkey); - } - } INT_PTR CALLBACK GeneralSettingsDlgProc(HWND hwndDlg, UINT msg, UNUSED WPARAM wParam, LPARAM lParam) { LPPSHNOTIFY psn; - langProcData langData = { - .languages = GetDlgItem(hwndDlg, ID_CMB_LANGUAGE), - .language = GetGUILanguage() - }; + langProcData langData = { .languages = GetDlgItem(hwndDlg, ID_CMB_LANGUAGE), + .language = GetGUILanguage() }; switch (msg) { - case WM_INITDIALOG: /* Populate UI language selection combo box */ - EnumResourceLanguages( NULL, RT_STRING, MAKEINTRESOURCE(IDS_LANGUAGE_NAME / 16 + 1), - (ENUMRESLANGPROC) FillLangListProc, (LONG_PTR) &langData ); + EnumResourceLanguages(NULL, + RT_STRING, + MAKEINTRESOURCE(IDS_LANGUAGE_NAME / 16 + 1), + (ENUMRESLANGPROC)FillLangListProc, + (LONG_PTR)&langData); /* If none of the available languages matched, select the fallback */ if (ComboBox_GetCurSel(langData.languages) == CB_ERR) { - ComboBox_SelectString(langData.languages, -1, - LangListEntry(IDS_LANGUAGE_NAME, fallbackLangId)); + ComboBox_SelectString( + langData.languages, -1, LangListEntry(IDS_LANGUAGE_NAME, fallbackLangId)); } /* Clear language id data for the selected item */ @@ -652,34 +663,36 @@ GeneralSettingsDlgProc(HWND hwndDlg, UINT msg, UNUSED WPARAM wParam, LPARAM lPar { /* change PLAPRegistration state */ HWND h = GetDlgItem(hwndDlg, ID_CHK_PLAP_REG); - BOOL newstate = Button_GetCheck(h) == BST_CHECKED ? TRUE : FALSE; - if (SetPLAPRegistration(newstate) != 0) /* failed or user cancelled -- reset checkmark */ + BOOL newstate = Button_GetCheck(h) == BST_CHECKED ? TRUE : FALSE; + if (SetPLAPRegistration(newstate) + != 0) /* failed or user cancelled -- reset checkmark */ { - Button_SetCheck(h, newstate ? BST_UNCHECKED : BST_CHECKED); + Button_SetCheck(h, newstate ? BST_UNCHECKED : BST_CHECKED); } } break; case WM_NOTIFY: - psn = (LPPSHNOTIFY) lParam; - if (psn->hdr.code == (UINT) PSN_APPLY) + psn = (LPPSHNOTIFY)lParam; + if (psn->hdr.code == (UINT)PSN_APPLY) { - LANGID langId = (LANGID) ComboBox_GetItemData(langData.languages, - ComboBox_GetCurSel(langData.languages)); + LANGID langId = (LANGID)ComboBox_GetItemData( + langData.languages, ComboBox_GetCurSel(langData.languages)); if (langId != 0) { SetGUILanguage(langId); } - SetLaunchOnStartup(Button_GetCheck(GetDlgItem(hwndDlg, ID_CHK_STARTUP)) == BST_CHECKED); + SetLaunchOnStartup(Button_GetCheck(GetDlgItem(hwndDlg, ID_CHK_STARTUP)) + == BST_CHECKED); o.log_append = (Button_GetCheck(GetDlgItem(hwndDlg, ID_CHK_LOG_APPEND)) == BST_CHECKED); o.silent_connection = (Button_GetCheck(GetDlgItem(hwndDlg, ID_CHK_SILENT)) == BST_CHECKED); - o.iservice_admin = - (Button_GetCheck(GetDlgItem(hwndDlg, ID_CHK_ALWAYS_USE_ISERVICE)) == BST_CHECKED); + o.iservice_admin = (Button_GetCheck(GetDlgItem(hwndDlg, ID_CHK_ALWAYS_USE_ISERVICE)) + == BST_CHECKED); if (IsDlgButtonChecked(hwndDlg, ID_RB_BALLOON0)) { o.show_balloon = 0; diff --git a/localization.h b/localization.h index cb2bab4ca..2de1c30da 100644 --- a/localization.h +++ b/localization.h @@ -60,6 +60,6 @@ LANGID GetGUILanguage(void); */ int LangFlowDirection(void); -#define MBOX_RTL_FLAGS ((LangFlowDirection() == 1) ? MB_RIGHT|MB_RTLREADING : 0) +#define MBOX_RTL_FLAGS ((LangFlowDirection() == 1) ? MB_RIGHT | MB_RTLREADING : 0) #endif /* ifndef LOCALIZATION_H */ diff --git a/main.c b/main.c index 338acc3f6..a64aab8a0 100644 --- a/main.c +++ b/main.c @@ -23,7 +23,7 @@ #include #endif -#if !defined (UNICODE) +#if !defined(UNICODE) #error UNICODE and _UNICODE must be defined. This version only supports unicode builds. #endif @@ -51,9 +51,9 @@ #include "echo.h" #include "as.h" -#define OVPN_EXITCODE_ERROR 1 -#define OVPN_EXITCODE_TIMEOUT 2 -#define OVPN_EXITCODE_NOTREADY 3 +#define OVPN_EXITCODE_ERROR 1 +#define OVPN_EXITCODE_TIMEOUT 2 +#define OVPN_EXITCODE_NOTREADY 3 /* Declare Windows procedure */ LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM); @@ -81,7 +81,7 @@ options_t o; __declspec(dllexport) char aslr_workaround; /* globals */ -static HWND settings_window; /* Handle of Settings window */ +static HWND settings_window; /* Handle of Settings window */ static int VerifyAutoConnections() @@ -118,8 +118,8 @@ NotifyRunningInstance() { /* GUI up and running -- send a message if any action is pecified, * else show the balloon */ - COPYDATASTRUCT config_data = {0}; - int timeout = 30*1000; /* 30 seconds */ + COPYDATASTRUCT config_data = { 0 }; + int timeout = 30 * 1000; /* 30 seconds */ if (!o.action) { o.action = WM_OVPN_NOTIFY; @@ -128,23 +128,25 @@ NotifyRunningInstance() config_data.dwData = o.action; if (o.action_arg) { - config_data.cbData = (wcslen(o.action_arg)+1)*sizeof(o.action_arg[0]); - config_data.lpData = (void *) o.action_arg; + config_data.cbData = (wcslen(o.action_arg) + 1) * sizeof(o.action_arg[0]); + config_data.lpData = (void *)o.action_arg; } PrintDebug(L"Instance 2: called with action %d : %ls", o.action, o.action_arg); - if (!SendMessageTimeout(hwnd_master, WM_COPYDATA, 0, - (LPARAM) &config_data, 0, timeout, NULL)) + if (!SendMessageTimeout( + hwnd_master, WM_COPYDATA, 0, (LPARAM)&config_data, 0, timeout, NULL)) { DWORD error = GetLastError(); if (error == ERROR_TIMEOUT) { exit_code = OVPN_EXITCODE_TIMEOUT; - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Sending command to running instance timed out."); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"Sending command to running instance timed out."); } else { exit_code = OVPN_EXITCODE_ERROR; - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Sending command to running instance failed (error = %lu).", + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"Sending command to running instance failed (error = %lu).", error); } } @@ -153,7 +155,8 @@ NotifyRunningInstance() { /* An instance is already running but its main window not yet initialized */ exit_code = OVPN_EXITCODE_NOTREADY; - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Previous instance not yet ready to accept commands. " + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"Previous instance not yet ready to accept commands. " "Try again later."); } @@ -166,38 +169,28 @@ _tWinMain(HINSTANCE hThisInstance, UNUSED LPTSTR lpszArgument, UNUSED int nCmdShow) { - MSG messages; /* Here messages to the application are saved */ - WNDCLASSEX wincl; /* Data structure for the windowclass */ + MSG messages; /* Here messages to the application are saved */ + WNDCLASSEX wincl; /* Data structure for the windowclass */ DWORD shell32_version; BOOL first_instance = TRUE; /* a session local semaphore to detect second instance */ - HANDLE session_semaphore = InitSemaphore(L"Local\\"PACKAGE_NAME); + HANDLE session_semaphore = InitSemaphore(L"Local\\" PACKAGE_NAME); srand(time(NULL)); /* try to lock the semaphore, else we are not the first instance */ - if (session_semaphore - && WaitForSingleObject(session_semaphore, 200) != WAIT_OBJECT_0) + if (session_semaphore && WaitForSingleObject(session_semaphore, 200) != WAIT_OBJECT_0) { first_instance = FALSE; } /* Initialize handlers for manangement interface notifications */ - mgmt_rtmsg_handler handler[] = { - { ready_, OnReady }, - { hold_, OnHold }, - { log_, OnLogLine }, - { state_, OnStateChange }, - { password_, OnPassword }, - { proxy_, OnProxy }, - { stop_, OnStop }, - { needok_, OnNeedOk }, - { needstr_, OnNeedStr }, - { echo_, OnEcho }, - { bytecount_, OnByteCount }, - { infomsg_, OnInfoMsg }, - { timeout_, OnTimeout }, - { 0, NULL } - }; + mgmt_rtmsg_handler handler[] = { { ready_, OnReady }, { hold_, OnHold }, + { log_, OnLogLine }, { state_, OnStateChange }, + { password_, OnPassword }, { proxy_, OnProxy }, + { stop_, OnStop }, { needok_, OnNeedOk }, + { needstr_, OnNeedStr }, { echo_, OnEcho }, + { bytecount_, OnByteCount }, { infomsg_, OnInfoMsg }, + { timeout_, OnTimeout }, { 0, NULL } }; InitManagement(handler); /* initialize options to default state */ @@ -247,7 +240,6 @@ _tWinMain(HINSTANCE hThisInstance, if (first_instance) { UpdateRegistry(); /* Checks version change and update keys/values */ - } GetRegistryKeys(); /* Parse command-line options */ @@ -270,7 +262,8 @@ _tWinMain(HINSTANCE hThisInstance, } else if (o.action) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Called with --command when no previous instance available"); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"Called with --command when no previous instance available"); exit(OVPN_EXITCODE_ERROR); } @@ -304,19 +297,19 @@ _tWinMain(HINSTANCE hThisInstance, /* The Window structure */ wincl.hInstance = hThisInstance; wincl.lpszClassName = szClassName; - wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */ - wincl.style = CS_DBLCLKS; /* Catch double-clicks */ + wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */ + wincl.style = CS_DBLCLKS; /* Catch double-clicks */ wincl.cbSize = sizeof(WNDCLASSEX); /* Use default icon and mouse-pointer */ wincl.hIcon = LoadLocalizedIcon(ID_ICO_APP); wincl.hIconSm = LoadLocalizedIcon(ID_ICO_APP); wincl.hCursor = LoadCursor(NULL, IDC_ARROW); - wincl.lpszMenuName = NULL; /* No menu */ - wincl.cbClsExtra = 0; /* No extra bytes after the window class */ - wincl.cbWndExtra = 0; /* structure or the window instance */ + wincl.lpszMenuName = NULL; /* No menu */ + wincl.cbClsExtra = 0; /* No extra bytes after the window class */ + wincl.cbWndExtra = 0; /* structure or the window instance */ /* Use Windows's default color as the background of the window */ - wincl.hbrBackground = (HBRUSH) COLOR_3DSHADOW; /*COLOR_BACKGROUND; */ + wincl.hbrBackground = (HBRUSH)COLOR_3DSHADOW; /*COLOR_BACKGROUND; */ /* Register the window class, and if it fails quit the program */ if (!RegisterClassEx(&wincl)) @@ -325,20 +318,19 @@ _tWinMain(HINSTANCE hThisInstance, } /* The class is registered, let's create the program*/ - CreateWindowEx( - 0, /* Extended possibilites for variation */ - szClassName, /* Classname */ - szTitleText, /* Title Text */ - WS_OVERLAPPEDWINDOW, /* default window */ - (int)CW_USEDEFAULT, /* Windows decides the position */ - (int)CW_USEDEFAULT, /* where the window ends up on the screen */ - 230, /* The programs width */ - 200, /* and height in pixels */ - HWND_DESKTOP, /* The window is a child-window to desktop */ - NULL, /* No menu */ - hThisInstance, /* Program Instance handler */ - NULL /* No Window Creation data */ - ); + CreateWindowEx(0, /* Extended possibilites for variation */ + szClassName, /* Classname */ + szTitleText, /* Title Text */ + WS_OVERLAPPEDWINDOW, /* default window */ + (int)CW_USEDEFAULT, /* Windows decides the position */ + (int)CW_USEDEFAULT, /* where the window ends up on the screen */ + 230, /* The programs width */ + 200, /* and height in pixels */ + HWND_DESKTOP, /* The window is a child-window to desktop */ + NULL, /* No menu */ + hThisInstance, /* Program Instance handler */ + NULL /* No Window Creation data */ + ); /* Run the message loop. It will run until GetMessage() returns 0 */ @@ -441,11 +433,13 @@ HandleCopyDataMessage(const COPYDATASTRUCT *copy_data) WCHAR *str = NULL; connection_t *c = NULL; PrintDebug(L"WM_COPYDATA message received. (dwData: %lu, cbData: %lu, lpData: %ls)", - copy_data->dwData, copy_data->cbData, copy_data->lpData); + copy_data->dwData, + copy_data->cbData, + copy_data->lpData); if (copy_data->cbData >= sizeof(WCHAR) && copy_data->lpData) { - str = (WCHAR *) copy_data->lpData; - str[copy_data->cbData/sizeof(WCHAR)-1] = L'\0'; /* in case not nul-terminated */ + str = (WCHAR *)copy_data->lpData; + str[copy_data->cbData / sizeof(WCHAR) - 1] = L'\0'; /* in case not nul-terminated */ c = GetConnByName(str); } if (copy_data->dwData == WM_OVPN_START && c) @@ -506,9 +500,12 @@ HandleCopyDataMessage(const COPYDATASTRUCT *copy_data) } else { - MsgToEventLog(EVENTLOG_ERROR_TYPE, - L"Unknown WM_COPYDATA message ignored. (dwData: %lu, cbData: %lu, lpData: %ls)", - copy_data->dwData, copy_data->cbData, copy_data->lpData); + MsgToEventLog( + EVENTLOG_ERROR_TYPE, + L"Unknown WM_COPYDATA message ignored. (dwData: %lu, cbData: %lu, lpData: %ls)", + copy_data->dwData, + copy_data->cbData, + copy_data->lpData); return FALSE; } return TRUE; /* indicate we handled the message */ @@ -529,8 +526,7 @@ ManagePersistent(HWND hwnd, UINT UNUSED msg, UINT_PTR id, DWORD UNUSED now) { for (connection_t *c = o.chead; c; c = c->next) { - if (c->flags & FLAG_DAEMON_PERSISTENT - && c->auto_connect + if (c->flags & FLAG_DAEMON_PERSISTENT && c->auto_connect && (c->state == disconnected || c->state == detached)) { /* disable auto-connect to avoid repeated re-connect @@ -539,7 +535,7 @@ ManagePersistent(HWND hwnd, UINT UNUSED msg, UINT_PTR id, DWORD UNUSED now) */ c->auto_connect = false; c->state = detached; /* this is required to retain management-hold on re-attach */ - StartOpenVPN(c); /* attach to the management i/f */ + StartOpenVPN(c); /* attach to the management i/f */ } } } @@ -556,8 +552,7 @@ HandleSessionLock(void) { for (connection_t *c = o.chead; c; c = c->next) { - if (c->flags & FLAG_DAEMON_PERSISTENT - && (c->state != disconnected && c->state != detached)) + if (c->flags & FLAG_DAEMON_PERSISTENT && (c->state != disconnected && c->state != detached)) { c->auto_connect = false; DetachOpenVPN(c); @@ -586,7 +581,7 @@ LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static UINT s_uTaskbarRestart; - MENUINFO minfo = {.cbSize = sizeof(MENUINFO)}; + MENUINFO minfo = { .cbSize = sizeof(MENUINFO) }; connection_t *c = NULL; switch (message) @@ -605,8 +600,8 @@ WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) HICON hIcon = LoadLocalizedIcon(ID_ICO_APP); if (hIcon) { - SendMessage(hwnd, WM_SETICON, (WPARAM) (ICON_SMALL), (LPARAM) (hIcon)); - SendMessage(hwnd, WM_SETICON, (WPARAM) (ICON_BIG), (LPARAM) (hIcon)); + SendMessage(hwnd, WM_SETICON, (WPARAM)(ICON_SMALL), (LPARAM)(hIcon)); + SendMessage(hwnd, WM_SETICON, (WPARAM)(ICON_BIG), (LPARAM)(hIcon)); } /* Enable next line to accept WM_COPYDATA messages from lower level processes */ @@ -645,12 +640,12 @@ WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) break; case WM_COPYDATA: /* custom messages with data from other processes */ - HandleCopyDataMessage((COPYDATASTRUCT *) lParam); - return TRUE; /* lets the sender free copy_data */ + HandleCopyDataMessage((COPYDATASTRUCT *)lParam); + return TRUE; /* lets the sender free copy_data */ case WM_MENUCOMMAND: /* Get the menu item id and save it in wParam for use below */ - wParam = GetMenuItemID((HMENU) lParam, wParam); + wParam = GetMenuItemID((HMENU)lParam, wParam); /* we first check global menu items which do not require a connnection index */ if (LOWORD(wParam) == IDM_IMPORT_FILE) @@ -677,15 +672,16 @@ WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) else { minfo.fMask = MIM_MENUDATA; - GetMenuInfo((HMENU) lParam, &minfo); - c = (connection_t *) minfo.dwMenuData; + GetMenuInfo((HMENU)lParam, &minfo); + c = (connection_t *)minfo.dwMenuData; if (!c) { break; /* ignore invalid connection */ } } - /* reach here only if the command did not match any global items and a valid connection id is available */ + /* reach here only if the command did not match any global items and a valid connection + * id is available */ if (LOWORD(wParam) == IDM_CONNECTMENU) { @@ -729,7 +725,7 @@ WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) break; case WM_QUERYENDSESSION: - return(TRUE); + return (TRUE); case WM_ENDSESSION: SaveAutoRestartList(); @@ -745,7 +741,9 @@ WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) o.session_locked = TRUE; /* Detach persistent connections so that other users can connect to it */ HandleSessionLock(); - KillTimer(hwnd, 1); /* This ensure ManagePersistent is not called when session is locked */ + KillTimer( + hwnd, + 1); /* This ensure ManagePersistent is not called when session is locked */ break; case WTS_SESSION_UNLOCK: @@ -765,7 +763,7 @@ WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) } break; - default: /* for messages that we don't deal with */ + default: /* for messages that we don't deal with */ if (message == s_uTaskbarRestart) { /* Explorer has restarted, re-register the tray icon. */ @@ -808,8 +806,8 @@ AboutDialogFunc(UNUSED HWND hDlg, UINT msg, UNUSED WPARAM wParam, LPARAM lParam) break; case WM_NOTIFY: - psn = (LPPSHNOTIFY) lParam; - if (psn->hdr.code == (UINT) PSN_APPLY) + psn = (LPPSHNOTIFY)lParam; + if (psn->hdr.code == (UINT)PSN_APPLY) { return TRUE; } @@ -885,14 +883,15 @@ ShowSettingsDialog() PROPSHEETHEADER psh; psh.dwSize = sizeof(PROPSHEETHEADER); - psh.dwFlags = PSH_USEHICON | PSH_PROPSHEETPAGE | PSH_NOAPPLYNOW | PSH_NOCONTEXTHELP | PSH_USECALLBACK; + psh.dwFlags = + PSH_USEHICON | PSH_PROPSHEETPAGE | PSH_NOAPPLYNOW | PSH_NOCONTEXTHELP | PSH_USECALLBACK; psh.hwndParent = o.hWnd; psh.hInstance = o.hInstance; psh.hIcon = LoadLocalizedIcon(ID_ICO_APP); psh.pszCaption = LoadLocalizedString(IDS_SETTINGS_CAPTION); psh.nPages = page_number; psh.nStartPage = 0; - psh.ppsp = (LPCPROPSHEETPAGE) &psp; + psh.ppsp = (LPCPROPSHEETPAGE)&psp; psh.pfnCallback = SettingsPsCallback; PropertySheet(&psh); @@ -907,14 +906,15 @@ CloseApplication(HWND hwnd, BOOL ask_user) /* Show a message if any non-persistent connections are active */ for (connection_t *c = o.chead; c && ask_user; c = c->next) { - if (c->state == disconnected - || c->flags & FLAG_DAEMON_PERSISTENT) + if (c->state == disconnected || c->flags & FLAG_DAEMON_PERSISTENT) { continue; } /* Ask for confirmation if still connected */ - if (ShowLocalizedMsgEx(MB_YESNO|MB_TOPMOST, o.hWnd, _T("Exit OpenVPN"), IDS_NFO_ACTIVE_CONN_EXIT) == IDNO) + if (ShowLocalizedMsgEx( + MB_YESNO | MB_TOPMOST, o.hWnd, _T("Exit OpenVPN"), IDS_NFO_ACTIVE_CONN_EXIT) + == IDNO) { /* recreate the tray icon */ ShowTrayIcon(); @@ -932,7 +932,7 @@ CloseApplication(HWND hwnd, BOOL ask_user) void ImportConfigFileFromDisk() { - TCHAR filter[2*_countof(o.ext_string)+5]; + TCHAR filter[2 * _countof(o.ext_string) + 5]; _sntprintf_0(filter, _T("*.%ls%lc*.%ls%lc"), o.ext_string, _T('\0'), o.ext_string, _T('\0')); @@ -968,7 +968,9 @@ PrintDebugMsg(TCHAR *msg) log_time = time(NULL); time_struct = localtime(&log_time); - _sntprintf(date, _countof(date), _T("%d-%.2d-%.2d %.2d:%.2d:%.2d"), + _sntprintf(date, + _countof(date), + _T("%d-%.2d-%.2d %.2d:%.2d:%.2d"), time_struct->tm_year + 1900, time_struct->tm_mon + 1, time_struct->tm_mday, @@ -996,8 +998,7 @@ GetDllVersion(LPCTSTR lpszDllName) if (hinstDll) { DLLGETVERSIONPROC pDllGetVersion; - pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, - "DllGetVersion"); + pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion"); /* Because some DLLs might not implement this function, you * must test for it explicitly. Depending on the particular @@ -1030,8 +1031,11 @@ ErrorExit(int exit_code, const wchar_t *msg) { if (msg) { - MessageBoxExW(NULL, msg, TEXT(PACKAGE_NAME), - MB_OK | MB_SETFOREGROUND | MB_ICONERROR | MBOX_RTL_FLAGS, GetGUILanguage()); + MessageBoxExW(NULL, + msg, + TEXT(PACKAGE_NAME), + MB_OK | MB_SETFOREGROUND | MB_ICONERROR | MBOX_RTL_FLAGS, + GetGUILanguage()); } if (o.hWnd) { @@ -1064,7 +1068,7 @@ SaveAutoRestartList() return; } - connection_t **active_conns = malloc((size_t) max_active*sizeof(connection_t *)); + connection_t **active_conns = malloc((size_t)max_active * sizeof(connection_t *)); if (!active_conns) { @@ -1074,8 +1078,7 @@ SaveAutoRestartList() for (connection_t *c = o.chead; c && nactive < max_active; c = c->next) { - if (c->state == disconnected - || c->flags & FLAG_DAEMON_PERSISTENT) + if (c->state == disconnected || c->flags & FLAG_DAEMON_PERSISTENT) { continue; } @@ -1087,8 +1090,7 @@ SaveAutoRestartList() if (len == 1) { - len++; /* two nuls for empty string */ - + len++; /* two nuls for empty string */ } /* Make a double nul terminated list of active connections */ wchar_t *list = calloc(len, sizeof(wchar_t)); @@ -1108,8 +1110,12 @@ SaveAutoRestartList() } /* Save the list in registry for auto-connect on restart */ - LSTATUS status = RegSetKeyValueW(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, L"auto_restart_list", - REG_MULTI_SZ, list, (DWORD) len*sizeof(wchar_t)); + LSTATUS status = RegSetKeyValueW(HKEY_CURRENT_USER, + GUI_REGKEY_HKCU, + L"auto_restart_list", + REG_MULTI_SZ, + list, + (DWORD)len * sizeof(wchar_t)); if (status != ERROR_SUCCESS) { MsgToEventLog(EVENTLOG_ERROR_TYPE, L"RegSetKeyValue returned error: status = %lu", status); @@ -1128,8 +1134,13 @@ LoadAutoRestartList() wchar_t *list; DWORD len = 0; - LSTATUS status = RegGetValueW(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, L"auto_restart_list", - RRF_RT_REG_MULTI_SZ, NULL, NULL, &len); + LSTATUS status = RegGetValueW(HKEY_CURRENT_USER, + GUI_REGKEY_HKCU, + L"auto_restart_list", + RRF_RT_REG_MULTI_SZ, + NULL, + NULL, + &len); if (status != ERROR_SUCCESS || len == 0) { return; @@ -1142,8 +1153,13 @@ LoadAutoRestartList() return; } - status = RegGetValueW(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, L"auto_restart_list", - RRF_RT_REG_MULTI_SZ, NULL, list, &len); + status = RegGetValueW(HKEY_CURRENT_USER, + GUI_REGKEY_HKCU, + L"auto_restart_list", + RRF_RT_REG_MULTI_SZ, + NULL, + list, + &len); if (status != ERROR_SUCCESS) { MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Error reading state from registry"); diff --git a/main.h b/main.h index 69ac7141c..7094100d0 100644 --- a/main.h +++ b/main.h @@ -29,53 +29,53 @@ /* Define this to enable DEBUG build */ /*#define DEBUG */ -#define DEBUG_FILE L"C:\\windows\\temp\\openvpngui_debug.txt" +#define DEBUG_FILE L"C:\\windows\\temp\\openvpngui_debug.txt" /* Registry key for User Settings */ -#define GUI_REGKEY_HKCU _T("Software\\OpenVPN-GUI") +#define GUI_REGKEY_HKCU _T("Software\\OpenVPN-GUI") -#define MAX_LOG_LENGTH 1024/* Max number of characters per log line */ -#define MAX_LOG_LINES 500 /* Max number of lines in LogWindow */ -#define DEL_LOG_LINES 10 /* Number of lines to delete from LogWindow */ -#define USAGE_BUF_SIZE 3000 /* Size of buffer used to display usage message */ +#define MAX_LOG_LENGTH 1024 /* Max number of characters per log line */ +#define MAX_LOG_LINES 500 /* Max number of lines in LogWindow */ +#define DEL_LOG_LINES 10 /* Number of lines to delete from LogWindow */ +#define USAGE_BUF_SIZE 3000 /* Size of buffer used to display usage message */ /* Authorized group who can use any options and config locations */ -#define OVPN_ADMIN_GROUP TEXT("OpenVPN Administrators") /* May be reset in registry */ +#define OVPN_ADMIN_GROUP TEXT("OpenVPN Administrators") /* May be reset in registry */ /* Application defined message IDs */ -#define WM_NOTIFYICONTRAY (WM_APP + 1) -#define WM_MANAGEMENT (WM_APP + 2) - -#define WM_OVPN_STOP (WM_APP + 10) -#define WM_OVPN_SUSPEND (WM_APP + 11) -#define WM_OVPN_RESTART (WM_APP + 12) -#define WM_OVPN_START (WM_APP + 13) -#define WM_OVPN_STOPALL (WM_APP + 14) -#define WM_OVPN_SHOWSTATUS (WM_APP + 15) -#define WM_OVPN_NOTIFY (WM_APP + 16) -#define WM_OVPN_EXIT (WM_APP + 17) -#define WM_OVPN_SILENT (WM_APP + 18) -#define WM_OVPN_RELEASE (WM_APP + 19) -#define WM_OVPN_IMPORT (WM_APP + 20) -#define WM_OVPN_RESCAN (WM_APP + 21) -#define WM_OVPN_ECHOMSG (WM_APP + 22) -#define WM_OVPN_STATE (WM_APP + 23) -#define WM_OVPN_DETACH (WM_APP + 24) - -#define MSGF_OVPN_WAIT (MSGF_USER + 1) +#define WM_NOTIFYICONTRAY (WM_APP + 1) +#define WM_MANAGEMENT (WM_APP + 2) + +#define WM_OVPN_STOP (WM_APP + 10) +#define WM_OVPN_SUSPEND (WM_APP + 11) +#define WM_OVPN_RESTART (WM_APP + 12) +#define WM_OVPN_START (WM_APP + 13) +#define WM_OVPN_STOPALL (WM_APP + 14) +#define WM_OVPN_SHOWSTATUS (WM_APP + 15) +#define WM_OVPN_NOTIFY (WM_APP + 16) +#define WM_OVPN_EXIT (WM_APP + 17) +#define WM_OVPN_SILENT (WM_APP + 18) +#define WM_OVPN_RELEASE (WM_APP + 19) +#define WM_OVPN_IMPORT (WM_APP + 20) +#define WM_OVPN_RESCAN (WM_APP + 21) +#define WM_OVPN_ECHOMSG (WM_APP + 22) +#define WM_OVPN_STATE (WM_APP + 23) +#define WM_OVPN_DETACH (WM_APP + 24) + +#define MSGF_OVPN_WAIT (MSGF_USER + 1) /* bool definitions */ -#define bool int -#define true 1 -#define false 0 +#define bool int +#define true 1 +#define false 0 /* GCC function attributes */ #ifdef _MSC_VER #define UNUSED #define NORETURN #else -#define UNUSED __attribute__ ((unused)) -#define NORETURN __attribute__ ((noreturn)) +#define UNUSED __attribute__((unused)) +#define NORETURN __attribute__((noreturn)) #endif #define PACKVERSION(major, minor) MAKELONG(minor, major) @@ -89,10 +89,11 @@ struct security_attributes #define CLEAR(x) memset(&(x), 0, sizeof(x)) /* _sntprintf with guaranteed \0 termination */ -#define _sntprintf_0(buf, ...) \ - do { \ +#define _sntprintf_0(buf, ...) \ + do \ + { \ __sntprintf_0(buf, _countof(buf), __VA_ARGS__); \ - } while(0); + } while (0); static inline int __sntprintf_0(TCHAR *buf, size_t size, TCHAR *format, ...) @@ -107,10 +108,11 @@ __sntprintf_0(TCHAR *buf, size_t size, TCHAR *format, ...) } /* _snprintf with guaranteed \0 termination */ -#define _snprintf_0(buf, ...) \ - do { \ +#define _snprintf_0(buf, ...) \ + do \ + { \ __snprintf_0(buf, sizeof(buf), __VA_ARGS__); \ - } while(0); + } while (0); static inline int __snprintf_0(char *buf, size_t size, char *format, ...) { @@ -125,17 +127,21 @@ __snprintf_0(char *buf, size_t size, char *format, ...) #ifdef DEBUG /* Print Debug Message */ -#define PrintDebug(...) \ - do { \ - TCHAR x_msg[256]; \ +#define PrintDebug(...) \ + do \ + { \ + TCHAR x_msg[256]; \ _sntprintf_0(x_msg, __VA_ARGS__); \ - PrintDebugMsg(x_msg); \ - } while(0) + PrintDebugMsg(x_msg); \ + } while (0) void PrintDebugMsg(TCHAR *msg); -#else /* ifdef DEBUG */ -#define PrintDebug(...) do { } while(0) +#else /* ifdef DEBUG */ +#define PrintDebug(...) \ + do \ + { \ + } while (0) #endif DWORD GetDllVersion(LPCTSTR lpszDllName); diff --git a/manage.c b/manage.c index 5ad56cef8..1b8f65637 100644 --- a/manage.c +++ b/manage.c @@ -74,8 +74,9 @@ OpenManagement(connection_t *c) WSACleanup(); return FALSE; } - if (WSAAsyncSelect(c->manage.sk, c->hwndStatus, WM_MANAGEMENT, - FD_CONNECT|FD_READ|FD_WRITE|FD_CLOSE) != 0) + if (WSAAsyncSelect( + c->manage.sk, c->hwndStatus, WM_MANAGEMENT, FD_CONNECT | FD_READ | FD_WRITE | FD_CLOSE) + != 0) { return FALSE; } @@ -223,16 +224,15 @@ OnManagement(SOCKET sk, LPARAM lParam) if (WSAGETSELECTERROR(lParam)) { /* keep trying for connections with persistent daemons */ - if (c->flags & FLAG_DAEMON_PERSISTENT - || time(NULL) < c->manage.timeout) + if (c->flags & FLAG_DAEMON_PERSISTENT || time(NULL) < c->manage.timeout) { /* show a message on status window */ if (rtmsg_handler[log_] && (c->flags & FLAG_DAEMON_PERSISTENT)) { char buf[256]; - _snprintf_0(buf, "%lld,W,Waiting for the management interface to come up", - (long long)time(NULL)) - rtmsg_handler[log_](c, buf); + _snprintf_0(buf, + "%lld,W,Waiting for the management interface to come up", + (long long)time(NULL)) rtmsg_handler[log_](c, buf); } connect(c->manage.sk, (SOCKADDR *)&c->manage.skaddr, sizeof(c->manage.skaddr)); @@ -254,8 +254,7 @@ OnManagement(SOCKET sk, LPARAM lParam) break; case FD_READ: - if (ioctlsocket(c->manage.sk, FIONREAD, &data_size) != 0 - || data_size == 0) + if (ioctlsocket(c->manage.sk, FIONREAD, &data_size) != 0 || data_size == 0) { return; } @@ -267,7 +266,7 @@ OnManagement(SOCKET sk, LPARAM lParam) } res = recv(c->manage.sk, data + c->manage.saved_size, data_size, 0); - if (res != (int) data_size) + if (res != (int)data_size) { free(data); return; @@ -328,7 +327,8 @@ OnManagement(SOCKET sk, LPARAM lParam) if (!*c->manage.password && passwd_request) { /* either we don't have a password or we used it and didn't match */ - MsgToEventLog(EVENTLOG_WARNING_TYPE, L"%ls: management password mismatch", + MsgToEventLog(EVENTLOG_WARNING_TYPE, + L"%ls: management password mismatch", c->config_name); c->state = disconnecting; CloseManagement(c); @@ -381,7 +381,8 @@ OnManagement(SOCKET sk, LPARAM lParam) else if (strncmp(pos, "INFO:", 5) == 0) { /* delay until management interface accepts input */ - /* use real sleep here, since WM_MANAGEMENT might arrive before management is ready */ + /* use real sleep here, since WM_MANAGEMENT might arrive before management + * is ready */ Sleep(100); c->manage.connected = 2; if (rtmsg_handler[ready_]) @@ -424,8 +425,7 @@ OnManagement(SOCKET sk, LPARAM lParam) rtmsg_handler[infomsg_](c, pos + 8); } } - else if (strncmp(pos, "PKCS11ID", 8) == 0 - && c->manage.cmd_queue) + else if (strncmp(pos, "PKCS11ID", 8) == 0 && c->manage.cmd_queue) { /* This is not a real-time message, but unfortunately implemented * in the core as one. Work around by handling the response here. @@ -452,11 +452,13 @@ OnManagement(SOCKET sk, LPARAM lParam) } else if (strncmp(line, "ERROR:", 6) == 0) { - /* Response sent to management is not processed. Log an error in status window */ + /* Response sent to management is not processed. Log an error in status + * window */ char buf[256]; - _snprintf_0(buf, "%lld,N,Previous command sent to management failed: %s", - (long long)time(NULL), line) - rtmsg_handler[log_](c, buf); + _snprintf_0(buf, + "%lld,N,Previous command sent to management failed: %s", + (long long)time(NULL), + line) rtmsg_handler[log_](c, buf); if (cmd->handler) { diff --git a/manage.h b/manage.h index 74739bb0b..9f222c729 100644 --- a/manage.h +++ b/manage.h @@ -24,7 +24,8 @@ #include -typedef enum { +typedef enum +{ ready_, stop_, bytecount_, @@ -42,19 +43,22 @@ typedef enum { mgmt_rtmsg_type_max } mgmt_rtmsg_type; -typedef enum { +typedef enum +{ regular, combined } mgmt_cmd_type; typedef void (*mgmt_msg_func)(connection_t *, char *); -typedef struct { +typedef struct +{ mgmt_rtmsg_type type; mgmt_msg_func handler; } mgmt_rtmsg_handler; -typedef struct mgmt_cmd { +typedef struct mgmt_cmd +{ struct mgmt_cmd *prev, *next; char *command; int size; diff --git a/misc.c b/misc.c index 4f278f6a4..6d811b131 100644 --- a/misc.c +++ b/misc.c @@ -52,7 +52,7 @@ BOOL Base64Encode(const char *input, int input_len, char **output) { DWORD output_len; - DWORD flags = CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF; + DWORD flags = CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF; if (input_len == 0) { @@ -60,8 +60,8 @@ Base64Encode(const char *input, int input_len, char **output) *output = calloc(1, sizeof(char)); return TRUE; } - if (!CryptBinaryToStringA((const BYTE *) input, (DWORD) input_len, - flags, NULL, &output_len) || output_len == 0) + if (!CryptBinaryToStringA((const BYTE *)input, (DWORD)input_len, flags, NULL, &output_len) + || output_len == 0) { #ifdef DEBUG PrintDebug(L"Error in CryptBinaryToStringA: input = '%.*hs'", input_len, input); @@ -75,8 +75,7 @@ Base64Encode(const char *input, int input_len, char **output) return FALSE; } - if (!CryptBinaryToStringA((const BYTE *) input, (DWORD) input_len, - flags, *output, &output_len)) + if (!CryptBinaryToStringA((const BYTE *)input, (DWORD)input_len, flags, *output, &output_len)) { #ifdef DEBUG PrintDebug(L"Error in CryptBinaryToStringA: input = '%.*hs'", input_len, input); @@ -103,8 +102,8 @@ Base64Decode(const char *input, char **output) DWORD len; PrintDebug(L"decoding %hs", input); - if (!CryptStringToBinaryA(input, 0, CRYPT_STRING_BASE64_ANY, - NULL, &len, NULL, NULL) || len == 0) + if (!CryptStringToBinaryA(input, 0, CRYPT_STRING_BASE64_ANY, NULL, &len, NULL, NULL) + || len == 0) { *output = NULL; return -1; @@ -116,8 +115,7 @@ Base64Decode(const char *input, char **output) return -1; } - if (!CryptStringToBinaryA(input, 0, - CRYPT_STRING_BASE64, (BYTE *) *output, &len, NULL, NULL)) + if (!CryptStringToBinaryA(input, 0, CRYPT_STRING_BASE64, (BYTE *)*output, &len, NULL, NULL)) { free(*output); *output = NULL; @@ -262,7 +260,6 @@ ManagementCommandFromInput(connection_t *c, LPCSTR fmt, HWND hDlg, int id) } - /* * Generate a management command from double user inputs and send it */ @@ -407,8 +404,7 @@ EnsureDirExists(LPTSTR dir) } /* No error if directory already exists */ - return (CreateDirectory(dir, NULL) == TRUE - || GetLastError() == ERROR_ALREADY_EXISTS); + return (CreateDirectory(dir, NULL) == TRUE || GetLastError() == ERROR_ALREADY_EXISTS); } return (attr & FILE_ATTRIBUTE_DIRECTORY ? TRUE : FALSE); @@ -480,11 +476,19 @@ BOOL IsUserAdmin(VOID) { BOOL b; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; PSID AdministratorsGroup; - b = AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, - DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, + b = AllocateAndInitializeSid(&NtAuthority, + 2, + SECURITY_BUILTIN_DOMAIN_RID, + DOMAIN_ALIAS_RID_ADMINS, + 0, + 0, + 0, + 0, + 0, + 0, &AdministratorsGroup); if (b) { @@ -495,7 +499,7 @@ IsUserAdmin(VOID) FreeSid(AdministratorsGroup); } - return(b); + return (b); } HANDLE @@ -530,8 +534,7 @@ CheckFileAccess(const TCHAR *path, int access) HANDLE h; bool ret = FALSE; - h = CreateFile(path, access, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL); + h = CreateFile(path, access, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h != INVALID_HANDLE_VALUE) { ret = TRUE; @@ -562,7 +565,7 @@ WidenEx(UINT codepage, const char *str) } if (wstr) { - nch = MultiByteToWideChar(codepage, 0, str, -1, wstr, nch); + nch = MultiByteToWideChar(codepage, 0, str, -1, wstr, nch); } if (nch == 0 && wstr) @@ -732,9 +735,10 @@ open_url(const wchar_t *url) HINSTANCE ret = ShellExecuteW(NULL, L"open", url, NULL, NULL, SW_SHOWNORMAL); - if (ret <= (HINSTANCE) 32) + if (ret <= (HINSTANCE)32) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"launch_url: ShellExecute <%ls> returned error: %d", url, ret); + MsgToEventLog( + EVENTLOG_ERROR_TYPE, L"launch_url: ShellExecute <%ls> returned error: %d", url, ret); return false; } return true; @@ -763,7 +767,7 @@ ImportConfigFile(const TCHAR *source, bool prompt_user) return; } - WCHAR destination[MAX_PATH+1]; + WCHAR destination[MAX_PATH + 1]; bool no_overwrite = TRUE; /* profile name must be unique: check whether a config by same name exists */ @@ -771,7 +775,9 @@ ImportConfigFile(const TCHAR *source, bool prompt_user) if (c && wcsnicmp(c->config_dir, o.config_dir, wcslen(o.config_dir)) == 0) { /* Ask the user whether to replace the profile or not. */ - if (ShowLocalizedMsgEx(MB_YESNO|MB_TOPMOST, o.hWnd, _T(PACKAGE_NAME), IDS_NFO_IMPORT_OVERWRITE, fileName) == IDNO) + if (ShowLocalizedMsgEx( + MB_YESNO | MB_TOPMOST, o.hWnd, _T(PACKAGE_NAME), IDS_NFO_IMPORT_OVERWRITE, fileName) + == IDNO) { return; } @@ -781,12 +787,16 @@ ImportConfigFile(const TCHAR *source, bool prompt_user) else { if (prompt_user - && ShowLocalizedMsgEx(MB_YESNO|MB_TOPMOST, o.hWnd, TEXT(PACKAGE_NAME), - IDS_NFO_IMPORT_SOURCE, fileName) == IDNO) + && ShowLocalizedMsgEx(MB_YESNO | MB_TOPMOST, + o.hWnd, + TEXT(PACKAGE_NAME), + IDS_NFO_IMPORT_SOURCE, + fileName) + == IDNO) { return; } - WCHAR dest_dir[MAX_PATH+1]; + WCHAR dest_dir[MAX_PATH + 1]; swprintf(dest_dir, MAX_PATH, L"%ls\\%ls", o.config_dir, fileName); dest_dir[MAX_PATH] = L'\0'; if (!EnsureDirExists(dest_dir)) @@ -800,8 +810,11 @@ ImportConfigFile(const TCHAR *source, bool prompt_user) if (!CopyFile(source, destination, no_overwrite)) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Copy file <%ls> to <%ls> failed (error = %lu)", - source, destination, GetLastError()); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"Copy file <%ls> to <%ls> failed (error = %lu)", + source, + destination, + GetLastError()); ShowLocalizedMsg(IDS_ERR_IMPORT_FAILED, destination); return; } @@ -835,7 +848,7 @@ find_free_tcp_port(SOCKADDR_IN *addr) MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs: socket open failed", __func__); goto out; } - while (bind(sk, (SOCKADDR *) addr, len)) + while (bind(sk, (SOCKADDR *)addr, len)) { if (addr->sin_port == 0) { @@ -844,7 +857,7 @@ find_free_tcp_port(SOCKADDR_IN *addr) } addr->sin_port = 0; } - if (getsockname(sk, (SOCKADDR *) &addr_bound, &len)) + if (getsockname(sk, (SOCKADDR *)&addr_bound, &len)) { MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs: getsockname failed", __func__); goto out; @@ -925,8 +938,7 @@ ParseManagementAddress(connection_t *c) } FILE *fp = _wfopen(pw_path, L"r"); - if (!fp - || !fgets(c->manage.password, sizeof(c->manage.password), fp)) + if (!fp || !fgets(c->manage.password, sizeof(c->manage.password), fp)) { /* This may be normal as not all users may be given access to this secret */ ret = false; @@ -942,7 +954,9 @@ ParseManagementAddress(connection_t *c) config_list_free(head); PrintDebug(L"ParseManagementAddress: host = %hs port = %d passwd_file = %s", - inet_ntoa(addr->sin_addr), ntohs(addr->sin_port), pw_path); + inet_ntoa(addr->sin_addr), + ntohs(addr->sin_port), + pw_path); return ret; } @@ -966,7 +980,7 @@ MsgToEventLog(WORD type, wchar_t *format, ...) va_list args; va_start(args, format); - int nchar = vswprintf(buf, size-1, format, args); + int nchar = vswprintf(buf, size - 1, format, args); va_end(args); if (nchar == -1) @@ -1022,7 +1036,7 @@ GetPLAPRegistrationStatus(void) { res = -1; } - else if (RegOpenKeyExW(HKEY_CLASSES_ROOT, L"CLSID\\"PLAP_CLASSID, 0, KEY_READ, ®key) + else if (RegOpenKeyExW(HKEY_CLASSES_ROOT, L"CLSID\\" PLAP_CLASSID, 0, KEY_READ, ®key) == ERROR_SUCCESS) { res = 1; @@ -1041,24 +1055,26 @@ SetPLAPRegistration(BOOL value) /* Run only if the state has changed */ int plap_status = GetPLAPRegistrationStatus(); - if (plap_status > 0 && (BOOL) plap_status == value) + if (plap_status > 0 && (BOOL)plap_status == value) { return 0; } if (value) { - _sntprintf_0( params, L"import \"%ls%ls\"", o.install_path, L"bin\\openvpn-plap-install.reg"); + _sntprintf_0( + params, L"import \"%ls%ls\"", o.install_path, L"bin\\openvpn-plap-install.reg"); } else { - _sntprintf_0( params, L"import \"%ls%ls\"", o.install_path, L"bin\\openvpn-plap-uninstall.reg"); + _sntprintf_0( + params, L"import \"%ls%ls\"", o.install_path, L"bin\\openvpn-plap-uninstall.reg"); } res = RunAsAdmin(cmd, params); if (res != 0) { - ShowLocalizedMsg(value ? IDS_ERR_PLAP_REG : IDS_ERR_PLAP_UNREG, res); + ShowLocalizedMsg(value ? IDS_ERR_PLAP_REG : IDS_ERR_PLAP_UNREG, res); } return res; } @@ -1106,14 +1122,15 @@ OVPNMsgWait(DWORD timeout, HWND hdlg) while (end > now) { - if (MsgWaitForMultipleObjectsEx(0, NULL, end - now, QS_ALLINPUT, MWMO_INPUTAVAILABLE) == WAIT_OBJECT_0) + if (MsgWaitForMultipleObjectsEx(0, NULL, end - now, QS_ALLINPUT, MWMO_INPUTAVAILABLE) + == WAIT_OBJECT_0) { MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { - PostQuitMessage((int) msg.wParam); + PostQuitMessage((int)msg.wParam); return false; } else if (!CallMsgFilter(&msg, MSGF_OVPN_WAIT) @@ -1144,7 +1161,7 @@ GetRandomPassword(char *buf, size_t len) return FALSE; } - if (!CryptGenRandom(cp, len, (PBYTE) buf)) + if (!CryptGenRandom(cp, len, (PBYTE)buf)) { goto out; } @@ -1182,7 +1199,7 @@ ResetPasswordReveal(HWND edit, HWND btn, WPARAM wParam) /* set the password field to be masked as a sane default */ SendMessage(edit, EM_SETPASSWORDCHAR, (WPARAM)'*', 0); - SendMessage(btn, STM_SETIMAGE, (WPARAM) IMAGE_ICON, (LPARAM)LoadLocalizedSmallIcon(ID_ICO_EYE)); + SendMessage(btn, STM_SETIMAGE, (WPARAM)IMAGE_ICON, (LPARAM)LoadLocalizedSmallIcon(ID_ICO_EYE)); /* if password is not masked on init, disable reveal "button" */ if (wParam == 0 && SendMessage(edit, EM_GETPASSWORDCHAR, 0, 0) == 0) @@ -1218,13 +1235,18 @@ ChangePasswordVisibility(HWND edit, HWND btn, WPARAM wParam) if (SendMessage(edit, EM_GETPASSWORDCHAR, 0, 0) == 0) /* currently visible */ { SendMessage(edit, EM_SETPASSWORDCHAR, (WPARAM)'*', 0); - SendMessage(btn, STM_SETIMAGE, (WPARAM) IMAGE_ICON, (LPARAM)LoadLocalizedSmallIcon(ID_ICO_EYE)); + SendMessage( + btn, STM_SETIMAGE, (WPARAM)IMAGE_ICON, (LPARAM)LoadLocalizedSmallIcon(ID_ICO_EYE)); } else { SendMessage(edit, EM_SETPASSWORDCHAR, 0, 0); - SendMessage(btn, STM_SETIMAGE, (WPARAM) IMAGE_ICON, (LPARAM)LoadLocalizedSmallIcon(ID_ICO_EYESTROKE)); + SendMessage(btn, + STM_SETIMAGE, + (WPARAM)IMAGE_ICON, + (LPARAM)LoadLocalizedSmallIcon(ID_ICO_EYESTROKE)); } - InvalidateRect(edit, NULL, TRUE); /* without this the control doesn't seem to get redrawn promptly */ + InvalidateRect( + edit, NULL, TRUE); /* without this the control doesn't seem to get redrawn promptly */ } } diff --git a/misc.h b/misc.h index 7da7dc238..283ae10a3 100644 --- a/misc.h +++ b/misc.h @@ -74,7 +74,8 @@ void CloseHandleEx(LPHANDLE h); char *url_decode(const char *src); /* digest functions */ -typedef struct md_ctx { +typedef struct md_ctx +{ HCRYPTPROV prov; HCRYPTHASH hash; } md_ctx; @@ -94,8 +95,7 @@ void ImportConfigFile(const TCHAR *path, bool prompt_user); * Helper function to convert UCS-2 text from a dialog item to UTF-8. * Caller must free *str if *len != 0. */ -BOOL -GetDlgItemTextUtf8(HWND hDlg, int id, LPSTR *str, int *len); +BOOL GetDlgItemTextUtf8(HWND hDlg, int id, LPSTR *str, int *len); /* Return escaped copy of a string */ char *escape_string(const char *str); diff --git a/openvpn-gui-res.h b/openvpn-gui-res.h index 2282c5992..e980b0bc1 100644 --- a/openvpn-gui-res.h +++ b/openvpn-gui-res.h @@ -23,152 +23,152 @@ #define OPENVPN_GUI_RES_H /* Icons */ -#define ID_ICO_APP 90 -#define ID_ICO_CONNECTED 91 -#define ID_ICO_CONNECTING 92 -#define ID_ICO_DISCONNECTED 93 -#define ID_ICO_EYE 94 -#define ID_ICO_EYESTROKE 95 +#define ID_ICO_APP 90 +#define ID_ICO_CONNECTED 91 +#define ID_ICO_CONNECTING 92 +#define ID_ICO_DISCONNECTED 93 +#define ID_ICO_EYE 94 +#define ID_ICO_EYESTROKE 95 /* About Dialog */ -#define ID_DLG_ABOUT 100 -#define ID_ICON_ABOUT 110 -#define ID_LTEXT_ABOUT2 122 -#define ID_LTEXT_ABOUT3 123 -#define ID_LTEXT_ABOUT4 124 +#define ID_DLG_ABOUT 100 +#define ID_ICON_ABOUT 110 +#define ID_LTEXT_ABOUT2 122 +#define ID_LTEXT_ABOUT3 123 +#define ID_LTEXT_ABOUT4 124 /* Ask for Passphrase Dialog */ -#define ID_DLG_PASSPHRASE 150 -#define ID_EDT_PASSPHRASE 151 -#define ID_LTEXT_PASSWORD 152 -#define ID_PASSWORD_REVEAL 153 +#define ID_DLG_PASSPHRASE 150 +#define ID_EDT_PASSPHRASE 151 +#define ID_LTEXT_PASSWORD 152 +#define ID_PASSWORD_REVEAL 153 /* Status Dialog */ -#define ID_DLG_STATUS 160 -#define ID_TXT_STATUS 161 -#define ID_EDT_LOG 162 -#define ID_DISCONNECT 163 -#define ID_RESTART 164 -#define ID_HIDE 165 -#define ID_TXT_VERSION 166 -#define ID_DETACH 167 -#define ID_TXT_BYTECOUNT 168 -#define ID_TXT_IP 169 +#define ID_DLG_STATUS 160 +#define ID_TXT_STATUS 161 +#define ID_EDT_LOG 162 +#define ID_DISCONNECT 163 +#define ID_RESTART 164 +#define ID_HIDE 165 +#define ID_TXT_VERSION 166 +#define ID_DETACH 167 +#define ID_TXT_BYTECOUNT 168 +#define ID_TXT_IP 169 /* Change Passphrase Dialog */ -#define ID_DLG_CHGPASS 170 -#define ID_EDT_PASS_CUR 174 -#define ID_EDT_PASS_NEW 175 -#define ID_EDT_PASS_NEW2 176 -#define ID_TXT_KEYFILE 177 -#define ID_TXT_KEYFORMAT 178 +#define ID_DLG_CHGPASS 170 +#define ID_EDT_PASS_CUR 174 +#define ID_EDT_PASS_NEW 175 +#define ID_EDT_PASS_NEW2 176 +#define ID_TXT_KEYFILE 177 +#define ID_TXT_KEYFORMAT 178 /* Auth Username/Password Dialog */ -#define ID_DLG_AUTH 180 -#define ID_EDT_AUTH_USER 181 -#define ID_EDT_AUTH_PASS 182 +#define ID_DLG_AUTH 180 +#define ID_EDT_AUTH_USER 181 +#define ID_EDT_AUTH_PASS 182 /* Auth Username/Password/Challenge Dialog */ -#define ID_DLG_AUTH_CHALLENGE 183 -#define ID_TXT_AUTH_CHALLENGE 184 -#define ID_EDT_AUTH_CHALLENGE 185 -#define ID_CHK_SAVE_PASS 186 -#define ID_TXT_WARNING 187 -#define ID_LTEXT_USERNAME 188 -#define ID_LTEXT_RESPONSE 189 +#define ID_DLG_AUTH_CHALLENGE 183 +#define ID_TXT_AUTH_CHALLENGE 184 +#define ID_EDT_AUTH_CHALLENGE 185 +#define ID_CHK_SAVE_PASS 186 +#define ID_TXT_WARNING 187 +#define ID_LTEXT_USERNAME 188 +#define ID_LTEXT_RESPONSE 189 /* Challenege Response Dialog */ -#define ID_DLG_CHALLENGE_RESPONSE 190 -#define ID_TXT_DESCRIPTION 191 -#define ID_EDT_RESPONSE 192 +#define ID_DLG_CHALLENGE_RESPONSE 190 +#define ID_TXT_DESCRIPTION 191 +#define ID_EDT_RESPONSE 192 /* Proxy Settings Dialog */ -#define ID_DLG_PROXY 200 -#define ID_GROUPBOX1 201 -#define ID_GROUPBOX2 202 -#define ID_GROUPBOX3 203 -#define ID_GROUPBOX4 204 -#define ID_LTEXT_PORT_OFFSET 205 -#define ID_GROUPBOX5 206 -#define ID_RB_PROXY_OPENVPN 210 -#define ID_RB_PROXY_MSIE 211 -#define ID_RB_PROXY_MANUAL 212 -#define ID_RB_PROXY_HTTP 213 -#define ID_RB_PROXY_SOCKS 219 -#define ID_EDT_PROXY_ADDRESS 214 -#define ID_EDT_PROXY_PORT 215 -#define ID_TXT_PROXY_ADDRESS 216 -#define ID_TXT_PROXY_PORT 217 +#define ID_DLG_PROXY 200 +#define ID_GROUPBOX1 201 +#define ID_GROUPBOX2 202 +#define ID_GROUPBOX3 203 +#define ID_GROUPBOX4 204 +#define ID_LTEXT_PORT_OFFSET 205 +#define ID_GROUPBOX5 206 +#define ID_RB_PROXY_OPENVPN 210 +#define ID_RB_PROXY_MSIE 211 +#define ID_RB_PROXY_MANUAL 212 +#define ID_RB_PROXY_HTTP 213 +#define ID_RB_PROXY_SOCKS 219 +#define ID_EDT_PROXY_ADDRESS 214 +#define ID_EDT_PROXY_PORT 215 +#define ID_TXT_PROXY_ADDRESS 216 +#define ID_TXT_PROXY_PORT 217 /* General Settings Dialog */ -#define ID_DLG_GENERAL 230 -#define ID_CMB_LANGUAGE 231 -#define ID_TXT_LANGUAGE 232 -#define ID_CHK_STARTUP 233 +#define ID_DLG_GENERAL 230 +#define ID_CMB_LANGUAGE 231 +#define ID_TXT_LANGUAGE 232 +#define ID_CHK_STARTUP 233 /* historic: #define ID_CHK_SERVICE_ONLY 234 */ -#define ID_TXT_LOG_APPEND 235 -#define ID_CHK_LOG_APPEND 236 -#define ID_CHK_SILENT 237 -#define ID_TXT_BALLOON 238 -#define ID_RB_BALLOON0 239 -#define ID_RB_BALLOON1 240 -#define ID_RB_BALLOON2 241 -#define ID_CHK_SHOW_SCRIPT_WIN 242 -#define ID_CHK_ALWAYS_USE_ISERVICE 243 -#define ID_RB_BALLOON3 244 -#define ID_RB_BALLOON4 245 -#define ID_RB_BALLOON5 246 -#define ID_TXT_PERSISTENT 247 -#define ID_CHK_PLAP_REG 248 -#define ID_CHK_AUTO_RESTART 249 +#define ID_TXT_LOG_APPEND 235 +#define ID_CHK_LOG_APPEND 236 +#define ID_CHK_SILENT 237 +#define ID_TXT_BALLOON 238 +#define ID_RB_BALLOON0 239 +#define ID_RB_BALLOON1 240 +#define ID_RB_BALLOON2 241 +#define ID_CHK_SHOW_SCRIPT_WIN 242 +#define ID_CHK_ALWAYS_USE_ISERVICE 243 +#define ID_RB_BALLOON3 244 +#define ID_RB_BALLOON4 245 +#define ID_RB_BALLOON5 246 +#define ID_TXT_PERSISTENT 247 +#define ID_CHK_PLAP_REG 248 +#define ID_CHK_AUTO_RESTART 249 /* Proxy Auth Dialog */ -#define ID_DLG_PROXY_AUTH 250 -#define ID_EDT_PROXY_USER 251 -#define ID_EDT_PROXY_PASS 252 +#define ID_DLG_PROXY_AUTH 250 +#define ID_EDT_PROXY_USER 251 +#define ID_EDT_PROXY_PASS 252 /* Advanced dialog */ -#define ID_DLG_ADVANCED 270 -#define ID_TXT_FOLDER 271 -#define ID_TXT_EXTENSION 272 -#define ID_EDT_CONFIG_DIR 274 -#define ID_EDT_CONFIG_EXT 275 -#define ID_EDT_LOG_DIR 276 -#define ID_BTN_CONFIG_DIR 277 -#define ID_BTN_LOG_DIR 278 -#define ID_TXT_PRECONNECT_TIMEOUT 279 -#define ID_TXT_CONNECT_TIMEOUT 280 -#define ID_TXT_DISCONNECT_TIMEOUT 281 -#define ID_EDT_PRECONNECT_TIMEOUT 282 -#define ID_EDT_CONNECT_TIMEOUT 283 -#define ID_EDT_DISCONNECT_TIMEOUT 284 -#define ID_EDT_MGMT_PORT 285 -#define ID_TXT_FOLDER1 286 -#define ID_EDT_POPUP_MUTE 287 -#define ID_RB_ENGINE_SELECTION 288 -#define ID_RB_ENGINE_OVPN2 289 -#define ID_RB_ENGINE_OVPN3 290 +#define ID_DLG_ADVANCED 270 +#define ID_TXT_FOLDER 271 +#define ID_TXT_EXTENSION 272 +#define ID_EDT_CONFIG_DIR 274 +#define ID_EDT_CONFIG_EXT 275 +#define ID_EDT_LOG_DIR 276 +#define ID_BTN_CONFIG_DIR 277 +#define ID_BTN_LOG_DIR 278 +#define ID_TXT_PRECONNECT_TIMEOUT 279 +#define ID_TXT_CONNECT_TIMEOUT 280 +#define ID_TXT_DISCONNECT_TIMEOUT 281 +#define ID_EDT_PRECONNECT_TIMEOUT 282 +#define ID_EDT_CONNECT_TIMEOUT 283 +#define ID_EDT_DISCONNECT_TIMEOUT 284 +#define ID_EDT_MGMT_PORT 285 +#define ID_TXT_FOLDER1 286 +#define ID_EDT_POPUP_MUTE 287 +#define ID_RB_ENGINE_SELECTION 288 +#define ID_RB_ENGINE_OVPN2 289 +#define ID_RB_ENGINE_OVPN3 290 /* Connections dialog */ -#define ID_DLG_CONNECTIONS 290 +#define ID_DLG_CONNECTIONS 290 /* Message Dialog */ -#define ID_DLG_MESSAGE 300 -#define ID_TXT_MESSAGE 301 +#define ID_DLG_MESSAGE 300 +#define ID_TXT_MESSAGE 301 -#define ID_DLG_URL_PROFILE_IMPORT 400 -#define ID_EDT_URL 401 -#define ID_CHK_AUTOLOGIN 402 -#define IDS_ERR_URL_IMPORT_PROFILE 403 +#define ID_DLG_URL_PROFILE_IMPORT 400 +#define ID_EDT_URL 401 +#define ID_CHK_AUTOLOGIN 402 +#define IDS_ERR_URL_IMPORT_PROFILE 403 /* pkcs11-id query dialog */ -#define ID_DLG_PKCS11_QUERY 450 -#define ID_LVW_PKCS11 451 -#define ID_TXT_PKCS11 452 +#define ID_DLG_PKCS11_QUERY 450 +#define ID_LVW_PKCS11 451 +#define ID_TXT_PKCS11 452 /* General settings contd.. */ -#define ID_CHK_CONCAT_OTP 470 +#define ID_CHK_CONCAT_OTP 470 /* * String Table Resources @@ -411,6 +411,6 @@ #define IDS_NFO_OVPN_STATE_UNKNOWN 2220 /* Timer IDs */ -#define IDT_STOP_TIMER 2500 /* Timer used to trigger force termination */ +#define IDT_STOP_TIMER 2500 /* Timer used to trigger force termination */ -#endif /* ifndef OPENVPN_GUI_RES_H */ +#endif /* ifndef OPENVPN_GUI_RES_H */ diff --git a/openvpn.c b/openvpn.c index 1e33c61bf..bd4589e3e 100644 --- a/openvpn.c +++ b/openvpn.c @@ -128,8 +128,7 @@ OnReady(connection_t *c, UNUSED char *msg) /* ask for the current state, especially useful when the daemon was prestarted */ ManagementCommand(c, "state", OnStateChange, regular); - if (c->flags & FLAG_DAEMON_PERSISTENT - && o.enable_persistent == 2) + if (c->flags & FLAG_DAEMON_PERSISTENT && o.enable_persistent == 2) { c->auto_connect = true; } @@ -143,8 +142,7 @@ void OnHold(connection_t *c, UNUSED char *msg) { EnableWindow(GetDlgItem(c->hwndStatus, ID_RESTART), TRUE); - if ((c->flags & FLAG_DAEMON_PERSISTENT) - && (c->state == disconnecting || c->state == resuming)) + if ((c->flags & FLAG_DAEMON_PERSISTENT) && (c->state == disconnecting || c->state == resuming)) { /* retain the hold state if we are here while disconnecting */ c->state = onhold; @@ -171,10 +169,7 @@ OnLogLine(connection_t *c, char *line) char *flags, *message; time_t timestamp; TCHAR *datetime; - const SETTEXTEX ste = { - .flags = ST_SELECTION, - .codepage = CP_UTF8 - }; + const SETTEXTEX ste = { .flags = ST_SELECTION, .codepage = CP_UTF8 }; flags = strchr(line, ',') + 1; if (flags - 1 == NULL) @@ -202,7 +197,7 @@ OnLogLine(connection_t *c, char *line) datetime[24] = _T(' '); /* deselect current selection, if any */ - SendMessage(logWnd, EM_SETSEL, (WPARAM) -1, (LPARAM) -1); + SendMessage(logWnd, EM_SETSEL, (WPARAM)-1, (LPARAM)-1); /* change text color if Warning or Error */ COLORREF text_clr = 0; @@ -218,16 +213,18 @@ OnLogLine(connection_t *c, char *line) if (text_clr != 0) { - CHARFORMAT cfm = { .cbSize = sizeof(CHARFORMAT), - .dwMask = CFM_COLOR|CFM_BOLD, - .dwEffects = 0, - .crTextColor = text_clr, }; - SendMessage(logWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cfm); + CHARFORMAT cfm = { + .cbSize = sizeof(CHARFORMAT), + .dwMask = CFM_COLOR | CFM_BOLD, + .dwEffects = 0, + .crTextColor = text_clr, + }; + SendMessage(logWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cfm); } /* Append line to log window */ - SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM) datetime); - SendMessage(logWnd, EM_SETTEXTEX, (WPARAM) &ste, (LPARAM) message); + SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM)datetime); + SendMessage(logWnd, EM_SETTEXTEX, (WPARAM)&ste, (LPARAM)message); SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM) _T("\n")); /* scroll to the caret */ @@ -251,9 +248,11 @@ parse_assigned_ip(connection_t *c, const char *msg) /* Convert the IP address to Unicode */ if (sep - msg > 0 - && MultiByteToWideChar(CP_UTF8, 0, msg, sep-msg, c->ip, _countof(c->ip)-1) == 0) + && MultiByteToWideChar(CP_UTF8, 0, msg, sep - msg, c->ip, _countof(c->ip) - 1) == 0) { - WriteStatusLog(c, L"GUI> ", L"Failed to extract the assigned ipv4 address (error = %d)", + WriteStatusLog(c, + L"GUI> ", + L"Failed to extract the assigned ipv4 address (error = %d)", GetLastError()); c->ip[0] = L'\0'; } @@ -272,9 +271,11 @@ parse_assigned_ip(connection_t *c, const char *msg) sep++; /* start of ipv6 address */ /* Convert the IP address to Unicode */ - if (MultiByteToWideChar(CP_UTF8, 0, sep, -1, c->ipv6, _countof(c->ipv6)-1) == 0) + if (MultiByteToWideChar(CP_UTF8, 0, sep, -1, c->ipv6, _countof(c->ipv6) - 1) == 0) { - WriteStatusLog(c, L"GUI> ", L"Failed to extract the assigned ipv6 address (error = %d)", + WriteStatusLog(c, + L"GUI> ", + L"Failed to extract the assigned ipv6 address (error = %d)", GetLastError()); c->ipv6[0] = L'\0'; } @@ -332,7 +333,7 @@ OnStateChange(connection_t *c, char *data) *pos = '\0'; /* notify the all windows in the thread of state change */ - EnumThreadWindows(GetCurrentThreadId(), NotifyStateChange, (LPARAM) state); + EnumThreadWindows(GetCurrentThreadId(), NotifyStateChange, (LPARAM)state); strncpy_s(c->daemon_state, _countof(c->daemon_state), state, _TRUNCATE); @@ -354,7 +355,11 @@ OnStateChange(connection_t *c, char *data) /* The daemon does not currently log this error. Add a line to the status window */ if (!strcmp(message, "ROUTE_ERROR")) { - WriteStatusLog(c, L"ERROR: ", L"Some routes were not successfully added. The connection may not function correctly", false); + WriteStatusLog( + c, + L"ERROR: ", + L"Some routes were not successfully added. The connection may not function correctly", + false); } else { @@ -377,9 +382,9 @@ OnStateChange(connection_t *c, char *data) } /* Show connection tray balloon */ - if ((c->state == connecting && o.show_balloon != 0) - || (c->state == resuming && o.show_balloon != 0) - || (c->state == reconnecting && o.show_balloon == 2)) + if ((c->state == connecting && o.show_balloon != 0) + || (c->state == resuming && o.show_balloon != 0) + || (c->state == reconnecting && o.show_balloon == 2)) { TCHAR msg[256]; DWORD id = success ? IDS_NFO_NOW_CONNECTED : IDS_NFO_NOTIFY_ROUTE_ERROR; @@ -401,7 +406,8 @@ OnStateChange(connection_t *c, char *data) if (!success) { - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_ROUTE_ERROR)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_ROUTE_ERROR)); return; } @@ -434,7 +440,8 @@ OnStateChange(connection_t *c, char *data) CheckAndSetTrayIcon(); /* And the texts in the status window */ - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_RECONNECTING)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_RECONNECTING)); SetDlgItemTextW(c->hwndStatus, ID_TXT_IP, L""); SetStatusWinIcon(c->hwndStatus, ID_ICO_CONNECTING); } @@ -452,15 +459,16 @@ SimulateButtonPress(HWND hwnd, UINT btn) } /* A private struct to keep autoclose parameters */ -typedef struct autoclose { - UINT start; /* start time in msec */ - UINT timeout; /* timeout in msec at which autoclose triggers */ - UINT btn; /* button which is 'pressed' for autoclose */ - UINT txtid; /* id of a text control to display an informaltional message */ - UINT txtres; /* resource id of localized text to use for message: - * LoadLocalizedString(txtid, time_remaining_in_seconds) - * is used to generate the message */ - COLORREF txtclr; /* color for message text */ +typedef struct autoclose +{ + UINT start; /* start time in msec */ + UINT timeout; /* timeout in msec at which autoclose triggers */ + UINT btn; /* button which is 'pressed' for autoclose */ + UINT txtid; /* id of a text control to display an informaltional message */ + UINT txtres; /* resource id of localized text to use for message: + * LoadLocalizedString(txtid, time_remaining_in_seconds) + * is used to generate the message */ + COLORREF txtclr; /* color for message text */ } autoclose; /* Cancel scheduled auto close of a dialog */ @@ -500,7 +508,8 @@ AutoCloseHandler(HWND hwnd, UINT UNUSED msg, UINT_PTR id, DWORD now) } else { - SetDlgItemText(hwnd, ac->txtid, LoadLocalizedString(ac->txtres, (ac->timeout - elapsed)/1000)); + SetDlgItemText( + hwnd, ac->txtid, LoadLocalizedString(ac->txtres, (ac->timeout - elapsed) / 1000)); SetTimer(hwnd, id, 500, AutoCloseHandler); } } @@ -527,15 +536,19 @@ AutoCloseSetup(HWND hwnd, UINT btn, UINT timeout, UINT txtid, UINT txtres) return; } - *ac = (autoclose) {.start = GetTickCount(), .timeout = timeout*1000, .btn = btn, - .txtid = txtid, .txtres = txtres, .txtclr = GetSysColor(COLOR_WINDOWTEXT)}; + *ac = (autoclose){ .start = GetTickCount(), + .timeout = timeout * 1000, + .btn = btn, + .txtid = txtid, + .txtres = txtres, + .txtclr = GetSysColor(COLOR_WINDOWTEXT) }; SetTimer(hwnd, 1, 500, AutoCloseHandler); /* using timer id = 1 */ if (txtid && txtres) { SetDlgItemText(hwnd, txtid, LoadLocalizedString(txtres, timeout)); } - SetPropW(hwnd, L"AutoClose", (HANDLE) ac); /* failure not critical */ + SetPropW(hwnd, L"AutoClose", (HANDLE)ac); /* failure not critical */ } } @@ -553,8 +566,8 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { case WM_INITDIALOG: /* Set connection for this dialog and show it */ - param = (auth_param_t *) lParam; - TRY_SETPROP(hwndDlg, cfgProp, (HANDLE) param); + param = (auth_param_t *)lParam; + TRY_SETPROP(hwndDlg, cfgProp, (HANDLE)param); SetStatusWinIcon(hwndDlg, ID_ICO_APP); if (param->str) @@ -564,7 +577,10 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) if (!wstr) { - WriteStatusLog(param->c, L"GUI> ", L"Error converting challenge string to widechar", false); + WriteStatusLog(param->c, + L"GUI> ", + L"Error converting challenge string to widechar", + false); } else { @@ -579,11 +595,11 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { SendMessage(wnd_challenge, EM_SETPASSWORDCHAR, 0, 0); } - } else if (param->flags & FLAG_CR_TYPE_CONCAT) { - SetDlgItemTextW(hwndDlg, ID_TXT_AUTH_CHALLENGE, LoadLocalizedString(IDS_NFO_OTP_PROMPT)); + SetDlgItemTextW( + hwndDlg, ID_TXT_AUTH_CHALLENGE, LoadLocalizedString(IDS_NFO_OTP_PROMPT)); } if (RecallUsername(param->c->config_name, username)) { @@ -593,7 +609,8 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) if (RecallAuthPass(param->c->config_name, password)) { SetDlgItemTextW(hwndDlg, ID_EDT_AUTH_PASS, password); - if (username[0] != L'\0' && !(param->flags & (FLAG_CR_TYPE_SCRV1|FLAG_CR_TYPE_CONCAT)) + if (username[0] != L'\0' + && !(param->flags & (FLAG_CR_TYPE_SCRV1 | FLAG_CR_TYPE_CONCAT)) && password[0] != L'\0' && param->c->failed_auth_attempts == 0) { /* user/pass available and no challenge response needed: skip dialog @@ -607,9 +624,10 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) /* if auth failed, highlight password so that user can type over */ else if (param->c->failed_auth_attempts) { - SendMessage(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), EM_SETSEL, 0, MAKELONG(0, -1)); + SendMessage( + GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), EM_SETSEL, 0, MAKELONG(0, -1)); } - else if (param->flags & (FLAG_CR_TYPE_SCRV1|FLAG_CR_TYPE_CONCAT)) + else if (param->flags & (FLAG_CR_TYPE_SCRV1 | FLAG_CR_TYPE_CONCAT)) { SetFocus(GetDlgItem(hwndDlg, ID_EDT_AUTH_CHALLENGE)); } @@ -627,7 +645,8 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) SetWindowText(hwndDlg, param->c->config_name); if (param->c->failed_auth_attempts > 0) { - SetDlgItemTextW(hwndDlg, ID_TXT_WARNING, LoadLocalizedString(IDS_NFO_AUTH_PASS_RETRY)); + SetDlgItemTextW( + hwndDlg, ID_TXT_WARNING, LoadLocalizedString(IDS_NFO_AUTH_PASS_RETRY)); } if (param->c->state == resuming) @@ -638,8 +657,8 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { SetForegroundWindow(hwndDlg); } - ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); + ResetPasswordReveal( + GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); break; case WM_LBUTTONDOWN: @@ -651,24 +670,27 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) break; case WM_COMMAND: - param = (auth_param_t *) GetProp(hwndDlg, cfgProp); + param = (auth_param_t *)GetProp(hwndDlg, cfgProp); switch (LOWORD(wParam)) { case ID_EDT_AUTH_PASS: ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); /* fall through */ case ID_EDT_AUTH_USER: case ID_EDT_AUTH_CHALLENGE: if (HIWORD(wParam) == EN_UPDATE) { - /* enable OK button only if username and either password or response are filled */ - BOOL enableOK = GetWindowTextLength(GetDlgItem(hwndDlg, ID_EDT_AUTH_USER)) - && (GetWindowTextLength(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS)) - || ((param->flags & (FLAG_CR_TYPE_SCRV1|FLAG_CR_TYPE_CONCAT)) - && GetWindowTextLength(GetDlgItem(hwndDlg, ID_EDT_AUTH_CHALLENGE))) - ); + /* enable OK button only if username and either password or response are + * filled */ + BOOL enableOK = + GetWindowTextLength(GetDlgItem(hwndDlg, ID_EDT_AUTH_USER)) + && (GetWindowTextLength(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS)) + || ((param->flags & (FLAG_CR_TYPE_SCRV1 | FLAG_CR_TYPE_CONCAT)) + && GetWindowTextLength( + GetDlgItem(hwndDlg, ID_EDT_AUTH_CHALLENGE)))); EnableWindow(GetDlgItem(hwndDlg, IDOK), enableOK); } AutoCloseCancel(hwndDlg); /* user interrupt */ @@ -693,7 +715,8 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { if (!validate_input(username, L"\n")) { - show_error_tip(GetDlgItem(hwndDlg, ID_EDT_AUTH_USER), LoadLocalizedString(IDS_ERR_INVALID_USERNAME_INPUT)); + show_error_tip(GetDlgItem(hwndDlg, ID_EDT_AUTH_USER), + LoadLocalizedString(IDS_ERR_INVALID_USERNAME_INPUT)); return 0; } SaveUsername(param->c->config_name, username); @@ -702,17 +725,21 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { if (!validate_input(password, L"\n")) { - show_error_tip(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), LoadLocalizedString(IDS_ERR_INVALID_PASSWORD_INPUT)); + show_error_tip(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), + LoadLocalizedString(IDS_ERR_INVALID_PASSWORD_INPUT)); SecureZeroMemory(password, sizeof(password)); return 0; } - if (param->c->flags & FLAG_SAVE_AUTH_PASS && wcslen(password) ) + if (param->c->flags & FLAG_SAVE_AUTH_PASS && wcslen(password)) { SaveAuthPass(param->c->config_name, password); } if (param->flags & FLAG_CR_TYPE_CONCAT) { - GetDlgItemTextW(hwndDlg, ID_EDT_AUTH_CHALLENGE, password + wcslen(password), _countof(password)-wcslen(password)); + GetDlgItemTextW(hwndDlg, + ID_EDT_AUTH_CHALLENGE, + password + wcslen(password), + _countof(password) - wcslen(password)); SetDlgItemTextW(hwndDlg, ID_EDT_AUTH_PASS, password); /* erase potentially secret contents in the response text box */ memset(password, L'x', wcslen(password)); @@ -721,15 +748,21 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) SecureZeroMemory(password, sizeof(password)); } - ManagementCommandFromInput(param->c, "username \"Auth\" \"%s\"", hwndDlg, ID_EDT_AUTH_USER); + ManagementCommandFromInput( + param->c, "username \"Auth\" \"%s\"", hwndDlg, ID_EDT_AUTH_USER); if (param->flags & FLAG_CR_TYPE_SCRV1) { - ManagementCommandFromTwoInputsBase64(param->c, "password \"Auth\" \"SCRV1:%s:%s\"", hwndDlg, ID_EDT_AUTH_PASS, ID_EDT_AUTH_CHALLENGE); + ManagementCommandFromTwoInputsBase64(param->c, + "password \"Auth\" \"SCRV1:%s:%s\"", + hwndDlg, + ID_EDT_AUTH_PASS, + ID_EDT_AUTH_CHALLENGE); } else { - ManagementCommandFromInput(param->c, "password \"Auth\" \"%s\"", hwndDlg, ID_EDT_AUTH_PASS); + ManagementCommandFromInput( + param->c, "password \"Auth\" \"%s\"", hwndDlg, ID_EDT_AUTH_PASS); } EndDialog(hwndDlg, LOWORD(wParam)); return TRUE; @@ -741,7 +774,8 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) case ID_PASSWORD_REVEAL: /* password reveal symbol clicked */ ChangePasswordVisibility(GetDlgItem(hwndDlg, ID_EDT_AUTH_PASS), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); return TRUE; } break; @@ -751,29 +785,30 @@ UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return TRUE; case WM_CTLCOLORSTATIC: - if (GetDlgCtrlID((HWND) lParam) == ID_TXT_WARNING) + if (GetDlgCtrlID((HWND)lParam) == ID_TXT_WARNING) { autoclose *ac = (autoclose *)GetProp(hwndDlg, L"AutoClose"); - HBRUSH br = (HBRUSH) DefWindowProc(hwndDlg, msg, wParam, lParam); - /* This text id is used for auth failure warning or autoclose message. Use appropriate color */ + HBRUSH br = (HBRUSH)DefWindowProc(hwndDlg, msg, wParam, lParam); + /* This text id is used for auth failure warning or autoclose message. Use + * appropriate color */ COLORREF clr = o.clr_warning; if (ac && ac->txtid == ID_TXT_WARNING) { clr = ac->txtclr; } - SetTextColor((HDC) wParam, clr); - return (INT_PTR) br; + SetTextColor((HDC)wParam, clr); + return (INT_PTR)br; } break; case WM_CLOSE: EndDialog(hwndDlg, LOWORD(wParam)); - param = (auth_param_t *) GetProp(hwndDlg, cfgProp); + param = (auth_param_t *)GetProp(hwndDlg, cfgProp); StopOpenVPN(param->c); return TRUE; case WM_NCDESTROY: - param = (auth_param_t *) GetProp(hwndDlg, cfgProp); + param = (auth_param_t *)GetProp(hwndDlg, cfgProp); free_auth_param(param); AutoCloseCancel(hwndDlg); RemoveProp(hwndDlg, cfgProp); @@ -795,13 +830,14 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) switch (msg) { case WM_INITDIALOG: - param = (auth_param_t *) lParam; - TRY_SETPROP(hwndDlg, cfgProp, (HANDLE) param); + param = (auth_param_t *)lParam; + TRY_SETPROP(hwndDlg, cfgProp, (HANDLE)param); WCHAR *wstr = Widen(param->str); if (!wstr) { - WriteStatusLog(param->c, L"GUI> ", L"Error converting challenge string to widechar", false); + WriteStatusLog( + param->c, L"GUI> ", L"Error converting challenge string to widechar", false); EndDialog(hwndDlg, LOWORD(wParam)); break; } @@ -816,8 +852,8 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) } /* Rendered size of challenge text and window rectangle */ - SIZE sz = {0}; - RECT rect = {0}; + SIZE sz = { 0 }; + RECT rect = { 0 }; HDC hdc = GetDC(GetDlgItem(hwndDlg, ID_TXT_DESCRIPTION)); GetWindowRect(hwndDlg, &rect); rect.right -= rect.left; @@ -825,7 +861,7 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) /* if space for text + some margin exceeds the window size, resize */ if (GetTextExtentPoint32W(hdc, wstr, wcslen(wstr), &sz) - && LPtoDP(hdc, (POINT *) &sz, 1) /* logical to device units */ + && LPtoDP(hdc, (POINT *)&sz, 1) /* logical to device units */ && sz.cx + DPI_SCALE(15) > rect.right) /* 15 nominal pixel margin space */ { /* new horizontal dimension with a max of 640 nominal pixels */ @@ -837,7 +873,9 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) else if (param->flags & FLAG_PASS_TOKEN) { SetWindowText(hwndDlg, LoadLocalizedString(IDS_NFO_TOKEN_PASSWORD_CAPTION)); - SetDlgItemText(hwndDlg, ID_TXT_DESCRIPTION, LoadLocalizedString(IDS_NFO_TOKEN_PASSWORD_REQUEST, param->id)); + SetDlgItemText(hwndDlg, + ID_TXT_DESCRIPTION, + LoadLocalizedString(IDS_NFO_TOKEN_PASSWORD_REQUEST, param->id)); } else { @@ -868,13 +906,13 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) /* disable OK button until response is filled-in */ EnableWindow(GetDlgItem(hwndDlg, IDOK), FALSE); } - ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); + ResetPasswordReveal( + GetDlgItem(hwndDlg, ID_EDT_RESPONSE), GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); break; case WM_COMMAND: - param = (auth_param_t *) GetProp(hwndDlg, cfgProp); + param = (auth_param_t *)GetProp(hwndDlg, cfgProp); const char *template; char *fmt; switch (LOWORD(wParam)) @@ -883,12 +921,13 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) if (!(param->flags & FLAG_CR_ECHO)) { ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); } if (HIWORD(wParam) == EN_UPDATE) { /* enable OK if response is non-empty */ - BOOL enableOK = GetWindowTextLength((HWND) lParam); + BOOL enableOK = GetWindowTextLength((HWND)lParam); EnableWindow(GetDlgItem(hwndDlg, IDOK), enableOK); } break; @@ -897,13 +936,15 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) if (GetDlgItemTextW(hwndDlg, ID_EDT_RESPONSE, password, _countof(password)) && !validate_input(password, L"\n")) { - show_error_tip(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), LoadLocalizedString(IDS_ERR_INVALID_PASSWORD_INPUT)); + show_error_tip(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), + LoadLocalizedString(IDS_ERR_INVALID_PASSWORD_INPUT)); SecureZeroMemory(password, sizeof(password)); return 0; } if (param->flags & FLAG_CR_TYPE_CRTEXT) { - ManagementCommandFromInputBase64(param->c, "cr-response \"%s\"", hwndDlg, ID_EDT_RESPONSE); + ManagementCommandFromInputBase64( + param->c, "cr-response \"%s\"", hwndDlg, ID_EDT_RESPONSE); EndDialog(hwndDlg, LOWORD(wParam)); return TRUE; } @@ -921,9 +962,13 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) } else /* no memory? send an emty username and let it error out */ { - WriteStatusLog(param->c, L"GUI> ", - L"Out of memory: sending a generic username for dynamic CR", false); - ManagementCommand(param->c, "username \"Auth\" \"user\"", NULL, regular); + WriteStatusLog( + param->c, + L"GUI> ", + L"Out of memory: sending a generic username for dynamic CR", + false); + ManagementCommand( + param->c, "username \"Auth\" \"user\"", NULL, regular); } free(fmt); free(username); @@ -946,8 +991,10 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) } else /* no memory? send stop signal */ { - WriteStatusLog(param->c, L"GUI> ", - L"Out of memory in password dialog: sending stop signal", false); + WriteStatusLog(param->c, + L"GUI> ", + L"Out of memory in password dialog: sending stop signal", + false); StopOpenVPN(param->c); } @@ -961,7 +1008,8 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) case ID_PASSWORD_REVEAL: /* password reveal symbol clicked */ ChangePasswordVisibility(GetDlgItem(hwndDlg, ID_EDT_RESPONSE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); return TRUE; } break; @@ -974,9 +1022,8 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) * other than GET_CONFIG. The state is in lParam. * For other auth dialogs any state change signals a restart: end the dialog */ - param = (auth_param_t *) GetProp(hwndDlg, cfgProp); - if (!(param->flags & FLAG_CR_TYPE_CRTEXT) - || strcmp((const char *) lParam, "GET_CONFIG")) + param = (auth_param_t *)GetProp(hwndDlg, cfgProp); + if (!(param->flags & FLAG_CR_TYPE_CRTEXT) || strcmp((const char *)lParam, "GET_CONFIG")) { EndDialog(hwndDlg, LOWORD(wParam)); } @@ -987,7 +1034,7 @@ GenericPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return TRUE; case WM_NCDESTROY: - param = (auth_param_t *) GetProp(hwndDlg, cfgProp); + param = (auth_param_t *)GetProp(hwndDlg, cfgProp); free_auth_param(param); RemoveProp(hwndDlg, cfgProp); break; @@ -1009,8 +1056,8 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { case WM_INITDIALOG: /* Set connection for this dialog and show it */ - c = (connection_t *) lParam; - TRY_SETPROP(hwndDlg, cfgProp, (HANDLE) c); + c = (connection_t *)lParam; + TRY_SETPROP(hwndDlg, cfgProp, (HANDLE)c); AppendTextToCaption(hwndDlg, c->config_name); if (RecallKeyPass(c->config_name, passphrase) && wcslen(passphrase) && c->failed_psw_attempts == 0) @@ -1018,7 +1065,8 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) /* Use the saved password and skip the dialog */ SetDlgItemTextW(hwndDlg, ID_EDT_PASSPHRASE, passphrase); SecureZeroMemory(passphrase, sizeof(passphrase)); - ManagementCommandFromInput(c, "password \"Private Key\" \"%s\"", hwndDlg, ID_EDT_PASSPHRASE); + ManagementCommandFromInput( + c, "password \"Private Key\" \"%s\"", hwndDlg, ID_EDT_PASSPHRASE); EndDialog(hwndDlg, IDOK); return TRUE; } @@ -1032,7 +1080,8 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) } if (c->failed_psw_attempts > 0) { - SetDlgItemTextW(hwndDlg, ID_TXT_WARNING, LoadLocalizedString(IDS_NFO_KEY_PASS_RETRY)); + SetDlgItemTextW( + hwndDlg, ID_TXT_WARNING, LoadLocalizedString(IDS_NFO_KEY_PASS_RETRY)); } if (c->state == resuming) { @@ -1045,12 +1094,12 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) /* disable OK button by default - not disabled in resources */ EnableWindow(GetDlgItem(hwndDlg, IDOK), FALSE); - ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_PASSPHRASE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); + ResetPasswordReveal( + GetDlgItem(hwndDlg, ID_EDT_PASSPHRASE), GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), 0); break; case WM_COMMAND: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); switch (LOWORD(wParam)) { case ID_CHK_SAVE_PASS: @@ -1068,21 +1117,24 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) case ID_EDT_PASSPHRASE: ResetPasswordReveal(GetDlgItem(hwndDlg, ID_EDT_PASSPHRASE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); if (HIWORD(wParam) == EN_UPDATE) { /* enable OK if response is non-empty */ - BOOL enableOK = GetWindowTextLength((HWND) lParam); + BOOL enableOK = GetWindowTextLength((HWND)lParam); EnableWindow(GetDlgItem(hwndDlg, IDOK), enableOK); } break; case IDOK: - if (GetDlgItemTextW(hwndDlg, ID_EDT_PASSPHRASE, passphrase, _countof(passphrase))) + if (GetDlgItemTextW( + hwndDlg, ID_EDT_PASSPHRASE, passphrase, _countof(passphrase))) { if (!validate_input(passphrase, L"\n")) { - show_error_tip(GetDlgItem(hwndDlg, ID_EDT_PASSPHRASE), LoadLocalizedString(IDS_ERR_INVALID_PASSWORD_INPUT)); + show_error_tip(GetDlgItem(hwndDlg, ID_EDT_PASSPHRASE), + LoadLocalizedString(IDS_ERR_INVALID_PASSWORD_INPUT)); SecureZeroMemory(passphrase, sizeof(passphrase)); return 0; } @@ -1092,7 +1144,8 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) } SecureZeroMemory(passphrase, sizeof(passphrase)); } - ManagementCommandFromInput(c, "password \"Private Key\" \"%s\"", hwndDlg, ID_EDT_PASSPHRASE); + ManagementCommandFromInput( + c, "password \"Private Key\" \"%s\"", hwndDlg, ID_EDT_PASSPHRASE); EndDialog(hwndDlg, LOWORD(wParam)); return TRUE; @@ -1103,7 +1156,8 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) case ID_PASSWORD_REVEAL: /* password reveal symbol clicked */ ChangePasswordVisibility(GetDlgItem(hwndDlg, ID_EDT_PASSPHRASE), - GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), wParam); + GetDlgItem(hwndDlg, ID_PASSWORD_REVEAL), + wParam); return TRUE; } break; @@ -1113,11 +1167,11 @@ PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return TRUE; case WM_CTLCOLORSTATIC: - if (GetDlgCtrlID((HWND) lParam) == ID_TXT_WARNING) + if (GetDlgCtrlID((HWND)lParam) == ID_TXT_WARNING) { - HBRUSH br = (HBRUSH) DefWindowProc(hwndDlg, msg, wParam, lParam); - SetTextColor((HDC) wParam, o.clr_warning); - return (INT_PTR) br; + HBRUSH br = (HBRUSH)DefWindowProc(hwndDlg, msg, wParam, lParam); + SetTextColor((HDC)wParam, o.clr_warning); + return (INT_PTR)br; } break; @@ -1148,7 +1202,7 @@ BOOL parse_dynamic_cr(const char *str, auth_param_t *param) { BOOL ret = FALSE; - char *token[4] = {0}; + char *token[4] = { 0 }; char *p = strdup(str); int i; @@ -1165,9 +1219,9 @@ parse_dynamic_cr(const char *str, auth_param_t *param) { if (i == 3) { - delim = ""; /* take the entire trailing string as the challenge */ + delim = ""; /* take the entire trailing string as the challenge */ } - token[i] = strtok(p1, delim); /* strtok is thread-safe on Windows */ + token[i] = strtok(p1, delim); /* strtok is thread-safe on Windows */ if (!token[i]) { WriteStatusLog(param->c, L"GUI> ", L"Error parsing dynamic challenge string", false); @@ -1177,7 +1231,8 @@ parse_dynamic_cr(const char *str, auth_param_t *param) if (Base64Decode(token[2], ¶m->user) < 0) { - WriteStatusLog(param->c, L"GUI> ", L"Error decoding the username in dynamic challenge string", false); + WriteStatusLog( + param->c, L"GUI> ", L"Error decoding the username in dynamic challenge string", false); goto out; } @@ -1254,14 +1309,14 @@ parse_input_request(const char *msg, auth_param_t *param) { BOOL ret = FALSE; char *p = strdup(msg); - char *sep[4] = {" ", "'", " ", ""}; /* separators to use to break up msg */ + char *sep[4] = { " ", "'", " ", "" }; /* separators to use to break up msg */ char *token[4]; char *p1 = p; for (int i = 0; i < 4; ++i, p1 = NULL) { - token[i] = strtok(p1, sep[i]); /* strtok is thread-safe on Windows */ - if (!token[i] && i < 3) /* first three tokens required */ + token[i] = strtok(p1, sep[i]); /* strtok is thread-safe on Windows */ + if (!token[i] && i < 3) /* first three tokens required */ { goto out; } @@ -1275,8 +1330,7 @@ parse_input_request(const char *msg, auth_param_t *param) token[3] = token[1]; } - PrintDebug(L"Tokens: '%hs' '%hs' '%hs' '%hs'", token[0], token[1], - token[2], token[3]); + PrintDebug(L"Tokens: '%hs' '%hs' '%hs' '%hs'", token[0], token[1], token[2], token[3]); if (strcmp(token[0], "Need") != 0) { @@ -1299,8 +1353,7 @@ parse_input_request(const char *msg, auth_param_t *param) param->flags |= FLAG_PASS_TOKEN; } } - else if (strcmp(token[2], "string") == 0 - && strcmp(param->id, "pkcs11-id-request") == 0) + else if (strcmp(token[2], "string") == 0 && strcmp(param->id, "pkcs11-id-request") == 0) { param->flags |= FLAG_STRING_PKCS11; } @@ -1312,7 +1365,9 @@ parse_input_request(const char *msg, auth_param_t *param) } PrintDebug(L"parse_input_request: id = '%hs' str = '%hs' flags = %u", - param->id, param->str, param->flags); + param->id, + param->str, + param->flags); ret = TRUE; out: @@ -1348,8 +1403,10 @@ OnEcho(connection_t *c, char *msg) { if (c->flags & FLAG_DISABLE_SAVE_PASS) { - WriteStatusLog(c, L"GUI> echo save-passwords: ", - L"Ignored as disable_save_passwords is enabled.", false); + WriteStatusLog(c, + L"GUI> echo save-passwords: ", + L"Ignored as disable_save_passwords is enabled.", + false); } else { @@ -1391,7 +1448,7 @@ OnPassword(connection_t *c, char *msg) /* Save the string for later processing during next Auth request */ c->dynamic_cr = strdup(chstr); - if (c->dynamic_cr && (chstr = strstr(c->dynamic_cr, "']")) != NULL) + if (c->dynamic_cr && (chstr = strstr(c->dynamic_cr, "']")) != NULL) { *chstr = '\0'; } @@ -1405,11 +1462,12 @@ OnPassword(connection_t *c, char *msg) if (strstr(msg, "'Auth'")) { char *chstr; - auth_param_t *param = (auth_param_t *) calloc(1, sizeof(auth_param_t)); + auth_param_t *param = (auth_param_t *)calloc(1, sizeof(auth_param_t)); if (!param) { - WriteStatusLog(c, L"GUI> ", L"Error: Out of memory - ignoring user-auth request", false); + WriteStatusLog( + c, L"GUI> ", L"Error: Out of memory - ignoring user-auth request", false); return; } param->c = c; @@ -1423,30 +1481,35 @@ OnPassword(connection_t *c, char *msg) free_auth_param(param); return; } - LocalizedDialogBoxParamEx(ID_DLG_CHALLENGE_RESPONSE, c->hwndStatus, GenericPassDialogFunc, (LPARAM) param); + LocalizedDialogBoxParamEx( + ID_DLG_CHALLENGE_RESPONSE, c->hwndStatus, GenericPassDialogFunc, (LPARAM)param); free_dynamic_cr(c); } - else if ( (chstr = strstr(msg, "SC:")) && strlen(chstr) > 5) + else if ((chstr = strstr(msg, "SC:")) && strlen(chstr) > 5) { - ULONG flags = strtoul(chstr+3, NULL, 10); + ULONG flags = strtoul(chstr + 3, NULL, 10); param->flags |= (flags & 0x2) ? FLAG_CR_TYPE_CONCAT : FLAG_CR_TYPE_SCRV1; param->flags |= (flags & 0x1) ? FLAG_CR_ECHO : 0; param->str = strdup(chstr + 5); - LocalizedDialogBoxParamEx(ID_DLG_AUTH_CHALLENGE, c->hwndStatus, UserAuthDialogFunc, (LPARAM) param); + LocalizedDialogBoxParamEx( + ID_DLG_AUTH_CHALLENGE, c->hwndStatus, UserAuthDialogFunc, (LPARAM)param); } else if (o.auth_pass_concat_otp) { param->flags |= FLAG_CR_ECHO | FLAG_CR_TYPE_CONCAT; - LocalizedDialogBoxParamEx(ID_DLG_AUTH_CHALLENGE, c->hwndStatus, UserAuthDialogFunc, (LPARAM) param); + LocalizedDialogBoxParamEx( + ID_DLG_AUTH_CHALLENGE, c->hwndStatus, UserAuthDialogFunc, (LPARAM)param); } else { - LocalizedDialogBoxParamEx(ID_DLG_AUTH, c->hwndStatus, UserAuthDialogFunc, (LPARAM) param); + LocalizedDialogBoxParamEx( + ID_DLG_AUTH, c->hwndStatus, UserAuthDialogFunc, (LPARAM)param); } } else if (strstr(msg, "'Private Key'")) { - LocalizedDialogBoxParamEx(ID_DLG_PASSPHRASE, c->hwndStatus, PrivKeyPassDialogFunc, (LPARAM) c); + LocalizedDialogBoxParamEx( + ID_DLG_PASSPHRASE, c->hwndStatus, PrivKeyPassDialogFunc, (LPARAM)c); } else if (strstr(msg, "'HTTP Proxy'")) { @@ -1459,11 +1522,12 @@ OnPassword(connection_t *c, char *msg) /* All other password requests such as PKCS11 pin */ else if (strncmp(msg, "Need '", 6) == 0) { - auth_param_t *param = (auth_param_t *) calloc(1, sizeof(auth_param_t)); + auth_param_t *param = (auth_param_t *)calloc(1, sizeof(auth_param_t)); if (!param) { - WriteStatusLog(c, L"GUI> ", L"Error: Out of memory - ignoring user-auth request", false); + WriteStatusLog( + c, L"GUI> ", L"Error: Out of memory - ignoring user-auth request", false); return; } param->c = c; @@ -1472,7 +1536,8 @@ OnPassword(connection_t *c, char *msg) free_auth_param(param); return; } - LocalizedDialogBoxParamEx(ID_DLG_CHALLENGE_RESPONSE, c->hwndStatus, GenericPassDialogFunc, (LPARAM) param); + LocalizedDialogBoxParamEx( + ID_DLG_CHALLENGE_RESPONSE, c->hwndStatus, GenericPassDialogFunc, (LPARAM)param); } } @@ -1496,8 +1561,11 @@ OnTimeout(connection_t *c, UNUSED char *msg) c->state = connecting; if (!OpenManagement(c)) { - MessageBoxExW(c->hwndStatus, L"Failed to open management", _T(PACKAGE_NAME), - MB_OK | MB_SETFOREGROUND | MB_ICONERROR | MBOX_RTL_FLAGS, GetGUILanguage()); + MessageBoxExW(c->hwndStatus, + L"Failed to open management", + _T(PACKAGE_NAME), + MB_OK | MB_SETFOREGROUND | MB_ICONERROR | MBOX_RTL_FLAGS, + GetGUILanguage()); StopOpenVPN(c); } return; @@ -1520,7 +1588,8 @@ OnStop(connection_t *c, UNUSED char *msg) c->failed_auth_attempts = 0; c->state = disconnected; CheckAndSetTrayIcon(); - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_DISCONNECTED)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_DISCONNECTED)); SetStatusWinIcon(c->hwndStatus, ID_ICO_DISCONNECTED); EnableWindow(GetDlgItem(c->hwndStatus, ID_DISCONNECT), FALSE); EnableWindow(GetDlgItem(c->hwndStatus, ID_RESTART), FALSE); @@ -1529,8 +1598,11 @@ OnStop(connection_t *c, UNUSED char *msg) SetForegroundWindow(c->hwndStatus); ShowWindow(c->hwndStatus, SW_SHOW); } - MessageBoxExW(c->hwndStatus, LoadLocalizedString(IDS_NFO_CONN_TERMINATED, c->config_file), - _T(PACKAGE_NAME), MB_OK | MBOX_RTL_FLAGS, GetGUILanguage()); + MessageBoxExW(c->hwndStatus, + LoadLocalizedString(IDS_NFO_CONN_TERMINATED, c->config_file), + _T(PACKAGE_NAME), + MB_OK | MBOX_RTL_FLAGS, + GetGUILanguage()); SendMessage(c->hwndStatus, WM_CLOSE, 0, 0); break; @@ -1553,8 +1625,11 @@ OnStop(connection_t *c, UNUSED char *msg) SetForegroundWindow(c->hwndStatus); ShowWindow(c->hwndStatus, SW_SHOW); } - MessageBoxExW(c->hwndStatus, LoadLocalizedString(msg_id, c->config_name), - _T(PACKAGE_NAME), MB_OK | MBOX_RTL_FLAGS, GetGUILanguage()); + MessageBoxExW(c->hwndStatus, + LoadLocalizedString(msg_id, c->config_name), + _T(PACKAGE_NAME), + MB_OK | MBOX_RTL_FLAGS, + GetGUILanguage()); SendMessage(c->hwndStatus, WM_CLOSE, 0, 0); break; @@ -1569,7 +1644,8 @@ OnStop(connection_t *c, UNUSED char *msg) c->auto_connect = false; } CheckAndSetTrayIcon(); - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_DISCONNECTED)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_DISCONNECTED)); SendMessage(c->hwndStatus, WM_CLOSE, 0, 0); break; @@ -1584,7 +1660,8 @@ OnStop(connection_t *c, UNUSED char *msg) case suspending: c->state = suspended; CheckAndSetTrayIcon(); - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_SUSPENDED)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_SUSPENDED)); break; default: @@ -1601,23 +1678,23 @@ OnStop(connection_t *c, UNUSED char *msg) static wchar_t * format_bytecount(wchar_t *buf, size_t len, unsigned long long c) { - const char *suf[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", NULL}; + const char *suf[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", NULL }; const char **s = suf; double x = c; if (c <= 1024) { swprintf(buf, len, L"%I64u B", c); - buf[len-1] = L'\0'; + buf[len - 1] = L'\0'; return buf; } - while (x > 1024 && *(s+1)) + while (x > 1024 && *(s + 1)) { x /= 1024.0; s++; } swprintf(buf, len, L"%I64u (%.1f %hs)", c, x, *s); - buf[len-1] = L'\0'; + buf[len - 1] = L'\0'; return buf; } @@ -1636,8 +1713,8 @@ OnByteCount(connection_t *c, char *msg) wchar_t in[32], out[32]; format_bytecount(in, _countof(in), c->bytes_in); format_bytecount(out, _countof(out), c->bytes_out); - SetDlgItemTextW(c->hwndStatus, ID_TXT_BYTECOUNT, - LoadLocalizedString(IDS_NFO_BYTECOUNT, in, out)); + SetDlgItemTextW( + c->hwndStatus, ID_TXT_BYTECOUNT, LoadLocalizedString(IDS_NFO_BYTECOUNT, in, out)); } /* @@ -1666,11 +1743,12 @@ OnInfoMsg(connection_t *c, char *msg) wchar_t *flags = Widen(msg + 9); if (flags) { - WriteStatusLog(c, L"GUI> Unsupported flags in WEB_AUTH request ignored: ", flags, false); + WriteStatusLog( + c, L"GUI> Unsupported flags in WEB_AUTH request ignored: ", flags, false); } free(flags); } - url = Widen(p+1); + url = Widen(p + 1); } if (url) @@ -1698,7 +1776,8 @@ OnInfoMsg(connection_t *c, char *msg) free_auth_param(param); return; } - LocalizedDialogBoxParamEx(ID_DLG_CHALLENGE_RESPONSE, c->hwndStatus, GenericPassDialogFunc, (LPARAM)param); + LocalizedDialogBoxParamEx( + ID_DLG_CHALLENGE_RESPONSE, c->hwndStatus, GenericPassDialogFunc, (LPARAM)param); } } @@ -1775,11 +1854,13 @@ WriteStatusLog(connection_t *c, const WCHAR *prefix, const WCHAR *line, BOOL fil if (text_clr != 0) { - CHARFORMAT cfm = { .cbSize = sizeof(CHARFORMAT), - .dwMask = CFM_COLOR|CFM_BOLD, - .dwEffects = 0, - .crTextColor = text_clr, }; - SendMessage(logWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &cfm); + CHARFORMAT cfm = { + .cbSize = sizeof(CHARFORMAT), + .dwMask = CFM_COLOR | CFM_BOLD, + .dwEffects = 0, + .crTextColor = text_clr, + }; + SendMessage(logWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cfm); } @@ -1791,11 +1872,11 @@ WriteStatusLog(connection_t *c, const WCHAR *prefix, const WCHAR *line, BOOL fil SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM) _T("")); } /* Append line to log window */ - SendMessage(logWnd, EM_SETSEL, (WPARAM) -1, (LPARAM) -1); - SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM) datetime); - SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM) prefix); - SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM) line); - SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM) L"\n"); + SendMessage(logWnd, EM_SETSEL, (WPARAM)-1, (LPARAM)-1); + SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM)datetime); + SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM)prefix); + SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM)line); + SendMessage(logWnd, EM_REPLACESEL, FALSE, (LPARAM)L"\n"); if (!fileio) { @@ -1834,7 +1915,8 @@ CloseServiceIO(service_io_t *s) static BOOL InitServiceIO(service_io_t *s) { - DWORD dwMode = o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? PIPE_READMODE_BYTE : PIPE_READMODE_MESSAGE; + DWORD dwMode = + o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? PIPE_READMODE_BYTE : PIPE_READMODE_MESSAGE; CLEAR(*s); @@ -1845,14 +1927,17 @@ InitServiceIO(service_io_t *s) return FALSE; } - s->pipe = CreateFile(o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? - OPENVPN_SERVICE_PIPE_NAME_OVPN3 : OPENVPN_SERVICE_PIPE_NAME_OVPN2, - GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); + s->pipe = CreateFile(o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? OPENVPN_SERVICE_PIPE_NAME_OVPN3 + : OPENVPN_SERVICE_PIPE_NAME_OVPN2, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, + NULL); - if (!s->pipe - || s->pipe == INVALID_HANDLE_VALUE - || !SetNamedPipeHandleState(s->pipe, &dwMode, NULL, NULL) - ) + if (!s->pipe || s->pipe == INVALID_HANDLE_VALUE + || !SetNamedPipeHandleState(s->pipe, &dwMode, NULL, NULL)) { CloseServiceIO(s); return FALSE; @@ -1868,16 +1953,16 @@ InitServiceIO(service_io_t *s) static void WINAPI HandleServiceIO(DWORD err, DWORD bytes, LPOVERLAPPED lpo) { - service_io_t *s = (service_io_t *) lpo; + service_io_t *s = (service_io_t *)lpo; int len, capacity; len = _countof(s->readbuf); - capacity = (len-1)*sizeof(*(s->readbuf)); + capacity = (len - 1) * sizeof(*(s->readbuf)); if (bytes > 0) { /* messages from the service are not nul terminated */ - int nchars = bytes/sizeof(s->readbuf[0]); + int nchars = bytes / sizeof(s->readbuf[0]); s->readbuf[nchars] = L'\0'; SetEvent(s->hEvent); return; @@ -1885,7 +1970,7 @@ HandleServiceIO(DWORD err, DWORD bytes, LPOVERLAPPED lpo) if (err) { _snwprintf(s->readbuf, len, L"0x%08x\nInteractive Service disconnected\n", err); - s->readbuf[len-1] = L'\0'; + s->readbuf[len - 1] = L'\0'; SetEvent(s->hEvent); return; } @@ -1906,8 +1991,11 @@ ValidatePipe(connection_t *c) } if (!GetNamedPipeServerProcessId(c->iserv.pipe, &ppid)) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs:%d Failed to get pipe server process id: (error = 0x%08x)", - __func__, __LINE__, GetLastError()); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"%hs:%d Failed to get pipe server process id: (error = 0x%08x)", + __func__, + __LINE__, + GetLastError()); return FALSE; } spid = GetServicePid(); @@ -1933,8 +2021,7 @@ WritePipe(HANDLE pipe, LPVOID buf, DWORD size) return retval; } - if (WriteFile(pipe, buf, size, NULL, &o) - || GetLastError() == ERROR_IO_PENDING) + if (WriteFile(pipe, buf, size, NULL, &o) || GetLastError() == ERROR_IO_PENDING) { if (WaitForSingleObject(o.hEvent, IO_TIMEOUT) == WAIT_OBJECT_0) { @@ -1967,7 +2054,7 @@ OnService(connection_t *c, UNUSED char *msg) * by calling HandleServiceIO with err = 0, bytes = 0. */ buf = wcsdup(c->iserv.readbuf); - HandleServiceIO(0, 0, (LPOVERLAPPED) &c->iserv); + HandleServiceIO(0, 0, (LPOVERLAPPED)&c->iserv); if (buf == NULL) { @@ -1986,7 +2073,7 @@ OnService(connection_t *c, UNUSED char *msg) if (!err && wcsstr(p, L"\nProcess ID") && swscanf(p, L"0x%08x", &pid) == 1 && pid != 0) { PrintDebug(L"Process ID of openvpn started by IService: %d", pid); - c->hProcess = OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_INFORMATION, FALSE, pid); + c->hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, pid); if (!c->hProcess) { PrintDebug(L"Failed to get process handle from pid of openvpn: error = %lu", @@ -2045,9 +2132,12 @@ OnProcess(connection_t *c, UNUSED char *msg) return; } - _snwprintf(tmp, _countof(tmp), L"OpenVPN terminated with exit code %lu. " - L"See the log file for details", err); - tmp[_countof(tmp)-1] = L'\0'; + _snwprintf(tmp, + _countof(tmp), + L"OpenVPN terminated with exit code %lu. " + L"See the log file for details", + err); + tmp[_countof(tmp) - 1] = L'\0'; WriteStatusLog(c, L"OpenVPN GUI> ", tmp, false); OnStop(c, NULL); @@ -2061,11 +2151,14 @@ OnNeedOk(connection_t *c, char *msg) { char *resp = NULL; WCHAR *wstr = NULL; - auth_param_t *param = (auth_param_t *) calloc(1, sizeof(auth_param_t)); + auth_param_t *param = (auth_param_t *)calloc(1, sizeof(auth_param_t)); if (!param) { - WriteStatusLog(c, L"GUI> ", L"Error: out of memory while processing NEED-OK. Sending stop signal", false); + WriteStatusLog(c, + L"GUI> ", + L"Error: out of memory while processing NEED-OK. Sending stop signal", + false); StopOpenVPN(c); return; } @@ -2080,13 +2173,18 @@ OnNeedOk(connection_t *c, char *msg) if (!wstr || !resp) { - WriteStatusLog(c, L"GUI> ", L"Error: out of memory while processing NEED-OK. Sending stop signal", false); + WriteStatusLog(c, + L"GUI> ", + L"Error: out of memory while processing NEED-OK. Sending stop signal", + false); StopOpenVPN(c); goto out; } const char *fmt; - if (MessageBoxExW(c->hwndStatus, wstr, L""PACKAGE_NAME, MB_OKCANCEL | MBOX_RTL_FLAGS, GetGUILanguage()) == IDOK) + if (MessageBoxExW( + c->hwndStatus, wstr, L"" PACKAGE_NAME, MB_OKCANCEL | MBOX_RTL_FLAGS, GetGUILanguage()) + == IDOK) { fmt = "needok \'%s\' ok"; } @@ -2186,15 +2284,60 @@ Cleanup(connection_t *c) void RenderStatusWindow(HWND hwndDlg, UINT w, UINT h) { - MoveWindow(GetDlgItem(hwndDlg, ID_EDT_LOG), DPI_SCALE(20), DPI_SCALE(25), w - DPI_SCALE(40), h - DPI_SCALE(110), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_TXT_STATUS), DPI_SCALE(20), DPI_SCALE(5), w-DPI_SCALE(30), DPI_SCALE(15), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_TXT_IP), DPI_SCALE(20), h - DPI_SCALE(75), w-DPI_SCALE(30), DPI_SCALE(15), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_TXT_BYTECOUNT), DPI_SCALE(20), h - DPI_SCALE(55), w-DPI_SCALE(210), DPI_SCALE(15), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_TXT_VERSION), w-DPI_SCALE(180), h - DPI_SCALE(55), DPI_SCALE(170), DPI_SCALE(15), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_DISCONNECT), DPI_SCALE(20), h - DPI_SCALE(30), DPI_SCALE(110), DPI_SCALE(23), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_RESTART), DPI_SCALE(145), h - DPI_SCALE(30), DPI_SCALE(110), DPI_SCALE(23), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_DETACH), DPI_SCALE(270), h - DPI_SCALE(30), DPI_SCALE(110), DPI_SCALE(23), TRUE); - MoveWindow(GetDlgItem(hwndDlg, ID_HIDE), w - DPI_SCALE(130), h - DPI_SCALE(30), DPI_SCALE(110), DPI_SCALE(23), TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_EDT_LOG), + DPI_SCALE(20), + DPI_SCALE(25), + w - DPI_SCALE(40), + h - DPI_SCALE(110), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_TXT_STATUS), + DPI_SCALE(20), + DPI_SCALE(5), + w - DPI_SCALE(30), + DPI_SCALE(15), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_TXT_IP), + DPI_SCALE(20), + h - DPI_SCALE(75), + w - DPI_SCALE(30), + DPI_SCALE(15), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_TXT_BYTECOUNT), + DPI_SCALE(20), + h - DPI_SCALE(55), + w - DPI_SCALE(210), + DPI_SCALE(15), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_TXT_VERSION), + w - DPI_SCALE(180), + h - DPI_SCALE(55), + DPI_SCALE(170), + DPI_SCALE(15), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_DISCONNECT), + DPI_SCALE(20), + h - DPI_SCALE(30), + DPI_SCALE(110), + DPI_SCALE(23), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_RESTART), + DPI_SCALE(145), + h - DPI_SCALE(30), + DPI_SCALE(110), + DPI_SCALE(23), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_DETACH), + DPI_SCALE(270), + h - DPI_SCALE(30), + DPI_SCALE(110), + DPI_SCALE(23), + TRUE); + MoveWindow(GetDlgItem(hwndDlg, ID_HIDE), + w - DPI_SCALE(130), + h - DPI_SCALE(30), + DPI_SCALE(110), + DPI_SCALE(23), + TRUE); } /* @@ -2213,51 +2356,67 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return TRUE; case WM_INITDIALOG: - c = (connection_t *) lParam; + c = (connection_t *)lParam; /* Set window icon "disconnected" */ SetStatusWinIcon(hwndDlg, ID_ICO_CONNECTING); /* Set connection for this dialog */ - if (!SetPropW(hwndDlg, cfgProp, (HANDLE) c)) + if (!SetPropW(hwndDlg, cfgProp, (HANDLE)c)) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs:%d SetProp failed (error = 0x%08x)", - __func__, __LINE__, GetLastError()); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"%hs:%d SetProp failed (error = 0x%08x)", + __func__, + __LINE__, + GetLastError()); DisconnectDaemon(c); DestroyWindow(hwndDlg); break; } /* Create log window */ - HWND hLogWnd = CreateWindowEx(0, RICHEDIT_CLASS, NULL, - WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|ES_SUNKEN|ES_LEFT - |ES_MULTILINE|ES_READONLY|ES_AUTOHSCROLL|ES_AUTOVSCROLL, - 20, 25, 350, 160, hwndDlg, (HMENU) ID_EDT_LOG, o.hInstance, NULL); + HWND hLogWnd = + CreateWindowEx(0, + RICHEDIT_CLASS, + NULL, + WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | ES_SUNKEN | ES_LEFT + | ES_MULTILINE | ES_READONLY | ES_AUTOHSCROLL | ES_AUTOVSCROLL, + 20, + 25, + 350, + 160, + hwndDlg, + (HMENU)ID_EDT_LOG, + o.hInstance, + NULL); if (!hLogWnd) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, c->hwndStatus, TEXT(PACKAGE_NAME), IDS_ERR_CREATE_EDIT_LOGWINDOW); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + c->hwndStatus, + TEXT(PACKAGE_NAME), + IDS_ERR_CREATE_EDIT_LOGWINDOW); /* We can't continue without a log window */ StopOpenVPN(c); return FALSE; } /* Set font and fontsize of the log window */ - CHARFORMAT cfm = { - .cbSize = sizeof(CHARFORMAT), - .dwMask = CFM_SIZE|CFM_FACE|CFM_BOLD, - .szFaceName = _T("Microsoft Sans Serif"), - .dwEffects = 0, - .yHeight = 160 - }; - if (SendMessage(hLogWnd, EM_SETCHARFORMAT, SCF_DEFAULT, (LPARAM) &cfm) == 0) + CHARFORMAT cfm = { .cbSize = sizeof(CHARFORMAT), + .dwMask = CFM_SIZE | CFM_FACE | CFM_BOLD, + .szFaceName = _T("Microsoft Sans Serif"), + .dwEffects = 0, + .yHeight = 160 }; + if (SendMessage(hLogWnd, EM_SETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cfm) == 0) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, c->hwndStatus, TEXT(PACKAGE_NAME), IDS_ERR_SET_SIZE); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, c->hwndStatus, TEXT(PACKAGE_NAME), IDS_ERR_SET_SIZE); } /* display version string as "OpenVPN GUI gui_version/core_version" */ wchar_t version[256]; - _sntprintf_0(version, L"%hs %hs/%hs", PACKAGE_NAME, PACKAGE_VERSION_RESOURCE_STR, o.ovpn_version) - SetDlgItemText(hwndDlg, ID_TXT_VERSION, version); + _sntprintf_0( + version, L"%hs %hs/%hs", PACKAGE_NAME, PACKAGE_VERSION_RESOURCE_STR, o.ovpn_version) + SetDlgItemText(hwndDlg, ID_TXT_VERSION, version); /* Set size and position of controls */ RECT rect; @@ -2265,8 +2424,13 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) /* Move the window by upto 100 random pixels to avoid all * status windows fall on top of each other. */ - SetWindowPos(hwndDlg, HWND_TOP, rect.left + rand()%100, - rect.top + rand()%100, 0, 0, SWP_NOSIZE); + SetWindowPos(hwndDlg, + HWND_TOP, + rect.left + rand() % 100, + rect.top + rand() % 100, + 0, + 0, + SWP_NOSIZE); GetClientRect(hwndDlg, &rect); RenderStatusWindow(hwndDlg, rect.right, rect.bottom); if (c->flags & FLAG_DAEMON_PERSISTENT && o.enable_persistent > 0) @@ -2294,7 +2458,7 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return TRUE; case WM_COMMAND: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); switch (LOWORD(wParam)) { case ID_DISCONNECT: @@ -2333,7 +2497,7 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return FALSE; case WM_CLOSE: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); if (c->state != disconnected && c->state != detached) { ShowWindow(hwndDlg, SW_HIDE); @@ -2354,19 +2518,19 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) break; case WM_OVPN_RELEASE: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); c->state = reconnecting; - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_RECONNECTING)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_RECONNECTING)); SetDlgItemTextW(c->hwndStatus, ID_TXT_IP, L""); SetStatusWinIcon(c->hwndStatus, ID_ICO_CONNECTING); OnHold(c, ""); break; case WM_OVPN_STOP: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); /* external messages can trigger when we are not ready -- check the state */ - if (!IsWindowEnabled(GetDlgItem(c->hwndStatus, ID_DISCONNECT)) - || c->state == onhold) + if (!IsWindowEnabled(GetDlgItem(c->hwndStatus, ID_DISCONNECT)) || c->state == onhold) { break; } @@ -2378,12 +2542,13 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) EnableWindow(GetDlgItem(c->hwndStatus, ID_DISCONNECT), FALSE); EnableWindow(GetDlgItem(c->hwndStatus, ID_RESTART), FALSE); SetMenuStatus(c, disconnecting); - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_WAIT_TERM)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_WAIT_TERM)); DisconnectDaemon(c); break; case WM_OVPN_DETACH: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); /* just stop the thread keeping openvpn.exe running */ c->state = detaching; EnableWindow(GetDlgItem(c->hwndStatus, ID_DISCONNECT), FALSE); @@ -2392,19 +2557,20 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) break; case WM_OVPN_SUSPEND: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); c->state = suspending; EnableWindow(GetDlgItem(c->hwndStatus, ID_DISCONNECT), FALSE); EnableWindow(GetDlgItem(c->hwndStatus, ID_RESTART), FALSE); SetMenuStatus(c, disconnecting); - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_WAIT_TERM)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_WAIT_TERM)); SetEvent(c->exit_event); SetTimer(hwndDlg, IDT_STOP_TIMER, 15000, NULL); break; case WM_TIMER: PrintDebug(L"WM_TIMER message with wParam = %lu", wParam); - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); if (wParam == IDT_STOP_TIMER) { /* openvpn failed to respond to stop signal -- terminate */ @@ -2415,13 +2581,14 @@ StatusDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) break; case WM_OVPN_RESTART: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); /* external messages can trigger when we are not ready -- check the state */ if (IsWindowEnabled(GetDlgItem(c->hwndStatus, ID_RESTART))) { c->state = reconnecting; ManagementCommand(c, "signal SIGHUP", NULL, regular); - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_RECONNECTING)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_RECONNECTING)); SetDlgItemTextW(c->hwndStatus, ID_TXT_IP, L""); SetStatusWinIcon(c->hwndStatus, ID_ICO_CONNECTING); } @@ -2454,7 +2621,7 @@ ThreadOpenVPNStatus(void *p) conn_name[_tcslen(conn_name) - _tcslen(o.ext_string) - 1] = _T('\0'); /* Create and Show Status Dialog */ - c->hwndStatus = CreateLocalizedDialogParam(ID_DLG_STATUS, StatusDialogFunc, (LPARAM) c); + c->hwndStatus = CreateLocalizedDialogParam(ID_DLG_STATUS, StatusDialogFunc, (LPARAM)c); if (!c->hwndStatus) { /* kill daemon process if we started it */ @@ -2471,15 +2638,18 @@ ThreadOpenVPNStatus(void *p) if (!OpenManagement(c)) { - MessageBoxExW(c->hwndStatus, L"Failed to open management", _T(PACKAGE_NAME), - MB_OK | MB_SETFOREGROUND | MB_ICONERROR | MBOX_RTL_FLAGS, GetGUILanguage()); + MessageBoxExW(c->hwndStatus, + L"Failed to open management", + _T(PACKAGE_NAME), + MB_OK | MB_SETFOREGROUND | MB_ICONERROR | MBOX_RTL_FLAGS, + GetGUILanguage()); StopOpenVPN(c); } /* Start the async read loop for service and set it as the wait event */ if (c->iserv.hEvent) { - HandleServiceIO(0, 0, (LPOVERLAPPED) &c->iserv); + HandleServiceIO(0, 0, (LPOVERLAPPED)&c->iserv); wait_event = c->iserv.hEvent; } else @@ -2505,10 +2675,12 @@ ThreadOpenVPNStatus(void *p) if (wait_event == NULL) /* for persistent connections there is no wait_event */ { res = GetMessage(&msg, NULL, 0, 0); - if (res == (DWORD) -1) /* log the error and continue */ + if (res == (DWORD)-1) /* log the error and continue */ { - MsgToEventLog(EVENTLOG_WARNING_TYPE, L"GetMessage for <%ls> returned error (status=%lu)", - c->config_name, GetLastError()); + MsgToEventLog(EVENTLOG_WARNING_TYPE, + L"GetMessage for <%ls> returned error (status=%lu)", + c->config_name, + GetLastError()); continue; } else if (res == 0) /* WM_QUIT */ @@ -2518,8 +2690,9 @@ ThreadOpenVPNStatus(void *p) } else if (!PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - if ((res = MsgWaitForMultipleObjectsEx(1, &wait_event, INFINITE, QS_ALLINPUT, - MWMO_ALERTABLE)) == WAIT_OBJECT_0) + if ((res = MsgWaitForMultipleObjectsEx( + 1, &wait_event, INFINITE, QS_ALLINPUT, MWMO_ALERTABLE)) + == WAIT_OBJECT_0) { if (wait_event == c->hProcess) { @@ -2575,15 +2748,18 @@ SetProcessPriority(DWORD *priority) } else { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_UNKNOWN_PRIORITY, o.priority_string); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + o.hWnd, + TEXT(PACKAGE_NAME), + IDS_ERR_UNKNOWN_PRIORITY, + o.priority_string); return FALSE; } return TRUE; } #ifdef ENABLE_OVPN3 -inline static -struct json_object * +inline static struct json_object * json_object_new_utf16_string(wchar_t *utf16) { DWORD input_size = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, NULL, NULL); @@ -2606,15 +2782,18 @@ json_object_new_utf16_string(wchar_t *utf16) static char * PrepareStartJsonRequest(connection_t *c, wchar_t *exit_event_name) { - const char *request_header = "POST /start HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: %zd\r\n\r\n"; + const char *request_header = + "POST /start HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: %zd\r\n\r\n"; json_object *jobj = json_object_new_object(); json_object_object_add(jobj, "config_file", json_object_new_utf16_string(c->config_file)); json_object_object_add(jobj, "config_dir", json_object_new_utf16_string(c->config_dir)); json_object_object_add(jobj, "exit_event_name", json_object_new_utf16_string(exit_event_name)); json_object_object_add(jobj, "management_password", json_object_new_string(c->manage.password)); - json_object_object_add(jobj, "management_host", json_object_new_string(inet_ntoa(c->manage.skaddr.sin_addr))); - json_object_object_add(jobj, "management_port", json_object_new_int(ntohs(c->manage.skaddr.sin_port))); + json_object_object_add( + jobj, "management_host", json_object_new_string(inet_ntoa(c->manage.skaddr.sin_addr))); + json_object_object_add( + jobj, "management_port", json_object_new_int(ntohs(c->manage.skaddr.sin_port))); json_object_object_add(jobj, "log", json_object_new_utf16_string(c->log_path)); json_object_object_add(jobj, "log-append", json_object_new_int(o.log_append)); @@ -2663,8 +2842,10 @@ StartOpenVPN(connection_t *c) /* the tread can hang around after disconnect if user has not dismissed any popups */ if (c->state == disconnected) { - WriteStatusLog(c, L"OpenVPN GUI> ", - L"Complete any pending dialog before starting a new connection", false); + WriteStatusLog(c, + L"OpenVPN GUI> ", + L"Complete any pending dialog before starting a new connection", + false); } if (!o.silent_connection) { @@ -2684,7 +2865,8 @@ StartOpenVPN(connection_t *c) HANDLE hThread = CreateThread(NULL, 0, ThreadOpenVPNStatus, c, CREATE_SUSPENDED, &c->threadId); if (hThread == NULL) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_CREATE_THREAD_STATUS); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_CREATE_THREAD_STATUS); return false; } @@ -2695,8 +2877,12 @@ StartOpenVPN(connection_t *c) /* Show an error if manually connecting */ if (c->state == disconnected) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_PARSE_MGMT_OPTION, - c->config_dir, c->config_file); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + o.hWnd, + TEXT(PACKAGE_NAME), + IDS_ERR_PARSE_MGMT_OPTION, + c->config_dir, + c->config_file); } else { @@ -2753,7 +2939,11 @@ LaunchOpenVPN(connection_t *c) c->exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name); if (c->exit_event == NULL) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_CREATE_EVENT, exit_event_name); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + o.hWnd, + TEXT(PACKAGE_NAME), + IDS_ERR_CREATE_EVENT, + exit_event_name); goto out; } @@ -2763,14 +2953,21 @@ LaunchOpenVPN(connection_t *c) find_free_tcp_port(&c->manage.skaddr); /* Construct command line -- put log first */ - _sntprintf_0(cmdline, _T("openvpn --log%ls \"%ls\" --config \"%ls\" " - "--setenv IV_GUI_VER \"%hs %hs\" --setenv IV_SSO openurl,webauth,crtext --service %ls 0 --auth-retry interact " - "--management %hs %hd stdin --management-query-passwords %ls" - "--management-hold"), - (o.log_append ? _T("-append") : _T("")), c->log_path, - c->config_file, PACKAGE_NAME, PACKAGE_VERSION_RESOURCE_STR, exit_event_name, - inet_ntoa(c->manage.skaddr.sin_addr), ntohs(c->manage.skaddr.sin_port), - (o.proxy_source != config ? _T("--management-query-proxy ") : _T(""))); + _sntprintf_0( + cmdline, + _T("openvpn --log%ls \"%ls\" --config \"%ls\" " + "--setenv IV_GUI_VER \"%hs %hs\" --setenv IV_SSO openurl,webauth,crtext --service %ls 0 --auth-retry interact " + "--management %hs %hd stdin --management-query-passwords %ls" + "--management-hold"), + (o.log_append ? _T("-append") : _T("")), + c->log_path, + c->config_file, + PACKAGE_NAME, + PACKAGE_VERSION_RESOURCE_STR, + exit_event_name, + inet_ntoa(c->manage.skaddr.sin_addr), + ntohs(c->manage.skaddr.sin_port), + (o.proxy_source != config ? _T("--management-query-proxy ") : _T(""))); BOOL use_iservice = (o.iservice_admin && IsWindows7OrGreater()) || !IsUserAdmin(); /* Try to open the service pipe */ @@ -2813,8 +3010,15 @@ LaunchOpenVPN(connection_t *c) const wchar_t *extra_options = L" --pull-filter ignore route-method"; size += wcslen(extra_options); - _sntprintf_0(startup_info, L"%ls%lc%ls%ls%lc%.*hs", c->config_dir, L'\0', - options, extra_options, L'\0', passwd_len, c->manage.password); + _sntprintf_0(startup_info, + L"%ls%lc%ls%ls%lc%.*hs", + c->config_dir, + L'\0', + options, + extra_options, + L'\0', + passwd_len, + c->manage.password); c->manage.password[passwd_len - 1] = '\0'; res = WritePipe(c->iserv.pipe, startup_info, size * sizeof(TCHAR)); @@ -2822,7 +3026,8 @@ LaunchOpenVPN(connection_t *c) if (!res) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_WRITE_SERVICE_PIPE); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_WRITE_SERVICE_PIPE); CloseHandle(c->exit_event); CloseServiceIO(&c->iserv); goto out; @@ -2831,7 +3036,8 @@ LaunchOpenVPN(connection_t *c) #ifdef ENABLE_OVPN3 else if (o.ovpn_engine == OPENVPN_ENGINE_OVPN3) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_WRITE_SERVICE_PIPE); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_WRITE_SERVICE_PIPE); CloseHandle(c->exit_event); CloseServiceIO(&c->iserv); goto out; @@ -2846,21 +3052,21 @@ LaunchOpenVPN(connection_t *c) SECURITY_DESCRIPTOR sd; /* Make I/O handles inheritable and accessible by all */ - SECURITY_ATTRIBUTES sa = { - .nLength = sizeof(sa), - .lpSecurityDescriptor = &sd, - .bInheritHandle = TRUE - }; + SECURITY_ATTRIBUTES sa = { .nLength = sizeof(sa), + .lpSecurityDescriptor = &sd, + .bInheritHandle = TRUE }; if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_INIT_SEC_DESC); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_INIT_SEC_DESC); CloseHandle(c->exit_event); return FALSE; } if (!SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE)) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_SET_SEC_DESC_ACL); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_SET_SEC_DESC_ACL); CloseHandle(c->exit_event); return FALSE; } @@ -2883,13 +3089,15 @@ LaunchOpenVPN(connection_t *c) /* Create the pipe for STDIN with only the read end inheritable */ if (!CreatePipe(&hStdInRead, &hStdInWrite, &sa, 0)) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_CREATE_PIPE_IN_READ); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_CREATE_PIPE_IN_READ); CloseHandle(c->exit_event); goto out; } if (!SetHandleInformation(hStdInWrite, HANDLE_FLAG_INHERIT, 0)) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_DUP_HANDLE_IN_WRITE); + ShowLocalizedMsgEx( + MB_OK | MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_DUP_HANDLE_IN_WRITE); CloseHandle(c->exit_event); goto out; } @@ -2903,10 +3111,24 @@ LaunchOpenVPN(connection_t *c) si.hStdError = hNul; /* Create an OpenVPN process for the connection */ - if (!CreateProcess(o.exe_path, cmdline, NULL, NULL, TRUE, - priority | CREATE_NO_WINDOW, NULL, c->config_dir, &si, &pi)) + if (!CreateProcess(o.exe_path, + cmdline, + NULL, + NULL, + TRUE, + priority | CREATE_NO_WINDOW, + NULL, + c->config_dir, + &si, + &pi)) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, o.hWnd, TEXT(PACKAGE_NAME), IDS_ERR_CREATE_PROCESS, o.exe_path, cmdline, c->config_dir); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + o.hWnd, + TEXT(PACKAGE_NAME), + IDS_ERR_CREATE_PROCESS, + o.exe_path, + cmdline, + c->config_dir); CloseHandle(c->exit_event); goto out; } @@ -2976,7 +3198,8 @@ TerminateOpenVPN(connection_t *c) } if (!GetExitCodeProcess(c->hProcess, &exit_code)) { - PrintDebug(L"In TerminateOpenVPN: failed to get process status: error = %lu", GetLastError()); + PrintDebug(L"In TerminateOpenVPN: failed to get process status: error = %lu", + GetLastError()); return FALSE; } if (exit_code == STILL_ACTIVE) @@ -3029,8 +3252,8 @@ SetStatusWinIcon(HWND hwndDlg, int iconId) { hIconBig = hIcon; } - SendMessage(hwndDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon); - SendMessage(hwndDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIconBig); + SendMessage(hwndDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); + SendMessage(hwndDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIconBig); } @@ -3106,11 +3329,9 @@ CheckVersion() /* Make handles inheritable and accessible by all */ SECURITY_DESCRIPTOR sd; - SECURITY_ATTRIBUTES sa = { - .nLength = sizeof(sa), - .lpSecurityDescriptor = &sd, - .bInheritHandle = TRUE - }; + SECURITY_ATTRIBUTES sa = { .nLength = sizeof(sa), + .lpSecurityDescriptor = &sd, + .bInheritHandle = TRUE }; if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { ShowLocalizedMsg(IDS_ERR_INIT_SEC_DESC); @@ -3150,8 +3371,8 @@ CheckVersion() si.hStdError = hStdOutWrite; /* Start OpenVPN to check version */ - bool success = CreateProcess(o.exe_path, cmdline, NULL, NULL, TRUE, - CREATE_NO_WINDOW, NULL, pwd, &si, &pi); + bool success = + CreateProcess(o.exe_path, cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, pwd, &si, &pi); if (!success) { ShowLocalizedMsg(IDS_ERR_CREATE_PROCESS, o.exe_path, cmdline, pwd); @@ -3172,9 +3393,9 @@ CheckVersion() if (p) { retval = TRUE; - p = strtok(p+8, " "); - strncpy(o.ovpn_version, p, _countof(o.ovpn_version)-1); - o.ovpn_version[_countof(o.ovpn_version)-1] = '\0'; + p = strtok(p + 8, " "); + strncpy(o.ovpn_version, p, _countof(o.ovpn_version) - 1); + o.ovpn_version[_countof(o.ovpn_version) - 1] = '\0'; } } @@ -3188,7 +3409,9 @@ CheckVersion() void ResetSavePasswords(connection_t *c) { - if (ShowLocalizedMsgEx(MB_OKCANCEL, o.hWnd, TEXT(PACKAGE_NAME), IDS_NFO_DELETE_PASS, c->config_name) == IDCANCEL) + if (ShowLocalizedMsgEx( + MB_OKCANCEL, o.hWnd, TEXT(PACKAGE_NAME), IDS_NFO_DELETE_PASS, c->config_name) + == IDCANCEL) { return; } @@ -3198,9 +3421,10 @@ ResetSavePasswords(connection_t *c) } /* keep this array in same order as corresponding resource ids -- IDS_NFO_OVPN_STATE_xxxxx */ -static const char *daemon_states[] = {"INITIAL", "CONNECTING", "ASSIGN_IP", - "ADD_ROUTES", "CONNECTED", "RECONNECTING", "EXITING", "WAIT", - "AUTH", "GET_CONFIG", "RESOLVE", "TCP_CONNECT", "AUTH_PENDING", NULL}; +static const char *daemon_states[] = { + "INITIAL", "CONNECTING", "ASSIGN_IP", "ADD_ROUTES", "CONNECTED", "RECONNECTING", "EXITING", + "WAIT", "AUTH", "GET_CONFIG", "RESOLVE", "TCP_CONNECT", "AUTH_PENDING", NULL +}; /* * Given an OpenVPN state as reported by the management interface diff --git a/openvpn.h b/openvpn.h index 123ab278e..a1d7df561 100644 --- a/openvpn.h +++ b/openvpn.h @@ -25,13 +25,15 @@ #include "options.h" -#define TRY_SETPROP(hwnd, name, p) \ - do { if (SetPropW(hwnd, name, p)) break; \ - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs:%d GetProp returned null", \ - __func__, __LINE__); \ - EndDialog(hwnd, IDABORT); \ - return false; \ - } while(0) +#define TRY_SETPROP(hwnd, name, p) \ + do \ + { \ + if (SetPropW(hwnd, name, p)) \ + break; \ + MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs:%d GetProp returned null", __func__, __LINE__); \ + EndDialog(hwnd, IDABORT); \ + return false; \ + } while (0) BOOL StartOpenVPN(connection_t *); @@ -79,24 +81,25 @@ extern const TCHAR *cfgProp; /* These error codes are from openvpn service sources */ #define ERROR_OPENVPN_STARTUP 0x20000000 -#define ERROR_STARTUP_DATA 0x20000001 -#define ERROR_MESSAGE_DATA 0x20000002 -#define ERROR_MESSAGE_TYPE 0x20000003 +#define ERROR_STARTUP_DATA 0x20000001 +#define ERROR_MESSAGE_DATA 0x20000002 +#define ERROR_MESSAGE_TYPE 0x20000003 /* Write a line to status window and optionally to the log file */ void WriteStatusLog(connection_t *c, const WCHAR *prefix, const WCHAR *line, BOOL fileio); -#define FLAG_CR_TYPE_SCRV1 0x1 /* static challenege */ -#define FLAG_CR_TYPE_CRV1 0x2 /* dynamic challenege */ -#define FLAG_CR_ECHO 0x4 /* echo the response */ -#define FLAG_CR_RESPONSE 0x8 /* response needed */ -#define FLAG_PASS_TOKEN 0x10 /* PKCS11 token password needed */ -#define FLAG_STRING_PKCS11 0x20 /* PKCS11 id needed */ -#define FLAG_PASS_PKEY 0x40 /* Private key password needed */ -#define FLAG_CR_TYPE_CRTEXT 0x80 /* crtext */ -#define FLAG_CR_TYPE_CONCAT 0x100 /* concatenate otp with password */ - -typedef struct { +#define FLAG_CR_TYPE_SCRV1 0x1 /* static challenege */ +#define FLAG_CR_TYPE_CRV1 0x2 /* dynamic challenege */ +#define FLAG_CR_ECHO 0x4 /* echo the response */ +#define FLAG_CR_RESPONSE 0x8 /* response needed */ +#define FLAG_PASS_TOKEN 0x10 /* PKCS11 token password needed */ +#define FLAG_STRING_PKCS11 0x20 /* PKCS11 id needed */ +#define FLAG_PASS_PKEY 0x40 /* Private key password needed */ +#define FLAG_CR_TYPE_CRTEXT 0x80 /* crtext */ +#define FLAG_CR_TYPE_CONCAT 0x100 /* concatenate otp with password */ + +typedef struct +{ connection_t *c; unsigned int flags; char *str; @@ -110,11 +113,9 @@ typedef struct { * true on success. The caller must free param->str and param->id * even on error. */ -BOOL -parse_dynamic_cr(const char *str, auth_param_t *param); +BOOL parse_dynamic_cr(const char *str, auth_param_t *param); -void -free_auth_param(auth_param_t *param); +void free_auth_param(auth_param_t *param); /* * Given an OpenVPN state as reported by the management interface diff --git a/openvpn_config.c b/openvpn_config.c index 56f055e49..668e5eae6 100644 --- a/openvpn_config.c +++ b/openvpn_config.c @@ -61,8 +61,7 @@ match(const WIN32_FIND_DATA *find, const TCHAR *ext) i = _tcslen(find->cFileName) - ext_len - 1; - if (i > 0 && find->cFileName[i] == '.' - && _tcsicmp(find->cFileName + i + 1, ext) == 0) + if (i > 0 && find->cFileName[i] == '.' && _tcsicmp(find->cFileName + i + 1, ext) == 0) { return match_file; } @@ -170,9 +169,9 @@ AddConfigFileToList(int group, const TCHAR *filename, const TCHAR *config_dir) } } -#define FLAG_WARN_DUPLICATES (0x1) -#define FLAG_WARN_MAX_CONFIGS (0x2) -#define FLAG_ADD_CONFIG_GROUPS (0x4) +#define FLAG_WARN_DUPLICATES (0x1) +#define FLAG_WARN_MAX_CONFIGS (0x2) +#define FLAG_ADD_CONFIG_GROUPS (0x4) /* * Create a new group with the given name as a child of the @@ -191,7 +190,7 @@ NewConfigGroup(const wchar_t *name, int parent, int flags) if (!o.groups || o.num_groups == o.max_groups) { o.max_groups += 10; - void *tmp = realloc(o.groups, sizeof(*o.groups)*o.max_groups); + void *tmp = realloc(o.groups, sizeof(*o.groups) * o.max_groups); if (!tmp) { o.max_groups -= 10; @@ -264,8 +263,7 @@ ActivateConfigGroups(void) config_group_t *cg = CONFIG_GROUP(c); /* if not root and has only this config as child -- squash it */ - if (PARENT_GROUP(cg) && cg->children == 1 - && !wcscmp(cg->name, c->config_name)) + if (PARENT_GROUP(cg) && cg->children == 1 && !wcscmp(cg->name, c->config_name)) { cg->children--; c->group = cg->parent; @@ -351,8 +349,7 @@ BuildFileList0(const TCHAR *config_dir, int recurse_depth, int group, int flags) match_t match_type = match(&find_obj, o.ext_string); if (match_type == match_dir) { - if (wcscmp(find_obj.cFileName, _T(".")) - && wcscmp(find_obj.cFileName, _T(".."))) + if (wcscmp(find_obj.cFileName, _T(".")) && wcscmp(find_obj.cFileName, _T(".."))) { /* recurse into subdirectory */ _sntprintf_0(subdir_name, _T("%ls\\%ls"), config_dir, find_obj.cFileName); @@ -376,23 +373,39 @@ GetFileInfo(const wchar_t *path, BY_HANDLE_FILE_INFORMATION *info) bool ret = false; /* FILE_FLAG_BACKUP_SEMANTICS required to open directories */ - HANDLE fd = CreateFileW(path, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + HANDLE fd = CreateFileW(path, + 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + NULL); if (fd == INVALID_HANDLE_VALUE) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"GetFileInfo: Error opening path <%ls> (status = %lu)", path, GetLastError()); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"GetFileInfo: Error opening path <%ls> (status = %lu)", + path, + GetLastError()); return ret; } ret = GetFileInformationByHandle(fd, info); if (!ret) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"GetFileInfo: Error accessing file information for path <%ls> (status = %lu)", path, GetLastError()); + MsgToEventLog( + EVENTLOG_ERROR_TYPE, + L"GetFileInfo: Error accessing file information for path <%ls> (status = %lu)", + path, + GetLastError()); } else { - PrintDebug(L"path = <%ls> volumeid = %lu file index = (%lu,%lu)", path, info->dwVolumeSerialNumber, info->nFileIndexLow, info->nFileIndexHigh); + PrintDebug(L"path = <%ls> volumeid = %lu file index = (%lu,%lu)", + path, + info->dwVolumeSerialNumber, + info->nFileIndexLow, + info->nFileIndexHigh); } CloseHandle(fd); @@ -474,8 +487,7 @@ BuildFileList() BuildFileList0(o.global_config_dir, recurse_depth, system_gp, flags); } - if (o.service_state == service_connected - && o.enable_persistent) + if (o.service_state == service_connected && o.enable_persistent) { if (!IsSamePath(o.config_auto_dir, o.config_dir)) { diff --git a/options.c b/options.c index f9005ab29..6de41ca88 100644 --- a/options.c +++ b/options.c @@ -52,7 +52,7 @@ extern options_t o; static version_t MakeVersion(short ma, short mi, short b, short r) { - version_t v = {ma, mi, b, r}; + version_t v = { ma, mi, b, r }; return v; } @@ -62,7 +62,7 @@ ExpandString(WCHAR *str, int max_len) WCHAR expanded_string[MAX_PATH]; int len = ExpandEnvironmentStringsW(str, expanded_string, _countof(expanded_string)); - if (len > max_len || len > (int) _countof(expanded_string)) + if (len > max_len || len > (int)_countof(expanded_string)) { PrintDebug(L"Failed to expanded env vars in '%ls'. String too long", str); return; @@ -96,7 +96,11 @@ add_option(options_t *options, int i, TCHAR **p) LoadLocalizedStringBuf(caption, _countof(caption), IDS_NFO_USAGECAPTION); LoadLocalizedStringBuf(msg, _countof(msg), IDS_NFO_USAGE); - MessageBoxExW(NULL, msg, caption, MB_OK | MB_SETFOREGROUND | MBOX_RTL_FLAGS | MB_ICONINFORMATION, GetGUILanguage()); + MessageBoxExW(NULL, + msg, + caption, + MB_OK | MB_SETFOREGROUND | MBOX_RTL_FLAGS | MB_ICONINFORMATION, + GetGUILanguage()); exit(0); } else if (streq(p[0], _T("connect")) && p[1]) @@ -105,7 +109,8 @@ add_option(options_t *options, int i, TCHAR **p) if (!options->auto_connect || options->num_auto_connect == options->max_auto_connect) { options->max_auto_connect += 10; - void *tmp = realloc(options->auto_connect, sizeof(wchar_t *)*options->max_auto_connect); + void *tmp = + realloc(options->auto_connect, sizeof(wchar_t *) * options->max_auto_connect); if (!tmp) { options->max_auto_connect -= 10; @@ -157,8 +162,7 @@ add_option(options_t *options, int i, TCHAR **p) ++i; _tcsncpy(options->priority_string, p[1], _countof(options->priority_string) - 1); } - else if ( (streq(p[0], _T("append_string")) - || streq(p[0], _T("log_append"))) && p[1]) + else if ((streq(p[0], _T("append_string")) || streq(p[0], _T("log_append"))) && p[1]) { ++i; options->log_append = _ttoi(p[1]) ? 1 : 0; @@ -316,9 +320,11 @@ add_option(options_t *options, int i, TCHAR **p) { ++i; int tmp = _wtoi(p[1]); - if (tmp < 1 || tmp > 61000) + if (tmp < 1 || tmp > 61000) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Specified management port offset is not valid (must be in the range 1 to 61000). Ignored."); + MsgToEventLog( + EVENTLOG_ERROR_TYPE, + L"Specified management port offset is not valid (must be in the range 1 to 61000). Ignored."); } else { @@ -410,8 +416,7 @@ ProcessCommandLine(options_t *options, TCHAR *command_line) { ++pos; } - } - while (*pos != _T('\0')); + } while (*pos != _T('\0')); if (argc == 0) { @@ -419,7 +424,7 @@ ProcessCommandLine(options_t *options, TCHAR *command_line) } /* Tokenize the arguments */ - argv = (TCHAR **) malloc(argc * sizeof(TCHAR *)); + argv = (TCHAR **)malloc(argc * sizeof(TCHAR *)); pos = command_line; argc = 0; @@ -458,8 +463,7 @@ ProcessCommandLine(options_t *options, TCHAR *command_line) } *pos++ = _T('\0'); - } - while (*pos != _T('\0')); + } while (*pos != _T('\0')); parse_argv(options, argc, argv); @@ -504,8 +508,7 @@ GetConnByName(const WCHAR *name) { for (connection_t *c = o.chead; c; c = c->next) { - if (wcsicmp(c->config_file, name) == 0 - || wcsicmp(c->config_name, name) == 0) + if (wcsicmp(c->config_file, name) == 0 || wcsicmp(c->config_name, name) == 0) { return c; } @@ -526,7 +529,8 @@ BrowseFolder(const WCHAR *initial_path, WCHAR *selected_path, size_t selected_pa return false; } - result = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_ALL, &IID_IFileOpenDialog, (void **)&pfd); + result = CoCreateInstance( + &CLSID_FileOpenDialog, NULL, CLSCTX_ALL, &IID_IFileOpenDialog, (void **)&pfd); if (SUCCEEDED(result)) { /* Select folders, not files */ @@ -580,7 +584,8 @@ BrowseFolder(const WCHAR *initial_path, WCHAR *selected_path, size_t selected_pa if (initResult != RPC_E_CHANGED_MODE && SUCCEEDED(initResult)) { - CoUninitialize(); /*All successful CoInitializeEx calls must be balanced by a corresponding CoUninitialize */ + CoUninitialize(); /*All successful CoInitializeEx calls must be balanced by a corresponding + CoUninitialize */ } return SUCCEEDED(dialogResult); @@ -610,8 +615,8 @@ CheckAdvancedDlgParams(HWND hdlg) ExpandString(tmp_path, _countof(tmp_path)); if (PathIsRelativeW(tmp_path)) { - MessageBox(hdlg, L"Specified config directory is not an absolute path", - L"Option error", MB_OK); + MessageBox( + hdlg, L"Specified config directory is not an absolute path", L"Option error", MB_OK); return false; } @@ -619,26 +624,31 @@ CheckAdvancedDlgParams(HWND hdlg) ExpandString(tmp_path, _countof(tmp_path)); if (PathIsRelativeW(tmp_path)) { - MessageBox(hdlg, L"Specified log directory is not an absolute path", - L"Option error", MB_OK); + MessageBox( + hdlg, L"Specified log directory is not an absolute path", L"Option error", MB_OK); return false; } BOOL status; int tmp = GetDlgItemInt(hdlg, ID_EDT_MGMT_PORT, &status, FALSE); - /* Restrict the port offset to sensible range -- port used is this + upto ~4000 as connection index */ + /* Restrict the port offset to sensible range -- port used is this + upto ~4000 as connection + * index */ if (!status || (tmp < 1 || tmp > 61000)) { - MessageBox(hdlg, L"Specified port is not valid (must be in the range 1 to 61000)", - L"Option error", MB_OK); + MessageBox(hdlg, + L"Specified port is not valid (must be in the range 1 to 61000)", + L"Option error", + MB_OK); return false; } tmp = GetDlgItemInt(hdlg, ID_EDT_POPUP_MUTE, &status, FALSE); if (!status || tmp < 0) { - MessageBox(hdlg, L"Specified mute interval is not valid (must be a positive integer)", - L"Option error", MB_OK); + MessageBox(hdlg, + L"Specified mute interval is not valid (must be a positive integer)", + L"Option error", + MB_OK); return false; } @@ -658,9 +668,9 @@ SaveAdvancedDlgParams(HWND hdlg) wcsncpy(tmp_path1, tmp_path, _countof(tmp_path1)); ExpandString(tmp_path1, _countof(tmp_path1)); - if (EnsureDirExists(tmp_path1)) /* this will try to create the path if needed */ + if (EnsureDirExists(tmp_path1)) /* this will try to create the path if needed */ { - wcsncpy(o.log_dir, tmp_path, _countof(o.log_dir)); /* save unexpanded path */ + wcsncpy(o.log_dir, tmp_path, _countof(o.log_dir)); /* save unexpanded path */ } else { @@ -700,8 +710,8 @@ SaveAdvancedDlgParams(HWND hdlg) o.popup_mute_interval = tmp; } - o.ovpn_engine = IsDlgButtonChecked(hdlg, ID_RB_ENGINE_OVPN3) ? - OPENVPN_ENGINE_OVPN3 : OPENVPN_ENGINE_OVPN2; + o.ovpn_engine = + IsDlgButtonChecked(hdlg, ID_RB_ENGINE_OVPN3) ? OPENVPN_ENGINE_OVPN3 : OPENVPN_ENGINE_OVPN2; SaveRegistryKeys(); ExpandOptions(); @@ -744,8 +754,11 @@ LoadAdvancedDlgParams(HWND hdlg) } #ifdef ENABLE_OVPN3 - CheckRadioButton(hdlg, ID_RB_ENGINE_OVPN2, ID_RB_ENGINE_OVPN3, - o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? ID_RB_ENGINE_OVPN3 : ID_RB_ENGINE_OVPN2); + CheckRadioButton(hdlg, + ID_RB_ENGINE_OVPN2, + ID_RB_ENGINE_OVPN3, + o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? ID_RB_ENGINE_OVPN3 + : ID_RB_ENGINE_OVPN2); #endif } @@ -756,7 +769,6 @@ AdvancedSettingsDlgProc(HWND hwndDlg, UINT msg, UNUSED WPARAM wParam, LPARAM lPa switch (msg) { - case WM_INITDIALOG: /* Limit extension editbox to 4 chars. */ SendMessage(GetDlgItem(hwndDlg, ID_EDT_CONFIG_EXT), EM_SETLIMITTEXT, 4, 0); @@ -790,13 +802,14 @@ AdvancedSettingsDlgProc(HWND hwndDlg, UINT msg, UNUSED WPARAM wParam, LPARAM lPa break; case WM_NOTIFY: - psn = (LPPSHNOTIFY) lParam; - if (psn->hdr.code == (UINT) PSN_KILLACTIVE) + psn = (LPPSHNOTIFY)lParam; + if (psn->hdr.code == (UINT)PSN_KILLACTIVE) { - SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (CheckAdvancedDlgParams(hwndDlg) ? FALSE : TRUE)); + SetWindowLongPtr( + hwndDlg, DWLP_MSGRESULT, (CheckAdvancedDlgParams(hwndDlg) ? FALSE : TRUE)); return TRUE; } - if (psn->hdr.code == (UINT) PSN_APPLY) + if (psn->hdr.code == (UINT)PSN_APPLY) { BOOL status = SaveAdvancedDlgParams(hwndDlg); SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, status ? PSNRET_NOERROR : PSNRET_INVALID); @@ -835,8 +848,8 @@ CompareStringExpanded(const WCHAR *str1, const WCHAR *str2) wcsncpy(str1_cpy, str1, _countof(str1_cpy)); wcsncpy(str2_cpy, str2, _countof(str2_cpy)); - str1_cpy[MAX_PATH-1] = L'\0'; - str2_cpy[MAX_PATH-1] = L'\0'; + str1_cpy[MAX_PATH - 1] = L'\0'; + str2_cpy[MAX_PATH - 1] = L'\0'; ExpandString(str1_cpy, _countof(str1_cpy)); ExpandString(str2_cpy, _countof(str2_cpy)); diff --git a/options.h b/options.h index 30d691183..a5d61b2a4 100644 --- a/options.h +++ b/options.h @@ -36,34 +36,38 @@ typedef struct connection connection_t; #include "echo.h" #include "pkcs11.h" -#define MAX_NAME (UNLEN + 1) +#define MAX_NAME (UNLEN + 1) /* * Maximum number of parameters associated with an option, * including the option name itself. */ -#define MAX_PARMS 5 /* Max number of parameters per option */ - -typedef enum { - service_noaccess = -1, - service_disconnected = 0, - service_connecting = 1, - service_connected = 2 +#define MAX_PARMS 5 /* Max number of parameters per option */ + +typedef enum +{ + service_noaccess = -1, + service_disconnected = 0, + service_connecting = 1, + service_connected = 2 } service_state_t; -typedef enum { +typedef enum +{ config, windows, manual } proxy_source_t; -typedef enum { +typedef enum +{ http, socks } proxy_t; /* connection states */ -typedef enum { +typedef enum +{ disconnected, onhold, connecting, @@ -78,29 +82,31 @@ typedef enum { } conn_state_t; /* Interactive Service IO parameters */ -typedef struct { +typedef struct +{ OVERLAPPED o; /* This has to be the first element */ HANDLE pipe; HANDLE hEvent; WCHAR readbuf[512]; } service_io_t; -#define FLAG_ALLOW_CHANGE_PASSPHRASE (1<<1) -#define FLAG_SAVE_KEY_PASS (1<<4) -#define FLAG_SAVE_AUTH_PASS (1<<5) -#define FLAG_DISABLE_SAVE_PASS (1<<6) -#define FLAG_DISABLE_ECHO_MSG (1<<7) -#define FLAG_DAEMON_PERSISTENT (1<<8) -#define FLAG_WAIT_UNLOCK (1<<9) +#define FLAG_ALLOW_CHANGE_PASSPHRASE (1 << 1) +#define FLAG_SAVE_KEY_PASS (1 << 4) +#define FLAG_SAVE_AUTH_PASS (1 << 5) +#define FLAG_DISABLE_SAVE_PASS (1 << 6) +#define FLAG_DISABLE_ECHO_MSG (1 << 7) +#define FLAG_DAEMON_PERSISTENT (1 << 8) +#define FLAG_WAIT_UNLOCK (1 << 9) -#define CONFIG_VIEW_AUTO (0) -#define CONFIG_VIEW_FLAT (1) -#define CONFIG_VIEW_NESTED (2) +#define CONFIG_VIEW_AUTO (0) +#define CONFIG_VIEW_FLAT (1) +#define CONFIG_VIEW_NESTED (2) -#define OPENVPN_ENGINE_OVPN2 (0) -#define OPENVPN_ENGINE_OVPN3 (1) +#define OPENVPN_ENGINE_OVPN2 (0) +#define OPENVPN_ENGINE_OVPN3 (1) -typedef struct { +typedef struct +{ unsigned short major, minor, build, revision; } version_t; @@ -110,92 +116,96 @@ typedef struct { * Not a complete tree: only navigation from child to parent is supported * which is enough for our purposes. */ -typedef struct config_group { - int id; /* A unique id for the group >= 0*/ - wchar_t name[40]; /* Name of the group -- possibly truncated */ - int parent; /* Id of parent group. -1 implies no parent */ - BOOL active; /* Displayed in the menu if true -- used to prune empty groups */ - int children; /* Number of children groups and configs */ - int pos; /* Index within the parent group -- used for rendering */ - HMENU menu; /* Handle to menu entry for this group */ +typedef struct config_group +{ + int id; /* A unique id for the group >= 0*/ + wchar_t name[40]; /* Name of the group -- possibly truncated */ + int parent; /* Id of parent group. -1 implies no parent */ + BOOL active; /* Displayed in the menu if true -- used to prune empty groups */ + int children; /* Number of children groups and configs */ + int pos; /* Index within the parent group -- used for rendering */ + HMENU menu; /* Handle to menu entry for this group */ } config_group_t; /* short hand for pointer to the group a config belongs to */ -#define CONFIG_GROUP(c) (&o.groups[(c)->group]) -#define PARENT_GROUP(cg) ((cg)->parent < 0 ? NULL : &o.groups[(cg)->parent]) +#define CONFIG_GROUP(c) (&o.groups[(c)->group]) +#define PARENT_GROUP(cg) ((cg)->parent < 0 ? NULL : &o.groups[(cg)->parent]) #define PERSISTENT_ROOT_GROUP (&o.groups[1]) /* Connections parameters */ -struct connection { - TCHAR config_file[MAX_PATH]; /* Name of the config file */ - TCHAR config_name[MAX_PATH]; /* Name of the connection */ - TCHAR config_dir[MAX_PATH]; /* Path to this configs dir */ - TCHAR log_path[MAX_PATH]; /* Path to Logfile */ - TCHAR ip[16]; /* Assigned IP address for this connection */ - TCHAR ipv6[46]; /* Assigned IPv6 address */ - BOOL auto_connect; /* AutoConnect at startup id TRUE */ - conn_state_t state; /* State the connection currently is in */ - int failed_psw_attempts; /* # of failed attempts entering password(s) */ - int failed_auth_attempts; /* # of failed user-auth attempts */ - time_t connected_since; /* Time when the connection was established */ - proxy_t proxy_type; /* Set during querying proxy credentials */ - int group; /* ID of the group this config belongs to */ - int pos; /* Index of the config within its group */ - - struct { +struct connection +{ + TCHAR config_file[MAX_PATH]; /* Name of the config file */ + TCHAR config_name[MAX_PATH]; /* Name of the connection */ + TCHAR config_dir[MAX_PATH]; /* Path to this configs dir */ + TCHAR log_path[MAX_PATH]; /* Path to Logfile */ + TCHAR ip[16]; /* Assigned IP address for this connection */ + TCHAR ipv6[46]; /* Assigned IPv6 address */ + BOOL auto_connect; /* AutoConnect at startup id TRUE */ + conn_state_t state; /* State the connection currently is in */ + int failed_psw_attempts; /* # of failed attempts entering password(s) */ + int failed_auth_attempts; /* # of failed user-auth attempts */ + time_t connected_since; /* Time when the connection was established */ + proxy_t proxy_type; /* Set during querying proxy credentials */ + int group; /* ID of the group this config belongs to */ + int pos; /* Index of the config within its group */ + + struct + { SOCKET sk; SOCKADDR_IN skaddr; time_t timeout; - char password[4096]; /* match with largest possible passwd in openvpn.exe */ + char password[4096]; /* match with largest possible passwd in openvpn.exe */ char *saved_data; size_t saved_size; mgmt_cmd_t *cmd_queue; - DWORD connected; /* 1: management interface connected, 2: connected and ready */ + DWORD connected; /* 1: management interface connected, 2: connected and ready */ } manage; - HANDLE hProcess; /* Handle of openvpn process if directly started */ + HANDLE hProcess; /* Handle of openvpn process if directly started */ service_io_t iserv; HANDLE exit_event; DWORD threadId; HWND hwndStatus; int flags; - char *dynamic_cr; /* Pointer to buffer for dynamic challenge string received */ + char *dynamic_cr; /* Pointer to buffer for dynamic challenge string received */ unsigned long long int bytes_in; unsigned long long int bytes_out; - struct env_item *es; /* Pointer to the head of config-specific env variables list */ - struct echo_msg echo_msg; /* Message echo-ed from server or client config and related data */ + struct env_item *es; /* Pointer to the head of config-specific env variables list */ + struct echo_msg echo_msg; /* Message echo-ed from server or client config and related data */ struct pkcs11_list pkcs11_list; - char daemon_state[20]; /* state of openvpn.ex: WAIT, AUTH, GET_CONFIG etc.. */ - int id; /* index of config -- treat as immutable once assigned */ + char daemon_state[20]; /* state of openvpn.ex: WAIT, AUTH, GET_CONFIG etc.. */ + int id; /* index of config -- treat as immutable once assigned */ connection_t *next; }; /* All options used within OpenVPN GUI */ -typedef struct { +typedef struct +{ /* Array of configs to autostart */ const TCHAR **auto_connect; /* Connection parameters */ - connection_t *chead; /* Head of connection list */ - connection_t *ctail; /* Tail of connection list */ - config_group_t *groups; /* Array of nodes defining the config groups tree */ - int num_configs; /* Number of configs */ - int num_auto_connect; /* Number of auto-connect configs */ - int num_groups; /* Number of config groups */ - int max_configs; /* Current capacity of conn array */ - int max_auto_connect; /* Current capacity of auto_connect array */ - int max_groups; /* Current capacity of groups array */ - - service_state_t service_state; /* State of the OpenVPN Service */ + connection_t *chead; /* Head of connection list */ + connection_t *ctail; /* Tail of connection list */ + config_group_t *groups; /* Array of nodes defining the config groups tree */ + int num_configs; /* Number of configs */ + int num_auto_connect; /* Number of auto-connect configs */ + int num_groups; /* Number of config groups */ + int max_configs; /* Current capacity of conn array */ + int max_auto_connect; /* Current capacity of auto_connect array */ + int max_groups; /* Current capacity of groups array */ + + service_state_t service_state; /* State of the OpenVPN Service */ /* Proxy Settings */ - proxy_source_t proxy_source; /* Where to get proxy information from */ - proxy_t proxy_type; /* The type of proxy to use */ - TCHAR proxy_http_address[100]; /* HTTP Proxy Address */ - TCHAR proxy_http_port[6]; /* HTTP Proxy Port */ - TCHAR proxy_socks_address[100]; /* SOCKS Proxy Address */ - TCHAR proxy_socks_port[6]; /* SOCKS Proxy Address */ + proxy_source_t proxy_source; /* Where to get proxy information from */ + proxy_t proxy_type; /* The type of proxy to use */ + TCHAR proxy_http_address[100]; /* HTTP Proxy Address */ + TCHAR proxy_http_port[6]; /* HTTP Proxy Port */ + TCHAR proxy_socks_address[100]; /* SOCKS Proxy Address */ + TCHAR proxy_socks_port[6]; /* SOCKS Proxy Address */ /* HKLM Registry values */ TCHAR exe_path[MAX_PATH]; @@ -218,18 +228,19 @@ typedef struct { DWORD iservice_admin; DWORD show_balloon; DWORD show_script_window; - DWORD connectscript_timeout; /* Connect Script execution timeout (sec) */ - DWORD disconnectscript_timeout; /* Disconnect Script execution timeout (sec) */ - DWORD preconnectscript_timeout; /* Preconnect Script execution timeout (sec) */ - DWORD config_menu_view; /* 0 for auto, 1 for original flat menu, 2 for hierarchical */ - DWORD disable_popup_messages; /* set nonzero to suppress all echo msg messages */ - DWORD popup_mute_interval; /* Interval in hours to suppress repeated echo messages */ - DWORD mgmt_port_offset; /* management interface port = this offset + index of connection profile */ - - DWORD ovpn_engine; /* 0 - openvpn2, 1 - openvpn3 */ - DWORD enable_persistent; /* 0 - disabled, 1 - enabled, 2 - enabled & auto attach */ - DWORD enable_auto_restart; /* 0 - disabled, >0 enabled */ - DWORD disable_password_reveal; /* read from group policy */ + DWORD connectscript_timeout; /* Connect Script execution timeout (sec) */ + DWORD disconnectscript_timeout; /* Disconnect Script execution timeout (sec) */ + DWORD preconnectscript_timeout; /* Preconnect Script execution timeout (sec) */ + DWORD config_menu_view; /* 0 for auto, 1 for original flat menu, 2 for hierarchical */ + DWORD disable_popup_messages; /* set nonzero to suppress all echo msg messages */ + DWORD popup_mute_interval; /* Interval in hours to suppress repeated echo messages */ + DWORD mgmt_port_offset; /* management interface port = this offset + index of connection profile + */ + + DWORD ovpn_engine; /* 0 - openvpn2, 1 - openvpn3 */ + DWORD enable_persistent; /* 0 - disabled, 1 - enabled, 2 - enabled & auto attach */ + DWORD enable_auto_restart; /* 0 - disabled, >0 enabled */ + DWORD disable_password_reveal; /* read from group policy */ #ifdef DEBUG FILE *debug_fp; #endif @@ -243,7 +254,7 @@ typedef struct { unsigned int dpi_scale; COLORREF clr_warning; COLORREF clr_error; - int action; /* action to send to a running instance */ + int action; /* action to send to a running instance */ TCHAR *action_arg; HANDLE session_semaphore; HANDLE event_log; diff --git a/pkcs11.c b/pkcs11.c index 07b5b2589..b228ed905 100644 --- a/pkcs11.c +++ b/pkcs11.c @@ -55,7 +55,7 @@ struct cert_info struct pkcs11_entry { - char *id; /* pkcs11-id string value as received from daemon */ + char *id; /* pkcs11-id string value as received from daemon */ struct cert_info cert; /* decoded certificate structure */ }; @@ -115,14 +115,18 @@ pkcs11_list_clear(struct pkcs11_list *l) static wchar_t * extract_name_entry(const CERT_CONTEXT *ctx, bool issuer) { - DWORD size = CertGetNameStringW(ctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE, - issuer ? CERT_NAME_ISSUER_FLAG : 0, NULL, NULL, 0); + DWORD size = CertGetNameStringW( + ctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE, issuer ? CERT_NAME_ISSUER_FLAG : 0, NULL, NULL, 0); - wchar_t *name = malloc(size*sizeof(wchar_t)); + wchar_t *name = malloc(size * sizeof(wchar_t)); if (name) { - size = CertGetNameStringW(ctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE, - issuer ? CERT_NAME_ISSUER_FLAG : 0, NULL, name, size); + size = CertGetNameStringW(ctx, + CERT_NAME_FRIENDLY_DISPLAY_TYPE, + issuer ? CERT_NAME_ISSUER_FLAG : 0, + NULL, + name, + size); } return name; @@ -138,14 +142,13 @@ decode_certificate(struct cert_info *cert, const char *b64) unsigned char *der = NULL; bool ret = false; - int len = Base64Decode(b64, (char **) &der); + int len = Base64Decode(b64, (char **)&der); if (len < 0) { goto out; } - const CERT_CONTEXT *ctx = - CertCreateCertificateContext(X509_ASN_ENCODING, der, (DWORD) len); + const CERT_CONTEXT *ctx = CertCreateCertificateContext(X509_ASN_ENCODING, der, (DWORD)len); if (!ctx) { @@ -171,7 +174,7 @@ static UINT pkcs11_entry_parse(const char *data, struct pkcs11_list *l) { char *token = NULL; - UINT index = (UINT) -1; + UINT index = (UINT)-1; const char *quotes = " '"; struct pkcs11_entry *pe = NULL; @@ -212,7 +215,7 @@ pkcs11_entry_parse(const char *data, struct pkcs11_list *l) if (!decode_certificate(&pe->cert, tmp)) { pkcs11_entry_free(pe); - index = (UINT) -1; + index = (UINT)-1; goto out; } } @@ -234,7 +237,7 @@ pkcs11_id_send(connection_t *c, const char *id) if (cmd) { snprintf(cmd, len, format, id ? id : ""); - cmd[len-1] = '\0'; + cmd[len - 1] = '\0'; ManagementCommand(c, cmd, NULL, regular); } else @@ -254,12 +257,13 @@ OnPkcs11(connection_t *c, UNUSED char *msg) struct pkcs11_list *l = &c->pkcs11_list; pkcs11_list_clear(l); - l->selected = (UINT) -1; /* set selection to an invalid index */ + l->selected = (UINT)-1; /* set selection to an invalid index */ /* prompt user to select a certificate */ - if (IDOK == LocalizedDialogBoxParamEx(ID_DLG_PKCS11_QUERY, c->hwndStatus, QueryPkcs11DialogProc, (LPARAM)c) - && l->state & STATE_SELECTED - && l->selected < l->count) + if (IDOK + == LocalizedDialogBoxParamEx( + ID_DLG_PKCS11_QUERY, c->hwndStatus, QueryPkcs11DialogProc, (LPARAM)c) + && l->state & STATE_SELECTED && l->selected < l->count) { pkcs11_id_send(c, l->pe[l->selected].id); } @@ -272,7 +276,7 @@ pkcs11_count_recv(connection_t *c, char *msg) struct pkcs11_list *l = &c->pkcs11_list; if (msg && strbegins(msg, ">PKCS11ID-COUNT:")) { - l->count = strtoul(msg+16, NULL, 10); + l->count = strtoul(msg + 16, NULL, 10); } else { @@ -293,19 +297,19 @@ static void pkcs11_entry_recv(connection_t *c, char *msg) { struct pkcs11_list *l = &c->pkcs11_list; - UINT index = (UINT) -1; + UINT index = (UINT)-1; if (msg && strbegins(msg, ">PKCS11ID-ENTRY:")) { - index = pkcs11_entry_parse(msg+16, l); + index = pkcs11_entry_parse(msg + 16, l); } - if (index == (UINT) -1) + if (index == (UINT)-1) { WriteStatusLog(c, L"GUI> ", L"Invalid pkcs11 entry ignored.", false); return; } - else if (index + 1 == l->count) /* done */ + else if (index + 1 == l->count) /* done */ { l->state |= STATE_FILLED; } @@ -326,15 +330,14 @@ pkcs11_list_update(connection_t *c) { struct pkcs11_list *l = &c->pkcs11_list; - if ((l->state & STATE_GET_COUNT) == 0) + if ((l->state & STATE_GET_COUNT) == 0) { ManagementCommand(c, "pkcs11-id-count", pkcs11_count_recv, regular); l->state |= STATE_GET_COUNT; } else if (l->count > 0 && (l->state & STATE_GET_ENTRY) == 0) { - if (!l->pe - && !pkcs11_list_alloc(l)) + if (!l->pe && !pkcs11_list_alloc(l)) { WriteStatusLog(c, L"GUI> ", L"Out of memory for pkcs11 entry list", false); l->count = 0; @@ -374,18 +377,37 @@ pkcs11_listview_resize(HWND hwnd, UINT w, UINT h) { HWND lv = GetDlgItem(hwnd, ID_LVW_PKCS11); - MoveWindow(lv, DPI_SCALE(20), DPI_SCALE(25), - w - DPI_SCALE(40), h - DPI_SCALE(120), TRUE); - MoveWindow(GetDlgItem(hwnd, ID_TXT_PKCS11), DPI_SCALE(20), DPI_SCALE(5), - w-DPI_SCALE(30), DPI_SCALE(15), TRUE); - MoveWindow(GetDlgItem(hwnd, ID_TXT_WARNING), DPI_SCALE(20), h - DPI_SCALE(80), - w-DPI_SCALE(20), DPI_SCALE(30), TRUE); - MoveWindow(GetDlgItem(hwnd, IDOK), DPI_SCALE(20), h - DPI_SCALE(30), - DPI_SCALE(60), DPI_SCALE(23), TRUE); - MoveWindow(GetDlgItem(hwnd, IDCANCEL), DPI_SCALE(90), h - DPI_SCALE(30), - DPI_SCALE(60), DPI_SCALE(23), TRUE); - MoveWindow(GetDlgItem(hwnd, IDRETRY), DPI_SCALE(200), h - DPI_SCALE(30), - DPI_SCALE(60), DPI_SCALE(23), TRUE); + MoveWindow(lv, DPI_SCALE(20), DPI_SCALE(25), w - DPI_SCALE(40), h - DPI_SCALE(120), TRUE); + MoveWindow(GetDlgItem(hwnd, ID_TXT_PKCS11), + DPI_SCALE(20), + DPI_SCALE(5), + w - DPI_SCALE(30), + DPI_SCALE(15), + TRUE); + MoveWindow(GetDlgItem(hwnd, ID_TXT_WARNING), + DPI_SCALE(20), + h - DPI_SCALE(80), + w - DPI_SCALE(20), + DPI_SCALE(30), + TRUE); + MoveWindow(GetDlgItem(hwnd, IDOK), + DPI_SCALE(20), + h - DPI_SCALE(30), + DPI_SCALE(60), + DPI_SCALE(23), + TRUE); + MoveWindow(GetDlgItem(hwnd, IDCANCEL), + DPI_SCALE(90), + h - DPI_SCALE(30), + DPI_SCALE(60), + DPI_SCALE(23), + TRUE); + MoveWindow(GetDlgItem(hwnd, IDRETRY), + DPI_SCALE(200), + h - DPI_SCALE(30), + DPI_SCALE(60), + DPI_SCALE(23), + TRUE); listview_set_column_width(lv); } @@ -406,7 +428,7 @@ pkcs11_listview_init(HWND parent) SendMessage(lv, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); /* Use bold font for header */ - HFONT hf = (HFONT) SendMessage(lv, WM_GETFONT, 0, 0); + HFONT hf = (HFONT)SendMessage(lv, WM_GETFONT, 0, 0); if (hf) { LOGFONT lf; @@ -425,7 +447,7 @@ pkcs11_listview_init(HWND parent) } /* Add column headings */ - int hdrs[] = {IDS_CERT_DISPLAYNAME, IDS_CERT_ISSUER, IDS_CERT_NOTAFTER}; + int hdrs[] = { IDS_CERT_DISPLAYNAME, IDS_CERT_ISSUER, IDS_CERT_NOTAFTER }; LVCOLUMNW lvc; lvc.mask = LVCF_TEXT | LVCF_SUBITEM; @@ -438,7 +460,7 @@ pkcs11_listview_init(HWND parent) } GetClientRect(parent, &rc); - pkcs11_listview_resize(parent, rc.right-rc.left, rc.bottom-rc.top); + pkcs11_listview_resize(parent, rc.right - rc.left, rc.bottom - rc.top); EnableWindow(lv, FALSE); /* disable until filled in */ EnableWindow(GetDlgItem(parent, IDOK), FALSE); @@ -454,13 +476,13 @@ pkcs11_listview_init(HWND parent) static void CALLBACK pkcs11_listview_fill(HWND hwnd, UINT UNUSED msg, UINT_PTR id, DWORD UNUSED now) { - connection_t *c = (connection_t *) GetProp(hwnd, cfgProp); + connection_t *c = (connection_t *)GetProp(hwnd, cfgProp); struct pkcs11_list *l = &c->pkcs11_list; HWND lv = GetDlgItem(hwnd, ID_LVW_PKCS11); - LVITEMW lvi = {0}; - lvi.mask = LVIF_TEXT|LVIF_PARAM; + LVITEMW lvi = { 0 }; + lvi.mask = LVIF_TEXT | LVIF_PARAM; if ((l->state & STATE_FILLED) == 0) { @@ -476,7 +498,7 @@ pkcs11_listview_fill(HWND hwnd, UINT UNUSED msg, UINT_PTR id, DWORD UNUSED now) lvi.iItem = i; lvi.iSubItem = 0; lvi.pszText = l->pe[i].cert.commonname; - lvi.lParam = (LPARAM) i; + lvi.lParam = (LPARAM)i; pos = ListView_InsertItem(lv, &lvi); ListView_SetItemText(lv, pos, 1, l->pe[i].cert.issuer); @@ -517,7 +539,7 @@ pkcs11_listview_fill(HWND hwnd, UINT UNUSED msg, UINT_PTR id, DWORD UNUSED now) static void pkcs11_listview_reset(HWND parent) { - connection_t *c = (connection_t *) GetProp(parent, cfgProp); + connection_t *c = (connection_t *)GetProp(parent, cfgProp); struct pkcs11_list *l = &c->pkcs11_list; HWND lv = GetDlgItem(parent, ID_LVW_PKCS11); @@ -551,12 +573,12 @@ display_certificate(HWND parent, connection_t *c, UINT i) * Remove this and corresponding check in configure.ac * when that changes. */ -#if defined(HAVE_LIBCRYPTUI) || defined (_MSC_VER) - CryptUIDlgViewContext(CERT_STORE_CERTIFICATE_CONTEXT, l->pe[i].cert.ctx, - parent, L"Certificate", 0, NULL); +#if defined(HAVE_LIBCRYPTUI) || defined(_MSC_VER) + CryptUIDlgViewContext( + CERT_STORE_CERTIFICATE_CONTEXT, l->pe[i].cert.ctx, parent, L"Certificate", 0, NULL); #else - (void) i; - (void) parent; + (void)i; + (void)parent; WriteStatusLog(c, L"GUI> ", L"Certificate display not supported in this build", false); #endif } @@ -571,7 +593,7 @@ QueryPkcs11DialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) switch (msg) { case WM_INITDIALOG: - c = (connection_t *) lParam; + c = (connection_t *)lParam; TRY_SETPROP(hwndDlg, cfgProp, (HANDLE)lParam); SetStatusWinIcon(hwndDlg, ID_ICO_APP); @@ -588,21 +610,22 @@ QueryPkcs11DialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return TRUE; case WM_COMMAND: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); if (LOWORD(wParam) == IDOK) { HWND lv = GetDlgItem(hwndDlg, ID_LVW_PKCS11); - int id = (int) ListView_GetNextItem(lv, -1, LVNI_ALL|LVNI_SELECTED); - LVITEM lvi = {.iItem = id, .mask = LVIF_PARAM}; + int id = (int)ListView_GetNextItem(lv, -1, LVNI_ALL | LVNI_SELECTED); + LVITEM lvi = { .iItem = id, .mask = LVIF_PARAM }; if (id >= 0 && ListView_GetItem(lv, &lvi)) { - c->pkcs11_list.selected = (UINT) lvi.lParam; + c->pkcs11_list.selected = (UINT)lvi.lParam; c->pkcs11_list.state |= STATE_SELECTED; } else if (c->pkcs11_list.count > 0) { /* No selection -- show an error message */ - SetDlgItemTextW(hwndDlg, ID_TXT_WARNING, LoadLocalizedString(IDS_ERR_SELECT_PKCS11)); + SetDlgItemTextW( + hwndDlg, ID_TXT_WARNING, LoadLocalizedString(IDS_ERR_SELECT_PKCS11)); return TRUE; } EndDialog(hwndDlg, wParam); @@ -626,12 +649,12 @@ QueryPkcs11DialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return TRUE; case WM_CTLCOLORSTATIC: - if (GetDlgCtrlID((HWND) lParam) == ID_TXT_WARNING) + if (GetDlgCtrlID((HWND)lParam) == ID_TXT_WARNING) { - HBRUSH br = (HBRUSH) DefWindowProc(hwndDlg, msg, wParam, lParam); + HBRUSH br = (HBRUSH)DefWindowProc(hwndDlg, msg, wParam, lParam); COLORREF clr = o.clr_warning; - SetTextColor((HDC) wParam, clr); - return (INT_PTR) br; + SetTextColor((HDC)wParam, clr); + return (INT_PTR)br; } break; @@ -641,10 +664,10 @@ QueryPkcs11DialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) return FALSE; case WM_NOTIFY: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); if (((NMHDR *)lParam)->idFrom == ID_LVW_PKCS11) { - NMITEMACTIVATE *ln = (NMITEMACTIVATE *) lParam; + NMITEMACTIVATE *ln = (NMITEMACTIVATE *)lParam; if (ln->iItem >= 0 && ln->uNewState & LVNI_SELECTED) { /* remove the no-selection warning */ @@ -652,20 +675,20 @@ QueryPkcs11DialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) } if (ln->hdr.code == NM_DBLCLK && ln->iItem >= 0) { - display_certificate(hwndDlg, c, (UINT) ln->iItem); + display_certificate(hwndDlg, c, (UINT)ln->iItem); } } break; case WM_CLOSE: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); StopOpenVPN(c); EndDialog(hwndDlg, wParam); return TRUE; case WM_NCDESTROY: RemoveProp(hwndDlg, cfgProp); - HFONT hf = (HFONT) GetProp(hwndDlg, hfontProp); + HFONT hf = (HFONT)GetProp(hwndDlg, hfontProp); if (hf) { DeleteObject(hf); diff --git a/pkcs11.h b/pkcs11.h index 001ad217a..3e68bfcdc 100644 --- a/pkcs11.h +++ b/pkcs11.h @@ -24,10 +24,10 @@ struct pkcs11_list { - unsigned int count; /* number of pkcs11 entries */ - unsigned int selected; /* entry selected by user: -1 if no selection */ - unsigned int state; /* a flag indicating list filling status */ - struct pkcs11_entry *pe; /* array of pkcs11-id entries */ + unsigned int count; /* number of pkcs11 entries */ + unsigned int selected; /* entry selected by user: -1 if no selection */ + unsigned int state; /* a flag indicating list filling status */ + struct pkcs11_entry *pe; /* array of pkcs11-id entries */ }; struct connection; diff --git a/plap/plap_common.c b/plap/plap_common.c index 87900464d..f42f06de6 100644 --- a/plap/plap_common.c +++ b/plap/plap_common.c @@ -70,7 +70,9 @@ x_dmsg(const char *file, const char *func, const wchar_t *fmt, ...) wchar_t date[30]; time_t log_time = time(NULL); struct tm *time_struct = localtime(&log_time); - _snwprintf(date, _countof(date), L"%d-%.2d-%.2d %.2d:%.2d:%.2d", + _snwprintf(date, + _countof(date), + L"%d-%.2d-%.2d %.2d:%.2d:%.2d", time_struct->tm_year + 1900, time_struct->tm_mon + 1, time_struct->tm_mday, @@ -97,7 +99,7 @@ void debug_print_guid(const GUID *riid, const wchar_t *context) { RPC_CSTR str = NULL; - if (UuidToStringA((GUID *) riid, &str) == RPC_S_OK) + if (UuidToStringA((GUID *)riid, &str) == RPC_S_OK) { x_dmsg(NULL, NULL, L"%ls %hs", context, str); RpcStringFreeA(&str); diff --git a/plap/plap_common.h b/plap/plap_common.h index 5bbe6e14c..17cfb7bad 100644 --- a/plap/plap_common.h +++ b/plap/plap_common.h @@ -26,32 +26,37 @@ #include #ifdef __GNUC__ -#define UNUSED __attribute__ ((unused)) +#define UNUSED __attribute__((unused)) #else #define UNUSED #endif #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #ifdef DEBUG -#define dmsg(fmt, ...) x_dmsg(__FILE__, __func__, fmt, ## __VA_ARGS__) +#define dmsg(fmt, ...) x_dmsg(__FILE__, __func__, fmt, ##__VA_ARGS__) #else -#define dmsg(...) do {; } while (0) +#define dmsg(...) \ + do \ + { \ + ; \ + } while (0) #endif -void x_dmsg(const char *file, const char *func, const wchar_t *fmt, ...); + void x_dmsg(const char *file, const char *func, const wchar_t *fmt, ...); -void init_debug(); + void init_debug(); -void uninit_debug(); + void uninit_debug(); -void debug_print_guid(const GUID *riid, const wchar_t *context); + void debug_print_guid(const GUID *riid, const wchar_t *context); /* Shortcuts for cumbersome calls to COM methods of an object through its v-table */ -#define ADDREF(p) (p)->lpVtbl->AddRef(p) -#define RELEASE(p) (p)->lpVtbl->Release(p) +#define ADDREF(p) (p)->lpVtbl->AddRef(p) +#define RELEASE(p) (p)->lpVtbl->Release(p) #define QUERY_INTERFACE(p, riid, ppv) (p)->lpVtbl->QueryInterface(p, riid, ppv) #ifdef __cplusplus @@ -66,6 +71,16 @@ void debug_print_guid(const GUID *riid, const wchar_t *context); * In other places this will get defined as an extern. */ #ifdef DEFINE_GUID -DEFINE_GUID(CLSID_OpenVPNProvider, 0x4fbb8b67, 0xcf02, 0x4982, 0xa7, 0xa8, - 0x3d, 0xd0, 0x6a, 0x2c, 0x2e, 0xbd); +DEFINE_GUID(CLSID_OpenVPNProvider, + 0x4fbb8b67, + 0xcf02, + 0x4982, + 0xa7, + 0xa8, + 0x3d, + 0xd0, + 0x6a, + 0x2c, + 0x2e, + 0xbd); #endif diff --git a/plap/plap_connection.c b/plap/plap_connection.c index 53c9f3a99..58fd85f7d 100644 --- a/plap/plap_connection.c +++ b/plap/plap_connection.c @@ -41,18 +41,18 @@ struct OpenVPNConnection /* "private" members */ ICredentialProviderCredentialEvents *events; /* Passed in by Logon UI for callbacks */ - connection_t *c; /* GUI connection data */ + connection_t *c; /* GUI connection data */ const wchar_t *display_name; - IQueryContinueWithStatus *qc; /* Passed in by LogonUI for checking status of connect */ - BOOL connect_cancelled; /* we set this true if user cancels the connect operation */ + IQueryContinueWithStatus *qc; /* Passed in by LogonUI for checking status of connect */ + BOOL connect_cancelled; /* we set this true if user cancels the connect operation */ LONG ref_count; }; -#define ICCPC IConnectableCredentialProviderCredential /* shorthand for a long name */ +#define ICCPC IConnectableCredentialProviderCredential /* shorthand for a long name */ -#define ISCONNECTED(c) (ConnectionState(c) == state_connected) +#define ISCONNECTED(c) (ConnectionState(c) == state_connected) #define ISDISCONNECTED(c) (ConnectionState(c) == state_disconnected) -#define ISONHOLD(c) (ConnectionState(c) == state_onhold) +#define ISONHOLD(c) (ConnectionState(c) == state_onhold) extern DWORD status_menu_id; @@ -74,7 +74,9 @@ static HRESULT WINAPI SetSelected(ICCPC *this, BOOL *auto_logon); static HRESULT WINAPI SetDeselected(ICCPC *this); -static HRESULT WINAPI GetFieldState(ICCPC *this, DWORD field, CREDENTIAL_PROVIDER_FIELD_STATE *fs, +static HRESULT WINAPI GetFieldState(ICCPC *this, + DWORD field, + CREDENTIAL_PROVIDER_FIELD_STATE *fs, CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE *fis); static HRESULT WINAPI GetStringValue(ICCPC *this, DWORD index, WCHAR **ws); @@ -87,9 +89,15 @@ static HRESULT WINAPI SetStringValue(ICCPC *this, DWORD field, const WCHAR *ws); static HRESULT WINAPI GetCheckboxValue(ICCPC *this, DWORD field, BOOL *checked, wchar_t **label); -static HRESULT WINAPI GetComboBoxValueCount(ICCPC *this, DWORD field, DWORD *items, DWORD *selected_item); +static HRESULT WINAPI GetComboBoxValueCount(ICCPC *this, + DWORD field, + DWORD *items, + DWORD *selected_item); -static HRESULT WINAPI GetComboBoxValueAt(ICCPC *this, DWORD field, DWORD item, wchar_t **item_value); +static HRESULT WINAPI GetComboBoxValueAt(ICCPC *this, + DWORD field, + DWORD item, + wchar_t **item_value); static HRESULT WINAPI SetCheckboxValue(ICCPC *this, DWORD field, BOOL checked); @@ -99,11 +107,15 @@ static HRESULT WINAPI CommandLinkClicked(ICCPC *this, DWORD field); static HRESULT WINAPI GetSerialization(ICCPC *this, CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE *response, - CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *cs, wchar_t **text, + CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *cs, + wchar_t **text, CREDENTIAL_PROVIDER_STATUS_ICON *icon); -static HRESULT WINAPI ReportResult(ICCPC *this, NTSTATUS status, NTSTATUS substatus, - wchar_t **status_text, CREDENTIAL_PROVIDER_STATUS_ICON *icon); +static HRESULT WINAPI ReportResult(ICCPC *this, + NTSTATUS status, + NTSTATUS substatus, + wchar_t **status_text, + CREDENTIAL_PROVIDER_STATUS_ICON *icon); /* IConnectableCredentialProviderCredential */ static HRESULT WINAPI Connect(ICCPC *this, IQueryContinueWithStatus *qc); @@ -146,7 +158,7 @@ OpenVPNConnection_new() OpenVPNConnection *oc = calloc(sizeof(*oc), 1); if (oc) { - oc->lpVtbl = &iccpc_vtbl; + oc->lpVtbl = &iccpc_vtbl; oc->ref_count = 1; dll_addref(); @@ -167,7 +179,7 @@ OpenVPNConnection_free(OpenVPNConnection *oc) static ULONG WINAPI AddRef(ICCPC *this) { - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; dmsg(L"Connection: ref_count after increment = %lu", oc->ref_count + 1); return InterlockedIncrement(&oc->ref_count); @@ -176,7 +188,7 @@ AddRef(ICCPC *this) static ULONG WINAPI Release(ICCPC *this) { - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; int count = InterlockedDecrement(&oc->ref_count); dmsg(L"Connection: ref_count after decrement = %lu", count); @@ -198,8 +210,7 @@ QueryInterface(ICCPC *this, REFIID riid, void **ppv) if (ppv != NULL) { - if (IsEqualIID(riid, &IID_IUnknown) - || IsEqualIID(riid, &IID_ICredentialProviderCredential) + if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_ICredentialProviderCredential) || IsEqualIID(riid, &IID_IConnectableCredentialProviderCredential)) { *ppv = this; @@ -223,15 +234,14 @@ QueryInterface(ICCPC *this, REFIID riid, void **ppv) * LogonUI calls Advise first and the passed in events may be used for * making callbacks to notify changes asynchronously */ -static HRESULT -WINAPI +static HRESULT WINAPI Advise(ICCPC *this, ICredentialProviderCredentialEvents *e) { HWND hwnd; dmsg(L"Entry"); - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; if (oc->events) { @@ -240,8 +250,7 @@ Advise(ICCPC *this, ICredentialProviderCredentialEvents *e) oc->events = e; ADDREF(e); - if (e - && e->lpVtbl->OnCreatingWindow(e, &hwnd) == S_OK) + if (e && e->lpVtbl->OnCreatingWindow(e, &hwnd) == S_OK) { dmsg(L"Setting hwnd"); SetParentWindow(hwnd); @@ -255,7 +264,7 @@ UnAdvise(ICCPC *this) { dmsg(L"Entry"); - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; if (oc->events) { @@ -273,10 +282,10 @@ static HRESULT WINAPI SetSelected(ICCPC *this, BOOL *auto_logon) { #ifdef DEBUG - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; dmsg(L"profile: %ls", oc->display_name); #else - (void) this; + (void)this; #endif /* setting true here will autoconnect the first entry and Windows will @@ -292,10 +301,10 @@ static HRESULT WINAPI SetDeselected(ICCPC *this) { #ifdef DEBUG - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; dmsg(L"profile: %ls", oc->display_name); #else - (void) this; + (void)this; #endif return S_OK; @@ -305,7 +314,8 @@ SetDeselected(ICCPC *this) * Return display states for a particular field of a tile */ static HRESULT WINAPI -GetFieldState(UNUSED ICCPC *this, DWORD field, +GetFieldState(UNUSED ICCPC *this, + DWORD field, CREDENTIAL_PROVIDER_FIELD_STATE *fs, CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE *fis) { @@ -321,7 +331,7 @@ GetFieldState(UNUSED ICCPC *this, DWORD field, } if (fis) { - *fis = (field_desc[field].cpft == CPFT_SUBMIT_BUTTON) ? CPFIS_FOCUSED : CPFIS_NONE; + *fis = (field_desc[field].cpft == CPFT_SUBMIT_BUTTON) ? CPFIS_FOCUSED : CPFIS_NONE; } hr = S_OK; } @@ -342,7 +352,7 @@ GetStringValue(ICCPC *this, DWORD index, WCHAR **ws) dmsg(L"index = %lu", index); - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; const wchar_t *val = L""; @@ -408,7 +418,7 @@ GetBitmapValue(UNUSED ICCPC *this, DWORD field, HBITMAP *bmp) * Return the index of the field the button should be placed adjacent to. */ static HRESULT WINAPI -GetSubmitButtonValue(UNUSED ICCPC *this, DWORD field, DWORD *adjacent ) +GetSubmitButtonValue(UNUSED ICCPC *this, DWORD field, DWORD *adjacent) { HRESULT hr; @@ -432,7 +442,7 @@ GetSubmitButtonValue(UNUSED ICCPC *this, DWORD field, DWORD *adjacent ) * This gets called as user types into a field. */ static HRESULT WINAPI -SetStringValue(UNUSED ICCPC *this, UNUSED DWORD field, UNUSED const WCHAR *ws ) +SetStringValue(UNUSED ICCPC *this, UNUSED DWORD field, UNUSED const WCHAR *ws) { HRESULT hr; @@ -445,15 +455,19 @@ SetStringValue(UNUSED ICCPC *this, UNUSED DWORD field, UNUSED const WCHAR *ws ) } static HRESULT WINAPI -GetCheckboxValue(UNUSED ICCPC *this, UNUSED DWORD field, - UNUSED BOOL *checked, UNUSED wchar_t **label) +GetCheckboxValue(UNUSED ICCPC *this, + UNUSED DWORD field, + UNUSED BOOL *checked, + UNUSED wchar_t **label) { dmsg(L"Entry"); return E_NOTIMPL; } static HRESULT WINAPI -GetComboBoxValueCount(UNUSED ICCPC *this, UNUSED DWORD field, UNUSED DWORD *items, +GetComboBoxValueCount(UNUSED ICCPC *this, + UNUSED DWORD field, + UNUSED DWORD *items, UNUSED DWORD *selected_item) { dmsg(L"Entry"); @@ -461,7 +475,9 @@ GetComboBoxValueCount(UNUSED ICCPC *this, UNUSED DWORD field, UNUSED DWORD *item } static HRESULT WINAPI -GetComboBoxValueAt(UNUSED ICCPC *this, UNUSED DWORD field, UNUSED DWORD item, +GetComboBoxValueAt(UNUSED ICCPC *this, + UNUSED DWORD field, + UNUSED DWORD item, UNUSED wchar_t **item_value) { dmsg(L"Entry"); @@ -497,13 +513,15 @@ CommandLinkClicked(UNUSED ICCPC *this, UNUSED DWORD field) * we got correct credentials for the Connect process or not. */ static HRESULT WINAPI -GetSerialization(ICCPC *this, CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE *response, - UNUSED CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *cs, wchar_t **text, +GetSerialization(ICCPC *this, + CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE *response, + UNUSED CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *cs, + wchar_t **text, CREDENTIAL_PROVIDER_STATUS_ICON *icon) { HRESULT hr = S_OK; - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; dmsg(L"Entry: profile <%ls>", oc->display_name); if (oc->connect_cancelled || !ISCONNECTED(oc->c)) @@ -544,8 +562,11 @@ GetSerialization(ICCPC *this, CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE *re } static HRESULT WINAPI -ReportResult(UNUSED ICCPC *this, UNUSED NTSTATUS status, UNUSED NTSTATUS substatus, - UNUSED wchar_t **status_text, UNUSED CREDENTIAL_PROVIDER_STATUS_ICON *icon) +ReportResult(UNUSED ICCPC *this, + UNUSED NTSTATUS status, + UNUSED NTSTATUS substatus, + UNUSED wchar_t **status_text, + UNUSED CREDENTIAL_PROVIDER_STATUS_ICON *icon) { dmsg(L"Entry"); return E_NOTIMPL; @@ -557,8 +578,8 @@ NotifyEvents(OpenVPNConnection *oc, const wchar_t *status) { if (oc->events) { - oc->events->lpVtbl->SetFieldString(oc->events, (ICredentialProviderCredential *) oc, - STATUS_FIELD_INDEX, status); + oc->events->lpVtbl->SetFieldString( + oc->events, (ICredentialProviderCredential *)oc, STATUS_FIELD_INDEX, status); } if (oc->qc) { @@ -571,7 +592,7 @@ ProgressCallback(HWND hwnd, UINT msg, WPARAM wParam, UNUSED LPARAM lParam, LONG_ { assert(ref_data); - OpenVPNConnection *oc = (OpenVPNConnection *) ref_data; + OpenVPNConnection *oc = (OpenVPNConnection *)ref_data; connection_t *c = oc->c; IQueryContinueWithStatus *qc = oc->qc; @@ -617,7 +638,7 @@ ProgressCallback(HWND hwnd, UINT msg, WPARAM wParam, UNUSED LPARAM lParam, LONG_ { GetConnectionStatusText(c, status, _countof(status)); NotifyEvents(oc, status); - SendMessageW(hwnd, TDM_UPDATE_ELEMENT_TEXT, TDE_CONTENT, (LPARAM) status); + SendMessageW(hwnd, TDM_UPDATE_ELEMENT_TEXT, TDE_CONTENT, (LPARAM)status); dmsg(L"Connection status <%ls>", status); } @@ -627,7 +648,7 @@ ProgressCallback(HWND hwnd, UINT msg, WPARAM wParam, UNUSED LPARAM lParam, LONG_ static HRESULT WINAPI Connect(ICCPC *this, IQueryContinueWithStatus *qc) { - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; wchar_t status[256] = L""; dmsg(L"profile: <%ls>", oc->display_name); @@ -650,7 +671,7 @@ Connect(ICCPC *this, IQueryContinueWithStatus *qc) if (!ISCONNECTED(oc->c) && !ISDISCONNECTED(oc->c)) { dmsg(L"Runninng progress dialog"); - int res = RunProgressDialog(oc->c, ProgressCallback, (LONG_PTR) oc); + int res = RunProgressDialog(oc->c, ProgressCallback, (LONG_PTR)oc); dmsg(L"Out of progress dialog with res = %d", res); if (res == IDRETRY && !ISCONNECTED(oc->c)) @@ -661,7 +682,7 @@ Connect(ICCPC *this, IQueryContinueWithStatus *qc) DisconnectHelper(oc->c); goto again; } - else if (res == IDCANCEL && !ISCONNECTED(oc->c) && !ISDISCONNECTED(oc->c)) + else if (res == IDCANCEL && !ISCONNECTED(oc->c) && !ISDISCONNECTED(oc->c)) { LoadLocalizedStringBuf(status, _countof(status), IDS_NFO_STATE_CANCELLING); NotifyEvents(oc, status); @@ -686,7 +707,7 @@ Connect(ICCPC *this, IQueryContinueWithStatus *qc) static HRESULT WINAPI Disconnect(ICCPC *this) { - OpenVPNConnection *oc = (OpenVPNConnection *) this; + OpenVPNConnection *oc = (OpenVPNConnection *)this; dmsg(L"profile <%ls>", oc->display_name); NotifyEvents(oc, LoadLocalizedString(IDS_NFO_STATE_DISCONNECTING)); @@ -710,7 +731,8 @@ OVPNConnection_Initialize(OpenVPNConnection *this, connection_t *conn, const wch return hr; } -/* Copy field descriptor -- caller will free using CoTaskMemFree, alloc using compatible allocator */ +/* Copy field descriptor -- caller will free using CoTaskMemFree, alloc using compatible allocator + */ HRESULT CopyFieldDescriptor(CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *fd_out, const CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *fd_in) diff --git a/plap/plap_connection.h b/plap/plap_connection.h index 1924445cc..9a25d78a7 100644 --- a/plap/plap_connection.h +++ b/plap/plap_connection.h @@ -31,21 +31,19 @@ * Field descriptors for the connection tiles shown to user. * array of {index, type, name, guid } -- guid unused here. */ -static const CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR field_desc[] = -{ - { 0, CPFT_TILE_IMAGE, (wchar_t *) L"Image", {0}}, - { 1, CPFT_LARGE_TEXT, (wchar_t *) L"VPN Profile", {0}}, - { 2, CPFT_SUBMIT_BUTTON, (wchar_t *) L"Connect", {0}}, - { 3, CPFT_SMALL_TEXT, (wchar_t *) L"Status", {0}}, +static const CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR field_desc[] = { + { 0, CPFT_TILE_IMAGE, (wchar_t *)L"Image", { 0 } }, + { 1, CPFT_LARGE_TEXT, (wchar_t *)L"VPN Profile", { 0 } }, + { 2, CPFT_SUBMIT_BUTTON, (wchar_t *)L"Connect", { 0 } }, + { 3, CPFT_SMALL_TEXT, (wchar_t *)L"Status", { 0 } }, }; #define STATUS_FIELD_INDEX 3 /* index to the status text in the above array */ /** Field states -- show image and name always, rest when selected */ -static const CREDENTIAL_PROVIDER_FIELD_STATE field_states[] = -{ - CPFS_DISPLAY_IN_BOTH, /* image */ - CPFS_DISPLAY_IN_BOTH, /* profile name */ +static const CREDENTIAL_PROVIDER_FIELD_STATE field_states[] = { + CPFS_DISPLAY_IN_BOTH, /* image */ + CPFS_DISPLAY_IN_BOTH, /* profile name */ CPFS_DISPLAY_IN_SELECTED_TILE, /* button */ CPFS_DISPLAY_IN_SELECTED_TILE, /* status text */ }; @@ -57,7 +55,8 @@ HRESULT CopyFieldDescriptor(CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *fd_out, typedef struct OpenVPNConnection OpenVPNConnection; HRESULT WINAPI OVPNConnection_Initialize(OpenVPNConnection *, - connection_t *conn, const wchar_t *display_name); + connection_t *conn, + const wchar_t *display_name); OpenVPNConnection *OpenVPNConnection_new(void); diff --git a/plap/plap_dll.c b/plap/plap_dll.c index 9732a219e..19e5d9f29 100644 --- a/plap/plap_dll.c +++ b/plap/plap_dll.c @@ -101,9 +101,7 @@ static IClassFactoryVtbl cf_vtbl = { .LockServer = LockServer, }; -static IClassFactory cf = { - .lpVtbl = &cf_vtbl -}; +static IClassFactory cf = { .lpVtbl = &cf_vtbl }; /* Implementation */ static ULONG WINAPI @@ -225,8 +223,8 @@ DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppv) if (IsEqualIID(&CLSID_OpenVPNProvider, rclsid)) { ADDREF(&cf); /* though we are reusing a static instance, follow the usual COM semantics */ - hr = QUERY_INTERFACE((IClassFactory *) &cf, riid, ppv); - RELEASE((IClassFactory *) &cf); + hr = QUERY_INTERFACE((IClassFactory *)&cf, riid, ppv); + RELEASE((IClassFactory *)&cf); } else { diff --git a/plap/plap_dll.h b/plap/plap_dll.h index ae6a395b7..2915b303d 100644 --- a/plap/plap_dll.h +++ b/plap/plap_dll.h @@ -29,16 +29,16 @@ extern "C" { #endif -extern HINSTANCE hinst_global; -HRESULT OpenVPNProvider_CreateInstance(REFIID riid, void **ppv); + extern HINSTANCE hinst_global; + HRESULT OpenVPNProvider_CreateInstance(REFIID riid, void **ppv); -void dll_addref(); + void dll_addref(); -void dll_release(); + void dll_release(); -STDAPI DllCanUnloadNow(); + STDAPI DllCanUnloadNow(); -STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppv); + STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppv); #ifdef __cplusplus } diff --git a/plap/plap_provider.c b/plap/plap_provider.c index 65846b30a..ebb859b67 100644 --- a/plap/plap_provider.c +++ b/plap/plap_provider.c @@ -43,7 +43,7 @@ typedef struct OpenVPNProvider OpenVPNConnection *connections[MAX_PROFILES]; LONG ref_count; -} OpenVPNProvider; +} OpenVPNProvider; /* methods we have to implement */ static HRESULT WINAPI QueryInterface(ICredentialProvider *this, REFIID riid, void **ppv); @@ -53,24 +53,31 @@ static ULONG WINAPI AddRef(ICredentialProvider *this); static ULONG WINAPI Release(ICredentialProvider *this); static HRESULT WINAPI SetUsageScenario(ICredentialProvider *this, - CREDENTIAL_PROVIDER_USAGE_SCENARIO us, DWORD flags); + CREDENTIAL_PROVIDER_USAGE_SCENARIO us, + DWORD flags); static HRESULT WINAPI SetSerialization(ICredentialProvider *this, const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION *cs); -static HRESULT WINAPI Advise(ICredentialProvider *this, ICredentialProviderEvents *e, UINT_PTR context); +static HRESULT WINAPI Advise(ICredentialProvider *this, + ICredentialProviderEvents *e, + UINT_PTR context); static HRESULT WINAPI UnAdvise(ICredentialProvider *this); static HRESULT WINAPI GetFieldDescriptorCount(ICredentialProvider *this, DWORD *count); -static HRESULT WINAPI GetFieldDescriptorAt(ICredentialProvider *this, DWORD index, +static HRESULT WINAPI GetFieldDescriptorAt(ICredentialProvider *this, + DWORD index, CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR **fd); -static HRESULT WINAPI GetCredentialCount(ICredentialProvider *this, DWORD *count, - DWORD *default_cred, BOOL *autologon_default); +static HRESULT WINAPI GetCredentialCount(ICredentialProvider *this, + DWORD *count, + DWORD *default_cred, + BOOL *autologon_default); -static HRESULT WINAPI GetCredentialAt(ICredentialProvider *this, DWORD index, +static HRESULT WINAPI GetCredentialAt(ICredentialProvider *this, + DWORD index, ICredentialProviderCredential **c); /* a helper function for generating our connection array */ @@ -78,20 +85,18 @@ static HRESULT CreateOVPNConnectionArray(OpenVPNProvider *op); /* make a static object for function table */ -#define M_(x) .x = x /* I hate typing */ -static const ICredentialProviderVtbl icp_vtbl = { - M_(QueryInterface), - M_(AddRef), - M_(Release), - M_(SetUsageScenario), - M_(SetSerialization), - M_(Advise), - M_(UnAdvise), - M_(GetFieldDescriptorCount), - M_(GetFieldDescriptorAt), - M_(GetCredentialCount), - M_(GetCredentialAt) -}; +#define M_(x) .x = x /* I hate typing */ +static const ICredentialProviderVtbl icp_vtbl = { M_(QueryInterface), + M_(AddRef), + M_(Release), + M_(SetUsageScenario), + M_(SetSerialization), + M_(Advise), + M_(UnAdvise), + M_(GetFieldDescriptorCount), + M_(GetFieldDescriptorAt), + M_(GetCredentialCount), + M_(GetCredentialAt) }; #define ICCPC IConnectableCredentialProviderCredential /* save some more typing */ @@ -124,7 +129,7 @@ OpenVPNProvider_free(OpenVPNProvider *this) { if (this->connections[i]) { - RELEASE((ICCPC *) this->connections[i]); + RELEASE((ICCPC *)this->connections[i]); } } /* Destroy GUI threads and any associated data */ @@ -139,9 +144,9 @@ OpenVPNProvider_free(OpenVPNProvider *this) static ULONG WINAPI AddRef(ICredentialProvider *this) { - OpenVPNProvider *op = (OpenVPNProvider *) this; + OpenVPNProvider *op = (OpenVPNProvider *)this; - dmsg(L"ref_count after addref = %d", op->ref_count+1); + dmsg(L"ref_count after addref = %d", op->ref_count + 1); return InterlockedIncrement(&op->ref_count); } @@ -149,7 +154,7 @@ AddRef(ICredentialProvider *this) static ULONG WINAPI Release(ICredentialProvider *this) { - OpenVPNProvider *op = (OpenVPNProvider *) this; + OpenVPNProvider *op = (OpenVPNProvider *)this; ULONG count = InterlockedDecrement(&op->ref_count); @@ -178,8 +183,7 @@ QueryInterface(ICredentialProvider *this, REFIID riid, void **ppv) dmsg(L"ppv is NULL!"); return E_POINTER; } - if (IsEqualIID(riid, &IID_IUnknown) - || IsEqualIID(riid, &IID_ICredentialProvider)) + if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_ICredentialProvider)) { *ppv = this; ADDREF(this); @@ -206,13 +210,14 @@ QueryInterface(ICredentialProvider *this, REFIID riid, void **ppv) */ static HRESULT WINAPI SetUsageScenario(ICredentialProvider *this, - CREDENTIAL_PROVIDER_USAGE_SCENARIO us, UNUSED DWORD flags) + CREDENTIAL_PROVIDER_USAGE_SCENARIO us, + UNUSED DWORD flags) { /* I think flags may be ignored for PLAP */ dmsg(L"cpus = %lu", us); - OpenVPNProvider *op = (OpenVPNProvider *) this; + OpenVPNProvider *op = (OpenVPNProvider *)this; if (us == CPUS_PLAP) { @@ -239,8 +244,7 @@ SetSerialization(UNUSED ICredentialProvider *this, * called by LogonUI to pass in events ptr -- we ignore this */ static HRESULT WINAPI -Advise(UNUSED ICredentialProvider *this, - UNUSED ICredentialProviderEvents *e, UNUSED UINT_PTR ctx) +Advise(UNUSED ICredentialProvider *this, UNUSED ICredentialProviderEvents *e, UNUSED UINT_PTR ctx) { dmsg(L"Entry"); return S_OK; @@ -278,7 +282,8 @@ GetFieldDescriptorCount(UNUSED ICredentialProvider *this, DWORD *count) * methods as the caller will use CoTaskMemFree to release memory. */ static HRESULT WINAPI -GetFieldDescriptorAt(UNUSED ICredentialProvider *this, DWORD index, +GetFieldDescriptorAt(UNUSED ICredentialProvider *this, + DWORD index, CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR **fd) { HRESULT hr = E_OUTOFMEMORY; @@ -289,8 +294,8 @@ GetFieldDescriptorAt(UNUSED ICredentialProvider *this, DWORD index, { /* LogonUI frees this using CoTaskMemFree, so we should not use malloc */ CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *tmp = - (CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *) - CoTaskMemAlloc(sizeof(CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR)); + (CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *)CoTaskMemAlloc( + sizeof(CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR)); if (tmp) { /* call our copy helper for deep copy */ @@ -320,10 +325,12 @@ GetFieldDescriptorAt(UNUSED ICredentialProvider *this, DWORD index, * for the default item. We don't want this, so set no default. */ static HRESULT WINAPI -GetCredentialCount(ICredentialProvider *this, DWORD *count, DWORD *default_cred, +GetCredentialCount(ICredentialProvider *this, + DWORD *count, + DWORD *default_cred, BOOL *autologon_default) { - OpenVPNProvider *op = (OpenVPNProvider *) this; + OpenVPNProvider *op = (OpenVPNProvider *)this; *count = op->conn_count; @@ -345,12 +352,13 @@ GetCredentialAt(ICredentialProvider *this, DWORD index, ICredentialProviderCrede dmsg(L"index = %lu", index); - OpenVPNProvider *op = (OpenVPNProvider *) this; + OpenVPNProvider *op = (OpenVPNProvider *)this; if (index < op->conn_count && ic) { - hr = QUERY_INTERFACE((ICredentialProviderCredential *) op->connections[index], - &IID_ICredentialProviderCredential, (void **)ic); + hr = QUERY_INTERFACE((ICredentialProviderCredential *)op->connections[index], + &IID_ICredentialProviderCredential, + (void **)ic); /* In our case the same as *ic = op->connections[index], but the above is standard COM way * which checks the IID and increments ref-count as well */ } @@ -380,7 +388,7 @@ CreateOVPNConnectionArray(OpenVPNProvider *op) /* delete previous connections if any */ for (size_t i = 0; i < op->conn_count; i++) { - RELEASE((ICCPC *) op->connections[i]); + RELEASE((ICCPC *)op->connections[i]); } op->conn_count = 0; @@ -410,7 +418,7 @@ CreateOVPNConnectionArray(OpenVPNProvider *op) } else { - RELEASE((ICCPC *) oc); + RELEASE((ICCPC *)oc); } } else @@ -438,8 +446,8 @@ OpenVPNProvider_CreateInstance(REFIID riid, void **ppv) OpenVPNProvider *p = OpenVPNProvider_new(); if (p) { - hr = QUERY_INTERFACE((ICredentialProvider *) p, riid, ppv); - RELEASE((ICredentialProvider *) p); + hr = QUERY_INTERFACE((ICredentialProvider *)p, riid, ppv); + RELEASE((ICredentialProvider *)p); } else { diff --git a/plap/resource.h b/plap/resource.h index ef811a11d..c05778124 100644 --- a/plap/resource.h +++ b/plap/resource.h @@ -1 +1 @@ -#define IDB_TILE_IMAGE 101 +#define IDB_TILE_IMAGE 101 diff --git a/plap/stub.c b/plap/stub.c index cad373c8c..02f425da2 100644 --- a/plap/stub.c +++ b/plap/stub.c @@ -42,8 +42,11 @@ ErrorExit(UNUSED int exit_code, const wchar_t *msg) { if (msg) { - MessageBoxExW(NULL, msg, TEXT(PACKAGE_NAME), - MB_OK | MB_SETFOREGROUND|MB_ICONERROR, GetGUILanguage()); + MessageBoxExW(NULL, + msg, + TEXT(PACKAGE_NAME), + MB_OK | MB_SETFOREGROUND | MB_ICONERROR, + GetGUILanguage()); } DetachAllOpenVPN(); /* do not exit */ diff --git a/plap/ui_glue.c b/plap/ui_glue.c index 9496b90ef..df0344798 100644 --- a/plap/ui_glue.c +++ b/plap/ui_glue.c @@ -19,7 +19,7 @@ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -#if !defined (UNICODE) +#if !defined(UNICODE) #error UNICODE and _UNICODE must be defined. This version only supports unicode builds. #endif @@ -45,8 +45,7 @@ /* Global options structure */ options_t o; -int state_connected = connected, state_disconnected = disconnected, - state_onhold = onhold; +int state_connected = connected, state_disconnected = disconnected, state_onhold = onhold; static connection_t *active_profile; DWORD status_menu_id = IDM_STATUSMENU; @@ -167,12 +166,11 @@ InitializeUI(HINSTANCE hinstance) WSADATA wsaData; /* a session local semaphore to detect second instance */ - HANDLE session_semaphore = InitSemaphore(L"Local\\"PACKAGE_NAME "-PLAP"); + HANDLE session_semaphore = InitSemaphore(L"Local\\" PACKAGE_NAME "-PLAP"); srand(time(NULL)); /* try to lock the semaphore, else we are not the first instance */ - if (session_semaphore - && WaitForSingleObject(session_semaphore, 200) != WAIT_OBJECT_0) + if (session_semaphore && WaitForSingleObject(session_semaphore, 200) != WAIT_OBJECT_0) { if (hinstance == o.hInstance) { @@ -181,7 +179,9 @@ InitializeUI(HINSTANCE hinstance) } else { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"InitializeUI called a second time with a different hinstance -- multiple instances of the UI not supported."); + MsgToEventLog( + EVENTLOG_ERROR_TYPE, + L"InitializeUI called a second time with a different hinstance -- multiple instances of the UI not supported."); return 1; } } @@ -201,22 +201,13 @@ InitializeUI(HINSTANCE hinstance) /* Initialize handlers for management interface notifications * Some handlers are replaced by local functions */ - mgmt_rtmsg_handler handler[] = { - { ready_, OnReady }, - { hold_, OnHold }, - { log_, OnLogLine }, - { state_, OnStateChange_ }, - { password_, OnPassword_ }, - { proxy_, OnProxy_ }, - { stop_, OnStop_ }, - { needok_, OnNeedOk_ }, - { needstr_, OnNeedStr_ }, - { echo_, OnEcho }, - { bytecount_, OnByteCount }, - { infomsg_, OnInfoMsg_ }, - { timeout_, OnTimeout }, - { 0, NULL} - }; + mgmt_rtmsg_handler handler[] = { { ready_, OnReady }, { hold_, OnHold }, + { log_, OnLogLine }, { state_, OnStateChange_ }, + { password_, OnPassword_ }, { proxy_, OnProxy_ }, + { stop_, OnStop_ }, { needok_, OnNeedOk_ }, + { needstr_, OnNeedStr_ }, { echo_, OnEcho }, + { bytecount_, OnByteCount }, { infomsg_, OnInfoMsg_ }, + { timeout_, OnTimeout }, { 0, NULL } }; InitManagement(handler); dmsg(L"Init Management done"); @@ -294,8 +285,7 @@ FindPLAPConnections(connection_t *conn[], size_t max_count) DWORD count = 0; for (connection_t *c = o.chead; c && count < max_count; c = c->next) { - if (!(c->flags & FLAG_DAEMON_PERSISTENT) - || !ParseManagementAddress(c)) + if (!(c->flags & FLAG_DAEMON_PERSISTENT) || !ParseManagementAddress(c)) { continue; } @@ -315,8 +305,8 @@ WaitOnThread(connection_t *c, DWORD timeout) } DWORD exit_code; - if (WaitForSingleObject(h, timeout) == WAIT_OBJECT_0 - && GetExitCodeThread(h, &exit_code) && exit_code != STILL_ACTIVE) + if (WaitForSingleObject(h, timeout) == WAIT_OBJECT_0 && GetExitCodeThread(h, &exit_code) + && exit_code != STILL_ACTIVE) { dmsg(L"Connection thread closed"); goto out; @@ -507,7 +497,8 @@ RunProgressDialog(connection_t *c, PFTASKDIALOGCALLBACK cb_fn, LONG_PTR cb_data) { dmsg(L"Entry with profile = <%ls>", c->config_name); - TASKDIALOG_FLAGS flags = TDF_SHOW_MARQUEE_PROGRESS_BAR|TDF_CALLBACK_TIMER|TDF_USE_HICON_MAIN; + TASKDIALOG_FLAGS flags = + TDF_SHOW_MARQUEE_PROGRESS_BAR | TDF_CALLBACK_TIMER | TDF_USE_HICON_MAIN; wchar_t main_text[256]; wchar_t details_btn_text[256]; @@ -519,7 +510,7 @@ RunProgressDialog(connection_t *c, PFTASKDIALOGCALLBACK cb_fn, LONG_PTR cb_data) LoadLocalizedStringBuf(details_btn_text, _countof(details_btn_text), IDS_MENU_STATUS); const TASKDIALOG_BUTTON extra_buttons[] = { - {status_menu_id, details_btn_text}, + { status_menu_id, details_btn_text }, }; const TASKDIALOGCONFIG taskcfg = { @@ -530,8 +521,8 @@ RunProgressDialog(connection_t *c, PFTASKDIALOGCALLBACK cb_fn, LONG_PTR cb_data) .hMainIcon = LoadLocalizedIcon(ID_ICO_APP), .cButtons = _countof(extra_buttons), .pButtons = extra_buttons, - .dwCommonButtons = TDCBF_CANCEL_BUTTON|TDCBF_RETRY_BUTTON, - .pszWindowTitle = L""PACKAGE_NAME " PLAP", + .dwCommonButtons = TDCBF_CANCEL_BUTTON | TDCBF_RETRY_BUTTON, + .pszWindowTitle = L"" PACKAGE_NAME " PLAP", .pszMainInstruction = main_text, .pszContent = L"Starting", /* updated in progress callback */ .pfCallback = cb_fn, diff --git a/plap/ui_glue.h b/plap/ui_glue.h index 291aa1261..7802c0242 100644 --- a/plap/ui_glue.h +++ b/plap/ui_glue.h @@ -23,98 +23,99 @@ #define UI_LINK_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -#include /* suppress warning about order of includes */ +#include /* suppress warning about order of includes */ #include -typedef struct connection connection_t; -/* access to GUI states without exposing the options header */ -extern int state_connected, state_disconnected, state_onhold; - -/** - * Initialize GUI data structures - * @param hinstance of the calling process/dll context - * @return 0 on success > 0 on error - */ -DWORD InitializeUI(HINSTANCE hinstance); - -/** - * Close threads, cleanup resources created by Initialize - */ -void DeleteUI(void); - -/** - * Enumerate PLAP enabled connection profiles. - * - * @param conn[] On output this contains an array of connection_t - * structs for PLAP enabled profiles - * @param max_count size of conn[] array on input - * @returns the number of connection profiles found. - */ -DWORD FindPLAPConnections(connection_t *conn[], size_t max_count); - -/** - * Display name of a connection profile. - * - * @param c connection_t struct for the profile (input) - * @returns a constant wide char string - */ -const wchar_t *ConfigDisplayName(connection_t *c); - -/** - * State of a connection - */ -int ConnectionState(connection_t *c); - -/** - * Textual description of current connection state - * - * @param status On input must have space of at least len wide characters - * On output contains the NUL-terminated status text - * @param len Capacity of memory pointed to by status - */ -void GetConnectionStatusText(connection_t *c, WCHAR *status, DWORD len); - -/** - * Set hwnd as the parent window handle for dialogs - */ -void SetParentWindow(HWND hwnd); - -void DetachAllOpenVPN(); - -/** - * Enable/Disable display of status Window for connection c - */ -void ShowStatusWindow(connection_t *c, BOOL show); - -/** - * Start or Release OpenVPN connection for c - * The connection is completed asynchronously. - */ -void ConnectHelper(connection_t *c); - -/** - * Stop OpenVPN connection for c - * After initiating a disconnection, this polls for the connection status - * and waits for the disconnection to complete for a max of 5 seconds. - */ -void DisconnectHelper(connection_t *c); - -/** - * Set c as the currently active profile selected for user interaction - * UI dialogs are suppressed for non-active profiles - */ -void SetActiveProfile(connection_t *c); - -/** - * A helper function to run a dialog showing progress of a connection process. - * - * @param c Connection to monitor - * @param cb_fn A callback function that is called back every 200 msec - * @param cb_data Data passed to the callback function - */ -int RunProgressDialog(connection_t *c, PFTASKDIALOGCALLBACK cb_fn, LONG_PTR cb_data); + typedef struct connection connection_t; + /* access to GUI states without exposing the options header */ + extern int state_connected, state_disconnected, state_onhold; + + /** + * Initialize GUI data structures + * @param hinstance of the calling process/dll context + * @return 0 on success > 0 on error + */ + DWORD InitializeUI(HINSTANCE hinstance); + + /** + * Close threads, cleanup resources created by Initialize + */ + void DeleteUI(void); + + /** + * Enumerate PLAP enabled connection profiles. + * + * @param conn[] On output this contains an array of connection_t + * structs for PLAP enabled profiles + * @param max_count size of conn[] array on input + * @returns the number of connection profiles found. + */ + DWORD FindPLAPConnections(connection_t *conn[], size_t max_count); + + /** + * Display name of a connection profile. + * + * @param c connection_t struct for the profile (input) + * @returns a constant wide char string + */ + const wchar_t *ConfigDisplayName(connection_t *c); + + /** + * State of a connection + */ + int ConnectionState(connection_t *c); + + /** + * Textual description of current connection state + * + * @param status On input must have space of at least len wide characters + * On output contains the NUL-terminated status text + * @param len Capacity of memory pointed to by status + */ + void GetConnectionStatusText(connection_t *c, WCHAR *status, DWORD len); + + /** + * Set hwnd as the parent window handle for dialogs + */ + void SetParentWindow(HWND hwnd); + + void DetachAllOpenVPN(); + + /** + * Enable/Disable display of status Window for connection c + */ + void ShowStatusWindow(connection_t *c, BOOL show); + + /** + * Start or Release OpenVPN connection for c + * The connection is completed asynchronously. + */ + void ConnectHelper(connection_t *c); + + /** + * Stop OpenVPN connection for c + * After initiating a disconnection, this polls for the connection status + * and waits for the disconnection to complete for a max of 5 seconds. + */ + void DisconnectHelper(connection_t *c); + + /** + * Set c as the currently active profile selected for user interaction + * UI dialogs are suppressed for non-active profiles + */ + void SetActiveProfile(connection_t *c); + + /** + * A helper function to run a dialog showing progress of a connection process. + * + * @param c Connection to monitor + * @param cb_fn A callback function that is called back every 200 msec + * @param cb_data Data passed to the callback function + */ + int RunProgressDialog(connection_t *c, PFTASKDIALOGCALLBACK cb_fn, LONG_PTR cb_data); #ifdef __cplusplus } diff --git a/proxy.c b/proxy.c index b71ea3e6e..255c5f6ff 100644 --- a/proxy.c +++ b/proxy.c @@ -56,8 +56,8 @@ ProxySettingsDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, UNUSED LPARAM lPa hIcon = LoadLocalizedIcon(ID_ICO_APP); if (hIcon) { - SendMessage(hwndDlg, WM_SETICON, (WPARAM) (ICON_SMALL), (LPARAM) (hIcon)); - SendMessage(hwndDlg, WM_SETICON, (WPARAM) (ICON_BIG), (LPARAM) (hIcon)); + SendMessage(hwndDlg, WM_SETICON, (WPARAM)(ICON_SMALL), (LPARAM)(hIcon)); + SendMessage(hwndDlg, WM_SETICON, (WPARAM)(ICON_BIG), (LPARAM)(hIcon)); } /* Limit Port editbox to 5 chars. */ @@ -124,13 +124,14 @@ ProxySettingsDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, UNUSED LPARAM lPa break; case WM_NOTIFY: - psn = (LPPSHNOTIFY) lParam; - if (psn->hdr.code == (UINT) PSN_KILLACTIVE) + psn = (LPPSHNOTIFY)lParam; + if (psn->hdr.code == (UINT)PSN_KILLACTIVE) { - SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (CheckProxySettings(hwndDlg) ? FALSE : TRUE)); + SetWindowLongPtr( + hwndDlg, DWLP_MSGRESULT, (CheckProxySettings(hwndDlg) ? FALSE : TRUE)); return TRUE; } - else if (psn->hdr.code == (UINT) PSN_APPLY) + else if (psn->hdr.code == (UINT)PSN_APPLY) { SaveProxySettings(hwndDlg); SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, PSNRET_NOERROR); @@ -175,7 +176,8 @@ CheckProxySettings(HWND hwndDlg) if ((port < 1) || (port > 65535)) { /* proxy port range error */ - ShowLocalizedMsg((http ? IDS_ERR_HTTP_PROXY_PORT_RANGE : IDS_ERR_SOCKS_PROXY_PORT_RANGE)); + ShowLocalizedMsg( + (http ? IDS_ERR_HTTP_PROXY_PORT_RANGE : IDS_ERR_SOCKS_PROXY_PORT_RANGE)); return 0; } } @@ -249,26 +251,33 @@ SaveProxySettings(HWND hwndDlg) o.proxy_type = http; proxy_type_string[0] = _T('0'); - GetDlgItemText(hwndDlg, ID_EDT_PROXY_ADDRESS, o.proxy_http_address, - _countof(o.proxy_http_address)); - GetDlgItemText(hwndDlg, ID_EDT_PROXY_PORT, o.proxy_http_port, - _countof(o.proxy_http_port)); + GetDlgItemText( + hwndDlg, ID_EDT_PROXY_ADDRESS, o.proxy_http_address, _countof(o.proxy_http_address)); + GetDlgItemText(hwndDlg, ID_EDT_PROXY_PORT, o.proxy_http_port, _countof(o.proxy_http_port)); } else { o.proxy_type = socks; proxy_type_string[0] = _T('1'); - GetDlgItemText(hwndDlg, ID_EDT_PROXY_ADDRESS, o.proxy_socks_address, - _countof(o.proxy_socks_address)); - GetDlgItemText(hwndDlg, ID_EDT_PROXY_PORT, o.proxy_socks_port, - _countof(o.proxy_socks_port)); + GetDlgItemText( + hwndDlg, ID_EDT_PROXY_ADDRESS, o.proxy_socks_address, _countof(o.proxy_socks_address)); + GetDlgItemText( + hwndDlg, ID_EDT_PROXY_PORT, o.proxy_socks_port, _countof(o.proxy_socks_port)); } /* Open Registry for writing */ _sntprintf_0(proxy_subkey, _T("%ls\\proxy"), GUI_REGKEY_HKCU); - if (RegCreateKeyEx(HKEY_CURRENT_USER, proxy_subkey, 0, _T(""), REG_OPTION_NON_VOLATILE, - KEY_WRITE, NULL, ®key, &dwDispos) != ERROR_SUCCESS) + if (RegCreateKeyEx(HKEY_CURRENT_USER, + proxy_subkey, + 0, + _T(""), + REG_OPTION_NON_VOLATILE, + KEY_WRITE, + NULL, + ®key, + &dwDispos) + != ERROR_SUCCESS) { /* error creating Registry-Key */ ShowLocalizedMsg(IDS_ERR_CREATE_REG_HKCU_KEY, proxy_subkey); @@ -305,11 +314,15 @@ GetProxyRegistrySettings() } /* get registry settings */ - GetRegistryValue(regkey, _T("proxy_http_address"), o.proxy_http_address, _countof(o.proxy_http_address)); + GetRegistryValue( + regkey, _T("proxy_http_address"), o.proxy_http_address, _countof(o.proxy_http_address)); GetRegistryValue(regkey, _T("proxy_http_port"), o.proxy_http_port, _countof(o.proxy_http_port)); - GetRegistryValue(regkey, _T("proxy_socks_address"), o.proxy_socks_address, _countof(o.proxy_socks_address)); - GetRegistryValue(regkey, _T("proxy_socks_port"), o.proxy_socks_port, _countof(o.proxy_socks_port)); - GetRegistryValue(regkey, _T("proxy_source"), proxy_source_string, _countof(proxy_source_string)); + GetRegistryValue( + regkey, _T("proxy_socks_address"), o.proxy_socks_address, _countof(o.proxy_socks_address)); + GetRegistryValue( + regkey, _T("proxy_socks_port"), o.proxy_socks_port, _countof(o.proxy_socks_port)); + GetRegistryValue( + regkey, _T("proxy_source"), proxy_source_string, _countof(proxy_source_string)); GetRegistryValue(regkey, _T("proxy_type"), proxy_type_string, _countof(proxy_type_string)); if (proxy_source_string[0] == _T('0')) @@ -342,8 +355,8 @@ ProxyAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { case WM_INITDIALOG: /* Set connection for this dialog and show it */ - c = (connection_t *) lParam; - TRY_SETPROP(hwndDlg, cfgProp, (HANDLE) c); + c = (connection_t *)lParam; + TRY_SETPROP(hwndDlg, cfgProp, (HANDLE)c); if (c->state == resuming) { ForceForegroundWindow(hwndDlg); @@ -360,13 +373,13 @@ ProxyAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) case ID_EDT_PROXY_USER: if (HIWORD(wParam) == EN_UPDATE) { - int len = Edit_GetTextLength((HWND) lParam); + int len = Edit_GetTextLength((HWND)lParam); EnableWindow(GetDlgItem(hwndDlg, IDOK), (len ? TRUE : FALSE)); } break; case IDOK: - c = (connection_t *) GetProp(hwndDlg, cfgProp); + c = (connection_t *)GetProp(hwndDlg, cfgProp); proxy_type = (c->proxy_type == http ? "HTTP" : "SOCKS"); snprintf(fmt, sizeof(fmt), "username \"%s Proxy\" \"%%s\"", proxy_type); @@ -400,11 +413,15 @@ void QueryProxyAuth(connection_t *c, proxy_t type) { c->proxy_type = type; - LocalizedDialogBoxParamEx(ID_DLG_PROXY_AUTH, c->hwndStatus, ProxyAuthDialogFunc, (LPARAM) c); + LocalizedDialogBoxParamEx(ID_DLG_PROXY_AUTH, c->hwndStatus, ProxyAuthDialogFunc, (LPARAM)c); } -typedef enum { HTTPS_URL, SOCKS_URL } url_scheme; +typedef enum +{ + HTTPS_URL, + SOCKS_URL +} url_scheme; static LPCWSTR UrlSchemeStr(const url_scheme scheme) { @@ -441,8 +458,8 @@ QueryWindowsProxySettings(const url_scheme scheme, LPCSTR host) if (auto_config_url) { - HINTERNET session = WinHttpOpen(NULL, WINHTTP_ACCESS_TYPE_NO_PROXY, - WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + HINTERNET session = WinHttpOpen( + NULL, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (session) { int size = _snwprintf(NULL, 0, L"%ls://%hs", UrlSchemeStr(scheme), host) + 1; @@ -453,14 +470,12 @@ QueryWindowsProxySettings(const url_scheme scheme, LPCSTR host) LPWSTR old_proxy = proxy; WINHTTP_PROXY_INFO proxy_info; - WINHTTP_AUTOPROXY_OPTIONS options = { - .fAutoLogonIfChallenged = TRUE, - .dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL, - .lpszAutoConfigUrl = auto_config_url, - .dwAutoDetectFlags = 0, - .lpvReserved = NULL, - .dwReserved = 0 - }; + WINHTTP_AUTOPROXY_OPTIONS options = { .fAutoLogonIfChallenged = TRUE, + .dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL, + .lpszAutoConfigUrl = auto_config_url, + .dwAutoDetectFlags = 0, + .lpvReserved = NULL, + .dwReserved = 0 }; if (WinHttpGetProxyForUrl(session, url, &options, &proxy_info)) { @@ -480,8 +495,7 @@ QueryWindowsProxySettings(const url_scheme scheme, LPCSTR host) static VOID -ParseProxyString(LPWSTR proxy_str, url_scheme scheme, - LPCSTR *type, LPCWSTR *host, LPCWSTR *port) +ParseProxyString(LPWSTR proxy_str, url_scheme scheme, LPCSTR *type, LPCWSTR *host, LPCWSTR *port) { if (proxy_str == NULL) { diff --git a/registry.c b/registry.c index cc133e4aa..eccd2c2d5 100644 --- a/registry.c +++ b/registry.c @@ -37,39 +37,39 @@ extern options_t o; -struct regkey_str { +struct regkey_str +{ const WCHAR *name; WCHAR *var; int len; const WCHAR *value; } regkey_str[] = { - {L"config_dir", o.config_dir, _countof(o.config_dir), L"%USERPROFILE%\\OpenVPN\\config"}, - {L"config_ext", o.ext_string, _countof(o.ext_string), L"ovpn"}, - {L"log_dir", o.log_dir, _countof(o.log_dir), L"%USERPROFILE%\\OpenVPN\\log"} + { L"config_dir", o.config_dir, _countof(o.config_dir), L"%USERPROFILE%\\OpenVPN\\config" }, + { L"config_ext", o.ext_string, _countof(o.ext_string), L"ovpn" }, + { L"log_dir", o.log_dir, _countof(o.log_dir), L"%USERPROFILE%\\OpenVPN\\log" } }; -struct regkey_int { +struct regkey_int +{ const WCHAR *name; DWORD *var; DWORD value; -} regkey_int[] = { - {L"log_append", &o.log_append, 0}, - {L"iservice_admin", &o.iservice_admin, 1}, - {L"show_balloon", &o.show_balloon, 1}, - {L"silent_connection", &o.silent_connection, 0}, - {L"preconnectscript_timeout", &o.preconnectscript_timeout, 10}, - {L"connectscript_timeout", &o.connectscript_timeout, 30}, - {L"disconnectscript_timeout", &o.disconnectscript_timeout, 10}, - {L"show_script_window", &o.show_script_window, 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}, - {L"management_port_offset", &o.mgmt_port_offset, 25340}, - {L"enable_peristent_connections", &o.enable_persistent, 2}, - {L"enable_auto_restart", &o.enable_auto_restart, 1}, - {L"auth_pass_concat_otp", &o.auth_pass_concat_otp, 0}, - {L"ovpn_engine", &o.ovpn_engine, OPENVPN_ENGINE_OVPN2} -}; +} regkey_int[] = { { L"log_append", &o.log_append, 0 }, + { L"iservice_admin", &o.iservice_admin, 1 }, + { L"show_balloon", &o.show_balloon, 1 }, + { L"silent_connection", &o.silent_connection, 0 }, + { L"preconnectscript_timeout", &o.preconnectscript_timeout, 10 }, + { L"connectscript_timeout", &o.connectscript_timeout, 30 }, + { L"disconnectscript_timeout", &o.disconnectscript_timeout, 10 }, + { L"show_script_window", &o.show_script_window, 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 }, + { L"management_port_offset", &o.mgmt_port_offset, 25340 }, + { L"enable_peristent_connections", &o.enable_persistent, 2 }, + { L"enable_auto_restart", &o.enable_auto_restart, 1 }, + { L"auth_pass_concat_otp", &o.auth_pass_concat_otp, 0 }, + { L"ovpn_engine", &o.ovpn_engine, OPENVPN_ENGINE_OVPN2 } }; static int RegValueExists(HKEY regkey, const WCHAR *name) @@ -120,27 +120,34 @@ GetGlobalRegistryKeys() } /* an admin-defined global config dir defined in HKLM\OpenVPN\config_dir */ - if (!regkey || !GetRegistryValue(regkey, _T("config_dir"), o.global_config_dir, _countof(o.global_config_dir))) + if (!regkey + || !GetRegistryValue( + regkey, _T("config_dir"), o.global_config_dir, _countof(o.global_config_dir))) { /* use default = openvpnpath\config */ _sntprintf_0(o.global_config_dir, _T("%lsconfig"), o.install_path); } - if (!regkey || !GetRegistryValue(regkey, _T("autostart_config_dir"), o.config_auto_dir, _countof(o.config_auto_dir))) + if (!regkey + || !GetRegistryValue( + regkey, _T("autostart_config_dir"), o.config_auto_dir, _countof(o.config_auto_dir))) { /* use default = openvpnpath\config-auto */ _sntprintf_0(o.config_auto_dir, L"%lsconfig-auto", o.install_path); } - if (!regkey || !GetRegistryValue(regkey, _T("log_dir"), o.global_log_dir, _countof(o.global_log_dir))) + if (!regkey + || !GetRegistryValue(regkey, _T("log_dir"), o.global_log_dir, _countof(o.global_log_dir))) { /* use default = openvpnpath\log */ _sntprintf_0(o.global_log_dir, L"%lslog", o.install_path); } - if (!regkey || !GetRegistryValue(regkey, _T("ovpn_admin_group"), o.ovpn_admin_group, _countof(o.ovpn_admin_group))) + if (!regkey + || !GetRegistryValue( + regkey, _T("ovpn_admin_group"), o.ovpn_admin_group, _countof(o.ovpn_admin_group))) { - _tcsncpy(o.ovpn_admin_group, OVPN_ADMIN_GROUP, _countof(o.ovpn_admin_group)-1); + _tcsncpy(o.ovpn_admin_group, OVPN_ADMIN_GROUP, _countof(o.ovpn_admin_group) - 1); } if (!regkey || !GetRegistryValue(regkey, _T("exe_path"), o.exe_path, _countof(o.exe_path))) @@ -148,11 +155,15 @@ GetGlobalRegistryKeys() _sntprintf_0(o.exe_path, _T("%lsbin\\openvpn.exe"), o.install_path); } - if (!regkey || !GetRegistryValue(regkey, _T("priority"), o.priority_string, _countof(o.priority_string))) + if (!regkey + || !GetRegistryValue( + regkey, _T("priority"), o.priority_string, _countof(o.priority_string))) { - _tcsncpy(o.priority_string, _T("NORMAL_PRIORITY_CLASS"), _countof(o.priority_string)-1); + _tcsncpy(o.priority_string, _T("NORMAL_PRIORITY_CLASS"), _countof(o.priority_string) - 1); } - if (!regkey || !GetRegistryValueNumeric(regkey, _T("disable_save_passwords"), &o.disable_save_passwords)) + if (!regkey + || !GetRegistryValueNumeric( + regkey, _T("disable_save_passwords"), &o.disable_save_passwords)) { o.disable_save_passwords = 0; } @@ -177,14 +188,14 @@ GetRegistryKeys() status = RegOpenKeyEx(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, 0, KEY_READ, ®key); - for (i = 0; i < (int) _countof(regkey_str); ++i) + for (i = 0; i < (int)_countof(regkey_str); ++i) { if (status != ERROR_SUCCESS || !GetRegistryValue(regkey, regkey_str[i].name, regkey_str[i].var, regkey_str[i].len)) { /* no value found in registry, use the default */ wcsncpy(regkey_str[i].var, regkey_str[i].value, regkey_str[i].len); - regkey_str[i].var[regkey_str[i].len-1] = L'\0'; + regkey_str[i].var[regkey_str[i].len - 1] = L'\0'; PrintDebug(L"default: %ls = %ls", regkey_str[i].name, regkey_str[i].var); } else @@ -193,7 +204,7 @@ GetRegistryKeys() } } - for (i = 0; i < (int) _countof(regkey_int); ++i) + for (i = 0; i < (int)_countof(regkey_int); ++i) { if (status != ERROR_SUCCESS || !GetRegistryValueNumeric(regkey, regkey_int[i].name, regkey_int[i].var)) @@ -229,7 +240,8 @@ GetRegistryKeys() } /* Read group policy setting for password reveal */ - status = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Policies\\Microsoft\\Windows\\CredUI", 0, KEY_READ, ®key); + status = RegOpenKeyExW( + HKEY_CURRENT_USER, L"Software\\Policies\\Microsoft\\Windows\\CredUI", 0, KEY_READ, ®key); if (status != ERROR_SUCCESS || !GetRegistryValueNumeric(regkey, L"DisablePasswordReveal", &o.disable_password_reveal)) { @@ -257,18 +269,25 @@ SaveRegistryKeys() int i; int ret = false; - status = RegCreateKeyEx(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, 0, NULL, REG_OPTION_NON_VOLATILE, - KEY_WRITE|KEY_READ, NULL, ®key, NULL); + status = RegCreateKeyEx(HKEY_CURRENT_USER, + GUI_REGKEY_HKCU, + 0, + NULL, + REG_OPTION_NON_VOLATILE, + KEY_WRITE | KEY_READ, + NULL, + ®key, + NULL); if (status != ERROR_SUCCESS) { ShowLocalizedMsg(IDS_ERR_CREATE_REG_HKCU_KEY, GUI_REGKEY_HKCU); goto out; } - for (i = 0; i < (int) _countof(regkey_str); ++i) + for (i = 0; i < (int)_countof(regkey_str); ++i) { /* save only if the value differs from default or already present in registry */ if (CompareStringExpanded(regkey_str[i].var, regkey_str[i].value) != 0 - || RegValueExists(regkey, regkey_str[i].name) ) + || RegValueExists(regkey, regkey_str[i].name)) { if (!SetRegistryValue(regkey, regkey_str[i].name, regkey_str[i].var)) { @@ -277,10 +296,9 @@ SaveRegistryKeys() } } - for (i = 0; i < (int) _countof(regkey_int); ++i) + for (i = 0; i < (int)_countof(regkey_int); ++i) { - if (*regkey_int[i].var != regkey_int[i].value - || RegValueExists(regkey, regkey_int[i].name) ) + if (*regkey_int[i].var != regkey_int[i].value || RegValueExists(regkey, regkey_int[i].name)) { if (!SetRegistryValueNumeric(regkey, regkey_int[i].name, *regkey_int[i].var)) { @@ -325,11 +343,19 @@ SetRegistryVersion(const version_t *v) DWORD status; BOOL ret = false; - status = RegCreateKeyEx(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, 0, NULL, REG_OPTION_NON_VOLATILE, - KEY_WRITE, NULL, ®key, NULL); + status = RegCreateKeyEx(HKEY_CURRENT_USER, + GUI_REGKEY_HKCU, + 0, + NULL, + REG_OPTION_NON_VOLATILE, + KEY_WRITE, + NULL, + ®key, + NULL); if (status == ERROR_SUCCESS) { - if (RegSetValueEx(regkey, L"version", 0, REG_BINARY, (const BYTE *) v, sizeof(*v)) == ERROR_SUCCESS) + if (RegSetValueEx(regkey, L"version", 0, REG_BINARY, (const BYTE *)v, sizeof(*v)) + == ERROR_SUCCESS) { ret = true; } @@ -349,15 +375,21 @@ MigrateNilingsKeys() BOOL ret = false; HKEY regkey, regkey_proxy, regkey_nilings; - status = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Nilings\\OpenVPN-GUI", 0, - KEY_READ, ®key_nilings); + status = RegOpenKeyEx( + HKEY_CURRENT_USER, L"Software\\Nilings\\OpenVPN-GUI", 0, KEY_READ, ®key_nilings); if (status != ERROR_SUCCESS) { return true; /* No old keys to migrate */ - } - status = RegCreateKeyEx(HKEY_CURRENT_USER, GUI_REGKEY_HKCU, 0, NULL, REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, NULL, ®key, NULL); + status = RegCreateKeyEx(HKEY_CURRENT_USER, + GUI_REGKEY_HKCU, + 0, + NULL, + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + NULL, + ®key, + NULL); if (status != ERROR_SUCCESS) { ShowLocalizedMsg(IDS_ERR_CREATE_REG_HKCU_KEY, GUI_REGKEY_HKCU); @@ -366,8 +398,15 @@ MigrateNilingsKeys() } /* For some reason this needs ALL_ACCESS for the CopyTree below to work */ - status = RegCreateKeyEx(regkey, L"proxy", 0, NULL, REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, NULL, ®key_proxy, NULL); + status = RegCreateKeyEx(regkey, + L"proxy", + 0, + NULL, + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + NULL, + ®key_proxy, + NULL); if (status == ERROR_SUCCESS) { DWORD ui_lang; @@ -380,7 +419,7 @@ MigrateNilingsKeys() status = RegCopyTree(regkey_nilings, NULL, regkey_proxy); if (status == ERROR_SUCCESS) { - RegDeleteValue(regkey_proxy, L"ui_language"); /* in case copied here */ + RegDeleteValue(regkey_proxy, L"ui_language"); /* in case copied here */ ret = true; } RegCloseKey(regkey_proxy); @@ -412,7 +451,7 @@ UpdateRegistry(void) { case 0: /* Cleanup GUI_REGKEY_HKCU and migrate any values under Nilings */ - RegDeleteTree(HKEY_CURRENT_USER, GUI_REGKEY_HKCU); /* delete all values and subkeys */ + RegDeleteTree(HKEY_CURRENT_USER, GUI_REGKEY_HKCU); /* delete all values and subkeys */ if (!MigrateNilingsKeys()) { @@ -444,10 +483,10 @@ GetRegistryValue(HKEY regkey, const TCHAR *name, TCHAR *data, DWORD len) data_len = len * sizeof(*data); /* get a registry string */ - status = RegQueryValueEx(regkey, name, NULL, &type, (byte *) data, &data_len); + status = RegQueryValueEx(regkey, name, NULL, &type, (byte *)data, &data_len); if (status != ERROR_SUCCESS || type != REG_SZ) { - return(0); + return (0); } data_len /= sizeof(*data); @@ -460,8 +499,7 @@ GetRegistryValue(HKEY regkey, const TCHAR *name, TCHAR *data, DWORD len) data[0] = L'\0'; } - return(data_len); - + return (data_len); } LONG @@ -469,7 +507,7 @@ GetRegistryValueNumeric(HKEY regkey, const TCHAR *name, DWORD *data) { DWORD type; DWORD size = sizeof(*data); - LONG status = RegQueryValueEx(regkey, name, NULL, &type, (PBYTE) data, &size); + LONG status = RegQueryValueEx(regkey, name, NULL, &type, (PBYTE)data, &size); return (type == REG_DWORD && status == ERROR_SUCCESS) ? 1 : 0; } @@ -478,20 +516,20 @@ SetRegistryValue(HKEY regkey, const TCHAR *name, const TCHAR *data) { /* set a registry string */ DWORD size = (_tcslen(data) + 1) * sizeof(*data); - if (RegSetValueEx(regkey, name, 0, REG_SZ, (PBYTE) data, size) != ERROR_SUCCESS) + if (RegSetValueEx(regkey, name, 0, REG_SZ, (PBYTE)data, size) != ERROR_SUCCESS) { /* Error writing registry value */ ShowLocalizedMsg(IDS_ERR_WRITE_REGVALUE, GUI_REGKEY_HKCU, name); - return(0); + return (0); } - return(1); + return (1); } int SetRegistryValueNumeric(HKEY regkey, const TCHAR *name, DWORD data) { - LONG status = RegSetValueEx(regkey, name, 0, REG_DWORD, (PBYTE) &data, sizeof(data)); + LONG status = RegSetValueEx(regkey, name, 0, REG_DWORD, (PBYTE)&data, sizeof(data)); if (status == ERROR_SUCCESS) { return 1; @@ -519,7 +557,7 @@ OpenConfigRegistryKey(const WCHAR *config_name, HKEY *regkey, BOOL create) } _snwprintf(name, count, fmt, config_name); - name[count-1] = L'\0'; + name[count - 1] = L'\0'; if (!create) { @@ -528,8 +566,15 @@ OpenConfigRegistryKey(const WCHAR *config_name, HKEY *regkey, BOOL create) else { /* create if key doesn't exist */ - status = RegCreateKeyEx(HKEY_CURRENT_USER, name, 0, NULL, - REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, regkey, NULL); + status = RegCreateKeyEx(HKEY_CURRENT_USER, + name, + 0, + NULL, + REG_OPTION_NON_VOLATILE, + KEY_READ | KEY_WRITE, + NULL, + regkey, + NULL); } free(name); @@ -537,7 +582,10 @@ OpenConfigRegistryKey(const WCHAR *config_name, HKEY *regkey, BOOL create) } int -SetConfigRegistryValueBinary(const WCHAR *config_name, const WCHAR *name, const BYTE *data, DWORD len) +SetConfigRegistryValueBinary(const WCHAR *config_name, + const WCHAR *name, + const BYTE *data, + DWORD len) { HKEY regkey; DWORD status; diff --git a/registry.h b/registry.h index 5128c2476..7f498ae08 100644 --- a/registry.h +++ b/registry.h @@ -38,7 +38,10 @@ int SetRegistryValue(HKEY regkey, const TCHAR *name, const TCHAR *data); int SetRegistryValueNumeric(HKEY regkey, const TCHAR *name, DWORD data); -int SetConfigRegistryValueBinary(const WCHAR *config_name, const WCHAR *name, const BYTE *data, DWORD len); +int SetConfigRegistryValueBinary(const WCHAR *config_name, + const WCHAR *name, + const BYTE *data, + DWORD len); DWORD GetConfigRegistryValue(const WCHAR *config_name, const WCHAR *name, BYTE *data, DWORD len); diff --git a/save_pass.c b/save_pass.c index f2dff33d9..cde660cd6 100644 --- a/save_pass.c +++ b/save_pass.c @@ -31,11 +31,11 @@ #include "save_pass.h" #include "misc.h" -#define KEY_PASS_DATA L"key-data" -#define AUTH_PASS_DATA L"auth-data" -#define ENTROPY_DATA L"entropy" -#define AUTH_USER_DATA L"username" -#define ENTROPY_LEN 16 +#define KEY_PASS_DATA L"key-data" +#define AUTH_PASS_DATA L"auth-data" +#define ENTROPY_DATA L"entropy" +#define AUTH_USER_DATA L"username" +#define ENTROPY_LEN 16 static DWORD crypt_protect(BYTE *data, int szdata, char *entropy, BYTE **out) @@ -46,7 +46,7 @@ crypt_protect(BYTE *data, int szdata, char *entropy, BYTE **out) data_in.pbData = data; data_in.cbData = szdata; - e.pbData = (BYTE *) entropy; + e.pbData = (BYTE *)entropy; e.cbData = entropy ? strlen(entropy) : 0; if (CryptProtectData(&data_in, NULL, &e, NULL, NULL, 0, &data_out)) @@ -62,12 +62,12 @@ static DWORD crypt_unprotect(BYTE *data, int szdata, char *entropy, BYTE **out) { DATA_BLOB data_in; - DATA_BLOB data_out = {0, 0}; + DATA_BLOB data_out = { 0, 0 }; DATA_BLOB e; data_in.pbData = data; data_in.cbData = szdata; - e.pbData = (BYTE *) entropy; + e.pbData = (BYTE *)entropy; e.cbData = entropy ? strlen(entropy) : 0; if (CryptUnprotectData(&data_in, NULL, &e, NULL, NULL, 0, &data_out)) @@ -93,16 +93,16 @@ get_entropy(const WCHAR *config_name, char *e, int sz, BOOL generate) { int len; - len = GetConfigRegistryValue(config_name, ENTROPY_DATA, (BYTE *) e, sz); + len = GetConfigRegistryValue(config_name, ENTROPY_DATA, (BYTE *)e, sz); if (len > 0) { - e[len-1] = '\0'; + e[len - 1] = '\0'; PrintDebug(L"Got entropy from registry: %hs (len = %d)", e, len); return; } else if (generate && GetRandomPassword(e, sz)) { - e[sz-1] = '\0'; + e[sz - 1] = '\0'; PrintDebug(L"Created new entropy string : %hs", e); if (SetConfigRegistryValueBinary(config_name, ENTROPY_DATA, (BYTE *)e, sz)) { @@ -126,10 +126,10 @@ save_encrypted(const WCHAR *config_name, const WCHAR *password, const WCHAR *nam { BYTE *out; DWORD len = (wcslen(password) + 1) * sizeof(WCHAR); - char entropy[ENTROPY_LEN+1]; + char entropy[ENTROPY_LEN + 1]; get_entropy(config_name, entropy, sizeof(entropy), true); - len = crypt_protect((BYTE *) password, len, entropy, &out); + len = crypt_protect((BYTE *)password, len, entropy, &out); if (len > 0) { SetConfigRegistryValueBinary(config_name, name, out, len); @@ -173,7 +173,7 @@ recall_encrypted(const WCHAR *config_name, WCHAR *password, DWORD capacity, cons BYTE *out; DWORD len; int retval = 0; - char entropy[ENTROPY_LEN+1]; + char entropy[ENTROPY_LEN + 1]; get_entropy(config_name, entropy, sizeof(entropy), false); @@ -194,7 +194,7 @@ recall_encrypted(const WCHAR *config_name, WCHAR *password, DWORD capacity, cons if (len <= capacity * sizeof(*password)) { memcpy(password, out, len); - password[capacity-1] = L'\0'; /* in case the data was corrupted */ + password[capacity - 1] = L'\0'; /* in case the data was corrupted */ retval = 1; } else @@ -234,7 +234,7 @@ int SaveUsername(const WCHAR *config_name, const WCHAR *username) { DWORD len = (wcslen(username) + 1) * sizeof(*username); - SetConfigRegistryValueBinary(config_name, AUTH_USER_DATA, (BYTE *) username, len); + SetConfigRegistryValueBinary(config_name, AUTH_USER_DATA, (BYTE *)username, len); return 1; } /* @@ -247,12 +247,12 @@ RecallUsername(const WCHAR *config_name, WCHAR *username) DWORD capacity = USER_PASS_LEN * sizeof(WCHAR); DWORD len; - len = GetConfigRegistryValue(config_name, AUTH_USER_DATA, (BYTE *) username, capacity); + len = GetConfigRegistryValue(config_name, AUTH_USER_DATA, (BYTE *)username, capacity); if (len == 0) { return 0; } - username[USER_PASS_LEN-1] = L'\0'; + username[USER_PASS_LEN - 1] = L'\0'; return 1; } diff --git a/save_pass.h b/save_pass.h index 034854ff5..3f895d2a9 100644 --- a/save_pass.h +++ b/save_pass.h @@ -25,7 +25,7 @@ #include #define USER_PASS_LEN 128 -#define KEY_PASS_LEN 128 +#define KEY_PASS_LEN 128 int SaveKeyPass(const WCHAR *config_name, const WCHAR *password); diff --git a/scripts.c b/scripts.c index d7b3cb6bc..e0ff08913 100644 --- a/scripts.c +++ b/scripts.c @@ -75,8 +75,13 @@ RunPreconnectScript(connection_t *c) sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; - HANDLE logfile_handle = CreateFile(script_log_filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, - &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE logfile_handle = CreateFile(script_log_filename, + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + &sa, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); /* fill in STARTUPINFO struct */ GetStartupInfo(&si); @@ -91,18 +96,24 @@ RunPreconnectScript(connection_t *c) * so we use the default process env here. */ - if (!CreateProcess(NULL, cmdline, NULL, NULL, TRUE, + if (!CreateProcess(NULL, + cmdline, + NULL, + NULL, + TRUE, (o.show_script_window ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW), - NULL, c->config_dir, &si, &pi)) + NULL, + c->config_dir, + &si, + &pi)) { goto out; } /* Wait process without blocking msg pump */ - for (i = 0; i <= (int) o.preconnectscript_timeout; i++) + for (i = 0; i <= (int)o.preconnectscript_timeout; i++) { - if (!GetExitCodeProcess(pi.hProcess, &exit_code) - || exit_code != STILL_ACTIVE + if (!GetExitCodeProcess(pi.hProcess, &exit_code) || exit_code != STILL_ACTIVE || !OVPNMsgWait(1000, NULL)) { break; @@ -141,7 +152,8 @@ RunConnectScript(connection_t *c, int run_as_service) if (!run_as_service) { - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_CONN_SCRIPT)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_CONN_SCRIPT)); } /* Create the filename of the logfile */ @@ -155,8 +167,13 @@ RunConnectScript(connection_t *c, int run_as_service) sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; - HANDLE logfile_handle = CreateFile(script_log_filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, - &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE logfile_handle = CreateFile(script_log_filename, + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + &sa, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); /* fill in STARTUPINFO struct */ GetStartupInfo(&si); @@ -171,12 +188,24 @@ RunConnectScript(connection_t *c, int run_as_service) WCHAR *env = c->es ? merge_env_block(c->es) : NULL; DWORD flags = CREATE_UNICODE_ENVIRONMENT; - if (!CreateProcess(NULL, cmdline, NULL, NULL, TRUE, - (o.show_script_window ? flags|CREATE_NEW_CONSOLE : flags|CREATE_NO_WINDOW), - env, c->config_dir, &si, &pi)) + if (!CreateProcess( + NULL, + cmdline, + NULL, + NULL, + TRUE, + (o.show_script_window ? flags | CREATE_NEW_CONSOLE : flags | CREATE_NO_WINDOW), + env, + c->config_dir, + &si, + &pi)) { PrintDebug(L"CreateProcess: error = %lu", GetLastError()); - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, c->hwndStatus, TEXT(PACKAGE_NAME), IDS_ERR_RUN_CONN_SCRIPT, cmdline); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + c->hwndStatus, + TEXT(PACKAGE_NAME), + IDS_ERR_RUN_CONN_SCRIPT, + cmdline); goto out; } @@ -185,11 +214,15 @@ RunConnectScript(connection_t *c, int run_as_service) goto out; } - for (i = 0; i <= (int) o.connectscript_timeout; i++) + for (i = 0; i <= (int)o.connectscript_timeout; i++) { if (!GetExitCodeProcess(pi.hProcess, &exit_code)) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, c->hwndStatus, TEXT(PACKAGE_NAME), IDS_ERR_GET_EXIT_CODE, cmdline); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + c->hwndStatus, + TEXT(PACKAGE_NAME), + IDS_ERR_GET_EXIT_CODE, + cmdline); goto out; } @@ -197,7 +230,11 @@ RunConnectScript(connection_t *c, int run_as_service) { if (exit_code != 0) { - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, c->hwndStatus, TEXT(PACKAGE_NAME), IDS_ERR_CONN_SCRIPT_FAILED, exit_code); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + c->hwndStatus, + TEXT(PACKAGE_NAME), + IDS_ERR_CONN_SCRIPT_FAILED, + exit_code); } goto out; } @@ -208,7 +245,11 @@ RunConnectScript(connection_t *c, int run_as_service) } } - ShowLocalizedMsgEx(MB_OK|MB_ICONERROR, c->hwndStatus, TEXT(PACKAGE_NAME), IDS_ERR_RUN_CONN_SCRIPT_TIMEOUT, o.connectscript_timeout); + ShowLocalizedMsgEx(MB_OK | MB_ICONERROR, + c->hwndStatus, + TEXT(PACKAGE_NAME), + IDS_ERR_RUN_CONN_SCRIPT_TIMEOUT, + o.connectscript_timeout); out: free(env); @@ -243,7 +284,8 @@ RunDisconnectScript(connection_t *c, int run_as_service) if (!run_as_service) { - SetDlgItemText(c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_DISCONN_SCRIPT)); + SetDlgItemText( + c->hwndStatus, ID_TXT_STATUS, LoadLocalizedString(IDS_NFO_STATE_DISCONN_SCRIPT)); } /* Create the filename of the logfile */ @@ -257,8 +299,13 @@ RunDisconnectScript(connection_t *c, int run_as_service) sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; - HANDLE logfile_handle = CreateFile(script_log_filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, - &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE logfile_handle = CreateFile(script_log_filename, + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + &sa, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); /* fill in STARTUPINFO struct */ GetStartupInfo(&si); @@ -273,17 +320,24 @@ RunDisconnectScript(connection_t *c, int run_as_service) WCHAR *env = c->es ? merge_env_block(c->es) : NULL; DWORD flags = CREATE_UNICODE_ENVIRONMENT; - if (!CreateProcess(NULL, cmdline, NULL, NULL, TRUE, - (o.show_script_window ? flags|CREATE_NEW_CONSOLE : flags|CREATE_NO_WINDOW), - NULL, c->config_dir, &si, &pi)) + if (!CreateProcess( + NULL, + cmdline, + NULL, + NULL, + TRUE, + (o.show_script_window ? flags | CREATE_NEW_CONSOLE : flags | CREATE_NO_WINDOW), + NULL, + c->config_dir, + &si, + &pi)) { goto out; } - for (i = 0; i <= (int) o.disconnectscript_timeout; i++) + for (i = 0; i <= (int)o.disconnectscript_timeout; i++) { - if (!GetExitCodeProcess(pi.hProcess, &exit_code) - || exit_code != STILL_ACTIVE + if (!GetExitCodeProcess(pi.hProcess, &exit_code) || exit_code != STILL_ACTIVE || !OVPNMsgWait(1000, c->hwndStatus)) /* WM_QUIT -- do not popup error */ { goto out; diff --git a/service.c b/service.c index 13b1f4eca..0508e16aa 100644 --- a/service.c +++ b/service.c @@ -51,14 +51,15 @@ CheckIServiceStatus(BOOL warn) if (NULL == schSCManager) { - return(false); + return (false); } - schService = OpenService(schSCManager, o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? - OPENVPN_SERVICE_NAME_OVPN3 : OPENVPN_SERVICE_NAME_OVPN2, SERVICE_QUERY_STATUS); + schService = OpenService(schSCManager, + o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? OPENVPN_SERVICE_NAME_OVPN3 + : OPENVPN_SERVICE_NAME_OVPN2, + SERVICE_QUERY_STATUS); - if (schService == NULL - && GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) + if (schService == NULL && GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) { /* warn that iservice is not installed */ if (warn) @@ -111,10 +112,9 @@ CheckServiceStatus() SERVICE_STATUS ssStatus; /* Open a handle to the SC Manager database. */ - schSCManager = OpenSCManager( - NULL, /* local machine */ - NULL, /* ServicesActive database */ - SC_MANAGER_CONNECT); /* Connect rights */ + schSCManager = OpenSCManager(NULL, /* local machine */ + NULL, /* ServicesActive database */ + SC_MANAGER_CONNECT); /* Connect rights */ if (NULL == schSCManager) { @@ -122,10 +122,9 @@ CheckServiceStatus() goto out; } - schService = OpenService( - schSCManager, /* SCM database */ - _T("OpenVPNService"), /* service name */ - SERVICE_QUERY_STATUS); + schService = OpenService(schSCManager, /* SCM database */ + _T("OpenVPNService"), /* service name */ + SERVICE_QUERY_STATUS); if (schService == NULL) { @@ -133,9 +132,8 @@ CheckServiceStatus() goto out; } - if (!QueryServiceStatus( - schService, /* handle to service */ - &ssStatus) ) /* address of status information structure */ + if (!QueryServiceStatus(schService, /* handle to service */ + &ssStatus)) /* address of status information structure */ { /* query failed */ o.service_state = service_noaccess; @@ -203,13 +201,16 @@ GetServicePid(void) schManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if (schManager) { - schService = OpenService(schManager, o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? - OPENVPN_SERVICE_NAME_OVPN3 : OPENVPN_SERVICE_NAME_OVPN2, SERVICE_QUERY_STATUS); + schService = OpenService(schManager, + o.ovpn_engine == OPENVPN_ENGINE_OVPN3 ? OPENVPN_SERVICE_NAME_OVPN3 + : OPENVPN_SERVICE_NAME_OVPN2, + SERVICE_QUERY_STATUS); if (schService) { - SERVICE_STATUS_PROCESS ssp = {0}; + SERVICE_STATUS_PROCESS ssp = { 0 }; DWORD nbytes = 0; - if (QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (BYTE *)&ssp, sizeof(ssp), &nbytes) + if (QueryServiceStatusEx( + schService, SC_STATUS_PROCESS_INFO, (BYTE *)&ssp, sizeof(ssp), &nbytes) && ssp.dwCurrentState == SERVICE_RUNNING) { pid = ssp.dwProcessId; @@ -220,8 +221,11 @@ GetServicePid(void) } if (pid == 0) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs:%d Failed to get service process id: (error = 0x%08x)", - __func__, __LINE__, GetLastError()); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"%hs:%d Failed to get service process id: (error = 0x%08x)", + __func__, + __LINE__, + GetLastError()); } return pid; } diff --git a/tray.c b/tray.c index c474e7927..4254312d8 100644 --- a/tray.c +++ b/tray.c @@ -58,8 +58,9 @@ TOOLINFO ti; /* global tool info structure for tool tip of tray icon*/ extern options_t o; -#define USE_NESTED_CONFIG_MENU ((o.config_menu_view == CONFIG_VIEW_AUTO && o.num_configs > 25) \ - || (o.config_menu_view == CONFIG_VIEW_NESTED)) +#define USE_NESTED_CONFIG_MENU \ + ((o.config_menu_view == CONFIG_VIEW_AUTO && o.num_configs > 25) \ + || (o.config_menu_view == CONFIG_VIEW_NESTED)) static void @@ -82,7 +83,6 @@ DeleteMenuBitmaps(void) static void CreateMenuBitmaps(void) { - DeleteMenuBitmaps(); int cx = GetSystemMetrics(SM_CXMENUCHECK); @@ -115,8 +115,8 @@ CreateMenuBitmaps(void) } /* Load the image and mask bitmaps into the DCs saving the default one's */ - HBITMAP def1 = (HBITMAP) SelectObject(imgDC, iconinfo.hbmColor); - HBITMAP def2 = (HBITMAP) SelectObject(maskDC, iconinfo.hbmMask); + HBITMAP def1 = (HBITMAP)SelectObject(imgDC, iconinfo.hbmColor); + HBITMAP def2 = (HBITMAP)SelectObject(maskDC, iconinfo.hbmMask); /* White mask pixels mark the background region */ COLORREF ref = RGB(255, 255, 255); @@ -134,7 +134,7 @@ CreateMenuBitmaps(void) } /* Save the result and restore the default bitmaps back in the DC */ - hbmpConnecting = (HBITMAP) SelectObject(imgDC, def1); + hbmpConnecting = (HBITMAP)SelectObject(imgDC, def1); SelectObject(maskDC, def2); /* We don't need the mask bitmap -- free it */ @@ -156,7 +156,7 @@ AllocateConnectionMenu() { return; } - HMENU *tmp = (HMENU *) realloc(hMenuConn, sizeof(HMENU)*(o.num_configs + 50)); + HMENU *tmp = (HMENU *)realloc(hMenuConn, sizeof(HMENU) * (o.num_configs + 50)); if (tmp) { hmenu_size = o.num_configs + 50; @@ -165,7 +165,9 @@ AllocateConnectionMenu() else { o.num_configs = hmenu_size; - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"Allocation of hMenuConn failed. Ignoring configs beyond index = %d", o.num_configs); + MsgToEventLog(EVENTLOG_ERROR_TYPE, + L"Allocation of hMenuConn failed. Ignoring configs beyond index = %d", + o.num_configs); } return; } @@ -180,21 +182,22 @@ CreatePopupMenus() */ if (o.num_groups <= 0) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs:%d Logic error - no config groups", __func__, __LINE__); + MsgToEventLog( + EVENTLOG_ERROR_TYPE, L"%hs:%d Logic error - no config groups", __func__, __LINE__); return; } AllocateConnectionMenu(); CreateMenuBitmaps(); - MENUINFO minfo = {.cbSize = sizeof(MENUINFO)}; + MENUINFO minfo = { .cbSize = sizeof(MENUINFO) }; for (connection_t *c = o.chead; c; c = c->next) { hMenuConn[c->id] = CreatePopupMenu(); /* Save the connection index in the menu.*/ minfo.fMask = MIM_MENUDATA; - minfo.dwMenuData = (ULONG_PTR) c; + minfo.dwMenuData = (ULONG_PTR)c; SetMenuInfo(hMenuConn[c->id], &minfo); } for (int i = 0; i < o.num_groups; i++) @@ -220,7 +223,7 @@ CreatePopupMenus() /* Set main menu's menudata to first connection */ minfo.fMask = MIM_MENUDATA; GetMenuInfo(hMenu, &minfo); - minfo.dwMenuData = (ULONG_PTR) o.chead; + minfo.dwMenuData = (ULONG_PTR)o.chead; SetMenuInfo(hMenu, &minfo); /* Create Main menu with actions */ @@ -238,15 +241,17 @@ CreatePopupMenus() 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)); + AppendMenu(hMenu, MF_POPUP, (UINT_PTR)hMenuImport, LoadLocalizedString(IDS_MENU_IMPORT)); + AppendMenu( + hMenuImport, MF_STRING, IDM_IMPORT_FILE, LoadLocalizedString(IDS_MENU_IMPORT_FILE)); AppendMenu(hMenuImport, MF_STRING, IDM_IMPORT_AS, LoadLocalizedString(IDS_MENU_IMPORT_AS)); - AppendMenu(hMenuImport, MF_STRING, IDM_IMPORT_URL, LoadLocalizedString(IDS_MENU_IMPORT_URL)); + AppendMenu( + hMenuImport, MF_STRING, IDM_IMPORT_URL, LoadLocalizedString(IDS_MENU_IMPORT_URL)); AppendMenu(hMenu, MF_STRING, IDM_SETTINGS, LoadLocalizedString(IDS_MENU_SETTINGS)); AppendMenu(hMenu, MF_STRING, IDM_CLOSE, LoadLocalizedString(IDS_MENU_CLOSE)); - SetMenuStatus(o.chead, o.chead->state); + SetMenuStatus(o.chead, o.chead->state); } else { @@ -265,11 +270,14 @@ CreatePopupMenus() { continue; } - AppendMenu(parent->menu, MF_POPUP, (UINT_PTR) this->menu, this->name); + AppendMenu(parent->menu, MF_POPUP, (UINT_PTR)this->menu, this->name); this->pos = parent->children++; PrintDebug(L"Submenu %d named %ls added to parent %ls with position %d", - i, this->name, parent->name, this->pos); + i, + this->name, + parent->name, + this->pos); } /* add config file (connection) entries */ @@ -288,16 +296,20 @@ CreatePopupMenus() } if (!parent) { - MsgToEventLog(EVENTLOG_ERROR_TYPE, L"%hs:%d Logic error - parent = NULL", __func__, __LINE__); + MsgToEventLog( + EVENTLOG_ERROR_TYPE, L"%hs:%d Logic error - parent = NULL", __func__, __LINE__); continue; /* ignore this config */ } /* Add config to the current sub menu */ - AppendMenu(parent->menu, MF_POPUP, (UINT_PTR) hMenuConn[c->id], c->config_name); + AppendMenu(parent->menu, MF_POPUP, (UINT_PTR)hMenuConn[c->id], c->config_name); c->pos = parent->children++; PrintDebug(L"Config %d named %ls added to submenu %ls with position %d", - c->id, c->config_name, parent->name, c->pos); + c->id, + c->config_name, + parent->name, + c->pos); } if (o.num_configs > 0) @@ -306,10 +318,12 @@ CreatePopupMenus() } 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)); + AppendMenu(hMenu, MF_POPUP, (UINT_PTR)hMenuImport, LoadLocalizedString(IDS_MENU_IMPORT)); + AppendMenu( + hMenuImport, MF_STRING, IDM_IMPORT_FILE, LoadLocalizedString(IDS_MENU_IMPORT_FILE)); AppendMenu(hMenuImport, MF_STRING, IDM_IMPORT_AS, LoadLocalizedString(IDS_MENU_IMPORT_AS)); - AppendMenu(hMenuImport, MF_STRING, IDM_IMPORT_URL, LoadLocalizedString(IDS_MENU_IMPORT_URL)); + AppendMenu( + hMenuImport, MF_STRING, IDM_IMPORT_URL, LoadLocalizedString(IDS_MENU_IMPORT_URL)); AppendMenu(hMenu, MF_STRING, IDM_SETTINGS, LoadLocalizedString(IDS_MENU_SETTINGS)); AppendMenu(hMenu, MF_STRING, IDM_CLOSE, LoadLocalizedString(IDS_MENU_CLOSE)); @@ -318,16 +332,29 @@ CreatePopupMenus() for (connection_t *c = o.chead; c; c = c->next) { int i = c->id; - 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_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)); + AppendMenu( + hMenuConn[i], MF_STRING, IDM_VIEWLOGMENU, LoadLocalizedString(IDS_MENU_VIEWLOG)); - AppendMenu(hMenuConn[i], MF_STRING, IDM_EDITMENU, LoadLocalizedString(IDS_MENU_EDITCONFIG)); - AppendMenu(hMenuConn[i], MF_STRING, IDM_CLEARPASSMENU, LoadLocalizedString(IDS_MENU_CLEARPASS)); + AppendMenu( + hMenuConn[i], MF_STRING, IDM_EDITMENU, LoadLocalizedString(IDS_MENU_EDITCONFIG)); + AppendMenu(hMenuConn[i], + MF_STRING, + IDM_CLEARPASSMENU, + LoadLocalizedString(IDS_MENU_CLEARPASS)); SetMenuStatus(c, c->state); } @@ -375,7 +402,7 @@ PositionTrayToolTip(LONG x, LONG y) RECT r; LONG cxmax = GetSystemMetrics(SM_CXSCREEN); LONG cymax = GetSystemMetrics(SM_CYSCREEN); - APPBARDATA abd = {.cbSize = sizeof(APPBARDATA) }; + APPBARDATA abd = { .cbSize = sizeof(APPBARDATA) }; GetWindowRect(traytip, &r); LONG w = r.right - r.left; LONG h = r.bottom - r.top; @@ -383,18 +410,17 @@ PositionTrayToolTip(LONG x, LONG y) * 10 pixels below y depending on whether we are closer to the bottom or top of the screen. * - horizontally, try to centre around x adjusting for overflow to the right or left */ - r.left = (x < w/2) ? 0 : ((x + w/2 < cxmax) ? x - w/2 : cxmax - w); - r.top = (y > h + 10) ? y - (h + 10) : y + 10; + r.left = (x < w / 2) ? 0 : ((x + w / 2 < cxmax) ? x - w / 2 : cxmax - w); + r.top = (y > h + 10) ? y - (h + 10) : y + 10; /* If taskbar is at top, move the top of the window to the bottom of the taskbar */ - if (SHAppBarMessage(ABM_GETTASKBARPOS, &abd) - && (abd.rc.bottom < cymax/2)) + if (SHAppBarMessage(ABM_GETTASKBARPOS, &abd) && (abd.rc.bottom < cymax / 2)) { r.top = abd.rc.bottom; } SendMessageW(traytip, TTM_TRACKPOSITION, 0, MAKELONG(r.left, r.top)); - SetWindowPos(traytip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE); + SetWindowPos(traytip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); } /* @@ -448,16 +474,19 @@ OnNotifyTray(LPARAM lParam) } break; - /* handle messages when mouse enters and leaves the icon -- we show the custom tooltip window */ + /* handle messages when mouse enters and leaves the icon -- we show the custom tooltip + * window */ case NIN_POPUPOPEN: if (traytip) { - NOTIFYICONIDENTIFIER nid = {.cbSize = sizeof(nid), .hWnd = o.hWnd, - .uID = HIWORD(lParam), .guidItem = GUID_NULL}; - RECT r = {0}; + NOTIFYICONIDENTIFIER nid = { .cbSize = sizeof(nid), + .hWnd = o.hWnd, + .uID = HIWORD(lParam), + .guidItem = GUID_NULL }; + RECT r = { 0 }; Shell_NotifyIconGetRect(&nid, &r); - SendMessageW(traytip, TTM_TRACKACTIVATE, (WPARAM)TRUE, (LPARAM) &ti); - PositionTrayToolTip((r.left+r.right)/2, r.top); + SendMessageW(traytip, TTM_TRACKACTIVATE, (WPARAM)TRUE, (LPARAM)&ti); + PositionTrayToolTip((r.left + r.right) / 2, r.top); } break; @@ -515,9 +544,18 @@ ShowTrayIcon() if (Shell_NotifyIcon(NIM_SETVERSION, &ni)) { /* create a custom tooltip for the tray */ - traytip = CreateWindowEx(0, TOOLTIPS_CLASS, NULL, WS_POPUP |TTS_ALWAYSTIP, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - o.hWnd, NULL, o.hInstance, NULL); + traytip = CreateWindowEx(0, + TOOLTIPS_CLASS, + NULL, + WS_POPUP | TTS_ALWAYSTIP, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + o.hWnd, + NULL, + o.hInstance, + NULL); if (!traytip) /* revert the version back so that we can use legacy ni.szTip for tip text */ { ni.uVersion = 0; @@ -527,10 +565,10 @@ ShowTrayIcon() if (traytip) { - LONG cx = GetSystemMetrics(SM_CXSCREEN)/4; /* max width of tray tooltip = 25% of screen */ + LONG cx = GetSystemMetrics(SM_CXSCREEN) / 4; /* max width of tray tooltip = 25% of screen */ ti.cbSize = sizeof(ti); - ti.uId = (UINT_PTR) traytip; - ti.uFlags = TTF_ABSOLUTE|TTF_TRACK|TTF_IDISHWND; + ti.uId = (UINT_PTR)traytip; + ti.uFlags = TTF_ABSOLUTE | TTF_TRACK | TTF_IDISHWND; if (LangFlowDirection() == 1) { ti.uFlags |= TTF_RTLREADING; @@ -538,7 +576,7 @@ ShowTrayIcon() ti.hwnd = o.hWnd; ti.lpszText = _T(PACKAGE_NAME); SendMessage(traytip, TTM_ADDTOOL, 0, (LPARAM)&ti); - SendMessage(traytip, TTM_SETMAXTIPWIDTH, 0, (LPARAM) cx); + SendMessage(traytip, TTM_SETMAXTIPWIDTH, 0, (LPARAM)cx); } } @@ -562,7 +600,9 @@ SetTrayIcon(conn_state_t state) if (c->state == connected) { /* Append connection name to Icon Tip Msg */ - _tcsncat(tip_msg, (first_conn ? msg_connected : _T(", ")), _countof(tip_msg) - _tcslen(tip_msg) - 1); + _tcsncat(tip_msg, + (first_conn ? msg_connected : _T(", ")), + _countof(tip_msg) - _tcslen(tip_msg) - 1); _tcsncat(tip_msg, c->config_name, _countof(tip_msg) - _tcslen(tip_msg) - 1); first_conn = FALSE; cc = c; @@ -575,7 +615,9 @@ SetTrayIcon(conn_state_t state) if (c->state == connecting || c->state == resuming || c->state == reconnecting) { /* Append connection name to Icon Tip Msg */ - _tcsncat(tip_msg, (first_conn ? msg_connecting : _T(", ")), _countof(tip_msg) - _tcslen(tip_msg) - 1); + _tcsncat(tip_msg, + (first_conn ? msg_connecting : _T(", ")), + _countof(tip_msg) - _tcslen(tip_msg) - 1); _tcsncat(tip_msg, c->config_name, _countof(tip_msg) - _tcslen(tip_msg) - 1); first_conn = FALSE; } @@ -592,13 +634,15 @@ SetTrayIcon(conn_state_t state) * Include about 50 characters for "Connected since:" and "Assigned IP:" prefixes. */ size_t max_msglen = _countof(tip_msg) - (_countof(time) + _countof(ip) + 50); - if (wcslen(tip_msg) > max_msglen && traytip) + if (wcslen(tip_msg) > max_msglen && traytip) { - wcsncpy_s(&tip_msg[max_msglen-1], 2, L"…", _TRUNCATE); + wcsncpy_s(&tip_msg[max_msglen - 1], 2, L"…", _TRUNCATE); } LocalizedTime(cc->connected_since, time, _countof(time)); - _tcsncat(tip_msg, LoadLocalizedString(IDS_TIP_CONNECTED_SINCE), _countof(tip_msg) - _tcslen(tip_msg) - 1); + _tcsncat(tip_msg, + LoadLocalizedString(IDS_TIP_CONNECTED_SINCE), + _countof(tip_msg) - _tcslen(tip_msg) - 1); _tcsncat(tip_msg, time, _countof(tip_msg) - _tcslen(tip_msg) - 1); /* concatenate ipv4 and ipv6 addresses into one string */ @@ -627,7 +671,7 @@ SetTrayIcon(conn_state_t state) if (traytip) { ti.lpszText = tip_msg; - SendMessage(traytip, TTM_UPDATETIPTEXT, 0, (LPARAM) &ti); + SendMessage(traytip, TTM_UPDATETIPTEXT, 0, (LPARAM)&ti); } else { @@ -649,7 +693,7 @@ CheckAndSetTrayIcon() else { if (CountConnState(connecting) != 0 || CountConnState(reconnecting) != 0 - || CountConnState(resuming) != 0) + || CountConnState(resuming) != 0) { SetTrayIcon(connecting); } @@ -748,17 +792,20 @@ SetMenuStatus(connection_t *c, conn_state_t state) if (checked == 1) { /* Connected: use system-default check mark */ - SetMenuItemBitmaps(parent->menu, pos, MF_BYPOSITION, NULL, NULL); + SetMenuItemBitmaps(parent->menu, pos, MF_BYPOSITION, NULL, NULL); } else if (checked == 2) { /* Connecting: use our custom check mark */ - SetMenuItemBitmaps(parent->menu, pos, MF_BYPOSITION, NULL, hbmpConnecting); + SetMenuItemBitmaps(parent->menu, pos, MF_BYPOSITION, NULL, hbmpConnecting); } CheckMenuItem(parent->menu, pos, MF_BYPOSITION | (checked ? MF_CHECKED : MF_UNCHECKED)); PrintDebug(L"Setting state of config %ls checked = %d, parent %ls, pos %d", - c->config_name, checked, (parent->id == 0) ? L"Main Menu" : L"SubMenu", pos); + c->config_name, + checked, + (parent->id == 0) ? L"Main Menu" : L"SubMenu", + pos); if (checked) /* also check all parent groups */ { diff --git a/tray.h b/tray.h index 199d3c39c..b3a287549 100644 --- a/tray.h +++ b/tray.h @@ -25,25 +25,25 @@ #include "options.h" -#define IDM_SERVICE_START 100 -#define IDM_SERVICE_STOP 101 -#define IDM_SERVICE_RESTART 102 - -#define IDM_SETTINGS 221 -#define IDM_CLOSE 223 -#define IDM_IMPORT 224 -#define IDM_IMPORT_FILE 225 -#define IDM_IMPORT_AS 226 -#define IDM_IMPORT_URL 227 - -#define IDM_CONNECTMENU 300 -#define IDM_DISCONNECTMENU (1 + IDM_CONNECTMENU) -#define IDM_STATUSMENU (1 + IDM_DISCONNECTMENU) -#define IDM_VIEWLOGMENU (1 + IDM_STATUSMENU) -#define IDM_EDITMENU (1 + IDM_VIEWLOGMENU) -#define IDM_PASSPHRASEMENU (1 + IDM_EDITMENU) -#define IDM_CLEARPASSMENU (1 + IDM_PASSPHRASEMENU) -#define IDM_RECONNECTMENU (1 + IDM_CLEARPASSMENU) +#define IDM_SERVICE_START 100 +#define IDM_SERVICE_STOP 101 +#define IDM_SERVICE_RESTART 102 + +#define IDM_SETTINGS 221 +#define IDM_CLOSE 223 +#define IDM_IMPORT 224 +#define IDM_IMPORT_FILE 225 +#define IDM_IMPORT_AS 226 +#define IDM_IMPORT_URL 227 + +#define IDM_CONNECTMENU 300 +#define IDM_DISCONNECTMENU (1 + IDM_CONNECTMENU) +#define IDM_STATUSMENU (1 + IDM_DISCONNECTMENU) +#define IDM_VIEWLOGMENU (1 + IDM_STATUSMENU) +#define IDM_EDITMENU (1 + IDM_VIEWLOGMENU) +#define IDM_PASSPHRASEMENU (1 + IDM_EDITMENU) +#define IDM_CLEARPASSMENU (1 + IDM_PASSPHRASEMENU) +#define IDM_RECONNECTMENU (1 + IDM_CLEARPASSMENU) void RecreatePopupMenus(void); diff --git a/viewlog.c b/viewlog.c index c1ea7441a..343109f62 100644 --- a/viewlog.c +++ b/viewlog.c @@ -40,7 +40,7 @@ extern options_t o; void ViewLog(connection_t *c) { - TCHAR filename[2*MAX_PATH]; + TCHAR filename[2 * MAX_PATH]; STARTUPINFO start_info; PROCESS_INFORMATION proc_info; @@ -54,17 +54,21 @@ ViewLog(connection_t *c) CLEAR(sd); /* Try first using file association */ - CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); /* Safe to init COM multiple times */ + CoInitializeEx(NULL, + COINIT_APARTMENTTHREADED + | COINIT_DISABLE_OLE1DDE); /* Safe to init COM multiple times */ status = ShellExecuteW(o.hWnd, L"open", c->log_path, NULL, o.log_dir, SW_SHOWNORMAL); - if (status > (HINSTANCE) 32) /* Success */ + if (status > (HINSTANCE)32) /* Success */ { return; } else { PrintDebug(L"Opening log file using ShellExecute with verb = open failed" - " for config '%ls' (status = %lu)", c->config_name, status); + " for config '%ls' (status = %lu)", + c->config_name, + status); } _sntprintf_0(filename, _T("%ls \"%ls\""), o.log_viewer, c->log_path); @@ -100,7 +104,7 @@ ViewLog(connection_t *c) void EditConfig(connection_t *c) { - TCHAR filename[2*MAX_PATH]; + TCHAR filename[2 * MAX_PATH]; STARTUPINFO start_info; PROCESS_INFORMATION proc_info; @@ -116,16 +120,20 @@ EditConfig(connection_t *c) /* Try first using file association */ _sntprintf_0(filename, L"%ls\\%ls", c->config_dir, c->config_file); - CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); /* Safe to init COM multiple times */ + CoInitializeEx(NULL, + COINIT_APARTMENTTHREADED + | COINIT_DISABLE_OLE1DDE); /* Safe to init COM multiple times */ status = ShellExecuteW(o.hWnd, L"open", filename, NULL, c->config_dir, SW_SHOWNORMAL); - if (status > (HINSTANCE) 32) + if (status > (HINSTANCE)32) { return; } else { PrintDebug(L"Opening config file using ShellExecute with verb = open failed" - " for config '%ls' (status = %lu)", c->config_name, status); + " for config '%ls' (status = %lu)", + c->config_name, + status); } _sntprintf_0(filename, _T("%ls \"%ls\\%ls\""), o.editor, c->config_dir, c->config_file); @@ -145,7 +153,7 @@ EditConfig(connection_t *c) TRUE, CREATE_NEW_CONSOLE, NULL, - c->config_dir, /*start-up dir */ + c->config_dir, /*start-up dir */ &start_info, &proc_info)) {