sl@0: /* sl@0: * tclUnixChan.c sl@0: * sl@0: * Common channel driver for Unix channels based on files, command sl@0: * pipes and TCP sockets. sl@0: * sl@0: * Copyright (c) 1995-1997 Sun Microsystems, Inc. sl@0: * Copyright (c) 1998-1999 by Scriptics Corporation. sl@0: * Portions Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiaries. All rights reserved. sl@0: * sl@0: * See the file "license.terms" for information on usage and redistribution sl@0: * of this file, and for a DISCLAIMER OF ALL WARRANTIES. sl@0: * sl@0: * RCS: @(#) $Id: tclUnixChan.c,v 1.42.2.10 2006/11/28 16:29:48 kennykb Exp $ sl@0: */ sl@0: sl@0: #include "tclInt.h" /* Internal definitions for Tcl. */ sl@0: #include "tclPort.h" /* Portability features for Tcl. */ sl@0: #include "tclIO.h" /* To get Channel type declaration. */ sl@0: sl@0: /* sl@0: * sys/ioctl.h has already been included by tclPort.h. Including termios.h sl@0: * or termio.h causes a bunch of warning messages because some duplicate sl@0: * (but not contradictory) #defines exist in termios.h and/or termio.h sl@0: */ sl@0: #undef NL0 sl@0: #undef NL1 sl@0: #undef CR0 sl@0: #undef CR1 sl@0: #undef CR2 sl@0: #undef CR3 sl@0: #undef TAB0 sl@0: #undef TAB1 sl@0: #undef TAB2 sl@0: #undef XTABS sl@0: #undef BS0 sl@0: #undef BS1 sl@0: #undef FF0 sl@0: #undef FF1 sl@0: #undef ECHO sl@0: #undef NOFLSH sl@0: #undef TOSTOP sl@0: #undef FLUSHO sl@0: #undef PENDIN sl@0: sl@0: #define SUPPORTS_TTY sl@0: sl@0: #ifdef USE_TERMIOS sl@0: # include sl@0: # ifdef HAVE_SYS_IOCTL_H sl@0: # include sl@0: # endif /* HAVE_SYS_IOCTL_H */ sl@0: # ifdef HAVE_SYS_MODEM_H sl@0: # include sl@0: # endif /* HAVE_SYS_MODEM_H */ sl@0: # define IOSTATE struct termios sl@0: # define GETIOSTATE(fd, statePtr) tcgetattr((fd), (statePtr)) sl@0: # define SETIOSTATE(fd, statePtr) tcsetattr((fd), TCSADRAIN, (statePtr)) sl@0: # define GETCONTROL(fd, intPtr) ioctl((fd), TIOCMGET, (intPtr)) sl@0: # define SETCONTROL(fd, intPtr) ioctl((fd), TIOCMSET, (intPtr)) sl@0: /* sl@0: * TIP #35 introduced a different on exit flush/close behavior that sl@0: * doesn't work correctly with standard channels on all systems. sl@0: * The problem is tcflush throws away waiting channel data. This may sl@0: * be necessary for true serial channels that may block, but isn't sl@0: * correct in the standard case. This might be replaced with tcdrain sl@0: * instead, but that can block. For now, we revert to making this do sl@0: * nothing, and TtyOutputProc being the same old FileOutputProc. sl@0: * -- hobbs [Bug #525783] sl@0: */ sl@0: # define BAD_TIP35_FLUSH 0 sl@0: # if BAD_TIP35_FLUSH sl@0: # define TTYFLUSH(fd) tcflush((fd), TCIOFLUSH); sl@0: # else sl@0: # define TTYFLUSH(fd) sl@0: # endif /* BAD_TIP35_FLUSH */ sl@0: # ifdef FIONREAD sl@0: # define GETREADQUEUE(fd, int) ioctl((fd), FIONREAD, &(int)) sl@0: # elif defined(FIORDCHK) sl@0: # define GETREADQUEUE(fd, int) int = ioctl((fd), FIORDCHK, NULL) sl@0: # endif /* FIONREAD */ sl@0: # ifdef TIOCOUTQ sl@0: # define GETWRITEQUEUE(fd, int) ioctl((fd), TIOCOUTQ, &(int)) sl@0: # endif /* TIOCOUTQ */ sl@0: # if defined(TIOCSBRK) && defined(TIOCCBRK) sl@0: /* sl@0: * Can't use ?: operator below because that messes up types on either sl@0: * Linux or Solaris (the two are mutually exclusive!) sl@0: */ sl@0: # define SETBREAK(fd, flag) \ sl@0: if (flag) { \ sl@0: ioctl((fd), TIOCSBRK, NULL); \ sl@0: } else { \ sl@0: ioctl((fd), TIOCCBRK, NULL); \ sl@0: } sl@0: # endif /* TIOCSBRK&TIOCCBRK */ sl@0: # if !defined(CRTSCTS) && defined(CNEW_RTSCTS) sl@0: # define CRTSCTS CNEW_RTSCTS sl@0: # endif /* !CRTSCTS&CNEW_RTSCTS */ sl@0: #else /* !USE_TERMIOS */ sl@0: sl@0: #ifdef USE_TERMIO sl@0: # include sl@0: # define IOSTATE struct termio sl@0: # define GETIOSTATE(fd, statePtr) ioctl((fd), TCGETA, (statePtr)) sl@0: # define SETIOSTATE(fd, statePtr) ioctl((fd), TCSETAW, (statePtr)) sl@0: #else /* !USE_TERMIO */ sl@0: sl@0: #ifdef USE_SGTTY sl@0: # include sl@0: # define IOSTATE struct sgttyb sl@0: # define GETIOSTATE(fd, statePtr) ioctl((fd), TIOCGETP, (statePtr)) sl@0: # define SETIOSTATE(fd, statePtr) ioctl((fd), TIOCSETP, (statePtr)) sl@0: #else /* !USE_SGTTY */ sl@0: # undef SUPPORTS_TTY sl@0: #endif /* !USE_SGTTY */ sl@0: sl@0: #endif /* !USE_TERMIO */ sl@0: #endif /* !USE_TERMIOS */ sl@0: sl@0: /* sl@0: * This structure describes per-instance state of a file based channel. sl@0: */ sl@0: sl@0: typedef struct FileState { sl@0: Tcl_Channel channel; /* Channel associated with this file. */ sl@0: int fd; /* File handle. */ sl@0: int validMask; /* OR'ed combination of TCL_READABLE, sl@0: * TCL_WRITABLE, or TCL_EXCEPTION: indicates sl@0: * which operations are valid on the file. */ sl@0: #ifdef DEPRECATED sl@0: struct FileState *nextPtr; /* Pointer to next file in list of all sl@0: * file channels. */ sl@0: #endif /* DEPRECATED */ sl@0: } FileState; sl@0: sl@0: #ifdef SUPPORTS_TTY sl@0: sl@0: /* sl@0: * The following structure describes per-instance state of a tty-based sl@0: * channel. sl@0: */ sl@0: sl@0: typedef struct TtyState { sl@0: FileState fs; /* Per-instance state of the file sl@0: * descriptor. Must be the first field. */ sl@0: int stateUpdated; /* Flag to say if the state has been sl@0: * modified and needs resetting. */ sl@0: IOSTATE savedState; /* Initial state of device. Used to reset sl@0: * state when device closed. */ sl@0: } TtyState; sl@0: sl@0: /* sl@0: * The following structure is used to set or get the serial port sl@0: * attributes in a platform-independant manner. sl@0: */ sl@0: sl@0: typedef struct TtyAttrs { sl@0: int baud; sl@0: int parity; sl@0: int data; sl@0: int stop; sl@0: } TtyAttrs; sl@0: sl@0: #endif /* !SUPPORTS_TTY */ sl@0: sl@0: #define UNSUPPORTED_OPTION(detail) \ sl@0: if (interp) { \ sl@0: Tcl_AppendResult(interp, (detail), \ sl@0: " not supported for this platform", (char *) NULL); \ sl@0: } sl@0: sl@0: #ifdef DEPRECATED sl@0: typedef struct ThreadSpecificData { sl@0: /* sl@0: * List of all file channels currently open. This is per thread and is sl@0: * used to match up fd's to channels, which rarely occurs. sl@0: */ sl@0: sl@0: FileState *firstFilePtr; sl@0: } ThreadSpecificData; sl@0: sl@0: static Tcl_ThreadDataKey dataKey; sl@0: #endif /* DEPRECATED */ sl@0: sl@0: /* sl@0: * This structure describes per-instance state of a tcp based channel. sl@0: */ sl@0: sl@0: typedef struct TcpState { sl@0: Tcl_Channel channel; /* Channel associated with this file. */ sl@0: int fd; /* The socket itself. */ sl@0: int flags; /* ORed combination of the bitfields sl@0: * defined below. */ sl@0: Tcl_TcpAcceptProc *acceptProc; sl@0: /* Proc to call on accept. */ sl@0: ClientData acceptProcData; /* The data for the accept proc. */ sl@0: } TcpState; sl@0: sl@0: /* sl@0: * These bits may be ORed together into the "flags" field of a TcpState sl@0: * structure. sl@0: */ sl@0: sl@0: #define TCP_ASYNC_SOCKET (1<<0) /* Asynchronous socket. */ sl@0: #define TCP_ASYNC_CONNECT (1<<1) /* Async connect in progress. */ sl@0: sl@0: /* sl@0: * The following defines the maximum length of the listen queue. This is sl@0: * the number of outstanding yet-to-be-serviced requests for a connection sl@0: * on a server socket, more than this number of outstanding requests and sl@0: * the connection request will fail. sl@0: */ sl@0: sl@0: #ifndef SOMAXCONN sl@0: # define SOMAXCONN 100 sl@0: #endif /* SOMAXCONN */ sl@0: sl@0: #if (SOMAXCONN < 100) sl@0: # undef SOMAXCONN sl@0: # define SOMAXCONN 100 sl@0: #endif /* SOMAXCONN < 100 */ sl@0: sl@0: /* sl@0: * The following defines how much buffer space the kernel should maintain sl@0: * for a socket. sl@0: */ sl@0: sl@0: #define SOCKET_BUFSIZE 4096 sl@0: sl@0: /* sl@0: * Static routines for this file: sl@0: */ sl@0: sl@0: static TcpState * CreateSocket _ANSI_ARGS_((Tcl_Interp *interp, sl@0: int port, CONST char *host, int server, sl@0: CONST char *myaddr, int myport, int async)); sl@0: static int CreateSocketAddress _ANSI_ARGS_( sl@0: (struct sockaddr_in *sockaddrPtr, sl@0: CONST char *host, int port)); sl@0: static int FileBlockModeProc _ANSI_ARGS_(( sl@0: ClientData instanceData, int mode)); sl@0: static int FileCloseProc _ANSI_ARGS_((ClientData instanceData, sl@0: Tcl_Interp *interp)); sl@0: static int FileGetHandleProc _ANSI_ARGS_((ClientData instanceData, sl@0: int direction, ClientData *handlePtr)); sl@0: static int FileInputProc _ANSI_ARGS_((ClientData instanceData, sl@0: char *buf, int toRead, int *errorCode)); sl@0: static int FileOutputProc _ANSI_ARGS_(( sl@0: ClientData instanceData, CONST char *buf, sl@0: int toWrite, int *errorCode)); sl@0: static int FileSeekProc _ANSI_ARGS_((ClientData instanceData, sl@0: long offset, int mode, int *errorCode)); sl@0: #ifdef DEPRECATED sl@0: static void FileThreadActionProc _ANSI_ARGS_ (( sl@0: ClientData instanceData, int action)); sl@0: #endif sl@0: static Tcl_WideInt FileWideSeekProc _ANSI_ARGS_((ClientData instanceData, sl@0: Tcl_WideInt offset, int mode, int *errorCode)); sl@0: static void FileWatchProc _ANSI_ARGS_((ClientData instanceData, sl@0: int mask)); sl@0: static void TcpAccept _ANSI_ARGS_((ClientData data, int mask)); sl@0: static int TcpBlockModeProc _ANSI_ARGS_((ClientData data, sl@0: int mode)); sl@0: static int TcpCloseProc _ANSI_ARGS_((ClientData instanceData, sl@0: Tcl_Interp *interp)); sl@0: static int TcpGetHandleProc _ANSI_ARGS_((ClientData instanceData, sl@0: int direction, ClientData *handlePtr)); sl@0: static int TcpGetOptionProc _ANSI_ARGS_((ClientData instanceData, sl@0: Tcl_Interp *interp, CONST char *optionName, sl@0: Tcl_DString *dsPtr)); sl@0: static int TcpInputProc _ANSI_ARGS_((ClientData instanceData, sl@0: char *buf, int toRead, int *errorCode)); sl@0: static int TcpOutputProc _ANSI_ARGS_((ClientData instanceData, sl@0: CONST char *buf, int toWrite, int *errorCode)); sl@0: static void TcpWatchProc _ANSI_ARGS_((ClientData instanceData, sl@0: int mask)); sl@0: #ifdef SUPPORTS_TTY sl@0: static int TtyCloseProc _ANSI_ARGS_((ClientData instanceData, sl@0: Tcl_Interp *interp)); sl@0: static void TtyGetAttributes _ANSI_ARGS_((int fd, sl@0: TtyAttrs *ttyPtr)); sl@0: static int TtyGetOptionProc _ANSI_ARGS_((ClientData instanceData, sl@0: Tcl_Interp *interp, CONST char *optionName, sl@0: Tcl_DString *dsPtr)); sl@0: static FileState * TtyInit _ANSI_ARGS_((int fd, int initialize)); sl@0: #if BAD_TIP35_FLUSH sl@0: static int TtyOutputProc _ANSI_ARGS_((ClientData instanceData, sl@0: CONST char *buf, int toWrite, int *errorCode)); sl@0: #endif /* BAD_TIP35_FLUSH */ sl@0: static int TtyParseMode _ANSI_ARGS_((Tcl_Interp *interp, sl@0: CONST char *mode, int *speedPtr, int *parityPtr, sl@0: int *dataPtr, int *stopPtr)); sl@0: static void TtySetAttributes _ANSI_ARGS_((int fd, sl@0: TtyAttrs *ttyPtr)); sl@0: static int TtySetOptionProc _ANSI_ARGS_((ClientData instanceData, sl@0: Tcl_Interp *interp, CONST char *optionName, sl@0: CONST char *value)); sl@0: #endif /* SUPPORTS_TTY */ sl@0: static int WaitForConnect _ANSI_ARGS_((TcpState *statePtr, sl@0: int *errorCodePtr)); sl@0: static Tcl_Channel MakeTcpClientChannelMode _ANSI_ARGS_( sl@0: (ClientData tcpSocket, sl@0: int mode)); sl@0: sl@0: sl@0: /* sl@0: * This structure describes the channel type structure for file based IO: sl@0: */ sl@0: sl@0: static Tcl_ChannelType fileChannelType = { sl@0: "file", /* Type name. */ sl@0: TCL_CHANNEL_VERSION_4, /* v4 channel */ sl@0: FileCloseProc, /* Close proc. */ sl@0: FileInputProc, /* Input proc. */ sl@0: FileOutputProc, /* Output proc. */ sl@0: FileSeekProc, /* Seek proc. */ sl@0: NULL, /* Set option proc. */ sl@0: NULL, /* Get option proc. */ sl@0: FileWatchProc, /* Initialize notifier. */ sl@0: FileGetHandleProc, /* Get OS handles out of channel. */ sl@0: NULL, /* close2proc. */ sl@0: FileBlockModeProc, /* Set blocking or non-blocking mode.*/ sl@0: NULL, /* flush proc. */ sl@0: NULL, /* handler proc. */ sl@0: FileWideSeekProc, /* wide seek proc. */ sl@0: #ifdef DEPRECATED sl@0: FileThreadActionProc, /* thread actions */ sl@0: #else sl@0: NULL, sl@0: #endif sl@0: }; sl@0: sl@0: #ifdef SUPPORTS_TTY sl@0: /* sl@0: * This structure describes the channel type structure for serial IO. sl@0: * Note that this type is a subclass of the "file" type. sl@0: */ sl@0: sl@0: static Tcl_ChannelType ttyChannelType = { sl@0: "tty", /* Type name. */ sl@0: TCL_CHANNEL_VERSION_4, /* v4 channel */ sl@0: TtyCloseProc, /* Close proc. */ sl@0: FileInputProc, /* Input proc. */ sl@0: #if BAD_TIP35_FLUSH sl@0: TtyOutputProc, /* Output proc. */ sl@0: #else /* !BAD_TIP35_FLUSH */ sl@0: FileOutputProc, /* Output proc. */ sl@0: #endif /* BAD_TIP35_FLUSH */ sl@0: NULL, /* Seek proc. */ sl@0: TtySetOptionProc, /* Set option proc. */ sl@0: TtyGetOptionProc, /* Get option proc. */ sl@0: FileWatchProc, /* Initialize notifier. */ sl@0: FileGetHandleProc, /* Get OS handles out of channel. */ sl@0: NULL, /* close2proc. */ sl@0: FileBlockModeProc, /* Set blocking or non-blocking mode.*/ sl@0: NULL, /* flush proc. */ sl@0: NULL, /* handler proc. */ sl@0: NULL, /* wide seek proc. */ sl@0: NULL, /* thread action proc. */ sl@0: }; sl@0: #endif /* SUPPORTS_TTY */ sl@0: sl@0: /* sl@0: * This structure describes the channel type structure for TCP socket sl@0: * based IO: sl@0: */ sl@0: sl@0: static Tcl_ChannelType tcpChannelType = { sl@0: "tcp", /* Type name. */ sl@0: TCL_CHANNEL_VERSION_4, /* v4 channel */ sl@0: TcpCloseProc, /* Close proc. */ sl@0: TcpInputProc, /* Input proc. */ sl@0: TcpOutputProc, /* Output proc. */ sl@0: NULL, /* Seek proc. */ sl@0: NULL, /* Set option proc. */ sl@0: TcpGetOptionProc, /* Get option proc. */ sl@0: TcpWatchProc, /* Initialize notifier. */ sl@0: TcpGetHandleProc, /* Get OS handles out of channel. */ sl@0: NULL, /* close2proc. */ sl@0: TcpBlockModeProc, /* Set blocking or non-blocking mode.*/ sl@0: NULL, /* flush proc. */ sl@0: NULL, /* handler proc. */ sl@0: NULL, /* wide seek proc. */ sl@0: NULL, /* thread action proc. */ sl@0: }; sl@0: sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileBlockModeProc -- sl@0: * sl@0: * Helper procedure to set blocking and nonblocking modes on a sl@0: * file based channel. Invoked by generic IO level code. sl@0: * sl@0: * Results: sl@0: * 0 if successful, errno when failed. sl@0: * sl@0: * Side effects: sl@0: * Sets the device into blocking or non-blocking mode. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: /* ARGSUSED */ sl@0: static int sl@0: FileBlockModeProc(instanceData, mode) sl@0: ClientData instanceData; /* File state. */ sl@0: int mode; /* The mode to set. Can be one of sl@0: * TCL_MODE_BLOCKING or sl@0: * TCL_MODE_NONBLOCKING. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: int curStatus; sl@0: sl@0: #ifndef USE_FIONBIO sl@0: curStatus = fcntl(fsPtr->fd, F_GETFL); sl@0: if (mode == TCL_MODE_BLOCKING) { sl@0: curStatus &= (~(O_NONBLOCK)); sl@0: } else { sl@0: curStatus |= O_NONBLOCK; sl@0: } sl@0: if (fcntl(fsPtr->fd, F_SETFL, curStatus) < 0) { sl@0: return errno; sl@0: } sl@0: curStatus = fcntl(fsPtr->fd, F_GETFL); sl@0: #else /* USE_FIONBIO */ sl@0: if (mode == TCL_MODE_BLOCKING) { sl@0: curStatus = 0; sl@0: } else { sl@0: curStatus = 1; sl@0: } sl@0: if (ioctl(fsPtr->fd, (int) FIONBIO, &curStatus) < 0) { sl@0: return errno; sl@0: } sl@0: #endif /* !USE_FIONBIO */ sl@0: return 0; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileInputProc -- sl@0: * sl@0: * This procedure is invoked from the generic IO level to read sl@0: * input from a file based channel. sl@0: * sl@0: * Results: sl@0: * The number of bytes read is returned or -1 on error. An output sl@0: * argument contains a POSIX error code if an error occurs, or zero. sl@0: * sl@0: * Side effects: sl@0: * Reads input from the input device of the channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: FileInputProc(instanceData, buf, toRead, errorCodePtr) sl@0: ClientData instanceData; /* File state. */ sl@0: char *buf; /* Where to store data read. */ sl@0: int toRead; /* How much space is available sl@0: * in the buffer? */ sl@0: int *errorCodePtr; /* Where to store error code. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: int bytesRead; /* How many bytes were actually sl@0: * read from the input device? */ sl@0: sl@0: *errorCodePtr = 0; sl@0: sl@0: /* sl@0: * Assume there is always enough input available. This will block sl@0: * appropriately, and read will unblock as soon as a short read is sl@0: * possible, if the channel is in blocking mode. If the channel is sl@0: * nonblocking, the read will never block. sl@0: */ sl@0: sl@0: bytesRead = read(fsPtr->fd, buf, (size_t) toRead); sl@0: if (bytesRead > -1) { sl@0: return bytesRead; sl@0: } sl@0: *errorCodePtr = errno; sl@0: return -1; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileOutputProc-- sl@0: * sl@0: * This procedure is invoked from the generic IO level to write sl@0: * output to a file channel. sl@0: * sl@0: * Results: sl@0: * The number of bytes written is returned or -1 on error. An sl@0: * output argument contains a POSIX error code if an error occurred, sl@0: * or zero. sl@0: * sl@0: * Side effects: sl@0: * Writes output on the output device of the channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: FileOutputProc(instanceData, buf, toWrite, errorCodePtr) sl@0: ClientData instanceData; /* File state. */ sl@0: CONST char *buf; /* The data buffer. */ sl@0: int toWrite; /* How many bytes to write? */ sl@0: int *errorCodePtr; /* Where to store error code. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: int written; sl@0: sl@0: *errorCodePtr = 0; sl@0: sl@0: if (toWrite == 0) { sl@0: /* sl@0: * SF Tcl Bug 465765. sl@0: * Do not try to write nothing into a file. STREAM based sl@0: * implementations will considers this as EOF (if there is a sl@0: * pipe behind the file). sl@0: */ sl@0: sl@0: return 0; sl@0: } sl@0: written = write(fsPtr->fd, buf, (size_t) toWrite); sl@0: if (written > -1) { sl@0: return written; sl@0: } sl@0: *errorCodePtr = errno; sl@0: return -1; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileCloseProc -- sl@0: * sl@0: * This procedure is called from the generic IO level to perform sl@0: * channel-type-specific cleanup when a file based channel is closed. sl@0: * sl@0: * Results: sl@0: * 0 if successful, errno if failed. sl@0: * sl@0: * Side effects: sl@0: * Closes the device of the channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: FileCloseProc(instanceData, interp) sl@0: ClientData instanceData; /* File state. */ sl@0: Tcl_Interp *interp; /* For error reporting - unused. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: int errorCode = 0; sl@0: #ifdef DEPRECATED sl@0: FileState **nextPtrPtr; sl@0: ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); sl@0: #endif /* DEPRECATED */ sl@0: Tcl_DeleteFileHandler(fsPtr->fd); sl@0: sl@0: /* sl@0: * Do not close standard channels while in thread-exit. sl@0: */ sl@0: sl@0: if (!TclInThreadExit() sl@0: || ((fsPtr->fd != 0) && (fsPtr->fd != 1) && (fsPtr->fd != 2))) { sl@0: if (close(fsPtr->fd) < 0) { sl@0: errorCode = errno; sl@0: } sl@0: } sl@0: ckfree((char *) fsPtr); sl@0: return errorCode; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileSeekProc -- sl@0: * sl@0: * This procedure is called by the generic IO level to move the sl@0: * access point in a file based channel. sl@0: * sl@0: * Results: sl@0: * -1 if failed, the new position if successful. An output sl@0: * argument contains the POSIX error code if an error occurred, sl@0: * or zero. sl@0: * sl@0: * Side effects: sl@0: * Moves the location at which the channel will be accessed in sl@0: * future operations. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: FileSeekProc(instanceData, offset, mode, errorCodePtr) sl@0: ClientData instanceData; /* File state. */ sl@0: long offset; /* Offset to seek to. */ sl@0: int mode; /* Relative to where should we seek? Can be sl@0: * one of SEEK_START, SEEK_SET or SEEK_END. */ sl@0: int *errorCodePtr; /* To store error code. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: Tcl_WideInt oldLoc, newLoc; sl@0: sl@0: /* sl@0: * Save our current place in case we need to roll-back the seek. sl@0: */ sl@0: oldLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) 0, SEEK_CUR); sl@0: if (oldLoc == Tcl_LongAsWide(-1)) { sl@0: /* sl@0: * Bad things are happening. Error out... sl@0: */ sl@0: *errorCodePtr = errno; sl@0: return -1; sl@0: } sl@0: sl@0: newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode); sl@0: sl@0: /* sl@0: * Check for expressability in our return type, and roll-back otherwise. sl@0: */ sl@0: if (newLoc > Tcl_LongAsWide(INT_MAX)) { sl@0: *errorCodePtr = EOVERFLOW; sl@0: TclOSseek(fsPtr->fd, (Tcl_SeekOffset) oldLoc, SEEK_SET); sl@0: return -1; sl@0: } else { sl@0: *errorCodePtr = (newLoc == Tcl_LongAsWide(-1)) ? errno : 0; sl@0: } sl@0: return (int) Tcl_WideAsLong(newLoc); sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileWideSeekProc -- sl@0: * sl@0: * This procedure is called by the generic IO level to move the sl@0: * access point in a file based channel, with offsets expressed sl@0: * as wide integers. sl@0: * sl@0: * Results: sl@0: * -1 if failed, the new position if successful. An output sl@0: * argument contains the POSIX error code if an error occurred, sl@0: * or zero. sl@0: * sl@0: * Side effects: sl@0: * Moves the location at which the channel will be accessed in sl@0: * future operations. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static Tcl_WideInt sl@0: FileWideSeekProc(instanceData, offset, mode, errorCodePtr) sl@0: ClientData instanceData; /* File state. */ sl@0: Tcl_WideInt offset; /* Offset to seek to. */ sl@0: int mode; /* Relative to where should we seek? Can be sl@0: * one of SEEK_START, SEEK_CUR or SEEK_END. */ sl@0: int *errorCodePtr; /* To store error code. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: Tcl_WideInt newLoc; sl@0: sl@0: newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode); sl@0: sl@0: *errorCodePtr = (newLoc == -1) ? errno : 0; sl@0: return newLoc; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileWatchProc -- sl@0: * sl@0: * Initialize the notifier to watch the fd from this channel. sl@0: * sl@0: * Results: sl@0: * None. sl@0: * sl@0: * Side effects: sl@0: * Sets up the notifier so that a future event on the channel will sl@0: * be seen by Tcl. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static void sl@0: FileWatchProc(instanceData, mask) sl@0: ClientData instanceData; /* The file state. */ sl@0: int mask; /* Events of interest; an OR-ed sl@0: * combination of TCL_READABLE, sl@0: * TCL_WRITABLE and TCL_EXCEPTION. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: sl@0: /* sl@0: * Make sure we only register for events that are valid on this file. sl@0: * Note that we are passing Tcl_NotifyChannel directly to sl@0: * Tcl_CreateFileHandler with the channel pointer as the client data. sl@0: */ sl@0: sl@0: mask &= fsPtr->validMask; sl@0: if (mask) { sl@0: Tcl_CreateFileHandler(fsPtr->fd, mask, sl@0: (Tcl_FileProc *) Tcl_NotifyChannel, sl@0: (ClientData) fsPtr->channel); sl@0: } else { sl@0: Tcl_DeleteFileHandler(fsPtr->fd); sl@0: } sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileGetHandleProc -- sl@0: * sl@0: * Called from Tcl_GetChannelHandle to retrieve OS handles from sl@0: * a file based channel. sl@0: * sl@0: * Results: sl@0: * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if sl@0: * there is no handle for the specified direction. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: FileGetHandleProc(instanceData, direction, handlePtr) sl@0: ClientData instanceData; /* The file state. */ sl@0: int direction; /* TCL_READABLE or TCL_WRITABLE */ sl@0: ClientData *handlePtr; /* Where to store the handle. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: sl@0: if (direction & fsPtr->validMask) { sl@0: *handlePtr = (ClientData) fsPtr->fd; sl@0: return TCL_OK; sl@0: } else { sl@0: return TCL_ERROR; sl@0: } sl@0: } sl@0: sl@0: #ifdef SUPPORTS_TTY sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TtyCloseProc -- sl@0: * sl@0: * This procedure is called from the generic IO level to perform sl@0: * channel-type-specific cleanup when a tty based channel is closed. sl@0: * sl@0: * Results: sl@0: * 0 if successful, errno if failed. sl@0: * sl@0: * Side effects: sl@0: * Closes the device of the channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: static int sl@0: TtyCloseProc(instanceData, interp) sl@0: ClientData instanceData; /* Tty state. */ sl@0: Tcl_Interp *interp; /* For error reporting - unused. */ sl@0: { sl@0: #if BAD_TIP35_FLUSH sl@0: TtyState *ttyPtr = (TtyState *) instanceData; sl@0: #endif /* BAD_TIP35_FLUSH */ sl@0: #ifdef TTYFLUSH sl@0: TTYFLUSH(ttyPtr->fs.fd); sl@0: #endif /* TTYFLUSH */ sl@0: #if 0 sl@0: /* sl@0: * TIP#35 agreed to remove the unsave so that TCL could be used as a sl@0: * simple stty. sl@0: * It would be cleaner to remove all the stuff related to sl@0: * TtyState.stateUpdated sl@0: * TtyState.savedState sl@0: * Then the structure TtyState would be the same as FileState. sl@0: * IMO this cleanup could better be done for the final 8.4 release sl@0: * after nobody complained about the missing unsave. -- schroedter sl@0: */ sl@0: if (ttyPtr->stateUpdated) { sl@0: SETIOSTATE(ttyPtr->fs.fd, &ttyPtr->savedState); sl@0: } sl@0: #endif sl@0: return FileCloseProc(instanceData, interp); sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TtyOutputProc-- sl@0: * sl@0: * This procedure is invoked from the generic IO level to write sl@0: * output to a TTY channel. sl@0: * sl@0: * Results: sl@0: * The number of bytes written is returned or -1 on error. An sl@0: * output argument contains a POSIX error code if an error occurred, sl@0: * or zero. sl@0: * sl@0: * Side effects: sl@0: * Writes output on the output device of the channel sl@0: * if the channel is not designated to be closed. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: #if BAD_TIP35_FLUSH sl@0: static int sl@0: TtyOutputProc(instanceData, buf, toWrite, errorCodePtr) sl@0: ClientData instanceData; /* File state. */ sl@0: CONST char *buf; /* The data buffer. */ sl@0: int toWrite; /* How many bytes to write? */ sl@0: int *errorCodePtr; /* Where to store error code. */ sl@0: { sl@0: if (TclInExit()) { sl@0: /* sl@0: * Do not write data during Tcl exit. sl@0: * Serial port may block preventing Tcl from exit. sl@0: */ sl@0: return toWrite; sl@0: } else { sl@0: return FileOutputProc(instanceData, buf, toWrite, errorCodePtr); sl@0: } sl@0: } sl@0: #endif /* BAD_TIP35_FLUSH */ sl@0: sl@0: #ifdef USE_TERMIOS sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TtyModemStatusStr -- sl@0: * sl@0: * Converts a RS232 modem status list of readable flags sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: static void sl@0: TtyModemStatusStr(status, dsPtr) sl@0: int status; /* RS232 modem status */ sl@0: Tcl_DString *dsPtr; /* Where to store string */ sl@0: { sl@0: #ifdef TIOCM_CTS sl@0: Tcl_DStringAppendElement(dsPtr, "CTS"); sl@0: Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CTS) ? "1" : "0"); sl@0: #endif /* TIOCM_CTS */ sl@0: #ifdef TIOCM_DSR sl@0: Tcl_DStringAppendElement(dsPtr, "DSR"); sl@0: Tcl_DStringAppendElement(dsPtr, (status & TIOCM_DSR) ? "1" : "0"); sl@0: #endif /* TIOCM_DSR */ sl@0: #ifdef TIOCM_RNG sl@0: Tcl_DStringAppendElement(dsPtr, "RING"); sl@0: Tcl_DStringAppendElement(dsPtr, (status & TIOCM_RNG) ? "1" : "0"); sl@0: #endif /* TIOCM_RNG */ sl@0: #ifdef TIOCM_CD sl@0: Tcl_DStringAppendElement(dsPtr, "DCD"); sl@0: Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CD) ? "1" : "0"); sl@0: #endif /* TIOCM_CD */ sl@0: } sl@0: #endif /* USE_TERMIOS */ sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TtySetOptionProc -- sl@0: * sl@0: * Sets an option on a channel. sl@0: * sl@0: * Results: sl@0: * A standard Tcl result. Also sets the interp's result on error if sl@0: * interp is not NULL. sl@0: * sl@0: * Side effects: sl@0: * May modify an option on a device. sl@0: * Sets Error message if needed (by calling Tcl_BadChannelOption). sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: TtySetOptionProc(instanceData, interp, optionName, value) sl@0: ClientData instanceData; /* File state. */ sl@0: Tcl_Interp *interp; /* For error reporting - can be NULL. */ sl@0: CONST char *optionName; /* Which option to set? */ sl@0: CONST char *value; /* New value for option. */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: unsigned int len, vlen; sl@0: TtyAttrs tty; sl@0: #ifdef USE_TERMIOS sl@0: int flag, control, argc; sl@0: CONST char **argv; sl@0: IOSTATE iostate; sl@0: #endif /* USE_TERMIOS */ sl@0: sl@0: len = strlen(optionName); sl@0: vlen = strlen(value); sl@0: sl@0: /* sl@0: * Option -mode baud,parity,databits,stopbits sl@0: */ sl@0: if ((len > 2) && (strncmp(optionName, "-mode", len) == 0)) { sl@0: if (TtyParseMode(interp, value, &tty.baud, &tty.parity, &tty.data, sl@0: &tty.stop) != TCL_OK) { sl@0: return TCL_ERROR; sl@0: } sl@0: /* sl@0: * system calls results should be checked there. -- dl sl@0: */ sl@0: sl@0: TtySetAttributes(fsPtr->fd, &tty); sl@0: ((TtyState *) fsPtr)->stateUpdated = 1; sl@0: return TCL_OK; sl@0: } sl@0: sl@0: #ifdef USE_TERMIOS sl@0: sl@0: /* sl@0: * Option -handshake none|xonxoff|rtscts|dtrdsr sl@0: */ sl@0: if ((len > 1) && (strncmp(optionName, "-handshake", len) == 0)) { sl@0: /* sl@0: * Reset all handshake options sl@0: * DTR and RTS are ON by default sl@0: */ sl@0: GETIOSTATE(fsPtr->fd, &iostate); sl@0: iostate.c_iflag &= ~(IXON | IXOFF | IXANY); sl@0: #ifdef CRTSCTS sl@0: iostate.c_cflag &= ~CRTSCTS; sl@0: #endif /* CRTSCTS */ sl@0: if (strncasecmp(value, "NONE", vlen) == 0) { sl@0: /* leave all handshake options disabled */ sl@0: } else if (strncasecmp(value, "XONXOFF", vlen) == 0) { sl@0: iostate.c_iflag |= (IXON | IXOFF | IXANY); sl@0: } else if (strncasecmp(value, "RTSCTS", vlen) == 0) { sl@0: #ifdef CRTSCTS sl@0: iostate.c_cflag |= CRTSCTS; sl@0: #else /* !CRTSTS */ sl@0: UNSUPPORTED_OPTION("-handshake RTSCTS"); sl@0: return TCL_ERROR; sl@0: #endif /* CRTSCTS */ sl@0: } else if (strncasecmp(value, "DTRDSR", vlen) == 0) { sl@0: UNSUPPORTED_OPTION("-handshake DTRDSR"); sl@0: return TCL_ERROR; sl@0: } else { sl@0: if (interp) { sl@0: Tcl_AppendResult(interp, "bad value for -handshake: ", sl@0: "must be one of xonxoff, rtscts, dtrdsr or none", sl@0: (char *) NULL); sl@0: } sl@0: return TCL_ERROR; sl@0: } sl@0: SETIOSTATE(fsPtr->fd, &iostate); sl@0: return TCL_OK; sl@0: } sl@0: sl@0: /* sl@0: * Option -xchar {\x11 \x13} sl@0: */ sl@0: if ((len > 1) && (strncmp(optionName, "-xchar", len) == 0)) { sl@0: GETIOSTATE(fsPtr->fd, &iostate); sl@0: if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) { sl@0: return TCL_ERROR; sl@0: } sl@0: if (argc == 2) { sl@0: iostate.c_cc[VSTART] = argv[0][0]; sl@0: iostate.c_cc[VSTOP] = argv[1][0]; sl@0: } else { sl@0: if (interp) { sl@0: Tcl_AppendResult(interp, sl@0: "bad value for -xchar: should be a list of two elements", sl@0: (char *) NULL); sl@0: } sl@0: ckfree((char *) argv); sl@0: return TCL_ERROR; sl@0: } sl@0: SETIOSTATE(fsPtr->fd, &iostate); sl@0: ckfree((char *) argv); sl@0: return TCL_OK; sl@0: } sl@0: sl@0: /* sl@0: * Option -timeout msec sl@0: */ sl@0: if ((len > 2) && (strncmp(optionName, "-timeout", len) == 0)) { sl@0: int msec; sl@0: sl@0: GETIOSTATE(fsPtr->fd, &iostate); sl@0: if (Tcl_GetInt(interp, value, &msec) != TCL_OK) { sl@0: return TCL_ERROR; sl@0: } sl@0: iostate.c_cc[VMIN] = 0; sl@0: iostate.c_cc[VTIME] = (msec == 0) ? 0 : (msec < 100) ? 1 : (msec+50)/100; sl@0: SETIOSTATE(fsPtr->fd, &iostate); sl@0: return TCL_OK; sl@0: } sl@0: sl@0: /* sl@0: * Option -ttycontrol {DTR 1 RTS 0 BREAK 0} sl@0: */ sl@0: if ((len > 4) && (strncmp(optionName, "-ttycontrol", len) == 0)) { sl@0: int i; sl@0: if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) { sl@0: return TCL_ERROR; sl@0: } sl@0: if ((argc % 2) == 1) { sl@0: if (interp) { sl@0: Tcl_AppendResult(interp, sl@0: "bad value for -ttycontrol: should be a list of", sl@0: "signal,value pairs", (char *) NULL); sl@0: } sl@0: ckfree((char *) argv); sl@0: return TCL_ERROR; sl@0: } sl@0: sl@0: GETCONTROL(fsPtr->fd, &control); sl@0: for (i = 0; i < argc-1; i += 2) { sl@0: if (Tcl_GetBoolean(interp, argv[i+1], &flag) == TCL_ERROR) { sl@0: ckfree((char *) argv); sl@0: return TCL_ERROR; sl@0: } sl@0: if (strncasecmp(argv[i], "DTR", strlen(argv[i])) == 0) { sl@0: #ifdef TIOCM_DTR sl@0: if (flag) { sl@0: control |= TIOCM_DTR; sl@0: } else { sl@0: control &= ~TIOCM_DTR; sl@0: } sl@0: #else /* !TIOCM_DTR */ sl@0: UNSUPPORTED_OPTION("-ttycontrol DTR"); sl@0: ckfree((char *) argv); sl@0: return TCL_ERROR; sl@0: #endif /* TIOCM_DTR */ sl@0: } else if (strncasecmp(argv[i], "RTS", strlen(argv[i])) == 0) { sl@0: #ifdef TIOCM_RTS sl@0: if (flag) { sl@0: control |= TIOCM_RTS; sl@0: } else { sl@0: control &= ~TIOCM_RTS; sl@0: } sl@0: #else /* !TIOCM_RTS*/ sl@0: UNSUPPORTED_OPTION("-ttycontrol RTS"); sl@0: ckfree((char *) argv); sl@0: return TCL_ERROR; sl@0: #endif /* TIOCM_RTS*/ sl@0: } else if (strncasecmp(argv[i], "BREAK", strlen(argv[i])) == 0) { sl@0: #ifdef SETBREAK sl@0: SETBREAK(fsPtr->fd, flag); sl@0: #else /* !SETBREAK */ sl@0: UNSUPPORTED_OPTION("-ttycontrol BREAK"); sl@0: ckfree((char *) argv); sl@0: return TCL_ERROR; sl@0: #endif /* SETBREAK */ sl@0: } else { sl@0: if (interp) { sl@0: Tcl_AppendResult(interp, "bad signal \"", argv[i], sl@0: "\" for -ttycontrol: must be ", sl@0: "DTR, RTS or BREAK", (char *) NULL); sl@0: } sl@0: ckfree((char *) argv); sl@0: return TCL_ERROR; sl@0: } sl@0: } /* -ttycontrol options loop */ sl@0: sl@0: SETCONTROL(fsPtr->fd, &control); sl@0: ckfree((char *) argv); sl@0: return TCL_OK; sl@0: } sl@0: sl@0: return Tcl_BadChannelOption(interp, optionName, sl@0: "mode handshake timeout ttycontrol xchar "); sl@0: sl@0: #else /* !USE_TERMIOS */ sl@0: return Tcl_BadChannelOption(interp, optionName, "mode"); sl@0: #endif /* USE_TERMIOS */ sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TtyGetOptionProc -- sl@0: * sl@0: * Gets a mode associated with an IO channel. If the optionName arg sl@0: * is non NULL, retrieves the value of that option. If the optionName sl@0: * arg is NULL, retrieves a list of alternating option names and sl@0: * values for the given channel. sl@0: * sl@0: * Results: sl@0: * A standard Tcl result. Also sets the supplied DString to the sl@0: * string value of the option(s) returned. sl@0: * sl@0: * Side effects: sl@0: * The string returned by this function is in static storage and sl@0: * may be reused at any time subsequent to the call. sl@0: * Sets Error message if needed (by calling Tcl_BadChannelOption). sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: TtyGetOptionProc(instanceData, interp, optionName, dsPtr) sl@0: ClientData instanceData; /* File state. */ sl@0: Tcl_Interp *interp; /* For error reporting - can be NULL. */ sl@0: CONST char *optionName; /* Option to get. */ sl@0: Tcl_DString *dsPtr; /* Where to store value(s). */ sl@0: { sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: unsigned int len; sl@0: char buf[3 * TCL_INTEGER_SPACE + 16]; sl@0: TtyAttrs tty; sl@0: int valid = 0; /* flag if valid option parsed */ sl@0: sl@0: if (optionName == NULL) { sl@0: len = 0; sl@0: } else { sl@0: len = strlen(optionName); sl@0: } sl@0: if (len == 0) { sl@0: Tcl_DStringAppendElement(dsPtr, "-mode"); sl@0: } sl@0: if (len==0 || (len>2 && strncmp(optionName, "-mode", len)==0)) { sl@0: valid = 1; sl@0: TtyGetAttributes(fsPtr->fd, &tty); sl@0: sprintf(buf, "%d,%c,%d,%d", tty.baud, tty.parity, tty.data, tty.stop); sl@0: Tcl_DStringAppendElement(dsPtr, buf); sl@0: } sl@0: sl@0: #ifdef USE_TERMIOS sl@0: /* sl@0: * get option -xchar sl@0: */ sl@0: if (len == 0) { sl@0: Tcl_DStringAppendElement(dsPtr, "-xchar"); sl@0: Tcl_DStringStartSublist(dsPtr); sl@0: } sl@0: if (len==0 || (len>1 && strncmp(optionName, "-xchar", len)==0)) { sl@0: IOSTATE iostate; sl@0: valid = 1; sl@0: sl@0: GETIOSTATE(fsPtr->fd, &iostate); sl@0: sprintf(buf, "%c", iostate.c_cc[VSTART]); sl@0: Tcl_DStringAppendElement(dsPtr, buf); sl@0: sprintf(buf, "%c", iostate.c_cc[VSTOP]); sl@0: Tcl_DStringAppendElement(dsPtr, buf); sl@0: } sl@0: if (len == 0) { sl@0: Tcl_DStringEndSublist(dsPtr); sl@0: } sl@0: sl@0: /* sl@0: * get option -queue sl@0: * option is readonly and returned by [fconfigure chan -queue] sl@0: * but not returned by unnamed [fconfigure chan] sl@0: */ sl@0: if ((len > 1) && (strncmp(optionName, "-queue", len) == 0)) { sl@0: int inQueue=0, outQueue=0; sl@0: int inBuffered, outBuffered; sl@0: valid = 1; sl@0: #ifdef GETREADQUEUE sl@0: GETREADQUEUE(fsPtr->fd, inQueue); sl@0: #endif /* GETREADQUEUE */ sl@0: #ifdef GETWRITEQUEUE sl@0: GETWRITEQUEUE(fsPtr->fd, outQueue); sl@0: #endif /* GETWRITEQUEUE */ sl@0: inBuffered = Tcl_InputBuffered(fsPtr->channel); sl@0: outBuffered = Tcl_OutputBuffered(fsPtr->channel); sl@0: sl@0: sprintf(buf, "%d", inBuffered+inQueue); sl@0: Tcl_DStringAppendElement(dsPtr, buf); sl@0: sprintf(buf, "%d", outBuffered+outQueue); sl@0: Tcl_DStringAppendElement(dsPtr, buf); sl@0: } sl@0: sl@0: /* sl@0: * get option -ttystatus sl@0: * option is readonly and returned by [fconfigure chan -ttystatus] sl@0: * but not returned by unnamed [fconfigure chan] sl@0: */ sl@0: if ((len > 4) && (strncmp(optionName, "-ttystatus", len) == 0)) { sl@0: int status; sl@0: valid = 1; sl@0: GETCONTROL(fsPtr->fd, &status); sl@0: TtyModemStatusStr(status, dsPtr); sl@0: } sl@0: #endif /* USE_TERMIOS */ sl@0: sl@0: if (valid) { sl@0: return TCL_OK; sl@0: } else { sl@0: return Tcl_BadChannelOption(interp, optionName, sl@0: #ifdef USE_TERMIOS sl@0: "mode queue ttystatus xchar"); sl@0: #else /* !USE_TERMIOS */ sl@0: "mode"); sl@0: #endif /* USE_TERMIOS */ sl@0: } sl@0: } sl@0: sl@0: #undef DIRECT_BAUD sl@0: #ifdef B4800 sl@0: # if (B4800 == 4800) sl@0: # define DIRECT_BAUD sl@0: # endif /* B4800 == 4800 */ sl@0: #endif /* B4800 */ sl@0: sl@0: #ifdef DIRECT_BAUD sl@0: # define TtyGetSpeed(baud) ((unsigned) (baud)) sl@0: # define TtyGetBaud(speed) ((int) (speed)) sl@0: #else /* !DIRECT_BAUD */ sl@0: sl@0: static struct {int baud; unsigned long speed;} speeds[] = { sl@0: #ifdef B0 sl@0: {0, B0}, sl@0: #endif sl@0: #ifdef B50 sl@0: {50, B50}, sl@0: #endif sl@0: #ifdef B75 sl@0: {75, B75}, sl@0: #endif sl@0: #ifdef B110 sl@0: {110, B110}, sl@0: #endif sl@0: #ifdef B134 sl@0: {134, B134}, sl@0: #endif sl@0: #ifdef B150 sl@0: {150, B150}, sl@0: #endif sl@0: #ifdef B200 sl@0: {200, B200}, sl@0: #endif sl@0: #ifdef B300 sl@0: {300, B300}, sl@0: #endif sl@0: #ifdef B600 sl@0: {600, B600}, sl@0: #endif sl@0: #ifdef B1200 sl@0: {1200, B1200}, sl@0: #endif sl@0: #ifdef B1800 sl@0: {1800, B1800}, sl@0: #endif sl@0: #ifdef B2400 sl@0: {2400, B2400}, sl@0: #endif sl@0: #ifdef B4800 sl@0: {4800, B4800}, sl@0: #endif sl@0: #ifdef B9600 sl@0: {9600, B9600}, sl@0: #endif sl@0: #ifdef B14400 sl@0: {14400, B14400}, sl@0: #endif sl@0: #ifdef B19200 sl@0: {19200, B19200}, sl@0: #endif sl@0: #ifdef EXTA sl@0: {19200, EXTA}, sl@0: #endif sl@0: #ifdef B28800 sl@0: {28800, B28800}, sl@0: #endif sl@0: #ifdef B38400 sl@0: {38400, B38400}, sl@0: #endif sl@0: #ifdef EXTB sl@0: {38400, EXTB}, sl@0: #endif sl@0: #ifdef B57600 sl@0: {57600, B57600}, sl@0: #endif sl@0: #ifdef _B57600 sl@0: {57600, _B57600}, sl@0: #endif sl@0: #ifdef B76800 sl@0: {76800, B76800}, sl@0: #endif sl@0: #ifdef B115200 sl@0: {115200, B115200}, sl@0: #endif sl@0: #ifdef _B115200 sl@0: {115200, _B115200}, sl@0: #endif sl@0: #ifdef B153600 sl@0: {153600, B153600}, sl@0: #endif sl@0: #ifdef B230400 sl@0: {230400, B230400}, sl@0: #endif sl@0: #ifdef B307200 sl@0: {307200, B307200}, sl@0: #endif sl@0: #ifdef B460800 sl@0: {460800, B460800}, sl@0: #endif sl@0: {-1, 0} sl@0: }; sl@0: sl@0: /* sl@0: *--------------------------------------------------------------------------- sl@0: * sl@0: * TtyGetSpeed -- sl@0: * sl@0: * Given a baud rate, get the mask value that should be stored in sl@0: * the termios, termio, or sgttyb structure in order to select that sl@0: * baud rate. sl@0: * sl@0: * Results: sl@0: * As above. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *--------------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static unsigned long sl@0: TtyGetSpeed(baud) sl@0: int baud; /* The baud rate to look up. */ sl@0: { sl@0: int bestIdx, bestDiff, i, diff; sl@0: sl@0: bestIdx = 0; sl@0: bestDiff = 1000000; sl@0: sl@0: /* sl@0: * If the baud rate does not correspond to one of the known mask values, sl@0: * choose the mask value whose baud rate is closest to the specified sl@0: * baud rate. sl@0: */ sl@0: sl@0: for (i = 0; speeds[i].baud >= 0; i++) { sl@0: diff = speeds[i].baud - baud; sl@0: if (diff < 0) { sl@0: diff = -diff; sl@0: } sl@0: if (diff < bestDiff) { sl@0: bestIdx = i; sl@0: bestDiff = diff; sl@0: } sl@0: } sl@0: return speeds[bestIdx].speed; sl@0: } sl@0: sl@0: /* sl@0: *--------------------------------------------------------------------------- sl@0: * sl@0: * TtyGetBaud -- sl@0: * sl@0: * Given a speed mask value from a termios, termio, or sgttyb sl@0: * structure, get the baus rate that corresponds to that mask value. sl@0: * sl@0: * Results: sl@0: * As above. If the mask value was not recognized, 0 is returned. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *--------------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: TtyGetBaud(speed) sl@0: unsigned long speed; /* Speed mask value to look up. */ sl@0: { sl@0: int i; sl@0: sl@0: for (i = 0; speeds[i].baud >= 0; i++) { sl@0: if (speeds[i].speed == speed) { sl@0: return speeds[i].baud; sl@0: } sl@0: } sl@0: return 0; sl@0: } sl@0: sl@0: #endif /* !DIRECT_BAUD */ sl@0: sl@0: sl@0: /* sl@0: *--------------------------------------------------------------------------- sl@0: * sl@0: * TtyGetAttributes -- sl@0: * sl@0: * Get the current attributes of the specified serial device. sl@0: * sl@0: * Results: sl@0: * None. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *--------------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static void sl@0: TtyGetAttributes(fd, ttyPtr) sl@0: int fd; /* Open file descriptor for serial port to sl@0: * be queried. */ sl@0: TtyAttrs *ttyPtr; /* Buffer filled with serial port sl@0: * attributes. */ sl@0: { sl@0: IOSTATE iostate; sl@0: int baud, parity, data, stop; sl@0: sl@0: GETIOSTATE(fd, &iostate); sl@0: sl@0: #ifdef USE_TERMIOS sl@0: baud = TtyGetBaud(cfgetospeed(&iostate)); sl@0: sl@0: parity = 'n'; sl@0: #ifdef PAREXT sl@0: switch ((int) (iostate.c_cflag & (PARENB | PARODD | PAREXT))) { sl@0: case PARENB : parity = 'e'; break; sl@0: case PARENB | PARODD : parity = 'o'; break; sl@0: case PARENB | PAREXT : parity = 's'; break; sl@0: case PARENB | PARODD | PAREXT : parity = 'm'; break; sl@0: } sl@0: #else /* !PAREXT */ sl@0: switch ((int) (iostate.c_cflag & (PARENB | PARODD))) { sl@0: case PARENB : parity = 'e'; break; sl@0: case PARENB | PARODD : parity = 'o'; break; sl@0: } sl@0: #endif /* !PAREXT */ sl@0: sl@0: data = iostate.c_cflag & CSIZE; sl@0: data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8; sl@0: sl@0: stop = (iostate.c_cflag & CSTOPB) ? 2 : 1; sl@0: #endif /* USE_TERMIOS */ sl@0: sl@0: #ifdef USE_TERMIO sl@0: baud = TtyGetBaud(iostate.c_cflag & CBAUD); sl@0: sl@0: parity = 'n'; sl@0: switch (iostate.c_cflag & (PARENB | PARODD | PAREXT)) { sl@0: case PARENB : parity = 'e'; break; sl@0: case PARENB | PARODD : parity = 'o'; break; sl@0: case PARENB | PAREXT : parity = 's'; break; sl@0: case PARENB | PARODD | PAREXT : parity = 'm'; break; sl@0: } sl@0: sl@0: data = iostate.c_cflag & CSIZE; sl@0: data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8; sl@0: sl@0: stop = (iostate.c_cflag & CSTOPB) ? 2 : 1; sl@0: #endif /* USE_TERMIO */ sl@0: sl@0: #ifdef USE_SGTTY sl@0: baud = TtyGetBaud(iostate.sg_ospeed); sl@0: sl@0: parity = 'n'; sl@0: if (iostate.sg_flags & EVENP) { sl@0: parity = 'e'; sl@0: } else if (iostate.sg_flags & ODDP) { sl@0: parity = 'o'; sl@0: } sl@0: sl@0: data = (iostate.sg_flags & (EVENP | ODDP)) ? 7 : 8; sl@0: sl@0: stop = 1; sl@0: #endif /* USE_SGTTY */ sl@0: sl@0: ttyPtr->baud = baud; sl@0: ttyPtr->parity = parity; sl@0: ttyPtr->data = data; sl@0: ttyPtr->stop = stop; sl@0: } sl@0: sl@0: /* sl@0: *--------------------------------------------------------------------------- sl@0: * sl@0: * TtySetAttributes -- sl@0: * sl@0: * Set the current attributes of the specified serial device. sl@0: * sl@0: * Results: sl@0: * None. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *--------------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static void sl@0: TtySetAttributes(fd, ttyPtr) sl@0: int fd; /* Open file descriptor for serial port to sl@0: * be modified. */ sl@0: TtyAttrs *ttyPtr; /* Buffer containing new attributes for sl@0: * serial port. */ sl@0: { sl@0: IOSTATE iostate; sl@0: sl@0: #ifdef USE_TERMIOS sl@0: int parity, data, flag; sl@0: sl@0: GETIOSTATE(fd, &iostate); sl@0: cfsetospeed(&iostate, TtyGetSpeed(ttyPtr->baud)); sl@0: cfsetispeed(&iostate, TtyGetSpeed(ttyPtr->baud)); sl@0: sl@0: flag = 0; sl@0: parity = ttyPtr->parity; sl@0: if (parity != 'n') { sl@0: flag |= PARENB; sl@0: #ifdef PAREXT sl@0: iostate.c_cflag &= ~PAREXT; sl@0: if ((parity == 'm') || (parity == 's')) { sl@0: flag |= PAREXT; sl@0: } sl@0: #endif /* PAREXT */ sl@0: if ((parity == 'm') || (parity == 'o')) { sl@0: flag |= PARODD; sl@0: } sl@0: } sl@0: data = ttyPtr->data; sl@0: flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8; sl@0: if (ttyPtr->stop == 2) { sl@0: flag |= CSTOPB; sl@0: } sl@0: sl@0: iostate.c_cflag &= ~(PARENB | PARODD | CSIZE | CSTOPB); sl@0: iostate.c_cflag |= flag; sl@0: sl@0: #endif /* USE_TERMIOS */ sl@0: sl@0: #ifdef USE_TERMIO sl@0: int parity, data, flag; sl@0: sl@0: GETIOSTATE(fd, &iostate); sl@0: iostate.c_cflag &= ~CBAUD; sl@0: iostate.c_cflag |= TtyGetSpeed(ttyPtr->baud); sl@0: sl@0: flag = 0; sl@0: parity = ttyPtr->parity; sl@0: if (parity != 'n') { sl@0: flag |= PARENB; sl@0: if ((parity == 'm') || (parity == 's')) { sl@0: flag |= PAREXT; sl@0: } sl@0: if ((parity == 'm') || (parity == 'o')) { sl@0: flag |= PARODD; sl@0: } sl@0: } sl@0: data = ttyPtr->data; sl@0: flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8; sl@0: if (ttyPtr->stop == 2) { sl@0: flag |= CSTOPB; sl@0: } sl@0: sl@0: iostate.c_cflag &= ~(PARENB | PARODD | PAREXT | CSIZE | CSTOPB); sl@0: iostate.c_cflag |= flag; sl@0: sl@0: #endif /* USE_TERMIO */ sl@0: sl@0: #ifdef USE_SGTTY sl@0: int parity; sl@0: sl@0: GETIOSTATE(fd, &iostate); sl@0: iostate.sg_ospeed = TtyGetSpeed(ttyPtr->baud); sl@0: iostate.sg_ispeed = TtyGetSpeed(ttyPtr->baud); sl@0: sl@0: parity = ttyPtr->parity; sl@0: if (parity == 'e') { sl@0: iostate.sg_flags &= ~ODDP; sl@0: iostate.sg_flags |= EVENP; sl@0: } else if (parity == 'o') { sl@0: iostate.sg_flags &= ~EVENP; sl@0: iostate.sg_flags |= ODDP; sl@0: } sl@0: #endif /* USE_SGTTY */ sl@0: sl@0: SETIOSTATE(fd, &iostate); sl@0: } sl@0: sl@0: /* sl@0: *--------------------------------------------------------------------------- sl@0: * sl@0: * TtyParseMode -- sl@0: * sl@0: * Parse the "-mode" argument to the fconfigure command. The argument sl@0: * is of the form baud,parity,data,stop. sl@0: * sl@0: * Results: sl@0: * The return value is TCL_OK if the argument was successfully sl@0: * parsed, TCL_ERROR otherwise. If TCL_ERROR is returned, an sl@0: * error message is left in the interp's result (if interp is non-NULL). sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *--------------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: TtyParseMode(interp, mode, speedPtr, parityPtr, dataPtr, stopPtr) sl@0: Tcl_Interp *interp; /* If non-NULL, interp for error return. */ sl@0: CONST char *mode; /* Mode string to be parsed. */ sl@0: int *speedPtr; /* Filled with baud rate from mode string. */ sl@0: int *parityPtr; /* Filled with parity from mode string. */ sl@0: int *dataPtr; /* Filled with data bits from mode string. */ sl@0: int *stopPtr; /* Filled with stop bits from mode string. */ sl@0: { sl@0: int i, end; sl@0: char parity; sl@0: static char *bad = "bad value for -mode"; sl@0: sl@0: i = sscanf(mode, "%d,%c,%d,%d%n", speedPtr, &parity, dataPtr, sl@0: stopPtr, &end); sl@0: if ((i != 4) || (mode[end] != '\0')) { sl@0: if (interp != NULL) { sl@0: Tcl_AppendResult(interp, bad, ": should be baud,parity,data,stop", sl@0: NULL); sl@0: } sl@0: return TCL_ERROR; sl@0: } sl@0: /* sl@0: * Only allow setting mark/space parity on platforms that support it sl@0: * Make sure to allow for the case where strchr is a macro. sl@0: * [Bug: 5089] sl@0: */ sl@0: if ( sl@0: #if defined(PAREXT) || defined(USE_TERMIO) sl@0: strchr("noems", parity) == NULL sl@0: #else sl@0: strchr("noe", parity) == NULL sl@0: #endif /* PAREXT|USE_TERMIO */ sl@0: ) { sl@0: if (interp != NULL) { sl@0: Tcl_AppendResult(interp, bad, sl@0: #if defined(PAREXT) || defined(USE_TERMIO) sl@0: " parity: should be n, o, e, m, or s", sl@0: #else sl@0: " parity: should be n, o, or e", sl@0: #endif /* PAREXT|USE_TERMIO */ sl@0: NULL); sl@0: } sl@0: return TCL_ERROR; sl@0: } sl@0: *parityPtr = parity; sl@0: if ((*dataPtr < 5) || (*dataPtr > 8)) { sl@0: if (interp != NULL) { sl@0: Tcl_AppendResult(interp, bad, " data: should be 5, 6, 7, or 8", sl@0: NULL); sl@0: } sl@0: return TCL_ERROR; sl@0: } sl@0: if ((*stopPtr < 0) || (*stopPtr > 2)) { sl@0: if (interp != NULL) { sl@0: Tcl_AppendResult(interp, bad, " stop: should be 1 or 2", NULL); sl@0: } sl@0: return TCL_ERROR; sl@0: } sl@0: return TCL_OK; sl@0: } sl@0: sl@0: /* sl@0: *--------------------------------------------------------------------------- sl@0: * sl@0: * TtyInit -- sl@0: * sl@0: * Given file descriptor that refers to a serial port, sl@0: * initialize the serial port to a set of sane values so that sl@0: * Tcl can talk to a device located on the serial port. sl@0: * Note that no initialization happens if the initialize flag sl@0: * is not set; this is necessary for the correct handling of sl@0: * UNIX console TTYs at startup. sl@0: * sl@0: * Results: sl@0: * A pointer to a FileState suitable for use with Tcl_CreateChannel sl@0: * and the ttyChannelType structure. sl@0: * sl@0: * Side effects: sl@0: * Serial device initialized to non-blocking raw mode, similar to sl@0: * sockets (if initialize flag is non-zero.) All other modes can sl@0: * be simulated on top of this in Tcl. sl@0: * sl@0: *--------------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static FileState * sl@0: TtyInit(fd, initialize) sl@0: int fd; /* Open file descriptor for serial port to sl@0: * be initialized. */ sl@0: int initialize; sl@0: { sl@0: TtyState *ttyPtr; sl@0: sl@0: ttyPtr = (TtyState *) ckalloc((unsigned) sizeof(TtyState)); sl@0: GETIOSTATE(fd, &ttyPtr->savedState); sl@0: ttyPtr->stateUpdated = 0; sl@0: if (initialize) { sl@0: IOSTATE iostate = ttyPtr->savedState; sl@0: sl@0: #if defined(USE_TERMIOS) || defined(USE_TERMIO) sl@0: if (iostate.c_iflag != IGNBRK || sl@0: iostate.c_oflag != 0 || sl@0: iostate.c_lflag != 0 || sl@0: iostate.c_cflag & CREAD || sl@0: iostate.c_cc[VMIN] != 1 || sl@0: iostate.c_cc[VTIME] != 0) { sl@0: ttyPtr->stateUpdated = 1; sl@0: } sl@0: iostate.c_iflag = IGNBRK; sl@0: iostate.c_oflag = 0; sl@0: iostate.c_lflag = 0; sl@0: iostate.c_cflag |= CREAD; sl@0: iostate.c_cc[VMIN] = 1; sl@0: iostate.c_cc[VTIME] = 0; sl@0: #endif /* USE_TERMIOS|USE_TERMIO */ sl@0: sl@0: #ifdef USE_SGTTY sl@0: if ((iostate.sg_flags & (EVENP | ODDP)) || sl@0: !(iostate.sg_flags & RAW)) { sl@0: ttyPtr->stateUpdated = 1; sl@0: } sl@0: iostate.sg_flags &= (EVENP | ODDP); sl@0: iostate.sg_flags |= RAW; sl@0: #endif /* USE_SGTTY */ sl@0: sl@0: /* sl@0: * Only update if we're changing anything to avoid possible sl@0: * blocking. sl@0: */ sl@0: if (ttyPtr->stateUpdated) { sl@0: SETIOSTATE(fd, &iostate); sl@0: } sl@0: } sl@0: sl@0: return &ttyPtr->fs; sl@0: } sl@0: #endif /* SUPPORTS_TTY */ sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TclpOpenFileChannel -- sl@0: * sl@0: * Open an file based channel on Unix systems. sl@0: * sl@0: * Results: sl@0: * The new channel or NULL. If NULL, the output argument sl@0: * errorCodePtr is set to a POSIX error and an error message is sl@0: * left in the interp's result if interp is not NULL. sl@0: * sl@0: * Side effects: sl@0: * May open the channel and may cause creation of a file on the sl@0: * file system. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: Tcl_Channel sl@0: TclpOpenFileChannel(interp, pathPtr, mode, permissions) sl@0: Tcl_Interp *interp; /* Interpreter for error reporting; sl@0: * can be NULL. */ sl@0: Tcl_Obj *pathPtr; /* Name of file to open. */ sl@0: int mode; /* POSIX open mode. */ sl@0: int permissions; /* If the open involves creating a sl@0: * file, with what modes to create sl@0: * it? */ sl@0: { sl@0: int fd, channelPermissions; sl@0: FileState *fsPtr; sl@0: CONST char *native, *translation; sl@0: char channelName[16 + TCL_INTEGER_SPACE]; sl@0: Tcl_ChannelType *channelTypePtr; sl@0: #ifdef SUPPORTS_TTY sl@0: int ctl_tty; sl@0: #endif /* SUPPORTS_TTY */ sl@0: #ifdef DEPRECATED sl@0: ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); sl@0: #endif /* DEPRECATED */ sl@0: sl@0: switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) { sl@0: case O_RDONLY: sl@0: channelPermissions = TCL_READABLE; sl@0: break; sl@0: case O_WRONLY: sl@0: channelPermissions = TCL_WRITABLE; sl@0: break; sl@0: case O_RDWR: sl@0: channelPermissions = (TCL_READABLE | TCL_WRITABLE); sl@0: break; sl@0: default: sl@0: /* sl@0: * This may occurr if modeString was "", for example. sl@0: */ sl@0: panic("TclpOpenFileChannel: invalid mode value"); sl@0: return NULL; sl@0: } sl@0: sl@0: native = Tcl_FSGetNativePath(pathPtr); sl@0: if (native == NULL) { sl@0: return NULL; sl@0: } sl@0: fd = TclOSopen(native, mode, permissions); sl@0: #ifdef SUPPORTS_TTY sl@0: ctl_tty = (strcmp (native, "/dev/tty") == 0); sl@0: #endif /* SUPPORTS_TTY */ sl@0: sl@0: if (fd < 0) { sl@0: if (interp != (Tcl_Interp *) NULL) { sl@0: Tcl_AppendResult(interp, "couldn't open \"", sl@0: Tcl_GetString(pathPtr), "\": ", sl@0: Tcl_PosixError(interp), (char *) NULL); sl@0: } sl@0: return NULL; sl@0: } sl@0: sl@0: /* sl@0: * Set close-on-exec flag on the fd so that child processes will not sl@0: * inherit this fd. sl@0: */ sl@0: sl@0: fcntl(fd, F_SETFD, FD_CLOEXEC); sl@0: sl@0: sprintf(channelName, "file%d", fd); sl@0: sl@0: #ifdef SUPPORTS_TTY sl@0: if (!ctl_tty && isatty(fd)) { sl@0: /* sl@0: * Initialize the serial port to a set of sane parameters. sl@0: * Especially important if the remote device is set to echo and sl@0: * the serial port driver was also set to echo -- as soon as a char sl@0: * were sent to the serial port, the remote device would echo it, sl@0: * then the serial driver would echo it back to the device, etc. sl@0: */ sl@0: sl@0: translation = "auto crlf"; sl@0: channelTypePtr = &ttyChannelType; sl@0: fsPtr = TtyInit(fd, 1); sl@0: } else sl@0: #endif /* SUPPORTS_TTY */ sl@0: { sl@0: translation = NULL; sl@0: channelTypePtr = &fileChannelType; sl@0: fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState)); sl@0: } sl@0: sl@0: #ifdef DEPRECATED sl@0: if (channelTypePtr == &fileChannelType) { sl@0: /* TIP #218. Removed the code inserting the new structure sl@0: * into the global list. This is now handled in the thread sl@0: * action callbacks, and only there. sl@0: */ sl@0: fsPtr->nextPtr = NULL; sl@0: } sl@0: #endif /* DEPRECATED */ sl@0: fsPtr->validMask = channelPermissions | TCL_EXCEPTION; sl@0: fsPtr->fd = fd; sl@0: sl@0: fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName, sl@0: (ClientData) fsPtr, channelPermissions); sl@0: sl@0: if (translation != NULL) { sl@0: /* sl@0: * Gotcha. Most modems need a "\r" at the end of the command sl@0: * sequence. If you just send "at\n", the modem will not respond sl@0: * with "OK" because it never got a "\r" to actually invoke the sl@0: * command. So, by default, newlines are translated to "\r\n" on sl@0: * output to avoid "bug" reports that the serial port isn't working. sl@0: */ sl@0: sl@0: if (Tcl_SetChannelOption(interp, fsPtr->channel, "-translation", sl@0: translation) != TCL_OK) { sl@0: Tcl_Close(NULL, fsPtr->channel); sl@0: return NULL; sl@0: } sl@0: } sl@0: sl@0: return fsPtr->channel; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * Tcl_MakeFileChannel -- sl@0: * sl@0: * Makes a Tcl_Channel from an existing OS level file handle. sl@0: * sl@0: * Results: sl@0: * The Tcl_Channel created around the preexisting OS level file handle. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: EXPORT_C Tcl_Channel sl@0: Tcl_MakeFileChannel(handle, mode) sl@0: ClientData handle; /* OS level handle. */ sl@0: int mode; /* ORed combination of TCL_READABLE and sl@0: * TCL_WRITABLE to indicate file mode. */ sl@0: { sl@0: FileState *fsPtr; sl@0: char channelName[16 + TCL_INTEGER_SPACE]; sl@0: int fd = (int) handle; sl@0: Tcl_ChannelType *channelTypePtr; sl@0: #ifdef DEPRECATED sl@0: ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); sl@0: #endif /* DEPRECATED */ sl@0: struct sockaddr sockaddr; sl@0: socklen_t sockaddrLen = sizeof(sockaddr); sl@0: sl@0: if (mode == 0) { sl@0: return NULL; sl@0: } sl@0: sl@0: sl@0: /* sl@0: * Look to see if a channel with this fd and the same mode already exists. sl@0: * If the fd is used, but the mode doesn't match, return NULL. sl@0: */ sl@0: sl@0: #ifdef DEPRECATED sl@0: for (fsPtr = tsdPtr->firstFilePtr; fsPtr != NULL; fsPtr = fsPtr->nextPtr) { sl@0: if (fsPtr->fd == fd) { sl@0: return ((mode|TCL_EXCEPTION) == fsPtr->validMask) ? sl@0: fsPtr->channel : NULL; sl@0: } sl@0: } sl@0: #endif /* DEPRECATED */ sl@0: sl@0: sockaddr.sa_family = AF_UNSPEC; sl@0: sl@0: #ifdef SUPPORTS_TTY sl@0: if (isatty(fd)) { sl@0: fsPtr = TtyInit(fd, 0); sl@0: channelTypePtr = &ttyChannelType; sl@0: sprintf(channelName, "serial%d", fd); sl@0: } else sl@0: #endif /* SUPPORTS_TTY */ sl@0: if (getsockname(fd, (struct sockaddr *)&sockaddr, &sockaddrLen) == 0 sl@0: && sockaddrLen > 0 sl@0: && sockaddr.sa_family == AF_INET) { sl@0: return MakeTcpClientChannelMode((ClientData) fd, mode); sl@0: } else { sl@0: channelTypePtr = &fileChannelType; sl@0: fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState)); sl@0: sprintf(channelName, "file%d", fd); sl@0: } sl@0: sl@0: #ifdef DEPRECATED sl@0: if (channelTypePtr == &fileChannelType) { sl@0: fsPtr->nextPtr = tsdPtr->firstFilePtr; sl@0: tsdPtr->firstFilePtr = fsPtr; sl@0: } sl@0: #endif /* DEPRECATED */ sl@0: fsPtr->fd = fd; sl@0: fsPtr->validMask = mode | TCL_EXCEPTION; sl@0: fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName, sl@0: (ClientData) fsPtr, mode); sl@0: sl@0: return fsPtr->channel; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpBlockModeProc -- sl@0: * sl@0: * This procedure is invoked by the generic IO level to set blocking sl@0: * and nonblocking mode on a TCP socket based channel. sl@0: * sl@0: * Results: sl@0: * 0 if successful, errno when failed. sl@0: * sl@0: * Side effects: sl@0: * Sets the device into blocking or nonblocking mode. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: /* ARGSUSED */ sl@0: static int sl@0: TcpBlockModeProc(instanceData, mode) sl@0: ClientData instanceData; /* Socket state. */ sl@0: int mode; /* The mode to set. Can be one of sl@0: * TCL_MODE_BLOCKING or sl@0: * TCL_MODE_NONBLOCKING. */ sl@0: { sl@0: TcpState *statePtr = (TcpState *) instanceData; sl@0: int setting; sl@0: sl@0: #ifndef USE_FIONBIO sl@0: setting = fcntl(statePtr->fd, F_GETFL); sl@0: if (mode == TCL_MODE_BLOCKING) { sl@0: statePtr->flags &= (~(TCP_ASYNC_SOCKET)); sl@0: setting &= (~(O_NONBLOCK)); sl@0: } else { sl@0: statePtr->flags |= TCP_ASYNC_SOCKET; sl@0: setting |= O_NONBLOCK; sl@0: } sl@0: if (fcntl(statePtr->fd, F_SETFL, setting) < 0) { sl@0: return errno; sl@0: } sl@0: #else /* USE_FIONBIO */ sl@0: if (mode == TCL_MODE_BLOCKING) { sl@0: statePtr->flags &= (~(TCP_ASYNC_SOCKET)); sl@0: setting = 0; sl@0: if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) { sl@0: return errno; sl@0: } sl@0: } else { sl@0: statePtr->flags |= TCP_ASYNC_SOCKET; sl@0: setting = 1; sl@0: if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) { sl@0: return errno; sl@0: } sl@0: } sl@0: #endif /* !USE_FIONBIO */ sl@0: sl@0: return 0; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * WaitForConnect -- sl@0: * sl@0: * Waits for a connection on an asynchronously opened socket to sl@0: * be completed. sl@0: * sl@0: * Results: sl@0: * None. sl@0: * sl@0: * Side effects: sl@0: * The socket is connected after this function returns. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: WaitForConnect(statePtr, errorCodePtr) sl@0: TcpState *statePtr; /* State of the socket. */ sl@0: int *errorCodePtr; /* Where to store errors? */ sl@0: { sl@0: int timeOut; /* How long to wait. */ sl@0: int state; /* Of calling TclWaitForFile. */ sl@0: int flags; /* fcntl flags for the socket. */ sl@0: sl@0: /* sl@0: * If an asynchronous connect is in progress, attempt to wait for it sl@0: * to complete before reading. sl@0: */ sl@0: sl@0: if (statePtr->flags & TCP_ASYNC_CONNECT) { sl@0: if (statePtr->flags & TCP_ASYNC_SOCKET) { sl@0: timeOut = 0; sl@0: } else { sl@0: timeOut = -1; sl@0: } sl@0: errno = 0; sl@0: state = TclUnixWaitForFile(statePtr->fd, sl@0: TCL_WRITABLE | TCL_EXCEPTION, timeOut); sl@0: if (!(statePtr->flags & TCP_ASYNC_SOCKET)) { sl@0: #ifndef USE_FIONBIO sl@0: flags = fcntl(statePtr->fd, F_GETFL); sl@0: flags &= (~(O_NONBLOCK)); sl@0: (void) fcntl(statePtr->fd, F_SETFL, flags); sl@0: #else /* USE_FIONBIO */ sl@0: flags = 0; sl@0: (void) ioctl(statePtr->fd, FIONBIO, &flags); sl@0: #endif /* !USE_FIONBIO */ sl@0: } sl@0: if (state & TCL_EXCEPTION) { sl@0: return -1; sl@0: } sl@0: if (state & TCL_WRITABLE) { sl@0: statePtr->flags &= (~(TCP_ASYNC_CONNECT)); sl@0: } else if (timeOut == 0) { sl@0: *errorCodePtr = errno = EWOULDBLOCK; sl@0: return -1; sl@0: } sl@0: } sl@0: return 0; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpInputProc -- sl@0: * sl@0: * This procedure is invoked by the generic IO level to read input sl@0: * from a TCP socket based channel. sl@0: * sl@0: * NOTE: We cannot share code with FilePipeInputProc because here sl@0: * we must use recv to obtain the input from the channel, not read. sl@0: * sl@0: * Results: sl@0: * The number of bytes read is returned or -1 on error. An output sl@0: * argument contains the POSIX error code on error, or zero if no sl@0: * error occurred. sl@0: * sl@0: * Side effects: sl@0: * Reads input from the input device of the channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: /* ARGSUSED */ sl@0: static int sl@0: TcpInputProc(instanceData, buf, bufSize, errorCodePtr) sl@0: ClientData instanceData; /* Socket state. */ sl@0: char *buf; /* Where to store data read. */ sl@0: int bufSize; /* How much space is available sl@0: * in the buffer? */ sl@0: int *errorCodePtr; /* Where to store error code. */ sl@0: { sl@0: TcpState *statePtr = (TcpState *) instanceData; sl@0: int bytesRead, state; sl@0: sl@0: *errorCodePtr = 0; sl@0: state = WaitForConnect(statePtr, errorCodePtr); sl@0: if (state != 0) { sl@0: return -1; sl@0: } sl@0: bytesRead = recv(statePtr->fd, buf, (size_t) bufSize, 0); sl@0: if (bytesRead > -1) { sl@0: return bytesRead; sl@0: } sl@0: if (errno == ECONNRESET) { sl@0: /* sl@0: * Turn ECONNRESET into a soft EOF condition. sl@0: */ sl@0: sl@0: return 0; sl@0: } sl@0: *errorCodePtr = errno; sl@0: return -1; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpOutputProc -- sl@0: * sl@0: * This procedure is invoked by the generic IO level to write output sl@0: * to a TCP socket based channel. sl@0: * sl@0: * NOTE: We cannot share code with FilePipeOutputProc because here sl@0: * we must use send, not write, to get reliable error reporting. sl@0: * sl@0: * Results: sl@0: * The number of bytes written is returned. An output argument is sl@0: * set to a POSIX error code if an error occurred, or zero. sl@0: * sl@0: * Side effects: sl@0: * Writes output on the output device of the channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) sl@0: ClientData instanceData; /* Socket state. */ sl@0: CONST char *buf; /* The data buffer. */ sl@0: int toWrite; /* How many bytes to write? */ sl@0: int *errorCodePtr; /* Where to store error code. */ sl@0: { sl@0: TcpState *statePtr = (TcpState *) instanceData; sl@0: int written; sl@0: int state; /* Of waiting for connection. */ sl@0: sl@0: *errorCodePtr = 0; sl@0: state = WaitForConnect(statePtr, errorCodePtr); sl@0: if (state != 0) { sl@0: return -1; sl@0: } sl@0: written = send(statePtr->fd, buf, (size_t) toWrite, 0); sl@0: if (written > -1) { sl@0: return written; sl@0: } sl@0: *errorCodePtr = errno; sl@0: return -1; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpCloseProc -- sl@0: * sl@0: * This procedure is invoked by the generic IO level to perform sl@0: * channel-type-specific cleanup when a TCP socket based channel sl@0: * is closed. sl@0: * sl@0: * Results: sl@0: * 0 if successful, the value of errno if failed. sl@0: * sl@0: * Side effects: sl@0: * Closes the socket of the channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: /* ARGSUSED */ sl@0: static int sl@0: TcpCloseProc(instanceData, interp) sl@0: ClientData instanceData; /* The socket to close. */ sl@0: Tcl_Interp *interp; /* For error reporting - unused. */ sl@0: { sl@0: TcpState *statePtr = (TcpState *) instanceData; sl@0: int errorCode = 0; sl@0: sl@0: /* sl@0: * Delete a file handler that may be active for this socket if this sl@0: * is a server socket - the file handler was created automatically sl@0: * by Tcl as part of the mechanism to accept new client connections. sl@0: * Channel handlers are already deleted in the generic IO channel sl@0: * closing code that called this function, so we do not have to sl@0: * delete them here. sl@0: */ sl@0: sl@0: Tcl_DeleteFileHandler(statePtr->fd); sl@0: sl@0: if (close(statePtr->fd) < 0) { sl@0: errorCode = errno; sl@0: } sl@0: ckfree((char *) statePtr); sl@0: sl@0: return errorCode; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpGetOptionProc -- sl@0: * sl@0: * Computes an option value for a TCP socket based channel, or a sl@0: * list of all options and their values. sl@0: * sl@0: * Note: This code is based on code contributed by John Haxby. sl@0: * sl@0: * Results: sl@0: * A standard Tcl result. The value of the specified option or a sl@0: * list of all options and their values is returned in the sl@0: * supplied DString. Sets Error message if needed. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: TcpGetOptionProc(instanceData, interp, optionName, dsPtr) sl@0: ClientData instanceData; /* Socket state. */ sl@0: Tcl_Interp *interp; /* For error reporting - can be NULL. */ sl@0: CONST char *optionName; /* Name of the option to sl@0: * retrieve the value for, or sl@0: * NULL to get all options and sl@0: * their values. */ sl@0: Tcl_DString *dsPtr; /* Where to store the computed sl@0: * value; initialized by caller. */ sl@0: { sl@0: TcpState *statePtr = (TcpState *) instanceData; sl@0: struct sockaddr_in sockname; sl@0: struct sockaddr_in peername; sl@0: struct hostent *hostEntPtr; sl@0: socklen_t size = sizeof(struct sockaddr_in); sl@0: size_t len = 0; sl@0: char buf[TCL_INTEGER_SPACE]; sl@0: sl@0: if (optionName != (char *) NULL) { sl@0: len = strlen(optionName); sl@0: } sl@0: sl@0: if ((len > 1) && (optionName[1] == 'e') && sl@0: (strncmp(optionName, "-error", len) == 0)) { sl@0: socklen_t optlen = sizeof(int); sl@0: int err, ret; sl@0: err = 0; sl@0: sl@0: sl@0: ret = getsockopt(statePtr->fd, SOL_SOCKET, SO_ERROR, sl@0: (char *)&err, &optlen); sl@0: if (ret < 0) { sl@0: err = errno; sl@0: } sl@0: if (err != 0) { sl@0: Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(err), -1); sl@0: } sl@0: return TCL_OK; sl@0: } sl@0: sl@0: if ((len == 0) || sl@0: ((len > 1) && (optionName[1] == 'p') && sl@0: (strncmp(optionName, "-peername", len) == 0))) { sl@0: if (getpeername(statePtr->fd, (struct sockaddr *) &peername, sl@0: &size) >= 0) { sl@0: if (len == 0) { sl@0: Tcl_DStringAppendElement(dsPtr, "-peername"); sl@0: Tcl_DStringStartSublist(dsPtr); sl@0: } sl@0: Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr)); sl@0: hostEntPtr = TclpGetHostByAddr( /* INTL: Native. */ sl@0: (char *) &peername.sin_addr, sl@0: sizeof(peername.sin_addr), AF_INET); sl@0: if (hostEntPtr != (struct hostent *) NULL) { sl@0: Tcl_DString ds; sl@0: sl@0: Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds); sl@0: Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds)); sl@0: Tcl_DStringFree(&ds); sl@0: } else { sl@0: Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr)); sl@0: } sl@0: TclFormatInt(buf, ntohs(peername.sin_port)); sl@0: Tcl_DStringAppendElement(dsPtr, buf); sl@0: if (len == 0) { sl@0: Tcl_DStringEndSublist(dsPtr); sl@0: } else { sl@0: return TCL_OK; sl@0: } sl@0: } else { sl@0: /* sl@0: * getpeername failed - but if we were asked for all the options sl@0: * (len==0), don't flag an error at that point because it could sl@0: * be an fconfigure request on a server socket. (which have sl@0: * no peer). same must be done on win&mac. sl@0: */ sl@0: sl@0: if (len) { sl@0: if (interp) { sl@0: Tcl_AppendResult(interp, "can't get peername: ", sl@0: Tcl_PosixError(interp), (char *) NULL); sl@0: } sl@0: return TCL_ERROR; sl@0: } sl@0: } sl@0: } sl@0: sl@0: if ((len == 0) || sl@0: ((len > 1) && (optionName[1] == 's') && sl@0: (strncmp(optionName, "-sockname", len) == 0))) { sl@0: if (getsockname(statePtr->fd, (struct sockaddr *) &sockname, sl@0: &size) >= 0) { sl@0: if (len == 0) { sl@0: Tcl_DStringAppendElement(dsPtr, "-sockname"); sl@0: Tcl_DStringStartSublist(dsPtr); sl@0: } sl@0: Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr)); sl@0: hostEntPtr = TclpGetHostByAddr( /* INTL: Native. */ sl@0: (char *) &sockname.sin_addr, sl@0: sizeof(sockname.sin_addr), AF_INET); sl@0: if (hostEntPtr != (struct hostent *) NULL) { sl@0: Tcl_DString ds; sl@0: sl@0: Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds); sl@0: Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds)); sl@0: Tcl_DStringFree(&ds); sl@0: } else { sl@0: Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr)); sl@0: } sl@0: TclFormatInt(buf, ntohs(sockname.sin_port)); sl@0: Tcl_DStringAppendElement(dsPtr, buf); sl@0: if (len == 0) { sl@0: Tcl_DStringEndSublist(dsPtr); sl@0: } else { sl@0: return TCL_OK; sl@0: } sl@0: } else { sl@0: if (interp) { sl@0: Tcl_AppendResult(interp, "can't get sockname: ", sl@0: Tcl_PosixError(interp), (char *) NULL); sl@0: } sl@0: return TCL_ERROR; sl@0: } sl@0: } sl@0: sl@0: if (len > 0) { sl@0: return Tcl_BadChannelOption(interp, optionName, "peername sockname"); sl@0: } sl@0: sl@0: return TCL_OK; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpWatchProc -- sl@0: * sl@0: * Initialize the notifier to watch the fd from this channel. sl@0: * sl@0: * Results: sl@0: * None. sl@0: * sl@0: * Side effects: sl@0: * Sets up the notifier so that a future event on the channel will sl@0: * be seen by Tcl. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static void sl@0: TcpWatchProc(instanceData, mask) sl@0: ClientData instanceData; /* The socket state. */ sl@0: int mask; /* Events of interest; an OR-ed sl@0: * combination of TCL_READABLE, sl@0: * TCL_WRITABLE and TCL_EXCEPTION. */ sl@0: { sl@0: TcpState *statePtr = (TcpState *) instanceData; sl@0: sl@0: /* sl@0: * Make sure we don't mess with server sockets since they will never sl@0: * be readable or writable at the Tcl level. This keeps Tcl scripts sl@0: * from interfering with the -accept behavior. sl@0: */ sl@0: sl@0: if (!statePtr->acceptProc) { sl@0: if (mask) { sl@0: Tcl_CreateFileHandler(statePtr->fd, mask, sl@0: (Tcl_FileProc *) Tcl_NotifyChannel, sl@0: (ClientData) statePtr->channel); sl@0: } else { sl@0: Tcl_DeleteFileHandler(statePtr->fd); sl@0: } sl@0: } sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpGetHandleProc -- sl@0: * sl@0: * Called from Tcl_GetChannelHandle to retrieve OS handles from inside sl@0: * a TCP socket based channel. sl@0: * sl@0: * Results: sl@0: * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if sl@0: * there is no handle for the specified direction. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: /* ARGSUSED */ sl@0: static int sl@0: TcpGetHandleProc(instanceData, direction, handlePtr) sl@0: ClientData instanceData; /* The socket state. */ sl@0: int direction; /* Not used. */ sl@0: ClientData *handlePtr; /* Where to store the handle. */ sl@0: { sl@0: TcpState *statePtr = (TcpState *) instanceData; sl@0: sl@0: *handlePtr = (ClientData)statePtr->fd; sl@0: return TCL_OK; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * CreateSocket -- sl@0: * sl@0: * This function opens a new socket in client or server mode sl@0: * and initializes the TcpState structure. sl@0: * sl@0: * Results: sl@0: * Returns a new TcpState, or NULL with an error in the interp's sl@0: * result, if interp is not NULL. sl@0: * sl@0: * Side effects: sl@0: * Opens a socket. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static TcpState * sl@0: CreateSocket(interp, port, host, server, myaddr, myport, async) sl@0: Tcl_Interp *interp; /* For error reporting; can be NULL. */ sl@0: int port; /* Port number to open. */ sl@0: CONST char *host; /* Name of host on which to open port. sl@0: * NULL implies INADDR_ANY */ sl@0: int server; /* 1 if socket should be a server socket, sl@0: * else 0 for a client socket. */ sl@0: CONST char *myaddr; /* Optional client-side address */ sl@0: int myport; /* Optional client-side port */ sl@0: int async; /* If nonzero and creating a client socket, sl@0: * attempt to do an async connect. Otherwise sl@0: * do a synchronous connect or bind. */ sl@0: { sl@0: int status, sock, asyncConnect, curState, origState; sl@0: struct sockaddr_in sockaddr; /* socket address */ sl@0: struct sockaddr_in mysockaddr; /* Socket address for client */ sl@0: TcpState *statePtr; sl@0: sl@0: sock = -1; sl@0: origState = 0; sl@0: if (! CreateSocketAddress(&sockaddr, host, port)) { sl@0: goto addressError; sl@0: } sl@0: if ((myaddr != NULL || myport != 0) && sl@0: ! CreateSocketAddress(&mysockaddr, myaddr, myport)) { sl@0: goto addressError; sl@0: } sl@0: sl@0: sock = socket(AF_INET, SOCK_STREAM, 0); sl@0: if (sock < 0) { sl@0: goto addressError; sl@0: } sl@0: sl@0: /* sl@0: * Set the close-on-exec flag so that the socket will not get sl@0: * inherited by child processes. sl@0: */ sl@0: sl@0: fcntl(sock, F_SETFD, FD_CLOEXEC); sl@0: sl@0: /* sl@0: * Set kernel space buffering sl@0: */ sl@0: sl@0: TclSockMinimumBuffers(sock, SOCKET_BUFSIZE); sl@0: sl@0: asyncConnect = 0; sl@0: status = 0; sl@0: if (server) { sl@0: /* sl@0: * Set up to reuse server addresses automatically and bind to the sl@0: * specified port. sl@0: */ sl@0: sl@0: status = 1; sl@0: (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status, sl@0: sizeof(status)); sl@0: status = bind(sock, (struct sockaddr *) &sockaddr, sl@0: sizeof(struct sockaddr)); sl@0: if (status != -1) { sl@0: status = listen(sock, SOMAXCONN); sl@0: } sl@0: } else { sl@0: if (myaddr != NULL || myport != 0) { sl@0: curState = 1; sl@0: (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, sl@0: (char *) &curState, sizeof(curState)); sl@0: status = bind(sock, (struct sockaddr *) &mysockaddr, sl@0: sizeof(struct sockaddr)); sl@0: if (status < 0) { sl@0: goto bindError; sl@0: } sl@0: } sl@0: sl@0: /* sl@0: * Attempt to connect. The connect may fail at present with an sl@0: * EINPROGRESS but at a later time it will complete. The caller sl@0: * will set up a file handler on the socket if she is interested in sl@0: * being informed when the connect completes. sl@0: */ sl@0: sl@0: if (async) { sl@0: #ifndef USE_FIONBIO sl@0: origState = fcntl(sock, F_GETFL); sl@0: curState = origState | O_NONBLOCK; sl@0: status = fcntl(sock, F_SETFL, curState); sl@0: #else /* USE_FIONBIO */ sl@0: curState = 1; sl@0: status = ioctl(sock, FIONBIO, &curState); sl@0: #endif /* !USE_FIONBIO */ sl@0: } else { sl@0: status = 0; sl@0: } sl@0: if (status > -1) { sl@0: status = connect(sock, (struct sockaddr *) &sockaddr, sl@0: sizeof(sockaddr)); sl@0: if (status < 0) { sl@0: if (errno == EINPROGRESS) { sl@0: asyncConnect = 1; sl@0: status = 0; sl@0: } sl@0: } else { sl@0: /* sl@0: * Here we are if the connect succeeds. In case of an sl@0: * asynchronous connect we have to reset the channel to sl@0: * blocking mode. This appears to happen not very often, sl@0: * but e.g. on a HP 9000/800 under HP-UX B.11.00 we enter sl@0: * this stage. [Bug: 4388] sl@0: */ sl@0: if (async) { sl@0: #ifndef USE_FIONBIO sl@0: origState = fcntl(sock, F_GETFL); sl@0: curState = origState & ~(O_NONBLOCK); sl@0: status = fcntl(sock, F_SETFL, curState); sl@0: #else /* USE_FIONBIO */ sl@0: curState = 0; sl@0: status = ioctl(sock, FIONBIO, &curState); sl@0: #endif /* !USE_FIONBIO */ sl@0: } sl@0: } sl@0: } sl@0: } sl@0: sl@0: bindError: sl@0: if (status < 0) { sl@0: if (interp != NULL) { sl@0: Tcl_AppendResult(interp, "couldn't open socket: ", sl@0: Tcl_PosixError(interp), (char *) NULL); sl@0: } sl@0: if (sock != -1) { sl@0: close(sock); sl@0: } sl@0: return NULL; sl@0: } sl@0: sl@0: /* sl@0: * Allocate a new TcpState for this socket. sl@0: */ sl@0: sl@0: statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState)); sl@0: statePtr->flags = 0; sl@0: if (asyncConnect) { sl@0: statePtr->flags = TCP_ASYNC_CONNECT; sl@0: } sl@0: statePtr->fd = sock; sl@0: sl@0: return statePtr; sl@0: sl@0: addressError: sl@0: if (sock != -1) { sl@0: close(sock); sl@0: } sl@0: if (interp != NULL) { sl@0: Tcl_AppendResult(interp, "couldn't open socket: ", sl@0: Tcl_PosixError(interp), (char *) NULL); sl@0: } sl@0: return NULL; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * CreateSocketAddress -- sl@0: * sl@0: * This function initializes a sockaddr structure for a host and port. sl@0: * sl@0: * Results: sl@0: * 1 if the host was valid, 0 if the host could not be converted to sl@0: * an IP address. sl@0: * sl@0: * Side effects: sl@0: * Fills in the *sockaddrPtr structure. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static int sl@0: CreateSocketAddress(sockaddrPtr, host, port) sl@0: struct sockaddr_in *sockaddrPtr; /* Socket address */ sl@0: CONST char *host; /* Host. NULL implies INADDR_ANY */ sl@0: int port; /* Port number */ sl@0: { sl@0: struct hostent *hostent; /* Host database entry */ sl@0: struct in_addr addr; /* For 64/32 bit madness */ sl@0: sl@0: #ifdef __SYMBIAN32__ sl@0: if (host && !strcmp(host, "localhost")) { sl@0: char* loc = strstr(host, "localhost"); sl@0: memcpy(loc, "127.0.0.1", 9); sl@0: } sl@0: #endif sl@0: (void) memset((VOID *) sockaddrPtr, '\0', sizeof(struct sockaddr_in)); sl@0: sockaddrPtr->sin_family = AF_INET; sl@0: sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF)); sl@0: if (host == NULL) { sl@0: addr.s_addr = INADDR_ANY; sl@0: } else { sl@0: Tcl_DString ds; sl@0: CONST char *native; sl@0: sl@0: if (host == NULL) { sl@0: native = NULL; sl@0: } else { sl@0: native = Tcl_UtfToExternalDString(NULL, host, -1, &ds); sl@0: } sl@0: addr.s_addr = inet_addr(native); /* INTL: Native. */ sl@0: /* sl@0: * This is 0xFFFFFFFF to ensure that it compares as a 32bit -1 sl@0: * on either 32 or 64 bits systems. sl@0: */ sl@0: if (addr.s_addr == 0xFFFFFFFF) { sl@0: hostent = TclpGetHostByName(native); /* INTL: Native. */ sl@0: if (hostent != (struct hostent *) NULL) { sl@0: memcpy((VOID *) &addr, sl@0: (VOID *) hostent->h_addr_list[0], sl@0: (size_t) hostent->h_length); sl@0: } else { sl@0: #ifdef EHOSTUNREACH sl@0: errno = EHOSTUNREACH; sl@0: #else /* !EHOSTUNREACH */ sl@0: #ifdef ENXIO sl@0: errno = ENXIO; sl@0: #endif /* ENXIO */ sl@0: #endif /* EHOSTUNREACH */ sl@0: if (native != NULL) { sl@0: Tcl_DStringFree(&ds); sl@0: } sl@0: return 0; /* error */ sl@0: } sl@0: } sl@0: if (native != NULL) { sl@0: Tcl_DStringFree(&ds); sl@0: } sl@0: } sl@0: sl@0: /* sl@0: * NOTE: On 64 bit machines the assignment below is rumored to not sl@0: * do the right thing. Please report errors related to this if you sl@0: * observe incorrect behavior on 64 bit machines such as DEC Alphas. sl@0: * Should we modify this code to do an explicit memcpy? sl@0: */ sl@0: sl@0: sockaddrPtr->sin_addr.s_addr = addr.s_addr; sl@0: return 1; /* Success. */ sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * Tcl_OpenTcpClient -- sl@0: * sl@0: * Opens a TCP client socket and creates a channel around it. sl@0: * sl@0: * Results: sl@0: * The channel or NULL if failed. An error message is returned sl@0: * in the interpreter on failure. sl@0: * sl@0: * Side effects: sl@0: * Opens a client socket and creates a new channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: EXPORT_C Tcl_Channel sl@0: Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async) sl@0: Tcl_Interp *interp; /* For error reporting; can be NULL. */ sl@0: int port; /* Port number to open. */ sl@0: CONST char *host; /* Host on which to open port. */ sl@0: CONST char *myaddr; /* Client-side address */ sl@0: int myport; /* Client-side port */ sl@0: int async; /* If nonzero, attempt to do an sl@0: * asynchronous connect. Otherwise sl@0: * we do a blocking connect. */ sl@0: { sl@0: TcpState *statePtr; sl@0: char channelName[16 + TCL_INTEGER_SPACE]; sl@0: sl@0: /* sl@0: * Create a new client socket and wrap it in a channel. sl@0: */ sl@0: sl@0: statePtr = CreateSocket(interp, port, host, 0, myaddr, myport, async); sl@0: if (statePtr == NULL) { sl@0: return NULL; sl@0: } sl@0: sl@0: statePtr->acceptProc = NULL; sl@0: statePtr->acceptProcData = (ClientData) NULL; sl@0: sl@0: sprintf(channelName, "sock%d", statePtr->fd); sl@0: sl@0: statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName, sl@0: (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE)); sl@0: if (Tcl_SetChannelOption(interp, statePtr->channel, "-translation", sl@0: "auto crlf") == TCL_ERROR) { sl@0: Tcl_Close((Tcl_Interp *) NULL, statePtr->channel); sl@0: return NULL; sl@0: } sl@0: return statePtr->channel; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * Tcl_MakeTcpClientChannel -- sl@0: * sl@0: * Creates a Tcl_Channel from an existing client TCP socket. sl@0: * sl@0: * Results: sl@0: * The Tcl_Channel wrapped around the preexisting TCP socket. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: EXPORT_C Tcl_Channel sl@0: Tcl_MakeTcpClientChannel(sock) sl@0: ClientData sock; /* The socket to wrap up into a channel. */ sl@0: { sl@0: return MakeTcpClientChannelMode(sock, (TCL_READABLE | TCL_WRITABLE)); sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * MakeTcpClientChannelMode -- sl@0: * sl@0: * Creates a Tcl_Channel from an existing client TCP socket sl@0: * with given mode. sl@0: * sl@0: * Results: sl@0: * The Tcl_Channel wrapped around the preexisting TCP socket. sl@0: * sl@0: * Side effects: sl@0: * None. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static Tcl_Channel sl@0: MakeTcpClientChannelMode(sock, mode) sl@0: ClientData sock; /* The socket to wrap up into a channel. */ sl@0: int mode; /* ORed combination of TCL_READABLE and sl@0: * TCL_WRITABLE to indicate file mode. */ sl@0: { sl@0: TcpState *statePtr; sl@0: char channelName[16 + TCL_INTEGER_SPACE]; sl@0: sl@0: statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState)); sl@0: statePtr->fd = (int) sock; sl@0: statePtr->flags = 0; sl@0: statePtr->acceptProc = NULL; sl@0: statePtr->acceptProcData = (ClientData) NULL; sl@0: sl@0: sprintf(channelName, "sock%d", statePtr->fd); sl@0: sl@0: statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName, sl@0: (ClientData) statePtr, mode); sl@0: if (Tcl_SetChannelOption((Tcl_Interp *) NULL, statePtr->channel, sl@0: "-translation", "auto crlf") == TCL_ERROR) { sl@0: Tcl_Close((Tcl_Interp *) NULL, statePtr->channel); sl@0: return NULL; sl@0: } sl@0: return statePtr->channel; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * Tcl_OpenTcpServer -- sl@0: * sl@0: * Opens a TCP server socket and creates a channel around it. sl@0: * sl@0: * Results: sl@0: * The channel or NULL if failed. If an error occurred, an sl@0: * error message is left in the interp's result if interp is sl@0: * not NULL. sl@0: * sl@0: * Side effects: sl@0: * Opens a server socket and creates a new channel. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: EXPORT_C Tcl_Channel sl@0: Tcl_OpenTcpServer(interp, port, myHost, acceptProc, acceptProcData) sl@0: Tcl_Interp *interp; /* For error reporting - may be sl@0: * NULL. */ sl@0: int port; /* Port number to open. */ sl@0: CONST char *myHost; /* Name of local host. */ sl@0: Tcl_TcpAcceptProc *acceptProc; /* Callback for accepting connections sl@0: * from new clients. */ sl@0: ClientData acceptProcData; /* Data for the callback. */ sl@0: { sl@0: TcpState *statePtr; sl@0: char channelName[16 + TCL_INTEGER_SPACE]; sl@0: sl@0: /* sl@0: * Create a new client socket and wrap it in a channel. sl@0: */ sl@0: sl@0: statePtr = CreateSocket(interp, port, myHost, 1, NULL, 0, 0); sl@0: if (statePtr == NULL) { sl@0: return NULL; sl@0: } sl@0: sl@0: statePtr->acceptProc = acceptProc; sl@0: statePtr->acceptProcData = acceptProcData; sl@0: sl@0: /* sl@0: * Set up the callback mechanism for accepting connections sl@0: * from new clients. sl@0: */ sl@0: sl@0: Tcl_CreateFileHandler(statePtr->fd, TCL_READABLE, TcpAccept, sl@0: (ClientData) statePtr); sl@0: sprintf(channelName, "sock%d", statePtr->fd); sl@0: statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName, sl@0: (ClientData) statePtr, 0); sl@0: return statePtr->channel; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TcpAccept -- sl@0: * Accept a TCP socket connection. This is called by the event loop. sl@0: * sl@0: * Results: sl@0: * None. sl@0: * sl@0: * Side effects: sl@0: * Creates a new connection socket. Calls the registered callback sl@0: * for the connection acceptance mechanism. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: /* ARGSUSED */ sl@0: static void sl@0: TcpAccept(data, mask) sl@0: ClientData data; /* Callback token. */ sl@0: int mask; /* Not used. */ sl@0: { sl@0: TcpState *sockState; /* Client data of server socket. */ sl@0: int newsock; /* The new client socket */ sl@0: TcpState *newSockState; /* State for new socket. */ sl@0: struct sockaddr_in addr; /* The remote address */ sl@0: socklen_t len; /* For accept interface */ sl@0: char channelName[16 + TCL_INTEGER_SPACE]; sl@0: sl@0: sockState = (TcpState *) data; sl@0: sl@0: len = sizeof(struct sockaddr_in); sl@0: newsock = accept(sockState->fd, (struct sockaddr *) &addr, &len); sl@0: if (newsock < 0) { sl@0: return; sl@0: } sl@0: sl@0: /* sl@0: * Set close-on-exec flag to prevent the newly accepted socket from sl@0: * being inherited by child processes. sl@0: */ sl@0: sl@0: (void) fcntl(newsock, F_SETFD, FD_CLOEXEC); sl@0: sl@0: newSockState = (TcpState *) ckalloc((unsigned) sizeof(TcpState)); sl@0: sl@0: newSockState->flags = 0; sl@0: newSockState->fd = newsock; sl@0: newSockState->acceptProc = NULL; sl@0: newSockState->acceptProcData = NULL; sl@0: sl@0: sprintf(channelName, "sock%d", newsock); sl@0: newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName, sl@0: (ClientData) newSockState, (TCL_READABLE | TCL_WRITABLE)); sl@0: sl@0: Tcl_SetChannelOption(NULL, newSockState->channel, "-translation", sl@0: "auto crlf"); sl@0: sl@0: if (sockState->acceptProc != NULL) { sl@0: (*sockState->acceptProc)(sockState->acceptProcData, sl@0: newSockState->channel, inet_ntoa(addr.sin_addr), sl@0: ntohs(addr.sin_port)); sl@0: } sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TclpGetDefaultStdChannel -- sl@0: * sl@0: * Creates channels for standard input, standard output or standard sl@0: * error output if they do not already exist. sl@0: * sl@0: * Results: sl@0: * Returns the specified default standard channel, or NULL. sl@0: * sl@0: * Side effects: sl@0: * May cause the creation of a standard channel and the underlying sl@0: * file. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: Tcl_Channel sl@0: TclpGetDefaultStdChannel(type) sl@0: int type; /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */ sl@0: { sl@0: Tcl_Channel channel = NULL; sl@0: int fd = 0; /* Initializations needed to prevent */ sl@0: int mode = 0; /* compiler warning (used before set). */ sl@0: char *bufMode = NULL; sl@0: sl@0: /* sl@0: * Some #def's to make the code a little clearer! sl@0: */ sl@0: #define ZERO_OFFSET ((Tcl_SeekOffset) 0) sl@0: #define ERROR_OFFSET ((Tcl_SeekOffset) -1) sl@0: sl@0: switch (type) { sl@0: case TCL_STDIN: sl@0: if ((TclOSseek(0, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET) sl@0: && (errno == EBADF)) { sl@0: return (Tcl_Channel) NULL; sl@0: } sl@0: fd = 0; sl@0: mode = TCL_READABLE; sl@0: bufMode = "line"; sl@0: break; sl@0: case TCL_STDOUT: sl@0: if ((TclOSseek(1, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET) sl@0: && (errno == EBADF)) { sl@0: return (Tcl_Channel) NULL; sl@0: } sl@0: fd = 1; sl@0: mode = TCL_WRITABLE; sl@0: bufMode = "line"; sl@0: break; sl@0: case TCL_STDERR: sl@0: if ((TclOSseek(2, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET) sl@0: && (errno == EBADF)) { sl@0: return (Tcl_Channel) NULL; sl@0: } sl@0: fd = 2; sl@0: mode = TCL_WRITABLE; sl@0: bufMode = "none"; sl@0: break; sl@0: default: sl@0: panic("TclGetDefaultStdChannel: Unexpected channel type"); sl@0: break; sl@0: } sl@0: sl@0: #undef ZERO_OFFSET sl@0: #undef ERROR_OFFSET sl@0: sl@0: channel = Tcl_MakeFileChannel((ClientData) fd, mode); sl@0: if (channel == NULL) { sl@0: return NULL; sl@0: } sl@0: sl@0: /* sl@0: * Set up the normal channel options for stdio handles. sl@0: */ sl@0: sl@0: if (Tcl_GetChannelType(channel) == &fileChannelType) { sl@0: Tcl_SetChannelOption(NULL, channel, "-translation", "auto"); sl@0: } else { sl@0: Tcl_SetChannelOption(NULL, channel, "-translation", "auto crlf"); sl@0: } sl@0: Tcl_SetChannelOption(NULL, channel, "-buffering", bufMode); sl@0: return channel; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * Tcl_GetOpenFile -- sl@0: * sl@0: * Given a name of a channel registered in the given interpreter, sl@0: * returns a FILE * for it. sl@0: * sl@0: * Results: sl@0: * A standard Tcl result. If the channel is registered in the given sl@0: * interpreter and it is managed by the "file" channel driver, and sl@0: * it is open for the requested mode, then the output parameter sl@0: * filePtr is set to a FILE * for the underlying file. On error, the sl@0: * filePtr is not set, TCL_ERROR is returned and an error message is sl@0: * left in the interp's result. sl@0: * sl@0: * Side effects: sl@0: * May invoke fdopen to create the FILE * for the requested file. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: EXPORT_C int sl@0: Tcl_GetOpenFile(interp, string, forWriting, checkUsage, filePtr) sl@0: Tcl_Interp *interp; /* Interpreter in which to find file. */ sl@0: CONST char *string; /* String that identifies file. */ sl@0: int forWriting; /* 1 means the file is going to be used sl@0: * for writing, 0 means for reading. */ sl@0: int checkUsage; /* 1 means verify that the file was opened sl@0: * in a mode that allows the access specified sl@0: * by "forWriting". Ignored, we always sl@0: * check that the channel is open for the sl@0: * requested mode. */ sl@0: ClientData *filePtr; /* Store pointer to FILE structure here. */ sl@0: { sl@0: Tcl_Channel chan; sl@0: int chanMode; sl@0: Tcl_ChannelType *chanTypePtr; sl@0: ClientData data; sl@0: int fd; sl@0: FILE *f; sl@0: sl@0: chan = Tcl_GetChannel(interp, string, &chanMode); sl@0: if (chan == (Tcl_Channel) NULL) { sl@0: return TCL_ERROR; sl@0: } sl@0: if ((forWriting) && ((chanMode & TCL_WRITABLE) == 0)) { sl@0: Tcl_AppendResult(interp, sl@0: "\"", string, "\" wasn't opened for writing", (char *) NULL); sl@0: return TCL_ERROR; sl@0: } else if ((!(forWriting)) && ((chanMode & TCL_READABLE) == 0)) { sl@0: Tcl_AppendResult(interp, sl@0: "\"", string, "\" wasn't opened for reading", (char *) NULL); sl@0: return TCL_ERROR; sl@0: } sl@0: sl@0: /* sl@0: * We allow creating a FILE * out of file based, pipe based and socket sl@0: * based channels. We currently do not allow any other channel types, sl@0: * because it is likely that stdio will not know what to do with them. sl@0: */ sl@0: sl@0: chanTypePtr = Tcl_GetChannelType(chan); sl@0: if ((chanTypePtr == &fileChannelType) sl@0: #ifdef SUPPORTS_TTY sl@0: || (chanTypePtr == &ttyChannelType) sl@0: #endif /* SUPPORTS_TTY */ sl@0: || (chanTypePtr == &tcpChannelType) sl@0: || (strcmp(chanTypePtr->typeName, "pipe") == 0)) { sl@0: if (Tcl_GetChannelHandle(chan, sl@0: (forWriting ? TCL_WRITABLE : TCL_READABLE), sl@0: (ClientData*) &data) == TCL_OK) { sl@0: fd = (int) data; sl@0: sl@0: /* sl@0: * The call to fdopen below is probably dangerous, since it will sl@0: * truncate an existing file if the file is being opened sl@0: * for writing.... sl@0: */ sl@0: sl@0: f = fdopen(fd, (forWriting ? "w" : "r")); sl@0: if (f == NULL) { sl@0: Tcl_AppendResult(interp, "cannot get a FILE * for \"", string, sl@0: "\"", (char *) NULL); sl@0: return TCL_ERROR; sl@0: } sl@0: *filePtr = (ClientData) f; sl@0: return TCL_OK; sl@0: } sl@0: } sl@0: sl@0: Tcl_AppendResult(interp, "\"", string, sl@0: "\" cannot be used to get a FILE *", (char *) NULL); sl@0: return TCL_ERROR; sl@0: } sl@0: sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * TclUnixWaitForFile -- sl@0: * sl@0: * This procedure waits synchronously for a file to become readable sl@0: * or writable, with an optional timeout. sl@0: * sl@0: * Results: sl@0: * The return value is an OR'ed combination of TCL_READABLE, sl@0: * TCL_WRITABLE, and TCL_EXCEPTION, indicating the conditions sl@0: * that are present on file at the time of the return. This sl@0: * procedure will not return until either "timeout" milliseconds sl@0: * have elapsed or at least one of the conditions given by mask sl@0: * has occurred for file (a return value of 0 means that a timeout sl@0: * occurred). No normal events will be serviced during the sl@0: * execution of this procedure. sl@0: * sl@0: * Side effects: sl@0: * Time passes. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: int sl@0: TclUnixWaitForFile(fd, mask, timeout) sl@0: int fd; /* Handle for file on which to wait. */ sl@0: int mask; /* What to wait for: OR'ed combination of sl@0: * TCL_READABLE, TCL_WRITABLE, and sl@0: * TCL_EXCEPTION. */ sl@0: int timeout; /* Maximum amount of time to wait for one sl@0: * of the conditions in mask to occur, in sl@0: * milliseconds. A value of 0 means don't sl@0: * wait at all, and a value of -1 means sl@0: * wait forever. */ sl@0: { sl@0: Tcl_Time abortTime = {0, 0}, now; /* silence gcc 4 warning */ sl@0: struct timeval blockTime, *timeoutPtr; sl@0: int index, numFound, result = 0; sl@0: fd_mask bit; sl@0: fd_mask readyMasks[3*MASK_SIZE]; sl@0: /* This array reflects the readable/writable sl@0: * conditions that were found to exist by the sl@0: * last call to select. */ sl@0: sl@0: /* sl@0: * If there is a non-zero finite timeout, compute the time when sl@0: * we give up. sl@0: */ sl@0: sl@0: if (timeout > 0) { sl@0: Tcl_GetTime(&now); sl@0: abortTime.sec = now.sec + timeout/1000; sl@0: abortTime.usec = now.usec + (timeout%1000)*1000; sl@0: if (abortTime.usec >= 1000000) { sl@0: abortTime.usec -= 1000000; sl@0: abortTime.sec += 1; sl@0: } sl@0: timeoutPtr = &blockTime; sl@0: } else if (timeout == 0) { sl@0: timeoutPtr = &blockTime; sl@0: blockTime.tv_sec = 0; sl@0: blockTime.tv_usec = 0; sl@0: } else { sl@0: timeoutPtr = NULL; sl@0: } sl@0: sl@0: /* sl@0: * Initialize the ready masks and compute the mask offsets. sl@0: */ sl@0: sl@0: if (fd >= FD_SETSIZE) { sl@0: panic("TclWaitForFile can't handle file id %d", fd); sl@0: } sl@0: memset((VOID *) readyMasks, 0, 3*MASK_SIZE*sizeof(fd_mask)); sl@0: index = fd/(NBBY*sizeof(fd_mask)); sl@0: bit = ((fd_mask) 1) << (fd%(NBBY*sizeof(fd_mask))); sl@0: sl@0: /* sl@0: * Loop in a mini-event loop of our own, waiting for either the sl@0: * file to become ready or a timeout to occur. sl@0: */ sl@0: sl@0: while (1) { sl@0: if (timeout > 0) { sl@0: blockTime.tv_sec = abortTime.sec - now.sec; sl@0: blockTime.tv_usec = abortTime.usec - now.usec; sl@0: if (blockTime.tv_usec < 0) { sl@0: blockTime.tv_sec -= 1; sl@0: blockTime.tv_usec += 1000000; sl@0: } sl@0: if (blockTime.tv_sec < 0) { sl@0: blockTime.tv_sec = 0; sl@0: blockTime.tv_usec = 0; sl@0: } sl@0: } sl@0: sl@0: /* sl@0: * Set the appropriate bit in the ready masks for the fd. sl@0: */ sl@0: sl@0: if (mask & TCL_READABLE) { sl@0: readyMasks[index] |= bit; sl@0: } sl@0: if (mask & TCL_WRITABLE) { sl@0: (readyMasks+MASK_SIZE)[index] |= bit; sl@0: } sl@0: if (mask & TCL_EXCEPTION) { sl@0: (readyMasks+2*(MASK_SIZE))[index] |= bit; sl@0: } sl@0: sl@0: /* sl@0: * Wait for the event or a timeout. sl@0: */ sl@0: sl@0: numFound = select(fd+1, (SELECT_MASK *) &readyMasks[0], sl@0: (SELECT_MASK *) &readyMasks[MASK_SIZE], sl@0: (SELECT_MASK *) &readyMasks[2*MASK_SIZE], timeoutPtr); sl@0: if (numFound == 1) { sl@0: if (readyMasks[index] & bit) { sl@0: result |= TCL_READABLE; sl@0: } sl@0: if ((readyMasks+MASK_SIZE)[index] & bit) { sl@0: result |= TCL_WRITABLE; sl@0: } sl@0: if ((readyMasks+2*(MASK_SIZE))[index] & bit) { sl@0: result |= TCL_EXCEPTION; sl@0: } sl@0: result &= mask; sl@0: if (result) { sl@0: break; sl@0: } sl@0: } sl@0: if (timeout == 0) { sl@0: break; sl@0: } sl@0: if (timeout < 0) { sl@0: continue; sl@0: } sl@0: sl@0: /* sl@0: * The select returned early, so we need to recompute the timeout. sl@0: */ sl@0: sl@0: Tcl_GetTime(&now); sl@0: if ((abortTime.sec < now.sec) sl@0: || ((abortTime.sec == now.sec) sl@0: && (abortTime.usec <= now.usec))) { sl@0: break; sl@0: } sl@0: } sl@0: return result; sl@0: } sl@0: sl@0: #ifdef DEPRECATED sl@0: /* sl@0: *---------------------------------------------------------------------- sl@0: * sl@0: * FileThreadActionProc -- sl@0: * sl@0: * Insert or remove any thread local refs to this channel. sl@0: * sl@0: * Results: sl@0: * None. sl@0: * sl@0: * Side effects: sl@0: * Changes thread local list of valid channels. sl@0: * sl@0: *---------------------------------------------------------------------- sl@0: */ sl@0: sl@0: static void sl@0: FileThreadActionProc (instanceData, action) sl@0: ClientData instanceData; sl@0: int action; sl@0: { sl@0: ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); sl@0: FileState *fsPtr = (FileState *) instanceData; sl@0: sl@0: if (action == TCL_CHANNEL_THREAD_INSERT) { sl@0: fsPtr->nextPtr = tsdPtr->firstFilePtr; sl@0: tsdPtr->firstFilePtr = fsPtr; sl@0: } else { sl@0: FileState **nextPtrPtr; sl@0: int removed = 0; sl@0: sl@0: for (nextPtrPtr = &(tsdPtr->firstFilePtr); (*nextPtrPtr) != NULL; sl@0: nextPtrPtr = &((*nextPtrPtr)->nextPtr)) { sl@0: if ((*nextPtrPtr) == fsPtr) { sl@0: (*nextPtrPtr) = fsPtr->nextPtr; sl@0: removed = 1; sl@0: break; sl@0: } sl@0: } sl@0: sl@0: /* sl@0: * This could happen if the channel was created in one sl@0: * thread and then moved to another without updating sl@0: * the thread local data in each thread. sl@0: */ sl@0: sl@0: if (!removed) { sl@0: panic("file info ptr not on thread channel list"); sl@0: } sl@0: } sl@0: } sl@0: #endif /* DEPRECATED */ sl@0: