aboutsummaryrefslogtreecommitdiffstats
path: root/proxy/proxy_common.c
blob: c5762dc59ee77cc90f1cb2498e1f363f253c7f6d (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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/* Copyright (C) 2007-2008 The Android Open Source Project
**
** This software is licensed under the terms of the GNU General Public
** License version 2, as published by the Free Software Foundation, and
** may be copied, distributed, and modified under those terms.
**
** 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.
*/
#include "proxy_int.h"
#include "sockets.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "vl.h"

int  proxy_log = 0;

void
proxy_LOG(const char*  fmt, ...)
{
    va_list  args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

void
proxy_set_verbose(int  mode)
{
    proxy_log = mode;
}

/** Global connection list
 **/

static ProxyConnection  s_connections[1];

static void
hex_dump( void*   base, int  size, const char*  prefix )
{
    uint8_t*   p         = (uint8_t*)base;
    const int  max_count = 16;

    while (size > 0) {
        int          count = size > max_count ? max_count : size;
        int          n;
        const char*  space = prefix;

        for (n = 0; n < count; n++) {
            proxy_LOG( "%s%02x", space, p[n] );
            space = " ";
        }

        proxy_LOG( "%-*s", 4 + 3*(max_count-n), "" );

        for (n = 0; n < count; n++) {
            int  c = p[n];

            if (c < 32 || c > 127)
                c = '.';
            proxy_LOG( "%c", c );
        }
        proxy_LOG( "\n" );
        size -= count;
        p    += count;
    }
}


void
proxy_connection_init( ProxyConnection*     conn,
                       int                  socket,
                       struct sockaddr_in*  address,
                       ProxyService*        service )
{
    conn->socket    = socket;
    conn->address   = address[0];
    conn->service   = service;
    conn->next      = NULL;

    {
        uint32_t  ip   = ntohl(address->sin_addr.s_addr);
        uint16_t  port = ntohs(address->sin_port);
        int       type = socket_get_type(socket);

        snprintf( conn->name, sizeof(conn->name),
                  "%s:%d.%d.%d.%d:%d(%d)",
                  (type == SOCK_STREAM) ? "tcp" : "udp",
                  (ip >> 24) & 255, (ip >> 16) & 255,
                  (ip >> 8)  & 255, ip & 255, port,
                  socket );

        /* just in case */
        conn->name[sizeof(conn->name)-1] = 0;
    }

    conn->buffer_pos = 0;
    conn->buffer_len = 0;
    conn->buffer     = conn->buffer0;
}

void
proxy_connection_done( ProxyConnection*  conn )
{
    if (conn->buffer != conn->buffer0) {
        qemu_free(conn->buffer);
    }
}


int
proxy_connection_send( ProxyConnection*  conn )
{
    int  result = -1;
    int  fd     = conn->socket;
    int  avail  = conn->buffer_len - conn->buffer_pos;

    if (proxy_log) {
        PROXY_LOG("%s: sending %d bytes:\n", conn->name, avail );
        hex_dump( conn->buffer + conn->buffer_pos, avail, ">> " );
    }

    while (avail > 0) {
        int  n = send(fd, conn->buffer + conn->buffer_pos, avail, 0);
        if (n < 0) {
            if (errno == EINTR)
                continue;
            if (errno == EWOULDBLOCK || errno == EAGAIN)
                return 0;
            PROXY_LOG("%s: error: %s\n", conn->name, strerror(errno));
            return -1;
        }
        conn->buffer_pos += n;
        avail            -= n;
    }
    return 1;
}

int
proxy_connection_receive( ProxyConnection*  conn )
{
    int  result = -1;
    int  fd     = conn->socket;
    int  avail  = conn->buffer_len - conn->buffer_pos;

    while (avail > 0) {
        int  n = recv(fd, conn->buffer + conn->buffer_pos, avail, 0);
        if (n < 0) {
            if (errno == EINTR)
                continue;
            if (errno == EWOULDBLOCK || errno == EAGAIN)
                return 0;
            PROXY_LOG("%s: error: %s\n", conn->name, strerror(errno));
            return -1;
        }

        if (proxy_log) {
            PROXY_LOG("%s: received %d bytes:\n", conn->name, n );
            hex_dump( conn->buffer + conn->buffer_pos, n, ">> " );
        }

        conn->buffer_pos += n;
        avail            -= n;
    }
    return 1;
}

int
proxy_connection_receive_line( ProxyConnection*  conn )
{
    int  result = -1;
    int  fd     = conn->socket;

    for (;;) {
        char  c;
        int   n = recv(fd, &c, 1, 0);
        if (n == 0) {
            PROXY_LOG("%s: disconnected from server\n", conn->name );
            return -1;
        }
        if (n < 0) {
            if (errno == EINTR)
                continue;
            if (errno == EWOULDBLOCK || errno == EAGAIN) {
                PROXY_LOG("%s: blocked\n", conn->name);
                return 0;
            }
            PROXY_LOG("%s: error: %s\n", conn->name, strerror(errno));
            return -1;
        }

        if (c == '\n') {
            if (conn->buffer_pos > 0 && conn->buffer[conn->buffer_pos-1] == '\r')
                conn->buffer_pos -= 1;

            conn->buffer[conn->buffer_pos] = 0;

            PROXY_LOG("%s: received '%.*s'\n", conn->name,
                      conn->buffer_pos, conn->buffer);
            return 1;
        }

        conn->buffer[ conn->buffer_pos++ ] = c;
        if (conn->buffer_pos == conn->buffer_len) {
            PROXY_LOG("%s: line received from proxy is too long\n", conn->name);
            return -1;
        }
    }
}



static void
proxy_connection_insert( ProxyConnection*  conn, ProxyConnection*  after )
{
    conn->next        = after->next;
    after->next->prev = conn;
    after->next       = conn;
    conn->prev        = after;
}

static void
proxy_connection_remove( ProxyConnection*  conn )
{
    conn->prev->next = conn->next;
    conn->next->prev = conn->prev;

    conn->next = conn->prev = conn;
}

/** Global service list
 **/

#define  MAX_SERVICES  4

static  ProxyService*  s_services[ MAX_SERVICES ];
static  int            s_num_services;
static  int            s_init;

static void  proxy_manager_atexit( void );

static void
proxy_manager_init(void)
{
    s_init = 1;
    s_connections->next = s_connections;
    s_connections->prev = s_connections;
    atexit( proxy_manager_atexit );
}


extern int
proxy_manager_add_service( ProxyService*  service )
{
    if (!service || s_num_services >= MAX_SERVICES)
        return -1;

    if (!s_init)
        proxy_manager_init();

    s_services[s_num_services++] = service;
    return 0;
}


extern void
proxy_manager_atexit( void )
{
    ProxyConnection*  conn = s_connections->next;
    int               n;

    /* free all proxy connections */
    while (conn != s_connections) {
        ProxyConnection*  next = conn->next;
        conn->service->conn_free( conn );
        conn = next;
    }
    conn->next = conn;
    conn->prev = conn;

    /* free all proxy services */
    for (n = s_num_services; n-- > 0;) {
        ProxyService*  service = s_services[n];
        service->serv_free( service->opaque );
    }
    s_num_services = 0;
}


void
proxy_connection_free( ProxyConnection*  conn,
                       ProxyEvent        event )
{
    if (conn) {
        int  fd = conn->socket;

        proxy_connection_remove(conn);

        if (event != PROXY_EVENT_NONE)
            conn->ev_func( conn->ev_opaque, event );

        conn->service->conn_free(conn);
    }
}


int
proxy_manager_add( int                  socket,
                   struct sockaddr_in*  address,
                   void*                ev_opaque,
                   ProxyEventFunc       ev_func )
{
    int  n;

    if (!s_init) {
        proxy_manager_init();
    }

    socket_set_nonblock(socket);

    for (n = 0; n < s_num_services; n++) {
        ProxyService*     service = s_services[n];
        ProxyConnection*  conn    = service->serv_connect( service->opaque,
                                                           socket,
                                                           address );
        if (conn != NULL) {
            conn->ev_opaque = ev_opaque;
            conn->ev_func   = ev_func;
            proxy_connection_insert(conn, s_connections->prev);
            return 0;
        }
    }
    return -1;
}


/* remove an on-going proxified socket connection from the manager's list.
 * this is only necessary when the socket connection must be canceled before
 * the connection accept/refusal occured
 */
void
proxy_manager_del( int  socket )
{
    ProxyConnection*  conn = s_connections->next;
    for ( ; conn != s_connections; conn = conn->next ) {
        if (conn->socket == socket) {
            int  fd = conn->socket;
            proxy_connection_remove(conn);
            conn->service->conn_free(conn);
            socket_close(fd);
            return;
        }
    }
}

/* this function is called to update the select file descriptor sets
 * with those of the proxified connection sockets that are currently managed */
void
proxy_manager_select_fill( int  *pcount, fd_set*  read_fds, fd_set*  write_fds, fd_set*  err_fds)
{
    ProxyConnection*  conn;

    if (!s_init)
        proxy_manager_init();

    conn = s_connections->next;
    for ( ; conn != s_connections; conn = conn->next ) {
        unsigned  flags = conn->service->conn_select(conn);
        int       fd    = conn->socket;

        if (!flags)
            continue;

        if (*pcount < fd+1)
            *pcount = fd+1;

        if (flags & PROXY_SELECT_READ) {
            FD_SET( fd, read_fds );
        }
        if (flags & PROXY_SELECT_WRITE) {
            FD_SET( fd, write_fds );
        }
        if (flags & PROXY_SELECT_ERROR) {
            FD_SET( fd, err_fds );
        }
    }
}

/* this function is called to act on proxified connection sockets when network events arrive */
void
proxy_manager_poll( fd_set*  read_fds, fd_set*  write_fds, fd_set*  err_fds )
{
    ProxyConnection*  conn = s_connections->next;
    while (conn != s_connections) {
        ProxyConnection*  next  = conn->next;
        int               fd    = conn->socket;
        unsigned          flags = 0;

        if ( FD_ISSET(fd, read_fds) )
            flags |= PROXY_SELECT_READ;
        if ( FD_ISSET(fd, write_fds) )
            flags |= PROXY_SELECT_WRITE;
        if ( FD_ISSET(fd, err_fds) )
            flags |= PROXY_SELECT_ERROR;

        if (flags != 0) {
            conn->service->conn_poll( conn, flags );
        }
        conn = next;
    }
}


int
proxy_base64_encode( const char*  src, int  srclen,
                     char*        dst, int  dstlen )
{
    static const char cb64[64]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    const char*       srcend = src + srclen;
    int               result = 0;

    while (src+3 <= srcend && result+4 <= dstlen)
    {
        dst[result+0] = cb64[ src[0] >> 2 ];
        dst[result+1] = cb64[ ((src[0] & 3) << 4) | ((src[1] & 0xf0) >> 4) ];
        dst[result+2] = cb64[ ((src[1] & 0xf) << 2) | ((src[2] & 0xc0) >> 6) ];
        dst[result+3] = cb64[ src[2] & 0x3f ];
        src    += 3;
        result += 4;
    }

    if (src < srcend) {
        unsigned char  in[4];

        if (result+4 > dstlen)
            return -1;

        in[0] = src[0];
        in[1] = src+1 < srcend ? src[1] : 0;
        in[2] = src+2 < srcend ? src[2] : 0;

        dst[result+0] = cb64[ in[0] >> 2 ];
        dst[result+1] = cb64[ ((in[0] & 3) << 4) | ((in[1] & 0xf0) >> 4) ];
        dst[result+2] = (unsigned char) (src+1 < srcend ? cb64[ ((in[1] & 0xf) << 2) | ((in[2] & 0xc0) >> 6) ] : '=');
        dst[result+3] = (unsigned char) (src+2 < srcend ? cb64[ in[2] & 0x3f ] : '=');
        result += 4;
    }
    return result;
}

int
proxy_resolve_server( struct sockaddr_in*  addr,
                      const char*          servername,
                      int                  servernamelen,
                      int                  serverport )
{
    char              name0[64], *name = name0;
    int               result = -1;
    struct hostent*   host;

    if (servernamelen < 0)
        servernamelen = strlen(servername);

    memset(addr, 0, sizeof(*addr));
    addr->sin_family = AF_INET;
    addr->sin_port   = htons(serverport);

    if (servernamelen >= sizeof(name0)) {
        name = qemu_malloc(servernamelen+1);
        if (name == NULL)
            return -1;
    }

    memcpy(name, servername, servernamelen);
    name[servernamelen] = 0;

    host = gethostbyname(name);
    if (host == NULL) {
        PROXY_LOG("%s: can't resolve proxy server name '%s'\n",
                  __FUNCTION__, name);
        goto Exit;
    }

    addr->sin_addr = *(struct in_addr*)host->h_addr;
    {
        uint32_t  a = ntohl(addr->sin_addr.s_addr);
        PROXY_LOG("server name '%s' resolved to %d.%d.%d.%d\n", name, (a>>24)&255, (a>>16)&255,(a>>8)&255,a&255);
    }
    result = 0;

Exit:
    if (name != name0)
        qemu_free(name);

    return result;
}