2 /* Jim - A small embeddable Tcl interpreter
4 * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5 * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
6 * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
7 * Copyright 2008 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
8 * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
9 * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
10 * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above
19 * copyright notice, this list of conditions and the following
20 * disclaimer in the documentation and/or other materials
21 * provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
25 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
26 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
28 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
32 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
34 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 * The views and conclusions contained in the software and documentation
37 * are those of the authors and should not be interpreted as representing
38 * official policies, either expressed or implied, of the Jim Tcl Project.
41 #include "jimautoconf.h"
53 #if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
54 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
66 #include "jim-eventloop.h"
67 #include "jim-subcmd.h"
69 #define AIO_CMD_LEN 32 /* e.g. aio.handleXXXXXX */
70 #define AIO_BUF_LEN 256 /* Can keep this small and rely on stdio buffering */
79 #define AIO_KEEPOPEN 1
90 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
93 struct sockaddr_in sin
;
95 struct sockaddr_in6 sin6
;
99 #ifndef HAVE_INET_NTOP
100 const char *inet_ntop(int af
, const void *src
, char *dst
, int size
)
105 snprintf(dst
, size
, "%s", inet_ntoa(((struct sockaddr_in
*)src
)->sin_addr
));
109 #endif /* JIM_BOOTSTRAP */
111 typedef struct AioFile
116 int OpenFlags
; /* AIO_KEEPOPEN? keep FILE* */
127 static int JimAioSubCmdProc(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
);
128 static int JimMakeChannel(Jim_Interp
*interp
, FILE *fh
, int fd
, Jim_Obj
*filename
,
129 const char *hdlfmt
, int family
, const char *mode
);
131 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
132 static int JimParseIPv6Address(Jim_Interp
*interp
, const char *hostport
, union sockaddr_any
*sa
, int *salen
)
136 * An IPv6 addr/port looks like:
139 * [fe80::223:6cff:fe95:bdc0%en1]:2000
143 * Note that the "any" address is ::, which is the same as when no address is specified.
151 stport
= strrchr(hostport
, ':');
153 /* No : so, the whole thing is the port */
156 sthost
= Jim_StrDup(hostport
);
162 if (*hostport
== '[') {
163 /* This is a numeric ipv6 address */
164 char *pt
= strchr(++hostport
, ']');
166 sthost
= Jim_StrDupLen(hostport
, pt
- hostport
);
171 sthost
= Jim_StrDupLen(hostport
, stport
- hostport
- 1);
174 memset(&req
, '\0', sizeof(req
));
175 req
.ai_family
= PF_INET6
;
177 if (getaddrinfo(sthost
, NULL
, &req
, &ai
)) {
178 Jim_SetResultFormatted(interp
, "Not a valid address: %s", hostport
);
182 memcpy(&sa
->sin
, ai
->ai_addr
, ai
->ai_addrlen
);
183 *salen
= ai
->ai_addrlen
;
185 sa
->sin
.sin_port
= htons(atoi(stport
));
193 Jim_SetResultString(interp
, "ipv6 not supported", -1);
198 static int JimParseIpAddress(Jim_Interp
*interp
, const char *hostport
, union sockaddr_any
*sa
, int *salen
)
200 /* An IPv4 addr/port looks like:
205 * If the address is missing, INADDR_ANY is used.
206 * If the port is missing, 0 is used (only useful for server sockets).
212 stport
= strrchr(hostport
, ':');
214 /* No : so, the whole thing is the port */
216 sthost
= Jim_StrDup("0.0.0.0");
219 sthost
= Jim_StrDupLen(hostport
, stport
- hostport
);
224 #ifdef HAVE_GETADDRINFO
227 memset(&req
, '\0', sizeof(req
));
228 req
.ai_family
= PF_INET
;
230 if (getaddrinfo(sthost
, NULL
, &req
, &ai
)) {
234 memcpy(&sa
->sin
, ai
->ai_addr
, ai
->ai_addrlen
);
235 *salen
= ai
->ai_addrlen
;
243 if ((he
= gethostbyname(sthost
)) != NULL
) {
244 if (he
->h_length
== sizeof(sa
->sin
.sin_addr
)) {
245 *salen
= sizeof(sa
->sin
);
246 sa
->sin
.sin_family
= he
->h_addrtype
;
247 memcpy(&sa
->sin
.sin_addr
, he
->h_addr
, he
->h_length
); /* set address */
253 sa
->sin
.sin_port
= htons(atoi(stport
));
258 Jim_SetResultFormatted(interp
, "Not a valid address: %s", hostport
);
265 static int JimParseDomainAddress(Jim_Interp
*interp
, const char *path
, struct sockaddr_un
*sa
)
267 sa
->sun_family
= PF_UNIX
;
268 snprintf(sa
->sun_path
, sizeof(sa
->sun_path
), "%s", path
);
273 #endif /* JIM_BOOTSTRAP */
275 static void JimAioSetError(Jim_Interp
*interp
, Jim_Obj
*name
)
278 Jim_SetResultFormatted(interp
, "%#s: %s", name
, strerror(errno
));
281 Jim_SetResultString(interp
, strerror(errno
), -1);
285 static void JimAioDelProc(Jim_Interp
*interp
, void *privData
)
287 AioFile
*af
= privData
;
291 if (!(af
->OpenFlags
& AIO_KEEPOPEN
)) {
295 Jim_DecrRefCount(interp
, af
->filename
);
297 #ifdef jim_ext_eventloop
298 /* remove all existing EventHandlers */
299 Jim_DeleteFileHandler(interp
, af
->fp
, JIM_EVENT_READABLE
| JIM_EVENT_WRITABLE
| JIM_EVENT_EXCEPTION
);
304 static int JimCheckStreamError(Jim_Interp
*interp
, AioFile
*af
)
306 if (!ferror(af
->fp
)) {
310 /* EAGAIN and similar are not error conditions. Just treat them like eof */
311 if (feof(af
->fp
) || errno
== EAGAIN
|| errno
== EINTR
) {
315 if (errno
== ECONNRESET
) {
320 if (errno
!= ECONNABORTED
) {
324 JimAioSetError(interp
, af
->filename
);
328 static int aio_cmd_read(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
330 AioFile
*af
= Jim_CmdPrivData(interp
);
331 char buf
[AIO_BUF_LEN
];
334 jim_wide neededLen
= -1; /* -1 is "read as much as possible" */
336 if (argc
&& Jim_CompareStringImmediate(interp
, argv
[0], "-nonewline")) {
342 if (Jim_GetWide(interp
, argv
[0], &neededLen
) != JIM_OK
)
345 Jim_SetResultString(interp
, "invalid parameter: negative len", -1);
352 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
353 while (neededLen
!= 0) {
357 if (neededLen
== -1) {
358 readlen
= AIO_BUF_LEN
;
361 readlen
= (neededLen
> AIO_BUF_LEN
? AIO_BUF_LEN
: neededLen
);
363 retval
= fread(buf
, 1, readlen
, af
->fp
);
365 Jim_AppendString(interp
, objPtr
, buf
, retval
);
366 if (neededLen
!= -1) {
370 if (retval
!= readlen
)
373 /* Check for error conditions */
374 if (JimCheckStreamError(interp
, af
)) {
375 Jim_FreeNewObj(interp
, objPtr
);
380 const char *s
= Jim_GetString(objPtr
, &len
);
382 if (len
> 0 && s
[len
- 1] == '\n') {
384 objPtr
->bytes
[objPtr
->length
] = '\0';
387 Jim_SetResult(interp
, objPtr
);
391 static int aio_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
393 AioFile
*af
= Jim_CmdPrivData(interp
);
395 jim_wide maxlen
= JIM_WIDE_MAX
;
396 FILE *outfh
= Jim_AioFilehandle(interp
, argv
[0]);
403 if (Jim_GetWide(interp
, argv
[1], &maxlen
) != JIM_OK
) {
408 while (count
< maxlen
) {
409 int ch
= fgetc(af
->fp
);
411 if (ch
== EOF
|| fputc(ch
, outfh
) == EOF
) {
417 if (ferror(af
->fp
)) {
418 Jim_SetResultFormatted(interp
, "error while reading: %s", strerror(errno
));
424 Jim_SetResultFormatted(interp
, "error while writing: %s", strerror(errno
));
429 Jim_SetResultInt(interp
, count
);
434 static int aio_cmd_gets(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
436 AioFile
*af
= Jim_CmdPrivData(interp
);
437 char buf
[AIO_BUF_LEN
];
443 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
445 buf
[AIO_BUF_LEN
- 1] = '_';
446 if (fgets(buf
, AIO_BUF_LEN
, af
->fp
) == NULL
)
449 if (buf
[AIO_BUF_LEN
- 1] == '\0' && buf
[AIO_BUF_LEN
- 2] != '\n') {
450 Jim_AppendString(interp
, objPtr
, buf
, AIO_BUF_LEN
- 1);
455 if (len
&& (buf
[len
- 1] == '\n')) {
460 Jim_AppendString(interp
, objPtr
, buf
, len
);
464 if (JimCheckStreamError(interp
, af
)) {
466 Jim_FreeNewObj(interp
, objPtr
);
471 if (Jim_SetVariable(interp
, argv
[0], objPtr
) != JIM_OK
) {
472 Jim_FreeNewObj(interp
, objPtr
);
476 len
= Jim_Length(objPtr
);
478 if (len
== 0 && feof(af
->fp
)) {
479 /* On EOF returns -1 if varName was specified */
482 Jim_SetResultInt(interp
, len
);
485 Jim_SetResult(interp
, objPtr
);
490 static int aio_cmd_puts(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
492 AioFile
*af
= Jim_CmdPrivData(interp
);
498 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-nonewline")) {
507 wdata
= Jim_GetString(strObj
, &wlen
);
508 if (fwrite(wdata
, 1, wlen
, af
->fp
) == (unsigned)wlen
) {
509 if (argc
== 2 || putc('\n', af
->fp
) != EOF
) {
513 JimAioSetError(interp
, af
->filename
);
517 static int aio_cmd_isatty(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
520 AioFile
*af
= Jim_CmdPrivData(interp
);
521 Jim_SetResultInt(interp
, isatty(fileno(af
->fp
)));
523 Jim_SetResultInt(interp
, 0);
529 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
530 static int aio_cmd_recvfrom(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
532 AioFile
*af
= Jim_CmdPrivData(interp
);
534 union sockaddr_any sa
;
536 socklen_t salen
= sizeof(sa
);
539 if (Jim_GetLong(interp
, argv
[0], &len
) != JIM_OK
) {
543 buf
= Jim_Alloc(len
+ 1);
545 rlen
= recvfrom(fileno(af
->fp
), buf
, len
, 0, &sa
.sa
, &salen
);
548 JimAioSetError(interp
, NULL
);
552 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, rlen
));
555 /* INET6_ADDRSTRLEN is 46. Add some for [] and port */
559 if (sa
.sa
.sa_family
== PF_INET6
) {
561 /* Allow 9 for []:65535\0 */
562 inet_ntop(sa
.sa
.sa_family
, &sa
.sin6
.sin6_addr
, addrbuf
+ 1, sizeof(addrbuf
) - 9);
563 snprintf(addrbuf
+ strlen(addrbuf
), 8, "]:%d", ntohs(sa
.sin
.sin_port
));
567 if (sa
.sa
.sa_family
== PF_INET
) {
568 /* Allow 7 for :65535\0 */
569 inet_ntop(sa
.sa
.sa_family
, &sa
.sin
.sin_addr
, addrbuf
, sizeof(addrbuf
) - 7);
570 snprintf(addrbuf
+ strlen(addrbuf
), 7, ":%d", ntohs(sa
.sin
.sin_port
));
573 /* recvfrom still works on unix domain sockets, etc */
577 if (Jim_SetVariable(interp
, argv
[1], Jim_NewStringObj(interp
, addrbuf
, -1)) != JIM_OK
) {
586 static int aio_cmd_sendto(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
588 AioFile
*af
= Jim_CmdPrivData(interp
);
592 union sockaddr_any sa
;
593 const char *addr
= Jim_String(argv
[1]);
596 if (IPV6
&& af
->addr_family
== PF_INET6
) {
597 if (JimParseIPv6Address(interp
, addr
, &sa
, &salen
) != JIM_OK
) {
601 else if (JimParseIpAddress(interp
, addr
, &sa
, &salen
) != JIM_OK
) {
604 wdata
= Jim_GetString(argv
[0], &wlen
);
606 /* Note that we don't validate the socket type. Rely on sendto() failing if appropriate */
607 len
= sendto(fileno(af
->fp
), wdata
, wlen
, 0, &sa
.sa
, salen
);
609 JimAioSetError(interp
, NULL
);
612 Jim_SetResultInt(interp
, len
);
616 static int aio_cmd_accept(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
618 AioFile
*af
= Jim_CmdPrivData(interp
);
620 union sockaddr_any sa
;
621 socklen_t addrlen
= sizeof(sa
);
623 sock
= accept(af
->fd
, &sa
.sa
, &addrlen
);
625 JimAioSetError(interp
, NULL
);
629 /* Create the file command */
630 return JimMakeChannel(interp
, NULL
, sock
, Jim_NewStringObj(interp
, "accept", -1),
631 "aio.sockstream%ld", af
->addr_family
, "r+");
634 static int aio_cmd_listen(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
636 AioFile
*af
= Jim_CmdPrivData(interp
);
639 if (Jim_GetLong(interp
, argv
[0], &backlog
) != JIM_OK
) {
643 if (listen(af
->fd
, backlog
)) {
644 JimAioSetError(interp
, NULL
);
650 #endif /* JIM_BOOTSTRAP */
652 static int aio_cmd_flush(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
654 AioFile
*af
= Jim_CmdPrivData(interp
);
656 if (fflush(af
->fp
) == EOF
) {
657 JimAioSetError(interp
, af
->filename
);
663 static int aio_cmd_eof(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
665 AioFile
*af
= Jim_CmdPrivData(interp
);
667 Jim_SetResultInt(interp
, feof(af
->fp
));
671 static int aio_cmd_close(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
675 static const char * const options
[] = { "r", "w", NULL
};
676 enum { OPT_R
, OPT_W
, };
678 AioFile
*af
= Jim_CmdPrivData(interp
);
680 if (Jim_GetEnum(interp
, argv
[2], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
683 if (shutdown(af
->fd
, option
== OPT_R
? SHUT_RD
: SHUT_WR
) == 0) {
686 JimAioSetError(interp
, NULL
);
688 Jim_SetResultString(interp
, "async close not supported", -1);
693 return Jim_DeleteCommand(interp
, Jim_String(argv
[0]));
696 static int aio_cmd_seek(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
698 AioFile
*af
= Jim_CmdPrivData(interp
);
703 if (Jim_CompareStringImmediate(interp
, argv
[1], "start"))
705 else if (Jim_CompareStringImmediate(interp
, argv
[1], "current"))
707 else if (Jim_CompareStringImmediate(interp
, argv
[1], "end"))
713 if (Jim_GetWide(interp
, argv
[0], &offset
) != JIM_OK
) {
716 if (fseeko(af
->fp
, offset
, orig
) == -1) {
717 JimAioSetError(interp
, af
->filename
);
723 static int aio_cmd_tell(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
725 AioFile
*af
= Jim_CmdPrivData(interp
);
727 Jim_SetResultInt(interp
, ftello(af
->fp
));
731 static int aio_cmd_filename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
733 AioFile
*af
= Jim_CmdPrivData(interp
);
735 Jim_SetResult(interp
, af
->filename
);
740 static int aio_cmd_ndelay(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
742 AioFile
*af
= Jim_CmdPrivData(interp
);
744 int fmode
= af
->flags
;
749 if (Jim_GetLong(interp
, argv
[0], &nb
) != JIM_OK
) {
758 fcntl(af
->fd
, F_SETFL
, fmode
);
761 Jim_SetResultInt(interp
, (fmode
& O_NONBLOCK
) ? 1 : 0);
766 static int aio_cmd_buffering(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
768 AioFile
*af
= Jim_CmdPrivData(interp
);
770 static const char * const options
[] = {
784 if (Jim_GetEnum(interp
, argv
[0], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
789 setvbuf(af
->fp
, NULL
, _IONBF
, 0);
792 setvbuf(af
->fp
, NULL
, _IOLBF
, BUFSIZ
);
795 setvbuf(af
->fp
, NULL
, _IOFBF
, BUFSIZ
);
801 #ifdef jim_ext_eventloop
802 static void JimAioFileEventFinalizer(Jim_Interp
*interp
, void *clientData
)
804 Jim_Obj
**objPtrPtr
= clientData
;
806 Jim_DecrRefCount(interp
, *objPtrPtr
);
810 static int JimAioFileEventHandler(Jim_Interp
*interp
, void *clientData
, int mask
)
812 Jim_Obj
**objPtrPtr
= clientData
;
814 return Jim_EvalObjBackground(interp
, *objPtrPtr
);
817 static int aio_eventinfo(Jim_Interp
*interp
, AioFile
* af
, unsigned mask
, Jim_Obj
**scriptHandlerObj
,
818 int argc
, Jim_Obj
* const *argv
)
821 /* Return current script */
822 if (*scriptHandlerObj
) {
823 Jim_SetResult(interp
, *scriptHandlerObj
);
828 if (*scriptHandlerObj
) {
829 /* Delete old handler */
830 Jim_DeleteFileHandler(interp
, af
->fp
, mask
);
833 /* Now possibly add the new script(s) */
834 if (Jim_Length(argv
[0]) == 0) {
835 /* Empty script, so done */
839 /* A new script to add */
840 Jim_IncrRefCount(argv
[0]);
841 *scriptHandlerObj
= argv
[0];
843 Jim_CreateFileHandler(interp
, af
->fp
, mask
,
844 JimAioFileEventHandler
, scriptHandlerObj
, JimAioFileEventFinalizer
);
849 static int aio_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
851 AioFile
*af
= Jim_CmdPrivData(interp
);
853 return aio_eventinfo(interp
, af
, JIM_EVENT_READABLE
, &af
->rEvent
, argc
, argv
);
856 static int aio_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
858 AioFile
*af
= Jim_CmdPrivData(interp
);
860 return aio_eventinfo(interp
, af
, JIM_EVENT_WRITABLE
, &af
->wEvent
, argc
, argv
);
863 static int aio_cmd_onexception(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
865 AioFile
*af
= Jim_CmdPrivData(interp
);
867 return aio_eventinfo(interp
, af
, JIM_EVENT_EXCEPTION
, &af
->wEvent
, argc
, argv
);
871 static const jim_subcmd_type aio_command_table
[] = {
873 "?-nonewline? ?len?",
877 /* Description: Read and return bytes from the stream. To eof if no len. */
884 /* Description: Copy up to 'size' bytes to the given filehandle, or to eof if no size. */
891 /* Description: Read one line and return it or store it in the var */
898 /* Description: Write the string, with newline unless -nonewline */
905 /* Description: Is the file descriptor a tty? */
907 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
913 /* Description: Receive up to 'len' bytes on the socket. Sets 'addrvar' with receive address, if set */
920 /* Description: Send 'str' to the given address (dgram only) */
927 /* Description: Server socket only: Accept a connection and return stream */
934 /* Description: Set the listen backlog for server socket */
936 #endif /* JIM_BOOTSTRAP */
942 /* Description: Flush the stream */
949 /* Description: Returns 1 if stream is at eof */
956 JIM_MODFLAG_FULLARGV
,
957 /* Description: Closes the stream. */
960 "offset ?start|current|end",
964 /* Description: Seeks in the stream (default 'current') */
971 /* Description: Returns the current seek position */
978 /* Description: Returns the original filename */
986 /* Description: Set O_NDELAY (if arg). Returns current/new setting. */
994 /* Description: Sets buffering */
996 #ifdef jim_ext_eventloop
1002 /* Description: Returns script, or invoke readable-script when readable, {} to remove */
1005 "?writable-script?",
1009 /* Description: Returns script, or invoke writable-script when writable, {} to remove */
1012 "?exception-script?",
1013 aio_cmd_onexception
,
1016 /* Description: Returns script, or invoke exception-script when oob data, {} to remove */
1022 static int JimAioSubCmdProc(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1024 return Jim_CallSubCmd(interp
, Jim_ParseSubCmd(interp
, aio_command_table
, argc
, argv
), argc
, argv
);
1027 static int JimAioOpenCommand(Jim_Interp
*interp
, int argc
,
1028 Jim_Obj
*const *argv
)
1031 const char *filename
;
1033 if (argc
!= 2 && argc
!= 3) {
1034 Jim_WrongNumArgs(interp
, 1, argv
, "filename ?mode?");
1038 mode
= (argc
== 3) ? Jim_String(argv
[2]) : "r";
1039 filename
= Jim_String(argv
[1]);
1041 #ifdef jim_ext_tclcompat
1042 /* If the filename starts with '|', use popen instead */
1043 if (*filename
== '|') {
1044 Jim_Obj
*evalObj
[3];
1046 evalObj
[0] = Jim_NewStringObj(interp
, "popen", -1);
1047 evalObj
[1] = Jim_NewStringObj(interp
, filename
+ 1, -1);
1048 evalObj
[2] = Jim_NewStringObj(interp
, mode
, -1);
1050 return Jim_EvalObjVector(interp
, 3, evalObj
);
1053 return JimMakeChannel(interp
, NULL
, -1, argv
[1], "aio.handle%ld", 0, mode
);
1057 * Creates a channel for fh/fd/filename.
1059 * If fh is not NULL, uses that as the channel (and set AIO_KEEPOPEN).
1060 * Otherwise, if fd is >= 0, uses that as the chanel.
1061 * Otherwise opens 'filename' with mode 'mode'.
1063 * hdlfmt is a sprintf format for the filehandle. Anything with %ld at the end will do.
1064 * mode is used for open or fdopen.
1066 * Creates the command and sets the name as the current result.
1068 static int JimMakeChannel(Jim_Interp
*interp
, FILE *fh
, int fd
, Jim_Obj
*filename
,
1069 const char *hdlfmt
, int family
, const char *mode
)
1072 char buf
[AIO_CMD_LEN
];
1075 if (filename
== NULL
) {
1076 filename
= Jim_NewStringObj(interp
, hdlfmt
, -1);
1079 Jim_IncrRefCount(filename
);
1083 fh
= fopen(Jim_String(filename
), mode
);
1086 fh
= fdopen(fd
, mode
);
1090 OpenFlags
= AIO_KEEPOPEN
;
1094 JimAioSetError(interp
, filename
);
1095 #if !defined(JIM_ANSIC)
1100 Jim_DecrRefCount(interp
, filename
);
1104 /* Create the file command */
1105 af
= Jim_Alloc(sizeof(*af
));
1106 memset(af
, 0, sizeof(*af
));
1108 af
->fd
= fileno(fh
);
1109 af
->filename
= filename
;
1111 if ((OpenFlags
& AIO_KEEPOPEN
) == 0) {
1112 fcntl(af
->fd
, F_SETFD
, FD_CLOEXEC
);
1115 af
->OpenFlags
= OpenFlags
;
1117 af
->flags
= fcntl(af
->fd
, F_GETFL
);
1119 af
->addr_family
= family
;
1120 snprintf(buf
, sizeof(buf
), hdlfmt
, Jim_GetId(interp
));
1121 Jim_CreateCommand(interp
, buf
, JimAioSubCmdProc
, af
, JimAioDelProc
);
1123 /* Note that the command must use the global namespace, even if
1124 * the current namespace is something different
1126 Jim_SetResult(interp
, Jim_MakeGlobalNamespaceName(interp
, Jim_NewStringObj(interp
, buf
, -1)));
1131 static int JimMakeChannelPair(Jim_Interp
*interp
, int p
[2], Jim_Obj
*filename
,
1132 const char *hdlfmt
, int family
, const char *mode
[2])
1134 if (JimMakeChannel(interp
, NULL
, p
[0], filename
, hdlfmt
, family
, mode
[0]) == JIM_OK
) {
1135 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
1136 Jim_ListAppendElement(interp
, objPtr
, Jim_GetResult(interp
));
1138 if (JimMakeChannel(interp
, NULL
, p
[1], filename
, hdlfmt
, family
, mode
[1]) == JIM_OK
) {
1139 Jim_ListAppendElement(interp
, objPtr
, Jim_GetResult(interp
));
1140 Jim_SetResult(interp
, objPtr
);
1145 /* Can only be here if fdopen() failed */
1148 JimAioSetError(interp
, NULL
);
1152 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
1154 static int JimAioSockCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1156 const char *hdlfmt
= "aio.unknown%ld";
1157 const char *socktypes
[] = {
1177 SOCK_STREAM_SOCKETPAIR
,
1181 const char *hostportarg
= NULL
;
1184 const char *mode
= "r+";
1185 int family
= PF_INET
;
1186 Jim_Obj
*argv0
= argv
[0];
1189 if (argc
> 1 && Jim_CompareStringImmediate(interp
, argv
[1], "-ipv6")) {
1191 Jim_SetResultString(interp
, "ipv6 not supported", -1);
1202 Jim_WrongNumArgs(interp
, 1, &argv0
, "?-ipv6? type ?address?");
1206 if (Jim_GetEnum(interp
, argv
[1], socktypes
, &socktype
, "socket type", JIM_ERRMSG
) != JIM_OK
)
1209 Jim_SetEmptyResult(interp
);
1211 hdlfmt
= "aio.sock%ld";
1214 hostportarg
= Jim_String(argv
[2]);
1218 case SOCK_DGRAM_CLIENT
:
1220 /* No address, so an unconnected dgram socket */
1221 sock
= socket(family
, SOCK_DGRAM
, 0);
1223 JimAioSetError(interp
, NULL
);
1229 case SOCK_STREAM_CLIENT
:
1231 union sockaddr_any sa
;
1239 if (JimParseIPv6Address(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1243 else if (JimParseIpAddress(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1246 sock
= socket(family
, (socktype
== SOCK_DGRAM_CLIENT
) ? SOCK_DGRAM
: SOCK_STREAM
, 0);
1248 JimAioSetError(interp
, NULL
);
1251 res
= connect(sock
, &sa
.sa
, salen
);
1253 JimAioSetError(interp
, argv
[2]);
1260 case SOCK_STREAM_SERVER
:
1261 case SOCK_DGRAM_SERVER
:
1263 union sockaddr_any sa
;
1271 if (JimParseIPv6Address(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1275 else if (JimParseIpAddress(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1278 sock
= socket(family
, (socktype
== SOCK_DGRAM_SERVER
) ? SOCK_DGRAM
: SOCK_STREAM
, 0);
1280 JimAioSetError(interp
, NULL
);
1284 /* Enable address reuse */
1285 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&on
, sizeof(on
));
1287 res
= bind(sock
, &sa
.sa
, salen
);
1289 JimAioSetError(interp
, argv
[2]);
1293 if (socktype
== SOCK_STREAM_SERVER
) {
1294 res
= listen(sock
, 5);
1296 JimAioSetError(interp
, NULL
);
1301 hdlfmt
= "aio.socksrv%ld";
1305 #ifdef HAVE_SYS_UN_H
1308 struct sockaddr_un sa
;
1311 if (argc
!= 3 || ipv6
) {
1315 if (JimParseDomainAddress(interp
, hostportarg
, &sa
) != JIM_OK
) {
1316 JimAioSetError(interp
, argv
[2]);
1320 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
1322 JimAioSetError(interp
, NULL
);
1325 len
= strlen(sa
.sun_path
) + 1 + sizeof(sa
.sun_family
);
1326 res
= connect(sock
, (struct sockaddr
*)&sa
, len
);
1328 JimAioSetError(interp
, argv
[2]);
1332 hdlfmt
= "aio.sockunix%ld";
1336 case SOCK_UNIX_SERVER
:
1338 struct sockaddr_un sa
;
1341 if (argc
!= 3 || ipv6
) {
1345 if (JimParseDomainAddress(interp
, hostportarg
, &sa
) != JIM_OK
) {
1346 JimAioSetError(interp
, argv
[2]);
1350 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
1352 JimAioSetError(interp
, NULL
);
1355 len
= strlen(sa
.sun_path
) + 1 + sizeof(sa
.sun_family
);
1356 res
= bind(sock
, (struct sockaddr
*)&sa
, len
);
1358 JimAioSetError(interp
, argv
[2]);
1362 res
= listen(sock
, 5);
1364 JimAioSetError(interp
, NULL
);
1368 hdlfmt
= "aio.sockunixsrv%ld";
1373 #if defined(HAVE_SOCKETPAIR) && defined(HAVE_SYS_UN_H)
1374 case SOCK_STREAM_SOCKETPAIR
:
1377 static const char *mode
[2] = { "r+", "r+" };
1379 if (argc
!= 2 || ipv6
) {
1383 if (socketpair(PF_UNIX
, SOCK_STREAM
, 0, p
) < 0) {
1384 JimAioSetError(interp
, NULL
);
1387 return JimMakeChannelPair(interp
, p
, argv
[1], "aio.sockpair%ld", PF_UNIX
, mode
);
1392 #if defined(HAVE_PIPE)
1393 case SOCK_STREAM_PIPE
:
1396 static const char *mode
[2] = { "r", "w" };
1398 if (argc
!= 2 || ipv6
) {
1403 JimAioSetError(interp
, NULL
);
1407 return JimMakeChannelPair(interp
, p
, argv
[1], "aio.pipe%ld", 0, mode
);
1413 Jim_SetResultString(interp
, "Unsupported socket type", -1);
1417 return JimMakeChannel(interp
, NULL
, sock
, argv
[1], hdlfmt
, family
, mode
);
1419 #endif /* JIM_BOOTSTRAP */
1421 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*command
)
1423 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, command
, JIM_ERRMSG
);
1425 if (cmdPtr
&& !cmdPtr
->isproc
&& cmdPtr
->u
.native
.cmdProc
== JimAioSubCmdProc
) {
1426 return ((AioFile
*) cmdPtr
->u
.native
.privData
)->fp
;
1428 Jim_SetResultFormatted(interp
, "Not a filehandle: \"%#s\"", command
);
1432 int Jim_aioInit(Jim_Interp
*interp
)
1434 if (Jim_PackageProvide(interp
, "aio", "1.0", JIM_ERRMSG
))
1437 Jim_CreateCommand(interp
, "open", JimAioOpenCommand
, NULL
, NULL
);
1439 Jim_CreateCommand(interp
, "socket", JimAioSockCommand
, NULL
, NULL
);
1442 /* Create filehandles for stdin, stdout and stderr */
1443 JimMakeChannel(interp
, stdin
, -1, NULL
, "stdin", 0, "r");
1444 JimMakeChannel(interp
, stdout
, -1, NULL
, "stdout", 0, "w");
1445 JimMakeChannel(interp
, stderr
, -1, NULL
, "stderr", 0, "w");