Coverage Report

Created: 2022-08-24 06:37

/src/wolfssl-normal-math/src/wolfio.c
Line
Count
Source (jump to first uncovered line)
1
/* wolfio.c
2
 *
3
 * Copyright (C) 2006-2022 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
23
24
#ifdef HAVE_CONFIG_H
25
    #include <config.h>
26
#endif
27
28
#include <wolfssl/wolfcrypt/settings.h>
29
30
#ifndef WOLFCRYPT_ONLY
31
32
#ifdef _WIN32_WCE
33
    /* On WinCE winsock2.h must be included before windows.h for socket stuff */
34
    #include <winsock2.h>
35
#endif
36
37
#include <wolfssl/internal.h>
38
#include <wolfssl/error-ssl.h>
39
#include <wolfssl/wolfio.h>
40
41
#if defined(HAVE_HTTP_CLIENT)
42
    #include <stdlib.h>   /* strtol() */
43
#endif
44
45
/*
46
Possible IO enable options:
47
 * WOLFSSL_USER_IO:     Disables default Embed* callbacks and     default: off
48
                        allows user to define their own using
49
                        wolfSSL_CTX_SetIORecv and wolfSSL_CTX_SetIOSend
50
 * USE_WOLFSSL_IO:      Enables the wolfSSL IO functions          default: on
51
 * HAVE_HTTP_CLIENT:    Enables HTTP client API's                 default: off
52
                                     (unless HAVE_OCSP or HAVE_CRL_IO defined)
53
 * HAVE_IO_TIMEOUT:     Enables support for connect timeout       default: off
54
 */
55
56
57
/* if user writes own I/O callbacks they can define WOLFSSL_USER_IO to remove
58
   automatic setting of default I/O functions EmbedSend() and EmbedReceive()
59
   but they'll still need SetCallback xxx() at end of file
60
*/
61
62
#if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT)
63
64
/* Translates return codes returned from
65
 * send() and recv() if need be.
66
 */
67
static WC_INLINE int TranslateReturnCode(int old, int sd)
68
0
{
69
0
    (void)sd;
70
71
#if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
72
    if (old == 0) {
73
        errno = SOCKET_EWOULDBLOCK;
74
        return -1;  /* convert to BSD style wouldblock as error */
75
    }
76
77
    if (old < 0) {
78
        errno = RTCS_geterror(sd);
79
        if (errno == RTCSERR_TCP_CONN_CLOSING)
80
            return 0;   /* convert to BSD style closing */
81
        if (errno == RTCSERR_TCP_CONN_RLSD)
82
            errno = SOCKET_ECONNRESET;
83
        if (errno == RTCSERR_TCP_TIMED_OUT)
84
            errno = SOCKET_EAGAIN;
85
    }
86
#endif
87
88
0
    return old;
89
0
}
90
91
static WC_INLINE int wolfSSL_LastError(int err)
92
0
{
93
0
    (void)err; /* Suppress unused arg */
94
95
#ifdef USE_WINDOWS_API
96
    return WSAGetLastError();
97
#elif defined(EBSNET)
98
    return xn_getlasterror();
99
#elif defined(WOLFSSL_LINUXKM)
100
    return err; /* Return provided error value */
101
#elif defined(FUSION_RTOS)
102
    #include <fclerrno.h>
103
    return FCL_GET_ERRNO;
104
#else
105
0
    return errno;
106
0
#endif
107
0
}
108
109
static int TranslateIoError(int err)
110
0
{
111
0
    if (err > 0)
112
0
        return err;
113
114
0
    err = wolfSSL_LastError(err);
115
#if SOCKET_EWOULDBLOCK != SOCKET_EAGAIN
116
    if ((err == SOCKET_EWOULDBLOCK) || (err == SOCKET_EAGAIN))
117
#else
118
0
    if (err == SOCKET_EWOULDBLOCK)
119
0
#endif
120
0
    {
121
0
        WOLFSSL_MSG("\tWould block");
122
0
        return WOLFSSL_CBIO_ERR_WANT_READ;
123
0
    }
124
0
    else if (err == SOCKET_ECONNRESET) {
125
0
        WOLFSSL_MSG("\tConnection reset");
126
0
        return WOLFSSL_CBIO_ERR_CONN_RST;
127
0
    }
128
0
    else if (err == SOCKET_EINTR) {
129
0
        WOLFSSL_MSG("\tSocket interrupted");
130
0
        return WOLFSSL_CBIO_ERR_ISR;
131
0
    }
132
0
    else if (err == SOCKET_EPIPE) {
133
0
        WOLFSSL_MSG("\tBroken pipe");
134
0
        return WOLFSSL_CBIO_ERR_CONN_CLOSE;
135
0
    }
136
0
    else if (err == SOCKET_ECONNABORTED) {
137
0
        WOLFSSL_MSG("\tConnection aborted");
138
0
        return WOLFSSL_CBIO_ERR_CONN_CLOSE;
139
0
    }
140
141
0
    WOLFSSL_MSG("\tGeneral error");
142
0
    return WOLFSSL_CBIO_ERR_GENERAL;
143
0
}
144
#endif /* USE_WOLFSSL_IO || HAVE_HTTP_CLIENT */
145
146
#ifdef OPENSSL_EXTRA
147
#ifndef NO_BIO
148
/* Use the WOLFSSL read BIO for receiving data. This is set by the function
149
 * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIORecv.
150
 *
151
 * ssl  WOLFSSL struct passed in that has this function set as the receive
152
 *      callback.
153
 * buf  buffer to fill with data read
154
 * sz   size of buf buffer
155
 * ctx  a user set context
156
 *
157
 * returns the amount of data read or want read. See WOLFSSL_CBIO_ERR_* values.
158
 */
159
int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx)
160
{
161
    int recvd = WOLFSSL_CBIO_ERR_GENERAL;
162
163
    WOLFSSL_ENTER("BioReceive");
164
165
    if (ssl->biord == NULL) {
166
        WOLFSSL_MSG("WOLFSSL biord not set");
167
        return WOLFSSL_CBIO_ERR_GENERAL;
168
    }
169
170
    recvd = wolfSSL_BIO_read(ssl->biord, buf, sz);
171
    if (recvd <= 0) {
172
        if (/* ssl->biowr->wrIdx is checked for Bind9 */
173
            wolfSSL_BIO_method_type(ssl->biowr) == WOLFSSL_BIO_BIO &&
174
            wolfSSL_BIO_wpending(ssl->biowr) != 0 &&
175
            /* Not sure this pending check is necessary but let's double
176
             * check that the read BIO is empty before we signal a write
177
             * need */
178
            wolfSSL_BIO_supports_pending(ssl->biord) &&
179
            wolfSSL_BIO_ctrl_pending(ssl->biord) == 0) {
180
            /* Let's signal to the app layer that we have
181
             * data pending that needs to be sent. */
182
            return WOLFSSL_CBIO_ERR_WANT_WRITE;
183
        }
184
        else if (ssl->biord->type == WOLFSSL_BIO_SOCKET) {
185
            if (recvd == 0) {
186
                WOLFSSL_MSG("BioReceive connection closed");
187
                return WOLFSSL_CBIO_ERR_CONN_CLOSE;
188
            }
189
        #ifdef USE_WOLFSSL_IO
190
            recvd = TranslateIoError(recvd);
191
        #endif
192
            return recvd;
193
        }
194
195
        /* If retry and read flags are set, return WANT_READ */
196
        if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_READ) &&
197
            (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
198
            return WOLFSSL_CBIO_ERR_WANT_READ;
199
        }
200
201
        WOLFSSL_MSG("BIO general error");
202
        return WOLFSSL_CBIO_ERR_GENERAL;
203
    }
204
205
    (void)ctx;
206
    return recvd;
207
}
208
209
210
/* Use the WOLFSSL write BIO for sending data. This is set by the function
211
 * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIOSend.
212
 *
213
 * ssl  WOLFSSL struct passed in that has this function set as the send callback.
214
 * buf  buffer with data to write out
215
 * sz   size of buf buffer
216
 * ctx  a user set context
217
 *
218
 * returns the amount of data sent or want send. See WOLFSSL_CBIO_ERR_* values.
219
 */
220
int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx)
221
{
222
    int sent = WOLFSSL_CBIO_ERR_GENERAL;
223
224
    WOLFSSL_ENTER("BioSend");
225
226
    if (ssl->biowr == NULL) {
227
        WOLFSSL_MSG("WOLFSSL biowr not set");
228
        return WOLFSSL_CBIO_ERR_GENERAL;
229
    }
230
231
    sent = wolfSSL_BIO_write(ssl->biowr, buf, sz);
232
    if (sent <= 0) {
233
        if (ssl->biowr->type == WOLFSSL_BIO_SOCKET) {
234
        #ifdef USE_WOLFSSL_IO
235
            sent = TranslateIoError(sent);
236
        #endif
237
            return sent;
238
        }
239
        else if (ssl->biowr->type == WOLFSSL_BIO_BIO) {
240
            if (sent == WOLFSSL_BIO_ERROR) {
241
                WOLFSSL_MSG("\tWould Block");
242
                return WOLFSSL_CBIO_ERR_WANT_WRITE;
243
            }
244
        }
245
246
        /* If retry and write flags are set, return WANT_WRITE */
247
        if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_WRITE) &&
248
            (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
249
            return WOLFSSL_CBIO_ERR_WANT_WRITE;
250
        }
251
252
        return WOLFSSL_CBIO_ERR_GENERAL;
253
    }
254
    (void)ctx;
255
256
    return sent;
257
}
258
#endif /* !NO_BIO */
259
#endif /* OPENSSL_EXTRA */
260
261
262
#ifdef USE_WOLFSSL_IO
263
264
/* The receive embedded callback
265
 *  return : nb bytes read, or error
266
 */
267
int EmbedReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
268
0
{
269
0
    int recvd;
270
0
#ifndef WOLFSSL_LINUXKM
271
0
    int sd = *(int*)ctx;
272
#else
273
    struct socket *sd = (struct socket*)ctx;
274
#endif
275
276
0
    recvd = wolfIO_Recv(sd, buf, sz, ssl->rflags);
277
0
    if (recvd < 0) {
278
0
        WOLFSSL_MSG("Embed Receive error");
279
0
        return TranslateIoError(recvd);
280
0
    }
281
0
    else if (recvd == 0) {
282
0
        WOLFSSL_MSG("Embed receive connection closed");
283
0
        return WOLFSSL_CBIO_ERR_CONN_CLOSE;
284
0
    }
285
286
0
    return recvd;
287
0
}
288
289
/* The send embedded callback
290
 *  return : nb bytes sent, or error
291
 */
292
int EmbedSend(WOLFSSL* ssl, char *buf, int sz, void *ctx)
293
0
{
294
0
    int sent;
295
0
#ifndef WOLFSSL_LINUXKM
296
0
    int sd = *(int*)ctx;
297
#else
298
    struct socket *sd = (struct socket*)ctx;
299
#endif
300
301
#ifdef WOLFSSL_MAX_SEND_SZ
302
    if (sz > WOLFSSL_MAX_SEND_SZ)
303
        sz = WOLFSSL_MAX_SEND_SZ;
304
#endif
305
306
0
    sent = wolfIO_Send(sd, buf, sz, ssl->wflags);
307
0
    if (sent < 0) {
308
0
        WOLFSSL_MSG("Embed Send error");
309
0
        return TranslateIoError(sent);
310
0
    }
311
312
0
    return sent;
313
0
}
314
315
316
#ifdef WOLFSSL_DTLS
317
318
#include <wolfssl/wolfcrypt/sha.h>
319
320
#ifndef DTLS_SENDTO_FUNCTION
321
    #define DTLS_SENDTO_FUNCTION sendto
322
#endif
323
#ifndef DTLS_RECVFROM_FUNCTION
324
    #define DTLS_RECVFROM_FUNCTION recvfrom
325
#endif
326
327
static int sockAddrEqual(
328
    SOCKADDR_S *a, XSOCKLENT aLen, SOCKADDR_S *b, XSOCKLENT bLen)
329
{
330
    if (aLen != bLen)
331
        return 0;
332
333
    if (a->ss_family != b->ss_family)
334
        return 0;
335
336
    if (a->ss_family == AF_INET) {
337
338
        if (aLen < (XSOCKLENT)sizeof(SOCKADDR_IN))
339
            return 0;
340
341
        if (((SOCKADDR_IN*)a)->sin_port != ((SOCKADDR_IN*)b)->sin_port)
342
            return 0;
343
344
        if (((SOCKADDR_IN*)a)->sin_addr.s_addr !=
345
            ((SOCKADDR_IN*)b)->sin_addr.s_addr)
346
            return 0;
347
348
        return 1;
349
    }
350
351
#ifdef WOLFSSL_IPV6
352
    if (a->ss_family == AF_INET6) {
353
        SOCKADDR_IN6 *a6, *b6;
354
355
        if (aLen < (XSOCKLENT)sizeof(SOCKADDR_IN6))
356
            return 0;
357
358
        a6 = (SOCKADDR_IN6*)a;
359
        b6 = (SOCKADDR_IN6*)b;
360
361
        if (((SOCKADDR_IN6*)a)->sin6_port != ((SOCKADDR_IN6*)b)->sin6_port)
362
            return 0;
363
364
        if (XMEMCMP((void*)&a6->sin6_addr, (void*)&b6->sin6_addr,
365
                sizeof(a6->sin6_addr)) != 0)
366
            return 0;
367
368
        return 1;
369
    }
370
#endif /* WOLFSSL_HAVE_IPV6 */
371
372
    return 0;
373
}
374
375
static int isDGramSock(int sfd)
376
{
377
    int type = 0;
378
    XSOCKLENT length = sizeof(int); /* optvalue 'type' is of size int */
379
380
    if (getsockopt(sfd, SOL_SOCKET, SO_TYPE, &type, &length) == 0 &&
381
            type != SOCK_DGRAM) {
382
        return 0;
383
    }
384
    else {
385
        return 1;
386
    }
387
}
388
389
/* The receive embedded callback
390
 *  return : nb bytes read, or error
391
 */
392
int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx)
393
{
394
    WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
395
    int recvd;
396
    int sd = dtlsCtx->rfd;
397
    int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
398
    byte doDtlsTimeout;
399
    SOCKADDR_S lclPeer;
400
    SOCKADDR_S* peer;
401
    XSOCKLENT peerSz;
402
403
    WOLFSSL_ENTER("EmbedReceiveFrom()");
404
405
    if (dtlsCtx->connected) {
406
        peer = NULL;
407
    }
408
    else if (dtlsCtx->userSet) {
409
        peer = &lclPeer;
410
        XMEMSET(&lclPeer, 0, sizeof(lclPeer));
411
        peerSz = sizeof(lclPeer);
412
    }
413
    else {
414
        /* Store the peer address. It is used to calculate the DTLS cookie. */
415
        if (dtlsCtx->peer.sa == NULL) {
416
            dtlsCtx->peer.sa = (void*)XMALLOC(sizeof(SOCKADDR_S),
417
                    ssl->heap, DYNAMIC_TYPE_SOCKADDR);
418
            dtlsCtx->peer.sz = 0;
419
            if (dtlsCtx->peer.sa != NULL)
420
                dtlsCtx->peer.bufSz = sizeof(SOCKADDR_S);
421
            else
422
                dtlsCtx->peer.bufSz = 0;
423
        }
424
        peer = (SOCKADDR_S*)dtlsCtx->peer.sa;
425
        peerSz = dtlsCtx->peer.bufSz;
426
    }
427
428
    /* Don't use ssl->options.handShakeDone since it is true even if
429
     * we are in the process of renegotiation */
430
    doDtlsTimeout = ssl->options.handShakeState != HANDSHAKE_DONE;
431
432
#ifdef WOLFSSL_DTLS13
433
    if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
434
        doDtlsTimeout =
435
            doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL ||
436
            (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL);
437
    }
438
#endif /* WOLFSSL_DTLS13 */
439
440
    if (!doDtlsTimeout)
441
        dtls_timeout = 0;
442
443
    if (!wolfSSL_get_using_nonblock(ssl)) {
444
        #ifdef USE_WINDOWS_API
445
            DWORD timeout = dtls_timeout * 1000;
446
            #ifdef WOLFSSL_DTLS13
447
            if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
448
                IsAtLeastTLSv1_3(ssl->version))
449
                timeout /= 4;
450
            #endif /* WOLFSSL_DTLS13 */
451
        #else
452
            struct timeval timeout;
453
            XMEMSET(&timeout, 0, sizeof(timeout));
454
            #ifdef WOLFSSL_DTLS13
455
            if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
456
                IsAtLeastTLSv1_3(ssl->version)) {
457
                if (dtls_timeout >= 4)
458
                    timeout.tv_sec = dtls_timeout / 4;
459
                else
460
                    timeout.tv_usec = dtls_timeout * 1000000 / 4;
461
            }
462
            else
463
            #endif /* WOLFSSL_DTLS13 */
464
                timeout.tv_sec = dtls_timeout;
465
        #endif
466
        if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,
467
                       sizeof(timeout)) != 0) {
468
                WOLFSSL_MSG("setsockopt rcvtimeo failed");
469
        }
470
    }
