~psiphon-inc/psiphon/trunk

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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
 * Copyright (c) 2010, Psiphon Inc.
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "stdafx.h"
#include "psiclient.h"
#include "sshtunnel.h"
#include "locallistener.h"
#include "libssh2.h"
#include "sshsession.h"
#include "config.h"
#include "embeddedconfigvalues.h"

#include <ws2tcpip.h>
#include <winsock2.h>

struct Connection;
DWORD WINAPI listen(LPVOID pData);
void process_connection(Connection connection, bool readFromClient);

SSHTunnel::SSHTunnel(void)
{
    m_listenThread = 0;
    m_shuttingDown = false;
}

SSHTunnel::~SSHTunnel(void)
{
    TearDown();
}

void SSHTunnel::StartUp(void)
{
    TearDown();

    m_shuttingDown = false;

    int rc = libssh2_init(0);
    if (rc)
    {
        my_print(false, _T("libssh2 initialization failed: %d"), rc);
        return;
    }

    // Start the listener
    m_listenThread = CreateThread(NULL, 0, listen, (LPVOID)this, 0, NULL);

    // TODO: should wait for listener to start before changing proxy settings and launching IE?

    // Configure the proxy settings
    if (!m_proxySettings.Configure())
    {
        my_print(false, _T("error configuring proxy settings"));
    }
    else
    {
        // Start IE
        m_webBrowser.Open();

        my_print(false, _T("PsiphonX started"));
    }
}

void SSHTunnel::ShutDown(void)
{
    TearDown();

    my_print(false, _T("PsiphonX stopped"));
}

bool SSHTunnel::ShuttingDown(void)
{
    return m_shuttingDown;
}

void SSHTunnel::TearDown(void)
{
    // Stop IE
    m_webBrowser.Close();

    // Reset the proxy settings
    m_proxySettings.Revert();

    // Stop the listener by setting close flag
    // TODO: signal event?

    m_shuttingDown = true;

    if (m_listenThread)
    {
        WaitForSingleObject(m_listenThread, INFINITE);

        m_listenThread = 0;
    }

    m_shuttingDown = false;

    libssh2_exit();
}

struct Connection
{
    int socket;
    LIBSSH2_CHANNEL *channel;
};
typedef vector<Connection>::const_iterator connection_iter;

DWORD WINAPI listen(LPVOID pData)
{
    SSHTunnel* pTunnel = (SSHTunnel*)pData;
    LocalListener listener(LOCAL_LISTEN_IP, LOCAL_LISTEN_PORT);
    ssh_credentials credentials = {
        UnpadValue(SSH_SERVER_HOST),
        atoi(UnpadValue(SSH_SERVER_PORT_NUMBER).c_str()),
        UnpadValue(SSH_USER_NAME),
        UnpadValue(SSH_USER_PASSWORD),
        UnpadValue(SSH_SERVER_FINGERPRINT)};
    SSHSession ssh_session(credentials);
    vector<Connection> connections;
    bool bTearDownSession = false;

    WSADATA wsadata;
    int rc = WSAStartup(MAKEWORD(2,0), &wsadata);

    if (rc)
    {
        my_print(false, _T("WSAStartup failed: %d"), rc);
        return 0;
    }
 
    try
    {
        // initialize local listener

        listener.Initialize();

        while (true)
        {
            if (pTunnel->ShuttingDown())
            {
                // The main thread is signalling us to shut down
                throw 0;
            }

            // to recover from major session errors, reset everything

            if (bTearDownSession)
            {
                my_print(false, _T("reset session"));

                // destroy an existing session (and connections)
                for (connection_iter conn = connections.begin(); conn != connections.end(); ++conn)
                {
                    libssh2_channel_free(conn->channel); 
                    closesocket(conn->socket);
                }
                connections.clear();

                ssh_session.TearDown();

                bTearDownSession = false;
            }

            fd_set fds;
            FD_ZERO(&fds);

            // - select on the listen socket
            FD_SET(listener.ListenSocket(), &fds);

            // - select on all connection sockets to see if there's anything to read from the clients
            for (connection_iter conn = connections.begin(); conn != connections.end(); ++conn)
            {
                FD_SET(conn->socket, &fds);
            }

            struct timeval tv;
            tv.tv_sec = 0;
            tv.tv_usec = 1;
            int rc = select(0, &fds, NULL, NULL, &tv);
            if (SOCKET_ERROR == rc)
            {
                my_print(false, _T("select error: %d"), WSAGetLastError());
                throw 0;
            }

            // accept connections and add to connection list

            if (FD_ISSET(listener.ListenSocket(), &fds))
            {
                int forwardSocket = -1;
                listener.Accept(forwardSocket);

                // initialize ssh connection/session on demand

                if (!ssh_session.IsConnected() && !ssh_session.Connect())
                {
                    my_print(false, _T("ssh connection failed"));

                    // wait for more work (or shutdown signal) before retrying to connect
                    continue;
                }

                // create channel for this connection

                // in libssh2, session needs to be in blocking mode for this operation
                libssh2_session_set_blocking(ssh_session.GetSession(), 1);

                // TODO: do we need a new channel each time?
                LIBSSH2_CHANNEL *channel = libssh2_channel_direct_tcpip_ex(
                                    ssh_session.GetSession(), 
                                    HTTP_PROXY_HOST,
                                    atoi(UnpadValue(HTTP_PROXY_PORT_NUMBER).c_str()),
                                    LOCAL_LISTEN_IP,
                                    LOCAL_LISTEN_PORT);

                if (!channel)
                {
                    // after "Could not open the direct-tcpip channel" the session seems broken,
                    // so force a complete reset
                    bTearDownSession = true;

                    my_print(false, _T("Could not open the direct-tcpip channel"));
                            //"(Note that this can be a problem at the server!"
                            //" Please review the server logs.)");
                    
                    // go to the top of the loop where the session will be restarted
                    continue;
                }
 
                // Must use non-blocking IO hereafter due to the current libssh2 API
                libssh2_session_set_blocking(ssh_session.GetSession(), 0);

                // add this connection to list for processing

                Connection connection = {forwardSocket, channel};
                connections.push_back(connection);
            }

            // process each connection:
            // - the check for browser-side reads has already been done by select above
            // - also, check for ssh-side reads

            connection_iter conn = connections.begin();
            while (conn != connections.end())
            {
                // try block for errors related to this connection: will reset connection "conn" only

                try
                {
                    process_connection(*conn, 0 != FD_ISSET(conn->socket, &fds));
                    ++conn;
                }
                catch (...)
                {
                    // connection was closed or error; shutdown and remove from list

                    my_print(true, _T("closing connection"));

                    libssh2_channel_free(conn->channel);
 
                    closesocket(conn->socket);

                    conn = connections.erase(conn);
                }
            }
        }
    }
    catch (...)
    {
    }
    // TODO: Don't throw 0.  Throw and catch a std::exception.
    // Maybe put the error message in the exception.

    // close all connections
    
    for (connection_iter conn = connections.begin(); conn != connections.end(); ++conn)
    {
        libssh2_channel_free(conn->channel); 
        closesocket(conn->socket);
    }
    connections.clear();

    return 0;
}

