File: io.c

package info (click to toggle)
mongrel2 1.9.1-6
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 5,956 kB
  • sloc: ansic: 43,228; python: 2,827; sql: 1,555; makefile: 347; sh: 307; asm: 234; yacc: 145; php: 73; sed: 5
file content (719 lines) | stat: -rw-r--r-- 18,514 bytes parent folder | download | duplicates (2)
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
/**
 *
 * Copyright (c) 2010, Zed A. Shaw and Mongrel2 Project Contributors.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 * 
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 * 
 *     * Neither the name of the Mongrel2 Project, Zed A. Shaw, nor the names
 *       of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written
 *       permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define _XOPEN_SOURCE 500

#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include "io.h"
#include "register.h"
#include "mem/halloc.h"
#include "dbg.h"
#include <polarssl/havege.h>
#include <polarssl/ssl.h>
#include "task/task.h"
#include "adt/darray.h"

int IO_SSL_VERIFY_METHOD = SSL_VERIFY_NONE;

static ssize_t null_send(IOBuf *iob, char *buffer, int len)
{
    (void)iob;
    (void)buffer;

    return len;
}

static ssize_t null_recv(IOBuf *iob, char *buffer, int len)
{
    (void)iob;
    (void)buffer;

    return len;
}

static ssize_t null_stream_file(IOBuf *iob, int fd, off_t len)
{
    (void)iob;
    (void)fd;

    return len;
}

static ssize_t plaintext_send(IOBuf *iob, char *buffer, int len)
{
    return fdsend(iob->fd, buffer, len);
}

static ssize_t plaintext_recv(IOBuf *iob, char *buffer, int len)
{
    return fdrecv(iob->fd, buffer, len);
}

static ssize_t file_send(IOBuf *iob, char *buffer, int len)
{
    return fdwrite(iob->fd, buffer, len);    
}

static ssize_t file_recv(IOBuf *iob, char *buffer, int len)
{
    return fdread(iob->fd, buffer, len);
}

static ssize_t plain_stream_file(IOBuf *iob, int fd, off_t len)
{
    off_t sent;
    off_t total = 0;
    off_t offset = 0;
    off_t block_size = MAX_SEND_BUFFER;
    int conn_fd = IOBuf_fd(iob);

    for(total = 0; fdwait(conn_fd, 'w') == 0 && total < len; total += sent) {

        block_size = (len - total) > block_size ? block_size : (len - total);
        sent = IOBuf_sendfile(conn_fd, fd, &offset, block_size);

        check(Register_write(iob->fd, sent) != -1, "Socket seems to be closed.");

        check_debug(sent > 0, "Client closed probably during sendfile on socket: %d from "
                    "file %d", conn_fd, fd);
    }
    
    check(total <= len,
            "Wrote way too much, wrote %d but size was %zd",
            (int)total, len);

    check(total == len,
            "Sent other than expected, sent: %d, but expected: %zd", 
            (int)total, len);

    return total;

error:
    return -1;
}

static int ssl_fdsend_wrapper(void *p_iob, const unsigned char *ubuffer, size_t len)
{
    IOBuf *iob = (IOBuf *) p_iob;
    return fdsend(iob->fd, (char *) ubuffer, len);
}

static int ssl_fdrecv_wrapper(void *p_iob, unsigned char *ubuffer, size_t len)
{
    IOBuf *iob = (IOBuf *) p_iob;
    return fdrecv1(iob->fd, (char *) ubuffer, len);
}

static int ssl_do_handshake(IOBuf *iob)
{
    int rcode;
    check(!iob->handshake_performed, "ssl_do_handshake called unnecessarily");
    while((rcode = ssl_handshake(&iob->ssl)) != 0) {

        check(rcode == POLARSSL_ERR_NET_WANT_READ
                || rcode == POLARSSL_ERR_NET_WANT_WRITE, "Handshake failed with error code: %d", rcode);
    }
    iob->handshake_performed = 1;
    return 0;
error:
    return -1;
}

static ssize_t ssl_send(IOBuf *iob, char *buffer, int len)
{
    int sent;
    int total = 0;

    check(iob->use_ssl, "IOBuf not set up to use ssl");

    if(!iob->handshake_performed) {
        int rcode = ssl_do_handshake(iob);
        check(rcode == 0, "SSL handshake failed: %d", rcode);
    }

    for(; len > 0; buffer += sent, len -= sent, total += sent) {
        sent = ssl_write(&iob->ssl, (const unsigned char*) buffer, len);

        check(sent != -1, "Error sending SSL data.");
        check(sent <= len, "Buffer overflow. Too much data sent by ssl_write");

        // make sure we don't hog the process trying to stream out
        if(sent < len) {
            taskyield();
        }
    };

    return total;

error:
    return -1;
}

static ssize_t ssl_recv(IOBuf *iob, char *buffer, int len)
{
    check(iob->use_ssl, "IOBuf not set up to use ssl");

    if(!iob->handshake_performed) {
        int rcode = ssl_do_handshake(iob);
        check(rcode == 0, "SSL handshake failed: %d", rcode);
    }

    return ssl_read(&iob->ssl, (unsigned char*) buffer, len);
error:
    return -1;
}

static ssize_t ssl_stream_file(IOBuf *iob, int fd, off_t len)
{
    ssize_t sent = 0;
    off_t total = 0;
    ssize_t amt = 0;
    ssize_t tosend = 0;
    int conn_fd = IOBuf_fd(iob);
    char buff[1024];

    for(total = 0; fdwait(conn_fd, 'w') == 0 && total < len; total += tosend) {
        tosend = pread(fd, buff, sizeof(buff), total);
        check_debug(tosend > 0, "Came up short in reading file %d\n", fd);

        // We do this in case the file somehow lengthened on us.  In general,
        // it shouldn't happen.
        if(tosend + total > len)
            tosend = len - total;

        sent = 0;
        while(sent < tosend) {
            amt = ssl_send(iob, buff, tosend);
            check_debug(amt > 0, "ssl_send failed in ssl_stream_file with "
                        "return code %zd", amt);
            sent += amt;
        }

        check(Register_write(iob->fd, sent) != -1, "Failed to record write, must have died.");
    }

    check(total <= len,
            "Wrote way too much, wrote %d but size was %zd",
            (int)total, len);

    check(total == len,
            "Sent other than expected, sent: %d, but expected: %zd", 
            (int)total, len);

    return total;

error:
    return -1;
}

void ssl_debug(void *p, int level, const char *msg)
{
    (void)p;
    if (msg) {}

    if(level < 2) {
        debug("polarssl: %s", msg);
    }
}

// -- quick hack taken from the polar ssl server code to see how it will work
//
/*
 * These session callbacks use a simple chained list
 * to store and retrieve the session information.
 */