471
#ifndef NO_ASN_TIME
472
    else if(IsSCR(ssl)) {
473
        if (ssl->dtls_start_timeout &&
474
                LowResTimer() - ssl->dtls_start_timeout > (word32)dtls_timeout) {
475
            ssl->dtls_start_timeout = 0;
476
            return WOLFSSL_CBIO_ERR_TIMEOUT;
477
        }
478
        else if (!ssl->dtls_start_timeout) {
479
            ssl->dtls_start_timeout = LowResTimer();
480
        }
481
    }
482
#endif /* !NO_ASN_TIME */
483
484
    recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags,
485
                      (SOCKADDR*)peer, peer != NULL ? &peerSz : NULL);
486
487
    /* From the RECV(2) man page
488
     * The returned address is truncated if the buffer provided is too small; in
489
     * this case, addrlen will return a value greater than was supplied to the
490
     * call.
491
     */
492
    if (dtlsCtx->connected) {
493
        /* No need to sanitize the value of peerSz */
494
    }
495
    else if (dtlsCtx->userSet) {
496
        /* Truncate peer size */
497
        if (peerSz > sizeof(lclPeer))
498
            peerSz = sizeof(lclPeer);
499
    }
500
    else {
501
        /* Truncate peer size */
502
        if (peerSz > dtlsCtx->peer.bufSz)
503
            peerSz = dtlsCtx->peer.bufSz;
504
    }
505
506
    recvd = TranslateReturnCode(recvd, sd);
507
508
    if (recvd < 0) {
509
        WOLFSSL_MSG("Embed Receive From error");
510
        recvd = TranslateIoError(recvd);
511
        if (recvd == WOLFSSL_CBIO_ERR_WANT_READ &&
512
            !wolfSSL_dtls_get_using_nonblock(ssl)) {
513
            recvd = WOLFSSL_CBIO_ERR_TIMEOUT;
514
        }
515
        return recvd;
516
    }
517
    else if (recvd == 0) {
518
        if (!isDGramSock(sd)) {
519
            /* Closed TCP connection */
520
            recvd = WOLFSSL_CBIO_ERR_CONN_CLOSE;
521
        }
522
        else {
523
            WOLFSSL_MSG("Ignoring 0-length datagram");
524
        }
525
        return recvd;
526
    }
527
    else if (dtlsCtx->connected) {
528
        /* Nothing to do */
529
    }
530
    else if (dtlsCtx->userSet) {
531
        /* Check we received the packet from the correct peer */
532
        if (dtlsCtx->peer.sz > 0 &&
533
            (peerSz != (XSOCKLENT)dtlsCtx->peer.sz ||
534
                !sockAddrEqual(peer, peerSz, (SOCKADDR_S*)dtlsCtx->peer.sa,
535
                    dtlsCtx->peer.sz))) {
536
            WOLFSSL_MSG("    Ignored packet from invalid peer");
537
            return WOLFSSL_CBIO_ERR_WANT_READ;
538
        }
539
    }
540
    else {
541
        /* Store size of saved address */
542
        dtlsCtx->peer.sz = peerSz;
543
    }
544
#ifndef NO_ASN_TIME
545
    ssl->dtls_start_timeout = 0;
546
#endif /* !NO_ASN_TIME */
547
548
    return recvd;
549
}
550
551
552
/* The send embedded callback
553
 *  return : nb bytes sent, or error
554
 */
555
int EmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx)
556
{
557
    WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
558
    int sd = dtlsCtx->wfd;
559
    int sent;
560
    const SOCKADDR_S* peer = NULL;
561
    XSOCKLENT peerSz = 0;
562
563
    WOLFSSL_ENTER("EmbedSendTo()");
564
565
    if (!isDGramSock(sd)) {
566
        /* Probably a TCP socket. peer and peerSz MUST be NULL and 0 */
567
    }
568
    else if (!dtlsCtx->connected) {
569
        peer   = (const SOCKADDR_S*)dtlsCtx->peer.sa;
570
        peerSz = dtlsCtx->peer.sz;
571
    }
572
573
    sent = (int)DTLS_SENDTO_FUNCTION(sd, buf, sz, ssl->wflags,
574
            (const SOCKADDR*)peer, peerSz);
575
576
    sent = TranslateReturnCode(sent, sd);
577
578
    if (sent < 0) {
579
        WOLFSSL_MSG("Embed Send To error");
580
        return TranslateIoError(sent);
581
    }
582
583
    return sent;
584
}
585
586
587
#ifdef WOLFSSL_MULTICAST
588
589
/* The alternate receive embedded callback for Multicast
590
 *  return : nb bytes read, or error
591
 */
592
int EmbedReceiveFromMcast(WOLFSSL *ssl, char *buf, int sz, void *ctx)
593
{
594
    WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
595
    int recvd;
596
    int sd = dtlsCtx->rfd;
597
598
    WOLFSSL_ENTER("EmbedReceiveFromMcast()");
599
600
    recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags, NULL, NULL);
601
602
    recvd = TranslateReturnCode(recvd, sd);
603
604
    if (recvd < 0) {
605
        WOLFSSL_MSG("Embed Receive From error");
606
        recvd = TranslateIoError(recvd);
607
        if (recvd == WOLFSSL_CBIO_ERR_WANT_READ &&
608
            !wolfSSL_dtls_get_using_nonblock(ssl)) {
609
            recvd = WOLFSSL_CBIO_ERR_TIMEOUT;
610
        }
611
        return recvd;
612
    }
613
614
    return recvd;
615
}
616
#endif /* WOLFSSL_MULTICAST */
617
618
619
/* The DTLS Generate Cookie callback
620
 *  return : number of bytes copied into buf, or error
621
 */
622
int EmbedGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx)
623
{
624
    int sd = ssl->wfd;
625
    SOCKADDR_S peer;
626
    XSOCKLENT peerSz = sizeof(peer);
627
    byte digest[WC_SHA256_DIGEST_SIZE];
628
    int  ret = 0;
629
630
    (void)ctx;
631
632
    XMEMSET(&peer, 0, sizeof(peer));
633
    if (getpeername(sd, (SOCKADDR*)&peer, &peerSz) != 0) {
634
        WOLFSSL_MSG("getpeername failed in EmbedGenerateCookie");
635
        return GEN_COOKIE_E;
636
    }
637
638
    ret = wc_Sha256Hash((byte*)&peer, peerSz, digest);
639
    if (ret != 0)
640
        return ret;
641
642
    if (sz > WC_SHA256_DIGEST_SIZE)
643
        sz = WC_SHA256_DIGEST_SIZE;
644
    XMEMCPY(buf, digest, sz);
645
646
    return sz;
647
}
648
#endif /* WOLFSSL_DTLS */
649
650
#ifdef WOLFSSL_SESSION_EXPORT
651
652
#ifdef WOLFSSL_DTLS
653
    static int EmbedGetPeerDTLS(WOLFSSL* ssl, char* ip, int* ipSz,
654
                                                 unsigned short* port, int* fam)
655
    {
656
        SOCKADDR_S peer;
657
        word32     peerSz;
658
        int        ret;
659
660
        /* get peer information stored in ssl struct */
661
        peerSz = sizeof(SOCKADDR_S);
662
        if ((ret = wolfSSL_dtls_get_peer(ssl, (void*)&peer, &peerSz))
663
                                                               != WOLFSSL_SUCCESS) {
664
            return ret;
665
        }
666
667
        /* extract family, ip, and port */
668
        *fam = ((SOCKADDR_S*)&peer)->ss_family;
669
        switch (*fam) {
670
            case WOLFSSL_IP4:
671
                if (XINET_NTOP(*fam, &(((SOCKADDR_IN*)&peer)->sin_addr),
672
                                                           ip, *ipSz) == NULL) {
673
                    WOLFSSL_MSG("XINET_NTOP error");
674
                    return SOCKET_ERROR_E;
675
                }
676
                *port = XNTOHS(((SOCKADDR_IN*)&peer)->sin_port);
677
                break;
678
679
            case WOLFSSL_IP6:
680
            #ifdef WOLFSSL_IPV6
681
                if (XINET_NTOP(*fam, &(((SOCKADDR_IN6*)&peer)->sin6_addr),
682
                                                           ip, *ipSz) == NULL) {
683
                    WOLFSSL_MSG("XINET_NTOP error");
684
                    return SOCKET_ERROR_E;
685
                }
686
                *port = XNTOHS(((SOCKADDR_IN6*)&peer)->sin6_port);
687
            #endif /* WOLFSSL_IPV6 */
688
                break;
689
690
            default:
691
                WOLFSSL_MSG("Unknown family type");
692
                return SOCKET_ERROR_E;
693
        }
694
        ip[*ipSz - 1] = '\0'; /* make sure has terminator */
695
        *ipSz = (word16)XSTRLEN(ip);
696
697
        return WOLFSSL_SUCCESS;
698
    }
699
700
    static int EmbedSetPeerDTLS(WOLFSSL* ssl, char* ip, int ipSz,
701
                                                   unsigned short port, int fam)
702
    {
703
        int    ret;
704
        SOCKADDR_S addr;
705
706
        /* sanity checks on arguments */
707
        if (ssl == NULL || ip == NULL || ipSz < 0 || ipSz > MAX_EXPORT_IP) {
708
            return BAD_FUNC_ARG;
709
        }
710
711
        addr.ss_family = fam;
712
        switch (addr.ss_family) {
713
            case WOLFSSL_IP4:
714
                if (XINET_PTON(addr.ss_family, ip,
715
                                     &(((SOCKADDR_IN*)&addr)->sin_addr)) <= 0) {
716
                    WOLFSSL_MSG("XINET_PTON error");
717
                    return SOCKET_ERROR_E;
718
                }
719
                ((SOCKADDR_IN*)&addr)->sin_port = XHTONS(port);
720
721
                /* peer sa is free'd in SSL_ResourceFree */
722
                if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN*)&addr,
723
                                          sizeof(SOCKADDR_IN)))!= WOLFSSL_SUCCESS) {
724
                    WOLFSSL_MSG("Import DTLS peer info error");
725
                    return ret;
726
                }
727
                break;
728
729
            case WOLFSSL_IP6:
730
            #ifdef WOLFSSL_IPV6
731
                if (XINET_PTON(addr.ss_family, ip,
732
                                   &(((SOCKADDR_IN6*)&addr)->sin6_addr)) <= 0) {
733
                    WOLFSSL_MSG("XINET_PTON error");
734
                    return SOCKET_ERROR_E;
735
                }
736
                ((SOCKADDR_IN6*)&addr)->sin6_port = XHTONS(port);
737
738
                /* peer sa is free'd in SSL_ResourceFree */
739
                if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN6*)&addr,
740
                                         sizeof(SOCKADDR_IN6)))!= WOLFSSL_SUCCESS) {
741
                    WOLFSSL_MSG("Import DTLS peer info error");
742
                    return ret;
743
                }
744
            #endif /* WOLFSSL_IPV6 */
745
                break;
746
747
            default:
748
                WOLFSSL_MSG("Unknown address family");
749
                return BUFFER_E;
750
        }
751
752
        return WOLFSSL_SUCCESS;
753
    }
754
#endif
755
756
    /* get the peer information in human readable form (ip, port, family)
757
     * default function assumes BSD sockets
758
     * can be overridden with wolfSSL_CTX_SetIOGetPeer
759
     */
760
    int EmbedGetPeer(WOLFSSL* ssl, char* ip, int* ipSz,
761
                                                 unsigned short* port, int* fam)
762
    {
763
        if (ssl == NULL || ip == NULL || ipSz == NULL ||
764
                                                  port == NULL || fam == NULL) {
765
            return BAD_FUNC_ARG;
766
        }
767
768
        if (ssl->options.dtls) {
769
        #ifdef WOLFSSL_DTLS
770
            return EmbedGetPeerDTLS(ssl, ip, ipSz, port, fam);
771
        #else
772
            return NOT_COMPILED_IN;
773
        #endif
774
        }
775
        else {
776
            *port = wolfSSL_get_fd(ssl);
777
            ip[0] = '\0';
778
            *ipSz = 0;
779
            *fam  = 0;
780
            return WOLFSSL_SUCCESS;
781
        }
782
    }
783
784
    /* set the peer information in human readable form (ip, port, family)
785
     * default function assumes BSD sockets
786
     * can be overridden with wolfSSL_CTX_SetIOSetPeer
787
     */
788
    int EmbedSetPeer(WOLFSSL* ssl, char* ip, int ipSz,
789
                                                   unsigned short port, int fam)
790
    {
791
        /* sanity checks on arguments */
792
        if (ssl == NULL || ip == NULL || ipSz < 0 || ipSz > MAX_EXPORT_IP) {
793
            return BAD_FUNC_ARG;
794
        }
795
796
        if (ssl->options.dtls) {
797
        #ifdef WOLFSSL_DTLS
798
            return EmbedSetPeerDTLS(ssl, ip, ipSz, port, fam);
799
        #else
800
            return NOT_COMPILED_IN;
801
        #endif
802
        }
803
        else {
804
            wolfSSL_set_fd(ssl, port);
805
            (void)fam;
806
            return WOLFSSL_SUCCESS;
807
        }
808
    }
809
#endif /* WOLFSSL_SESSION_EXPORT */
810
811
#ifdef WOLFSSL_LINUXKM
812
static int linuxkm_send(struct socket *socket, void *buf, int size,
813
    unsigned int flags)
814
{
815
    int ret;
816
    struct kvec vec = { .iov_base = buf, .iov_len = size };
817
    struct msghdr msg = { .msg_flags = flags };
818
    ret = kernel_sendmsg(socket, &msg, &vec, 1, size);
819
    return ret;
820
}
821
822
static int linuxkm_recv(struct socket *socket, void *buf, int size,
823
    unsigned int flags)
824
{
825
    int ret;
826
    struct kvec vec = { .iov_base = buf, .iov_len = size };
827
    struct msghdr msg = { .msg_flags = flags };
828
    ret = kernel_recvmsg(socket, &msg, &vec, 1, size, msg.msg_flags);
829
    return ret;
830
}
831
#endif /* WOLFSSL_LINUXKM */
832
833
834
int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags)
835
0
{
836
0
    int recvd;
837
838
0
    recvd = (int)RECV_FUNCTION(sd, buf, sz, rdFlags);
839
0
    recvd = TranslateReturnCode(recvd, sd);
840
841
0
    return recvd;
842
0
}
843
844
int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags)
845
0
{
846
0
    int sent;
847
848
0
    sent = (int)SEND_FUNCTION(sd, buf, sz, wrFlags);
849
0
    sent = TranslateReturnCode(sent, sd);
850
851
0
    return sent;
852
0
}
853
854
#endif /* USE_WOLFSSL_IO */
855
856
857
#ifdef HAVE_HTTP_CLIENT
858
859
#ifndef HAVE_IO_TIMEOUT
860
    #define io_timeout_sec 0
861
#else
862
863
    #ifndef DEFAULT_TIMEOUT_SEC
864
        #define DEFAULT_TIMEOUT_SEC 0 /* no timeout */
865
    #endif
866
867
    static int io_timeout_sec = DEFAULT_TIMEOUT_SEC;
868
869
    void wolfIO_SetTimeout(int to_sec)
870
    {
871
        io_timeout_sec = to_sec;
872
    }
873
874
    int wolfIO_SetBlockingMode(SOCKET_T sockfd, int non_blocking)
875
    {
876
        int ret = 0;
877
878
    #ifdef USE_WINDOWS_API
879
        unsigned long blocking = non_blocking;
880
        ret = ioctlsocket(sockfd, FIONBIO, &blocking);
881
        if (ret == SOCKET_ERROR)
882
            ret = -1;
883
    #else
884
        ret = fcntl(sockfd, F_GETFL, 0);
885
        if (ret >= 0) {
886
            if (non_blocking)
887
                ret |= O_NONBLOCK;
888
            else
889
                ret &= ~O_NONBLOCK;
890
            ret = fcntl(sockfd, F_SETFL, ret);
891
        }
892
    #endif
893
        if (ret < 0) {
894
            WOLFSSL_MSG("wolfIO_SetBlockingMode failed");
895
        }
896
897
        return ret;
898
    }
899
900
    int wolfIO_Select(SOCKET_T sockfd, int to_sec)
901
    {
902
        fd_set rfds, wfds;
903
        int nfds = 0;
904
        struct timeval timeout = { (to_sec > 0) ? to_sec : 0, 0};
905
        int ret;
906
907
    #ifndef USE_WINDOWS_API
908
        nfds = (int)sockfd + 1;
909
    #endif
910
911
        if ((sockfd < 0) || (sockfd >= FD_SETSIZE)) {
912
            WOLFSSL_MSG("socket fd out of FDSET range");
913
            return -1;
914
        }
915
916
        FD_ZERO(&rfds);
917
        FD_SET(sockfd, &rfds);
918
        wfds = rfds;
919
920
        ret = select(nfds, &rfds, &wfds, NULL, &timeout);
921
        if (ret == 0) {
922
        #ifdef DEBUG_HTTP
923
            fprintf(stderr, "Timeout: %d\n", ret);
924
        #endif
925
            return HTTP_TIMEOUT;
926
        }
927
        else if (ret > 0) {
928
            if (FD_ISSET(sockfd, &wfds)) {
929
                if (!FD_ISSET(sockfd, &rfds)) {
930
                    return 0;
931
                }
932
            }
933
        }
934
935
        WOLFSSL_MSG("Select error");
936
        return SOCKET_ERROR_E;
937
    }
