summaryrefslogtreecommitdiff
path: root/Win/controller.cpp
blob: 8d240f5ba9c2f7fb4ce0ecacaf57c3310c5d9179 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 *   The contents of this file are subject to the Mozilla Public License Version
 *   1.1 (the "License"); you may not use this file except in compliance with
 *   the License. You may obtain a copy of the License at
 *   http://www.mozilla.org/MPL/
 *
 *   Software distributed under the License is distributed on an "AS IS" basis,
 *   WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 *   for the specific language governing rights and limitations under the
 *   License.
 *
 *   Copyright 2009-2011, Red Hat Inc.
 *   Based on mozilla.org's scriptable plugin example
 *
 *   The Original Code is mozilla.org code.
 *
 *   The Initial Developer of the Original Code is
 *   Netscape Communications Corporation.
 *   Portions created by the Initial Developer are Copyright (C) 1998
 *   the Initial Developer. All Rights Reserved.
 *
 *   Contributor(s):
 *   Uri Lublin
 *   Martin Stransky
 *   Peter Hatina
 *
 *   Alternatively, the contents of this file may be used under the terms of
 *   either the GNU General Public License Version 2 or later (the "GPL"), or
 *   the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 *   in which case the provisions of the GPL or the LGPL are applicable instead
 *   of those above. If you wish to allow use of your version of this file only
 *   under the terms of either the GPL or the LGPL, and not to allow others to
 *   use your version of this file under the terms of the MPL, indicate your
 *   decision by deleting the provisions above and replace them with the notice
 *   and other provisions required by the GPL or the LGPL. If you do not delete
 *   the provisions above, a recipient may use your version of this file under
 *   the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include <glib.h>

#include "controller.h"

SpiceController::SpiceController()
{
}

SpiceController::~SpiceController()
{
    g_debug(G_STRFUNC);
    Disconnect();
}

int SpiceController::Connect()
{
    if (m_hClientProcess) {
        TerminateProcess(m_hClientProcess, 0);
        CloseHandle(m_hClientProcess);
        m_hClientProcess = NULL;
    }
    if (m_hClientPipe) {
        CloseHandle(m_hClientPipe);
        m_hClientPipe = NULL;
    }
    if (m_hEventThread) {
        CloseHandle(m_hEventThread);
        m_hEventThread = NULL;
    }
    return -1;
}

int SpiceController::Connect(const int nRetries)
{
    return -1;
}

void SpiceController::Cleanup()
{
    if (m_hClientProcess) {
        TerminateProcess(m_hClientProcess, 0);
        CloseHandle(m_hClientProcess);
        m_hClientProcess = NULL;
    }
    if (m_hClientPipe) {
        CloseHandle(m_hClientPipe);
        m_hClientPipe = NULL;
    }
    if (m_hEventThread) {
        CloseHandle(m_hEventThread);
        m_hEventThread = NULL;
    }
}

void SpiceController::Disconnect()
{
    if (m_hClientProcess == NULL) {
        return SPICEX_ERROR_CLIENT_PROCESS_NOT_CONNECTED;
    }

    this->Cleanup();
}

uint32_t SpiceController::Write(const void *lpBuffer, uint32_t nBytesToWrite)
{
    bool res = true;
    DWORD written;
    size_t size;

    EnterCriticalSection(&m_WriteLock);
    if (!GetOverlappedResult(m_hClientPipe, &m_OverlappedWrite, &written, FALSE)) {
        LeaveCriticalSection(&m_WriteLock);
        return false;
    }

    m_WritePending = false;
    m_WriteStart = m_WriteBuffer + (m_WriteStart - m_WriteBuffer + written) % PIPE_BUF_SIZE;
    if (m_WriteStart <= m_WriteEnd) {
        size = m_WriteEnd - m_WriteStart;
    } else {
        size = m_WriteBuffer + PIPE_BUF_SIZE - m_WriteStart;
    }
    if (size) {
        if (WriteFile(m_hClientPipe, m_WriteStart, (DWORD)size, NULL, &m_OverlappedWrite) ||
                                                          GetLastError() == ERROR_IO_PENDING) {
            m_WritePending = true;
        } else {
            res = false;
        }
    }
    LeaveCriticalSection(&m_WriteLock);
    return res;
}

