diff --git a/src/common.cpp b/src/common.cpp index c44d8c6..70f2612 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -1,1089 +1,1140 @@ /* common.c - Common routines used by GpgOL * Copyright (C) 2005, 2007, 2008 g10 Code GmbH * 2015, 2016, 2017 Bundesamt für Sicherheit in der Informationstechnik * Software engineering by Intevation GmbH * 2020 g10 Code GmbH * * This file is part of GpgOL. * * GpgOL is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GpgOL 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 Lesser General Public License * along with this program; if not, see . */ #include #define OEMRESOURCE /* Required for OBM_CHECKBOXES. */ #include #include #ifndef CSIDL_APPDATA #define CSIDL_APPDATA 0x001a #endif #ifndef CSIDL_LOCAL_APPDATA #define CSIDL_LOCAL_APPDATA 0x001c #endif #ifndef CSIDL_FLAG_CREATE #define CSIDL_FLAG_CREATE 0x8000 #endif #include #include #include #include "common.h" #include "dialogs.h" #include "cpphelp.h" #include #include #include #include #include #define COPYBUFSIZE (8 * 1024) HINSTANCE glob_hinst = NULL; void set_global_hinstance (HINSTANCE hinst) { glob_hinst = hinst; } void bring_to_front (HWND wid) { if (wid) { if (!SetForegroundWindow (wid)) { log_debug ("%s:%s: SetForegroundWindow failed", SRCNAME, __func__); /* Yet another fallback which will not work on some * versions and is not recommended by msdn */ if (!ShowWindow (wid, SW_SHOWNORMAL)) { log_debug ("%s:%s: ShowWindow failed.", SRCNAME, __func__); } } } log_debug ("%s:%s: done", SRCNAME, __func__); } void fatal_error (const char *format, ...) { va_list arg_ptr; char buf[512]; va_start (arg_ptr, format); vsnprintf (buf, sizeof buf -1, format, arg_ptr); buf[sizeof buf - 1] = 0; va_end (arg_ptr); MessageBox (NULL, buf, "Fatal Error", MB_OK); abort (); } /* Helper for read_w32_registry_string(). */ static HKEY get_root_key(const char *root) { HKEY root_key; if( !root ) root_key = HKEY_CURRENT_USER; else if( !strcmp( root, "HKEY_CLASSES_ROOT" ) ) root_key = HKEY_CLASSES_ROOT; else if( !strcmp( root, "HKEY_CURRENT_USER" ) ) root_key = HKEY_CURRENT_USER; else if( !strcmp( root, "HKEY_LOCAL_MACHINE" ) ) root_key = HKEY_LOCAL_MACHINE; else if( !strcmp( root, "HKEY_USERS" ) ) root_key = HKEY_USERS; else if( !strcmp( root, "HKEY_PERFORMANCE_DATA" ) ) root_key = HKEY_PERFORMANCE_DATA; else if( !strcmp( root, "HKEY_CURRENT_CONFIG" ) ) root_key = HKEY_CURRENT_CONFIG; else return NULL; return root_key; } #if defined(_WIN64) #define CROSS_ACCESS KEY_WOW64_32KEY #else #define CROSS_ACCESS KEY_WOW64_64KEY #endif +/* Read a registry value from HKLM or HKCU of type dword and + return 1 if the value is larger then 0, 0 if it is zero and + -1 if it is not set or not found. */ +int +read_reg_bool (HKEY root, const char *path, const char *value) +{ + TSTART; + HKEY h; + HKEY tmp = root ? root : HKEY_CURRENT_USER; + + int err = RegOpenKeyEx (tmp, path , 0, KEY_READ, &h); + if (err != ERROR_SUCCESS) + { + log_debug ("%s:%s: not found %s", + SRCNAME, __func__, path); + if (!root) + { + TRETURN read_reg_bool (HKEY_LOCAL_MACHINE, path, value); + } + TRETURN -1; + } + DWORD type; + err = RegQueryValueEx (h, value, NULL, &type, NULL, NULL); + if (err != ERROR_SUCCESS || type != REG_DWORD) + { + log_debug ("%s:%s: No type or key for %s", + SRCNAME, __func__, value); + if (!root) + { + TRETURN read_reg_bool (HKEY_LOCAL_MACHINE, path, value); + } + TRETURN -1; + } + DWORD data; + DWORD size = sizeof (DWORD); + err = RegQueryValueEx (h, value, NULL, NULL, (LPBYTE)&data, + &size); + if (err != ERROR_SUCCESS) + { + log_debug ("%s:%s: Failed to find value of %s", + SRCNAME, __func__, value); + if (!root) + { + TRETURN read_reg_bool (HKEY_LOCAL_MACHINE, path, value); + } + TRETURN -1; + } + TRETURN !!data; +} + + std::string _readRegStr (HKEY root_key, const char *dir, const char *name, bool alternate) { #ifndef _WIN32 (void) root_key; (void)alternate; (void)dir; (void)name; return std::string(); #else HKEY key_handle; DWORD n1, nbytes, type; std::string ret; DWORD flags = KEY_READ; if (alternate) { flags |= CROSS_ACCESS; } if (RegOpenKeyExA(root_key, dir, 0, flags, &key_handle)) { return ret; } nbytes = 1; if (RegQueryValueExA(key_handle, name, 0, nullptr, nullptr, &nbytes)) { RegCloseKey (key_handle); return ret; } n1 = nbytes+1; char result[n1]; if (RegQueryValueExA(key_handle, name, 0, &type, (LPBYTE)result, &n1)) { RegCloseKey(key_handle); return ret; } RegCloseKey(key_handle); result[nbytes] = 0; /* make sure it is really a string */ ret = result; if (type == REG_EXPAND_SZ && strchr (result, '%')) { n1 += 1000; char tmp[n1 +1]; nbytes = ExpandEnvironmentStringsA(ret.c_str(), tmp, n1); if (nbytes && nbytes > n1) { n1 = nbytes; char tmp2[n1 +1]; nbytes = ExpandEnvironmentStringsA(result, tmp2, n1); if (nbytes && nbytes > n1) { /* oops - truncated, better don't expand at all */ return ret; } tmp2[nbytes] = 0; ret = tmp2; } else if (nbytes) { /* okay, reduce the length */ tmp[nbytes] = 0; ret = tmp; } } return ret; #endif } std::string readRegStr (const char *root, const char *dir, const char *name) { #ifndef _WIN32 (void)root; (void)dir; (void)name; return std::string(); #else HKEY root_key; std::string ret; if (!(root_key = get_root_key(root))) { return ret; } ret = _readRegStr (root_key, dir, name, false); if (ret.empty()) { // Try alternate as fallback ret = _readRegStr (root_key, dir, name, true); } if (ret.empty()) { // Try local machine as fallback. ret = _readRegStr (HKEY_LOCAL_MACHINE, dir, name, false); if (ret.empty()) { // Try alternative registry view as fallback ret = _readRegStr (HKEY_LOCAL_MACHINE, dir, name, true); } } return ret; #endif } /* Return a string from the Win32 Registry or NULL in case of error. Caller must release the return value. A NULL for root is an alias for HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE in turn. NOTE: The value is allocated with a plain xmalloc () - use xfree () and not the usual xfree(). */ char * read_w32_registry_string (const char *root, const char *dir, const char *name) { const auto ret = readRegStr (root, dir, name); if (ret.empty()) { return nullptr; } return xstrdup (ret.c_str ()); } /* Return the data dir used for forms etc. Returns NULL on error. */ char * get_data_dir (void) { char *instdir; char *p; char *dname; instdir = get_gpg4win_dir(); if (!instdir) return NULL; /* Build the key: "/share/gpgol". */ #define SDDIR "\\share\\gpgol" dname = (char*) xmalloc (strlen (instdir) + strlen (SDDIR) + 1); if (!dname) { xfree (instdir); return NULL; } p = dname; strcpy (p, instdir); p += strlen (instdir); strcpy (p, SDDIR); xfree (instdir); #undef SDDIR return dname; } /* Percent-escape the string STR by replacing colons with '%3a'. If EXTRA is not NULL all characters in it are also escaped. */ char * percent_escape (const char *str, const char *extra) { int i, j; char *ptr; if (!str) return NULL; for (i=j=0; str[i]; i++) if (str[i] == ':' || str[i] == '%' || (extra && strchr (extra, str[i]))) j++; ptr = (char *) xmalloc (i + 2 * j + 1); i = 0; while (*str) { /* FIXME: Work around a bug in Kleo. */ if (*str == ':') { ptr[i++] = '%'; ptr[i++] = '3'; ptr[i++] = 'a'; } else { if (*str == '%') { ptr[i++] = '%'; ptr[i++] = '2'; ptr[i++] = '5'; } else if (extra && strchr (extra, *str)) { ptr[i++] = '%'; ptr[i++] = tohex_lower ((*str >> 4) & 15); ptr[i++] = tohex_lower (*str & 15); } else ptr[i++] = *str; } str++; } ptr[i] = '\0'; return ptr; } /* Fix linebreaks. This replaces all consecutive \r or \n characters by a single \n. There can be extremly weird combinations of linebreaks like \r\r\n\r\r\n at the end of each line when getting the body of a mail message. */ void fix_linebreaks (char *str, int *len) { char *src; char *dst; src = str; dst = str; while (*src) { if (*src == '\r' || *src == '\n') { do src++; while (*src == '\r' || *src == '\n'); *(dst++) = '\n'; } else { *(dst++) = *(src++); } } *dst = '\0'; *len = dst - str; } /* Get a pretty name for the file at path path. File extension will be set to work for the protocol as provided in protocol and depends on the signature setting. Set signature to 0 if the extension should not be a signature extension. Returns NULL on success. Caller must free result. */ wchar_t * get_pretty_attachment_name (wchar_t *path, protocol_t protocol, int signature) { wchar_t* pretty; wchar_t* buf; if (!path || !wcslen (path)) { log_error("%s:%s: No path given", SRCNAME, __func__); return NULL; } pretty = (wchar_t*) xmalloc ((MAX_PATH + 1) * sizeof (wchar_t)); memset (pretty, 0, (MAX_PATH + 1) * sizeof (wchar_t)); buf = wcsrchr (path, '\\') + 1; if (!buf || !*buf) { log_error("%s:%s: No filename found in path", SRCNAME, __func__); xfree (pretty); return NULL; } wcscpy (pretty, buf); buf = pretty + wcslen(pretty); if (signature) { if (protocol == PROTOCOL_SMIME) { *(buf++) = '.'; *(buf++) = 'p'; *(buf++) = '7'; *(buf++) = 's'; } else { *(buf++) = '.'; *(buf++) = 's'; *(buf++) = 'i'; *(buf++) = 'g'; } } else { if (protocol == PROTOCOL_SMIME) { *(buf++) = '.'; *(buf++) = 'p'; *(buf++) = '7'; *(buf++) = 'm'; } else { *(buf++) = '.'; *(buf++) = 'g'; *(buf++) = 'p'; *(buf++) = 'g'; } } return pretty; } HANDLE CreateFileUtf8 (const char *utf8Name) { if (!utf8Name) { return INVALID_HANDLE_VALUE; } wchar_t *wname = utf8_to_wchar (utf8Name); if (!wname) { TRACEPOINT; return INVALID_HANDLE_VALUE; } auto ret = CreateFileW (wname, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL); xfree (wname); return ret; } int readFullFile (HANDLE hFile, GpgME::Data &data) { char buf[COPYBUFSIZE]; DWORD bRead = 0; BOOL ret; while ((ret = ReadFile (hFile, buf, COPYBUFSIZE, &bRead, nullptr))) { if (!bRead) { // EOF break; } data.write (buf, bRead); } if (!ret && bRead) { log_err ("Failed to read from file"); TRETURN -1; } TRETURN 0; } static std::string getTmpPathUtf8 () { static std::string ret; if (!ret.empty()) { return ret; } wchar_t tmpPath[MAX_PATH + 2]; if (!GetTempPathW (MAX_PATH, tmpPath)) { log_error ("%s:%s: Could not get tmp path.", SRCNAME, __func__); return ret; } char *utf8Name = wchar_to_utf8 (tmpPath); if (!utf8Name) { TRACEPOINT; return ret; } ret = utf8Name; xfree (utf8Name); return ret; } /* Open a file in a temporary directory, take name as a suggestion and put the open Handle in outHandle. Returns the actually used file name in case there were other files with that name. */ wchar_t* get_tmp_outfile (const wchar_t *name, HANDLE *outHandle) { const auto utf8Name = wchar_to_utf8_string (name); const auto tmpPath = getTmpPathUtf8 (); if (utf8Name.empty() || tmpPath.empty()) { TRACEPOINT; return nullptr; } auto outName = tmpPath + utf8Name; log_data("%s:%s: Attachment candidate is %s", SRCNAME, __func__, outName.c_str ()); int tries = 1; while ((*outHandle = CreateFileUtf8 (outName.c_str ())) == INVALID_HANDLE_VALUE) { log_debug_w32 (-1, "%s:%s: Failed to open candidate '%s'", SRCNAME, __func__, anonstr (outName.c_str())); char *outNameC = xstrdup ((tmpPath + utf8Name).c_str ()); const auto lastBackslash = strrchr (outNameC, '\\'); if (!lastBackslash) { /* This is an error because tmp name by definition contains one */ log_error ("%s:%s: No backslash in origname '%s'", SRCNAME, __func__, outNameC); xfree (outNameC); return NULL; } auto fileExt = strchr (lastBackslash, '.'); if (fileExt) { *fileExt = '\0'; ++fileExt; } // OutNameC is now without an extension and if // there is a file ext it now points to the extension. outName = outNameC + std::string("_") + std::to_string(tries++); if (fileExt) { outName += std::string(".") + fileExt; } xfree (outNameC); if (tries == 50) { /* Mmh fishy, maybe the name cannot be created on the file system. Let's switch to a generic name. */ log_dbg ("Can't find an attachment name. " "Switching over to a generic attachment name."); outName = tmpPath + "attachment"; if (fileExt) { outName += "."; outName += fileExt; } } if (tries > 100) { /* You have to know when to give up,.. */ log_error ("%s:%s: Could not get a name out of 100 tries", SRCNAME, __func__); return NULL; } } return utf8_to_wchar (outName.c_str ()); } char * get_tmp_outfile_utf8 (const char *name, HANDLE *outHandle) { wchar_t *wname = utf8_to_wchar (name); wchar_t *wret = get_tmp_outfile (wname, outHandle); xfree (wname); char *ret = wchar_to_utf8 (wret); xfree (wret); return ret; } /** Get the Gpg4win Install directory. * * Looks first for the Gpg4win 3.x registry key. Then for the Gpg4win * 2.x registry key. And checks that the directory can be read. * * @returns NULL if no dir could be found. Otherwise a malloced string. */ char * get_gpg4win_dir() { const char *g4win_keys[] = {GPG4WIN_REGKEY_3, GPG4WIN_REGKEY_2, NULL}; const char **key; for (key = g4win_keys; *key; key++) { char *tmp = read_w32_registry_string (NULL, *key, "Install Directory"); if (!tmp) { continue; } if (!access(tmp, R_OK)) { return tmp; } else { log_debug ("Failed to access: %s\n", tmp); xfree (tmp); } } return NULL; } static void epoch_to_file_time (unsigned long time, LPFILETIME pft) { LONGLONG ll; ll = Int32x32To64(time, 10000000) + 116444736000000000; pft->dwLowDateTime = (DWORD)ll; pft->dwHighDateTime = ll >> 32; } char * format_date_from_gpgme (unsigned long time) { wchar_t buf[256]; FILETIME ft; SYSTEMTIME st; epoch_to_file_time (time, &ft); FileTimeToSystemTime(&ft, &st); int ret = GetDateFormatEx (NULL, DATE_SHORTDATE, &st, NULL, buf, 256, NULL); if (ret == 0) { return NULL; } return wchar_to_utf8 (buf); } /* Return the name of the default UI server. This name is used to auto start an UI server if an initial connect failed. */ char * get_uiserver_name (void) { char *name = NULL; char *dir, *uiserver, *p; int extra_arglen = 9; const char * server_names[] = {"kleopatra.exe", "bin\\kleopatra.exe", "gpa.exe", "bin\\gpa.exe", NULL}; const char **tmp = NULL; dir = get_gpg4win_dir (); if (!dir) { log_error ("Failed to find gpg4win dir"); return NULL; } uiserver = read_w32_registry_string (NULL, GPG4WIN_REGKEY_3, "UI Server"); if (!uiserver) { uiserver = read_w32_registry_string (NULL, GPG4WIN_REGKEY_2, "UI Server"); } if (uiserver) { name = (char*) xmalloc (strlen (dir) + strlen (uiserver) + extra_arglen + 2); strcpy (stpcpy (stpcpy (name, dir), "\\"), uiserver); for (p = name; *p; p++) if (*p == '/') *p = '\\'; xfree (uiserver); } if (name && !access (name, F_OK)) { /* Set through registry and is accessible */ xfree(dir); return name; } /* Fallbacks */ for (tmp = server_names; *tmp; tmp++) { if (name) { xfree (name); } name = (char *) xmalloc (strlen (dir) + strlen (*tmp) + extra_arglen + 2); strcpy (stpcpy (stpcpy (name, dir), "\\"), *tmp); for (p = name; *p; p++) if (*p == '/') *p = '\\'; if (!access (name, F_OK)) { /* Found a viable candidate */ if (strstr (name, "kleopatra.exe")) { strcat (name, " --daemon"); } xfree (dir); return name; } } xfree (dir); log_error ("Failed to find a viable UIServer"); return NULL; } int has_high_integrity(HANDLE hToken) { PTOKEN_MANDATORY_LABEL integrity_label = NULL; DWORD integrity_level = 0, size = 0; if (hToken == NULL || hToken == INVALID_HANDLE_VALUE) { log_debug ("Invalid parameters."); return 0; } /* Get the required size */ if (!GetTokenInformation (hToken, TokenIntegrityLevel, NULL, 0, &size)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { log_debug ("Failed to get required size.\n"); return 0; } } integrity_label = (PTOKEN_MANDATORY_LABEL) LocalAlloc(0, size); if (integrity_label == NULL) { log_debug ("Failed to allocate label. \n"); return 0; } if (!GetTokenInformation (hToken, TokenIntegrityLevel, integrity_label, size, &size)) { log_debug ("Failed to get integrity level.\n"); LocalFree(integrity_label); return 0; } /* Get the last integrity level */ integrity_level = *GetSidSubAuthority(integrity_label->Label.Sid, (DWORD)(UCHAR)(*GetSidSubAuthorityCount( integrity_label->Label.Sid) - 1)); LocalFree (integrity_label); return integrity_level >= SECURITY_MANDATORY_HIGH_RID; } int is_elevated() { int ret = 0; HANDLE hToken = NULL; if (OpenProcessToken (GetCurrentProcess(), TOKEN_QUERY, &hToken)) { DWORD elevation; DWORD cbSize = sizeof (DWORD); if (GetTokenInformation (hToken, TokenElevation, &elevation, sizeof (TokenElevation), &cbSize)) { ret = elevation; } } /* Elevation will be true and ElevationType TokenElevationTypeFull even if the token is a user token created by SAFER so we additionally check the integrity level of the token which will only be high in the real elevated process and medium otherwise. */ ret = ret && has_high_integrity (hToken); if (hToken) CloseHandle (hToken); return ret; } int gpgol_message_box (HWND parent, const char *utf8_text, const char *utf8_caption, UINT type) { wchar_t *w_text = utf8_to_wchar (utf8_text); wchar_t *w_caption = utf8_to_wchar (utf8_caption); int ret = 0; MSGBOXPARAMSW mbp; mbp.cbSize = sizeof (MSGBOXPARAMS); mbp.hwndOwner = parent; mbp.hInstance = glob_hinst; mbp.lpszText = w_text; mbp.lpszCaption = w_caption; mbp.dwStyle = type | MB_USERICON; mbp.dwLanguageId = MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT); mbp.lpfnMsgBoxCallback = NULL; mbp.dwContextHelpId = 0; mbp.lpszIcon = (LPCWSTR) MAKEINTRESOURCE (IDI_GPGOL_LOCK_ICON); ret = MessageBoxIndirectW (&mbp); xfree (w_text); xfree (w_caption); return ret; } void gpgol_bug (HWND parent, int code) { const char *bugmsg = utf8_gettext ("Operation failed.\n\n" "This is usually caused by a bug in GpgOL or an error in your setup.\n" "Please see https://www.gpg4win.org/reporting-bugs.html " "or ask your Administrator for support."); char *with_code; gpgrt_asprintf (&with_code, "%s\nCode: %i", bugmsg, code); memdbg_alloc (with_code); gpgol_message_box (parent, with_code, _("GpgOL Error"), MB_OK); xfree (with_code); return; } static int store_config_value (HKEY hk, const char *path, const char *key, const char *val) { HKEY h; int type; int ec; if (hk == NULL) { hk = HKEY_CURRENT_USER; } ec = RegCreateKeyEx (hk, path, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &h, NULL); if (ec != ERROR_SUCCESS) { log_debug_w32 (ec, "creating/opening registry key `%s' failed", path); return -1; } type = strchr (val, '%')? REG_EXPAND_SZ : REG_SZ; ec = RegSetValueEx (h, key, 0, type, (const BYTE*)val, strlen (val)); if (ec != ERROR_SUCCESS) { log_debug_w32 (ec, "saving registry key `%s'->`%s' failed", path, key); RegCloseKey(h); return -1; } RegCloseKey(h); return 0; } /* Store a key in the registry with the key given by @key and the value @value. */ int store_extension_value (const char *key, const char *val) { return store_config_value (HKEY_CURRENT_USER, GPGOL_REGPATH, key, val); } /* Load a key from the registry with the key given by @key. The value is returned in @val and needs to freed by the caller. */ int load_extension_value (const char *key, char **val) { if (!val) { STRANGEPOINT; return -1; } *val = read_w32_registry_string (nullptr, GPGOL_REGPATH, key); log_debug ("%s:%s: LoadReg '%s' val '%s'", SRCNAME, __func__, key ? key : "null", *val ? *val : "null"); return 0; } int store_extension_subkey_value (const char *subkey, const char *key, const char *val) { int ret; char *path; gpgrt_asprintf (&path, "%s\\%s", GPGOL_REGPATH, subkey); memdbg_alloc (path); ret = store_config_value (HKEY_CURRENT_USER, path, key, val); xfree (path); return ret; } bool in_de_vs_mode() { /* We cache the values only once. A change requires restart. This is because checking this is very expensive as gpgconf spawns each process to query the settings. */ static bool checked; static bool vs_mode; if (checked) { return vs_mode; } checked = true; GpgME::Error err; const auto components = GpgME::Configuration::Component::load (err); log_debug ("%s:%s: Checking for de-vs mode.", SRCNAME, __func__); if (err) { log_error ("%s:%s: Failed to get gpgconf components: %s", SRCNAME, __func__, err.asString ()); vs_mode = false; return vs_mode; } for (const auto &component: components) { if (component.name () && !strcmp (component.name (), "gpg")) { for (const auto &option: component.options ()) { if (option.name () && !strcmp (option.name (), "compliance") && option.currentValue ().stringValue () && #ifdef HAVE_W32_SYSTEM !stricmp (option.currentValue ().stringValue (), "de-vs")) #else !strcasecmp (option.currentValue ().stringValue (), "de-vs")) #endif { log_debug ("%s:%s: Detected de-vs mode", SRCNAME, __func__); vs_mode = true; return vs_mode; } } vs_mode = false; return vs_mode; } } vs_mode = false; return false; } const char * de_vs_name (bool isCompliant) { static std::string compName; static std::string uncompName; if (!compName.empty() && isCompliant) { return compName.c_str (); } if (!uncompName.empty() && !isCompliant) { return uncompName.c_str (); } TSTART; /* Only look once */ compName = _("VS-NfD compliant"); uncompName = _("not VS-NfD compliant"); /* Find the libkleopatrarc */ char *instdir = get_gpg4win_dir(); if (!instdir) { STRANGEPOINT; TRETURN isCompliant ? compName.c_str () : uncompName.c_str (); } std::string filename = instdir; filename += "\\share\\libkleopatrarc"; std::ifstream file(filename.c_str ()); if (!file.is_open ()) { log_err ("Failed to open '%s'", filename.c_str ()); TRETURN isCompliant ? compName.c_str () : uncompName.c_str (); } std::string line; bool in_de_vs_filter = false; bool in_not_de_vs_filter = false; const char *lname = gettext_localename (); /* lname is never null */ std::string localemain = gpgol_split (lname, '_')[0]; std::string idealname = std::string ("Name[") + localemain + std::string("]"); while (std::getline(file, line)) { if (starts_with (line, "[")) { in_de_vs_filter = false; in_not_de_vs_filter = false; continue; } if (starts_with (line, "id=de-vs-filter")) { in_de_vs_filter = true; continue; } if (starts_with (line, "id=not-de-vs-filter")) { in_not_de_vs_filter = true; continue; } if ((in_de_vs_filter || in_not_de_vs_filter) && starts_with (line, "Name")) { const auto split = gpgol_split (line, '='); if (split.size() != 2) { log_err ("Invalid libkleopatrarc line: %s", line.c_str()); continue; } if (split[0] == "Name") { if (in_de_vs_filter) { compName = split[1]; } else { uncompName = split[1]; } } if (split[0] == idealname) { log_dbg ("Found localized de-vs name %s", split[1].c_str ()); if (in_de_vs_filter) { compName = split[1]; } else { uncompName = split[1]; } } } } file.close(); TRETURN isCompliant ? compName.c_str () : uncompName.c_str (); } std::string compliance_string (bool forVerify, bool forDecrypt, bool isCompliant) { const char *comp_name = de_vs_name (isCompliant); if (forDecrypt && forVerify) { return asprintf_s (_("The message is %s."), comp_name); } if (forVerify) { /* TRANSLATORS %s is compliance name like VS-NfD */ return asprintf_s (_("The signature is %s."), comp_name); } if (forDecrypt) { /* TRANSLATORS %s is compliance name like VS-NfD */ return asprintf_s (_("The encryption is %s."), comp_name); } /* Should not happen */ log_err ("Invalid call to compliance string."); STRANGEPOINT; return std::string(); } diff --git a/src/common.h b/src/common.h index 1b9d063..839f675 100644 --- a/src/common.h +++ b/src/common.h @@ -1,159 +1,165 @@ /* common.h - Common declarations for GpgOL * Copyright (C) 2004 Timo Schulz * Copyright (C) 2005, 2006, 2007, 2008 g10 Code GmbH * Copyright (C) 2015, 2016 by Bundesamt für Sicherheit in der Informationstechnik * Software engineering by Intevation GmbH * * This file is part of GpgOL. * * GpgOL is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GpgOL 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 Lesser General Public License * along with this program; if not, see . */ #ifndef GPGOL_COMMON_H #define GPGOL_COMMON_H #ifdef HAVE_CONFIG_H #include #endif #include #include "common_indep.h" #include /* i18n stuff */ #include "w32-gettext.h" #define _(a) w32_gettext (a) #define N_(a) gettext_noop (a) /* Registry path to store plugin settings */ #define GPGOL_REGPATH "Software\\GNU\\GpgOL" #ifdef __cplusplus #include std::string readRegStr (const char *root, const char *dir, const char *name); namespace GpgME { class Data; } // namespace GpgME /* Read a file into a GpgME::Data object returns 0 on success */ int readFullFile (HANDLE hFile, GpgME::Data &data); extern "C" { #if 0 } #endif #endif extern HINSTANCE glob_hinst; extern UINT this_dll; /*-- common.c --*/ void set_global_hinstance (HINSTANCE hinst); char *get_data_dir (void); char *get_gpg4win_dir (void); int store_extension_value (const char *key, const char *val); int store_extension_subkey_value (const char *subkey, const char *key, const char *val); int load_extension_value (const char *key, char **val); /* Get a temporary filename with and its name */ wchar_t *get_tmp_outfile (const wchar_t *name, HANDLE *outHandle); char *get_tmp_outfile_utf8 (const char *name, HANDLE *outHandle); wchar_t *get_pretty_attachment_name (wchar_t *path, protocol_t protocol, int signature); /*-- verify-dialog.c --*/ int verify_dialog_box (gpgme_protocol_t protocol, gpgme_verify_result_t res, const char *filename); /*-- inspectors.cpp --*/ int initialize_inspectors (void); #if __GNUC__ >= 4 # define GPGOL_GCC_A_SENTINEL(a) __attribute__ ((sentinel(a))) #else # define GPGOL_GCC_A_SENTINEL(a) #endif /*-- common.c --*/ void fatal_error (const char *format, ...); char *read_w32_registry_string (const char *root, const char *dir, const char *name); char *percent_escape (const char *str, const char *extra); void fix_linebreaks (char *str, int *len); /* Format a date from gpgme (seconds since epoch) with windows system locale. */ char *format_date_from_gpgme (unsigned long time); /* Get the name of the uiserver */ char *get_uiserver_name (void); int is_elevated (void); /*-- main.c --*/ void read_options (void); int write_options (void); extern int g_ol_version_major; void bring_to_front (HWND wid); int gpgol_message_box (HWND parent, const char *utf8_text, const char *utf8_caption, UINT type); /* Show a bug message with the code. */ void gpgol_bug (HWND parent, int code); void i18n_init (void); #define ERR_CRYPT_RESOLVER_FAILED 1 #define ERR_WANTS_SEND_MIME_BODY 2 #define ERR_WANTS_SEND_INLINE_BODY 3 #define ERR_INLINE_BODY_TO_BODY 4 #define ERR_INLINE_BODY_INV_STATE 5 #define ERR_SEND_FALLBACK_FAILED 6 #define ERR_GET_BASE_MSG_FAILED 7 #define ERR_SPLIT_UNEXPECTED 8 #define ERR_SPLIT_RECIPIENTS 9 #ifdef __cplusplus } /* Check if we are in de_vs mode. */ bool in_de_vs_mode (); /* Get the name of the de_vs compliance mode as configured in libkleopatrarc */ const char *de_vs_name (bool isCompliant = false); /* Get a localized string of the compliance of an operation mode is the usual 1 encrypt, 2 sign. isCompliant if the value of the operation was compliant or not. */ std::string compliance_string (bool forVerify, bool forDecrypt, bool isCompliant); HANDLE CreateFileUtf8 (const char *utf8Name); + +/* Read a registry value from HKLM or HKCU of type dword and + return 1 if the value is larger then 0, 0 if it is zero and + -1 if it is not set or not found. */ +int +read_reg_bool (HKEY root, const char *path, const char *value); #endif #endif /*GPGOL_COMMON_H*/ diff --git a/src/gpgoladdin.cpp b/src/gpgoladdin.cpp index 0442781..f24fe54 100644 --- a/src/gpgoladdin.cpp +++ b/src/gpgoladdin.cpp @@ -1,1354 +1,1336 @@ /* gpgoladdin.cpp - Connect GpgOL to Outlook as an addin * Copyright (C) 2013 Intevation GmbH * 2015 by Bundesamt für Sicherheit in der Informationstechnik * Software engineering by Intevation GmbH * * This file is part of GpgOL. * * GpgOL is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * GpgOL 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see . */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include "common.h" #include "gpgoladdin.h" #include "mymapi.h" #include "mymapitags.h" #include "mapihelp.h" #include "oomhelp.h" #include "olflange.h" #include "gpgol-ids.h" #include "ribbon-callbacks.h" #include "eventsinks.h" #include "eventsink.h" #include "windowmessages.h" #include "mail.h" #include "addin-options.h" #include "cpphelp.h" #include "dispcache.h" #include "categorymanager.h" #include "keycache.h" #include #include #define ICON_SIZE_LARGE 32 #define ICON_SIZE_NORMAL 16 /* We use UTF-8 internally. */ #undef _ #define _(a) utf8_gettext (a) ULONG addinLocks = 0; bool can_unload = false; static GpgolAddin * addin_instance = NULL; /* This is the main entry point for the addin Outlook uses this function to query for an Object implementing the IClassFactory interface. */ STDAPI DllGetClassObject (REFCLSID rclsid, REFIID riid, LPVOID* ppvObj) { if (!ppvObj) return E_POINTER; *ppvObj = NULL; if (rclsid != CLSID_GPGOL) return CLASS_E_CLASSNOTAVAILABLE; /* Let the factory give the requested interface. */ GpgolAddinFactory* factory = new GpgolAddinFactory(); if (!factory) return E_OUTOFMEMORY; HRESULT hr = factory->QueryInterface (riid, ppvObj); if(FAILED(hr)) { *ppvObj = NULL; delete factory; } return hr; } STDAPI DllCanUnloadNow() { /* This is called regularly to check if memory can be freed by unloading the dll. The following unload will not call any addin methods like disconnect etc. It will just unload the Library. Any callbacks will become invalid. So we _only_ say it's ok to unload if we were disconnected. For the epic story behind the next line see GnuPG-Bug-Id 1837 */ TRACEPOINT; return can_unload ? S_OK : S_FALSE; } /* Class factory */ STDMETHODIMP GpgolAddinFactory::QueryInterface (REFIID riid, LPVOID* ppvObj) { HRESULT hr = S_OK; *ppvObj = NULL; if ((IID_IUnknown == riid) || (IID_IClassFactory == riid)) *ppvObj = static_cast(this); else { hr = E_NOINTERFACE; LPOLESTR sRiid = NULL; StringFromIID (riid, &sRiid); /* Should not happen */ log_debug ("GpgolAddinFactory queried for unknown interface: %S \n", sRiid); } if (*ppvObj) ((LPUNKNOWN)*ppvObj)->AddRef(); return hr; } /* This actually creates the instance of our COM object */ STDMETHODIMP GpgolAddinFactory::CreateInstance (LPUNKNOWN punk, REFIID riid, LPVOID* ppvObj) { (void)punk; *ppvObj = NULL; GpgolAddin* obj = GpgolAddin::get_instance(); if (NULL == obj) return E_OUTOFMEMORY; HRESULT hr = obj->QueryInterface (riid, ppvObj); if (FAILED(hr)) { LPOLESTR sRiid = NULL; StringFromIID (riid, &sRiid); fprintf(stderr, "failed to create instance for: %S", sRiid); } return hr; } GpgolAddinFactory::~GpgolAddinFactory() { log_debug ("%s:%s: Object deleted\n", SRCNAME, __func__); } /* GpgolAddin definition */ /* Constructor of GpgolAddin Initializes members and creates the interface objects for the new context. Does the DLL initialization if it has not been done before. The ref count is set by the factory after creation. */ GpgolAddin::GpgolAddin (void) : m_lRef(0), m_application(nullptr), m_addin(nullptr), m_applicationEventSink(nullptr), m_explorersEventSink(nullptr), m_disabled(false), m_shutdown(false), m_hook(nullptr), m_dispcache(new DispCache) { read_options (); /* RibbonExtender is it's own object to avoid the pitfalls of multiple inheritance */ m_ribbonExtender = new GpgolRibbonExtender(); } GpgolAddin::~GpgolAddin (void) { if (m_disabled) { return; } addin_instance = NULL; log_debug ("%s:%s: Object deleted\n", SRCNAME, __func__); } STDMETHODIMP GpgolAddin::QueryInterface (REFIID riid, LPVOID* ppvObj) { HRESULT hr = S_OK; *ppvObj = NULL; if (m_disabled) return E_NOINTERFACE; if ((riid == IID_IUnknown) || (riid == IID_IDTExtensibility2) || (riid == IID_IDispatch)) { *ppvObj = (LPUNKNOWN) this; } else if (riid == IID_IRibbonExtensibility) { return m_ribbonExtender->QueryInterface (riid, ppvObj); } else { hr = E_NOINTERFACE; #if 0 LPOLESTR sRiid = NULL; StringFromIID(riid, &sRiid); log_debug ("%s:%s: queried for unimplmented interface: %S", SRCNAME, __func__, sRiid); #endif } if (*ppvObj) ((LPUNKNOWN)*ppvObj)->AddRef(); return hr; } static void addGpgOLToReg (const std::string &path) { HKEY h; int err = RegOpenKeyEx (HKEY_CURRENT_USER, path.c_str(), 0, KEY_ALL_ACCESS, &h); if (err != ERROR_SUCCESS) { log_debug ("%s:%s: no DoNotDisableAddinList entry '%s' creating it", SRCNAME, __func__, path.c_str ()); err = RegCreateKeyEx (HKEY_CURRENT_USER, path.c_str (), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &h, NULL); } if (err != ERROR_SUCCESS) { log_error ("%s:%s: failed to create key.", SRCNAME, __func__); return; } DWORD type; err = RegQueryValueEx (h, GPGOL_PROGID, NULL, &type, NULL, NULL); if (err == ERROR_SUCCESS) { log_debug ("%s:%s: Found gpgol reg key. Leaving it unchanged.", SRCNAME, __func__); RegCloseKey (h); return; } // No key exists. Create one. DWORD dwTemp = 1; err = RegSetValueEx (h, GPGOL_PROGID, 0, REG_DWORD, (BYTE*)&dwTemp, 4); RegCloseKey (h); if (err != ERROR_SUCCESS) { log_error ("%s:%s: failed to set registry value.", SRCNAME, __func__); } else { log_debug ("%s:%s: added gpgol to %s", SRCNAME, __func__, path.c_str ()); } } /* This is a bit evil as we basically disable outlooks resiliency for us. But users are still able to manually disable the addon or change the donotdisable setting to zero and we won't change it. It has been much requested by users that we do this automatically. */ static void setupDoNotDisable () { std::string path = "Software\\Microsoft\\Office\\"; path += std::to_string (g_ol_version_major); path += ".0\\Outlook\\Resiliency\\DoNotDisableAddinList"; addGpgOLToReg (path); path = "Software\\Microsoft\\Office\\"; path += std::to_string (g_ol_version_major); path += ".0\\Outlook\\Resiliency\\AddinList"; addGpgOLToReg (path); } STDMETHODIMP GpgolAddin::OnConnection (LPDISPATCH Application, ext_ConnectMode ConnectMode, LPDISPATCH AddInInst, SAFEARRAY ** custom) { (void)custom; char* version; log_debug ("%s:%s: this is GpgOL %s\n", SRCNAME, __func__, PACKAGE_VERSION); m_shutdown = false; can_unload = false; m_application = Application; m_application->AddRef(); memdbg_addRef (m_application); m_addin = AddInInst; version = get_oom_string (Application, "Version"); log_debug ("%s:%s: using GPGME %s\n", SRCNAME, __func__, gpgme_check_version (NULL)); log_debug ("%s:%s: in Outlook %s\n", SRCNAME, __func__, version); g_ol_version_major = atoi (version); if (!version || !strlen (version) || (strncmp (version, "14", 2) && strncmp (version, "15", 2) && strncmp (version, "16", 2))) { m_disabled = true; log_debug ("%s:%s: Disabled addin for unsupported version.", SRCNAME, __func__); xfree (version); return S_OK; } xfree (version); setupDoNotDisable (); if (ConnectMode != ext_cm_Startup) { OnStartupComplete (custom); } return S_OK; } STDMETHODIMP GpgolAddin::OnDisconnection (ext_DisconnectMode RemoveMode, SAFEARRAY** custom) { (void)custom; (void)RemoveMode; log_debug ("%s:%s: cleaning up GpgolAddin object;", SRCNAME, __func__); /* Doing the wipe in the dtor is too late. Outlook does not allow us any OOM calls then and only returns "Unexpected error" in that case. Weird. */ shutdown (); can_unload = true; return S_OK; } STDMETHODIMP GpgolAddin::OnAddInsUpdate (SAFEARRAY** custom) { (void)custom; return S_OK; } void check_html_preferred() { /* Check if HTML Mail should be enabled. */ - HKEY h; - std::string path = "Software\\Microsoft\\Office\\"; - path += std::to_string (g_ol_version_major); - path += ".0\\Outlook\\Options\\Mail"; - opt.prefer_html = 1; - int err = RegOpenKeyEx (HKEY_CURRENT_USER, path.c_str() , 0, KEY_READ, &h); - if (err != ERROR_SUCCESS) + std::string path = "Software\\Microsoft\\Office\\" + + std::to_string (g_ol_version_major) + + ".0\\Outlook\\Options\\Mail"; + + int val = read_reg_bool (nullptr, path.c_str (), "ReadAsPlain"); + if (val == -1) { - log_debug ("%s:%s: no mail options under %s", - SRCNAME, __func__, path.c_str()); - return; + path = "Software\\policies\\Microsoft\\Office\\" + + std::to_string (g_ol_version_major) + + ".0\\Outlook\\Options\\Mail"; + val = read_reg_bool (nullptr, path.c_str (), "ReadAsPlain"); + } + if (val == -1) + { + opt.prefer_html = 1; } else { - DWORD type; - err = RegQueryValueEx (h, "ReadAsPlain", NULL, &type, NULL, NULL); - if (err != ERROR_SUCCESS || type != REG_DWORD) - { - log_debug ("%s:%s: No type or key for ReadAsPlain", - SRCNAME, __func__); - return; - } - else - { - DWORD data; - DWORD size = sizeof (DWORD); - err = RegQueryValueEx (h, "ReadAsPlain", NULL, NULL, (LPBYTE)&data, - &size); - if (err != ERROR_SUCCESS) - { - log_debug ("%s:%s: Failed to find out ReadAsPlain", - SRCNAME, __func__); - return; - } - opt.prefer_html = data ? 0 : 1; - return; - } + opt.prefer_html = !val; } } static LPDISPATCH install_explorer_sinks (LPDISPATCH application) { LPDISPATCH explorers = get_oom_object (application, "Explorers"); if (!explorers) { log_error ("%s:%s: No explorers object", SRCNAME, __func__); return nullptr; } int count = get_oom_int (explorers, "Count"); for (int i = 1; i <= count; i++) { std::string item = "Item("; item += std::to_string (i) + ")"; LPDISPATCH explorer = get_oom_object (explorers, item.c_str()); if (!explorer) { log_error ("%s:%s: failed to get explorer %i", SRCNAME, __func__, i); continue; } /* Explorers delete themself in the close event of the explorer. */ LPDISPATCH sink = install_ExplorerEvents_sink (explorer); if (!sink) { log_error ("%s:%s: failed to create eventsink for explorer %i", SRCNAME, __func__, i); } else { log_oom ("%s:%s: created sink %p for explorer %i", SRCNAME, __func__, sink, i); GpgolAddin::get_instance ()->registerExplorerSink (sink); } gpgol_release (explorer); } /* Now install the event sink to handle new explorers */ LPDISPATCH ret = install_ExplorersEvents_sink (explorers); gpgol_release (explorers); return ret; } static DWORD WINAPI init_gpgme_config (LPVOID) { /* This is a check we need to do anyway. GpgME++ caches the configuration once it is accessed for the first time so this call also initializes GpgME++ */ bool de_vs_mode = in_de_vs_mode (); log_debug ("%s:%s: init_gpgme_config de_vs_mode %i", SRCNAME, __func__, de_vs_mode); return 0; } STDMETHODIMP GpgolAddin::OnStartupComplete (SAFEARRAY** custom) { (void)custom; TRACEPOINT; i18n_init (); if (!create_responder_window()) { log_error ("%s:%s: Failed to create the responder window;", SRCNAME, __func__); } if (!m_application) { /* Should not happen as OnConnection should be called before */ log_error ("%s:%s: no application set;", SRCNAME, __func__); return E_NOINTERFACE; } if (!(m_hook = create_message_hook ())) { log_error ("%s:%s: Failed to create messagehook. ", SRCNAME, __func__); } /* Clean GpgOL prefixed categories. They might be left over from a crash or something unexpected error. We want to avoid pollution with the signed by categories. */ CategoryManager::removeAllGpgOLCategories (); install_forms (); m_applicationEventSink = install_ApplicationEvents_sink (m_application); m_explorersEventSink = install_explorer_sinks (m_application); check_html_preferred (); CloseHandle (CreateThread (NULL, 0, init_gpgme_config, nullptr, 0, NULL)); KeyCache::instance ()->populate (); return S_OK; } STDMETHODIMP GpgolAddin::OnBeginShutdown (SAFEARRAY * * custom) { (void)custom; TRACEPOINT; return S_OK; } STDMETHODIMP GpgolAddin::GetTypeInfoCount (UINT *r_count) { *r_count = 0; TRACEPOINT; /* Should not happen */ return S_OK; } STDMETHODIMP GpgolAddin::GetTypeInfo (UINT iTypeInfo, LCID lcid, LPTYPEINFO *r_typeinfo) { (void)iTypeInfo; (void)lcid; (void)r_typeinfo; TRACEPOINT; /* Should not happen */ return S_OK; } STDMETHODIMP GpgolAddin::GetIDsOfNames (REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { (void)riid; (void)rgszNames; (void)cNames; (void)lcid; (void)rgDispId; TRACEPOINT; /* Should not happen */ return E_NOINTERFACE; } STDMETHODIMP GpgolAddin::Invoke (DISPID dispid, REFIID riid, LCID lcid, WORD flags, DISPPARAMS *parms, VARIANT *result, EXCEPINFO *exepinfo, UINT *argerr) { USE_INVOKE_ARGS TRACEPOINT; /* Should not happen */ return DISP_E_MEMBERNOTFOUND; } /* Definition of GpgolRibbonExtender */ GpgolRibbonExtender::GpgolRibbonExtender (void) : m_lRef(0) { } GpgolRibbonExtender::~GpgolRibbonExtender (void) { log_debug ("%s:%s: cleaning up GpgolRibbonExtender object;", SRCNAME, __func__); memdbg_dump (); } STDMETHODIMP GpgolRibbonExtender::QueryInterface(REFIID riid, LPVOID* ppvObj) { HRESULT hr = S_OK; *ppvObj = NULL; if ((riid == IID_IUnknown) || (riid == IID_IRibbonExtensibility) || (riid == IID_IDispatch)) { *ppvObj = (LPUNKNOWN) this; } else { LPOLESTR sRiid = NULL; StringFromIID (riid, &sRiid); log_debug ("%s:%s: queried for unknown interface: %S", SRCNAME, __func__, sRiid); } if (*ppvObj) ((LPUNKNOWN)*ppvObj)->AddRef(); return hr; } STDMETHODIMP GpgolRibbonExtender::GetTypeInfoCount (UINT *r_count) { *r_count = 0; TRACEPOINT; /* Should not happen */ return S_OK; } STDMETHODIMP GpgolRibbonExtender::GetTypeInfo (UINT iTypeInfo, LCID lcid, LPTYPEINFO *r_typeinfo) { (void)iTypeInfo; (void)lcid; (void)r_typeinfo; TRACEPOINT; /* Should not happen */ return S_OK; } /* Good documentation of what this function is supposed to do can be found at: http://msdn.microsoft.com/en-us/library/cc237568.aspx There is also a very good blog explaining how Ribbon Extensibility is supposed to work. http://blogs.msdn.com/b/andreww/archive/2007/03/09/ why-is-it-so-hard-to-shim-iribbonextensibility.aspx */ #define ID_MAPPER(name,id) \ if (!wcscmp (rgszNames[i], name)) \ { \ found = true; \ rgDispId[i] = id; \ break; \ } \ STDMETHODIMP GpgolRibbonExtender::GetIDsOfNames (REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { (void)riid; (void)lcid; bool found = false; if (!rgszNames || !cNames || !rgDispId) { return E_POINTER; } for (unsigned int i = 0; i < cNames; i++) { log_debug ("%s:%s: GetIDsOfNames for: %S", SRCNAME, __func__, rgszNames[i]); /* How this is supposed to work with cNames > 1 is unknown, but we can just say that we won't support callbacks with different parameters and just match the name (the first element) and we give it one of our own dispIds's that are later handled in the invoke part */ ID_MAPPER (L"btnDecrypt", ID_BTN_DECRYPT) ID_MAPPER (L"btnDecryptLarge", ID_BTN_DECRYPT_LARGE) ID_MAPPER (L"btnEncrypt", ID_BTN_ENCRYPT) ID_MAPPER (L"btnEncryptLarge", ID_BTN_ENCRYPT_LARGE) ID_MAPPER (L"btnEncryptSmall", IDI_ENCRYPT_20_PNG) ID_MAPPER (L"btnSignSmall", IDI_SIGN_20_PNG) ID_MAPPER (L"btnSignEncryptLarge", IDI_SIGN_ENCRYPT_40_PNG) ID_MAPPER (L"btnEncryptFileLarge", ID_BTN_ENCSIGN_LARGE) ID_MAPPER (L"btnSignLarge", ID_BTN_SIGN_LARGE) ID_MAPPER (L"btnVerifyLarge", ID_BTN_VERIFY_LARGE) ID_MAPPER (L"btnSigstateLarge", ID_BTN_SIGSTATE_LARGE) /* MIME support: */ ID_MAPPER (L"encryptMime", ID_CMD_MIME_ENCRYPT) ID_MAPPER (L"encryptMimeEx", ID_CMD_MIME_ENCRYPT_EX) ID_MAPPER (L"signMime", ID_CMD_MIME_SIGN) ID_MAPPER (L"signMimeEx", ID_CMD_MIME_SIGN_EX) ID_MAPPER (L"encryptSignMime", ID_CMD_SIGN_ENCRYPT_MIME) ID_MAPPER (L"encryptSignMimeEx", ID_CMD_SIGN_ENCRYPT_MIME_EX) ID_MAPPER (L"getEncryptPressed", ID_GET_ENCRYPT_PRESSED) ID_MAPPER (L"getEncryptPressedEx", ID_GET_ENCRYPT_PRESSED_EX) ID_MAPPER (L"getSignPressed", ID_GET_SIGN_PRESSED) ID_MAPPER (L"getSignPressedEx", ID_GET_SIGN_PRESSED_EX) ID_MAPPER (L"getSignEncryptPressed", ID_GET_SIGN_ENCRYPT_PRESSED) ID_MAPPER (L"getSignEncryptPressedEx", ID_GET_SIGN_ENCRYPT_PRESSED_EX) ID_MAPPER (L"ribbonLoaded", ID_ON_LOAD) ID_MAPPER (L"openOptions", ID_CMD_OPEN_OPTIONS) ID_MAPPER (L"getSigLabel", ID_GET_SIG_LABEL) ID_MAPPER (L"getSigSTip", ID_GET_SIG_STIP) ID_MAPPER (L"getSigTip", ID_GET_SIG_TTIP) ID_MAPPER (L"launchDetails", ID_LAUNCH_CERT_DETAILS) ID_MAPPER (L"getIsDetailsEnabled", ID_GET_IS_DETAILS_ENABLED) ID_MAPPER (L"getIsAddrBookEnabled", ID_GET_IS_ADDR_BOOK_ENABLED) ID_MAPPER (L"getIsCrypto", ID_GET_IS_CRYPTO_MAIL) ID_MAPPER (L"openContactKey", ID_CMD_OPEN_CONTACT_KEY) ID_MAPPER (L"overrideFileClose", ID_CMD_FILE_CLOSE) ID_MAPPER (L"overrideFileSaveAs", ID_CMD_FILE_SAVE_AS) ID_MAPPER (L"overrideFileSaveAsWindowed", ID_CMD_FILE_SAVE_AS_IN_WINDOW) ID_MAPPER (L"decryptPermanently", ID_CMD_DECRYPT_PERMANENTLY) } if (cNames > 1) { log_debug ("More then one name provided. Should not happen"); } return found ? S_OK : E_NOINTERFACE; } STDMETHODIMP GpgolRibbonExtender::Invoke (DISPID dispid, REFIID riid, LCID lcid, WORD flags, DISPPARAMS *parms, VARIANT *result, EXCEPINFO *exepinfo, UINT *argerr) { USE_INVOKE_ARGS log_oom ("%s:%s: enter with dispid: %x", SRCNAME, __func__, (int)dispid); /* log_oom ("%s:%s: Parms: %s", SRCNAME, __func__, format_dispparams (parms).c_str ()); */ if (!(flags & DISPATCH_METHOD)) { log_debug ("%s:%s: not called in method mode. Bailing out.", SRCNAME, __func__); return DISP_E_MEMBERNOTFOUND; } switch (dispid) { case ID_CMD_SIGN_ENCRYPT_MIME: return mark_mime_action (parms->rgvarg[1].pdispVal, OP_SIGN|OP_ENCRYPT, false); case ID_CMD_SIGN_ENCRYPT_MIME_EX: return mark_mime_action (parms->rgvarg[1].pdispVal, OP_SIGN|OP_ENCRYPT, true); case ID_CMD_MIME_ENCRYPT: return mark_mime_action (parms->rgvarg[1].pdispVal, OP_ENCRYPT, false); case ID_CMD_MIME_SIGN: return mark_mime_action (parms->rgvarg[1].pdispVal, OP_SIGN, false); case ID_GET_ENCRYPT_PRESSED: return get_crypt_pressed (parms->rgvarg[0].pdispVal, OP_ENCRYPT, result, false); case ID_GET_SIGN_PRESSED: return get_crypt_pressed (parms->rgvarg[0].pdispVal, OP_SIGN, result, false); case ID_GET_SIGN_ENCRYPT_PRESSED: return get_crypt_pressed (parms->rgvarg[0].pdispVal, OP_SIGN | OP_ENCRYPT, result, false); case ID_CMD_MIME_SIGN_EX: return mark_mime_action (parms->rgvarg[1].pdispVal, OP_SIGN, true); case ID_CMD_MIME_ENCRYPT_EX: return mark_mime_action (parms->rgvarg[1].pdispVal, OP_ENCRYPT, true); case ID_GET_ENCRYPT_PRESSED_EX: return get_crypt_pressed (parms->rgvarg[0].pdispVal, OP_ENCRYPT, result, true); case ID_GET_SIGN_PRESSED_EX: return get_crypt_pressed (parms->rgvarg[0].pdispVal, OP_SIGN, result, true); case ID_GET_SIGN_ENCRYPT_PRESSED_EX: return get_crypt_pressed (parms->rgvarg[0].pdispVal, OP_SIGN | OP_ENCRYPT, result, true); case ID_GET_SIG_STIP: return get_sig_stip (parms->rgvarg[0].pdispVal, result); case ID_GET_SIG_TTIP: return get_sig_ttip (parms->rgvarg[0].pdispVal, result); case ID_GET_SIG_LABEL: return get_sig_label (parms->rgvarg[0].pdispVal, result); case ID_LAUNCH_CERT_DETAILS: return launch_cert_details (parms->rgvarg[0].pdispVal); case ID_GET_IS_DETAILS_ENABLED: return get_is_details_enabled (parms->rgvarg[0].pdispVal, result); case ID_GET_IS_ADDR_BOOK_ENABLED: return get_is_addr_book_enabled (parms->rgvarg[0].pdispVal, result); case ID_ON_LOAD: { GpgolAddin::get_instance ()->addRibbon (parms->rgvarg[0].pdispVal); return S_OK; } case ID_CMD_OPEN_OPTIONS: { options_dialog_box (NULL); return S_OK; } case ID_CMD_DECRYPT_PERMANENTLY: return decrypt_permanently (parms->rgvarg[0].pdispVal); case ID_GET_IS_CRYPTO_MAIL: return get_is_crypto_mail (parms->rgvarg[0].pdispVal, result); case ID_CMD_OPEN_CONTACT_KEY: return open_contact_key (parms->rgvarg[0].pdispVal); case ID_CMD_FILE_CLOSE : return override_file_close (); case ID_CMD_FILE_SAVE_AS: return override_file_save_as (parms); case ID_CMD_FILE_SAVE_AS_IN_WINDOW: return override_file_save_as_in_window (parms); case ID_BTN_ENCRYPT: case ID_BTN_DECRYPT: case ID_BTN_DECRYPT_LARGE: case ID_BTN_ENCRYPT_LARGE: case ID_BTN_ENCSIGN_LARGE: case ID_BTN_SIGN_LARGE: case ID_BTN_VERIFY_LARGE: case IDI_SIGN_ENCRYPT_40_PNG: case IDI_ENCRYPT_20_PNG: case IDI_SIGN_20_PNG: return getIcon (dispid, result); case ID_BTN_SIGSTATE_LARGE: return get_crypto_icon (parms->rgvarg[0].pdispVal, result); } log_debug ("%s:%s: leave", SRCNAME, __func__); return DISP_E_MEMBERNOTFOUND; } /* Returns the XML markup for the various RibbonID's The custom ui syntax is documented at: http://msdn.microsoft.com/en-us/library/dd926139%28v=office.12%29.aspx The outlook specific elements are documented at: http://msdn.microsoft.com/en-us/library/office/ee692172%28v=office.14%29.aspx */ static STDMETHODIMP GetCustomUI_MIME (BSTR RibbonID, BSTR * RibbonXml) { char * buffer = NULL; /* const char *certManagerTTip = _("Start the Certificate Management Software"); const char *certManagerSTip = _("Open GPA or Kleopatra to manage your certificates. " "You can use this you to generate your " "own certificates. ");*/ const char *encryptTTip = _("Encrypt the message"); const char *encryptSTip = _("Encrypts the message and all attachments before sending"); const char *signTTip = _("Sign the message"); const char *signSTip = _("Sign the message and all attachments before sending"); const char *secureTTip = _("Sign and encrypt the message"); const char *secureSTip = _("Encrypting and cryptographically signing a message means that the " "recipients can be sure that no one modified the message and only the " "recipients can read it"); const char *optsSTip = _("Open the settings dialog for GpgOL"); log_debug ("%s:%s: GetCustomUI_MIME for id: %ls", SRCNAME, __func__, RibbonID); if (!RibbonXml || !RibbonID) return E_POINTER; if (!wcscmp (RibbonID, L"Microsoft.Outlook.Mail.Compose")) { gpgrt_asprintf (&buffer, "" " " " " /* " " " " " " " " " " " " */ " " " " " " " " " " " " " " " " " " "