938
#endif /* HAVE_IO_TIMEOUT */
939
940
static int wolfIO_Word16ToString(char* d, word16 number)
941
{
942
    int i = 0;
943
    word16 order = 10000;
944
    word16 digit;
945
946
    if (d == NULL)
947
        return i;
948
949
    if (number == 0)
950
        d[i++] = '0';
951
    else {
952
        while (order) {
953
            digit = number / order;
954
            if (i > 0 || digit != 0)
955
                d[i++] = (char)digit + '0';
956
            if (digit != 0)
957
                number %= digit * order;
958
959
            order = (order > 1) ? order / 10 : 0;
960
        }
961
    }
962
    d[i] = 0; /* null terminate */
963
964
    return i;
965
}
966
967
int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec)
968
{
969
#ifdef HAVE_SOCKADDR
970
    int ret = 0;
971
    SOCKADDR_S addr;
972
    int sockaddr_len;
973
#if defined(HAVE_GETADDRINFO)
974
    /* use getaddrinfo */
975
    ADDRINFO hints;
976
    ADDRINFO* answer = NULL;
977
    char strPort[6];
978
#else
979
    /* use gethostbyname */
980
#if !defined(WOLFSSL_USE_POPEN_HOST)
981
#if defined(__GLIBC__) && (__GLIBC__ >= 2) && defined(__USE_MISC) && \
982
    !defined(SINGLE_THREADED)
983
    HOSTENT entry_buf, *entry = NULL;
984
    char *ghbn_r_buf = NULL;
985
    int ghbn_r_errno;
986
#else
987
    HOSTENT *entry;
988
#endif
989
#endif
990
#ifdef WOLFSSL_IPV6
991
    SOCKADDR_IN6 *sin;
992
#else
993
    SOCKADDR_IN *sin;
994
#endif
995
#endif /* HAVE_SOCKADDR */
996
997
    if (sockfd == NULL || ip == NULL) {
998
        return -1;
999
    }
1000
1001
#if !defined(HAVE_GETADDRINFO)
1002
#ifdef WOLFSSL_IPV6
1003
    sockaddr_len = sizeof(SOCKADDR_IN6);
1004
#else
1005
    sockaddr_len = sizeof(SOCKADDR_IN);
1006
#endif
1007
#endif
1008
    XMEMSET(&addr, 0, sizeof(addr));
1009
1010
#ifdef WOLFIO_DEBUG
1011
    printf("TCP Connect: %s:%d\n", ip, port);
1012
#endif
1013
1014
    /* use gethostbyname for c99 */
1015
#if defined(HAVE_GETADDRINFO)
1016
    XMEMSET(&hints, 0, sizeof(hints));
1017
    hints.ai_family = AF_UNSPEC; /* detect IPv4 or IPv6 */
1018
    hints.ai_socktype = SOCK_STREAM;
1019
    hints.ai_protocol = IPPROTO_TCP;
1020
1021
    if (wolfIO_Word16ToString(strPort, port) == 0) {
1022
        WOLFSSL_MSG("invalid port number for responder");
1023
        return -1;
1024
    }
1025
1026
    if (getaddrinfo(ip, strPort, &hints, &answer) < 0 || answer == NULL) {
1027
        WOLFSSL_MSG("no addr info for responder");
1028
        return -1;
1029
    }
1030
1031
    sockaddr_len = answer->ai_addrlen;
1032
    XMEMCPY(&addr, answer->ai_addr, sockaddr_len);
1033
    freeaddrinfo(answer);
1034
#elif defined(WOLFSSL_USE_POPEN_HOST) && !defined(WOLFSSL_IPV6)
1035
    {
1036
        char host_ipaddr[4] = { 127, 0, 0, 1 };
1037
        int found = 1;
1038
1039
        if ((XSTRNCMP(ip, "localhost", 10) != 0) &&
1040
            (XSTRNCMP(ip, "127.0.0.1", 10) != 0)) {
1041
            FILE* fp;
1042
            char host_out[100];
1043
            char cmd[100];
1044
1045
            XSTRNCPY(cmd, "host ", 6);
1046
            XSTRNCAT(cmd, ip, 99 - XSTRLEN(cmd));
1047
            found = 0;
1048
            fp = popen(cmd, "r");
1049
            if (fp != NULL) {
1050
                while (fgets(host_out, sizeof(host_out), fp) != NULL) {
1051
                    int i;
1052
                    int j = 0;
1053
                    for (j = 0; host_out[j] != '\0'; j++) {
1054
                        if ((host_out[j] >= '0') && (host_out[j] <= '9')) {
1055
                            break;
1056
                        }
1057
                    }
1058
                    found = (host_out[j] >= '0') && (host_out[j] <= '9');
1059
                    if (!found) {
1060
                        continue;
1061
                    }
1062
1063
                    for (i = 0; i < 4; i++) {
1064
                        host_ipaddr[i] = atoi(host_out + j);
1065
                        while ((host_out[j] >= '0') && (host_out[j] <= '9')) {
1066
                            j++;
1067
                        }
1068
                        if (host_out[j] == '.') {
1069
                            j++;
1070
                            found &= (i != 3);
1071
                        }
1072
                        else {
1073
                            found &= (i == 3);
1074
                            break;
1075
                        }
1076
                    }
1077
                    if (found) {
1078
                        break;
1079
                    }
1080
                }
1081
                pclose(fp);
1082
            }
1083
        }
1084
        if (found) {
1085
            sin = (SOCKADDR_IN *)&addr;
1086
            sin->sin_family = AF_INET;
1087
            sin->sin_port = XHTONS(port);
1088
            XMEMCPY(&sin->sin_addr.s_addr, host_ipaddr, sizeof(host_ipaddr));
1089
        }
1090
        else {
1091
            WOLFSSL_MSG("no addr info for responder");
1092
            return -1;
1093
        }
1094
    }
1095
#else
1096
#if defined(__GLIBC__) && (__GLIBC__ >= 2) && defined(__USE_MISC) && \
1097
    !defined(SINGLE_THREADED)
1098
    /* 2048 is a magic number that empirically works.  the header and
1099
     * documentation provide no guidance on appropriate buffer size other than
1100
     * "if buf is too small, the functions will return ERANGE, and the call
1101
     * should be retried with a larger buffer."
1102
     */
1103
    ghbn_r_buf = (char *)XMALLOC(2048, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1104
    if (ghbn_r_buf != NULL) {
1105
        gethostbyname_r(ip, &entry_buf, ghbn_r_buf, 2048, &entry, &ghbn_r_errno);
1106
    }
1107
#else
1108
    entry = gethostbyname(ip);
1109
#endif
1110
1111
    if (entry) {
1112
    #ifdef WOLFSSL_IPV6
1113
        sin = (SOCKADDR_IN6 *)&addr;
1114
        sin->sin6_family = AF_INET6;
1115
        sin->sin6_port = XHTONS(port);
1116
        XMEMCPY(&sin->sin6_addr, entry->h_addr_list[0], entry->h_length);
1117
    #else
1118
        sin = (SOCKADDR_IN *)&addr;
1119
        sin->sin_family = AF_INET;
1120
        sin->sin_port = XHTONS(port);
1121
        XMEMCPY(&sin->sin_addr.s_addr, entry->h_addr_list[0], entry->h_length);
1122
    #endif
1123
    }
1124
1125
#if defined(__GLIBC__) && (__GLIBC__ >= 2) && defined(__USE_MISC) && \
1126
    !defined(SINGLE_THREADED)
1127
    XFREE(ghbn_r_buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1128
#endif
1129
1130
    if (entry == NULL) {
1131
        WOLFSSL_MSG("no addr info for responder");
1132
        return -1;
1133
    }
1134
#endif
1135
1136
    *sockfd = (SOCKET_T)socket(addr.ss_family, SOCK_STREAM, 0);
1137
#ifdef USE_WINDOWS_API
1138
    if (*sockfd == SOCKET_INVALID)
1139
#else
1140
    if (*sockfd <= SOCKET_INVALID)
1141
#endif
1142
    {
1143
        WOLFSSL_MSG("bad socket fd, out of fds?");
1144
        return -1;
1145
    }
1146
1147
#ifdef HAVE_IO_TIMEOUT
1148
    /* if timeout value provided then set socket non-blocking */
1149
    if (to_sec > 0) {
1150
        wolfIO_SetBlockingMode(*sockfd, 1);
1151
    }
1152
#else
1153
    (void)to_sec;
1154
#endif
1155
1156
    ret = connect(*sockfd, (SOCKADDR *)&addr, sockaddr_len);
1157
#ifdef HAVE_IO_TIMEOUT
1158
    if (ret != 0) {
1159
        if ((errno == EINPROGRESS) && (to_sec > 0)) {
1160
            /* wait for connect to complete */
1161
            ret = wolfIO_Select(*sockfd, to_sec);
1162
1163
            /* restore blocking mode */
1164
            wolfIO_SetBlockingMode(*sockfd, 0);
1165
        }
1166
    }
1167
#endif
1168
    if (ret != 0) {
1169
        WOLFSSL_MSG("Responder tcp connect failed");
1170
        CloseSocket(*sockfd);
1171
        *sockfd = SOCKET_INVALID;
1172
        return -1;
1173
    }
1174
    return ret;
1175
#else
1176
    (void)sockfd;
1177
    (void)ip;
1178
    (void)port;
1179
    (void)to_sec;
1180
    return -1;
1181
#endif /* HAVE_SOCKADDR */
1182
}
1183
1184
int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port)
1185
{
1186
#ifdef HAVE_SOCKADDR
1187
    int ret = 0;
1188
    SOCKADDR_S addr;
1189
    int sockaddr_len = sizeof(SOCKADDR_IN);
1190
    SOCKADDR_IN *sin = (SOCKADDR_IN *)&addr;
1191
1192
    if (sockfd == NULL || port < 1) {
1193
        return -1;
1194
    }
1195
1196
    XMEMSET(&addr, 0, sizeof(addr));
1197
1198
    sin->sin_family = AF_INET;
1199
    sin->sin_addr.s_addr = INADDR_ANY;
1200
    sin->sin_port = XHTONS(port);
1201
    *sockfd = (SOCKET_T)socket(AF_INET, SOCK_STREAM, 0);
1202
1203
    if (*sockfd < 0) {
1204
        WOLFSSL_MSG("socket failed");
1205
        *sockfd = SOCKET_INVALID;
1206
        return -1;
1207
    }
1208
1209
#if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\
1210
                   && !defined(WOLFSSL_KEIL_TCP_NET) && !defined(WOLFSSL_ZEPHYR)
1211
    {
1212
        int optval  = 1;
1213
        XSOCKLENT optlen = sizeof(optval);
1214
        ret = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, optlen);
1215
    }
1216
#endif
1217
1218
    if (ret == 0)
1219
        ret = bind(*sockfd, (SOCKADDR *)sin, sockaddr_len);
1220
    if (ret == 0)
1221
        ret = listen(*sockfd, SOMAXCONN);
1222
1223
    if (ret != 0) {
1224
        WOLFSSL_MSG("wolfIO_TcpBind failed");
1225
        CloseSocket(*sockfd);
1226
        *sockfd = SOCKET_INVALID;
1227
        ret = -1;
1228
    }
1229
1230
    return ret;
1231
#else
1232
    (void)sockfd;
1233
    (void)port;
1234
    return -1;
1235
#endif /* HAVE_SOCKADDR */
1236
}
1237
1238
#ifdef HAVE_SOCKADDR
1239
int wolfIO_TcpAccept(SOCKET_T sockfd, SOCKADDR* peer_addr, XSOCKLENT* peer_len)
1240
{
1241
    return (int)accept(sockfd, peer_addr, peer_len);
1242
}
1243
#endif /* HAVE_SOCKADDR */
1244
1245
#ifndef HTTP_SCRATCH_BUFFER_SIZE
1246
    #define HTTP_SCRATCH_BUFFER_SIZE 512
1247
#endif
1248
#ifndef MAX_URL_ITEM_SIZE
1249
    #define MAX_URL_ITEM_SIZE   80
1250
#endif
1251
1252
int wolfIO_DecodeUrl(const char* url, int urlSz, char* outName, char* outPath,
1253
    word16* outPort)
1254
{
1255
    int result = -1;
1256
1257
    if (url == NULL || urlSz == 0) {
1258
        if (outName)
1259
            *outName = 0;
1260
        if (outPath)
1261
            *outPath = 0;
1262
        if (outPort)
1263
            *outPort = 0;
1264
    }
1265
    else {
1266
        int i, cur;
1267
1268
        /* need to break the url down into scheme, address, and port */
1269
        /*     "http://example.com:8080/" */
1270
        /*     "http://[::1]:443/"        */
1271
        if (XSTRNCMP(url, "http://", 7) == 0) {
1272
            cur = 7;
1273
        } else cur = 0;
1274
1275
        i = 0;
1276
        if (url[cur] == '[') {
1277
            cur++;
1278
            /* copy until ']' */
1279
            while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0 &&
1280
                    url[cur] != ']') {
1281
                if (outName)
1282
                    outName[i] = url[cur];
1283
                i++; cur++;
1284
            }
1285
            cur++; /* skip ']' */
1286
        }
1287
        else {
1288
            while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0 &&
1289
                    url[cur] != ':' && url[cur] != '/') {
1290
                if (outName)
1291
                    outName[i] = url[cur];
1292
                i++; cur++;
1293
            }
1294
        }
1295
        if (outName)
1296
            outName[i] = 0;
1297
        /* Need to pick out the path after the domain name */
1298
1299
        if (cur < urlSz && url[cur] == ':') {
1300
            char port[6];
1301
            int j;
1302
            word32 bigPort = 0;
1303
            i = 0;
1304
            cur++;
1305
            while (i < 6 && cur < urlSz && url[cur] != 0 && url[cur] != '/') {
1306
                port[i] = url[cur];
1307
                i++; cur++;
1308
            }
1309
1310
            for (j = 0; j < i; j++) {
1311
                if (port[j] < '0' || port[j] > '9') return -1;
1312
                bigPort = (bigPort * 10) + (port[j] - '0');
1313
            }
1314
            if (outPort)
1315
                *outPort = (word16)bigPort;
1316
        }
1317
        else if (outPort)
1318
            *outPort = 80;
1319
1320
1321
        if (cur < urlSz && url[cur] == '/') {
1322
            i = 0;
1323
            while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0) {
1324
                if (outPath)
1325
                    outPath[i] = url[cur];
1326
                i++; cur++;
1327
            }
1328
            if (outPath)
1329
                outPath[i] = 0;
1330
        }
1331
        else if (outPath) {
1332
            outPath[0] = '/';
1333
            outPath[1] = 0;
1334
        }
1335
1336
        result = 0;
1337
    }
1338
1339
    return result;
1340
}
1341
1342
static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf,
1343
    int* recvBufSz, int chunkSz, char* start, int len, int dynType, void* heap)
1344
{
1345
    byte* newRecvBuf = NULL;
1346
    int newRecvSz = *recvBufSz + chunkSz;
1347
    int pos = 0;
1348
1349
    WOLFSSL_MSG("Processing HTTP response");
1350
#ifdef WOLFIO_DEBUG
1351
    printf("HTTP Chunk %d->%d\n", *recvBufSz, chunkSz);
1352
#endif
1353
1354
    (void)heap;
1355
    (void)dynType;
1356
1357
    if (chunkSz < 0 || len < 0) {
1358
        WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf invalid chunk or length size");
1359
        return MEMORY_E;
1360
    }
1361
1362
    if (newRecvSz <= 0) {
1363
        WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf new receive size overflow");
1364
        return MEMORY_E;
1365
    }
1366
1367
    newRecvBuf = (byte*)XMALLOC(newRecvSz, heap, dynType);
1368
    if (newRecvBuf == NULL) {
1369
        WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf malloc failed");
1370
        return MEMORY_E;
1371
    }
1372
1373
    /* if buffer already exists, then we are growing it */
1374
    if (*recvBuf) {
1375
        XMEMCPY(&newRecvBuf[pos], *recvBuf, *recvBufSz);
1376
        XFREE(*recvBuf, heap, dynType);
1377
        pos += *recvBufSz;
1378
        *recvBuf = NULL;
1379
    }
1380
1381
    /* copy the remainder of the httpBuf into the respBuf */
1382
    if (len != 0) {
1383
        if (pos + len <= newRecvSz) {
1384
            XMEMCPY(&newRecvBuf[pos], start, len);
1385
            pos += len;
1386
        }
1387
        else {
1388
            WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf bad size");
1389
            XFREE(newRecvBuf, heap, dynType);
1390
            return -1;
1391
        }
1392
    }
1393
1394
    /* receive the remainder of chunk */
1395
    while (len < chunkSz) {
1396
        int rxSz = wolfIO_Recv(sfd, (char*)&newRecvBuf[pos], chunkSz-len, 0);
1397
        if (rxSz > 0) {
1398
            len += rxSz;
1399
            pos += rxSz;
1400
        }
1401
        else {
1402
            WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf recv failed");
1403
            XFREE(newRecvBuf, heap, dynType);
1404
            return -1;
1405
        }
1406
    }
1407
1408
    *recvBuf = newRecvBuf;
1409
    *recvBufSz = newRecvSz;
1410
1411
    return 0;
1412
}
1413
1414
int wolfIO_HttpProcessResponse(int sfd, const char** appStrList,
1415
    byte** respBuf, byte* httpBuf, int httpBufSz, int dynType, void* heap)