int SpiceController::TranslateRC(int nRC)
{
    switch (nRC)
    {
    case SPICEC_ERROR_CODE_SUCCESS:
        return 0;

    case SPICEC_ERROR_CODE_GETHOSTBYNAME_FAILED:
        return RDP_ERROR_CODE_HOST_NOT_FOUND;

    case SPICEC_ERROR_CODE_CONNECT_FAILED:
        return RDP_ERROR_CODE_WINSOCK_CONNECT_FAILED;

    case SPICEC_ERROR_CODE_ERROR:
    case SPICEC_ERROR_CODE_SOCKET_FAILED:
        return RDP_ERROR_CODE_INTERNAL_ERROR;

    case SPICEC_ERROR_CODE_RECV_FAILED:
        return RDP_ERROR_RECV_WINSOCK_FAILED;

    case SPICEC_ERROR_CODE_SEND_FAILED:
        return RDP_ERROR_SEND_WINSOCK_FAILED;

    case SPICEC_ERROR_CODE_NOT_ENOUGH_MEMORY:
        return RDP_ERROR_CODE_OUT_OF_MEMORY;

    case SPICEC_ERROR_CODE_AGENT_TIMEOUT:
        return RDP_ERROR_CODE_TIMEOUT;

    case SPICEC_ERROR_CODE_AGENT_ERROR:
        return RDP_ERROR_CODE_INTERNAL_ERROR;

    default:
        return RDP_ERROR_CODE_INTERNAL_ERROR;
    }
}

bool SpiceController::InitSocket(void)
{
    return false;
}

void SpiceController::StopClient()
{
}

bool SpiceController::StartClient(void)
{
    if (m_hClientProcess != NULL) {
        return SPICEX_ERROR_CLIENT_PROCESS_ALREADY_CONNECTED;
    }
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&m_pi, sizeof(m_pi));

    // FIXME: do we need the GetModuleXXX calls?
    // we assume the Spice client binary is located in the same dir as the
    // ActiveX dll
    if (hModule = GetModuleHandle(SPICE_X_DLL)) {
        if (dwRetVal = GetModuleFileName(hModule, lpCommandLine, MAX_PATH)) {
            // locate the 1st char of the ActiveX name (past the last '\')
            lpProcName = (wcsrchr(lpCommandLine, L'\\') + 1);
            // zero it so we can append the red client name
            if (lpProcName) {
                lpProcName[0] = 0;
            }
        }
    }

    lret = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\spice-space.org\\spicex", 0, KEY_READ, &hkey);
    if (lret == ERROR_SUCCESS) {
        DWORD dwType = REG_SZ;
        DWORD dwSize = sizeof(lpCommandLine);
        lret = RegQueryValueEx(hkey, L"client", NULL, &dwType, (LPBYTE)lpCommandLine, &dwSize);
        RegCloseKey(hkey);
    }

    if (lret != ERROR_SUCCESS) {
        StringCchPrintf(lpCommandLine, CMDLINE_LENGTH, L"%s%s --controller",
                        lpCommandLine, RED_CLIENT_FILE_NAME);
    }

    DBG(0, "Running spicec (%S)", lpCommandLine);

    if (!CreateProcess(NULL, lpCommandLine,	NULL, NULL, FALSE, 0, NULL, NULL, &si, &m_pi)) {
        DWORD err = GetLastError();
        LOG_ERROR("Failed to run spicec (%S) -- %lu", lpCommandLine, err);
        return MAKE_HRESULT(1, FACILITY_CREATE_RED_PROCESS, err);
    }
    LOG_INFO("spicec pid %lu", ::GetProcessId(m_pi.hProcess));
    m_hClientProcess = m_pi.hProcess;
    WaitForInputIdle(m_hClientProcess, INFINITE);

    DBG(0, "connecting to spice client's pipe");
    wchar_t lpszClientPipeName[RED_CLIENT_PIPE_NAME_MAX_LEN];
    StringCchPrintf(lpszClientPipeName, RED_CLIENT_PIPE_NAME_MAX_LEN, RED_CLIENT_PIPE_NAME,
                    m_pi.dwProcessId);
    for (int retry = 0; retry < 5; retry++) {
        m_hClientPipe = CreateFile(lpszClientPipeName, GENERIC_READ |  GENERIC_WRITE, 0, NULL,
                                   OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
                                   FILE_FLAG_OVERLAPPED, NULL);
        if (m_hClientPipe != INVALID_HANDLE_VALUE) {
            break;
        }
        Sleep(1000);
    }

    // Verify the named-pipe-server owner is the current user.
    // Do it here so upon failure use next condition cleanup code.
    if (m_hClientPipe != INVALID_HANDLE_VALUE) {
        if (!is_same_user(m_hClientPipe)) {
            LOG_ERROR("Closing pipe to spicec -- it is not safe");
            CloseHandle(m_hClientPipe);
            m_hClientPipe = INVALID_HANDLE_VALUE;
        }
    }

    if (m_hClientPipe == INVALID_HANDLE_VALUE) {
        LOG_ERROR("failed to connect to spice client pipe");
        TerminateProcess(m_hClientProcess, 0);
        CloseHandle(m_hClientProcess);
        m_hClientProcess = NULL;
        return MAKE_HRESULT(1, FACILITY_CREATE_RED_PIPE, GetLastError());
    }

    m_hEventThread = CreateThread(NULL, 0, event_thread, this, 0, NULL);
    if (m_hEventThread == NULL) {
        LOG_ERROR("failed to create event thread");
        cleanup();
        return MAKE_HRESULT(1, FACILITY_CREATE_RED_PIPE, GetLastError());
    }

    return false;
}

