summaryrefslogtreecommitdiff
path: root/src/lacconnection.c
blob: db095c981ff92bc18127e129ea0205851a8d962d (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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- */

/*  Lac - Library for asynchronous communication
 *  Copyright (C) 2000, 2001, 2002, 2003  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 "lac.h"
#include <string.h>

/*
 * Prototypes for a primitive abstraction covering TCP and SSL
 */

typedef struct Socket Socket;

static Socket * socket_new_tcp      (GError            **err);
static Socket * socket_new_ssl      (GError            **err);
static gboolean socket_connect      (Socket             *socket,
                                     LacAddress         *address,
                                     gint                port,
                                     GError            **err);
static gboolean socket_is_connected (Socket             *socket);
static gint     socket_send         (Socket             *socket,
                                     const guint8       *msg,
                                     guint               len,
                                     GError            **err);
static gint     socket_recv         (Socket             *socket,
                                     guint8             *buf,
                                     guint               size,
                                     GError            **err);
#if 0
static int      socket_get_fd       (Socket             *socket);
#endif
static void     socket_flush        (Socket             *socket);
static gboolean socket_shutdown     (Socket             *socket,
                                     LacShutdownMethod   how,
                                     GError            **err);
static gboolean socket_set_blocking (Socket             *socket,
                                     gboolean            blocking,
                                     GError            **err);
static gboolean socket_close        (Socket             *socket,
                                     GError            **err);
static void     socket_add_watch    (Socket             *socket,
                                     gpointer            data);
static void     socket_remove_watch (Socket             *socket);
static void     socket_set_read_cb  (Socket           *socket,
                                     LacWatchCallback  read_cb);
static void     socket_set_write_cb (Socket           *socket,
                                     LacWatchCallback  write_cb);


typedef enum {
    UNDEFINED,
    CONNECT_IN_PROGRESS,
    CONNECTED,
    DISCONNECTED,
} ConnectionState;

struct _LacConnection {
    Socket *            socket;
    LacAddress *        address;
    gint                port;
    LacConnectionFunc   callback;
    gpointer            data;

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


static void
event_free (LacConnectionEvent *event)
{
    if (event->type == LAC_CONNECTION_EVENT_READ)
        g_free ((gchar *)event->read.data);
    else if (event->type == LAC_CONNECTION_EVENT_ERROR)
        g_error_free ((GError *)event->error.err);
    
    g_free (event);
}

static void
queue_connect (LacConnection *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 (LacConnection *connection, const guint8 *data, guint len)
{
    LacConnectionEvent *event = g_new (LacConnectionEvent, 1);
    
    event->type = LAC_CONNECTION_EVENT_READ;
    event->read.data = g_memdup (data, len);
    event->read.len = len;

    g_queue_push_tail (connection->pending_events, event);
}

static void
queue_close (LacConnection *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 (LacConnection *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 (LacConnection *connection)
{
    LacConnectionEvent *event;

    if (connection->in_emit_events)
        return;

    connection->in_emit_events = TRUE;
    lac_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)
                {
                    socket_remove_watch (connection->socket);
                    socket_close (connection->socket, NULL);
                    connection->has_fd = FALSE;
                }
            }
            
            connection->callback (connection, event);
        }
        
        event_free (event);
    }

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

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

    lac_connection_unref (connection);

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

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

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

    do
    {
        guint8 buf [BUF_SIZE];
        GError *err = NULL;
        
        len = socket_recv (connection->socket, buf, BUF_SIZE, &err);
        if (len < 0)
        {
            g_assert (err);
            
            if (!g_error_matches (
                    err, LAC_SOCKET_ERROR, LAC_SOCKET_ERROR_AGAIN))
            {
                queue_error (connection, err);
            }

            g_error_free (err);
        }
        else if (len == 0)
        {
            queue_close (connection, TRUE);
        }
        else
        {
            queue_read (connection, buf, len);
        }

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

static void lac_connection_writable (gpointer data);

static void
lac_connection_do_writes (LacConnection *connection)
{
    if (connection->state != CONNECTED)
    {
        socket_set_write_cb (connection->socket, lac_connection_writable);
        return;
    }
    
    while (lac_byte_queue_get_length (connection->unwritten) > 0)
    {
        GError       *err = NULL;
        const guint8 *unwritten;
        gsize         len, sent;
        
        unwritten = lac_byte_queue_get_data (connection->unwritten, &len);

        sent = socket_send (connection->socket, unwritten, len, &err);

        lac_byte_queue_append (
            connection->unwritten, unwritten, err? len : len - sent);
        
        if (err)
        {
            lac_byte_queue_append (connection->unwritten, unwritten, len);
            
            if (g_error_matches (
                err, LAC_SOCKET_ERROR, LAC_SOCKET_ERROR_AGAIN))
            {
                socket_set_write_cb (
                    connection->socket, lac_connection_writable);
            }
            else
            {
                queue_error (connection, err);
            }

            g_error_free (err);
            return;
        }

        /* FIXME check that we haven't used too much time? */
    }

    socket_set_write_cb (connection->socket, NULL);
    
    if (connection->need_flush)
    {
        socket_flush (connection->socket);

        connection->need_flush = FALSE;
    }

    if (connection->write_shutdown)
    {
        GError *err = NULL;
        
        socket_shutdown (connection->socket, LAC_SHUTDOWN_WRITE, &err);
        if (err)
        {
            queue_error (connection, err);
            g_error_free (err);
        }
    }
}

static void
lac_connection_readable (gpointer data)
{
    LacConnection *connection = data;
    
    lac_connection_do_reads (connection);
    emit_events (connection);
}

static void
lac_connection_writable (gpointer data)
{
    LacConnection *connection = data;
    
    if (connection->state == CONNECT_IN_PROGRESS)
    {
        if (!socket_is_connected (connection->socket))
            return;
        
        connection->state = CONNECTED;
        queue_connect (connection);
    }

    lac_connection_do_writes (connection);
    emit_events (connection);
}

static void
lac_connection_connect (LacConnection *connection)
{
    GError *err = NULL;
    
    socket_connect (connection->socket,
                    connection->address, connection->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_connection_do_writes (connection);
    }
}

static void
lac_connection_discard_pending_events (LacConnection *connection)
{
    LacConnectionEvent *event;

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

static void
lac_connection_add_watch (LacConnection *connection)
{
    socket_add_watch (connection->socket, connection);

    socket_set_read_cb (connection->socket, lac_connection_readable);
    socket_set_write_cb (connection->socket, lac_connection_writable);
}

LacConnection *
lac_connection_new (const LacAddress  *address,
                    gint               port,
                    LacConnectionFunc  callback,
                    gpointer           data)
{
    LacConnection *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 (LacConnection, 1);
    
    connection->ref_count = 1;
    
    connection->address = lac_address_copy (address);
    connection->port = port;
    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->write_shutdown = FALSE;
    connection->in_emit_events = FALSE;
    connection->need_flush = FALSE;
        
    connection->socket = socket_new_tcp (&err);
    if (err)
    {
        queue_error (connection, err);
        emit_events_idle (connection);
        g_error_free (err);
        return connection;
    }

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

    lac_connection_add_watch (connection);
    lac_connection_connect (connection);

    emit_events_idle (connection);
    
    return connection;
}

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

void
lac_connection_write (LacConnection     *connection,
                      const guint8      *data,
                      guint              len)
{
    gboolean do_writes;

    g_return_if_fail (connection != NULL);
    g_return_if_fail (data != NULL);
    g_return_if_fail (!connection->write_shutdown);
    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_connection_do_writes (connection);
        emit_events (connection);
    }
}

void
lac_connection_write_cstr (LacConnection     *connection,
                           const gchar       *data)
{
    guint len;
    
    g_return_if_fail (connection != NULL);
    g_return_if_fail (data != NULL);
    g_return_if_fail (!connection->write_shutdown);

    len = strlen (data);
    
    if (len > 0)
        lac_connection_write (connection, (const guint8 *)data, len);
}

void
lac_connection_shutdown_write (LacConnection     *connection)
{
    g_return_if_fail (connection != NULL);
    
    connection->write_shutdown = TRUE;

    lac_connection_do_writes (connection);
    emit_events (connection);
}

void
lac_connection_close (LacConnection    *connection)
{
    g_return_if_fail (connection != NULL);

    lac_connection_discard_pending_events (connection);

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

LacConnection *
lac_connection_ref (LacConnection     *connection)
{
    ++connection->ref_count;
    
    return connection;
}

void
lac_connection_unref (LacConnection     *connection)
{
    if (--connection->ref_count == 0)
    {
        lac_address_free (connection->address);

        lac_connection_discard_pending_events (connection);
        g_queue_free (connection->pending_events);

        lac_byte_queue_free (connection->unwritten, TRUE);
        
        if (connection->has_fd)
        {
            socket_remove_watch (connection->socket);
            socket_close (connection->socket, NULL);
        }

        g_free (connection);
    }
}

G_CONST_RETURN LacAddress *
lac_connection_get_address (LacConnection     *connection)
{
    return connection->address;
}

gint
lac_connection_get_port    (LacConnection     *connection)
{
    return connection->port;
}

gboolean
lac_connection_is_connected (LacConnection *connection)
{
    return connection->state == CONNECTED;
}

void
lac_connection_flush (LacConnection     *connection)
{
    connection->need_flush = TRUE;

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


/*
 * Socket abstraction
 */
struct Socket
{
    gboolean ssl;

    union
    {
        struct
        {
            int         fd;
        } tcp;

        struct
        {
            int                 fd;
            LacTLS             *tls;
            gboolean            override;
            gpointer            data;
            LacWatchCallback    read_cb;
            LacWatchCallback    write_cb;
        } ssl;
    } u;
};

static Socket *
socket_new_tcp (GError **err)
{
    Socket *socket;    
    int fd;

    fd = lac_socket_tcp (err);

    if (fd < 0)
        return NULL;
    
    socket = g_new0 (Socket, 1);
    socket->u.ssl.tls = FALSE;
    socket->u.ssl.fd = fd;
    socket->u.ssl.override = FALSE;
    socket->u.ssl.read_cb = NULL;
    socket->u.ssl.write_cb = NULL;
    
    return socket;
}

static Socket *
socket_new_ssl (GError **err)
{
    Socket *socket;
    int fd;

    fd = lac_socket_tcp (err);
    if (fd < 0)
        return NULL;

    socket = g_new0 (Socket, 1);
    socket->ssl = TRUE;
    socket->u.ssl.fd = fd;
    socket->u.ssl.tls = NULL; // lac_tls

    return socket;
}

static gboolean
socket_connect (Socket       *socket,
                LacAddress   *address,
                gint          port,
                GError      **err)
{
    if (socket->ssl)
    {
        lac_connect (socket->u.ssl.fd, address, port, err);
        
    }
    else
    {
        return lac_connect (socket->u.tcp.fd, address, port, err);
    }
}

static gboolean
socket_is_connected (Socket  *socket)
{
    /* We only get called when the fd is writable, which
     * for TCP sockets means it's connected
     */
    return TRUE;
}

static void
set_normal_callbacks (Socket *socket)
{
    g_assert (socket->ssl);
    
    lac_fd_set_read_callback (socket->u.ssl.fd, socket->u.ssl.read_cb);
    lac_fd_set_write_callback (socket->u.ssl.fd, socket->u.ssl.write_cb);

    socket->u.ssl.override = FALSE;
}

static void
override_readable (gpointer data)
{
    Socket *socket = data;

    if (socket->u.ssl.read_cb)
        socket->u.ssl.read_cb (socket->u.ssl.data);

    set_normal_callbacks (socket);
}

static void
override_writable (gpointer data)
{
    Socket *socket = data;

    if (socket->u.ssl.write_cb)
        socket->u.ssl.write_cb (socket->u.ssl.data);

    set_normal_callbacks (socket);
}

static gboolean
lactls_needs_write (LacTLS *tls)
{
    return FALSE;
}

static void
override_callbacks (Socket           *socket,
                    LacWatchCallback  func)
{
    gboolean needs_write;
    
    g_assert (socket->ssl);

    needs_write = lactls_needs_write (socket->u.ssl.tls);

    lac_fd_set_write_callback (socket->u.ssl.fd, needs_write? func : NULL);
    lac_fd_set_read_callback (socket->u.ssl.fd, needs_write? NULL : func);

#if 0
    socket->u.ssl.overridden = TRUE;
#endif
}

static gint
socket_send (Socket       *socket,
             const guint8 *msg,
             guint         len,
             GError      **err)
{
    if (socket->ssl)
    {
        GError *err = NULL;
        
#if 0
        lac_tls_send (socket->u.ssl.tls, msg, len, &err);
#endif

        if (err)
        {
#if 0
            if (AGAIN)
                override_callbacks (socket, override_writable);
#endif
        }
    }
    else
    {
        return lac_send (socket->u.tcp.fd, msg, len, err);
    }
}

static gint
socket_recv (Socket       *socket,
             guint8       *buf,
             guint         size,
             GError      **err)
{
    if (socket->ssl)
    {
    }
    else
    {
        return lac_recv (socket->u.tcp.fd, (gchar *)buf, size, err);
    }
}

static gboolean
socket_close   (Socket       *socket,
                GError      **err)
{
    if (socket->ssl)
    {
    }
    else
    {
        return lac_close (socket->u.tcp.fd, err);
    }
}

static void
socket_flush (Socket *socket)
{
    if (socket->ssl)
    {
    }
    else
    {
        /* Turn Nagle off, then on, to make the kernel send everything it
         * has queued up.
         */
        
        lac_set_nagle (socket->u.tcp.fd, FALSE, NULL);
        lac_set_nagle (socket->u.tcp.fd, TRUE, NULL);
    }
    
}

static gboolean
socket_set_blocking (Socket             *socket,
                     gboolean            blocking,
                     GError            **err)
{
    if (socket->ssl)
    {
    }
    else
    {
        return lac_set_blocking (socket->u.tcp.fd, blocking, err);
    }
}

static gboolean
socket_shutdown (Socket *socket,
                 LacShutdownMethod   how,
                 GError **err)
{
    if (socket->ssl)
    {
    }
    else
    {
        return lac_shutdown (socket->u.tcp.fd, how, err);
    }
}

static void
socket_add_watch (Socket *socket,
                  gpointer data)
{
    if (socket->ssl)
    {
        socket->u.ssl.data = data;
        lac_fd_add_watch (socket->u.ssl.fd, data);
    }
    else
    {
        lac_fd_add_watch (socket->u.tcp.fd, data);
    }
}

static void
socket_remove_watch (Socket *socket)
{
    if (socket->ssl)
    {
        socket->u.ssl.data = NULL;
        lac_fd_remove_watch (socket->u.ssl.fd);
    }
    else
    {
        lac_fd_remove_watch (socket->u.tcp.fd);
    }
}

static void
socket_set_read_cb (Socket           *socket,
                    LacWatchCallback  read_cb)
{
    if (socket->ssl)
    {
    }
    else
    {
        lac_fd_set_read_callback (socket->u.tcp.fd, read_cb);
        lac_fd_set_hangup_callback (socket->u.tcp.fd, read_cb);
        lac_fd_set_error_callback (socket->u.tcp.fd, read_cb);
        lac_fd_set_write_callback (socket->u.tcp.fd, read_cb);
    }
}

static void
socket_set_write_cb (Socket           *socket,
                     LacWatchCallback  write_cb)
{
    if (socket->ssl)
    {
    }
    else
    {
        lac_fd_set_write_callback (socket->u.tcp.fd, write_cb);
    }
}