void process_connection(Connection connection, bool readFromClient)
{
    ssize_t len, wr;
    char buf[16384];

    if (readFromClient)
    {
        len = recv(connection.socket, buf, sizeof(buf), 0);
        if (len < 0)
        {
            // errno=11 corresponds to "resource is not available" which apparently means
            // the peer closed the the socket seems to be reported a lot; perhaps IE is abandoning
            // the request due to delays.  for now, since IE seems to retry, only showing this
            // error in debug
            my_print((errno == 11), _T("read error: %s: %d"), _tcserror(errno), WSAGetLastError());
            throw 0;
        }
        else if (0 == len)
        {
            // TODO: correctly detect client shutdown?
            //my_print(_T("the client at %hs:%d disconnected"), shost, sport);
            my_print(true, _T("the client disconnected"));
            throw 0;
        }
        else
        {
            wr = 0;
            while (wr < len)
            {
                int i = libssh2_channel_write(connection.channel, buf, len);
                if (i == LIBSSH2_ERROR_EAGAIN)
                {
                    // TODO: wait?
                    continue;
                }
                else if (i < 0)
                {
                    my_print(false, _T("libssh2_channel_write error: %d"), i);
                    throw 0;
                }
                else if (i == 0)
                {
                    // TODO: need this condition?
                    break;
                }
                wr += i;
            }
        }
    }
    while (true)
    {
        len = libssh2_channel_read(connection.channel, buf, sizeof(buf));

        if (LIBSSH2_ERROR_EAGAIN == len)
        {
            break;
        }
        else if (len < 0)
        {
            my_print(false, _T("libssh2_channel_read error: %d"), len);
            throw 0;
        }
        wr = 0;
        while (wr < len)
        {
            int i = send(connection.socket, buf + wr, len - wr, 0);
            if (i <= 0)
            {
                // see comment above about errno=11
                my_print((errno == 11), _T("write error: %s: %d"), _tcserror(errno), WSAGetLastError());
                throw 0;
            }
            wr += i;
        }
        if (libssh2_channel_eof(connection.channel))
        {
            my_print(true,
                     _T("the server at %hs:%hs disconnected"),
                     HTTP_PROXY_HOST,
                     UnpadValue(HTTP_PROXY_PORT_NUMBER).c_str());
            throw 0;
        }
    }
}