std::string SpiceController::WriteCAFile(const std::string &ca_cert)
{
    USES_CONVERSION;
    SECURITY_ATTRIBUTES sa;
    SECURITY_DESCRIPTOR sd;
    PACL dacl = NULL;


    // Allow access only to current user
    if (DWORD err = get_security_attributes(&sa, &sd, &dacl))
    {
        warning("failed to get security attributes: %d", HRESULT_FROM_WIN32(err));
        return std::string();
    }

    WCHAR szCAFileName[MAX_PATH];

    if (::ExpandEnvironmentStrings(L"%TEMP%\\truststore.pem",
            szCAFileName, sizeof(szCAFileName)) == 0)
    {
        LocalFree(dacl);
        warning("failed to expand %TEMP%\\truststore.pem: %d", HRESULT_FROM_WIN32(::GetLastError()));
        return std::string();
    }

    HANDLE hTrustStore = ::CreateFile(szCAFileName, GENERIC_WRITE,
                                      0, NULL, CREATE_ALWAYS, 0, &sa);
    LocalFree(dacl);
    if (hTrustStore == INVALID_HANDLE_VALUE)
    {
        return HRESULT_FROM_WIN32(::GetLastError());
        warning("failed to create %s: %d", szCAFileName, HRESULT_FROM_WIN32(::GetLastError()));
        return std::string();
    }

    std::string truststore = W2A(ca_cert.c_str());
    DWORD dwBytesWritten;

    if ((::WriteFile(hTrustStore, truststore.c_str(),
            DWORD(truststore.length() + 1), &dwBytesWritten, NULL) == FALSE) ||
        (dwBytesWritten != (truststore.length() + 1)))
    {
        ::CloseHandle(hTrustStore);
        warning("failed to write to %s: %d", szCAFileName, HRESULT_FROM_WIN32(::GetLastError()));
        return std::string();
    }

    ::CloseHandle(hTrustStore);

    return std::string(szCAFileName);
}