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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
|
/* 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 <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include "jim.h"
#include "jimautoconf.h"
#if !defined(JIM_ANSIC)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#endif
#include "jim-eventloop.h"
#include "jim-subcmd.h"
#define AIO_CMD_LEN 32 /* e.g. aio.handleXXXXXX */
#define AIO_BUF_LEN 256 /* Can keep this small and rely on stdio buffering */
#define AIO_KEEPOPEN 1
#if defined(JIM_IPV6)
#define IPV6 1
#else
#define IPV6 0
#ifndef PF_INET6
#define PF_INET6 0
#endif
#endif
#ifndef JIM_ANSIC
union sockaddr_any {
struct sockaddr sa;
struct sockaddr_in sin;
#if IPV6
struct sockaddr_in6 sin6;
#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
typedef struct AioFile
{
FILE *fp;
Jim_Obj *filename;
int type;
int OpenFlags; /* AIO_KEEPOPEN? keep FILE* */
int fd;
#ifdef O_NDELAY
int flags;
#endif
Jim_Obj *rEvent;
Jim_Obj *wEvent;
Jim_Obj *eEvent;
#ifndef JIM_ANSIC
int addr_family;
#endif
} AioFile;
static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
#ifndef JIM_ANSIC
static int JimParseIPv6Address(Jim_Interp *interp, const char *hostport, union sockaddr_any *sa, int *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;
if (getaddrinfo(sthost, NULL, &req, &ai)) {
Jim_SetResultFormatted(interp, "Not a valid address: %s", hostport);
ret = JIM_ERR;
}
else {
memcpy(&sa->sin, ai->ai_addr, ai->ai_addrlen);
*salen = ai->ai_addrlen;
sa->sin.sin_port = htons(atoi(stport));
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, const char *hostport, union sockaddr_any *sa, int *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;
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++;
}
{
#ifdef HAVE_GETADDRINFO
struct addrinfo req;
struct addrinfo *ai;
memset(&req, '\0', sizeof(req));
req.ai_family = PF_INET;
if (getaddrinfo(sthost, NULL, &req, &ai)) {
ret = JIM_ERR;
}
else {
memcpy(&sa->sin, ai->ai_addr, ai->ai_addrlen);
*salen = ai->ai_addrlen;
freeaddrinfo(ai);
}
#else
struct hostent *he;
ret = JIM_ERR;
if ((he = gethostbyname(sthost)) != NULL) {
if (he->h_length == sizeof(sa->sin.sin_addr)) {
*salen = sizeof(sa->sin);
sa->sin.sin_family= he->h_addrtype;
memcpy(&sa->sin.sin_addr, he->h_addr, he->h_length); /* set address */
ret = JIM_OK;
}
}
#endif
sa->sin.sin_port = htons(atoi(stport));
}
Jim_Free(sthost);
if (ret != JIM_OK) {
Jim_SetResultFormatted(interp, "Not a valid address: %s", hostport);
}
return ret;
}
#ifdef HAVE_SYS_UN_H
static int JimParseDomainAddress(Jim_Interp *interp, const char *path, struct sockaddr_un *sa)
{
sa->sun_family = PF_UNIX;
strcpy(sa->sun_path, path);
return JIM_OK;
}
#endif
#endif
static void JimAioSetError(Jim_Interp *interp, Jim_Obj *name)
{
if (name) {
Jim_SetResultFormatted(interp, "%#s: %s", name, strerror(errno));
}
else {
Jim_SetResultString(interp, strerror(errno), -1);
}
}
static void JimAioDelProc(Jim_Interp *interp, void *privData)
{
AioFile *af = privData;
JIM_NOTUSED(interp);
Jim_DecrRefCount(interp, af->filename);
if (!(af->OpenFlags & AIO_KEEPOPEN)) {
fclose(af->fp);
}
#ifdef jim_ext_eventloop
/* remove existing EventHandlers */
if (af->rEvent) {
Jim_DeleteFileHandler(interp, af->fp);
}
if (af->wEvent) {
Jim_DeleteFileHandler(interp, af->fp);
}
if (af->eEvent) {
Jim_DeleteFileHandler(interp, af->fp);
}
#endif
Jim_Free(af);
}
static int aio_cmd_read(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
char buf[AIO_BUF_LEN];
Jim_Obj *objPtr;
int nonewline = 0;
int neededLen = -1; /* -1 is "read as much as possible" */
if (argc && Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
nonewline = 1;
argv++;
argc--;
}
if (argc == 1) {
jim_wide wideValue;
if (Jim_GetWide(interp, argv[0], &wideValue) != JIM_OK)
return JIM_ERR;
if (wideValue < 0) {
Jim_SetResultString(interp, "invalid parameter: negative len", -1);
return JIM_ERR;
}
neededLen = (int)wideValue;
}
else if (argc) {
return -1;
}
objPtr = Jim_NewStringObj(interp, NULL, 0);
while (neededLen != 0) {
int retval;
int readlen;
if (neededLen == -1) {
readlen = AIO_BUF_LEN;
}
else {
readlen = (neededLen > AIO_BUF_LEN ? AIO_BUF_LEN : neededLen);
}
retval = fread(buf, 1, readlen, af->fp);
if (retval > 0) {
Jim_AppendString(interp, objPtr, buf, retval);
if (neededLen != -1) {
neededLen -= retval;
}
}
if (retval != readlen)
break;
}
/* Check for error conditions */
if (ferror(af->fp) && errno != EAGAIN) {
/* I/O error */
Jim_FreeNewObj(interp, objPtr);
JimAioSetError(interp, af->filename);
clearerr(af->fp);
return JIM_ERR;
}
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);
return JIM_OK;
}
static int aio_cmd_gets(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
char buf[AIO_BUF_LEN];
Jim_Obj *objPtr;
errno = 0;
objPtr = Jim_NewStringObj(interp, NULL, 0);
while (1) {
int more = 0;
buf[AIO_BUF_LEN - 1] = '_';
if (fgets(buf, AIO_BUF_LEN, af->fp) == NULL)
break;
if (buf[AIO_BUF_LEN - 1] == '\0' && buf[AIO_BUF_LEN - 2] != '\n')
more = 1;
if (more) {
Jim_AppendString(interp, objPtr, buf, AIO_BUF_LEN - 1);
}
else {
int len = strlen(buf);
if (len) {
int hasnl = (buf[len - 1] == '\n');
/* strip "\n" */
Jim_AppendString(interp, objPtr, buf, strlen(buf) - hasnl);
}
}
if (!more)
break;
}
if (ferror(af->fp) && errno != EAGAIN && errno != EINTR) {
/* I/O error */
Jim_FreeNewObj(interp, objPtr);
JimAioSetError(interp, af->filename);
clearerr(af->fp);
return JIM_ERR;
}
/* On EOF returns -1 if varName was specified, or the empty string. */
if (feof(af->fp) && Jim_Length(objPtr) == 0) {
Jim_FreeNewObj(interp, objPtr);
if (argc) {
Jim_SetResultInt(interp, -1);
}
return JIM_OK;
}
if (argc) {
int totLen;
Jim_GetString(objPtr, &totLen);
if (Jim_SetVariable(interp, argv[0], objPtr) != JIM_OK) {
Jim_FreeNewObj(interp, objPtr);
return JIM_ERR;
}
Jim_SetResultInt(interp, totLen);
}
else {
Jim_SetResult(interp, objPtr);
}
return JIM_OK;
}
static int aio_cmd_puts(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
int wlen;
const char *wdata;
Jim_Obj *strObj;
if (argc == 2) {
if (!Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
return -1;
}
strObj = argv[1];
}
else {
strObj = argv[0];
}
wdata = Jim_GetString(strObj, &wlen);
if (fwrite(wdata, 1, wlen, af->fp) == (unsigned)wlen) {
if (argc == 2 || putc('\n', af->fp) != EOF) {
return JIM_OK;
}
}
JimAioSetError(interp, af->filename);
return JIM_ERR;
}
#ifndef JIM_ANSIC
static int aio_cmd_recvfrom(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
char *buf;
union sockaddr_any sa;
long len;
socklen_t salen = sizeof(sa);
int rlen;
if (Jim_GetLong(interp, argv[0], &len) != JIM_OK) {
return JIM_ERR;
}
buf = Jim_Alloc(len + 1);
rlen = recvfrom(fileno(af->fp), buf, len, 0, &sa.sa, &salen);
if (rlen < 0) {
Jim_Free(buf);
JimAioSetError(interp, NULL);
return JIM_ERR;
}
buf[rlen] = 0;
Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, rlen));
if (argc > 1) {
/* INET6_ADDRSTRLEN is 46. Add some for [] and port */
char addrbuf[60];
#if IPV6
if (sa.sa.sa_family == 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.sin.sin_port));
}
else
#endif
{
/* 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));
}
if (Jim_SetVariable(interp, argv[1], Jim_NewStringObj(interp, addrbuf, -1)) != JIM_OK) {
return JIM_ERR;
}
}
return JIM_OK;
}
static int aio_cmd_sendto(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
int wlen;
int len;
const char *wdata;
union sockaddr_any sa;
const char *addr = Jim_GetString(argv[1], NULL);
int salen;
if (IPV6 && af->addr_family == PF_INET6) {
if (JimParseIPv6Address(interp, addr, &sa, &salen) != JIM_OK) {
return JIM_ERR;
}
}
else if (JimParseIpAddress(interp, addr, &sa, &salen) != JIM_OK) {
return JIM_ERR;
}
wdata = Jim_GetString(argv[0], &wlen);
/* Note that we don't validate the socket type. Rely on sendto() failing if appropriate */
len = sendto(fileno(af->fp), wdata, wlen, 0, &sa.sa, salen);
if (len < 0) {
JimAioSetError(interp, NULL);
return JIM_ERR;
}
Jim_SetResultInt(interp, len);
return JIM_OK;
}
static int aio_cmd_accept(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *serv_af = Jim_CmdPrivData(interp);
int sock;
union sockaddr_any sa;
socklen_t addrlen = sizeof(sa);
AioFile *af;
char buf[AIO_CMD_LEN];
sock = accept(serv_af->fd, &sa.sa, &addrlen);
if (sock < 0)
return JIM_ERR;
/* Create the file command */
af = Jim_Alloc(sizeof(*af));
af->fd = sock;
af->filename = Jim_NewStringObj(interp, "accept", -1);
Jim_IncrRefCount(af->filename);
af->fp = fdopen(sock, "r+");
af->OpenFlags = 0;
#ifdef O_NDELAY
af->flags = fcntl(af->fd, F_GETFL);
#endif
af->rEvent = NULL;
af->wEvent = NULL;
af->eEvent = NULL;
af->addr_family = serv_af->addr_family;
sprintf(buf, "aio.sockstream%ld", Jim_GetId(interp));
Jim_CreateCommand(interp, buf, JimAioSubCmdProc, af, JimAioDelProc);
Jim_SetResultString(interp, buf, -1);
return JIM_OK;
}
#endif
static int aio_cmd_flush(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
if (fflush(af->fp) == EOF) {
JimAioSetError(interp, af->filename);
return JIM_ERR;
}
return JIM_OK;
}
static int aio_cmd_eof(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
Jim_SetResultInt(interp, feof(af->fp));
return JIM_OK;
}
static int aio_cmd_close(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
Jim_DeleteCommand(interp, Jim_GetString(argv[0], NULL));
return JIM_OK;
}
static int aio_cmd_seek(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
int orig = SEEK_SET;
long offset;
if (argc == 2) {
if (Jim_CompareStringImmediate(interp, argv[1], "start"))
orig = SEEK_SET;
else if (Jim_CompareStringImmediate(interp, argv[1], "current"))
orig = SEEK_CUR;
else if (Jim_CompareStringImmediate(interp, argv[1], "end"))
orig = SEEK_END;
else {
return -1;
}
}
if (Jim_GetLong(interp, argv[0], &offset) != JIM_OK) {
return JIM_ERR;
}
if (fseek(af->fp, offset, orig) == -1) {
JimAioSetError(interp, af->filename);
return JIM_ERR;
}
return JIM_OK;
}
static int aio_cmd_tell(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
Jim_SetResultInt(interp, ftell(af->fp));
return JIM_OK;
}
static int aio_cmd_filename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
Jim_SetResult(interp, af->filename);
return JIM_OK;
}
#ifdef O_NDELAY
static int aio_cmd_ndelay(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
int fmode = af->flags;
if (argc) {
long nb;
if (Jim_GetLong(interp, argv[0], &nb) != JIM_OK) {
return JIM_ERR;
}
if (nb) {
fmode |= O_NDELAY;
}
else {
fmode &= ~O_NDELAY;
}
fcntl(af->fd, F_SETFL, fmode);
af->flags = fmode;
}
Jim_SetResultInt(interp, (fmode & O_NONBLOCK) ? 1 : 0);
return JIM_OK;
}
#endif
#ifdef jim_ext_eventloop
static void JimAioFileEventFinalizer(Jim_Interp *interp, void *clientData)
{
Jim_Obj *objPtr = clientData;
Jim_DecrRefCount(interp, objPtr);
}
static int JimAioFileEventHandler(Jim_Interp *interp, void *clientData, int mask)
{
Jim_Obj *objPtr = clientData;
return Jim_EvalObjBackground(interp, objPtr);
}
static int aio_eventinfo(Jim_Interp *interp, AioFile * af, unsigned mask, Jim_Obj **scriptHandlerObj,
int argc, Jim_Obj * const *argv)
{
int scriptlen = 0;
if (argc == 0) {
/* Return current script */
if (*scriptHandlerObj) {
Jim_SetResult(interp, *scriptHandlerObj);
}
return JIM_OK;
}
if (*scriptHandlerObj) {
/* Delete old handler */
Jim_DeleteFileHandler(interp, af->fp);
*scriptHandlerObj = NULL;
}
/* Now possibly add the new script(s) */
Jim_GetString(argv[0], &scriptlen);
if (scriptlen == 0) {
/* Empty script, so done */
return JIM_OK;
}
/* A new script to add */
Jim_IncrRefCount(argv[0]);
*scriptHandlerObj = argv[0];
Jim_CreateFileHandler(interp, af->fp, mask,
JimAioFileEventHandler, *scriptHandlerObj, JimAioFileEventFinalizer);
return JIM_OK;
}
static int aio_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
return aio_eventinfo(interp, af, JIM_EVENT_READABLE, &af->rEvent, argc, argv);
}
static int aio_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
return aio_eventinfo(interp, af, JIM_EVENT_WRITABLE, &af->wEvent, argc, argv);
}
static int aio_cmd_onexception(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
AioFile *af = Jim_CmdPrivData(interp);
return aio_eventinfo(interp, af, JIM_EVENT_EXCEPTION, &af->wEvent, argc, argv);
}
#endif
static const jim_subcmd_type aio_command_table[] = {
{ .cmd = "read",
.args = "?-nonewline? ?len?",
.function = aio_cmd_read,
.minargs = 0,
.maxargs = 2,
.description = "Read and return bytes from the stream. To eof if no len."
},
{ .cmd = "gets",
.args = "?var?",
.function = aio_cmd_gets,
.minargs = 0,
.maxargs = 1,
.description = "Read one line and return it or store it in the var"
},
{ .cmd = "puts",
.args = "?-nonewline? str",
.function = aio_cmd_puts,
.minargs = 1,
.maxargs = 2,
.description = "Write the string, with newline unless -nonewline"
},
#ifndef JIM_ANSIC
{ .cmd = "recvfrom",
.args = "len ?addrvar?",
.function = aio_cmd_recvfrom,
.minargs = 1,
.maxargs = 2,
.description = "Receive up to 'len' bytes on the socket. Sets 'addrvar' with receive address, if set"
},
{ .cmd = "sendto",
.args = "str address",
.function = aio_cmd_sendto,
.minargs = 2,
.maxargs = 2,
.description = "Send 'str' to the given address (dgram only)"
},
{ .cmd = "accept",
.function = aio_cmd_accept,
.description = "Server socket only: Accept a connection and return stream"
},
#endif
{ .cmd = "flush",
.function = aio_cmd_flush,
.description = "Flush the stream"
},
{ .cmd = "eof",
.function = aio_cmd_eof,
.description = "Returns 1 if stream is at eof"
},
{ .cmd = "close",
.flags = JIM_MODFLAG_FULLARGV,
.function = aio_cmd_close,
.description = "Closes the stream"
},
{ .cmd = "seek",
.args = "offset ?start|current|end",
.function = aio_cmd_seek,
.minargs = 1,
.maxargs = 2,
.description = "Seeks in the stream (default 'current')"
},
{ .cmd = "tell",
.function = aio_cmd_tell,
.description = "Returns the current seek position"
},
{ .cmd = "filename",
.function = aio_cmd_filename,
.description = "Returns the original filename"
},
#ifdef O_NDELAY
{ .cmd = "ndelay",
.args = "?0|1?",
.function = aio_cmd_ndelay,
.minargs = 0,
.maxargs = 1,
.description = "Set O_NDELAY (if arg). Returns current/new setting."
},
#endif
#ifdef jim_ext_eventloop
{ .cmd = "readable",
.args = "?readable-script?",
.minargs = 0,
.maxargs = 1,
.function = aio_cmd_readable,
.description = "Returns script, or invoke readable-script when readable, {} to remove",
},
{ .cmd = "writable",
.args = "?writable-script?",
.minargs = 0,
.maxargs = 1,
.function = aio_cmd_writable,
.description = "Returns script, or invoke writable-script when writable, {} to remove",
},
{ .cmd = "onexception",
.args = "?exception-script?",
.minargs = 0,
.maxargs = 1,
.function = aio_cmd_onexception,
.description = "Returns script, or invoke exception-script when oob data, {} to remove",
},
#endif
{ 0 }
};
static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
return Jim_CallSubCmd(interp, Jim_ParseSubCmd(interp, aio_command_table, argc, argv), argc, argv);
}
static int JimAioOpenCommand(Jim_Interp *interp, int argc,
Jim_Obj *const *argv)
{
FILE *fp;
AioFile *af;
char buf[AIO_CMD_LEN];
int OpenFlags = 0;
const char *cmdname;
if (argc != 2 && argc != 3) {
Jim_WrongNumArgs(interp, 1, argv, "filename ?mode?");
return JIM_ERR;
}
cmdname = Jim_GetString(argv[1], NULL);
if (Jim_CompareStringImmediate(interp, argv[1], "stdin")) {
OpenFlags |= AIO_KEEPOPEN;
fp = stdin;
}
else if (Jim_CompareStringImmediate(interp, argv[1], "stdout")) {
OpenFlags |= AIO_KEEPOPEN;
fp = stdout;
}
else if (Jim_CompareStringImmediate(interp, argv[1], "stderr")) {
OpenFlags |= AIO_KEEPOPEN;
fp = stderr;
}
else {
const char *mode = (argc == 3) ? Jim_GetString(argv[2], NULL) : "r";
const char *filename = Jim_GetString(argv[1], NULL);
#ifdef jim_ext_tclcompat
/* If the filename starts with '|', use popen instead */
if (*filename == '|') {
Jim_Obj *evalObj[3];
evalObj[0] = Jim_NewStringObj(interp, "popen", -1);
evalObj[1] = Jim_NewStringObj(interp, filename + 1, -1);
evalObj[2] = Jim_NewStringObj(interp, mode, -1);
return Jim_EvalObjVector(interp, 3, evalObj);
}
#endif
fp = fopen(filename, mode);
if (fp == NULL) {
JimAioSetError(interp, argv[1]);
return JIM_ERR;
}
/* Get the next file id */
sprintf(buf, "aio.handle%ld", Jim_GetId(interp));
cmdname = buf;
}
/* Create the file command */
af = Jim_Alloc(sizeof(*af));
af->fp = fp;
af->fd = fileno(fp);
#ifdef O_NDELAY
af->flags = fcntl(af->fd, F_GETFL);
#endif
af->filename = argv[1];
Jim_IncrRefCount(af->filename);
af->OpenFlags = OpenFlags;
af->rEvent = NULL;
af->wEvent = NULL;
af->eEvent = NULL;
Jim_CreateCommand(interp, cmdname, JimAioSubCmdProc, af, JimAioDelProc);
Jim_SetResultString(interp, cmdname, -1);
return JIM_OK;
}
#ifndef JIM_ANSIC
/**
* Creates a channel for fd.
*
* hdlfmt is a sprintf format for the filehandle. Anything with %ld at the end will do.
* mode is usual "r+", but may be another fdopen() mode as required.
*
* Creates the command and lappends the name of the command to the current result.
*
*/
static int JimMakeChannel(Jim_Interp *interp, Jim_Obj *filename, const char *hdlfmt, int fd, int family,
const char *mode)
{
AioFile *af;
char buf[AIO_CMD_LEN];
FILE *fp = fdopen(fd, mode);
if (fp == NULL) {
close(fd);
JimAioSetError(interp, NULL);
return JIM_ERR;
}
/* Create the file command */
af = Jim_Alloc(sizeof(*af));
af->fp = fp;
af->fd = fd;
af->OpenFlags = 0;
af->filename = filename;
Jim_IncrRefCount(af->filename);
#ifdef O_NDELAY
af->flags = fcntl(af->fd, F_GETFL);
#endif
af->rEvent = NULL;
af->wEvent = NULL;
af->eEvent = NULL;
af->addr_family = family;
snprintf(buf, sizeof(buf), hdlfmt, Jim_GetId(interp));
Jim_CreateCommand(interp, buf, JimAioSubCmdProc, af, JimAioDelProc);
Jim_ListAppendElement(interp, Jim_GetResult(interp), Jim_NewStringObj(interp, buf, -1));
return JIM_OK;
}
static int JimAioSockCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
const char *hdlfmt = "aio.unknown%ld";
const char *socktypes[] = {
"unix",
"unix.server",
"dgram",
"dgram.server",
"stream",
"stream.server",
"pipe",
NULL
};
enum
{
SOCK_UNIX,
SOCK_UNIX_SERVER,
SOCK_DGRAM_CLIENT,
SOCK_DGRAM_SERVER,
SOCK_STREAM_CLIENT,
SOCK_STREAM_SERVER,
SOCK_STREAM_PIPE,
SOCK_DGRAM6_CLIENT,
SOCK_DGRAM6_SERVER,
SOCK_STREAM6_CLIENT,
SOCK_STREAM6_SERVER,
};
int socktype;
int sock;
const char *hostportarg = NULL;
int res;
int on = 1;
const char *mode = "r+";
int family = PF_INET;
Jim_Obj *argv0 = argv[0];
int ipv6 = 0;
if (argc > 1 && Jim_CompareStringImmediate(interp, argv[1], "-ipv6")) {
if (!IPV6) {
Jim_SetResultString(interp, "ipv6 not supported", -1);
return JIM_ERR;
}
ipv6 = 1;
family = PF_INET6;
}
argc -= ipv6;
argv += ipv6;
if (argc < 2) {
wrongargs:
Jim_WrongNumArgs(interp, 1, &argv0, "?-ipv6? type ?address?");
return JIM_ERR;
}
if (Jim_GetEnum(interp, argv[1], socktypes, &socktype, "socket type", JIM_ERRMSG) != JIM_OK)
return JIM_ERR;
Jim_SetResultString(interp, "", 0);
hdlfmt = "aio.sock%ld";
if (argc > 2) {
hostportarg = Jim_GetString(argv[2], NULL);
}
switch (socktype) {
case SOCK_DGRAM_CLIENT:
if (argc == 2) {
/* No address, so an unconnected dgram socket */
sock = socket(family, SOCK_DGRAM, 0);
if (sock < 0) {
JimAioSetError(interp, NULL);
return JIM_ERR;
}
break;
}
/* fall through */
case SOCK_STREAM_CLIENT:
{
union sockaddr_any sa;
int salen;
if (argc != 3) {
goto wrongargs;
}
if (ipv6) {
if (JimParseIPv6Address(interp, hostportarg, &sa, &salen) != JIM_OK) {
return JIM_ERR;
}
}
else if (JimParseIpAddress(interp, hostportarg, &sa, &salen) != JIM_OK) {
return JIM_ERR;
}
sock = socket(family, (socktype == SOCK_DGRAM_CLIENT) ? SOCK_DGRAM : SOCK_STREAM, 0);
if (sock < 0) {
JimAioSetError(interp, NULL);
return JIM_ERR;
}
res = connect(sock, &sa.sa, salen);
if (res) {
JimAioSetError(interp, argv[2]);
close(sock);
return JIM_ERR;
}
}
break;
case SOCK_STREAM_SERVER:
case SOCK_DGRAM_SERVER:
{
union sockaddr_any sa;
int salen;
if (argc != 3) {
goto wrongargs;
}
if (ipv6) {
if (JimParseIPv6Address(interp, hostportarg, &sa, &salen) != JIM_OK) {
return JIM_ERR;
}
}
else if (JimParseIpAddress(interp, hostportarg, &sa, &salen) != JIM_OK) {
return JIM_ERR;
}
sock = socket(family, (socktype == SOCK_DGRAM_SERVER) ? SOCK_DGRAM : SOCK_STREAM, 0);
if (sock < 0) {
JimAioSetError(interp, NULL);
return JIM_ERR;
}
/* Enable address reuse */
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
res = bind(sock, &sa.sa, salen);
if (res) {
JimAioSetError(interp, argv[2]);
close(sock);
return JIM_ERR;
}
if (socktype == SOCK_STREAM_SERVER) {
res = listen(sock, 5);
if (res) {
JimAioSetError(interp, NULL);
close(sock);
return JIM_ERR;
}
}
hdlfmt = "aio.socksrv%ld";
}
break;
#ifdef HAVE_SYS_UN_H
case SOCK_UNIX:
{
struct sockaddr_un sa;
socklen_t len;
if (argc != 3 || ipv6) {
goto wrongargs;
}
if (JimParseDomainAddress(interp, hostportarg, &sa) != JIM_OK) {
JimAioSetError(interp, argv[2]);
return JIM_ERR;
}
family = PF_UNIX;
sock = socket(PF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
JimAioSetError(interp, NULL);
return JIM_ERR;
}
len = strlen(sa.sun_path) + 1 + sizeof(sa.sun_family);
res = connect(sock, (struct sockaddr *)&sa, len);
if (res) {
JimAioSetError(interp, argv[2]);
close(sock);
return JIM_ERR;
}
hdlfmt = "aio.sockunix%ld";
break;
}
case SOCK_UNIX_SERVER:
{
struct sockaddr_un sa;
socklen_t len;
if (argc != 3 || ipv6) {
goto wrongargs;
}
if (JimParseDomainAddress(interp, hostportarg, &sa) != JIM_OK) {
JimAioSetError(interp, argv[2]);
return JIM_ERR;
}
family = PF_UNIX;
sock = socket(PF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
JimAioSetError(interp, NULL);
return JIM_ERR;
}
len = strlen(sa.sun_path) + 1 + sizeof(sa.sun_family);
res = bind(sock, (struct sockaddr *)&sa, len);
if (res) {
JimAioSetError(interp, argv[2]);
close(sock);
return JIM_ERR;
}
res = listen(sock, 5);
if (res) {
JimAioSetError(interp, NULL);
close(sock);
return JIM_ERR;
}
hdlfmt = "aio.sockunixsrv%ld";
break;
}
#endif
#ifdef HAVE_PIPE
case SOCK_STREAM_PIPE:
{
int p[2];
if (argc != 2 || ipv6) {
goto wrongargs;
}
if (pipe(p) < 0) {
JimAioSetError(interp, NULL);
return JIM_ERR;
}
hdlfmt = "aio.pipe%ld";
if (JimMakeChannel(interp, argv[1], hdlfmt, p[0], family, "r") != JIM_OK) {
close(p[0]);
close(p[1]);
JimAioSetError(interp, NULL);
return JIM_ERR;
}
/* Note, if this fails it will leave p[0] open, but this should never happen */
mode = "w";
sock = p[1];
}
break;
#endif
default:
Jim_SetResultString(interp, "Unsupported socket type", -1);
return JIM_ERR;
}
return JimMakeChannel(interp, argv[1], hdlfmt, sock, family, mode);
}
#endif
FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command)
{
Jim_Cmd *cmdPtr = Jim_GetCommand(interp, command, JIM_ERRMSG);
if (cmdPtr && cmdPtr->cmdProc == JimAioSubCmdProc) {
return ((AioFile *) cmdPtr->privData)->fp;
}
return NULL;
}
int Jim_aioInit(Jim_Interp *interp)
{
if (Jim_PackageProvide(interp, "aio", "1.0", JIM_ERRMSG))
return JIM_ERR;
Jim_CreateCommand(interp, "open", JimAioOpenCommand, NULL, NULL);
#ifndef JIM_ANSIC
Jim_CreateCommand(interp, "socket", JimAioSockCommand, NULL, NULL);
#endif
/* Takeover stdin, stdout and stderr */
Jim_EvalGlobal(interp, "open stdin; open stdout; open stderr");
return JIM_OK;
}
|