static darray_t *SSL_SESSION_CACHE = NULL;
const int SSL_INITIAL_CACHE_SIZE = 300;

static inline int setup_ssl_session_cache()
{
    if(SSL_SESSION_CACHE == NULL) {
        SSL_SESSION_CACHE = darray_create(SSL_INITIAL_CACHE_SIZE, sizeof(ssl_session));
        check_mem(SSL_SESSION_CACHE);
    }
    return 0;
error:
    return -1;
}


static int simple_get_cache( void *p_ssl, ssl_session *ssn )
{
    ssl_context *ssl = (ssl_context *) p_ssl;
    int i = 0;

    check(setup_ssl_session_cache() == 0, "Failed to initialize SSL session cache.");

    if( ssl->handshake->resume == 0 ) return 1;
    ssl_session *cur = NULL;

    for(i = 0; i < darray_end(SSL_SESSION_CACHE); i++) {
        cur = darray_get(SSL_SESSION_CACHE, i);

        if( ssn->ciphersuite != cur->ciphersuite ||
            ssn->length != cur->length ) 
        {
            continue;
        }

        if( memcmp( ssn->id, cur->id, cur->length ) != 0 ) {
            continue;
        }

        // TODO: odd, why 48? this is from polarssl
        memcpy( ssn->master, cur->master, 48 );

        x509_crt* _x509P  = cur->peer_cert;
        if (_x509P == NULL) {
            debug("failed to find peer_cert in handshake during get");
            return 0;
        }
        ssn->peer_cert=_x509P;

        return 0;
    }

error: // fallthrough
    return 1;
}

