1 /* Jim - A small embeddable Tcl interpreter
3 * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
4 * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
5 * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
6 * Copyright 2008 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
7 * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
8 * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
9 * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above
18 * copyright notice, this list of conditions and the following
19 * disclaimer in the documentation and/or other materials
20 * provided with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
23 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
27 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 * The views and conclusions contained in the software and documentation
36 * are those of the authors and should not be interpreted as representing
37 * official policies, either expressed or implied, of the Jim Tcl Project.
40 #include "jimautoconf.h"
54 #if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
55 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
67 #include <openssl/ssl.h>
68 #include <openssl/err.h>
71 #include "jim-eventloop.h"
72 #include "jim-subcmd.h"
74 #define AIO_CMD_LEN 32 /* e.g. aio.handleXXXXXX */
75 #define AIO_BUF_LEN 256 /* Can keep this small and rely on stdio buffering */
84 #define AIO_KEEPOPEN 1
95 #define JimCheckStreamError(interp, af) af->fops->error(af)
97 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
100 struct sockaddr_in sin
;
102 struct sockaddr_in6 sin6
;
106 #ifndef HAVE_INET_NTOP
107 const char *inet_ntop(int af
, const void *src
, char *dst
, int size
)
112 snprintf(dst
, size
, "%s", inet_ntoa(((struct sockaddr_in
*)src
)->sin_addr
));
116 #endif /* JIM_BOOTSTRAP */
121 int (*writer
)(struct AioFile
*af
, const char *buf
, int len
);
122 int (*reader
)(struct AioFile
*af
, char *buf
, int len
);
123 const char *(*getline
)(struct AioFile
*af
, char *buf
, int len
);
124 int (*error
)(const struct AioFile
*af
);
125 const char *(*strerror
)(struct AioFile
*af
);
126 int (*verify
)(struct AioFile
*af
);
129 typedef struct AioFile
134 int openFlags
; /* AIO_KEEPOPEN? keep FILE* */
141 const JimAioFopsType
*fops
;
144 static int stdio_writer(struct AioFile
*af
, const char *buf
, int len
)
146 return fwrite(buf
, 1, len
, af
->fp
);
149 static int stdio_reader(struct AioFile
*af
, char *buf
, int len
)
151 return fread(buf
, 1, len
, af
->fp
);
154 static const char *stdio_getline(struct AioFile
*af
, char *buf
, int len
)
156 return fgets(buf
, len
, af
->fp
);
159 static int stdio_error(const AioFile
*af
)
161 if (!ferror(af
->fp
)) {
165 /* EAGAIN and similar are not error conditions. Just treat them like eof */
166 if (feof(af
->fp
) || errno
== EAGAIN
|| errno
== EINTR
) {
170 if (errno
== ECONNRESET
) {
175 if (errno
!= ECONNABORTED
) {
182 static const char *stdio_strerror(struct AioFile
*af
)
184 return strerror(errno
);
187 static const JimAioFopsType stdio_fops
= {
196 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
198 static SSL_CTX
*JimAioSslCtx(Jim_Interp
*interp
);
200 static int ssl_writer(struct AioFile
*af
, const char *buf
, int len
)
202 return SSL_write(af
->ssl
, buf
, len
);
205 static int ssl_reader(struct AioFile
*af
, char *buf
, int len
)
207 return SSL_read(af
->ssl
, buf
, len
);
210 static const char *ssl_getline(struct AioFile
*af
, char *buf
, int len
)
213 for (i
= 0; i
< len
+ 1; i
++) {
214 if (SSL_read(af
->ssl
, &buf
[i
], 1) != 1) {
220 if (buf
[i
] == '\n') {
228 static int ssl_error(const struct AioFile
*af
)
230 if (ERR_peek_error() == 0) {
237 static const char *ssl_strerror(struct AioFile
*af
)
239 int err
= ERR_get_error();
242 return ERR_error_string(err
, NULL
);
245 /* should not happen */
246 return "unknown SSL error";
249 static int ssl_verify(struct AioFile
*af
)
253 cert
= SSL_get_peer_certificate(af
->ssl
);
259 if (SSL_get_verify_result(af
->ssl
) == X509_V_OK
) {
266 static const JimAioFopsType ssl_fops
= {
274 #endif /* JIM_BOOTSTRAP */
276 static int JimAioSubCmdProc(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
);
277 static AioFile
*JimMakeChannel(Jim_Interp
*interp
, FILE *fh
, int fd
, Jim_Obj
*filename
,
278 const char *hdlfmt
, int family
, const char *mode
);
280 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
281 static int JimParseIPv6Address(Jim_Interp
*interp
, const char *hostport
, union sockaddr_any
*sa
, int *salen
)
285 * An IPv6 addr/port looks like:
288 * [fe80::223:6cff:fe95:bdc0%en1]:2000
292 * Note that the "any" address is ::, which is the same as when no address is specified.
300 stport
= strrchr(hostport
, ':');
302 /* No : so, the whole thing is the port */
305 sthost
= Jim_StrDup(hostport
);
311 if (*hostport
== '[') {
312 /* This is a numeric ipv6 address */
313 char *pt
= strchr(++hostport
, ']');
315 sthost
= Jim_StrDupLen(hostport
, pt
- hostport
);
320 sthost
= Jim_StrDupLen(hostport
, stport
- hostport
- 1);
323 memset(&req
, '\0', sizeof(req
));
324 req
.ai_family
= PF_INET6
;
326 if (getaddrinfo(sthost
, NULL
, &req
, &ai
)) {
327 Jim_SetResultFormatted(interp
, "Not a valid address: %s", hostport
);
331 memcpy(&sa
->sin
, ai
->ai_addr
, ai
->ai_addrlen
);
332 *salen
= ai
->ai_addrlen
;
334 sa
->sin
.sin_port
= htons(atoi(stport
));
342 Jim_SetResultString(interp
, "ipv6 not supported", -1);
347 static int JimParseIpAddress(Jim_Interp
*interp
, const char *hostport
, union sockaddr_any
*sa
, int *salen
)
349 /* An IPv4 addr/port looks like:
354 * If the address is missing, INADDR_ANY is used.
355 * If the port is missing, 0 is used (only useful for server sockets).
361 stport
= strrchr(hostport
, ':');
363 /* No : so, the whole thing is the port */
365 sthost
= Jim_StrDup("0.0.0.0");
368 sthost
= Jim_StrDupLen(hostport
, stport
- hostport
);
373 #ifdef HAVE_GETADDRINFO
376 memset(&req
, '\0', sizeof(req
));
377 req
.ai_family
= PF_INET
;
379 if (getaddrinfo(sthost
, NULL
, &req
, &ai
)) {
383 memcpy(&sa
->sin
, ai
->ai_addr
, ai
->ai_addrlen
);
384 *salen
= ai
->ai_addrlen
;
392 if ((he
= gethostbyname(sthost
)) != NULL
) {
393 if (he
->h_length
== sizeof(sa
->sin
.sin_addr
)) {
394 *salen
= sizeof(sa
->sin
);
395 sa
->sin
.sin_family
= he
->h_addrtype
;
396 memcpy(&sa
->sin
.sin_addr
, he
->h_addr
, he
->h_length
); /* set address */
402 sa
->sin
.sin_port
= htons(atoi(stport
));
407 Jim_SetResultFormatted(interp
, "Not a valid address: %s", hostport
);
414 static int JimParseDomainAddress(Jim_Interp
*interp
, const char *path
, struct sockaddr_un
*sa
)
416 sa
->sun_family
= PF_UNIX
;
417 snprintf(sa
->sun_path
, sizeof(sa
->sun_path
), "%s", path
);
424 * Format that address in 'sa' as a string and store in variable 'varObjPtr'
426 static int JimFormatIpAddress(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
, const union sockaddr_any
*sa
)
428 /* INET6_ADDRSTRLEN is 46. Add some for [] and port */
432 if (sa
->sa
.sa_family
== PF_INET6
) {
434 /* Allow 9 for []:65535\0 */
435 inet_ntop(sa
->sa
.sa_family
, &sa
->sin6
.sin6_addr
, addrbuf
+ 1, sizeof(addrbuf
) - 9);
436 snprintf(addrbuf
+ strlen(addrbuf
), 8, "]:%d", ntohs(sa
->sin
.sin_port
));
440 if (sa
->sa
.sa_family
== PF_INET
) {
441 /* Allow 7 for :65535\0 */
442 inet_ntop(sa
->sa
.sa_family
, &sa
->sin
.sin_addr
, addrbuf
, sizeof(addrbuf
) - 7);
443 snprintf(addrbuf
+ strlen(addrbuf
), 7, ":%d", ntohs(sa
->sin
.sin_port
));
446 /* recvfrom still works on unix domain sockets, etc */
450 return Jim_SetVariable(interp
, varObjPtr
, Jim_NewStringObj(interp
, addrbuf
, -1));
453 #endif /* JIM_BOOTSTRAP */
455 static const char *JimAioErrorString(AioFile
*af
)
458 return af
->fops
->strerror(af
);
460 return strerror(errno
);
463 static void JimAioSetError(Jim_Interp
*interp
, Jim_Obj
*name
)
465 AioFile
*af
= Jim_CmdPrivData(interp
);
468 Jim_SetResultFormatted(interp
, "%#s: %s", name
, JimAioErrorString(af
));
471 Jim_SetResultString(interp
, JimAioErrorString(af
), -1);
475 static void JimAioDelProc(Jim_Interp
*interp
, void *privData
)
477 AioFile
*af
= privData
;
481 Jim_DecrRefCount(interp
, af
->filename
);
483 #ifdef jim_ext_eventloop
484 /* remove all existing EventHandlers */
485 Jim_DeleteFileHandler(interp
, af
->fd
, JIM_EVENT_READABLE
| JIM_EVENT_WRITABLE
| JIM_EVENT_EXCEPTION
);
489 if (af
->ssl
!= NULL
) {
494 if (!(af
->openFlags
& AIO_KEEPOPEN
)) {
501 static int aio_cmd_read(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
503 AioFile
*af
= Jim_CmdPrivData(interp
);
504 char buf
[AIO_BUF_LEN
];
507 jim_wide neededLen
= -1; /* -1 is "read as much as possible" */
509 if (argc
&& Jim_CompareStringImmediate(interp
, argv
[0], "-nonewline")) {
515 if (Jim_GetWide(interp
, argv
[0], &neededLen
) != JIM_OK
)
518 Jim_SetResultString(interp
, "invalid parameter: negative len", -1);
525 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
526 while (neededLen
!= 0) {
530 if (neededLen
== -1) {
531 readlen
= AIO_BUF_LEN
;
534 readlen
= (neededLen
> AIO_BUF_LEN
? AIO_BUF_LEN
: neededLen
);
536 retval
= af
->fops
->reader(af
, buf
, readlen
);
538 Jim_AppendString(interp
, objPtr
, buf
, retval
);
539 if (neededLen
!= -1) {
543 if (retval
!= readlen
)
546 /* Check for error conditions */
547 if (JimCheckStreamError(interp
, af
)) {
548 Jim_FreeNewObj(interp
, objPtr
);
553 const char *s
= Jim_GetString(objPtr
, &len
);
555 if (len
> 0 && s
[len
- 1] == '\n') {
557 objPtr
->bytes
[objPtr
->length
] = '\0';
560 Jim_SetResult(interp
, objPtr
);
564 AioFile
*Jim_AioFile(Jim_Interp
*interp
, Jim_Obj
*command
)
566 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, command
, JIM_ERRMSG
);
568 /* XXX: There ought to be a supported API for this */
569 if (cmdPtr
&& !cmdPtr
->isproc
&& cmdPtr
->u
.native
.cmdProc
== JimAioSubCmdProc
) {
570 return (AioFile
*) cmdPtr
->u
.native
.privData
;
572 Jim_SetResultFormatted(interp
, "Not a filehandle: \"%#s\"", command
);
576 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*command
)
580 af
= Jim_AioFile(interp
, command
);
588 static int aio_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
590 AioFile
*af
= Jim_CmdPrivData(interp
);
592 jim_wide maxlen
= JIM_WIDE_MAX
;
593 AioFile
*outf
= Jim_AioFile(interp
, argv
[0]);
600 if (Jim_GetWide(interp
, argv
[1], &maxlen
) != JIM_OK
) {
605 while (count
< maxlen
) {
608 if (af
->fops
->reader(af
, &ch
, 1) != 1) {
611 if (outf
->fops
->writer(outf
, &ch
, 1) != 1) {
617 if (JimCheckStreamError(interp
, af
) || JimCheckStreamError(interp
, outf
)) {
621 Jim_SetResultInt(interp
, count
);
626 static int aio_cmd_gets(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
628 AioFile
*af
= Jim_CmdPrivData(interp
);
629 char buf
[AIO_BUF_LEN
];
635 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
637 buf
[AIO_BUF_LEN
- 1] = '_';
639 if (af
->fops
->getline(af
, buf
, AIO_BUF_LEN
) == NULL
)
642 if (buf
[AIO_BUF_LEN
- 1] == '\0' && buf
[AIO_BUF_LEN
- 2] != '\n') {
643 Jim_AppendString(interp
, objPtr
, buf
, AIO_BUF_LEN
- 1);
648 if (len
&& (buf
[len
- 1] == '\n')) {
653 Jim_AppendString(interp
, objPtr
, buf
, len
);
658 if (JimCheckStreamError(interp
, af
)) {
660 Jim_FreeNewObj(interp
, objPtr
);
665 if (Jim_SetVariable(interp
, argv
[0], objPtr
) != JIM_OK
) {
666 Jim_FreeNewObj(interp
, objPtr
);
670 len
= Jim_Length(objPtr
);
672 if (len
== 0 && feof(af
->fp
)) {
673 /* On EOF returns -1 if varName was specified */
676 Jim_SetResultInt(interp
, len
);
679 Jim_SetResult(interp
, objPtr
);
684 static int aio_cmd_puts(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
686 AioFile
*af
= Jim_CmdPrivData(interp
);
692 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-nonewline")) {
701 wdata
= Jim_GetString(strObj
, &wlen
);
702 if (af
->fops
->writer(af
, wdata
, wlen
) == wlen
) {
703 if (argc
== 2 || af
->fops
->writer(af
, "\n", 1) == 1) {
707 JimAioSetError(interp
, af
->filename
);
711 static int aio_cmd_isatty(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
714 AioFile
*af
= Jim_CmdPrivData(interp
);
715 Jim_SetResultInt(interp
, isatty(fileno(af
->fp
)));
717 Jim_SetResultInt(interp
, 0);
723 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
724 static int aio_cmd_recvfrom(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
726 AioFile
*af
= Jim_CmdPrivData(interp
);
728 union sockaddr_any sa
;
730 socklen_t salen
= sizeof(sa
);
733 if (Jim_GetLong(interp
, argv
[0], &len
) != JIM_OK
) {
737 buf
= Jim_Alloc(len
+ 1);
739 rlen
= recvfrom(fileno(af
->fp
), buf
, len
, 0, &sa
.sa
, &salen
);
742 JimAioSetError(interp
, NULL
);
746 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, rlen
));
749 return JimFormatIpAddress(interp
, argv
[1], &sa
);
756 static int aio_cmd_sendto(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
758 AioFile
*af
= Jim_CmdPrivData(interp
);
762 union sockaddr_any sa
;
763 const char *addr
= Jim_String(argv
[1]);
766 if (IPV6
&& af
->addr_family
== PF_INET6
) {
767 if (JimParseIPv6Address(interp
, addr
, &sa
, &salen
) != JIM_OK
) {
771 else if (JimParseIpAddress(interp
, addr
, &sa
, &salen
) != JIM_OK
) {
774 wdata
= Jim_GetString(argv
[0], &wlen
);
776 /* Note that we don't validate the socket type. Rely on sendto() failing if appropriate */
777 len
= sendto(fileno(af
->fp
), wdata
, wlen
, 0, &sa
.sa
, salen
);
779 JimAioSetError(interp
, NULL
);
782 Jim_SetResultInt(interp
, len
);
786 static int aio_cmd_accept(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
788 AioFile
*af
= Jim_CmdPrivData(interp
);
790 union sockaddr_any sa
;
791 socklen_t addrlen
= sizeof(sa
);
793 sock
= accept(af
->fd
, &sa
.sa
, &addrlen
);
795 JimAioSetError(interp
, NULL
);
800 if (JimFormatIpAddress(interp
, argv
[0], &sa
) != JIM_OK
) {
805 /* Create the file command */
806 return JimMakeChannel(interp
, NULL
, sock
, Jim_NewStringObj(interp
, "accept", -1),
807 "aio.sockstream%ld", af
->addr_family
, "r+") ? JIM_OK
: JIM_ERR
;
810 static int aio_cmd_listen(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
812 AioFile
*af
= Jim_CmdPrivData(interp
);
815 if (Jim_GetLong(interp
, argv
[0], &backlog
) != JIM_OK
) {
819 if (listen(af
->fd
, backlog
)) {
820 JimAioSetError(interp
, NULL
);
826 #endif /* JIM_BOOTSTRAP */
828 static int aio_cmd_flush(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
830 AioFile
*af
= Jim_CmdPrivData(interp
);
832 if (fflush(af
->fp
) == EOF
) {
833 JimAioSetError(interp
, af
->filename
);
839 static int aio_cmd_eof(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
841 AioFile
*af
= Jim_CmdPrivData(interp
);
843 Jim_SetResultInt(interp
, feof(af
->fp
));
847 static int aio_cmd_close(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
850 #if !defined(JIM_ANSIC) && defined(HAVE_SHUTDOWN)
851 static const char * const options
[] = { "r", "w", NULL
};
852 enum { OPT_R
, OPT_W
, };
854 AioFile
*af
= Jim_CmdPrivData(interp
);
856 if (Jim_GetEnum(interp
, argv
[2], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
859 if (shutdown(af
->fd
, option
== OPT_R
? SHUT_RD
: SHUT_WR
) == 0) {
862 JimAioSetError(interp
, NULL
);
864 Jim_SetResultString(interp
, "async close not supported", -1);
869 return Jim_DeleteCommand(interp
, Jim_String(argv
[0]));
872 static int aio_cmd_seek(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
874 AioFile
*af
= Jim_CmdPrivData(interp
);
879 if (Jim_CompareStringImmediate(interp
, argv
[1], "start"))
881 else if (Jim_CompareStringImmediate(interp
, argv
[1], "current"))
883 else if (Jim_CompareStringImmediate(interp
, argv
[1], "end"))
889 if (Jim_GetWide(interp
, argv
[0], &offset
) != JIM_OK
) {
892 if (fseeko(af
->fp
, offset
, orig
) == -1) {
893 JimAioSetError(interp
, af
->filename
);
899 static int aio_cmd_tell(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
901 AioFile
*af
= Jim_CmdPrivData(interp
);
903 Jim_SetResultInt(interp
, ftello(af
->fp
));
907 static int aio_cmd_filename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
909 AioFile
*af
= Jim_CmdPrivData(interp
);
911 Jim_SetResult(interp
, af
->filename
);
916 static int aio_cmd_ndelay(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
918 AioFile
*af
= Jim_CmdPrivData(interp
);
920 int fmode
= fcntl(af
->fd
, F_GETFL
);
925 if (Jim_GetLong(interp
, argv
[0], &nb
) != JIM_OK
) {
934 (void)fcntl(af
->fd
, F_SETFL
, fmode
);
936 Jim_SetResultInt(interp
, (fmode
& O_NONBLOCK
) ? 1 : 0);
942 static int aio_cmd_sync(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
944 AioFile
*af
= Jim_CmdPrivData(interp
);
952 static int aio_cmd_buffering(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
954 AioFile
*af
= Jim_CmdPrivData(interp
);
956 static const char * const options
[] = {
970 if (Jim_GetEnum(interp
, argv
[0], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
975 setvbuf(af
->fp
, NULL
, _IONBF
, 0);
978 setvbuf(af
->fp
, NULL
, _IOLBF
, BUFSIZ
);
981 setvbuf(af
->fp
, NULL
, _IOFBF
, BUFSIZ
);
987 #ifdef jim_ext_eventloop
988 static void JimAioFileEventFinalizer(Jim_Interp
*interp
, void *clientData
)
990 Jim_Obj
**objPtrPtr
= clientData
;
992 Jim_DecrRefCount(interp
, *objPtrPtr
);
996 static int JimAioFileEventHandler(Jim_Interp
*interp
, void *clientData
, int mask
)
998 Jim_Obj
**objPtrPtr
= clientData
;
1000 return Jim_EvalObjBackground(interp
, *objPtrPtr
);
1003 static int aio_eventinfo(Jim_Interp
*interp
, AioFile
* af
, unsigned mask
, Jim_Obj
**scriptHandlerObj
,
1004 int argc
, Jim_Obj
* const *argv
)
1007 /* Return current script */
1008 if (*scriptHandlerObj
) {
1009 Jim_SetResult(interp
, *scriptHandlerObj
);
1014 if (*scriptHandlerObj
) {
1015 /* Delete old handler */
1016 Jim_DeleteFileHandler(interp
, af
->fd
, mask
);
1019 /* Now possibly add the new script(s) */
1020 if (Jim_Length(argv
[0]) == 0) {
1021 /* Empty script, so done */
1025 /* A new script to add */
1026 Jim_IncrRefCount(argv
[0]);
1027 *scriptHandlerObj
= argv
[0];
1029 Jim_CreateFileHandler(interp
, af
->fd
, mask
,
1030 JimAioFileEventHandler
, scriptHandlerObj
, JimAioFileEventFinalizer
);
1035 static int aio_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1037 AioFile
*af
= Jim_CmdPrivData(interp
);
1039 return aio_eventinfo(interp
, af
, JIM_EVENT_READABLE
, &af
->rEvent
, argc
, argv
);
1042 static int aio_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1044 AioFile
*af
= Jim_CmdPrivData(interp
);
1046 return aio_eventinfo(interp
, af
, JIM_EVENT_WRITABLE
, &af
->wEvent
, argc
, argv
);
1049 static int aio_cmd_onexception(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1051 AioFile
*af
= Jim_CmdPrivData(interp
);
1053 return aio_eventinfo(interp
, af
, JIM_EVENT_EXCEPTION
, &af
->eEvent
, argc
, argv
);
1057 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
1058 static int aio_cmd_ssl(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1060 AioFile
*af
= Jim_CmdPrivData(interp
);
1066 if (!Jim_CompareStringImmediate(interp
, argv
[2], "-server")) {
1071 else if (argc
!= 2) {
1072 Jim_WrongNumArgs(interp
, 2, argv
, "?-server cert priv?");
1076 fd
= fileno(af
->fp
);
1077 #if defined(HAVE_DUP)
1083 ssl_ctx
= JimAioSslCtx(interp
);
1084 if (ssl_ctx
== NULL
) {
1088 ssl
= SSL_new(ssl_ctx
);
1090 #if defined(HAVE_DUP)
1093 Jim_SetResultString(interp
, ERR_error_string(ERR_get_error(), NULL
), -1);
1097 SSL_set_cipher_list(ssl
, "ALL");
1099 if (SSL_set_fd(ssl
, fileno(af
->fp
)) == 0) {
1104 if (SSL_use_certificate_file(ssl
, Jim_String(argv
[3]), SSL_FILETYPE_PEM
) != 1) {
1108 if (SSL_use_PrivateKey_file(ssl
, Jim_String(argv
[4]), SSL_FILETYPE_PEM
) != 1) {
1112 if (SSL_accept(ssl
) != 1) {
1117 if (SSL_connect(ssl
) != 1) {
1122 af
= JimMakeChannel(interp
, NULL
, fd
, NULL
, "aio.sslstream%ld", af
->addr_family
, "r+");
1128 af
->fops
= &ssl_fops
;
1133 #if defined(HAVE_DUP)
1137 Jim_SetResultString(interp
, ERR_error_string(ERR_get_error(), NULL
), -1);
1141 static int aio_cmd_verify(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1143 AioFile
*af
= Jim_CmdPrivData(interp
);
1146 if (!af
->fops
->verify
) {
1150 ret
= af
->fops
->verify(af
);
1151 if (ret
!= JIM_OK
) {
1152 if (JimCheckStreamError(interp
, af
)) {
1153 JimAioSetError(interp
, af
->filename
);
1155 Jim_SetResultString(interp
, "failed to verify the connection authenticity", -1);
1160 #endif /* JIM_BOOTSTRAP */
1162 #if defined(HAVE_STRUCT_FLOCK) && !defined(JIM_BOOTSTRAP)
1163 static int aio_cmd_lock(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1165 AioFile
*af
= Jim_CmdPrivData(interp
);
1170 fl
.l_type
= F_WRLCK
;
1171 fl
.l_whence
= SEEK_SET
;
1173 switch (fcntl(af
->fd
, F_SETLK
, &fl
))
1176 Jim_SetResultInt(interp
, 1);
1179 if (errno
== EACCES
|| errno
== EAGAIN
)
1180 Jim_SetResultInt(interp
, 0);
1183 Jim_SetResultFormatted(interp
, "lock failed: %s",
1189 Jim_SetResultInt(interp
, 0);
1196 static int aio_cmd_unlock(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1198 AioFile
*af
= Jim_CmdPrivData(interp
);
1202 fl
.l_type
= F_UNLCK
;
1203 fl
.l_whence
= SEEK_SET
;
1205 Jim_SetResultInt(interp
, fcntl(af
->fd
, F_SETLK
, &fl
) == 0);
1208 #endif /* JIM_BOOTSTRAP */
1210 static const jim_subcmd_type aio_command_table
[] = {
1212 "?-nonewline? ?len?",
1216 /* Description: Read and return bytes from the stream. To eof if no len. */
1223 /* Description: Copy up to 'size' bytes to the given filehandle, or to eof if no size. */
1230 /* Description: Read one line and return it or store it in the var */
1237 /* Description: Write the string, with newline unless -nonewline */
1244 /* Description: Is the file descriptor a tty? */
1246 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
1252 /* Description: Receive up to 'len' bytes on the socket. Sets 'addrvar' with receive address, if set */
1259 /* Description: Send 'str' to the given address (dgram only) */
1266 /* Description: Server socket only: Accept a connection and return stream */
1273 /* Description: Set the listen backlog for server socket */
1275 #endif /* JIM_BOOTSTRAP */
1281 /* Description: Flush the stream */
1288 /* Description: Returns 1 if stream is at eof */
1295 JIM_MODFLAG_FULLARGV
,
1296 /* Description: Closes the stream. */
1299 "offset ?start|current|end",
1303 /* Description: Seeks in the stream (default 'current') */
1310 /* Description: Returns the current seek position */
1317 /* Description: Returns the original filename */
1325 /* Description: Set O_NDELAY (if arg). Returns current/new setting. */
1334 /* Description: Flush and fsync() the stream */
1342 /* Description: Sets buffering */
1344 #ifdef jim_ext_eventloop
1346 "?readable-script?",
1350 /* Description: Returns script, or invoke readable-script when readable, {} to remove */
1353 "?writable-script?",
1357 /* Description: Returns script, or invoke writable-script when writable, {} to remove */
1360 "?exception-script?",
1361 aio_cmd_onexception
,
1364 /* Description: Returns script, or invoke exception-script when oob data, {} to remove */
1367 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
1369 "?-server cert priv?",
1373 JIM_MODFLAG_FULLARGV
1374 /* Description: Wraps a stream socket with SSL/TLS and returns a new channel */
1381 /* Description: Verifies the certificate of a SSL/TLS channel */
1383 #endif /* JIM_BOOTSTRAP */
1384 #if defined(HAVE_STRUCT_FLOCK) && !defined(JIM_BOOTSTRAP)
1390 /* Description: Attempt to get a lock. */
1397 /* Description: Relase a lock. */
1399 #endif /* JIM_BOOTSTRAP */
1403 static int JimAioSubCmdProc(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1405 return Jim_CallSubCmd(interp
, Jim_ParseSubCmd(interp
, aio_command_table
, argc
, argv
), argc
, argv
);
1408 static int JimAioOpenCommand(Jim_Interp
*interp
, int argc
,
1409 Jim_Obj
*const *argv
)
1413 if (argc
!= 2 && argc
!= 3) {
1414 Jim_WrongNumArgs(interp
, 1, argv
, "filename ?mode?");
1418 mode
= (argc
== 3) ? Jim_String(argv
[2]) : "r";
1420 #ifdef jim_ext_tclcompat
1422 const char *filename
= Jim_String(argv
[1]);
1424 /* If the filename starts with '|', use popen instead */
1425 if (*filename
== '|') {
1426 Jim_Obj
*evalObj
[3];
1428 evalObj
[0] = Jim_NewStringObj(interp
, "::popen", -1);
1429 evalObj
[1] = Jim_NewStringObj(interp
, filename
+ 1, -1);
1430 evalObj
[2] = Jim_NewStringObj(interp
, mode
, -1);
1432 return Jim_EvalObjVector(interp
, 3, evalObj
);
1436 return JimMakeChannel(interp
, NULL
, -1, argv
[1], "aio.handle%ld", 0, mode
) ? JIM_OK
: JIM_ERR
;
1439 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
1440 static void JimAioSslContextDelProc(struct Jim_Interp
*interp
, void *privData
)
1442 SSL_CTX_free((SSL_CTX
*)privData
);
1446 static SSL_CTX
*JimAioSslCtx(Jim_Interp
*interp
)
1448 SSL_CTX
*ssl_ctx
= (SSL_CTX
*)Jim_GetAssocData(interp
, "ssl_ctx");
1449 if (ssl_ctx
== NULL
) {
1450 SSL_load_error_strings();
1452 ssl_ctx
= SSL_CTX_new(TLSv1_2_method());
1453 if (ssl_ctx
&& SSL_CTX_set_default_verify_paths(ssl_ctx
)) {
1454 SSL_CTX_set_verify(ssl_ctx
, SSL_VERIFY_NONE
, NULL
);
1455 Jim_SetAssocData(interp
, "ssl_ctx", JimAioSslContextDelProc
, ssl_ctx
);
1457 Jim_SetResultString(interp
, ERR_error_string(ERR_get_error(), NULL
), -1);
1462 #endif /* JIM_BOOTSTRAP */
1465 * Creates a channel for fh/fd/filename.
1467 * If fh is not NULL, uses that as the channel (and sets AIO_KEEPOPEN).
1468 * Otherwise, if fd is >= 0, uses that as the channel.
1469 * Otherwise opens 'filename' with mode 'mode'.
1471 * hdlfmt is a sprintf format for the filehandle. Anything with %ld at the end will do.
1472 * mode is used for open or fdopen.
1474 * Creates the command and sets the name as the current result.
1475 * Returns the AioFile pointer on sucess or NULL on failure.
1477 static AioFile
*JimMakeChannel(Jim_Interp
*interp
, FILE *fh
, int fd
, Jim_Obj
*filename
,
1478 const char *hdlfmt
, int family
, const char *mode
)
1481 char buf
[AIO_CMD_LEN
];
1484 snprintf(buf
, sizeof(buf
), hdlfmt
, Jim_GetId(interp
));
1487 openFlags
= AIO_KEEPOPEN
;
1490 snprintf(buf
, sizeof(buf
), hdlfmt
, Jim_GetId(interp
));
1492 filename
= Jim_NewStringObj(interp
, buf
, -1);
1495 Jim_IncrRefCount(filename
);
1498 #if !defined(JIM_ANSIC)
1500 fh
= fdopen(fd
, mode
);
1504 fh
= fopen(Jim_String(filename
), mode
);
1507 JimAioSetError(interp
, filename
);
1508 #if !defined(JIM_ANSIC)
1513 Jim_DecrRefCount(interp
, filename
);
1518 /* Create the file command */
1519 af
= Jim_Alloc(sizeof(*af
));
1520 memset(af
, 0, sizeof(*af
));
1522 af
->fd
= fileno(fh
);
1523 af
->filename
= filename
;
1525 if ((openFlags
& AIO_KEEPOPEN
) == 0) {
1526 (void)fcntl(af
->fd
, F_SETFD
, FD_CLOEXEC
);
1529 af
->openFlags
= openFlags
;
1530 af
->addr_family
= family
;
1531 af
->fops
= &stdio_fops
;
1534 Jim_CreateCommand(interp
, buf
, JimAioSubCmdProc
, af
, JimAioDelProc
);
1536 /* Note that the command must use the global namespace, even if
1537 * the current namespace is something different
1539 Jim_SetResult(interp
, Jim_MakeGlobalNamespaceName(interp
, Jim_NewStringObj(interp
, buf
, -1)));
1544 #if defined(HAVE_PIPE) || (defined(HAVE_SOCKETPAIR) && defined(HAVE_SYS_UN_H))
1546 * Create a pair of channels. e.g. from pipe() or socketpair()
1548 static int JimMakeChannelPair(Jim_Interp
*interp
, int p
[2], Jim_Obj
*filename
,
1549 const char *hdlfmt
, int family
, const char *mode
[2])
1551 if (JimMakeChannel(interp
, NULL
, p
[0], filename
, hdlfmt
, family
, mode
[0])) {
1552 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
1553 Jim_ListAppendElement(interp
, objPtr
, Jim_GetResult(interp
));
1555 if (JimMakeChannel(interp
, NULL
, p
[1], filename
, hdlfmt
, family
, mode
[1])) {
1556 Jim_ListAppendElement(interp
, objPtr
, Jim_GetResult(interp
));
1557 Jim_SetResult(interp
, objPtr
);
1562 /* Can only be here if fdopen() failed */
1565 JimAioSetError(interp
, NULL
);
1570 #if !defined(JIM_ANSIC) && !defined(JIM_BOOTSTRAP)
1572 static int JimAioSockCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1574 const char *hdlfmt
= "aio.unknown%ld";
1575 const char *socktypes
[] = {
1595 SOCK_STREAM_SOCKETPAIR
,
1599 const char *hostportarg
= NULL
;
1602 const char *mode
= "r+";
1603 int family
= PF_INET
;
1604 Jim_Obj
*argv0
= argv
[0];
1607 if (argc
> 1 && Jim_CompareStringImmediate(interp
, argv
[1], "-ipv6")) {
1609 Jim_SetResultString(interp
, "ipv6 not supported", -1);
1620 Jim_WrongNumArgs(interp
, 1, &argv0
, "?-ipv6? type ?address?");
1624 if (Jim_GetEnum(interp
, argv
[1], socktypes
, &socktype
, "socket type", JIM_ERRMSG
) != JIM_OK
)
1627 Jim_SetEmptyResult(interp
);
1629 hdlfmt
= "aio.sock%ld";
1632 hostportarg
= Jim_String(argv
[2]);
1636 case SOCK_DGRAM_CLIENT
:
1638 /* No address, so an unconnected dgram socket */
1639 sock
= socket(family
, SOCK_DGRAM
, 0);
1641 JimAioSetError(interp
, NULL
);
1647 case SOCK_STREAM_CLIENT
:
1649 union sockaddr_any sa
;
1657 if (JimParseIPv6Address(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1661 else if (JimParseIpAddress(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1664 sock
= socket(family
, (socktype
== SOCK_DGRAM_CLIENT
) ? SOCK_DGRAM
: SOCK_STREAM
, 0);
1666 JimAioSetError(interp
, NULL
);
1669 res
= connect(sock
, &sa
.sa
, salen
);
1671 JimAioSetError(interp
, argv
[2]);
1678 case SOCK_STREAM_SERVER
:
1679 case SOCK_DGRAM_SERVER
:
1681 union sockaddr_any sa
;
1689 if (JimParseIPv6Address(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1693 else if (JimParseIpAddress(interp
, hostportarg
, &sa
, &salen
) != JIM_OK
) {
1696 sock
= socket(family
, (socktype
== SOCK_DGRAM_SERVER
) ? SOCK_DGRAM
: SOCK_STREAM
, 0);
1698 JimAioSetError(interp
, NULL
);
1702 /* Enable address reuse */
1703 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&on
, sizeof(on
));
1705 res
= bind(sock
, &sa
.sa
, salen
);
1707 JimAioSetError(interp
, argv
[2]);
1711 if (socktype
== SOCK_STREAM_SERVER
) {
1712 res
= listen(sock
, 5);
1714 JimAioSetError(interp
, NULL
);
1719 hdlfmt
= "aio.socksrv%ld";
1723 #ifdef HAVE_SYS_UN_H
1726 struct sockaddr_un sa
;
1729 if (argc
!= 3 || ipv6
) {
1733 if (JimParseDomainAddress(interp
, hostportarg
, &sa
) != JIM_OK
) {
1734 JimAioSetError(interp
, argv
[2]);
1738 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
1740 JimAioSetError(interp
, NULL
);
1743 len
= strlen(sa
.sun_path
) + 1 + sizeof(sa
.sun_family
);
1744 res
= connect(sock
, (struct sockaddr
*)&sa
, len
);
1746 JimAioSetError(interp
, argv
[2]);
1750 hdlfmt
= "aio.sockunix%ld";
1754 case SOCK_UNIX_SERVER
:
1756 struct sockaddr_un sa
;
1759 if (argc
!= 3 || ipv6
) {
1763 if (JimParseDomainAddress(interp
, hostportarg
, &sa
) != JIM_OK
) {
1764 JimAioSetError(interp
, argv
[2]);
1768 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
1770 JimAioSetError(interp
, NULL
);
1773 len
= strlen(sa
.sun_path
) + 1 + sizeof(sa
.sun_family
);
1774 res
= bind(sock
, (struct sockaddr
*)&sa
, len
);
1776 JimAioSetError(interp
, argv
[2]);
1780 res
= listen(sock
, 5);
1782 JimAioSetError(interp
, NULL
);
1786 hdlfmt
= "aio.sockunixsrv%ld";
1791 #if defined(HAVE_SOCKETPAIR) && defined(HAVE_SYS_UN_H)
1792 case SOCK_STREAM_SOCKETPAIR
:
1795 static const char *mode
[2] = { "r+", "r+" };
1797 if (argc
!= 2 || ipv6
) {
1801 if (socketpair(PF_UNIX
, SOCK_STREAM
, 0, p
) < 0) {
1802 JimAioSetError(interp
, NULL
);
1805 return JimMakeChannelPair(interp
, p
, argv
[1], "aio.sockpair%ld", PF_UNIX
, mode
);
1810 #if defined(HAVE_PIPE)
1811 case SOCK_STREAM_PIPE
:
1814 static const char *mode
[2] = { "r", "w" };
1816 if (argc
!= 2 || ipv6
) {
1821 JimAioSetError(interp
, NULL
);
1825 return JimMakeChannelPair(interp
, p
, argv
[1], "aio.pipe%ld", 0, mode
);
1831 Jim_SetResultString(interp
, "Unsupported socket type", -1);
1835 return JimMakeChannel(interp
, NULL
, sock
, argv
[1], hdlfmt
, family
, mode
) ? JIM_OK
: JIM_ERR
;
1837 #endif /* JIM_BOOTSTRAP */
1840 * Returns the file descriptor of a writable, newly created temp file
1843 * On success, leaves the filename in the interpreter result, otherwise
1844 * leaves an error message.
1846 int Jim_MakeTempFile(Jim_Interp
*interp
, const char *template)
1851 Jim_Obj
*filenameObj
;
1853 if (template == NULL
) {
1854 const char *tmpdir
= getenv("TMPDIR");
1855 if (tmpdir
== NULL
|| *tmpdir
== '\0' || access(tmpdir
, W_OK
) != 0) {
1858 filenameObj
= Jim_NewStringObj(interp
, tmpdir
, -1);
1859 if (tmpdir
[0] && tmpdir
[strlen(tmpdir
) - 1] != '/') {
1860 Jim_AppendString(interp
, filenameObj
, "/", 1);
1862 Jim_AppendString(interp
, filenameObj
, "tcl.tmp.XXXXXX", -1);
1865 filenameObj
= Jim_NewStringObj(interp
, template, -1);
1868 #if defined(S_IRWXG) && defined(S_IRWXO)
1869 mask
= umask(S_IXUSR
| S_IRWXG
| S_IRWXO
);
1871 /* MinGW does not have group/owner permissions */
1872 mask
= umask(S_IXUSR
);
1875 /* Update the template name directly with the filename */
1876 fd
= mkstemp(filenameObj
->bytes
);
1879 JimAioSetError(interp
, filenameObj
);
1880 Jim_FreeNewObj(interp
, filenameObj
);
1884 Jim_SetResult(interp
, filenameObj
);
1887 Jim_SetResultString(interp
, "platform has no tempfile support", -1);
1892 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
1893 static int JimAioLoadSSLCertsCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1898 Jim_WrongNumArgs(interp
, 1, argv
, "dir");
1902 ssl_ctx
= JimAioSslCtx(interp
);
1906 if (SSL_CTX_load_verify_locations(ssl_ctx
, NULL
, Jim_String(argv
[1])) == 1) {
1909 Jim_SetResultString(interp
, ERR_error_string(ERR_get_error(), NULL
), -1);
1912 #endif /* JIM_BOOTSTRAP */
1914 int Jim_aioInit(Jim_Interp
*interp
)
1916 if (Jim_PackageProvide(interp
, "aio", "1.0", JIM_ERRMSG
))
1919 #if defined(JIM_SSL)
1920 Jim_CreateCommand(interp
, "load_ssl_certs", JimAioLoadSSLCertsCommand
, NULL
, NULL
);
1923 Jim_CreateCommand(interp
, "open", JimAioOpenCommand
, NULL
, NULL
);
1925 Jim_CreateCommand(interp
, "socket", JimAioSockCommand
, NULL
, NULL
);
1928 /* Create filehandles for stdin, stdout and stderr */
1929 JimMakeChannel(interp
, stdin
, -1, NULL
, "stdin", 0, "r");
1930 JimMakeChannel(interp
, stdout
, -1, NULL
, "stdout", 0, "w");
1931 JimMakeChannel(interp
, stderr
, -1, NULL
, "stderr", 0, "w");