1416
{
1417
    static const char HTTP_PROTO[] = "HTTP/1.";
1418
    static const char HTTP_STATUS_200[] = "200";
1419
    int result = 0;
1420
    int len = 0;
1421
    char *start, *end;
1422
    int respBufSz = 0;
1423
    int isChunked = 0, chunkSz = 0;
1424
    enum phr_state { phr_init, phr_http_start, phr_have_length, phr_have_type,
1425
                     phr_wait_end, phr_get_chunk_len, phr_get_chunk_data,
1426
                     phr_http_end
1427
    } state = phr_init;
1428
1429
    WOLFSSL_ENTER("wolfIO_HttpProcessResponse");
1430
1431
    *respBuf = NULL;
1432
    start = end = NULL;
1433
    do {
1434
        if (state == phr_get_chunk_data) {
1435
            /* get chunk of data */
1436
            result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz,
1437
                chunkSz, start, len, dynType, heap);
1438
1439
            state = (result != 0) ? phr_http_end : phr_get_chunk_len;
1440
            end = NULL;
1441
            len = 0;
1442
        }
1443
1444
        /* read data if no \r\n or first time */
1445
        if ((start == NULL) || (end == NULL)) {
1446
            result = wolfIO_Recv(sfd, (char*)httpBuf+len, httpBufSz-len-1, 0);
1447
            if (result > 0) {
1448
                len += result;
1449
                start = (char*)httpBuf;
1450
                start[len] = 0;
1451
            }
1452
            else {
1453
                result = TranslateReturnCode(result, sfd);
1454
                result = wolfSSL_LastError(result);
1455
                if (result == SOCKET_EWOULDBLOCK || result == SOCKET_EAGAIN) {
1456
                    return OCSP_WANT_READ;
1457
                }
1458
1459
                WOLFSSL_MSG("wolfIO_HttpProcessResponse recv http from peer failed");
1460
                return HTTP_RECV_ERR;
1461
            }
1462
        }
1463
        end = XSTRSTR(start, "\r\n"); /* locate end */
1464
1465
        /* handle incomplete rx */
1466
        if (end == NULL) {
1467
            if (len != 0)
1468
                XMEMMOVE(httpBuf, start, len);
1469
            start = end = NULL;
1470
        }
1471
        /* when start is "\r\n" */
1472
        else if (end == start) {
1473
            /* if waiting for end or need chunk len */
1474
            if (state == phr_wait_end || state == phr_get_chunk_len) {
1475
                state = (isChunked) ? phr_get_chunk_len : phr_http_end;
1476
                len -= 2; start += 2; /* skip \r\n */
1477
             }
1478
             else {
1479
                WOLFSSL_MSG("wolfIO_HttpProcessResponse header ended early");
1480
                return HTTP_HEADER_ERR;
1481
             }
1482
        }
1483
        else {
1484
            *end = 0; /* null terminate */
1485
            len -= (int)(end - start) + 2;
1486
                /* adjust len to remove the first line including the /r/n */
1487
1488
        #ifdef WOLFIO_DEBUG
1489
            printf("HTTP Resp: %s\n", start);
1490
        #endif
1491
1492
            switch (state) {
1493
                case phr_init:
1494
                    /* length of "HTTP/1.x 200" == 12*/
1495
                    if (XSTRLEN(start) < 12) {
1496
                        WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
1497
                            "too short.");
1498
                        return HTTP_HEADER_ERR;
1499
                    }
1500
                    if (XSTRNCASECMP(start, HTTP_PROTO,
1501
                                     sizeof(HTTP_PROTO) - 1) != 0) {
1502
                        WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
1503
                            "doesn't start with HTTP/1.");
1504
                        return HTTP_PROTO_ERR;
1505
                    }
1506
                    /* +2 for HTTP minor version and space between version and
1507
                     * status code. */
1508
                    start += sizeof(HTTP_PROTO) - 1 + 2 ;
1509
                    if (XSTRNCASECMP(start, HTTP_STATUS_200,
1510
                                     sizeof(HTTP_STATUS_200) - 1) != 0) {
1511
                        WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
1512
                            "doesn't have status code 200.");
1513
                        return HTTP_STATUS_ERR;
1514
                    }
1515
                    state = phr_http_start;
1516
                    break;
1517
                case phr_http_start:
1518
                case phr_have_length:
1519
                case phr_have_type:
1520
                    if (XSTRLEN(start) < 13) { /* 13 is the shortest of the following
1521
                                          next lines we're checking for. */
1522
                        WOLFSSL_MSG("wolfIO_HttpProcessResponse content type is too short.");
1523
                        return HTTP_VERSION_ERR;
1524
                    }
1525
1526
                    if (XSTRNCASECMP(start, "Content-Type:", 13) == 0) {
1527
                        int i;
1528
1529
                        start += 13;
1530
                        while (*start == ' ') start++;
1531
1532
                        /* try and match against appStrList */
1533
                        i = 0;
1534
                        while (appStrList[i] != NULL) {
1535
                            if (XSTRNCASECMP(start, appStrList[i],
1536
                                                XSTRLEN(appStrList[i])) == 0) {
1537
                                break;
1538
                            }
1539
                            i++;
1540
                        }
1541
                        if (appStrList[i] == NULL) {
1542
                            WOLFSSL_MSG("wolfIO_HttpProcessResponse appstr mismatch");
1543
                            return HTTP_APPSTR_ERR;
1544
                        }
1545
                        state = (state == phr_http_start) ? phr_have_type : phr_wait_end;
1546
                    }
1547
                    else if (XSTRNCASECMP(start, "Content-Length:", 15) == 0) {
1548
                        start += 15;
1549
                        while (*start == ' ') start++;
1550
                        chunkSz = XATOI(start);
1551
                        state = (state == phr_http_start) ? phr_have_length : phr_wait_end;
1552
                    }
1553
                    else if (XSTRNCASECMP(start, "Transfer-Encoding:", 18) == 0) {
1554
                        start += 18;
1555
                        while (*start == ' ') start++;
1556
                        if (XSTRNCASECMP(start, "chunked", 7) == 0) {
1557
                            isChunked = 1;
1558
                            state = (state == phr_http_start) ? phr_have_length : phr_wait_end;
1559
                        }
1560
                    }
1561
                    break;
1562
                case phr_get_chunk_len:
1563
                    chunkSz = (int)strtol(start, NULL, 16); /* hex format */
1564
                    state = (chunkSz == 0) ? phr_http_end : phr_get_chunk_data;
1565
                    break;
1566
                case phr_get_chunk_data:
1567
                    /* processing for chunk data done above, since \r\n isn't required */
1568
                case phr_wait_end:
1569
                case phr_http_end:
1570
                    /* do nothing */
1571
                    break;
1572
            } /* switch (state) */
1573
1574
            /* skip to end plus \r\n */
1575
            start = end + 2;
1576
        }
1577
    } while (state != phr_http_end);
1578
1579
    if (!isChunked) {
1580
        result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz, chunkSz,
1581
                                                    start, len, dynType, heap);
1582
    }
1583
1584
    if (result >= 0) {
1585
        result = respBufSz;
1586
    }
1587
    else {
1588
        WOLFSSL_ERROR(result);
1589
    }
1590
1591
    return result;
1592
}
1593
int wolfIO_HttpBuildRequest(const char *reqType, const char *domainName,
1594
                               const char *path, int pathLen, int reqSz, const char *contentType,
1595
                               byte *buf, int bufSize)
1596
{
1597
    return wolfIO_HttpBuildRequest_ex(reqType, domainName, path, pathLen, reqSz, contentType, "", buf, bufSize);
1598
}
1599
1600
    int wolfIO_HttpBuildRequest_ex(const char *reqType, const char *domainName,
1601
                                const char *path, int pathLen, int reqSz, const char *contentType,
1602
                                const char *exHdrs, byte *buf, int bufSize)
1603
    {
1604
    word32 reqTypeLen, domainNameLen, reqSzStrLen, contentTypeLen, exHdrsLen, maxLen;
1605
    char reqSzStr[6];
1606
    char* req = (char*)buf;
1607
    const char* blankStr = " ";
1608
    const char* http11Str = " HTTP/1.1";
1609
    const char* hostStr = "\r\nHost: ";
1610
    const char* contentLenStr = "\r\nContent-Length: ";
1611
    const char* contentTypeStr = "\r\nContent-Type: ";
1612
    const char* singleCrLfStr = "\r\n";
1613
    const char* doubleCrLfStr = "\r\n\r\n";
1614
    word32 blankStrLen, http11StrLen, hostStrLen, contentLenStrLen,
1615
        contentTypeStrLen, singleCrLfStrLen, doubleCrLfStrLen;
1616
1617
    reqTypeLen = (word32)XSTRLEN(reqType);
1618
    domainNameLen = (word32)XSTRLEN(domainName);
1619
    reqSzStrLen = wolfIO_Word16ToString(reqSzStr, (word16)reqSz);
1620
    contentTypeLen = (word32)XSTRLEN(contentType);
1621
1622
    blankStrLen = (word32)XSTRLEN(blankStr);
1623
    http11StrLen = (word32)XSTRLEN(http11Str);
1624
    hostStrLen = (word32)XSTRLEN(hostStr);
1625
    contentLenStrLen = (word32)XSTRLEN(contentLenStr);
1626
    contentTypeStrLen = (word32)XSTRLEN(contentTypeStr);
1627
1628
    if(exHdrs){
1629
        singleCrLfStrLen = (word32)XSTRLEN(singleCrLfStr);
1630
        exHdrsLen = (word32)XSTRLEN(exHdrs);
1631
    } else {
1632
        singleCrLfStrLen = 0;
1633
        exHdrsLen = 0;
1634
    }
1635
1636
    doubleCrLfStrLen = (word32)XSTRLEN(doubleCrLfStr);
1637
1638
    /* determine max length and check it */
1639
    maxLen =
1640
        reqTypeLen +
1641
        blankStrLen +
1642
        pathLen +
1643
        http11StrLen +
1644
        hostStrLen +
1645
        domainNameLen +
1646
        contentLenStrLen +
1647
        reqSzStrLen +
1648
        contentTypeStrLen +
1649
        contentTypeLen +
1650
        singleCrLfStrLen +
1651
        exHdrsLen +
1652
        doubleCrLfStrLen +
1653
        1 /* null term */;
1654
    if (maxLen > (word32)bufSize)
1655
        return 0;
1656
1657
    XSTRNCPY((char*)buf, reqType, bufSize);
1658
    buf += reqTypeLen; bufSize -= reqTypeLen;
1659
    XSTRNCPY((char*)buf, blankStr, bufSize);
1660
    buf += blankStrLen; bufSize -= blankStrLen;
1661
    XSTRNCPY((char*)buf, path, bufSize);
1662
    buf += pathLen; bufSize -= pathLen;
1663
    XSTRNCPY((char*)buf, http11Str, bufSize);
1664
    buf += http11StrLen; bufSize -= http11StrLen;
1665
    if (domainNameLen > 0) {
1666
        XSTRNCPY((char*)buf, hostStr, bufSize);
1667
        buf += hostStrLen; bufSize -= hostStrLen;
1668
        XSTRNCPY((char*)buf, domainName, bufSize);
1669
        buf += domainNameLen; bufSize -= domainNameLen;
1670
    }
1671
    if (reqSz > 0 && reqSzStrLen > 0) {
1672
        XSTRNCPY((char*)buf, contentLenStr, bufSize);
1673
        buf += contentLenStrLen; bufSize -= contentLenStrLen;
1674
        XSTRNCPY((char*)buf, reqSzStr, bufSize);
1675
        buf += reqSzStrLen; bufSize -= reqSzStrLen;
1676
    }
1677
    if (contentTypeLen > 0) {
1678
        XSTRNCPY((char*)buf, contentTypeStr, bufSize);
1679
        buf += contentTypeStrLen; bufSize -= contentTypeStrLen;
1680
        XSTRNCPY((char*)buf, contentType, bufSize);
1681
        buf += contentTypeLen; bufSize -= contentTypeLen;
1682
    }
1683
    if (exHdrsLen > 0)
1684
    {
1685
        XSTRNCPY((char *)buf, singleCrLfStr, bufSize);
1686
        buf += singleCrLfStrLen;
1687
        bufSize -= singleCrLfStrLen;
1688
        XSTRNCPY((char *)buf, exHdrs, bufSize);
1689
        buf += exHdrsLen;
1690
        bufSize -= exHdrsLen;
1691
    }
1692
    XSTRNCPY((char*)buf, doubleCrLfStr, bufSize);
1693
    buf += doubleCrLfStrLen;
1694
1695
#ifdef WOLFIO_DEBUG
1696
    printf("HTTP %s: %s", reqType, req);
1697
#endif
1698
1699
    /* calculate actual length based on original and new pointer */
1700
    return (int)((char*)buf - req);
1701
}
1702
1703
1704
#ifdef HAVE_OCSP
1705
1706
int wolfIO_HttpBuildRequestOcsp(const char* domainName, const char* path,
1707
                                    int ocspReqSz, byte* buf, int bufSize)
1708
{
1709
    const char *cacheCtl = "Cache-Control: no-cache";
1710
    return wolfIO_HttpBuildRequest_ex("POST", domainName, path, (int)XSTRLEN(path),
1711
        ocspReqSz, "application/ocsp-request", cacheCtl, buf, bufSize);
1712
}
1713
1714
/* return: >0 OCSP Response Size
1715
 *         -1 error */
1716
int wolfIO_HttpProcessResponseOcsp(int sfd, byte** respBuf,
1717
                                       byte* httpBuf, int httpBufSz, void* heap)
1718
{
1719
    const char* appStrList[] = {
1720
        "application/ocsp-response",
1721
        NULL
1722
    };
1723
1724
    return wolfIO_HttpProcessResponse(sfd, appStrList,
1725
        respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_OCSP, heap);
1726
}
1727
1728
/* in default wolfSSL callback ctx is the heap pointer */
1729
int EmbedOcspLookup(void* ctx, const char* url, int urlSz,
1730
                        byte* ocspReqBuf, int ocspReqSz, byte** ocspRespBuf)
