Coverage Report

Created: 2025-09-01 06:47

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