-
Notifications
You must be signed in to change notification settings - Fork 34
/
znet.h
executable file
·2804 lines (2416 loc) · 80.5 KB
/
znet.h
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
/* znet - C version of zsummerX */
#ifndef znet_h
#define znet_h
#ifndef ZN_NS_BEGIN
# ifdef __cplusplus
# define ZN_NS_BEGIN extern "C" {
# define ZN_NS_END }
# else
# define ZN_NS_BEGIN
# define ZN_NS_END
# endif
#endif /* ZN_NS_BEGIN */
#ifndef ZN_STATIC
# if __GNUC__
# define ZN_STATIC static __attribute__((unused))
# else
# define ZN_STATIC static
# endif
#endif
#ifdef ZN_STATIC_API
# ifndef ZN_IMPLEMENTATION
# define ZN_IMPLEMENTATION
# endif
# define ZN_API ZN_STATIC
#endif
#if !defined(ZN_API) && defined(_WIN32)
# ifdef ZN_IMPLEMENTATION
# define ZN_API __declspec(dllexport)
# else
# define ZN_API __declspec(dllimport)
# endif
#endif
#ifndef ZN_API
# define ZN_API extern
#endif
#ifndef zn_Time
# ifdef ZN_USE_64BIT_TIMER
typedef unsigned long long zn_Time;
# else
typedef unsigned zn_Time;
# endif
# define zn_Time zn_Time
#endif /* zn_Time */
#ifndef ZN_MAX_EVENTS
# define ZN_MAX_EVENTS 1024
#endif
#define ZN_MAX_ADDRLEN 50
#define ZN_MAX_TIMERPOOL 512
#define ZN_MAX_TIMERHEAP 512
#define ZN_MAX_PAGESIZE 4096
#define ZN_TIMER_NOINDEX (~(unsigned)0)
#define ZN_FOREVER ((~(zn_Time)0)-100)
#define ZN_MAX_SIZET ((~(size_t)0)-100)
ZN_NS_BEGIN
#define ZN_ERRORS(X) \
X(OK, "No error") \
X(ERROR, "Operation failed") \
X(ECLOSE, "socket closed") \
X(ECLOSED, "Remote socket closed") \
X(EHANGUP, "Remote socket hang up") \
X(ESOCKET, "Socket creation error") \
X(ECONNECT, "Connect error") \
X(EBIND, "Local address bind error") \
X(EPARAM, "Parameter error") \
X(EPOLL, "Register to poll error") \
X(ESTATE, "State error") \
X(EBUSY, "Another operation performed") \
typedef enum zn_Error {
#define X(name, msg) ZN_##name,
ZN_ERRORS(X)
#undef X
ZN_ERROR_COUNT
} zn_Error;
typedef struct zn_State zn_State;
typedef struct zn_Accept zn_Accept;
typedef struct zn_Tcp zn_Tcp;
typedef struct zn_Udp zn_Udp;
typedef struct zn_Timer zn_Timer;
typedef struct zn_PeerInfo {
char addr[ZN_MAX_ADDRLEN];
unsigned port;
} zn_PeerInfo;
typedef zn_Time zn_TimerHandler (void *ud, zn_Timer *timer, zn_Time delayed);
typedef void zn_PostHandler (void *ud, zn_State *S);
typedef void zn_AcceptHandler (void *ud, zn_Accept *accept, unsigned err, zn_Tcp *tcp);
typedef void zn_ConnectHandler (void *ud, zn_Tcp *tcp, unsigned err);
typedef void zn_SendHandler (void *ud, zn_Tcp *tcp, unsigned err, unsigned count);
typedef void zn_RecvHandler (void *ud, zn_Tcp *tcp, unsigned err, unsigned count);
typedef void zn_RecvFromHandler (void *ud, zn_Udp *udp, unsigned err, unsigned count,
const char *addr, unsigned port);
/* znet state routines */
ZN_API void zn_initialize (void);
ZN_API void zn_deinitialize (void);
ZN_API const char *zn_strerror (int err);
ZN_API const char *zn_engine (void);
ZN_API zn_State *zn_newstate (void);
ZN_API void zn_close (zn_State *S);
ZN_API void *zn_getuserdata (zn_State *S);
ZN_API void zn_setuserdata (zn_State *S, void *ud);
ZN_API unsigned zn_retain (zn_State *S);
ZN_API unsigned zn_release (zn_State *S);
ZN_API int zn_run (zn_State *S, int mode);
#define ZN_RUN_ONCE 0
#define ZN_RUN_CHECK 1
#define ZN_RUN_LOOP 2
ZN_API int zn_post (zn_State *S, zn_PostHandler *cb, void *ud);
/* znet timer routines */
ZN_API zn_Time zn_time (void);
ZN_API zn_Timer *zn_newtimer (zn_State *S, zn_TimerHandler *cb, void *ud);
ZN_API void zn_deltimer (zn_Timer *timer);
ZN_API int zn_starttimer (zn_Timer *timer, zn_Time delayms);
ZN_API void zn_canceltimer (zn_Timer *timer);
/* znet accept routines */
ZN_API zn_Accept* zn_newaccept (zn_State *S, int packet);
ZN_API int zn_closeaccept (zn_Accept *accept);
ZN_API void zn_delaccept (zn_Accept *accept);
ZN_API int zn_listen (zn_Accept *accept, const char *addr, unsigned port);
ZN_API int zn_accept (zn_Accept *accept, zn_AcceptHandler *cb, void *ud);
/* znet tcp socket routines */
ZN_API zn_Tcp* zn_newtcp (zn_State *S);
ZN_API int zn_closetcp (zn_Tcp *tcp);
ZN_API void zn_deltcp (zn_Tcp *tcp);
ZN_API void zn_getpeerinfo (zn_Tcp *tcp, zn_PeerInfo *info);
ZN_API int zn_connect (zn_Tcp *tcp, const char *addr, unsigned port,
int packet,
zn_ConnectHandler *cb, void *ud);
ZN_API int zn_send (zn_Tcp *tcp, const char *buff, unsigned len,
zn_SendHandler *cb, void *ud);
ZN_API int zn_recv (zn_Tcp *tcp, char *buff, unsigned len,
zn_RecvHandler *cb, void *ud);
/* znet udp socket routines */
ZN_API zn_Udp* zn_newudp (zn_State *S, const char *addr, unsigned port);
ZN_API int zn_closeudp (zn_Udp *udp);
ZN_API void zn_deludp (zn_Udp *udp);
ZN_API int zn_sendto (zn_Udp *udp, const char *buff, unsigned len,
const char *addr, unsigned port);
ZN_API int zn_recvfrom (zn_Udp *udp, char *buff, unsigned len,
zn_RecvFromHandler *cb, void *ud);
ZN_NS_END
#endif /* znet_h */
/* implementations */
#if defined(ZN_IMPLEMENTATION) && !defined(znet_implemented)
#define znet_implemented
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) ||\
defined(__DragonFly__) || defined(__MACOSX__) ||\
(defined(__APPLE__) && defined(__MACH__))
# define zn_have_kqueue
#endif
#if !defined(_WIN32)
# define zn_have_info /* all objects have zn_SocketInfo field */
#endif
ZN_NS_BEGIN
#define zn_use_mempool
#define zn_use_timer
#include "znet.h"
#if defined(_WIN32)
# define zn_use_platform_win32
# define zn_use_backend_iocp
#else /* POSIX systems */
# define zn_use_platform_posix
# define zn_use_postqueue
# if defined(__linux__) && !defined(ZN_USE_SELECT)
# define zn_use_resultqueue
# define zn_use_backend_reactive
# define zn_use_backend_epoll
# elif defined(zn_have_kqueue) && !defined(ZN_USE_SELECT)
# define zn_use_resultqueue
# define zn_use_backend_reactive
# define zn_use_backend_kqueue
# else
# define zn_use_backend_select
# endif
#endif
#define zn_use_addr
#define zn_use_state
#include "znet.h"
#define zn_use_api
#include "znet.h"
ZN_NS_END
#endif /* ZN_IMPLEMENTATION */
#ifndef zn_list_h
#define zn_list_h
#define zn_rawset(l, r) (*(void**)&(l) = (void*)(r))
#define zn_reverse(T, h) do { \
T *ret_ = NULL, *next_; \
while (h) next_ = h->next, h->next = ret_, \
ret_ = h, h = next_; \
(h) = ret_; } while (0)
#define znL_entry(T) T *next; T *prev
#define znL_head(T) struct T##_hlist { znL_entry(T); }
#define znL_init(h) (zn_rawset((h)->prev, h), zn_rawset((h)->next, h))
#define znL_empty(h) ((void*)(h)->prev == (void*)&(h))
#define znL_insert(h,n) (zn_rawset((n)->next, h), \
(n)->prev = (h)->prev, \
(h)->prev->next = (n), \
(h)->prev = (n)) \
#define znL_remove(n) ((n)->prev->next = (n)->next, \
(n)->next->prev = (n)->prev) \
#define znL_apply(T, h, stmt) do { \
T *cur, *next_ = (h)->next; \
while (cur = next_, next_ = next_->next, cur != (T*)(h)) \
{ stmt; } } while (0)
#define znQ_entry(T) T *next
#define znQ_head(T) struct T##_qlist { T *first, **plast; }
#define znQ_init(h) ((h)->first = NULL, (h)->plast = &(h)->first)
#define znQ_first(h) ((h)->first)
#define znQ_empty(h) ((h)->first == NULL)
#define znQ_enqueue(h, n) ((n)->next = NULL, \
*(h)->plast = (n), \
(h)->plast = &(n)->next) \
#define znQ_dequeue(h, pn) do { \
if (((pn) = (h)->first) != NULL) { \
(h)->first = (h)->first->next; \
if ((h)->plast == &(pn)->next) \
(h)->plast = &(h)->first; } } while (0)
#define znQ_apply(T, h, stmt) do { \
T *cur = (h), *next_; \
while (cur) { next_ = cur->next; stmt; cur = next_; } } while (0)
#endif /* zn_list_h */
#ifdef zn_use_mempool /* memory pool */
#undef zn_use_mempool
#include <assert.h>
#include <stdlib.h>
typedef struct zn_MemPool {
void *pages;
void *freed;
size_t size;
} zn_MemPool;
static void znM_putobject(zn_MemPool *pool, void *obj)
{ *(void**)obj = pool->freed; pool->freed = obj; }
static void znM_initpool(zn_MemPool *pool, size_t size) {
size_t sp = sizeof(void*);
pool->pages = NULL;
pool->freed = NULL;
pool->size = size;
assert(((sp - 1) & sp) == 0);
assert(size >= sp && size % sp == 0);
assert(ZN_MAX_PAGESIZE / size > 2);
}
static void znM_freepool(zn_MemPool *pool) {
const size_t offset = ZN_MAX_PAGESIZE - sizeof(void*);
while (pool->pages != NULL) {
void *next = *(void**)((char*)pool->pages + offset);
free(pool->pages);
pool->pages = next;
}
znM_initpool(pool, pool->size);
}
static void *znM_getobject(zn_MemPool *pool) {
void *obj = pool->freed;
if (obj == NULL) {
const size_t offset = ZN_MAX_PAGESIZE - sizeof(void*);
void *end, *newpage = malloc(ZN_MAX_PAGESIZE);
if (newpage == NULL) return NULL;
*(void**)((char*)newpage + offset) = pool->pages;
pool->pages = newpage;
end = (char*)newpage + (offset/pool->size-1)*pool->size;
while (end != newpage) {
*(void**)end = pool->freed;
pool->freed = (void**)end;
end = (char*)end - pool->size;
}
return end;
}
pool->freed = *(void**)obj;
return obj;
}
#endif /* zn_use_mempool */
#ifdef zn_use_timer /* need: mempool */
#undef zn_use_timer
#include <string.h>
typedef struct zn_TimerState {
zn_MemPool timers; \
zn_Timer **heap;
zn_Time nexttime;
unsigned used;
unsigned size;
} zn_TimerState;
struct zn_Timer {
union { zn_Timer *next; void *ud; } u;
zn_TimerHandler *handler;
zn_TimerState *ts;
unsigned index;
zn_Time start;
zn_Time emit;
};
static int znT_hastimers(zn_TimerState *ts)
{ return ts->used != 0; }
static void znT_cleartimers(zn_TimerState *ts) {
znM_freepool(&ts->timers);
free(ts->heap);
memset(ts, 0, sizeof(*ts));
ts->nexttime = ZN_FOREVER;
}
static void znT_updatetimers(zn_TimerState *ts, zn_Time current) {
if (ts->nexttime > current) return;
while (ts->used && ts->heap[0]->emit <= current) {
zn_Timer *timer = ts->heap[0];
zn_canceltimer(timer);
if (timer->handler) {
int ret = timer->handler(timer->u.ud,
timer, current - timer->start);
if (ret > 0) zn_starttimer(timer, ret);
}
}
ts->nexttime = ts->used == 0 ? ZN_FOREVER : ts->heap[0]->emit;
}
static zn_Time znT_gettimeout(zn_TimerState *ts, zn_Time current) {
zn_Time emit = ts->nexttime;
if (emit < current) return 0;
return emit - current;
}
static int znT_resizeheap(zn_TimerState *ts, size_t size) {
zn_Timer **heap;
size_t realsize = ZN_MAX_TIMERHEAP;
while (realsize < size && realsize < ZN_MAX_SIZET/sizeof(zn_Timer*)/2)
realsize <<= 1;
if (realsize < size) return 0;
heap = (zn_Timer**)realloc(ts->heap, realsize*sizeof(zn_Timer*));
if (heap == NULL) return 0;
ts->heap = heap;
ts->size = (unsigned)realsize;
return 1;
}
static zn_Timer *znT_newtimer(zn_TimerState *ts, zn_TimerHandler *cb, void *ud) {
zn_Timer *timer = (zn_Timer*)znM_getobject(&ts->timers);
if (timer == NULL) return NULL;
timer->u.ud = ud;
timer->handler = cb;
timer->ts = ts;
timer->index = ZN_TIMER_NOINDEX;
return timer;
}
ZN_API void zn_deltimer(zn_Timer *timer) {
zn_canceltimer(timer);
timer->handler = NULL;
znM_putobject(&timer->ts->timers, timer);
}
ZN_API int zn_starttimer(zn_Timer *timer, zn_Time delayms) {
zn_TimerState *ts = timer->ts;
unsigned i, p;
if (timer->index != ZN_TIMER_NOINDEX)
zn_canceltimer(timer);
if (ts->size == ts->used
&& !znT_resizeheap(ts, ts->size * 2))
return ZN_ERROR;
i = ts->used++;
timer->start = zn_time();
timer->emit = timer->start + delayms;
while (p = (i-1)>>1, i > 0 && ts->heap[p]->emit > timer->emit)
(ts->heap[i] = ts->heap[p])->index = i, i = p;
(ts->heap[i] = timer)->index = i;
if (i == 0) ts->nexttime = timer->emit;
return ZN_OK;
}
ZN_API void zn_canceltimer(zn_Timer *timer) {
zn_TimerState *ts = timer->ts;
unsigned i = timer->index, p, k;
if (i == ZN_TIMER_NOINDEX) return;
timer->index = ZN_TIMER_NOINDEX;
if (ts->used == 0 || timer == ts->heap[--ts->used])
return;
timer = ts->heap[ts->used];
while (p = (i-1)>>1, i > 0 && ts->heap[p]->emit > timer->emit)
(ts->heap[i] = ts->heap[p])->index = i, i = p;
while ((k = i<<1|1) < ts->used
&& timer->emit > ts->heap[
k += k+1 < ts->used && ts->heap[k]->emit > ts->heap[k+1]->emit
]->emit)
(ts->heap[i] = ts->heap[k])->index = i, i = k;
(ts->heap[i] = timer)->index = i;
}
#endif /* zn_use_timer */
#ifdef zn_use_api /* need: state, backend, addr */
#undef zn_use_api
ZN_API unsigned zn_retain (zn_State *S) { return ++S->waitings; }
ZN_API unsigned zn_release (zn_State *S) { return --S->waitings; }
ZN_API void *zn_getuserdata (zn_State *S) { return S->userdata; }
ZN_API void zn_setuserdata (zn_State *S, void *ud) { S->userdata = ud; }
ZN_API zn_Timer *zn_newtimer(zn_State *S, zn_TimerHandler *h, void *ud)
{ return znT_newtimer(&S->ts, h, ud); }
ZN_API void zn_getpeerinfo(zn_Tcp *tcp, zn_PeerInfo *info)
{ *info = tcp->peer_info; }
ZN_API int zn_closeaccept(zn_Accept *accept) { return znP_closeaccept(accept); }
ZN_API int zn_closetcp(zn_Tcp *tcp) { return znP_closetcp(tcp); }
ZN_API int zn_closeudp(zn_Udp *udp) { return znP_closeudp(udp); }
static int znS_poll(zn_State *S, int checkonly) {
zn_Time current, timeout = 0;
int has_more;
S->status = ZN_STATUS_IN_RUN;
znT_updatetimers(&S->ts, current = zn_time());
if (!checkonly) timeout = znT_gettimeout(&S->ts, current);
has_more = znP_poll(S, timeout);
znT_updatetimers(&S->ts, zn_time());
if (S->status == ZN_STATUS_CLOSING_IN_RUN) {
S->status = ZN_STATUS_READY; /* trigger real close */
zn_close(S);
return 0;
}
S->status = ZN_STATUS_READY;
return has_more || znT_hastimers(&S->ts) || S->waitings > 0;
}
ZN_API const char *zn_strerror(int err) {
const char *msg = "Unknown error";
switch (err) {
#define X(name, str) case ZN_##name: msg = str; break;
ZN_ERRORS(X)
#undef X
}
return msg;
}
ZN_API zn_State *zn_newstate(void) {
zn_State *S = (zn_State*)malloc(sizeof(zn_State));
if (S == NULL) return NULL;
memset(S, 0, sizeof(*S));
S->ts.nexttime = ZN_FOREVER;
znL_init(&S->active_accepts);
znL_init(&S->active_tcps);
znL_init(&S->active_udps);
znM_initpool(&S->ts.timers, sizeof(zn_Timer));
znM_initpool(&S->posts, sizeof(zn_Post));
znM_initpool(&S->accepts, sizeof(zn_Accept));
znM_initpool(&S->tcps, sizeof(zn_Tcp));
znM_initpool(&S->udps, sizeof(zn_Udp));
if (!znP_init(S)) {
free(S);
return NULL;
}
return S;
}
ZN_API void zn_close(zn_State *S) {
int status = S->status;
if (status == ZN_STATUS_IN_RUN || status == ZN_STATUS_CLOSING_IN_RUN) {
S->status = ZN_STATUS_CLOSING_IN_RUN;
return;
}
/* 0. doesn't allow create new objects */
S->status = ZN_STATUS_CLOSING;
/* 1. cancel all operations */
znT_cleartimers(&S->ts);
znL_apply(zn_Accept, &S->active_accepts, zn_delaccept(cur));
znL_apply(zn_Tcp, &S->active_tcps, zn_deltcp(cur));
znL_apply(zn_Udp, &S->active_udps, zn_deludp(cur));
znP_close(S);
/* 2. delete all remaining objects */
znM_freepool(&S->posts);
znM_freepool(&S->accepts);
znM_freepool(&S->tcps);
znM_freepool(&S->udps);
free(S);
}
ZN_API int zn_run(zn_State *S, int mode) {
int err;
switch (mode) {
case ZN_RUN_CHECK:
return znS_poll(S, 1);
case ZN_RUN_ONCE:
return znS_poll(S, 0);
case ZN_RUN_LOOP:
while ((err = znS_poll(S, 0)) > 0)
;
return err;
}
return -ZN_ERROR;
}
ZN_API zn_Accept* zn_newaccept(zn_State *S, int packet) {
ZN_GETOBJECT(S, zn_Accept, accept);
accept->socket = ZN_INVALID_SOCKET;
#ifdef zn_have_info
accept->info.type = ZN_SOCK_ACCEPT;
accept->info.head = accept;
#endif /* zn_have_info */
accept->type = packet ? SOCK_DGRAM : SOCK_STREAM;
znP_initaccept(accept);
return accept;
}
ZN_API void zn_delaccept(zn_Accept *accept) {
if (accept == NULL) return;
zn_closeaccept(accept);
if (accept->accept_handler == NULL)
ZN_PUTOBJECT(accept);
}
ZN_API int zn_listen(zn_Accept *accept, const char *addr, unsigned port) {
zn_SockAddr local_addr;
if (accept == NULL) return ZN_EPARAM;
if (accept->socket != ZN_INVALID_SOCKET) return ZN_ESTATE;
if (accept->accept_handler != NULL) return ZN_EBUSY;
if (!znU_parseaddr(&local_addr, addr, port)) return ZN_EPARAM;
return znP_listen(accept, &local_addr);
}
ZN_API int zn_accept(zn_Accept *accept, zn_AcceptHandler *cb, void *ud) {
int ret;
if (accept == NULL || cb == NULL) return ZN_EPARAM;
if (accept->socket == ZN_INVALID_SOCKET) return ZN_ESTATE;
if ((ret = znP_accept(accept)) == ZN_OK) {
accept->accept_handler = cb;
accept->accept_ud = ud;
zn_retain(accept->S);
}
return ret;
}
ZN_API zn_Tcp* zn_newtcp(zn_State *S) {
ZN_GETOBJECT(S, zn_Tcp, tcp);
tcp->socket = ZN_INVALID_SOCKET;
#ifdef zn_have_info
tcp->info.type = ZN_SOCK_TCP;
tcp->info.head = tcp;
#endif /* zn_have_info */
znP_inittcp(tcp);
return tcp;
}
ZN_API void zn_deltcp(zn_Tcp *tcp) {
if (tcp == NULL) return;
zn_closetcp(tcp);
/* if a request is on-the-go, then the IOCP will give callback, we
* delete object on that callback. notice if you do not submit a
* request, IOCP will not queued the callback, so delete is safe.
* same as zn_delaccept() and zn_deludp() */
if (tcp->connect_handler == NULL
&& tcp->recv_handler == NULL
&& tcp->send_handler == NULL)
ZN_PUTOBJECT(tcp);
}
ZN_API int zn_connect(zn_Tcp *tcp, const char *addr, unsigned port, int packet, zn_ConnectHandler *cb, void *ud) {
zn_SockAddr remote_addr;
int ret;
if (tcp == NULL || cb == NULL) return ZN_EPARAM;
if (tcp->socket != ZN_INVALID_SOCKET) return ZN_ESTATE;
if (tcp->connect_handler != NULL) return ZN_EBUSY;
if (znU_parseaddr(&remote_addr, addr, port) == 0) return ZN_EPARAM;
if ((ret = znP_connect(tcp, &remote_addr, packet ?
SOCK_DGRAM : SOCK_STREAM)) != ZN_OK)
return ret;
assert(strlen(addr) < ZN_MAX_ADDRLEN);
strcpy(tcp->peer_info.addr, addr);
tcp->peer_info.port = port;
tcp->connect_handler = cb;
tcp->connect_ud = ud;
zn_retain(tcp->S);
return ret;
}
ZN_API int zn_send(zn_Tcp *tcp, const char *buff, unsigned len, zn_SendHandler *cb, void *ud) {
int ret;
if (tcp == NULL || cb == NULL || len == 0) return ZN_EPARAM;
if (tcp->socket == ZN_INVALID_SOCKET) return ZN_ESTATE;
if (tcp->send_handler != NULL) return ZN_EBUSY;
tcp->send_buffer.buf = (char*)buff;
tcp->send_buffer.len = len;
if ((ret = znP_send(tcp)) != ZN_OK) {
tcp->send_buffer.buf = NULL;
tcp->send_buffer.len = 0;
} else {
tcp->send_handler = cb;
tcp->send_ud = ud;
zn_retain(tcp->S);
}
return ret;
}
ZN_API int zn_recv(zn_Tcp *tcp, char *buff, unsigned len, zn_RecvHandler *cb, void *ud) {
int ret;
if (tcp == NULL || cb == NULL || len == 0) return ZN_EPARAM;
if (tcp->socket == ZN_INVALID_SOCKET) return ZN_ESTATE;
if (tcp->recv_handler != NULL) return ZN_EBUSY;
tcp->recv_buffer.buf = buff;
tcp->recv_buffer.len = len;
if ((ret = znP_recv(tcp)) != ZN_OK) {
tcp->recv_buffer.buf = NULL;
tcp->recv_buffer.len = 0;
} else {
tcp->recv_handler = cb;
tcp->recv_ud = ud;
zn_retain(tcp->S);
}
return ret;
}
ZN_API zn_Udp* zn_newudp(zn_State *S, const char *addr, unsigned port) {
zn_SockAddr local_addr;
ZN_GETOBJECT(S, zn_Udp, udp);
if (znU_parseaddr(&local_addr, addr, port) == 0) {
ZN_PUTOBJECT(udp);
return NULL;
}
udp->socket = ZN_INVALID_SOCKET;
if (znP_initudp(udp, &local_addr) != ZN_OK) {
ZN_PUTOBJECT(udp);
return NULL;
}
#ifdef zn_have_info
udp->info.type = ZN_SOCK_UDP;
udp->info.head = udp;
#endif /* zn_have_info */
return udp;
}
ZN_API void zn_deludp(zn_Udp *udp) {
if (udp == NULL) return;
znP_closeudp(udp);
if (udp->recv_handler == NULL)
ZN_PUTOBJECT(udp);
}
ZN_API int zn_sendto(zn_Udp *udp, const char *buff, unsigned len, const char *addr, unsigned port) {
zn_SockAddr remote_addr;
if (udp == NULL || len == 0 || len >1200) return ZN_EPARAM;
if (udp->socket == ZN_INVALID_SOCKET) return ZN_ESTATE;
if (znU_parseaddr(&remote_addr, addr, port) == 0) return ZN_EPARAM;
return znP_sendto(udp, buff, len, &remote_addr);
}
ZN_API int zn_recvfrom(zn_Udp *udp, char *buff, unsigned len, zn_RecvFromHandler *cb, void *ud) {
int ret;
if (udp == NULL || len == 0 || cb == NULL) return ZN_EPARAM;
if (udp->socket == ZN_INVALID_SOCKET) return ZN_ESTATE;
if (udp->recv_handler) return ZN_EBUSY;
udp->recv_buffer.buf = buff;
udp->recv_buffer.len = len;
if ((ret = znP_recvfrom(udp)) != ZN_OK) {
udp->recv_buffer.buf = NULL;
udp->recv_buffer.len = 0;
} else {
udp->recv_handler = cb;
udp->recv_ud = ud;
zn_retain(udp->S);
}
return ret;
}
#endif /* zn_use_api */
#ifdef zn_use_platform_win32
#undef zn_use_platform_win32
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#include <WinSock2.h>
#include <WS2Tcpip.h>
#include <MSWSock.h>
#ifdef _MSC_VER
# pragma warning(disable: 4996) /* deprecated stuffs */
# pragma warning(disable: 4127) /* for do {} while(0) */
# pragma comment(lib, "ws2_32")
#endif /* _MSC_VER */
#define ZN_INVALID_SOCKET INVALID_SOCKET
static int znU_pton(int af, const char *src, void *dst) {
struct sockaddr_storage ss;
int size = sizeof(ss);
char src_copy[INET6_ADDRSTRLEN+1];
ZeroMemory(&ss, sizeof(ss));
strncpy(src_copy, src, INET6_ADDRSTRLEN+1);
src_copy[INET6_ADDRSTRLEN] = 0;
if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr*)&ss, &size) == 0) {
switch(af) {
case AF_INET:
*(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
return 1;
case AF_INET6:
*(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
return 1;
}
}
return 0;
}
static const char *znU_ntop(int af, const void *src, char *dst, socklen_t size) {
struct sockaddr_storage ss;
unsigned long s = size;
ZeroMemory(&ss, sizeof(ss));
ss.ss_family = af;
switch(af) {
case AF_INET:
((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src;
break;
case AF_INET6:
((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src;
break;
default:
return NULL;
}
return WSAAddressToString(
(struct sockaddr*)&ss, sizeof(ss), NULL, dst, &s) == 0 ? dst : NULL;
}
static int znU_set_nodelay(SOCKET socket) {
BOOL bEnable = 1;
return setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,
(const char*)&bEnable, sizeof(bEnable)) == 0;
}
static int znU_update_acceptinfo(SOCKET server, SOCKET client) {
return setsockopt(client, SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT,
(const char*)&server, sizeof(server)) == 0;
}
static int znU_set_reuseaddr(SOCKET socket) {
BOOL bReuseAddr = TRUE;
return setsockopt(socket, SOL_SOCKET, SO_REUSEADDR,
(const char*)&bReuseAddr, sizeof(BOOL)) == 0;
}
static int znU_error(int syserr) {
switch (syserr) {
case WSAECONNABORTED:
case WSAECONNREFUSED:
case WSAECONNRESET:
return ZN_EHANGUP;
}
return ZN_ERROR;
}
ZN_API zn_Time zn_time(void) {
static LARGE_INTEGER counterFreq;
static LARGE_INTEGER startTime;
LARGE_INTEGER current;
if (counterFreq.QuadPart == 0) {
QueryPerformanceFrequency(&counterFreq);
QueryPerformanceCounter(&startTime);
assert(counterFreq.HighPart == 0);
return 0;
}
QueryPerformanceCounter(¤t);
return (zn_Time)((current.QuadPart - startTime.QuadPart) * 1000
/ counterFreq.LowPart);
}
#endif /* zn_use_platform_win32 */
#ifdef zn_use_platform_posix
#undef zn_use_platform_posix
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#ifdef zn_use_backend_epoll
# include <sys/eventfd.h>
# include <sys/epoll.h>
#endif
#ifdef zn_use_backend_kqueue
# include <sys/event.h>
#endif
#ifdef __MACH__
# include <mach/mach.h>
# include <mach/mach_time.h>
#endif /* __MACH__ */
#define ZN_INVALID_SOCKET (-1)
#ifdef MSG_NOSIGNAL
# define ZN_NOSIGNAL MSG_NOSIGNAL
#else
# define ZN_NOSIGNAL 0
#endif
#define znU_pton inet_pton
#define znU_ntop inet_ntop
typedef enum zn_SocketType {
ZN_SOCK_ACCEPT,
ZN_SOCK_TCP,
ZN_SOCK_UDP,
} zn_SocketType;
typedef struct zn_SocketInfo {
int type;
void *head;
} zn_SocketInfo;
typedef struct zn_DataBuffer {
size_t len;
char *buf;
} zn_DataBuffer;
static int znU_set_nodelay(int socket) {
int enable = 1;
return setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,
(const void*)&enable, sizeof(enable)) == 0;
}
static int znU_set_nonblock(int socket) {
return fcntl(socket, F_SETFL,
fcntl(socket, F_GETFL)|O_NONBLOCK) == 0;
}
static int znU_set_reuseaddr(int socket) {
int reuse_addr = 1;
return setsockopt(socket, SOL_SOCKET, SO_REUSEADDR,
(const void*)&reuse_addr, sizeof(reuse_addr)) == 0;
}
static int znU_set_nosigpipe(int socket) {
#ifdef SO_NOSIGPIPE
int no_sigpipe = 1;
return setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE,
(char*)&no_sigpipe, sizeof(no_sigpipe)) == 0;
#else
(void)socket;
return 0;
#endif /* SO_NOSIGPIPE */
}
static int znU_error(int syserr) {
switch (syserr) {
case EPIPE:
case ECONNABORTED:
case ECONNREFUSED:
case ECONNRESET:
return ZN_EHANGUP;
}
return ZN_ERROR;
}
ZN_API zn_Time zn_time(void) {
#ifdef __MACH__
static mach_timebase_info_data_t time_info;
static uint64_t start;
uint64_t now = mach_absolute_time();
if (!time_info.numer) {
start = now;
(void)mach_timebase_info(&time_info);
return 0;
}
return (zn_Time)((now - start) * time_info.numer / time_info.denom / 1000000);
#else
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
return 0;
return (zn_Time)(ts.tv_sec*1000+ts.tv_nsec/1000000);
#endif
}
#endif /* zn_use_platform_posix */
#ifdef zn_use_addr /* need: platform */
#undef zn_use_addr
#define znU_family(sa) ((sa)->addr.sa_family)
#define znU_isv6(sa) (znU_family(sa) == AF_INET6)
#define znU_size(sa) (znU_isv6(sa)? sizeof((sa)->ipv6) : sizeof((sa)->ipv4))
typedef union zn_SockAddr {
struct sockaddr addr;
struct sockaddr_in ipv4;
struct sockaddr_in6 ipv6;
} zn_SockAddr;
static int znU_ipproto(int type)
{ return type == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP; }
static int znU_parseaddr(zn_SockAddr *ret, const char *addr, unsigned port) {
memset(ret, 0, sizeof(*ret));
if (strchr(addr, ':') != 0) {
ret->ipv6.sin6_family = AF_INET6;
ret->ipv6.sin6_port = htons(port);
if (znU_pton(AF_INET6, addr, &ret->ipv6.sin6_addr) != 1)
return 0;
} else {
ret->ipv4.sin_family = AF_INET;
ret->ipv4.sin_port = htons(port);
if (znU_pton(AF_INET, addr, &ret->ipv4.sin_addr) != 1)
return 0;