static int simple_set_cache( void *p_ssl, const ssl_session *ssn )
{
    ssl_context *ssl = (ssl_context *) p_ssl;
    int i = 0;
    ssl_session *cur = NULL;
    int make_new = 1;
    check(setup_ssl_session_cache() == 0, "Failed to initialize SSL session cache.");

    for(i = 0; i < darray_end(SSL_SESSION_CACHE); i++) {
        cur = darray_get(SSL_SESSION_CACHE, i);

        if( memcmp( ssn->id, cur->id, cur->length ) == 0 ) {
            make_new = 0;
            break; /* client reconnected */
        }
    }

    if(make_new) {
        cur = (ssl_session *) darray_new(SSL_SESSION_CACHE);
        check_mem(cur);
        darray_push(SSL_SESSION_CACHE, cur);
    }

    *cur = *ssn;

    const x509_crt* _x509P  = ssl_get_peer_cert( ssl );
    if (_x509P == NULL) {
        debug("failed to find peer_cert in handshake");
        return 0;
    }

    int rc = 0;
    if ((rc = x509_crt_parse( cur->peer_cert,  _x509P->raw.p, _x509P->raw.len)) != 0) {
        debug("failed to set peer_cert during handshake:rc:%d:", rc);
    }

    return 0;
error:
    return 1;
}



static inline int iobuf_ssl_setup(IOBuf *buf)
{
    int rc = 0;

    buf->use_ssl = 1;
    buf->handshake_performed = 0;

    rc = ssl_init(&buf->ssl);
    check(rc == 0, "Failed to initialize SSL structure.");

    ssl_set_endpoint(&buf->ssl, SSL_IS_SERVER);
    ssl_set_authmode(&buf->ssl, IO_SSL_VERIFY_METHOD);

    havege_init(&buf->hs);
    ssl_set_rng(&buf->ssl, havege_random, &buf->hs);

#ifndef DEBUG
    ssl_set_dbg(&buf->ssl, ssl_debug, NULL);
#endif

    ssl_set_bio(&buf->ssl, ssl_fdrecv_wrapper, buf, 
                ssl_fdsend_wrapper, buf);

    memset(&buf->ssn, 0, sizeof(buf->ssn));
    ssl_set_session(&buf->ssl, &buf->ssn);

    ssl_set_session_cache(&buf->ssl, simple_get_cache, &buf->ssl, simple_set_cache, &buf->ssl);

    return 0;
error:
    return -1;
}

IOBuf *IOBuf_create(size_t len, int fd, IOBufType type)
{
    IOBuf *buf = malloc(sizeof(IOBuf));
    check_mem(buf);

    buf->len = len;
    buf->avail = 0;
    buf->cur = 0;
    buf->closed = 0;
    buf->buf = malloc(len + 1);
    check_mem(buf->buf);
    buf->type = type;
    buf->fd = fd;
    buf->use_ssl = 0;

    if(type == IOBUF_SSL) {
        check(iobuf_ssl_setup(buf) != -1, "Failed to setup SSL.");
        buf->send = ssl_send;
        buf->recv = ssl_recv;
        buf->stream_file = ssl_stream_file;
    } else if(type == IOBUF_NULL) {
        buf->send = null_send;
        buf->recv = null_recv;
        buf->stream_file = null_stream_file;
    } else if(type == IOBUF_FILE) {
        buf->send = file_send;
        buf->recv = file_recv;
        buf->stream_file = plain_stream_file;
    } else if(type == IOBUF_SOCKET) {
        buf->send = plaintext_send;
        buf->recv = plaintext_recv;
        buf->stream_file = plain_stream_file;
    } else {
        sentinel("Invalid IOBufType given: %d", type);
    }

    return buf;

error:
    if(buf) h_free(buf);
    return NULL;
}