1731
{
1732
    SOCKET_T sfd = SOCKET_INVALID;
1733
    word16   port;
1734
    int      ret = -1;
1735
#ifdef WOLFSSL_SMALL_STACK
1736
    char*    path;
1737
    char*    domainName;
1738
#else
1739
    char     path[MAX_URL_ITEM_SIZE];
1740
    char     domainName[MAX_URL_ITEM_SIZE];
1741
#endif
1742
1743
#ifdef WOLFSSL_SMALL_STACK
1744
    path = (char*)XMALLOC(MAX_URL_ITEM_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1745
    if (path == NULL)
1746
        return MEMORY_E;
1747
1748
    domainName = (char*)XMALLOC(MAX_URL_ITEM_SIZE, NULL,
1749
            DYNAMIC_TYPE_TMP_BUFFER);
1750
    if (domainName == NULL) {
1751
        XFREE(path, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1752
        return MEMORY_E;
1753
    }
1754
#endif
1755
1756
    if (ocspReqBuf == NULL || ocspReqSz == 0) {
1757
        WOLFSSL_MSG("OCSP request is required for lookup");
1758
    }
1759
    else if (ocspRespBuf == NULL) {
1760
        WOLFSSL_MSG("Cannot save OCSP response");
1761
    }
1762
    else if (wolfIO_DecodeUrl(url, urlSz, domainName, path, &port) < 0) {
1763
        WOLFSSL_MSG("Unable to decode OCSP URL");
1764
    }
1765
    else {
1766
        /* Note, the library uses the EmbedOcspRespFree() callback to
1767
         * free this buffer. */
1768
        int   httpBufSz = HTTP_SCRATCH_BUFFER_SIZE;
1769
        byte* httpBuf   = (byte*)XMALLOC(httpBufSz, ctx, DYNAMIC_TYPE_OCSP);
1770
1771
        if (httpBuf == NULL) {
1772
            WOLFSSL_MSG("Unable to create OCSP response buffer");
1773
        }
1774
        else {
1775
            httpBufSz = wolfIO_HttpBuildRequestOcsp(domainName, path, ocspReqSz,
1776
                                                            httpBuf, httpBufSz);
1777
1778
            ret = wolfIO_TcpConnect(&sfd, domainName, port, io_timeout_sec);
1779
            if (ret != 0) {
1780
                WOLFSSL_MSG("OCSP Responder connection failed");
1781
            }
1782
            else if (wolfIO_Send(sfd, (char*)httpBuf, httpBufSz, 0) !=
1783
                                                                    httpBufSz) {
1784
                WOLFSSL_MSG("OCSP http request failed");
1785
            }
1786
            else if (wolfIO_Send(sfd, (char*)ocspReqBuf, ocspReqSz, 0) !=
1787
                                                                    ocspReqSz) {
1788
                WOLFSSL_MSG("OCSP ocsp request failed");
1789
            }
1790
            else {
1791
                ret = wolfIO_HttpProcessResponseOcsp(sfd, ocspRespBuf, httpBuf,
1792
                                                 HTTP_SCRATCH_BUFFER_SIZE, ctx);
1793
            }
1794
            if (sfd != SOCKET_INVALID)
1795
                CloseSocket(sfd);
1796
            XFREE(httpBuf, ctx, DYNAMIC_TYPE_OCSP);
1797
        }
1798
    }
1799
1800
#ifdef WOLFSSL_SMALL_STACK
1801
    XFREE(path,       NULL, DYNAMIC_TYPE_TMP_BUFFER);
1802
    XFREE(domainName, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1803
#endif
1804
1805
    return ret;
1806
}
1807
1808
/* in default callback ctx is heap hint */
1809
void EmbedOcspRespFree(void* ctx, byte *resp)
1810
{
1811
    if (resp)
1812
        XFREE(resp, ctx, DYNAMIC_TYPE_OCSP);
1813
1814
    (void)ctx;
1815
}
1816
#endif /* HAVE_OCSP */
1817
1818
1819
#if defined(HAVE_CRL) && defined(HAVE_CRL_IO)
1820
1821
int wolfIO_HttpBuildRequestCrl(const char* url, int urlSz,
1822
    const char* domainName, byte* buf, int bufSize)
1823
{
1824
    const char *cacheCtl = "Cache-Control: no-cache";
1825
    return wolfIO_HttpBuildRequest_ex("GET", domainName, url, urlSz, 0, "",
1826
                                   cacheCtl, buf, bufSize);
1827
}
1828
1829
int wolfIO_HttpProcessResponseCrl(WOLFSSL_CRL* crl, int sfd, byte* httpBuf,
1830
    int httpBufSz)
1831
{
1832
    int ret;
1833
    byte *respBuf = NULL;
1834
1835
    const char* appStrList[] = {
1836
        "application/pkix-crl",
1837
        "application/x-pkcs7-crl",
1838
        NULL
1839
    };
1840
1841
1842
    ret = wolfIO_HttpProcessResponse(sfd, appStrList,
1843
        &respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_CRL, crl->heap);
1844
    if (ret >= 0) {
1845
        ret = BufferLoadCRL(crl, respBuf, ret, WOLFSSL_FILETYPE_ASN1, 0);
1846
    }
1847
    XFREE(respBuf, crl->heap, DYNAMIC_TYPE_CRL);
1848
1849
    return ret;
1850
}
1851
1852
int EmbedCrlLookup(WOLFSSL_CRL* crl, const char* url, int urlSz)
1853
{
1854
    SOCKET_T sfd = SOCKET_INVALID;
1855
    word16   port;
1856
    int      ret = -1;
1857
#ifdef WOLFSSL_SMALL_STACK
1858
    char*    domainName;
1859
#else
1860
    char     domainName[MAX_URL_ITEM_SIZE];
1861
#endif
1862
1863
#ifdef WOLFSSL_SMALL_STACK
1864
    domainName = (char*)XMALLOC(MAX_URL_ITEM_SIZE, crl->heap,
1865
                                                       DYNAMIC_TYPE_TMP_BUFFER);
1866
    if (domainName == NULL) {
1867
        return MEMORY_E;
1868
    }
1869
#endif
1870
1871
    if (wolfIO_DecodeUrl(url, urlSz, domainName, NULL, &port) < 0) {
1872
        WOLFSSL_MSG("Unable to decode CRL URL");
1873
    }
1874
    else {
1875
        int   httpBufSz = HTTP_SCRATCH_BUFFER_SIZE;
1876
        byte* httpBuf   = (byte*)XMALLOC(httpBufSz, crl->heap,
1877
                                                              DYNAMIC_TYPE_CRL);
1878
        if (httpBuf == NULL) {
1879
            WOLFSSL_MSG("Unable to create CRL response buffer");
1880
        }
1881
        else {
1882
            httpBufSz = wolfIO_HttpBuildRequestCrl(url, urlSz, domainName,
1883
                httpBuf, httpBufSz);
1884
1885
            ret = wolfIO_TcpConnect(&sfd, domainName, port, io_timeout_sec);
1886
            if (ret != 0) {
1887
                WOLFSSL_MSG("CRL connection failed");
1888
            }
1889
            else if (wolfIO_Send(sfd, (char*)httpBuf, httpBufSz, 0)
1890
                                                                 != httpBufSz) {
1891
                WOLFSSL_MSG("CRL http get failed");
1892
            }
1893
            else {
1894
                ret = wolfIO_HttpProcessResponseCrl(crl, sfd, httpBuf,
1895
                                                      HTTP_SCRATCH_BUFFER_SIZE);
1896
            }
1897
            if (sfd != SOCKET_INVALID)
1898
                CloseSocket(sfd);
1899
            XFREE(httpBuf, crl->heap, DYNAMIC_TYPE_CRL);
1900
        }
1901
    }
1902
1903
#ifdef WOLFSSL_SMALL_STACK
1904
    XFREE(domainName, crl->heap, DYNAMIC_TYPE_TMP_BUFFER);
1905
#endif
1906
1907
    return ret;
1908
}
1909
#endif /* HAVE_CRL && HAVE_CRL_IO */
1910
1911
#endif /* HAVE_HTTP_CLIENT */
1912
1913
1914
1915
void wolfSSL_CTX_SetIORecv(WOLFSSL_CTX *ctx, CallbackIORecv CBIORecv)
1916
36
{
1917
36
    if (ctx) {
1918
36
        ctx->CBIORecv = CBIORecv;
1919
    #ifdef OPENSSL_EXTRA
1920
        ctx->cbioFlag |= WOLFSSL_CBIO_RECV;
1921
    #endif
1922
36
    }
1923
36
}
1924
1925
1926
void wolfSSL_CTX_SetIOSend(WOLFSSL_CTX *ctx, CallbackIOSend CBIOSend)
1927
36
{
1928
36
    if (ctx) {
1929
36
        ctx->CBIOSend = CBIOSend;
1930
    #ifdef OPENSSL_EXTRA
1931
        ctx->cbioFlag |= WOLFSSL_CBIO_SEND;
1932
    #endif
1933
36
    }
1934
36
}
1935
1936
1937
/* sets the IO callback to use for receives at WOLFSSL level */
1938
void wolfSSL_SSLSetIORecv(WOLFSSL *ssl, CallbackIORecv CBIORecv)
1939
0
{
1940
0
    if (ssl) {
1941
0
        ssl->CBIORecv = CBIORecv;
1942
    #ifdef OPENSSL_EXTRA
1943
        ssl->cbioFlag |= WOLFSSL_CBIO_RECV;
1944
    #endif
1945
0
    }
1946
0
}
1947
1948
1949
/* sets the IO callback to use for sends at WOLFSSL level */
1950
void wolfSSL_SSLSetIOSend(WOLFSSL *ssl, CallbackIOSend CBIOSend)
1951
0
{
1952
0
    if (ssl) {
1953
0
        ssl->CBIOSend = CBIOSend;
1954
    #ifdef OPENSSL_EXTRA
1955
        ssl->cbioFlag |= WOLFSSL_CBIO_SEND;
1956
    #endif
1957
0
    }
1958
0
}
1959
1960
1961
void wolfSSL_SetIOReadCtx(WOLFSSL* ssl, void *rctx)
1962
0
{
1963
0
    if (ssl)
1964
0
        ssl->IOCB_ReadCtx = rctx;
1965
0
}
1966
1967
1968
void wolfSSL_SetIOWriteCtx(WOLFSSL* ssl, void *wctx)
1969
0
{
1970
0
    if (ssl)
1971
0
        ssl->IOCB_WriteCtx = wctx;
1972
0
}
1973
1974
1975
void* wolfSSL_GetIOReadCtx(WOLFSSL* ssl)
1976
0
{
1977
0
    if (ssl)
1978
0
        return ssl->IOCB_ReadCtx;
1979
1980
0
    return NULL;
1981
0
}
1982
1983
1984
void* wolfSSL_GetIOWriteCtx(WOLFSSL* ssl)
1985
0
{
1986
0
    if (ssl)
1987
0
        return ssl->IOCB_WriteCtx;
1988
1989
0
    return NULL;
1990
0
}
1991
1992
1993
void wolfSSL_SetIOReadFlags(WOLFSSL* ssl, int flags)
1994
0
{
1995
0
    if (ssl)
1996
0
        ssl->rflags = flags;
1997
0
}
1998
1999
2000
void wolfSSL_SetIOWriteFlags(WOLFSSL* ssl, int flags)
2001
0
{
2002
0
    if (ssl)
2003
0
        ssl->wflags = flags;
2004
0
}
2005
2006
2007
#ifdef WOLFSSL_DTLS
2008
2009
void wolfSSL_CTX_SetGenCookie(WOLFSSL_CTX* ctx, CallbackGenCookie cb)
2010
{
2011
    if (ctx)
2012
        ctx->CBIOCookie = cb;
2013
}
2014
2015
2016
void wolfSSL_SetCookieCtx(WOLFSSL* ssl, void *ctx)
2017
{
2018
    if (ssl)
2019
        ssl->IOCB_CookieCtx = ctx;
2020
}
2021
2022
2023
void* wolfSSL_GetCookieCtx(WOLFSSL* ssl)
2024
{
2025
    if (ssl)
2026
        return ssl->IOCB_CookieCtx;
2027
2028
    return NULL;
2029
}
2030
#endif /* WOLFSSL_DTLS */
2031
2032
#ifdef WOLFSSL_SESSION_EXPORT
2033
2034
void wolfSSL_CTX_SetIOGetPeer(WOLFSSL_CTX* ctx, CallbackGetPeer cb)
2035
{
2036
    if (ctx)
2037
        ctx->CBGetPeer = cb;
2038
}
2039
2040
2041
void wolfSSL_CTX_SetIOSetPeer(WOLFSSL_CTX* ctx, CallbackSetPeer cb)
2042
{
2043
    if (ctx)
2044
        ctx->CBSetPeer = cb;
2045
}
2046
2047
#endif /* WOLFSSL_SESSION_EXPORT */
2048
2049
2050
#ifdef HAVE_NETX
2051
2052
/* The NetX receive callback
2053
 *  return :  bytes read, or error
2054
 */
2055
int NetX_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
2056
{
2057
    NetX_Ctx* nxCtx = (NetX_Ctx*)ctx;
2058
    ULONG left;
2059
    ULONG total;
2060
    ULONG copied = 0;
2061
    UINT  status;
2062
2063
    (void)ssl;
2064
2065
    if (nxCtx == NULL || nxCtx->nxSocket == NULL) {
2066
        WOLFSSL_MSG("NetX Recv NULL parameters");
2067
        return WOLFSSL_CBIO_ERR_GENERAL;
2068
    }
2069
2070
    if (nxCtx->nxPacket == NULL) {
2071
        status = nx_tcp_socket_receive(nxCtx->nxSocket, &nxCtx->nxPacket,
2072
                                       nxCtx->nxWait);
2073
        if (status != NX_SUCCESS) {
2074
            WOLFSSL_MSG("NetX Recv receive error");
2075
            return WOLFSSL_CBIO_ERR_GENERAL;
2076
        }
2077
    }
2078
2079
    if (nxCtx->nxPacket) {
2080
        status = nx_packet_length_get(nxCtx->nxPacket, &total);
2081
        if (status != NX_SUCCESS) {
2082
            WOLFSSL_MSG("NetX Recv length get error");
2083
            return WOLFSSL_CBIO_ERR_GENERAL;
2084
        }
2085
2086
        left = total - nxCtx->nxOffset;
2087
        status = nx_packet_data_extract_offset(nxCtx->nxPacket, nxCtx->nxOffset,
2088
                                               buf, sz, &copied);
2089
        if (status != NX_SUCCESS) {
2090
            WOLFSSL_MSG("NetX Recv data extract offset error");
2091
            return WOLFSSL_CBIO_ERR_GENERAL;
2092
        }
2093
2094
        nxCtx->nxOffset += copied;
2095
2096
        if (copied == left) {
2097
            WOLFSSL_MSG("NetX Recv Drained packet");
2098
            nx_packet_release(nxCtx->nxPacket);
2099
            nxCtx->nxPacket = NULL;
2100
            nxCtx->nxOffset = 0;
2101
        }
2102
    }
2103
2104
    return copied;
2105
}
2106
2107
2108
/* The NetX send callback
2109
 *  return : bytes sent, or error
2110
 */
2111
int NetX_Send(WOLFSSL* ssl, char *buf, int sz, void *ctx)
2112
{
2113
    NetX_Ctx*       nxCtx = (NetX_Ctx*)ctx;
2114
    NX_PACKET*      packet;
2115
    NX_PACKET_POOL* pool;   /* shorthand */
2116
    UINT            status;
2117
2118
    (void)ssl;
2119
2120
    if (nxCtx == NULL || nxCtx->nxSocket == NULL) {
2121
        WOLFSSL_MSG("NetX Send NULL parameters");
2122
        return WOLFSSL_CBIO_ERR_GENERAL;
2123
    }
2124
2125
    pool = nxCtx->nxSocket->nx_tcp_socket_ip_ptr->nx_ip_default_packet_pool;
2126
    status = nx_packet_allocate(pool, &packet, NX_TCP_PACKET,
2127
                                nxCtx->nxWait);
2128
    if (status != NX_SUCCESS) {
2129
        WOLFSSL_MSG("NetX Send packet alloc error");
2130
        return WOLFSSL_CBIO_ERR_GENERAL;
2131
    }
2132
2133
    status = nx_packet_data_append(packet, buf, sz, pool, nxCtx->nxWait);
2134
    if (status != NX_SUCCESS) {
2135
        nx_packet_release(packet);
2136
        WOLFSSL_MSG("NetX Send data append error");
2137
        return WOLFSSL_CBIO_ERR_GENERAL;
2138
    }
2139
2140
    status = nx_tcp_socket_send(nxCtx->nxSocket, packet, nxCtx->nxWait);
2141
    if (status != NX_SUCCESS) {
2142
        nx_packet_release(packet);
2143
        WOLFSSL_MSG("NetX Send socket send error");
2144
        return WOLFSSL_CBIO_ERR_GENERAL;
2145
    }
2146
2147
    return sz;
2148
}
2149
2150
2151
/* like set_fd, but for default NetX context */
2152
void wolfSSL_SetIO_NetX(WOLFSSL* ssl, NX_TCP_SOCKET* nxSocket, ULONG waitOption)
2153
{
2154
    if (ssl) {
2155
        ssl->nxCtx.nxSocket = nxSocket;
2156
        ssl->nxCtx.nxWait   = waitOption;
2157
    }
2158
}
2159
2160
#endif /* HAVE_NETX */
2161
2162
2163
#ifdef MICRIUM
2164
2165
/* Micrium uTCP/IP port, using the NetSock API
2166
 * TCP and UDP are currently supported with the callbacks below.
2167
 *
2168
 * WOLFSSL_SESSION_EXPORT is not yet supported, would need EmbedGetPeer()
2169
 * and EmbedSetPeer() callbacks implemented.
2170
 *
2171
 * HAVE_CRL is not yet supported, would need an EmbedCrlLookup()
2172
 * callback implemented.
2173
 *
2174
 * HAVE_OCSP is not yet supported, would need an EmbedOCSPLookup()
2175
 * callback implemented.
2176
 */
2177
2178
/* The Micrium uTCP/IP send callback
2179
 * return : bytes sent, or error
2180
 */
2181
int MicriumSend(WOLFSSL* ssl, char* buf, int sz, void* ctx)
2182
{
2183
    NET_SOCK_ID sd = *(int*)ctx;
2184
    NET_SOCK_RTN_CODE ret;
2185
    NET_ERR err;
2186
2187
    ret = NetSock_TxData(sd, buf, sz, ssl->wflags, &err);
2188
    if (ret < 0) {
2189
        WOLFSSL_MSG("Embed Send error");
2190
2191
        if (err == NET_ERR_TX) {
2192
            WOLFSSL_MSG("\tWould block");
2193
            return WOLFSSL_CBIO_ERR_WANT_WRITE;
2194
2195
        } else {
2196
            WOLFSSL_MSG("\tGeneral error");
2197
            return WOLFSSL_CBIO_ERR_GENERAL;
2198
        }
2199
    }
2200
2201
    return ret;
2202
}
2203
2204
/* The Micrium uTCP/IP receive callback
2205
 *  return : nb bytes read, or error
2206
 */
2207
int MicriumReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
2208
{
2209
    NET_SOCK_ID sd = *(int*)ctx;
2210
    NET_SOCK_RTN_CODE ret;
2211
    NET_ERR err;
2212
2213
    #ifdef WOLFSSL_DTLS
2214
    {
2215
        int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
2216
        /* Don't use ssl->options.handShakeDone since it is true even if
2217
         * we are in the process of renegotiation */
2218
        byte doDtlsTimeout = ssl->options.handShakeState != HANDSHAKE_DONE;
2219
        #ifdef WOLFSSL_DTLS13
2220
        if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
2221
            doDtlsTimeout =
2222
                doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL ||
2223
                (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL);
2224
        }
2225
        #endif /* WOLFSSL_DTLS13 */
2226
2227
        if (!doDtlsTimeout)
2228
            dtls_timeout = 0;
2229
2230
        if (!wolfSSL_dtls_get_using_nonblock(ssl)) {
2231
            /* needs timeout in milliseconds */
2232
            #ifdef WOLFSSL_DTLS13
2233
            if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
2234
                IsAtLeastTLSv1_3(ssl->version)) {
2235
                dtls_timeout = (1000 * dtls_timeout) / 4;
2236
            } else
2237
            #endif /* WOLFSSL_DTLS13 */
2238
                dtls_timeout = 1000 * dtls_timeout;
2239
            NetSock_CfgTimeoutRxQ_Set(sd, dtls_timeout, &err);
2240
            if (err != NET_SOCK_ERR_NONE) {
2241
                WOLFSSL_MSG("NetSock_CfgTimeoutRxQ_Set failed");
2242
            }
2243
        }
2244
    }
2245
    #endif
2246
2247
    ret = NetSock_RxData(sd, buf, sz, ssl->rflags, &err);
2248
    if (ret < 0) {
2249
        WOLFSSL_MSG("Embed Receive error");
2250
2251
        if (err == NET_ERR_RX || err == NET_SOCK_ERR_RX_Q_EMPTY ||
2252
            err == NET_ERR_FAULT_LOCK_ACQUIRE) {
2253
            if (!wolfSSL_dtls(ssl) || wolfSSL_dtls_get_using_nonblock(ssl)) {
2254
                WOLFSSL_MSG("\tWould block");
2255
                return WOLFSSL_CBIO_ERR_WANT_READ;
2256
            }
2257
            else {
2258
                WOLFSSL_MSG("\tSocket timeout");
2259
                return WOLFSSL_CBIO_ERR_TIMEOUT;
2260
            }
2261
2262
        } else if (err == NET_SOCK_ERR_CLOSED) {
2263
            WOLFSSL_MSG("Embed receive connection closed");
2264
            return WOLFSSL_CBIO_ERR_CONN_CLOSE;
2265
2266
        } else {
2267
            WOLFSSL_MSG("\tGeneral error");
2268
            return WOLFSSL_CBIO_ERR_GENERAL;
2269
        }
2270
    }
2271
2272
    return ret;
2273
}
2274
2275
/* The Micrium uTCP/IP receivefrom callback
2276
 *  return : nb bytes read, or error
2277
 */
2278
int MicriumReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx)
2279
{
2280
    WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
2281
    NET_SOCK_ID       sd = dtlsCtx->rfd;
2282
    NET_SOCK_ADDR     peer;
2283
    NET_SOCK_ADDR_LEN peerSz = sizeof(peer);
2284
    NET_SOCK_RTN_CODE ret;
2285
    NET_ERR err;
2286
2287
    WOLFSSL_ENTER("MicriumReceiveFrom()");
2288
2289
#ifdef WOLFSSL_DTLS
2290
    {
2291
        int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
2292
        /* Don't use ssl->options.handShakeDone since it is true even if
2293
         * we are in the process of renegotiation */
2294
        byte doDtlsTimeout = ssl->options.handShakeState != HANDSHAKE_DONE;
2295
2296
        #ifdef WOLFSSL_DTLS13
2297
        if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
2298
            doDtlsTimeout =
2299
                doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL ||
2300
                (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL);
2301
        }
2302
        #endif /* WOLFSSL_DTLS13 */
2303
2304
        if (!doDtlsTimeout)
2305
            dtls_timeout = 0;
2306
2307
        if (!wolfSSL_dtls_get_using_nonblock(ssl)) {
2308
            /* needs timeout in milliseconds */
2309
            #ifdef WOLFSSL_DTLS13
2310
            if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
2311
                IsAtLeastTLSv1_3(ssl->version)) {
2312
                dtls_timeout = (1000 * dtls_timeout) / 4;
2313
            } else
2314
            #endif /* WOLFSSL_DTLS13 */
2315
                dtls_timeout = 1000 * dtls_timeout;
2316
            NetSock_CfgTimeoutRxQ_Set(sd, dtls_timeout, &err);
2317
            if (err != NET_SOCK_ERR_NONE) {
2318
                WOLFSSL_MSG("NetSock_CfgTimeoutRxQ_Set failed");
2319
            }
2320
        }
