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"
56 #include "jimiocompat.h"
58 #if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <netinet/tcp.h>
62 #include <arpa/inet.h>
68 #elif defined (__MINGW32__)
69 /* currently mingw32 doesn't support sockets, but has pipe, fdopen */
75 #include <openssl/ssl.h>
76 #include <openssl/err.h>
83 #include "jim-eventloop.h"
84 #include "jim-subcmd.h"
86 #define AIO_CMD_LEN 32 /* e.g. aio.handleXXXXXX */
87 #define AIO_BUF_LEN 256 /* Can keep this small and rely on stdio buffering */
96 #define AIO_KEEPOPEN 1
97 #define AIO_NODELETE 2
107 #if defined(HAVE_SYS_UN_H) && defined(PF_UNIX)
108 #define UNIX_SOCKETS 1
110 #define UNIX_SOCKETS 0
114 /* no fdopen() with ANSIC, so can't support these */
116 #undef HAVE_SOCKETPAIR
119 #if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
120 /* Avoid type punned pointers */
123 struct sockaddr_in sin
;
125 struct sockaddr_in6 sin6
;
128 struct sockaddr_un sun
;
132 #ifndef HAVE_INET_NTOP
133 const char *inet_ntop(int af
, const void *src
, char *dst
, int size
)
138 snprintf(dst
, size
, "%s", inet_ntoa(((struct sockaddr_in
*)src
)->sin_addr
));
142 #endif /* JIM_BOOTSTRAP */
147 int (*writer
)(struct AioFile
*af
, const char *buf
, int len
);
148 int (*reader
)(struct AioFile
*af
, char *buf
, int len
);
149 const char *(*getline
)(struct AioFile
*af
, char *buf
, int len
);
150 int (*error
)(const struct AioFile
*af
);
151 const char *(*strerror
)(struct AioFile
*af
);
152 int (*verify
)(struct AioFile
*af
);
155 typedef struct AioFile
160 int openFlags
; /* AIO_KEEPOPEN? keep FILE* */
167 const JimAioFopsType
*fops
;
170 static int stdio_writer(struct AioFile
*af
, const char *buf
, int len
)
172 return fwrite(buf
, 1, len
, af
->fp
);
175 static int stdio_reader(struct AioFile
*af
, char *buf
, int len
)
177 return fread(buf
, 1, len
, af
->fp
);
180 static const char *stdio_getline(struct AioFile
*af
, char *buf
, int len
)
182 return fgets(buf
, len
, af
->fp
);
185 static int stdio_error(const AioFile
*af
)
187 if (!ferror(af
->fp
)) {
191 /* EAGAIN and similar are not error conditions. Just treat them like eof */
192 if (feof(af
->fp
) || errno
== EAGAIN
|| errno
== EINTR
) {
196 if (errno
== ECONNRESET
) {
201 if (errno
== ECONNABORTED
) {
208 static const char *stdio_strerror(struct AioFile
*af
)
210 return strerror(errno
);
213 static const JimAioFopsType stdio_fops
= {
222 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
224 static SSL_CTX
*JimAioSslCtx(Jim_Interp
*interp
);
226 static int ssl_writer(struct AioFile
*af
, const char *buf
, int len
)
228 return SSL_write(af
->ssl
, buf
, len
);
231 static int ssl_reader(struct AioFile
*af
, char *buf
, int len
)
233 return SSL_read(af
->ssl
, buf
, len
);
236 static const char *ssl_getline(struct AioFile
*af
, char *buf
, int len
)
239 for (i
= 0; i
< len
+ 1; i
++) {
240 if (SSL_read(af
->ssl
, &buf
[i
], 1) != 1) {
246 if (buf
[i
] == '\n') {
254 static int ssl_error(const struct AioFile
*af
)
256 if (ERR_peek_error() == 0) {
263 static const char *ssl_strerror(struct AioFile
*af
)
265 int err
= ERR_get_error();
268 return ERR_error_string(err
, NULL
);
271 return stdio_strerror(af
);
275 static int ssl_verify(struct AioFile
*af
)
279 cert
= SSL_get_peer_certificate(af
->ssl
);
285 if (SSL_get_verify_result(af
->ssl
) == X509_V_OK
) {
292 static const JimAioFopsType ssl_fops
= {
300 #endif /* JIM_BOOTSTRAP */
302 static int JimAioSubCmdProc(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
);
303 static AioFile
*JimMakeChannel(Jim_Interp
*interp
, FILE *fh
, int fd
, Jim_Obj
*filename
,
304 const char *hdlfmt
, int family
, const char *mode
, int flags
);
306 #if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
307 #ifndef HAVE_GETADDRINFO
309 * Poor man's getaddrinfo().
310 * hints->ai_family must be set and must be PF_INET or PF_INET6
311 * Only returns the first matching result.
312 * servname must be numeric.
316 socklen_t ai_addrlen
;
317 struct sockaddr
*ai_addr
; /* simply points to ai_storage */
318 union sockaddr_any ai_storage
;
321 static int getaddrinfo(const char *hostname
, const char *servname
,
322 const struct addrinfo
*hints
, struct addrinfo
**res
)
326 unsigned long port
= strtoul(servname
, &end
, 10);
327 if (port
== 0 || port
> 65536 || *end
) {
332 if ((he
= gethostbyname(hostname
)) != NULL
) {
334 for (i
= 0; he
->h_addr_list
[i
]; i
++) {
335 if (he
->h_addrtype
== hints
->ai_family
) {
336 struct addrinfo
*ai
= malloc(sizeof(*ai
));
337 memset(ai
, 0, sizeof(*ai
));
338 ai
->ai_family
= he
->h_addrtype
;
339 ai
->ai_addr
= &ai
->ai_storage
.sa
;
340 if (ai
->ai_family
== PF_INET
) {
341 ai
->ai_addrlen
= sizeof(ai
->ai_storage
.sin
);
342 ai
->ai_storage
.sin
.sin_family
= he
->h_addrtype
;
343 assert(sizeof(ai
->ai_storage
.sin
.sin_addr
) == he
->h_length
);
344 memcpy(&ai
->ai_storage
.sin
.sin_addr
, he
->h_addr_list
[i
], he
->h_length
);
345 ai
->ai_storage
.sin
.sin_port
= htons(port
);
349 ai
->ai_addrlen
= sizeof(ai
->ai_storage
.sin6
);
350 ai
->ai_storage
.sin6
.sin6_family
= he
->h_addrtype
;
351 assert(sizeof(ai
->ai_storage
.sin6
.sin6_addr
) == he
->h_length
);
352 memcpy(&ai
->ai_storage
.sin6
.sin6_addr
, he
->h_addr_list
[i
], he
->h_length
);
353 ai
->ai_storage
.sin6
.sin6_port
= htons(port
);
364 static void freeaddrinfo(struct addrinfo
*ai
)
370 static int JimParseIPv6Address(Jim_Interp
*interp
, const char *hostport
, union sockaddr_any
*sa
, socklen_t
*salen
)
374 * An IPv6 addr/port looks like:
377 * [fe80::223:6cff:fe95:bdc0%en1]:2000
381 * Note that the "any" address is ::, which is the same as when no address is specified.
389 stport
= strrchr(hostport
, ':');
391 /* No : so, the whole thing is the port */
394 sthost
= Jim_StrDup(hostport
);
400 if (*hostport
== '[') {
401 /* This is a numeric ipv6 address */
402 char *pt
= strchr(++hostport
, ']');
404 sthost
= Jim_StrDupLen(hostport
, pt
- hostport
);
409 sthost
= Jim_StrDupLen(hostport
, stport
- hostport
- 1);
412 memset(&req
, '\0', sizeof(req
));
413 req
.ai_family
= PF_INET6
;
415 if (getaddrinfo(sthost
, stport
, &req
, &ai
)) {
416 Jim_SetResultFormatted(interp
, "Not a valid address: %s", hostport
);
420 memcpy(&sa
->sin6
, ai
->ai_addr
, ai
->ai_addrlen
);
421 *salen
= ai
->ai_addrlen
;
428 Jim_SetResultString(interp
, "ipv6 not supported", -1);
433 static int JimParseIpAddress(Jim_Interp
*interp
, const char *hostport
, union sockaddr_any
*sa
, socklen_t
*salen
)
435 /* An IPv4 addr/port looks like:
440 * If the address is missing, INADDR_ANY is used.
441 * If the port is missing, 0 is used (only useful for server sockets).
449 stport
= strrchr(hostport
, ':');
451 /* No : so, the whole thing is the port */
453 sthost
= Jim_StrDup("0.0.0.0");
456 sthost
= Jim_StrDupLen(hostport
, stport
- hostport
);
460 memset(&req
, '\0', sizeof(req
));
461 req
.ai_family
= PF_INET
;
463 if (getaddrinfo(sthost
, stport
, &req
, &ai
)) {
467 memcpy(&sa
->sin
, ai
->ai_addr
, ai
->ai_addrlen
);
468 *salen
= ai
->ai_addrlen
;
474 Jim_SetResultFormatted(interp
, "Not a valid address: %s", hostport
);
481 static int JimParseDomainAddress(Jim_Interp
*interp
, const char *path
, union sockaddr_any
*sa
, socklen_t
*salen
)
483 sa
->sun
.sun_family
= PF_UNIX
;
484 snprintf(sa
->sun
.sun_path
, sizeof(sa
->sun
.sun_path
), "%s", path
);
485 *salen
= strlen(sa
->sun
.sun_path
) + 1 + sizeof(sa
->sun
.sun_family
);
491 static int JimParseSocketAddress(Jim_Interp
*interp
, int family
, const char *addr
, union sockaddr_any
*sa
, socklen_t
*salen
)
496 return JimParseDomainAddress(interp
, addr
, sa
, salen
);
499 return JimParseIPv6Address(interp
, addr
, sa
, salen
);
501 return JimParseIpAddress(interp
, addr
, sa
, salen
);
507 * Format that address in 'sa' as a string and return it as a zero-refcount object.
510 static Jim_Obj
*JimFormatSocketAddress(Jim_Interp
*interp
, const union sockaddr_any
*sa
, socklen_t salen
)
512 /* INET6_ADDRSTRLEN is 46. Add some for [] and port */
514 const char *addr
= addrbuf
;
517 switch (sa
->sa
.sa_family
) {
520 addr
= sa
->sun
.sun_path
;
521 addrlen
= salen
- 1 - sizeof(sa
->sun
.sun_family
);
530 /* Allow 9 for []:65535\0 */
531 inet_ntop(sa
->sa
.sa_family
, &sa
->sin6
.sin6_addr
, addrbuf
+ 1, sizeof(addrbuf
) - 9);
532 snprintf(addrbuf
+ strlen(addrbuf
), 8, "]:%d", ntohs(sa
->sin6
.sin6_port
));
536 /* Allow 7 for :65535\0 */
537 inet_ntop(sa
->sa
.sa_family
, &sa
->sin
.sin_addr
, addrbuf
, sizeof(addrbuf
) - 7);
538 snprintf(addrbuf
+ strlen(addrbuf
), 7, ":%d", ntohs(sa
->sin
.sin_port
));
542 /* Otherwise just an empty address */
544 fprintf(stderr
, "%s:%d", __FILE__
, __LINE__
);
548 return Jim_NewStringObj(interp
, addr
, addrlen
);
551 static int JimSetVariableSocketAddress(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
, const union sockaddr_any
*sa
, socklen_t salen
)
554 Jim_Obj
*objPtr
= JimFormatSocketAddress(interp
, sa
, salen
);
555 Jim_IncrRefCount(objPtr
);
556 ret
= Jim_SetVariable(interp
, varObjPtr
, objPtr
);
557 Jim_DecrRefCount(interp
, objPtr
);
561 static Jim_Obj
*aio_sockname(Jim_Interp
*interp
, AioFile
*af
)
563 union sockaddr_any sa
;
564 socklen_t salen
= sizeof(sa
);
566 if (getsockname(af
->fd
, &sa
.sa
, &salen
) < 0) {
569 return JimFormatSocketAddress(interp
, &sa
, salen
);
571 #endif /* JIM_BOOTSTRAP */
573 static const char *JimAioErrorString(AioFile
*af
)
576 return af
->fops
->strerror(af
);
578 return strerror(errno
);
581 static void JimAioSetError(Jim_Interp
*interp
, Jim_Obj
*name
)
583 AioFile
*af
= Jim_CmdPrivData(interp
);
586 Jim_SetResultFormatted(interp
, "%#s: %s", name
, JimAioErrorString(af
));
589 Jim_SetResultString(interp
, JimAioErrorString(af
), -1);
593 static int JimCheckStreamError(Jim_Interp
*interp
, AioFile
*af
)
595 int ret
= af
->fops
->error(af
);
597 JimAioSetError(interp
, af
->filename
);
602 static void JimAioDelProc(Jim_Interp
*interp
, void *privData
)
604 AioFile
*af
= privData
;
609 if (af
->addr_family
== PF_UNIX
&& (af
->openFlags
& AIO_NODELETE
) == 0) {
610 /* If this is bound, delete the socket file now */
611 Jim_Obj
*filenameObj
= aio_sockname(interp
, af
);
613 if (Jim_Length(filenameObj
)) {
614 remove(Jim_String(filenameObj
));
616 Jim_FreeNewObj(interp
, filenameObj
);
621 Jim_DecrRefCount(interp
, af
->filename
);
623 #ifdef jim_ext_eventloop
624 /* remove all existing EventHandlers */
625 Jim_DeleteFileHandler(interp
, af
->fd
, JIM_EVENT_READABLE
| JIM_EVENT_WRITABLE
| JIM_EVENT_EXCEPTION
);
629 if (af
->ssl
!= NULL
) {
633 if (!(af
->openFlags
& AIO_KEEPOPEN
)) {
640 static int aio_cmd_read(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
642 AioFile
*af
= Jim_CmdPrivData(interp
);
643 char buf
[AIO_BUF_LEN
];
646 jim_wide neededLen
= -1; /* -1 is "read as much as possible" */
648 if (argc
&& Jim_CompareStringImmediate(interp
, argv
[0], "-nonewline")) {
654 if (Jim_GetWide(interp
, argv
[0], &neededLen
) != JIM_OK
)
657 Jim_SetResultString(interp
, "invalid parameter: negative len", -1);
664 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
665 while (neededLen
!= 0) {
669 if (neededLen
== -1) {
670 readlen
= AIO_BUF_LEN
;
673 readlen
= (neededLen
> AIO_BUF_LEN
? AIO_BUF_LEN
: neededLen
);
675 retval
= af
->fops
->reader(af
, buf
, readlen
);
677 Jim_AppendString(interp
, objPtr
, buf
, retval
);
678 if (neededLen
!= -1) {
682 if (retval
!= readlen
)
685 /* Check for error conditions */
686 if (JimCheckStreamError(interp
, af
)) {
687 Jim_FreeNewObj(interp
, objPtr
);
692 const char *s
= Jim_GetString(objPtr
, &len
);
694 if (len
> 0 && s
[len
- 1] == '\n') {
696 objPtr
->bytes
[objPtr
->length
] = '\0';
699 Jim_SetResult(interp
, objPtr
);
703 AioFile
*Jim_AioFile(Jim_Interp
*interp
, Jim_Obj
*command
)
705 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, command
, JIM_ERRMSG
);
707 /* XXX: There ought to be a supported API for this */
708 if (cmdPtr
&& !cmdPtr
->isproc
&& cmdPtr
->u
.native
.cmdProc
== JimAioSubCmdProc
) {
709 return (AioFile
*) cmdPtr
->u
.native
.privData
;
711 Jim_SetResultFormatted(interp
, "Not a filehandle: \"%#s\"", command
);
715 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*command
)
719 af
= Jim_AioFile(interp
, command
);
727 static int aio_cmd_getfd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
729 AioFile
*af
= Jim_CmdPrivData(interp
);
732 Jim_SetResultInt(interp
, fileno(af
->fp
));
737 static int aio_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
739 AioFile
*af
= Jim_CmdPrivData(interp
);
741 jim_wide maxlen
= JIM_WIDE_MAX
;
742 AioFile
*outf
= Jim_AioFile(interp
, argv
[0]);
749 if (Jim_GetWide(interp
, argv
[1], &maxlen
) != JIM_OK
) {
754 while (count
< maxlen
) {
755 /* A reasonable compromise between stack size and speed */
756 char buf
[AIO_BUF_LEN
];
757 jim_wide len
= maxlen
- count
;
758 if (len
> sizeof(buf
)) {
762 len
= af
->fops
->reader(af
, buf
, len
);
766 if (outf
->fops
->writer(outf
, buf
, len
) != len
) {
772 if (JimCheckStreamError(interp
, af
) || JimCheckStreamError(interp
, outf
)) {
776 Jim_SetResultInt(interp
, count
);
781 static int aio_cmd_gets(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
783 AioFile
*af
= Jim_CmdPrivData(interp
);
784 char buf
[AIO_BUF_LEN
];
790 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
792 buf
[AIO_BUF_LEN
- 1] = '_';
794 if (af
->fops
->getline(af
, buf
, AIO_BUF_LEN
) == NULL
)
797 if (buf
[AIO_BUF_LEN
- 1] == '\0' && buf
[AIO_BUF_LEN
- 2] != '\n') {
798 Jim_AppendString(interp
, objPtr
, buf
, AIO_BUF_LEN
- 1);
803 if (len
&& (buf
[len
- 1] == '\n')) {
808 Jim_AppendString(interp
, objPtr
, buf
, len
);
813 if (JimCheckStreamError(interp
, af
)) {
815 Jim_FreeNewObj(interp
, objPtr
);
820 if (Jim_SetVariable(interp
, argv
[0], objPtr
) != JIM_OK
) {
821 Jim_FreeNewObj(interp
, objPtr
);
825 len
= Jim_Length(objPtr
);
827 if (len
== 0 && feof(af
->fp
)) {
828 /* On EOF returns -1 if varName was specified */
831 Jim_SetResultInt(interp
, len
);
834 Jim_SetResult(interp
, objPtr
);
839 static int aio_cmd_puts(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
841 AioFile
*af
= Jim_CmdPrivData(interp
);
847 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-nonewline")) {
856 wdata
= Jim_GetString(strObj
, &wlen
);
857 if (af
->fops
->writer(af
, wdata
, wlen
) == wlen
) {
858 if (argc
== 2 || af
->fops
->writer(af
, "\n", 1) == 1) {
862 JimAioSetError(interp
, af
->filename
);
866 static int aio_cmd_isatty(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
869 AioFile
*af
= Jim_CmdPrivData(interp
);
870 Jim_SetResultInt(interp
, isatty(fileno(af
->fp
)));
872 Jim_SetResultInt(interp
, 0);
878 #if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
879 static int aio_cmd_recvfrom(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
881 AioFile
*af
= Jim_CmdPrivData(interp
);
883 union sockaddr_any sa
;
885 socklen_t salen
= sizeof(sa
);
888 if (Jim_GetLong(interp
, argv
[0], &len
) != JIM_OK
) {
892 buf
= Jim_Alloc(len
+ 1);
894 rlen
= recvfrom(fileno(af
->fp
), buf
, len
, 0, &sa
.sa
, &salen
);
897 JimAioSetError(interp
, NULL
);
901 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, rlen
));
904 return JimSetVariableSocketAddress(interp
, argv
[1], &sa
, salen
);
911 static int aio_cmd_sendto(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
913 AioFile
*af
= Jim_CmdPrivData(interp
);
917 union sockaddr_any sa
;
918 const char *addr
= Jim_String(argv
[1]);
921 if (JimParseSocketAddress(interp
, af
->addr_family
, addr
, &sa
, &salen
) != JIM_OK
) {
924 wdata
= Jim_GetString(argv
[0], &wlen
);
926 /* Note that we don't validate the socket type. Rely on sendto() failing if appropriate */
927 len
= sendto(fileno(af
->fp
), wdata
, wlen
, 0, &sa
.sa
, salen
);
929 JimAioSetError(interp
, NULL
);
932 Jim_SetResultInt(interp
, len
);
936 static int aio_cmd_accept(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
938 AioFile
*af
= Jim_CmdPrivData(interp
);
940 union sockaddr_any sa
;
941 socklen_t salen
= sizeof(sa
);
943 sock
= accept(af
->fd
, &sa
.sa
, &salen
);
945 JimAioSetError(interp
, NULL
);
950 if (JimSetVariableSocketAddress(interp
, argv
[0], &sa
, salen
) != JIM_OK
) {
955 /* Create the file command */
956 return JimMakeChannel(interp
, NULL
, sock
, Jim_NewStringObj(interp
, "accept", -1),
957 "aio.sockstream%ld", af
->addr_family
, "r+", AIO_NODELETE
) ? JIM_OK
: JIM_ERR
;
960 static int aio_cmd_sockname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
962 AioFile
*af
= Jim_CmdPrivData(interp
);
963 Jim_Obj
*objPtr
= aio_sockname(interp
, af
);
965 if (objPtr
== NULL
) {
966 JimAioSetError(interp
, NULL
);
969 Jim_SetResult(interp
, objPtr
);
973 static int aio_cmd_peername(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
975 AioFile
*af
= Jim_CmdPrivData(interp
);
976 union sockaddr_any sa
;
977 socklen_t salen
= sizeof(sa
);
979 if (getpeername(af
->fd
, &sa
.sa
, &salen
) < 0) {
980 JimAioSetError(interp
, NULL
);
983 Jim_SetResult(interp
, JimFormatSocketAddress(interp
, &sa
, salen
));
987 static int aio_cmd_listen(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
989 AioFile
*af
= Jim_CmdPrivData(interp
);
992 if (Jim_GetLong(interp
, argv
[0], &backlog
) != JIM_OK
) {
996 if (listen(af
->fd
, backlog
)) {
997 JimAioSetError(interp
, NULL
);
1003 #endif /* JIM_BOOTSTRAP */
1005 static int aio_cmd_flush(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1007 AioFile
*af
= Jim_CmdPrivData(interp
);
1009 if (fflush(af
->fp
) == EOF
) {
1010 JimAioSetError(interp
, af
->filename
);
1016 static int aio_cmd_eof(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1018 AioFile
*af
= Jim_CmdPrivData(interp
);
1020 Jim_SetResultInt(interp
, feof(af
->fp
));
1024 static int aio_cmd_close(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1028 #if defined(HAVE_SOCKETS)
1029 static const char * const options
[] = { "r", "w", "-nodelete", NULL
};
1030 enum { OPT_R
, OPT_W
, OPT_NODELETE
};
1031 AioFile
*af
= Jim_CmdPrivData(interp
);
1033 if (Jim_GetEnum(interp
, argv
[2], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
1038 #if defined(HAVE_SHUTDOWN)
1041 if (shutdown(af
->fd
, option
== OPT_R
? SHUT_RD
: SHUT_WR
) == 0) {
1044 JimAioSetError(interp
, NULL
);
1049 if (af
->addr_family
== PF_UNIX
) {
1050 af
->openFlags
|= AIO_NODELETE
;
1056 Jim_SetResultString(interp
, "not supported", -1);
1061 return Jim_DeleteCommand(interp
, Jim_String(argv
[0]));
1064 static int aio_cmd_seek(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1066 AioFile
*af
= Jim_CmdPrivData(interp
);
1067 int orig
= SEEK_SET
;
1071 if (Jim_CompareStringImmediate(interp
, argv
[1], "start"))
1073 else if (Jim_CompareStringImmediate(interp
, argv
[1], "current"))
1075 else if (Jim_CompareStringImmediate(interp
, argv
[1], "end"))
1081 if (Jim_GetWide(interp
, argv
[0], &offset
) != JIM_OK
) {
1084 if (fseeko(af
->fp
, offset
, orig
) == -1) {
1085 JimAioSetError(interp
, af
->filename
);
1091 static int aio_cmd_tell(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1093 AioFile
*af
= Jim_CmdPrivData(interp
);
1095 Jim_SetResultInt(interp
, ftello(af
->fp
));
1099 static int aio_cmd_filename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1101 AioFile
*af
= Jim_CmdPrivData(interp
);
1103 Jim_SetResult(interp
, af
->filename
);
1108 static int aio_cmd_ndelay(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1110 AioFile
*af
= Jim_CmdPrivData(interp
);
1112 int fmode
= fcntl(af
->fd
, F_GETFL
);
1117 if (Jim_GetLong(interp
, argv
[0], &nb
) != JIM_OK
) {
1126 (void)fcntl(af
->fd
, F_SETFL
, fmode
);
1128 Jim_SetResultInt(interp
, (fmode
& O_NONBLOCK
) ? 1 : 0);
1133 #if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
1134 #define SOCKOPT_BOOL 0
1135 #define SOCKOPT_INT 1
1136 #define SOCKOPT_TIMEVAL 2 /* not currently supported */
1138 static const struct sockopt_def
{
1142 int type
; /* SOCKOPT_xxx */
1146 { "broadcast", SOL_SOCKET
, SO_BROADCAST
},
1149 { "debug", SOL_SOCKET
, SO_DEBUG
},
1152 { "keepalive", SOL_SOCKET
, SO_KEEPALIVE
},
1155 { "nosigpipe", SOL_SOCKET
, SO_NOSIGPIPE
},
1158 { "oobinline", SOL_SOCKET
, SO_OOBINLINE
},
1161 { "sndbuf", SOL_SOCKET
, SO_SNDBUF
, SOCKOPT_INT
},
1164 { "rcvbuf", SOL_SOCKET
, SO_RCVBUF
, SOCKOPT_INT
},
1166 #if 0 && defined(SO_SNDTIMEO)
1167 { "sndtimeo", SOL_SOCKET
, SO_SNDTIMEO
, SOCKOPT_TIMEVAL
},
1169 #if 0 && defined(SO_RCVTIMEO)
1170 { "rcvtimeo", SOL_SOCKET
, SO_RCVTIMEO
, SOCKOPT_TIMEVAL
},
1175 { "tcp_nodelay", IPPROTO_TCP
, TCP_NODELAY
},
1180 static int aio_cmd_sockopt(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1182 AioFile
*af
= Jim_CmdPrivData(interp
);
1186 Jim_Obj
*dictObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
1187 for (i
= 0; i
< sizeof(sockopts
) / sizeof(*sockopts
); i
++) {
1189 socklen_t len
= sizeof(value
);
1190 if (getsockopt(af
->fd
, sockopts
[i
].level
, sockopts
[i
].opt
, (void *)&value
, &len
) == 0) {
1191 if (sockopts
[i
].type
== SOCKOPT_BOOL
) {
1194 Jim_ListAppendElement(interp
, dictObjPtr
, Jim_NewStringObj(interp
, sockopts
[i
].name
, -1));
1195 Jim_ListAppendElement(interp
, dictObjPtr
, Jim_NewIntObj(interp
, value
));
1198 Jim_SetResult(interp
, dictObjPtr
);
1206 for (i
= 0; i
< sizeof(sockopts
) / sizeof(*sockopts
); i
++) {
1207 if (strcmp(Jim_String(argv
[0]), sockopts
[i
].name
) == 0) {
1209 if (sockopts
[i
].type
== SOCKOPT_BOOL
) {
1210 if (Jim_GetBoolean(interp
, argv
[1], &on
) != JIM_OK
) {
1216 if (Jim_GetLong(interp
, argv
[1], &longval
) != JIM_OK
) {
1221 if (setsockopt(af
->fd
, sockopts
[i
].level
, sockopts
[i
].opt
, (void *)&on
, sizeof(on
)) < 0) {
1222 Jim_SetResultFormatted(interp
, "Failed to set %#s: %s", argv
[0], strerror(errno
));
1229 Jim_SetResultFormatted(interp
, "Unknown sockopt %#s", argv
[0]);
1232 #endif /* JIM_BOOTSTRAP */
1235 static int aio_cmd_sync(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1237 AioFile
*af
= Jim_CmdPrivData(interp
);
1245 static int aio_cmd_buffering(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1247 AioFile
*af
= Jim_CmdPrivData(interp
);
1249 static const char * const options
[] = {
1263 if (Jim_GetEnum(interp
, argv
[0], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
1268 setvbuf(af
->fp
, NULL
, _IONBF
, 0);
1271 setvbuf(af
->fp
, NULL
, _IOLBF
, BUFSIZ
);
1274 setvbuf(af
->fp
, NULL
, _IOFBF
, BUFSIZ
);
1280 #ifdef jim_ext_eventloop
1281 static void JimAioFileEventFinalizer(Jim_Interp
*interp
, void *clientData
)
1283 Jim_Obj
**objPtrPtr
= clientData
;
1285 Jim_DecrRefCount(interp
, *objPtrPtr
);
1289 static int JimAioFileEventHandler(Jim_Interp
*interp
, void *clientData
, int mask
)
1291 Jim_Obj
**objPtrPtr
= clientData
;
1293 return Jim_EvalObjBackground(interp
, *objPtrPtr
);
1296 static int aio_eventinfo(Jim_Interp
*interp
, AioFile
* af
, unsigned mask
, Jim_Obj
**scriptHandlerObj
,
1297 int argc
, Jim_Obj
* const *argv
)
1300 /* Return current script */
1301 if (*scriptHandlerObj
) {
1302 Jim_SetResult(interp
, *scriptHandlerObj
);
1307 if (*scriptHandlerObj
) {
1308 /* Delete old handler */
1309 Jim_DeleteFileHandler(interp
, af
->fd
, mask
);
1312 /* Now possibly add the new script(s) */
1313 if (Jim_Length(argv
[0]) == 0) {
1314 /* Empty script, so done */
1318 /* A new script to add */
1319 Jim_IncrRefCount(argv
[0]);
1320 *scriptHandlerObj
= argv
[0];
1322 Jim_CreateFileHandler(interp
, af
->fd
, mask
,
1323 JimAioFileEventHandler
, scriptHandlerObj
, JimAioFileEventFinalizer
);
1328 static int aio_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1330 AioFile
*af
= Jim_CmdPrivData(interp
);
1332 return aio_eventinfo(interp
, af
, JIM_EVENT_READABLE
, &af
->rEvent
, argc
, argv
);
1335 static int aio_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1337 AioFile
*af
= Jim_CmdPrivData(interp
);
1339 return aio_eventinfo(interp
, af
, JIM_EVENT_WRITABLE
, &af
->wEvent
, argc
, argv
);
1342 static int aio_cmd_onexception(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1344 AioFile
*af
= Jim_CmdPrivData(interp
);
1346 return aio_eventinfo(interp
, af
, JIM_EVENT_EXCEPTION
, &af
->eEvent
, argc
, argv
);
1350 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
1351 static int aio_cmd_ssl(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1353 AioFile
*af
= Jim_CmdPrivData(interp
);
1359 if (!Jim_CompareStringImmediate(interp
, argv
[2], "-server")) {
1364 else if (argc
!= 2) {
1369 Jim_SetResultFormatted(interp
, "%#s: stream is already ssl", argv
[0]);
1373 ssl_ctx
= JimAioSslCtx(interp
);
1374 if (ssl_ctx
== NULL
) {
1378 ssl
= SSL_new(ssl_ctx
);
1383 SSL_set_cipher_list(ssl
, "ALL");
1385 if (SSL_set_fd(ssl
, fileno(af
->fp
)) == 0) {
1390 if (SSL_use_certificate_file(ssl
, Jim_String(argv
[3]), SSL_FILETYPE_PEM
) != 1) {
1394 if (SSL_use_PrivateKey_file(ssl
, Jim_String(argv
[4]), SSL_FILETYPE_PEM
) != 1) {
1398 if (SSL_accept(ssl
) != 1) {
1403 if (SSL_connect(ssl
) != 1) {
1409 af
->fops
= &ssl_fops
;
1411 /* Set the command name as the result */
1412 Jim_SetResult(interp
, argv
[0]);
1420 Jim_SetResultString(interp
, ERR_error_string(ERR_get_error(), NULL
), -1);
1424 static int aio_cmd_verify(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1426 AioFile
*af
= Jim_CmdPrivData(interp
);
1429 if (!af
->fops
->verify
) {
1433 ret
= af
->fops
->verify(af
);
1434 if (ret
!= JIM_OK
) {
1435 if (JimCheckStreamError(interp
, af
) == JIM_OK
) {
1436 Jim_SetResultString(interp
, "failed to verify the connection authenticity", -1);
1441 #endif /* JIM_BOOTSTRAP */
1443 #if defined(HAVE_STRUCT_FLOCK) && !defined(JIM_BOOTSTRAP)
1444 static int aio_cmd_lock(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1446 AioFile
*af
= Jim_CmdPrivData(interp
);
1448 int lockmode
= F_SETLK
;
1451 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-wait")) {
1454 lockmode
= F_SETLKW
;
1459 fl
.l_type
= F_WRLCK
;
1460 fl
.l_whence
= SEEK_SET
;
1462 switch (fcntl(af
->fd
, lockmode
, &fl
))
1465 Jim_SetResultInt(interp
, 1);
1468 if (errno
== EACCES
|| errno
== EAGAIN
)
1469 Jim_SetResultInt(interp
, 0);
1472 Jim_SetResultFormatted(interp
, "lock failed: %s",
1478 Jim_SetResultInt(interp
, 0);
1485 static int aio_cmd_unlock(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1487 AioFile
*af
= Jim_CmdPrivData(interp
);
1491 fl
.l_type
= F_UNLCK
;
1492 fl
.l_whence
= SEEK_SET
;
1494 Jim_SetResultInt(interp
, fcntl(af
->fd
, F_SETLK
, &fl
) == 0);
1497 #endif /* JIM_BOOTSTRAP */
1499 #if defined(HAVE_TERMIOS_H) && !defined(JIM_BOOTSTRAP)
1500 static int aio_cmd_tty(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1502 AioFile
*af
= Jim_CmdPrivData(interp
);
1503 Jim_Obj
*dictObjPtr
;
1507 /* get the current settings as a dictionary */
1508 dictObjPtr
= Jim_GetTtySettings(interp
, af
->fd
);
1509 if (dictObjPtr
== NULL
) {
1510 JimAioSetError(interp
, NULL
);
1513 Jim_SetResult(interp
, dictObjPtr
);
1518 /* Convert name value arguments to a dictionary */
1519 dictObjPtr
= Jim_NewListObj(interp
, argv
, argc
);
1522 /* The settings are already given as a list */
1523 dictObjPtr
= argv
[0];
1525 Jim_IncrRefCount(dictObjPtr
);
1527 if (Jim_ListLength(interp
, dictObjPtr
) % 2) {
1528 /* Must be a valid dictionary */
1529 Jim_DecrRefCount(interp
, dictObjPtr
);
1533 ret
= Jim_SetTtySettings(interp
, af
->fd
, dictObjPtr
);
1535 JimAioSetError(interp
, NULL
);
1538 Jim_DecrRefCount(interp
, dictObjPtr
);
1542 #endif /* JIM_BOOTSTRAP */
1544 static const jim_subcmd_type aio_command_table
[] = {
1546 "?-nonewline? ?len?",
1550 /* Description: Read and return bytes from the stream. To eof if no len. */
1557 /* Description: Copy up to 'size' bytes to the given filehandle, or to eof if no size. */
1564 /* Description: Internal command to return the underlying file descriptor. */
1571 /* Description: Read one line and return it or store it in the var */
1578 /* Description: Write the string, with newline unless -nonewline */
1585 /* Description: Is the file descriptor a tty? */
1587 #if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
1593 /* Description: Receive up to 'len' bytes on the socket. Sets 'addrvar' with receive address, if set */
1600 /* Description: Send 'str' to the given address (dgram only) */
1607 /* Description: Server socket only: Accept a connection and return stream */
1614 /* Description: Set the listen backlog for server socket */
1621 /* Description: Return a dictionary of sockopts, or set the value of a sockopt */
1628 /* Description: Returns the local address of the socket, if any */
1635 /* Description: Returns the remote address of the socket, if any */
1637 #endif /* JIM_BOOTSTRAP */
1643 /* Description: Flush the stream */
1650 /* Description: Returns 1 if stream is at eof */
1657 JIM_MODFLAG_FULLARGV
,
1658 /* Description: Closes the stream. */
1661 "offset ?start|current|end",
1665 /* Description: Seeks in the stream (default 'current') */
1672 /* Description: Returns the current seek position */
1679 /* Description: Returns the original filename */
1687 /* Description: Set O_NDELAY (if arg). Returns current/new setting. */
1696 /* Description: Flush and fsync() the stream */
1704 /* Description: Sets buffering */
1706 #ifdef jim_ext_eventloop
1708 "?readable-script?",
1712 /* Description: Returns script, or invoke readable-script when readable, {} to remove */
1715 "?writable-script?",
1719 /* Description: Returns script, or invoke writable-script when writable, {} to remove */
1722 "?exception-script?",
1723 aio_cmd_onexception
,
1726 /* Description: Returns script, or invoke exception-script when oob data, {} to remove */
1729 #if !defined(JIM_BOOTSTRAP)
1730 #if defined(JIM_SSL)
1732 "?-server cert priv?",
1736 JIM_MODFLAG_FULLARGV
1737 /* Description: Wraps a stream socket with SSL/TLS and returns a new channel */
1744 /* Description: Verifies the certificate of a SSL/TLS channel */
1747 #if defined(HAVE_STRUCT_FLOCK)
1753 /* Description: Attempt to get a lock, possibly waiting */
1760 /* Description: Relase a lock. */
1763 #if defined(HAVE_TERMIOS_H)
1765 "?baud rate? ?data bits? ?stop bits? ?parity even|odd|none? ?handshake xonxoff|rtscts|none? ?input raw|cooked? ?output raw|cooked? ?vmin n? ?vtime n?",
1769 /* Description: Get or set tty settings - valid only on a tty */
1772 #endif /* JIM_BOOTSTRAP */
1776 static int JimAioSubCmdProc(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1778 return Jim_CallSubCmd(interp
, Jim_ParseSubCmd(interp
, aio_command_table
, argc
, argv
), argc
, argv
);
1781 static int JimAioOpenCommand(Jim_Interp
*interp
, int argc
,
1782 Jim_Obj
*const *argv
)
1786 if (argc
!= 2 && argc
!= 3) {
1787 Jim_WrongNumArgs(interp
, 1, argv
, "filename ?mode?");
1791 mode
= (argc
== 3) ? Jim_String(argv
[2]) : "r";
1793 #ifdef jim_ext_tclcompat
1795 const char *filename
= Jim_String(argv
[1]);
1797 /* If the filename starts with '|', use popen instead */
1798 if (*filename
== '|') {
1799 Jim_Obj
*evalObj
[3];
1801 evalObj
[0] = Jim_NewStringObj(interp
, "::popen", -1);
1802 evalObj
[1] = Jim_NewStringObj(interp
, filename
+ 1, -1);
1803 evalObj
[2] = Jim_NewStringObj(interp
, mode
, -1);
1805 return Jim_EvalObjVector(interp
, 3, evalObj
);
1809 return JimMakeChannel(interp
, NULL
, -1, argv
[1], "aio.handle%ld", 0, mode
, 0) ? JIM_OK
: JIM_ERR
;
1812 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
1813 static void JimAioSslContextDelProc(struct Jim_Interp
*interp
, void *privData
)
1815 SSL_CTX_free((SSL_CTX
*)privData
);
1819 #ifdef USE_TLSv1_2_method
1820 #define TLS_method TLSv1_2_method
1823 static SSL_CTX
*JimAioSslCtx(Jim_Interp
*interp
)
1825 SSL_CTX
*ssl_ctx
= (SSL_CTX
*)Jim_GetAssocData(interp
, "ssl_ctx");
1826 if (ssl_ctx
== NULL
) {
1827 SSL_load_error_strings();
1829 ssl_ctx
= SSL_CTX_new(TLS_method());
1830 if (ssl_ctx
&& SSL_CTX_set_default_verify_paths(ssl_ctx
)) {
1831 SSL_CTX_set_verify(ssl_ctx
, SSL_VERIFY_NONE
, NULL
);
1832 Jim_SetAssocData(interp
, "ssl_ctx", JimAioSslContextDelProc
, ssl_ctx
);
1834 Jim_SetResultString(interp
, ERR_error_string(ERR_get_error(), NULL
), -1);
1839 #endif /* JIM_BOOTSTRAP */
1842 * Creates a channel for fh/fd/filename.
1844 * If fh is not NULL, uses that as the channel (and sets AIO_KEEPOPEN).
1845 * Otherwise, if fd is >= 0, uses that as the channel.
1846 * Otherwise opens 'filename' with mode 'mode'.
1848 * hdlfmt is a sprintf format for the filehandle. Anything with %ld at the end will do.
1849 * mode is used for open or fdopen.
1851 * Creates the command and sets the name as the current result.
1852 * Returns the AioFile pointer on sucess or NULL on failure.
1854 static AioFile
*JimMakeChannel(Jim_Interp
*interp
, FILE *fh
, int fd
, Jim_Obj
*filename
,
1855 const char *hdlfmt
, int family
, const char *mode
, int flags
)
1858 char buf
[AIO_CMD_LEN
];
1860 snprintf(buf
, sizeof(buf
), hdlfmt
, Jim_GetId(interp
));
1862 filename
= Jim_NewStringObj(interp
, buf
, -1);
1865 Jim_IncrRefCount(filename
);
1870 fh
= fdopen(fd
, mode
);
1874 fh
= fopen(Jim_String(filename
), mode
);
1877 JimAioSetError(interp
, filename
);
1883 Jim_DecrRefCount(interp
, filename
);
1888 /* Create the file command */
1889 af
= Jim_Alloc(sizeof(*af
));
1890 memset(af
, 0, sizeof(*af
));
1892 af
->filename
= filename
;
1893 af
->openFlags
= flags
;
1895 af
->fd
= fileno(fh
);
1897 if ((flags
& AIO_KEEPOPEN
) == 0) {
1898 (void)fcntl(af
->fd
, F_SETFD
, FD_CLOEXEC
);
1902 af
->addr_family
= family
;
1903 af
->fops
= &stdio_fops
;
1906 Jim_CreateCommand(interp
, buf
, JimAioSubCmdProc
, af
, JimAioDelProc
);
1908 /* Note that the command must use the global namespace, even if
1909 * the current namespace is something different
1911 Jim_SetResult(interp
, Jim_MakeGlobalNamespaceName(interp
, Jim_NewStringObj(interp
, buf
, -1)));
1916 #if defined(HAVE_PIPE) || (defined(HAVE_SOCKETPAIR) && UNIX_SOCKETS)
1918 * Create a pair of channels. e.g. from pipe() or socketpair()
1920 static int JimMakeChannelPair(Jim_Interp
*interp
, int p
[2], Jim_Obj
*filename
,
1921 const char *hdlfmt
, int family
, const char * const mode
[2])
1923 if (JimMakeChannel(interp
, NULL
, p
[0], filename
, hdlfmt
, family
, mode
[0], 0)) {
1924 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
1925 Jim_ListAppendElement(interp
, objPtr
, Jim_GetResult(interp
));
1926 if (JimMakeChannel(interp
, NULL
, p
[1], filename
, hdlfmt
, family
, mode
[1], 0)) {
1927 Jim_ListAppendElement(interp
, objPtr
, Jim_GetResult(interp
));
1928 Jim_SetResult(interp
, objPtr
);
1933 /* Can only be here if fdopen() failed */
1936 JimAioSetError(interp
, NULL
);
1942 static int JimAioPipeCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1945 static const char * const mode
[2] = { "r", "w" };
1948 Jim_WrongNumArgs(interp
, 1, argv
, "");
1953 JimAioSetError(interp
, NULL
);
1957 return JimMakeChannelPair(interp
, p
, argv
[0], "aio.pipe%ld", 0, mode
);
1961 #if defined(HAVE_SOCKETS) && !defined(JIM_BOOTSTRAP)
1963 static int JimAioSockCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
1965 const char *socktypes
[] = {
1969 "unix.dgram.server",
1983 SOCK_UNIX_DGRAM_SERVER
,
1989 SOCK_STREAM_SOCKETPAIR
,
1993 const char *addr
= NULL
;
1994 const char *bind_addr
= NULL
;
1995 const char *connect_addr
= NULL
;
1996 union sockaddr_any sa
;
2001 int family
= PF_INET
;
2002 int type
= SOCK_STREAM
;
2003 Jim_Obj
*argv0
= argv
[0];
2006 if (argc
> 1 && Jim_CompareStringImmediate(interp
, argv
[1], "-ipv6")) {
2008 Jim_SetResultString(interp
, "ipv6 not supported", -1);
2019 Jim_WrongNumArgs(interp
, 1, &argv0
, "?-ipv6? type ?address?");
2023 if (Jim_GetEnum(interp
, argv
[1], socktypes
, &socktype
, "socket type", JIM_ERRMSG
) != JIM_OK
)
2024 return Jim_CheckShowCommands(interp
, argv
[1], socktypes
);
2026 Jim_SetEmptyResult(interp
);
2029 addr
= Jim_String(argv
[2]);
2032 #if defined(HAVE_SOCKETPAIR) && UNIX_SOCKETS
2033 if (socktype
== SOCK_STREAM_SOCKETPAIR
) {
2035 static const char * const mode
[2] = { "r+", "r+" };
2041 if (socketpair(PF_UNIX
, SOCK_STREAM
, 0, p
) < 0) {
2042 JimAioSetError(interp
, NULL
);
2045 return JimMakeChannelPair(interp
, p
, argv
[1], "aio.sockpair%ld", PF_UNIX
, mode
);
2049 #if defined(HAVE_PIPE)
2050 if (socktype
== SOCK_STREAM_PIPE
) {
2054 return JimAioPipeCommand(interp
, 1, &argv
[1]);
2058 /* Now all these socket types are very similar */
2060 case SOCK_DGRAM_CLIENT
:
2061 connect_addr
= addr
;
2065 case SOCK_STREAM_CLIENT
:
2069 connect_addr
= addr
;
2072 case SOCK_STREAM_SERVER
:
2081 case SOCK_DGRAM_SERVER
:
2095 connect_addr
= addr
;
2099 case SOCK_UNIX_DGRAM
:
2100 connect_addr
= addr
;
2103 /* A dgram unix domain socket client needs to bind
2104 * to a temporary address to allow the server to
2108 int tmpfd
= Jim_MakeTempFile(interp
, NULL
, 1);
2113 /* This will be valid until a result is next set, which is long enough here */
2114 bind_addr
= Jim_String(Jim_GetResult(interp
));
2118 case SOCK_UNIX_SERVER
:
2127 case SOCK_UNIX_DGRAM_SERVER
:
2138 Jim_SetResultString(interp
, "Unsupported socket type", -1);
2142 /* Now do all the steps necessary for the given socket type */
2143 sock
= socket(family
, type
, 0);
2145 JimAioSetError(interp
, NULL
);
2149 if (JimParseSocketAddress(interp
, family
, bind_addr
, &sa
, &salen
) != JIM_OK
) {
2154 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&on
, sizeof(on
));
2156 if (bind(sock
, &sa
.sa
, salen
)) {
2157 Jim_SetResultFormatted(interp
, "%s: bind: %s", bind_addr
, strerror(errno
));
2163 if (JimParseSocketAddress(interp
, family
, connect_addr
, &sa
, &salen
) != JIM_OK
) {
2167 if (connect(sock
, &sa
.sa
, salen
)) {
2168 Jim_SetResultFormatted(interp
, "%s: connect: %s", connect_addr
, strerror(errno
));
2174 if (listen(sock
, 5)) {
2175 Jim_SetResultFormatted(interp
, "listen: %s", strerror(errno
));
2181 return JimMakeChannel(interp
, NULL
, sock
, argv
[1], "aio.sock%ld", family
, "r+", 0) ? JIM_OK
: JIM_ERR
;
2183 #endif /* JIM_BOOTSTRAP */
2185 #if defined(JIM_SSL) && !defined(JIM_BOOTSTRAP)
2186 static int JimAioLoadSSLCertsCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
2191 Jim_WrongNumArgs(interp
, 1, argv
, "dir");
2195 ssl_ctx
= JimAioSslCtx(interp
);
2199 if (SSL_CTX_load_verify_locations(ssl_ctx
, NULL
, Jim_String(argv
[1])) == 1) {
2202 Jim_SetResultString(interp
, ERR_error_string(ERR_get_error(), NULL
), -1);
2205 #endif /* JIM_BOOTSTRAP */
2207 int Jim_aioInit(Jim_Interp
*interp
)
2209 if (Jim_PackageProvide(interp
, "aio", "1.0", JIM_ERRMSG
))
2212 #if defined(JIM_SSL)
2213 Jim_CreateCommand(interp
, "load_ssl_certs", JimAioLoadSSLCertsCommand
, NULL
, NULL
);
2216 Jim_CreateCommand(interp
, "open", JimAioOpenCommand
, NULL
, NULL
);
2218 Jim_CreateCommand(interp
, "socket", JimAioSockCommand
, NULL
, NULL
);
2221 Jim_CreateCommand(interp
, "pipe", JimAioPipeCommand
, NULL
, NULL
);
2224 /* Create filehandles for stdin, stdout and stderr */
2225 JimMakeChannel(interp
, stdin
, -1, NULL
, "stdin", 0, "r", AIO_KEEPOPEN
);
2226 JimMakeChannel(interp
, stdout
, -1, NULL
, "stdout", 0, "w", AIO_KEEPOPEN
);
2227 JimMakeChannel(interp
, stderr
, -1, NULL
, "stderr", 0, "w", AIO_KEEPOPEN
);