-
Notifications
You must be signed in to change notification settings - Fork 0
/
lsocket.c
1440 lines (1308 loc) · 34.5 KB
/
lsocket.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
/* lsocket.c
*
* provide simple and easy socket support for lua
*
* Gunnar Zötl <gz@tset.de>, 2013-03
* Released under MIT/X11 license. See file LICENSE for details.
*
*
*/
#include "mbuf.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include <sys/stat.h>
#include <dirent.h>
#include <ifaddrs.h>
#include <stdint.h>
#ifndef IPV6_ADD_MEMBERSHIP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif
#include "lua.h"
#include "lauxlib.h"
#define LSOCKET_VERSION "1.1"
#define LSOCKET "socket"
#define TOSTRING_BUFSIZ 64
#define READER_BUFSIZ 4096
#define LSOCKET_EMPTY "lsocket_empty_table"
/* address families */
#define LSOCKET_INET "inet"
#define LSOCKET_INET6 "inet6"
/* socket types */
#define LSOCKET_TCP "tcp"
#define LSOCKET_UDP "udp"
#define LSOCKET_MCAST "mcast"
/* default TTL for multicast sockets */
#define LSOCKET_DFLTTL 1
/* default backlog for listening connections */
#define DFL_BACKLOG 5
#if LUA_VERSION_NUM == 501
#define luaL_newlib(L,funcs) lua_newtable(L); luaL_register(L, NULL, funcs)
#define luaL_setfuncs(L,funcs,x) luaL_register(L, NULL, funcs)
#endif
/*** Userdata handling ***/
/* structure for socket userdata */
typedef struct _lsocket_socket {
int sockfd;
int family;
int type;
int mcast;
int protocol;
int listening;
mbuf_t *input_buf; //接收buf
} lSocket;
/* lsocket_checklSocket
*
* Checks whether the item at the index on the lua stack is a userdata of
* the type LSOCKET. If so, returns its block address, else throw an error.
*
* Arguments:
* L Lua State
* index stack index where the userdata is expected
*/
static lSocket* lsocket_checklSocket(lua_State *L, int index)
{
lSocket *sock = (lSocket*) luaL_checkudata(L, index, LSOCKET);
return sock;
}
/* lsocket_islSocket
*
* Checks whether the item at the index on the lua stack is a userdata of
* the type LSOCKET. Returns 1 if it is, 0 otherwise.
*
* Arguments:
* L Lua State
* index stack index where the userdata is expected
*/
static int lsocket_islSocket(lua_State *L, int index)
{
if (lua_isuserdata(L, index)) {
if (lua_getmetatable(L, index)) {
luaL_getmetatable(L, LSOCKET);
if (lua_rawequal(L, -1, -2)) {
lua_pop(L, 2);
return 1;
}
lua_pop(L, 2);
}
}
return 0;
}
/* lsocket_pushlSocket
*
* create a new, empty lSocket userdata, attach its metatable and push it to the stack.
*
* Arguments:
* L Lua state
*
* Lua Returns:
* +1 lSocket userdata
*/
static lSocket* lsocket_pushlSocket(lua_State *L)
{
lSocket *sock = (lSocket*) lua_newuserdata(L, sizeof(lSocket));
sock->input_buf = (mbuf_t *)malloc(sizeof(mbuf_t));
mbuf_init(sock->input_buf, 10240);
luaL_getmetatable(L, LSOCKET);
lua_setmetatable(L, -2);
return sock;
}
/*** Housekeeping metamethods ***/
/* lsocket_gc
*
* __gc metamethod for the sock userdata.
* closes socket if it is still open
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 lSocket userdata
*/
static int lsocket_sock__gc(lua_State *L)
{
lSocket *sock = (lSocket*) lua_touserdata(L, 1);
if (sock->sockfd > 0)
close(sock->sockfd);
mbuf_free(sock->input_buf);
sock->sockfd = -1;
sock->input_buf = NULL;
return 0;
}
/* lsocket_toString
*
* __tostring metamethod for the lsock userdata.
* Returns a string representation of the lSocket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 lSocket userdata
*
* Lua Returns:
* +1 string representation of lSocket userdata
*/
static int lsocket_sock__toString(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
char buf[TOSTRING_BUFSIZ];
/* length of type name + length of hex pointer rep + '0x' + ': ' + '\0' */
if (strlen(LSOCKET) + (sizeof(void*) * 2) + 2 + 3 > TOSTRING_BUFSIZ)
return luaL_error(L, "Whoopsie... the string representation seems to be too long.");
/* this should not happen, just to be sure! */
sprintf(buf, "%s: %p", LSOCKET, sock);
lua_pushstring(L, buf);
return 1;
}
/* metamethods for the sock userdata
*/
static const luaL_Reg lSocket_meta[] = {
{"__gc", lsocket_sock__gc},
{"__tostring", lsocket_sock__toString},
{0, 0}
};
/*** global helper functions ***/
/* lsocket_error
*
* pushes nil and an error message onto the lua stack and returns 2
*
* Arguments:
* L lua State
* msg error message
*
* Returns:
* 2 (number of items put on the lua stack)
*/
static int lsocket_error(lua_State *L, const char *msg)
{
lua_pushnil(L);
lua_pushstring(L, msg);
return 2;
}
/* _initsocket
*
* helper function: initialize a socket object.
*
* Arguments:
* sock the socket userdata
* type, protocol
* as specified for socket creation
* listen flag for whether the socket is listening for incoming connections
*
* Returns:
* 0 if all went ok, -1 on failure.
*/
static int _initsocket(lSocket *sock, int family, int type, int mcast, int protocol, int listening)
{
if (sock->sockfd == -1)
return 0;
int on = 1;
setsockopt(sock->sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
fcntl(sock->sockfd, F_SETFL, O_NONBLOCK);
#if defined(SO_NOSIGPIPE)
on = 1;
setsockopt(sock->sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *) &on, sizeof(on));
#endif
sock->family = family;
sock->type = type;
sock->mcast = mcast;
sock->protocol = protocol;
sock->listening = listening;
return 0;
}
/* _addr2string
*
* helper function: converts a sockaddr to a string, family independent
*
* Arguments:
* sa sockaddr to convert
* buf buffer to write result into
* buflen length of buffer
*
* Returns:
* the result of inet_ntop: a pointer to buf on success, or NULL on
* failure.
*/
static const char *_addr2string(struct sockaddr *sa, char *buf, int buflen)
{
const char *s;
if (sa->sa_family == AF_INET)
s = inet_ntop(sa->sa_family, (const void*) &((struct sockaddr_in*)sa)->sin_addr, buf, TOSTRING_BUFSIZ);
else
s = inet_ntop(sa->sa_family, (const void*) &((struct sockaddr_in6*)sa)->sin6_addr, buf, TOSTRING_BUFSIZ);
return s;
}
/* _portnumber
*
* extracts the port number from a sockaddr, family independent
*
* Arguments:
* sa sockaddr to extract port number from
*
* Returns:
* the extracted and to local byte order converted port number
*/
static uint16_t _portnumber(struct sockaddr *sa)
{
uint16_t port;
if (sa->sa_family == AF_INET)
port = ((struct sockaddr_in*)sa)->sin_port;
else
port = ((struct sockaddr_in6*)sa)->sin6_port;
return ntohs(port);
}
/* _needsnolookup
*
* helper function: checks if the address consists only of chars that
* make up a valid ip(v4 or v6) address, and thus needs no nslookup.
*
* Arguments:
* addr address to check
*
* Returns:
* 1 if the address consists only of chars that make up a valid ip(v4
* or v6) address, 0 otherwise.
*
* Note: this does not check whether the address is a valid ip address,
* just whether it consists of chars that make up one.
*/
static int _needsnolookup(const char *addr)
{
int len = strlen(addr);
int pfx = strspn(addr, "0123456789.");
if (pfx != len) {
pfx = strspn(addr, "0123456789abcdefABCDEF:");
/* last 2 words may be in dot notation */
if (addr[pfx] == '.')
pfx += strspn(addr + pfx, "0123456789.");
}
return pfx == len;
}
/* _gethostaddr
*
* gets the address of a host passed by name, and fills out a sockaddr
* structure
*
* Arguments:
* L lua State
* addr ip address or hostname
* type SOCK_STREAM or SOCK_DGRAM
* port port number for sockaddr
* family (out) address family (AF_INET or AF_INET6) of address
* protocol (out) protocol of address
* sa (out) pointer to struct sockaddr to fill with data.
* slen (inout) length of sa, and on return length of data
*
* Returns:
* 0 when the lookup succeeded, -1 otherwise
* On success, the arguments family, protocol, sa and slen will have
* been updated with values from the looked up address
*/
static int _gethostaddr(lua_State *L, const char *addr, int type, int port, int *family, int *protocol, struct sockaddr *sa, socklen_t *slen)
{
struct addrinfo hint, *info =0;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
hint.ai_socktype = type;
if (_needsnolookup(addr))
hint.ai_flags = AI_NUMERICHOST;
int err = getaddrinfo(addr, 0, &hint, &info);
if (err != 0) {
if (info) freeaddrinfo(info);
return lsocket_error(L, gai_strerror(err));
} else if (info->ai_family != AF_INET && info->ai_family != AF_INET6) {
if (info) freeaddrinfo(info);
return lsocket_error(L, "unknown address family");
}
*family = info->ai_family;
*slen = info->ai_addrlen;
*protocol = info->ai_protocol;
memcpy(sa, info->ai_addr, *slen);
if (*family == AF_INET)
((struct sockaddr_in*) sa)->sin_port = htons(port);
else
((struct sockaddr_in6*) sa)->sin6_port = htons(port);
freeaddrinfo(info);
return 0;
}
/*** socket constructors */
/* lsocket_bind
*
* bind a socket to a specific address and port.
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 (optional) "tcp" or "udp" or "mcast"
* 2 (optional) the address to bind to, as a hostname or ip address string
* 3 the port to bind to
* 4 (optional) backlog for listen
*
* Lua Returns:
* +1 the lSocket userdata passed as first argument
* or +1 nil, +2 error message
*/
static int lsocket_bind(lua_State *L)
{
char sabuf[sizeof(struct sockaddr_in6)];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
int family = AF_INET;
int protocol = 0;
int mcast = 0;
const char *addr = NULL;
int type = SOCK_STREAM;
int top = 1;
/* (optional) socket type */
if (lua_type(L, top) == LUA_TSTRING) {
const char *str = lua_tostring(L, top);
if (!strcasecmp(str, LSOCKET_TCP)) {
top += 1;
} else if (!strcasecmp(str, LSOCKET_UDP)) {
type = SOCK_DGRAM;
top += 1;
} else if (!strcasecmp(str, LSOCKET_MCAST)) {
type = SOCK_DGRAM;
mcast = 1;
top += 1;
}
}
/* (optional) ip address to bind to */
if (lua_type(L, top) == LUA_TSTRING) {
addr = lua_tostring(L, top++);
}
/* port to bind to */
int port = luaL_checknumber(L, top++);
/* backlog len */
int backlog = luaL_optnumber(L, top, DFL_BACKLOG);
if (addr) {
int err = _gethostaddr(L, addr, type, port, &family, &protocol, sa, &slen);
if (err) return err;
} else {
/* default: bind to ipv4 INADDR_ANY */
memset(&sabuf, 0, sizeof(sabuf));
struct sockaddr_in *si = (struct sockaddr_in*) sa;
sa->sa_family = AF_INET;
si->sin_addr.s_addr = INADDR_ANY;
si->sin_port = htons(port);
slen = sizeof(struct sockaddr_in);
}
lSocket *sock = lsocket_pushlSocket(L);
sock->sockfd = socket(family, type, protocol);
_initsocket(sock, family, type, mcast, protocol, 1);
/* setup socket for broad/multicast if necessary */
if (mcast) {
if (family == AF_INET) {
if (setsockopt(sock->sockfd, SOL_SOCKET, SO_BROADCAST, &mcast, sizeof(mcast)) < 0)
return lsocket_error(L, strerror(errno));
} else {
struct ipv6_mreq mcr;
memcpy(&mcr.ipv6mr_multiaddr, &((struct sockaddr_in6*)sa)->sin6_addr, sizeof(mcr.ipv6mr_multiaddr));
mcr.ipv6mr_interface = 0;
if (setsockopt(sock->sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mcr, sizeof(mcr)) < 0)
return lsocket_error(L, strerror(errno));
}
}
if (bind(sock->sockfd, sa, slen) < 0)
return lsocket_error(L, strerror(errno));
/* only listen for tcp sockets, does not make much sense for udp */
if (type == SOCK_STREAM)
if (listen(sock->sockfd, backlog) < 0)
return lsocket_error(L, strerror(errno));
return 1;
}
/* lsocket_connect
*
* connect a socket to a specific address and port.
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 (optional) "tcp" or "udp" or "mcast"
* 2 the address to bind to, as a hostname or ip address string
* 3 the port to bind to
* 4 (optional) ttl for multicasts
*
* Lua Returns:
* +1 the lSocket userdata passed as first argument
* or +1 nil, +2 error message
*/
static int lsocket_connect(lua_State *L)
{
int type = SOCK_STREAM;
int top = 1;
char sabuf[sizeof(struct sockaddr_in6)];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
int family = AF_INET;
int protocol = 0;
int mcast = 0;
/* (optional) socket type */
if (lua_type(L, top) == LUA_TSTRING) {
const char *str = lua_tostring(L, 1);
if (!strcasecmp(str, LSOCKET_TCP))
top += 1;
else if (!strcasecmp(str, LSOCKET_UDP)) {
type = SOCK_DGRAM;
top += 1;
} else if (!strcasecmp(str, LSOCKET_MCAST)) {
type = SOCK_DGRAM;
mcast = 1;
top += 1;
}
}
/* ip address to connect to */
const char *addr = luaL_checkstring(L, top);
/* port to connect to */
int port = luaL_checknumber(L, top + 1);
/* ttl in the case of multicast */
int ttl = luaL_optnumber(L, top + 2, LSOCKET_DFLTTL);
int err = _gethostaddr(L, addr, type, port, &family, &protocol, sa, &slen);
if (err) return err;
lSocket *sock = lsocket_pushlSocket(L);
sock->sockfd = socket(family, type, protocol);
_initsocket(sock, family, type, mcast, protocol, 0);
if (mcast) {
int ok;
if (setsockopt(sock->sockfd, SOL_SOCKET, SO_BROADCAST, &mcast, sizeof(mcast)) < 0)
return lsocket_error(L, strerror(errno));
if (family == AF_INET) {
ok = setsockopt(sock->sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
} else
ok = setsockopt(sock->sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl));
if (ok < 0)
return lsocket_error(L, strerror(errno));
}
if (connect(sock->sockfd, sa, slen) < 0 && errno != EINPROGRESS)
return lsocket_error(L, strerror(errno));
return 1;
}
/*** socket methods ***/
/* _push_sockname
*
* helper for lsocket_sock_info: create a table with fields port, family
* and addr from the sockaddr passed as argument, and leave it on the
* stack. Leave nil on error.
*
* Arguments:
* L Lua State
* sa pointer to sockaddr to get data from
*
* Lua Returns:
* +1 table with info about address, or nil
*/
static void _push_sockname(lua_State *L, struct sockaddr *sa)
{
char buf[TOSTRING_BUFSIZ];
const char *s;
lua_newtable(L);
lua_pushliteral(L, "port");
lua_pushnumber(L, _portnumber(sa));
lua_rawset(L, -3);
lua_pushliteral(L, "family");
lua_pushstring(L, sa->sa_family == AF_INET ? LSOCKET_INET : LSOCKET_INET6);
lua_rawset(L, -3);
lua_pushliteral(L, "addr");
s = _addr2string(sa, buf, TOSTRING_BUFSIZ);
if (s) {
lua_pushstring(L, s);
lua_rawset(L, -3);
} else {
lua_pop(L, 1);
}
}
/* lsocket_sock_info
*
* returns a table with information about the socket, such as file descriptor,
* family, type, and listening, or local and peer addresses.
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
* 2 (optional) what to return info about ("peer", "socket")
*
* Lua Returns:
* +1 the table with the information
* for what==none or nil: in the fields fd, family, type, listening
* for what == "peer" or "socket": addr, port
*/
static int lsocket_sock_info(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
const char *which = luaL_optstring(L, 2, NULL);
char sabuf [sizeof(struct sockaddr_in6)];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
if (which == NULL) {
lua_newtable(L);
lua_pushliteral(L, "fd");
lua_pushnumber(L, sock->sockfd);
lua_rawset(L, -3);
lua_pushliteral(L, "family");
switch (sock->family) {
case AF_INET: lua_pushliteral(L, LSOCKET_INET); break;
case AF_INET6: lua_pushliteral(L, LSOCKET_INET6); break;
default: lua_pushliteral(L, "unknown");
}
lua_rawset(L, -3);
lua_pushliteral(L, "type");
switch (sock->type) {
case SOCK_STREAM: lua_pushliteral(L, LSOCKET_TCP); break;
case SOCK_DGRAM: lua_pushliteral(L, LSOCKET_UDP); break;
default: lua_pushliteral(L, "unknown");
}
lua_rawset(L, -3);
lua_pushliteral(L, "listening");
lua_pushboolean(L, sock->listening);
lua_rawset(L, -3);
lua_pushliteral(L, "multicast");
lua_pushboolean(L, sock->mcast);
lua_rawset(L, -3);
} else if (!strcasecmp(which, "peer")) {
if (getpeername(sock->sockfd, sa, &slen) >= 0)
_push_sockname(L, sa);
else
return lsocket_error(L, strerror(errno));
} else if (!strcasecmp(which, "socket")) {
if (getsockname(sock->sockfd, sa, &slen) >= 0)
_push_sockname(L, sa);
else
return lsocket_error(L, strerror(errno));
} else {
lua_pop(L, 1);
lua_pushnil(L);
}
return 1;
}
static int lsocket_sock_status(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
int err;
socklen_t errl = sizeof(err);
if (getsockopt(sock->sockfd, SOL_SOCKET, SO_ERROR, &err, &errl) >= 0) {
if (err == 0)
lua_pushboolean(L, 1);
else
return lsocket_error(L, strerror(err));
} else
return lsocket_error(L, strerror(errno));
return 1;
}
/* _canacceptdata
*
* helper for all socket methods: check whether a send or receive operation
* can be performed without blocking
*
* Arguments:
* fd socket desctiptor to check
* send flag for whether to test if data can be sent (1) or received (0)
*
* Returns:
* 1 if the operation can be performed, 0 otherwise
*/
static int _canacceptdata(int fd, int send)
{
fd_set rfds;
struct timeval tv;
int ok = -1;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
if (send == 0)
ok = select(fd + 1, &rfds, NULL, NULL, &tv);
else
ok = select(fd + 1, NULL, &rfds, NULL, &tv);
return ok;
}
/* lsocket_sock_accept
*
* accept a new connection on a socket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
*
* Lua Returns:
* +1 new socket, +2 client ip, +3 client port on success
* or +1 false if nonblocking socket returned EAGAIN
* or +1 nil, +2 error message on error
*/
static int lsocket_sock_accept(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
char buf[TOSTRING_BUFSIZ];
if (!_canacceptdata(sock->sockfd, 0)) {
lua_pushboolean(L, 0);
return 1;
}
char sabuf[sizeof(struct sockaddr_in6)];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
int newfd = accept(sock->sockfd, sa, &slen);
if (newfd < 0)
return lsocket_error(L, strerror(errno));
lSocket *nsock = lsocket_pushlSocket(L);
nsock->sockfd = newfd;
if (_initsocket(nsock, sa->sa_family, sock->type, sock->mcast, sock->protocol, 0) == -1)
return lsocket_error(L, strerror(errno));
lua_pushstring(L, _addr2string(sa, buf, TOSTRING_BUFSIZ));
lua_pushnumber(L, _portnumber(sa));
return 3;
}
/* lsocket_sock_recv
*
* reads data from a socket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
* 2 (optional) the length of the buffer to use for reading, defaults
* to some internal value
*
* Lua Returns:
* +1 a string containing the data read
* or +1 false if nonblocking socket returned EAGAIN (no data available)
* or +1 nil if the remote end has closed the socket
* or +1 nil, +2 error message on error
*/
static int lsocket_sock_recv(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
uint32_t howmuch = luaL_optnumber(L, 2, READER_BUFSIZ);
if (lua_tonumber(L, 2) > UINT_MAX)
return luaL_error(L, "bad argument #1 to 'recv' (invalid number)");
char *buf = malloc(howmuch);
int nrd = recv(sock->sockfd, buf, howmuch, 0);
if (nrd < 0) {
free(buf);
if (errno == EAGAIN || errno == EWOULDBLOCK)
lua_pushboolean(L, 0);
else
return lsocket_error(L, strerror(errno));
} else if (nrd == 0)
lua_pushnil(L);
else {
lua_pushlstring(L, buf, nrd);
free(buf);
}
return 1;
}
/* lsocket_sock_recv_pkg
*
* reads packet from a socket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
* 2 (optional) the length of the buffer to use for reading, defaults
* to some internal value
*
* Lua Returns:
* +1 a string containing the packet data
* or +1 false if nonblocking socket returned EAGAIN (no data available)
* or +1 nil if the remote end has closed the socket
* or +1 nil, +2 error message on error
*/
//接收一个完整包,包含一个4字节头部,来确认包的长度
static int lsocket_sock_recv_pkg(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
uint32_t howmuch = luaL_optnumber(L, 2, READER_BUFSIZ);
if (lua_tonumber(L, 2) > UINT_MAX)
return luaL_error(L, "bad argument #1 to 'recv' (invalid number)");
char *buf = malloc(howmuch);
int nrd = recv(sock->sockfd, buf, howmuch, 0);
if (nrd < 0) {
free(buf);
if (errno == EAGAIN || errno == EWOULDBLOCK)
lua_pushboolean(L, 0);
else
return lsocket_error(L, strerror(errno));
} else if (nrd == 0) {
free(buf);
lua_pushnil(L);
}
else {
mbuf_enq(sock->input_buf, buf, nrd);
free(buf);
}
if (nrd <= 0) {
return 1;
}
//check if we get a packet
uint32_t sz = sock->input_buf->data_size;
if (sz <= 4) {
lua_pushboolean(L, 0);
return 1;
}
const char *data = mbuf_pullup(sock->input_buf);
uint32_t pkg_len = *(uint32_t *)data;
if (pkg_len + 4 > sz) {
lua_pushboolean(L, 0);
return 1;
}
lua_pushlstring(L, data + 4, pkg_len);
mbuf_drain(sock->input_buf, pkg_len + 4);
return 1;
}
//给数据打包成packet
static int lsocket_packet_pack(lua_State *L)
{
size_t sz;
const char *data = luaL_checklstring(L, 1, &sz);
uint32_t n = (uint32_t)sz;
char *buf = (char *)malloc(n + sizeof(n));
memcpy(buf, &n, sizeof(n));
memcpy(buf + sizeof(n), data, n);
lua_pushlstring(L, buf, n + sizeof(n));
free(buf);
return 1;
}
/* lsocket_sock_recvfrom
*
* reads data from a socket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
* 2 (optional) the length of the buffer to use for reading, defaults
* to some internal value
*
* Lua Returns:
* +1 a string containing the data read
* +2 ip address if remote end
* +3 port of remote end
* or +1 false if nonblocking socket returned EAGAIN (no data available)
* or +1 nil if the remote end has closed the socket
* or +1 nil, +2 error message on error
*/
static int lsocket_sock_recvfrom(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
uint32_t howmuch = luaL_optnumber(L, 2, READER_BUFSIZ);
if (lua_tonumber(L, 2) > UINT_MAX)
return luaL_error(L, "bad argument #1 to 'recvfrom' (invalid number)");
char sabuf[sizeof(struct sockaddr_in6)];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
char *buf = malloc(howmuch);
int nrd = recvfrom(sock->sockfd, buf, howmuch, 0, sa, &slen);
if (nrd < 0) {
free(buf);
if (errno == EAGAIN || errno == EWOULDBLOCK)
lua_pushboolean(L, 0);
else
return lsocket_error(L, strerror(errno));
} else if (nrd == 0)
lua_pushnil(L); /* not possible for udp, so should not get here */
else {
lua_pushlstring(L, buf, nrd);
free(buf);
char ipbuf[TOSTRING_BUFSIZ];
const char *s = _addr2string(sa, ipbuf, TOSTRING_BUFSIZ);
if (s)
lua_pushstring(L, s);
else
return lsocket_error(L, strerror(errno)); /* should not happen */
lua_pushnumber(L, _portnumber(sa));
return 3;
}
return 1;
}
/* lsocket_sock_send
*
* writes data to a socket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
* 2 string containing data to be written to socket
*
* Lua Returns:
* +1 the number of bytes written
* or +1 false if nonblocking socket returned EAGAIN (not ready to accept data)
* or +1 nil, +2 error message
*/
static int lsocket_sock_send(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
size_t len;
const char *data = luaL_checklstring(L, 2, &len);
int flags = 0;
#if defined(MSG_NOSIGNAL)
flags = MSG_NOSIGNAL;
#elif !defined(SO_NOSIGPIPE)
struct sigaction sa_old, sa_new;
sa_new.sa_handler = SIG_IGN;
sa_new.sa_flags = 0;
sigemptyset(&sa_new.sa_mask);
sigaction(SIGPIPE, &sa_new, &sa_old);
#endif
int nwr = send(sock->sockfd, data, len, flags);
#if !defined(MSG_NOSIGNAL) && !defined(SO_NOSIGPIPE)
sigaction(SIGPIPE, &sa_old, NULL);
#endif
if (nwr < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
lua_pushboolean(L, 0);
else
return lsocket_error(L, strerror(errno));
}
lua_pushnumber(L, nwr);
return 1;
}
/* lsocket_sock_sendto
*
* writes data to a socket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
* 2 string containing data to be written to socket
* 3 ip address to sent to
* 4 port to send to
*
* Lua Returns:
* +1 the number of bytes written
* or +1 false if nonblocking socket returned EAGAIN (not ready to accept data)
* or +1 nil, +2 error message
*/
static int lsocket_sock_sendto(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
size_t len;
const char *data = luaL_checklstring(L, 2, &len);
const char *addr = luaL_checkstring(L, 3);
int port = luaL_checknumber(L, 4);
char sabuf[sizeof(struct sockaddr_in6)];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
int family, protocol;
int err = _gethostaddr(L, addr, sock->type, port, &family, &protocol, sa, &slen);
if (err) return err;