Coverage Report

Created: 2025-12-31 07:08

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