-
Notifications
You must be signed in to change notification settings - Fork 120
/
jim-aio.c
2849 lines (2527 loc) · 74.5 KB
/
jim-aio.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
/* Jim - A small embeddable Tcl interpreter
*
* Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
* Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
* Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
* Copyright 2008 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
* Copyright 2008 Andrew Lunn <andrew@lunn.ch>
* Copyright 2008 Duane Ellis <openocd@duaneellis.com>
* Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the Jim Tcl Project.
**/
#include "jimautoconf.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#include <sys/stat.h>
#endif
#ifdef HAVE_UTIL_H
#include <util.h>
#endif
#ifdef HAVE_PTY_H
#include <pty.h>
#endif
#include "jim.h"
#if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#define HAVE_SOCKETS
#elif defined (__MINGW32__)
/* currently mingw32 doesn't support sockets, but has pipe, fdopen */
#endif
#if defined(JIM_SSL)
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif
#ifdef HAVE_TERMIOS_H
#include <jim-tty.h>
#endif
#include "jim-eventloop.h"
#include "jim-subcmd.h"
#include "jimiocompat.h"
#define AIO_CMD_LEN 32 /* e.g. aio.handleXXXXXX */
#define AIO_BUF_LEN 256 /* read size for gets, read */
#define AIO_WBUF_FULL_SIZE (64 * 1024) /* This could be configurable */
#define AIO_KEEPOPEN 1 /* don't set O_CLOEXEC, don't close on command delete */
#define AIO_NODELETE 2 /* don't delete AF_UNIX path on close */
#define AIO_EOF 4 /* EOF was reached */
#define AIO_WBUF_NONE 8 /* default to buffering=none */
#define AIO_NONBLOCK 16 /* socket is non-blocking */
enum wbuftype {
WBUF_OPT_NONE, /* write immediately */
WBUF_OPT_LINE, /* write if NL is seen */
WBUF_OPT_FULL, /* write when write buffer is full or on flush */
};
#if defined(JIM_IPV6)
#define IPV6 1
#else
#define IPV6 0
#ifndef PF_INET6
#define PF_INET6 0
#endif
#endif
#if defined(HAVE_SYS_UN_H) && defined(PF_UNIX)
#define UNIX_SOCKETS 1
#else
#define UNIX_SOCKETS 0
#endif
#ifndef MAXPATHLEN
#define MAXPATHLEN JIM_PATH_LEN
#endif
#if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
/* Avoid type punned pointers */
union sockaddr_any {
struct sockaddr sa;
struct sockaddr_in sin;
#if IPV6
struct sockaddr_in6 sin6;
#endif
#if UNIX_SOCKETS
struct sockaddr_un sun;
#endif
};
#ifndef HAVE_INET_NTOP
const char *inet_ntop(int af, const void *src, char *dst, int size)
{
if (af != PF_INET) {
return NULL;
}
snprintf(dst, size, "%s", inet_ntoa(((struct sockaddr_in *)src)->sin_addr));
return dst;
}
#endif
#endif /* JIM_BOOTSTRAP */
/* Wait for the fd to be readable and return JIM_OK if ok or JIM_ERR on timeout */
/* ms=0 means block forever */
static int JimReadableTimeout(int fd, long ms)
{
#ifdef HAVE_SELECT
int retval;
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = ms / 1000;
tv.tv_usec = (ms % 1000) * 1000;
retval = select(fd + 1, &rfds, NULL, NULL, ms == 0 ? NULL : &tv);
if (retval > 0) {
return JIM_OK;
}
return JIM_ERR;
#else
return JIM_OK;
#endif
}
struct AioFile;
typedef struct {
int (*writer)(struct AioFile *af, const char *buf, int len);
int (*reader)(struct AioFile *af, char *buf, int len, int pending);
int (*error)(const struct AioFile *af);
const char *(*strerror)(struct AioFile *af);
int (*verify)(struct AioFile *af);
} JimAioFopsType;
typedef struct AioFile
{
Jim_Obj *filename; /* filename or equivalent for error reporting */
int wbuft; /* enum wbuftype */
int flags; /* AIO_KEEPOPEN | AIO_NODELETE | AIO_EOF */
long timeout; /* timeout (in ms) for read operations if blocking */
int fd;
int addr_family;
void *ssl;
const JimAioFopsType *fops;
Jim_Obj *readbuf; /* Contains any buffered read data. NULL if empty. refcount=0 */
Jim_Obj *writebuf; /* Contains any buffered write data. refcount=1 */
} AioFile;
static int stdio_writer(struct AioFile *af, const char *buf, int len)
{
return write(af->fd, buf, len);
}
static int stdio_reader(struct AioFile *af, char *buf, int len, int nb)
{
if (nb || af->timeout == 0 || JimReadableTimeout(af->fd, af->timeout) == JIM_OK) {
/* timeout on blocking read */
int ret;
errno = 0;
ret = read(af->fd, buf, len);
if (ret <= 0 && errno != EAGAIN && errno != EINTR) {
af->flags |= AIO_EOF;
}
return ret;
}
errno = ETIMEDOUT;
return -1;
}
static int stdio_error(const AioFile *af)
{
if (af->flags & AIO_EOF) {
return JIM_OK;
}
/* XXX Probably errno should have been stashed in af->err instead */
switch (errno) {
case EAGAIN:
case EINTR:
case ETIMEDOUT:
#ifdef ECONNRESET
case ECONNRESET:
#endif
#ifdef ECONNABORTED
case ECONNABORTED:
#endif
return JIM_OK;
default:
return JIM_ERR;
}
}
static const char *stdio_strerror(struct AioFile *af)
{
return strerror(errno);
}
static const JimAioFopsType stdio_fops = {
stdio_writer,
stdio_reader,
stdio_error,
stdio_strerror,
NULL, /* verify */
};
#if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
static SSL_CTX *JimAioSslCtx(Jim_Interp *interp);
static int ssl_writer(struct AioFile *af, const char *buf, int len)
{
return SSL_write(af->ssl, buf, len);
}
static int ssl_reader(struct AioFile *af, char *buf, int len, int nb)
{
if (nb || af->timeout == 0 || SSL_pending(af->ssl) || JimReadableTimeout(af->fd, af->timeout) == JIM_OK) {
int ret;
if (SSL_pending(af->ssl)) {
/* If there is pending data to read return it first */
if (len > SSL_pending(af->ssl)) {
len = SSL_pending(af->ssl);
}
}
ret = SSL_read(af->ssl, buf, len);
if (ret <= 0 && errno != EAGAIN && errno != EINTR) {
af->flags |= AIO_EOF;
}
return ret;
}
errno = ETIMEDOUT;
return -1;
}
static int ssl_error(const struct AioFile *af)
{
int ret = SSL_get_error(af->ssl, 0);
/* These indicate "normal" conditions */
if (ret == SSL_ERROR_ZERO_RETURN || ret == SSL_ERROR_NONE || ret == SSL_ERROR_WANT_READ) {
return JIM_OK;
}
if (ret == SSL_ERROR_SYSCALL) {
return stdio_error(af);
}
return JIM_ERR;
}
static const char *ssl_strerror(struct AioFile *af)
{
int err = ERR_get_error();
if (err) {
return ERR_error_string(err, NULL);
}
else {
return stdio_strerror(af);
}
}
static int ssl_verify(struct AioFile *af)
{
X509 *cert;
cert = SSL_get_peer_certificate(af->ssl);
if (!cert) {
return JIM_ERR;
}
X509_free(cert);
if (SSL_get_verify_result(af->ssl) == X509_V_OK) {
return JIM_OK;
}
return JIM_ERR;
}
static const JimAioFopsType ssl_fops = {
ssl_writer,
ssl_reader,
ssl_error,
ssl_strerror,
ssl_verify,
};
#endif /* JIM_BOOTSTRAP */
/**
* Sets nonblocking on the channel (if different from current)
* and updates the flags in af->flags.
*/
static void aio_set_nonblocking(AioFile *af, int nb)
{
#ifdef O_NDELAY
int old = !!(af->flags & AIO_NONBLOCK);
if (old != nb) {
int fmode = fcntl(af->fd, F_GETFL);
if (nb) {
fmode |= O_NDELAY;
af->flags |= AIO_NONBLOCK;
}
else {
fmode &= ~O_NDELAY;
af->flags &= ~AIO_NONBLOCK;
}
(void)fcntl(af->fd, F_SETFL, fmode);
}
#endif
}
/**
* If the socket is blocking (not nonblocking) and a timeout is set,
* put the socket in non-blocking mode.
*
* Returns the original mode.
*/
static int aio_start_nonblocking(AioFile *af)
{
int old = !!(af->flags & AIO_NONBLOCK);
if (af->timeout) {
aio_set_nonblocking(af, 1);
}
return old;
}
static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
static AioFile *JimMakeChannel(Jim_Interp *interp, int fd, Jim_Obj *filename,
const char *hdlfmt, int family, int flags);
#if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
#ifndef HAVE_GETADDRINFO
/*
* Poor man's getaddrinfo().
* hints->ai_family must be set and must be PF_INET or PF_INET6
* Only returns the first matching result.
* servname must be numeric.
*/
struct addrinfo {
int ai_family;
socklen_t ai_addrlen;
struct sockaddr *ai_addr; /* simply points to ai_storage */
union sockaddr_any ai_storage;
};
static int getaddrinfo(const char *hostname, const char *servname,
const struct addrinfo *hints, struct addrinfo **res)
{
struct hostent *he;
char *end;
unsigned long port = strtoul(servname, &end, 10);
if (port == 0 || port > 65536 || *end) {
errno = EINVAL;
return -1;
}
if ((he = gethostbyname(hostname)) != NULL) {
int i;
for (i = 0; he->h_addr_list[i]; i++) {
if (he->h_addrtype == hints->ai_family) {
struct addrinfo *ai = malloc(sizeof(*ai));
memset(ai, 0, sizeof(*ai));
ai->ai_family = he->h_addrtype;
ai->ai_addr = &ai->ai_storage.sa;
if (ai->ai_family == PF_INET) {
ai->ai_addrlen = sizeof(ai->ai_storage.sin);
ai->ai_storage.sin.sin_family = he->h_addrtype;
assert(sizeof(ai->ai_storage.sin.sin_addr) == he->h_length);
memcpy(&ai->ai_storage.sin.sin_addr, he->h_addr_list[i], he->h_length);
ai->ai_storage.sin.sin_port = htons(port);
}
#if IPV6
else {
ai->ai_addrlen = sizeof(ai->ai_storage.sin6);
ai->ai_storage.sin6.sin6_family = he->h_addrtype;
assert(sizeof(ai->ai_storage.sin6.sin6_addr) == he->h_length);
memcpy(&ai->ai_storage.sin6.sin6_addr, he->h_addr_list[i], he->h_length);
ai->ai_storage.sin6.sin6_port = htons(port);
}
#endif
*res = ai;
return 0;
}
}
}
return ENOENT;
}
static void freeaddrinfo(struct addrinfo *ai)
{
free(ai);
}
#endif
static int JimParseIPv6Address(Jim_Interp *interp, int socktype, const char *hostport, union sockaddr_any *sa, socklen_t *salen)
{
#if IPV6
/*
* An IPv6 addr/port looks like:
* [::1]
* [::1]:2000
* [fe80::223:6cff:fe95:bdc0%en1]:2000
* [::]:2000
* 2000
*
* Note that the "any" address is ::, which is the same as when no address is specified.
*/
char *sthost = NULL;
const char *stport;
int ret = JIM_OK;
struct addrinfo req;
struct addrinfo *ai;
stport = strrchr(hostport, ':');
if (!stport) {
/* No : so, the whole thing is the port */
stport = hostport;
hostport = "::";
sthost = Jim_StrDup(hostport);
}
else {
stport++;
}
if (*hostport == '[') {
/* This is a numeric ipv6 address */
char *pt = strchr(++hostport, ']');
if (pt) {
sthost = Jim_StrDupLen(hostport, pt - hostport);
}
}
if (!sthost) {
sthost = Jim_StrDupLen(hostport, stport - hostport - 1);
}
memset(&req, '\0', sizeof(req));
req.ai_family = PF_INET6;
req.ai_socktype = socktype;
if (getaddrinfo(sthost, stport, &req, &ai)) {
Jim_SetResultFormatted(interp, "Not a valid address: %s:%s", sthost, stport);
ret = JIM_ERR;
}
else {
memcpy(&sa->sin6, ai->ai_addr, ai->ai_addrlen);
*salen = ai->ai_addrlen;
freeaddrinfo(ai);
}
Jim_Free(sthost);
return ret;
#else
Jim_SetResultString(interp, "ipv6 not supported", -1);
return JIM_ERR;
#endif
}
static int JimParseIpAddress(Jim_Interp *interp, int socktype, const char *hostport, union sockaddr_any *sa, socklen_t *salen)
{
/* An IPv4 addr/port looks like:
* 192.168.1.5
* 192.168.1.5:2000
* 2000
*
* If the address is missing, INADDR_ANY is used.
* If the port is missing, 0 is used (only useful for server sockets).
*/
char *sthost = NULL;
const char *stport;
int ret = JIM_OK;
struct addrinfo req;
struct addrinfo *ai;
stport = strrchr(hostport, ':');
if (!stport) {
/* No : so, the whole thing is the port */
stport = hostport;
sthost = Jim_StrDup("0.0.0.0");
}
else {
sthost = Jim_StrDupLen(hostport, stport - hostport);
stport++;
}
memset(&req, '\0', sizeof(req));
req.ai_family = PF_INET;
req.ai_socktype = socktype;
if (getaddrinfo(sthost, stport, &req, &ai)) {
ret = JIM_ERR;
}
else {
memcpy(&sa->sin, ai->ai_addr, ai->ai_addrlen);
*salen = ai->ai_addrlen;
freeaddrinfo(ai);
}
Jim_Free(sthost);
if (ret != JIM_OK) {
Jim_SetResultFormatted(interp, "Not a valid address: %s", hostport);
}
return ret;
}
#if UNIX_SOCKETS
static int JimParseDomainAddress(Jim_Interp *interp, const char *path, union sockaddr_any *sa, socklen_t *salen)
{
sa->sun.sun_family = PF_UNIX;
snprintf(sa->sun.sun_path, sizeof(sa->sun.sun_path), "%s", path);
*salen = strlen(sa->sun.sun_path) + 1 + sizeof(sa->sun.sun_family);
return JIM_OK;
}
#endif
static int JimParseSocketAddress(Jim_Interp *interp, int family, int socktype, const char *addr, union sockaddr_any *sa, socklen_t *salen)
{
switch (family) {
#if UNIX_SOCKETS
case PF_UNIX:
return JimParseDomainAddress(interp, addr, sa, salen);
#endif
case PF_INET6:
return JimParseIPv6Address(interp, socktype, addr, sa, salen);
case PF_INET:
return JimParseIpAddress(interp, socktype, addr, sa, salen);
}
return JIM_ERR;
}
/**
* Format that address in 'sa' as a string and return it as a zero-refcount object.
*
*/
static Jim_Obj *JimFormatSocketAddress(Jim_Interp *interp, const union sockaddr_any *sa, socklen_t salen)
{
/* INET6_ADDRSTRLEN is 46. Add some for [] and port */
char addrbuf[60];
const char *addr = addrbuf;
int addrlen = -1;
switch (sa->sa.sa_family) {
#if UNIX_SOCKETS
case PF_UNIX:
addr = sa->sun.sun_path;
addrlen = salen - 1 - sizeof(sa->sun.sun_family);
if (addrlen < 0) {
addrlen = 0;
}
break;
#endif
#if IPV6
case PF_INET6:
addrbuf[0] = '[';
/* Allow 9 for []:65535\0 */
inet_ntop(sa->sa.sa_family, &sa->sin6.sin6_addr, addrbuf + 1, sizeof(addrbuf) - 9);
snprintf(addrbuf + strlen(addrbuf), 8, "]:%d", ntohs(sa->sin6.sin6_port));
break;
#endif
case PF_INET:
/* Allow 7 for :65535\0 */
inet_ntop(sa->sa.sa_family, &sa->sin.sin_addr, addrbuf, sizeof(addrbuf) - 7);
snprintf(addrbuf + strlen(addrbuf), 7, ":%d", ntohs(sa->sin.sin_port));
break;
default:
/* Otherwise just an empty address */
addr = "";
break;
}
return Jim_NewStringObj(interp, addr, addrlen);
}
static int JimSetVariableSocketAddress(Jim_Interp *interp, Jim_Obj *varObjPtr, const union sockaddr_any *sa, socklen_t salen)
{
int ret;
Jim_Obj *objPtr = JimFormatSocketAddress(interp, sa, salen);
Jim_IncrRefCount(objPtr);
ret = Jim_SetVariable(interp, varObjPtr, objPtr);
Jim_DecrRefCount(interp, objPtr);
return ret;
}
static Jim_Obj *aio_sockname(Jim_Interp *interp, int fd)
{
union sockaddr_any sa;
socklen_t salen = sizeof(sa);
if (getsockname(fd, &sa.sa, &salen) < 0) {
return NULL;
}
return JimFormatSocketAddress(interp, &sa, salen);
}
static Jim_Obj *aio_peername(Jim_Interp *interp, int fd)
{
union sockaddr_any sa;
socklen_t salen = sizeof(sa);
if (getpeername(fd, &sa.sa, &salen) < 0) {
return NULL;
}
return JimFormatSocketAddress(interp, &sa, salen);
}
#endif /* JIM_BOOTSTRAP */
static const char *JimAioErrorString(AioFile *af)
{
if (af && af->fops)
return af->fops->strerror(af);
return strerror(errno);
}
static void JimAioSetError(Jim_Interp *interp, Jim_Obj *name)
{
AioFile *af = Jim_CmdPrivData(interp);
if (name) {
Jim_SetResultFormatted(interp, "%#s: %s", name, JimAioErrorString(af));
}
else {
Jim_SetResultString(interp, JimAioErrorString(af), -1);
}
}
static int aio_eof(AioFile *af)
{
return af->flags & AIO_EOF;
}
static int JimCheckStreamError(Jim_Interp *interp, AioFile *af)
{
int ret = 0;
if (!aio_eof(af)) {
ret = af->fops->error(af);
if (ret) {
JimAioSetError(interp, af->filename);
}
}
return ret;
}
/**
* Removes n bytes from the beginning of objPtr.
*
* objPtr must have a string rep.
* n must be <= bytelen(objPtr)
*/
static void aio_consume(Jim_Obj *objPtr, int n)
{
assert(objPtr->bytes);
assert(n <= objPtr->length);
/* Move the data down, plus 1 for the null terminator */
memmove(objPtr->bytes, objPtr->bytes + n, objPtr->length - n + 1);
objPtr->length -= n;
/* Note that we don't have to worry about utf8 len because the read and write
* buffers are used as pure byte buffers
*/
}
/* forward declaration */
static int aio_autoflush(Jim_Interp *interp, void *clientData, int mask);
/**
* Flushes af->writebuf to the channel and removes that data
* from af->writebuf.
*
* If not all data could be written, starts a writable callback to continue
* flushing. This will only run when the eventloop does.
*
* On error or if not all data could be written, consumes only
* what was written and returns an error.
*/
static int aio_flush(Jim_Interp *interp, AioFile *af)
{
int len;
const char *pt = Jim_GetString(af->writebuf, &len);
if (len) {
int ret = af->fops->writer(af, pt, len);
if (ret > 0) {
/* Consume what we wrote */
aio_consume(af->writebuf, ret);
}
if (ret < 0) {
return JimCheckStreamError(interp, af);
}
/* If not all data could be written, but with no error, and there is no writable
* handler, we can try to auto-flush
*/
if (Jim_Length(af->writebuf)) {
#ifdef jim_ext_eventloop
void *handler = Jim_FindFileHandler(interp, af->fd, JIM_EVENT_WRITABLE);
if (handler == NULL) {
Jim_CreateFileHandler(interp, af->fd, JIM_EVENT_WRITABLE, aio_autoflush, af, NULL);
return JIM_OK;
}
else if (handler == af) {
/* Nothing to do, handler already installed */
return JIM_OK;
}
#endif
/* There is an existing foreign handler or no event loop so return an error */
Jim_SetResultString(interp, "send buffer is full", -1);
return JIM_ERR;
}
}
return JIM_OK;
}
/**
* Called when the channel is writable.
* Write what we can and return -1 when the write buffer is empty to remove the handler.
*/
static int aio_autoflush(Jim_Interp *interp, void *clientData, int mask)
{
AioFile *af = clientData;
aio_flush(interp, af);
if (Jim_Length(af->writebuf) == 0) {
/* Done, so remove the handler */
return -1;
}
return 0;
}
/**
* Read until 'len' bytes are available in readbuf.
*
* If nonblocking or timeout, may return early.
* 'len' may be -1 to read until eof (or until no more data if nonblocking)
*
* Returns JIM_OK if data was read or JIM_ERR on error.
*/
static int aio_read_len(Jim_Interp *interp, AioFile *af, int nb, char *buf, size_t buflen, int neededLen)
{
if (!af->readbuf) {
af->readbuf = Jim_NewStringObj(interp, NULL, 0);
}
if (neededLen >= 0) {
neededLen -= Jim_Length(af->readbuf);
if (neededLen <= 0) {
return JIM_OK;
}
}
while (neededLen && !aio_eof(af)) {
int retval;
int readlen;
if (neededLen == -1) {
readlen = AIO_BUF_LEN;
}
else {
readlen = (neededLen > AIO_BUF_LEN ? AIO_BUF_LEN : neededLen);
}
retval = af->fops->reader(af, buf, readlen, nb);
if (retval > 0) {
Jim_AppendString(interp, af->readbuf, buf, retval);
if (neededLen != -1) {
neededLen -= retval;
}
continue;
}
if (JimCheckStreamError(interp, af)) {
return JIM_ERR;
}
break;
}
return JIM_OK;
}
/**
* Consumes neededLen bytes from readbuf and those
* bytes as a string object.
*
* If neededLen is -1, or >= len(readbuf), returns the entire readbuf.
*
* Returns NULL if no data available.
*/
static Jim_Obj *aio_read_consume(Jim_Interp *interp, AioFile *af, int neededLen)
{
Jim_Obj *objPtr = NULL;
if (neededLen < 0 || af->readbuf == NULL || Jim_Length(af->readbuf) <= neededLen) {
objPtr = af->readbuf;
af->readbuf = NULL;
}
else if (af->readbuf) {
/* Need to consume part of the readbuf */
int len;
const char *pt = Jim_GetString(af->readbuf, &len);
objPtr = Jim_NewStringObj(interp, pt, neededLen);
aio_consume(af->readbuf, neededLen);
}
return objPtr;
}
static void JimAioDelProc(Jim_Interp *interp, void *privData)
{
AioFile *af = privData;
JIM_NOTUSED(interp);
/* Try to flush and write data before close */
aio_flush(interp, af);
Jim_DecrRefCount(interp, af->writebuf);
#if UNIX_SOCKETS
if (af->addr_family == PF_UNIX && (af->flags & AIO_NODELETE) == 0) {
/* If this is bound, delete the socket file now */
Jim_Obj *filenameObj = aio_sockname(interp, af->fd);
if (filenameObj) {
if (Jim_Length(filenameObj)) {
remove(Jim_String(filenameObj));
}
Jim_FreeNewObj(interp, filenameObj);
}
}
#endif
Jim_DecrRefCount(interp, af->filename);
#ifdef jim_ext_eventloop
/* remove all existing EventHandlers */
Jim_DeleteFileHandler(interp, af->fd, JIM_EVENT_READABLE | JIM_EVENT_WRITABLE | JIM_EVENT_EXCEPTION);
#endif
#if defined(JIM_SSL)
if (af->ssl != NULL) {
SSL_free(af->ssl);
}
#endif
if (!(af->flags & AIO_KEEPOPEN)) {
close(af->fd);
}
if (af->readbuf) {
Jim_FreeNewObj(interp, af->readbuf);
}
Jim_Free(af);
}
static int aio_cmd_read(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
int nonewline = 0;
jim_wide neededLen = -1; /* -1 is "read as much as possible" */
static const char * const options[] = { "-pending", "-nonewline", NULL };
enum { OPT_PENDING, OPT_NONEWLINE };
int option;
int nb;
Jim_Obj *objPtr;
char buf[AIO_BUF_LEN];
if (argc) {
if (*Jim_String(argv[0]) == '-') {
if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
return JIM_ERR;
}
switch (option) {
case OPT_PENDING:
/* accepted for compatibility, but ignored */
break;
case OPT_NONEWLINE:
nonewline++;
break;
}
}
else {
if (Jim_GetWide(interp, argv[0], &neededLen) != JIM_OK)
return JIM_ERR;
if (neededLen < 0) {
Jim_SetResultString(interp, "invalid parameter: negative len", -1);
return JIM_ERR;
}
}
argc--;
argv++;
}
if (argc) {
return -1;
}
/* reads are nonblocking if a timeout is given */
nb = aio_start_nonblocking(af);
if (aio_read_len(interp, af, nb, buf, sizeof(buf), neededLen) != JIM_OK) {
aio_set_nonblocking(af, nb);
return JIM_ERR;
}
objPtr = aio_read_consume(interp, af, neededLen);
aio_set_nonblocking(af, nb);
if (objPtr) {
if (nonewline) {
int len;
const char *s = Jim_GetString(objPtr, &len);
if (len > 0 && s[len - 1] == '\n') {
objPtr->length--;
objPtr->bytes[objPtr->length] = '\0';
}
}
Jim_SetResult(interp, objPtr);
}
else {
Jim_SetEmptyResult(interp);
}
return JIM_OK;
}
/* Use 'name getfd' to get the file descriptor associated with channel 'name'
* Currently this is only used by 'info channels'. Is there a better way?
*/
int Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command)
{
Jim_Cmd *cmdPtr = Jim_GetCommand(interp, command, JIM_ERRMSG);
/* XXX: There ought to be a supported API for this */
if (cmdPtr && !cmdPtr->isproc && cmdPtr->u.native.cmdProc == JimAioSubCmdProc) {
return ((AioFile *) cmdPtr->u.native.privData)->fd;
}
Jim_SetResultFormatted(interp, "Not a filehandle: \"%#s\"", command);
return -1;
}
static int aio_cmd_getfd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
/* XXX Should we return this error? */
aio_flush(interp, af);
Jim_SetResultInt(interp, af->fd);
return JIM_OK;
}
static int aio_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
jim_wide count = 0;
jim_wide maxlen = JIM_WIDE_MAX;
/* Small, static buffer for small files */