int IOBuf_close(IOBuf *buf)
{
    int rc = 0;

    if(buf) {
        if(buf->use_ssl) {
            rc = ssl_close_notify(&buf->ssl);
        }
        
        fdclose(buf->fd);
        buf->fd=-1;
    }

    return rc;
}

void IOBuf_destroy(IOBuf *buf)
{
    if(buf) {
        IOBuf_close(buf); // ignore return

        if(buf->use_ssl) {
            ssl_free(&buf->ssl);
        }
        
        if(buf->buf) free(buf->buf);
        free(buf);
    }
}

void IOBuf_resize(IOBuf *buf, size_t new_size)
{
    buf->buf = realloc(buf->buf, new_size);
    buf->len = new_size;
}


static inline void IOBuf_compact(IOBuf *buf)
{
    memmove(buf->buf, IOBuf_start(buf), buf->avail);
    buf->cur = 0;
}

/**
 * Does a non-blocking read and either reads in the amount you requested
 * with "need" or less so you can try again.  It sets out_len to what is
 * available (<= need) so you can decide after that.  You can keep attempting
 * to read more and more (up to buf->len) and you'll get the same start point
 * each time.
 *
 * Once you're done with the data you've been trying to read, you use IOBuf_read_commit
 * to commit the "need" amount and then start doing new reads.
 *
 * Internally this works like a "half open ring buffer" and it tries to greedily
 * read as much as possible without blocking or copying.
 *
 * To just get as much as possible, use the IOBuf_read_some macro.
 */
char *IOBuf_read(IOBuf *buf, int need, int *out_len)
{
    int rc = 0;
    assert(buf->cur + buf->avail <= buf->len && 
            "Buffer math off, cur+avail can't be more than > len.");
    assert(buf->cur >= 0 && "Buffer cur can't be < 0");
    assert(buf->avail >= 0 && "Buffer avail can't be < 0");
    assert(need <= buf->len && "Request for more than possible in the buffer.");

    if(IOBuf_closed(buf)) {
        if(buf->avail > 0) {
            *out_len = buf->avail;
        } else {
            *out_len = 0;
            return NULL;
        }
    } else if(buf->avail < need) {
        if(buf->cur > 0 && IOBuf_compact_needed(buf, need)) {
            IOBuf_compact(buf);
        }
        rc = buf->recv(buf, IOBuf_read_point(buf), IOBuf_remaining(buf));

        if(rc <= 0) {
            debug("Socket was closed, will return only what's available: %d", buf->avail);
            buf->closed = 1;
        } else {
            buf->avail = buf->avail + rc;
        }

        if(buf->avail < need) {
            // less than expected
            *out_len = buf->avail;
        } else {
            // more than expected
            *out_len = need;
        }
    } else if(buf->avail >= need) {
        *out_len = need;
    } else {
        sentinel("Invalid branch processing buffer, Tell Zed.");
    }

    return IOBuf_start(buf);

error:
    return NULL;
}

/**
 * Commits the amount given by need to the buffer, moving the internal
 * counters around so that the next read starts after the need point.
 * You use this after you're done working with the data and want to
 * do the next read.
 */
int IOBuf_read_commit(IOBuf *buf, int need)
{
    buf->avail -= need;
    assert(buf->avail >= 0 && "Buffer commit reduced avail to < 0.");
    
    check(Register_read(buf->fd, need) != -1, "Failed to record read, must have died.");

    buf->mark = 0;

    if(buf->avail == 0) {
        // if there's nothing available then just start at the beginning
        buf->cur = 0;
    } else {
        buf->cur += need;
    }

    return 0;
error:
    return -1;
}

