-
Notifications
You must be signed in to change notification settings - Fork 81
/
u_sock.c
2932 lines (2631 loc) · 112 KB
/
u_sock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2019-2023 u-blox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Only #includes of u_* and the C standard library are allowed here,
* no platform stuff and no OS stuff. Anything required from
* the platform/OS must be brought in through u_port* to maintain
* portability.
*/
/** @file
* @brief Implementation of the common, network-independent portion
* of the sockets API. This includes re-entrancy, error checking,
* checking of socket state, handling of blocking and socket select
* for TCP server operation.
*
* This implementation expects to call on underlying cell/wifi
* APIs for the functions listed below, where "Xxx" could be Cell
* or Wifi (and in future BLE). The format of the calls to these
* functions are deliberately left loose to accommodate variations
* in implementation but the forms below are the simplest ones to
* integrate with.
*
* In all cases the value of devHandle will be taken from the
* appropriate range in u_network_handle.h and will have been brought
* up before any socket operation is conducted.
*
* All of the required types are defined in u_sock.h and, if security
* is required, u_security_tls.h.
*
* In all cases an error from cell/wifi must be indicated by returning
* a negative error value taken from the errno's listed in
* u_sock_errno.h: for instance -U_SOCK_EPERM or -U_SOCK_EAGAIN -11.
* This implementation then negates these values and writes them
* to errno as is usual for a BSD sockets API before returning
* a value of -1 to the user to indicate that an error has
* occurred. Zero, in this case U_SOCK_ENONE, remains the
* indication of success (and nothing is written to errno in this
* case).
*
* Initialise sockets layer (mandatory):
*
* int32_t uXxxSockInit();
*
* Will be called before any other socket function is called,
* can be used to setup up global resources etc. for the
* entire socket layer. If the socket layer is already
* initialised when this function is called the function
* must return U_SOCK_ENONE without making any changes.
*
* Initialise sockets instance (mandatory):
*
* int32_t uXxxSockInitInstance(uDeviceHandle_t devHandle);
*
* Will be called before any other socket function is
* called on the given network instance, can be used to
* setup up resources specific to that instance. If the
* instance is already initialised when this function
* is called the function must return U_SOCK_ENONE without
* making any changes.
*
* Create socket (mandatory):
*
* int32_t uXxxSockCreate(uDeviceHandle_t devHandle,
* uSockType_t type,
* uSockProtocol_t protocol);
*
* Returns a sockHandle that identifies the socket that has
* been created for all future calls (or negative error code).
* The type and protocol parameters are checked before this
* function is called.
*
* Set blocking (mandatory):
*
* void uXxxSockBlockingSet(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* bool isBlocking);
*
* Since blocking is handled at this level, the underlying
* socket must always be non-blocking and this function
* will be called to effect that.
*
* Close (mandatory):
*
* int32_t uXxxSockClose(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* void (pCallback) (int32_t,
* int32_t));
*
* This call should block until the socket is closed.
* If socket closure will take many seconds, e.g. due
* to strict adherence to TCP socket closing rules,
* the pCallback parameter should be taken and be
* called, with the first parameter being devHandle
* and the second parameter sockHandle, when the socket
* is finally closed. The callback should only be
* called once.
*
* DNS look-up (recommended):
*
* int32_t uXxxSockGetHostByName(uDeviceHandle_t devHandle,
* const char *pHostName,
* uSockIpAddress_t *pHostIpAddress);
*
* Get local address of socket (recommended):
*
* int32_t uXxxSockGetLocalAddress(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* uSockAddress_t *pLocalAddress);
*
* Note that there is NO requirement for a
* uXxxSockGetRemoteAddress() function since this layer
* remembers the remote address and always provides that
* remote address with the UDP send-to function. Hence there
* is also no requirement on the underlying socket layer
* to remember the remote address.
*
* Connect to a server (required if TCP is supported):
*
* int32_t uXxxSockConnect(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* const uSockAddress_t *pRemoteAddress);
*
* This function will only be called on a socket in state
* U_SOCK_STATE_CREATED.
*
* Deinitialise (optional):
*
* void uXxxSockDeinit();
*
* Will be called after the socket layer has shut down,
* can be used to release global resources etc. Does NOT
* need to close sockets or the like, this layer will
* ensure that those calls have already been made.
*
* Cleanup (optional):
*
* void uXxxSockCleanup(uDeviceHandle_t devHandle);
*
* Where present this may be called after a socket or sockets
* have been closed. Can be useful to allow freeing of
* resources associated with the given network instance.
*
* Set option (optional):
*
* int32_t uXxxSockOptionSet(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* int32_t level,
* int32_t option,
* const void *pOptionValue,
* size_t optionValueLength);
*
* The value of level shall be taken from U_SOCK_OPT_LEVEL_xxx
* and the values if option from U_SOCK_OPT_xxx. pOptionValue
* points to the value to set and optionValueLength is its
* length in bytes but usually the options are either a single
* int32_t (for an integer value), so length 4, or two int32_t
* values (i.e. uSockLinger_t), so length 8, or a timeval
* struct also consisting of two int32_t's. No checking
* is performed on the level, option, pOptionValue or
* optionValueLength parameters, it is entirely up to the
* implementation to do this and return sensible error values
* (e.g. -U_SOCK_EINVAL). All options are passed transparently
* through except for U_SOCK_OPT_RCVTIMEO which is handled
* here in the u_sock layer (since blocking is handled here).
*
* Get option (optional):
*
* int32_t uXxxSockOptionGet(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* int32_t level,
* int32_t option,
* void *pOptionValue,
* size_t *pOptionValueLength);
*
* As uXxxSockOptionSet() but with pOptionValue being
* populated with the result. However, pOptionValue may be NULL,
* in which case the length of the option that _would_ have
* been got should be returned in pOptionValueLength. No
* checking is performed on the level, option, pOptionValue
* or optionValueLength parameters, it is entirely up to the
* implementation to do this and return sensible error values
* (e.g. -U_SOCK_EINVAL). All options are passed transparently
* through except for U_SOCK_OPT_RCVTIMEO which is handled
* here in the u_sock layer (since blocking is handled here).
*
* Send-to, i.e. datagram, AKA UDP, data transmission
* (optional):
*
* int32_t uXxxSockSendTo(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* const uSockAddress_t *pRemoteAddress,
* const void *pData, size_t dataSizeBytes);
*
* Returns the number of bytes sent or negative errno in the
* usual way. pRemoteAddress will always be provided. If
* dataSizeBytes cannot fit into the maximum permitted
* size of a datagram for the given network no data shall
* be sent and an error (e.g. -U_SOCK_EMSGSIZE) shall be
* returned. It is valid to use this call on a TCP socket.
*
* Receive-from, i.e. datagram, AKA UDP, data reception
* (optional):
*
* int32_t uXxxSockReceiveFrom(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* const uSockAddress_t *pRemoteAddress,
* void *pData, size_t dataSizeBytes);
*
* Returns the number of bytes received or negative errno in the
* usual way. pRemoteAddress may be NULL. If dataSizeBytes is
* insufficient to read in a whole received datagram any remainder
* shall be discarded. If no data is available, U_SOCK_EWOULDBLOCK
* should be returned; this is different to the case where a zero
* length datagram has been received (where zero should be returned).
* It is valid to use this call on a TCP socket.
*
* Write, i.e. byte-oriented or streamed, AKA TCP, data
* transmission over a connected socket (optional):
*
* int32_t uXxxSockWrite(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* const void *pData, size_t dataSizeBytes);
*
* Will only be called on a TCP socket that is connected.
* dataSizeBytes is not limited (except to INT_MAX): the
* function should loop until no more bytes can be sent or
* an error occurs. Returns the number of bytes sent or
* negative errno in the usual way.
*
* Read, i.e. byte-oriented or streamed, AKA TCP, data
* reception over a connected socket (optional):
*
* int32_t uXxxSockRead(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* void *pData, size_t dataSizeBytes);
*
* Will only be called on a TCP socket that is connected.
* The function should loop until dataSizeBytes have been
* filled, no more data is available or an error has occureed.
* Returns the number of bytes received or negative errno in the
* usual way. If no data at all is available,
* U_SOCK_EWOULDBLOCK should be returned.
*
* Register a callback on data being received (optional):
*
* void uXxxSockRegisterCallbackData(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* void (pCallback) (int32_t,
* int32_t));
*
* When new data is received pCallback should be called
* with the first parameter being devHandle and the
* second parameter sockHandle. pCallback will be
* set to NULL to remove an existing callback.
*
* Register a callback on a socket being closed, either
* locally or by the remote host (optional):
*
* void uXxxSockRegisterCallbackClosed(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* void (pCallback) (int32_t,
* int32_t));
*
* When the socket is closed pCallback should be called
* with the first parameter being devHandle and the
* second parameter sockHandle. pCallback will be set
* to NULL to remove an existing callback. The callback
* should only be called once.
*
* Bind a socket to a local IP address for receiving
* incoming TCP connections (required for TCP server only):
*
* int32_t uXxxSockBind(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* const uSockAddress_t *pLocalAddress);
*
* Set listening mode (required for TCP server only):
*
* int32_t uXxxSockListen(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* size_t backlog);
*
* Accept an incoming TCP connection (required for TCP
* server only):
*
* int32_t uXxxSockAccept(uDeviceHandle_t devHandle,
* int32_t sockHandle,
* uSockAddress_t *pRemoteAddress);
*
* The return value is the sockHandle to be used with
* the new connection from now on.
*/
#ifdef U_CFG_OVERRIDE
# include "u_cfg_override.h" // For a customer's configuration override
#endif
#include "limits.h" // For UCHAR_MAX, USHRT_MAX, INT_MAX
#include "errno.h"
#include "stdlib.h" // strtol()
#include "stddef.h" // NULL, size_t etc.
#include "stdint.h" // int32_t etc.
#include "stdbool.h"
#include "string.h" // strlen(), strchr(), strtol()
#include "stdio.h" // snprintf()
#include "sys/time.h" // mktime() and struct timeval in most cases
#include "u_cfg_sw.h"
#include "u_error_common.h"
#include "u_device_shared.h"
#include "u_port_clib_platform_specific.h" /* struct timeval in some cases and
integer stdio, must be included
before the other port files if
any print or scan function is used. */
#include "u_port.h"
#include "u_port_os.h"
#include "u_port_heap.h"
#include "u_port_debug.h"
#include "u_sock.h"
#include "u_sock_security.h"
#include "u_sock_errno.h"
#include "u_cell_sec_tls.h"
#include "u_cell_sock.h"
#include "u_wifi_sock.h"
/* ----------------------------------------------------------------
* COMPILE-TIME MACROS
* -------------------------------------------------------------- */
#ifndef U_SOCK_NUM_STATIC_SOCKETS
/** The number of statically allocated sockets. When
* more than this number of sockets are required to
* be open simultaneously they will be allocated and
* it is up to the user to call uSockCleanUp()
* to release the memory occupied by closed allocated
* sockets when done.
*/
# define U_SOCK_NUM_STATIC_SOCKETS 7
#endif
/** Increment a socket descriptor.
*/
#define U_SOCK_INC_DESCRIPTOR(d) (d)++; \
if ((d) < 0) { \
d = 0; \
}
/* ----------------------------------------------------------------
* TYPES
* -------------------------------------------------------------- */
/** Socket state.
*/
typedef enum {
U_SOCK_STATE_CREATED, /**< Freshly created, unsullied. */
U_SOCK_STATE_CONNECTED, /**< TCP connected or UDP has an address. */
U_SOCK_STATE_SHUTDOWN_FOR_READ, /**< Block all reads. */
U_SOCK_STATE_SHUTDOWN_FOR_WRITE, /**< Block all writes. */
U_SOCK_STATE_SHUTDOWN_FOR_READ_WRITE, /**< Block all reads and
writes. */
U_SOCK_STATE_CLOSING, /**< Block all reads and writes, waiting
for far end to complete closure, can be
tidied up. */
U_SOCK_STATE_CLOSED /**< Actually closed, cannot be found,
container may be re-used. */
} uSockState_t;
/** A socket.
*/
typedef struct {
uSockType_t type;
uSockProtocol_t protocol;
uDeviceHandle_t devHandle;
int32_t sockHandle; /**< This is the socket handle
that is returned by the
underlying socket layer and
is NOTHING TO DO with the socket
descriptor. */
uSockState_t state;
uSockAddress_t remoteAddress;
int64_t receiveTimeoutMs;
int32_t bytesSent;
uSecurityTlsContext_t *pSecurityContext;
void (*pDataCallback) (void *);
void *pDataCallbackParameter;
void (*pClosedCallback) (void *);
void *pClosedCallbackParameter;
bool blocking; // At end to optimise structure packing
} uSockSocket_t;
/** A socket container.
*/
typedef struct uSockContainer_t {
struct uSockContainer_t *pPrevious;
uSockDescriptor_t descriptor;
uSockSocket_t socket;
struct uSockContainer_t *pNext;
bool isStatic; // At end to optimise structure packing
} uSockContainer_t;
/* ----------------------------------------------------------------
* VARIABLES
* -------------------------------------------------------------- */
/** Keep track of whether we're initialised or not.
*/
static bool gInitialised = false;
/** Mutex to protect the container list.
*/
static uPortMutexHandle_t gMutexContainer = NULL;
/** Mutex to protect just the callbacks in the container list.
*/
static uPortMutexHandle_t gMutexCallbacks = NULL;
/** Root of the socket container list.
*/
static uSockContainer_t *gpContainerListHead = NULL;
/** The next descriptor to use.
*/
static uSockDescriptor_t gNextDescriptor = 0;
/** Containers for statically allocated sockets.
*/
static uSockContainer_t gStaticContainers[U_SOCK_NUM_STATIC_SOCKETS];
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: MISC
* -------------------------------------------------------------- */
// Initialise.
static int32_t init()
{
int32_t errorCode = (int32_t) U_ERROR_COMMON_SUCCESS;
int32_t errnoLocal = U_SOCK_ENOMEM;
int32_t errnoLocalCell;
uSockContainer_t **ppContainer = &gpContainerListHead;
uSockContainer_t *pTmp = NULL;
uSockContainer_t **ppPreviousNext = NULL;
// The mutexes are set up once only
if (gMutexContainer == NULL) {
errorCode = uPortMutexCreate(&gMutexContainer);
if (errorCode == 0) {
// Mark this as a perpetual mutex for accounting purposes
uPortOsResourcePerpetualAdd(U_PORT_OS_RESOURCE_TYPE_MUTEX);
}
}
if ((errorCode == 0) && (gMutexCallbacks == NULL)) {
errorCode = uPortMutexCreate(&gMutexCallbacks);
if (errorCode == 0) {
// Mark this as a perpetual mutex for accounting purposes
uPortOsResourcePerpetualAdd(U_PORT_OS_RESOURCE_TYPE_MUTEX);
}
}
if (errorCode == 0) {
errnoLocal = U_SOCK_ENONE;
if (!gInitialised) {
// uXxxSockInit returns a negated value of errno
// from the U_SOCK_Exxx list; one of cellular or
// wifi may return -U_SOCK_ENOSYS and that's OK,
// just means they've been compiled out
errnoLocalCell = uCellSockInit();
if ((errnoLocalCell == U_SOCK_ENONE) || (errnoLocalCell == -U_SOCK_ENOSYS)) {
errnoLocal = uWifiSockInit();
if (errnoLocal == -U_SOCK_ENOSYS) {
errnoLocal = errnoLocalCell;
}
} else {
errnoLocal = errnoLocalCell;
}
if (errnoLocal == U_SOCK_ENONE) {
// Link the static containers into the start of the container list
for (size_t x = 0; x < sizeof(gStaticContainers) /
sizeof(gStaticContainers[0]); x++) {
*ppContainer = &gStaticContainers[x];
(*ppContainer)->isStatic = true;
(*ppContainer)->socket.state = U_SOCK_STATE_CLOSED;
(*ppContainer)->pNext = NULL;
if (ppPreviousNext != NULL) {
*ppPreviousNext = *ppContainer;
}
ppPreviousNext = &((*ppContainer)->pNext);
(*ppContainer)->pPrevious = pTmp;
pTmp = *ppContainer;
ppContainer = &((*ppContainer)->pNext);
}
gInitialised = true;
} else {
// Clean up on error
uCellSockDeinit();
uWifiSockDeinit();
}
}
}
return errnoLocal;
}
// Deinitialise.
static void deinitButNotMutex()
{
if (gInitialised) {
// IMPORTANT: can't delete the mutexes here as we can't
// know if anyone has hold of them. They just have
// to remain.
uCellSockDeinit();
uWifiSockDeinit();
gInitialised = false;
}
}
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: CONTAINER STUFF
* -------------------------------------------------------------- */
// Find the socket container for the given descriptor.
// Will not find sockets in state CLOSED.
// This does NOT lock the mutex, you need to do that.
static uSockContainer_t *pContainerFindByDescriptor(uSockDescriptor_t descriptor)
{
uSockContainer_t *pContainer = NULL;
uSockContainer_t *pContainerThis = gpContainerListHead;
while ((pContainerThis != NULL) &&
(pContainer == NULL)) {
if ((pContainerThis->descriptor == descriptor) &&
(pContainerThis->socket.state != U_SOCK_STATE_CLOSED)) {
pContainer = pContainerThis;
}
pContainerThis = pContainerThis->pNext;
}
return pContainer;
}
// Find the socket container for the given network handle
// and socket handle. If sockHandle is less than zero,
// returns the first entry for the given devHandle.
// Will not find sockets in state CLOSED.
// This does NOT lock the mutex, you need to do that.
static uSockContainer_t *pContainerFindByDeviceHandle(uDeviceHandle_t devHandle,
int32_t sockHandle)
{
uSockContainer_t *pContainer = NULL;
uSockContainer_t *pContainerThis = gpContainerListHead;
while ((pContainerThis != NULL) &&
(pContainer == NULL)) {
if ((pContainerThis->socket.devHandle == devHandle) &&
((pContainerThis->socket.sockHandle == sockHandle) ||
(pContainerThis->socket.sockHandle < 0)) &&
(pContainerThis->socket.state != U_SOCK_STATE_CLOSED)) {
pContainer = pContainerThis;
}
pContainerThis = pContainerThis->pNext;
}
return pContainer;
}
// Determine the number of non-closed sockets.
// This does NOT lock the mutex, you need to do that.
static size_t numContainersInUse()
{
uSockContainer_t *pContainer = gpContainerListHead;
size_t numInUse = 0;
while (pContainer != NULL) {
if (pContainer->socket.state != U_SOCK_STATE_CLOSED) {
numInUse++;
}
pContainer = pContainer->pNext;
}
return numInUse;
}
// Create a socket in a container with the given descriptor.
// This does NOT lock the mutex, you need to do that.
static uSockContainer_t *pSockContainerCreate(uSockDescriptor_t descriptor,
uSockType_t type,
uSockProtocol_t protocol)
{
uSockContainer_t *pContainer = NULL;
uSockContainer_t *pContainerPrevious = NULL;
uSockContainer_t **ppContainerThis = &gpContainerListHead;
// Traverse the list, stopping if there is a container
// that holds a closed socket, which we could re-use
while ((*ppContainerThis != NULL) && (pContainer == NULL)) {
if ((*ppContainerThis)->socket.state == U_SOCK_STATE_CLOSED) {
pContainer = *ppContainerThis;
}
pContainerPrevious = *ppContainerThis;
ppContainerThis = &((*ppContainerThis)->pNext);
}
if (pContainer == NULL) {
// Reached the end of the list and found no re-usable
// containers, so allocate memory for the new container
// and add it to the list
pContainer = (uSockContainer_t *) pUPortMalloc(sizeof (*pContainer));
if (pContainer != NULL) {
pContainer->isStatic = false;
pContainer->pPrevious = pContainerPrevious;
pContainer->pNext = NULL;
*ppContainerThis = pContainer;
}
}
// Set up the new container and socket
if (pContainer != NULL) {
pContainer->descriptor = descriptor;
memset(&(pContainer->socket), 0, sizeof(pContainer->socket));
pContainer->socket.type = type;
pContainer->socket.protocol = protocol;
pContainer->socket.devHandle = NULL;
pContainer->socket.sockHandle = -1;
pContainer->socket.state = U_SOCK_STATE_CREATED;
pContainer->socket.blocking = true;
pContainer->socket.receiveTimeoutMs = U_SOCK_DEFAULT_RECEIVE_TIMEOUT_MS;
pContainer->socket.pSecurityContext = NULL;
pContainer->socket.pDataCallback = NULL;
pContainer->socket.pDataCallbackParameter = NULL;
pContainer->socket.pClosedCallback = NULL;
pContainer->socket.pClosedCallbackParameter = NULL;
}
return pContainer;
}
// Free the container corresponding to the descriptor.
// Has no effect on static containers.
// This does NOT lock the mutex, you need to do that.
static bool containerFree(uSockDescriptor_t descriptor)
{
uSockContainer_t **ppContainer = NULL;
uSockContainer_t **ppContainerThis = &gpContainerListHead;
bool success = false;
while ((*ppContainerThis != NULL) &&
(ppContainer == NULL)) {
if ((*ppContainerThis)->descriptor == descriptor) {
ppContainer = ppContainerThis;
} else {
ppContainerThis = &((*ppContainerThis)->pNext);
}
}
if ((ppContainer != NULL) && (*ppContainer != NULL)) {
if (!(*ppContainer)->isStatic) {
// If we found it, and it wasn't static, free it
// If there is a previous container, move its pNext
if ((*ppContainer)->pPrevious != NULL) {
(*ppContainer)->pPrevious->pNext = (*ppContainer)->pNext;
}
// If there is a next container, move its pPrevious
if ((*ppContainer)->pNext != NULL) {
(*ppContainer)->pNext->pPrevious = (*ppContainer)->pPrevious;
}
// Free the memory and NULL the pointer
uPortFree(*ppContainer);
*ppContainer = NULL;
} else {
// Nothing to do for a static container,
}
success = true;
}
return success;
}
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: CALLBACKS
* -------------------------------------------------------------- */
// Callback for when local socket closures at the underlying
// cell/wifi socket layer happen asynchronously, either
// due to local closure or by the remote host
static void closedCallback(uDeviceHandle_t devHandle,
int32_t sockHandle)
{
uSockContainer_t *pContainer;
// Don't lock the container mutex here as this
// needs to be callable while a send or receive is
// in progress and that already has the mutex
pContainer = pContainerFindByDeviceHandle(devHandle,
sockHandle);
if (pContainer != NULL) {
// Mark the container as closed
pContainer->socket.state = U_SOCK_STATE_CLOSED;
U_PORT_MUTEX_LOCK(gMutexCallbacks);
if (pContainer->socket.pClosedCallback != NULL) {
pContainer->socket.pClosedCallback(pContainer->socket.pClosedCallbackParameter);
pContainer->socket.pClosedCallback = NULL;
}
// We can now finally release any security
// context
uSecurityTlsRemove(pContainer->socket.pSecurityContext);
pContainer->socket.pSecurityContext = NULL;
U_PORT_MUTEX_UNLOCK(gMutexCallbacks);
}
}
// Callback for when data has been received at the
// underlying cell/wifi socket layer.
static void dataCallback(uDeviceHandle_t devHandle,
int32_t sockHandle)
{
uSockContainer_t *pContainer;
// Don't lock the container mutex here as this
// needs to be callable while a send or receive is
// in progress and that already has the mutex
pContainer = pContainerFindByDeviceHandle(devHandle,
sockHandle);
if (pContainer != NULL) {
U_PORT_MUTEX_LOCK(gMutexCallbacks);
if (pContainer->socket.pDataCallback != NULL) {
pContainer->socket.pDataCallback(pContainer->socket.pDataCallbackParameter);
}
U_PORT_MUTEX_UNLOCK(gMutexCallbacks);
}
}
/* ----------------------------------------------------------------
* STATIC FUNCTIONS: ADDRESS CONVERSION
* -------------------------------------------------------------- */
// Given a string, which may be an IP address or a
// domain name, return a pointer to the separator
// character for the port number part of it,
// or NULL if there is no port number
//lint -e{818} Suppress could be declared as pointing
// to const 'cos when called from pUSockDomainRemovePort()
// it can't.
static char *pAddressPortSeparator(char *pAddress)
{
char *pColon = NULL;
if (pAddress != NULL) {
// If there's a square bracket at the start of
// the domain string then we've been given an
// IPV6 address with port number so move
// the pointer to the closing square bracket
if (*pAddress == '[') {
pAddress = strchr(pAddress, ']');
}
if (pAddress != NULL) {
// Check for a port number on the end
pColon = strchr(pAddress, ':');
if (pColon != NULL) {
// Check if there are more colons in the
// string: if so this is an IPV6 address
// without a port number on the end
if (strchr(pColon + 1, ':') != NULL) {
pColon = NULL;
}
}
}
}
return pColon;
}
// Determine whether the given IP address string is IPV4.
static bool addressStringIsIpv4(const char *pAddressString)
{
// If it's got a dot in it, must be IPV4
return (strchr(pAddressString, '.') != NULL);
}
// Convert an IPV4 address string "xxx.yyy.www.zzz:65535" into
// a struct.
static bool ipv4StringToAddress(const char *pAddressString,
uSockAddress_t *pAddress)
{
bool success = true;
uint8_t digits[4];
int32_t y;
size_t z = 0;
char *pTmp;
const char *pColon = NULL;
pAddress->ipAddress.type = U_SOCK_ADDRESS_TYPE_V4;
pAddress->ipAddress.address.ipv4 = 0;
pAddress->port = 0;
// Get the numbers from the IP address part,
// moving pAddressString along as we go
for (size_t x = 0; (x < sizeof(digits) /
sizeof(digits[0])) &&
success; x++) {
y = strtol(pAddressString, &pTmp, 10);
digits[x] = (uint8_t) y;
success = (pTmp > pAddressString) &&
(y >= 0) && (y <= UCHAR_MAX) &&
((*pTmp == '.') || (*pTmp == 0) ||
(*pTmp == ':'));
if (*pTmp == ':') {
pColon = pTmp;
}
pAddressString = pTmp;
pAddressString++;
z++;
}
if (success && (z == sizeof(digits) /
sizeof(digits[0]))) {
// Got enough digits, now calculate the
// IP address part in network-byte order
pAddress->ipAddress.address.ipv4 = (((uint32_t) digits[0]) << 24) |
(((uint32_t) digits[1]) << 16) |
(((uint32_t) digits[2]) << 8) |
(((uint32_t) digits[3]) << 0);
// Check the port number on the end
if (pColon != NULL) {
success = false;
// Fill in the port number
y = strtol(pColon + 1, NULL, 10);
if (y <= (int32_t) USHRT_MAX) {
pAddress->port = (uint16_t) y;
success = true;
}
}
}
return success;
}
// Convert an IPV6 address string "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
// or "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:65535" into a struct.
static bool ipv6StringToAddress(const char *pAddressString,
uSockAddress_t *pAddress)
{
bool success = true;
uint16_t digits[8];
bool hasPort = false;
const char *pPortColon = NULL;
char *pTmp;
int32_t y;
size_t z = 0;
pAddress->ipAddress.type = U_SOCK_ADDRESS_TYPE_V6;
memset(pAddress->ipAddress.address.ipv6, 0,
sizeof(pAddress->ipAddress.address.ipv6));
pAddress->port = 0;
// See if there's a '[' on the start
if ((strlen(pAddressString) > 0) && (*pAddressString == '[')) {
hasPort = true;
pAddressString++;
}
// Get the hex numbers from the IP address part,
// moving pAddressString along and checking
// for the colon before the port number as we go
for (size_t x = 0; (x < sizeof(digits) /
sizeof(digits[0])) &&
success; x++) {
y = strtol(pAddressString, &pTmp, 16);
digits[x] = (uint16_t) y;
success = (pTmp > pAddressString) &&
(y >= 0) && (y <= (int32_t) USHRT_MAX) &&
((*pTmp == ':') || (*pTmp == 0) ||
((*pTmp == ']') && hasPort));
if ((*pTmp == ']') && hasPort &&
(*(pTmp + 1) == ':')) {
pPortColon = pTmp + 1;
}
pAddressString = pTmp;
pAddressString++;
z++;
}
if (success && (z == sizeof(digits) /
sizeof(digits[0]))) {
// Got enough digits, now slot the uint16_t's
// into the array in network-byte order
pAddress->ipAddress.address.ipv6[3] = (((uint32_t) digits[0]) << 16) | (digits[1]);
pAddress->ipAddress.address.ipv6[2] = (((uint32_t) digits[2]) << 16) | (digits[3]);
pAddress->ipAddress.address.ipv6[1] = (((uint32_t) digits[4]) << 16) | (digits[5]);
pAddress->ipAddress.address.ipv6[0] = (((uint32_t) digits[6]) << 16) | (digits[7]);
// Get the port number if there was one
if (hasPort) {
success = false;
if (pPortColon != NULL) {
// Fill in the port number
y = strtol(pPortColon + 1, NULL, 10);
if (y <= (int32_t) USHRT_MAX) {
pAddress->port = (uint16_t) y;
success = true;
}
}
}
}
return success;
}
// Convert an IP address struct (i.e. without a port number) into a
// string, returning the length of the string.
static int32_t ipAddressToString(const uSockIpAddress_t *pIpAddress,
char *pBuffer,
size_t sizeBytes)
{
int32_t stringLengthOrError = (int32_t) U_ERROR_COMMON_INVALID_PARAMETER;
size_t thisLength;
// Convert the address in network byte order (MSB first);
switch (pIpAddress->type) {
case U_SOCK_ADDRESS_TYPE_V4:
stringLengthOrError = snprintf(pBuffer, sizeBytes,
"%u.%u.%u.%u",
(unsigned int) ((pIpAddress->address.ipv4 >> 24) & 0xFF),
(unsigned int) ((pIpAddress->address.ipv4 >> 16) & 0xFF),
(unsigned int) ((pIpAddress->address.ipv4 >> 8) & 0xFF),
(unsigned int) ((pIpAddress->address.ipv4 >> 0) & 0xFF));
break;
case U_SOCK_ADDRESS_TYPE_V6:
stringLengthOrError = 0;
for (int32_t x = 3; (x >= 0) && (stringLengthOrError >= 0); x--) {
thisLength = snprintf(pBuffer, sizeBytes,
"%x:%x",
(unsigned int) ((pIpAddress->address.ipv6[x] >> 16) & 0xFFFF),
(unsigned int) ((pIpAddress->address.ipv6[x] >> 0) & 0xFFFF));
if (x > 0) {
if (thisLength < sizeBytes) {
*(pBuffer + thisLength) = ':';
thisLength++;
} else {
stringLengthOrError = (int32_t) U_ERROR_COMMON_NO_MEMORY;
}
}
if (thisLength < sizeBytes) {
sizeBytes -= thisLength;
pBuffer += thisLength;
stringLengthOrError += (int32_t) thisLength;
} else {
stringLengthOrError = (int32_t) U_ERROR_COMMON_NO_MEMORY;
}
}
break;
case U_SOCK_ADDRESS_TYPE_V4_V6:
//fall-through
default:
break;
}
return stringLengthOrError;
}
// Convert an address struct, which includes a port number,
// into a string, returning the length of the string.
static int32_t addressToString(const uSockAddress_t *pAddress,
bool includePortNumber,
char *pBuffer,
size_t sizeBytes)
{
int32_t stringLengthOrError = (int32_t) U_ERROR_COMMON_SUCCESS;
int32_t thisLength;
if (includePortNumber) {
// If this is an IPV6 address, then start with a square bracket
// to delineate the IP address part
if (pAddress->ipAddress.type == U_SOCK_ADDRESS_TYPE_V6) {
if (sizeBytes > 1) {
*pBuffer = '[';
stringLengthOrError++;
sizeBytes--;