-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathip.h
More file actions
2458 lines (2222 loc) · 74.3 KB
/
ip.h
File metadata and controls
2458 lines (2222 loc) · 74.3 KB
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
#ifndef IP_H
#define IP_H
#define IP_PROJECT "Portable IP/TCP/UDP stack"
#define IP_AUTHOR "Richard James Howe"
#define IP_EMAIL "howe.r.j.89@gmail.com"
#define IP_LICENSE "0BSD"
#define IP_REPO "https://github.com/howerj/ip"
#include <stdint.h>
#include <stddef.h>
/* NOTE: https://stackoverflow.com/questions/8568432 */
#ifndef IP_PACKED
#define IP_PACKED __attribute__((packed))
#endif
enum { /* There are many more see <https://en.wikipedia.org/wiki/EtherType> */
IP_ETHERNET_TYPE_IPV4 = 0x0800u,
IP_ETHERNET_TYPE_ARP = 0x0806u,
IP_ETHERNET_TYPE_RARP = 0x8035u,
IP_ETHERNET_TYPE_IPV6 = 0x86DDu,
};
typedef struct {
uint8_t destination[6];
uint8_t source[6];
uint16_t type;
} ip_ethernet_t;
#define IP_ETHERNET_HEADER_BYTE_COUNT (14)
enum {
IP_V4_PROTO_ICMP = 0x00u,
IP_V4_PROTO_TCP = 0x06u,
IP_V4_PROTO_UDP = 0x11u,
};
typedef struct {
uint8_t vhl; /* 4 bit version and 4 bit header length */
uint8_t tos; /* 8 bit type of service */
uint16_t len; /* 16 bit length */
uint16_t id; /* 16 bit identification */
uint16_t frags; /* 3 bit flags 13 bit fragment offset */
uint8_t ttl; /* 8 bit time to live */
uint8_t proto; /* 8 bit protocol number */
uint16_t checksum; /* 16 bit checksum */
uint32_t source; /* 32 bit source address */
uint32_t destination; /* 32 bit destination address */
} ip_ipv4_t;
#define IP_HEADER_BYTE_COUNT (20)
typedef struct {
uint32_t flags;
uint16_t length;
uint8_t next;
uint8_t hops;
uint8_t source[16];
uint8_t destination[16];
} ip_ipv6_t;
#define IP_V6_HEADER_BYTE_COUNT (4 + 2 + 1 + 1 + 16 + 16)
typedef struct {
uint16_t hw; /* 16 bit hw type */
uint16_t proto; /* 16 bit protocol */
uint8_t hlen; /* 8 bit hw address length */
uint8_t plen; /* 8 bit protocol address length */
uint16_t op; /* 16 bit operation */
uint8_t shw[6]; /* 48 bit sender hw address */
uint32_t sp; /* 32 bit sender ipv4 address */
uint8_t thw[6]; /* 48 bit target hw address */
uint32_t tp; /* 32 bit target ipv4 address */
} ip_arp_t;
#define IP_ARP_HEADER_BYTE_COUNT (28)
typedef struct {
uint8_t type; /* 8 bits type */
uint8_t code; /* 8 bits code */
uint16_t checksum; /* 16 bits checksum */
uint32_t rest; /* 32 bits rest of header */
} ip_icmp_t;
#define IP_ICMP_HEADER_BYTE_COUNT (8)
typedef struct {
uint16_t source; /* 16 bit source port */
uint16_t destination; /* 16 bit destination port */
uint16_t length; /* 16 bit length */
uint16_t checksum; /* 16 bit checksum */
} ip_udp_t;
#define IP_UDP_HEADER_BYTE_COUNT (8)
typedef struct {
uint16_t source; /* 16 bit source port */
uint16_t destination; /* 16 bit destination port */
uint32_t seq; /* 32 bit sequence number */
uint32_t ack; /* 32 bit acknowledgement */
uint8_t offset; /* 8 bit offset */
uint16_t flags; /* 16 bit flags */
uint8_t window; /* 8 bit window size */
uint16_t checksum; /* 16 bit checksum */
uint16_t urgent; /* 16 bit urgent pointer */
} ip_tcp_t;
#define IP_TCP_HEADER_BYTE_COUNT (20)
typedef struct {
uint8_t livnm; /* 2-bit Leap, 3-bit version, 3-bit mode */
uint8_t stratum; /* Stratum [closeness to good clock] */
uint8_t poll; /* Poll field, max suggested poll rate */
uint8_t precision; /* Precision [signed log2 seconds] */
uint32_t root_delay; /* Root delay */
uint32_t root_dispersion; /* Root dispersion */
uint32_t refid; /* Reference ID */
uint64_t ref_ts; /* Reference Time Stamp */
uint64_t orig_ts; /* Origin Time Stamp */
uint64_t rx_ts; /* RX Time Stamp */
uint64_t tx_ts; /* 8-byte Transmit time stamp */
/* There are more optional fields, of varying length, such as key ids, message digests, auth, etcetera. */
} ip_ntp_t;
#define IP_NTP_HEADER_BYTE_COUNT (48)
typedef struct {
uint8_t op;
uint8_t htype;
uint8_t hlen;
uint8_t hops;
uint32_t xid;
uint16_t secs;
uint16_t flags;
uint32_t ciaddr;
uint32_t yiaddr;
uint32_t siaddr;
uint32_t giaddr;
uint8_t chaddr[16];
uint8_t opts[192];
uint32_t magic_cookie;
} ip_dhcp_t;
#define IP_DHCP_HEADER_BYTE_COUNT (240)
enum {
IP_DHCP_XID = 0x3903F326ul,
IP_DHCP_MAGIC_COOKIE = 0x63825363ul,
};
typedef struct {
uint16_t transaction_id;
uint16_t flags; /* See: https://en.wikipedia.org/wiki/Domain_Name_System#DNS_message_format */
uint16_t num_of_questions;
uint16_t num_of_answers;
uint16_t num_of_authority_rrs;
uint16_t num_of_additional_rrs;
} ip_dns_t;
#define IP_DNS_HEADER_BYTE_COUNT (12)
// TODO:
// - Export functions, turn into header only library like
// <https://github.com/howerj/hexy>
#ifdef IP_IMPLEMENTATION
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifndef CONFIG_IP_MAX_RX_BUF
#define CONFIG_IP_MAX_RX_BUF (2048)
#endif
#ifndef CONFIG_IP_MAX_TX_BUF
#define CONFIG_IP_MAX_TX_BUF (CONFIG_IP_MAX_RX_BUF)
#endif
#ifndef CONFIG_IP_ARP_CACHE_TIMEOUT_MS /* Time out for an ARP cache entry, obviously */
#define CONFIG_IP_ARP_CACHE_TIMEOUT_MS (60l * 1000l)
#endif
#ifndef CONFIG_IP_ARP_CACHE_COUNT /* For large values the search needs design */
#define CONFIG_IP_ARP_CACHE_COUNT (64)
#endif
#ifndef CONFIG_IP_V4_DEFAULT /* 192.168.1.2 */
#define CONFIG_IP_V4_DEFAULT (0xC0A80102ul)
#endif
#ifndef CONFIG_IP_V4_DEFAULT_GATEWAY /* 192.168.1.254 */
#define CONFIG_IP_V4_DEFAULT_GATEWAY (0xC0A801FEul)
#endif
#ifndef CONFIG_IP_V4_DEFAULT_NETMASK /* 255.255.255.0 */
#define CONFIG_IP_V4_DEFAULT_NETMASK (0xFFFFFF00ul)
#endif
#ifndef CONFIG_IP_MAC_ADDR_DEFAULT /* Our default MAC address: generated online, just a random address */
#define CONFIG_IP_MAC_ADDR_DEFAULT { 0x60, 0x08, 0xAD, 0x7D, 0x47, 0xE2, }
#endif
#ifndef CONFIG_IP_ARP_RETRY_COUNT /* number of times to try and resolve an IP <-> MAC using ARP */
#define CONFIG_IP_ARP_RETRY_COUNT (3)
#endif
#ifndef CONFIG_IP_ARP_TIMEOUT_MS /* ARP request response timeout */
#define CONFIG_IP_ARP_TIMEOUT_MS (1000)
#endif
#ifndef CONFIG_IP_TTL_DEFAULT /* default IPv4 TTL */
#define CONFIG_IP_TTL_DEFAULT (0x80u)
#endif
#ifndef CONFIG_IP_TCP_MAX_CONNECTIONS
#define CONFIG_IP_TCP_MAX_CONNECTIONS (8)
#endif
#define IP_IFACE_METHOD_PCAP (0) /* use libpcap to tx/rx IP packets */
#define IP_IFACE_METHOD_LINUX_TAP (1) /* use Linux TAP interface to tx/rx IP packets */
#define IP_IFACE_METHOD_CUSTOM (2) /* use something *you* supply */
#ifndef CONFIG_IP_IFACE_METHOD /* Interface method (PCAP = 0, Linux TUN = TODO) */
#define CONFIG_IP_IFACE_METHOD (IP_IFACE_METHOD_LINUX_TAP)
#endif
#ifndef CONFIG_IP_PRINT_ENABLE /* Enable print functions */
#define CONFIG_IP_PRINT_ENABLE (1)
#endif
#ifndef CONFIG_IP_QUEUE_DEPTH
#define CONFIG_IP_QUEUE_DEPTH (32)
#endif
#ifdef NDEBUG
#define IP_DEBUG (0)
#else
#define IP_DEBUG (1)
#endif
#define IP_V4_BROADCAST_ADDRESS (0xFFFFFFFFul)
#define IP_ETHERNET_BROADCAST_ADDRESS { 255, 255, 255, 255, 255, 255, }
#define IP_ETHERNET_EMPTY_ADDRESS { 0, 0, 0, 0, 0, 0, }
#define IP_NELEMS(X) (sizeof((X)) / sizeof((X)[0]))
#define IP_UNUSED(X) ((void)(X))
#define IPV4(A, B, C, D) ((((A) & 255) << 24) | (((B) & 255) << 16) | (((C) & 255) << 8) | (((D) & 255) << 0))
#define IP_MAX(X, Y) ((X) < (Y) ? (Y) : (X))
#define IP_MIN(X, Y) ((X) > (Y) ? (Y) : (X))
#define IP_NL "\n"
#define IP_IN "\t"
enum { IP_ARP_CACHE_ENTRY_UNUSED, IP_ARP_CACHE_ENTRY_WAITING, IP_ARP_CACHE_ENTRY_ACTIVE, IP_ARP_CACHE_ENTRY_STATIC, };
typedef struct {
unsigned long start_ms, timeout_ms;
int state; /* -1 = error, 0 = uninitialized, 1 = initialized, 2 = expired */
} ip_timer_t;
enum { IP_ARP_CACHE_UNUSED, IP_ARP_CACHE_WAITING, IP_ARP_CACHE_ACTIVE, IP_ARP_CACHE_STATIC, };
typedef struct {
ip_timer_t timer;
uint32_t ipv4;
uint8_t mac[6];
uint8_t state /* unused, waiting, active, static */;
} ip_arp_cache_entry_t;
#define IP_ARP_CACHE_ENTRY_BYTE_COUNT (4 + 4 + 6 + 1)
struct ip_queue_element {
struct ip_queue_element *next; /* next element in free-list */
uint8_t *buf; /* buffer, what wondrous things will you store here? */
size_t buf_len, /* length of the buffer, obvs */
used; /* set by user - that means you! Do not exceed buf_len, do not bounce. */
};
typedef struct ip_queue_element ip_queue_element_t;
/* There are many different allocations strategies that could be done
* in order to make these queues as efficient as possible, for example the
* queue elements could be a Flexible Array Member. This unfortunately makes
* static allocation non-portable (and generate a bunch of warnings). We could
* go further and allocate the buffer after the elements and allocate one big
* slab. This has advantages (fewer memory allocations, only one allocate and
* free functions, it is clear who owns what, fewer pointers), but also
* disadvantages (it is technically not allowed, alignment issues, we would
* need to know all buffer sizes at allocation time). For a low level language
* C does not make it easy to allocate memory exactly how you would like it
* whilst still conforming to the language. */
typedef struct {
ip_queue_element_t *head, *tail;
/*size_t queue_length; // total length of queue */
int used; /* number of elements used in queue */
} ip_queue_t;
/* From RFC 793, cool diagram.
+---------+ ---------\ active OPEN
| CLOSED | \ -----------
+---------+<---------\ \ create TCB
| ^ \ \ snd SYN
passive OPEN | | CLOSE \ \
------------ | | ---------- \ \
create TCB | | delete TCB \ \
V | \ \
+---------+ CLOSE | \
| LISTEN | ---------- | |
+---------+ delete TCB | |
rcv SYN | | SEND | |
----------- | | ------- | V
+---------+ snd SYN,ACK / \ snd SYN +---------+
| |<----------------- ------------------>| |
| SYN | rcv SYN | SYN |
| RCVD |<-----------------------------------------------| SENT |
| | snd ACK | |
| |------------------ -------------------| |
+---------+ rcv ACK of SYN \ / rcv SYN,ACK +---------+
| -------------- | | -----------
| x | | snd ACK
| V V
| CLOSE +---------+
| ------- | ESTAB |
| snd FIN +---------+
| CLOSE | | rcv FIN
V ------- | | -------
+---------+ snd FIN / \ snd ACK +---------+
| FIN |<----------------- ------------------>| CLOSE |
| WAIT-1 |------------------ | WAIT |
+---------+ rcv FIN \ +---------+
| rcv ACK of FIN ------- | CLOSE |
| -------------- snd ACK | ------- |
V x V snd FIN V
+---------+ +---------+ +---------+
|FINWAIT-2| | CLOSING | | LAST-ACK|
+---------+ +---------+ +---------+
| rcv ACK of FIN | rcv ACK of FIN |
| rcv FIN -------------- | Timeout=2MSL -------------- |
| ------- x V ------------ x V
\ snd ACK +---------+delete TCB +---------+
------------------------>|TIME WAIT|------------------>| CLOSED |
+---------+ +---------+
*/
enum { /* TCP states */
IP_TCP_ST_CLOSED, /* Inactive Connection, starting state */
IP_TCP_ST_LISTEN, /* Wait for a connection request */
IP_TCP_ST_SYN_RCVD, /* TCP server received first message in 3-way handshake, message had SYN set */
IP_TCP_ST_SYN_SENT, /* TCP client sent first message with SYN set */
IP_TCP_ST_ESTABLISHED, /* Normal running, connection can send and receive data */
IP_TCP_ST_CLOSE_WAIT, /* Local end point has rx'd a connection termination request, local end point needs to do active close*/
IP_TCP_ST_LAST_ACK, /* Local end point has performed a passive close, and initiated active close */
IP_TCP_ST_FIN_WAIT_1, /* First step of an active close */
IP_TCP_ST_FIN_WAIT_2, /* The remote end point has send ack for previously sent termination req */
IP_TCP_ST_CLOSING, /* The local end point is waiting for ack for connection termination req before going to time-wait */
IP_TCP_ST_TIME_WAIT, /* The local end-point wait twice maximum segment lifetime before going to CLOSED to make sure remote ack rx'd*/
};
typedef struct { /* TCP Transmission Control Block */
ip_queue_element_t *window; /* instead of `uint8_t window[4096]` we use queues as our generic allocator */
int state;
uint16_t ack,
req;
uint16_t port, remote_port;
uint32_t remote_ipv4;
// TODO, fill out and add printing, we could also add a callback
} ip_tcp_tcb_t;
typedef struct { // TODO: Move to export portion of file
int (*os_time_ms)(void *os_time, long *time_ms);
int (*os_sleep_ms)(void *os_sleep, long *sleep_ms);
int (*os_random)(void *os_random, uint8_t *buf, size_t len);
long (*ethernet_rx)(void *ethernet, uint8_t *buf, size_t buflen);
long (*ethernet_tx)(void *ethernet, uint8_t *buf, size_t buflen);
void *os_time, /* OS timer object, most likely NULL */
*os_sleep, /* OS sleep object, most likely NULL */
*random, /* random object, most likely NULL */
*ethernet, /* Ethernet interface handle */
*error; /* Error stream, most likely `stderr` */
uint8_t *rx, *tx; /* packet buffers; these are always available, but should not be used to pass packets around */
size_t rx_len, tx_len;
ip_queue_t q; /* packets buffers that can be passed around */
ip_queue_element_t qs[CONFIG_IP_QUEUE_DEPTH];
ip_tcp_tcb_t tcp[CONFIG_IP_TCP_MAX_CONNECTIONS];
// TODO: Callbacks for UDP? UDP connection manager?
uint32_t ipv4_interface,
ipv4_default_gateway,
ipv4_netmask;
long ipv4_ttl;
uint8_t mac[6]; /* interface MAC */
uint16_t ip_id; /* IP Id field, increments each send */
ip_queue_t arpq; /* packets from `q` are put here until ARP is resolved */
ip_arp_cache_entry_t arp_cache[CONFIG_IP_ARP_CACHE_COUNT];
unsigned long arp_cache_timeout_ms;
uint32_t arp_ipv4; /* IP address we want to link with a MAC addr */
int arp_state, /* ARP state machine */
arp_retries, /* Number of times to retry an ARP request */
arp_opts; /* ARP options */
ip_timer_t arp_timer; /* ARP retry timer */
int fatal; /* fatal error occurred, we should exit gracefully */
int stop; /* stop processing any data, return, if true (applies to `ip_stack` function). */
long log_level; /* level to log at */
} ip_stack_t;
static int ip_queue_init(ip_queue_t *q, ip_queue_element_t *es, size_t elements, uint8_t *arena, size_t arena_len) {
assert(q);
assert(es);
assert(arena);
/*assert((((uintptr_t)arena) & 0xF) == 0); // We could align arena up ourselves, and decrement arena_len */
memset(q, 0, sizeof *q);
memset(arena, 0, arena_len);
memset(es, 0, sizeof (*es) * elements);
size_t chunk = !elements || !arena_len ? 0 : arena_len / elements;
if (chunk < 16) /* min align is 16 bytes */
return -1;
chunk += 0xF;
chunk &= ~0xFull;
q->used = 0;
/*q->queue_length = elements;*/
q->head = &es[0];
q->tail = &es[elements - 1];
for (size_t i = 0; i < elements; i++) {
ip_queue_element_t *e = &es[i];
e->next = i < (elements - 1) ? &es[i + 1] : NULL;
assert((chunk * i) < arena_len);
e->buf = &arena[chunk * i];
e->buf_len = chunk;
}
return 0;
}
static int ip_queue_is_empty(ip_queue_t *q) {
assert(q);
return q->head == NULL;
}
/* N.B. We could make FIFO/FILO behavior selectable */
static ip_queue_element_t *ip_queue_get(ip_queue_t *q) {
assert(q);
if (ip_queue_is_empty(q))
return NULL;
ip_queue_element_t *r = q->head;
q->head = q->head->next;
if (q->head == NULL)
q->tail = NULL;
/*assert(q->used < q->queue_length);*/
q->used++;
r->next = NULL;
return r;
}
static ip_queue_element_t *ip_queue_peek(ip_queue_t *q) {
assert(q);
if (ip_queue_is_empty(q))
return NULL;
return q->head;
}
static void ip_queue_put(ip_queue_t *q, ip_queue_element_t *e) {
assert(q);
assert(e);
if (ip_queue_is_empty(q)) {
q->tail = e;
q->head = e;
/*assert(q->used > 0);*/
q->used--;
return;
}
e->next = NULL;
q->tail->next = e;
q->tail = e;
/*assert(q->used > 0);*/
q->used--;
}
enum { IP_LOG_FATAL, IP_LOG_ERROR, IP_LOG_WARNING, IP_LOG_INFO, IP_LOG_DEBUG, };
static int ip_log(ip_stack_t *ip, int fatal, unsigned level, const char *func, unsigned line, const char *fmt, ...) {
assert(fmt);
assert(func);
FILE *out = ip && ip->error ? ip->error : stderr;
if (!ip || level <= ip->log_level) {
assert(level <= IP_LOG_DEBUG);
static const char *level_str[] = { "fatal", "error", "warning", "info", "debug", };
const int r1 = fprintf(out, "[%s] %s %u: ", level_str[level], func, line);
va_list ap;
va_start(ap, fmt);
const int r2 = vfprintf(out, fmt, ap);
va_end(ap);
const int r3 = fputc('\n', out);
const int r4 = fflush(out);
if (r1 < 0 || r2 < 0 || r3 < 0 || r4 < 0) {
if (ip)
ip->fatal = -1;
}
}
if (ip && fatal) {
ip->fatal = line;
} else if (fatal) {
exit(1);
}
return 0;
}
static int ip_printf(const char *fmt, ...) {
assert(fmt);
if (!CONFIG_IP_PRINT_ENABLE)
return 0;
FILE *out = stderr;
va_list ap;
va_start(ap, fmt);
const int r = vfprintf(out, fmt, ap);
va_end(ap);
return r < 0 ? -1 : 0;
}
static inline int ip_dump(const char *banner, const unsigned char *m, size_t len) {
assert(banner);
assert(m);
const size_t col = 16;
if (ip_printf("\n%s\nLEN: %d\n", banner, (int)len) < 0) return -1;
for (size_t i = 0; i < len; i += col) {
if (ip_printf("%04X: ", (unsigned)i) < 0) return -1;
for (size_t j = i; j < len && j < (i + col); j++) {
if (ip_printf("%02X ", (unsigned)m[j]) < 0) return -1;
}
if (ip_printf("\n") < 0) return -1;
}
return 0;
}
static int ip_random(ip_stack_t *ip, uint8_t *buf, size_t len) {
assert(ip);
assert(ip->os_random);
assert(buf);
return ip->os_random(ip->random, buf, len);
}
static int ip_sleep(ip_stack_t *ip, long *sleep_ms) {
assert(ip);
assert(ip->os_sleep_ms);
assert(sleep_ms);
return ip->os_sleep_ms(ip->os_sleep, sleep_ms);
}
static int ip_time_ms(ip_stack_t *ip, long *time_ms) {
assert(ip);
assert(ip->os_time_ms);
assert(time_ms);
return ip->os_time_ms(ip->os_time, time_ms);
}
static int ip_ethernet_rx(ip_stack_t *ip, uint8_t *buf, size_t buflen) {
assert(ip);
assert(buf);
assert(ip->ethernet_rx);
return ip->ethernet_rx(ip->ethernet, buf, buflen);
}
static int ip_ethernet_tx(ip_stack_t *ip, uint8_t *buf, size_t buflen) {
assert(ip);
assert(buf);
assert(ip->ethernet_tx);
return ip->ethernet_tx(ip->ethernet, buf, buflen);
}
#define ip_fatal(IP, ...) ip_log((IP), 1, IP_LOG_FATAL, __func__, __LINE__, __VA_ARGS__)
#define ip_error(IP, ...) ip_log((IP), 0, IP_LOG_ERROR, __func__, __LINE__, __VA_ARGS__)
#define ip_warn(IP, ...) ip_log((IP), 0, IP_LOG_WARNING, __func__, __LINE__, __VA_ARGS__)
#define ip_info(IP, ...) ip_log((IP), 0, IP_LOG_INFO, __func__, __LINE__, __VA_ARGS__)
#define ip_debug(IP, ...) ip_log((IP), 0, IP_LOG_DEBUG, __func__, __LINE__, __VA_ARGS__)
static inline uint16_t ip_u16swap(uint16_t x) { return (x >> 8) | (x << 8); }
static inline uint32_t ip_u32swap(uint32_t x) {
return ((x >> 24) & 0x000000FFul) | ((x >> 8) & 0x0000FF00ul)
| ((x << 8) & 0x00FF0000ul) | ((x << 24) & 0xFF000000ul);
}
static inline uint64_t ip_u64swap(uint64_t x) {
x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32;
x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16;
x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8;
return x;
}
static inline int ip_endianess(void) { /* 0 = Little Endian (Intel/i386), 1 = Big Endian (network order, Motorola) */
union { uint8_t c[4]; uint32_t i; } data = { .c = { 0, }, };
data.i = 0x12345678ul; /* technically some undefined behavior here */
return data.c[0] == 0x12;
}
static inline uint16_t ip_ntohs(uint16_t x) { return ip_endianess() ? x : ip_u16swap(x); }
static inline uint32_t ip_ntohl(uint16_t x) { return ip_endianess() ? x : ip_u32swap(x); }
static inline uint16_t ip_htons(uint16_t x) { return ip_endianess() ? x : ip_u16swap(x); }
static inline uint32_t ip_htonl(uint32_t x) { return ip_endianess() ? x : ip_u32swap(x); }
static inline uint32_t ip_htonll(uint64_t x) { return ip_endianess() ? x : ip_u64swap(x); }
static int ip_v4addr(const char *s, uint32_t *addr) {
assert(s);
assert(addr);
*addr = 0;
int ip[4] = { 0, };
const int r = sscanf(s, "%i.%i.%i.%i", &ip[0], &ip[1], &ip[2], &ip[3]);
if (r != 4)
return -1;
const uint32_t ipv4 =
((ip[0] & 255) << 24) |
((ip[1] & 255) << 16) |
((ip[2] & 255) << 8) |
((ip[3] & 255) << 0) ;
*addr = ipv4;
return 0;
}
static int ip_v4addr_to_string(uint32_t addr, char *s, size_t len) {
assert(s);
int ip[4] = { (addr >> 24) & 255, (addr >> 16) & 255, (addr >> 8) & 255, (addr >> 0) & 255, };
return snprintf(s, len, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
}
static inline void ip_htons_b(uint16_t x, uint8_t *buf) {
assert(buf);
x = ip_htons(x);
buf[0] = x >> 0;
buf[1] = x >> 8;
}
static inline void ip_htonl_b(uint32_t x, uint8_t *buf) {
assert(buf);
x = ip_htonl(x);
buf[0] = x >> 0;
buf[1] = x >> 8;
buf[2] = x >> 16;
buf[3] = x >> 24;
}
static inline void ip_htonll_b(uint64_t x, uint8_t *buf) {
assert(buf);
x = ip_htonll(x);
buf[0] = x >> 0;
buf[1] = x >> 8;
buf[2] = x >> 16;
buf[3] = x >> 24;
buf[4] = x >> 32;
buf[5] = x >> 40;
buf[6] = x >> 48;
buf[7] = x >> 56;
}
static inline uint16_t ip_ntohs_b(const uint8_t *buf) {
assert(buf);
const uint16_t x =
(((uint16_t)buf[0]) << 0) |
(((uint16_t)buf[1]) << 8) ;
return ip_ntohs(x);
}
static inline uint32_t ip_ntohl_b(const uint8_t *buf) {
assert(buf);
const uint32_t x =
(((uint32_t)buf[0]) << 0) |
(((uint32_t)buf[1]) << 8) |
(((uint32_t)buf[2]) << 16) |
(((uint32_t)buf[3]) << 24) ;
return ip_htonl(x);
}
static inline uint64_t ip_ntohll_b(const uint8_t *buf) {
assert(buf);
const uint64_t x =
(((uint64_t)buf[0]) << 0) |
(((uint64_t)buf[1]) << 8) |
(((uint64_t)buf[2]) << 16) |
(((uint64_t)buf[3]) << 24) |
(((uint64_t)buf[4]) << 32) |
(((uint64_t)buf[5]) << 40) |
(((uint64_t)buf[6]) << 48) |
(((uint64_t)buf[7]) << 56) ;
return ip_htonll(x);
}
static void ip_serdes_start(const char *name, size_t packet_len, int serialize) {
assert(name);
if (serialize < 0)
ip_printf("%s -- %zu" IP_NL, name, packet_len);
}
static inline void ip_u8_buf_serdes(uint8_t *x, uint8_t *buf, int serialize) {
assert(x);
assert(buf);
if (serialize < 0) {
(void)ip_printf(IP_IN "u8:%x" IP_NL, *x);
return;
}
if (serialize) {
buf[0] = *x;
return;
}
*x = buf[0];
}
/* It might be an idea to return the number of items read/wrote, this would
* mean we would not have to manually track that count. */
static inline void ip_u16_buf_serdes(uint16_t *x, uint8_t *buf, int serialize) {
assert(x);
assert(buf);
if (serialize < 0) {
(void)ip_printf(IP_IN "u16:%x" IP_NL, *x);
return;
}
if (serialize) {
ip_htons_b(*x, buf);
return;
}
*x = ip_ntohs_b(buf);
}
static inline void ip_u32_buf_serdes(uint32_t *x, uint8_t *buf, int serialize) {
assert(x);
assert(buf);
if (serialize < 0) {
(void)ip_printf(IP_IN "u32:%lx" IP_NL, *x);
return;
}
if (serialize) {
ip_htonl_b(*x, buf);
return;
}
*x = ip_ntohl_b(buf);
}
static inline void ip_u64_buf_serdes(uint64_t *x, uint8_t *buf, int serialize) {
assert(x);
assert(buf);
if (serialize < 0) {
(void)ip_printf(IP_IN "u64:%llx" IP_NL, *x);
return;
}
if (serialize) {
ip_htonll_b(*x, buf);
return;
}
*x = ip_ntohll_b(buf);
}
static inline void ip_memory_serdes(uint8_t *structure, uint8_t *network, size_t length, int serialize) {
assert(structure);
assert(network);
if (serialize < 0) {
(void)ip_printf(IP_IN "u8[%zu]:", length);
for (size_t i = 0; i < length; i++) {
(void)ip_printf("%x,", structure[i]);
}
(void)ip_printf(IP_NL, length);
return;
}
if (serialize) {
memcpy(network, structure, length);
return;
}
memcpy(structure, network, length);
}
enum { IP_TIMER_ERROR = -1, IP_TIMER_UNINIT = 0, IP_TIMER_INIT = 1, IP_TIMER_EXPIRED = 2, };
static int ip_timer_start_ms(ip_stack_t *ip, ip_timer_t *t, unsigned ms) {
assert(ip);
assert(t);
long now = 0;
memset(t, 0, sizeof (*t));
t->state = IP_TIMER_UNINIT;
if (ip_time_ms(ip, &now) < 0) {
t->state = IP_TIMER_ERROR;
return -1;
}
t->start_ms = (unsigned long)now;
t->timeout_ms = ms;
t->state = IP_TIMER_INIT;
return 0;
}
static int ip_timer_expired(ip_stack_t *ip, ip_timer_t *t) {
assert(ip);
assert(t);
assert(t->state > IP_TIMER_UNINIT); /* not in error or uninitialized state */
if (t->state == IP_TIMER_EXPIRED)
return 1;
long now = 0;
if (ip_time_ms(ip, &now) < 0)
return -1;
unsigned long diff = ((unsigned long)now) - t->start_ms;
if (diff > t->timeout_ms) {
t->state = IP_TIMER_EXPIRED;
return 1;
}
return 0;
}
static int ip_timer_reset_ms(ip_stack_t *ip, ip_timer_t *t, unsigned ms) {
assert(ip);
assert(t);
return ip_timer_start_ms(ip, t, ms);
}
static uint32_t ip_checksum_add(const uint8_t *buf, size_t len) {
uint32_t r = 0;
for (size_t i = 0; i < len; i++) {
if (i & 1)
r += ((uint32_t)buf[i]) << 0;
else
r += ((uint32_t)buf[i]) << 8;
}
return r;
}
static uint16_t ip_checksum_finish(uint32_t sum) {
while (sum >> 16)
sum = (sum & 0xFFFFul) + (sum >> 16);
return ~sum;
}
static int ip_ethernet_header_serdes(ip_ethernet_t *e, uint8_t *buf, size_t buf_len, int serialize) {
assert(e);
assert(buf);
if (buf_len < IP_ETHERNET_HEADER_BYTE_COUNT)
return -1;
/* If these structures are packed we can replace this with a
single memcpy and then ntohX/htonX functions, if the host is in
network order, those function calls to ntohX/htonX can be elided, if
we are clever we could get the compiler to optimize this out. */
ip_serdes_start("ethernet", buf_len, serialize);
ip_memory_serdes(e->destination, buf + 0, 6, serialize);
ip_memory_serdes(e->source, buf + 6, 6, serialize);
ip_u16_buf_serdes(&e->type, buf + 12, serialize);
return IP_ETHERNET_HEADER_BYTE_COUNT;
}
static int ip_ipv4_header_serdes(ip_ipv4_t *i, uint8_t *buf, size_t buf_len, int serialize) {
assert(i);
assert(buf);
if (buf_len < IP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("ipv4", buf_len, serialize);
ip_u8_buf_serdes(&i->vhl, buf + 0, serialize);
ip_u8_buf_serdes(&i->tos, buf + 1, serialize);
ip_u16_buf_serdes(&i->len, buf + 2, serialize);
ip_u16_buf_serdes(&i->id, buf + 4, serialize);
ip_u16_buf_serdes(&i->frags, buf + 6, serialize);
ip_u8_buf_serdes(&i->ttl, buf + 8, serialize);
ip_u8_buf_serdes(&i->proto, buf + 9, serialize);
ip_u16_buf_serdes(&i->checksum, buf + 10, serialize);
ip_u32_buf_serdes(&i->source, buf + 12, serialize);
ip_u32_buf_serdes(&i->destination, buf + 16, serialize);
return IP_HEADER_BYTE_COUNT; // TODO: Calculate larger header lengths / fail if header too big
}
static int ip_ipv6_header_serdes(ip_ipv6_t *i, uint8_t *buf, size_t buf_len, int serialize) {
assert(i);
assert(buf);
if (buf_len < IP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("ipv6", buf_len, serialize);
ip_u32_buf_serdes(&i->flags, buf + 0, serialize);
ip_u16_buf_serdes(&i->length, buf + 4, serialize);
ip_u8_buf_serdes(&i->next, buf + 6, serialize);
ip_u8_buf_serdes(&i->hops, buf + 7, serialize);
ip_memory_serdes(i->source, buf + 8, 16, serialize);
ip_memory_serdes(i->destination, buf + 24, 16, serialize);
return IP_V6_HEADER_BYTE_COUNT; // TODO: Calculate larger headers / fail if header too big
}
static int ip_arp_header_serdes(ip_arp_t *arp, uint8_t *buf, size_t buf_len, int serialize) {
assert(arp);
assert(buf);
if (buf_len < IP_ARP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("arp", buf_len, serialize);
ip_u16_buf_serdes(&arp->hw, buf + 0, serialize);
ip_u16_buf_serdes(&arp->proto, buf + 2, serialize);
ip_u8_buf_serdes(&arp->hlen, buf + 4, serialize);
ip_u8_buf_serdes(&arp->plen, buf + 5, serialize);
ip_u16_buf_serdes(&arp->op, buf + 6, serialize);
ip_memory_serdes(arp->shw, buf + 8, 6, serialize);
ip_u32_buf_serdes(&arp->sp, buf + 14, serialize);
ip_memory_serdes(arp->thw, buf + 18, 6, serialize);
ip_u32_buf_serdes(&arp->tp, buf + 24, serialize);
return IP_ARP_HEADER_BYTE_COUNT;
}
static int ip_icmp_header_serdes(ip_icmp_t *icmp, uint8_t *buf, size_t buf_len, int serialize) {
assert(icmp);
assert(buf);
if (buf_len < IP_ICMP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("icmp", buf_len, serialize);
ip_u8_buf_serdes(&icmp->type, buf + 0, serialize);
ip_u8_buf_serdes(&icmp->code, buf + 1, serialize);
ip_u16_buf_serdes(&icmp->checksum, buf + 2, serialize);
ip_u32_buf_serdes(&icmp->rest, buf + 4, serialize);
return IP_ICMP_HEADER_BYTE_COUNT;
}
static int ip_udp_header_serdes(ip_udp_t *udp, uint8_t *buf, size_t buf_len, int serialize) {
assert(udp);
assert(buf);
if (buf_len < IP_UDP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("udp", buf_len, serialize);
ip_u16_buf_serdes(&udp->source, buf + 0, serialize);
ip_u16_buf_serdes(&udp->destination, buf + 2, serialize);
ip_u16_buf_serdes(&udp->length, buf + 4, serialize);
ip_u16_buf_serdes(&udp->checksum, buf + 6, serialize);
return IP_UDP_HEADER_BYTE_COUNT;
}
static int ip_tcp_header_serdes(ip_tcp_t *tcp, uint8_t *buf, size_t buf_len, int serialize) {
assert(tcp);
assert(buf);
if (buf_len < IP_TCP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("tcp", buf_len, serialize);
ip_u16_buf_serdes(&tcp->source, buf + 0, serialize);
ip_u16_buf_serdes(&tcp->destination, buf + 2, serialize);
ip_u32_buf_serdes(&tcp->seq, buf + 4, serialize);
ip_u32_buf_serdes(&tcp->ack, buf + 8, serialize);
ip_u8_buf_serdes(&tcp->offset, buf + 12, serialize);
ip_u16_buf_serdes(&tcp->flags, buf + 13, serialize);
ip_u8_buf_serdes(&tcp->window, buf + 15, serialize);
ip_u16_buf_serdes(&tcp->checksum, buf + 16, serialize);
ip_u16_buf_serdes(&tcp->urgent, buf + 18, serialize);
return IP_TCP_HEADER_BYTE_COUNT;
}
static int ip_ntp_header_serdes(ip_ntp_t *ntp, uint8_t *buf, size_t buf_len, int serialize) {
assert(ntp);
assert(buf);
if (buf_len < IP_NTP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("ntp", buf_len, serialize);
ip_u8_buf_serdes(&ntp->livnm, buf + 0, serialize);
ip_u8_buf_serdes(&ntp->stratum, buf + 1, serialize);
ip_u8_buf_serdes(&ntp->poll, buf + 2, serialize);
ip_u8_buf_serdes(&ntp->precision, buf + 3, serialize);
ip_u32_buf_serdes(&ntp->root_delay, buf + 4, serialize);
ip_u32_buf_serdes(&ntp->root_dispersion, buf + 8, serialize);
ip_u32_buf_serdes(&ntp->refid, buf + 12, serialize);
ip_u64_buf_serdes(&ntp->ref_ts, buf + 16, serialize);
ip_u64_buf_serdes(&ntp->orig_ts, buf + 24, serialize);
ip_u64_buf_serdes(&ntp->rx_ts, buf + 32, serialize);
ip_u64_buf_serdes(&ntp->tx_ts, buf + 40, serialize);
/* There are more optional fields, of varying length, such as key ids, message digests, auth, etcetera. */
return IP_NTP_HEADER_BYTE_COUNT;
}
static int ip_arp_cache_entry_serdes(ip_arp_cache_entry_t *arp, uint8_t *buf, size_t buf_len, int serialize) {
assert(arp);
assert(buf);
if (buf_len < IP_ARP_CACHE_ENTRY_BYTE_COUNT)
return -1;
ip_serdes_start("arp-cache", buf_len, serialize);
/*ip_u32_buf_serdes(&arp->ttl_ms, buf + 0, serialize); // We could serialize the timer as well */
ip_u32_buf_serdes(&arp->ipv4, buf + 4, serialize);
ip_memory_serdes(arp->mac, buf + 8, 6, serialize);
ip_u8_buf_serdes(&arp->state, buf + 14, serialize);
return IP_ARP_CACHE_ENTRY_BYTE_COUNT;
}
static int ip_dhcp_header_serdes(ip_dhcp_t *dhcp, uint8_t *buf, size_t buf_len, int serialize) {
assert(dhcp);
assert(buf);
if (buf_len < IP_DHCP_HEADER_BYTE_COUNT)
return -1;
ip_serdes_start("dhcp", buf_len, serialize);
ip_u8_buf_serdes(&dhcp->op, buf + 0, serialize);
ip_u8_buf_serdes(&dhcp->htype, buf + 1, serialize);
ip_u8_buf_serdes(&dhcp->hlen, buf + 2, serialize);
ip_u8_buf_serdes(&dhcp->hops, buf + 3, serialize);
ip_u32_buf_serdes(&dhcp->xid, buf + 4, serialize);
ip_u16_buf_serdes(&dhcp->secs, buf + 8, serialize);
ip_u16_buf_serdes(&dhcp->flags, buf + 10, serialize);
ip_u32_buf_serdes(&dhcp->ciaddr, buf + 12, serialize);
ip_u32_buf_serdes(&dhcp->yiaddr, buf + 16, serialize);
ip_u32_buf_serdes(&dhcp->siaddr, buf + 20, serialize);
ip_u32_buf_serdes(&dhcp->giaddr, buf + 24, serialize);
ip_memory_serdes(dhcp->chaddr, buf + 28, 16, serialize);