/**
 * Wraps the usual send, so not much to it other than it'll avoid doing
 * any calls if the socket is already closed.
 */
int IOBuf_send(IOBuf *buf, char *data, int len)
{
    int rc = 0;

    rc = buf->send(buf, data, len);

    if(rc >= 0) {
        check(Register_write(buf->fd, rc) != -1, "Failed to record write, must have died.");
    } else {
        buf->closed = 1;
    }

    return rc;

error:
    return -1;
}

/**
 * Reads the entire amount requested into the IOBuf (as long as there's
 * space to hold it) and then commits that read in one shot.
 */
char *IOBuf_read_all(IOBuf *buf, int len, int retries)
{
    int nread = 0;
    int attempts = 0;

    check_debug(!IOBuf_closed(buf), "Closed when attempting to read from buffer.");

    if(len > buf->len) {
        // temporarily grow the buffer
        IOBuf_resize(buf, len);
    }

    char *data = IOBuf_read(buf, len, &nread);

    debug("INITIAL READ: len: %d, nread: %d", len, nread);
    for(attempts = 0; nread < len; attempts++) {
        data = IOBuf_read(buf, len, &nread);

        check_debug(data, "Read error from socket.");

        assert(nread <= len && "Invalid nread size (too much) on IOBuf read.");

        if(nread == len) {
            break;
        } else {
            check(!IOBuf_closed(buf), "Socket closed during IOBuf_read_all.");
            fdwait(buf->fd, 'r');
        }
    }
   
    debug("ATTEMPTS: %d, RETRIES: %d", attempts, retries);

    if(attempts > retries) {
        log_warn("Read of %d length attempted %d times which is over %d retry limit..", len, attempts, retries);
    }

    check(IOBuf_read_commit(buf, len) != -1, "Final commit failed of read_all.");
    return data;

error:
    buf->closed = 1;
    return NULL;
}


/**
 * Streams data out of the from IOBuf and into the to IOBuf
 * until it's moved total bytes between them.
 */
int IOBuf_stream(IOBuf *from, IOBuf *to, int total)
{
    int need = 0;
    int remain = total;
    int avail = 0;
    int rc = 0;

    if(from->len > to->len) IOBuf_resize(to, from->len);

    while(remain > 0) {
        need = remain <= from->len ? remain : from->len;

        IOBuf_read(from, need, &avail);
        check_debug(avail > 0, "Nothing in read buffer.");

        rc = IOBuf_send_all(to, IOBuf_start(from), avail);
        check_debug(rc == avail, "Failed to send all of the data: %d of %d", rc, avail)

        // commit whatever we just did
        check(IOBuf_read_commit(from, rc) != -1, "Final commit failed during streaming.");

        // reduce it by the given amount
        remain -= rc;
    }

    assert(remain == 0 && "Buffer math is wrong.");

    return total - remain;

error:
    return -1;
}



int IOBuf_send_all(IOBuf *buf, char *data, int len)
{
    int rc = 0;
    int total = len;

    do {
        rc = IOBuf_send(buf, data, total);
        check(rc > 0, "Write error when sending all.");
        total -= rc;
    } while(total > 0);

    assert(total == 0 && "Math error sending all from buffer.");

    return len;

error:
    return -1;
}

int IOBuf_register_disconnect(IOBuf *buf)
{
    int rc=0;
    if(IOBuf_fd(buf)>0) {
        rc= Register_disconnect(IOBuf_fd(buf));
        return rc;
    }
    return 0;
}


int IOBuf_stream_file(IOBuf *buf, int fd, off_t len)
{
    int rc = 0;

    // We depend on the stream_file callback to call Register_write.
    // Doing it here would make the connection look inactive for long periods
    // if we are streaming a large file.
    rc = buf->stream_file(buf, fd, len);

    if(rc < 0) buf->closed = 1;

    return rc;
}