From af58213e6005cbf4b9ce8be2ad66eb6eae3df4a9 Mon Sep 17 00:00:00 2001 From: George Hazan Date: Sun, 16 Aug 2015 22:18:54 +0000 Subject: code cleaning git-svn-id: http://svn.miranda-ng.org/main/trunk@14974 1316c22d-e87f-b044-9b9b-93d7a3e3ba9c --- plugins/New_GPG/src/main.cpp | 3842 ++++++++++++++++++------------------- plugins/New_GPG/src/messages.cpp | 912 ++++----- plugins/New_GPG/src/options.cpp | 1459 +++++++------- plugins/New_GPG/src/utilities.cpp | 1130 +++++------ 4 files changed, 3385 insertions(+), 3958 deletions(-) diff --git a/plugins/New_GPG/src/main.cpp b/plugins/New_GPG/src/main.cpp index 9aab074d5a..3de785cc84 100755 --- a/plugins/New_GPG/src/main.cpp +++ b/plugins/New_GPG/src/main.cpp @@ -30,1253 +30,1152 @@ int itemnum = 0; HWND hwndList_g = NULL; BOOL CheckStateStoreDB(HWND hwndDlg, int idCtrl, const char* szSetting); -TCHAR key_id_global[17] = {0}; +TCHAR key_id_global[17] = { 0 }; -static INT_PTR CALLBACK DlgProcFirstRun(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam) +static INT_PTR CALLBACK DlgProcFirstRun(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { - HWND hwndList=GetDlgItem(hwndDlg, IDC_KEY_LIST); + HWND hwndList = GetDlgItem(hwndDlg, IDC_KEY_LIST); hwndList_g = hwndList; - LVCOLUMN col = {0}; - LVITEM item = {0}; - NMLISTVIEW * hdr = (NMLISTVIEW *) lParam; - TCHAR fp[16] = {0}; - switch (msg) - { - case WM_INITDIALOG: - { - SetWindowPos(hwndDlg, 0, firstrun_rect.left, firstrun_rect.top, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW); - TranslateDialogDefault(hwndDlg); - SetWindowText(hwndDlg, TranslateT("Set own key")); - EnableWindow(GetDlgItem(hwndDlg, IDC_COPY_PUBKEY), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_EXPORT_PRIVATE), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_CHANGE_PASSWD), 0); - col.pszText = _T("Key ID"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 50; - ListView_InsertColumn(hwndList, 0, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Email"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 1, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Name"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 250; - ListView_InsertColumn(hwndList, 2, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Creation date"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 3, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Expire date"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 4, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Key length"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 5, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Accounts"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 6, &col); - ListView_SetExtendedListViewStyleEx(hwndList, 0, LVS_EX_FULLROWSELECT); - int i = 1, iRow = 0; - { - item.mask = LVIF_TEXT; - item.iItem = i; - item.iSubItem = 0; - item.pszText = _T(""); - {//parse gpg output - string out; - DWORD code; - pxResult result; - wstring::size_type p = 0, p2 = 0, stop = 0; - { - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"--list-secret-keys"); - gpg_execution_params params(cmd); - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - { - break; - } - if(result == pxNotFound) - break; - } - while(p != string::npos) + LVITEM item = { 0 }; + TCHAR fp[16] = { 0 }; + switch (uMsg) { + case WM_INITDIALOG: + { + SetWindowPos(hwndDlg, 0, firstrun_rect.left, firstrun_rect.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); + TranslateDialogDefault(hwndDlg); + SetWindowText(hwndDlg, TranslateT("Set own key")); + EnableWindow(GetDlgItem(hwndDlg, IDC_COPY_PUBKEY), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_EXPORT_PRIVATE), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_CHANGE_PASSWD), 0); + + LVCOLUMN col = { 0 }; + col.pszText = _T("Key ID"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 50; + ListView_InsertColumn(hwndList, 0, &col); + + col.pszText = TranslateT("Email"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 1, &col); + + col.pszText = TranslateT("Name"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 250; + ListView_InsertColumn(hwndList, 2, &col); + + col.pszText = TranslateT("Creation date"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 3, &col); + + col.pszText = TranslateT("Expire date"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 4, &col); + + col.pszText = TranslateT("Key length"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 5, &col); + + col.pszText = TranslateT("Accounts"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 6, &col); + ListView_SetExtendedListViewStyleEx(hwndList, 0, LVS_EX_FULLROWSELECT); + int i = 1, iRow = 0; + { + item.mask = LVIF_TEXT; + item.iItem = i; + item.iSubItem = 0; + item.pszText = _T(""); { - if((p = out.find("sec ", p)) == string::npos) - break; - p += 5; - if(p < stop) - break; - stop = p; - p2 = out.find("/", p) - 1; - TCHAR *key_len = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()), *creation_date = NULL, *expire_date = NULL; - p2+=2; - p = out.find(" ", p2); - std::wstring key_id = toUTF16(out.substr(p2,p-p2)); - p += 1; - p2 = out.find(" ", p); - std::string::size_type p3 = out.find("\n", p); - if((p2 != std::string::npos) && (p3 < p2)) + //parse gpg output + string out; + DWORD code; + pxResult result; + wstring::size_type p = 0, p2 = 0, stop = 0; { - p2 = p3; - creation_date = mir_wstrdup(toUTF16(out.substr(p,p2-p-1)).c_str()); + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"--list-secret-keys"); + gpg_execution_params params(cmd); + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) + break; + if (result == pxNotFound) + break; } - else - { - creation_date = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - p2 = out.find("[", p2); - p2 = out.find("expires:", p2); - p2 += mir_strlen("expires:"); - if(p2 != std::string::npos) - { - p2++; - p = p2; - p2 = out.find("]", p); - expire_date = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - //check expiration - bool expired = false; - { - boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); - TCHAR buf[5]; - _tcsncpy_s(buf, expire_date, _TRUNCATE); - int year = _ttoi(buf); - if(year < now.date().year()) - expired = true; - else if(year == now.date().year()) + while (p != string::npos) { + if ((p = out.find("sec ", p)) == string::npos) + break; + p += 5; + if (p < stop) + break; + stop = p; + p2 = out.find("/", p) - 1; + TCHAR *key_len = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()), *creation_date = NULL, *expire_date = NULL; + p2 += 2; + p = out.find(" ", p2); + std::wstring key_id = toUTF16(out.substr(p2, p - p2)); + p += 1; + p2 = out.find(" ", p); + std::string::size_type p3 = out.find("\n", p); + if ((p2 != std::string::npos) && (p3 < p2)) { + p2 = p3; + creation_date = mir_wstrdup(toUTF16(out.substr(p, p2 - p - 1)).c_str()); + } + else { + creation_date = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + p2 = out.find("[", p2); + p2 = out.find("expires:", p2); + p2 += mir_strlen("expires:"); + if (p2 != std::string::npos) { + p2++; + p = p2; + p2 = out.find("]", p); + expire_date = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + //check expiration + bool expired = false; { - _tcsncpy_s(buf, (expire_date + 5), _TRUNCATE); - int month = _ttoi(buf); - if(month < now.date().month()) + boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); + TCHAR buf[5]; + _tcsncpy_s(buf, expire_date, _TRUNCATE); + int year = _ttoi(buf); + if (year < now.date().year()) expired = true; - else if(month == now.date().month()) { - _tcsncpy_s(buf, (expire_date + 8), _TRUNCATE); - unsigned day = _ttoi(buf); - if(day <= now.date().day_number()) + else if (year == now.date().year()) { + _tcsncpy_s(buf, (expire_date + 5), _TRUNCATE); + int month = _ttoi(buf); + if (month < now.date().month()) expired = true; + else if (month == now.date().month()) { + _tcsncpy_s(buf, (expire_date + 8), _TRUNCATE); + unsigned day = _ttoi(buf); + if (day <= now.date().day_number()) + expired = true; + } } } - } - if(expired) - { - mir_free(key_len); - mir_free(creation_date); - mir_free(expire_date); - //mimic normal behaviour - p = out.find("uid ", p); - p2 = out.find_first_not_of(" ", p+5); - p = out.find("<", p2); - p++; - //p2 = out.find(">", p); - // - continue; //does not add to key list + if (expired) { + mir_free(key_len); + mir_free(creation_date); + mir_free(expire_date); + //mimic normal behaviour + p = out.find("uid ", p); + p2 = out.find_first_not_of(" ", p + 5); + p = out.find("<", p2); + p++; + //p2 = out.find(">", p); + // + continue; //does not add to key list + } } } - } - iRow = ListView_InsertItem(hwndList, &item); - ListView_SetItemText(hwndList, iRow, 3, creation_date); - mir_free(creation_date); - if(expire_date) - { - ListView_SetItemText(hwndList, iRow, 4, expire_date); - mir_free(expire_date); - } - ListView_SetItemText(hwndList, iRow, 5, key_len); - mir_free(key_len); - ListView_SetItemText(hwndList, iRow, 0, (TCHAR*)key_id.c_str()); - p = out.find("uid ", p); - p2 = out.find_first_not_of(" ", p+5); - p = out.find("<", p2); - TCHAR *tmp = mir_wstrdup(toUTF16(out.substr(p2,p-p2)).c_str()); - ListView_SetItemText(hwndList, iRow, 2, tmp); - mir_free(tmp); - p++; - p2 = out.find(">", p); - tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - ListView_SetItemText(hwndList, iRow, 1, tmp); - mir_free(tmp); - { //get accounts + iRow = ListView_InsertItem(hwndList, &item); + ListView_SetItemText(hwndList, iRow, 3, creation_date); + mir_free(creation_date); + if (expire_date) { + ListView_SetItemText(hwndList, iRow, 4, expire_date); + mir_free(expire_date); + } + ListView_SetItemText(hwndList, iRow, 5, key_len); + mir_free(key_len); + ListView_SetItemText(hwndList, iRow, 0, (TCHAR*)key_id.c_str()); + p = out.find("uid ", p); + p2 = out.find_first_not_of(" ", p + 5); + p = out.find("<", p2); + + wstring tmp = toUTF16(out.substr(p2, p - p2)); + ListView_SetItemText(hwndList, iRow, 2, (TCHAR*)tmp.c_str()); + + p++; + p2 = out.find(">", p); + + tmp = toUTF16(out.substr(p, p2 - p)); + ListView_SetItemText(hwndList, iRow, 1, (TCHAR*)tmp.c_str()); + + // get accounts int count = 0; PROTOACCOUNT **accounts; Proto_EnumAccounts(&count, &accounts); std::wstring accs; - for(int i = 0; i < count; i++) - { - std::string setting = toUTF8(accounts[i]->tszAccountName); + for (int n = 0; n < count; n++) { + std::string setting = toUTF8(accounts[n]->tszAccountName); setting += "("; - setting += accounts[i]->szModuleName; - setting += ")" ; + setting += accounts[n]->szModuleName; + setting += ")"; setting += "_KeyID"; TCHAR *str = UniGetContactSettingUtf(NULL, szGPGModuleName, setting.c_str(), _T("")); - if(key_id == str) - { - if(accs.empty()) - accs += accounts[i]->tszAccountName; - else - { + if (key_id == str) { + if (!accs.empty()) accs += _T(","); - accs += accounts[i]->tszAccountName; - } + accs += accounts[n]->tszAccountName; } mir_free(str); } ListView_SetItemText(hwndList, iRow, 6, (TCHAR*)accs.c_str()); } i++; + + ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 5, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 6, LVSCW_AUTOSIZE); } - ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 5, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 6, LVSCW_AUTOSIZE); } - } - { - SendDlgItemMessageA(hwndDlg, IDC_ACCOUNT, CB_ADDSTRING, 0, (LPARAM)Translate("Default")); - int count = 0; - PROTOACCOUNT **accounts; - Proto_EnumAccounts(&count, &accounts); - for(int i = 0; i < count; i++) { - if(StriStr(accounts[i]->szModuleName, "metacontacts")) - continue; - if(StriStr(accounts[i]->szModuleName, "weather")) - continue; - std::string acc = toUTF8(accounts[i]->tszAccountName); - acc += "("; - acc += accounts[i]->szModuleName; - acc += ")"; - //acc += "_KeyID"; - SendDlgItemMessageA(hwndDlg, IDC_ACCOUNT, CB_ADDSTRING, 0, (LPARAM)acc.c_str()); + SendDlgItemMessageA(hwndDlg, IDC_ACCOUNT, CB_ADDSTRING, 0, (LPARAM)Translate("Default")); + int count = 0; + PROTOACCOUNT **accounts; + Proto_EnumAccounts(&count, &accounts); + for (int n = 0; n < count; n++) { + if (StriStr(accounts[n]->szModuleName, "metacontacts")) + continue; + if (StriStr(accounts[n]->szModuleName, "weather")) + continue; + std::string acc = toUTF8(accounts[n]->tszAccountName); + acc += "("; + acc += accounts[n]->szModuleName; + acc += ")"; + //acc += "_KeyID"; + SendDlgItemMessageA(hwndDlg, IDC_ACCOUNT, CB_ADDSTRING, 0, (LPARAM)acc.c_str()); + } + SendDlgItemMessageA(hwndDlg, IDC_ACCOUNT, CB_SELECTSTRING, 0, (LPARAM)Translate("Default")); + string keyinfo = Translate("key ID"); + keyinfo += ": "; + char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); + keyinfo += (mir_strlen(keyid) > 0) ? keyid : Translate("not set"); + mir_free(keyid); + SetDlgItemTextA(hwndDlg, IDC_KEY_ID, keyinfo.c_str()); } - SendDlgItemMessageA(hwndDlg, IDC_ACCOUNT, CB_SELECTSTRING, 0, (LPARAM)Translate("Default")); - string keyinfo = Translate("key ID"); - keyinfo += ": "; - char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); - keyinfo += (mir_strlen(keyid) > 0)?keyid:Translate("not set"); - mir_free(keyid); - SetDlgItemTextA(hwndDlg, IDC_KEY_ID, keyinfo.c_str()); } return TRUE; - } - - - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDC_GENERATE_KEY: - void ShowKeyGenDialog(); - ShowKeyGenDialog(); - break; - case ID_OK: - { - ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); - TCHAR *name = new TCHAR [64]; - ListView_GetItemText(hwndList, itemnum, 2, name, 64); - { - if(_tcschr(name, _T('('))) - { - wstring str = name; - wstring::size_type p = str.find(_T("("))-1; - mir_tstrcpy(name, str.substr(0, p).c_str()); - } - } - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"-a"); - cmd.push_back(L"--export"); - cmd.push_back(fp); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - { - break; - } - if(result == pxNotFound) - break; - - boost::algorithm::erase_all(out, "\r"); - { - char buf[64]; - GetDlgItemTextA(hwndDlg, IDC_ACCOUNT, buf, _countof(buf)); - if(!mir_strcmp(buf, Translate("Default"))) - { - db_set_s(NULL, szGPGModuleName, "GPGPubKey", out.c_str()); - db_set_ts(NULL, szGPGModuleName, "KeyMainName", name); - db_set_ts(NULL, szGPGModuleName, "KeyID", fp); - } - else - { - std::string acc_str = buf; - acc_str += "_GPGPubKey"; - db_set_s(NULL, szGPGModuleName, acc_str.c_str(), out.c_str()); - acc_str = buf; - acc_str += "_KeyMainName"; - db_set_ts(NULL, szGPGModuleName, acc_str.c_str(), name); - acc_str = buf; - acc_str += "_KeyID"; - db_set_ts(NULL, szGPGModuleName, acc_str.c_str(), fp); - } - if(!mir_strcmp(buf, Translate("Default"))) - { - wstring keyinfo = TranslateT("Default private key ID"); - keyinfo += _T(": "); - keyinfo += (fp[0])?fp:_T("not set"); - extern HWND hwndCurKey_p; - SetWindowText(hwndCurKey_p, keyinfo.c_str()); - } - } - TCHAR passwd[64]; - GetDlgItemText(hwndDlg, IDC_KEY_PASSWORD, passwd, _countof(passwd)); - if(passwd[0]) - { - string dbsetting = "szKey_"; - char *keyid = mir_t2a(fp); - dbsetting += keyid; - mir_free(keyid); - dbsetting += "_Password"; - db_set_ts(NULL, szGPGModuleName, dbsetting.c_str(), passwd); - } - delete [] name; - } - bAutoExchange = CheckStateStoreDB(hwndDlg, IDC_AUTO_EXCHANGE, "bAutoExchange") != 0; - gpg_valid = isGPGValid(); - gpg_keyexist = isGPGKeyExist(); - DestroyWindow(hwndDlg); - break; - case IDC_OTHER: - { - void ShowLoadPublicKeyDialog(); - item_num = 0; //black magic here - user_data[1] = 0; - ShowLoadPublicKeyDialog(); - ListView_DeleteAllItems(hwndList); - { - int i = 1, iRow = 0; - item.mask = LVIF_TEXT; - item.iItem = i; - item.iSubItem = 0; - item.pszText = _T(""); - {//parse gpg output - string out; - DWORD code; - wstring::size_type p = 0, p2 = 0, stop = 0; - { - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"--list-secret-keys"); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - { - break; - } - if(result == pxNotFound) - break; - } - while(p != string::npos) - { - if((p = out.find("sec ", p)) == string::npos) - break; - p += 5; - if(p < stop) - break; - stop = p; - p2 = out.find("/", p) - 1; - TCHAR *tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - item.pszText = tmp; - iRow = ListView_InsertItem(hwndList, &item); - ListView_SetItemText(hwndList, iRow, 4, tmp); - mir_free(tmp); - p2+=2; - p = out.find(" ", p2); - tmp = mir_wstrdup(toUTF16(out.substr(p2,p-p2)).c_str()); - ListView_SetItemText(hwndList, iRow, 0, tmp); - mir_free(tmp); - p = out.find("uid ", p); - p2 = out.find_first_not_of(" ", p+5); - p = out.find("<", p2); - tmp = mir_wstrdup(toUTF16(out.substr(p2,p-p2)).c_str()); - ListView_SetItemText(hwndList, iRow, 2, tmp); - mir_free(tmp); - p++; - p2 = out.find(">", p); - tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - ListView_SetItemText(hwndList, iRow, 1, tmp); - mir_free(tmp); - p = out.find("ssb ", p2) + 6; - p = out.find(" ", p) + 1; - p2 = out.find("\n", p); - tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p-1)).c_str()); - ListView_SetItemText(hwndList, iRow, 3, tmp); - mir_free(tmp); - ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE);// not sure about this - ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); - i++; - } - } - } - } - break; - case IDC_DELETE_KEY: - ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); - { - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"--fingerprint"); - cmd.push_back(fp); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - { - break; - } - if(result == pxNotFound) - break; - string::size_type s = out.find("Key fingerprint = "); - s += mir_strlen("Key fingerprint = "); - string::size_type s2 = out.find("\n", s); - TCHAR *fp = NULL; - { - string tmp = out.substr(s, s2-s-1).c_str(); - string::size_type p = 0; - while((p = tmp.find(" ", p)) != string::npos) - { - tmp.erase(p, 1); - } - fp = mir_a2t(tmp.c_str()); - } - cmd.clear(); - out.clear(); - cmd.push_back(L"--batch"); - cmd.push_back(L"--delete-secret-and-public-key"); - cmd.push_back(L"--fingerprint"); - cmd.push_back(fp); - mir_free(fp); - if(!gpg_launcher(params)) - { - break; - } - if(result == pxNotFound) - break; - } - { - char buf[64]; - GetDlgItemTextA(hwndDlg, IDC_ACCOUNT, buf, _countof(buf)); - if(!mir_strcmp(buf, Translate("Default"))) - { - db_unset(NULL, szGPGModuleName, "GPGPubKey"); - db_unset(NULL, szGPGModuleName, "KeyID"); - db_unset(NULL, szGPGModuleName, "KeyComment"); - db_unset(NULL, szGPGModuleName, "KeyMainName"); - db_unset(NULL, szGPGModuleName, "KeyMainEmail"); - db_unset(NULL, szGPGModuleName, "KeyType"); - } - else - { - std::string acc_str = buf; - acc_str += "_GPGPubKey"; - db_unset(NULL, szGPGModuleName, acc_str.c_str()); - acc_str = buf; - acc_str += "_KeyMainName"; - db_unset(NULL, szGPGModuleName, acc_str.c_str()); - acc_str = buf; - acc_str += "_KeyID"; - db_unset(NULL, szGPGModuleName, acc_str.c_str()); - acc_str = buf; - acc_str += "_KeyComment"; - db_unset(NULL, szGPGModuleName, acc_str.c_str()); - acc_str = buf; - acc_str += "_KeyMainEmail"; - db_unset(NULL, szGPGModuleName, acc_str.c_str()); - acc_str = buf; - acc_str += "_KeyType"; - db_unset(NULL, szGPGModuleName, acc_str.c_str()); - } - } - ListView_DeleteItem(hwndList, itemnum); - break; - case IDC_GENERATE_RANDOM: - { - wstring path; - { //generating key file - TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - path = tmp; - mir_free(tmp); - path.append(_T("\\new_key")); - wfstream f(path.c_str(), std::ios::out); - if(!f.is_open()) - { - MessageBox(0, TranslateT("Failed to open file"), TranslateT("Error"), MB_OK); - break; - } - f<<"Key-Type: RSA"; - f<<"\n"; - f<<"Key-Length: 4096"; - f<<"\n"; - f<<"Subkey-Type: RSA"; - f<<"\n"; - f<<"Name-Real: "; - f< cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"--yes"); - cmd.push_back(L"--gen-key"); - cmd.push_back(path); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - extern HFONT bold_font; - SendDlgItemMessage(hwndDlg, IDC_GENERATING_KEY, WM_SETFONT, (WPARAM)bold_font, TRUE); - SetDlgItemText(hwndDlg, IDC_GENERATING_KEY, TranslateT("Generating new random key, please wait")); - EnableWindow(GetDlgItem(hwndDlg, IDC_GENERATE_KEY), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_OTHER), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_DELETE_KEY), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_LIST), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_GENERATE_RANDOM), 0); - if(!gpg_launcher(params, boost::posix_time::minutes(10))) - { - break; - } - if(result == pxNotFound) - break; - boost::filesystem::remove(path); - string::size_type p1 = 0; - if((p1 = out.find("key ")) != string::npos) - path = toUTF16(out.substr(p1+4, 8)); - else - path.clear(); - } - if(!path.empty()) - { - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"-a"); - cmd.push_back(L"--export"); - cmd.push_back(path); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - { - break; - } - if(result == pxNotFound) - break; - string::size_type s = 0; - while((s = out.find("\r", s)) != string::npos) - { - out.erase(s, 1); - } - { - char buf[64]; - GetDlgItemTextA(hwndDlg, IDC_ACCOUNT, buf, _countof(buf)); - if(!mir_strcmp(buf, Translate("Default"))) - { - db_set_s(NULL, szGPGModuleName, "GPGPubKey", out.c_str()); - db_set_ts(NULL, szGPGModuleName, "KeyID", fp); - } - else - { - std::string acc_str = buf; - acc_str += "_GPGPubKey"; - db_set_s(NULL, szGPGModuleName, acc_str.c_str(), out.c_str()); - acc_str = buf; - acc_str += "_KeyID"; - db_set_ts(NULL, szGPGModuleName, acc_str.c_str(), fp); - } - } - extern HWND hwndCurKey_p; - SetWindowText(hwndCurKey_p, path.c_str()); - } - } - DestroyWindow(hwndDlg); - break; - case IDC_ACCOUNT: + case WM_COMMAND: + switch (LOWORD(wParam)) { + case IDC_GENERATE_KEY: + void ShowKeyGenDialog(); + ShowKeyGenDialog(); + break; + case ID_OK: + { + ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); + TCHAR *name = new TCHAR[64]; + ListView_GetItemText(hwndList, itemnum, 2, name, 64); + { + if (_tcschr(name, _T('('))) { + wstring str = name; + wstring::size_type p = str.find(_T("(")) - 1; + mir_tstrcpy(name, str.substr(0, p).c_str()); + } + } + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"-a"); + cmd.push_back(L"--export"); + cmd.push_back(fp); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) { + break; + } + if (result == pxNotFound) + break; + + boost::algorithm::erase_all(out, "\r"); + { + char buf[64]; + GetDlgItemTextA(hwndDlg, IDC_ACCOUNT, buf, _countof(buf)); + if (!mir_strcmp(buf, Translate("Default"))) { + db_set_s(NULL, szGPGModuleName, "GPGPubKey", out.c_str()); + db_set_ts(NULL, szGPGModuleName, "KeyMainName", name); + db_set_ts(NULL, szGPGModuleName, "KeyID", fp); + } + else { + std::string acc_str = buf; + acc_str += "_GPGPubKey"; + db_set_s(NULL, szGPGModuleName, acc_str.c_str(), out.c_str()); + acc_str = buf; + acc_str += "_KeyMainName"; + db_set_ts(NULL, szGPGModuleName, acc_str.c_str(), name); + acc_str = buf; + acc_str += "_KeyID"; + db_set_ts(NULL, szGPGModuleName, acc_str.c_str(), fp); + } + if (!mir_strcmp(buf, Translate("Default"))) { + wstring keyinfo = TranslateT("Default private key ID"); + keyinfo += _T(": "); + keyinfo += (fp[0]) ? fp : _T("not set"); + extern HWND hwndCurKey_p; + SetWindowText(hwndCurKey_p, keyinfo.c_str()); + } + } + TCHAR passwd[64]; + GetDlgItemText(hwndDlg, IDC_KEY_PASSWORD, passwd, _countof(passwd)); + if (passwd[0]) { + string dbsetting = "szKey_"; + char *keyid = mir_t2a(fp); + dbsetting += keyid; + mir_free(keyid); + dbsetting += "_Password"; + db_set_ts(NULL, szGPGModuleName, dbsetting.c_str(), passwd); + } + delete[] name; + } + bAutoExchange = CheckStateStoreDB(hwndDlg, IDC_AUTO_EXCHANGE, "bAutoExchange") != 0; + gpg_valid = isGPGValid(); + gpg_keyexist = isGPGKeyExist(); + DestroyWindow(hwndDlg); + break; + case IDC_OTHER: + { + void ShowLoadPublicKeyDialog(); + item_num = 0; //black magic here + user_data[1] = 0; + ShowLoadPublicKeyDialog(); + ListView_DeleteAllItems(hwndList); + { + int i = 1, iRow = 0; + item.mask = LVIF_TEXT; + item.iItem = i; + item.iSubItem = 0; + item.pszText = _T(""); + {//parse gpg output + string out; + DWORD code; + wstring::size_type p = 0, p2 = 0, stop = 0; + { + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"--list-secret-keys"); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) { + break; + } + if (result == pxNotFound) + break; + } + while (p != string::npos) { + if ((p = out.find("sec ", p)) == string::npos) + break; + p += 5; + if (p < stop) + break; + stop = p; + p2 = out.find("/", p) - 1; + TCHAR *tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + item.pszText = tmp; + iRow = ListView_InsertItem(hwndList, &item); + ListView_SetItemText(hwndList, iRow, 4, tmp); + mir_free(tmp); + p2 += 2; + p = out.find(" ", p2); + tmp = mir_wstrdup(toUTF16(out.substr(p2, p - p2)).c_str()); + ListView_SetItemText(hwndList, iRow, 0, tmp); + mir_free(tmp); + p = out.find("uid ", p); + p2 = out.find_first_not_of(" ", p + 5); + p = out.find("<", p2); + tmp = mir_wstrdup(toUTF16(out.substr(p2, p - p2)).c_str()); + ListView_SetItemText(hwndList, iRow, 2, tmp); + mir_free(tmp); + p++; + p2 = out.find(">", p); + tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + ListView_SetItemText(hwndList, iRow, 1, tmp); + mir_free(tmp); + p = out.find("ssb ", p2) + 6; + p = out.find(" ", p) + 1; + p2 = out.find("\n", p); + tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p - 1)).c_str()); + ListView_SetItemText(hwndList, iRow, 3, tmp); + mir_free(tmp); + ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE);// not sure about this + ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); + i++; + } + } + } + } + break; + case IDC_DELETE_KEY: + ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); + { + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"--fingerprint"); + cmd.push_back(fp); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) + break; + if (result == pxNotFound) + break; + string::size_type s = out.find("Key fingerprint = "); + s += mir_strlen("Key fingerprint = "); + string::size_type s2 = out.find("\n", s); + TCHAR *str = NULL; + { + string tmp = out.substr(s, s2 - s - 1).c_str(); + string::size_type p = 0; + while ((p = tmp.find(" ", p)) != string::npos) + tmp.erase(p, 1); + + str = mir_a2t(tmp.c_str()); + } + cmd.clear(); + out.clear(); + cmd.push_back(L"--batch"); + cmd.push_back(L"--delete-secret-and-public-key"); + cmd.push_back(L"--fingerprint"); + cmd.push_back(str); + mir_free(str); + if (!gpg_launcher(params)) + break; + if (result == pxNotFound) + break; + } { char buf[64]; GetDlgItemTextA(hwndDlg, IDC_ACCOUNT, buf, _countof(buf)); - if(!mir_strcmp(buf, Translate("Default"))) + if (!mir_strcmp(buf, Translate("Default"))) { + db_unset(NULL, szGPGModuleName, "GPGPubKey"); + db_unset(NULL, szGPGModuleName, "KeyID"); + db_unset(NULL, szGPGModuleName, "KeyComment"); + db_unset(NULL, szGPGModuleName, "KeyMainName"); + db_unset(NULL, szGPGModuleName, "KeyMainEmail"); + db_unset(NULL, szGPGModuleName, "KeyType"); + } + else { + std::string acc_str = buf; + acc_str += "_GPGPubKey"; + db_unset(NULL, szGPGModuleName, acc_str.c_str()); + acc_str = buf; + acc_str += "_KeyMainName"; + db_unset(NULL, szGPGModuleName, acc_str.c_str()); + acc_str = buf; + acc_str += "_KeyID"; + db_unset(NULL, szGPGModuleName, acc_str.c_str()); + acc_str = buf; + acc_str += "_KeyComment"; + db_unset(NULL, szGPGModuleName, acc_str.c_str()); + acc_str = buf; + acc_str += "_KeyMainEmail"; + db_unset(NULL, szGPGModuleName, acc_str.c_str()); + acc_str = buf; + acc_str += "_KeyType"; + db_unset(NULL, szGPGModuleName, acc_str.c_str()); + } + } + ListView_DeleteItem(hwndList, itemnum); + break; + case IDC_GENERATE_RANDOM: + { + wstring path; { - string keyinfo = Translate("key ID"); - keyinfo += ": "; - char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); - keyinfo += (mir_strlen(keyid) > 0)?keyid:Translate("not set"); - mir_free(keyid); - SetDlgItemTextA(hwndDlg, IDC_KEY_ID, keyinfo.c_str()); + // generating key file + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + path = tmp; + mir_free(tmp); + path.append(_T("\\new_key")); + wfstream f(path.c_str(), std::ios::out); + if (!f.is_open()) { + MessageBox(0, TranslateT("Failed to open file"), TranslateT("Error"), MB_OK); + break; + } + f << "Key-Type: RSA"; + f << "\n"; + f << "Key-Length: 4096"; + f << "\n"; + f << "Subkey-Type: RSA"; + f << "\n"; + f << "Name-Real: "; + f << get_random(6).c_str(); + f << "\n"; + f << "Name-Email: "; + f << get_random(5).c_str(); + f << "@"; + f << get_random(5).c_str(); + f << "."; + f << get_random(3).c_str(); + f << "\n"; + f.close(); + } + { // gpg execution + DWORD code; + string out; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"--yes"); + cmd.push_back(L"--gen-key"); + cmd.push_back(path); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + extern HFONT bold_font; + SendDlgItemMessage(hwndDlg, IDC_GENERATING_KEY, WM_SETFONT, (WPARAM)bold_font, TRUE); + SetDlgItemText(hwndDlg, IDC_GENERATING_KEY, TranslateT("Generating new random key, please wait")); + EnableWindow(GetDlgItem(hwndDlg, IDC_GENERATE_KEY), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_OTHER), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_DELETE_KEY), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_LIST), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_GENERATE_RANDOM), 0); + if (!gpg_launcher(params, boost::posix_time::minutes(10))) + break; + if (result == pxNotFound) + break; + + boost::filesystem::remove(path); + string::size_type p1 = 0; + if ((p1 = out.find("key ")) != string::npos) + path = toUTF16(out.substr(p1 + 4, 8)); + else + path.clear(); + } + if (!path.empty()) { + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"-a"); + cmd.push_back(L"--export"); + cmd.push_back(path); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) { + break; + } + if (result == pxNotFound) + break; + string::size_type s = 0; + while ((s = out.find("\r", s)) != string::npos) { + out.erase(s, 1); + } + { + char buf[64]; + GetDlgItemTextA(hwndDlg, IDC_ACCOUNT, buf, _countof(buf)); + if (!mir_strcmp(buf, Translate("Default"))) { + db_set_s(NULL, szGPGModuleName, "GPGPubKey", out.c_str()); + db_set_ts(NULL, szGPGModuleName, "KeyID", fp); + } + else { + std::string acc_str = buf; + acc_str += "_GPGPubKey"; + db_set_s(NULL, szGPGModuleName, acc_str.c_str(), out.c_str()); + acc_str = buf; + acc_str += "_KeyID"; + db_set_ts(NULL, szGPGModuleName, acc_str.c_str(), fp); + } + } + extern HWND hwndCurKey_p; + SetWindowText(hwndCurKey_p, path.c_str()); + } + } + DestroyWindow(hwndDlg); + break; + + case IDC_ACCOUNT: + char buf[64]; + GetDlgItemTextA(hwndDlg, IDC_ACCOUNT, buf, _countof(buf)); + if (!mir_strcmp(buf, Translate("Default"))) { + string keyinfo = Translate("key ID"); + keyinfo += ": "; + char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); + keyinfo += (mir_strlen(keyid) > 0) ? keyid : Translate("not set"); + mir_free(keyid); + SetDlgItemTextA(hwndDlg, IDC_KEY_ID, keyinfo.c_str()); + } + else { + string keyinfo = Translate("key ID"); + keyinfo += ": "; + std::string acc_str = buf; + acc_str += "_KeyID"; + char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, acc_str.c_str(), ""); + keyinfo += (mir_strlen(keyid) > 0) ? keyid : Translate("not set"); + mir_free(keyid); + SetDlgItemTextA(hwndDlg, IDC_KEY_ID, keyinfo.c_str()); + } + break; + + case IDC_COPY_PUBKEY: + if (OpenClipboard(hwndDlg)) { + ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"-a"); + cmd.push_back(L"--export"); + cmd.push_back(fp); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) + break; + if (result == pxNotFound) + break; + boost::algorithm::erase_all(out, "\r"); + HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, out.size() + 1); + if (!hMem) { + MessageBox(0, TranslateT("Failed to allocate memory"), TranslateT("Error"), MB_OK); + break; + } + char *szKey = (char*)GlobalLock(hMem); + if (!szKey) { + TCHAR msg[64]; + mir_sntprintf(msg, TranslateT("Failed to lock memory with error %d"), GetLastError()); + MessageBox(0, msg, TranslateT("Error"), MB_OK); + GlobalFree(hMem); + } + memcpy(szKey, out.c_str(), out.size()); + szKey[out.size()] = '\0'; + EmptyClipboard(); + GlobalUnlock(hMem); + if (!SetClipboardData(CF_OEMTEXT, hMem)) { + GlobalFree(hMem); + TCHAR msg[64]; + mir_sntprintf(msg, TranslateT("Failed write to clipboard with error %d"), GetLastError()); + MessageBox(0, msg, TranslateT("Error"), MB_OK); + } + CloseClipboard(); + } + break; + + case IDC_EXPORT_PRIVATE: + { + TCHAR *p = GetFilePath(_T("Choose file to export key"), _T("*"), _T("Any file"), true); + if (!p || !p[0]) { + delete[] p; + //TODO: handle error + break; + } + char *path = mir_t2a(p); + delete[] p; + std::ofstream file; + file.open(path, std::ios::trunc | std::ios::out); + mir_free(path); + if (!file.is_open()) + break; //TODO: handle error + ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"-a"); + cmd.push_back(L"--export-secret-keys"); + cmd.push_back(fp); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) { + break; + } + if (result == pxNotFound) + break; + boost::algorithm::erase_all(out, "\r"); + file << out; + if (file.is_open()) + file.close(); + } + break; + + case IDC_CHANGE_PASSWD: + ListView_GetItemText(hwndList, itemnum, 0, key_id_global, _countof(key_id_global)); + + //temporary code follows + std::vector cmd; + std::string old_pass, new_pass; + string output; + DWORD exitcode; + cmd.push_back(L"--edit-key"); + cmd.push_back(key_id_global); + cmd.push_back(L"passwd"); + gpg_execution_params_pass params(cmd, old_pass, new_pass); + pxResult result; + params.out = &output; + params.code = &exitcode; + params.result = &result; + boost::thread gpg_thread(boost::bind(&pxEexcute_passwd_change_thread, ¶ms)); + if (!gpg_thread.timed_join(boost::posix_time::minutes(10))) { + gpg_thread.~thread(); + if (params.child) + boost::process::terminate(*(params.child)); + if (bDebugLog) + debuglog << std::string(time_str() + ": GPG execution timed out, aborted"); + DestroyWindow(hwndDlg); + break; + } + if (result == pxNotFound) + break; + break; + } + break; + + case WM_NOTIFY: + { + NMLISTVIEW *hdr = (NMLISTVIEW *)lParam; + if (hdr && IsWindowVisible(hdr->hdr.hwndFrom) && hdr->iItem != (-1)) { + if (hdr->hdr.code == NM_CLICK) { + EnableWindow(GetDlgItem(hwndDlg, ID_OK), 1); + EnableWindow(GetDlgItem(hwndDlg, IDC_COPY_PUBKEY), 1); + EnableWindow(GetDlgItem(hwndDlg, IDC_EXPORT_PRIVATE), 1); + EnableWindow(GetDlgItem(hwndDlg, IDC_CHANGE_PASSWD), 1); + itemnum = hdr->iItem; + } + } + } + break; + + case WM_CLOSE: + DestroyWindow(hwndDlg); + break; + + case WM_DESTROY: + GetWindowRect(hwndDlg, &firstrun_rect); + db_set_dw(NULL, szGPGModuleName, "FirstrunWindowX", firstrun_rect.left); + db_set_dw(NULL, szGPGModuleName, "FirstrunWindowY", firstrun_rect.top); + hwndFirstRun = NULL; + break; + } + + return FALSE; +} + +static INT_PTR CALLBACK DlgProcGpgBinOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM) +{ + switch (msg) { + case WM_INITDIALOG: + TranslateDialogDefault(hwndDlg); + { + TCHAR *path = (TCHAR*)mir_alloc(sizeof(TCHAR) * MAX_PATH); + bool gpg_exists = false, lang_exists = false; + { + ptrA mir_path((char*)mir_alloc(sizeof(char) * MAX_PATH)); + PathToAbsolute("\\", mir_path); + SetCurrentDirectoryA(mir_path); + + ptrT tmp(mir_a2t(mir_path)); + + wstring gpg_path(tmp); gpg_path += _T("\\GnuPG\\gpg.exe"); + wstring gpg_lang_path(tmp); gpg_lang_path += _T("\\GnuPG\\gnupg.nls\\en@quot.mo"); + + if (boost::filesystem::exists(gpg_path)) { + gpg_exists = true; + mir_tstrcpy(path, _T("GnuPG\\gpg.exe")); + } + else mir_tstrcpy(path, gpg_path.c_str()); + + if (boost::filesystem::exists(gpg_lang_path)) + lang_exists = true; + if (gpg_exists && !lang_exists) + MessageBox(0, TranslateT("GPG binary found in Miranda folder, but English locale does not exist.\nIt's highly recommended that you place \\gnupg.nls\\en@quot.mo in GnuPG folder under Miranda root.\nWithout this file you may experience many problems with GPG output on non-English systems\nand plugin may completely not work.\nYou have been warned."), TranslateT("Warning"), MB_OK); + } + DWORD len = MAX_PATH; + bool bad_version = false; + { + ptrT tmp; + if (!gpg_exists) { + tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", (SHGetValue(HKEY_CURRENT_USER, _T("Software\\GNU\\GnuPG"), _T("gpgProgram"), 0, path, &len) == ERROR_SUCCESS) ? path : _T("")); + if (tmp[0]) + if (!boost::filesystem::exists((TCHAR*)tmp)) + MessageBox(0, TranslateT("Wrong GPG binary location found in system.\nPlease choose another location"), TranslateT("Warning"), MB_OK); + } + else tmp = mir_wstrdup(path); + mir_free(path); + + SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); + if (gpg_exists/* && lang_exists*/) { + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--version"); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + gpg_valid = true; + gpg_launcher(params); + gpg_valid = false; + db_unset(NULL, szGPGModuleName, "szGpgBinPath"); + string::size_type p1 = out.find("(GnuPG) "); + if (p1 != string::npos) { + p1 += mir_strlen("(GnuPG) "); + if (out[p1] != '1') + bad_version = true; + } + else { + bad_version = false; + MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Error"), MB_OK); + } + if (bad_version) + MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); + } + } + { + ptrT tmp(UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T(""))); + if (!tmp[0]) { + mir_free(tmp); + char *mir_path = (char*)mir_alloc(sizeof(char) * MAX_PATH); + PathToAbsolute("\\", mir_path); + mir_strcat(mir_path, "\\gpg"); + if (_access(mir_path, 0) != -1) { + tmp = mir_wstrdup(toUTF16(mir_path).c_str()); + MessageBox(0, TranslateT("\"GPG\" directory found in Miranda root.\nAssuming it's GPG home directory.\nGPG home directory set."), TranslateT("Info"), MB_OK); + } + else { + wstring path_ = _wgetenv(_T("APPDATA")); + path_ += _T("\\GnuPG"); + tmp = mir_wstrdup(path_.c_str()); + } + } + SetDlgItemText(hwndDlg, IDC_HOME_DIR, !gpg_exists ? tmp : _T("gpg")); + } + //TODO: additional check for write access + if (gpg_exists && lang_exists && !bad_version) + MessageBox(0, TranslateT("Your GPG version is supported. The language file was found.\nGPG plugin should work fine.\nPress OK to continue."), TranslateT("Info"), MB_OK); + extern bool bIsMiranda09; + EnableWindow(GetDlgItem(hwndDlg, IDC_AUTO_EXCHANGE), bIsMiranda09); + return TRUE; + } + + + case WM_COMMAND: + { + switch (LOWORD(wParam)) { + case IDC_SET_BIN_PATH: + { + GetFilePath(_T("Choose gpg.exe"), "szGpgBinPath", _T("*.exe"), _T("EXE Executables")); + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("gpg.exe")); + SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); + char mir_path[MAX_PATH]; + char *atmp = mir_t2a(tmp); + mir_free(tmp); + PathToAbsolute("\\", mir_path); + char* p_path = NULL; + if (StriStr(atmp, mir_path)) { + p_path = atmp + mir_strlen(mir_path); + tmp = mir_a2t(p_path); + SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); + } + } + break; + case IDC_SET_HOME_DIR: + { + GetFolderPath(_T("Set home directory"), "szHomePath"); + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); + char mir_path[MAX_PATH]; + char *atmp = mir_t2a(tmp); + mir_free(tmp); + PathToAbsolute("\\", mir_path); + char* p_path = NULL; + if (StriStr(atmp, mir_path)) { + p_path = atmp + mir_strlen(mir_path); + tmp = mir_a2t(p_path); + SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); + } + } + break; + case ID_OK: + { + TCHAR tmp[512]; + GetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp, _countof(tmp)); + if (tmp[0]) { + char *mir_path = new char[MAX_PATH]; + PathToAbsolute("\\", mir_path); + SetCurrentDirectoryA(mir_path); + delete[] mir_path; + if (!boost::filesystem::exists(tmp)) { + MessageBox(0, TranslateT("GPG binary does not exist.\nPlease choose another location"), TranslateT("Warning"), MB_OK); + break; + } + } + else { + MessageBox(0, TranslateT("Please choose GPG binary location"), TranslateT("Warning"), MB_OK); + break; + } + { + bool bad_version = false; + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--version"); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + gpg_valid = true; + gpg_launcher(params); + gpg_valid = false; + db_unset(NULL, szGPGModuleName, "szGpgBinPath"); + string::size_type p1 = out.find("(GnuPG) "); + if (p1 != string::npos) { + p1 += mir_strlen("(GnuPG) "); + if (out[p1] != '1') + bad_version = true; + } + else { + bad_version = false; + MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); + } + if (bad_version) + MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); + } + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); + GetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp, _countof(tmp)); + while (tmp[mir_tstrlen(tmp) - 1] == '\\') + tmp[mir_tstrlen(tmp) - 1] = '\0'; + if (!tmp[0]) { + MessageBox(0, TranslateT("Please set keyring's home directory"), TranslateT("Warning"), MB_OK); + break; + } + db_set_ts(NULL, szGPGModuleName, "szHomePath", tmp); + { + TCHAR *path = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + DWORD dwFileAttr = GetFileAttributes(path); + if (dwFileAttr != INVALID_FILE_ATTRIBUTES) { + dwFileAttr &= ~FILE_ATTRIBUTE_READONLY; + SetFileAttributes(path, dwFileAttr); + } + mir_free(path); + } + gpg_valid = true; + db_set_b(NULL, szGPGModuleName, "FirstRun", 0); + DestroyWindow(hwndDlg); + ShowFirstRunDialog(); + } + break; + case IDC_GENERATE_RANDOM: + { + TCHAR tmp[512]; + GetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp, _countof(tmp)); + if (tmp[0]) { + char *mir_path = new char[MAX_PATH]; + PathToAbsolute("\\", mir_path); + SetCurrentDirectoryA(mir_path); + delete[] mir_path; + if (!boost::filesystem::exists(tmp)) { + MessageBox(0, TranslateT("GPG binary does not exist.\nPlease choose another location"), TranslateT("Warning"), MB_OK); + break; + } + } + else { + MessageBox(0, TranslateT("Please choose GPG binary location"), TranslateT("Warning"), MB_OK); + break; + } + { + bool bad_version = false; + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--version"); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + gpg_valid = true; + gpg_launcher(params); + gpg_valid = false; + db_unset(NULL, szGPGModuleName, "szGpgBinPath"); + string::size_type p1 = out.find("(GnuPG) "); + if (p1 != string::npos) { + p1 += mir_strlen("(GnuPG) "); + if (out[p1] != '1') + bad_version = true; + } + else { + bad_version = false; + MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); + } + if (bad_version) + MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); + } + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); + GetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp, _countof(tmp)); + while (tmp[mir_tstrlen(tmp) - 1] == '\\') + tmp[mir_tstrlen(tmp) - 1] = '\0'; + if (!tmp[0]) { + MessageBox(0, TranslateT("Please set keyring's home directory"), TranslateT("Warning"), MB_OK); + break; + } + db_set_ts(NULL, szGPGModuleName, "szHomePath", tmp); + { + TCHAR *path = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + DWORD dwFileAttr = GetFileAttributes(path); + if (dwFileAttr != INVALID_FILE_ATTRIBUTES) { + dwFileAttr &= ~FILE_ATTRIBUTE_READONLY; + SetFileAttributes(path, dwFileAttr); + } + mir_free(path); + } } - else { - string keyinfo = Translate("key ID"); - keyinfo += ": "; - std::string acc_str= buf; - acc_str += "_KeyID"; - char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, acc_str.c_str(), ""); - keyinfo += (mir_strlen(keyid) > 0)?keyid:Translate("not set"); - mir_free(keyid); - SetDlgItemTextA(hwndDlg, IDC_KEY_ID, keyinfo.c_str()); - } - } - break; - case IDC_COPY_PUBKEY: - { - if(OpenClipboard(hwndDlg)) - { - ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"-a"); - cmd.push_back(L"--export"); - cmd.push_back(fp); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - { - break; - } - if(result == pxNotFound) - break; - boost::algorithm::erase_all(out, "\r"); - HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, out.size() +1); - if(!hMem) - { - MessageBox(0, TranslateT("Failed to allocate memory"), TranslateT("Error"), MB_OK); - break; - } - char *szKey = (char*)GlobalLock(hMem); - if(!szKey) - { - TCHAR msg[64]; - mir_sntprintf(msg, _countof(msg), TranslateT("Failed to lock memory with error %d"), GetLastError()); - MessageBox(0, msg, TranslateT("Error"), MB_OK); - GlobalFree(hMem); - } - memcpy(szKey, out.c_str(), out.size()); - szKey[out.size()] = '\0'; - EmptyClipboard(); - GlobalUnlock(hMem); - if(!SetClipboardData(CF_OEMTEXT, hMem)) - { - GlobalFree(hMem); - TCHAR msg[64]; - mir_sntprintf(msg, _countof(msg), TranslateT("Failed write to clipboard with error %d"), GetLastError()); - MessageBox(0, msg, TranslateT("Error"), MB_OK); - } - CloseClipboard(); + wstring path; + { //generating key file + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + path = tmp; + mir_free(tmp); + path.append(_T("\\new_key")); + wfstream f(path.c_str(), std::ios::out); + if (!f.is_open()) { + MessageBox(0, TranslateT("Failed to open file"), TranslateT("Error"), MB_OK); + break; } + f << "Key-Type: RSA"; + f << "\n"; + f << "Key-Length: 2048"; + f << "\n"; + f << "Subkey-Type: RSA"; + f << "\n"; + f << "Name-Real: "; + f << get_random(6).c_str(); + f << "\n"; + f << "Name-Email: "; + f << get_random(5).c_str(); + f << "@"; + f << get_random(5).c_str(); + f << "."; + f << get_random(3).c_str(); + f << "\n"; + f.close(); } - break; - case IDC_EXPORT_PRIVATE: - { - TCHAR *p = GetFilePath(_T("Choose file to export key"), _T("*"), _T("Any file"), true); - if(!p || !p[0]) - { - delete [] p; - //TODO: handle error + { //gpg execution + DWORD code; + string out; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"--yes"); + cmd.push_back(L"--gen-key"); + cmd.push_back(path); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + gpg_valid = true; + if (!gpg_launcher(params, boost::posix_time::minutes(10))) { + gpg_valid = false; break; } - char *path = mir_t2a(p); - delete [] p; - std::ofstream file; - file.open(path, std::ios::trunc | std::ios::out); - mir_free(path); - if(!file.is_open()) - break; //TODO: handle error - ListView_GetItemText(hwndList, itemnum, 0, fp, _countof(fp)); + gpg_valid = false; + if (result == pxNotFound) + break; + boost::filesystem::remove(path); + string::size_type p1 = 0; + if ((p1 = out.find("key ")) != string::npos) + path = toUTF16(out.substr(p1 + 4, 8)); + else + path.clear(); + } + if (!path.empty()) { string out; DWORD code; std::vector cmd; cmd.push_back(L"--batch"); cmd.push_back(L"-a"); - cmd.push_back(L"--export-secret-keys"); - cmd.push_back(fp); + cmd.push_back(L"--export"); + cmd.push_back(path); gpg_execution_params params(cmd); pxResult result; params.out = &out; params.code = &code; params.result = &result; - if(!gpg_launcher(params)) - { + gpg_valid = true; + if (!gpg_launcher(params)) { + gpg_valid = false; break; } - if(result == pxNotFound) + gpg_valid = false; + if (result == pxNotFound) break; - boost::algorithm::erase_all(out, "\r"); - file< cmd; - std::string old_pass, new_pass; - string output; - DWORD exitcode; - cmd.push_back(L"--edit-key"); - cmd.push_back(key_id_global); - cmd.push_back(L"passwd"); - gpg_execution_params_pass params(cmd, old_pass, new_pass); - pxResult result; - params.out = &output; - params.code = &exitcode; - params.result = &result; - boost::thread gpg_thread(boost::bind(&pxEexcute_passwd_change_thread, ¶ms)); - if(!gpg_thread.timed_join(boost::posix_time::minutes(10))) - { - gpg_thread.~thread(); - if(params.child) - boost::process::terminate(*(params.child)); - if(bDebugLog) - debuglog<hdr.hwndFrom) && hdr->iItem != (-1)) - { - if(hdr->hdr.code == NM_CLICK) - { - EnableWindow(GetDlgItem(hwndDlg, ID_OK), 1); - EnableWindow(GetDlgItem(hwndDlg, IDC_COPY_PUBKEY), 1); - EnableWindow(GetDlgItem(hwndDlg, IDC_EXPORT_PRIVATE), 1); - EnableWindow(GetDlgItem(hwndDlg, IDC_CHANGE_PASSWD), 1); - itemnum = hdr->iItem; + } + bAutoExchange = CheckStateStoreDB(hwndDlg, IDC_AUTO_EXCHANGE, "bAutoExchange") != 0; + gpg_valid = true; + db_set_b(NULL, szGPGModuleName, "FirstRun", 0); + DestroyWindow(hwndDlg); + break; + default: + break; } + + break; } -/* switch(LOWORD(wParam)) + + case WM_NOTIFY: { - default: - break; - }; */ -/* switch (((LPNMHDR)lParam)->code) - { - default: - break; - } */ - } - break; + /* switch (((LPNMHDR)lParam)->code) + { + default: + break; + }*/ + } + break; case WM_CLOSE: DestroyWindow(hwndDlg); break; case WM_DESTROY: - { - GetWindowRect(hwndDlg, &firstrun_rect); - db_set_dw(NULL, szGPGModuleName, "FirstrunWindowX", firstrun_rect.left); - db_set_dw(NULL, szGPGModuleName, "FirstrunWindowY", firstrun_rect.top); - } - hwndFirstRun = NULL; + hwndSetDirs = NULL; + void InitCheck(); + InitCheck(); break; - } - - return FALSE; -} - -static INT_PTR CALLBACK DlgProcGpgBinOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM) -{ - TCHAR *tmp = NULL; - switch (msg) - { - case WM_INITDIALOG: - { - TranslateDialogDefault(hwndDlg); - TCHAR *path = (TCHAR*)mir_alloc(sizeof(TCHAR) * MAX_PATH); - bool gpg_exists = false, lang_exists = false; - { - char *mir_path = (char*)mir_alloc(sizeof(char) * MAX_PATH); - PathToAbsolute("\\", mir_path); - SetCurrentDirectoryA(mir_path); - tmp = mir_a2t(mir_path); - mir_free(mir_path); - //mir_realloc(path, (mir_tstrlen(path)+128)*sizeof(TCHAR)); - TCHAR *gpg_path = (TCHAR*)mir_alloc(sizeof(TCHAR) * MAX_PATH), *gpg_lang_path = (TCHAR*)mir_alloc(sizeof(TCHAR) * MAX_PATH); - mir_tstrcpy(gpg_path, tmp); - mir_tstrcat(gpg_path, _T("\\GnuPG\\gpg.exe")); - mir_tstrcpy(gpg_lang_path, tmp); - mir_tstrcat(gpg_lang_path, _T("\\GnuPG\\gnupg.nls\\en@quot.mo")); - mir_free(tmp); - if(boost::filesystem::exists(gpg_path)) - { - gpg_exists = true; - mir_tstrcpy(path, _T("GnuPG\\gpg.exe")); - } - else - mir_tstrcpy(path, gpg_path); - if(boost::filesystem::exists(gpg_lang_path)) - lang_exists = true; - if(gpg_exists && !lang_exists) - MessageBox(0, TranslateT("GPG binary found in Miranda folder, but English locale does not exist.\nIt's highly recommended that you place \\gnupg.nls\\en@quot.mo in GnuPG folder under Miranda root.\nWithout this file you may experience many problems with GPG output on non-English systems\nand plugin may completely not work.\nYou have been warned."), TranslateT("Warning"), MB_OK); - mir_free(gpg_path); - mir_free(gpg_lang_path); - } - DWORD len = MAX_PATH; - if(!gpg_exists) - { - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", (SHGetValue(HKEY_CURRENT_USER, _T("Software\\GNU\\GnuPG"), _T("gpgProgram"), 0, path, &len) == ERROR_SUCCESS)?path:_T("")); - if(tmp[0]) - if(!boost::filesystem::exists(tmp)) - MessageBox(0, TranslateT("Wrong GPG binary location found in system.\nPlease choose another location"), TranslateT("Warning"), MB_OK); - } - else - tmp = mir_wstrdup(path); - mir_free(path); - - SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); - bool bad_version = false; - if(gpg_exists/* && lang_exists*/) - { - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--version"); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - gpg_valid = true; - gpg_launcher(params); - gpg_valid = false; - db_unset(NULL, szGPGModuleName, "szGpgBinPath"); - string::size_type p1 = out.find("(GnuPG) "); - if(p1 != string::npos) - { - p1 += mir_strlen("(GnuPG) "); - if(out[p1] != '1') - bad_version = true; - } - else - { - bad_version = false; - MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Error"), MB_OK); - } - if(bad_version) - MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); - } - mir_free(tmp); - { - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - if(!tmp[0]) - { - mir_free(tmp); - char *mir_path = (char*)mir_alloc(sizeof(char) * MAX_PATH); - PathToAbsolute("\\", mir_path); - mir_strcat(mir_path, "\\gpg"); - if(_access(mir_path, 0) != -1) - { - tmp = mir_wstrdup(toUTF16(mir_path).c_str()); - MessageBox(0, TranslateT("\"GPG\" directory found in Miranda root.\nAssuming it's GPG home directory.\nGPG home directory set."), TranslateT("Info"), MB_OK); - } - else - { - wstring path_ = _wgetenv(_T("APPDATA")); - path_ += _T("\\GnuPG"); - tmp = mir_wstrdup(path_.c_str()); - } - } - SetDlgItemText(hwndDlg, IDC_HOME_DIR, !gpg_exists?tmp:_T("gpg")); - mir_free(tmp); - } - //TODO: additional check for write access - if(gpg_exists && lang_exists && !bad_version) - MessageBox(0, TranslateT("Your GPG version is supported. The language file was found.\nGPG plugin should work fine.\nPress OK to continue."), TranslateT("Info"), MB_OK); - extern bool bIsMiranda09; - EnableWindow(GetDlgItem(hwndDlg, IDC_AUTO_EXCHANGE), bIsMiranda09); - return TRUE; - } - - - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDC_SET_BIN_PATH: - { - GetFilePath(_T("Choose gpg.exe"), "szGpgBinPath", _T("*.exe"), _T("EXE Executables")); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("gpg.exe")); - SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); - char mir_path[MAX_PATH]; - char *atmp = mir_t2a(tmp); - mir_free(tmp); - PathToAbsolute("\\", mir_path); - char* p_path = NULL; - if(StriStr(atmp, mir_path)) - { - p_path = atmp + mir_strlen(mir_path); - tmp = mir_a2t(p_path); - SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); - } - } - break; - case IDC_SET_HOME_DIR: - { - GetFolderPath(_T("Set home directory"), "szHomePath"); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); - char mir_path[MAX_PATH]; - char *atmp = mir_t2a(tmp); - mir_free(tmp); - PathToAbsolute("\\", mir_path); - char* p_path = NULL; - if(StriStr(atmp, mir_path)) - { - p_path = atmp + mir_strlen(mir_path); - tmp = mir_a2t(p_path); - SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); - } - } - break; - case ID_OK: - { - TCHAR tmp[512]; - GetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp, _countof(tmp)); - if(tmp[0]) - { - char *mir_path = new char [MAX_PATH]; - PathToAbsolute("\\", mir_path); - SetCurrentDirectoryA(mir_path); - delete [] mir_path; - if(!boost::filesystem::exists(tmp)) - { - MessageBox(0, TranslateT("GPG binary does not exist.\nPlease choose another location"), TranslateT("Warning"), MB_OK); - break; - } - } - else - { - MessageBox(0, TranslateT("Please choose GPG binary location"), TranslateT("Warning"), MB_OK); - break; - } - { - bool bad_version = false; - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--version"); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - gpg_valid = true; - gpg_launcher(params); - gpg_valid = false; - db_unset(NULL, szGPGModuleName, "szGpgBinPath"); - string::size_type p1 = out.find("(GnuPG) "); - if(p1 != string::npos) - { - p1 += mir_strlen("(GnuPG) "); - if(out[p1] != '1') - bad_version = true; - } - else - { - bad_version = false; - MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); - } - if(bad_version) - MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); - } - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); - GetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp, _countof(tmp)); - while(tmp[mir_tstrlen(tmp)-1] == '\\') - tmp[mir_tstrlen(tmp)-1] = '\0'; - if(!tmp[0]) - { - MessageBox(0, TranslateT("Please set keyring's home directory"), TranslateT("Warning"), MB_OK); - break; - } - db_set_ts(NULL, szGPGModuleName, "szHomePath", tmp); - { - TCHAR *path = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - DWORD dwFileAttr = GetFileAttributes(path); - if (dwFileAttr != INVALID_FILE_ATTRIBUTES) - { - dwFileAttr &=~ FILE_ATTRIBUTE_READONLY; - SetFileAttributes(path, dwFileAttr); - } - mir_free(path); - } - gpg_valid = true; - db_set_b(NULL, szGPGModuleName, "FirstRun", 0); - DestroyWindow(hwndDlg); - ShowFirstRunDialog(); - } - break; - case IDC_GENERATE_RANDOM: - { - TCHAR tmp[512]; - GetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp, _countof(tmp)); - if(tmp[0]) - { - char *mir_path = new char [MAX_PATH]; - PathToAbsolute("\\", mir_path); - SetCurrentDirectoryA(mir_path); - delete [] mir_path; - if(!boost::filesystem::exists(tmp)) - { - MessageBox(0, TranslateT("GPG binary does not exist.\nPlease choose another location"), TranslateT("Warning"), MB_OK); - break; - } - } - else - { - MessageBox(0, TranslateT("Please choose GPG binary location"), TranslateT("Warning"), MB_OK); - break; - } - { - bool bad_version = false; - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--version"); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - gpg_valid = true; - gpg_launcher(params); - gpg_valid = false; - db_unset(NULL, szGPGModuleName, "szGpgBinPath"); - string::size_type p1 = out.find("(GnuPG) "); - if(p1 != string::npos) - { - p1 += mir_strlen("(GnuPG) "); - if(out[p1] != '1') - bad_version = true; - } - else - { - bad_version = false; - MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); - } - if(bad_version) - MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); - } - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); - GetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp, _countof(tmp)); - while(tmp[mir_tstrlen(tmp)-1] == '\\') - tmp[mir_tstrlen(tmp)-1] = '\0'; - if(!tmp[0]) - { - MessageBox(0, TranslateT("Please set keyring's home directory"), TranslateT("Warning"), MB_OK); - break; - } - db_set_ts(NULL, szGPGModuleName, "szHomePath", tmp); - { - TCHAR *path = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - DWORD dwFileAttr = GetFileAttributes(path); - if (dwFileAttr != INVALID_FILE_ATTRIBUTES) - { - dwFileAttr &=~ FILE_ATTRIBUTE_READONLY; - SetFileAttributes(path, dwFileAttr); - } - mir_free(path); - } - } - { - wstring path; - { //generating key file - TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - path = tmp; - mir_free(tmp); - path.append(_T("\\new_key")); - wfstream f(path.c_str(), std::ios::out); - if(!f.is_open()) - { - MessageBox(0, TranslateT("Failed to open file"), TranslateT("Error"), MB_OK); - break; - } - f<<"Key-Type: RSA"; - f<<"\n"; - f<<"Key-Length: 2048"; - f<<"\n"; - f<<"Subkey-Type: RSA"; - f<<"\n"; - f<<"Name-Real: "; - f< cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"--yes"); - cmd.push_back(L"--gen-key"); - cmd.push_back(path); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - gpg_valid = true; - if(!gpg_launcher(params, boost::posix_time::minutes(10))) - { - gpg_valid = false; - break; - } - gpg_valid = false; - if(result == pxNotFound) - break; - boost::filesystem::remove(path); - string::size_type p1 = 0; - if((p1 = out.find("key ")) != string::npos) - path = toUTF16(out.substr(p1+4, 8)); - else - path.clear(); - } - if(!path.empty()) - { - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"-a"); - cmd.push_back(L"--export"); - cmd.push_back(path); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - gpg_valid = true; - if(!gpg_launcher(params)) - { - gpg_valid = false; - break; - } - gpg_valid = false; - if(result == pxNotFound) - break; - string::size_type s = 0; - while((s = out.find("\r", s)) != string::npos) - { - out.erase(s, 1); - } - db_set_s(NULL, szGPGModuleName, "GPGPubKey", out.c_str()); - db_set_ts(NULL, szGPGModuleName, "KeyID", path.c_str()); - extern HWND hwndCurKey_p; - SetWindowText(hwndCurKey_p, path.c_str()); - } - } - bAutoExchange = CheckStateStoreDB(hwndDlg, IDC_AUTO_EXCHANGE, "bAutoExchange") != 0; - gpg_valid = true; - db_set_b(NULL, szGPGModuleName, "FirstRun", 0); - DestroyWindow(hwndDlg); - break; - default: - break; - } - - break; - } - - case WM_NOTIFY: - { -/* switch (((LPNMHDR)lParam)->code) - { - default: - break; - }*/ } - break; - case WM_CLOSE: - DestroyWindow(hwndDlg); - break; - case WM_DESTROY: - hwndSetDirs = NULL; - void InitCheck(); - InitCheck(); - break; - - } - return FALSE; + return FALSE; } static INT_PTR CALLBACK DlgProcNewKeyDialog(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM) @@ -1284,23 +1183,22 @@ static INT_PTR CALLBACK DlgProcNewKeyDialog(HWND hwndDlg, UINT msg, WPARAM wPara static MCONTACT hContact = INVALID_CONTACT_ID; void ImportKey(); - switch (msg) - { + switch (msg) { case WM_INITDIALOG: { hContact = new_key_hcnt; //new_key_hcnt_mutex.unlock(); - SetWindowPos(hwndDlg, 0, new_key_rect.left, new_key_rect.top, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW); + SetWindowPos(hwndDlg, 0, new_key_rect.left, new_key_rect.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); TranslateDialogDefault(hwndDlg); TCHAR *tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", _T("")); - SetDlgItemText(hwndDlg, IDC_MESSAGE, tmp[0]?TranslateT("There is existing key for contact, would you like to replace it with new key?"):TranslateT("New public key was received, do you want to import it?")); - EnableWindow(GetDlgItem(hwndDlg, IDC_IMPORT_AND_USE), db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0)?0:1); - SetDlgItemText(hwndDlg, ID_IMPORT, tmp[0]?TranslateT("Replace"):TranslateT("Accept")); + SetDlgItemText(hwndDlg, IDC_MESSAGE, tmp[0] ? TranslateT("There is existing key for contact, would you like to replace it with new key?") : TranslateT("New public key was received, do you want to import it?")); + EnableWindow(GetDlgItem(hwndDlg, IDC_IMPORT_AND_USE), db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0) ? 0 : 1); + SetDlgItemText(hwndDlg, ID_IMPORT, tmp[0] ? TranslateT("Replace") : TranslateT("Accept")); mir_free(tmp); - tmp = new TCHAR [256]; - mir_sntprintf(tmp, 255*sizeof(TCHAR),TranslateT("Received key from %s"), pcli->pfnGetContactDisplayName(hContact, 0)); + tmp = new TCHAR[256]; + mir_sntprintf(tmp, 255 * sizeof(TCHAR), TranslateT("Received key from %s"), pcli->pfnGetContactDisplayName(hContact, 0)); SetDlgItemText(hwndDlg, IDC_KEY_FROM, tmp); - delete [] tmp; + delete[] tmp; } return TRUE; @@ -1344,555 +1242,524 @@ static INT_PTR CALLBACK DlgProcNewKeyDialog(HWND hwndDlg, UINT msg, WPARAM wPara static INT_PTR CALLBACK DlgProcKeyGenDialog(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM) { - switch (msg) - { - case WM_INITDIALOG: - { - SetWindowPos(hwndDlg, 0, key_gen_rect.left, key_gen_rect.top, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW); - TranslateDialogDefault(hwndDlg); - SetWindowText(hwndDlg, TranslateT("Key Generation dialog")); - ComboBoxAddStringUtf(GetDlgItem(hwndDlg, IDC_KEY_TYPE), _T("RSA"), 0); - ComboBoxAddStringUtf(GetDlgItem(hwndDlg, IDC_KEY_TYPE), _T("DSA"), 1); - SendDlgItemMessage(hwndDlg, IDC_KEY_TYPE, CB_SETCURSEL, 1, 0); - SetDlgItemInt(hwndDlg, IDC_KEY_EXPIRE_DATE, 0, 0); - SetDlgItemInt(hwndDlg, IDC_KEY_LENGTH, 4096, 0); - return TRUE; - } - - - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDCANCEL: - DestroyWindow(hwndDlg); - break; - case IDOK: - { - wstring path; - { //data sanity checks - TCHAR *tmp = (TCHAR*)mir_alloc(sizeof(TCHAR)*5); - GetDlgItemText(hwndDlg, IDC_KEY_TYPE, tmp, 5); - if(mir_tstrlen(tmp) < 3) - { - mir_free(tmp); tmp = NULL; - MessageBox(0, TranslateT("You must set encryption algorithm first"), TranslateT("Error"), MB_OK); - break; - } - if(tmp) - mir_free(tmp); - tmp = (TCHAR*)mir_alloc(sizeof(TCHAR)*6); - GetDlgItemText(hwndDlg, IDC_KEY_LENGTH, tmp, 5); - int length = _ttoi(tmp); - mir_free(tmp); - if(length < 1024 || length > 4096) - { - MessageBox(0, TranslateT("Key length must be of length from 1024 to 4096 bits"), TranslateT("Error"), MB_OK); - break; - } - tmp = (TCHAR*)mir_alloc(sizeof(TCHAR)*12); - GetDlgItemText(hwndDlg, IDC_KEY_EXPIRE_DATE, tmp, 11); - if(mir_tstrlen(tmp) != 10 && tmp[0] != '0') - { - MessageBox(0, TranslateT("Invalid date"), TranslateT("Error"), MB_OK); - mir_free(tmp); - break; - } - mir_free(tmp); - tmp = (TCHAR*)mir_alloc(sizeof(TCHAR)*128); - GetDlgItemText(hwndDlg, IDC_KEY_REAL_NAME, tmp, 127); - if(mir_tstrlen(tmp) < 5) - { - MessageBox(0, TranslateT("Name must contain at least 5 characters"), TranslateT("Error"), MB_OK); - mir_free(tmp); - break; - } - else if (_tcschr(tmp, _T('(')) || _tcschr(tmp, _T(')'))) - { - MessageBox(0, TranslateT("Name cannot contain '(' or ')'"), TranslateT("Error"), MB_OK); - mir_free(tmp); - break; - } - mir_free(tmp); - tmp = (TCHAR*)mir_alloc(sizeof(TCHAR)*128); - GetDlgItemText(hwndDlg, IDC_KEY_EMAIL, tmp, 128); - if((mir_tstrlen(tmp)) < 5 || (!_tcschr(tmp, _T('@'))) || (!_tcschr(tmp, _T('.')))) - { - MessageBox(0, TranslateT("Invalid Email"), TranslateT("Error"), MB_OK); - mir_free(tmp); - break; - } - mir_free(tmp); - } - { //generating key file - TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - char *tmp2;// = mir_t2a(tmp); - path = tmp; - mir_free(tmp); - // mir_free(tmp2); - path.append(_T("\\new_key")); - wfstream f(path.c_str(), std::ios::out); - if(!f.is_open()) - { - MessageBox(0, TranslateT("Failed to open file"), TranslateT("Error"), MB_OK); - break; - } - f<<"Key-Type: "; - tmp = (TCHAR*)mir_alloc(sizeof(TCHAR)*5); - GetDlgItemText(hwndDlg, IDC_KEY_TYPE, tmp, 5); - tmp2 = mir_t2a(tmp); - mir_free(tmp); - char *subkeytype = (char*)mir_alloc(6); - if(strstr(tmp2, "RSA")) - mir_strcpy(subkeytype, "RSA"); - else if(strstr(tmp2, "DSA")) //this is useless check for now, but it will be required if someone add another key types support - mir_strcpy(subkeytype, "ELG-E"); - f< cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"--yes"); - cmd.push_back(L"--gen-key"); - cmd.push_back(path); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - SendDlgItemMessage(hwndDlg, IDC_GENERATING_TEXT, WM_SETFONT, (WPARAM)bold_font, TRUE); - SetDlgItemText(hwndDlg, IDC_GENERATING_TEXT, TranslateT("Generating new key, please wait...")); - EnableWindow(GetDlgItem(hwndDlg, IDCANCEL), 0); - EnableWindow(GetDlgItem(hwndDlg, IDOK), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_TYPE), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_LENGTH), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_PASSWD), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_REAL_NAME), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_EMAIL), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_COMMENT), 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_EXPIRE_DATE), 0); - if(!gpg_launcher(params, boost::posix_time::minutes(10))) - break; - if(result == pxNotFound) - break; - } - boost::filesystem::remove(path); - DestroyWindow(hwndDlg); - {//parse gpg output - LVITEM item = {0}; - int i = 1, iRow = 0; - item.mask = LVIF_TEXT; - item.iItem = i; - item.iSubItem = 0; - item.pszText = _T(""); - string out; - DWORD code; - string::size_type p = 0, p2 = 0, stop = 0; - { - std::vector cmd; - cmd.push_back(L"--list-secret-keys"); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - break; - if(result == pxNotFound) - break; - } - ListView_DeleteAllItems(hwndList_g); - while(p != string::npos) + switch (msg) { + case WM_INITDIALOG: + { + SetWindowPos(hwndDlg, 0, key_gen_rect.left, key_gen_rect.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); + TranslateDialogDefault(hwndDlg); + SetWindowText(hwndDlg, TranslateT("Key Generation dialog")); + ComboBoxAddStringUtf(GetDlgItem(hwndDlg, IDC_KEY_TYPE), _T("RSA"), 0); + ComboBoxAddStringUtf(GetDlgItem(hwndDlg, IDC_KEY_TYPE), _T("DSA"), 1); + SendDlgItemMessage(hwndDlg, IDC_KEY_TYPE, CB_SETCURSEL, 1, 0); + SetDlgItemInt(hwndDlg, IDC_KEY_EXPIRE_DATE, 0, 0); + SetDlgItemInt(hwndDlg, IDC_KEY_LENGTH, 4096, 0); + return TRUE; + } + + + case WM_COMMAND: + { + switch (LOWORD(wParam)) { + case IDCANCEL: + DestroyWindow(hwndDlg); + break; + case IDOK: { - if((p = out.find("sec ", p)) == string::npos) - break; - p += 5; - if(p < stop) - break; - stop = p; - p2 = out.find("/", p) - 1; - TCHAR *tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - item.pszText = tmp; - iRow = ListView_InsertItem(hwndList_g, &item); - ListView_SetItemText(hwndList_g, iRow, 4, tmp); - mir_free(tmp); - p2+=2; - p = out.find(" ", p2); - tmp = mir_wstrdup(toUTF16(out.substr(p2,p-p2)).c_str()); - ListView_SetItemText(hwndList_g, iRow, 0, tmp); - mir_free(tmp); - p = out.find("uid ", p); - p2 = out.find_first_not_of(" ", p+5); - p = out.find("<", p2); - tmp = mir_wstrdup(toUTF16(out.substr(p2,p-p2)).c_str()); - ListView_SetItemText(hwndList_g, iRow, 2, tmp); - mir_free(tmp); - p++; - p2 = out.find(">", p); - tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - ListView_SetItemText(hwndList_g, iRow, 1, tmp); - mir_free(tmp); - p = out.find("ssb ", p2) + 6; - p = out.find(" ", p) + 1; - p2 = out.find("\n", p); - tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p-1)).c_str()); - ListView_SetItemText(hwndList_g, iRow, 3, tmp); - mir_free(tmp); - ListView_SetColumnWidth(hwndList_g, 0, LVSCW_AUTOSIZE);// not sure about this - ListView_SetColumnWidth(hwndList_g, 1, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList_g, 2, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList_g, 3, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList_g, 4, LVSCW_AUTOSIZE); - i++; + wstring path; + { //data sanity checks + TCHAR *tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 5); + GetDlgItemText(hwndDlg, IDC_KEY_TYPE, tmp, 5); + if (mir_tstrlen(tmp) < 3) { + mir_free(tmp); tmp = NULL; + MessageBox(0, TranslateT("You must set encryption algorithm first"), TranslateT("Error"), MB_OK); + break; + } + if (tmp) + mir_free(tmp); + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 6); + GetDlgItemText(hwndDlg, IDC_KEY_LENGTH, tmp, 5); + int length = _ttoi(tmp); + mir_free(tmp); + if (length < 1024 || length > 4096) { + MessageBox(0, TranslateT("Key length must be of length from 1024 to 4096 bits"), TranslateT("Error"), MB_OK); + break; + } + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 12); + GetDlgItemText(hwndDlg, IDC_KEY_EXPIRE_DATE, tmp, 11); + if (mir_tstrlen(tmp) != 10 && tmp[0] != '0') { + MessageBox(0, TranslateT("Invalid date"), TranslateT("Error"), MB_OK); + mir_free(tmp); + break; + } + mir_free(tmp); + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 128); + GetDlgItemText(hwndDlg, IDC_KEY_REAL_NAME, tmp, 127); + if (mir_tstrlen(tmp) < 5) { + MessageBox(0, TranslateT("Name must contain at least 5 characters"), TranslateT("Error"), MB_OK); + mir_free(tmp); + break; + } + else if (_tcschr(tmp, _T('(')) || _tcschr(tmp, _T(')'))) { + MessageBox(0, TranslateT("Name cannot contain '(' or ')'"), TranslateT("Error"), MB_OK); + mir_free(tmp); + break; + } + mir_free(tmp); + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 128); + GetDlgItemText(hwndDlg, IDC_KEY_EMAIL, tmp, 128); + if ((mir_tstrlen(tmp)) < 5 || (!_tcschr(tmp, _T('@'))) || (!_tcschr(tmp, _T('.')))) { + MessageBox(0, TranslateT("Invalid Email"), TranslateT("Error"), MB_OK); + mir_free(tmp); + break; + } + mir_free(tmp); + } + { //generating key file + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + char *tmp2;// = mir_t2a(tmp); + path = tmp; + mir_free(tmp); + // mir_free(tmp2); + path.append(_T("\\new_key")); + wfstream f(path.c_str(), std::ios::out); + if (!f.is_open()) { + MessageBox(0, TranslateT("Failed to open file"), TranslateT("Error"), MB_OK); + break; + } + f << "Key-Type: "; + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 5); + GetDlgItemText(hwndDlg, IDC_KEY_TYPE, tmp, 5); + tmp2 = mir_t2a(tmp); + mir_free(tmp); + char *subkeytype = (char*)mir_alloc(6); + if (strstr(tmp2, "RSA")) + mir_strcpy(subkeytype, "RSA"); + else if (strstr(tmp2, "DSA")) //this is useless check for now, but it will be required if someone add another key types support + mir_strcpy(subkeytype, "ELG-E"); + f << tmp2; + mir_free(tmp2); + f << "\n"; + f << "Key-Length: "; + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 5); + GetDlgItemText(hwndDlg, IDC_KEY_LENGTH, tmp, 5); + int length = _ttoi(tmp); + mir_free(tmp); + f << length; + f << "\n"; + f << "Subkey-Length: "; + f << length; + f << "\n"; + f << "Subkey-Type: "; + f << subkeytype; + mir_free(subkeytype); + f << "\n"; + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 64); //i hope this is enough for password + GetDlgItemText(hwndDlg, IDC_KEY_PASSWD, tmp, 64); + if (tmp[0]) { + f << "Passphrase: "; + tmp2 = mir_strdup(toUTF8(tmp).c_str()); + f << tmp2; + f << "\n"; + mir_free(tmp2); + } + mir_free(tmp); + f << "Name-Real: "; + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 128); + GetDlgItemText(hwndDlg, IDC_KEY_REAL_NAME, tmp, 128); + tmp2 = mir_strdup(toUTF8(tmp).c_str()); + f << tmp2; + mir_free(tmp2); + mir_free(tmp); + f << "\n"; + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 512); + GetDlgItemText(hwndDlg, IDC_KEY_COMMENT, tmp, 512); + if (tmp[0]) { + tmp2 = mir_strdup(toUTF8(tmp).c_str()); + f << "Name-Comment: "; + f << tmp2; + f << "\n"; + } + mir_free(tmp2); + mir_free(tmp); + f << "Name-Email: "; + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 128); + GetDlgItemText(hwndDlg, IDC_KEY_EMAIL, tmp, 128); + tmp2 = mir_strdup(toUTF8(tmp).c_str()); + f << tmp2; + mir_free(tmp2); + mir_free(tmp); + f << "\n"; + f << "Expire-Date: "; + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * 12); + GetDlgItemText(hwndDlg, IDC_KEY_EXPIRE_DATE, tmp, 12); + tmp2 = mir_strdup(toUTF8(tmp).c_str()); + f << tmp2; + mir_free(tmp2); + mir_free(tmp); + f << "\n"; + f.close(); + } + { //gpg execution + DWORD code; + string out; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"--yes"); + cmd.push_back(L"--gen-key"); + cmd.push_back(path); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + SendDlgItemMessage(hwndDlg, IDC_GENERATING_TEXT, WM_SETFONT, (WPARAM)bold_font, TRUE); + SetDlgItemText(hwndDlg, IDC_GENERATING_TEXT, TranslateT("Generating new key, please wait...")); + EnableWindow(GetDlgItem(hwndDlg, IDCANCEL), 0); + EnableWindow(GetDlgItem(hwndDlg, IDOK), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_TYPE), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_LENGTH), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_PASSWD), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_REAL_NAME), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_EMAIL), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_COMMENT), 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_KEY_EXPIRE_DATE), 0); + if (!gpg_launcher(params, boost::posix_time::minutes(10))) + break; + if (result == pxNotFound) + break; + } + boost::filesystem::remove(path); + DestroyWindow(hwndDlg); + {//parse gpg output + LVITEM item = { 0 }; + int i = 1, iRow = 0; + item.mask = LVIF_TEXT; + item.iItem = i; + item.iSubItem = 0; + item.pszText = _T(""); + string out; + DWORD code; + string::size_type p = 0, p2 = 0, stop = 0; + { + std::vector cmd; + cmd.push_back(L"--list-secret-keys"); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) + break; + if (result == pxNotFound) + break; + } + ListView_DeleteAllItems(hwndList_g); + while (p != string::npos) { + if ((p = out.find("sec ", p)) == string::npos) + break; + p += 5; + if (p < stop) + break; + stop = p; + p2 = out.find("/", p) - 1; + TCHAR *tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + item.pszText = tmp; + iRow = ListView_InsertItem(hwndList_g, &item); + ListView_SetItemText(hwndList_g, iRow, 4, tmp); + mir_free(tmp); + p2 += 2; + p = out.find(" ", p2); + tmp = mir_wstrdup(toUTF16(out.substr(p2, p - p2)).c_str()); + ListView_SetItemText(hwndList_g, iRow, 0, tmp); + mir_free(tmp); + p = out.find("uid ", p); + p2 = out.find_first_not_of(" ", p + 5); + p = out.find("<", p2); + tmp = mir_wstrdup(toUTF16(out.substr(p2, p - p2)).c_str()); + ListView_SetItemText(hwndList_g, iRow, 2, tmp); + mir_free(tmp); + p++; + p2 = out.find(">", p); + tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + ListView_SetItemText(hwndList_g, iRow, 1, tmp); + mir_free(tmp); + p = out.find("ssb ", p2) + 6; + p = out.find(" ", p) + 1; + p2 = out.find("\n", p); + tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p - 1)).c_str()); + ListView_SetItemText(hwndList_g, iRow, 3, tmp); + mir_free(tmp); + ListView_SetColumnWidth(hwndList_g, 0, LVSCW_AUTOSIZE);// not sure about this + ListView_SetColumnWidth(hwndList_g, 1, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList_g, 2, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList_g, 3, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList_g, 4, LVSCW_AUTOSIZE); + i++; + } + } } + break; + default: + break; } - } - break; - default: + + break; + } + + case WM_NOTIFY: + { + /* switch (((LPNMHDR)lParam)->code) + { + default: + break; + } */ + } break; - } - - break; - } - - case WM_NOTIFY: - { -/* switch (((LPNMHDR)lParam)->code) - { - default: - break; - } */ + case WM_CLOSE: + DestroyWindow(hwndDlg); + break; + case WM_DESTROY: + { + GetWindowRect(hwndDlg, &key_gen_rect); + db_set_dw(NULL, szGPGModuleName, "KeyGenWindowX", key_gen_rect.left); + db_set_dw(NULL, szGPGModuleName, "KeyGenWindowY", key_gen_rect.top); + } + hwndKeyGen = NULL; + break; + } - break; - case WM_CLOSE: - DestroyWindow(hwndDlg); - break; - case WM_DESTROY: - { - GetWindowRect(hwndDlg, &key_gen_rect); - db_set_dw(NULL, szGPGModuleName, "KeyGenWindowX", key_gen_rect.left); - db_set_dw(NULL, szGPGModuleName, "KeyGenWindowY", key_gen_rect.top); - } - hwndKeyGen = NULL; - break; - - } - return FALSE; + return FALSE; } int itemnum2 = 0; -static INT_PTR CALLBACK DlgProcLoadExistingKey(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam) +static INT_PTR CALLBACK DlgProcLoadExistingKey(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { - HWND hwndList=GetDlgItem(hwndDlg, IDC_EXISTING_KEY_LIST); + HWND hwndList = GetDlgItem(hwndDlg, IDC_EXISTING_KEY_LIST); hwndList_g = hwndList; - LVCOLUMN col = {0}; - LVITEM item = {0}; - NMLISTVIEW * hdr = (NMLISTVIEW *) lParam; - TCHAR id[16] = {0}; - switch (msg) - { - case WM_INITDIALOG: - { - SetWindowPos(hwndDlg, 0, load_existing_key_rect.left, load_existing_key_rect.top, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW); - TranslateDialogDefault(hwndDlg); - col.pszText = _T("Key ID"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 50; - ListView_InsertColumn(hwndList, 0, &col); - memset(&col, 0, sizeof(col)); - col.pszText = _T("Email"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 1, &col); - memset(&col, 0, sizeof(col)); - col.pszText = _T("Name"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 250; - ListView_InsertColumn(hwndList, 2, &col); - memset(&col, 0, sizeof(col)); - col.pszText = _T("Creation date"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 3, &col); - memset(&col, 0, sizeof(col)); - col.pszText = _T("Expiration date"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 4, &col); - memset(&col, 0, sizeof(col)); - col.pszText = _T("Key length"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 30; - ListView_InsertColumn(hwndList, 5, &col); - ListView_SetExtendedListViewStyleEx(hwndList, 0, LVS_EX_FULLROWSELECT); - int i = 1, iRow = 0; - { - item.mask = LVIF_TEXT; - item.iItem = i; - item.iSubItem = 0; - item.pszText = _T(""); - {//parse gpg output - string out; - DWORD code; - string::size_type p = 0, p2 = 0, stop = 0; - { - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"--list-keys"); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - break; - if(result == pxNotFound) - break; - } - while(p != string::npos) - { - if((p = out.find("pub ", p)) == string::npos) - break; - p += 5; - if(p < stop) - break; - stop = p; - p2 = out.find("/", p) - 1; - TCHAR *tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - item.pszText = tmp; - iRow = ListView_InsertItem(hwndList, &item); - ListView_SetItemText(hwndList, iRow, 5, tmp); - mir_free(tmp); - p2+=2; - p = out.find(" ", p2); - tmp = mir_wstrdup(toUTF16(out.substr(p2,p-p2)).c_str()); - ListView_SetItemText(hwndList, iRow, 0, tmp); - mir_free(tmp); - p++; - p2 = out.find("\n", p); - string::size_type p3 = out.substr(p, p2-p).find("["); - if(p3 != string::npos) + LVCOLUMN col = { 0 }; + LVITEM item = { 0 }; + NMLISTVIEW * hdr = (NMLISTVIEW *)lParam; + TCHAR id[16] = { 0 }; + switch (msg) { + case WM_INITDIALOG: + { + SetWindowPos(hwndDlg, 0, load_existing_key_rect.left, load_existing_key_rect.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); + TranslateDialogDefault(hwndDlg); + col.pszText = _T("Key ID"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 50; + ListView_InsertColumn(hwndList, 0, &col); + memset(&col, 0, sizeof(col)); + col.pszText = _T("Email"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 1, &col); + memset(&col, 0, sizeof(col)); + col.pszText = _T("Name"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 250; + ListView_InsertColumn(hwndList, 2, &col); + memset(&col, 0, sizeof(col)); + col.pszText = _T("Creation date"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 3, &col); + memset(&col, 0, sizeof(col)); + col.pszText = _T("Expiration date"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 4, &col); + memset(&col, 0, sizeof(col)); + col.pszText = _T("Key length"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 30; + ListView_InsertColumn(hwndList, 5, &col); + ListView_SetExtendedListViewStyleEx(hwndList, 0, LVS_EX_FULLROWSELECT); + int i = 1, iRow = 0; + { + item.mask = LVIF_TEXT; + item.iItem = i; + item.iSubItem = 0; + item.pszText = _T(""); + {//parse gpg output + string out; + DWORD code; + string::size_type p = 0, p2 = 0, stop = 0; { - p3+=p; - p2 = p3; - p2--; - p3++; - p3+=mir_strlen("expires: "); - string::size_type p4 = out.find("]", p3); - tmp = mir_wstrdup(toUTF16(out.substr(p3,p4-p3)).c_str()); - ListView_SetItemText(hwndList, iRow, 4, tmp); + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"--list-keys"); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) + break; + if (result == pxNotFound) + break; + } + while (p != string::npos) { + if ((p = out.find("pub ", p)) == string::npos) + break; + p += 5; + if (p < stop) + break; + stop = p; + p2 = out.find("/", p) - 1; + TCHAR *tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + item.pszText = tmp; + iRow = ListView_InsertItem(hwndList, &item); + ListView_SetItemText(hwndList, iRow, 5, tmp); + mir_free(tmp); + p2 += 2; + p = out.find(" ", p2); + tmp = mir_wstrdup(toUTF16(out.substr(p2, p - p2)).c_str()); + ListView_SetItemText(hwndList, iRow, 0, tmp); + mir_free(tmp); + p++; + p2 = out.find("\n", p); + string::size_type p3 = out.substr(p, p2 - p).find("["); + if (p3 != string::npos) { + p3 += p; + p2 = p3; + p2--; + p3++; + p3 += mir_strlen("expires: "); + string::size_type p4 = out.find("]", p3); + tmp = mir_wstrdup(toUTF16(out.substr(p3, p4 - p3)).c_str()); + ListView_SetItemText(hwndList, iRow, 4, tmp); + mir_free(tmp); + } + else + p2--; + tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + ListView_SetItemText(hwndList, iRow, 3, tmp); + mir_free(tmp); + p = out.find("uid ", p); + p += mir_strlen("uid "); + p2 = out.find("\n", p); + p3 = out.substr(p, p2 - p).find("<"); + if (p3 != string::npos) { + p3 += p; + p2 = p3; + p2--; + p3++; + string::size_type p4 = out.find(">", p3); + tmp = mir_wstrdup(toUTF16(out.substr(p3, p4 - p3)).c_str()); + ListView_SetItemText(hwndList, iRow, 1, tmp); + mir_free(tmp); + } + else + p2--; + p = out.find_first_not_of(" ", p); + tmp = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); + ListView_SetItemText(hwndList, iRow, 2, tmp); mir_free(tmp); + // p = out.find("sub ", p2) + 6; + // p = out.find(" ", p) + 1; + // p2 = out.find("\n", p); + // tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p-1)).c_str()); + // ListView_SetItemText(hwndList, iRow, 3, tmp); + // mir_free(tmp); + ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE);// not sure about this + ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 5, LVSCW_AUTOSIZE); + i++; } - else - p2--; - tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - ListView_SetItemText(hwndList, iRow, 3, tmp); - mir_free(tmp); - p = out.find("uid ", p); - p+= mir_strlen("uid "); - p2 = out.find("\n", p); - p3 = out.substr(p, p2-p).find("<"); - if(p3 != string::npos) - { - p3+=p; - p2=p3; - p2--; - p3++; - string::size_type p4 = out.find(">", p3); - tmp = mir_wstrdup(toUTF16(out.substr(p3,p4-p3)).c_str()); - ListView_SetItemText(hwndList, iRow, 1, tmp); + } + } + return TRUE; + } + case WM_COMMAND: + switch (LOWORD(wParam)) { + case IDOK: + { + ListView_GetItemText(hwndList, itemnum2, 0, id, _countof(id)); + extern HWND hPubKeyEdit; + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--batch"); + cmd.push_back(L"-a"); + cmd.push_back(L"--export"); + cmd.push_back(id); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) + break; + if (result == pxNotFound) + break; + string::size_type s = 0; + while ((s = out.find("\r", s)) != string::npos) { + out.erase(s, 1); + } + std::string::size_type p1 = 0, p2 = 0; + p1 = out.find("-----BEGIN PGP PUBLIC KEY BLOCK-----"); + if (p1 != std::string::npos) { + p2 = out.find("-----END PGP PUBLIC KEY BLOCK-----", p1); + if (p2 != std::string::npos) { + p2 += mir_strlen("-----END PGP PUBLIC KEY BLOCK-----"); + out = out.substr(p1, p2 - p1); + TCHAR *tmp = mir_a2t(out.c_str()); + SetWindowText(hPubKeyEdit, tmp); mir_free(tmp); } else - p2--; - p = out.find_first_not_of(" ", p); - tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); - ListView_SetItemText(hwndList, iRow, 2, tmp); - mir_free(tmp); -// p = out.find("sub ", p2) + 6; -// p = out.find(" ", p) + 1; -// p2 = out.find("\n", p); -// tmp = mir_wstrdup(toUTF16(out.substr(p,p2-p-1)).c_str()); -// ListView_SetItemText(hwndList, iRow, 3, tmp); -// mir_free(tmp); - ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE);// not sure about this - ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 5, LVSCW_AUTOSIZE); - i++; + MessageBox(NULL, TranslateT("Failed to export public key."), TranslateT("Error"), MB_OK); } + else + MessageBox(NULL, TranslateT("Failed to export public key."), TranslateT("Error"), MB_OK); + // SetDlgItemText(hPubKeyEdit, IDC_PUBLIC_KEY_EDIT, tmp); } + DestroyWindow(hwndDlg); + break; + case IDCANCEL: + DestroyWindow(hwndDlg); + break; } - return TRUE; - } - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDOK: - { - ListView_GetItemText(hwndList, itemnum2, 0, id, _countof(id)); - extern HWND hPubKeyEdit; - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"-a"); - cmd.push_back(L"--export"); - cmd.push_back(id); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - break; - if(result == pxNotFound) - break; - string::size_type s = 0; - while((s = out.find("\r", s)) != string::npos) - { - out.erase(s, 1); - } - std::string::size_type p1 = 0, p2 = 0; - p1 = out.find("-----BEGIN PGP PUBLIC KEY BLOCK-----"); - if(p1 != std::string::npos) - { - p2 = out.find("-----END PGP PUBLIC KEY BLOCK-----", p1); - if(p2 != std::string::npos) - { - p2 += mir_strlen("-----END PGP PUBLIC KEY BLOCK-----"); - out = out.substr(p1, p2-p1); - TCHAR *tmp = mir_a2t(out.c_str()); - SetWindowText(hPubKeyEdit, tmp); - mir_free(tmp); - } - else - MessageBox(NULL, TranslateT("Failed to export public key."), TranslateT("Error"), MB_OK); - } - else - MessageBox(NULL, TranslateT("Failed to export public key."), TranslateT("Error"), MB_OK); -// SetDlgItemText(hPubKeyEdit, IDC_PUBLIC_KEY_EDIT, tmp); - } - DestroyWindow(hwndDlg); - break; - case IDCANCEL: - DestroyWindow(hwndDlg); - break; - } - break; - } - - case WM_NOTIFY: - { - if(hdr && IsWindowVisible(hdr->hdr.hwndFrom) && hdr->iItem != (-1)) - { - if(hdr->hdr.code == NM_CLICK) - { + break; + + case WM_NOTIFY: + if (hdr && IsWindowVisible(hdr->hdr.hwndFrom) && hdr->iItem != (-1)) { + if (hdr->hdr.code == NM_CLICK) { EnableWindow(GetDlgItem(hwndDlg, IDOK), 1); itemnum2 = hdr->iItem; } } - switch (((LPNMHDR)lParam)->code) - { - - case PSN_APPLY: - { - return TRUE; - } - } - } - break; + switch (((LPNMHDR)lParam)->code) { + case PSN_APPLY: + return TRUE; + } + break; + case WM_CLOSE: DestroyWindow(hwndDlg); break; + case WM_DESTROY: - { - GetWindowRect(hwndDlg, &load_existing_key_rect); - db_set_dw(NULL, szGPGModuleName, "LoadExistingKeyWindowX", load_existing_key_rect.left); - db_set_dw(NULL, szGPGModuleName, "LoadExistingKeyWindowY", load_existing_key_rect.top); - } + GetWindowRect(hwndDlg, &load_existing_key_rect); + db_set_dw(NULL, szGPGModuleName, "LoadExistingKeyWindowX", load_existing_key_rect.left); + db_set_dw(NULL, szGPGModuleName, "LoadExistingKeyWindowY", load_existing_key_rect.top); hwndSelectExistingKey = NULL; break; + } - } - - return FALSE; + return FALSE; } static INT_PTR CALLBACK DlgProcImportKeyDialog(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM) @@ -1904,7 +1771,7 @@ static INT_PTR CALLBACK DlgProcImportKeyDialog(HWND hwndDlg, UINT msg, WPARAM wP { hContact = new_key_hcnt; new_key_hcnt_mutex.unlock(); - SetWindowPos(hwndDlg, 0 , import_key_rect.left, import_key_rect.top, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW); + SetWindowPos(hwndDlg, 0, import_key_rect.left, import_key_rect.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); TranslateDialogDefault(hwndDlg); ComboBoxAddStringUtf(GetDlgItem(hwndDlg, IDC_KEYSERVER), _T("subkeys.pgp.net"), 0); ComboBoxAddStringUtf(GetDlgItem(hwndDlg, IDC_KEYSERVER), _T("keys.gnupg.net"), 0); @@ -1919,10 +1786,10 @@ static INT_PTR CALLBACK DlgProcImportKeyDialog(HWND hwndDlg, UINT msg, WPARAM wP DWORD code; std::vector cmd; cmd.push_back(L"--keyserver"); - TCHAR *server= new TCHAR [128]; + TCHAR *server = new TCHAR[128]; GetDlgItemText(hwndDlg, IDC_KEYSERVER, server, 128); cmd.push_back(server); - delete [] server; + delete[] server; cmd.push_back(L"--recv-keys"); cmd.push_back(toUTF16(hcontact_data[hContact].key_in_prescense)); gpg_execution_params params(cmd); @@ -1955,8 +1822,7 @@ extern HINSTANCE hInst; void ShowFirstRunDialog() { - if (hwndFirstRun == NULL) - { + if (hwndFirstRun == NULL) { hwndFirstRun = CreateDialog(hInst, MAKEINTRESOURCE(IDD_FIRST_RUN), NULL, DlgProcFirstRun); } SetForegroundWindow(hwndFirstRun); @@ -1965,8 +1831,7 @@ void ShowFirstRunDialog() void ShowSetDirsDialog() { - if (hwndSetDirs == NULL) - { + if (hwndSetDirs == NULL) { hwndSetDirs = CreateDialog(hInst, MAKEINTRESOURCE(IDD_BIN_PATH), NULL, DlgProcGpgBinOpts); } SetForegroundWindow(hwndSetDirs); @@ -1980,8 +1845,7 @@ void ShowNewKeyDialog() void ShowKeyGenDialog() { - if (hwndKeyGen == NULL) - { + if (hwndKeyGen == NULL) { hwndKeyGen = CreateDialog(hInst, MAKEINTRESOURCE(IDD_KEY_GEN), NULL, DlgProcKeyGenDialog); } SetForegroundWindow(hwndKeyGen); @@ -1989,8 +1853,7 @@ void ShowKeyGenDialog() void ShowSelectExistingKeyDialog() { - if (hwndSelectExistingKey == NULL) - { + if (hwndSelectExistingKey == NULL) { hwndSelectExistingKey = CreateDialog(hInst, MAKEINTRESOURCE(IDD_LOAD_EXISTING_KEY), NULL, DlgProcLoadExistingKey); } SetForegroundWindow(hwndSelectExistingKey); @@ -2001,19 +1864,17 @@ void ShowImportKeyDialog() CreateDialog(hInst, MAKEINTRESOURCE(IDD_IMPORT_KEY), NULL, DlgProcImportKeyDialog); } - - - void FirstRun() { - if(!db_get_b(NULL, szGPGModuleName, "FirstRun", 1)) + if (!db_get_b(NULL, szGPGModuleName, "FirstRun", 1)) return; ShowSetDirsDialog(); } void InitCheck() { - {//parse gpg output + { + // parse gpg output TCHAR *current_home = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); db_set_ts(NULL, szGPGModuleName, "szHomePath", _T("")); //we do not need home for gpg binary validation gpg_valid = isGPGValid(); @@ -2027,10 +1888,9 @@ void InitCheck() test_path += toUTF16(get_random(13)); wfstream test_file; test_file.open(test_path, std::ios::trunc | std::ios::out); - if(test_file.is_open() && test_file.good()) - { - test_file<<_T("access_test\n"); - if(test_file.good()) + if (test_file.is_open() && test_file.good()) { + test_file << _T("access_test\n"); + if (test_file.good()) home_dir_access = true; test_file.close(); boost::filesystem::remove(test_path); @@ -2040,25 +1900,23 @@ void InitCheck() test_path += _T("/"); test_path += toUTF16(get_random(13)); test_file.open(test_path, std::ios::trunc | std::ios::out); - if(test_file.is_open() && test_file.good()) - { - test_file<<_T("access_test\n"); - if(test_file.good()) + if (test_file.is_open() && test_file.good()) { + test_file << _T("access_test\n"); + if (test_file.good()) temp_access = true; test_file.close(); boost::filesystem::remove(test_path); } - if(!home_dir_access || !temp_access || !gpg_valid) - { + if (!home_dir_access || !temp_access || !gpg_valid) { TCHAR buf[4096]; - _tcsncpy(buf, gpg_valid?TranslateT("GPG binary is set and valid (this is good).\n"):TranslateT("GPG binary unset or invalid (plugin will not work).\n"), _countof(buf)); - mir_tstrncat(buf, home_dir_access?TranslateT("Home dir write access granted (this is good).\n"):TranslateT("Home dir has no write access (plugin most probably will not work).\n"), _countof(buf) - mir_tstrlen(buf)); - mir_tstrncat(buf, temp_access?TranslateT("Temp dir write access granted (this is good).\n"):TranslateT("Temp dir has no write access (plugin should work, but may have some problems, file transfers will not work)."), _countof(buf) - mir_tstrlen(buf)); - if(!gpg_valid) + _tcsncpy(buf, gpg_valid ? TranslateT("GPG binary is set and valid (this is good).\n") : TranslateT("GPG binary unset or invalid (plugin will not work).\n"), _countof(buf)); + mir_tstrncat(buf, home_dir_access ? TranslateT("Home dir write access granted (this is good).\n") : TranslateT("Home dir has no write access (plugin most probably will not work).\n"), _countof(buf) - mir_tstrlen(buf)); + mir_tstrncat(buf, temp_access ? TranslateT("Temp dir write access granted (this is good).\n") : TranslateT("Temp dir has no write access (plugin should work, but may have some problems, file transfers will not work)."), _countof(buf) - mir_tstrlen(buf)); + if (!gpg_valid) mir_tstrncat(buf, TranslateT("\nGPG will be disabled until you solve these problems"), _countof(buf) - mir_tstrlen(buf)); MessageBox(0, buf, TranslateT("GPG plugin problems"), MB_OK); } - if(!gpg_valid) + if (!gpg_valid) return; gpg_keyexist = isGPGKeyExist(); string out; @@ -2073,9 +1931,9 @@ void InitCheck() params.out = &out; params.code = &code; params.result = &result; - if(!gpg_launcher(params)) + if (!gpg_launcher(params)) return; - if(result == pxNotFound) + if (result == pxNotFound) return; } home_dir = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); @@ -2087,13 +1945,11 @@ void InitCheck() PROTOACCOUNT **accounts; Proto_EnumAccounts(&count, &accounts); string question; - //char *keyid = nullptr, *key = nullptr; char *keyid = nullptr; - for(int i = 0; i < count; i++) - { - if(StriStr(accounts[i]->szModuleName, "metacontacts")) + for (int i = 0; i < count; i++) { + if (StriStr(accounts[i]->szModuleName, "metacontacts")) continue; - if(StriStr(accounts[i]->szModuleName, "weather")) + if (StriStr(accounts[i]->szModuleName, "weather")) continue; std::string acc = toUTF8(accounts[i]->tszAccountName); acc += "("; @@ -2101,68 +1957,60 @@ void InitCheck() acc += ")"; acc += "_KeyID"; keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, acc.c_str(), ""); - if(keyid[0]) - { + if (keyid[0]) { question = Translate("Your secret key with ID: "); mir_free(keyid); keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); - //key = UniGetContactSettingUtf(NULL, szGPGModuleName, "GPGPubKey", ""); - if((p = out.find(keyid)) == string::npos) - { + if ((p = out.find(keyid)) == string::npos) { question += keyid; question += Translate(" for account "); question += toUTF8(accounts[i]->tszAccountName); question += Translate(" deleted from GPG secret keyring.\nDo you want to set another key?"); - if(MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) + if (MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) ShowFirstRunDialog(); } p2 = p; p = out.find("[", p); p2 = out.find("\n", p2); - if((p != std::string::npos) && (p < p2)) - { + if ((p != std::string::npos) && (p < p2)) { p = out.find("expires:", p); p += mir_strlen("expires:"); p++; p2 = out.find("]", p); - TCHAR *expire_date = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); + TCHAR *expire_date = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); bool expired = false; { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); TCHAR buf[5]; _tcsncpy_s(buf, expire_date, _TRUNCATE); int year = _ttoi(buf); - if(year < now.date().year()) + if (year < now.date().year()) expired = true; - else if(year == now.date().year()) - { + else if (year == now.date().year()) { _tcsncpy_s(buf, (expire_date + 5), _TRUNCATE); int month = _ttoi(buf); - if(month < now.date().month()) + if (month < now.date().month()) expired = true; - else if(month == now.date().month()) - { + else if (month == now.date().month()) { _tcsncpy_s(buf, (expire_date + 8), _TRUNCATE); unsigned day = _ttoi(buf); - if(day <= now.date().day_number()) + if (day <= now.date().day_number()) expired = true; } } } - if(expired) - { + if (expired) { question += keyid; question += Translate(" for account "); question += toUTF8(accounts[i]->tszAccountName); question += Translate(" expired and will not work.\nDo you want to set another key?"); - if(MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) + if (MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) ShowFirstRunDialog(); } mir_free(expire_date); } } - if(keyid) - { + if (keyid) { mir_free(keyid); keyid = nullptr; } @@ -2170,77 +2018,69 @@ void InitCheck() question = Translate("Your secret key with ID: "); keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); char *key = UniGetContactSettingUtf(NULL, szGPGModuleName, "GPGPubKey", ""); - if(!db_get_b(NULL, szGPGModuleName, "FirstRun", 1) && (!keyid[0] || !key[0])) - { + if (!db_get_b(NULL, szGPGModuleName, "FirstRun", 1) && (!keyid[0] || !key[0])) { question = Translate("You didn't set a private key.\nWould you like to set it now?"); - if(MessageBoxA(0, question.c_str(), Translate("Own private key warning"), MB_YESNO) == IDYES) + if (MessageBoxA(0, question.c_str(), Translate("Own private key warning"), MB_YESNO) == IDYES) ShowFirstRunDialog(); } - if((p = out.find(keyid)) == string::npos) - { + if ((p = out.find(keyid)) == string::npos) { question += keyid; question += Translate(" deleted from GPG secret keyring.\nDo you want to set another key?"); - if(MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) + if (MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) ShowFirstRunDialog(); } p2 = p; p = out.find("[", p); p2 = out.find("\n", p2); - if((p != std::string::npos) && (p < p2)) - { + if ((p != std::string::npos) && (p < p2)) { p = out.find("expires:", p); p += mir_strlen("expires:"); p++; p2 = out.find("]", p); - TCHAR *expire_date = mir_wstrdup(toUTF16(out.substr(p,p2-p)).c_str()); + TCHAR *expire_date = mir_wstrdup(toUTF16(out.substr(p, p2 - p)).c_str()); bool expired = false; { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); TCHAR buf[5]; _tcsncpy_s(buf, expire_date, _TRUNCATE); int year = _ttoi(buf); - if(year < now.date().year()) + if (year < now.date().year()) expired = true; - else if(year == now.date().year()) - { + else if (year == now.date().year()) { _tcsncpy_s(buf, (expire_date + 5), _TRUNCATE); int month = _ttoi(buf); - if(month < now.date().month()) + if (month < now.date().month()) expired = true; - else if(month == now.date().month()) - { + else if (month == now.date().month()) { _tcsncpy_s(buf, (expire_date + 8), _TRUNCATE); unsigned day = _ttoi(buf); - if(day <= now.date().day_number()) + if (day <= now.date().day_number()) expired = true; } } } - if(expired) - { + if (expired) { question += keyid; question += Translate(" expired and will not work.\nDo you want to set another key?"); - if(MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) + if (MessageBoxA(0, question.c_str(), Translate("Own secret key warning"), MB_YESNO) == IDYES) ShowFirstRunDialog(); } mir_free(expire_date); } - //TODO: check for expired key + // TODO: check for expired key mir_free(keyid); mir_free(key); } { TCHAR *path = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); DWORD dwFileAttr = GetFileAttributes(path); - if (dwFileAttr != INVALID_FILE_ATTRIBUTES) - { - dwFileAttr &=~ FILE_ATTRIBUTE_READONLY; + if (dwFileAttr != INVALID_FILE_ATTRIBUTES) { + dwFileAttr &= ~FILE_ATTRIBUTE_READONLY; SetFileAttributes(path, dwFileAttr); } mir_free(path); } - if(bAutoExchange) - { + if (bAutoExchange) { int count = 0; PROTOACCOUNT **accounts; Proto_EnumAccounts(&count, &accounts); @@ -2250,12 +2090,11 @@ void InitCheck() strncpy(cap.name, "GPG Key AutoExchange", MAX_CAPNAME); strncpy(cap.caps, "GPGAutoExchange", sizeof(cap.caps)); - for(int i = 0; i < count; i++) - if( ProtoServiceExists(accounts[i]->szProtoName, PS_ICQ_ADDCAPABILITY)) + for (int i = 0; i < count; i++) + if (ProtoServiceExists(accounts[i]->szProtoName, PS_ICQ_ADDCAPABILITY)) CallProtoService(accounts[i]->szProtoName, PS_ICQ_ADDCAPABILITY, 0, (LPARAM)&cap); } - if(bFileTransfers) - { + if (bFileTransfers) { int count = 0; PROTOACCOUNT **accounts; Proto_EnumAccounts(&count, &accounts); @@ -2265,8 +2104,8 @@ void InitCheck() strncpy(cap.name, "GPG Encrypted FileTransfers", MAX_CAPNAME); strncpy(cap.caps, "GPGFileTransfer", sizeof(cap.caps)); - for(int i = 0; i < count; i++) - if( ProtoServiceExists(accounts[i]->szProtoName, PS_ICQ_ADDCAPABILITY)) + for (int i = 0; i < count; i++) + if (ProtoServiceExists(accounts[i]->szProtoName, PS_ICQ_ADDCAPABILITY)) CallProtoService(accounts[i]->szProtoName, PS_ICQ_ADDCAPABILITY, 0, (LPARAM)&cap); } } @@ -2276,17 +2115,15 @@ void ImportKey() MCONTACT hContact = new_key_hcnt; new_key_hcnt_mutex.unlock(); bool for_all_sub = false; - if(db_mc_isMeta(hContact)) { - if(MessageBox(0, TranslateT("Do you want to load key for all subcontacts?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) + if (db_mc_isMeta(hContact)) { + if (MessageBox(0, TranslateT("Do you want to load key for all subcontacts?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) for_all_sub = true; - if(for_all_sub) - { + if (for_all_sub) { int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) + if (hcnt) db_set_ts(hcnt, szGPGModuleName, "GPGPubKey", new_key.c_str()); } } @@ -2295,265 +2132,232 @@ void ImportKey() else db_set_ts(hContact, szGPGModuleName, "GPGPubKey", new_key.c_str()); new_key.clear(); - { //gpg execute block - std::vector cmd; - TCHAR tmp2[MAX_PATH] = {0}; - TCHAR *ptmp; - string output; - DWORD exitcode; - { - ptmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - _tcsncpy(tmp2, ptmp, MAX_PATH-1); - mir_free(ptmp); - mir_tstrncat(tmp2, _T("\\"), _countof(tmp2) - mir_tstrlen(tmp2)); - mir_tstrncat(tmp2, _T("temporary_exported.asc"), _countof(tmp2) - mir_tstrlen(tmp2)); - boost::filesystem::remove(tmp2); - wfstream f(tmp2, std::ios::out); - if(db_mc_isMeta(hContact)) - ptmp = UniGetContactSettingUtf(metaGetMostOnline(hContact), szGPGModuleName, "GPGPubKey", _T("")); - else - ptmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", _T("")); - wstring new_key = ptmp; - mir_free(ptmp); - f< output.find("<", s)) - s2 = output.find("<", s); - if(s != string::npos && s2 != string::npos) - { - tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s,s2-s-(uncommon?1:0)).length()+1)); - mir_strcpy(tmp, output.substr(s,s2-s-(uncommon?1:0)).c_str()); - mir_utf8decode(tmp, 0); - db_set_s(hcnt, szGPGModuleName, "KeyMainName", tmp); - mir_free(tmp); - } - if((s = output.find(")", s2)) == string::npos) - s = output.find(">", s2); - else if(s > output.find(">", s2)) - s = output.find(">", s2); - s2++; - if(s != string::npos && s2 != string::npos) - { - if(output[s] == ')') - { - tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2,s-s2).length()+1)); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); - mir_utf8decode(tmp, 0); - db_set_s(hcnt, szGPGModuleName, "KeyComment", tmp); - mir_free(tmp); - s+=3; - s2 = output.find(">", s); - if(s != string::npos && s2 != string::npos) - { - tmp = (char*) mir_alloc(sizeof(char)*(output.substr(s,s2-s).length()+1)); - mir_strcpy(tmp, output.substr(s,s2-s).c_str()); - mir_utf8decode(tmp, 0); - db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", tmp); - mir_free(tmp); - } - } - else - { - tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2,s-s2).length()+1)); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); - mir_utf8decode(tmp, 0); - db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); - mir_free(tmp); - } - } - db_unset(hcnt, szGPGModuleName, "bAlwatsTrust"); - } - } - } - else - { + // gpg execute block + std::vector cmd; + TCHAR tmp2[MAX_PATH] = { 0 }; + { + _tcsncpy(tmp2, ptrT(UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T(""))), MAX_PATH - 1); + mir_tstrncat(tmp2, _T("\\"), _countof(tmp2) - mir_tstrlen(tmp2)); + mir_tstrncat(tmp2, _T("temporary_exported.asc"), _countof(tmp2) - mir_tstrlen(tmp2)); + boost::filesystem::remove(tmp2); + + ptrT ptmp; + if (db_mc_isMeta(hContact)) + ptmp = UniGetContactSettingUtf(metaGetMostOnline(hContact), szGPGModuleName, "GPGPubKey", _T("")); + else + ptmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", _T("")); + + wfstream f(tmp2, std::ios::out); + f << ptmp; + f.close(); + cmd.push_back(L"--batch"); + cmd.push_back(L"--import"); + cmd.push_back(tmp2); + } + + gpg_execution_params params(cmd); + string output; + DWORD exitcode; + pxResult result; + params.out = &output; + params.code = &exitcode; + params.result = &result; + if (!gpg_launcher(params)) + return; + if (result == pxNotFound) + return; + + if (db_mc_isMeta(hContact)) { + if (for_all_sub) { + int count = db_mc_getSubCount(hContact); + for (int i = 0; i < count; i++) { + MCONTACT hcnt = db_mc_getSub(hContact, i); + if (hcnt) { char *tmp = NULL; string::size_type s = output.find("gpg: key ") + mir_strlen("gpg: key "); string::size_type s2 = output.find(":", s); - db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyID", output.substr(s,s2-s).c_str()); + db_set_s(hcnt, szGPGModuleName, "KeyID", output.substr(s, s2 - s).c_str()); s = output.find("“", s2); - if(s == string::npos) - { + if (s == string::npos) { s = output.find("\"", s2); s += 1; } - else - s += 3; + else s += 3; + bool uncommon = false; - if((s2 = output.find("(", s)) == string::npos) - { - if((s2 = output.find("<", s)) == string::npos) - { + if ((s2 = output.find("(", s)) == string::npos) { + if ((s2 = output.find("<", s)) == string::npos) { s2 = output.find("”", s); uncommon = true; } } - else if(s2 > output.find("<", s)) + else if (s2 > output.find("<", s)) s2 = output.find("<", s); - if(s != string::npos && s2 != string::npos) - { - tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s,s2-s-(uncommon?1:0)).length()+1)); - mir_strcpy(tmp, output.substr(s,s2-s-(uncommon?1:0)).c_str()); + if (s != string::npos && s2 != string::npos) { + tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s, s2 - s - (uncommon ? 1 : 0)).length() + 1)); + mir_strcpy(tmp, output.substr(s, s2 - s - (uncommon ? 1 : 0)).c_str()); mir_utf8decode(tmp, 0); - db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainName", tmp); + db_set_s(hcnt, szGPGModuleName, "KeyMainName", tmp); mir_free(tmp); } - if((s = output.find(")", s2)) == string::npos) + + if ((s = output.find(")", s2)) == string::npos) s = output.find(">", s2); - else if(s > output.find(">", s2)) + else if (s > output.find(">", s2)) s = output.find(">", s2); s2++; - if(s != string::npos && s2 != string::npos) - { - if(output[s] == ')') - { - tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2,s-s2).length()+1)); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); + if (s != string::npos && s2 != string::npos) { + if (output[s] == ')') { + tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2, s - s2).length() + 1)); + mir_strcpy(tmp, output.substr(s2, s - s2).c_str()); mir_utf8decode(tmp, 0); - db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyComment", tmp); + db_set_s(hcnt, szGPGModuleName, "KeyComment", tmp); mir_free(tmp); - s+=3; + s += 3; s2 = output.find(">", s); - if(s != string::npos && s2 != string::npos) - { - tmp = (char*) mir_alloc(sizeof(char)*(output.substr(s,s2-s).length()+1)); - mir_strcpy(tmp, output.substr(s,s2-s).c_str()); + if (s != string::npos && s2 != string::npos) { + tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s, s2 - s).length() + 1)); + mir_strcpy(tmp, output.substr(s, s2 - s).c_str()); mir_utf8decode(tmp, 0); - db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", tmp); + db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", tmp); mir_free(tmp); } } - else - { - tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2,s-s2).length()+1)); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); + else { + tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2, s - s2).length() + 1)); + mir_strcpy(tmp, output.substr(s2, s - s2).c_str()); mir_utf8decode(tmp, 0); - db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); + db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", output.substr(s2, s - s2).c_str()); mir_free(tmp); } } - db_unset(metaGetMostOnline(hContact), szGPGModuleName, "bAlwatsTrust"); + db_unset(hcnt, szGPGModuleName, "bAlwatsTrust"); } } + } + else { + char *tmp = NULL; + string::size_type s = output.find("gpg: key ") + mir_strlen("gpg: key "); + string::size_type s2 = output.find(":", s); + db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyID", output.substr(s, s2 - s).c_str()); + s = output.find("“", s2); + if (s == string::npos) { + s = output.find("\"", s2); + s += 1; + } else - { - char *tmp = NULL; - string::size_type s = output.find("gpg: key ") + mir_strlen("gpg: key "); - string::size_type s2 = output.find(":", s); - db_set_s(hContact, szGPGModuleName, "KeyID", output.substr(s,s2-s).c_str()); - s = output.find("“", s2); - if(s == string::npos) - { - s = output.find("\"", s2); - s += 1; + s += 3; + bool uncommon = false; + if ((s2 = output.find("(", s)) == string::npos) { + if ((s2 = output.find("<", s)) == string::npos) { + s2 = output.find("”", s); + uncommon = true; } - else + } + else if (s2 > output.find("<", s)) + s2 = output.find("<", s); + if (s != string::npos && s2 != string::npos) { + tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s, s2 - s - (uncommon ? 1 : 0)).length() + 1)); + mir_strcpy(tmp, output.substr(s, s2 - s - (uncommon ? 1 : 0)).c_str()); + mir_utf8decode(tmp, 0); + db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainName", tmp); + mir_free(tmp); + } + if ((s = output.find(")", s2)) == string::npos) + s = output.find(">", s2); + else if (s > output.find(">", s2)) + s = output.find(">", s2); + s2++; + if (s != string::npos && s2 != string::npos) { + if (output[s] == ')') { + tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2, s - s2).length() + 1)); + mir_strcpy(tmp, output.substr(s2, s - s2).c_str()); + mir_utf8decode(tmp, 0); + db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyComment", tmp); + mir_free(tmp); s += 3; - bool uncommon = false; - if((s2 = output.find("(", s)) == string::npos) - { - if((s2 = output.find("<", s)) == string::npos) - { - s2 = output.find("”", s); - uncommon = true; + s2 = output.find(">", s); + if (s != string::npos && s2 != string::npos) { + tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s, s2 - s).length() + 1)); + mir_strcpy(tmp, output.substr(s, s2 - s).c_str()); + mir_utf8decode(tmp, 0); + db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", tmp); + mir_free(tmp); } } - else if(s2 > output.find("<", s)) - s2 = output.find("<", s); - if(s != string::npos && s2 != string::npos) - { - tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s,s2-s-(uncommon?1:0)).length()+1)); - mir_strcpy(tmp, output.substr(s,s2-s-(uncommon?1:0)).c_str()); + else { + tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2, s - s2).length() + 1)); + mir_strcpy(tmp, output.substr(s2, s - s2).c_str()); mir_utf8decode(tmp, 0); - db_set_s(hContact, szGPGModuleName, "KeyMainName", tmp); + db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", output.substr(s2, s - s2).c_str()); mir_free(tmp); } - if((s = output.find(")", s2)) == string::npos) - s = output.find(">", s2); - else if(s > output.find(">", s2)) - s = output.find(">", s2); - s2++; - if(s != string::npos && s2 != string::npos) - { - if(output[s] == ')') - { - tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2,s-s2).length()+1)); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); - mir_utf8decode(tmp, 0); - db_set_s(hContact, szGPGModuleName, "KeyComment", tmp); - mir_free(tmp); - s+=3; - s2 = output.find(">", s); - if(s != string::npos && s2 != string::npos) - { - tmp = (char*) mir_alloc(sizeof(char)*(output.substr(s,s2-s).length()+1)); - mir_strcpy(tmp, output.substr(s,s2-s).c_str()); - mir_utf8decode(tmp, 0); - db_set_s(hContact, szGPGModuleName, "KeyMainEmail", tmp); - mir_free(tmp); - } - } - else - { - tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2,s-s2).length()+1)); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); - mir_utf8decode(tmp, 0); - db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); - mir_free(tmp); - } + } + db_unset(metaGetMostOnline(hContact), szGPGModuleName, "bAlwatsTrust"); + } + } + else { + char *tmp = NULL; + string::size_type s = output.find("gpg: key ") + mir_strlen("gpg: key "); + string::size_type s2 = output.find(":", s); + db_set_s(hContact, szGPGModuleName, "KeyID", output.substr(s, s2 - s).c_str()); + s = output.find("“", s2); + if (s == string::npos) { + s = output.find("\"", s2); + s += 1; + } + else + s += 3; + bool uncommon = false; + if ((s2 = output.find("(", s)) == string::npos) { + if ((s2 = output.find("<", s)) == string::npos) { + s2 = output.find("”", s); + uncommon = true; + } + } + else if (s2 > output.find("<", s)) + s2 = output.find("<", s); + if (s != string::npos && s2 != string::npos) { + tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s, s2 - s - (uncommon ? 1 : 0)).length() + 1)); + mir_strcpy(tmp, output.substr(s, s2 - s - (uncommon ? 1 : 0)).c_str()); + mir_utf8decode(tmp, 0); + db_set_s(hContact, szGPGModuleName, "KeyMainName", tmp); + mir_free(tmp); + } + if ((s = output.find(")", s2)) == string::npos) + s = output.find(">", s2); + else if (s > output.find(">", s2)) + s = output.find(">", s2); + s2++; + if (s != string::npos && s2 != string::npos) { + if (output[s] == ')') { + tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2, s - s2).length() + 1)); + mir_strcpy(tmp, output.substr(s2, s - s2).c_str()); + mir_utf8decode(tmp, 0); + db_set_s(hContact, szGPGModuleName, "KeyComment", tmp); + mir_free(tmp); + s += 3; + s2 = output.find(">", s); + if (s != string::npos && s2 != string::npos) { + tmp = (char*)mir_alloc(sizeof(char)*(output.substr(s, s2 - s).length() + 1)); + mir_strcpy(tmp, output.substr(s, s2 - s).c_str()); + mir_utf8decode(tmp, 0); + db_set_s(hContact, szGPGModuleName, "KeyMainEmail", tmp); + mir_free(tmp); } - db_unset(hContact, szGPGModuleName, "bAlwatsTrust"); + } + else { + tmp = (char*)mir_alloc(sizeof(char)* (output.substr(s2, s - s2).length() + 1)); + mir_strcpy(tmp, output.substr(s2, s - s2).c_str()); + mir_utf8decode(tmp, 0); + db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2, s - s2).c_str()); + mir_free(tmp); } } - ptmp = mir_wstrdup(toUTF16(output).c_str()); - MessageBox(0, ptmp, _T(""), MB_OK); - mir_free(ptmp); - boost::filesystem::remove(tmp2); + db_unset(hContact, szGPGModuleName, "bAlwatsTrust"); } -} \ No newline at end of file + + MessageBox(0, toUTF16(output).c_str(), _T(""), MB_OK); + boost::filesystem::remove(tmp2); +} diff --git a/plugins/New_GPG/src/messages.cpp b/plugins/New_GPG/src/messages.cpp index 3890e57e45..31efb228aa 100755 --- a/plugins/New_GPG/src/messages.cpp +++ b/plugins/New_GPG/src/messages.cpp @@ -25,116 +25,101 @@ int returnNoError(MCONTACT hContact); std::list sent_msgs; void RecvMsgSvc_func(MCONTACT hContact, std::wstring str, char *msg, DWORD, DWORD timestamp) -{ +{ DWORD dbflags = DBEF_UTF; - { //check for gpg related data - wstring::size_type s1 = wstring::npos, s2 = wstring::npos; - - s1 = str.find(_T("-----BEGIN PGP MESSAGE-----")); - s2 = str.find(_T("-----END PGP MESSAGE-----")); - if((s2 != wstring::npos) && (s1 != wstring::npos)) - { //this is generic encrypted data block - if(!isContactSecured(hContact)) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))+" with turned off encryption"); - if(MessageBox(0, TranslateT("We received encrypted message from contact with encryption turned off.\nDo you want to turn on encryption for this contact?"), TranslateT("Warning"), MB_YESNO) == IDYES) - { - if(!isContactHaveKey(hContact)) - { + { + // check for gpg related data + wstring::size_type s1 = str.find(_T("-----BEGIN PGP MESSAGE-----")); + wstring::size_type s2 = str.find(_T("-----END PGP MESSAGE-----")); + if (s2 != wstring::npos && s1 != wstring::npos) { //this is generic encrypted data block + if (!isContactSecured(hContact)) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: received encrypted message from: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " with turned off encryption"); + if (MessageBox(0, TranslateT("We received encrypted message from contact with encryption turned off.\nDo you want to turn on encryption for this contact?"), TranslateT("Warning"), MB_YESNO) == IDYES) { + if (!isContactHaveKey(hContact)) { void ShowLoadPublicKeyDialog(); item_num = 0; //black magic here user_data[1] = hContact; ShowLoadPublicKeyDialog(); } - else - { - db_set_b(db_mc_isMeta(hContact)?metaGetMostOnline(hContact):hContact, szGPGModuleName, "GPGEncryption", 1); + else { + db_set_b(db_mc_isMeta(hContact) ? metaGetMostOnline(hContact) : hContact, szGPGModuleName, "GPGEncryption", 1); setSrmmIcon(hContact); setClistIcon(hContact); } - if(isContactHaveKey(hContact)) - { - db_set_b(db_mc_isMeta(hContact)?metaGetMostOnline(hContact):hContact, szGPGModuleName, "GPGEncryption", 1); + if (isContactHaveKey(hContact)) { + db_set_b(db_mc_isMeta(hContact) ? metaGetMostOnline(hContact) : hContact, szGPGModuleName, "GPGEncryption", 1); setSrmmIcon(hContact); setClistIcon(hContact); } } - else if(MessageBox(0, TranslateT("Do you want to try to decrypt encrypted message?"), TranslateT("Warning"), MB_YESNO) == IDNO) - { + else if (MessageBox(0, TranslateT("Do you want to try to decrypt encrypted message?"), TranslateT("Warning"), MB_YESNO) == IDNO) { HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); return; } } - else if(bDebugLog) - { - debuglog<pfnGetContactDisplayName(hContact, 0))); + else if (bDebugLog) { + debuglog << std::string(time_str() + ": info: received encrypted message from: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); } boost::algorithm::erase_all(str, "\r"); s2 += mir_tstrlen(_T("-----END PGP MESSAGE-----")); - char *tmp = mir_t2a(str.substr(s1,s2-s1).c_str()); - TCHAR *tmp2 = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - wstring path = tmp2; + + ptrT ptszHomePath(UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T(""))); wstring encfile = toUTF16(get_random(10)); wstring decfile = toUTF16(get_random(10)); - path.append(_T("\\tmp\\")); - path.append(encfile); - boost::filesystem::remove(path); - fstream f(path.c_str(), std::ios::out); - while(!f.is_open()) - f.open(path.c_str(), std::ios::out); - f< cmd; cmd.push_back(L"--batch"); { - char *inkeyid = UniGetContactSettingUtf(db_mc_isMeta(hContact)?metaGetMostOnline(hContact):hContact, szGPGModuleName, "InKeyID", ""); + char *inkeyid = UniGetContactSettingUtf(db_mc_isMeta(hContact) ? metaGetMostOnline(hContact) : hContact, szGPGModuleName, "InKeyID", ""); TCHAR *pass = NULL; - if(inkeyid[0]) - { + if (inkeyid[0]) { string dbsetting = "szKey_"; dbsetting += inkeyid; dbsetting += "_Password"; pass = UniGetContactSettingUtf(NULL, szGPGModuleName, dbsetting.c_str(), _T("")); - if(pass[0] && bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))+" with password"); + if (pass[0] && bDebugLog) + debuglog << std::string(time_str() + ": info: found password in database for key ID: " + inkeyid + ", trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " with password"); } - else - { + else { pass = UniGetContactSettingUtf(NULL, szGPGModuleName, "szKeyPassword", _T("")); - if(pass[0] && bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))+" with password"); + if (pass[0] && bDebugLog) + debuglog << std::string(time_str() + ": info: found password for all keys in database, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " with password"); } - if(pass && pass[0]) - { + if (pass && pass[0]) { cmd.push_back(L"--passphrase"); cmd.push_back(pass); } - else if(password && password[0]) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))+" with password"); + else if (password && password[0]) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: found password in memory, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " with password"); cmd.push_back(L"--passphrase"); cmd.push_back(password); } else if (bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))+" with out password"); + debuglog << std::string(time_str() + ": info: passwords not found in database or memory, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " with out password"); mir_free(pass); mir_free(inkeyid); } - { - wstring path = tmp2; - path += _T("\\tmp\\"); - path += decfile; - boost::filesystem::remove(path); - } + + boost::filesystem::remove(wstring(ptszHomePath) + _T("\\tmp\\") + decfile); + cmd.push_back(L"--output"); - cmd.push_back(std::wstring(tmp2) + L"\\tmp\\" + decfile); + cmd.push_back(std::wstring(ptszHomePath) + L"\\tmp\\" + decfile); cmd.push_back(L"-d"); cmd.push_back(L"-a"); cmd.push_back(path); @@ -143,8 +128,7 @@ void RecvMsgSvc_func(MCONTACT hContact, std::wstring str, char *msg, DWORD, DWOR params.out = &out; params.code = &code; params.result = &result; - if(!gpg_launcher(params)) - { + if (!gpg_launcher(params)) { boost::filesystem::remove(path); HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); BYTE enc = db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0); @@ -154,14 +138,12 @@ void RecvMsgSvc_func(MCONTACT hContact, std::wstring str, char *msg, DWORD, DWOR db_set_b(hContact, szGPGModuleName, "GPGEncryption", enc); return; } - if(result == pxNotFound) - { + if (result == pxNotFound) { boost::filesystem::remove(path); HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); return; } - if(result == pxSuccessExitCodeInvalid) - { + if (result == pxSuccessExitCodeInvalid) { boost::filesystem::remove(path); HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); HistoryLog(hContact, db_event(Translate("failed to decrypt message, GPG returned error, turn on debug log for more details"), timestamp, 0, 0)); @@ -170,12 +152,10 @@ void RecvMsgSvc_func(MCONTACT hContact, std::wstring str, char *msg, DWORD, DWOR //TODO: check gpg output for errors _terminate = false; - while(out.find("public key decryption failed: bad passphrase") != string::npos) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))+" password needed, trying to get one"); - if(_terminate) - { + while (out.find("public key decryption failed: bad passphrase") != string::npos) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: failed to decrypt messaage from " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " password needed, trying to get one"); + if (_terminate) { BYTE enc = db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0); db_set_b(hContact, szGPGModuleName, "GPGEncryption", 0); CallContactService(hContact, PSS_MESSAGE, 0, (LPARAM)"Unable to decrypt PGP encrypted message"); @@ -187,31 +167,28 @@ void RecvMsgSvc_func(MCONTACT hContact, std::wstring str, char *msg, DWORD, DWOR string::size_type s = out.find(" encrypted with "); s = out.find(" ID ", s); s += mir_strlen(" ID "); - string::size_type s2 = out.find(",",s); - db_set_s(db_mc_isMeta(hContact)?metaGetMostOnline(hContact):hContact, szGPGModuleName, "InKeyID", out.substr(s, s2-s).c_str()); + db_set_s(db_mc_isMeta(hContact) ? metaGetMostOnline(hContact) : hContact, szGPGModuleName, "InKeyID", out.substr(s, out.find(",", s) - s).c_str()); } void ShowLoadKeyPasswordWindow(); new_key_hcnt_mutex.lock(); new_key_hcnt = hContact; ShowLoadKeyPasswordWindow(); std::vector cmd2 = cmd; - if(password) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); - std::vector tmp; - tmp.push_back(L"--passphrase"); - tmp.push_back(password); - cmd2.insert(cmd2.begin(), tmp.begin(), tmp.end()); + if (password) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: found password in memory, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); + std::vector tmp3; + tmp3.push_back(L"--passphrase"); + tmp3.push_back(password); + cmd2.insert(cmd2.begin(), tmp3.begin(), tmp3.end()); } out.clear(); - gpg_execution_params params(cmd2); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) - { + gpg_execution_params params2(cmd2); + pxResult result2; + params2.out = &out; + params2.code = &code; + params2.result = &result2; + if (!gpg_launcher(params2)) { boost::filesystem::remove(path); HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); BYTE enc = db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0); @@ -221,16 +198,14 @@ void RecvMsgSvc_func(MCONTACT hContact, std::wstring str, char *msg, DWORD, DWOR db_set_b(hContact, szGPGModuleName, "GPGEncryption", enc); return; } - if(result == pxNotFound) - { + if (result2 == pxNotFound) { boost::filesystem::remove(path); HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); return; } } out.clear(); - if(!gpg_launcher(params)) - { + if (!gpg_launcher(params)) { boost::filesystem::remove(path); HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); BYTE enc = db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0); @@ -240,96 +215,77 @@ void RecvMsgSvc_func(MCONTACT hContact, std::wstring str, char *msg, DWORD, DWOR db_set_b(hContact, szGPGModuleName, "GPGEncryption", enc); return; } - if(result == pxNotFound) - { + if (result == pxNotFound) { boost::filesystem::remove(path); HistoryLog(hContact, db_event(msg, timestamp, 0, dbflags)); } - { - wstring tmp = tmp2; - tmp += _T("\\tmp\\"); - tmp += encfile; - boost::filesystem::remove(tmp); - } - { - wstring tmp = tmp2; - tmp += _T("\\tmp\\"); - tmp += decfile; - if(!boost::filesystem::exists(tmp)) - { - string str = msg; - str.insert(0, "Received unencrypted message:\n"); - if(bDebugLog) - debuglog<hContact)) - { - if(!strstr(msg, "-----BEGIN PGP MESSAGE-----")) + if (db_mc_isMeta(ccs->hContact)) { + if (!strstr(msg, "-----BEGIN PGP MESSAGE-----")) return Proto_ChainRecv(w, ccs); - else - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); + else { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: blocked pgp message to metacontact:" + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); return 0; } } wstring str = toUTF16(msg); - wstring::size_type s1 = wstring::npos, s2 = wstring::npos; - if(bAutoExchange && (str.find(_T("-----PGP KEY RESPONSE-----")) != wstring::npos)) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); + size_t s1, s2; + if (bAutoExchange && (str.find(_T("-----PGP KEY RESPONSE-----")) != wstring::npos)) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange): parsing key response:" + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); s2 = str.find(_T("-----END PGP PUBLIC KEY BLOCK-----")); s1 = str.find(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----")); - if(s1 != wstring::npos && s2 != wstring::npos) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); + if (s1 != wstring::npos && s2 != wstring::npos) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange): found pubkey block:" + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); s2 += mir_tstrlen(_T("-----END PGP PUBLIC KEY BLOCK-----")); - db_set_ts(ccs->hContact, szGPGModuleName, "GPGPubKey", str.substr(s1,s2-s1).c_str()); + db_set_ts(ccs->hContact, szGPGModuleName, "GPGPubKey", str.substr(s1, s2 - s1).c_str()); { //gpg execute block std::vector cmd; - TCHAR tmp2[MAX_PATH] = {0}; - TCHAR *ptmp; + TCHAR tmp2[MAX_PATH] = { 0 }; string output; DWORD exitcode; { - ptmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + ptrT ptmp(UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T(""))); mir_tstrcpy(tmp2, ptmp); mir_free(ptmp); mir_tstrcat(tmp2, _T("\\")); @@ -391,12 +342,10 @@ INT_PTR RecvMsgSvc(WPARAM w, LPARAM l) //mir_tstrcat(tmp2, _T("temporary_exported.asc")); boost::filesystem::remove(tmp2); wfstream f(tmp2, std::ios::out); - while(!f.is_open()) + while (!f.is_open()) f.open(tmp2, std::ios::out); ptmp = UniGetContactSettingUtf(ccs->hContact, szGPGModuleName, "GPGPubKey", _T("")); - wstring new_key = ptmp; - mir_free(ptmp); - f<hContact, db_event(Translate("failed to decrypt message, GPG returned error, turn on debug log for more details"))); return 1; } { char *tmp = NULL; - string::size_type s = output.find("gpg: key ") + mir_strlen("gpg: key "); - string::size_type s2 = output.find(":", s); - db_set_s(ccs->hContact, szGPGModuleName, "KeyID", output.substr(s,s2-s).c_str()); - s2+=2; - s = output.find("“", s2); - if(s == string::npos) - { - s = output.find("\"", s2); - s += 1; + s1 = output.find("gpg: key ") + mir_strlen("gpg: key "); + s2 = output.find(":", s1); + db_set_s(ccs->hContact, szGPGModuleName, "KeyID", output.substr(s1, s2 - s1).c_str()); + s2 += 2; + s1 = output.find("“", s2); + if (s1 == string::npos) { + s1 = output.find("\"", s2); + s1 += 1; } - else - s += 3; - if((s2 = output.find("(", s)) == string::npos) - s2 = output.find("<", s); - else if(s2 > output.find("<", s)) - s2 = output.find("<", s); - tmp = (char*)mir_alloc(output.substr(s,s2-s-1).length()+1); - mir_strcpy(tmp, output.substr(s,s2-s-1).c_str()); + else s1 += 3; + + if ((s2 = output.find("(", s1)) == string::npos) + s2 = output.find("<", s1); + else if (s2 > output.find("<", s1)) + s2 = output.find("<", s1); + tmp = (char*)mir_alloc(output.substr(s1, s2 - s1 - 1).length() + 1); + mir_strcpy(tmp, output.substr(s1, s2 - s1 - 1).c_str()); mir_utf8decode(tmp, 0); db_set_s(ccs->hContact, szGPGModuleName, "KeyMainName", tmp); mir_free(tmp); - if((s = output.find(")", s2)) == string::npos) - s = output.find(">", s2); - else if(s > output.find(">", s2)) - s = output.find(">", s2); + if ((s1 = output.find(")", s2)) == string::npos) + s1 = output.find(">", s2); + else if (s1 > output.find(">", s2)) + s1 = output.find(">", s2); s2++; - if(output[s] == ')') - { - tmp = (char*)mir_alloc(output.substr(s2,s-s2).length()+1); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); + if (output[s1] == ')') { + tmp = (char*)mir_alloc(output.substr(s2, s1 - s2).length() + 1); + mir_strcpy(tmp, output.substr(s2, s1 - s2).c_str()); mir_utf8decode(tmp, 0); db_set_s(ccs->hContact, szGPGModuleName, "KeyComment", tmp); mir_free(tmp); - s+=3; - s2 = output.find(">", s); - tmp = (char*)mir_alloc(output.substr(s,s2-s).length()+1); - mir_strcpy(tmp, output.substr(s,s2-s).c_str()); + s1 += 3; + s2 = output.find(">", s1); + tmp = (char*)mir_alloc(output.substr(s1, s2 - s1).length() + 1); + mir_strcpy(tmp, output.substr(s1, s2 - s1).c_str()); mir_utf8decode(tmp, 0); db_set_s(ccs->hContact, szGPGModuleName, "KeyMainEmail", tmp); mir_free(tmp); } - else - { - tmp = (char*)mir_alloc(output.substr(s2,s-s2).length()+1); - mir_strcpy(tmp, output.substr(s2,s-s2).c_str()); + else { + tmp = (char*)mir_alloc(output.substr(s2, s1 - s2).length() + 1); + mir_strcpy(tmp, output.substr(s2, s1 - s2).c_str()); mir_utf8decode(tmp, 0); - db_set_s(ccs->hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); + db_set_s(ccs->hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2, s1 - s2).c_str()); mir_free(tmp); } db_set_b(ccs->hContact, szGPGModuleName, "GPGEncryption", 1); db_set_b(ccs->hContact, szGPGModuleName, "bAlwatsTrust", 1); setSrmmIcon(ccs->hContact); setClistIcon(ccs->hContact); - if(db_mc_isSub(ccs->hContact)) - { + if (db_mc_isSub(ccs->hContact)) { setSrmmIcon(db_mc_getMeta(ccs->hContact)); setClistIcon(db_mc_getMeta(ccs->hContact)); } HistoryLog(ccs->hContact, "PGP Encryption turned on by key autoexchange feature"); } - } - return 1; } + return 1; } - if(((s2 = str.find(_T("-----END PGP PUBLIC KEY BLOCK-----"))) == wstring::npos) || ((s1 = str.find(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----"))) == wstring::npos)) - { - s2 = str.find(_T("-----END PGP PRIVATE KEY BLOCK-----")); - s1 = str.find(_T("-----BEGIN PGP PRIVATE KEY BLOCK-----")); + } + if (((s2 = str.find(_T("-----END PGP PUBLIC KEY BLOCK-----"))) == wstring::npos) || ((s1 = str.find(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----"))) == wstring::npos)) { + s2 = str.find(_T("-----END PGP PRIVATE KEY BLOCK-----")); + s1 = str.find(_T("-----BEGIN PGP PRIVATE KEY BLOCK-----")); + } + if ((s2 != wstring::npos) && (s1 != wstring::npos)) { //this is public key + if (bDebugLog) + debuglog << std::string(time_str() + ": info: received key from: " + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); + s1 = 0; + while ((s1 = str.find(_T("\r"), s1)) != wstring::npos) + str.erase(s1, 1); + void ShowNewKeyDialog(); + if (((s2 = str.find(_T("-----END PGP PUBLIC KEY BLOCK-----"))) != wstring::npos) && ((s1 = str.find(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----"))) != wstring::npos)) { + s2 += mir_tstrlen(_T("-----END PGP PUBLIC KEY BLOCK-----")); } - if((s2 != wstring::npos) && (s1 != wstring::npos)) - { //this is public key - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); - s1 = 0; - while((s1 = str.find(_T("\r"), s1)) != wstring::npos) - str.erase(s1, 1); - void ShowNewKeyDialog(); - if(((s2 = str.find(_T("-----END PGP PUBLIC KEY BLOCK-----"))) != wstring::npos) && ((s1 = str.find(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----"))) != wstring::npos)) - { - s2 += mir_tstrlen(_T("-----END PGP PUBLIC KEY BLOCK-----")); - } - else if(((s2 = str.find(_T("-----BEGIN PGP PRIVATE KEY BLOCK-----"))) != wstring::npos) && ((s1 = str.find(_T("-----END PGP PRIVATE KEY BLOCK-----"))) != wstring::npos)) - { - s2 += mir_tstrlen(_T("-----END PGP PRIVATE KEY BLOCK-----")); - } - new_key.append(str.substr(s1,s2-s1)); - //new_key_hcnt_mutex.lock(); - new_key_hcnt = ccs->hContact; - ShowNewKeyDialog(); - HistoryLog(ccs->hContact, db_event(msg, 0, 0, dbflags)); - return 0; + else if (((s2 = str.find(_T("-----BEGIN PGP PRIVATE KEY BLOCK-----"))) != wstring::npos) && ((s1 = str.find(_T("-----END PGP PRIVATE KEY BLOCK-----"))) != wstring::npos)) { + s2 += mir_tstrlen(_T("-----END PGP PRIVATE KEY BLOCK-----")); } - if(bAutoExchange && strstr(msg, "-----PGP KEY REQUEST-----") && gpg_valid && gpg_keyexist) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); - char *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "GPGPubKey", ""); - if(tmp[0]) - { - int enc_state = db_get_b(ccs->hContact, szGPGModuleName, "GPGEncryption", 0); - if(enc_state) - db_set_b(ccs->hContact, szGPGModuleName, "GPGEncryption", 0); - string str = "-----PGP KEY RESPONSE-----"; - str.append(tmp); - CallContactService(ccs->hContact, PSS_MESSAGE, 0, (LPARAM)str.c_str()); - if(enc_state) - db_set_b(ccs->hContact, szGPGModuleName, "GPGEncryption", 1); - } - mir_free(tmp); - return 0; + new_key.append(str.substr(s1, s2 - s1)); + //new_key_hcnt_mutex.lock(); + new_key_hcnt = ccs->hContact; + ShowNewKeyDialog(); + HistoryLog(ccs->hContact, db_event(msg, 0, 0, dbflags)); + return 0; + } + if (bAutoExchange && strstr(msg, "-----PGP KEY REQUEST-----") && gpg_valid && gpg_keyexist) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange): received key request from: " + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); + + ptrA tmp(UniGetContactSettingUtf(NULL, szGPGModuleName, "GPGPubKey", "")); + if (tmp[0]) { + int enc_state = db_get_b(ccs->hContact, szGPGModuleName, "GPGEncryption", 0); + if (enc_state) + db_set_b(ccs->hContact, szGPGModuleName, "GPGEncryption", 0); + + string str1 = "-----PGP KEY RESPONSE-----"; + str1.append(tmp); + CallContactService(ccs->hContact, PSS_MESSAGE, 0, (LPARAM)str1.c_str()); + if (enc_state) + db_set_b(ccs->hContact, szGPGModuleName, "GPGEncryption", 1); } - else if(!isContactHaveKey(ccs->hContact) && bAutoExchange && gpg_valid && gpg_keyexist) - { - char *proto = GetContactProto(ccs->hContact); - DWORD uin = db_get_dw(ccs->hContact, proto, "UIN", 0); - if(uin) { - if( ProtoServiceExists(proto, PS_ICQ_CHECKCAPABILITY)) { - ICQ_CUSTOMCAP cap = {0}; - strncpy(cap.caps, "GPGAutoExchange", sizeof(cap.caps)); - if(CallProtoService(proto, PS_ICQ_CHECKCAPABILITY, (WPARAM)ccs->hContact, (LPARAM)&cap)) { - CallContactService(ccs->hContact, PSS_MESSAGE, 0, (LPARAM)"-----PGP KEY REQUEST-----"); - return 0; - } + return 0; + } + else if (!isContactHaveKey(ccs->hContact) && bAutoExchange && gpg_valid && gpg_keyexist) { + char *proto = GetContactProto(ccs->hContact); + DWORD uin = db_get_dw(ccs->hContact, proto, "UIN", 0); + if (uin) { + if (ProtoServiceExists(proto, PS_ICQ_CHECKCAPABILITY)) { + ICQ_CUSTOMCAP cap = { 0 }; + strncpy(cap.caps, "GPGAutoExchange", sizeof(cap.caps)); + if (CallProtoService(proto, PS_ICQ_CHECKCAPABILITY, (WPARAM)ccs->hContact, (LPARAM)&cap)) { + CallContactService(ccs->hContact, PSS_MESSAGE, 0, (LPARAM)"-----PGP KEY REQUEST-----"); + return 0; } } - else - { - TCHAR *jid = UniGetContactSettingUtf(ccs->hContact, proto, "jid", _T("")); - if(jid[0]) - { - extern list Accounts; - list::iterator end = Accounts.end(); - for(list::iterator p = Accounts.begin(); p != end; p++) - { - TCHAR *caps = (*p)->getJabberInterface()->GetResourceFeatures(jid); - if(caps) - { - wstring str; - for(int i =0;;i++) - { - str.push_back(caps[i]); - if(caps[i] == '\0') - if(caps[i+1] == '\0') - break; - } - mir_free(caps); - if(str.find(_T("GPG_Key_Auto_Exchange:0")) != string::npos) - { - CallContactService(ccs->hContact, PSS_MESSAGE, 0, (LPARAM)"-----PGP KEY REQUEST-----"); - return 0; - } + } + else { + TCHAR *jid = UniGetContactSettingUtf(ccs->hContact, proto, "jid", _T("")); + if (jid[0]) { + extern list Accounts; + list::iterator end = Accounts.end(); + for (list::iterator p = Accounts.begin(); p != end; p++) { + TCHAR *caps = (*p)->getJabberInterface()->GetResourceFeatures(jid); + if (caps) { + wstring str1; + for (int i = 0;; i++) { + str1.push_back(caps[i]); + if (caps[i] == '\0') + if (caps[i + 1] == '\0') + break; + } + mir_free(caps); + if (str1.find(_T("GPG_Key_Auto_Exchange:0")) != string::npos) { + CallContactService(ccs->hContact, PSS_MESSAGE, 0, (LPARAM)"-----PGP KEY REQUEST-----"); + return 0; } } } - mir_free(jid); } + mir_free(jid); } - if(!strstr(msg, "-----BEGIN PGP MESSAGE-----")) - return Proto_ChainRecv(w, ccs); - - new boost::thread(boost::bind(RecvMsgSvc_func, ccs->hContact, str, msg, (DWORD)ccs->wParam, pre->timestamp)); - return 0; + } + if (!strstr(msg, "-----BEGIN PGP MESSAGE-----")) + return Proto_ChainRecv(w, ccs); + + new boost::thread(boost::bind(RecvMsgSvc_func, ccs->hContact, str, msg, (DWORD)ccs->wParam, pre->timestamp)); + return 0; } void SendMsgSvc_func(MCONTACT hContact, char *msg, DWORD flags) { wstring str = toUTF16(msg); - if(bStripTags && bAppendTags) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (bStripTags && bAppendTags) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: stripping tags in outgoing message, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); strip_tags(str); } -/* for(std::wstring::size_type i = str.find(_T("\r\n")); i != std::wstring::npos; i = str.find(_T("\r\n"), i+1)) - str.replace(i, 2, _T("\n")); */ + /* for(std::wstring::size_type i = str.find(_T("\r\n")); i != std::wstring::npos; i = str.find(_T("\r\n"), i+1)) + str.replace(i, 2, _T("\n")); */ string out; DWORD code; wstring file = toUTF16(get_random(10)), path; std::vector cmd; extern bool bJabberAPI, bIsMiranda09; - char *tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyID", ""); - if(!tmp[0]) - { - mir_free(tmp); - HistoryLog(hContact, db_event("Failed to encrypt message with GPG (not found key for encryption in db)", 0,0, DBEF_SENT)); - CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); - return; - } - if(!bJabberAPI || !bIsMiranda09) //force jabber to handle encrypted message by itself { - cmd.push_back(L"--comment"); - cmd.push_back(L"\"\""); - cmd.push_back(L"--no-version"); + TCHAR *tmp2; + { + char *tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyID", ""); + if (!tmp[0]) { + mir_free(tmp); + HistoryLog(hContact, db_event("Failed to encrypt message with GPG (not found key for encryption in db)", 0, 0, DBEF_SENT)); + CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); + return; + } + if (!bJabberAPI || !bIsMiranda09) //force jabber to handle encrypted message by itself + { + cmd.push_back(L"--comment"); + cmd.push_back(L"\"\""); + cmd.push_back(L"--no-version"); + } + if (db_get_b(hContact, szGPGModuleName, "bAlwaysTrust", 0)) { + cmd.push_back(L"--trust-model"); + cmd.push_back(L"always"); + } + cmd.push_back(L"--batch"); + cmd.push_back(L"--yes"); + cmd.push_back(L"-eatr"); + tmp2 = mir_a2t(tmp); + mir_free(tmp); + } + cmd.push_back(tmp2); + mir_free(tmp2); } - if(db_get_b(hContact, szGPGModuleName, "bAlwaysTrust", 0)) { - cmd.push_back(L"--trust-model"); - cmd.push_back(L"always"); + TCHAR *tmp2 = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + path = tmp2; + cmd.push_back(std::wstring(tmp2) + L"\\tmp\\" + file); + mir_free(tmp2); } - cmd.push_back(L"--batch"); - cmd.push_back(L"--yes"); - cmd.push_back(L"-eatr"); - TCHAR *tmp2 = mir_a2t(tmp); - mir_free(tmp); - cmd.push_back(tmp2); - mir_free(tmp2); - tmp2 = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - path = tmp2; - cmd.push_back(std::wstring(tmp2) + L"\\tmp\\" + file); - mir_free(tmp2); path += L"\\tmp\\"; path += file; { fstream f(path.c_str(), std::ios::out); - while(!f.is_open()) - { + while (!f.is_open()) { boost::this_thread::sleep(boost::posix_time::milliseconds(50)); f.open(path.c_str(), std::ios::out); } @@ -642,67 +577,55 @@ void SendMsgSvc_func(MCONTACT hContact, char *msg, DWORD flags) f.write(tmp.c_str(), tmp.size()); f.close(); } - gpg_execution_params params(cmd); pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) { - //mir_free(msg); - CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); - return; - } - if(result == pxNotFound) - { - //mir_free(msg); - CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); - return; + gpg_execution_params params(cmd); + params.out = &out; + params.code = &code; + params.result = &result; + if (!gpg_launcher(params)) { + //mir_free(msg); + CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); + return; + } + if (result == pxNotFound) { + //mir_free(msg); + CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); + return; + } } - if(out.find("There is no assurance this key belongs to the named user") != string::npos) - { + + if (out.find("There is no assurance this key belongs to the named user") != string::npos) { out.clear(); - if(MessageBox(0, TranslateT("We're trying to encrypt with untrusted key. Do you want to trust this key permanently?"), TranslateT("Warning"), MB_YESNO) == IDYES) - { + if (MessageBox(0, TranslateT("We're trying to encrypt with untrusted key. Do you want to trust this key permanently?"), TranslateT("Warning"), MB_YESNO) == IDYES) { db_set_b(hContact, szGPGModuleName, "bAlwaysTrust", 1); std::vector tmp; tmp.push_back(L"--trust-model"); tmp.push_back(L"always"); cmd.insert(cmd.begin(), tmp.begin(), tmp.end()); gpg_execution_params params(cmd); - pxResult result; params.out = &out; params.code = &code; params.result = &result; - if(!gpg_launcher(params)) - { - //mir_free(msg); + if (!gpg_launcher(params)) { CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); return; } - if(result == pxNotFound) - { - //mir_free(msg); + if (result == pxNotFound) { CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); return; } //TODO: check gpg output for errors } - else - { - //mir_free(msg); - return; - } + else return; } - if(result == pxSuccessExitCodeInvalid) - { + if (result == pxSuccessExitCodeInvalid) { //mir_free(msg); - HistoryLog(hContact, db_event(Translate("failed to encrypt message, GPG returned error, turn on debug log for more details"), 0,0, DBEF_SENT)); + HistoryLog(hContact, db_event(Translate("failed to encrypt message, GPG returned error, turn on debug log for more details"), 0, 0, DBEF_SENT)); boost::filesystem::remove(path); return; } - if(out.find("usage: ") != string::npos) - { + if (out.find("usage: ") != string::npos) { MessageBox(0, TranslateT("Something is wrong, GPG does not understand us, aborting encryption."), TranslateT("Warning"), MB_OK); //mir_free(msg); CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)msg); @@ -712,41 +635,37 @@ void SendMsgSvc_func(MCONTACT hContact, char *msg, DWORD flags) boost::filesystem::remove(path); path.append(_T(".asc")); wfstream f(path.c_str(), std::ios::in | std::ios::ate | std::ios::binary); - while(!f.is_open()) - { + while (!f.is_open()) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); f.open(path.c_str(), std::ios::in | std::ios::ate | std::ios::binary); } str.clear(); - if(f.is_open()) - { + if (f.is_open()) { std::wifstream::pos_type size = f.tellg(); - TCHAR *tmp = new TCHAR [(std::ifstream::pos_type)size+(std::ifstream::pos_type)1]; + TCHAR *tmp = new TCHAR[(std::ifstream::pos_type)size + (std::ifstream::pos_type)1]; f.seekg(0, std::ios::beg); f.read(tmp, size); - tmp[size]= '\0'; + tmp[size] = '\0'; str.append(tmp); - delete [] tmp; + delete[] tmp; f.close(); boost::filesystem::remove(path); } - if(str.empty()) - { - HistoryLog(hContact, db_event("Failed to encrypt message with GPG", 0,0, DBEF_SENT)); - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))+" on send message."); + if (bDebugLog) + debuglog << std::string(time_str() + ": adding event to contact: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " on send message."); fix_line_term(str); sent_msgs.push_back((HANDLE)CallContactService(hContact, PSS_MESSAGE, flags, (LPARAM)toUTF8(str).c_str())); @@ -757,29 +676,26 @@ INT_PTR SendMsgSvc(WPARAM w, LPARAM l) CCSDATA *ccs = (CCSDATA*)l; if (!ccs) return Proto_ChainSend(w, ccs); - if(!ccs->lParam) + if (!ccs->lParam) return Proto_ChainSend(w, ccs); char *msg = (char*)ccs->lParam; - if (!msg) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); + if (!msg) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: failed to get message data, name: " + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); return Proto_ChainSend(w, ccs); } - if(strstr(msg,"-----BEGIN PGP MESSAGE-----")) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); + if (strstr(msg, "-----BEGIN PGP MESSAGE-----")) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: encrypted messge, let it go, name: " + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); return Proto_ChainSend(w, ccs); } - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); - if(bDebugLog && db_mc_isMeta(ccs->hContact)) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); - if(!isContactSecured(ccs->hContact) || db_mc_isMeta(ccs->hContact)) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ccs->hContact, 0))); + if (bDebugLog) + debuglog << std::string(time_str() + ": info: contact have key, name: " + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); + if (bDebugLog && db_mc_isMeta(ccs->hContact)) + debuglog << std::string(time_str() + ": info: protocol is metacontacts, name: " + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); + if (!isContactSecured(ccs->hContact) || db_mc_isMeta(ccs->hContact)) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: contact not secured, name: " + toUTF8(pcli->pfnGetContactDisplayName(ccs->hContact, 0))); return Proto_ChainSend(w, ccs); } return returnNoError(ccs->hContact); @@ -789,54 +705,51 @@ boost::mutex event_processing_mutex; int HookSendMsg(WPARAM w, LPARAM l) { - if(!l) + if (!l) return 0; DBEVENTINFO * dbei = (DBEVENTINFO*)l; - if(dbei->eventType != EVENTTYPE_MESSAGE) + if (dbei->eventType != EVENTTYPE_MESSAGE) return 0; MCONTACT hContact = (MCONTACT)w; - if(dbei->flags & DBEF_SENT) - { - if(isContactSecured(hContact) && strstr((char*)dbei->pBlob, "-----BEGIN PGP MESSAGE-----")) //our service data, can be double added by metacontacts e.t.c. + if (dbei->flags & DBEF_SENT) { + if (isContactSecured(hContact) && strstr((char*)dbei->pBlob, "-----BEGIN PGP MESSAGE-----")) //our service data, can be double added by metacontacts e.t.c. { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (bDebugLog) + debuglog << std::string(time_str() + ": info(send handler): block pgp message event, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); return 1; } - if(bAutoExchange && (strstr((char*)dbei->pBlob, "-----PGP KEY RESPONSE-----") || strstr((char*)dbei->pBlob, "-----PGP KEY REQUEST-----"))) ///do not show service data in history + if (bAutoExchange && (strstr((char*)dbei->pBlob, "-----PGP KEY RESPONSE-----") || strstr((char*)dbei->pBlob, "-----PGP KEY REQUEST-----"))) ///do not show service data in history { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (bDebugLog) + debuglog << std::string(time_str() + ": info(send handler): block pgp key request/response event, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); return 1; } } - if(db_mc_isMeta(hContact)) + if (db_mc_isMeta(hContact)) return 0; - if(!isContactHaveKey(hContact)) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); - if(bAutoExchange && !strstr((char*)dbei->pBlob, "-----PGP KEY REQUEST-----") && !strstr((char*)dbei->pBlob, "-----BEGIN PGP PUBLIC KEY BLOCK-----") && gpg_valid) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (!isContactHaveKey(hContact)) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: contact have not key, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); + if (bAutoExchange && !strstr((char*)dbei->pBlob, "-----PGP KEY REQUEST-----") && !strstr((char*)dbei->pBlob, "-----BEGIN PGP PUBLIC KEY BLOCK-----") && gpg_valid) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: checking for autoexchange possibility, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); + LPSTR proto = GetContactProto(hContact); DWORD uin = db_get_dw(hContact, proto, "UIN", 0); - if(uin) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); - - char *proto = GetContactProto(hContact); - if( ProtoServiceExists(proto, PS_ICQ_CHECKCAPABILITY)) { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); - ICQ_CUSTOMCAP cap = {0}; + if (uin) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange): protocol looks like icq, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); + + char *proto2 = GetContactProto(hContact); + if (ProtoServiceExists(proto2, PS_ICQ_CHECKCAPABILITY)) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange, icq): checking for autoexchange icq capability, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); + ICQ_CUSTOMCAP cap = { 0 }; strncpy(cap.caps, "GPGAutoExchange", sizeof(cap.caps)); - if (CallProtoService(proto, PS_ICQ_CHECKCAPABILITY, hContact, (LPARAM)&cap)) { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (CallProtoService(proto2, PS_ICQ_CHECKCAPABILITY, hContact, (LPARAM)&cap)) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange, icq): sending key requiest, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); CallContactService(hContact, PSS_MESSAGE, 0, (LPARAM)"-----PGP KEY REQUEST-----"); hcontact_data[hContact].msgs_to_send.push_back((char*)dbei->pBlob); new boost::thread(boost::bind(send_encrypted_msgs_thread, (void*)hContact)); @@ -844,33 +757,27 @@ int HookSendMsg(WPARAM w, LPARAM l) } } } - else - { + else { TCHAR *jid = UniGetContactSettingUtf(hContact, proto, "jid", _T("")); - if(jid[0]) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (jid[0]) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange): protocol looks like jabber, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); extern list Accounts; list::iterator end = Accounts.end(); - for(list::iterator p = Accounts.begin(); p != end; p++) - { + for (list::iterator p = Accounts.begin(); p != end; p++) { TCHAR *caps = (*p)->getJabberInterface()->GetResourceFeatures(jid); - if(caps) - { + if (caps) { wstring str; - for(int i=0;;i++) - { + for (int i = 0;; i++) { str.push_back(caps[i]); - if(caps[i] == '\0') - if(caps[i+1] == '\0') + if (caps[i] == '\0') + if (caps[i + 1] == '\0') break; } mir_free(caps); - if(str.find(_T("GPG_Key_Auto_Exchange:0")) != string::npos) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (str.find(_T("GPG_Key_Auto_Exchange:0")) != string::npos) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(autoexchange, jabber): autoexchange capability found, sending key request, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); CallContactService(hContact, PSS_MESSAGE, 0, (LPARAM)"-----PGP KEY REQUEST-----"); hcontact_data[hContact].msgs_to_send.push_back((char*)dbei->pBlob); new boost::thread(boost::bind(send_encrypted_msgs_thread, (void*)hContact)); @@ -882,17 +789,15 @@ int HookSendMsg(WPARAM w, LPARAM l) mir_free(jid); } } - else - { + else { return 0; } } - if(isContactSecured(hContact) && (dbei->flags & DBEF_SENT)) //aggressive outgoing events filtering + if (isContactSecured(hContact) && (dbei->flags & DBEF_SENT)) //aggressive outgoing events filtering { SendMsgSvc_func(hContact, (char*)dbei->pBlob, 0); //TODO: handle errors somehow ... - if(bAppendTags) - { + if (bAppendTags) { string str_event = (char*)dbei->pBlob; //mir_free(dbei->pBlob); str_event.insert(0, toUTF8(outopentag)); @@ -903,21 +808,18 @@ int HookSendMsg(WPARAM w, LPARAM l) return 0; } - if(!isContactSecured(hContact)) - { - if(bDebugLog) - debuglog<pBlob+"\" passed event filter, contact "+toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))+" is unsecured"); + if (!isContactSecured(hContact)) { + if (bDebugLog) + debuglog << std::string(time_str() + ": event message: \"" + (char*)dbei->pBlob + "\" passed event filter, contact " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0)) + " is unsecured"); return 0; } - if(!(dbei->flags & DBEF_SENT) && db_mc_isMeta((MCONTACT)w)) - { + if (!(dbei->flags & DBEF_SENT) && db_mc_isMeta((MCONTACT)w)) { char tmp[29]; strncpy(tmp, (char*)dbei->pBlob, 27); tmp[28] = '\0'; - if(strstr(tmp, "-----BEGIN PGP MESSAGE-----")) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (strstr(tmp, "-----BEGIN PGP MESSAGE-----")) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info(send handler): block pgp message event, name: " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); return 1; } } @@ -927,23 +829,21 @@ int HookSendMsg(WPARAM w, LPARAM l) static INT_PTR CALLBACK DlgProcKeyPassword(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM) { char *inkeyid = NULL; - switch (msg) - { + switch (msg) { case WM_INITDIALOG: - { - inkeyid = UniGetContactSettingUtf(new_key_hcnt, szGPGModuleName, "InKeyID", ""); - new_key_hcnt_mutex.unlock(); + inkeyid = UniGetContactSettingUtf(new_key_hcnt, szGPGModuleName, "InKeyID", ""); + new_key_hcnt_mutex.unlock(); - SetWindowPos(hwndDlg, 0, key_password_rect.left, key_password_rect.top, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW); - TranslateDialogDefault(hwndDlg); + SetWindowPos(hwndDlg, 0, key_password_rect.left, key_password_rect.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); + TranslateDialogDefault(hwndDlg); + { string questionstr = "Please enter password for key with ID: "; questionstr += inkeyid; mir_free(inkeyid); SetDlgItemTextA(hwndDlg, IDC_KEYID, questionstr.c_str()); EnableWindow(GetDlgItem(hwndDlg, IDC_DEFAULT_PASSWORD), 0); - return TRUE; } - + return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { @@ -951,25 +851,21 @@ static INT_PTR CALLBACK DlgProcKeyPassword(HWND hwndDlg, UINT msg, WPARAM wParam { TCHAR tmp[64]; GetDlgItemText(hwndDlg, IDC_KEY_PASSWORD, tmp, _countof(tmp)); - if(tmp[0]) - { + if (tmp[0]) { extern TCHAR *password; - if(IsDlgButtonChecked(hwndDlg, IDC_SAVE_PASSWORD)) - { + if (IsDlgButtonChecked(hwndDlg, IDC_SAVE_PASSWORD)) { inkeyid = UniGetContactSettingUtf(new_key_hcnt, szGPGModuleName, "InKeyID", ""); - if(inkeyid && inkeyid[0] && BST_UNCHECKED == IsDlgButtonChecked(hwndDlg, IDC_DEFAULT_PASSWORD)) - { + if (inkeyid && inkeyid[0] && BST_UNCHECKED == IsDlgButtonChecked(hwndDlg, IDC_DEFAULT_PASSWORD)) { string dbsetting = "szKey_"; dbsetting += inkeyid; dbsetting += "_Password"; db_set_ts(NULL, szGPGModuleName, dbsetting.c_str(), tmp); } - else - db_set_ts(NULL, szGPGModuleName, "szKeyPassword", tmp); + else db_set_ts(NULL, szGPGModuleName, "szKeyPassword", tmp); } - if(password) + if (password) mir_free(password); - password = (TCHAR*)mir_alloc(sizeof(TCHAR)*(mir_tstrlen(tmp)+1)); + password = (TCHAR*)mir_alloc(sizeof(TCHAR)*(mir_tstrlen(tmp) + 1)); mir_tstrcpy(password, tmp); } mir_free(inkeyid); @@ -989,7 +885,7 @@ static INT_PTR CALLBACK DlgProcKeyPassword(HWND hwndDlg, UINT msg, WPARAM wParam mir_free(inkeyid); DestroyWindow(hwndDlg); break; - + case WM_DESTROY: GetWindowRect(hwndDlg, &key_password_rect); db_set_dw(NULL, szGPGModuleName, "PasswordWindowX", key_password_rect.left); diff --git a/plugins/New_GPG/src/options.cpp b/plugins/New_GPG/src/options.cpp index 79c5d5773b..8b48874774 100755 --- a/plugins/New_GPG/src/options.cpp +++ b/plugins/New_GPG/src/options.cpp @@ -17,6 +17,7 @@ #include "stdafx.h" extern HINSTANCE hInst; +extern bool bJabberAPI, bFileTransfers; static INT_PTR CALLBACK DlgProcGpgOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); static INT_PTR CALLBACK DlgProcGpgBinOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); @@ -73,365 +74,324 @@ HWND hwndList_p = NULL; HWND hwndCurKey_p = NULL; void ShowLoadPublicKeyDialog(); -static INT_PTR CALLBACK DlgProcGpgOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +static INT_PTR CALLBACK DlgProcGpgOpts(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { - HWND hwndList=GetDlgItem(hwndDlg, IDC_USERLIST); + HWND hwndList = GetDlgItem(hwndDlg, IDC_USERLIST); hwndList_p = hwndList; hwndCurKey_p = GetDlgItem(hwndDlg, IDC_CURRENT_KEY); - LVCOLUMN col = {0}; - LVITEM item = {0}; - TCHAR *tmp = NULL; - char *tmp2 = NULL; + LVITEM item = { 0 }; extern bool bIsMiranda09, bJabberAPI; - NMLISTVIEW * hdr = (NMLISTVIEW *) lParam; - switch (msg) - { - case WM_INITDIALOG: - { + NMLISTVIEW *hdr = (NMLISTVIEW *)lParam; + switch (uMsg) { + case WM_INITDIALOG: TranslateDialogDefault(hwndDlg); - col.pszText = TranslateT("Contact"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 60; - ListView_InsertColumn(hwndList, 0, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Key ID"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 50; - ListView_InsertColumn(hwndList, 1, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Name"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 50; - ListView_InsertColumn(hwndList, 2, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Email"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 50; - ListView_InsertColumn(hwndList, 3, &col); - memset(&col, 0, sizeof(col)); - col.pszText = TranslateT("Protocol"); - col.mask = LVCF_TEXT | LVCF_WIDTH; - col.fmt = LVCFMT_LEFT; - col.cx = 60; - ListView_InsertColumn(hwndList, 4, &col); - ListView_SetExtendedListViewStyleEx(hwndList, 0, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT); - int i = 1, iRow = 0; - for(MCONTACT hContact = db_find_first(); hContact != NULL; hContact = db_find_next(hContact)) { - if(isContactHaveKey(hContact)) { - TCHAR *name = pcli->pfnGetContactDisplayName(hContact, 0); - item.mask = LVIF_TEXT; - item.iItem = i; - item.iSubItem = 0; - item.pszText = name; - iRow = ListView_InsertItem(hwndList, &item); - ListView_SetItemText(hwndList, iRow, 0, name); - TCHAR *tmp = mir_a2t(GetContactProto(hContact)); - ListView_SetItemText(hwndList, iRow, 4, tmp); - mir_free(tmp); - tmp2 = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyID", ""); - tmp = mir_a2t(tmp2); - mir_free(tmp2); - ListView_SetItemText(hwndList, iRow, 1, (mir_tstrlen(tmp) > 1)?tmp:_T("not set")); - mir_free(tmp); - char *tmp2 = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainName", ""); - if(!toUTF16(tmp2).empty()) - tmp = mir_wstrdup(toUTF16(tmp2).c_str()); - else - tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainName", _T("")); - mir_free(tmp2); - ListView_SetItemText(hwndList, iRow, 2, (mir_tstrlen(tmp) > 1)?tmp:_T("not set")); - mir_free(tmp); - tmp2 = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainEmail", ""); - if(!toUTF16(tmp2).empty()) - tmp = mir_wstrdup(toUTF16(tmp2).c_str()); - else - tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainEmail", _T("")); - mir_free(tmp2); - ListView_SetItemText(hwndList, iRow, 3, (mir_tstrlen(tmp) > 1)?tmp:_T("not set")); - mir_free(tmp); - if(db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0)) - ListView_SetCheckState(hwndList, iRow, 1); - user_data[i] = hContact; - memset(&item, 0, sizeof(item)); - ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE);// not sure about this - ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); - i++; - } - } - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szLogFilePath", _T("")); - SetDlgItemText(hwndDlg, IDC_LOG_FILE_EDIT, (mir_tstrlen(tmp) > 1)?tmp:_T("c:\\GPGdebug.log")); - mir_free(tmp); - CheckStateLoadDB(hwndDlg, IDC_DEBUG_LOG, "bDebugLog", 0); - EnableWindow(GetDlgItem(hwndDlg, IDC_JABBER_API), bIsMiranda09); - EnableWindow(GetDlgItem(hwndDlg, IDC_AUTO_EXCHANGE), (bIsMiranda09 && bJabberAPI)); { - string keyinfo = Translate("Default private key ID"); - keyinfo += ": "; - char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); - keyinfo += (mir_strlen(keyid) > 0)?keyid:Translate("not set"); - mir_free(keyid); - SetDlgItemTextA(hwndDlg, IDC_CURRENT_KEY, keyinfo.c_str()); - } - if(bIsMiranda09) - CheckStateLoadDB(hwndDlg, IDC_JABBER_API, "bJabberAPI", 1); - CheckStateLoadDB(hwndDlg, IDC_FILE_TRANSFERS, "bFileTransfers", 0); - CheckStateLoadDB(hwndDlg, IDC_AUTO_EXCHANGE, "bAutoExchange", 0); - return TRUE; - } - - - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDC_DELETE_KEY_BUTTON: - void setClistIcon(MCONTACT hContact); - void setSrmmIcon(MCONTACT hContact); - { //gpg execute block - TCHAR *ptmp; - char *tmp; - bool keep = false; - bool ismetacontact = false; - MCONTACT meta = NULL; - MCONTACT hContact = user_data[item_num+1]; - if(db_mc_isMeta(hContact)) - { - meta = hContact; - hContact = metaGetMostOnline(hContact); - ismetacontact = true; - } - else if((meta = db_mc_getMeta(user_data[item_num+1])) != NULL) - { - hContact = metaGetMostOnline(meta); - ismetacontact = true; - } - tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyID", ""); - for(MCONTACT hcnttmp = db_find_first(); hcnttmp != NULL; hcnttmp = db_find_next(hcnttmp)) { - if(hcnttmp != hContact) { - char *tmp2 = UniGetContactSettingUtf(hcnttmp, szGPGModuleName, "KeyID", ""); - if(!mir_strcmp(tmp, tmp2)) { - mir_free(tmp2); - keep = true; - break; - } - mir_free(tmp2); - } - } - if(!keep) - if(MessageBox(0, TranslateT("This key is not used by any contact. Do you want to remove it from public keyring?"), TranslateT("Key info"), MB_YESNO) == IDYES) - { - std::vector cmd; - string output; - DWORD exitcode; - cmd.push_back(L"--batch"); - cmd.push_back(L"--yes"); - cmd.push_back(L"--delete-key"); - ptmp = mir_a2t(tmp); - cmd.push_back(ptmp); - mir_free(ptmp); - gpg_execution_params params(cmd); - pxResult result; - params.out = &output; - params.code = &exitcode; - params.result = &result; - if(!gpg_launcher(params)) - { - mir_free(tmp); - break; - } - if(result == pxNotFound) - { - mir_free(tmp); - break; - } - if(output.find("--delete-secret-keys") != string::npos) - MessageBox(0, TranslateT("we have secret key for this public key, do not removing from GPG keyring"), TranslateT("info"), MB_OK); - else - MessageBox(0, TranslateT("Key removed from GPG keyring"), TranslateT("info"), MB_OK); - } - mir_free(tmp); - if(ismetacontact) - { - if(MessageBox(0, TranslateT("Do you want to remove key from entire metacontact (all subcontacts)?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) - { - MCONTACT hcnt = NULL; - int count = db_mc_getSubCount(meta); - for(int i = 0; i < count; i++) - { - hcnt = db_mc_getSub(meta, i); - if(hcnt) - { - db_unset(hcnt, szGPGModuleName, "KeyID"); - db_unset(hcnt, szGPGModuleName, "GPGPubKey"); - db_unset(hcnt, szGPGModuleName, "KeyMainName"); - db_unset(hcnt, szGPGModuleName, "KeyType"); - db_unset(hcnt, szGPGModuleName, "KeyMainEmail"); - db_unset(hcnt, szGPGModuleName, "KeyComment"); - setClistIcon(hcnt); - setSrmmIcon(hcnt); - } - } - } - else - { - db_unset(hContact, szGPGModuleName, "KeyID"); - db_unset(hContact, szGPGModuleName, "GPGPubKey"); - db_unset(hContact, szGPGModuleName, "KeyMainName"); - db_unset(hContact, szGPGModuleName, "KeyType"); - db_unset(hContact, szGPGModuleName, "KeyMainEmail"); - db_unset(hContact, szGPGModuleName, "KeyComment"); - setClistIcon(hContact); - setSrmmIcon(hContact); - } - } - else - { - db_unset(user_data[item_num+1], szGPGModuleName, "KeyID"); - db_unset(user_data[item_num+1], szGPGModuleName, "GPGPubKey"); - db_unset(user_data[item_num+1], szGPGModuleName, "KeyMainName"); - db_unset(user_data[item_num+1], szGPGModuleName, "KeyType"); - db_unset(user_data[item_num+1], szGPGModuleName, "KeyMainEmail"); - db_unset(user_data[item_num+1], szGPGModuleName, "KeyComment"); - setClistIcon(user_data[item_num+1]); - setSrmmIcon(user_data[item_num+1]); - } - } - ListView_SetItemText(hwndList, item_num, 3, TranslateT("not set")); - ListView_SetItemText(hwndList, item_num, 2, TranslateT("not set")); - ListView_SetItemText(hwndList, item_num, 1, TranslateT("not set")); - break; - case IDC_SELECT_KEY: - { - void ShowFirstRunDialog(); - ShowFirstRunDialog(); - } - break; - case IDC_SAVE_KEY_BUTTON: - { - tmp = GetFilePath(TranslateT("Export public key"), _T("*"), TranslateT(".asc pubkey file"), true); - if(!tmp) - { - break; - } - wstring str; - { - TCHAR *tmp = UniGetContactSettingUtf(user_data[item_num+1], szGPGModuleName, "GPGPubKey", _T("")); - str.append(tmp); - mir_free(tmp); - } - wstring::size_type s = 0; - while((s = str.find(_T("\r"), s)) != wstring::npos) - { - str.erase(s, 1); - } - wfstream f(tmp, std::ios::out); - delete [] tmp; - f<hdr.hwndFrom) && hdr->iItem != (-1)) - { - if(hdr->hdr.code == NM_CLICK) + LVCOLUMN col = { 0 }; + col.pszText = TranslateT("Contact"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 60; + ListView_InsertColumn(hwndList, 0, &col); + + col.pszText = TranslateT("Key ID"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 50; + ListView_InsertColumn(hwndList, 1, &col); + + col.pszText = TranslateT("Name"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 50; + ListView_InsertColumn(hwndList, 2, &col); + + col.pszText = TranslateT("Email"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 50; + ListView_InsertColumn(hwndList, 3, &col); + + col.pszText = TranslateT("Protocol"); + col.mask = LVCF_TEXT | LVCF_WIDTH; + col.fmt = LVCFMT_LEFT; + col.cx = 60; + ListView_InsertColumn(hwndList, 4, &col); + ListView_SetExtendedListViewStyleEx(hwndList, 0, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT); + int i = 1, iRow = 0; + for (MCONTACT hContact = db_find_first(); hContact != NULL; hContact = db_find_next(hContact)) { + if (isContactHaveKey(hContact)) { + TCHAR *name = pcli->pfnGetContactDisplayName(hContact, 0); + item.mask = LVIF_TEXT; + item.iItem = i; + item.iSubItem = 0; + item.pszText = name; + iRow = ListView_InsertItem(hwndList, &item); + ListView_SetItemText(hwndList, iRow, 0, name); + + TCHAR *tmp = mir_a2t(GetContactProto(hContact)); + ListView_SetItemText(hwndList, iRow, 4, tmp); + mir_free(tmp); + + char *tmp2 = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyID", ""); + tmp = mir_a2t(tmp2); + mir_free(tmp2); + ListView_SetItemText(hwndList, iRow, 1, (mir_tstrlen(tmp) > 1) ? tmp : _T("not set")); + mir_free(tmp); + + tmp2 = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainName", ""); + if (!toUTF16(tmp2).empty()) + tmp = mir_wstrdup(toUTF16(tmp2).c_str()); + else + tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainName", _T("")); + mir_free(tmp2); + ListView_SetItemText(hwndList, iRow, 2, (mir_tstrlen(tmp) > 1) ? tmp : _T("not set")); + mir_free(tmp); + + tmp2 = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainEmail", ""); + if (!toUTF16(tmp2).empty()) + tmp = mir_wstrdup(toUTF16(tmp2).c_str()); + else + tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyMainEmail", _T("")); + mir_free(tmp2); + ListView_SetItemText(hwndList, iRow, 3, (mir_tstrlen(tmp) > 1) ? tmp : _T("not set")); + mir_free(tmp); + + if (db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0)) + ListView_SetCheckState(hwndList, iRow, 1); + user_data[i] = hContact; + memset(&item, 0, sizeof(item)); + ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE);// not sure about this + ListView_SetColumnWidth(hwndList, 1, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 2, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 3, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(hwndList, 4, LVSCW_AUTOSIZE); + i++; + } + } + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szLogFilePath", _T("")); + SetDlgItemText(hwndDlg, IDC_LOG_FILE_EDIT, (mir_tstrlen(tmp) > 1) ? tmp : _T("c:\\GPGdebug.log")); + mir_free(tmp); + CheckStateLoadDB(hwndDlg, IDC_DEBUG_LOG, "bDebugLog", 0); + EnableWindow(GetDlgItem(hwndDlg, IDC_JABBER_API), bIsMiranda09); + EnableWindow(GetDlgItem(hwndDlg, IDC_AUTO_EXCHANGE), (bIsMiranda09 && bJabberAPI)); { - item_num = hdr->iItem; + string keyinfo = Translate("Default private key ID"); + keyinfo += ": "; + char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); + keyinfo += (mir_strlen(keyid) > 0) ? keyid : Translate("not set"); + mir_free(keyid); + SetDlgItemTextA(hwndDlg, IDC_CURRENT_KEY, keyinfo.c_str()); + } + if (bIsMiranda09) + CheckStateLoadDB(hwndDlg, IDC_JABBER_API, "bJabberAPI", 1); + CheckStateLoadDB(hwndDlg, IDC_FILE_TRANSFERS, "bFileTransfers", 0); + CheckStateLoadDB(hwndDlg, IDC_AUTO_EXCHANGE, "bAutoExchange", 0); + } + return TRUE; + + case WM_COMMAND: + switch (LOWORD(wParam)) { + case IDC_DELETE_KEY_BUTTON: + void setClistIcon(MCONTACT hContact); + void setSrmmIcon(MCONTACT hContact); + { //gpg execute block + TCHAR *ptmp; + char *tmp; + bool keep = false; + bool ismetacontact = false; + MCONTACT meta = NULL; + MCONTACT hContact = user_data[item_num + 1]; + if (db_mc_isMeta(hContact)) { + meta = hContact; + hContact = metaGetMostOnline(hContact); + ismetacontact = true; + } + else if ((meta = db_mc_getMeta(user_data[item_num + 1])) != NULL) { + hContact = metaGetMostOnline(meta); + ismetacontact = true; + } + tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyID", ""); + for (MCONTACT hcnttmp = db_find_first(); hcnttmp != NULL; hcnttmp = db_find_next(hcnttmp)) { + if (hcnttmp != hContact) { + char *tmp2 = UniGetContactSettingUtf(hcnttmp, szGPGModuleName, "KeyID", ""); + if (!mir_strcmp(tmp, tmp2)) { + mir_free(tmp2); + keep = true; + break; + } + mir_free(tmp2); + } + } + if (!keep) + if (MessageBox(0, TranslateT("This key is not used by any contact. Do you want to remove it from public keyring?"), TranslateT("Key info"), MB_YESNO) == IDYES) { + std::vector cmd; + string output; + DWORD exitcode; + cmd.push_back(L"--batch"); + cmd.push_back(L"--yes"); + cmd.push_back(L"--delete-key"); + ptmp = mir_a2t(tmp); + cmd.push_back(ptmp); + mir_free(ptmp); + gpg_execution_params params(cmd); + pxResult result; + params.out = &output; + params.code = &exitcode; + params.result = &result; + if (!gpg_launcher(params)) { + mir_free(tmp); + break; + } + if (result == pxNotFound) { + mir_free(tmp); + break; + } + if (output.find("--delete-secret-keys") != string::npos) + MessageBox(0, TranslateT("we have secret key for this public key, do not removing from GPG keyring"), TranslateT("info"), MB_OK); + else + MessageBox(0, TranslateT("Key removed from GPG keyring"), TranslateT("info"), MB_OK); + } + mir_free(tmp); + if (ismetacontact) { + if (MessageBox(0, TranslateT("Do you want to remove key from entire metacontact (all subcontacts)?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) { + MCONTACT hcnt = NULL; + int count = db_mc_getSubCount(meta); + for (int i = 0; i < count; i++) { + hcnt = db_mc_getSub(meta, i); + if (hcnt) { + db_unset(hcnt, szGPGModuleName, "KeyID"); + db_unset(hcnt, szGPGModuleName, "GPGPubKey"); + db_unset(hcnt, szGPGModuleName, "KeyMainName"); + db_unset(hcnt, szGPGModuleName, "KeyType"); + db_unset(hcnt, szGPGModuleName, "KeyMainEmail"); + db_unset(hcnt, szGPGModuleName, "KeyComment"); + setClistIcon(hcnt); + setSrmmIcon(hcnt); + } + } + } + else { + db_unset(hContact, szGPGModuleName, "KeyID"); + db_unset(hContact, szGPGModuleName, "GPGPubKey"); + db_unset(hContact, szGPGModuleName, "KeyMainName"); + db_unset(hContact, szGPGModuleName, "KeyType"); + db_unset(hContact, szGPGModuleName, "KeyMainEmail"); + db_unset(hContact, szGPGModuleName, "KeyComment"); + setClistIcon(hContact); + setSrmmIcon(hContact); + } + } + else { + db_unset(user_data[item_num + 1], szGPGModuleName, "KeyID"); + db_unset(user_data[item_num + 1], szGPGModuleName, "GPGPubKey"); + db_unset(user_data[item_num + 1], szGPGModuleName, "KeyMainName"); + db_unset(user_data[item_num + 1], szGPGModuleName, "KeyType"); + db_unset(user_data[item_num + 1], szGPGModuleName, "KeyMainEmail"); + db_unset(user_data[item_num + 1], szGPGModuleName, "KeyComment"); + setClistIcon(user_data[item_num + 1]); + setSrmmIcon(user_data[item_num + 1]); + } } - else if(hdr->hdr.code == LVN_ITEMCHANGED) + ListView_SetItemText(hwndList, item_num, 3, TranslateT("not set")); + ListView_SetItemText(hwndList, item_num, 2, TranslateT("not set")); + ListView_SetItemText(hwndList, item_num, 1, TranslateT("not set")); + break; + + case IDC_SELECT_KEY: + void ShowFirstRunDialog(); + ShowFirstRunDialog(); + break; + + case IDC_SAVE_KEY_BUTTON: { + TCHAR *tmp = GetFilePath(TranslateT("Export public key"), _T("*"), TranslateT(".asc pubkey file"), true); + if (tmp) { + wstring str(ptrT(UniGetContactSettingUtf(user_data[item_num + 1], szGPGModuleName, "GPGPubKey", _T("")))); + wstring::size_type s = 0; + while ((s = str.find(_T("\r"), s)) != wstring::npos) + str.erase(s, 1); + + wfstream f(tmp, std::ios::out); + delete[] tmp; + f << str.c_str(); + f.close(); + } + } + break; + + case IDC_COPY_KEY: + if (OpenClipboard(hwndDlg)) { + char *szKey = UniGetContactSettingUtf(NULL, szGPGModuleName, "GPGPubKey", ""); + std::string str = szKey; + mir_free(szKey); + boost::algorithm::replace_all(str, "\n", "\r\n"); + HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, str.size() + 1); + if (!hMem) { + MessageBox(0, TranslateT("Failed to allocate memory"), TranslateT("Error"), MB_OK); + break; + } + szKey = (char*)GlobalLock(hMem); + if (!szKey) { + TCHAR msg[64]; + mir_sntprintf(msg, TranslateT("Failed to lock memory with error %d"), GetLastError()); + MessageBox(0, msg, TranslateT("Error"), MB_OK); + GlobalFree(hMem); + } + else { + memcpy(szKey, str.c_str(), str.size()); + szKey[str.size()] = '\0'; + str.clear(); + EmptyClipboard(); + GlobalUnlock(hMem); + if (!SetClipboardData(CF_OEMTEXT, hMem)) { + GlobalFree(hMem); + TCHAR msg[64]; + mir_sntprintf(msg, TranslateT("Failed write to clipboard with error %d"), GetLastError()); + MessageBox(0, msg, TranslateT("Error"), MB_OK); + } + CloseClipboard(); + } + } + else { + TCHAR msg[64]; + mir_sntprintf(msg, TranslateT("Failed to open clipboard with error %d"), GetLastError()); + MessageBox(0, msg, TranslateT("Error"), MB_OK); + } + break; + + case IDC_LOG_FILE_SET: + SetDlgItemText(hwndDlg, IDC_LOG_FILE_EDIT, ptrT(GetFilePath(TranslateT("Set log file"), _T("*"), TranslateT("LOG files"), 1))); + break; + } + SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0); + break; + + case WM_NOTIFY: + EnableWindow(GetDlgItem(hwndDlg, IDC_AUTO_EXCHANGE), (bIsMiranda09 && IsDlgButtonChecked(hwndDlg, IDC_JABBER_API))); + if (hdr && IsWindowVisible(hdr->hdr.hwndFrom) && hdr->iItem != (-1)) { + if (hdr->hdr.code == NM_CLICK) + item_num = hdr->iItem; + else if (hdr->hdr.code == LVN_ITEMCHANGED) { void setClistIcon(MCONTACT hContact); void setSrmmIcon(MCONTACT hContact); - if(ListView_GetCheckState(hwndList, item_num)) - db_set_b(user_data[item_num+1], szGPGModuleName, "GPGEncryption", 1); + if (ListView_GetCheckState(hwndList, item_num)) + db_set_b(user_data[item_num + 1], szGPGModuleName, "GPGEncryption", 1); else - db_set_b(user_data[item_num+1], szGPGModuleName, "GPGEncryption", 0); - setClistIcon(user_data[item_num+1]); - setSrmmIcon(user_data[item_num+1]); + db_set_b(user_data[item_num + 1], szGPGModuleName, "GPGEncryption", 0); + setClistIcon(user_data[item_num + 1]); + setSrmmIcon(user_data[item_num + 1]); } } - switch (((LPNMHDR)lParam)->code) - { - - case PSN_APPLY: - { - extern bool bJabberAPI, bFileTransfers; + + switch (((LPNMHDR)lParam)->code) { + case PSN_APPLY: bDebugLog = CheckStateStoreDB(hwndDlg, IDC_DEBUG_LOG, "bDebugLog") != 0; - if(bDebugLog) + if (bDebugLog) debuglog.init(); bJabberAPI = CheckStateStoreDB(hwndDlg, IDC_JABBER_API, "bJabberAPI") != 0; bool old_bFileTransfers = db_get_b(NULL, szGPGModuleName, "bFileTransfers", 0) != 0; bFileTransfers = CheckStateStoreDB(hwndDlg, IDC_FILE_TRANSFERS, "bFileTransfers") != 0; - if(bFileTransfers != old_bFileTransfers) - { + if (bFileTransfers != old_bFileTransfers) { db_set_b(NULL, szGPGModuleName, "bSameAction", 0); bSameAction = false; } @@ -441,227 +401,199 @@ static INT_PTR CALLBACK DlgProcGpgOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LP GetDlgItemText(hwndDlg, IDC_LOG_FILE_EDIT, tmp, _countof(tmp)); db_set_ts(NULL, szGPGModuleName, "szLogFilePath", tmp); } - return TRUE; - } - } - } - break; - } + return TRUE; + } + break; + } - return FALSE; + return FALSE; } static INT_PTR CALLBACK DlgProcGpgBinOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { - TCHAR *tmp = NULL; - switch (msg) - { - case WM_INITDIALOG: - { + switch (msg) { + case WM_INITDIALOG: TranslateDialogDefault(hwndDlg); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("gpg.exe")); - SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); - mir_free(tmp); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("gpg")); - SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); - mir_free(tmp); - return TRUE; - } - - - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDC_SET_BIN_PATH: - { - GetFilePath(TranslateT("Choose gpg.exe"), "szGpgBinPath", _T("*.exe"), TranslateT("EXE Executables")); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("gpg.exe")); - SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); - bool gpg_exists = false; - { - if(_waccess(tmp, 0) != -1) - gpg_exists = true; - if(gpg_exists) - { - bool bad_version = false; - TCHAR *tmp_path = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("")); - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); - string out; - DWORD code; - std::vector cmd; - cmd.push_back(L"--version"); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - auto old_gpg_state = gpg_valid; - gpg_valid = true; - gpg_launcher(params); - gpg_valid = old_gpg_state; - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp_path); - mir_free(tmp_path); - string::size_type p1 = out.find("(GnuPG) "); - if(p1 != string::npos) - { - p1 += mir_strlen("(GnuPG) "); - if(out[p1] != '1') - bad_version = true; - } - else - { - bad_version = false; - MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); - } -/* if(bad_version) //looks like working fine with gpg2 - MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), _T("Warning"), MB_OK); */ - } - } - char mir_path[MAX_PATH]; - char *atmp = mir_t2a(tmp); - mir_free(tmp); - PathToAbsolute("\\", mir_path); - char* p_path = NULL; - if(StriStr(atmp, mir_path)) - { - p_path = atmp + mir_strlen(mir_path); - tmp = mir_a2t(p_path); - SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); - } - } - break; - case IDC_SET_HOME_DIR: - { - GetFolderPath(TranslateT("Set home directory"), "szHomePath"); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); - char mir_path[MAX_PATH]; - char *atmp = mir_t2a(tmp); - mir_free(tmp); - PathToAbsolute("\\", mir_path); - char* p_path = NULL; - if(StriStr(atmp, mir_path)) - { - p_path = atmp + mir_strlen(mir_path); - tmp = mir_a2t(p_path); - SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); - } - mir_free(atmp); - } - break; - default: + SetDlgItemText(hwndDlg, IDC_BIN_PATH, ptrT(UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("gpg.exe")))); + SetDlgItemText(hwndDlg, IDC_HOME_DIR, ptrT(UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("gpg")))); + return TRUE; + + case WM_COMMAND: + switch (LOWORD(wParam)) { + case IDC_SET_BIN_PATH: + { + GetFilePath(TranslateT("Choose gpg.exe"), "szGpgBinPath", _T("*.exe"), TranslateT("EXE Executables")); + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("gpg.exe")); + SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); + bool gpg_exists = false; + { + if (_waccess(tmp, 0) != -1) + gpg_exists = true; + if (gpg_exists) { + bool bad_version = false; + TCHAR *tmp_path = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("")); + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); + string out; + DWORD code; + std::vector cmd; + cmd.push_back(L"--version"); + gpg_execution_params params(cmd); + pxResult result; + params.out = &out; + params.code = &code; + params.result = &result; + auto old_gpg_state = gpg_valid; + gpg_valid = true; + gpg_launcher(params); + gpg_valid = old_gpg_state; + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp_path); + mir_free(tmp_path); + string::size_type p1 = out.find("(GnuPG) "); + if (p1 != string::npos) { + p1 += mir_strlen("(GnuPG) "); + if (out[p1] != '1') + bad_version = true; + } + else { + bad_version = false; + MessageBox(0, TranslateT("This is not GnuPG binary!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), TranslateT("Warning"), MB_OK); + } + /* if(bad_version) //looks like working fine with gpg2 + MessageBox(0, TranslateT("Unsupported GnuPG version found, use at you own risk!\nIt is recommended that you use GnuPG v1.x.x with this plugin."), _T("Warning"), MB_OK); */ + } + } + char mir_path[MAX_PATH]; + char *atmp = mir_t2a(tmp); + mir_free(tmp); + PathToAbsolute("\\", mir_path); + char* p_path = NULL; + if (StriStr(atmp, mir_path)) { + p_path = atmp + mir_strlen(mir_path); + tmp = mir_a2t(p_path); + SetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp); + } + } + break; + case IDC_SET_HOME_DIR: + { + GetFolderPath(TranslateT("Set home directory"), "szHomePath"); + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); + SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); + char mir_path[MAX_PATH]; + char *atmp = mir_t2a(tmp); + mir_free(tmp); + PathToAbsolute("\\", mir_path); + char* p_path = NULL; + if (StriStr(atmp, mir_path)) { + p_path = atmp + mir_strlen(mir_path); + tmp = mir_a2t(p_path); + SetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp); + } + mir_free(atmp); + } + break; + default: + break; + } + + SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0); + break; + + case WM_NOTIFY: + switch (((LPNMHDR)lParam)->code) { + case PSN_APPLY: + TCHAR tmp[512]; + GetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp, _countof(tmp)); + db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); + GetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp, _countof(tmp)); + while (tmp[mir_tstrlen(tmp) - 1] == '\\') + tmp[mir_tstrlen(tmp) - 1] = '\0'; + db_set_ts(NULL, szGPGModuleName, "szHomePath", tmp); + return TRUE; + } break; - } - - SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0); - break; - } - - case WM_NOTIFY: - { - switch (((LPNMHDR)lParam)->code) - { - - case PSN_APPLY: - { - TCHAR tmp[512]; - GetDlgItemText(hwndDlg, IDC_BIN_PATH, tmp, _countof(tmp)); - db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); - GetDlgItemText(hwndDlg, IDC_HOME_DIR, tmp, _countof(tmp)); - while(tmp[mir_tstrlen(tmp)-1] == '\\') - tmp[mir_tstrlen(tmp)-1] = '\0'; - db_set_ts(NULL, szGPGModuleName, "szHomePath", tmp); - return TRUE; - } - } } - break; - } - return FALSE; + return FALSE; } static INT_PTR CALLBACK DlgProcGpgMsgOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { - switch (msg) - { - case WM_INITDIALOG: - { - TranslateDialogDefault(hwndDlg); - CheckStateLoadDB(hwndDlg, IDC_APPEND_TAGS, "bAppendTags", 0); - CheckStateLoadDB(hwndDlg, IDC_STRIP_TAGS, "bStripTags", 0); + switch (msg) { + case WM_INITDIALOG: { - TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szInOpenTag", _T("")); - SetDlgItemText(hwndDlg, IDC_IN_OPEN_TAG, tmp); - mir_free(tmp); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szInCloseTag", _T("")); - SetDlgItemText(hwndDlg, IDC_IN_CLOSE_TAG, tmp); - mir_free(tmp); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szOutOpenTag", _T("")); - SetDlgItemText(hwndDlg, IDC_OUT_OPEN_TAG, tmp); - mir_free(tmp); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szOutCloseTag", _T("")); - SetDlgItemText(hwndDlg, IDC_OUT_CLOSE_TAG, tmp); - mir_free(tmp); - } - return TRUE; - } - - - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDC_APPEND_TAGS: - break; - default: - break; - } - - SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0); - break; - } - - case WM_NOTIFY: - { - switch (((LPNMHDR)lParam)->code) - { - - case PSN_APPLY: - { - bAppendTags = CheckStateStoreDB(hwndDlg, IDC_APPEND_TAGS, "bAppendTags") != 0; - bStripTags = CheckStateStoreDB(hwndDlg, IDC_STRIP_TAGS, "bStripTags") != 0; + TranslateDialogDefault(hwndDlg); + CheckStateLoadDB(hwndDlg, IDC_APPEND_TAGS, "bAppendTags", 0); + CheckStateLoadDB(hwndDlg, IDC_STRIP_TAGS, "bStripTags", 0); { - TCHAR tmp[128]; - GetDlgItemText(hwndDlg, IDC_IN_OPEN_TAG, tmp, _countof(tmp)); - db_set_ts(NULL, szGPGModuleName, "szInOpenTag", tmp); - mir_free(inopentag); - inopentag = (TCHAR*)mir_alloc(sizeof(TCHAR)* (mir_tstrlen(tmp)+1)); - mir_tstrcpy(inopentag, tmp); - GetDlgItemText(hwndDlg, IDC_IN_CLOSE_TAG, tmp, _countof(tmp)); - db_set_ts(NULL, szGPGModuleName, "szInCloseTag", tmp); - mir_free(inclosetag); - inclosetag = (TCHAR*)mir_alloc(sizeof(TCHAR)* (mir_tstrlen(tmp)+1)); - mir_tstrcpy(inclosetag, tmp); - GetDlgItemText(hwndDlg, IDC_OUT_OPEN_TAG, tmp, _countof(tmp)); - db_set_ts(NULL, szGPGModuleName, "szOutOpenTag", tmp); - mir_free(outopentag); - outopentag = (TCHAR*)mir_alloc(sizeof(TCHAR)* (mir_tstrlen(tmp)+1)); - mir_tstrcpy(outopentag, tmp); - GetDlgItemText(hwndDlg, IDC_OUT_CLOSE_TAG, tmp, _countof(tmp)); - db_set_ts(NULL, szGPGModuleName, "szOutCloseTag", tmp); - mir_free(outclosetag); - outclosetag = (TCHAR*)mir_alloc(sizeof(TCHAR)*(mir_tstrlen(tmp)+1)); - mir_tstrcpy(outclosetag, tmp); + TCHAR *tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szInOpenTag", _T("")); + SetDlgItemText(hwndDlg, IDC_IN_OPEN_TAG, tmp); + mir_free(tmp); + tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szInCloseTag", _T("")); + SetDlgItemText(hwndDlg, IDC_IN_CLOSE_TAG, tmp); + mir_free(tmp); + tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szOutOpenTag", _T("")); + SetDlgItemText(hwndDlg, IDC_OUT_OPEN_TAG, tmp); + mir_free(tmp); + tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szOutCloseTag", _T("")); + SetDlgItemText(hwndDlg, IDC_OUT_CLOSE_TAG, tmp); + mir_free(tmp); } - return TRUE; - } - } + return TRUE; + } + + + case WM_COMMAND: + { + switch (LOWORD(wParam)) { + case IDC_APPEND_TAGS: + break; + default: + break; + } + + SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0); + break; + } + + case WM_NOTIFY: + { + switch (((LPNMHDR)lParam)->code) { + + case PSN_APPLY: + { + bAppendTags = CheckStateStoreDB(hwndDlg, IDC_APPEND_TAGS, "bAppendTags") != 0; + bStripTags = CheckStateStoreDB(hwndDlg, IDC_STRIP_TAGS, "bStripTags") != 0; + { + TCHAR tmp[128]; + GetDlgItemText(hwndDlg, IDC_IN_OPEN_TAG, tmp, _countof(tmp)); + db_set_ts(NULL, szGPGModuleName, "szInOpenTag", tmp); + mir_free(inopentag); + inopentag = (TCHAR*)mir_alloc(sizeof(TCHAR)* (mir_tstrlen(tmp) + 1)); + mir_tstrcpy(inopentag, tmp); + GetDlgItemText(hwndDlg, IDC_IN_CLOSE_TAG, tmp, _countof(tmp)); + db_set_ts(NULL, szGPGModuleName, "szInCloseTag", tmp); + mir_free(inclosetag); + inclosetag = (TCHAR*)mir_alloc(sizeof(TCHAR)* (mir_tstrlen(tmp) + 1)); + mir_tstrcpy(inclosetag, tmp); + GetDlgItemText(hwndDlg, IDC_OUT_OPEN_TAG, tmp, _countof(tmp)); + db_set_ts(NULL, szGPGModuleName, "szOutOpenTag", tmp); + mir_free(outopentag); + outopentag = (TCHAR*)mir_alloc(sizeof(TCHAR)* (mir_tstrlen(tmp) + 1)); + mir_tstrcpy(outopentag, tmp); + GetDlgItemText(hwndDlg, IDC_OUT_CLOSE_TAG, tmp, _countof(tmp)); + db_set_ts(NULL, szGPGModuleName, "szOutCloseTag", tmp); + mir_free(outclosetag); + outclosetag = (TCHAR*)mir_alloc(sizeof(TCHAR)*(mir_tstrlen(tmp) + 1)); + mir_tstrcpy(outclosetag, tmp); + } + return TRUE; + } + } + } + break; } - break; - } - return FALSE; + return FALSE; } static INT_PTR CALLBACK DlgProcGpgAdvOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) @@ -707,28 +639,27 @@ static INT_PTR CALLBACK DlgProcGpgAdvOpts(HWND hwndDlg, UINT msg, WPARAM wParam, HWND hPubKeyEdit = NULL; -static LRESULT CALLBACK editctrl_ctrl_a(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam) +static LRESULT CALLBACK editctrl_ctrl_a(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { - switch(msg) { + switch (msg) { case WM_KEYDOWN: - if(wParam == 0x41 && GetKeyState(VK_CONTROL)< 0 ) + if (wParam == 0x41 && GetKeyState(VK_CONTROL) < 0) SendMessage(hwndDlg, EM_SETSEL, 0, -1); return 0; } return mir_callNextSubclass(hwndDlg, editctrl_ctrl_a, msg, wParam, lParam); } -static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam) +static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { static MCONTACT hContact; - TCHAR *tmp = NULL; wstring key_buf; wstring::size_type ws1 = 0, ws2 = 0; - switch (msg) { + switch (uMsg) { case WM_INITDIALOG: { hContact = user_data[1]; - SetWindowPos(hwndDlg, 0, load_key_rect.left, load_key_rect.top, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW); + SetWindowPos(hwndDlg, 0, load_key_rect.left, load_key_rect.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); mir_subclassWindow(GetDlgItem(hwndDlg, IDC_PUBLIC_KEY_EDIT), editctrl_ctrl_a); MCONTACT hcnt = db_mc_tryMeta(hContact); TranslateDialogDefault(hwndDlg); @@ -737,46 +668,36 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam msg += pcli->pfnGetContactDisplayName(hcnt, 0); SetWindowText(hwndDlg, msg.c_str()); } - if(!hcnt) - { + if (!hcnt) { EnableWindow(GetDlgItem(hwndDlg, IDC_SELECT_EXISTING), 0); EnableWindow(GetDlgItem(hwndDlg, IDC_ENABLE_ENCRYPTION), 0); } - if(isContactSecured(hcnt)) + if (isContactSecured(hcnt)) SetDlgItemText(hwndDlg, IDC_ENABLE_ENCRYPTION, TranslateT("Turn off encryption")); - else - { + else { SetDlgItemText(hwndDlg, IDC_ENABLE_ENCRYPTION, TranslateT("Turn on encryption")); CheckDlgButton(hwndDlg, IDC_ENABLE_ENCRYPTION, BST_CHECKED); } - if(hcnt) - { - tmp = UniGetContactSettingUtf(hcnt, szGPGModuleName, "GPGPubKey", _T("")); + if (hcnt) { + TCHAR *tmp = UniGetContactSettingUtf(hcnt, szGPGModuleName, "GPGPubKey", _T("")); wstring str = tmp; mir_free(tmp); tmp = NULL; - wstring::size_type p = 0, stop = 0; - if(!str.empty()) - { - for(;;) - { - if((p = str.find(_T("\n"), p+2)) != wstring::npos) - { - if(p > stop) - { + if (!str.empty()) { + wstring::size_type p = 0, stop = 0; + for (;;) { + if ((p = str.find(_T("\n"), p + 2)) != wstring::npos) { + if (p > stop) { stop = p; str.insert(p, _T("\r")); - } - else - break; + } + else break; } } } // char *tmp = UniGetContactSettingUtf(hcnt, szGPGModuleName, "KeyID_Prescense", ""); - if(!hcontact_data[hcnt].key_in_prescense.empty()) - { + if (!hcontact_data[hcnt].key_in_prescense.empty()) { char *tmp2 = UniGetContactSettingUtf(hcnt, szGPGModuleName, "KeyID", ""); - if(!tmp2[0]) - { + if (!tmp2[0]) { string out; DWORD code; std::vector cmd; @@ -789,19 +710,15 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam params.code = &code; params.result = &result; gpg_launcher(params); //TODO: handle errors - if((out.find("-----BEGIN PGP PUBLIC KEY BLOCK-----") != string::npos) && (out.find("-----END PGP PUBLIC KEY BLOCK-----") != string::npos)) - { + if ((out.find("-----BEGIN PGP PUBLIC KEY BLOCK-----") != string::npos) && (out.find("-----END PGP PUBLIC KEY BLOCK-----") != string::npos)) { string::size_type p = 0, stop = 0; - for(;;) - { - if((p = out.find("\n", p+2)) != string::npos) - { - if(p > stop) - { + for (;;) { + if ((p = out.find("\n", p + 2)) != string::npos) { + if (p > stop) { stop = p; out.insert(p, "\r"); - } - else + } + else break; } } @@ -816,8 +733,7 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam msg += Translate(" found in presence, and exists in keyring.)"); SetWindowTextA(hwndDlg, msg.c_str()); } - else - { + else { string msg = Translate("Load Public GPG Key (Key ID: "); msg += hcontact_data[hcnt].key_in_prescense; msg += Translate(" found in presence.)"); @@ -827,9 +743,9 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam } mir_free(tmp2); } - if(tmp) + if (tmp) mir_free(tmp); - SetDlgItemText(hwndDlg, IDC_PUBLIC_KEY_EDIT, !str.empty()?str.c_str():_T("")); + SetDlgItemText(hwndDlg, IDC_PUBLIC_KEY_EDIT, !str.empty() ? str.c_str() : _T("")); } hPubKeyEdit = GetDlgItem(hwndDlg, IDC_PUBLIC_KEY_EDIT); return TRUE; @@ -837,72 +753,64 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam case WM_COMMAND: { - switch (LOWORD(wParam)) - { + switch (LOWORD(wParam)) { case ID_OK: { - tmp = new TCHAR [40960]; + TCHAR *tmp = new TCHAR[40960]; TCHAR *begin, *end; GetDlgItemText(hwndDlg, IDC_PUBLIC_KEY_EDIT, tmp, 40960); key_buf.append(tmp); key_buf.append(_T("\n")); //no new line at end of file ) - delete [] tmp; - while((ws1 = key_buf.find(_T("\r"), ws1)) != wstring::npos) - { + delete[] tmp; + while ((ws1 = key_buf.find(_T("\r"), ws1)) != wstring::npos) { key_buf.erase(ws1, 1); //remove windows specific trash } ws1 = 0; - if(((ws2 = key_buf.find(_T("-----END PGP PUBLIC KEY BLOCK-----"))) != wstring::npos) && ((ws1 = key_buf.find(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----"))) != wstring::npos)) - { + if (((ws2 = key_buf.find(_T("-----END PGP PUBLIC KEY BLOCK-----"))) != wstring::npos) && ((ws1 = key_buf.find(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----"))) != wstring::npos)) { begin = (TCHAR*)mir_alloc(sizeof(TCHAR) * (mir_tstrlen(_T("-----BEGIN PGP PUBLIC KEY BLOCK-----")) + 1)); mir_tstrcpy(begin, _T("-----BEGIN PGP PUBLIC KEY BLOCK-----")); - end = (TCHAR*)mir_alloc(sizeof( TCHAR) * (mir_tstrlen(_T("-----END PGP PUBLIC KEY BLOCK-----")) + 1)); + end = (TCHAR*)mir_alloc(sizeof(TCHAR) * (mir_tstrlen(_T("-----END PGP PUBLIC KEY BLOCK-----")) + 1)); mir_tstrcpy(end, _T("-----END PGP PUBLIC KEY BLOCK-----")); } - else if(((ws2 = key_buf.find(_T("-----END PGP PRIVATE KEY BLOCK-----"))) != wstring::npos) && ((ws1 = key_buf.find(_T("-----BEGIN PGP PRIVATE KEY BLOCK-----"))) != wstring::npos)) - { + else if (((ws2 = key_buf.find(_T("-----END PGP PRIVATE KEY BLOCK-----"))) != wstring::npos) && ((ws1 = key_buf.find(_T("-----BEGIN PGP PRIVATE KEY BLOCK-----"))) != wstring::npos)) { begin = (TCHAR*)mir_alloc(sizeof(TCHAR) * (mir_tstrlen(_T("-----BEGIN PGP PRIVATE KEY BLOCK-----")) + 1)); mir_tstrcpy(begin, _T("-----BEGIN PGP PRIVATE KEY BLOCK-----")); end = (TCHAR*)mir_alloc(sizeof(TCHAR) * (mir_tstrlen(_T("-----END PGP PRIVATE KEY BLOCK-----")) + 1)); mir_tstrcpy(end, _T("-----END PGP PRIVATE KEY BLOCK-----")); } - else - { + else { MessageBox(0, TranslateT("This is not public or private key"), _T("INFO"), MB_OK); break; } ws2 += mir_tstrlen(end); bool allsubcontacts = false; { - if(db_mc_isMeta(hContact)) - { - if(MessageBox(0, TranslateT("Do you want to load key for all subcontacts?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) - { + if (db_mc_isMeta(hContact)) { + if (MessageBox(0, TranslateT("Do you want to load key for all subcontacts?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) { allsubcontacts = true; int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) - db_set_ts(hcnt, szGPGModuleName, "GPGPubKey", key_buf.substr(ws1,ws2-ws1).c_str()); + if (hcnt) + db_set_ts(hcnt, szGPGModuleName, "GPGPubKey", key_buf.substr(ws1, ws2 - ws1).c_str()); } } - else db_set_ts(metaGetMostOnline(hContact), szGPGModuleName, "GPGPubKey", key_buf.substr(ws1,ws2-ws1).c_str()); + else db_set_ts(metaGetMostOnline(hContact), szGPGModuleName, "GPGPubKey", key_buf.substr(ws1, ws2 - ws1).c_str()); } - else db_set_ts(hContact, szGPGModuleName, "GPGPubKey", key_buf.substr(ws1,ws2-ws1).c_str()); + else db_set_ts(hContact, szGPGModuleName, "GPGPubKey", key_buf.substr(ws1, ws2 - ws1).c_str()); } - tmp = (TCHAR*)mir_alloc(sizeof( TCHAR) * (key_buf.length()+1)); - mir_tstrcpy(tmp, key_buf.substr(ws1,ws2-ws1).c_str()); + tmp = (TCHAR*)mir_alloc(sizeof(TCHAR) * (key_buf.length() + 1)); + mir_tstrcpy(tmp, key_buf.substr(ws1, ws2 - ws1).c_str()); { //gpg execute block std::vector cmd; - TCHAR tmp2[MAX_PATH] = {0}; + TCHAR tmp2[MAX_PATH] = { 0 }; TCHAR *ptmp; string output; DWORD exitcode; { MCONTACT hcnt = db_mc_tryMeta(hContact); ptmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - _tcsncpy(tmp2, ptmp, MAX_PATH-1); + _tcsncpy(tmp2, ptmp, MAX_PATH - 1); mir_free(ptmp); mir_tstrncat(tmp2, _T("\\"), _countof(tmp2) - mir_tstrlen(tmp2)); mir_tstrncat(tmp2, _T("temporary_exported.asc"), _countof(tmp2) - mir_tstrlen(tmp2)); @@ -912,11 +820,10 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam wstring str = ptmp; mir_free(ptmp); wstring::size_type s = 0; - while((s = str.find(_T("\r"), s)) != wstring::npos) - { + while ((s = str.find(_T("\r"), s)) != wstring::npos) { str.erase(s, 1); } - f< output.find("<", s)) + else if (s2 > output.find("<", s)) s2 = output.find("<", s); - if(s2 != string::npos && s != string::npos) - { - tmp2 = (char*)mir_alloc(sizeof(char)*(output.substr(s,s2-s-(uncommon?1:0)).length()+1)); - mir_strcpy(tmp2, output.substr(s,s2-s-(uncommon?1:0)).c_str()); - mir_utf8decode(tmp2, 0); - if(hContact) + if (s2 != string::npos && s != string::npos) { { - if(db_mc_isMeta(hContact)) - { - if(allsubcontacts) - { - int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { - MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) - db_set_s(hcnt, szGPGModuleName, "KeyMainName", output.substr(s,s2-s-1).c_str()); + char *tmp3 = (char*)mir_alloc(sizeof(char)*(output.substr(s, s2 - s - (uncommon ? 1 : 0)).length() + 1)); + mir_strcpy(tmp3, output.substr(s, s2 - s - (uncommon ? 1 : 0)).c_str()); + mir_utf8decode(tmp3, 0); + if (hContact) { + if (db_mc_isMeta(hContact)) { + if (allsubcontacts) { + int count = db_mc_getSubCount(hContact); + for (int i = 0; i < count; i++) { + MCONTACT hcnt = db_mc_getSub(hContact, i); + if (hcnt) + db_set_s(hcnt, szGPGModuleName, "KeyMainName", output.substr(s, s2 - s - 1).c_str()); + } } + else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainName", output.substr(s, s2 - s - 1).c_str()); } - else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainName", output.substr(s,s2-s-1).c_str()); + else db_set_s(hContact, szGPGModuleName, "KeyMainName", output.substr(s, s2 - s - 1).c_str()); } - else db_set_s(hContact, szGPGModuleName, "KeyMainName", output.substr(s,s2-s-1).c_str()); + mir_free(tmp3); } - mir_free(tmp2); - tmp = mir_wstrdup(toUTF16(output.substr(s,s2-s-1)).c_str()); - if(hContact && hwndList_p) + tmp = mir_wstrdup(toUTF16(output.substr(s, s2 - s - 1)).c_str()); + if (hContact && hwndList_p) ListView_SetItemText(hwndList_p, item_num, 2, tmp); mir_free(tmp); - if((s = output.find(")", s2)) == string::npos) + if ((s = output.find(")", s2)) == string::npos) s = output.find(">", s2); - else if(s > output.find(">", s2)) + else if (s > output.find(">", s2)) s = output.find(">", s2); s2++; - if(s != string::npos && s2 != string::npos) - { - if(output[s] == ')') - { - tmp2 = (char*)mir_alloc((output.substr(s2,s-s2).length()+1)*sizeof(char)); - mir_strcpy(tmp2, output.substr(s2,s-s2).c_str()); - mir_utf8decode(tmp2, 0); - if(hContact) - { - if(db_mc_isMeta(hContact)) - { - if(allsubcontacts) - { + if (s != string::npos && s2 != string::npos) { + if (output[s] == ')') { + char *tmp3 = (char*)mir_alloc((output.substr(s2, s - s2).length() + 1)*sizeof(char)); + mir_strcpy(tmp3, output.substr(s2, s - s2).c_str()); + mir_utf8decode(tmp3, 0); + if (hContact) { + if (db_mc_isMeta(hContact)) { + if (allsubcontacts) { int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) - db_set_s(hcnt, szGPGModuleName, "KeyComment", output.substr(s2,s-s2).c_str()); + if (hcnt) + db_set_s(hcnt, szGPGModuleName, "KeyComment", output.substr(s2, s - s2).c_str()); } } - else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyComment", output.substr(s2,s-s2).c_str()); + else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyComment", output.substr(s2, s - s2).c_str()); } - else db_set_s(hContact, szGPGModuleName, "KeyComment", output.substr(s2,s-s2).c_str()); + else db_set_s(hContact, szGPGModuleName, "KeyComment", output.substr(s2, s - s2).c_str()); } - mir_free(tmp2); - s+=3; + mir_free(tmp3); + s += 3; s2 = output.find(">", s); - tmp2 = (char*)mir_alloc((output.substr(s,s2-s).length()+1) * sizeof(char)); - mir_strcpy(tmp2, output.substr(s,s2-s).c_str()); - mir_utf8decode(tmp2, 0); - if(hContact) - { - if(db_mc_isMeta(hContact)) - { - if(allsubcontacts) - { + tmp3 = (char*)mir_alloc((output.substr(s, s2 - s).length() + 1) * sizeof(char)); + mir_strcpy(tmp3, output.substr(s, s2 - s).c_str()); + mir_utf8decode(tmp3, 0); + if (hContact) { + if (db_mc_isMeta(hContact)) { + if (allsubcontacts) { int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) - db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", output.substr(s,s2-s).c_str()); + if (hcnt) + db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", output.substr(s, s2 - s).c_str()); } } - else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", output.substr(s,s2-s).c_str()); + else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", output.substr(s, s2 - s).c_str()); } - else db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s,s2-s).c_str()); + else db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s, s2 - s).c_str()); } - mir_free(tmp2); - tmp = mir_wstrdup(toUTF16(output.substr(s,s2-s)).c_str()); - if(hContact && hwndList_p) + mir_free(tmp3); + tmp = mir_wstrdup(toUTF16(output.substr(s, s2 - s)).c_str()); + if (hContact && hwndList_p) ListView_SetItemText(hwndList_p, item_num, 3, tmp); mir_free(tmp); } - else - { - tmp2 = (char*)mir_alloc(output.substr(s2,s-s2).length()+1); - mir_strcpy(tmp2, output.substr(s2,s-s2).c_str()); - mir_utf8decode(tmp2, 0); - if(hContact) - { - if(db_mc_isMeta(hContact)) - { - if(allsubcontacts) - { + else { + char *tmp3 = (char*)mir_alloc(output.substr(s2, s - s2).length() + 1); + mir_strcpy(tmp3, output.substr(s2, s - s2).c_str()); + mir_utf8decode(tmp3, 0); + if (hContact) { + if (db_mc_isMeta(hContact)) { + if (allsubcontacts) { int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) - db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); + if (hcnt) + db_set_s(hcnt, szGPGModuleName, "KeyMainEmail", output.substr(s2, s - s2).c_str()); } } - else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); + else db_set_s(metaGetMostOnline(hContact), szGPGModuleName, "KeyMainEmail", output.substr(s2, s - s2).c_str()); } - else db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); + else db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2, s - s2).c_str()); } - mir_free(tmp2); - tmp = mir_wstrdup(toUTF16(output.substr(s2,s-s2)).c_str()); - if(hContact && hwndList_p) + mir_free(tmp3); + tmp = mir_wstrdup(toUTF16(output.substr(s2, s - s2)).c_str()); + if (hContact && hwndList_p) ListView_SetItemText(hwndList_p, item_num, 3, tmp); mir_free(tmp); } } } - if(hContact && hwndList_p) - { + if (hContact && hwndList_p) { ListView_SetColumnWidth(hwndList_p, 0, LVSCW_AUTOSIZE); ListView_SetColumnWidth(hwndList_p, 1, LVSCW_AUTOSIZE); ListView_SetColumnWidth(hwndList_p, 2, LVSCW_AUTOSIZE); ListView_SetColumnWidth(hwndList_p, 3, LVSCW_AUTOSIZE); } } - if(!hContact) - { + if (!hContact) { TCHAR *fp = UniGetContactSettingUtf(hContact, szGPGModuleName, "KeyID", _T("")); { string out; DWORD code; - std::vector cmd; - cmd.push_back(L"--batch"); - cmd.push_back(L"-a"); - cmd.push_back(L"--export"); - cmd.push_back(fp); + std::vector cmds; + cmds.push_back(L"--batch"); + cmds.push_back(L"-a"); + cmds.push_back(L"--export"); + cmds.push_back(fp); mir_free(fp); - gpg_execution_params params(cmd); - pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params)) + gpg_execution_params params2(cmds); + pxResult result2; + params2.out = &out; + params2.code = &code; + params2.result = &result2; + if (!gpg_launcher(params2)) break; - if(result == pxNotFound) + if (result2 == pxNotFound) break; string::size_type s = 0; - while((s = out.find("\r", s)) != string::npos) - { + while ((s = out.find("\r", s)) != string::npos) { out.erase(s, 1); } db_set_s(hContact, szGPGModuleName, "GPGPubKey", out.c_str()); @@ -1170,21 +1045,15 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam boost::filesystem::remove(tmp2); } key_buf.clear(); - if(IsDlgButtonChecked(hwndDlg, IDC_ENABLE_ENCRYPTION)) - { - if(hContact) - { - if(db_mc_isMeta(hContact)) - { - if(allsubcontacts) - { + if (IsDlgButtonChecked(hwndDlg, IDC_ENABLE_ENCRYPTION)) { + if (hContact) { + if (db_mc_isMeta(hContact)) { + if (allsubcontacts) { int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) - { - if(!isContactSecured(hcnt)) + if (hcnt) { + if (!isContactSecured(hcnt)) db_set_b(hcnt, szGPGModuleName, "GPGEncryption", 1); else db_set_b(hcnt, szGPGModuleName, "GPGEncryption", 0); @@ -1193,12 +1062,12 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam } } } - else if(!isContactSecured(hContact)) + else if (!isContactSecured(hContact)) db_set_b(metaGetMostOnline(hContact), szGPGModuleName, "GPGEncryption", 1); else db_set_b(metaGetMostOnline(hContact), szGPGModuleName, "GPGEncryption", 0); } - else if(!isContactSecured(hContact)) + else if (!isContactSecured(hContact)) db_set_b(hContact, szGPGModuleName, "GPGEncryption", 1); else db_set_b(hContact, szGPGModuleName, "GPGEncryption", 0); @@ -1209,59 +1078,55 @@ static INT_PTR CALLBACK DlgProcLoadPublicKey(HWND hwndDlg,UINT msg,WPARAM wParam break; case ID_LOAD_FROM_FILE: { - tmp = GetFilePath(TranslateT("Set file containing GPG public key"), _T("*"), TranslateT("GPG public key file")); - if(!tmp) - { + TCHAR *tmp = GetFilePath(TranslateT("Set file containing GPG public key"), _T("*"), TranslateT("GPG public key file")); + if (!tmp) break; - } + wfstream f(tmp, std::ios::in | std::ios::ate | std::ios::binary); - delete [] tmp; - if(!f.is_open()) - { + delete[] tmp; + if (!f.is_open()) { MessageBox(0, TranslateT("Failed to open file"), TranslateT("Error"), MB_OK); break; } - if(f.is_open()) - { + if (f.is_open()) { std::wifstream::pos_type size = f.tellg(); - TCHAR *tmp = new TCHAR [(std::ifstream::pos_type)size+(std::ifstream::pos_type)1]; + TCHAR *temp = new TCHAR[(std::ifstream::pos_type)size + (std::ifstream::pos_type)1]; f.seekg(0, std::ios::beg); - f.read(tmp, size); - tmp[size]= '\0'; - key_buf.append(tmp); - delete [] tmp; + f.read(temp, size); + temp[size] = '\0'; + key_buf.append(temp); + delete[] temp; f.close(); } - if(key_buf.empty()) - { + if (key_buf.empty()) { key_buf.clear(); - if(bDebugLog) - debuglog<Free(pidl); imalloc->Release(); } @@ -157,32 +150,28 @@ INT_PTR SendKey(WPARAM w, LPARAM) LPSTR proto = GetContactProto(hContact); PROTOACCOUNT *acc = Proto_GetAccount(proto); std::string acc_str; - if(acc) - { + if (acc) { acc_str = toUTF8(acc->tszAccountName); acc_str += "("; acc_str += acc->szModuleName; - acc_str += ")" ; + acc_str += ")"; key_id_str = acc_str; key_id_str += "_KeyID"; acc_str += "_GPGPubKey"; } - szMessage = UniGetContactSettingUtf(NULL, szGPGModuleName, acc_str.empty()?"GPGPubKey":acc_str.c_str(), ""); - if(!szMessage[0]) - { + szMessage = UniGetContactSettingUtf(NULL, szGPGModuleName, acc_str.empty() ? "GPGPubKey" : acc_str.c_str(), ""); + if (!szMessage[0]) { mir_free(szMessage); szMessage = UniGetContactSettingUtf(NULL, szGPGModuleName, "GPGPubKey", ""); //try to get default key as fallback in any way } } - if(szMessage[0]) - { + if (szMessage[0]) { BYTE enc = db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0); db_set_b(hContact, szGPGModuleName, "GPGEncryption", 0); CallContactService(hContact, PSS_MESSAGE, 0, (LPARAM)szMessage); std::string msg = "Public key "; char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, key_id_str.c_str(), ""); - if(!keyid[0]) - { + if (!keyid[0]) { mir_free(keyid); keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); } @@ -203,24 +192,21 @@ INT_PTR ToggleEncryption(WPARAM w, LPARAM) { MCONTACT hContact = (MCONTACT)w; BYTE enc; - if(db_mc_isMeta(hContact)) - { + if (db_mc_isMeta(hContact)) { enc = db_get_b(metaGetMostOnline(hContact), szGPGModuleName, "GPGEncryption", 0); - if(MessageBox(0, TranslateT("Do you want to toggle encryption for all subcontacts?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) - { + if (MessageBox(0, TranslateT("Do you want to toggle encryption for all subcontacts?"), TranslateT("Metacontact detected"), MB_YESNO) == IDYES) { int count = db_mc_getSubCount(hContact); - for(int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { MCONTACT hcnt = db_mc_getSub(hContact, i); - if(hcnt) - db_set_b(hcnt, szGPGModuleName, "GPGEncryption", enc?0:1); + if (hcnt) + db_set_b(hcnt, szGPGModuleName, "GPGEncryption", enc ? 0 : 1); } - db_set_b(hContact, szGPGModuleName, "GPGEncryption", enc?0:1); + db_set_b(hContact, szGPGModuleName, "GPGEncryption", enc ? 0 : 1); } } else { enc = db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0); - db_set_b(hContact, szGPGModuleName, "GPGEncryption", enc?0:1); + db_set_b(hContact, szGPGModuleName, "GPGEncryption", enc ? 0 : 1); } void setSrmmIcon(MCONTACT hContact); void setClistIcon(MCONTACT hContact); @@ -239,21 +225,19 @@ int OnPreBuildContactMenu(WPARAM w, LPARAM) LPSTR proto = GetContactProto(hContact); PROTOACCOUNT *acc = Proto_GetAccount(proto); std::string setting; - if(acc) - { + if (acc) { setting = toUTF8(acc->tszAccountName); setting += "("; setting += acc->szModuleName; - setting += ")" ; + setting += ")"; setting += "_KeyID"; } char *keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, setting.c_str(), ""); - if(!keyid[0]) - { + if (!keyid[0]) { mir_free(keyid); keyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); } - TCHAR buf[128] = {0}; + TCHAR buf[128] = { 0 }; mir_sntprintf(buf, _T("%s: %s"), TranslateT("Send public key"), toUTF16(keyid).c_str()); mir_free(keyid); Menu_ModifyItem(hSendKey, buf); @@ -261,14 +245,13 @@ int OnPreBuildContactMenu(WPARAM w, LPARAM) int flags; TCHAR *tmp = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", _T("")); - if(!tmp[0]) - { + if (!tmp[0]) { db_unset(hContact, szGPGModuleName, "GPGEncryption"); flags = CMIF_GRAYED; } else flags = 0; - Menu_ModifyItem(hToggleEncryption, + Menu_ModifyItem(hToggleEncryption, db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0) ? _T("Turn off GPG encryption") : _T("Turn on GPG encryption"), INVALID_HANDLE_VALUE, flags); mir_free(tmp); @@ -282,46 +265,40 @@ DWORD file_msg_state = -1; int onProtoAck(WPARAM, LPARAM l) { - ACKDATA *ack=(ACKDATA*)l; - if(ack->type == ACKTYPE_FILE) - { - switch(ack->result) - { - case ACKRESULT_DENIED: case ACKRESULT_FAILED: + ACKDATA *ack = (ACKDATA*)l; + if (ack->type == ACKTYPE_FILE) { + switch (ack->result) { + case ACKRESULT_DENIED: case ACKRESULT_FAILED: break; case ACKRESULT_SUCCESS: { - PROTOFILETRANSFERSTATUS *f = (PROTOFILETRANSFERSTATUS*) ack->hProcess; - if((f->flags & PFTS_SENDING) != PFTS_SENDING) - { + PROTOFILETRANSFERSTATUS *f = (PROTOFILETRANSFERSTATUS*)ack->hProcess; + if ((f->flags & PFTS_SENDING) != PFTS_SENDING) { TCHAR *filename = NULL; - if(f->flags & PFTS_UNICODE) - { - if(f->tszCurrentFile && f->tszCurrentFile[0]) + if (f->flags & PFTS_UNICODE) { + if (f->tszCurrentFile && f->tszCurrentFile[0]) filename = mir_wstrdup(f->tszCurrentFile); - if(!filename) + if (!filename) return 0; } - else - { - if(f->szCurrentFile && f->szCurrentFile[0]) + else { + if (f->szCurrentFile && f->szCurrentFile[0]) filename = mir_utf8decodeT(f->szCurrentFile); - if(!filename) + if (!filename) return 0; } - if(_tcsstr(filename, _T(".gpg"))) //decrypt it + if (_tcsstr(filename, _T(".gpg"))) //decrypt it { //process encrypted file - if(!bFileTransfers && !bSameAction) - { + if (!bFileTransfers && !bSameAction) { void ShowEncryptedFileMsgBox(); ShowEncryptedFileMsgBox(); } - if(!bFileTransfers && bSameAction) + if (!bFileTransfers && bSameAction) return 0; - if(file_msg_state < 1) + if (file_msg_state < 1) return 0; - HistoryLog(ack->hContact, db_event("Received encrypted file, trying to decrypt", 0,0, 0)); - if(!boost::filesystem::exists(f->tszCurrentFile)) + HistoryLog(ack->hContact, db_event("Received encrypted file, trying to decrypt", 0, 0, 0)); + if (!boost::filesystem::exists(f->tszCurrentFile)) return 0; string out; DWORD code; @@ -331,9 +308,8 @@ int onProtoAck(WPARAM, LPARAM l) wstring file = filename; wstring::size_type p1 = file.rfind(_T(".gpg")); file.erase(p1, mir_tstrlen(_T(".gpg"))); - if(boost::filesystem::exists(file)) - { - if(MessageBox(0, TranslateT("Target file exists, do you want to replace it?"), TranslateT("Warning"), MB_YESNO) == IDNO) + if (boost::filesystem::exists(file)) { + if (MessageBox(0, TranslateT("Target file exists, do you want to replace it?"), TranslateT("Warning"), MB_YESNO) == IDNO) return 0; } cmd.push_back(file); @@ -342,35 +318,31 @@ int onProtoAck(WPARAM, LPARAM l) { // password TCHAR *pass = NULL; char *keyid = UniGetContactSettingUtf(ack->hContact, szGPGModuleName, "KeyID", ""); - if(mir_strlen(keyid) > 0) - { + if (mir_strlen(keyid) > 0) { string dbsetting = "szKey_"; dbsetting += keyid; dbsetting += "_Password"; pass = UniGetContactSettingUtf(NULL, szGPGModuleName, dbsetting.c_str(), _T("")); - if(mir_tstrlen(pass) > 0 && bDebugLog) - debuglog<pfnGetContactDisplayName(ack->hContact, 0))+" with password"); + if (mir_tstrlen(pass) > 0 && bDebugLog) + debuglog << std::string(time_str() + ": info: found password in database for key ID: " + keyid + ", trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(ack->hContact, 0)) + " with password"); } - else - { + else { pass = UniGetContactSettingUtf(NULL, szGPGModuleName, "szKeyPassword", _T("")); - if(mir_tstrlen(pass) > 0 && bDebugLog) - debuglog<pfnGetContactDisplayName(ack->hContact, 0))+" with password"); + if (mir_tstrlen(pass) > 0 && bDebugLog) + debuglog << std::string(time_str() + ": info: found password for all keys in database, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(ack->hContact, 0)) + " with password"); } - if(mir_tstrlen(pass) > 0) - { + if (mir_tstrlen(pass) > 0) { cmd.push_back(L"--passphrase"); cmd.push_back(pass); } - else if(password) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ack->hContact, 0))+" with password"); + else if (password) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: found password in memory, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(ack->hContact, 0)) + " with password"); cmd.push_back(L"--passphrase"); cmd.push_back(password); } else if (bDebugLog) - debuglog<pfnGetContactDisplayName(ack->hContact, 0))+" with out password"); + debuglog << std::string(time_str() + ": info: passwords not found in database or memory, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(ack->hContact, 0)) + " with out password"); mir_free(pass); mir_free(keyid); } @@ -380,79 +352,66 @@ int onProtoAck(WPARAM, LPARAM l) params.out = &out; params.code = &code; params.result = &result; - if(!gpg_launcher(params, boost::posix_time::minutes(15))) + if (!gpg_launcher(params, boost::posix_time::minutes(15))) return 0; - while(out.find("public key decryption failed: bad passphrase") != string::npos) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ack->hContact, 0))+" password needed, trying to get one"); - if(_terminate) + while (out.find("public key decryption failed: bad passphrase") != string::npos) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: failed to decrypt messaage from " + toUTF8(pcli->pfnGetContactDisplayName(ack->hContact, 0)) + " password needed, trying to get one"); + if (_terminate) break; { //save inkey id string::size_type s = out.find(" encrypted with "); s = out.find(" ID ", s); s += mir_strlen(" ID "); - string::size_type s2 = out.find(",",s); - if(db_mc_isMeta(ack->hContact)) - db_set_s(metaGetMostOnline(ack->hContact), szGPGModuleName, "InKeyID", out.substr(s, s2-s).c_str()); + string::size_type s2 = out.find(",", s); + if (db_mc_isMeta(ack->hContact)) + db_set_s(metaGetMostOnline(ack->hContact), szGPGModuleName, "InKeyID", out.substr(s, s2 - s).c_str()); else - db_set_s(ack->hContact, szGPGModuleName, "InKeyID", out.substr(s, s2-s).c_str()); + db_set_s(ack->hContact, szGPGModuleName, "InKeyID", out.substr(s, s2 - s).c_str()); } void ShowLoadKeyPasswordWindow(); new_key_hcnt_mutex.lock(); new_key_hcnt = ack->hContact; ShowLoadKeyPasswordWindow(); std::vector cmd2 = cmd; - if(password) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(ack->hContact, 0))); + if (password) { + if (bDebugLog) + debuglog << std::string(time_str() + ": info: found password in memory, trying to decrypt message from " + toUTF8(pcli->pfnGetContactDisplayName(ack->hContact, 0))); std::vector tmp; tmp.push_back(L"--passphrase"); tmp.push_back(password); cmd2.insert(cmd2.begin(), tmp.begin(), tmp.end()); } out.clear(); - gpg_execution_params params(cmd2); - //pxResult result; - params.out = &out; - params.code = &code; - params.result = &result; - if(!gpg_launcher(params, boost::posix_time::seconds(15))) - { - //boost::filesystem::remove(filename); + gpg_execution_params params2(cmd2); + params2.out = &out; + params2.code = &code; + params2.result = &result; + if (!gpg_launcher(params2, boost::posix_time::seconds(15))) return 0; - } - if(result == pxNotFound) - { - //boost::filesystem::remove(filename); + if (result == pxNotFound) return 0; - } } - if(result == pxSuccess) + if (result == pxSuccess) boost::filesystem::remove(filename); + } + mir_free(filename); } - mir_free(filename); } + break; } - break; } - } - else if(ack->type == ACKTYPE_MESSAGE) - { + else if (ack->type == ACKTYPE_MESSAGE) { extern std::list sent_msgs; - if(!sent_msgs.empty()) - { - if(ack->result == ACKRESULT_FAILED) - { + if (!sent_msgs.empty()) { + if (ack->result == ACKRESULT_FAILED) { std::list::iterator it = std::find(sent_msgs.begin(), sent_msgs.end(), ack->hProcess); - if(it != sent_msgs.end()) - HistoryLog(ack->hContact, db_event("Failed to send encrypted message", 0,0, 0)); + if (it != sent_msgs.end()) + HistoryLog(ack->hContact, db_event("Failed to send encrypted message", 0, 0, 0)); } - else if(ack->result == ACKRESULT_SUCCESS) - { + else if (ack->result == ACKRESULT_SUCCESS) { std::list::iterator it = std::find(sent_msgs.begin(), sent_msgs.end(), ack->hProcess); - if(it != sent_msgs.end()) + if (it != sent_msgs.end()) sent_msgs.erase(it); } } @@ -465,23 +424,22 @@ std::wstring encrypt_file(MCONTACT hContact, TCHAR *filename) string out; DWORD code; pxResult result; - MCONTACT hcnt = db_mc_isMeta(hContact)?metaGetMostOnline(hContact):hContact; + MCONTACT hcnt = db_mc_isMeta(hContact) ? metaGetMostOnline(hContact) : hContact; std::vector cmd; cmd.push_back(L"--batch"); cmd.push_back(L"--tes"); cmd.push_back(L"-r"); char *keyid = UniGetContactSettingUtf(hcnt, szGPGModuleName, "KeyID", ""); TCHAR *szKeyid = mir_a2t(keyid); - TCHAR *name = _tcsrchr(filename,_T('\\')); - if( !name ) + TCHAR *name = _tcsrchr(filename, _T('\\')); + if (!name) name = filename; else name++; - TCHAR *file_out = new TCHAR [mir_tstrlen(name) + mir_tstrlen(_T(".gpg")) + 1]; + TCHAR *file_out = new TCHAR[mir_tstrlen(name) + mir_tstrlen(_T(".gpg")) + 1]; mir_sntprintf(file_out, mir_tstrlen(name) + mir_tstrlen(_T(".gpg")) + 1, _T("%s.gpg"), name); cmd.push_back(szKeyid); - if(db_get_b(hcnt, szGPGModuleName, "bAlwaysTrust", 0)) - { + if (db_get_b(hcnt, szGPGModuleName, "bAlwaysTrust", 0)) { cmd.push_back(L"--trust-model"); cmd.push_back(L"always"); } @@ -500,20 +458,18 @@ std::wstring encrypt_file(MCONTACT hContact, TCHAR *filename) params.out = &out; params.code = &code; params.result = &result; - delete [] file_out; - if(!gpg_launcher(params, boost::posix_time::minutes(3))) + delete[] file_out; + if (!gpg_launcher(params, boost::posix_time::minutes(3))) return 0; - if(out.find("There is no assurance this key belongs to the named user") != string::npos) - { + if (out.find("There is no assurance this key belongs to the named user") != string::npos) { out.clear(); - if(MessageBox(0, TranslateT("We're trying to encrypt with untrusted key. Do you want to trust this key permanently?"), TranslateT("Warning"), MB_YESNO) == IDYES) - { + if (MessageBox(0, TranslateT("We're trying to encrypt with untrusted key. Do you want to trust this key permanently?"), TranslateT("Warning"), MB_YESNO) == IDYES) { db_set_b(hcnt, szGPGModuleName, "bAlwaysTrust", 1); std::vector tmp; tmp.push_back(L"--trust-model"); tmp.push_back(L"always"); cmd.insert(cmd.begin(), tmp.begin(), tmp.end()); - if(!gpg_launcher(params, boost::posix_time::minutes(3))) + if (!gpg_launcher(params, boost::posix_time::minutes(3))) return 0; } else @@ -525,73 +481,62 @@ std::wstring encrypt_file(MCONTACT hContact, TCHAR *filename) //from secureim partially INT_PTR onSendFile(WPARAM w, LPARAM l) { - CCSDATA *ccs=(CCSDATA*)l; - if(!bFileTransfers) + CCSDATA *ccs = (CCSDATA*)l; + if (!bFileTransfers) return Proto_ChainSend(w, ccs); - if(isContactSecured(ccs->hContact)) - { + if (isContactSecured(ccs->hContact)) { char *proto = GetContactProto(ccs->hContact); DWORD uin = db_get_dw(ccs->hContact, proto, "UIN", 0); bool cap_found = false, supported_proto = false; - if(uin) - { - if( ProtoServiceExists(proto, PS_ICQ_CHECKCAPABILITY)) { + if (uin) { + if (ProtoServiceExists(proto, PS_ICQ_CHECKCAPABILITY)) { supported_proto = true; - ICQ_CUSTOMCAP cap = {0}; - strncpy(cap.caps, "GPGFileTransfer",sizeof(cap.caps)); + ICQ_CUSTOMCAP cap = { 0 }; + strncpy(cap.caps, "GPGFileTransfer", sizeof(cap.caps)); if (CallProtoService(proto, PS_ICQ_CHECKCAPABILITY, (WPARAM)ccs->hContact, (LPARAM)&cap)) cap_found = true; } } - else - { + else { TCHAR *jid = UniGetContactSettingUtf(ccs->hContact, proto, "jid", _T("")); - if(jid[0]) - { + if (jid[0]) { extern list Accounts; list::iterator end = Accounts.end(); - for(list::iterator p = Accounts.begin(); p != end; p++) - { + for (list::iterator p = Accounts.begin(); p != end; p++) { TCHAR *caps = (*p)->getJabberInterface()->GetResourceFeatures(jid); - if(caps) - { + if (caps) { supported_proto = true; wstring str; - for(int i=0;;i++) - { + for (int i = 0;; i++) { str.push_back(caps[i]); - if(caps[i] == '\0') - if(caps[i+1] == '\0') + if (caps[i] == '\0') + if (caps[i + 1] == '\0') break; } mir_free(caps); - if(str.find(_T("GPG_Encrypted_FileTransfers:0")) != string::npos) + if (str.find(_T("GPG_Encrypted_FileTransfers:0")) != string::npos) cap_found = true; } } } mir_free(jid); } - if(supported_proto && !cap_found) - { - if(MessageBox(0, TranslateT("Capability to decrypt file not found on other side.\nRecipient may be unable to decrypt file(s).\nDo you want to encrypt file(s) anyway?"), TranslateT("File transfer warning"), MB_YESNO) == IDNO) + if (supported_proto && !cap_found) { + if (MessageBox(0, TranslateT("Capability to decrypt file not found on other side.\nRecipient may be unable to decrypt file(s).\nDo you want to encrypt file(s) anyway?"), TranslateT("File transfer warning"), MB_YESNO) == IDNO) return Proto_ChainSend(w, ccs); } - if(!supported_proto) - { - if(MessageBox(0, TranslateT("Unable to check encryption support on other side.\nRecipient may be unable to decrypt file(s).\nCurrently capability check supported only for ICQ and Jabber protocols.\nIt will work for any other proto if Miranda with New_GPG is used on other side.\nDo you want to encrypt file(s) anyway?"), TranslateT("File transfer warning"), MB_YESNO) == IDNO) + if (!supported_proto) { + if (MessageBox(0, TranslateT("Unable to check encryption support on other side.\nRecipient may be unable to decrypt file(s).\nCurrently capability check supported only for ICQ and Jabber protocols.\nIt will work for any other proto if Miranda with New_GPG is used on other side.\nDo you want to encrypt file(s) anyway?"), TranslateT("File transfer warning"), MB_YESNO) == IDNO) return Proto_ChainSend(w, ccs); } HistoryLog(ccs->hContact, db_event(Translate("encrypting file for transfer"), 0, 0, DBEF_SENT)); - if(StriStr(ccs->szProtoService, "/sendfilew")) - { - TCHAR **file=(TCHAR **)ccs->lParam; - for(int i = 0; file[i]; i++) - { - if(!boost::filesystem::exists(file[i])) + if (StriStr(ccs->szProtoService, "/sendfilew")) { + TCHAR **file = (TCHAR **)ccs->lParam; + for (int i = 0; file[i]; i++) { + if (!boost::filesystem::exists(file[i])) return 0; //we do not want to send file unencrypted (sometimes ack have wrong info) - if (_tcsstr(file[i],_T(".gpg"))) + if (_tcsstr(file[i], _T(".gpg"))) continue; std::wstring path_out = encrypt_file(ccs->hContact, file[i]); mir_free(file[i]); @@ -599,14 +544,12 @@ INT_PTR onSendFile(WPARAM w, LPARAM l) transfers.push_back(path_out); } } - else - { - char **file = (char**) ccs->lParam; - for(int i = 0; file[i]; i++) - { - if(!boost::filesystem::exists(file[i])) + else { + char **file = (char**)ccs->lParam; + for (int i = 0; file[i]; i++) { + if (!boost::filesystem::exists(file[i])) return 0; //we do not want to send file unencrypted (sometimes ack have wrong info) - if (strstr(file[i],".gpg")) + if (strstr(file[i], ".gpg")) continue; TCHAR *tmp = mir_utf8decodeT(file[i]); std::wstring path_out = encrypt_file(ccs->hContact, tmp); @@ -629,11 +572,11 @@ void HistoryLog(MCONTACT hContact, db_event evt) Event.szModule = szGPGModuleName; Event.eventType = evt.eventType; Event.flags = evt.flags; - if(!evt.timestamp) + if (!evt.timestamp) Event.timestamp = (DWORD)time(NULL); else Event.timestamp = evt.timestamp; - Event.cbBlob = (DWORD)mir_strlen((char*)evt.pBlob)+1; + Event.cbBlob = (DWORD)mir_strlen((char*)evt.pBlob) + 1; Event.pBlob = (PBYTE)_strdup((char*)evt.pBlob); db_event_add(hContact, &Event); } @@ -666,20 +609,17 @@ int GetJabberInterface(WPARAM, LPARAM) //get interface for all jabber accounts, Accounts.push_back(new JabberAccount); p = Accounts.begin(); (*p)->setAccountNumber(0); - for(int i = 0; i < count; i++) //get only jabber accounts from all accounts + for (int i = 0; i < count; i++) //get only jabber accounts from all accounts { IJabberInterface *JIftmp = getJabberApi(accounts[i]->szModuleName); int a = 0; - if(JIftmp) - { + if (JIftmp) { (*p)->setJabberInterface(JIftmp); - if(accounts[i]->tszAccountName) - { + if (accounts[i]->tszAccountName) { TCHAR* tmp = mir_tstrdup(accounts[i]->tszAccountName); (*p)->setAccountName(tmp); } - else - { + else { TCHAR *tmp = mir_a2t(accounts[i]->szModuleName); (*p)->setAccountName(tmp); } @@ -697,53 +637,44 @@ int GetJabberInterface(WPARAM, LPARAM) //get interface for all jabber accounts, static JABBER_HANDLER_FUNC SendHandler(IJabberInterface *ji, HXML node, void*) { HXML local_node = node; - for(int n = 0; n <= xmlGetChildCount(node); n++) - { - LPCTSTR str = xmlGetText(local_node); + for (int n = 0; n <= xmlGetChildCount(node); n++) { + LPCTSTR str = xmlGetText(local_node); LPCTSTR nodename = xmlGetName(local_node); LPCTSTR attr = xmlGetAttrValue(local_node, _T("to")); - if(attr) - { + if (attr) { MCONTACT hContact = ji->ContactFromJID(attr); - if(hContact) - if(!isContactSecured(hContact)) + if (hContact) + if (!isContactSecured(hContact)) return FALSE; } - if(str) - { - if(_tcsstr(str, _T("-----BEGIN PGP MESSAGE-----")) && _tcsstr(str, _T("-----END PGP MESSAGE-----"))) - { + if (str) { + if (_tcsstr(str, _T("-----BEGIN PGP MESSAGE-----")) && _tcsstr(str, _T("-----END PGP MESSAGE-----"))) { wstring data = str; xmlSetText(local_node, _T("This message is encrypted.")); wstring::size_type p1 = data.find(_T("-----BEGIN PGP MESSAGE-----")) + mir_tstrlen(_T("-----BEGIN PGP MESSAGE-----")); - while(data.find(_T("Version: "), p1) != wstring::npos) - { + while (data.find(_T("Version: "), p1) != wstring::npos) { p1 = data.find(_T("Version: "), p1); p1 = data.find(_T("\n"), p1); } - while(data.find(_T("Comment: "), p1) != wstring::npos) - { + while (data.find(_T("Comment: "), p1) != wstring::npos) { p1 = data.find(_T("Comment: "), p1); p1 = data.find(_T("\n"), p1); } - while(data.find(_T("Encoding: "), p1) != wstring::npos) - { + while (data.find(_T("Encoding: "), p1) != wstring::npos) { p1 = data.find(_T("Encoding: "), p1); p1 = data.find(_T("\n"), p1); } - p1+=3; + p1 += 3; wstring::size_type p2 = data.find(_T("-----END PGP MESSAGE-----")); - wstring data2 = data.substr(p1, p2-p1-2); + wstring data2 = data.substr(p1, p2 - p1 - 2); strip_line_term(data2); HXML encrypted_data = xmlAddChild(node, _T("x"), data2.c_str()); xmlAddAttr(encrypted_data, _T("xmlns"), _T("jabber:x:encrypted")); return FALSE; } } - if(bPresenceSigning && nodename) - { - if(_tcsstr(nodename, _T("status"))) - { + if (bPresenceSigning && nodename) { + if (_tcsstr(nodename, _T("status"))) { TCHAR *path_c = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); wstring path_out = path_c; wstring file = toUTF16(get_random(10)); @@ -752,12 +683,11 @@ static JABBER_HANDLER_FUNC SendHandler(IJabberInterface *ji, HXML node, void*) path_out += file; boost::filesystem::remove(path_out); wfstream f(path_out.c_str(), std::ios::out); - f<GetModuleName(); char setting[64]; - mir_snprintf(setting, sizeof(setting)-1,"%s_KeyID",proto); + mir_snprintf(setting, sizeof(setting) - 1, "%s_KeyID", proto); inkeyid = UniGetContactSettingUtf(NULL, szGPGModuleName, setting, ""); - if(!inkeyid[0]) - { + if (!inkeyid[0]) { mir_free(inkeyid); inkeyid = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", ""); } } TCHAR *pass = NULL; - if(inkeyid[0]) - { + if (inkeyid[0]) { string dbsetting = "szKey_"; dbsetting += inkeyid; dbsetting += "_Password"; pass = UniGetContactSettingUtf(NULL, szGPGModuleName, dbsetting.c_str(), _T("")); - if(pass[0] && bDebugLog) - debuglog< Accounts; - list ::iterator p = Accounts.begin(); - for(unsigned int i = 0; i < Accounts.size(); i++, p++) - { - if(!(*p)) + list ::iterator p = Accounts.begin(); + for (unsigned int m = 0; m < Accounts.size(); m++, p++) { + if (!(*p)) break; hContact = (*p)->getJabberInterface()->ContactFromJID(xmlGetAttrValue(node, _T("from"))); - if(hContact) - hcontact_data[hContact].key_in_prescense = out.substr(p1, p2-p1-1).c_str(); + if (hContact) + hcontact_data[hContact].key_in_prescense = out.substr(p1, p2 - p1 - 1).c_str(); } } } @@ -1023,30 +928,24 @@ static JABBER_HANDLER_FUNC MessageHandler(IJabberInterface*, HXML, void*) return FALSE; } - - - void AddHandlers() { extern list Accounts; list::iterator end = Accounts.end(); - for(list::iterator p = Accounts.begin(); p != end; p++) - { - if(!(*p)) + for (list::iterator p = Accounts.begin(); p != end; p++) { + if (!(*p)) break; - if((*p)->getSendHandler() == INVALID_HANDLE_VALUE) + if ((*p)->getSendHandler() == INVALID_HANDLE_VALUE) (*p)->setSendHandler((*p)->getJabberInterface()->AddSendHandler((JABBER_HANDLER_FUNC)SendHandler)); - if((*p)->getPrescenseHandler() == INVALID_HANDLE_VALUE) + if ((*p)->getPrescenseHandler() == INVALID_HANDLE_VALUE) (*p)->setPrescenseHandler((*p)->getJabberInterface()->AddPresenceHandler((JABBER_HANDLER_FUNC)PrescenseHandler)); -// if((*p)->getMessageHandler() == INVALID_HANDLE_VALUE) -// (*p)->setMessageHandler((*p)->getJabberInterface()->AddMessageHandler((JABBER_HANDLER_FUNC)MessageHandler, JABBER_MESSAGE_TYPE_ANY ,NULL,NULL)); - if(bAutoExchange) - { + // if((*p)->getMessageHandler() == INVALID_HANDLE_VALUE) + // (*p)->setMessageHandler((*p)->getJabberInterface()->AddMessageHandler((JABBER_HANDLER_FUNC)MessageHandler, JABBER_MESSAGE_TYPE_ANY ,NULL,NULL)); + if (bAutoExchange) { (*p)->getJabberInterface()->RegisterFeature(_T("GPG_Key_Auto_Exchange:0"), _T("Indicates that gpg installed and configured to public key auto exchange (currently implemented in new_gpg plugin for Miranda IM and Miranda NG)")); (*p)->getJabberInterface()->AddFeatures(_T("GPG_Key_Auto_Exchange:0\0\0")); } - if(bFileTransfers) - { + if (bFileTransfers) { (*p)->getJabberInterface()->RegisterFeature(_T("GPG_Encrypted_FileTransfers:0"), _T("Indicates that gpg installed and configured to encrypt files (currently implemented in new_gpg plugin for Miranda IM and Miranda NG)")); (*p)->getJabberInterface()->AddFeatures(_T("GPG_Encrypted_FileTransfers:0\0\0")); } @@ -1056,34 +955,30 @@ void AddHandlers() bool isContactSecured(MCONTACT hContact) { BYTE gpg_enc = db_get_b(hContact, szGPGModuleName, "GPGEncryption", 0); - if(!gpg_enc) - { - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (!gpg_enc) { + if (bDebugLog) + debuglog << std::string(time_str() + ": encryption is turned off for " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); return false; } - if(!db_mc_isMeta(hContact)) - { + if (!db_mc_isMeta(hContact)) { TCHAR *key = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", _T("")); - if(!key[0]) - { + if (!key[0]) { mir_free(key); - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (bDebugLog) + debuglog << std::string(time_str() + ": encryption is turned off for " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); return false; } mir_free(key); } - if(bDebugLog) - debuglog<pfnGetContactDisplayName(hContact, 0))); + if (bDebugLog) + debuglog << std::string(time_str() + ": encryption is turned on for " + toUTF8(pcli->pfnGetContactDisplayName(hContact, 0))); return true; } bool isContactHaveKey(MCONTACT hContact) { TCHAR *key = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", _T("")); - if(mir_tstrlen(key) > 0) - { + if (mir_tstrlen(key) > 0) { mir_free(key); return true; } @@ -1095,8 +990,7 @@ bool isGPGKeyExist() { TCHAR *id = UniGetContactSettingUtf(NULL, szGPGModuleName, "KeyID", _T("")); char *key = UniGetContactSettingUtf(NULL, szGPGModuleName, "GPGPubKey", ""); - if(id[0] && key[0]) - { + if (id[0] && key[0]) { mir_free(id); mir_free(key); return true; @@ -1112,10 +1006,9 @@ bool isGPGValid() tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szGpgBinPath", _T("")); boost::filesystem::path p(tmp); - if(boost::filesystem::exists(p) && boost::filesystem::is_regular_file(p)) + if (boost::filesystem::exists(p) && boost::filesystem::is_regular_file(p)) gpg_exists = true; - else - { + else { mir_free(tmp); tmp = NULL; TCHAR *path = (TCHAR*)mir_alloc(sizeof(TCHAR)*MAX_PATH); @@ -1131,8 +1024,7 @@ bool isGPGValid() mir_free(tmp); tmp = NULL; p = boost::filesystem::path(gpg_path); - if(boost::filesystem::exists(p) && boost::filesystem::is_regular_file(p)) - { + if (boost::filesystem::exists(p) && boost::filesystem::is_regular_file(p)) { gpg_exists = true; mir_tstrcpy(path, _T("GnuPG\\gpg.exe")); } @@ -1141,8 +1033,7 @@ bool isGPGValid() mir_free(path); } - if(gpg_exists) - { + if (gpg_exists) { db_set_ts(NULL, szGPGModuleName, "szGpgBinPath", tmp); mir_free(tmp); tmp = NULL; @@ -1159,22 +1050,21 @@ bool isGPGValid() gpg_launcher(params); gpg_valid = false; string::size_type p1 = out.find("(GnuPG) "); - if(p1 == string::npos) + if (p1 == string::npos) is_valid = false; } - if(tmp) - { + if (tmp) { mir_free(tmp); tmp = NULL; } -/* if(!gpg_exists) - { - wstring path_ = _wgetenv(_T("APPDATA")); - path_ += _T("\\GnuPG"); - tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", (TCHAR*)path_.c_str()); - } - if(tmp) - mir_free(tmp); */ + /* if(!gpg_exists) + { + wstring path_ = _wgetenv(_T("APPDATA")); + path_ += _T("\\GnuPG"); + tmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", (TCHAR*)path_.c_str()); + } + if(tmp) + mir_free(tmp); */ return is_valid && gpg_exists; } @@ -1189,18 +1079,18 @@ const bool StriStr(const char *str, const char *substr) CharUpperBuffA(str_up, (DWORD)mir_strlen(str_up)); CharUpperBuffA(substr_up, (DWORD)mir_strlen(substr_up)); - if(strstr (str_up, substr_up)) + if (strstr(str_up, substr_up)) i = true; mir_free(str_up); mir_free(substr_up); - + return i; } bool IsOnline(MCONTACT hContact) { - if(db_get_b(hContact, szGPGModuleName, "Status", 0) == ID_STATUS_OFFLINE) + if (db_get_b(hContact, szGPGModuleName, "Status", 0) == ID_STATUS_OFFLINE) return false; return true; } @@ -1208,13 +1098,15 @@ bool IsOnline(MCONTACT hContact) //from secureim #include -struct TFakeAckParams { - inline TFakeAckParams( HANDLE p1, MCONTACT p2, LONG p3, LPCSTR p4 ) : - hEvent( p1 ), - hContact( p2 ), - id( p3 ), - msg( p4 ) - {} +struct TFakeAckParams +{ + inline TFakeAckParams(HANDLE p1, MCONTACT p2, LONG p3, LPCSTR p4) : + hEvent(p1), + hContact(p2), + id(p3), + msg(p4) + { + } HANDLE hEvent; MCONTACT hContact; @@ -1224,32 +1116,33 @@ struct TFakeAckParams { __forceinline int SendBroadcast(MCONTACT hContact, int type, int result, HANDLE hProcess, LPARAM lParam) { - return ProtoBroadcastAck( GetContactProto(hContact), hContact, type, result, hProcess, lParam); + return ProtoBroadcastAck(GetContactProto(hContact), hContact, type, result, hProcess, lParam); } unsigned __stdcall sttFakeAck(void *param) { - TFakeAckParams *tParam = ( TFakeAckParams* )param; - WaitForSingleObject( tParam->hEvent, INFINITE ); + TFakeAckParams *tParam = (TFakeAckParams*)param; + WaitForSingleObject(tParam->hEvent, INFINITE); - Sleep( 100 ); - if ( tParam->msg == NULL ) - SendBroadcast(tParam->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, (HANDLE)tParam->id, 0 ); + Sleep(100); + if (tParam->msg == NULL) + SendBroadcast(tParam->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, (HANDLE)tParam->id, 0); else SendBroadcast(tParam->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, (HANDLE)tParam->id, LPARAM(tParam->msg)); - CloseHandle( tParam->hEvent ); + CloseHandle(tParam->hEvent); delete tParam; return 0; } -int returnNoError(MCONTACT hContact) { - HANDLE hEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); +int returnNoError(MCONTACT hContact) +{ + HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); unsigned int tID; - CloseHandle( (HANDLE) _beginthreadex(NULL, 0, sttFakeAck, new TFakeAckParams(hEvent,hContact,777,0), 0, &tID) ); - SetEvent( hEvent ); + CloseHandle((HANDLE)_beginthreadex(NULL, 0, sttFakeAck, new TFakeAckParams(hEvent, hContact, 777, 0), 0, &tID)); + SetEvent(hEvent); return 777; } // end from secureim @@ -1259,14 +1152,13 @@ int returnNoError(MCONTACT hContact) { string toUTF8(wstring str) { string ustr; - try{ - utf8::utf16to8(str.begin(), str.end(), back_inserter(ustr)); + try { + utf8::utf16to8(str.begin(), str.end(), back_inserter(ustr)); } - catch(const utf8::exception& e) - { - if(bDebugLog) - debuglog<> gen(rng, boost::uniform_int<>(0, (int)chars.length()-1)); - for(int i = 0; i < length; ++i) - data += chars[gen()]; + boost::variate_generator> gen(rng, boost::uniform_int<>(0, (int)chars.length() - 1)); + for (int i = 0; i < length; ++i) + data += chars[gen()]; return data; } void send_encrypted_msgs_thread(void *param) { - MCONTACT hContact = (MCONTACT)param; - while(true) - { + MCONTACT hContact = (MCONTACT)(DWORD_PTR)param; + while (true) { //char *key = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", ""); - while(!isContactSecured(hContact)) + while (!isContactSecured(hContact)) boost::this_thread::sleep(boost::posix_time::seconds(1)); - if(!hcontact_data[hContact].msgs_to_send.empty()) - { + if (!hcontact_data[hContact].msgs_to_send.empty()) { boost::this_thread::sleep(boost::posix_time::seconds(1)); list::iterator end = hcontact_data[hContact].msgs_to_send.end(); extern std::list sent_msgs; - for(list::iterator p = hcontact_data[hContact].msgs_to_send.begin(); p != end; ++p) - { + for (list::iterator p = hcontact_data[hContact].msgs_to_send.begin(); p != end; ++p) { sent_msgs.push_back((HANDLE)CallContactService(hContact, PSS_MESSAGE, 0, (LPARAM)p->c_str())); - HistoryLog(hContact, db_event((char*)p->c_str(),0,0, DBEF_SENT)); + HistoryLog(hContact, db_event((char*)p->c_str(), 0, 0, DBEF_SENT)); boost::this_thread::sleep(boost::posix_time::seconds(1)); } hcontact_data[hContact].msgs_to_send.clear(); @@ -1336,11 +1224,10 @@ string time_str() int handleEnum(const char *szSetting, LPARAM lParam) { - if(!*(bool*)lParam && szSetting[0] && StriStr(szSetting, "tabsrmm")) - { + if (!*(bool*)lParam && szSetting[0] && StriStr(szSetting, "tabsrmm")) { bool f = false, *found = (bool*)lParam; - f = !db_get_b(NULL, "PluginDisable", szSetting, 0); - if(f) + f = !db_get_b(NULL, "PluginDisable", szSetting, 0); + if (f) *found = f; } return 0; @@ -1348,12 +1235,12 @@ int handleEnum(const char *szSetting, LPARAM lParam) bool isTabsrmmUsed() { - DBCONTACTENUMSETTINGS enm = {0}; + DBCONTACTENUMSETTINGS enm = { 0 }; bool found = false; enm.lParam = (LPARAM)&found; enm.pfnEnumProc = handleEnum; enm.szModule = "PluginDisable"; - if(CallService(MS_DB_CONTACT_ENUMSETTINGS, 0, (LPARAM)&enm) == -1) + if (CallService(MS_DB_CONTACT_ENUMSETTINGS, 0, (LPARAM)&enm) == -1) return false; return found; @@ -1361,42 +1248,39 @@ bool isTabsrmmUsed() void ExportGpGKeysFunc(int type) { - TCHAR *p = GetFilePath(_T("Choose file to export keys"), _T("*"), _T("Any file"), true); - if(!p || !p[0]) - { - delete [] p; + TCHAR *p = GetFilePath(_T("Choose file to export keys"), _T("*"), _T("Any file"), true); + if (!p || !p[0]) { + delete[] p; //TODO: handle error return; } char *path = mir_t2a(p); - delete [] p; + delete[] p; std::ofstream file; file.open(path, std::ios::trunc | std::ios::out); mir_free(path); int exported_keys = 0; - if(!file.is_open()) + if (!file.is_open()) return; //TODO: handle error - if(!type || type == 2) { - for(MCONTACT hContact = db_find_first(); hContact; hContact = db_find_next(hContact)) { + if (!type || type == 2) { + for (MCONTACT hContact = db_find_first(); hContact; hContact = db_find_next(hContact)) { char *k = UniGetContactSettingUtf(hContact, szGPGModuleName, "GPGPubKey", ""); std::string key; - if(!k[0]) - { + if (!k[0]) { mir_free(k); continue; } - else - { + else { key = k; mir_free(k); } - + const char* proto = (const char*)GetContactProto(hContact); std::string id = "Comment: login "; - const char * uid = (const char*)CallProtoService(proto, PS_GETCAPS, (WPARAM)PFLAG_UNIQUEIDSETTING, 0); - DBVARIANT dbv = {0}; + const char * uid = (const char*)CallProtoService(proto, PS_GETCAPS, (WPARAM)PFLAG_UNIQUEIDSETTING, 0); + DBVARIANT dbv = { 0 }; db_get(0, proto, uid, &dbv); - switch(dbv.type) { + switch (dbv.type) { case DBVT_DELETED: continue; @@ -1430,7 +1314,7 @@ void ExportGpGKeysFunc(int type) case DBVT_UTF8: { char *tmp = mir_utf8decodeA(dbv.pszVal); - if(tmp[0]) + if (tmp[0]) id += tmp; mir_free(tmp); db_free(&dbv); @@ -1448,7 +1332,7 @@ void ExportGpGKeysFunc(int type) id += " contact_id "; memset(&dbv, 0, sizeof(dbv)); db_get(hContact, proto, uid, &dbv); - switch(dbv.type) { + switch (dbv.type) { case DBVT_DELETED: continue; case DBVT_BYTE: @@ -1469,7 +1353,7 @@ void ExportGpGKeysFunc(int type) { char _id[64]; mir_snprintf(_id, "%d", dbv.dVal); - id += _id; + id += _id; } break; case DBVT_ASCIIZ: @@ -1481,7 +1365,7 @@ void ExportGpGKeysFunc(int type) case DBVT_UTF8: { char *tmp = mir_utf8decodeA(dbv.pszVal); - if(tmp[0]) + if (tmp[0]) id += tmp; mir_free(tmp); db_free(&dbv); @@ -1497,19 +1381,18 @@ void ExportGpGKeysFunc(int type) break; } std::string::size_type p1 = key.find("-----BEGIN PGP PUBLIC KEY BLOCK-----"); - if(p1 == std::string::npos) + if (p1 == std::string::npos) continue; p1 += mir_strlen("-----BEGIN PGP PUBLIC KEY BLOCK-----"); - p1 ++; + p1++; id += '\n'; key.insert(p1, id); - file<szModuleName, PS_GETCAPS, (WPARAM)PFLAG_UNIQUEIDSETTING, 0); - DBVARIANT dbv = {0}; + const char * uid = (const char*)CallProtoService(accs[i]->szModuleName, PS_GETCAPS, (WPARAM)PFLAG_UNIQUEIDSETTING, 0); + DBVARIANT dbv = { 0 }; db_get(0, accs[i]->szModuleName, uid, &dbv); std::string id; - switch(dbv.type) - { + switch (dbv.type) { case DBVT_DELETED: continue; break; @@ -1609,7 +1492,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) char _id[64]; mir_snprintf(_id, "%d", dbv.bVal); id += _id; - if(id == login) + if (id == login) acc = accs[i]->szModuleName; } break; @@ -1618,7 +1501,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) char _id[64]; mir_snprintf(_id, "%d", dbv.wVal); id += _id; - if(id == login) + if (id == login) acc = accs[i]->szModuleName; } break; @@ -1627,7 +1510,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) char _id[64]; mir_snprintf(_id, "%d", dbv.dVal); id += _id; - if(id == login) + if (id == login) acc = accs[i]->szModuleName; } break; @@ -1635,18 +1518,18 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) { id += dbv.pszVal; db_free(&dbv); - if(id == login) + if (id == login) acc = accs[i]->szModuleName; } break; case DBVT_UTF8: { char *tmp = mir_utf8decodeA(dbv.pszVal); - if(tmp[0]) + if (tmp[0]) id += tmp; mir_free(tmp); db_free(&dbv); - if(id == login) + if (id == login) acc = accs[i]->szModuleName; } break; @@ -1660,16 +1543,14 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) break; } } - if(acc.length()) - { - const char * uid = (const char*)CallProtoService(acc.c_str(), PS_GETCAPS, (WPARAM)PFLAG_UNIQUEIDSETTING, 0); - for(MCONTACT hContact = db_find_first(acc.c_str()); hContact; hContact = db_find_next(hContact, acc.c_str())) { - DBVARIANT dbv = {0}; + if (acc.length()) { + const char * uid = (const char*)CallProtoService(acc.c_str(), PS_GETCAPS, (WPARAM)PFLAG_UNIQUEIDSETTING, 0); + for (MCONTACT hContact = db_find_first(acc.c_str()); hContact; hContact = db_find_next(hContact, acc.c_str())) { + DBVARIANT dbv = { 0 }; db_get(hContact, acc.c_str(), uid, &dbv); std::string id; bool found = false; - switch(dbv.type) - { + switch (dbv.type) { case DBVT_DELETED: continue; break; @@ -1678,7 +1559,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) char _id[64]; mir_snprintf(_id, "%d", dbv.bVal); id += _id; - if(id == contact_id) + if (id == contact_id) found = true; } break; @@ -1687,7 +1568,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) char _id[64]; mir_snprintf(_id, "%d", dbv.wVal); id += _id; - if(id == contact_id) + if (id == contact_id) found = true; } break; @@ -1696,7 +1577,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) char _id[64]; mir_snprintf(_id, "%d", dbv.dVal); id += _id; - if(id == contact_id) + if (id == contact_id) found = true; } break; @@ -1704,18 +1585,18 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) { id += dbv.pszVal; db_free(&dbv); - if(id == contact_id) + if (id == contact_id) found = true; } break; case DBVT_UTF8: { char *tmp = mir_utf8decodeA(dbv.pszVal); - if(tmp[0]) + if (tmp[0]) id += tmp; mir_free(tmp); db_free(&dbv); - if(id == contact_id) + if (id == contact_id) found = true; } break; @@ -1728,8 +1609,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) db_free(&dbv); break; } - if(found) - { + if (found) { wstring path; std::vector cmd; TCHAR *ptmp; @@ -1744,7 +1624,7 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) path += rand; boost::filesystem::remove(path); wfstream f(path, std::ios::out); - f< output.find("<", s)) + else if (s2 > output.find("<", s)) s2 = output.find("<", s); - if(s2 != string::npos) - { - tmp2 = (char*)mir_alloc((output.substr(s,s2-s-1).length()+1) * sizeof(char)); - mir_strcpy(tmp2, output.substr(s,s2-s-1).c_str()); + if (s2 != string::npos) { + tmp2 = (char*)mir_alloc((output.substr(s, s2 - s - 1).length() + 1) * sizeof(char)); + mir_strcpy(tmp2, output.substr(s, s2 - s - 1).c_str()); mir_utf8decode(tmp2, 0); - if(hContact) - { - db_set_s(hContact, szGPGModuleName, "KeyMainName", output.substr(s,s2-s-1).c_str()); + if (hContact) { + db_set_s(hContact, szGPGModuleName, "KeyMainName", output.substr(s, s2 - s - 1).c_str()); } mir_free(tmp2); - if((s = output.find(")", s2)) == string::npos) + if ((s = output.find(")", s2)) == string::npos) s = output.find(">", s2); - else if(s > output.find(">", s2)) + else if (s > output.find(">", s2)) s = output.find(">", s2); s2++; - if(output[s] == ')') - { - tmp2 = (char*)mir_alloc((output.substr(s2,s-s2).length()+1) * sizeof(char)); - mir_strcpy(tmp2, output.substr(s2,s-s2).c_str()); + if (output[s] == ')') { + tmp2 = (char*)mir_alloc((output.substr(s2, s - s2).length() + 1) * sizeof(char)); + mir_strcpy(tmp2, output.substr(s2, s - s2).c_str()); mir_utf8decode(tmp2, 0); - if(hContact) - db_set_s(hContact, szGPGModuleName, "KeyComment", output.substr(s2,s-s2).c_str()); + if (hContact) + db_set_s(hContact, szGPGModuleName, "KeyComment", output.substr(s2, s - s2).c_str()); mir_free(tmp2); - s+=3; + s += 3; s2 = output.find(">", s); - tmp2 = (char*)mir_alloc((output.substr(s,s2-s).length()+1) * sizeof(char)); - mir_strcpy(tmp2, output.substr(s,s2-s).c_str()); + tmp2 = (char*)mir_alloc((output.substr(s, s2 - s).length() + 1) * sizeof(char)); + mir_strcpy(tmp2, output.substr(s, s2 - s).c_str()); mir_utf8decode(tmp2, 0); - if(hContact) - db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s,s2-s).c_str()); + if (hContact) + db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s, s2 - s).c_str()); mir_free(tmp2); } - else - { - tmp2 = (char*)mir_alloc((output.substr(s2,s-s2).length()+1) * sizeof(char)); - mir_strcpy(tmp2, output.substr(s2,s-s2).c_str()); + else { + tmp2 = (char*)mir_alloc((output.substr(s2, s - s2).length() + 1) * sizeof(char)); + mir_strcpy(tmp2, output.substr(s2, s - s2).c_str()); mir_utf8decode(tmp2, 0); - if(hContact) - db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2,s-s2).c_str()); + if (hContact) + db_set_s(hContact, szGPGModuleName, "KeyMainEmail", output.substr(s2, s - s2).c_str()); mir_free(tmp2); } } @@ -1840,22 +1714,21 @@ INT_PTR ImportGpGKeys(WPARAM, LPARAM) } key.clear(); } - if(strstr(line, "-----END PGP PRIVATE KEY BLOCK-----")) - { + if (strstr(line, "-----END PGP PRIVATE KEY BLOCK-----")) { std::vector cmd; - TCHAR tmp2[MAX_PATH] = {0}; + TCHAR tmp2[MAX_PATH] = { 0 }; TCHAR *ptmp; string output; DWORD exitcode; { ptmp = UniGetContactSettingUtf(NULL, szGPGModuleName, "szHomePath", _T("")); - _tcsncpy(tmp2, ptmp, MAX_PATH-1); + _tcsncpy(tmp2, ptmp, MAX_PATH - 1); mir_free(ptmp); mir_tstrncat(tmp2, _T("\\"), _countof(tmp2) - mir_tstrlen(tmp2)); mir_tstrncat(tmp2, _T("temporary_exported.asc"), _countof(tmp2) - mir_tstrlen(tmp2)); boost::filesystem::remove(tmp2); wfstream f(tmp2, std::ios::out); - f< cmd; string output; DWORD exitcode; @@ -2076,17 +1942,16 @@ static INT_PTR CALLBACK DlgProcChangePasswd(HWND hwndDlg, UINT msg, WPARAM wPara params.code = &exitcode; params.result = &result; boost::thread gpg_thread(boost::bind(&pxEexcute_passwd_change_thread, ¶ms)); - if(!gpg_thread.timed_join(boost::posix_time::minutes(10))) - { + if (!gpg_thread.timed_join(boost::posix_time::minutes(10))) { gpg_thread.~thread(); - if(params.child) + if (params.child) boost::process::terminate(*(params.child)); - if(bDebugLog) - debuglog<path())) - { - if((i->path().filename().generic_string().length() == 10 && (i->path().filename().generic_string().find(".") == std::string::npos)) || + for (directory_iterator i = directory_iterator(p), end = directory_iterator(); i != end; ++i) { + if (boost::filesystem::is_regular_file(i->path())) { + if ((i->path().filename().generic_string().length() == 10 && (i->path().filename().generic_string().find(".") == std::string::npos)) || i->path().extension() == ".sig" || i->path().extension() == ".asc" || i->path().extension() == ".status") boost::filesystem::remove(i->path()); } } } -} \ No newline at end of file +} -- cgit v1.2.3