summaryrefslogtreecommitdiff
path: root/src/lactcpconnection.c
blob: 258ff788cdc850d7bccfbd37a912e3e5bab9b782 (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
503
504
505
506
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- */

/*  Lac - Library for asynchronous communication
 *  Copyright (C) 2000, 2001, 2002, 2003, 2007  Søren Sandmann
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the 
 *  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 *  Boston, MA  02111-1307, USA.
 */

#include <string.h>
#include "lac.h"
#include "lacinternals.h"

/*
 * Prototypes for a primitive abstraction covering TCP and SSL
 */
typedef enum {
    UNDEFINED,
    CONNECT_IN_PROGRESS,
    CONNECTED,
    DISCONNECTED,
} ConnectionState;

struct _LacTcpConnection {
    int                         fd;
    LacTcpConnectionFunc        callback;
    gpointer                    data;

    GQueue *                    pending_events;
    
    ConnectionState             state;
    LacByteQueue *              unwritten;
    
    gboolean                    has_fd;
    gboolean                    in_emit_events;
    gboolean                    need_flush;
    gint                        ref_count;
};

static void
event_free (LacConnectionEvent *event)
{
    if (event->type == LAC_CONNECTION_EVENT_READ)
    {
        /* FIXME: at some point we should support pushing
         * data back into the queue, ie., it must be kept alive
         */
        lac_byte_queue_free (event->read.byte_queue, TRUE);
    }
    else if (event->type == LAC_CONNECTION_EVENT_ERROR)
        g_error_free ((GError *)event->error.err);
    
    g_free (event);
}

static void
queue_connect (LacTcpConnection *connection)
{
    LacConnectionEvent *event = g_new (LacConnectionEvent, 1);

    event->type = LAC_CONNECTION_EVENT_CONNECT;

    g_queue_push_tail (connection->pending_events, event);
}

static void
queue_read (LacTcpConnection *connection, LacByteQueue *queue)
{
    LacConnectionEvent *event = g_new (LacConnectionEvent, 1);
    
    event->type = LAC_CONNECTION_EVENT_READ;
    event->read.byte_queue = queue;
    event->read.data = lac_byte_queue_peek (queue, &(event->read.len));

    g_queue_push_tail (connection->pending_events, event);
}

static void
queue_close (LacTcpConnection *connection, gboolean remote)
{
    LacConnectionEvent *event = g_new (LacConnectionEvent, 1);

    event->type = LAC_CONNECTION_EVENT_CLOSE;
    event->close.remote_closed = remote;

    g_queue_push_tail (connection->pending_events, event);
}

static void
queue_error (LacTcpConnection *connection, const GError *err)
{
    LacConnectionEvent *event = g_new (LacConnectionEvent, 1);
    
    event->type = LAC_CONNECTION_EVENT_ERROR;
    event->error.err = g_error_copy (err);

    g_queue_push_tail (connection->pending_events, event);
}

static void
emit_events (LacTcpConnection *connection)
{
    LacConnectionEvent *event;

    if (connection->in_emit_events)
        return;

    connection->in_emit_events = TRUE;
    lac_tcp_connection_ref (connection);

    while ((event = g_queue_pop_head (connection->pending_events)))
    {
        if (connection->state != DISCONNECTED)
        {
            if (event->type == LAC_CONNECTION_EVENT_CLOSE ||
                event->type == LAC_CONNECTION_EVENT_ERROR)
            {
                connection->state = DISCONNECTED;

                if (connection->has_fd)
                {
                    lac_fd_remove_watch (connection->fd);
                    lac_close (connection->fd, NULL);
                    connection->has_fd = FALSE;
                }
            }
            
            connection->callback (connection, event);
        }
        
        event_free (event);
    }

    connection->in_emit_events = FALSE;
    lac_tcp_connection_unref (connection);
}

static gboolean
emit_events_idle_handler (gpointer data)
{
    LacTcpConnection *connection = data;
    emit_events (connection);

    lac_tcp_connection_unref (connection);

    return FALSE; /* don't call me again */
}

static void
emit_events_idle (LacTcpConnection *connection)
{
    if (!g_queue_is_empty (connection->pending_events))
    {
        lac_tcp_connection_ref (connection);
        
        g_idle_add (
            emit_events_idle_handler, connection);
    }
}

static void
lac_tcp_connection_do_reads (gpointer data)
{
    LacTcpConnection *connection = data;
    gint len;
    
    enum { BUF_SIZE = 8280 };

    do
    {
        GError *err = NULL;
        LacByteQueue *queue = lac_byte_queue_new ();
        gchar *buf = lac_byte_queue_alloc_tail (queue, BUF_SIZE);
        
        len = lac_recv (connection->fd, buf, BUF_SIZE, &err);

        if (len > 0)
        {
            lac_byte_queue_delete_tail (queue, BUF_SIZE - len);
        
            queue_read (connection, queue);
        }
        else
        {
            lac_byte_queue_free (queue, TRUE);
            
            if (len == 0)
            {
                queue_close (connection, TRUE);
            }
            else
            {
                g_assert (err);
                
                if (!g_error_matches (
                        err, LAC_SOCKET_ERROR, LAC_SOCKET_ERROR_AGAIN))
                {
                    queue_error (connection, err);
                }
                
                g_error_free (err);
            }
        }

        /* FIXME: check that we haven't used too much time? */
    }
    while (len == BUF_SIZE);
}

static void lac_tcp_connection_writable (gpointer data);

static void
lac_tcp_connection_do_writes (LacTcpConnection *connection)
{
    if (connection->state != CONNECTED)
    {
        lac_fd_set_write_callback (connection->fd, lac_tcp_connection_writable);
        return;
    }
    
    while (lac_byte_queue_get_length (connection->unwritten) > 0)
    {
        GError       *err = NULL;
        const gchar  *unwritten;
        gsize         len, sent;
        
        unwritten = lac_byte_queue_peek (connection->unwritten, &len);

        sent = lac_send (connection->fd, unwritten, len, &err);

        if (err)
        {
            if (g_error_matches (
                err, LAC_SOCKET_ERROR, LAC_SOCKET_ERROR_AGAIN))
            {
                lac_fd_set_write_callback (
                    connection->fd, lac_tcp_connection_writable);
            }
            else
            {
                queue_error (connection, err);
            }

            g_error_free (err);
            return;
        }

        lac_byte_queue_delete_head (connection->unwritten, sent);
        
        /* FIXME check that we haven't used too much time? */
    }

    lac_fd_set_write_callback (connection->fd, NULL);
    
    if (connection->need_flush)
    {
        lac_set_nagle (connection->fd, FALSE, NULL);
        lac_set_nagle (connection->fd, TRUE, NULL);

        connection->need_flush = FALSE;
    }
}

static void
lac_tcp_connection_readable (gpointer data)
{
    LacTcpConnection *connection = data;
    
    lac_tcp_connection_do_reads (connection);
    emit_events (connection);
}

static void
lac_tcp_connection_writable (gpointer data)
{
    LacTcpConnection *connection = data;
    
    if (connection->state == CONNECT_IN_PROGRESS)
    {
        connection->state = CONNECTED;
        queue_connect (connection);
    }

    lac_tcp_connection_do_writes (connection);
    emit_events (connection);
}

static void
lac_tcp_connection_connect (LacTcpConnection *connection,
                            const LacAddress *address,
                            int               port)
{
    GError *err = NULL;
    
    lac_connect (connection->fd, address, port, &err);

    if (err)
    {
        if (g_error_matches (
            err, LAC_SOCKET_ERROR, LAC_SOCKET_ERROR_IN_PROGRESS))
        {
            connection->state = CONNECT_IN_PROGRESS;
        }
        else
        {
            queue_error (connection, err);
        }

        g_error_free (err);
    }
    else
    {
        connection->state = CONNECTED;
        queue_connect (connection);
        lac_tcp_connection_do_writes (connection);
    }
}

static void
lac_tcp_connection_discard_pending_events (LacTcpConnection *connection)
{
    LacConnectionEvent *event;

    while ((event = g_queue_pop_head (connection->pending_events)))
        event_free (event);
}

static void
lac_tcp_connection_add_watch (LacTcpConnection *connection)
{
    lac_fd_add_watch (connection->fd, connection);

    lac_fd_set_read_callback (connection->fd, lac_tcp_connection_readable);
    lac_fd_set_write_callback (connection->fd, lac_tcp_connection_writable);
}

LacTcpConnection *
lac_tcp_connection_new (const LacAddress  *address,
                    gint               port,
                    LacTcpConnectionFunc  callback,
                    gpointer           data)
{
    LacTcpConnection *connection;
    GError *err = NULL;
    
    g_return_val_if_fail (address != NULL, NULL);
    g_return_val_if_fail (port > 0, NULL);
    g_return_val_if_fail (callback != NULL, NULL);
    
    connection = g_new (LacTcpConnection, 1);
    
    connection->ref_count = 1;
    
    connection->callback = callback;
    connection->data = data;

    connection->pending_events = g_queue_new ();
    
    connection->state = UNDEFINED;
    connection->has_fd = FALSE;
    connection->unwritten = lac_byte_queue_new ();
    
    connection->in_emit_events = FALSE;
    connection->need_flush = FALSE;
        
    connection->fd = lac_socket_tcp (&err);
    if (err)
    {
        queue_error (connection, err);
        emit_events_idle (connection);
        g_error_free (err);
        return connection;
    }

    connection->has_fd = TRUE;
    
    lac_set_blocking (connection->fd, FALSE, &err);
    if (err)
    {
        queue_error (connection, err);
        emit_events_idle (connection);
        g_error_free (err);
        return connection;
    }

    lac_tcp_connection_add_watch (connection);
    lac_tcp_connection_connect (connection, address, port);

    emit_events_idle (connection);
    
    return connection;
}

gpointer
lac_tcp_connection_get_data (LacTcpConnection     *connection)
{
    g_return_val_if_fail (connection != NULL, NULL);
    
    return connection->data;
}

void
lac_tcp_connection_write (LacTcpConnection     *connection,
                      const gchar       *data,
                      guint              len)
{
    gboolean do_writes;

    g_return_if_fail (connection != NULL);
    g_return_if_fail (data != NULL);
    g_return_if_fail (connection->state != DISCONNECTED);

    if (len == 0)
        return;
    
    do_writes = (lac_byte_queue_get_length (connection->unwritten) == 0);

    lac_byte_queue_append (connection->unwritten, data, len);

    if (do_writes)
    {
        lac_tcp_connection_do_writes (connection);
        emit_events (connection);
    }
}

void
lac_tcp_connection_write_cstr (LacTcpConnection     *connection,
                               const gchar       *data)
{
    guint len;
    
    g_return_if_fail (connection != NULL);
    g_return_if_fail (data != NULL);

    len = strlen (data);
    
    if (len > 0)
        lac_tcp_connection_write (connection, data, len);
}

void
lac_tcp_connection_close (LacTcpConnection    *connection)
{
    g_return_if_fail (connection != NULL);

    lac_tcp_connection_discard_pending_events (connection);

    queue_close (connection, FALSE);
    emit_events (connection);
}

LacTcpConnection *
lac_tcp_connection_ref (LacTcpConnection     *connection)
{
    ++connection->ref_count;
    
    return connection;
}

void
lac_tcp_connection_unref (LacTcpConnection     *connection)
{
    if (--connection->ref_count == 0)
    {
        lac_tcp_connection_discard_pending_events (connection);
        g_queue_free (connection->pending_events);

        lac_byte_queue_free (connection->unwritten, TRUE);
        
        if (connection->has_fd)
        {
            lac_fd_remove_watch (connection->fd);
            lac_close (connection->fd, NULL);
        }

        g_free (connection);
    }
}

gboolean
lac_tcp_connection_is_connected (LacTcpConnection *connection)
{
    return connection->state == CONNECTED;
}

void
lac_tcp_connection_flush (LacTcpConnection     *connection)
{
    connection->need_flush = TRUE;

    if (lac_byte_queue_get_length (connection->unwritten) == 0)
        lac_tcp_connection_do_writes (connection);
}