2321
    }
2322
#endif /* WOLFSSL_DTLS */
2323
2324
    ret = NetSock_RxDataFrom(sd, buf, sz, ssl->rflags, &peer, &peerSz,
2325
                             0, 0, 0, &err);
2326
    if (ret < 0) {
2327
        WOLFSSL_MSG("Embed Receive From error");
2328
2329
        if (err == NET_ERR_RX || err == NET_SOCK_ERR_RX_Q_EMPTY ||
2330
            err == NET_ERR_FAULT_LOCK_ACQUIRE) {
2331
            if (wolfSSL_dtls_get_using_nonblock(ssl)) {
2332
                WOLFSSL_MSG("\tWould block");
2333
                return WOLFSSL_CBIO_ERR_WANT_READ;
2334
            }
2335
            else {
2336
                WOLFSSL_MSG("\tSocket timeout");
2337
                return WOLFSSL_CBIO_ERR_TIMEOUT;
2338
            }
2339
        } else {
2340
            WOLFSSL_MSG("\tGeneral error");
2341
            return WOLFSSL_CBIO_ERR_GENERAL;
2342
        }
2343
    }
2344
    else {
2345
        if (dtlsCtx->peer.sz > 0
2346
                && peerSz != (NET_SOCK_ADDR_LEN)dtlsCtx->peer.sz
2347
                && XMEMCMP(&peer, dtlsCtx->peer.sa, peerSz) != 0) {
2348
            WOLFSSL_MSG("\tIgnored packet from invalid peer");
2349
            return WOLFSSL_CBIO_ERR_WANT_READ;
2350
        }
2351
    }
2352
2353
    return ret;
2354
}
2355
2356
/* The Micrium uTCP/IP sendto callback
2357
 *  return : nb bytes sent, or error
2358
 */
2359
int MicriumSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx)
2360
{
2361
    WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
2362
    NET_SOCK_ID sd = dtlsCtx->wfd;
2363
    NET_SOCK_RTN_CODE ret;
2364
    NET_ERR err;
2365
2366
    WOLFSSL_ENTER("MicriumSendTo()");
2367
2368
    ret = NetSock_TxDataTo(sd, buf, sz, ssl->wflags,
2369
                           (NET_SOCK_ADDR*)dtlsCtx->peer.sa,
2370
                           (NET_SOCK_ADDR_LEN)dtlsCtx->peer.sz,
2371
                           &err);
2372
    if (err < 0) {
2373
        WOLFSSL_MSG("Embed Send To error");
2374
2375
        if (err == NET_ERR_TX) {
2376
            WOLFSSL_MSG("\tWould block");
2377
            return WOLFSSL_CBIO_ERR_WANT_WRITE;
2378
2379
        } else {
2380
            WOLFSSL_MSG("\tGeneral error");
2381
            return WOLFSSL_CBIO_ERR_GENERAL;
2382
        }
2383
    }
2384
2385
    return ret;
2386
}
2387
2388
/* Micrium DTLS Generate Cookie callback
2389
 *  return : number of bytes copied into buf, or error
2390
 */
2391
int MicriumGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx)
2392
{
2393
    NET_SOCK_ADDR peer;
2394
    NET_SOCK_ADDR_LEN peerSz = sizeof(peer);
2395
    byte digest[WC_SHA_DIGEST_SIZE];
2396
    int  ret = 0;
2397
2398
    (void)ctx;
2399
2400
    XMEMSET(&peer, 0, sizeof(peer));
2401
    if (wolfSSL_dtls_get_peer(ssl, (void*)&peer,
2402
                              (unsigned int*)&peerSz) != WOLFSSL_SUCCESS) {
2403
        WOLFSSL_MSG("getpeername failed in MicriumGenerateCookie");
2404
        return GEN_COOKIE_E;
2405
    }
2406
2407
    ret = wc_ShaHash((byte*)&peer, peerSz, digest);
2408
    if (ret != 0)
2409
        return ret;
2410
2411
    if (sz > WC_SHA_DIGEST_SIZE)
2412
        sz = WC_SHA_DIGEST_SIZE;
2413
    XMEMCPY(buf, digest, sz);
2414
2415
    return sz;
2416
}
2417
2418
#endif /* MICRIUM */
2419
2420
#if defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
2421
2422
#include <os/os_error.h>
2423
#include <os/os_mbuf.h>
2424
#include <os/os_mempool.h>
2425
2426
#define MB_NAME "wolfssl_mb"
2427
2428
typedef struct Mynewt_Ctx {
2429
        struct mn_socket *mnSocket;          /* send/recv socket handler */
2430
        struct mn_sockaddr_in mnSockAddrIn;  /* socket address */
2431
        struct os_mbuf *mnPacket;            /* incoming packet handle
2432
                                                for short reads */
2433
        int reading;                         /* reading flag */
2434
2435
        /* private */
2436
        void *mnMemBuffer;                   /* memory buffer for mempool */
2437
        struct os_mempool mnMempool;         /* mempool */
2438
        struct os_mbuf_pool mnMbufpool;      /* mbuf pool */
2439
} Mynewt_Ctx;
2440
2441
void mynewt_ctx_clear(void *ctx) {
2442
    Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
2443
    if(!mynewt_ctx) return;
2444
2445
    if(mynewt_ctx->mnPacket) {
2446
        os_mbuf_free_chain(mynewt_ctx->mnPacket);
2447
        mynewt_ctx->mnPacket = NULL;
2448
    }
2449
    os_mempool_clear(&mynewt_ctx->mnMempool);
2450
    XFREE(mynewt_ctx->mnMemBuffer, 0, 0);
2451
    XFREE(mynewt_ctx, 0, 0);
2452
}
2453
2454
/* return Mynewt_Ctx instance */
2455
void* mynewt_ctx_new() {
2456
    int rc = 0;
2457
    Mynewt_Ctx *mynewt_ctx;
2458
    int mem_buf_count = MYNEWT_VAL(WOLFSSL_MNSOCK_MEM_BUF_COUNT);
2459
    int mem_buf_size = MYNEWT_VAL(WOLFSSL_MNSOCK_MEM_BUF_SIZE);
2460
    int mempool_bytes = OS_MEMPOOL_BYTES(mem_buf_count, mem_buf_size);
2461
2462
    mynewt_ctx = (Mynewt_Ctx *)XMALLOC(sizeof(struct Mynewt_Ctx),
2463
                                       NULL, DYNAMIC_TYPE_TMP_BUFFER);
2464
    if(!mynewt_ctx) return NULL;
2465
2466
    XMEMSET(mynewt_ctx, 0, sizeof(Mynewt_Ctx));
2467
    mynewt_ctx->mnMemBuffer = (void *)XMALLOC(mempool_bytes, 0, 0);
2468
    if(!mynewt_ctx->mnMemBuffer) {
2469
        mynewt_ctx_clear((void*)mynewt_ctx);
2470
        return NULL;
2471
    }
2472
2473
    rc = os_mempool_init(&mynewt_ctx->mnMempool,
2474
                         mem_buf_count, mem_buf_size,
2475
                         mynewt_ctx->mnMemBuffer, MB_NAME);
2476
    if(rc != 0) {
2477
        mynewt_ctx_clear((void*)mynewt_ctx);
2478
        return NULL;
2479
    }
2480
    rc = os_mbuf_pool_init(&mynewt_ctx->mnMbufpool, &mynewt_ctx->mnMempool,
2481
                           mem_buf_count, mem_buf_size);
2482
    if(rc != 0) {
2483
        mynewt_ctx_clear((void*)mynewt_ctx);
2484
        return NULL;
2485
    }
2486
2487
    return mynewt_ctx;
2488
}
2489
2490
static void mynewt_sock_writable(void *arg, int err);
2491
static void mynewt_sock_readable(void *arg, int err);
2492
static const union mn_socket_cb mynewt_sock_cbs = {
2493
    .socket.writable = mynewt_sock_writable,
2494
    .socket.readable = mynewt_sock_readable,
2495
};
2496
static void mynewt_sock_writable(void *arg, int err)
2497
{
2498
    /* do nothing */
2499
}
2500
static void mynewt_sock_readable(void *arg, int err)
2501
{
2502
    Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx *)arg;
2503
    if (err && mynewt_ctx->reading) {
2504
        mynewt_ctx->reading = 0;
2505
    }
2506
}
2507
2508
/* The Mynewt receive callback
2509
 *  return :  bytes read, or error
2510
 */
2511
int Mynewt_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
2512
{
2513
    Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
2514
    int rc = 0;
2515
    struct mn_sockaddr_in from;
2516
    struct os_mbuf *m;
2517
    int read_sz = 0;
2518
    word16 total;
2519
2520
    if (mynewt_ctx == NULL || mynewt_ctx->mnSocket == NULL) {
2521
        WOLFSSL_MSG("Mynewt Recv NULL parameters");
2522
        return WOLFSSL_CBIO_ERR_GENERAL;
2523
    }
2524
2525
    if(mynewt_ctx->mnPacket == NULL) {
2526
        mynewt_ctx->mnPacket = os_mbuf_get_pkthdr(&mynewt_ctx->mnMbufpool, 0);
2527
        if(mynewt_ctx->mnPacket == NULL) {
2528
            return MEMORY_E;
2529
        }
2530
2531
        mynewt_ctx->reading = 1;
2532
        while(mynewt_ctx->reading && rc == 0) {
2533
            rc = mn_recvfrom(mynewt_ctx->mnSocket, &m, (struct mn_sockaddr *) &from);
2534
            if(rc == MN_ECONNABORTED) {
2535
                rc = 0;
2536
                mynewt_ctx->reading = 0;
2537
                break;
2538
            }
2539
            if (!(rc == 0 || rc == MN_EAGAIN)) {
2540
                WOLFSSL_MSG("Mynewt Recv receive error");
2541
                mynewt_ctx->reading = 0;
2542
                break;
2543
            }
2544
            if(rc == 0) {
2545
                int len = OS_MBUF_PKTLEN(m);
2546
                if(len == 0) {
2547
                    break;
2548
                }
2549
                rc = os_mbuf_appendfrom(mynewt_ctx->mnPacket, m, 0, len);
2550
                if(rc != 0) {
2551
                    WOLFSSL_MSG("Mynewt Recv os_mbuf_appendfrom error");
2552
                    break;
2553
                }
2554
                os_mbuf_free_chain(m);
2555
                m = NULL;
2556
            } else if(rc == MN_EAGAIN) {
2557
                /* continue to until reading all of packet data. */
2558
                rc = 0;
2559
                break;
2560
            }
2561
        }
2562
        if(rc != 0) {
2563
            mynewt_ctx->reading = 0;
2564
            os_mbuf_free_chain(mynewt_ctx->mnPacket);
2565
            mynewt_ctx->mnPacket = NULL;
2566
            return rc;
2567
        }
2568
    }
2569
2570
    if(mynewt_ctx->mnPacket) {
2571
        total = OS_MBUF_PKTLEN(mynewt_ctx->mnPacket);
2572
        read_sz = (total >= sz)? sz : total;
2573
2574
        os_mbuf_copydata(mynewt_ctx->mnPacket, 0, read_sz, (void*)buf);
2575
        os_mbuf_adj(mynewt_ctx->mnPacket, read_sz);
2576
2577
        if (read_sz == total) {
2578
            WOLFSSL_MSG("Mynewt Recv Drained packet");
2579
            os_mbuf_free_chain(mynewt_ctx->mnPacket);
2580
            mynewt_ctx->mnPacket = NULL;
2581
        }
2582
    }
2583
2584
    return read_sz;
2585
}
2586
2587
/* The Mynewt send callback
2588
 *  return : bytes sent, or error
2589
 */
2590
int Mynewt_Send(WOLFSSL* ssl, char *buf, int sz, void *ctx)
2591
{
2592
    Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
2593
    int rc = 0;
2594
    struct os_mbuf *m;
2595
    int write_sz = 0;
2596
    m = os_msys_get_pkthdr(sz, 0);
2597
    if (!m) {
2598
        WOLFSSL_MSG("Mynewt Send os_msys_get_pkthdr error");
2599
        return WOLFSSL_CBIO_ERR_GENERAL;
2600
    }
2601
    rc = os_mbuf_copyinto(m, 0, buf, sz);
2602
    if (rc != 0) {
2603
        WOLFSSL_MSG("Mynewt Send os_mbuf_copyinto error");
2604
        os_mbuf_free_chain(m);
2605
        return rc;
2606
    }
2607
    rc = mn_sendto(mynewt_ctx->mnSocket, m, (struct mn_sockaddr *)&mynewt_ctx->mnSockAddrIn);
2608
    if(rc != 0) {
2609
        WOLFSSL_MSG("Mynewt Send mn_sendto error");
2610
        os_mbuf_free_chain(m);
2611
        return rc;
2612
    }
2613
    write_sz = sz;
2614
    return write_sz;
2615
}
2616
2617
/* like set_fd, but for default NetX context */
2618
void wolfSSL_SetIO_Mynewt(WOLFSSL* ssl, struct mn_socket* mnSocket, struct mn_sockaddr_in* mnSockAddrIn)
2619
{
2620
    if (ssl && ssl->mnCtx) {
2621
        Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx *)ssl->mnCtx;
2622
        mynewt_ctx->mnSocket = mnSocket;
2623
        XMEMCPY(&mynewt_ctx->mnSockAddrIn, mnSockAddrIn, sizeof(struct mn_sockaddr_in));
2624
        mn_socket_set_cbs(mynewt_ctx->mnSocket, mnSocket, &mynewt_sock_cbs);
2625
    }
