summaryrefslogtreecommitdiffstats
path: root/unix/tclUnixChan.c
diff options
context:
space:
mode:
Diffstat (limited to 'unix/tclUnixChan.c')
-rw-r--r--unix/tclUnixChan.c2649
1 files changed, 1577 insertions, 1072 deletions
diff --git a/unix/tclUnixChan.c b/unix/tclUnixChan.c
index 9f31e8f..8448b77 100644
--- a/unix/tclUnixChan.c
+++ b/unix/tclUnixChan.c
@@ -1,60 +1,79 @@
-/*
+/*
* tclUnixChan.c
*
- * Common channel driver for Unix channels based on files, command
- * pipes and TCP sockets.
+ * Common channel driver for Unix channels based on files, command pipes
+ * and TCP sockets.
*
* Copyright (c) 1995-1997 Sun Microsystems, Inc.
* Copyright (c) 1998-1999 by Scriptics Corporation.
*
- * See the file "license.terms" for information on usage and redistribution
- * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
- *
- * RCS: @(#) $Id: tclUnixChan.c,v 1.21 2001/08/30 08:53:15 vincentdarley Exp $
+ * See the file "license.terms" for information on usage and redistribution of
+ * this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
-#include "tclInt.h" /* Internal definitions for Tcl. */
-#include "tclPort.h" /* Portability features for Tcl. */
-
-/*
- * sys/ioctl.h has already been included by tclPort.h. Including termios.h
- * or termio.h causes a bunch of warning messages because some duplicate
- * (but not contradictory) #defines exist in termios.h and/or termio.h
- */
-#undef NL0
-#undef NL1
-#undef CR0
-#undef CR1
-#undef CR2
-#undef CR3
-#undef TAB0
-#undef TAB1
-#undef TAB2
-#undef XTABS
-#undef BS0
-#undef BS1
-#undef FF0
-#undef FF1
-#undef ECHO
-#undef NOFLSH
-#undef TOSTOP
-#undef FLUSHO
-#undef PENDIN
+#include "tclInt.h" /* Internal definitions for Tcl. */
+#include "tclIO.h" /* To get Channel type declaration. */
#define SUPPORTS_TTY
+#undef DIRECT_BAUD
+#ifdef B4800
+# if (B4800 == 4800)
+# define DIRECT_BAUD
+# endif /* B4800 == 4800 */
+#endif /* B4800 */
+
#ifdef USE_TERMIOS
# include <termios.h>
+# ifdef HAVE_SYS_IOCTL_H
+# include <sys/ioctl.h>
+# endif /* HAVE_SYS_IOCTL_H */
+# ifdef HAVE_SYS_MODEM_H
+# include <sys/modem.h>
+# endif /* HAVE_SYS_MODEM_H */
# define IOSTATE struct termios
# define GETIOSTATE(fd, statePtr) tcgetattr((fd), (statePtr))
# define SETIOSTATE(fd, statePtr) tcsetattr((fd), TCSADRAIN, (statePtr))
+# define GETCONTROL(fd, intPtr) ioctl((fd), TIOCMGET, (intPtr))
+# define SETCONTROL(fd, intPtr) ioctl((fd), TIOCMSET, (intPtr))
+
+# ifdef FIONREAD
+# define GETREADQUEUE(fd, int) ioctl((fd), FIONREAD, &(int))
+# elif defined(FIORDCHK)
+# define GETREADQUEUE(fd, int) int = ioctl((fd), FIORDCHK, NULL)
+# endif /* FIONREAD */
+# ifdef TIOCOUTQ
+# define GETWRITEQUEUE(fd, int) ioctl((fd), TIOCOUTQ, &(int))
+# endif /* TIOCOUTQ */
+# if defined(TIOCSBRK) && defined(TIOCCBRK)
+
+/*
+ * Can't use ?: operator below because that messes up types on either Linux or
+ * Solaris (the two are mutually exclusive!)
+ */
+
+# define SETBREAK(fd, flag) \
+ if (flag) { \
+ ioctl((fd), TIOCSBRK, NULL); \
+ } else { \
+ ioctl((fd), TIOCCBRK, NULL); \
+ }
+# endif /* TIOCSBRK&TIOCCBRK */
+# if !defined(CRTSCTS) && defined(CNEW_RTSCTS)
+# define CRTSCTS CNEW_RTSCTS
+# endif /* !CRTSCTS&CNEW_RTSCTS */
+# if !defined(PAREXT) && defined(CMSPAR)
+# define PAREXT CMSPAR
+# endif /* !PAREXT&&CMSPAR */
#else /* !USE_TERMIOS */
+
#ifdef USE_TERMIO
# include <termio.h>
# define IOSTATE struct termio
# define GETIOSTATE(fd, statePtr) ioctl((fd), TCGETA, (statePtr))
# define SETIOSTATE(fd, statePtr) ioctl((fd), TCSETAW, (statePtr))
#else /* !USE_TERMIO */
+
#ifdef USE_SGTTY
# include <sgtty.h>
# define IOSTATE struct sgttyb
@@ -63,10 +82,20 @@
#else /* !USE_SGTTY */
# undef SUPPORTS_TTY
#endif /* !USE_SGTTY */
+
#endif /* !USE_TERMIO */
#endif /* !USE_TERMIOS */
/*
+ * Helper macros to make parts of this file clearer. The macros do exactly
+ * what they say on the tin. :-) They also only ever refer to their arguments
+ * once, and so can be used without regard to side effects.
+ */
+
+#define SET_BITS(var, bits) ((var) |= (bits))
+#define CLEAR_BITS(var, bits) ((var) &= ~(bits))
+
+/*
* This structure describes per-instance state of a file based channel.
*/
@@ -76,10 +105,6 @@ typedef struct FileState {
int validMask; /* OR'ed combination of TCL_READABLE,
* TCL_WRITABLE, or TCL_EXCEPTION: indicates
* which operations are valid on the file. */
-#ifdef DEPRECATED
- struct FileState *nextPtr; /* Pointer to next file in list of all
- * file channels. */
-#endif
} FileState;
#ifdef SUPPORTS_TTY
@@ -90,17 +115,17 @@ typedef struct FileState {
*/
typedef struct TtyState {
- FileState fs; /* Per-instance state of the file
- * descriptor. Must be the first field. */
- IOSTATE savedState; /* Initial state of device. Used to reset
+ FileState fs; /* Per-instance state of the file descriptor.
+ * Must be the first field. */
+ IOSTATE savedState; /* Initial state of device. Used to reset
* state when device closed. */
} TtyState;
/*
- * The following structure is used to set or get the serial port
- * attributes in a platform-independant manner.
+ * The following structure is used to set or get the serial port attributes in
+ * a platform-independant manner.
*/
-
+
typedef struct TtyAttrs {
int baud;
int parity;
@@ -110,18 +135,11 @@ typedef struct TtyAttrs {
#endif /* !SUPPORTS_TTY */
-#ifdef DEPRECATED
-typedef struct ThreadSpecificData {
- /*
- * List of all file channels currently open. This is per thread and is
- * used to match up fd's to channels, which rarely occurs.
- */
-
- FileState *firstFilePtr;
-} ThreadSpecificData;
-
-static Tcl_ThreadDataKey dataKey;
-#endif
+#define UNSUPPORTED_OPTION(detail) \
+ if (interp) { \
+ Tcl_AppendResult(interp, (detail), \
+ " not supported for this platform", NULL); \
+ }
/*
* This structure describes per-instance state of a tcp based channel.
@@ -130,8 +148,9 @@ static Tcl_ThreadDataKey dataKey;
typedef struct TcpState {
Tcl_Channel channel; /* Channel associated with this file. */
int fd; /* The socket itself. */
- int flags; /* ORed combination of the bitfields
- * defined below. */
+ int flags; /* ORed combination of the bitfields defined
+ * below. */
+ int interest; /* Events types of interest. */
Tcl_TcpAcceptProc *acceptProc;
/* Proc to call on accept. */
ClientData acceptProcData; /* The data for the accept proc. */
@@ -146,24 +165,24 @@ typedef struct TcpState {
#define TCP_ASYNC_CONNECT (1<<1) /* Async connect in progress. */
/*
- * The following defines the maximum length of the listen queue. This is
- * the number of outstanding yet-to-be-serviced requests for a connection
- * on a server socket, more than this number of outstanding requests and
- * the connection request will fail.
+ * The following defines the maximum length of the listen queue. This is the
+ * number of outstanding yet-to-be-serviced requests for a connection on a
+ * server socket, more than this number of outstanding requests and the
+ * connection request will fail.
*/
-#ifndef SOMAXCONN
-#define SOMAXCONN 100
-#endif
+#ifndef SOMAXCONN
+# define SOMAXCONN 100
+#endif /* SOMAXCONN */
-#if (SOMAXCONN < 100)
-#undef SOMAXCONN
-#define SOMAXCONN 100
-#endif
+#if (SOMAXCONN < 100)
+# undef SOMAXCONN
+# define SOMAXCONN 100
+#endif /* SOMAXCONN < 100 */
/*
- * The following defines how much buffer space the kernel should maintain
- * for a socket.
+ * The following defines how much buffer space the kernel should maintain for
+ * a socket.
*/
#define SOCKET_BUFSIZE 4096
@@ -172,63 +191,65 @@ typedef struct TcpState {
* Static routines for this file:
*/
-static TcpState * CreateSocket _ANSI_ARGS_((Tcl_Interp *interp,
- int port, char *host, int server,
- char *myaddr, int myport, int async));
-static int CreateSocketAddress _ANSI_ARGS_(
- (struct sockaddr_in *sockaddrPtr,
- char *host, int port));
-static int FileBlockModeProc _ANSI_ARGS_((
- ClientData instanceData, int mode));
-static int FileCloseProc _ANSI_ARGS_((ClientData instanceData,
- Tcl_Interp *interp));
-static int FileGetHandleProc _ANSI_ARGS_((ClientData instanceData,
- int direction, ClientData *handlePtr));
-static int FileInputProc _ANSI_ARGS_((ClientData instanceData,
- char *buf, int toRead, int *errorCode));
-static int FileOutputProc _ANSI_ARGS_((
- ClientData instanceData, char *buf, int toWrite,
- int *errorCode));
-static int FileSeekProc _ANSI_ARGS_((ClientData instanceData,
- long offset, int mode, int *errorCode));
-static void FileWatchProc _ANSI_ARGS_((ClientData instanceData,
- int mask));
-static void TcpAccept _ANSI_ARGS_((ClientData data, int mask));
-static int TcpBlockModeProc _ANSI_ARGS_((ClientData data,
- int mode));
-static int TcpCloseProc _ANSI_ARGS_((ClientData instanceData,
- Tcl_Interp *interp));
-static int TcpGetHandleProc _ANSI_ARGS_((ClientData instanceData,
- int direction, ClientData *handlePtr));
-static int TcpGetOptionProc _ANSI_ARGS_((ClientData instanceData,
- Tcl_Interp *interp, char *optionName,
- Tcl_DString *dsPtr));
-static int TcpInputProc _ANSI_ARGS_((ClientData instanceData,
- char *buf, int toRead, int *errorCode));
-static int TcpOutputProc _ANSI_ARGS_((ClientData instanceData,
- char *buf, int toWrite, int *errorCode));
-static void TcpWatchProc _ANSI_ARGS_((ClientData instanceData,
- int mask));
+static TcpState * CreateSocket(Tcl_Interp *interp, int port,
+ const char *host, int server, const char *myaddr,
+ int myport, int async);
+static int CreateSocketAddress(struct sockaddr_in *sockaddrPtr,
+ const char *host, int port, int willBind,
+ const char **errorMsgPtr);
+static int FileBlockModeProc(ClientData instanceData, int mode);
+static int FileCloseProc(ClientData instanceData,
+ Tcl_Interp *interp);
+static int FileGetHandleProc(ClientData instanceData,
+ int direction, ClientData *handlePtr);
+static int FileInputProc(ClientData instanceData, char *buf,
+ int toRead, int *errorCode);
+static int FileOutputProc(ClientData instanceData,
+ const char *buf, int toWrite, int *errorCode);
+static int FileSeekProc(ClientData instanceData, long offset,
+ int mode, int *errorCode);
+static int FileTruncateProc(ClientData instanceData,
+ Tcl_WideInt length);
+static Tcl_WideInt FileWideSeekProc(ClientData instanceData,
+ Tcl_WideInt offset, int mode, int *errorCode);
+static void FileWatchProc(ClientData instanceData, int mask);
+static void TcpAccept(ClientData data, int mask);
+static int TcpBlockModeProc(ClientData data, int mode);
+static int TcpCloseProc(ClientData instanceData,
+ Tcl_Interp *interp);
+static int TcpGetHandleProc(ClientData instanceData,
+ int direction, ClientData *handlePtr);
+static int TcpGetOptionProc(ClientData instanceData,
+ Tcl_Interp *interp, const char *optionName,
+ Tcl_DString *dsPtr);
+static int TcpInputProc(ClientData instanceData, char *buf,
+ int toRead, int *errorCode);
+static int TcpOutputProc(ClientData instanceData,
+ const char *buf, int toWrite, int *errorCode);
+static void TcpWatchProc(ClientData instanceData, int mask);
#ifdef SUPPORTS_TTY
-static int TtyCloseProc _ANSI_ARGS_((ClientData instanceData,
- Tcl_Interp *interp));
-static void TtyGetAttributes _ANSI_ARGS_((int fd,
- TtyAttrs *ttyPtr));
-static int TtyGetOptionProc _ANSI_ARGS_((ClientData instanceData,
- Tcl_Interp *interp, char *optionName,
- Tcl_DString *dsPtr));
-static FileState * TtyInit _ANSI_ARGS_((int fd, int initialize));
-static int TtyParseMode _ANSI_ARGS_((Tcl_Interp *interp,
- CONST char *mode, int *speedPtr, int *parityPtr,
- int *dataPtr, int *stopPtr));
-static void TtySetAttributes _ANSI_ARGS_((int fd,
- TtyAttrs *ttyPtr));
-static int TtySetOptionProc _ANSI_ARGS_((ClientData instanceData,
- Tcl_Interp *interp, char *optionName,
- char *value));
+static void TtyGetAttributes(int fd, TtyAttrs *ttyPtr);
+static int TtyGetOptionProc(ClientData instanceData,
+ Tcl_Interp *interp, const char *optionName,
+ Tcl_DString *dsPtr);
+#ifndef DIRECT_BAUD
+static int TtyGetBaud(unsigned long speed);
+static unsigned long TtyGetSpeed(int baud);
+#endif /* DIRECT_BAUD */
+static FileState * TtyInit(int fd, int initialize);
+static void TtyModemStatusStr(int status, Tcl_DString *dsPtr);
+static int TtyParseMode(Tcl_Interp *interp, const char *mode,
+ int *speedPtr, int *parityPtr, int *dataPtr,
+ int *stopPtr);
+static void TtySetAttributes(int fd, TtyAttrs *ttyPtr);
+static int TtySetOptionProc(ClientData instanceData,
+ Tcl_Interp *interp, const char *optionName,
+ const char *value);
#endif /* SUPPORTS_TTY */
-static int WaitForConnect _ANSI_ARGS_((TcpState *statePtr,
- int *errorCodePtr));
+static int WaitForConnect(TcpState *statePtr, int *errorCodePtr);
+static Tcl_Channel MakeTcpClientChannelMode(ClientData tcpSocket,
+ int mode);
+static void WrapNotify(ClientData clientData, int mask);
/*
* This structure describes the channel type structure for file based IO:
@@ -236,7 +257,7 @@ static int WaitForConnect _ANSI_ARGS_((TcpState *statePtr,
static Tcl_ChannelType fileChannelType = {
"file", /* Type name. */
- TCL_CHANNEL_VERSION_2, /* v2 channel */
+ TCL_CHANNEL_VERSION_5, /* v5 channel */
FileCloseProc, /* Close proc. */
FileInputProc, /* Input proc. */
FileOutputProc, /* Output proc. */
@@ -249,6 +270,9 @@ static Tcl_ChannelType fileChannelType = {
FileBlockModeProc, /* Set blocking or non-blocking mode.*/
NULL, /* flush proc. */
NULL, /* handler proc. */
+ FileWideSeekProc, /* wide seek proc. */
+ NULL,
+ FileTruncateProc, /* truncate proc. */
};
#ifdef SUPPORTS_TTY
@@ -259,8 +283,8 @@ static Tcl_ChannelType fileChannelType = {
static Tcl_ChannelType ttyChannelType = {
"tty", /* Type name. */
- TCL_CHANNEL_VERSION_2, /* v2 channel */
- TtyCloseProc, /* Close proc. */
+ TCL_CHANNEL_VERSION_5, /* v5 channel */
+ FileCloseProc, /* Close proc. */
FileInputProc, /* Input proc. */
FileOutputProc, /* Output proc. */
NULL, /* Seek proc. */
@@ -272,6 +296,9 @@ static Tcl_ChannelType ttyChannelType = {
FileBlockModeProc, /* Set blocking or non-blocking mode.*/
NULL, /* flush proc. */
NULL, /* handler proc. */
+ NULL, /* wide seek proc. */
+ NULL, /* thread action proc. */
+ NULL, /* truncate proc. */
};
#endif /* SUPPORTS_TTY */
@@ -282,7 +309,7 @@ static Tcl_ChannelType ttyChannelType = {
static Tcl_ChannelType tcpChannelType = {
"tcp", /* Type name. */
- TCL_CHANNEL_VERSION_2, /* v2 channel */
+ TCL_CHANNEL_VERSION_5, /* v5 channel */
TcpCloseProc, /* Close proc. */
TcpInputProc, /* Input proc. */
TcpOutputProc, /* Output proc. */
@@ -295,16 +322,18 @@ static Tcl_ChannelType tcpChannelType = {
TcpBlockModeProc, /* Set blocking or non-blocking mode.*/
NULL, /* flush proc. */
NULL, /* handler proc. */
+ NULL, /* wide seek proc. */
+ NULL, /* thread action proc. */
+ NULL, /* truncate proc. */
};
-
/*
*----------------------------------------------------------------------
*
* FileBlockModeProc --
*
- * Helper procedure to set blocking and nonblocking modes on a
- * file based channel. Invoked by generic IO level code.
+ * Helper function to set blocking and nonblocking modes on a file based
+ * channel. Invoked by generic IO level code.
*
* Results:
* 0 if successful, errno when failed.
@@ -317,36 +346,18 @@ static Tcl_ChannelType tcpChannelType = {
/* ARGSUSED */
static int
-FileBlockModeProc(instanceData, mode)
- ClientData instanceData; /* File state. */
- int mode; /* The mode to set. Can be one of
- * TCL_MODE_BLOCKING or
- * TCL_MODE_NONBLOCKING. */
+FileBlockModeProc(
+ ClientData instanceData, /* File state. */
+ int mode) /* The mode to set. Can be one of
+ * TCL_MODE_BLOCKING or
+ * TCL_MODE_NONBLOCKING. */
{
FileState *fsPtr = (FileState *) instanceData;
- int curStatus;
-#ifndef USE_FIONBIO
- curStatus = fcntl(fsPtr->fd, F_GETFL);
- if (mode == TCL_MODE_BLOCKING) {
- curStatus &= (~(O_NONBLOCK));
- } else {
- curStatus |= O_NONBLOCK;
- }
- if (fcntl(fsPtr->fd, F_SETFL, curStatus) < 0) {
- return errno;
- }
- curStatus = fcntl(fsPtr->fd, F_GETFL);
-#else
- if (mode == TCL_MODE_BLOCKING) {
- curStatus = 0;
- } else {
- curStatus = 1;
- }
- if (ioctl(fsPtr->fd, (int) FIONBIO, &curStatus) < 0) {
+ if (TclUnixSetBlockingMode(fsPtr->fd, mode) < 0) {
return errno;
}
-#endif
+
return 0;
}
@@ -355,8 +366,8 @@ FileBlockModeProc(instanceData, mode)
*
* FileInputProc --
*
- * This procedure is invoked from the generic IO level to read
- * input from a file based channel.
+ * This function is invoked from the generic IO level to read input from
+ * a file based channel.
*
* Results:
* The number of bytes read is returned or -1 on error. An output
@@ -369,19 +380,19 @@ FileBlockModeProc(instanceData, mode)
*/
static int
-FileInputProc(instanceData, buf, toRead, errorCodePtr)
- ClientData instanceData; /* File state. */
- char *buf; /* Where to store data read. */
- int toRead; /* How much space is available
- * in the buffer? */
- int *errorCodePtr; /* Where to store error code. */
+FileInputProc(
+ ClientData instanceData, /* File state. */
+ char *buf, /* Where to store data read. */
+ int toRead, /* How much space is available in the
+ * buffer? */
+ int *errorCodePtr) /* Where to store error code. */
{
FileState *fsPtr = (FileState *) instanceData;
- int bytesRead; /* How many bytes were actually
- * read from the input device? */
+ int bytesRead; /* How many bytes were actually read from the
+ * input device? */
*errorCodePtr = 0;
-
+
/*
* Assume there is always enough input available. This will block
* appropriately, and read will unblock as soon as a short read is
@@ -391,7 +402,7 @@ FileInputProc(instanceData, buf, toRead, errorCodePtr)
bytesRead = read(fsPtr->fd, buf, (size_t) toRead);
if (bytesRead > -1) {
- return bytesRead;
+ return bytesRead;
}
*errorCodePtr = errno;
return -1;
@@ -402,13 +413,12 @@ FileInputProc(instanceData, buf, toRead, errorCodePtr)
*
* FileOutputProc--
*
- * This procedure is invoked from the generic IO level to write
- * output to a file channel.
+ * This function is invoked from the generic IO level to write output to
+ * a file channel.
*
* Results:
- * The number of bytes written is returned or -1 on error. An
- * output argument contains a POSIX error code if an error occurred,
- * or zero.
+ * The number of bytes written is returned or -1 on error. An output
+ * argument contains a POSIX error code if an error occurred, or zero.
*
* Side effects:
* Writes output on the output device of the channel.
@@ -417,19 +427,29 @@ FileInputProc(instanceData, buf, toRead, errorCodePtr)
*/
static int
-FileOutputProc(instanceData, buf, toWrite, errorCodePtr)
- ClientData instanceData; /* File state. */
- char *buf; /* The data buffer. */
- int toWrite; /* How many bytes to write? */
- int *errorCodePtr; /* Where to store error code. */
+FileOutputProc(
+ ClientData instanceData, /* File state. */
+ const char *buf, /* The data buffer. */
+ int toWrite, /* How many bytes to write? */
+ int *errorCodePtr) /* Where to store error code. */
{
FileState *fsPtr = (FileState *) instanceData;
int written;
*errorCodePtr = 0;
+
+ if (toWrite == 0) {
+ /*
+ * SF Tcl Bug 465765. Do not try to write nothing into a file. STREAM
+ * based implementations will considers this as EOF (if there is a
+ * pipe behind the file).
+ */
+
+ return 0;
+ }
written = write(fsPtr->fd, buf, (size_t) toWrite);
if (written > -1) {
- return written;
+ return written;
}
*errorCodePtr = errno;
return -1;
@@ -440,7 +460,7 @@ FileOutputProc(instanceData, buf, toWrite, errorCodePtr)
*
* FileCloseProc --
*
- * This procedure is called from the generic IO level to perform
+ * This function is called from the generic IO level to perform
* channel-type-specific cleanup when a file based channel is closed.
*
* Results:
@@ -453,39 +473,25 @@ FileOutputProc(instanceData, buf, toWrite, errorCodePtr)
*/
static int
-FileCloseProc(instanceData, interp)
- ClientData instanceData; /* File state. */
- Tcl_Interp *interp; /* For error reporting - unused. */
+FileCloseProc(
+ ClientData instanceData, /* File state. */
+ Tcl_Interp *interp) /* For error reporting - unused. */
{
FileState *fsPtr = (FileState *) instanceData;
-#ifdef DEPRECATED
- FileState **nextPtrPtr;
-#endif
int errorCode = 0;
-#ifdef DEPRECATED
- ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
-#endif
+
Tcl_DeleteFileHandler(fsPtr->fd);
/*
* Do not close standard channels while in thread-exit.
*/
- if (!TclInExit()
+ if (!TclInThreadExit()
|| ((fsPtr->fd != 0) && (fsPtr->fd != 1) && (fsPtr->fd != 2))) {
if (close(fsPtr->fd) < 0) {
errorCode = errno;
}
}
-#ifdef DEPRECATED
- for (nextPtrPtr = &(tsdPtr->firstFilePtr); (*nextPtrPtr) != NULL;
- nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
- if ((*nextPtrPtr) == fsPtr) {
- (*nextPtrPtr) = fsPtr->nextPtr;
- break;
- }
- }
-#endif
ckfree((char *) fsPtr);
return errorCode;
}
@@ -495,35 +501,93 @@ FileCloseProc(instanceData, interp)
*
* FileSeekProc --
*
- * This procedure is called by the generic IO level to move the
- * access point in a file based channel.
+ * This function is called by the generic IO level to move the access
+ * point in a file based channel.
*
* Results:
- * -1 if failed, the new position if successful. An output
- * argument contains the POSIX error code if an error occurred,
- * or zero.
+ * -1 if failed, the new position if successful. An output argument
+ * contains the POSIX error code if an error occurred, or zero.
*
* Side effects:
- * Moves the location at which the channel will be accessed in
- * future operations.
+ * Moves the location at which the channel will be accessed in future
+ * operations.
*
*----------------------------------------------------------------------
*/
static int
-FileSeekProc(instanceData, offset, mode, errorCodePtr)
- ClientData instanceData; /* File state. */
- long offset; /* Offset to seek to. */
- int mode; /* Relative to where
- * should we seek? Can be
- * one of SEEK_START,
- * SEEK_SET or SEEK_END. */
- int *errorCodePtr; /* To store error code. */
+FileSeekProc(
+ ClientData instanceData, /* File state. */
+ long offset, /* Offset to seek to. */
+ int mode, /* Relative to where should we seek? Can be
+ * one of SEEK_START, SEEK_SET or SEEK_END. */
+ int *errorCodePtr) /* To store error code. */
{
FileState *fsPtr = (FileState *) instanceData;
- int newLoc;
+ Tcl_WideInt oldLoc, newLoc;
+
+ /*
+ * Save our current place in case we need to roll-back the seek.
+ */
+
+ oldLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) 0, SEEK_CUR);
+ if (oldLoc == Tcl_LongAsWide(-1)) {
+ /*
+ * Bad things are happening. Error out...
+ */
+
+ *errorCodePtr = errno;
+ return -1;
+ }
- newLoc = lseek(fsPtr->fd, (off_t) offset, mode);
+ newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode);
+
+ /*
+ * Check for expressability in our return type, and roll-back otherwise.
+ */
+
+ if (newLoc > Tcl_LongAsWide(INT_MAX)) {
+ *errorCodePtr = EOVERFLOW;
+ TclOSseek(fsPtr->fd, (Tcl_SeekOffset) oldLoc, SEEK_SET);
+ return -1;
+ } else {
+ *errorCodePtr = (newLoc == Tcl_LongAsWide(-1)) ? errno : 0;
+ }
+ return (int) Tcl_WideAsLong(newLoc);
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * FileWideSeekProc --
+ *
+ * This function is called by the generic IO level to move the access
+ * point in a file based channel, with offsets expressed as wide
+ * integers.
+ *
+ * Results:
+ * -1 if failed, the new position if successful. An output argument
+ * contains the POSIX error code if an error occurred, or zero.
+ *
+ * Side effects:
+ * Moves the location at which the channel will be accessed in future
+ * operations.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static Tcl_WideInt
+FileWideSeekProc(
+ ClientData instanceData, /* File state. */
+ Tcl_WideInt offset, /* Offset to seek to. */
+ int mode, /* Relative to where should we seek? Can be
+ * one of SEEK_START, SEEK_CUR or SEEK_END. */
+ int *errorCodePtr) /* To store error code. */
+{
+ FileState *fsPtr = (FileState *) instanceData;
+ Tcl_WideInt newLoc;
+
+ newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode);
*errorCodePtr = (newLoc == -1) ? errno : 0;
return newLoc;
@@ -547,18 +611,18 @@ FileSeekProc(instanceData, offset, mode, errorCodePtr)
*/
static void
-FileWatchProc(instanceData, mask)
- ClientData instanceData; /* The file state. */
- int mask; /* Events of interest; an OR-ed
- * combination of TCL_READABLE,
- * TCL_WRITABLE and TCL_EXCEPTION. */
+FileWatchProc(
+ ClientData instanceData, /* The file state. */
+ int mask) /* Events of interest; an OR-ed combination of
+ * TCL_READABLE, TCL_WRITABLE and
+ * TCL_EXCEPTION. */
{
FileState *fsPtr = (FileState *) instanceData;
/*
- * Make sure we only register for events that are valid on this file.
- * Note that we are passing Tcl_NotifyChannel directly to
- * Tcl_CreateFileHandler with the channel pointer as the client data.
+ * Make sure we only register for events that are valid on this file. Note
+ * that we are passing Tcl_NotifyChannel directly to Tcl_CreateFileHandler
+ * with the channel pointer as the client data.
*/
mask &= fsPtr->validMask;
@@ -576,12 +640,12 @@ FileWatchProc(instanceData, mask)
*
* FileGetHandleProc --
*
- * Called from Tcl_GetChannelHandle to retrieve OS handles from
- * a file based channel.
+ * Called from Tcl_GetChannelHandle to retrieve OS handles from a file
+ * based channel.
*
* Results:
- * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
- * there is no handle for the specified direction.
+ * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
+ * handle for the specified direction.
*
* Side effects:
* None.
@@ -590,51 +654,55 @@ FileWatchProc(instanceData, mask)
*/
static int
-FileGetHandleProc(instanceData, direction, handlePtr)
- ClientData instanceData; /* The file state. */
- int direction; /* TCL_READABLE or TCL_WRITABLE */
- ClientData *handlePtr; /* Where to store the handle. */
+FileGetHandleProc(
+ ClientData instanceData, /* The file state. */
+ int direction, /* TCL_READABLE or TCL_WRITABLE */
+ ClientData *handlePtr) /* Where to store the handle. */
{
FileState *fsPtr = (FileState *) instanceData;
if (direction & fsPtr->validMask) {
- *handlePtr = (ClientData) fsPtr->fd;
+ *handlePtr = (ClientData) INT2PTR(fsPtr->fd);
return TCL_OK;
- } else {
- return TCL_ERROR;
}
+ return TCL_ERROR;
}
-
-#ifdef SUPPORTS_TTY
+#ifdef SUPPORTS_TTY
+#ifdef USE_TERMIOS
/*
*----------------------------------------------------------------------
*
- * TtyCloseProc --
- *
- * This procedure is called from the generic IO level to perform
- * channel-type-specific cleanup when a tty based channel is closed.
+ * TtyModemStatusStr --
*
- * Results:
- * 0 if successful, errno if failed.
- *
- * Side effects:
- * Restores the settings and closes the device of the channel.
+ * Converts a RS232 modem status list of readable flags
*
*----------------------------------------------------------------------
*/
-static int
-TtyCloseProc(instanceData, interp)
- ClientData instanceData; /* Tty state. */
- Tcl_Interp *interp; /* For error reporting - unused. */
+static void
+TtyModemStatusStr(
+ int status, /* RS232 modem status */
+ Tcl_DString *dsPtr) /* Where to store string */
{
- TtyState *ttyPtr;
-
- ttyPtr = (TtyState *) instanceData;
- SETIOSTATE(ttyPtr->fs.fd, &ttyPtr->savedState);
- return FileCloseProc(instanceData, interp);
+#ifdef TIOCM_CTS
+ Tcl_DStringAppendElement(dsPtr, "CTS");
+ Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CTS) ? "1" : "0");
+#endif /* TIOCM_CTS */
+#ifdef TIOCM_DSR
+ Tcl_DStringAppendElement(dsPtr, "DSR");
+ Tcl_DStringAppendElement(dsPtr, (status & TIOCM_DSR) ? "1" : "0");
+#endif /* TIOCM_DSR */
+#ifdef TIOCM_RNG
+ Tcl_DStringAppendElement(dsPtr, "RING");
+ Tcl_DStringAppendElement(dsPtr, (status & TIOCM_RNG) ? "1" : "0");
+#endif /* TIOCM_RNG */
+#ifdef TIOCM_CD
+ Tcl_DStringAppendElement(dsPtr, "DCD");
+ Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CD) ? "1" : "0");
+#endif /* TIOCM_CD */
}
+#endif /* USE_TERMIOS */
/*
*----------------------------------------------------------------------
@@ -648,38 +716,219 @@ TtyCloseProc(instanceData, interp)
* interp is not NULL.
*
* Side effects:
- * May modify an option on a device.
- * Sets Error message if needed (by calling Tcl_BadChannelOption).
+ * May modify an option on a device. Sets Error message if needed (by
+ * calling Tcl_BadChannelOption).
*
*----------------------------------------------------------------------
*/
-static int
-TtySetOptionProc(instanceData, interp, optionName, value)
- ClientData instanceData; /* File state. */
- Tcl_Interp *interp; /* For error reporting - can be NULL. */
- char *optionName; /* Which option to set? */
- char *value; /* New value for option. */
+static int
+TtySetOptionProc(
+ ClientData instanceData, /* File state. */
+ Tcl_Interp *interp, /* For error reporting - can be NULL. */
+ const char *optionName, /* Which option to set? */
+ const char *value) /* New value for option. */
{
FileState *fsPtr = (FileState *) instanceData;
- unsigned int len;
+ unsigned int len, vlen;
TtyAttrs tty;
+#ifdef USE_TERMIOS
+ int flag, control, argc;
+ const char **argv;
+ IOSTATE iostate;
+#endif /* USE_TERMIOS */
len = strlen(optionName);
- if ((len > 1) && (strncmp(optionName, "-mode", len) == 0)) {
+ vlen = strlen(value);
+
+ /*
+ * Option -mode baud,parity,databits,stopbits
+ */
+ if ((len > 2) && (strncmp(optionName, "-mode", len) == 0)) {
if (TtyParseMode(interp, value, &tty.baud, &tty.parity, &tty.data,
&tty.stop) != TCL_OK) {
return TCL_ERROR;
}
+
/*
- * system calls results should be checked there. -- dl
+ * system calls results should be checked there. - dl
*/
TtySetAttributes(fsPtr->fd, &tty);
return TCL_OK;
- } else {
- return Tcl_BadChannelOption(interp, optionName, "mode");
}
+
+#ifdef USE_TERMIOS
+
+ /*
+ * Option -handshake none|xonxoff|rtscts|dtrdsr
+ */
+
+ if ((len > 1) && (strncmp(optionName, "-handshake", len) == 0)) {
+ /*
+ * Reset all handshake options. DTR and RTS are ON by default.
+ */
+
+ GETIOSTATE(fsPtr->fd, &iostate);
+ CLEAR_BITS(iostate.c_iflag, IXON | IXOFF | IXANY);
+#ifdef CRTSCTS
+ CLEAR_BITS(iostate.c_cflag, CRTSCTS);
+#endif /* CRTSCTS */
+ if (strncasecmp(value, "NONE", vlen) == 0) {
+ /* leave all handshake options disabled */
+ } else if (strncasecmp(value, "XONXOFF", vlen) == 0) {
+ SET_BITS(iostate.c_iflag, IXON | IXOFF | IXANY);
+ } else if (strncasecmp(value, "RTSCTS", vlen) == 0) {
+#ifdef CRTSCTS
+ SET_BITS(iostate.c_cflag, CRTSCTS);
+#else /* !CRTSTS */
+ UNSUPPORTED_OPTION("-handshake RTSCTS");
+ return TCL_ERROR;
+#endif /* CRTSCTS */
+ } else if (strncasecmp(value, "DTRDSR", vlen) == 0) {
+ UNSUPPORTED_OPTION("-handshake DTRDSR");
+ return TCL_ERROR;
+ } else {
+ if (interp) {
+ Tcl_AppendResult(interp, "bad value for -handshake: "
+ "must be one of xonxoff, rtscts, dtrdsr or none",
+ NULL);
+ }
+ return TCL_ERROR;
+ }
+ SETIOSTATE(fsPtr->fd, &iostate);
+ return TCL_OK;
+ }
+
+ /*
+ * Option -xchar {\x11 \x13}
+ */
+
+ if ((len > 1) && (strncmp(optionName, "-xchar", len) == 0)) {
+ GETIOSTATE(fsPtr->fd, &iostate);
+ if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
+ return TCL_ERROR;
+ }
+ if (argc == 2) {
+ Tcl_DString ds;
+ Tcl_DStringInit(&ds);
+
+ Tcl_UtfToExternalDString(NULL, argv[0], -1, &ds);
+ iostate.c_cc[VSTART] = *(const cc_t *) Tcl_DStringValue(&ds);
+ Tcl_DStringSetLength(&ds, 0);
+
+ Tcl_UtfToExternalDString(NULL, argv[1], -1, &ds);
+ iostate.c_cc[VSTOP] = *(const cc_t *) Tcl_DStringValue(&ds);
+ Tcl_DStringFree(&ds);
+ } else {
+ if (interp) {
+ Tcl_AppendResult(interp, "bad value for -xchar: "
+ "should be a list of two elements", NULL);
+ }
+ ckfree((char *) argv);
+ return TCL_ERROR;
+ }
+ SETIOSTATE(fsPtr->fd, &iostate);
+ ckfree((char *) argv);
+ return TCL_OK;
+ }
+
+ /*
+ * Option -timeout msec
+ */
+
+ if ((len > 2) && (strncmp(optionName, "-timeout", len) == 0)) {
+ int msec;
+
+ GETIOSTATE(fsPtr->fd, &iostate);
+ if (Tcl_GetInt(interp, value, &msec) != TCL_OK) {
+ return TCL_ERROR;
+ }
+ iostate.c_cc[VMIN] = 0;
+ iostate.c_cc[VTIME] = (msec==0) ? 0 : (msec<100) ? 1 : (msec+50)/100;
+ SETIOSTATE(fsPtr->fd, &iostate);
+ return TCL_OK;
+ }
+
+ /*
+ * Option -ttycontrol {DTR 1 RTS 0 BREAK 0}
+ */
+
+ if ((len > 4) && (strncmp(optionName, "-ttycontrol", len) == 0)) {
+ int i;
+
+ if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
+ return TCL_ERROR;
+ }
+ if ((argc % 2) == 1) {
+ if (interp) {
+ Tcl_AppendResult(interp, "bad value for -ttycontrol: "
+ "should be a list of signal,value pairs", NULL);
+ }
+ ckfree((char *) argv);
+ return TCL_ERROR;
+ }
+
+ GETCONTROL(fsPtr->fd, &control);
+ for (i = 0; i < argc-1; i += 2) {
+ if (Tcl_GetBoolean(interp, argv[i+1], &flag) == TCL_ERROR) {
+ ckfree((char *) argv);
+ return TCL_ERROR;
+ }
+ if (strncasecmp(argv[i], "DTR", strlen(argv[i])) == 0) {
+#ifdef TIOCM_DTR
+ if (flag) {
+ SET_BITS(control, TIOCM_DTR);
+ } else {
+ CLEAR_BITS(control, TIOCM_DTR);
+ }
+#else /* !TIOCM_DTR */
+ UNSUPPORTED_OPTION("-ttycontrol DTR");
+ ckfree((char *) argv);
+ return TCL_ERROR;
+#endif /* TIOCM_DTR */
+ } else if (strncasecmp(argv[i], "RTS", strlen(argv[i])) == 0) {
+#ifdef TIOCM_RTS
+ if (flag) {
+ SET_BITS(control, TIOCM_RTS);
+ } else {
+ CLEAR_BITS(control, TIOCM_RTS);
+ }
+#else /* !TIOCM_RTS*/
+ UNSUPPORTED_OPTION("-ttycontrol RTS");
+ ckfree((char *) argv);
+ return TCL_ERROR;
+#endif /* TIOCM_RTS*/
+ } else if (strncasecmp(argv[i], "BREAK", strlen(argv[i])) == 0) {
+#ifdef SETBREAK
+ SETBREAK(fsPtr->fd, flag);
+#else /* !SETBREAK */
+ UNSUPPORTED_OPTION("-ttycontrol BREAK");
+ ckfree((char *) argv);
+ return TCL_ERROR;
+#endif /* SETBREAK */
+ } else {
+ if (interp) {
+ Tcl_AppendResult(interp, "bad signal \"", argv[i],
+ "\" for -ttycontrol: must be "
+ "DTR, RTS or BREAK", NULL);
+ }
+ ckfree((char *) argv);
+ return TCL_ERROR;
+ }
+ } /* -ttycontrol options loop */
+
+ SETCONTROL(fsPtr->fd, &control);
+ ckfree((char *) argv);
+ return TCL_OK;
+ }
+
+ return Tcl_BadChannelOption(interp, optionName,
+ "mode handshake timeout ttycontrol xchar");
+
+#else /* !USE_TERMIOS */
+ return Tcl_BadChannelOption(interp, optionName, "mode");
+#endif /* USE_TERMIOS */
}
/*
@@ -687,65 +936,136 @@ TtySetOptionProc(instanceData, interp, optionName, value)
*
* TtyGetOptionProc --
*
- * Gets a mode associated with an IO channel. If the optionName arg
- * is non NULL, retrieves the value of that option. If the optionName
- * arg is NULL, retrieves a list of alternating option names and
- * values for the given channel.
+ * Gets a mode associated with an IO channel. If the optionName arg is
+ * non-NULL, retrieves the value of that option. If the optionName arg is
+ * NULL, retrieves a list of alternating option names and values for the
+ * given channel.
*
* Results:
- * A standard Tcl result. Also sets the supplied DString to the
- * string value of the option(s) returned.
+ * A standard Tcl result. Also sets the supplied DString to the string
+ * value of the option(s) returned.
*
* Side effects:
- * The string returned by this function is in static storage and
- * may be reused at any time subsequent to the call.
- * Sets Error message if needed (by calling Tcl_BadChannelOption).
+ * The string returned by this function is in static storage and may be
+ * reused at any time subsequent to the call. Sets error message if
+ * needed (by calling Tcl_BadChannelOption).
*
*----------------------------------------------------------------------
*/
-static int
-TtyGetOptionProc(instanceData, interp, optionName, dsPtr)
- ClientData instanceData; /* File state. */
- Tcl_Interp *interp; /* For error reporting - can be NULL. */
- char *optionName; /* Option to get. */
- Tcl_DString *dsPtr; /* Where to store value(s). */
+static int
+TtyGetOptionProc(
+ ClientData instanceData, /* File state. */
+ Tcl_Interp *interp, /* For error reporting - can be NULL. */
+ const char *optionName, /* Option to get. */
+ Tcl_DString *dsPtr) /* Where to store value(s). */
{
FileState *fsPtr = (FileState *) instanceData;
unsigned int len;
- char buf[3 * TCL_INTEGER_SPACE + 16];
- TtyAttrs tty;
+ char buf[3*TCL_INTEGER_SPACE + 16];
+ int valid = 0; /* Flag if valid option parsed. */
if (optionName == NULL) {
- Tcl_DStringAppendElement(dsPtr, "-mode");
len = 0;
} else {
len = strlen(optionName);
}
- if ((len == 0) ||
- ((len > 1) && (strncmp(optionName, "-mode", len) == 0))) {
+ if (len == 0) {
+ Tcl_DStringAppendElement(dsPtr, "-mode");
+ }
+ if (len==0 || (len>2 && strncmp(optionName, "-mode", len)==0)) {
+ TtyAttrs tty;
+
+ valid = 1;
TtyGetAttributes(fsPtr->fd, &tty);
sprintf(buf, "%d,%c,%d,%d", tty.baud, tty.parity, tty.data, tty.stop);
Tcl_DStringAppendElement(dsPtr, buf);
+ }
+
+#ifdef USE_TERMIOS
+ /*
+ * Get option -xchar
+ */
+
+ if (len == 0) {
+ Tcl_DStringAppendElement(dsPtr, "-xchar");
+ Tcl_DStringStartSublist(dsPtr);
+ }
+ if (len==0 || (len>1 && strncmp(optionName, "-xchar", len)==0)) {
+ IOSTATE iostate;
+ Tcl_DString ds;
+ valid = 1;
+
+ GETIOSTATE(fsPtr->fd, &iostate);
+ Tcl_DStringInit(&ds);
+
+ Tcl_ExternalToUtfDString(NULL, (const char *) &iostate.c_cc[VSTART], 1, &ds);
+ Tcl_DStringAppendElement(dsPtr, (const char *) Tcl_DStringValue(&ds));
+ Tcl_DStringSetLength(&ds, 0);
+
+ Tcl_ExternalToUtfDString(NULL, (const char *) &iostate.c_cc[VSTOP], 1, &ds);
+ Tcl_DStringAppendElement(dsPtr, (const char *) Tcl_DStringValue(&ds));
+ Tcl_DStringFree(&ds);
+ }
+ if (len == 0) {
+ Tcl_DStringEndSublist(dsPtr);
+ }
+
+ /*
+ * Get option -queue
+ * Option is readonly and returned by [fconfigure chan -queue] but not
+ * returned by unnamed [fconfigure chan].
+ */
+
+ if ((len > 1) && (strncmp(optionName, "-queue", len) == 0)) {
+ int inQueue=0, outQueue=0, inBuffered, outBuffered;
+
+ valid = 1;
+#ifdef GETREADQUEUE
+ GETREADQUEUE(fsPtr->fd, inQueue);
+#endif /* GETREADQUEUE */
+#ifdef GETWRITEQUEUE
+ GETWRITEQUEUE(fsPtr->fd, outQueue);
+#endif /* GETWRITEQUEUE */
+ inBuffered = Tcl_InputBuffered(fsPtr->channel);
+ outBuffered = Tcl_OutputBuffered(fsPtr->channel);
+
+ sprintf(buf, "%d", inBuffered+inQueue);
+ Tcl_DStringAppendElement(dsPtr, buf);
+ sprintf(buf, "%d", outBuffered+outQueue);
+ Tcl_DStringAppendElement(dsPtr, buf);
+ }
+
+ /*
+ * Get option -ttystatus
+ * Option is readonly and returned by [fconfigure chan -ttystatus] but not
+ * returned by unnamed [fconfigure chan].
+ */
+ if ((len > 4) && (strncmp(optionName, "-ttystatus", len) == 0)) {
+ int status;
+
+ valid = 1;
+ GETCONTROL(fsPtr->fd, &status);
+ TtyModemStatusStr(status, dsPtr);
+ }
+#endif /* USE_TERMIOS */
+
+ if (valid) {
return TCL_OK;
- } else {
- return Tcl_BadChannelOption(interp, optionName, "mode");
}
+ return Tcl_BadChannelOption(interp, optionName, "mode"
+#ifdef USE_TERMIOS
+ " queue ttystatus xchar"
+#endif /* USE_TERMIOS */
+ );
}
-#undef DIRECT_BAUD
-#ifdef B4800
-# if (B4800 == 4800)
-# define DIRECT_BAUD
-# endif
-#endif
-
#ifdef DIRECT_BAUD
-# define TtyGetSpeed(baud) ((unsigned) (baud))
-# define TtyGetBaud(speed) ((int) (speed))
-#else
+# define TtyGetSpeed(baud) ((unsigned) (baud))
+# define TtyGetBaud(speed) ((int) (speed))
+#else /* !DIRECT_BAUD */
-static struct {int baud; unsigned long speed;} speeds[] = {
+static CONST struct {int baud; unsigned long speed;} speeds[] = {
#ifdef B0
{0, B0},
#endif
@@ -833,6 +1153,39 @@ static struct {int baud; unsigned long speed;} speeds[] = {
#ifdef B460800
{460800, B460800},
#endif
+#ifdef B500000
+ {500000, B500000},
+#endif
+#ifdef B576000
+ {576000, B576000},
+#endif
+#ifdef B921600
+ {921600, B921600},
+#endif
+#ifdef B1000000
+ {1000000, B1000000},
+#endif
+#ifdef B1152000
+ {1152000, B1152000},
+#endif
+#ifdef B1500000
+ {1500000,B1500000},
+#endif
+#ifdef B2000000
+ {2000000, B2000000},
+#endif
+#ifdef B2500000
+ {2500000,B2500000},
+#endif
+#ifdef B3000000
+ {3000000,B3000000},
+#endif
+#ifdef B3500000
+ {3500000,B3500000},
+#endif
+#ifdef B4000000
+ {4000000,B4000000},
+#endif
{-1, 0}
};
@@ -841,9 +1194,9 @@ static struct {int baud; unsigned long speed;} speeds[] = {
*
* TtyGetSpeed --
*
- * Given a baud rate, get the mask value that should be stored in
- * the termios, termio, or sgttyb structure in order to select that
- * baud rate.
+ * Given a baud rate, get the mask value that should be stored in the
+ * termios, termio, or sgttyb structure in order to select that baud
+ * rate.
*
* Results:
* As above.
@@ -855,18 +1208,18 @@ static struct {int baud; unsigned long speed;} speeds[] = {
*/
static unsigned long
-TtyGetSpeed(baud)
- int baud; /* The baud rate to look up. */
+TtyGetSpeed(
+ int baud) /* The baud rate to look up. */
{
int bestIdx, bestDiff, i, diff;
-
+
bestIdx = 0;
bestDiff = 1000000;
-
+
/*
* If the baud rate does not correspond to one of the known mask values,
- * choose the mask value whose baud rate is closest to the specified
- * baud rate.
+ * choose the mask value whose baud rate is closest to the specified baud
+ * rate.
*/
for (i = 0; speeds[i].baud >= 0; i++) {
@@ -887,11 +1240,11 @@ TtyGetSpeed(baud)
*
* TtyGetBaud --
*
- * Given a speed mask value from a termios, termio, or sgttyb
- * structure, get the baus rate that corresponds to that mask value.
+ * Given a speed mask value from a termios, termio, or sgttyb structure,
+ * get the baus rate that corresponds to that mask value.
*
* Results:
- * As above. If the mask value was not recognized, 0 is returned.
+ * As above. If the mask value was not recognized, 0 is returned.
*
* Side effects:
* None.
@@ -900,11 +1253,11 @@ TtyGetSpeed(baud)
*/
static int
-TtyGetBaud(speed)
- unsigned long speed; /* Speed mask value to look up. */
+TtyGetBaud(
+ unsigned long speed) /* Speed mask value to look up. */
{
int i;
-
+
for (i = 0; speeds[i].baud >= 0; i++) {
if (speeds[i].speed == speed) {
return speeds[i].baud;
@@ -912,9 +1265,7 @@ TtyGetBaud(speed)
}
return 0;
}
-
-#endif /* !DIRECT_BAUD */
-
+#endif /* !DIRECT_BAUD */
/*
*---------------------------------------------------------------------------
@@ -931,12 +1282,12 @@ TtyGetBaud(speed)
*
*---------------------------------------------------------------------------
*/
-
+
static void
-TtyGetAttributes(fd, ttyPtr)
- int fd; /* Open file descriptor for serial port to
- * be queried. */
- TtyAttrs *ttyPtr; /* Buffer filled with serial port
+TtyGetAttributes(
+ int fd, /* Open file descriptor for serial port to be
+ * queried. */
+ TtyAttrs *ttyPtr) /* Buffer filled with serial port
* attributes. */
{
IOSTATE iostate;
@@ -946,44 +1297,44 @@ TtyGetAttributes(fd, ttyPtr)
#ifdef USE_TERMIOS
baud = TtyGetBaud(cfgetospeed(&iostate));
-
+
parity = 'n';
#ifdef PAREXT
switch ((int) (iostate.c_cflag & (PARENB | PARODD | PAREXT))) {
- case PARENB : parity = 'e'; break;
- case PARENB | PARODD : parity = 'o'; break;
- case PARENB | PAREXT : parity = 's'; break;
- case PARENB | PARODD | PAREXT : parity = 'm'; break;
+ case PARENB : parity = 'e'; break;
+ case PARENB | PARODD : parity = 'o'; break;
+ case PARENB | PAREXT : parity = 's'; break;
+ case PARENB | PARODD | PAREXT : parity = 'm'; break;
}
-#else /* !PAREXT */
+#else /* !PAREXT */
switch ((int) (iostate.c_cflag & (PARENB | PARODD))) {
- case PARENB : parity = 'e'; break;
- case PARENB | PARODD : parity = 'o'; break;
+ case PARENB : parity = 'e'; break;
+ case PARENB | PARODD : parity = 'o'; break;
}
-#endif /* !PAREXT */
+#endif /* !PAREXT */
data = iostate.c_cflag & CSIZE;
data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8;
stop = (iostate.c_cflag & CSTOPB) ? 2 : 1;
-#endif /* USE_TERMIOS */
+#endif /* USE_TERMIOS */
#ifdef USE_TERMIO
baud = TtyGetBaud(iostate.c_cflag & CBAUD);
parity = 'n';
switch (iostate.c_cflag & (PARENB | PARODD | PAREXT)) {
- case PARENB : parity = 'e'; break;
- case PARENB | PARODD : parity = 'o'; break;
- case PARENB | PAREXT : parity = 's'; break;
- case PARENB | PARODD | PAREXT : parity = 'm'; break;
+ case PARENB : parity = 'e'; break;
+ case PARENB | PARODD : parity = 'o'; break;
+ case PARENB | PAREXT : parity = 's'; break;
+ case PARENB | PARODD | PAREXT : parity = 'm'; break;
}
data = iostate.c_cflag & CSIZE;
data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8;
stop = (iostate.c_cflag & CSTOPB) ? 2 : 1;
-#endif /* USE_TERMIO */
+#endif /* USE_TERMIO */
#ifdef USE_SGTTY
baud = TtyGetBaud(iostate.sg_ospeed);
@@ -998,7 +1349,7 @@ TtyGetAttributes(fd, ttyPtr)
data = (iostate.sg_flags & (EVENP | ODDP)) ? 7 : 8;
stop = 1;
-#endif /* USE_SGTTY */
+#endif /* USE_SGTTY */
ttyPtr->baud = baud;
ttyPtr->parity = parity;
@@ -1011,7 +1362,7 @@ TtyGetAttributes(fd, ttyPtr)
*
* TtySetAttributes --
*
- * Set the current attributes of the specified serial device.
+ * Set the current attributes of the specified serial device.
*
* Results:
* None.
@@ -1021,13 +1372,13 @@ TtyGetAttributes(fd, ttyPtr)
*
*---------------------------------------------------------------------------
*/
-
+
static void
-TtySetAttributes(fd, ttyPtr)
- int fd; /* Open file descriptor for serial port to
- * be modified. */
- TtyAttrs *ttyPtr; /* Buffer containing new attributes for
- * serial port. */
+TtySetAttributes(
+ int fd, /* Open file descriptor for serial port to be
+ * modified. */
+ TtyAttrs *ttyPtr) /* Buffer containing new attributes for serial
+ * port. */
{
IOSTATE iostate;
@@ -1041,25 +1392,28 @@ TtySetAttributes(fd, ttyPtr)
flag = 0;
parity = ttyPtr->parity;
if (parity != 'n') {
- flag |= PARENB;
+ SET_BITS(flag, PARENB);
#ifdef PAREXT
- iostate.c_cflag &= ~PAREXT;
+ CLEAR_BITS(iostate.c_cflag, PAREXT);
if ((parity == 'm') || (parity == 's')) {
- flag |= PAREXT;
+ SET_BITS(flag, PAREXT);
}
-#endif
+#endif /* PAREXT */
if ((parity == 'm') || (parity == 'o')) {
- flag |= PARODD;
+ SET_BITS(flag, PARODD);
}
}
data = ttyPtr->data;
- flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8;
+ SET_BITS(flag,
+ (data == 5) ? CS5 :
+ (data == 6) ? CS6 :
+ (data == 7) ? CS7 : CS8);
if (ttyPtr->stop == 2) {
- flag |= CSTOPB;
+ SET_BITS(flag, CSTOPB);
}
- iostate.c_cflag &= ~(PARENB | PARODD | CSIZE | CSTOPB);
- iostate.c_cflag |= flag;
+ CLEAR_BITS(iostate.c_cflag, PARENB | PARODD | CSIZE | CSTOPB);
+ SET_BITS(iostate.c_cflag, flag);
#endif /* USE_TERMIOS */
@@ -1067,28 +1421,31 @@ TtySetAttributes(fd, ttyPtr)
int parity, data, flag;
GETIOSTATE(fd, &iostate);
- iostate.c_cflag &= ~CBAUD;
- iostate.c_cflag |= TtyGetSpeed(ttyPtr->baud);
+ CLEAR_BITS(iostate.c_cflag, CBAUD);
+ SET_BITS(iostate.c_cflag, TtyGetSpeed(ttyPtr->baud));
flag = 0;
parity = ttyPtr->parity;
if (parity != 'n') {
- flag |= PARENB;
+ SET_BITS(flag, PARENB);
if ((parity == 'm') || (parity == 's')) {
- flag |= PAREXT;
+ SET_BITS(flag, PAREXT);
}
if ((parity == 'm') || (parity == 'o')) {
- flag |= PARODD;
+ SET_BITS(flag, PARODD);
}
}
data = ttyPtr->data;
- flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8;
+ SET_BITS(flag,
+ (data == 5) ? CS5 :
+ (data == 6) ? CS6 :
+ (data == 7) ? CS7 : CS8);
if (ttyPtr->stop == 2) {
- flag |= CSTOPB;
+ SET_BITS(flag, CSTOPB);
}
- iostate.c_cflag &= ~(PARENB | PARODD | PAREXT | CSIZE | CSTOPB);
- iostate.c_cflag |= flag;
+ CLEAR_BITS(iostate.c_cflag, PARENB | PARODD | PAREXT | CSIZE | CSTOPB);
+ SET_BITS(iostate.c_cflag, flag);
#endif /* USE_TERMIO */
@@ -1101,11 +1458,11 @@ TtySetAttributes(fd, ttyPtr)
parity = ttyPtr->parity;
if (parity == 'e') {
- iostate.sg_flags &= ~ODDP;
- iostate.sg_flags |= EVENP;
+ CLEAR_BITS(iostate.sg_flags, ODDP);
+ SET_BITS(iostate.sg_flags, EVENP);
} else if (parity == 'o') {
- iostate.sg_flags &= ~EVENP;
- iostate.sg_flags |= ODDP;
+ CLEAR_BITS(iostate.sg_flags, EVENP);
+ SET_BITS(iostate.sg_flags, ODDP);
}
#endif /* USE_SGTTY */
@@ -1117,32 +1474,32 @@ TtySetAttributes(fd, ttyPtr)
*
* TtyParseMode --
*
- * Parse the "-mode" argument to the fconfigure command. The argument
- * is of the form baud,parity,data,stop.
+ * Parse the "-mode" argument to the fconfigure command. The argument is
+ * of the form baud,parity,data,stop.
*
* Results:
- * The return value is TCL_OK if the argument was successfully
- * parsed, TCL_ERROR otherwise. If TCL_ERROR is returned, an
- * error message is left in the interp's result (if interp is non-NULL).
+ * The return value is TCL_OK if the argument was successfully parsed,
+ * TCL_ERROR otherwise. If TCL_ERROR is returned, an error message is
+ * left in the interp's result (if interp is non-NULL).
*
* Side effects:
* None.
*
*---------------------------------------------------------------------------
*/
-
+
static int
-TtyParseMode(interp, mode, speedPtr, parityPtr, dataPtr, stopPtr)
- Tcl_Interp *interp; /* If non-NULL, interp for error return. */
- CONST char *mode; /* Mode string to be parsed. */
- int *speedPtr; /* Filled with baud rate from mode string. */
- int *parityPtr; /* Filled with parity from mode string. */
- int *dataPtr; /* Filled with data bits from mode string. */
- int *stopPtr; /* Filled with stop bits from mode string. */
+TtyParseMode(
+ Tcl_Interp *interp, /* If non-NULL, interp for error return. */
+ const char *mode, /* Mode string to be parsed. */
+ int *speedPtr, /* Filled with baud rate from mode string. */
+ int *parityPtr, /* Filled with parity from mode string. */
+ int *dataPtr, /* Filled with data bits from mode string. */
+ int *stopPtr) /* Filled with stop bits from mode string. */
{
int i, end;
char parity;
- static char *bad = "bad value for -mode";
+ static const char *bad = "bad value for -mode";
i = sscanf(mode, "%d,%c,%d,%d%n", speedPtr, &parity, dataPtr,
stopPtr, &end);
@@ -1153,25 +1510,24 @@ TtyParseMode(interp, mode, speedPtr, parityPtr, dataPtr, stopPtr)
}
return TCL_ERROR;
}
+
/*
- * Only allow setting mark/space parity on platforms that support it
- * Make sure to allow for the case where strchr is a macro.
- * [Bug: 5089]
+ * Only allow setting mark/space parity on platforms that support it Make
+ * sure to allow for the case where strchr is a macro. [Bug: 5089]
*/
- if (
+
#if defined(PAREXT) || defined(USE_TERMIO)
- strchr("noems", parity) == NULL
+ if (strchr("noems", parity) == NULL) {
#else
- strchr("noe", parity) == NULL
-#endif
- ) {
+ if (strchr("noe", parity) == NULL) {
+#endif /* PAREXT|USE_TERMIO */
if (interp != NULL) {
- Tcl_AppendResult(interp, bad,
+ Tcl_AppendResult(interp, bad, " parity: should be ",
#if defined(PAREXT) || defined(USE_TERMIO)
- " parity: should be n, o, e, m, or s",
+ "n, o, e, m, or s",
#else
- " parity: should be n, o, or e",
-#endif
+ "n, o, or e",
+#endif /* PAREXT|USE_TERMIO */
NULL);
}
return TCL_ERROR;
@@ -1198,63 +1554,71 @@ TtyParseMode(interp, mode, speedPtr, parityPtr, dataPtr, stopPtr)
*
* TtyInit --
*
- * Given file descriptor that refers to a serial port,
- * initialize the serial port to a set of sane values so that
- * Tcl can talk to a device located on the serial port.
- * Note that no initialization happens if the initialize flag
- * is not set; this is necessary for the correct handling of
- * UNIX console TTYs at startup.
+ * Given file descriptor that refers to a serial port, initialize the
+ * serial port to a set of sane values so that Tcl can talk to a device
+ * located on the serial port. Note that no initialization happens if the
+ * initialize flag is not set; this is necessary for the correct handling
+ * of UNIX console TTYs at startup.
*
* Results:
- * A pointer to a FileState suitable for use with Tcl_CreateChannel
- * and the ttyChannelType structure.
+ * A pointer to a FileState suitable for use with Tcl_CreateChannel and
+ * the ttyChannelType structure.
*
* Side effects:
- * Serial device initialized to non-blocking raw mode, similar to
- * sockets (if initialize flag is non-zero.) All other modes can
- * be simulated on top of this in Tcl.
+ * Serial device initialized to non-blocking raw mode, similar to sockets
+ * (if initialize flag is non-zero.) All other modes can be simulated on
+ * top of this in Tcl.
*
*---------------------------------------------------------------------------
*/
static FileState *
-TtyInit(fd, initialize)
- int fd; /* Open file descriptor for serial port to
- * be initialized. */
- int initialize;
+TtyInit(
+ int fd, /* Open file descriptor for serial port to be
+ * initialized. */
+ int initialize)
{
TtyState *ttyPtr;
+ int stateUpdated = 0;
ttyPtr = (TtyState *) ckalloc((unsigned) sizeof(TtyState));
GETIOSTATE(fd, &ttyPtr->savedState);
-
if (initialize) {
IOSTATE iostate = ttyPtr->savedState;
-#ifdef USE_TERMIOS
- iostate.c_iflag = IGNBRK;
- iostate.c_oflag = 0;
- iostate.c_lflag = 0;
- iostate.c_cflag |= CREAD;
- iostate.c_cc[VMIN] = 1;
- iostate.c_cc[VTIME] = 0;
-#endif /* USE_TERMIOS */
-
-#ifdef USE_TERMIO
+#if defined(USE_TERMIOS) || defined(USE_TERMIO)
+ if (iostate.c_iflag != IGNBRK ||
+ iostate.c_oflag != 0 ||
+ iostate.c_lflag != 0 ||
+ iostate.c_cflag & CREAD ||
+ iostate.c_cc[VMIN] != 1 ||
+ iostate.c_cc[VTIME] != 0) {
+ stateUpdated = 1;
+ }
iostate.c_iflag = IGNBRK;
iostate.c_oflag = 0;
iostate.c_lflag = 0;
- iostate.c_cflag |= CREAD;
+ SET_BITS(iostate.c_cflag, CREAD);
iostate.c_cc[VMIN] = 1;
iostate.c_cc[VTIME] = 0;
-#endif /* USE_TERMIO */
+#endif /* USE_TERMIOS|USE_TERMIO */
#ifdef USE_SGTTY
- iostate.sg_flags &= (EVENP | ODDP);
- iostate.sg_flags |= RAW;
+ if ((iostate.sg_flags & (EVENP | ODDP)) ||
+ !(iostate.sg_flags & RAW)) {
+ ttyPtr->stateUpdated = 1;
+ }
+ iostate.sg_flags &= EVENP | ODDP;
+ SET_BITS(iostate.sg_flags, RAW);
#endif /* USE_SGTTY */
- SETIOSTATE(fd, &iostate);
+ /*
+ * Only update if we're changing anything to avoid possible blocking.
+ */
+
+ if (stateUpdated) {
+ SETIOSTATE(fd, &iostate);
+ }
}
return &ttyPtr->fs;
@@ -1269,97 +1633,104 @@ TtyInit(fd, initialize)
* Open an file based channel on Unix systems.
*
* Results:
- * The new channel or NULL. If NULL, the output argument
- * errorCodePtr is set to a POSIX error and an error message is
- * left in the interp's result if interp is not NULL.
+ * The new channel or NULL. If NULL, the output argument errorCodePtr is
+ * set to a POSIX error and an error message is left in the interp's
+ * result if interp is not NULL.
*
* Side effects:
- * May open the channel and may cause creation of a file on the
- * file system.
+ * May open the channel and may cause creation of a file on the file
+ * system.
*
*----------------------------------------------------------------------
*/
Tcl_Channel
-TclpOpenFileChannel(interp, pathPtr, modeString, permissions)
- Tcl_Interp *interp; /* Interpreter for error reporting;
- * can be NULL. */
- Tcl_Obj *pathPtr; /* Name of file to open. */
- char *modeString; /* A list of POSIX open modes or
- * a string such as "rw". */
- int permissions; /* If the open involves creating a
- * file, with what modes to create
- * it? */
+TclpOpenFileChannel(
+ Tcl_Interp *interp, /* Interpreter for error reporting; can be
+ * NULL. */
+ Tcl_Obj *pathPtr, /* Name of file to open. */
+ int mode, /* POSIX open mode. */
+ int permissions) /* If the open involves creating a file, with
+ * what modes to create it? */
{
- int fd, seekFlag, mode, channelPermissions;
+ int fd, channelPermissions;
FileState *fsPtr;
- char *native, *translation;
+ const char *native, *translation;
char channelName[16 + TCL_INTEGER_SPACE];
Tcl_ChannelType *channelTypePtr;
-#ifdef DEPRECATED
- ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
-#endif
- mode = TclGetOpenMode(interp, modeString, &seekFlag);
- if (mode == -1) {
- return NULL;
- }
switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
- case O_RDONLY:
- channelPermissions = TCL_READABLE;
- break;
- case O_WRONLY:
- channelPermissions = TCL_WRITABLE;
- break;
- case O_RDWR:
- channelPermissions = (TCL_READABLE | TCL_WRITABLE);
- break;
- default:
- /*
- * This may occurr if modeString was "", for example.
- */
- panic("TclpOpenFileChannel: invalid mode value");
- return NULL;
+ case O_RDONLY:
+ channelPermissions = TCL_READABLE;
+ break;
+ case O_WRONLY:
+ channelPermissions = TCL_WRITABLE;
+ break;
+ case O_RDWR:
+ channelPermissions = (TCL_READABLE | TCL_WRITABLE);
+ break;
+ default:
+ /*
+ * This may occurr if modeString was "", for example.
+ */
+
+ Tcl_Panic("TclpOpenFileChannel: invalid mode value");
+ return NULL;
}
native = Tcl_FSGetNativePath(pathPtr);
if (native == NULL) {
+ if (interp != (Tcl_Interp *) NULL) {
+ Tcl_AppendResult(interp, "couldn't open \"",
+ TclGetString(pathPtr), "\": filename is invalid on this platform",
+ NULL);
+ }
return NULL;
}
- fd = open(native, mode, permissions);
+
+#ifdef DJGPP
+ SET_BITS(mode, O_BINARY);
+#endif
+
+ fd = TclOSopen(native, mode, permissions);
if (fd < 0) {
- if (interp != (Tcl_Interp *) NULL) {
- Tcl_AppendResult(interp, "couldn't open \"",
- Tcl_GetString(pathPtr), "\": ",
- Tcl_PosixError(interp), (char *) NULL);
- }
- return NULL;
+ if (interp != NULL) {
+ Tcl_AppendResult(interp, "couldn't open \"", TclGetString(pathPtr),
+ "\": ", Tcl_PosixError(interp), NULL);
+ }
+ return NULL;
}
/*
* Set close-on-exec flag on the fd so that child processes will not
* inherit this fd.
*/
-
+
fcntl(fd, F_SETFD, FD_CLOEXEC);
-
+
sprintf(channelName, "file%d", fd);
-
+
#ifdef SUPPORTS_TTY
- if (isatty(fd)) {
+ if (strcmp(native, "/dev/tty") != 0 && isatty(fd)) {
/*
- * Initialize the serial port to a set of sane parameters.
- * Especially important if the remote device is set to echo and
- * the serial port driver was also set to echo -- as soon as a char
- * were sent to the serial port, the remote device would echo it,
- * then the serial driver would echo it back to the device, etc.
+ * Initialize the serial port to a set of sane parameters. Especially
+ * important if the remote device is set to echo and the serial port
+ * driver was also set to echo -- as soon as a char were sent to the
+ * serial port, the remote device would echo it, then the serial
+ * driver would echo it back to the device, etc.
+ *
+ * Note that we do not do this if we're dealing with /dev/tty itself,
+ * as that tends to cause Bad Things To Happen when you're working
+ * interactively. Strictly a better check would be to see if the FD
+ * being set up is a device and has the same major/minor as the
+ * initial std FDs (beware reopening!) but that's nearly as messy.
*/
-
+
translation = "auto crlf";
channelTypePtr = &ttyChannelType;
fsPtr = TtyInit(fd, 1);
- } else
+ } else
#endif /* SUPPORTS_TTY */
{
translation = NULL;
@@ -1367,36 +1738,21 @@ TclpOpenFileChannel(interp, pathPtr, modeString, permissions)
fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState));
}
-#ifdef DEPRECATED
- fsPtr->nextPtr = tsdPtr->firstFilePtr;
- tsdPtr->firstFilePtr = fsPtr;
-#endif
fsPtr->validMask = channelPermissions | TCL_EXCEPTION;
fsPtr->fd = fd;
-
+
fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName,
(ClientData) fsPtr, channelPermissions);
- if (seekFlag) {
- if (Tcl_Seek(fsPtr->channel, 0, SEEK_END) < 0) {
- if (interp != (Tcl_Interp *) NULL) {
- Tcl_AppendResult(interp, "couldn't seek to end of file on \"",
- channelName, "\": ", Tcl_PosixError(interp), NULL);
- }
- Tcl_Close(NULL, fsPtr->channel);
- return NULL;
- }
- }
-
if (translation != NULL) {
/*
- * Gotcha. Most modems need a "\r" at the end of the command
- * sequence. If you just send "at\n", the modem will not respond
- * with "OK" because it never got a "\r" to actually invoke the
- * command. So, by default, newlines are translated to "\r\n" on
- * output to avoid "bug" reports that the serial port isn't working.
+ * Gotcha. Most modems need a "\r" at the end of the command sequence.
+ * If you just send "at\n", the modem will not respond with "OK"
+ * because it never got a "\r" to actually invoke the command. So, by
+ * default, newlines are translated to "\r\n" on output to avoid "bug"
+ * reports that the serial port isn't working.
*/
-
+
if (Tcl_SetChannelOption(interp, fsPtr->channel, "-translation",
translation) != TCL_OK) {
Tcl_Close(NULL, fsPtr->channel);
@@ -1424,39 +1780,23 @@ TclpOpenFileChannel(interp, pathPtr, modeString, permissions)
*/
Tcl_Channel
-Tcl_MakeFileChannel(handle, mode)
- ClientData handle; /* OS level handle. */
- int mode; /* ORed combination of TCL_READABLE and
- * TCL_WRITABLE to indicate file mode. */
+Tcl_MakeFileChannel(
+ ClientData handle, /* OS level handle. */
+ int mode) /* ORed combination of TCL_READABLE and
+ * TCL_WRITABLE to indicate file mode. */
{
FileState *fsPtr;
char channelName[16 + TCL_INTEGER_SPACE];
- int fd = (int) handle;
+ int fd = PTR2INT(handle);
Tcl_ChannelType *channelTypePtr;
-#ifdef DEPRECATED
- ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
-#endif
- int socketType = 0;
- int argLength = sizeof(int);
+ struct sockaddr sockaddr;
+ socklen_t sockaddrLen = sizeof(sockaddr);
if (mode == 0) {
- return NULL;
+ return NULL;
}
-
- /*
- * Look to see if a channel with this fd and the same mode already exists.
- * If the fd is used, but the mode doesn't match, return NULL.
- */
-
-#ifdef DEPRECATED
- for (fsPtr = tsdPtr->firstFilePtr; fsPtr != NULL; fsPtr = fsPtr->nextPtr) {
- if (fsPtr->fd == fd) {
- return ((mode|TCL_EXCEPTION) == fsPtr->validMask) ?
- fsPtr->channel : NULL;
- }
- }
-#endif
+ sockaddr.sa_family = AF_UNSPEC;
#ifdef SUPPORTS_TTY
if (isatty(fd)) {
@@ -1464,27 +1804,21 @@ Tcl_MakeFileChannel(handle, mode)
channelTypePtr = &ttyChannelType;
sprintf(channelName, "serial%d", fd);
} else
-#endif
- if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (VOID *)&socketType,
- &argLength) == 0 && socketType == SOCK_STREAM) {
- /*
- * The mode parameter gets lost here, unfortunately.
- */
- return Tcl_MakeTcpClientChannel((ClientData) fd);
+#endif /* SUPPORTS_TTY */
+ if (getsockname(fd, (struct sockaddr *)&sockaddr, &sockaddrLen) == 0
+ && sockaddrLen > 0
+ && sockaddr.sa_family == AF_INET) {
+ return MakeTcpClientChannelMode((ClientData) INT2PTR(fd), mode);
} else {
channelTypePtr = &fileChannelType;
fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState));
sprintf(channelName, "file%d", fd);
}
-#ifdef DEPRECATED
- fsPtr->nextPtr = tsdPtr->firstFilePtr;
- tsdPtr->firstFilePtr = fsPtr;
-#endif
fsPtr->fd = fd;
fsPtr->validMask = mode | TCL_EXCEPTION;
fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName,
- (ClientData) fsPtr, mode);
+ (ClientData) fsPtr, mode);
return fsPtr->channel;
}
@@ -1494,8 +1828,8 @@ Tcl_MakeFileChannel(handle, mode)
*
* TcpBlockModeProc --
*
- * This procedure is invoked by the generic IO level to set blocking
- * and nonblocking mode on a TCP socket based channel.
+ * This function is invoked by the generic IO level to set blocking and
+ * nonblocking mode on a TCP socket based channel.
*
* Results:
* 0 if successful, errno when failed.
@@ -1508,45 +1842,22 @@ Tcl_MakeFileChannel(handle, mode)
/* ARGSUSED */
static int
-TcpBlockModeProc(instanceData, mode)
- ClientData instanceData; /* Socket state. */
- int mode; /* The mode to set. Can be one of
- * TCL_MODE_BLOCKING or
- * TCL_MODE_NONBLOCKING. */
+TcpBlockModeProc(
+ ClientData instanceData, /* Socket state. */
+ int mode) /* The mode to set. Can be one of
+ * TCL_MODE_BLOCKING or
+ * TCL_MODE_NONBLOCKING. */
{
TcpState *statePtr = (TcpState *) instanceData;
- int setting;
-
-#ifndef USE_FIONBIO
- setting = fcntl(statePtr->fd, F_GETFL);
- if (mode == TCL_MODE_BLOCKING) {
- statePtr->flags &= (~(TCP_ASYNC_SOCKET));
- setting &= (~(O_NONBLOCK));
- } else {
- statePtr->flags |= TCP_ASYNC_SOCKET;
- setting |= O_NONBLOCK;
- }
- if (fcntl(statePtr->fd, F_SETFL, setting) < 0) {
- return errno;
- }
-#endif
-#ifdef USE_FIONBIO
if (mode == TCL_MODE_BLOCKING) {
- statePtr->flags &= (~(TCP_ASYNC_SOCKET));
- setting = 0;
- if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) {
- return errno;
- }
+ CLEAR_BITS(statePtr->flags, TCP_ASYNC_SOCKET);
} else {
- statePtr->flags |= TCP_ASYNC_SOCKET;
- setting = 1;
- if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) {
- return errno;
- }
+ SET_BITS(statePtr->flags, TCP_ASYNC_SOCKET);
+ }
+ if (TclUnixSetBlockingMode(statePtr->fd, mode) < 0) {
+ return errno;
}
-#endif
-
return 0;
}
@@ -1555,8 +1866,8 @@ TcpBlockModeProc(instanceData, mode)
*
* WaitForConnect --
*
- * Waits for a connection on an asynchronously opened socket to
- * be completed.
+ * Waits for a connection on an asynchronously opened socket to be
+ * completed.
*
* Results:
* None.
@@ -1568,49 +1879,39 @@ TcpBlockModeProc(instanceData, mode)
*/
static int
-WaitForConnect(statePtr, errorCodePtr)
- TcpState *statePtr; /* State of the socket. */
- int *errorCodePtr; /* Where to store errors? */
+WaitForConnect(
+ TcpState *statePtr, /* State of the socket. */
+ int *errorCodePtr) /* Where to store errors? */
{
int timeOut; /* How long to wait. */
int state; /* Of calling TclWaitForFile. */
- int flags; /* fcntl flags for the socket. */
/*
- * If an asynchronous connect is in progress, attempt to wait for it
- * to complete before reading.
+ * If an asynchronous connect is in progress, attempt to wait for it to
+ * complete before reading.
*/
-
+
if (statePtr->flags & TCP_ASYNC_CONNECT) {
- if (statePtr->flags & TCP_ASYNC_SOCKET) {
- timeOut = 0;
- } else {
- timeOut = -1;
- }
- errno = 0;
- state = TclUnixWaitForFile(statePtr->fd,
+ if (statePtr->flags & TCP_ASYNC_SOCKET) {
+ timeOut = 0;
+ } else {
+ timeOut = -1;
+ }
+ errno = 0;
+ state = TclUnixWaitForFile(statePtr->fd,
TCL_WRITABLE | TCL_EXCEPTION, timeOut);
- if (!(statePtr->flags & TCP_ASYNC_SOCKET)) {
-#ifndef USE_FIONBIO
- flags = fcntl(statePtr->fd, F_GETFL);
- flags &= (~(O_NONBLOCK));
- (void) fcntl(statePtr->fd, F_SETFL, flags);
-#endif
-
-#ifdef USE_FIONBIO
- flags = 0;
- (void) ioctl(statePtr->fd, FIONBIO, &flags);
-#endif
- }
- if (state & TCL_EXCEPTION) {
- return -1;
- }
- if (state & TCL_WRITABLE) {
- statePtr->flags &= (~(TCP_ASYNC_CONNECT));
- } else if (timeOut == 0) {
- *errorCodePtr = errno = EWOULDBLOCK;
- return -1;
- }
+ if (!(statePtr->flags & TCP_ASYNC_SOCKET)) {
+ (void) TclUnixSetBlockingMode(statePtr->fd, TCL_MODE_BLOCKING);
+ }
+ if (state & TCL_EXCEPTION) {
+ return -1;
+ }
+ if (state & TCL_WRITABLE) {
+ CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
+ } else if (timeOut == 0) {
+ *errorCodePtr = errno = EWOULDBLOCK;
+ return -1;
+ }
}
return 0;
}
@@ -1620,16 +1921,16 @@ WaitForConnect(statePtr, errorCodePtr)
*
* TcpInputProc --
*
- * This procedure is invoked by the generic IO level to read input
- * from a TCP socket based channel.
+ * This function is invoked by the generic IO level to read input from a
+ * TCP socket based channel.
*
- * NOTE: We cannot share code with FilePipeInputProc because here
- * we must use recv to obtain the input from the channel, not read.
+ * NOTE: We cannot share code with FilePipeInputProc because here we must
+ * use recv to obtain the input from the channel, not read.
*
* Results:
* The number of bytes read is returned or -1 on error. An output
- * argument contains the POSIX error code on error, or zero if no
- * error occurred.
+ * argument contains the POSIX error code on error, or zero if no error
+ * occurred.
*
* Side effects:
* Reads input from the input device of the channel.
@@ -1639,12 +1940,12 @@ WaitForConnect(statePtr, errorCodePtr)
/* ARGSUSED */
static int
-TcpInputProc(instanceData, buf, bufSize, errorCodePtr)
- ClientData instanceData; /* Socket state. */
- char *buf; /* Where to store data read. */
- int bufSize; /* How much space is available
- * in the buffer? */
- int *errorCodePtr; /* Where to store error code. */
+TcpInputProc(
+ ClientData instanceData, /* Socket state. */
+ char *buf, /* Where to store data read. */
+ int bufSize, /* How much space is available in the
+ * buffer? */
+ int *errorCodePtr) /* Where to store error code. */
{
TcpState *statePtr = (TcpState *) instanceData;
int bytesRead, state;
@@ -1652,19 +1953,18 @@ TcpInputProc(instanceData, buf, bufSize, errorCodePtr)
*errorCodePtr = 0;
state = WaitForConnect(statePtr, errorCodePtr);
if (state != 0) {
- return -1;
+ return -1;
}
bytesRead = recv(statePtr->fd, buf, (size_t) bufSize, 0);
if (bytesRead > -1) {
- return bytesRead;
+ return bytesRead;
}
if (errno == ECONNRESET) {
+ /*
+ * Turn ECONNRESET into a soft EOF condition.
+ */
- /*
- * Turn ECONNRESET into a soft EOF condition.
- */
-
- return 0;
+ return 0;
}
*errorCodePtr = errno;
return -1;
@@ -1675,15 +1975,15 @@ TcpInputProc(instanceData, buf, bufSize, errorCodePtr)
*
* TcpOutputProc --
*
- * This procedure is invoked by the generic IO level to write output
- * to a TCP socket based channel.
+ * This function is invoked by the generic IO level to write output to a
+ * TCP socket based channel.
*
- * NOTE: We cannot share code with FilePipeOutputProc because here
- * we must use send, not write, to get reliable error reporting.
+ * NOTE: We cannot share code with FilePipeOutputProc because here we
+ * must use send, not write, to get reliable error reporting.
*
* Results:
- * The number of bytes written is returned. An output argument is
- * set to a POSIX error code if an error occurred, or zero.
+ * The number of bytes written is returned. An output argument is set to
+ * a POSIX error code if an error occurred, or zero.
*
* Side effects:
* Writes output on the output device of the channel.
@@ -1692,11 +1992,11 @@ TcpInputProc(instanceData, buf, bufSize, errorCodePtr)
*/
static int
-TcpOutputProc(instanceData, buf, toWrite, errorCodePtr)
- ClientData instanceData; /* Socket state. */
- char *buf; /* The data buffer. */
- int toWrite; /* How many bytes to write? */
- int *errorCodePtr; /* Where to store error code. */
+TcpOutputProc(
+ ClientData instanceData, /* Socket state. */
+ const char *buf, /* The data buffer. */
+ int toWrite, /* How many bytes to write? */
+ int *errorCodePtr) /* Where to store error code. */
{
TcpState *statePtr = (TcpState *) instanceData;
int written;
@@ -1705,11 +2005,11 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr)
*errorCodePtr = 0;
state = WaitForConnect(statePtr, errorCodePtr);
if (state != 0) {
- return -1;
+ return -1;
}
written = send(statePtr->fd, buf, (size_t) toWrite, 0);
if (written > -1) {
- return written;
+ return written;
}
*errorCodePtr = errno;
return -1;
@@ -1720,9 +2020,9 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr)
*
* TcpCloseProc --
*
- * This procedure is invoked by the generic IO level to perform
- * channel-type-specific cleanup when a TCP socket based channel
- * is closed.
+ * This function is invoked by the generic IO level to perform
+ * channel-type-specific cleanup when a TCP socket based channel is
+ * closed.
*
* Results:
* 0 if successful, the value of errno if failed.
@@ -1735,20 +2035,19 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr)
/* ARGSUSED */
static int
-TcpCloseProc(instanceData, interp)
- ClientData instanceData; /* The socket to close. */
- Tcl_Interp *interp; /* For error reporting - unused. */
+TcpCloseProc(
+ ClientData instanceData, /* The socket to close. */
+ Tcl_Interp *interp) /* For error reporting - unused. */
{
TcpState *statePtr = (TcpState *) instanceData;
int errorCode = 0;
/*
- * Delete a file handler that may be active for this socket if this
- * is a server socket - the file handler was created automatically
- * by Tcl as part of the mechanism to accept new client connections.
- * Channel handlers are already deleted in the generic IO channel
- * closing code that called this function, so we do not have to
- * delete them here.
+ * Delete a file handler that may be active for this socket if this is a
+ * server socket - the file handler was created automatically by Tcl as
+ * part of the mechanism to accept new client connections. Channel
+ * handlers are already deleted in the generic IO channel closing code
+ * that called this function, so we do not have to delete them here.
*/
Tcl_DeleteFileHandler(statePtr->fd);
@@ -1766,15 +2065,15 @@ TcpCloseProc(instanceData, interp)
*
* TcpGetOptionProc --
*
- * Computes an option value for a TCP socket based channel, or a
- * list of all options and their values.
+ * Computes an option value for a TCP socket based channel, or a list of
+ * all options and their values.
*
* Note: This code is based on code contributed by John Haxby.
*
* Results:
- * A standard Tcl result. The value of the specified option or a
- * list of all options and their values is returned in the
- * supplied DString. Sets Error message if needed.
+ * A standard Tcl result. The value of the specified option or a list of
+ * all options and their values is returned in the supplied DString. Sets
+ * Error message if needed.
*
* Side effects:
* None.
@@ -1783,34 +2082,32 @@ TcpCloseProc(instanceData, interp)
*/
static int
-TcpGetOptionProc(instanceData, interp, optionName, dsPtr)
- ClientData instanceData; /* Socket state. */
- Tcl_Interp *interp; /* For error reporting - can be NULL. */
- char *optionName; /* Name of the option to
- * retrieve the value for, or
- * NULL to get all options and
- * their values. */
- Tcl_DString *dsPtr; /* Where to store the computed
- * value; initialized by caller. */
+TcpGetOptionProc(
+ ClientData instanceData, /* Socket state. */
+ Tcl_Interp *interp, /* For error reporting - can be NULL. */
+ const char *optionName, /* Name of the option to retrieve the value
+ * for, or NULL to get all options and their
+ * values. */
+ Tcl_DString *dsPtr) /* Where to store the computed value;
+ * initialized by caller. */
{
TcpState *statePtr = (TcpState *) instanceData;
struct sockaddr_in sockname;
struct sockaddr_in peername;
struct hostent *hostEntPtr;
- int size = sizeof(struct sockaddr_in);
+ socklen_t size = sizeof(struct sockaddr_in);
size_t len = 0;
char buf[TCL_INTEGER_SPACE];
- if (optionName != (char *) NULL) {
- len = strlen(optionName);
+ if (optionName != NULL) {
+ len = strlen(optionName);
}
if ((len > 1) && (optionName[1] == 'e') &&
(strncmp(optionName, "-error", len) == 0)) {
- int optlen;
+ socklen_t optlen = sizeof(int);
int err, ret;
-
- optlen = sizeof(int);
+
ret = getsockopt(statePtr->fd, SOL_SOCKET, SO_ERROR,
(char *)&err, &optlen);
if (ret < 0) {
@@ -1819,96 +2116,105 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr)
if (err != 0) {
Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(err), -1);
}
- return TCL_OK;
+ return TCL_OK;
}
if ((len == 0) ||
- ((len > 1) && (optionName[1] == 'p') &&
- (strncmp(optionName, "-peername", len) == 0))) {
- if (getpeername(statePtr->fd, (struct sockaddr *) &peername,
+ ((len > 1) && (optionName[1] == 'p') &&
+ (strncmp(optionName, "-peername", len) == 0))) {
+ if (getpeername(statePtr->fd, (struct sockaddr *) &peername,
&size) >= 0) {
- if (len == 0) {
- Tcl_DStringAppendElement(dsPtr, "-peername");
- Tcl_DStringStartSublist(dsPtr);
- }
- Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
- hostEntPtr = gethostbyaddr( /* INTL: Native. */
+ if (len == 0) {
+ Tcl_DStringAppendElement(dsPtr, "-peername");
+ Tcl_DStringStartSublist(dsPtr);
+ }
+ Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
+ hostEntPtr = TclpGetHostByAddr( /* INTL: Native. */
(char *) &peername.sin_addr,
sizeof(peername.sin_addr), AF_INET);
- if (hostEntPtr != NULL) {
+ if (hostEntPtr != NULL) {
Tcl_DString ds;
Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds);
- Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
- } else {
- Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
- }
- TclFormatInt(buf, ntohs(peername.sin_port));
- Tcl_DStringAppendElement(dsPtr, buf);
- if (len == 0) {
- Tcl_DStringEndSublist(dsPtr);
- } else {
- return TCL_OK;
- }
- } else {
- /*
- * getpeername failed - but if we were asked for all the options
- * (len==0), don't flag an error at that point because it could
- * be an fconfigure request on a server socket. (which have
- * no peer). same must be done on win&mac.
- */
-
- if (len) {
- if (interp) {
- Tcl_AppendResult(interp, "can't get peername: ",
- Tcl_PosixError(interp),
- (char *) NULL);
- }
- return TCL_ERROR;
- }
- }
+ Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
+ Tcl_DStringFree(&ds);
+ } else {
+ Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
+ }
+ TclFormatInt(buf, ntohs(peername.sin_port));
+ Tcl_DStringAppendElement(dsPtr, buf);
+ if (len == 0) {
+ Tcl_DStringEndSublist(dsPtr);
+ } else {
+ return TCL_OK;
+ }
+ } else {
+ /*
+ * getpeername failed - but if we were asked for all the options
+ * (len==0), don't flag an error at that point because it could be
+ * an fconfigure request on a server socket (which have no peer).
+ * Same must be done on win&mac.
+ */
+
+ if (len) {
+ if (interp) {
+ Tcl_AppendResult(interp, "can't get peername: ",
+ Tcl_PosixError(interp), NULL);
+ }
+ return TCL_ERROR;
+ }
+ }
}
if ((len == 0) ||
- ((len > 1) && (optionName[1] == 's') &&
- (strncmp(optionName, "-sockname", len) == 0))) {
- if (getsockname(statePtr->fd, (struct sockaddr *) &sockname, &size)
- >= 0) {
- if (len == 0) {
- Tcl_DStringAppendElement(dsPtr, "-sockname");
- Tcl_DStringStartSublist(dsPtr);
+ ((len > 1) && (optionName[1] == 's') &&
+ (strncmp(optionName, "-sockname", len) == 0))) {
+ if (getsockname(statePtr->fd, (struct sockaddr *) &sockname,
+ &size) >= 0) {
+ if (len == 0) {
+ Tcl_DStringAppendElement(dsPtr, "-sockname");
+ Tcl_DStringStartSublist(dsPtr);
+ }
+ Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
+ if (sockname.sin_addr.s_addr == INADDR_ANY) {
+ /*
+ * We don't want to resolve INADDR_ANY; it can sometimes cause
+ * problems (and never has a name).
+ */
+
+ hostEntPtr = NULL;
+ } else {
+ hostEntPtr = TclpGetHostByAddr( /* INTL: Native. */
+ (char *) &sockname.sin_addr,
+ sizeof(sockname.sin_addr), AF_INET);
}
- Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
- hostEntPtr = gethostbyaddr( /* INTL: Native. */
- (char *) &sockname.sin_addr,
- sizeof(sockname.sin_addr), AF_INET);
- if (hostEntPtr != (struct hostent *) NULL) {
+ if (hostEntPtr != NULL) {
Tcl_DString ds;
Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds);
- Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
- } else {
- Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
- }
- TclFormatInt(buf, ntohs(sockname.sin_port));
- Tcl_DStringAppendElement(dsPtr, buf);
- if (len == 0) {
- Tcl_DStringEndSublist(dsPtr);
- } else {
- return TCL_OK;
- }
- } else {
+ Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
+ Tcl_DStringFree(&ds);
+ } else {
+ Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
+ }
+ TclFormatInt(buf, ntohs(sockname.sin_port));
+ Tcl_DStringAppendElement(dsPtr, buf);
+ if (len == 0) {
+ Tcl_DStringEndSublist(dsPtr);
+ } else {
+ return TCL_OK;
+ }
+ } else {
if (interp) {
Tcl_AppendResult(interp, "can't get sockname: ",
- Tcl_PosixError(interp),
- (char *) NULL);
+ Tcl_PosixError(interp), NULL);
}
return TCL_ERROR;
}
}
if (len > 0) {
- return Tcl_BadChannelOption(interp, optionName, "peername sockname");
+ return Tcl_BadChannelOption(interp, optionName, "peername sockname");
}
return TCL_OK;
@@ -1925,32 +2231,82 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr)
* None.
*
* Side effects:
- * Sets up the notifier so that a future event on the channel will
- * be seen by Tcl.
+ * Sets up the notifier so that a future event on the channel will be
+ * seen by Tcl.
*
*----------------------------------------------------------------------
*/
static void
-TcpWatchProc(instanceData, mask)
- ClientData instanceData; /* The socket state. */
- int mask; /* Events of interest; an OR-ed
- * combination of TCL_READABLE,
- * TCL_WRITABLE and TCL_EXCEPTION. */
+WrapNotify(
+ ClientData clientData,
+ int mask)
+{
+ TcpState *statePtr = (TcpState *) clientData;
+ int newmask = mask & statePtr->interest;
+
+ if (newmask == 0) {
+ /*
+ * There was no overlap between the states the channel is
+ * interested in notifications for, and the states that are
+ * reported present on the file descriptor by select(). The
+ * only way that can happen is when the channel is interested
+ * in a writable condition, and only a readable state is reported
+ * present (see TcpWatchProc() below). In that case, signal back
+ * to the caller the writable state, which is really an error
+ * condition. As an extra check on that assumption, check for
+ * a non-zero value of errno before reporting an artificial
+ * writable state.
+ */
+ if (errno == 0) {
+ return;
+ }
+ newmask = TCL_WRITABLE;
+ }
+ Tcl_NotifyChannel(statePtr->channel, newmask);
+}
+
+static void
+TcpWatchProc(
+ ClientData instanceData, /* The socket state. */
+ int mask) /* Events of interest; an OR-ed combination of
+ * TCL_READABLE, TCL_WRITABLE and
+ * TCL_EXCEPTION. */
{
TcpState *statePtr = (TcpState *) instanceData;
/*
- * Make sure we don't mess with server sockets since they will never
- * be readable or writable at the Tcl level. This keeps Tcl scripts
- * from interfering with the -accept behavior.
+ * Make sure we don't mess with server sockets since they will never be
+ * readable or writable at the Tcl level. This keeps Tcl scripts from
+ * interfering with the -accept behavior.
*/
if (!statePtr->acceptProc) {
if (mask) {
- Tcl_CreateFileHandler(statePtr->fd, mask,
- (Tcl_FileProc *) Tcl_NotifyChannel,
- (ClientData) statePtr->channel);
+
+ /*
+ * Whether it is a bug or feature or otherwise, it is a fact
+ * of life that on at least some Linux kernels select() fails
+ * to report that a socket file descriptor is writable when
+ * the other end of the socket is closed. This is in contrast
+ * to the guarantees Tcl makes that its channels become
+ * writable and fire writable events on an error conditon.
+ * This has caused a leak of file descriptors in a state of
+ * background flushing. See Tcl ticket 1758a0b603.
+ *
+ * As a workaround, when our caller indicates an interest in
+ * writable notifications, we must tell the notifier built
+ * around select() that we are interested in the readable state
+ * of the file descriptor as well, as that is the only reliable
+ * means to get notified of error conditions. Then it is the
+ * task of WrapNotify() above to untangle the meaning of these
+ * channel states and report the chan events as best it can.
+ * We save a copy of the mask passed in to assist with that.
+ */
+
+ statePtr->interest = mask;
+ Tcl_CreateFileHandler(statePtr->fd, mask|TCL_READABLE,
+ (Tcl_FileProc *) WrapNotify, (ClientData) statePtr);
} else {
Tcl_DeleteFileHandler(statePtr->fd);
}
@@ -1962,12 +2318,12 @@ TcpWatchProc(instanceData, mask)
*
* TcpGetHandleProc --
*
- * Called from Tcl_GetChannelHandle to retrieve OS handles from inside
- * a TCP socket based channel.
+ * Called from Tcl_GetChannelHandle to retrieve OS handles from inside a
+ * TCP socket based channel.
*
* Results:
- * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
- * there is no handle for the specified direction.
+ * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
+ * handle for the specified direction.
*
* Side effects:
* None.
@@ -1977,14 +2333,14 @@ TcpWatchProc(instanceData, mask)
/* ARGSUSED */
static int
-TcpGetHandleProc(instanceData, direction, handlePtr)
- ClientData instanceData; /* The socket state. */
- int direction; /* Not used. */
- ClientData *handlePtr; /* Where to store the handle. */
+TcpGetHandleProc(
+ ClientData instanceData, /* The socket state. */
+ int direction, /* Not used. */
+ ClientData *handlePtr) /* Where to store the handle. */
{
TcpState *statePtr = (TcpState *) instanceData;
- *handlePtr = (ClientData)statePtr->fd;
+ *handlePtr = (ClientData) INT2PTR(statePtr->fd);
return TCL_OK;
}
@@ -1993,12 +2349,12 @@ TcpGetHandleProc(instanceData, direction, handlePtr)
*
* CreateSocket --
*
- * This function opens a new socket in client or server mode
- * and initializes the TcpState structure.
+ * This function opens a new socket in client or server mode and
+ * initializes the TcpState structure.
*
* Results:
- * Returns a new TcpState, or NULL with an error in the interp's
- * result, if interp is not NULL.
+ * Returns a new TcpState, or NULL with an error in the interp's result,
+ * if interp is not NULL.
*
* Side effects:
* Opens a socket.
@@ -2007,31 +2363,31 @@ TcpGetHandleProc(instanceData, direction, handlePtr)
*/
static TcpState *
-CreateSocket(interp, port, host, server, myaddr, myport, async)
- Tcl_Interp *interp; /* For error reporting; can be NULL. */
- int port; /* Port number to open. */
- char *host; /* Name of host on which to open port.
- * NULL implies INADDR_ANY */
- int server; /* 1 if socket should be a server socket,
- * else 0 for a client socket. */
- char *myaddr; /* Optional client-side address */
- int myport; /* Optional client-side port */
- int async; /* If nonzero and creating a client socket,
- * attempt to do an async connect. Otherwise
- * do a synchronous connect or bind. */
+CreateSocket(
+ Tcl_Interp *interp, /* For error reporting; can be NULL. */
+ int port, /* Port number to open. */
+ const char *host, /* Name of host on which to open port. NULL
+ * implies INADDR_ANY */
+ int server, /* 1 if socket should be a server socket, else
+ * 0 for a client socket. */
+ const char *myaddr, /* Optional client-side address */
+ int myport, /* Optional client-side port */
+ int async) /* If nonzero and creating a client socket,
+ * attempt to do an async connect. Otherwise
+ * do a synchronous connect or bind. */
{
- int status, sock, asyncConnect, curState, origState;
+ int status, sock, asyncConnect, curState;
struct sockaddr_in sockaddr; /* socket address */
struct sockaddr_in mysockaddr; /* Socket address for client */
TcpState *statePtr;
+ const char *errorMsg = NULL;
sock = -1;
- origState = 0;
- if (! CreateSocketAddress(&sockaddr, host, port)) {
+ if (!CreateSocketAddress(&sockaddr, host, port, 0, &errorMsg)) {
goto addressError;
}
if ((myaddr != NULL || myport != 0) &&
- ! CreateSocketAddress(&mysockaddr, myaddr, myport)) {
+ !CreateSocketAddress(&mysockaddr, myaddr, myport, 1, &errorMsg)) {
goto addressError;
}
@@ -2041,12 +2397,12 @@ CreateSocket(interp, port, host, server, myaddr, myport, async)
}
/*
- * Set the close-on-exec flag so that the socket will not get
- * inherited by child processes.
+ * Set the close-on-exec flag so that the socket will not get inherited by
+ * child processes.
*/
fcntl(sock, F_SETFD, FD_CLOEXEC);
-
+
/*
* Set kernel space buffering
*/
@@ -2056,25 +2412,24 @@ CreateSocket(interp, port, host, server, myaddr, myport, async)
asyncConnect = 0;
status = 0;
if (server) {
-
/*
* Set up to reuse server addresses automatically and bind to the
* specified port.
*/
-
+
status = 1;
(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status,
sizeof(status));
status = bind(sock, (struct sockaddr *) &sockaddr,
- sizeof(struct sockaddr));
+ sizeof(struct sockaddr));
if (status != -1) {
status = listen(sock, SOMAXCONN);
- }
+ }
} else {
- if (myaddr != NULL || myport != 0) {
+ if (myaddr != NULL || myport != 0) {
curState = 1;
(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
- (char *) &curState, sizeof(curState));
+ (char *) &curState, sizeof(curState));
status = bind(sock, (struct sockaddr *) &mysockaddr,
sizeof(struct sockaddr));
if (status < 0) {
@@ -2084,67 +2439,50 @@ CreateSocket(interp, port, host, server, myaddr, myport, async)
/*
* Attempt to connect. The connect may fail at present with an
- * EINPROGRESS but at a later time it will complete. The caller
- * will set up a file handler on the socket if she is interested in
- * being informed when the connect completes.
+ * EINPROGRESS but at a later time it will complete. The caller will
+ * set up a file handler on the socket if she is interested in being
+ * informed when the connect completes.
*/
- if (async) {
-#ifndef USE_FIONBIO
- origState = fcntl(sock, F_GETFL);
- curState = origState | O_NONBLOCK;
- status = fcntl(sock, F_SETFL, curState);
-#endif
-
-#ifdef USE_FIONBIO
- curState = 1;
- status = ioctl(sock, FIONBIO, &curState);
-#endif
- } else {
- status = 0;
- }
- if (status > -1) {
- status = connect(sock, (struct sockaddr *) &sockaddr,
- sizeof(sockaddr));
- if (status < 0) {
- if (errno == EINPROGRESS) {
- asyncConnect = 1;
- status = 0;
- }
+ if (async) {
+ status = TclUnixSetBlockingMode(sock, TCL_MODE_NONBLOCKING);
+ } else {
+ status = 0;
+ }
+ if (status > -1) {
+ status = connect(sock, (struct sockaddr *) &sockaddr,
+ sizeof(sockaddr));
+ if (status < 0) {
+ if (errno == EINPROGRESS) {
+ asyncConnect = 1;
+ status = 0;
+ }
} else {
/*
* Here we are if the connect succeeds. In case of an
* asynchronous connect we have to reset the channel to
- * blocking mode. This appears to happen not very often,
- * but e.g. on a HP 9000/800 under HP-UX B.11.00 we enter
- * this stage. [Bug: 4388]
+ * blocking mode. This appears to happen not very often, but
+ * e.g. on a HP 9000/800 under HP-UX B.11.00 we enter this
+ * stage. [Bug: 4388]
*/
- if (async) {
-#ifndef USE_FIONBIO
- origState = fcntl(sock, F_GETFL);
- curState = origState & ~(O_NONBLOCK);
- status = fcntl(sock, F_SETFL, curState);
-#endif
-#ifdef USE_FIONBIO
- curState = 0;
- status = ioctl(sock, FIONBIO, &curState);
-#endif
+ if (async) {
+ status = TclUnixSetBlockingMode(sock, TCL_MODE_BLOCKING);
}
}
- }
+ }
}
-bindError:
+ bindError:
if (status < 0) {
- if (interp != NULL) {
- Tcl_AppendResult(interp, "couldn't open socket: ",
- Tcl_PosixError(interp), (char *) NULL);
- }
- if (sock != -1) {
- close(sock);
- }
- return NULL;
+ if (interp != NULL) {
+ Tcl_AppendResult(interp, "couldn't open socket: ",
+ Tcl_PosixError(interp), NULL);
+ }
+ if (sock != -1) {
+ close(sock);
+ }
+ return NULL;
}
/*
@@ -2154,19 +2492,23 @@ bindError:
statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
statePtr->flags = 0;
if (asyncConnect) {
- statePtr->flags = TCP_ASYNC_CONNECT;
+ statePtr->flags = TCP_ASYNC_CONNECT;
}
+ statePtr->interest = 0;
statePtr->fd = sock;
return statePtr;
-addressError:
+ addressError:
if (sock != -1) {
- close(sock);
+ close(sock);
}
if (interp != NULL) {
Tcl_AppendResult(interp, "couldn't open socket: ",
- Tcl_PosixError(interp), (char *) NULL);
+ Tcl_PosixError(interp), NULL);
+ if (errorMsg != NULL) {
+ Tcl_AppendResult(interp, " (", errorMsg, ")", NULL);
+ }
}
return NULL;
}
@@ -2179,8 +2521,8 @@ addressError:
* This function initializes a sockaddr structure for a host and port.
*
* Results:
- * 1 if the host was valid, 0 if the host could not be converted to
- * an IP address.
+ * 1 if the host was valid, 0 if the host could not be converted to an IP
+ * address.
*
* Side effects:
* Fills in the *sockaddrPtr structure.
@@ -2189,67 +2531,132 @@ addressError:
*/
static int
-CreateSocketAddress(sockaddrPtr, host, port)
- struct sockaddr_in *sockaddrPtr; /* Socket address */
- char *host; /* Host. NULL implies INADDR_ANY */
- int port; /* Port number */
+CreateSocketAddress(
+ struct sockaddr_in *sockaddrPtr, /* Socket address */
+ const char *host, /* Host. NULL implies INADDR_ANY */
+ int port, /* Port number */
+ int willBind, /* Is this an address to bind() to or
+ * to connect() to? */
+ const char **errorMsgPtr) /* Place to store the error message
+ * detail, if available. */
{
- struct hostent *hostent; /* Host database entry */
+#ifdef HAVE_GETADDRINFO
+ struct addrinfo hints, *resPtr = NULL;
+ char *native;
+ Tcl_DString ds;
+ int result;
+
+ if (host == NULL) {
+ sockaddrPtr->sin_family = AF_INET;
+ sockaddrPtr->sin_addr.s_addr = INADDR_ANY;
+ addPort:
+ sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF));
+ return 1;
+ }
+
+ (void) memset(&hints, 0, sizeof(struct addrinfo));
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ if (willBind) {
+ hints.ai_flags |= AI_PASSIVE;
+ }
+
+ /*
+ * Note that getaddrinfo() *is* thread-safe. If a platform doesn't get
+ * that right, it shouldn't use this part of the code.
+ */
+
+ native = Tcl_UtfToExternalDString(NULL, host, -1, &ds);
+ result = getaddrinfo(native, NULL, &hints, &resPtr);
+ Tcl_DStringFree(&ds);
+ if (result == 0) {
+ memcpy(sockaddrPtr, resPtr->ai_addr, sizeof(struct sockaddr_in));
+ freeaddrinfo(resPtr);
+ goto addPort;
+ }
+
+ /*
+ * Ought to use gai_strerror() here...
+ */
+
+ switch (result) {
+ case EAI_NONAME:
+ case EAI_SERVICE:
+#if defined(EAI_ADDRFAMILY) && EAI_ADDRFAMILY != EAI_NONAME
+ case EAI_ADDRFAMILY:
+#endif
+#if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
+ case EAI_NODATA:
+#endif
+ *errorMsgPtr = gai_strerror(result);
+ errno = EHOSTUNREACH;
+ return 0;
+ case EAI_SYSTEM:
+ return 0;
+ default:
+ *errorMsgPtr = gai_strerror(result);
+ errno = ENXIO;
+ return 0;
+ }
+#else /* !HAVE_GETADDRINFO */
struct in_addr addr; /* For 64/32 bit madness */
- (void) memset((VOID *) sockaddrPtr, '\0', sizeof(struct sockaddr_in));
+ (void) memset(sockaddrPtr, '\0', sizeof(struct sockaddr_in));
sockaddrPtr->sin_family = AF_INET;
sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF));
if (host == NULL) {
addr.s_addr = INADDR_ANY;
} else {
+ struct hostent *hostent; /* Host database entry */
Tcl_DString ds;
- CONST char *native;
+ const char *native;
if (host == NULL) {
native = NULL;
} else {
native = Tcl_UtfToExternalDString(NULL, host, -1, &ds);
}
- addr.s_addr = inet_addr(native); /* INTL: Native. */
+ addr.s_addr = inet_addr(native); /* INTL: Native. */
+
/*
- * This is 0xFFFFFFFF to ensure that it compares as a 32bit -1
- * on either 32 or 64 bits systems.
+ * This is 0xFFFFFFFF to ensure that it compares as a 32bit -1 on
+ * either 32 or 64 bits systems.
*/
- if (addr.s_addr == 0xFFFFFFFF) {
- hostent = gethostbyname(native); /* INTL: Native. */
- if (hostent != NULL) {
- memcpy((VOID *) &addr,
- (VOID *) hostent->h_addr_list[0],
- (size_t) hostent->h_length);
- } else {
+
+ if (addr.s_addr == 0xFFFFFFFF) {
+ hostent = TclpGetHostByName(native); /* INTL: Native. */
+ if (hostent != NULL) {
+ memcpy(&addr, hostent->h_addr_list[0],
+ (size_t) hostent->h_length);
+ } else {
#ifdef EHOSTUNREACH
- errno = EHOSTUNREACH;
-#else
+ errno = EHOSTUNREACH;
+#else /* !EHOSTUNREACH */
#ifdef ENXIO
- errno = ENXIO;
-#endif
-#endif
+ errno = ENXIO;
+#endif /* ENXIO */
+#endif /* EHOSTUNREACH */
if (native != NULL) {
Tcl_DStringFree(&ds);
}
- return 0; /* error */
- }
- }
+ return 0; /* Error. */
+ }
+ }
if (native != NULL) {
Tcl_DStringFree(&ds);
}
}
-
+
/*
- * NOTE: On 64 bit machines the assignment below is rumored to not
- * do the right thing. Please report errors related to this if you
- * observe incorrect behavior on 64 bit machines such as DEC Alphas.
- * Should we modify this code to do an explicit memcpy?
+ * NOTE: On 64 bit machines the assignment below is rumored to not do the
+ * right thing. Please report errors related to this if you observe
+ * incorrect behavior on 64 bit machines such as DEC Alphas. Should we
+ * modify this code to do an explicit memcpy?
*/
sockaddrPtr->sin_addr.s_addr = addr.s_addr;
- return 1; /* Success. */
+ return 1; /* Success. */
+#endif /* HAVE_GETADDRINFO */
}
/*
@@ -2260,8 +2667,8 @@ CreateSocketAddress(sockaddrPtr, host, port)
* Opens a TCP client socket and creates a channel around it.
*
* Results:
- * The channel or NULL if failed. An error message is returned
- * in the interpreter on failure.
+ * The channel or NULL if failed. An error message is returned in the
+ * interpreter on failure.
*
* Side effects:
* Opens a client socket and creates a new channel.
@@ -2270,15 +2677,15 @@ CreateSocketAddress(sockaddrPtr, host, port)
*/
Tcl_Channel
-Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async)
- Tcl_Interp *interp; /* For error reporting; can be NULL. */
- int port; /* Port number to open. */
- char *host; /* Host on which to open port. */
- char *myaddr; /* Client-side address */
- int myport; /* Client-side port */
- int async; /* If nonzero, attempt to do an
- * asynchronous connect. Otherwise
- * we do a blocking connect. */
+Tcl_OpenTcpClient(
+ Tcl_Interp *interp, /* For error reporting; can be NULL. */
+ int port, /* Port number to open. */
+ const char *host, /* Host on which to open port. */
+ const char *myaddr, /* Client-side address */
+ int myport, /* Client-side port */
+ int async) /* If nonzero, attempt to do an asynchronous
+ * connect. Otherwise we do a blocking
+ * connect. */
{
TcpState *statePtr;
char channelName[16 + TCL_INTEGER_SPACE];
@@ -2293,16 +2700,16 @@ Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async)
}
statePtr->acceptProc = NULL;
- statePtr->acceptProcData = (ClientData) NULL;
+ statePtr->acceptProcData = NULL;
sprintf(channelName, "sock%d", statePtr->fd);
statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
- (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE));
+ (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE));
if (Tcl_SetChannelOption(interp, statePtr->channel, "-translation",
"auto crlf") == TCL_ERROR) {
- Tcl_Close((Tcl_Interp *) NULL, statePtr->channel);
- return NULL;
+ Tcl_Close(NULL, statePtr->channel);
+ return NULL;
}
return statePtr->channel;
}
@@ -2324,25 +2731,53 @@ Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async)
*/
Tcl_Channel
-Tcl_MakeTcpClientChannel(sock)
- ClientData sock; /* The socket to wrap up into a channel. */
+Tcl_MakeTcpClientChannel(
+ ClientData sock) /* The socket to wrap up into a channel. */
+{
+ return MakeTcpClientChannelMode(sock, (TCL_READABLE | TCL_WRITABLE));
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * MakeTcpClientChannelMode --
+ *
+ * Creates a Tcl_Channel from an existing client TCP socket
+ * with given mode.
+ *
+ * Results:
+ * The Tcl_Channel wrapped around the preexisting TCP socket.
+ *
+ * Side effects:
+ * None.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static Tcl_Channel
+MakeTcpClientChannelMode(
+ ClientData sock, /* The socket to wrap up into a channel. */
+ int mode) /* ORed combination of TCL_READABLE and
+ * TCL_WRITABLE to indicate file mode. */
{
TcpState *statePtr;
char channelName[16 + TCL_INTEGER_SPACE];
statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
- statePtr->fd = (int) sock;
+ statePtr->fd = PTR2INT(sock);
+ statePtr->flags = 0;
+ statePtr->interest = 0;
statePtr->acceptProc = NULL;
- statePtr->acceptProcData = (ClientData) NULL;
+ statePtr->acceptProcData = NULL;
sprintf(channelName, "sock%d", statePtr->fd);
-
+
statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
- (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE));
- if (Tcl_SetChannelOption((Tcl_Interp *) NULL, statePtr->channel,
- "-translation", "auto crlf") == TCL_ERROR) {
- Tcl_Close((Tcl_Interp *) NULL, statePtr->channel);
- return NULL;
+ (ClientData) statePtr, mode);
+ if (Tcl_SetChannelOption(NULL, statePtr->channel, "-translation",
+ "auto crlf") == TCL_ERROR) {
+ Tcl_Close(NULL, statePtr->channel);
+ return NULL;
}
return statePtr->channel;
}
@@ -2355,9 +2790,8 @@ Tcl_MakeTcpClientChannel(sock)
* Opens a TCP server socket and creates a channel around it.
*
* Results:
- * The channel or NULL if failed. If an error occurred, an
- * error message is left in the interp's result if interp is
- * not NULL.
+ * The channel or NULL if failed. If an error occurred, an error message
+ * is left in the interp's result if interp is not NULL.
*
* Side effects:
* Opens a server socket and creates a new channel.
@@ -2366,14 +2800,14 @@ Tcl_MakeTcpClientChannel(sock)
*/
Tcl_Channel
-Tcl_OpenTcpServer(interp, port, myHost, acceptProc, acceptProcData)
- Tcl_Interp *interp; /* For error reporting - may be
- * NULL. */
- int port; /* Port number to open. */
- char *myHost; /* Name of local host. */
- Tcl_TcpAcceptProc *acceptProc; /* Callback for accepting connections
- * from new clients. */
- ClientData acceptProcData; /* Data for the callback. */
+Tcl_OpenTcpServer(
+ Tcl_Interp *interp, /* For error reporting - may be NULL. */
+ int port, /* Port number to open. */
+ const char *myHost, /* Name of local host. */
+ Tcl_TcpAcceptProc *acceptProc,
+ /* Callback for accepting connections from new
+ * clients. */
+ ClientData acceptProcData) /* Data for the callback. */
{
TcpState *statePtr;
char channelName[16 + TCL_INTEGER_SPACE];
@@ -2391,15 +2825,15 @@ Tcl_OpenTcpServer(interp, port, myHost, acceptProc, acceptProcData)
statePtr->acceptProcData = acceptProcData;
/*
- * Set up the callback mechanism for accepting connections
- * from new clients.
+ * Set up the callback mechanism for accepting connections from new
+ * clients.
*/
Tcl_CreateFileHandler(statePtr->fd, TCL_READABLE, TcpAccept,
- (ClientData) statePtr);
+ (ClientData) statePtr);
sprintf(channelName, "sock%d", statePtr->fd);
statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
- (ClientData) statePtr, 0);
+ (ClientData) statePtr, 0);
return statePtr->channel;
}
@@ -2407,29 +2841,29 @@ Tcl_OpenTcpServer(interp, port, myHost, acceptProc, acceptProcData)
*----------------------------------------------------------------------
*
* TcpAccept --
- * Accept a TCP socket connection. This is called by the event loop.
+ * Accept a TCP socket connection. This is called by the event loop.
*
* Results:
* None.
*
* Side effects:
- * Creates a new connection socket. Calls the registered callback
- * for the connection acceptance mechanism.
+ * Creates a new connection socket. Calls the registered callback for the
+ * connection acceptance mechanism.
*
*----------------------------------------------------------------------
*/
/* ARGSUSED */
static void
-TcpAccept(data, mask)
- ClientData data; /* Callback token. */
- int mask; /* Not used. */
+TcpAccept(
+ ClientData data, /* Callback token. */
+ int mask) /* Not used. */
{
- TcpState *sockState; /* Client data of server socket. */
- int newsock; /* The new client socket */
- TcpState *newSockState; /* State for new socket. */
- struct sockaddr_in addr; /* The remote address */
- int len; /* For accept interface */
+ TcpState *sockState; /* Client data of server socket. */
+ int newsock; /* The new client socket */
+ TcpState *newSockState; /* State for new socket. */
+ struct sockaddr_in addr; /* The remote address */
+ socklen_t len; /* For accept interface */
char channelName[16 + TCL_INTEGER_SPACE];
sockState = (TcpState *) data;
@@ -2437,23 +2871,24 @@ TcpAccept(data, mask)
len = sizeof(struct sockaddr_in);
newsock = accept(sockState->fd, (struct sockaddr *) &addr, &len);
if (newsock < 0) {
- return;
+ return;
}
/*
- * Set close-on-exec flag to prevent the newly accepted socket from
- * being inherited by child processes.
+ * Set close-on-exec flag to prevent the newly accepted socket from being
+ * inherited by child processes.
*/
(void) fcntl(newsock, F_SETFD, FD_CLOEXEC);
-
+
newSockState = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
newSockState->flags = 0;
+ newSockState->interest = 0;
newSockState->fd = newsock;
newSockState->acceptProc = NULL;
newSockState->acceptProcData = NULL;
-
+
sprintf(channelName, "sock%d", newsock);
newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
(ClientData) newSockState, (TCL_READABLE | TCL_WRITABLE));
@@ -2473,62 +2908,71 @@ TcpAccept(data, mask)
*
* TclpGetDefaultStdChannel --
*
- * Creates channels for standard input, standard output or standard
- * error output if they do not already exist.
+ * Creates channels for standard input, standard output or standard error
+ * output if they do not already exist.
*
* Results:
* Returns the specified default standard channel, or NULL.
*
* Side effects:
- * May cause the creation of a standard channel and the underlying
- * file.
+ * May cause the creation of a standard channel and the underlying file.
*
*----------------------------------------------------------------------
*/
Tcl_Channel
-TclpGetDefaultStdChannel(type)
- int type; /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
+TclpGetDefaultStdChannel(
+ int type) /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
{
Tcl_Channel channel = NULL;
int fd = 0; /* Initializations needed to prevent */
int mode = 0; /* compiler warning (used before set). */
- char *bufMode = NULL;
+ const char *bufMode = NULL;
+
+ /*
+ * Some #def's to make the code a little clearer!
+ */
+
+#define ZERO_OFFSET ((Tcl_SeekOffset) 0)
+#define ERROR_OFFSET ((Tcl_SeekOffset) -1)
switch (type) {
- case TCL_STDIN:
- if ((lseek(0, (off_t) 0, SEEK_CUR) == -1) &&
- (errno == EBADF)) {
- return (Tcl_Channel) NULL;
- }
- fd = 0;
- mode = TCL_READABLE;
- bufMode = "line";
- break;
- case TCL_STDOUT:
- if ((lseek(1, (off_t) 0, SEEK_CUR) == -1) &&
- (errno == EBADF)) {
- return (Tcl_Channel) NULL;
- }
- fd = 1;
- mode = TCL_WRITABLE;
- bufMode = "line";
- break;
- case TCL_STDERR:
- if ((lseek(2, (off_t) 0, SEEK_CUR) == -1) &&
- (errno == EBADF)) {
- return (Tcl_Channel) NULL;
- }
- fd = 2;
- mode = TCL_WRITABLE;
- bufMode = "none";
- break;
- default:
- panic("TclGetDefaultStdChannel: Unexpected channel type");
- break;
+ case TCL_STDIN:
+ if ((TclOSseek(0, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
+ && (errno == EBADF)) {
+ return NULL;
+ }
+ fd = 0;
+ mode = TCL_READABLE;
+ bufMode = "line";
+ break;
+ case TCL_STDOUT:
+ if ((TclOSseek(1, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
+ && (errno == EBADF)) {
+ return NULL;
+ }
+ fd = 1;
+ mode = TCL_WRITABLE;
+ bufMode = "line";
+ break;
+ case TCL_STDERR:
+ if ((TclOSseek(2, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
+ && (errno == EBADF)) {
+ return NULL;
+ }
+ fd = 2;
+ mode = TCL_WRITABLE;
+ bufMode = "none";
+ break;
+ default:
+ Tcl_Panic("TclGetDefaultStdChannel: Unexpected channel type");
+ break;
}
- channel = Tcl_MakeFileChannel((ClientData) fd, mode);
+#undef ZERO_OFFSET
+#undef ERROR_OFFSET
+
+ channel = Tcl_MakeFileChannel((ClientData) INT2PTR(fd), mode);
if (channel == NULL) {
return NULL;
}
@@ -2551,16 +2995,16 @@ TclpGetDefaultStdChannel(type)
*
* Tcl_GetOpenFile --
*
- * Given a name of a channel registered in the given interpreter,
- * returns a FILE * for it.
+ * Given a name of a channel registered in the given interpreter, returns
+ * a FILE * for it.
*
* Results:
* A standard Tcl result. If the channel is registered in the given
- * interpreter and it is managed by the "file" channel driver, and
- * it is open for the requested mode, then the output parameter
- * filePtr is set to a FILE * for the underlying file. On error, the
- * filePtr is not set, TCL_ERROR is returned and an error message is
- * left in the interp's result.
+ * interpreter and it is managed by the "file" channel driver, and it is
+ * open for the requested mode, then the output parameter filePtr is set
+ * to a FILE * for the underlying file. On error, the filePtr is not set,
+ * TCL_ERROR is returned and an error message is left in the interp's
+ * result.
*
* Side effects:
* May invoke fdopen to create the FILE * for the requested file.
@@ -2569,37 +3013,36 @@ TclpGetDefaultStdChannel(type)
*/
int
-Tcl_GetOpenFile(interp, string, forWriting, checkUsage, filePtr)
- Tcl_Interp *interp; /* Interpreter in which to find file. */
- char *string; /* String that identifies file. */
- int forWriting; /* 1 means the file is going to be used
- * for writing, 0 means for reading. */
- int checkUsage; /* 1 means verify that the file was opened
- * in a mode that allows the access specified
- * by "forWriting". Ignored, we always
- * check that the channel is open for the
- * requested mode. */
- ClientData *filePtr; /* Store pointer to FILE structure here. */
+Tcl_GetOpenFile(
+ Tcl_Interp *interp, /* Interpreter in which to find file. */
+ const char *chanID, /* String that identifies file. */
+ int forWriting, /* 1 means the file is going to be used for
+ * writing, 0 means for reading. */
+ int checkUsage, /* 1 means verify that the file was opened in
+ * a mode that allows the access specified by
+ * "forWriting". Ignored, we always check that
+ * the channel is open for the requested
+ * mode. */
+ ClientData *filePtr) /* Store pointer to FILE structure here. */
{
Tcl_Channel chan;
- int chanMode;
- Tcl_ChannelType *chanTypePtr;
+ int chanMode, fd;
+ const Tcl_ChannelType *chanTypePtr;
ClientData data;
- int fd;
FILE *f;
-
- chan = Tcl_GetChannel(interp, string, &chanMode);
+
+ chan = Tcl_GetChannel(interp, chanID, &chanMode);
if (chan == (Tcl_Channel) NULL) {
- return TCL_ERROR;
+ return TCL_ERROR;
}
if ((forWriting) && ((chanMode & TCL_WRITABLE) == 0)) {
- Tcl_AppendResult(interp,
- "\"", string, "\" wasn't opened for writing", (char *) NULL);
- return TCL_ERROR;
- } else if ((!(forWriting)) && ((chanMode & TCL_READABLE) == 0)) {
- Tcl_AppendResult(interp,
- "\"", string, "\" wasn't opened for reading", (char *) NULL);
- return TCL_ERROR;
+ Tcl_AppendResult(interp, "\"", chanID, "\" wasn't opened for writing",
+ NULL);
+ return TCL_ERROR;
+ } else if ((!forWriting) && ((chanMode & TCL_READABLE) == 0)) {
+ Tcl_AppendResult(interp, "\"", chanID, "\" wasn't opened for reading",
+ NULL);
+ return TCL_ERROR;
}
/*
@@ -2612,24 +3055,24 @@ Tcl_GetOpenFile(interp, string, forWriting, checkUsage, filePtr)
if ((chanTypePtr == &fileChannelType)
#ifdef SUPPORTS_TTY
|| (chanTypePtr == &ttyChannelType)
-#endif /* SUPPORTS_TTY */
+#endif /* SUPPORTS_TTY */
|| (chanTypePtr == &tcpChannelType)
|| (strcmp(chanTypePtr->typeName, "pipe") == 0)) {
- if (Tcl_GetChannelHandle(chan,
+ if (Tcl_GetChannelHandle(chan,
(forWriting ? TCL_WRITABLE : TCL_READABLE),
(ClientData*) &data) == TCL_OK) {
- fd = (int) data;
+ fd = PTR2INT(data);
/*
* The call to fdopen below is probably dangerous, since it will
- * truncate an existing file if the file is being opened
- * for writing....
+ * truncate an existing file if the file is being opened for
+ * writing....
*/
-
+
f = fdopen(fd, (forWriting ? "w" : "r"));
if (f == NULL) {
- Tcl_AppendResult(interp, "cannot get a FILE * for \"", string,
- "\"", (char *) NULL);
+ Tcl_AppendResult(interp, "cannot get a FILE * for \"", chanID,
+ "\"", NULL);
return TCL_ERROR;
}
*filePtr = (ClientData) f;
@@ -2637,28 +3080,29 @@ Tcl_GetOpenFile(interp, string, forWriting, checkUsage, filePtr)
}
}
- Tcl_AppendResult(interp, "\"", string,
- "\" cannot be used to get a FILE *", (char *) NULL);
- return TCL_ERROR;
+ Tcl_AppendResult(interp, "\"", chanID,
+ "\" cannot be used to get a FILE *", NULL);
+ return TCL_ERROR;
}
+#ifndef HAVE_COREFOUNDATION /* Darwin/Mac OS X CoreFoundation notifier is
+ * in tclMacOSXNotify.c */
/*
*----------------------------------------------------------------------
*
* TclUnixWaitForFile --
*
- * This procedure waits synchronously for a file to become readable
- * or writable, with an optional timeout.
+ * This function waits synchronously for a file to become readable or
+ * writable, with an optional timeout.
*
* Results:
* The return value is an OR'ed combination of TCL_READABLE,
- * TCL_WRITABLE, and TCL_EXCEPTION, indicating the conditions
- * that are present on file at the time of the return. This
- * procedure will not return until either "timeout" milliseconds
- * have elapsed or at least one of the conditions given by mask
- * has occurred for file (a return value of 0 means that a timeout
- * occurred). No normal events will be serviced during the
- * execution of this procedure.
+ * TCL_WRITABLE, and TCL_EXCEPTION, indicating the conditions that are
+ * present on file at the time of the return. This function will not
+ * return until either "timeout" milliseconds have elapsed or at least
+ * one of the conditions given by mask has occurred for file (a return
+ * value of 0 means that a timeout occurred). No normal events will be
+ * serviced during the execution of this function.
*
* Side effects:
* Time passes.
@@ -2667,32 +3111,42 @@ Tcl_GetOpenFile(interp, string, forWriting, checkUsage, filePtr)
*/
int
-TclUnixWaitForFile(fd, mask, timeout)
- int fd; /* Handle for file on which to wait. */
- int mask; /* What to wait for: OR'ed combination of
+TclUnixWaitForFile(
+ int fd, /* Handle for file on which to wait. */
+ int mask, /* What to wait for: OR'ed combination of
* TCL_READABLE, TCL_WRITABLE, and
* TCL_EXCEPTION. */
- int timeout; /* Maximum amount of time to wait for one
- * of the conditions in mask to occur, in
- * milliseconds. A value of 0 means don't
- * wait at all, and a value of -1 means
- * wait forever. */
+ int timeout) /* Maximum amount of time to wait for one of
+ * the conditions in mask to occur, in
+ * milliseconds. A value of 0 means don't wait
+ * at all, and a value of -1 means wait
+ * forever. */
{
- Tcl_Time abortTime, now;
+ Tcl_Time abortTime = {0, 0}, now; /* silence gcc 4 warning */
struct timeval blockTime, *timeoutPtr;
- int index, bit, numFound, result = 0;
- fd_mask readyMasks[3*MASK_SIZE];
- /* This array reflects the readable/writable
- * conditions that were found to exist by the
- * last call to select. */
+ int numFound, result = 0;
+ fd_set readableMask;
+ fd_set writableMask;
+ fd_set exceptionalMask;
+
+#ifndef _DARWIN_C_SOURCE
+ /*
+ * Sanity check fd.
+ */
+
+ if (fd >= FD_SETSIZE) {
+ Tcl_Panic("TclUnixWaitForFile can't handle file id %d", fd);
+ /* must never get here, or select masks overrun will occur below */
+ }
+#endif
/*
- * If there is a non-zero finite timeout, compute the time when
- * we give up.
+ * If there is a non-zero finite timeout, compute the time when we give
+ * up.
*/
if (timeout > 0) {
- TclpGetTime(&now);
+ Tcl_GetTime(&now);
abortTime.sec = now.sec + timeout/1000;
abortTime.usec = now.usec + (timeout%1000)*1000;
if (abortTime.usec >= 1000000) {
@@ -2709,19 +3163,16 @@ TclUnixWaitForFile(fd, mask, timeout)
}
/*
- * Initialize the ready masks and compute the mask offsets.
+ * Initialize the select masks.
*/
- if (fd >= FD_SETSIZE) {
- panic("TclWaitForFile can't handle file id %d", fd);
- }
- memset((VOID *) readyMasks, 0, 3*MASK_SIZE*sizeof(fd_mask));
- index = fd/(NBBY*sizeof(fd_mask));
- bit = 1 << (fd%(NBBY*sizeof(fd_mask)));
-
+ FD_ZERO(&readableMask);
+ FD_ZERO(&writableMask);
+ FD_ZERO(&exceptionalMask);
+
/*
- * Loop in a mini-event loop of our own, waiting for either the
- * file to become ready or a timeout to occur.
+ * Loop in a mini-event loop of our own, waiting for either the file to
+ * become ready or a timeout to occur.
*/
while (1) {
@@ -2737,37 +3188,36 @@ TclUnixWaitForFile(fd, mask, timeout)
blockTime.tv_usec = 0;
}
}
-
+
/*
- * Set the appropriate bit in the ready masks for the fd.
+ * Setup the select masks for the fd.
*/
- if (mask & TCL_READABLE) {
- readyMasks[index] |= bit;
+ if (mask & TCL_READABLE) {
+ FD_SET(fd, &readableMask);
}
- if (mask & TCL_WRITABLE) {
- (readyMasks+MASK_SIZE)[index] |= bit;
+ if (mask & TCL_WRITABLE) {
+ FD_SET(fd, &writableMask);
}
if (mask & TCL_EXCEPTION) {
- (readyMasks+2*(MASK_SIZE))[index] |= bit;
+ FD_SET(fd, &exceptionalMask);
}
/*
* Wait for the event or a timeout.
*/
- numFound = select(fd+1, (SELECT_MASK *) &readyMasks[0],
- (SELECT_MASK *) &readyMasks[MASK_SIZE],
- (SELECT_MASK *) &readyMasks[2*MASK_SIZE], timeoutPtr);
+ numFound = select(fd + 1, &readableMask, &writableMask,
+ &exceptionalMask, timeoutPtr);
if (numFound == 1) {
- if (readyMasks[index] & bit) {
- result |= TCL_READABLE;
+ if (FD_ISSET(fd, &readableMask)) {
+ SET_BITS(result, TCL_READABLE);
}
- if ((readyMasks+MASK_SIZE)[index] & bit) {
- result |= TCL_WRITABLE;
+ if (FD_ISSET(fd, &writableMask)) {
+ SET_BITS(result, TCL_WRITABLE);
}
- if ((readyMasks+2*(MASK_SIZE))[index] & bit) {
- result |= TCL_EXCEPTION;
+ if (FD_ISSET(fd, &exceptionalMask)) {
+ SET_BITS(result, TCL_EXCEPTION);
}
result &= mask;
if (result) {
@@ -2777,17 +3227,72 @@ TclUnixWaitForFile(fd, mask, timeout)
if (timeout == 0) {
break;
}
+ if (timeout < 0) {
+ continue;
+ }
/*
* The select returned early, so we need to recompute the timeout.
*/
- TclpGetTime(&now);
+ Tcl_GetTime(&now);
if ((abortTime.sec < now.sec)
- || ((abortTime.sec == now.sec)
- && (abortTime.usec <= now.usec))) {
+ || (abortTime.sec==now.sec && abortTime.usec<=now.usec)) {
break;
}
}
return result;
}
+#endif /* HAVE_COREFOUNDATION */
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * FileTruncateProc --
+ *
+ * Truncates a file to a given length.
+ *
+ * Results:
+ * 0 if the operation succeeded, and -1 if it failed (in which case
+ * *errorCodePtr will be set to errno).
+ *
+ * Side effects:
+ * The underlying file is potentially truncated. This can have a wide
+ * variety of side effects, including moving file pointers that point at
+ * places later in the file than the truncate point.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int
+FileTruncateProc(
+ ClientData instanceData,
+ Tcl_WideInt length)
+{
+ FileState *fsPtr = (FileState *) instanceData;
+ int result;
+
+#ifdef HAVE_TYPE_OFF64_T
+ /*
+ * We assume this goes with the type for now...
+ */
+
+ result = ftruncate64(fsPtr->fd, (off64_t) length);
+#else
+ result = ftruncate(fsPtr->fd, (off_t) length);
+#endif
+ if (result) {
+ return errno;
+ }
+ return 0;
+}
+
+/*
+ * Local Variables:
+ * mode: c
+ * c-basic-offset: 4
+ * fill-column: 78
+ * tab-width: 8
+ * indent-tabs-mode: nil
+ * End:
+ */