-
Notifications
You must be signed in to change notification settings - Fork 41
/
lsocket.c
1571 lines (1425 loc) · 37.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 <[email protected]>, 2013-2015
* Released under the terms of the MIT license. See file LICENSE for details.
*/
#define LUA_LIB
#include <stdlib.h>
#if _WINDOWS && _MSC_VER > 0
#include <io.h>
#define strncasecmp _strnicmp
#define strcasecmp _stricmp
#else
#include <unistd.h>
#endif // _WINDOWS && _MSC_VER > 0
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#if (defined _WIN32 ) || (defined _WIN64)
#include "win_compat.h"
// winsock do not need check select fd
static void
check_select_fd(lua_State *L, int fd, int index) {
if (index >= FD_SETSIZE) {
luaL_error(L, "bad argument to 'select' (socket file descriptor too many)");
}
}
#else
#define SOCKET int
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/select.h>
#include <netdb.h>
#include <sys/stat.h>
#include <dirent.h>
#include <ifaddrs.h>
#define init_socketlib(L)
static void
check_select_fd(lua_State *L, int fd, int index) {
if (fd >= FD_SETSIZE) {
luaL_error(L, "bad argument to 'select' (socket file descriptor too big)");
}
}
#endif
#ifndef IPV6_ADD_MEMBERSHIP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif
#ifndef UNIX_PATH_MAX
#define UNIX_PATH_MAX 108
#endif
/* which platforms have abstract unix domain sockets (most probably only linux)
*/
#ifdef __linux__
#define HAVE_ABSTRACT_UDSOCKETS
#endif
#define LSOCKET_VERSION "1.4.1"
#define LSOCKET "socket"
#define TOSTRING_BUFSIZ 64
#define SOCKADDR_BUFSIZ (sizeof(struct sockaddr_un) + UNIX_PATH_MAX + 1)
#define LSOCKET_EMPTY "lsocket_empty_table"
/* address families */
#define LSOCKET_INET "inet"
#define LSOCKET_INET6 "inet6"
#define LSOCKET_UNIX "unix"
/* 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)
static void myL_pushresultsize(luaL_Buffer *lbp, size_t sz)
{
luaL_addsize(lbp, sz);
luaL_pushresult(lbp);
}
#define luaL_pushresultsize(lbp, sz) myL_pushresultsize(lbp, sz)
#endif
/*** Userdata handling ***/
/* structure for socket userdata */
typedef struct _lsocket_socket {
int sockfd;
int family;
int type;
int mcast;
int protocol;
int listening;
} 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->sockfd = -1;
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);
sock->sockfd = -1;
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);
lua_pushfstring(L, "%s: %p", LSOCKET, sock);
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, socklen_t slen, char *buf, int buflen)
{
const char *s = 0;
if (sa->sa_family == AF_INET)
s = inet_ntop(sa->sa_family, (const void*) &((struct sockaddr_in*)sa)->sin_addr, buf, buflen);
else if (sa->sa_family == AF_INET6)
s = inet_ntop(sa->sa_family, (const void*) &((struct sockaddr_in6*)sa)->sin6_addr, buf, buflen);
else if (sa->sa_family == AF_UNIX) {
if (slen > offsetof(struct sockaddr_un, sun_path))
strncpy(buf, ((struct sockaddr_un*)sa)->sun_path, buflen);
else
*buf = 0;
s = buf;
}
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 = 0;
if (sa->sa_family == AF_INET)
port = ((struct sockaddr_in*)sa)->sin_port;
else if (sa->sa_family == AF_INET6)
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] == '.') {
int lpfx = strrchr(addr, ':') - addr;
if (lpfx <= 0 || lpfx > pfx) return 0;
pfx = lpfx + 1 + strspn(addr + lpfx + 1, "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, hostname or unix domain path name
* 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, 2 otherwise
* On success, the arguments family, protocol, sa and slen will have
* been updated with values from the looked up address. On error, the
* lua stack will contail nil + error message
*/
static int _gethostaddr(lua_State *L, const char *addr, int type, int port, int *family, int *protocol, struct sockaddr *sa, socklen_t *slen)
{
if (strchr(addr, '/') || *addr == '@') {
if (strlen(addr) > UNIX_PATH_MAX)
return lsocket_error(L, "unix domain path too long");
*family = AF_UNIX;
*slen = sizeof(sa_family_t) + strlen(addr) + 1;
*protocol = 0;
struct sockaddr_un* su = (struct sockaddr_un*) sa;
sa->sa_family = AF_UNIX;
strcpy(&su->sun_path[0], addr);
#ifdef HAVE_ABSTRACT_UDSOCKETS
if (*addr == '@') su->sun_path[0] = '\0';
#endif
return 0;
}
struct addrinfo hint, *info = 0;
char svc[TOSTRING_BUFSIZ];
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
hint.ai_socktype = type;
hint.ai_protocol = type == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP;
if (_needsnolookup(addr))
hint.ai_flags = AI_NUMERICHOST;
snprintf(svc, TOSTRING_BUFSIZ , "%d", port);
int err = getaddrinfo(addr, svc, &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);
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[SOCKADDR_BUFSIZ];
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_optnumber(L, top++, -1);
/* 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;
family = AF_INET;
si->sin_addr.s_addr = INADDR_ANY;
si->sin_port = htons(port);
slen = sizeof(struct sockaddr_in);
protocol = 0;
}
if (sa->sa_family != AF_UNIX && port == -1)
luaL_argerror(L, top - 1, "number expected, got no value X");
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_UNIX)
return lsocket_error(L, "multicast not available for unix domain sockets.");
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[SOCKADDR_BUFSIZ];
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_optnumber(L, top + 1, -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;
if (family != AF_UNIX && port == -1)
luaL_argerror(L, 2, "number expected, got no value.");
lSocket *sock = lsocket_pushlSocket(L);
sock->sockfd = socket(family, type, protocol);
_initsocket(sock, family, type, mcast, protocol, 0);
if (mcast) {
if (family == AF_UNIX)
return lsocket_error(L, "multicast not available for unix domain sockets.");
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) {
#if defined(WIN32)
if (errno != EAGAIN && errno != EWOULDBLOCK) {
#else
if (errno != EINPROGRESS) {
#endif
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, socklen_t slen)
{
char buf[SOCKADDR_BUFSIZ];
const char *s;
lua_newtable(L);
if (sa->sa_family != AF_UNIX) {
lua_pushliteral(L, "port");
lua_pushinteger(L, _portnumber(sa));
lua_rawset(L, -3);
}
lua_pushliteral(L, "family");
switch (sa->sa_family) {
case AF_INET: lua_pushstring(L, LSOCKET_INET); break;
case AF_INET6: lua_pushstring(L, LSOCKET_INET6); break;
case AF_UNIX: lua_pushstring(L, LSOCKET_UNIX); break;
default: lua_pushnil(L);
}
lua_rawset(L, -3);
lua_pushliteral(L, "addr");
s = _addr2string(sa, slen, buf, SOCKADDR_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 [SOCKADDR_BUFSIZ];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
if (which == NULL) {
lua_newtable(L);
lua_pushliteral(L, "fd");
lua_pushinteger(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;
case AF_UNIX: lua_pushliteral(L, LSOCKET_UNIX); 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, slen);
else
return lsocket_error(L, strerror(errno));
} else if (!strcasecmp(which, "socket")) {
if (getsockname(sock->sockfd, sa, &slen) >= 0)
_push_sockname(L, sa, slen);
else
return lsocket_error(L, strerror(errno));
} else {
lua_pop(L, 1);
lua_pushnil(L);
}
return 1;
}
/* lsocket_sock_status
*
* checks the error status of a socket
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
*
* Lua Returns:
* +1 true, if the socket has no errors, nil + error message otherwise.
*/
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;
}
/* lsocket_sock_getfd
*
* returns the file descriptor for a socket.
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
*
* Lua Returns:
* +1 the sockets file descriptor
*/
static int lsocket_sock_getfd(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
lua_pushinteger(L, sock->sockfd);
return 1;
}
/* lsocket_sock_setfd
*
* sets the file descriptor for a socket.
*
* Arguments:
* L Lua State
*
* Lua Stack:
* 1 the lSocket userdata
* 2 the new file descriptor, must be -1
*
* Lua Returns:
* +1 true, if the the new file descriptor was -1 and has been set,
* nil + error message otherwise.
*/
static int lsocket_sock_setfd(lua_State *L)
{
lSocket *sock = lsocket_checklSocket(L, 1);
int fd = luaL_checkinteger(L, 2);
if (fd != -1)
return lsocket_error(L, "bad argument #1 to 'setfd' (invalid fd)");
sock->sockfd = fd;
lua_pushboolean(L, 1);
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[SOCKADDR_BUFSIZ];
if (!_canacceptdata(sock->sockfd, 0)) {
lua_pushboolean(L, 0);
return 1;
}
char sabuf[SOCKADDR_BUFSIZ];
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));
fcntl(newfd, F_SETFL, O_NONBLOCK);
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));
if (sa->sa_family != AF_UNIX) {
lua_pushstring(L, _addr2string(sa, slen, buf, SOCKADDR_BUFSIZ));
lua_pushinteger(L, _portnumber(sa));
} else {
lua_pushnil(L);
lua_pushnil(L);
}
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 LUAL_BUFFERSIZE
*
* 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, LUAL_BUFFERSIZE);
if (lua_tointeger(L, 2) > UINT_MAX)
return luaL_error(L, "bad argument #1 to 'recv' (invalid number)");
luaL_Buffer lbuf;
char *buf = 0;
#if LUA_VERSION_NUM == 501
if (howmuch <= LUAL_BUFFERSIZE) {
luaL_buffinit(L, &lbuf);
buf = luaL_prepbuffer(&lbuf);
} else {
// allocate buffer as userdata, will then be collected later
buf = lua_newuserdata(L, howmuch);
}
#else
luaL_buffinit(L, &lbuf);
buf = luaL_prepbuffsize(&lbuf, howmuch);
#endif
int nrd = recv(sock->sockfd, buf, howmuch, 0);
if (nrd < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
lua_pushboolean(L, 0);
else
return lsocket_error(L, strerror(errno));
} else if (nrd == 0) {
lua_pushnil(L);
} else {
#if LUA_VERSION_NUM == 501
if (howmuch > LUAL_BUFFERSIZE)
lua_pushlstring(L, buf, nrd);
else
#endif
luaL_pushresultsize(&lbuf, nrd);
}
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 LUAL_BUFFERSIZE
*
* 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, LUAL_BUFFERSIZE);
if (lua_tointeger(L, 2) > UINT_MAX)
return luaL_error(L, "bad argument #1 to 'recvfrom' (invalid number)");
char sabuf[SOCKADDR_BUFSIZ];
struct sockaddr *sa = (struct sockaddr*) sabuf;
socklen_t slen = sizeof(sabuf);
luaL_Buffer lbuf;
char *buf = 0;
#if LUA_VERSION_NUM == 501
if (howmuch <= LUAL_BUFFERSIZE) {
luaL_buffinit(L, &lbuf);
buf = luaL_prepbuffer(&lbuf);
} else {
// allocate buffer as userdata, will then be collected later
buf = lua_newuserdata(L, howmuch);
}
#else
luaL_buffinit(L, &lbuf);