os/persistentdata/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/unix/tclUnixChan.c
First public contribution.
4 * Common channel driver for Unix channels based on files, command
5 * pipes and TCP sockets.
7 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
8 * Copyright (c) 1998-1999 by Scriptics Corporation.
9 * Portions Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiaries. All rights reserved.
11 * See the file "license.terms" for information on usage and redistribution
12 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 * RCS: @(#) $Id: tclUnixChan.c,v 1.42.2.10 2006/11/28 16:29:48 kennykb Exp $
17 #include "tclInt.h" /* Internal definitions for Tcl. */
18 #include "tclPort.h" /* Portability features for Tcl. */
19 #include "tclIO.h" /* To get Channel type declaration. */
22 * sys/ioctl.h has already been included by tclPort.h. Including termios.h
23 * or termio.h causes a bunch of warning messages because some duplicate
24 * (but not contradictory) #defines exist in termios.h and/or termio.h
50 # ifdef HAVE_SYS_IOCTL_H
51 # include <sys/ioctl.h>
52 # endif /* HAVE_SYS_IOCTL_H */
53 # ifdef HAVE_SYS_MODEM_H
54 # include <sys/modem.h>
55 # endif /* HAVE_SYS_MODEM_H */
56 # define IOSTATE struct termios
57 # define GETIOSTATE(fd, statePtr) tcgetattr((fd), (statePtr))
58 # define SETIOSTATE(fd, statePtr) tcsetattr((fd), TCSADRAIN, (statePtr))
59 # define GETCONTROL(fd, intPtr) ioctl((fd), TIOCMGET, (intPtr))
60 # define SETCONTROL(fd, intPtr) ioctl((fd), TIOCMSET, (intPtr))
62 * TIP #35 introduced a different on exit flush/close behavior that
63 * doesn't work correctly with standard channels on all systems.
64 * The problem is tcflush throws away waiting channel data. This may
65 * be necessary for true serial channels that may block, but isn't
66 * correct in the standard case. This might be replaced with tcdrain
67 * instead, but that can block. For now, we revert to making this do
68 * nothing, and TtyOutputProc being the same old FileOutputProc.
69 * -- hobbs [Bug #525783]
71 # define BAD_TIP35_FLUSH 0
73 # define TTYFLUSH(fd) tcflush((fd), TCIOFLUSH);
76 # endif /* BAD_TIP35_FLUSH */
78 # define GETREADQUEUE(fd, int) ioctl((fd), FIONREAD, &(int))
79 # elif defined(FIORDCHK)
80 # define GETREADQUEUE(fd, int) int = ioctl((fd), FIORDCHK, NULL)
81 # endif /* FIONREAD */
83 # define GETWRITEQUEUE(fd, int) ioctl((fd), TIOCOUTQ, &(int))
84 # endif /* TIOCOUTQ */
85 # if defined(TIOCSBRK) && defined(TIOCCBRK)
87 * Can't use ?: operator below because that messes up types on either
88 * Linux or Solaris (the two are mutually exclusive!)
90 # define SETBREAK(fd, flag) \
92 ioctl((fd), TIOCSBRK, NULL); \
94 ioctl((fd), TIOCCBRK, NULL); \
96 # endif /* TIOCSBRK&TIOCCBRK */
97 # if !defined(CRTSCTS) && defined(CNEW_RTSCTS)
98 # define CRTSCTS CNEW_RTSCTS
99 # endif /* !CRTSCTS&CNEW_RTSCTS */
100 #else /* !USE_TERMIOS */
104 # define IOSTATE struct termio
105 # define GETIOSTATE(fd, statePtr) ioctl((fd), TCGETA, (statePtr))
106 # define SETIOSTATE(fd, statePtr) ioctl((fd), TCSETAW, (statePtr))
107 #else /* !USE_TERMIO */
111 # define IOSTATE struct sgttyb
112 # define GETIOSTATE(fd, statePtr) ioctl((fd), TIOCGETP, (statePtr))
113 # define SETIOSTATE(fd, statePtr) ioctl((fd), TIOCSETP, (statePtr))
114 #else /* !USE_SGTTY */
116 #endif /* !USE_SGTTY */
118 #endif /* !USE_TERMIO */
119 #endif /* !USE_TERMIOS */
122 * This structure describes per-instance state of a file based channel.
125 typedef struct FileState {
126 Tcl_Channel channel; /* Channel associated with this file. */
127 int fd; /* File handle. */
128 int validMask; /* OR'ed combination of TCL_READABLE,
129 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
130 * which operations are valid on the file. */
132 struct FileState *nextPtr; /* Pointer to next file in list of all
134 #endif /* DEPRECATED */
140 * The following structure describes per-instance state of a tty-based
144 typedef struct TtyState {
145 FileState fs; /* Per-instance state of the file
146 * descriptor. Must be the first field. */
147 int stateUpdated; /* Flag to say if the state has been
148 * modified and needs resetting. */
149 IOSTATE savedState; /* Initial state of device. Used to reset
150 * state when device closed. */
154 * The following structure is used to set or get the serial port
155 * attributes in a platform-independant manner.
158 typedef struct TtyAttrs {
165 #endif /* !SUPPORTS_TTY */
167 #define UNSUPPORTED_OPTION(detail) \
169 Tcl_AppendResult(interp, (detail), \
170 " not supported for this platform", (char *) NULL); \
174 typedef struct ThreadSpecificData {
176 * List of all file channels currently open. This is per thread and is
177 * used to match up fd's to channels, which rarely occurs.
180 FileState *firstFilePtr;
181 } ThreadSpecificData;
183 static Tcl_ThreadDataKey dataKey;
184 #endif /* DEPRECATED */
187 * This structure describes per-instance state of a tcp based channel.
190 typedef struct TcpState {
191 Tcl_Channel channel; /* Channel associated with this file. */
192 int fd; /* The socket itself. */
193 int flags; /* ORed combination of the bitfields
195 Tcl_TcpAcceptProc *acceptProc;
196 /* Proc to call on accept. */
197 ClientData acceptProcData; /* The data for the accept proc. */
201 * These bits may be ORed together into the "flags" field of a TcpState
205 #define TCP_ASYNC_SOCKET (1<<0) /* Asynchronous socket. */
206 #define TCP_ASYNC_CONNECT (1<<1) /* Async connect in progress. */
209 * The following defines the maximum length of the listen queue. This is
210 * the number of outstanding yet-to-be-serviced requests for a connection
211 * on a server socket, more than this number of outstanding requests and
212 * the connection request will fail.
216 # define SOMAXCONN 100
217 #endif /* SOMAXCONN */
219 #if (SOMAXCONN < 100)
221 # define SOMAXCONN 100
222 #endif /* SOMAXCONN < 100 */
225 * The following defines how much buffer space the kernel should maintain
229 #define SOCKET_BUFSIZE 4096
232 * Static routines for this file:
235 static TcpState * CreateSocket _ANSI_ARGS_((Tcl_Interp *interp,
236 int port, CONST char *host, int server,
237 CONST char *myaddr, int myport, int async));
238 static int CreateSocketAddress _ANSI_ARGS_(
239 (struct sockaddr_in *sockaddrPtr,
240 CONST char *host, int port));
241 static int FileBlockModeProc _ANSI_ARGS_((
242 ClientData instanceData, int mode));
243 static int FileCloseProc _ANSI_ARGS_((ClientData instanceData,
244 Tcl_Interp *interp));
245 static int FileGetHandleProc _ANSI_ARGS_((ClientData instanceData,
246 int direction, ClientData *handlePtr));
247 static int FileInputProc _ANSI_ARGS_((ClientData instanceData,
248 char *buf, int toRead, int *errorCode));
249 static int FileOutputProc _ANSI_ARGS_((
250 ClientData instanceData, CONST char *buf,
251 int toWrite, int *errorCode));
252 static int FileSeekProc _ANSI_ARGS_((ClientData instanceData,
253 long offset, int mode, int *errorCode));
255 static void FileThreadActionProc _ANSI_ARGS_ ((
256 ClientData instanceData, int action));
258 static Tcl_WideInt FileWideSeekProc _ANSI_ARGS_((ClientData instanceData,
259 Tcl_WideInt offset, int mode, int *errorCode));
260 static void FileWatchProc _ANSI_ARGS_((ClientData instanceData,
262 static void TcpAccept _ANSI_ARGS_((ClientData data, int mask));
263 static int TcpBlockModeProc _ANSI_ARGS_((ClientData data,
265 static int TcpCloseProc _ANSI_ARGS_((ClientData instanceData,
266 Tcl_Interp *interp));
267 static int TcpGetHandleProc _ANSI_ARGS_((ClientData instanceData,
268 int direction, ClientData *handlePtr));
269 static int TcpGetOptionProc _ANSI_ARGS_((ClientData instanceData,
270 Tcl_Interp *interp, CONST char *optionName,
271 Tcl_DString *dsPtr));
272 static int TcpInputProc _ANSI_ARGS_((ClientData instanceData,
273 char *buf, int toRead, int *errorCode));
274 static int TcpOutputProc _ANSI_ARGS_((ClientData instanceData,
275 CONST char *buf, int toWrite, int *errorCode));
276 static void TcpWatchProc _ANSI_ARGS_((ClientData instanceData,
279 static int TtyCloseProc _ANSI_ARGS_((ClientData instanceData,
280 Tcl_Interp *interp));
281 static void TtyGetAttributes _ANSI_ARGS_((int fd,
283 static int TtyGetOptionProc _ANSI_ARGS_((ClientData instanceData,
284 Tcl_Interp *interp, CONST char *optionName,
285 Tcl_DString *dsPtr));
286 static FileState * TtyInit _ANSI_ARGS_((int fd, int initialize));
288 static int TtyOutputProc _ANSI_ARGS_((ClientData instanceData,
289 CONST char *buf, int toWrite, int *errorCode));
290 #endif /* BAD_TIP35_FLUSH */
291 static int TtyParseMode _ANSI_ARGS_((Tcl_Interp *interp,
292 CONST char *mode, int *speedPtr, int *parityPtr,
293 int *dataPtr, int *stopPtr));
294 static void TtySetAttributes _ANSI_ARGS_((int fd,
296 static int TtySetOptionProc _ANSI_ARGS_((ClientData instanceData,
297 Tcl_Interp *interp, CONST char *optionName,
299 #endif /* SUPPORTS_TTY */
300 static int WaitForConnect _ANSI_ARGS_((TcpState *statePtr,
302 static Tcl_Channel MakeTcpClientChannelMode _ANSI_ARGS_(
303 (ClientData tcpSocket,
308 * This structure describes the channel type structure for file based IO:
311 static Tcl_ChannelType fileChannelType = {
312 "file", /* Type name. */
313 TCL_CHANNEL_VERSION_4, /* v4 channel */
314 FileCloseProc, /* Close proc. */
315 FileInputProc, /* Input proc. */
316 FileOutputProc, /* Output proc. */
317 FileSeekProc, /* Seek proc. */
318 NULL, /* Set option proc. */
319 NULL, /* Get option proc. */
320 FileWatchProc, /* Initialize notifier. */
321 FileGetHandleProc, /* Get OS handles out of channel. */
322 NULL, /* close2proc. */
323 FileBlockModeProc, /* Set blocking or non-blocking mode.*/
324 NULL, /* flush proc. */
325 NULL, /* handler proc. */
326 FileWideSeekProc, /* wide seek proc. */
328 FileThreadActionProc, /* thread actions */
336 * This structure describes the channel type structure for serial IO.
337 * Note that this type is a subclass of the "file" type.
340 static Tcl_ChannelType ttyChannelType = {
341 "tty", /* Type name. */
342 TCL_CHANNEL_VERSION_4, /* v4 channel */
343 TtyCloseProc, /* Close proc. */
344 FileInputProc, /* Input proc. */
346 TtyOutputProc, /* Output proc. */
347 #else /* !BAD_TIP35_FLUSH */
348 FileOutputProc, /* Output proc. */
349 #endif /* BAD_TIP35_FLUSH */
350 NULL, /* Seek proc. */
351 TtySetOptionProc, /* Set option proc. */
352 TtyGetOptionProc, /* Get option proc. */
353 FileWatchProc, /* Initialize notifier. */
354 FileGetHandleProc, /* Get OS handles out of channel. */
355 NULL, /* close2proc. */
356 FileBlockModeProc, /* Set blocking or non-blocking mode.*/
357 NULL, /* flush proc. */
358 NULL, /* handler proc. */
359 NULL, /* wide seek proc. */
360 NULL, /* thread action proc. */
362 #endif /* SUPPORTS_TTY */
365 * This structure describes the channel type structure for TCP socket
369 static Tcl_ChannelType tcpChannelType = {
370 "tcp", /* Type name. */
371 TCL_CHANNEL_VERSION_4, /* v4 channel */
372 TcpCloseProc, /* Close proc. */
373 TcpInputProc, /* Input proc. */
374 TcpOutputProc, /* Output proc. */
375 NULL, /* Seek proc. */
376 NULL, /* Set option proc. */
377 TcpGetOptionProc, /* Get option proc. */
378 TcpWatchProc, /* Initialize notifier. */
379 TcpGetHandleProc, /* Get OS handles out of channel. */
380 NULL, /* close2proc. */
381 TcpBlockModeProc, /* Set blocking or non-blocking mode.*/
382 NULL, /* flush proc. */
383 NULL, /* handler proc. */
384 NULL, /* wide seek proc. */
385 NULL, /* thread action proc. */
390 *----------------------------------------------------------------------
392 * FileBlockModeProc --
394 * Helper procedure to set blocking and nonblocking modes on a
395 * file based channel. Invoked by generic IO level code.
398 * 0 if successful, errno when failed.
401 * Sets the device into blocking or non-blocking mode.
403 *----------------------------------------------------------------------
408 FileBlockModeProc(instanceData, mode)
409 ClientData instanceData; /* File state. */
410 int mode; /* The mode to set. Can be one of
411 * TCL_MODE_BLOCKING or
412 * TCL_MODE_NONBLOCKING. */
414 FileState *fsPtr = (FileState *) instanceData;
418 curStatus = fcntl(fsPtr->fd, F_GETFL);
419 if (mode == TCL_MODE_BLOCKING) {
420 curStatus &= (~(O_NONBLOCK));
422 curStatus |= O_NONBLOCK;
424 if (fcntl(fsPtr->fd, F_SETFL, curStatus) < 0) {
427 curStatus = fcntl(fsPtr->fd, F_GETFL);
428 #else /* USE_FIONBIO */
429 if (mode == TCL_MODE_BLOCKING) {
434 if (ioctl(fsPtr->fd, (int) FIONBIO, &curStatus) < 0) {
437 #endif /* !USE_FIONBIO */
442 *----------------------------------------------------------------------
446 * This procedure is invoked from the generic IO level to read
447 * input from a file based channel.
450 * The number of bytes read is returned or -1 on error. An output
451 * argument contains a POSIX error code if an error occurs, or zero.
454 * Reads input from the input device of the channel.
456 *----------------------------------------------------------------------
460 FileInputProc(instanceData, buf, toRead, errorCodePtr)
461 ClientData instanceData; /* File state. */
462 char *buf; /* Where to store data read. */
463 int toRead; /* How much space is available
465 int *errorCodePtr; /* Where to store error code. */
467 FileState *fsPtr = (FileState *) instanceData;
468 int bytesRead; /* How many bytes were actually
469 * read from the input device? */
474 * Assume there is always enough input available. This will block
475 * appropriately, and read will unblock as soon as a short read is
476 * possible, if the channel is in blocking mode. If the channel is
477 * nonblocking, the read will never block.
480 bytesRead = read(fsPtr->fd, buf, (size_t) toRead);
481 if (bytesRead > -1) {
484 *errorCodePtr = errno;
489 *----------------------------------------------------------------------
493 * This procedure is invoked from the generic IO level to write
494 * output to a file channel.
497 * The number of bytes written is returned or -1 on error. An
498 * output argument contains a POSIX error code if an error occurred,
502 * Writes output on the output device of the channel.
504 *----------------------------------------------------------------------
508 FileOutputProc(instanceData, buf, toWrite, errorCodePtr)
509 ClientData instanceData; /* File state. */
510 CONST char *buf; /* The data buffer. */
511 int toWrite; /* How many bytes to write? */
512 int *errorCodePtr; /* Where to store error code. */
514 FileState *fsPtr = (FileState *) instanceData;
522 * Do not try to write nothing into a file. STREAM based
523 * implementations will considers this as EOF (if there is a
524 * pipe behind the file).
529 written = write(fsPtr->fd, buf, (size_t) toWrite);
533 *errorCodePtr = errno;
538 *----------------------------------------------------------------------
542 * This procedure is called from the generic IO level to perform
543 * channel-type-specific cleanup when a file based channel is closed.
546 * 0 if successful, errno if failed.
549 * Closes the device of the channel.
551 *----------------------------------------------------------------------
555 FileCloseProc(instanceData, interp)
556 ClientData instanceData; /* File state. */
557 Tcl_Interp *interp; /* For error reporting - unused. */
559 FileState *fsPtr = (FileState *) instanceData;
562 FileState **nextPtrPtr;
563 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
564 #endif /* DEPRECATED */
565 Tcl_DeleteFileHandler(fsPtr->fd);
568 * Do not close standard channels while in thread-exit.
571 if (!TclInThreadExit()
572 || ((fsPtr->fd != 0) && (fsPtr->fd != 1) && (fsPtr->fd != 2))) {
573 if (close(fsPtr->fd) < 0) {
577 ckfree((char *) fsPtr);
582 *----------------------------------------------------------------------
586 * This procedure is called by the generic IO level to move the
587 * access point in a file based channel.
590 * -1 if failed, the new position if successful. An output
591 * argument contains the POSIX error code if an error occurred,
595 * Moves the location at which the channel will be accessed in
598 *----------------------------------------------------------------------
602 FileSeekProc(instanceData, offset, mode, errorCodePtr)
603 ClientData instanceData; /* File state. */
604 long offset; /* Offset to seek to. */
605 int mode; /* Relative to where should we seek? Can be
606 * one of SEEK_START, SEEK_SET or SEEK_END. */
607 int *errorCodePtr; /* To store error code. */
609 FileState *fsPtr = (FileState *) instanceData;
610 Tcl_WideInt oldLoc, newLoc;
613 * Save our current place in case we need to roll-back the seek.
615 oldLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) 0, SEEK_CUR);
616 if (oldLoc == Tcl_LongAsWide(-1)) {
618 * Bad things are happening. Error out...
620 *errorCodePtr = errno;
624 newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode);
627 * Check for expressability in our return type, and roll-back otherwise.
629 if (newLoc > Tcl_LongAsWide(INT_MAX)) {
630 *errorCodePtr = EOVERFLOW;
631 TclOSseek(fsPtr->fd, (Tcl_SeekOffset) oldLoc, SEEK_SET);
634 *errorCodePtr = (newLoc == Tcl_LongAsWide(-1)) ? errno : 0;
636 return (int) Tcl_WideAsLong(newLoc);
640 *----------------------------------------------------------------------
642 * FileWideSeekProc --
644 * This procedure is called by the generic IO level to move the
645 * access point in a file based channel, with offsets expressed
649 * -1 if failed, the new position if successful. An output
650 * argument contains the POSIX error code if an error occurred,
654 * Moves the location at which the channel will be accessed in
657 *----------------------------------------------------------------------
661 FileWideSeekProc(instanceData, offset, mode, errorCodePtr)
662 ClientData instanceData; /* File state. */
663 Tcl_WideInt offset; /* Offset to seek to. */
664 int mode; /* Relative to where should we seek? Can be
665 * one of SEEK_START, SEEK_CUR or SEEK_END. */
666 int *errorCodePtr; /* To store error code. */
668 FileState *fsPtr = (FileState *) instanceData;
671 newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode);
673 *errorCodePtr = (newLoc == -1) ? errno : 0;
678 *----------------------------------------------------------------------
682 * Initialize the notifier to watch the fd from this channel.
688 * Sets up the notifier so that a future event on the channel will
691 *----------------------------------------------------------------------
695 FileWatchProc(instanceData, mask)
696 ClientData instanceData; /* The file state. */
697 int mask; /* Events of interest; an OR-ed
698 * combination of TCL_READABLE,
699 * TCL_WRITABLE and TCL_EXCEPTION. */
701 FileState *fsPtr = (FileState *) instanceData;
704 * Make sure we only register for events that are valid on this file.
705 * Note that we are passing Tcl_NotifyChannel directly to
706 * Tcl_CreateFileHandler with the channel pointer as the client data.
709 mask &= fsPtr->validMask;
711 Tcl_CreateFileHandler(fsPtr->fd, mask,
712 (Tcl_FileProc *) Tcl_NotifyChannel,
713 (ClientData) fsPtr->channel);
715 Tcl_DeleteFileHandler(fsPtr->fd);
720 *----------------------------------------------------------------------
722 * FileGetHandleProc --
724 * Called from Tcl_GetChannelHandle to retrieve OS handles from
725 * a file based channel.
728 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
729 * there is no handle for the specified direction.
734 *----------------------------------------------------------------------
738 FileGetHandleProc(instanceData, direction, handlePtr)
739 ClientData instanceData; /* The file state. */
740 int direction; /* TCL_READABLE or TCL_WRITABLE */
741 ClientData *handlePtr; /* Where to store the handle. */
743 FileState *fsPtr = (FileState *) instanceData;
745 if (direction & fsPtr->validMask) {
746 *handlePtr = (ClientData) fsPtr->fd;
756 *----------------------------------------------------------------------
760 * This procedure is called from the generic IO level to perform
761 * channel-type-specific cleanup when a tty based channel is closed.
764 * 0 if successful, errno if failed.
767 * Closes the device of the channel.
769 *----------------------------------------------------------------------
772 TtyCloseProc(instanceData, interp)
773 ClientData instanceData; /* Tty state. */
774 Tcl_Interp *interp; /* For error reporting - unused. */
777 TtyState *ttyPtr = (TtyState *) instanceData;
778 #endif /* BAD_TIP35_FLUSH */
780 TTYFLUSH(ttyPtr->fs.fd);
781 #endif /* TTYFLUSH */
784 * TIP#35 agreed to remove the unsave so that TCL could be used as a
786 * It would be cleaner to remove all the stuff related to
787 * TtyState.stateUpdated
788 * TtyState.savedState
789 * Then the structure TtyState would be the same as FileState.
790 * IMO this cleanup could better be done for the final 8.4 release
791 * after nobody complained about the missing unsave. -- schroedter
793 if (ttyPtr->stateUpdated) {
794 SETIOSTATE(ttyPtr->fs.fd, &ttyPtr->savedState);
797 return FileCloseProc(instanceData, interp);
801 *----------------------------------------------------------------------
805 * This procedure is invoked from the generic IO level to write
806 * output to a TTY channel.
809 * The number of bytes written is returned or -1 on error. An
810 * output argument contains a POSIX error code if an error occurred,
814 * Writes output on the output device of the channel
815 * if the channel is not designated to be closed.
817 *----------------------------------------------------------------------
822 TtyOutputProc(instanceData, buf, toWrite, errorCodePtr)
823 ClientData instanceData; /* File state. */
824 CONST char *buf; /* The data buffer. */
825 int toWrite; /* How many bytes to write? */
826 int *errorCodePtr; /* Where to store error code. */
830 * Do not write data during Tcl exit.
831 * Serial port may block preventing Tcl from exit.
835 return FileOutputProc(instanceData, buf, toWrite, errorCodePtr);
838 #endif /* BAD_TIP35_FLUSH */
842 *----------------------------------------------------------------------
844 * TtyModemStatusStr --
846 * Converts a RS232 modem status list of readable flags
848 *----------------------------------------------------------------------
851 TtyModemStatusStr(status, dsPtr)
852 int status; /* RS232 modem status */
853 Tcl_DString *dsPtr; /* Where to store string */
856 Tcl_DStringAppendElement(dsPtr, "CTS");
857 Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CTS) ? "1" : "0");
858 #endif /* TIOCM_CTS */
860 Tcl_DStringAppendElement(dsPtr, "DSR");
861 Tcl_DStringAppendElement(dsPtr, (status & TIOCM_DSR) ? "1" : "0");
862 #endif /* TIOCM_DSR */
864 Tcl_DStringAppendElement(dsPtr, "RING");
865 Tcl_DStringAppendElement(dsPtr, (status & TIOCM_RNG) ? "1" : "0");
866 #endif /* TIOCM_RNG */
868 Tcl_DStringAppendElement(dsPtr, "DCD");
869 Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CD) ? "1" : "0");
870 #endif /* TIOCM_CD */
872 #endif /* USE_TERMIOS */
875 *----------------------------------------------------------------------
877 * TtySetOptionProc --
879 * Sets an option on a channel.
882 * A standard Tcl result. Also sets the interp's result on error if
883 * interp is not NULL.
886 * May modify an option on a device.
887 * Sets Error message if needed (by calling Tcl_BadChannelOption).
889 *----------------------------------------------------------------------
893 TtySetOptionProc(instanceData, interp, optionName, value)
894 ClientData instanceData; /* File state. */
895 Tcl_Interp *interp; /* For error reporting - can be NULL. */
896 CONST char *optionName; /* Which option to set? */
897 CONST char *value; /* New value for option. */
899 FileState *fsPtr = (FileState *) instanceData;
900 unsigned int len, vlen;
903 int flag, control, argc;
906 #endif /* USE_TERMIOS */
908 len = strlen(optionName);
909 vlen = strlen(value);
912 * Option -mode baud,parity,databits,stopbits
914 if ((len > 2) && (strncmp(optionName, "-mode", len) == 0)) {
915 if (TtyParseMode(interp, value, &tty.baud, &tty.parity, &tty.data,
916 &tty.stop) != TCL_OK) {
920 * system calls results should be checked there. -- dl
923 TtySetAttributes(fsPtr->fd, &tty);
924 ((TtyState *) fsPtr)->stateUpdated = 1;
931 * Option -handshake none|xonxoff|rtscts|dtrdsr
933 if ((len > 1) && (strncmp(optionName, "-handshake", len) == 0)) {
935 * Reset all handshake options
936 * DTR and RTS are ON by default
938 GETIOSTATE(fsPtr->fd, &iostate);
939 iostate.c_iflag &= ~(IXON | IXOFF | IXANY);
941 iostate.c_cflag &= ~CRTSCTS;
943 if (strncasecmp(value, "NONE", vlen) == 0) {
944 /* leave all handshake options disabled */
945 } else if (strncasecmp(value, "XONXOFF", vlen) == 0) {
946 iostate.c_iflag |= (IXON | IXOFF | IXANY);
947 } else if (strncasecmp(value, "RTSCTS", vlen) == 0) {
949 iostate.c_cflag |= CRTSCTS;
951 UNSUPPORTED_OPTION("-handshake RTSCTS");
954 } else if (strncasecmp(value, "DTRDSR", vlen) == 0) {
955 UNSUPPORTED_OPTION("-handshake DTRDSR");
959 Tcl_AppendResult(interp, "bad value for -handshake: ",
960 "must be one of xonxoff, rtscts, dtrdsr or none",
965 SETIOSTATE(fsPtr->fd, &iostate);
970 * Option -xchar {\x11 \x13}
972 if ((len > 1) && (strncmp(optionName, "-xchar", len) == 0)) {
973 GETIOSTATE(fsPtr->fd, &iostate);
974 if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
978 iostate.c_cc[VSTART] = argv[0][0];
979 iostate.c_cc[VSTOP] = argv[1][0];
982 Tcl_AppendResult(interp,
983 "bad value for -xchar: should be a list of two elements",
986 ckfree((char *) argv);
989 SETIOSTATE(fsPtr->fd, &iostate);
990 ckfree((char *) argv);
995 * Option -timeout msec
997 if ((len > 2) && (strncmp(optionName, "-timeout", len) == 0)) {
1000 GETIOSTATE(fsPtr->fd, &iostate);
1001 if (Tcl_GetInt(interp, value, &msec) != TCL_OK) {
1004 iostate.c_cc[VMIN] = 0;
1005 iostate.c_cc[VTIME] = (msec == 0) ? 0 : (msec < 100) ? 1 : (msec+50)/100;
1006 SETIOSTATE(fsPtr->fd, &iostate);
1011 * Option -ttycontrol {DTR 1 RTS 0 BREAK 0}
1013 if ((len > 4) && (strncmp(optionName, "-ttycontrol", len) == 0)) {
1015 if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
1018 if ((argc % 2) == 1) {
1020 Tcl_AppendResult(interp,
1021 "bad value for -ttycontrol: should be a list of",
1022 "signal,value pairs", (char *) NULL);
1024 ckfree((char *) argv);
1028 GETCONTROL(fsPtr->fd, &control);
1029 for (i = 0; i < argc-1; i += 2) {
1030 if (Tcl_GetBoolean(interp, argv[i+1], &flag) == TCL_ERROR) {
1031 ckfree((char *) argv);
1034 if (strncasecmp(argv[i], "DTR", strlen(argv[i])) == 0) {
1037 control |= TIOCM_DTR;
1039 control &= ~TIOCM_DTR;
1041 #else /* !TIOCM_DTR */
1042 UNSUPPORTED_OPTION("-ttycontrol DTR");
1043 ckfree((char *) argv);
1045 #endif /* TIOCM_DTR */
1046 } else if (strncasecmp(argv[i], "RTS", strlen(argv[i])) == 0) {
1049 control |= TIOCM_RTS;
1051 control &= ~TIOCM_RTS;
1053 #else /* !TIOCM_RTS*/
1054 UNSUPPORTED_OPTION("-ttycontrol RTS");
1055 ckfree((char *) argv);
1057 #endif /* TIOCM_RTS*/
1058 } else if (strncasecmp(argv[i], "BREAK", strlen(argv[i])) == 0) {
1060 SETBREAK(fsPtr->fd, flag);
1061 #else /* !SETBREAK */
1062 UNSUPPORTED_OPTION("-ttycontrol BREAK");
1063 ckfree((char *) argv);
1065 #endif /* SETBREAK */
1068 Tcl_AppendResult(interp, "bad signal \"", argv[i],
1069 "\" for -ttycontrol: must be ",
1070 "DTR, RTS or BREAK", (char *) NULL);
1072 ckfree((char *) argv);
1075 } /* -ttycontrol options loop */
1077 SETCONTROL(fsPtr->fd, &control);
1078 ckfree((char *) argv);
1082 return Tcl_BadChannelOption(interp, optionName,
1083 "mode handshake timeout ttycontrol xchar ");
1085 #else /* !USE_TERMIOS */
1086 return Tcl_BadChannelOption(interp, optionName, "mode");
1087 #endif /* USE_TERMIOS */
1091 *----------------------------------------------------------------------
1093 * TtyGetOptionProc --
1095 * Gets a mode associated with an IO channel. If the optionName arg
1096 * is non NULL, retrieves the value of that option. If the optionName
1097 * arg is NULL, retrieves a list of alternating option names and
1098 * values for the given channel.
1101 * A standard Tcl result. Also sets the supplied DString to the
1102 * string value of the option(s) returned.
1105 * The string returned by this function is in static storage and
1106 * may be reused at any time subsequent to the call.
1107 * Sets Error message if needed (by calling Tcl_BadChannelOption).
1109 *----------------------------------------------------------------------
1113 TtyGetOptionProc(instanceData, interp, optionName, dsPtr)
1114 ClientData instanceData; /* File state. */
1115 Tcl_Interp *interp; /* For error reporting - can be NULL. */
1116 CONST char *optionName; /* Option to get. */
1117 Tcl_DString *dsPtr; /* Where to store value(s). */
1119 FileState *fsPtr = (FileState *) instanceData;
1121 char buf[3 * TCL_INTEGER_SPACE + 16];
1123 int valid = 0; /* flag if valid option parsed */
1125 if (optionName == NULL) {
1128 len = strlen(optionName);
1131 Tcl_DStringAppendElement(dsPtr, "-mode");
1133 if (len==0 || (len>2 && strncmp(optionName, "-mode", len)==0)) {
1135 TtyGetAttributes(fsPtr->fd, &tty);
1136 sprintf(buf, "%d,%c,%d,%d", tty.baud, tty.parity, tty.data, tty.stop);
1137 Tcl_DStringAppendElement(dsPtr, buf);
1145 Tcl_DStringAppendElement(dsPtr, "-xchar");
1146 Tcl_DStringStartSublist(dsPtr);
1148 if (len==0 || (len>1 && strncmp(optionName, "-xchar", len)==0)) {
1152 GETIOSTATE(fsPtr->fd, &iostate);
1153 sprintf(buf, "%c", iostate.c_cc[VSTART]);
1154 Tcl_DStringAppendElement(dsPtr, buf);
1155 sprintf(buf, "%c", iostate.c_cc[VSTOP]);
1156 Tcl_DStringAppendElement(dsPtr, buf);
1159 Tcl_DStringEndSublist(dsPtr);
1164 * option is readonly and returned by [fconfigure chan -queue]
1165 * but not returned by unnamed [fconfigure chan]
1167 if ((len > 1) && (strncmp(optionName, "-queue", len) == 0)) {
1168 int inQueue=0, outQueue=0;
1169 int inBuffered, outBuffered;
1172 GETREADQUEUE(fsPtr->fd, inQueue);
1173 #endif /* GETREADQUEUE */
1174 #ifdef GETWRITEQUEUE
1175 GETWRITEQUEUE(fsPtr->fd, outQueue);
1176 #endif /* GETWRITEQUEUE */
1177 inBuffered = Tcl_InputBuffered(fsPtr->channel);
1178 outBuffered = Tcl_OutputBuffered(fsPtr->channel);
1180 sprintf(buf, "%d", inBuffered+inQueue);
1181 Tcl_DStringAppendElement(dsPtr, buf);
1182 sprintf(buf, "%d", outBuffered+outQueue);
1183 Tcl_DStringAppendElement(dsPtr, buf);
1187 * get option -ttystatus
1188 * option is readonly and returned by [fconfigure chan -ttystatus]
1189 * but not returned by unnamed [fconfigure chan]
1191 if ((len > 4) && (strncmp(optionName, "-ttystatus", len) == 0)) {
1194 GETCONTROL(fsPtr->fd, &status);
1195 TtyModemStatusStr(status, dsPtr);
1197 #endif /* USE_TERMIOS */
1202 return Tcl_BadChannelOption(interp, optionName,
1204 "mode queue ttystatus xchar");
1205 #else /* !USE_TERMIOS */
1207 #endif /* USE_TERMIOS */
1213 # if (B4800 == 4800)
1214 # define DIRECT_BAUD
1215 # endif /* B4800 == 4800 */
1219 # define TtyGetSpeed(baud) ((unsigned) (baud))
1220 # define TtyGetBaud(speed) ((int) (speed))
1221 #else /* !DIRECT_BAUD */
1223 static struct {int baud; unsigned long speed;} speeds[] = {
1315 *---------------------------------------------------------------------------
1319 * Given a baud rate, get the mask value that should be stored in
1320 * the termios, termio, or sgttyb structure in order to select that
1329 *---------------------------------------------------------------------------
1332 static unsigned long
1334 int baud; /* The baud rate to look up. */
1336 int bestIdx, bestDiff, i, diff;
1342 * If the baud rate does not correspond to one of the known mask values,
1343 * choose the mask value whose baud rate is closest to the specified
1347 for (i = 0; speeds[i].baud >= 0; i++) {
1348 diff = speeds[i].baud - baud;
1352 if (diff < bestDiff) {
1357 return speeds[bestIdx].speed;
1361 *---------------------------------------------------------------------------
1365 * Given a speed mask value from a termios, termio, or sgttyb
1366 * structure, get the baus rate that corresponds to that mask value.
1369 * As above. If the mask value was not recognized, 0 is returned.
1374 *---------------------------------------------------------------------------
1379 unsigned long speed; /* Speed mask value to look up. */
1383 for (i = 0; speeds[i].baud >= 0; i++) {
1384 if (speeds[i].speed == speed) {
1385 return speeds[i].baud;
1391 #endif /* !DIRECT_BAUD */
1395 *---------------------------------------------------------------------------
1397 * TtyGetAttributes --
1399 * Get the current attributes of the specified serial device.
1407 *---------------------------------------------------------------------------
1411 TtyGetAttributes(fd, ttyPtr)
1412 int fd; /* Open file descriptor for serial port to
1414 TtyAttrs *ttyPtr; /* Buffer filled with serial port
1418 int baud, parity, data, stop;
1420 GETIOSTATE(fd, &iostate);
1423 baud = TtyGetBaud(cfgetospeed(&iostate));
1427 switch ((int) (iostate.c_cflag & (PARENB | PARODD | PAREXT))) {
1428 case PARENB : parity = 'e'; break;
1429 case PARENB | PARODD : parity = 'o'; break;
1430 case PARENB | PAREXT : parity = 's'; break;
1431 case PARENB | PARODD | PAREXT : parity = 'm'; break;
1434 switch ((int) (iostate.c_cflag & (PARENB | PARODD))) {
1435 case PARENB : parity = 'e'; break;
1436 case PARENB | PARODD : parity = 'o'; break;
1438 #endif /* !PAREXT */
1440 data = iostate.c_cflag & CSIZE;
1441 data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8;
1443 stop = (iostate.c_cflag & CSTOPB) ? 2 : 1;
1444 #endif /* USE_TERMIOS */
1447 baud = TtyGetBaud(iostate.c_cflag & CBAUD);
1450 switch (iostate.c_cflag & (PARENB | PARODD | PAREXT)) {
1451 case PARENB : parity = 'e'; break;
1452 case PARENB | PARODD : parity = 'o'; break;
1453 case PARENB | PAREXT : parity = 's'; break;
1454 case PARENB | PARODD | PAREXT : parity = 'm'; break;
1457 data = iostate.c_cflag & CSIZE;
1458 data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8;
1460 stop = (iostate.c_cflag & CSTOPB) ? 2 : 1;
1461 #endif /* USE_TERMIO */
1464 baud = TtyGetBaud(iostate.sg_ospeed);
1467 if (iostate.sg_flags & EVENP) {
1469 } else if (iostate.sg_flags & ODDP) {
1473 data = (iostate.sg_flags & (EVENP | ODDP)) ? 7 : 8;
1476 #endif /* USE_SGTTY */
1478 ttyPtr->baud = baud;
1479 ttyPtr->parity = parity;
1480 ttyPtr->data = data;
1481 ttyPtr->stop = stop;
1485 *---------------------------------------------------------------------------
1487 * TtySetAttributes --
1489 * Set the current attributes of the specified serial device.
1497 *---------------------------------------------------------------------------
1501 TtySetAttributes(fd, ttyPtr)
1502 int fd; /* Open file descriptor for serial port to
1504 TtyAttrs *ttyPtr; /* Buffer containing new attributes for
1510 int parity, data, flag;
1512 GETIOSTATE(fd, &iostate);
1513 cfsetospeed(&iostate, TtyGetSpeed(ttyPtr->baud));
1514 cfsetispeed(&iostate, TtyGetSpeed(ttyPtr->baud));
1517 parity = ttyPtr->parity;
1518 if (parity != 'n') {
1521 iostate.c_cflag &= ~PAREXT;
1522 if ((parity == 'm') || (parity == 's')) {
1526 if ((parity == 'm') || (parity == 'o')) {
1530 data = ttyPtr->data;
1531 flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8;
1532 if (ttyPtr->stop == 2) {
1536 iostate.c_cflag &= ~(PARENB | PARODD | CSIZE | CSTOPB);
1537 iostate.c_cflag |= flag;
1539 #endif /* USE_TERMIOS */
1542 int parity, data, flag;
1544 GETIOSTATE(fd, &iostate);
1545 iostate.c_cflag &= ~CBAUD;
1546 iostate.c_cflag |= TtyGetSpeed(ttyPtr->baud);
1549 parity = ttyPtr->parity;
1550 if (parity != 'n') {
1552 if ((parity == 'm') || (parity == 's')) {
1555 if ((parity == 'm') || (parity == 'o')) {
1559 data = ttyPtr->data;
1560 flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8;
1561 if (ttyPtr->stop == 2) {
1565 iostate.c_cflag &= ~(PARENB | PARODD | PAREXT | CSIZE | CSTOPB);
1566 iostate.c_cflag |= flag;
1568 #endif /* USE_TERMIO */
1573 GETIOSTATE(fd, &iostate);
1574 iostate.sg_ospeed = TtyGetSpeed(ttyPtr->baud);
1575 iostate.sg_ispeed = TtyGetSpeed(ttyPtr->baud);
1577 parity = ttyPtr->parity;
1578 if (parity == 'e') {
1579 iostate.sg_flags &= ~ODDP;
1580 iostate.sg_flags |= EVENP;
1581 } else if (parity == 'o') {
1582 iostate.sg_flags &= ~EVENP;
1583 iostate.sg_flags |= ODDP;
1585 #endif /* USE_SGTTY */
1587 SETIOSTATE(fd, &iostate);
1591 *---------------------------------------------------------------------------
1595 * Parse the "-mode" argument to the fconfigure command. The argument
1596 * is of the form baud,parity,data,stop.
1599 * The return value is TCL_OK if the argument was successfully
1600 * parsed, TCL_ERROR otherwise. If TCL_ERROR is returned, an
1601 * error message is left in the interp's result (if interp is non-NULL).
1606 *---------------------------------------------------------------------------
1610 TtyParseMode(interp, mode, speedPtr, parityPtr, dataPtr, stopPtr)
1611 Tcl_Interp *interp; /* If non-NULL, interp for error return. */
1612 CONST char *mode; /* Mode string to be parsed. */
1613 int *speedPtr; /* Filled with baud rate from mode string. */
1614 int *parityPtr; /* Filled with parity from mode string. */
1615 int *dataPtr; /* Filled with data bits from mode string. */
1616 int *stopPtr; /* Filled with stop bits from mode string. */
1620 static char *bad = "bad value for -mode";
1622 i = sscanf(mode, "%d,%c,%d,%d%n", speedPtr, &parity, dataPtr,
1624 if ((i != 4) || (mode[end] != '\0')) {
1625 if (interp != NULL) {
1626 Tcl_AppendResult(interp, bad, ": should be baud,parity,data,stop",
1632 * Only allow setting mark/space parity on platforms that support it
1633 * Make sure to allow for the case where strchr is a macro.
1637 #if defined(PAREXT) || defined(USE_TERMIO)
1638 strchr("noems", parity) == NULL
1640 strchr("noe", parity) == NULL
1641 #endif /* PAREXT|USE_TERMIO */
1643 if (interp != NULL) {
1644 Tcl_AppendResult(interp, bad,
1645 #if defined(PAREXT) || defined(USE_TERMIO)
1646 " parity: should be n, o, e, m, or s",
1648 " parity: should be n, o, or e",
1649 #endif /* PAREXT|USE_TERMIO */
1654 *parityPtr = parity;
1655 if ((*dataPtr < 5) || (*dataPtr > 8)) {
1656 if (interp != NULL) {
1657 Tcl_AppendResult(interp, bad, " data: should be 5, 6, 7, or 8",
1662 if ((*stopPtr < 0) || (*stopPtr > 2)) {
1663 if (interp != NULL) {
1664 Tcl_AppendResult(interp, bad, " stop: should be 1 or 2", NULL);
1672 *---------------------------------------------------------------------------
1676 * Given file descriptor that refers to a serial port,
1677 * initialize the serial port to a set of sane values so that
1678 * Tcl can talk to a device located on the serial port.
1679 * Note that no initialization happens if the initialize flag
1680 * is not set; this is necessary for the correct handling of
1681 * UNIX console TTYs at startup.
1684 * A pointer to a FileState suitable for use with Tcl_CreateChannel
1685 * and the ttyChannelType structure.
1688 * Serial device initialized to non-blocking raw mode, similar to
1689 * sockets (if initialize flag is non-zero.) All other modes can
1690 * be simulated on top of this in Tcl.
1692 *---------------------------------------------------------------------------
1696 TtyInit(fd, initialize)
1697 int fd; /* Open file descriptor for serial port to
1698 * be initialized. */
1703 ttyPtr = (TtyState *) ckalloc((unsigned) sizeof(TtyState));
1704 GETIOSTATE(fd, &ttyPtr->savedState);
1705 ttyPtr->stateUpdated = 0;
1707 IOSTATE iostate = ttyPtr->savedState;
1709 #if defined(USE_TERMIOS) || defined(USE_TERMIO)
1710 if (iostate.c_iflag != IGNBRK ||
1711 iostate.c_oflag != 0 ||
1712 iostate.c_lflag != 0 ||
1713 iostate.c_cflag & CREAD ||
1714 iostate.c_cc[VMIN] != 1 ||
1715 iostate.c_cc[VTIME] != 0) {
1716 ttyPtr->stateUpdated = 1;
1718 iostate.c_iflag = IGNBRK;
1719 iostate.c_oflag = 0;
1720 iostate.c_lflag = 0;
1721 iostate.c_cflag |= CREAD;
1722 iostate.c_cc[VMIN] = 1;
1723 iostate.c_cc[VTIME] = 0;
1724 #endif /* USE_TERMIOS|USE_TERMIO */
1727 if ((iostate.sg_flags & (EVENP | ODDP)) ||
1728 !(iostate.sg_flags & RAW)) {
1729 ttyPtr->stateUpdated = 1;
1731 iostate.sg_flags &= (EVENP | ODDP);
1732 iostate.sg_flags |= RAW;
1733 #endif /* USE_SGTTY */
1736 * Only update if we're changing anything to avoid possible
1739 if (ttyPtr->stateUpdated) {
1740 SETIOSTATE(fd, &iostate);
1746 #endif /* SUPPORTS_TTY */
1749 *----------------------------------------------------------------------
1751 * TclpOpenFileChannel --
1753 * Open an file based channel on Unix systems.
1756 * The new channel or NULL. If NULL, the output argument
1757 * errorCodePtr is set to a POSIX error and an error message is
1758 * left in the interp's result if interp is not NULL.
1761 * May open the channel and may cause creation of a file on the
1764 *----------------------------------------------------------------------
1768 TclpOpenFileChannel(interp, pathPtr, mode, permissions)
1769 Tcl_Interp *interp; /* Interpreter for error reporting;
1771 Tcl_Obj *pathPtr; /* Name of file to open. */
1772 int mode; /* POSIX open mode. */
1773 int permissions; /* If the open involves creating a
1774 * file, with what modes to create
1777 int fd, channelPermissions;
1779 CONST char *native, *translation;
1780 char channelName[16 + TCL_INTEGER_SPACE];
1781 Tcl_ChannelType *channelTypePtr;
1784 #endif /* SUPPORTS_TTY */
1786 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1787 #endif /* DEPRECATED */
1789 switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
1791 channelPermissions = TCL_READABLE;
1794 channelPermissions = TCL_WRITABLE;
1797 channelPermissions = (TCL_READABLE | TCL_WRITABLE);
1801 * This may occurr if modeString was "", for example.
1803 panic("TclpOpenFileChannel: invalid mode value");
1807 native = Tcl_FSGetNativePath(pathPtr);
1808 if (native == NULL) {
1811 fd = TclOSopen(native, mode, permissions);
1813 ctl_tty = (strcmp (native, "/dev/tty") == 0);
1814 #endif /* SUPPORTS_TTY */
1817 if (interp != (Tcl_Interp *) NULL) {
1818 Tcl_AppendResult(interp, "couldn't open \"",
1819 Tcl_GetString(pathPtr), "\": ",
1820 Tcl_PosixError(interp), (char *) NULL);
1826 * Set close-on-exec flag on the fd so that child processes will not
1830 fcntl(fd, F_SETFD, FD_CLOEXEC);
1832 sprintf(channelName, "file%d", fd);
1835 if (!ctl_tty && isatty(fd)) {
1837 * Initialize the serial port to a set of sane parameters.
1838 * Especially important if the remote device is set to echo and
1839 * the serial port driver was also set to echo -- as soon as a char
1840 * were sent to the serial port, the remote device would echo it,
1841 * then the serial driver would echo it back to the device, etc.
1844 translation = "auto crlf";
1845 channelTypePtr = &ttyChannelType;
1846 fsPtr = TtyInit(fd, 1);
1848 #endif /* SUPPORTS_TTY */
1851 channelTypePtr = &fileChannelType;
1852 fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState));
1856 if (channelTypePtr == &fileChannelType) {
1857 /* TIP #218. Removed the code inserting the new structure
1858 * into the global list. This is now handled in the thread
1859 * action callbacks, and only there.
1861 fsPtr->nextPtr = NULL;
1863 #endif /* DEPRECATED */
1864 fsPtr->validMask = channelPermissions | TCL_EXCEPTION;
1867 fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName,
1868 (ClientData) fsPtr, channelPermissions);
1870 if (translation != NULL) {
1872 * Gotcha. Most modems need a "\r" at the end of the command
1873 * sequence. If you just send "at\n", the modem will not respond
1874 * with "OK" because it never got a "\r" to actually invoke the
1875 * command. So, by default, newlines are translated to "\r\n" on
1876 * output to avoid "bug" reports that the serial port isn't working.
1879 if (Tcl_SetChannelOption(interp, fsPtr->channel, "-translation",
1880 translation) != TCL_OK) {
1881 Tcl_Close(NULL, fsPtr->channel);
1886 return fsPtr->channel;
1890 *----------------------------------------------------------------------
1892 * Tcl_MakeFileChannel --
1894 * Makes a Tcl_Channel from an existing OS level file handle.
1897 * The Tcl_Channel created around the preexisting OS level file handle.
1902 *----------------------------------------------------------------------
1905 EXPORT_C Tcl_Channel
1906 Tcl_MakeFileChannel(handle, mode)
1907 ClientData handle; /* OS level handle. */
1908 int mode; /* ORed combination of TCL_READABLE and
1909 * TCL_WRITABLE to indicate file mode. */
1912 char channelName[16 + TCL_INTEGER_SPACE];
1913 int fd = (int) handle;
1914 Tcl_ChannelType *channelTypePtr;
1916 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1917 #endif /* DEPRECATED */
1918 struct sockaddr sockaddr;
1919 socklen_t sockaddrLen = sizeof(sockaddr);
1927 * Look to see if a channel with this fd and the same mode already exists.
1928 * If the fd is used, but the mode doesn't match, return NULL.
1932 for (fsPtr = tsdPtr->firstFilePtr; fsPtr != NULL; fsPtr = fsPtr->nextPtr) {
1933 if (fsPtr->fd == fd) {
1934 return ((mode|TCL_EXCEPTION) == fsPtr->validMask) ?
1935 fsPtr->channel : NULL;
1938 #endif /* DEPRECATED */
1940 sockaddr.sa_family = AF_UNSPEC;
1944 fsPtr = TtyInit(fd, 0);
1945 channelTypePtr = &ttyChannelType;
1946 sprintf(channelName, "serial%d", fd);
1948 #endif /* SUPPORTS_TTY */
1949 if (getsockname(fd, (struct sockaddr *)&sockaddr, &sockaddrLen) == 0
1951 && sockaddr.sa_family == AF_INET) {
1952 return MakeTcpClientChannelMode((ClientData) fd, mode);
1954 channelTypePtr = &fileChannelType;
1955 fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState));
1956 sprintf(channelName, "file%d", fd);
1960 if (channelTypePtr == &fileChannelType) {
1961 fsPtr->nextPtr = tsdPtr->firstFilePtr;
1962 tsdPtr->firstFilePtr = fsPtr;
1964 #endif /* DEPRECATED */
1966 fsPtr->validMask = mode | TCL_EXCEPTION;
1967 fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName,
1968 (ClientData) fsPtr, mode);
1970 return fsPtr->channel;
1974 *----------------------------------------------------------------------
1976 * TcpBlockModeProc --
1978 * This procedure is invoked by the generic IO level to set blocking
1979 * and nonblocking mode on a TCP socket based channel.
1982 * 0 if successful, errno when failed.
1985 * Sets the device into blocking or nonblocking mode.
1987 *----------------------------------------------------------------------
1992 TcpBlockModeProc(instanceData, mode)
1993 ClientData instanceData; /* Socket state. */
1994 int mode; /* The mode to set. Can be one of
1995 * TCL_MODE_BLOCKING or
1996 * TCL_MODE_NONBLOCKING. */
1998 TcpState *statePtr = (TcpState *) instanceData;
2002 setting = fcntl(statePtr->fd, F_GETFL);
2003 if (mode == TCL_MODE_BLOCKING) {
2004 statePtr->flags &= (~(TCP_ASYNC_SOCKET));
2005 setting &= (~(O_NONBLOCK));
2007 statePtr->flags |= TCP_ASYNC_SOCKET;
2008 setting |= O_NONBLOCK;
2010 if (fcntl(statePtr->fd, F_SETFL, setting) < 0) {
2013 #else /* USE_FIONBIO */
2014 if (mode == TCL_MODE_BLOCKING) {
2015 statePtr->flags &= (~(TCP_ASYNC_SOCKET));
2017 if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) {
2021 statePtr->flags |= TCP_ASYNC_SOCKET;
2023 if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) {
2027 #endif /* !USE_FIONBIO */
2033 *----------------------------------------------------------------------
2037 * Waits for a connection on an asynchronously opened socket to
2044 * The socket is connected after this function returns.
2046 *----------------------------------------------------------------------
2050 WaitForConnect(statePtr, errorCodePtr)
2051 TcpState *statePtr; /* State of the socket. */
2052 int *errorCodePtr; /* Where to store errors? */
2054 int timeOut; /* How long to wait. */
2055 int state; /* Of calling TclWaitForFile. */
2056 int flags; /* fcntl flags for the socket. */
2059 * If an asynchronous connect is in progress, attempt to wait for it
2060 * to complete before reading.
2063 if (statePtr->flags & TCP_ASYNC_CONNECT) {
2064 if (statePtr->flags & TCP_ASYNC_SOCKET) {
2070 state = TclUnixWaitForFile(statePtr->fd,
2071 TCL_WRITABLE | TCL_EXCEPTION, timeOut);
2072 if (!(statePtr->flags & TCP_ASYNC_SOCKET)) {
2074 flags = fcntl(statePtr->fd, F_GETFL);
2075 flags &= (~(O_NONBLOCK));
2076 (void) fcntl(statePtr->fd, F_SETFL, flags);
2077 #else /* USE_FIONBIO */
2079 (void) ioctl(statePtr->fd, FIONBIO, &flags);
2080 #endif /* !USE_FIONBIO */
2082 if (state & TCL_EXCEPTION) {
2085 if (state & TCL_WRITABLE) {
2086 statePtr->flags &= (~(TCP_ASYNC_CONNECT));
2087 } else if (timeOut == 0) {
2088 *errorCodePtr = errno = EWOULDBLOCK;
2096 *----------------------------------------------------------------------
2100 * This procedure is invoked by the generic IO level to read input
2101 * from a TCP socket based channel.
2103 * NOTE: We cannot share code with FilePipeInputProc because here
2104 * we must use recv to obtain the input from the channel, not read.
2107 * The number of bytes read is returned or -1 on error. An output
2108 * argument contains the POSIX error code on error, or zero if no
2112 * Reads input from the input device of the channel.
2114 *----------------------------------------------------------------------
2119 TcpInputProc(instanceData, buf, bufSize, errorCodePtr)
2120 ClientData instanceData; /* Socket state. */
2121 char *buf; /* Where to store data read. */
2122 int bufSize; /* How much space is available
2124 int *errorCodePtr; /* Where to store error code. */
2126 TcpState *statePtr = (TcpState *) instanceData;
2127 int bytesRead, state;
2130 state = WaitForConnect(statePtr, errorCodePtr);
2134 bytesRead = recv(statePtr->fd, buf, (size_t) bufSize, 0);
2135 if (bytesRead > -1) {
2138 if (errno == ECONNRESET) {
2140 * Turn ECONNRESET into a soft EOF condition.
2145 *errorCodePtr = errno;
2150 *----------------------------------------------------------------------
2154 * This procedure is invoked by the generic IO level to write output
2155 * to a TCP socket based channel.
2157 * NOTE: We cannot share code with FilePipeOutputProc because here
2158 * we must use send, not write, to get reliable error reporting.
2161 * The number of bytes written is returned. An output argument is
2162 * set to a POSIX error code if an error occurred, or zero.
2165 * Writes output on the output device of the channel.
2167 *----------------------------------------------------------------------
2171 TcpOutputProc(instanceData, buf, toWrite, errorCodePtr)
2172 ClientData instanceData; /* Socket state. */
2173 CONST char *buf; /* The data buffer. */
2174 int toWrite; /* How many bytes to write? */
2175 int *errorCodePtr; /* Where to store error code. */
2177 TcpState *statePtr = (TcpState *) instanceData;
2179 int state; /* Of waiting for connection. */
2182 state = WaitForConnect(statePtr, errorCodePtr);
2186 written = send(statePtr->fd, buf, (size_t) toWrite, 0);
2190 *errorCodePtr = errno;
2195 *----------------------------------------------------------------------
2199 * This procedure is invoked by the generic IO level to perform
2200 * channel-type-specific cleanup when a TCP socket based channel
2204 * 0 if successful, the value of errno if failed.
2207 * Closes the socket of the channel.
2209 *----------------------------------------------------------------------
2214 TcpCloseProc(instanceData, interp)
2215 ClientData instanceData; /* The socket to close. */
2216 Tcl_Interp *interp; /* For error reporting - unused. */
2218 TcpState *statePtr = (TcpState *) instanceData;
2222 * Delete a file handler that may be active for this socket if this
2223 * is a server socket - the file handler was created automatically
2224 * by Tcl as part of the mechanism to accept new client connections.
2225 * Channel handlers are already deleted in the generic IO channel
2226 * closing code that called this function, so we do not have to
2230 Tcl_DeleteFileHandler(statePtr->fd);
2232 if (close(statePtr->fd) < 0) {
2235 ckfree((char *) statePtr);
2241 *----------------------------------------------------------------------
2243 * TcpGetOptionProc --
2245 * Computes an option value for a TCP socket based channel, or a
2246 * list of all options and their values.
2248 * Note: This code is based on code contributed by John Haxby.
2251 * A standard Tcl result. The value of the specified option or a
2252 * list of all options and their values is returned in the
2253 * supplied DString. Sets Error message if needed.
2258 *----------------------------------------------------------------------
2262 TcpGetOptionProc(instanceData, interp, optionName, dsPtr)
2263 ClientData instanceData; /* Socket state. */
2264 Tcl_Interp *interp; /* For error reporting - can be NULL. */
2265 CONST char *optionName; /* Name of the option to
2266 * retrieve the value for, or
2267 * NULL to get all options and
2269 Tcl_DString *dsPtr; /* Where to store the computed
2270 * value; initialized by caller. */
2272 TcpState *statePtr = (TcpState *) instanceData;
2273 struct sockaddr_in sockname;
2274 struct sockaddr_in peername;
2275 struct hostent *hostEntPtr;
2276 socklen_t size = sizeof(struct sockaddr_in);
2278 char buf[TCL_INTEGER_SPACE];
2280 if (optionName != (char *) NULL) {
2281 len = strlen(optionName);
2284 if ((len > 1) && (optionName[1] == 'e') &&
2285 (strncmp(optionName, "-error", len) == 0)) {
2286 socklen_t optlen = sizeof(int);
2291 ret = getsockopt(statePtr->fd, SOL_SOCKET, SO_ERROR,
2292 (char *)&err, &optlen);
2297 Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(err), -1);
2303 ((len > 1) && (optionName[1] == 'p') &&
2304 (strncmp(optionName, "-peername", len) == 0))) {
2305 if (getpeername(statePtr->fd, (struct sockaddr *) &peername,
2308 Tcl_DStringAppendElement(dsPtr, "-peername");
2309 Tcl_DStringStartSublist(dsPtr);
2311 Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
2312 hostEntPtr = TclpGetHostByAddr( /* INTL: Native. */
2313 (char *) &peername.sin_addr,
2314 sizeof(peername.sin_addr), AF_INET);
2315 if (hostEntPtr != (struct hostent *) NULL) {
2318 Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds);
2319 Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
2320 Tcl_DStringFree(&ds);
2322 Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
2324 TclFormatInt(buf, ntohs(peername.sin_port));
2325 Tcl_DStringAppendElement(dsPtr, buf);
2327 Tcl_DStringEndSublist(dsPtr);
2333 * getpeername failed - but if we were asked for all the options
2334 * (len==0), don't flag an error at that point because it could
2335 * be an fconfigure request on a server socket. (which have
2336 * no peer). same must be done on win&mac.
2341 Tcl_AppendResult(interp, "can't get peername: ",
2342 Tcl_PosixError(interp), (char *) NULL);
2350 ((len > 1) && (optionName[1] == 's') &&
2351 (strncmp(optionName, "-sockname", len) == 0))) {
2352 if (getsockname(statePtr->fd, (struct sockaddr *) &sockname,
2355 Tcl_DStringAppendElement(dsPtr, "-sockname");
2356 Tcl_DStringStartSublist(dsPtr);
2358 Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
2359 hostEntPtr = TclpGetHostByAddr( /* INTL: Native. */
2360 (char *) &sockname.sin_addr,
2361 sizeof(sockname.sin_addr), AF_INET);
2362 if (hostEntPtr != (struct hostent *) NULL) {
2365 Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds);
2366 Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
2367 Tcl_DStringFree(&ds);
2369 Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
2371 TclFormatInt(buf, ntohs(sockname.sin_port));
2372 Tcl_DStringAppendElement(dsPtr, buf);
2374 Tcl_DStringEndSublist(dsPtr);
2380 Tcl_AppendResult(interp, "can't get sockname: ",
2381 Tcl_PosixError(interp), (char *) NULL);
2388 return Tcl_BadChannelOption(interp, optionName, "peername sockname");
2395 *----------------------------------------------------------------------
2399 * Initialize the notifier to watch the fd from this channel.
2405 * Sets up the notifier so that a future event on the channel will
2408 *----------------------------------------------------------------------
2412 TcpWatchProc(instanceData, mask)
2413 ClientData instanceData; /* The socket state. */
2414 int mask; /* Events of interest; an OR-ed
2415 * combination of TCL_READABLE,
2416 * TCL_WRITABLE and TCL_EXCEPTION. */
2418 TcpState *statePtr = (TcpState *) instanceData;
2421 * Make sure we don't mess with server sockets since they will never
2422 * be readable or writable at the Tcl level. This keeps Tcl scripts
2423 * from interfering with the -accept behavior.
2426 if (!statePtr->acceptProc) {
2428 Tcl_CreateFileHandler(statePtr->fd, mask,
2429 (Tcl_FileProc *) Tcl_NotifyChannel,
2430 (ClientData) statePtr->channel);
2432 Tcl_DeleteFileHandler(statePtr->fd);
2438 *----------------------------------------------------------------------
2440 * TcpGetHandleProc --
2442 * Called from Tcl_GetChannelHandle to retrieve OS handles from inside
2443 * a TCP socket based channel.
2446 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
2447 * there is no handle for the specified direction.
2452 *----------------------------------------------------------------------
2457 TcpGetHandleProc(instanceData, direction, handlePtr)
2458 ClientData instanceData; /* The socket state. */
2459 int direction; /* Not used. */
2460 ClientData *handlePtr; /* Where to store the handle. */
2462 TcpState *statePtr = (TcpState *) instanceData;
2464 *handlePtr = (ClientData)statePtr->fd;
2469 *----------------------------------------------------------------------
2473 * This function opens a new socket in client or server mode
2474 * and initializes the TcpState structure.
2477 * Returns a new TcpState, or NULL with an error in the interp's
2478 * result, if interp is not NULL.
2483 *----------------------------------------------------------------------
2487 CreateSocket(interp, port, host, server, myaddr, myport, async)
2488 Tcl_Interp *interp; /* For error reporting; can be NULL. */
2489 int port; /* Port number to open. */
2490 CONST char *host; /* Name of host on which to open port.
2491 * NULL implies INADDR_ANY */
2492 int server; /* 1 if socket should be a server socket,
2493 * else 0 for a client socket. */
2494 CONST char *myaddr; /* Optional client-side address */
2495 int myport; /* Optional client-side port */
2496 int async; /* If nonzero and creating a client socket,
2497 * attempt to do an async connect. Otherwise
2498 * do a synchronous connect or bind. */
2500 int status, sock, asyncConnect, curState, origState;
2501 struct sockaddr_in sockaddr; /* socket address */
2502 struct sockaddr_in mysockaddr; /* Socket address for client */
2507 if (! CreateSocketAddress(&sockaddr, host, port)) {
2510 if ((myaddr != NULL || myport != 0) &&
2511 ! CreateSocketAddress(&mysockaddr, myaddr, myport)) {
2515 sock = socket(AF_INET, SOCK_STREAM, 0);
2521 * Set the close-on-exec flag so that the socket will not get
2522 * inherited by child processes.
2525 fcntl(sock, F_SETFD, FD_CLOEXEC);
2528 * Set kernel space buffering
2531 TclSockMinimumBuffers(sock, SOCKET_BUFSIZE);
2537 * Set up to reuse server addresses automatically and bind to the
2542 (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status,
2544 status = bind(sock, (struct sockaddr *) &sockaddr,
2545 sizeof(struct sockaddr));
2547 status = listen(sock, SOMAXCONN);
2550 if (myaddr != NULL || myport != 0) {
2552 (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
2553 (char *) &curState, sizeof(curState));
2554 status = bind(sock, (struct sockaddr *) &mysockaddr,
2555 sizeof(struct sockaddr));
2562 * Attempt to connect. The connect may fail at present with an
2563 * EINPROGRESS but at a later time it will complete. The caller
2564 * will set up a file handler on the socket if she is interested in
2565 * being informed when the connect completes.
2570 origState = fcntl(sock, F_GETFL);
2571 curState = origState | O_NONBLOCK;
2572 status = fcntl(sock, F_SETFL, curState);
2573 #else /* USE_FIONBIO */
2575 status = ioctl(sock, FIONBIO, &curState);
2576 #endif /* !USE_FIONBIO */
2581 status = connect(sock, (struct sockaddr *) &sockaddr,
2584 if (errno == EINPROGRESS) {
2590 * Here we are if the connect succeeds. In case of an
2591 * asynchronous connect we have to reset the channel to
2592 * blocking mode. This appears to happen not very often,
2593 * but e.g. on a HP 9000/800 under HP-UX B.11.00 we enter
2594 * this stage. [Bug: 4388]
2598 origState = fcntl(sock, F_GETFL);
2599 curState = origState & ~(O_NONBLOCK);
2600 status = fcntl(sock, F_SETFL, curState);
2601 #else /* USE_FIONBIO */
2603 status = ioctl(sock, FIONBIO, &curState);
2604 #endif /* !USE_FIONBIO */
2612 if (interp != NULL) {
2613 Tcl_AppendResult(interp, "couldn't open socket: ",
2614 Tcl_PosixError(interp), (char *) NULL);
2623 * Allocate a new TcpState for this socket.
2626 statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
2627 statePtr->flags = 0;
2629 statePtr->flags = TCP_ASYNC_CONNECT;
2631 statePtr->fd = sock;
2639 if (interp != NULL) {
2640 Tcl_AppendResult(interp, "couldn't open socket: ",
2641 Tcl_PosixError(interp), (char *) NULL);
2647 *----------------------------------------------------------------------
2649 * CreateSocketAddress --
2651 * This function initializes a sockaddr structure for a host and port.
2654 * 1 if the host was valid, 0 if the host could not be converted to
2658 * Fills in the *sockaddrPtr structure.
2660 *----------------------------------------------------------------------
2664 CreateSocketAddress(sockaddrPtr, host, port)
2665 struct sockaddr_in *sockaddrPtr; /* Socket address */
2666 CONST char *host; /* Host. NULL implies INADDR_ANY */
2667 int port; /* Port number */
2669 struct hostent *hostent; /* Host database entry */
2670 struct in_addr addr; /* For 64/32 bit madness */
2672 #ifdef __SYMBIAN32__
2673 if (host && !strcmp(host, "localhost")) {
2674 char* loc = strstr(host, "localhost");
2675 memcpy(loc, "127.0.0.1", 9);
2678 (void) memset((VOID *) sockaddrPtr, '\0', sizeof(struct sockaddr_in));
2679 sockaddrPtr->sin_family = AF_INET;
2680 sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF));
2682 addr.s_addr = INADDR_ANY;
2690 native = Tcl_UtfToExternalDString(NULL, host, -1, &ds);
2692 addr.s_addr = inet_addr(native); /* INTL: Native. */
2694 * This is 0xFFFFFFFF to ensure that it compares as a 32bit -1
2695 * on either 32 or 64 bits systems.
2697 if (addr.s_addr == 0xFFFFFFFF) {
2698 hostent = TclpGetHostByName(native); /* INTL: Native. */
2699 if (hostent != (struct hostent *) NULL) {
2700 memcpy((VOID *) &addr,
2701 (VOID *) hostent->h_addr_list[0],
2702 (size_t) hostent->h_length);
2705 errno = EHOSTUNREACH;
2706 #else /* !EHOSTUNREACH */
2710 #endif /* EHOSTUNREACH */
2711 if (native != NULL) {
2712 Tcl_DStringFree(&ds);
2714 return 0; /* error */
2717 if (native != NULL) {
2718 Tcl_DStringFree(&ds);
2723 * NOTE: On 64 bit machines the assignment below is rumored to not
2724 * do the right thing. Please report errors related to this if you
2725 * observe incorrect behavior on 64 bit machines such as DEC Alphas.
2726 * Should we modify this code to do an explicit memcpy?
2729 sockaddrPtr->sin_addr.s_addr = addr.s_addr;
2730 return 1; /* Success. */
2734 *----------------------------------------------------------------------
2736 * Tcl_OpenTcpClient --
2738 * Opens a TCP client socket and creates a channel around it.
2741 * The channel or NULL if failed. An error message is returned
2742 * in the interpreter on failure.
2745 * Opens a client socket and creates a new channel.
2747 *----------------------------------------------------------------------
2750 EXPORT_C Tcl_Channel
2751 Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async)
2752 Tcl_Interp *interp; /* For error reporting; can be NULL. */
2753 int port; /* Port number to open. */
2754 CONST char *host; /* Host on which to open port. */
2755 CONST char *myaddr; /* Client-side address */
2756 int myport; /* Client-side port */
2757 int async; /* If nonzero, attempt to do an
2758 * asynchronous connect. Otherwise
2759 * we do a blocking connect. */
2762 char channelName[16 + TCL_INTEGER_SPACE];
2765 * Create a new client socket and wrap it in a channel.
2768 statePtr = CreateSocket(interp, port, host, 0, myaddr, myport, async);
2769 if (statePtr == NULL) {
2773 statePtr->acceptProc = NULL;
2774 statePtr->acceptProcData = (ClientData) NULL;
2776 sprintf(channelName, "sock%d", statePtr->fd);
2778 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2779 (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE));
2780 if (Tcl_SetChannelOption(interp, statePtr->channel, "-translation",
2781 "auto crlf") == TCL_ERROR) {
2782 Tcl_Close((Tcl_Interp *) NULL, statePtr->channel);
2785 return statePtr->channel;
2789 *----------------------------------------------------------------------
2791 * Tcl_MakeTcpClientChannel --
2793 * Creates a Tcl_Channel from an existing client TCP socket.
2796 * The Tcl_Channel wrapped around the preexisting TCP socket.
2801 *----------------------------------------------------------------------
2804 EXPORT_C Tcl_Channel
2805 Tcl_MakeTcpClientChannel(sock)
2806 ClientData sock; /* The socket to wrap up into a channel. */
2808 return MakeTcpClientChannelMode(sock, (TCL_READABLE | TCL_WRITABLE));
2812 *----------------------------------------------------------------------
2814 * MakeTcpClientChannelMode --
2816 * Creates a Tcl_Channel from an existing client TCP socket
2820 * The Tcl_Channel wrapped around the preexisting TCP socket.
2825 *----------------------------------------------------------------------
2829 MakeTcpClientChannelMode(sock, mode)
2830 ClientData sock; /* The socket to wrap up into a channel. */
2831 int mode; /* ORed combination of TCL_READABLE and
2832 * TCL_WRITABLE to indicate file mode. */
2835 char channelName[16 + TCL_INTEGER_SPACE];
2837 statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
2838 statePtr->fd = (int) sock;
2839 statePtr->flags = 0;
2840 statePtr->acceptProc = NULL;
2841 statePtr->acceptProcData = (ClientData) NULL;
2843 sprintf(channelName, "sock%d", statePtr->fd);
2845 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2846 (ClientData) statePtr, mode);
2847 if (Tcl_SetChannelOption((Tcl_Interp *) NULL, statePtr->channel,
2848 "-translation", "auto crlf") == TCL_ERROR) {
2849 Tcl_Close((Tcl_Interp *) NULL, statePtr->channel);
2852 return statePtr->channel;
2856 *----------------------------------------------------------------------
2858 * Tcl_OpenTcpServer --
2860 * Opens a TCP server socket and creates a channel around it.
2863 * The channel or NULL if failed. If an error occurred, an
2864 * error message is left in the interp's result if interp is
2868 * Opens a server socket and creates a new channel.
2870 *----------------------------------------------------------------------
2873 EXPORT_C Tcl_Channel
2874 Tcl_OpenTcpServer(interp, port, myHost, acceptProc, acceptProcData)
2875 Tcl_Interp *interp; /* For error reporting - may be
2877 int port; /* Port number to open. */
2878 CONST char *myHost; /* Name of local host. */
2879 Tcl_TcpAcceptProc *acceptProc; /* Callback for accepting connections
2880 * from new clients. */
2881 ClientData acceptProcData; /* Data for the callback. */
2884 char channelName[16 + TCL_INTEGER_SPACE];
2887 * Create a new client socket and wrap it in a channel.
2890 statePtr = CreateSocket(interp, port, myHost, 1, NULL, 0, 0);
2891 if (statePtr == NULL) {
2895 statePtr->acceptProc = acceptProc;
2896 statePtr->acceptProcData = acceptProcData;
2899 * Set up the callback mechanism for accepting connections
2903 Tcl_CreateFileHandler(statePtr->fd, TCL_READABLE, TcpAccept,
2904 (ClientData) statePtr);
2905 sprintf(channelName, "sock%d", statePtr->fd);
2906 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2907 (ClientData) statePtr, 0);
2908 return statePtr->channel;
2912 *----------------------------------------------------------------------
2915 * Accept a TCP socket connection. This is called by the event loop.
2921 * Creates a new connection socket. Calls the registered callback
2922 * for the connection acceptance mechanism.
2924 *----------------------------------------------------------------------
2929 TcpAccept(data, mask)
2930 ClientData data; /* Callback token. */
2931 int mask; /* Not used. */
2933 TcpState *sockState; /* Client data of server socket. */
2934 int newsock; /* The new client socket */
2935 TcpState *newSockState; /* State for new socket. */
2936 struct sockaddr_in addr; /* The remote address */
2937 socklen_t len; /* For accept interface */
2938 char channelName[16 + TCL_INTEGER_SPACE];
2940 sockState = (TcpState *) data;
2942 len = sizeof(struct sockaddr_in);
2943 newsock = accept(sockState->fd, (struct sockaddr *) &addr, &len);
2949 * Set close-on-exec flag to prevent the newly accepted socket from
2950 * being inherited by child processes.
2953 (void) fcntl(newsock, F_SETFD, FD_CLOEXEC);
2955 newSockState = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
2957 newSockState->flags = 0;
2958 newSockState->fd = newsock;
2959 newSockState->acceptProc = NULL;
2960 newSockState->acceptProcData = NULL;
2962 sprintf(channelName, "sock%d", newsock);
2963 newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2964 (ClientData) newSockState, (TCL_READABLE | TCL_WRITABLE));
2966 Tcl_SetChannelOption(NULL, newSockState->channel, "-translation",
2969 if (sockState->acceptProc != NULL) {
2970 (*sockState->acceptProc)(sockState->acceptProcData,
2971 newSockState->channel, inet_ntoa(addr.sin_addr),
2972 ntohs(addr.sin_port));
2977 *----------------------------------------------------------------------
2979 * TclpGetDefaultStdChannel --
2981 * Creates channels for standard input, standard output or standard
2982 * error output if they do not already exist.
2985 * Returns the specified default standard channel, or NULL.
2988 * May cause the creation of a standard channel and the underlying
2991 *----------------------------------------------------------------------
2995 TclpGetDefaultStdChannel(type)
2996 int type; /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
2998 Tcl_Channel channel = NULL;
2999 int fd = 0; /* Initializations needed to prevent */
3000 int mode = 0; /* compiler warning (used before set). */
3001 char *bufMode = NULL;
3004 * Some #def's to make the code a little clearer!
3006 #define ZERO_OFFSET ((Tcl_SeekOffset) 0)
3007 #define ERROR_OFFSET ((Tcl_SeekOffset) -1)
3011 if ((TclOSseek(0, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
3012 && (errno == EBADF)) {
3013 return (Tcl_Channel) NULL;
3016 mode = TCL_READABLE;
3020 if ((TclOSseek(1, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
3021 && (errno == EBADF)) {
3022 return (Tcl_Channel) NULL;
3025 mode = TCL_WRITABLE;
3029 if ((TclOSseek(2, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
3030 && (errno == EBADF)) {
3031 return (Tcl_Channel) NULL;
3034 mode = TCL_WRITABLE;
3038 panic("TclGetDefaultStdChannel: Unexpected channel type");
3045 channel = Tcl_MakeFileChannel((ClientData) fd, mode);
3046 if (channel == NULL) {
3051 * Set up the normal channel options for stdio handles.
3054 if (Tcl_GetChannelType(channel) == &fileChannelType) {
3055 Tcl_SetChannelOption(NULL, channel, "-translation", "auto");
3057 Tcl_SetChannelOption(NULL, channel, "-translation", "auto crlf");
3059 Tcl_SetChannelOption(NULL, channel, "-buffering", bufMode);
3064 *----------------------------------------------------------------------
3066 * Tcl_GetOpenFile --
3068 * Given a name of a channel registered in the given interpreter,
3069 * returns a FILE * for it.
3072 * A standard Tcl result. If the channel is registered in the given
3073 * interpreter and it is managed by the "file" channel driver, and
3074 * it is open for the requested mode, then the output parameter
3075 * filePtr is set to a FILE * for the underlying file. On error, the
3076 * filePtr is not set, TCL_ERROR is returned and an error message is
3077 * left in the interp's result.
3080 * May invoke fdopen to create the FILE * for the requested file.
3082 *----------------------------------------------------------------------
3086 Tcl_GetOpenFile(interp, string, forWriting, checkUsage, filePtr)
3087 Tcl_Interp *interp; /* Interpreter in which to find file. */
3088 CONST char *string; /* String that identifies file. */
3089 int forWriting; /* 1 means the file is going to be used
3090 * for writing, 0 means for reading. */
3091 int checkUsage; /* 1 means verify that the file was opened
3092 * in a mode that allows the access specified
3093 * by "forWriting". Ignored, we always
3094 * check that the channel is open for the
3095 * requested mode. */
3096 ClientData *filePtr; /* Store pointer to FILE structure here. */
3100 Tcl_ChannelType *chanTypePtr;
3105 chan = Tcl_GetChannel(interp, string, &chanMode);
3106 if (chan == (Tcl_Channel) NULL) {
3109 if ((forWriting) && ((chanMode & TCL_WRITABLE) == 0)) {
3110 Tcl_AppendResult(interp,
3111 "\"", string, "\" wasn't opened for writing", (char *) NULL);
3113 } else if ((!(forWriting)) && ((chanMode & TCL_READABLE) == 0)) {
3114 Tcl_AppendResult(interp,
3115 "\"", string, "\" wasn't opened for reading", (char *) NULL);
3120 * We allow creating a FILE * out of file based, pipe based and socket
3121 * based channels. We currently do not allow any other channel types,
3122 * because it is likely that stdio will not know what to do with them.
3125 chanTypePtr = Tcl_GetChannelType(chan);
3126 if ((chanTypePtr == &fileChannelType)
3128 || (chanTypePtr == &ttyChannelType)
3129 #endif /* SUPPORTS_TTY */
3130 || (chanTypePtr == &tcpChannelType)
3131 || (strcmp(chanTypePtr->typeName, "pipe") == 0)) {
3132 if (Tcl_GetChannelHandle(chan,
3133 (forWriting ? TCL_WRITABLE : TCL_READABLE),
3134 (ClientData*) &data) == TCL_OK) {
3138 * The call to fdopen below is probably dangerous, since it will
3139 * truncate an existing file if the file is being opened
3143 f = fdopen(fd, (forWriting ? "w" : "r"));
3145 Tcl_AppendResult(interp, "cannot get a FILE * for \"", string,
3146 "\"", (char *) NULL);
3149 *filePtr = (ClientData) f;
3154 Tcl_AppendResult(interp, "\"", string,
3155 "\" cannot be used to get a FILE *", (char *) NULL);
3160 *----------------------------------------------------------------------
3162 * TclUnixWaitForFile --
3164 * This procedure waits synchronously for a file to become readable
3165 * or writable, with an optional timeout.
3168 * The return value is an OR'ed combination of TCL_READABLE,
3169 * TCL_WRITABLE, and TCL_EXCEPTION, indicating the conditions
3170 * that are present on file at the time of the return. This
3171 * procedure will not return until either "timeout" milliseconds
3172 * have elapsed or at least one of the conditions given by mask
3173 * has occurred for file (a return value of 0 means that a timeout
3174 * occurred). No normal events will be serviced during the
3175 * execution of this procedure.
3180 *----------------------------------------------------------------------
3184 TclUnixWaitForFile(fd, mask, timeout)
3185 int fd; /* Handle for file on which to wait. */
3186 int mask; /* What to wait for: OR'ed combination of
3187 * TCL_READABLE, TCL_WRITABLE, and
3189 int timeout; /* Maximum amount of time to wait for one
3190 * of the conditions in mask to occur, in
3191 * milliseconds. A value of 0 means don't
3192 * wait at all, and a value of -1 means
3195 Tcl_Time abortTime = {0, 0}, now; /* silence gcc 4 warning */
3196 struct timeval blockTime, *timeoutPtr;
3197 int index, numFound, result = 0;
3199 fd_mask readyMasks[3*MASK_SIZE];
3200 /* This array reflects the readable/writable
3201 * conditions that were found to exist by the
3202 * last call to select. */
3205 * If there is a non-zero finite timeout, compute the time when
3211 abortTime.sec = now.sec + timeout/1000;
3212 abortTime.usec = now.usec + (timeout%1000)*1000;
3213 if (abortTime.usec >= 1000000) {
3214 abortTime.usec -= 1000000;
3217 timeoutPtr = &blockTime;
3218 } else if (timeout == 0) {
3219 timeoutPtr = &blockTime;
3220 blockTime.tv_sec = 0;
3221 blockTime.tv_usec = 0;
3227 * Initialize the ready masks and compute the mask offsets.
3230 if (fd >= FD_SETSIZE) {
3231 panic("TclWaitForFile can't handle file id %d", fd);
3233 memset((VOID *) readyMasks, 0, 3*MASK_SIZE*sizeof(fd_mask));
3234 index = fd/(NBBY*sizeof(fd_mask));
3235 bit = ((fd_mask) 1) << (fd%(NBBY*sizeof(fd_mask)));
3238 * Loop in a mini-event loop of our own, waiting for either the
3239 * file to become ready or a timeout to occur.
3244 blockTime.tv_sec = abortTime.sec - now.sec;
3245 blockTime.tv_usec = abortTime.usec - now.usec;
3246 if (blockTime.tv_usec < 0) {
3247 blockTime.tv_sec -= 1;
3248 blockTime.tv_usec += 1000000;
3250 if (blockTime.tv_sec < 0) {
3251 blockTime.tv_sec = 0;
3252 blockTime.tv_usec = 0;
3257 * Set the appropriate bit in the ready masks for the fd.
3260 if (mask & TCL_READABLE) {
3261 readyMasks[index] |= bit;
3263 if (mask & TCL_WRITABLE) {
3264 (readyMasks+MASK_SIZE)[index] |= bit;
3266 if (mask & TCL_EXCEPTION) {
3267 (readyMasks+2*(MASK_SIZE))[index] |= bit;
3271 * Wait for the event or a timeout.
3274 numFound = select(fd+1, (SELECT_MASK *) &readyMasks[0],
3275 (SELECT_MASK *) &readyMasks[MASK_SIZE],
3276 (SELECT_MASK *) &readyMasks[2*MASK_SIZE], timeoutPtr);
3277 if (numFound == 1) {
3278 if (readyMasks[index] & bit) {
3279 result |= TCL_READABLE;
3281 if ((readyMasks+MASK_SIZE)[index] & bit) {
3282 result |= TCL_WRITABLE;
3284 if ((readyMasks+2*(MASK_SIZE))[index] & bit) {
3285 result |= TCL_EXCEPTION;
3300 * The select returned early, so we need to recompute the timeout.
3304 if ((abortTime.sec < now.sec)
3305 || ((abortTime.sec == now.sec)
3306 && (abortTime.usec <= now.usec))) {
3315 *----------------------------------------------------------------------
3317 * FileThreadActionProc --
3319 * Insert or remove any thread local refs to this channel.
3325 * Changes thread local list of valid channels.
3327 *----------------------------------------------------------------------
3331 FileThreadActionProc (instanceData, action)
3332 ClientData instanceData;
3335 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
3336 FileState *fsPtr = (FileState *) instanceData;
3338 if (action == TCL_CHANNEL_THREAD_INSERT) {
3339 fsPtr->nextPtr = tsdPtr->firstFilePtr;
3340 tsdPtr->firstFilePtr = fsPtr;
3342 FileState **nextPtrPtr;
3345 for (nextPtrPtr = &(tsdPtr->firstFilePtr); (*nextPtrPtr) != NULL;
3346 nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
3347 if ((*nextPtrPtr) == fsPtr) {
3348 (*nextPtrPtr) = fsPtr->nextPtr;
3355 * This could happen if the channel was created in one
3356 * thread and then moved to another without updating
3357 * the thread local data in each thread.
3361 panic("file info ptr not on thread channel list");
3365 #endif /* DEPRECATED */