2626
}
2627
2628
#endif /* defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP) */
2629
2630
#ifdef WOLFSSL_UIP
2631
#include <uip.h>
2632
#include <stdio.h>
2633
2634
/* uIP TCP/IP port, using the native tcp/udp socket api.
2635
 * TCP and UDP are currently supported with the callbacks below.
2636
 *
2637
 */
2638
/* The uIP tcp send callback
2639
 * return : bytes sent, or error
2640
 */
2641
int uIPSend(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
2642
{
2643
    uip_wolfssl_ctx *ctx = (struct uip_wolfssl_ctx *)_ctx;
2644
    int ret;
2645
    unsigned int max_sendlen;
2646
    int total_written = 0;
2647
    (void)ssl;
2648
    do {
2649
        unsigned int bytes_left = sz - total_written;
2650
        max_sendlen = tcp_socket_max_sendlen(&ctx->conn.tcp);
2651
        if (bytes_left > max_sendlen) {
2652
            fprintf(stderr, "uIPSend: Send limited by buffer\r\n");
2653
            bytes_left = max_sendlen;
2654
        }
2655
        if (bytes_left == 0) {
2656
            fprintf(stderr, "uIPSend: Buffer full!\r\n");
2657
            break;
2658
        }
2659
        ret = tcp_socket_send(&ctx->conn.tcp, (unsigned char *)buf + total_written, bytes_left);
2660
        if (ret <= 0)
2661
            break;
2662
        total_written += ret;
2663
    } while(total_written < sz);
2664
    if (total_written == 0)
2665
        return WOLFSSL_CBIO_ERR_WANT_WRITE;
2666
    return total_written;
2667
}
2668
2669
int uIPSendTo(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
2670
{
2671
    uip_wolfssl_ctx *ctx = (struct uip_wolfssl_ctx *)_ctx;
2672
    int ret = 0;
2673
    (void)ssl;
2674
    ret = udp_socket_sendto(&ctx->conn.udp, (unsigned char *)buf, sz, &ctx->peer_addr, ctx->peer_port );
2675
    if (ret == 0)
2676
        return WOLFSSL_CBIO_ERR_WANT_WRITE;
2677
    return ret;
2678
}
2679
2680
/* The uIP uTCP/IP receive callback
2681
 *  return : nb bytes read, or error
2682
 */
2683
int uIPReceive(WOLFSSL *ssl, char *buf, int sz, void *_ctx)
2684
{
2685
    uip_wolfssl_ctx *ctx = (uip_wolfssl_ctx *)_ctx;
2686
    if (!ctx || !ctx->ssl_rx_databuf)
2687
        return -1;
2688
    (void)ssl;
2689
    if (ctx->ssl_rb_len > 0) {
2690
        if (sz > ctx->ssl_rb_len - ctx->ssl_rb_off)
2691
            sz = ctx->ssl_rb_len - ctx->ssl_rb_off;
2692
        XMEMCPY(buf, ctx->ssl_rx_databuf + ctx->ssl_rb_off, sz);
2693
        ctx->ssl_rb_off += sz;
2694
        if (ctx->ssl_rb_off >= ctx->ssl_rb_len) {
2695
            ctx->ssl_rb_len = 0;
2696
            ctx->ssl_rb_off = 0;
2697
        }
2698
        return sz;
2699
    } else {
2700
        return WOLFSSL_CBIO_ERR_WANT_READ;
2701
    }
2702
}
2703
2704
/* uIP DTLS Generate Cookie callback
2705
 *  return : number of bytes copied into buf, or error
2706
 */
2707
int uIPGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *_ctx)
2708
{
2709
    uip_wolfssl_ctx *ctx = (uip_wolfssl_ctx *)_ctx;
2710
    byte token[32];
2711
    byte digest[WC_SHA_DIGEST_SIZE];
2712
    int  ret = 0;
2713
    XMEMSET(token, 0, sizeof(token));
2714
    XMEMCPY(token, &ctx->peer_addr, sizeof(uip_ipaddr_t));
2715
    XMEMCPY(token + sizeof(uip_ipaddr_t), &ctx->peer_port, sizeof(word16));
2716
    ret = wc_ShaHash(token, sizeof(uip_ipaddr_t) + sizeof(word16), digest);
2717
    if (ret != 0)
2718
        return ret;
2719
    if (sz > WC_SHA_DIGEST_SIZE)
2720
        sz = WC_SHA_DIGEST_SIZE;
2721
    XMEMCPY(buf, digest, sz);
2722
    return sz;
2723
}
2724
2725
#endif /* WOLFSSL_UIP */
2726
2727
#ifdef WOLFSSL_GNRC
2728
2729
#include <net/sock.h>
2730
#include <net/sock/tcp.h>
2731
#include <stdio.h>
2732
2733
/* GNRC TCP/IP port, using the native tcp/udp socket api.
2734
 * TCP and UDP are currently supported with the callbacks below.
2735
 *
2736
 */
2737
/* The GNRC tcp send callback
2738
 * return : bytes sent, or error
2739
 */
2740
2741
int GNRC_SendTo(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
2742
{
2743
    sock_tls_t *ctx = (sock_tls_t *)_ctx;
2744
    int ret = 0;
2745
    (void)ssl;
2746
    if (!ctx)
2747
        return WOLFSSL_CBIO_ERR_GENERAL;
2748
    ret = sock_udp_send(&ctx->conn.udp, (unsigned char *)buf, sz, &ctx->peer_addr);
2749
    if (ret == 0)
2750
        return WOLFSSL_CBIO_ERR_WANT_WRITE;
2751
    return ret;
2752
}
2753
2754
/* The GNRC TCP/IP receive callback
2755
 *  return : nb bytes read, or error
2756
 */
2757
int GNRC_ReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *_ctx)
2758
{
2759
    sock_udp_ep_t ep;
2760
    int ret;
2761
    word32 timeout = wolfSSL_dtls_get_current_timeout(ssl) * 1000000;
2762
    sock_tls_t *ctx = (sock_tls_t *)_ctx;
2763
    if (!ctx)
2764
        return WOLFSSL_CBIO_ERR_GENERAL;
2765
    (void)ssl;
2766
    if (wolfSSL_get_using_nonblock(ctx->ssl)) {
2767
        timeout = 0;
2768
    }
2769
    ret = sock_udp_recv(&ctx->conn.udp, buf, sz, timeout, &ep);
2770
    if (ret > 0) {
2771
        if (ctx->peer_addr.port == 0)
2772
            XMEMCPY(&ctx->peer_addr, &ep, sizeof(sock_udp_ep_t));
2773
    }
2774
    if (ret == -ETIMEDOUT) {
2775
        return WOLFSSL_CBIO_ERR_WANT_READ;
2776
    }
2777
    return ret;
2778
}
2779
2780
/* GNRC DTLS Generate Cookie callback
2781
 *  return : number of bytes copied into buf, or error
2782
 */
2783
#define GNRC_MAX_TOKEN_SIZE (32)
2784
int GNRC_GenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *_ctx)
2785
{
2786
    sock_tls_t *ctx = (sock_tls_t *)_ctx;
2787
    if (!ctx)
2788
        return WOLFSSL_CBIO_ERR_GENERAL;
2789
    byte token[GNRC_MAX_TOKEN_SIZE];
2790
    byte digest[WC_SHA_DIGEST_SIZE];
2791
    int  ret = 0;
2792
    size_t token_size = sizeof(sock_udp_ep_t);
2793
    (void)ssl;
2794
    if (token_size > GNRC_MAX_TOKEN_SIZE)
2795
        token_size = GNRC_MAX_TOKEN_SIZE;
2796
    XMEMSET(token, 0, GNRC_MAX_TOKEN_SIZE);
2797
    XMEMCPY(token, &ctx->peer_addr, token_size);
2798
    ret = wc_ShaHash(token, token_size, digest);
2799
    if (ret != 0)
2800
        return ret;
2801
    if (sz > WC_SHA_DIGEST_SIZE)
2802
        sz = WC_SHA_DIGEST_SIZE;
2803
    XMEMCPY(buf, digest, sz);
2804
    return sz;
2805
}
2806
2807
#endif /* WOLFSSL_GNRC */
2808
2809
#ifdef WOLFSSL_LWIP_NATIVE
2810
int LwIPNativeSend(WOLFSSL* ssl, char* buf, int sz, void* ctx)
2811
{
2812
    err_t ret;
2813
    WOLFSSL_LWIP_NATIVE_STATE* nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)ctx;
2814
2815
    ret = tcp_write(nlwip->pcb, buf, sz, TCP_WRITE_FLAG_COPY);
2816
    if (ret != ERR_OK) {
2817
        sz = -1;
2818
    }
2819
2820
    return sz;
2821
}
2822
2823
2824
int LwIPNativeReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx)
2825
{
2826
    struct pbuf *current, *head;
2827
    WOLFSSL_LWIP_NATIVE_STATE* nlwip;
2828
    int ret = 0;
2829
2830
    if (ctx == NULL) {
2831
        return WOLFSSL_CBIO_ERR_GENERAL;
2832
    }
2833
    nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)ctx;
2834
2835
    current = nlwip->pbuf;
2836
    if (current == NULL || sz > current->tot_len) {
2837
        WOLFSSL_MSG("LwIP native pbuf list is null or not enough data, want read");
2838
        ret = WOLFSSL_CBIO_ERR_WANT_READ;
2839
    }
2840
    else {
2841
        int read = 0; /* total amount read */
2842
        head = nlwip->pbuf; /* save pointer to current head */
2843
2844
        /* loop through buffers reading data */
2845
        while (current != NULL) {
2846
            int len; /* current amount to be read */
2847
2848
            len = (current->len - nlwip->pulled < sz) ?
2849
                                            (current->len - nlwip->pulled) : sz;
2850
2851
            if (read + len > sz) {
2852
                /* should never be hit but have sanity check before use */
2853
                return WOLFSSL_CBIO_ERR_GENERAL;
2854
            }
2855
2856
            /* check if is a partial read from before */
2857
            XMEMCPY(&buf[read],
2858
                   (const char *)&(((char *)(current->payload))[nlwip->pulled]),
2859
2860
                    len);
2861
            nlwip->pulled = nlwip->pulled + len;
2862
            if (nlwip->pulled >= current->len) {
2863
                WOLFSSL_MSG("Native LwIP read full pbuf");
2864
                nlwip->pbuf = current->next;
2865
                current = nlwip->pbuf;
2866
                nlwip->pulled = 0;
2867
            }
2868
            read = read + len;
2869
            ret  = read;
2870
2871
            /* read enough break out */
2872
            if (read >= sz) {
2873
                /* if more pbuf's are left in the chain then increment the
2874
                 * ref count for next in chain and free all from begining till
2875
                 * next */
2876
                if (current != NULL) {
2877
                    pbuf_ref(current);
2878
                }
2879
2880
                /* ack and start free'ing from the current head of the chain */
2881
                pbuf_free(head);
2882
                break;
2883
            }
2884
        }
2885
    }
2886
    WOLFSSL_LEAVE("LwIPNativeReceive", ret);
2887
    return ret;
2888
}
2889
2890
2891
static err_t LwIPNativeReceiveCB(void* cb, struct tcp_pcb* pcb,
2892
                                struct pbuf* pbuf, err_t err)
2893
{
2894
    WOLFSSL_LWIP_NATIVE_STATE* nlwip;
2895
2896
    if (cb == NULL || pcb == NULL) {
2897
        WOLFSSL_MSG("Expected callback was null, abort");
2898
        return ERR_ABRT;
2899
    }
2900
2901
    nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)cb;
2902
    if (pbuf == NULL && err == ERR_OK) {
2903
        return ERR_OK;
2904
    }
2905
2906
    if (nlwip->pbuf == NULL) {
2907
        nlwip->pbuf = pbuf;
2908
    }
2909
    else {
2910
        if (nlwip->pbuf != pbuf) {
2911
            tcp_recved(nlwip->pcb, pbuf->tot_len);
2912
            pbuf_cat(nlwip->pbuf, pbuf); /* add chain to head */
2913
        }
2914
    }
2915
2916
    if (nlwip->recv_fn) {
2917
        return nlwip->recv_fn(nlwip->arg, pcb, pbuf, err);
2918
    }
2919
2920
    WOLFSSL_LEAVE("LwIPNativeReceiveCB", nlwip->pbuf->tot_len);
2921
    return ERR_OK;
2922
}
2923
2924
2925
static err_t LwIPNativeSentCB(void* cb, struct tcp_pcb* pcb, u16_t len)
2926
{
2927
    WOLFSSL_LWIP_NATIVE_STATE* nlwip;
2928
2929
    if (cb == NULL || pcb == NULL) {
2930
        WOLFSSL_MSG("Expected callback was null, abort");
2931
        return ERR_ABRT;
2932
    }
2933
2934
    nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)cb;
2935
    if (nlwip->sent_fn) {
2936
        return nlwip->sent_fn(nlwip->arg, pcb, len);
2937
    }
2938
    return ERR_OK;
2939
}
2940
2941
2942
int wolfSSL_SetIO_LwIP(WOLFSSL* ssl, void* pcb,
2943
                          tcp_recv_fn recv_fn, tcp_sent_fn sent_fn, void *arg)
2944
{
2945
    if (ssl == NULL || pcb == NULL)
2946
        return BAD_FUNC_ARG;
2947
2948
    ssl->lwipCtx.pcb = (struct tcp_pcb *)pcb;
2949
    ssl->lwipCtx.recv_fn = recv_fn; /*  recv user callback */
2950
    ssl->lwipCtx.sent_fn = sent_fn; /*  sent user callback */
2951
    ssl->lwipCtx.arg  = arg;
2952
    ssl->lwipCtx.pbuf = 0;
2953
    ssl->lwipCtx.pulled = 0;
2954
    ssl->lwipCtx.wait   = 0;
2955
2956
    /* wolfSSL_LwIP_recv/sent_cb invokes recv/sent user callback in them. */
2957
    tcp_recv(pcb, LwIPNativeReceiveCB);
2958
    tcp_sent(pcb, LwIPNativeSentCB);
2959
    tcp_arg (pcb, (void *)&ssl->lwipCtx);
2960
    wolfSSL_SetIOReadCtx(ssl, &ssl->lwipCtx);
2961
    wolfSSL_SetIOWriteCtx(ssl, &ssl->lwipCtx);
2962
2963
    return ERR_OK;
2964
}
2965
#endif
2966
2967
#ifdef WOLFSSL_ISOTP
2968
static int isotp_send_single_frame(struct isotp_wolfssl_ctx *ctx, char *buf,
2969
        word16 length)
2970
{
2971
    /* Length will be at most 7 bytes to get here. Packet is length and type
2972
     * for the first byte, then up to 7 bytes of data */
2973
    ctx->frame.data[0] = ((byte)length) | (ISOTP_FRAME_TYPE_SINGLE << 4);
2974
    XMEMCPY(&ctx->frame.data[1], buf, length);
2975
    ctx->frame.length = length + 1;
2976
    return ctx->send_fn(&ctx->frame, ctx->arg);
2977
}
2978
2979
static int isotp_send_flow_control(struct isotp_wolfssl_ctx *ctx,
2980
        byte overflow)
2981
{
2982
    int ret;
2983
    /* Overflow is set it if we have been asked to receive more data than the
2984
     * user allocated a buffer for */
2985
    if (overflow) {
2986
        ctx->frame.data[0] = ISOTP_FLOW_CONTROL_ABORT |
2987
            (ISOTP_FRAME_TYPE_CONTROL << 4);
2988
    } else {
2989
        ctx->frame.data[0] = ISOTP_FLOW_CONTROL_CTS |
2990
            (ISOTP_FRAME_TYPE_CONTROL << 4);
2991
    }
2992
    /* Set the number of frames between flow control to infinite */
2993
    ctx->frame.data[1] = ISOTP_FLOW_CONTROL_FRAMES;
2994
    /* User specified frame delay */
2995
    ctx->frame.data[2] = ctx->receive_delay;
2996
    ctx->frame.length = ISOTP_FLOW_CONTROL_PACKET_SIZE;
2997
    ret = ctx->send_fn(&ctx->frame, ctx->arg);
2998
    return ret;
2999
}
3000
3001
static int isotp_receive_flow_control(struct isotp_wolfssl_ctx *ctx)
3002
{
3003
    int ret;
3004
    enum isotp_frame_type type;
3005
    enum isotp_flow_control flow_control;
3006
    ret = ctx->recv_fn(&ctx->frame, ctx->arg, ISOTP_DEFAULT_TIMEOUT);
3007
    if (ret == 0) {
3008
        return WOLFSSL_CBIO_ERR_TIMEOUT;
3009
    } else if (ret < 0) {
3010
        WOLFSSL_MSG("ISO-TP error receiving flow control packet");
3011
        return WOLFSSL_CBIO_ERR_GENERAL;
3012
    }
3013
    /* Flow control is the frame type and flow response for the first byte,
3014
     * number of frames until the next flow control packet for the second
3015
     * byte, time between frames for the third byte */
3016
    type = ctx->frame.data[0] >> 4;
3017
3018
    if (type != ISOTP_FRAME_TYPE_CONTROL) {
3019
        WOLFSSL_MSG("ISO-TP frames out of sequence");
3020
        return WOLFSSL_CBIO_ERR_GENERAL;
3021
    }
3022
3023
    flow_control = ctx->frame.data[0] & 0xf;
3024
3025
    ctx->flow_counter = 0;
3026
    ctx->flow_packets = ctx->frame.data[1];
3027
    ctx->frame_delay = ctx->frame.data[2];
3028
3029
    return flow_control;
3030
}
3031
3032
static int isotp_send_consecutive_frame(struct isotp_wolfssl_ctx *ctx)
3033
{
3034
    /* Sequence is 0 - 15 and then starts again, the first frame has an
3035
     * implied sequence of '0' */
3036
    ctx->sequence += 1;
3037
    if (ctx->sequence > ISOTP_MAX_SEQUENCE_COUNTER) {
3038
        ctx->sequence = 0;
3039
    }
3040
    ctx->flow_counter++;
3041
    /* First byte it type and sequence number, up to 7 bytes of data */
3042
    ctx->frame.data[0] = ctx->sequence | (ISOTP_FRAME_TYPE_CONSECUTIVE << 4);
3043
    if (ctx->buf_length > ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE) {
3044
        XMEMCPY(&ctx->frame.data[1], ctx->buf_ptr,
3045
                ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE);
3046
        ctx->buf_ptr += ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE;
3047
        ctx->buf_length -= ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE;
3048
        ctx->frame.length = ISOTP_CAN_BUS_PAYLOAD_SIZE;
3049
    } else {
3050
        XMEMCPY(&ctx->frame.data[1], ctx->buf_ptr, ctx->buf_length);
3051
        ctx->frame.length = ctx->buf_length + 1;
3052
        ctx->buf_length = 0;
3053
    }
3054
    return ctx->send_fn(&ctx->frame, ctx->arg);
3055
3056
}
3057
3058
static int isotp_send_first_frame(struct isotp_wolfssl_ctx *ctx, char *buf,
3059
        word16 length)
3060
{
3061
    int ret;
3062
    ctx->sequence = 0;
3063
    /* Set to 1 to trigger a flow control straight away, the flow control
3064
     * packet will set these properly */
3065
    ctx->flow_packets = ctx->flow_counter = 1;
3066
    /* First frame has 1 nibble for type, 3 nibbles for length followed by
3067
     * 6 bytes for data*/
3068
    ctx->frame.data[0] = (length >> 8) | (ISOTP_FRAME_TYPE_FIRST << 4);
3069
    ctx->frame.data[1] = length & 0xff;
3070
    XMEMCPY(&ctx->frame.data[2], buf, ISOTP_FIRST_FRAME_DATA_SIZE);
3071
    ctx->buf_ptr = buf + ISOTP_FIRST_FRAME_DATA_SIZE;
3072
    ctx->buf_length = length - ISOTP_FIRST_FRAME_DATA_SIZE;
3073
    ctx->frame.length = ISOTP_CAN_BUS_PAYLOAD_SIZE;
3074
    ret = ctx->send_fn(&ctx->frame, ctx->arg);
3075
    if (ret <= 0) {
3076
        WOLFSSL_MSG("ISO-TP error sending first frame");
3077
        return WOLFSSL_CBIO_ERR_GENERAL;
3078
    }
3079
    while(ctx->buf_length) {
3080
        /* The receiver can set how often to get a flow control packet. If it
3081
         * is time, then get the packet. Note that this will always happen
3082
         * after the first packet */
3083
        if ((ctx->flow_packets > 0) &&
3084
                (ctx->flow_counter == ctx->flow_packets)) {
3085
            ret = isotp_receive_flow_control(ctx);
3086
        }
3087
        /* Frame delay <= 0x7f is in ms, 0xfX is X * 100 us */
3088
        if (ctx->frame_delay) {
3089
            if (ctx->frame_delay <= ISOTP_MAX_MS_FRAME_DELAY) {
3090
                ctx->delay_fn(ctx->frame_delay * 1000);
3091
            } else {
3092
                ctx->delay_fn((ctx->frame_delay & 0xf) * 100);
3093
            }
3094
        }
3095
        switch (ret) {
3096
            /* Clear to send */
3097
            case ISOTP_FLOW_CONTROL_CTS:
3098
                if (isotp_send_consecutive_frame(ctx) < 0) {
3099
                    WOLFSSL_MSG("ISO-TP error sending consecutive frame");
3100
                    return WOLFSSL_CBIO_ERR_GENERAL;
3101
                }
3102
                break;
3103
            /* Receiver says "WAIT", so we wait for another flow control
3104
             * packet, or abort if we have waited too long */
3105
            case ISOTP_FLOW_CONTROL_WAIT:
3106
                ctx->wait_counter += 1;
3107
                if (ctx->wait_counter > ISOTP_DEFAULT_WAIT_COUNT) {
3108
                    WOLFSSL_MSG("ISO-TP receiver told us to wait too many"
3109
                            " times");
3110
                    return WOLFSSL_CBIO_ERR_WANT_WRITE;
3111
                }
3112
                break;
3113
            /* Receiver is not ready to receive packet, so abort */
3114
            case ISOTP_FLOW_CONTROL_ABORT:
3115
                WOLFSSL_MSG("ISO-TP receiver aborted transmission");
3116
                return WOLFSSL_CBIO_ERR_WANT_WRITE;
3117
            default:
3118
                WOLFSSL_MSG("ISO-TP got unexpected flow control packet");
3119
                return WOLFSSL_CBIO_ERR_GENERAL;
3120
        }
3121
    }
3122
    return 0;
3123
}
3124
3125
int ISOTP_Send(WOLFSSL* ssl, char* buf, int sz, void* ctx)
3126
{
3127
    int ret;
3128
    struct isotp_wolfssl_ctx *isotp_ctx;
3129
    (void) ssl;
3130
3131
    if (!ctx) {
3132
        WOLFSSL_MSG("ISO-TP requires wolfSSL_SetIO_ISOTP to be called first");
3133
        return WOLFSSL_CBIO_ERR_GENERAL;
3134
    }
3135
    isotp_ctx = (struct isotp_wolfssl_ctx*) ctx;
3136
3137
    /* ISO-TP cannot send more than 4095 bytes, this limits the packet size
3138
     * and wolfSSL will try again with the remaining data */
3139
    if (sz > ISOTP_MAX_DATA_SIZE) {
3140
        sz = ISOTP_MAX_DATA_SIZE;
3141
    }
3142
    /* Can't send whilst we are receiving */
3143
    if (isotp_ctx->state != ISOTP_CONN_STATE_IDLE) {
3144
        return WOLFSSL_ERROR_WANT_WRITE;
3145
    }
3146
    isotp_ctx->state = ISOTP_CONN_STATE_SENDING;
3147
3148
    /* Assuming normal addressing */
3149
    if (sz <= ISOTP_SINGLE_FRAME_DATA_SIZE) {
3150
        ret = isotp_send_single_frame(isotp_ctx, buf, (word16)sz);
3151
    } else {
3152
        ret = isotp_send_first_frame(isotp_ctx, buf, (word16)sz);
3153
    }
3154
    isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
3155
3156
    if (ret == 0) {
3157
        return sz;
3158
    }
3159
    return ret;
3160
}
3161
3162
static int isotp_receive_single_frame(struct isotp_wolfssl_ctx *ctx)
3163
{
3164
    byte data_size;
3165
3166
    /* 1 nibble for data size which will be 1 - 7 in a regular 8 byte CAN
3167
     * packet */
3168
    data_size = (byte)ctx->frame.data[0] & 0xf;
3169
    if (ctx->receive_buffer_size < (int)data_size) {
3170
        WOLFSSL_MSG("ISO-TP buffer is too small to receive data");
3171
        return BUFFER_E;
3172
    }
3173
    XMEMCPY(ctx->receive_buffer, &ctx->frame.data[1], data_size);
3174
    return data_size;
3175
}
3176
3177
static int isotp_receive_multi_frame(struct isotp_wolfssl_ctx *ctx)
3178
{
3179
    int ret;
3180
    word16 data_size;
3181
    byte delay = 0;
3182
3183
    /* Increase receive timeout for enforced ms delay */
3184
    if (ctx->receive_delay <= ISOTP_MAX_MS_FRAME_DELAY) {
3185
        delay = ctx->receive_delay;
3186
    }
3187
    /* Still processing first frame.
3188
     * Full data size is lower nibble of first byte for the most significant
3189
     * followed by the second byte for the rest. Last 6 bytes are data */
3190
    data_size = ((ctx->frame.data[0] & 0xf) << 8) + ctx->frame.data[1];
3191
    XMEMCPY(ctx->receive_buffer, &ctx->frame.data[2], ISOTP_FIRST_FRAME_DATA_SIZE);
3192
    /* Need to send a flow control packet to either cancel or continue
3193
     * transmission of data */
3194
    if (ctx->receive_buffer_size < data_size) {
3195
        isotp_send_flow_control(ctx, TRUE);
3196
        WOLFSSL_MSG("ISO-TP buffer is too small to receive data");
3197
        return BUFFER_E;
3198
    }
3199
    isotp_send_flow_control(ctx, FALSE);
3200
3201
    ctx->buf_length = ISOTP_FIRST_FRAME_DATA_SIZE;
3202
    ctx->buf_ptr = ctx->receive_buffer + ISOTP_FIRST_FRAME_DATA_SIZE;
3203
    data_size -= ISOTP_FIRST_FRAME_DATA_SIZE;
3204
    ctx->sequence = 1;
3205
3206
    while(data_size) {
3207
        enum isotp_frame_type type;
3208
        byte sequence;
3209
        byte frame_len;
3210
        ret = ctx->recv_fn(&ctx->frame, ctx->arg, ISOTP_DEFAULT_TIMEOUT +
3211
                (delay / 1000));
3212
        if (ret == 0) {
3213
            return WOLFSSL_CBIO_ERR_TIMEOUT;
3214
        }
3215
        type = ctx->frame.data[0] >> 4;
3216
        /* Consecutive frames have sequence number as lower nibble */
3217
        sequence = ctx->frame.data[0] & 0xf;
3218
        if (type != ISOTP_FRAME_TYPE_CONSECUTIVE) {
3219
            WOLFSSL_MSG("ISO-TP frames out of sequence");
3220
            return WOLFSSL_CBIO_ERR_GENERAL;
3221
        }
3222
        if (sequence != ctx->sequence) {
3223
            WOLFSSL_MSG("ISO-TP frames out of sequence");
3224
            return WOLFSSL_CBIO_ERR_GENERAL;
3225
        }
3226
        /* Last 7 bytes or whatever we got after the first byte is data */
3227
        frame_len = ctx->frame.length - 1;
3228
        XMEMCPY(ctx->buf_ptr, &ctx->frame.data[1], frame_len);
3229
        ctx->buf_ptr += frame_len;
3230
        ctx->buf_length += frame_len;
3231
        data_size -= frame_len;
3232
3233
        /* Sequence is 0 - 15 (first 0 is implied for first packet */
3234
        ctx->sequence++;
3235
        if (ctx->sequence > ISOTP_MAX_SEQUENCE_COUNTER) {
3236
            ctx->sequence = 0;
3237
        }
3238
    }
3239
    return ctx->buf_length;
3240
3241
}
3242
3243
/* The wolfSSL receive callback, needs to buffer because we need to grab all
3244
 * incoming data, even if wolfSSL doesn't want it all yet */
3245
int ISOTP_Receive(WOLFSSL* ssl, char* buf, int sz, void* ctx)
3246
{
3247
    enum isotp_frame_type type;
3248
    int ret;
3249
    struct isotp_wolfssl_ctx *isotp_ctx;
3250
    (void) ssl;
3251
3252
    if (!ctx) {
3253
        WOLFSSL_MSG("ISO-TP requires wolfSSL_SetIO_ISOTP to be called first");
3254
        return WOLFSSL_CBIO_ERR_TIMEOUT;
3255
    }
3256
    isotp_ctx = (struct isotp_wolfssl_ctx*)ctx;
3257
3258
    /* Is buffer empty? If so, fill it */
3259
    if (!isotp_ctx->receive_buffer_len) {
3260
        /* Can't send whilst we are receiving */
3261
        if (isotp_ctx->state != ISOTP_CONN_STATE_IDLE) {
3262
            return WOLFSSL_ERROR_WANT_READ;
3263
        }
3264
        isotp_ctx->state = ISOTP_CONN_STATE_RECEIVING;
3265
        do {
3266
            ret = isotp_ctx->recv_fn(&isotp_ctx->frame, isotp_ctx->arg,
3267
                    ISOTP_DEFAULT_TIMEOUT);
3268
        } while (ret == 0);
3269
        if (ret == 0) {
3270
            isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
3271
            return WOLFSSL_CBIO_ERR_TIMEOUT;
3272
        } else if (ret < 0) {
3273
            isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
3274
            WOLFSSL_MSG("ISO-TP receive error");
3275
            return WOLFSSL_CBIO_ERR_GENERAL;
3276
        }
3277
3278
        type = (enum isotp_frame_type) isotp_ctx->frame.data[0] >> 4;
3279
3280
        if (type == ISOTP_FRAME_TYPE_SINGLE) {
3281
            isotp_ctx->receive_buffer_len =
3282
                isotp_receive_single_frame(isotp_ctx);
3283
        } else if (type == ISOTP_FRAME_TYPE_FIRST) {
3284
            isotp_ctx->receive_buffer_len =
3285
                isotp_receive_multi_frame(isotp_ctx);
3286
        } else {
3287
            /* Should never get here */
3288
            isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
3289
            WOLFSSL_MSG("ISO-TP frames out of sequence");
3290
            return WOLFSSL_CBIO_ERR_GENERAL;
3291
        }
3292
        if (isotp_ctx->receive_buffer_len <= 1) {
3293
            isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
3294
            return isotp_ctx->receive_buffer_len;
3295
        } else {
3296
            isotp_ctx->receive_buffer_ptr = isotp_ctx->receive_buffer;
3297
        }
3298
        isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
3299
    }
3300
3301
    /* Return from the buffer */
3302
    if (isotp_ctx->receive_buffer_len >= sz) {
3303
        XMEMCPY(buf, isotp_ctx->receive_buffer_ptr, sz);
3304
        isotp_ctx->receive_buffer_ptr+= sz;
3305
        isotp_ctx->receive_buffer_len-= sz;
3306
        return sz;
3307
    } else {
3308
        XMEMCPY(buf, isotp_ctx->receive_buffer_ptr,
3309
                isotp_ctx->receive_buffer_len);
3310
        sz = isotp_ctx->receive_buffer_len;
3311
        isotp_ctx->receive_buffer_len = 0;
3312
        return sz;
3313
    }
3314
}
3315
3316
int wolfSSL_SetIO_ISOTP(WOLFSSL *ssl, isotp_wolfssl_ctx *ctx,
3317
        can_recv_fn recv_fn, can_send_fn send_fn, can_delay_fn delay_fn,
3318
        word32 receive_delay, char *receive_buffer, int receive_buffer_size,
3319
        void *arg)
3320
{
3321
    if (!ctx || !recv_fn || !send_fn || !delay_fn || !receive_buffer) {
3322
        WOLFSSL_MSG("ISO-TP has missing required parameter");
3323
        return WOLFSSL_CBIO_ERR_GENERAL;
3324
    }
3325
    ctx->recv_fn = recv_fn;
3326
    ctx->send_fn = send_fn;
3327
    ctx->arg = arg;
3328
    ctx->delay_fn = delay_fn;
3329
    ctx->frame_delay = 0;
3330
    ctx->receive_buffer = receive_buffer;
3331
    ctx->receive_buffer_size = receive_buffer_size;
3332
    ctx->receive_buffer_len = 0;
3333
    ctx->state = ISOTP_CONN_STATE_IDLE;
3334
3335
    wolfSSL_SetIOReadCtx(ssl, ctx);
3336
    wolfSSL_SetIOWriteCtx(ssl, ctx);
3337
3338
    /* Delay of 100 - 900us is 0xfX where X is value / 100. Delay of
3339
     * >= 1000 is divided by 1000. > 127ms is invalid */
3340
    if (receive_delay < 1000) {
3341
        ctx->receive_delay = 0xf0 + (receive_delay / 100);
3342
    } else if (receive_delay <= ISOTP_MAX_MS_FRAME_DELAY * 1000) {
3343
        ctx->receive_delay = receive_delay / 1000;
3344
    } else {
3345
        WOLFSSL_MSG("ISO-TP delay parameter out of bounds");
3346
        return WOLFSSL_CBIO_ERR_GENERAL;
3347
    }
3348
    return 0;
3349
}
3350
#endif
3351
#endif /* WOLFCRYPT_ONLY */