os/persistentdata/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/unix/tclUnixChan.c
author sl@SLION-WIN7.fritz.box
Fri, 15 Jun 2012 03:10:57 +0200
changeset 0 bde4ae8d615e
permissions -rw-r--r--
First public contribution.
     1 /* 
     2  * tclUnixChan.c
     3  *
     4  *	Common channel driver for Unix channels based on files, command
     5  *	pipes and TCP sockets.
     6  *
     7  * Copyright (c) 1995-1997 Sun Microsystems, Inc.
     8  * Copyright (c) 1998-1999 by Scriptics Corporation.
     9  * Portions Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiaries. All rights reserved.  
    10  *
    11  * See the file "license.terms" for information on usage and redistribution
    12  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
    13  *
    14  * RCS: @(#) $Id: tclUnixChan.c,v 1.42.2.10 2006/11/28 16:29:48 kennykb Exp $
    15  */
    16 
    17 #include "tclInt.h"	/* Internal definitions for Tcl. */
    18 #include "tclPort.h"	/* Portability features for Tcl. */
    19 #include "tclIO.h"	/* To get Channel type declaration. */
    20 
    21 /*
    22  * sys/ioctl.h has already been included by tclPort.h.	Including termios.h
    23  * or termio.h causes a bunch of warning messages because some duplicate
    24  * (but not contradictory) #defines exist in termios.h and/or termio.h
    25  */
    26 #undef NL0
    27 #undef NL1
    28 #undef CR0
    29 #undef CR1
    30 #undef CR2
    31 #undef CR3
    32 #undef TAB0
    33 #undef TAB1
    34 #undef TAB2
    35 #undef XTABS
    36 #undef BS0
    37 #undef BS1
    38 #undef FF0
    39 #undef FF1
    40 #undef ECHO
    41 #undef NOFLSH
    42 #undef TOSTOP
    43 #undef FLUSHO
    44 #undef PENDIN
    45 
    46 #define SUPPORTS_TTY
    47 
    48 #ifdef USE_TERMIOS
    49 #   include <termios.h>
    50 #   ifdef HAVE_SYS_IOCTL_H
    51 #	include <sys/ioctl.h>
    52 #   endif /* HAVE_SYS_IOCTL_H */
    53 #   ifdef HAVE_SYS_MODEM_H
    54 #	include <sys/modem.h>
    55 #   endif /* HAVE_SYS_MODEM_H */
    56 #   define IOSTATE			struct termios
    57 #   define GETIOSTATE(fd, statePtr)	tcgetattr((fd), (statePtr))
    58 #   define SETIOSTATE(fd, statePtr)	tcsetattr((fd), TCSADRAIN, (statePtr))
    59 #   define GETCONTROL(fd, intPtr)	ioctl((fd), TIOCMGET, (intPtr))
    60 #   define SETCONTROL(fd, intPtr)	ioctl((fd), TIOCMSET, (intPtr))
    61     /*
    62      * TIP #35 introduced a different on exit flush/close behavior that
    63      * doesn't work correctly with standard channels on all systems.
    64      * The problem is tcflush throws away waiting channel data.	 This may
    65      * be necessary for true serial channels that may block, but isn't
    66      * correct in the standard case.  This might be replaced with tcdrain
    67      * instead, but that can block.  For now, we revert to making this do
    68      * nothing, and TtyOutputProc being the same old FileOutputProc.
    69      * -- hobbs [Bug #525783]
    70      */
    71 #   define BAD_TIP35_FLUSH 0
    72 #   if BAD_TIP35_FLUSH
    73 #	define TTYFLUSH(fd)		tcflush((fd), TCIOFLUSH);
    74 #   else
    75 #	define TTYFLUSH(fd)
    76 #   endif /* BAD_TIP35_FLUSH */
    77 #   ifdef FIONREAD
    78 #	define GETREADQUEUE(fd, int)	ioctl((fd), FIONREAD, &(int))
    79 #   elif defined(FIORDCHK)
    80 #	define GETREADQUEUE(fd, int)	int = ioctl((fd), FIORDCHK, NULL)
    81 #   endif /* FIONREAD */
    82 #   ifdef TIOCOUTQ
    83 #	define GETWRITEQUEUE(fd, int)	ioctl((fd), TIOCOUTQ, &(int))
    84 #   endif /* TIOCOUTQ */
    85 #   if defined(TIOCSBRK) && defined(TIOCCBRK)
    86 /*
    87  * Can't use ?: operator below because that messes up types on either
    88  * Linux or Solaris (the two are mutually exclusive!)
    89  */
    90 #	define SETBREAK(fd, flag) \
    91 		if (flag) {				\
    92 		    ioctl((fd), TIOCSBRK, NULL);	\
    93 		} else {				\
    94 		    ioctl((fd), TIOCCBRK, NULL);	\
    95 		}
    96 #   endif /* TIOCSBRK&TIOCCBRK */
    97 #   if !defined(CRTSCTS) && defined(CNEW_RTSCTS)
    98 #	define CRTSCTS CNEW_RTSCTS
    99 #   endif /* !CRTSCTS&CNEW_RTSCTS */
   100 #else	/* !USE_TERMIOS */
   101 
   102 #ifdef USE_TERMIO
   103 #   include <termio.h>
   104 #   define IOSTATE			struct termio
   105 #   define GETIOSTATE(fd, statePtr)	ioctl((fd), TCGETA, (statePtr))
   106 #   define SETIOSTATE(fd, statePtr)	ioctl((fd), TCSETAW, (statePtr))
   107 #else	/* !USE_TERMIO */
   108 
   109 #ifdef USE_SGTTY
   110 #   include <sgtty.h>
   111 #   define IOSTATE			struct sgttyb
   112 #   define GETIOSTATE(fd, statePtr)	ioctl((fd), TIOCGETP, (statePtr))
   113 #   define SETIOSTATE(fd, statePtr)	ioctl((fd), TIOCSETP, (statePtr))
   114 #else	/* !USE_SGTTY */
   115 #   undef SUPPORTS_TTY
   116 #endif	/* !USE_SGTTY */
   117 
   118 #endif	/* !USE_TERMIO */
   119 #endif	/* !USE_TERMIOS */
   120 
   121 /*
   122  * This structure describes per-instance state of a file based channel.
   123  */
   124 
   125 typedef struct FileState {
   126     Tcl_Channel channel;	/* Channel associated with this file. */
   127     int fd;			/* File handle. */
   128     int validMask;		/* OR'ed combination of TCL_READABLE,
   129 				 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
   130 				 * which operations are valid on the file. */
   131 #ifdef DEPRECATED
   132     struct FileState *nextPtr;	/* Pointer to next file in list of all
   133 				 * file channels. */
   134 #endif /* DEPRECATED */
   135 } FileState;
   136 
   137 #ifdef SUPPORTS_TTY
   138 
   139 /*
   140  * The following structure describes per-instance state of a tty-based
   141  * channel.
   142  */
   143 
   144 typedef struct TtyState {
   145     FileState fs;		/* Per-instance state of the file
   146 				 * descriptor.	Must be the first field. */
   147     int stateUpdated;		/* Flag to say if the state has been
   148 				 * modified and needs resetting. */
   149     IOSTATE savedState;		/* Initial state of device.  Used to reset
   150 				 * state when device closed. */
   151 } TtyState;
   152 
   153 /*
   154  * The following structure is used to set or get the serial port
   155  * attributes in a platform-independant manner.
   156  */
   157 
   158 typedef struct TtyAttrs {
   159     int baud;
   160     int parity;
   161     int data;
   162     int stop;
   163 } TtyAttrs;
   164 
   165 #endif	/* !SUPPORTS_TTY */
   166 
   167 #define UNSUPPORTED_OPTION(detail) \
   168 	if (interp) {							\
   169 	    Tcl_AppendResult(interp, (detail),				\
   170 		    " not supported for this platform", (char *) NULL); \
   171 	}
   172 
   173 #ifdef DEPRECATED
   174 typedef struct ThreadSpecificData {
   175     /*
   176      * List of all file channels currently open.  This is per thread and is
   177      * used to match up fd's to channels, which rarely occurs.
   178      */
   179 
   180     FileState *firstFilePtr;
   181 } ThreadSpecificData;
   182 
   183 static Tcl_ThreadDataKey dataKey;
   184 #endif /* DEPRECATED */
   185 
   186 /*
   187  * This structure describes per-instance state of a tcp based channel.
   188  */
   189 
   190 typedef struct TcpState {
   191     Tcl_Channel channel;	/* Channel associated with this file. */
   192     int fd;			/* The socket itself. */
   193     int flags;			/* ORed combination of the bitfields
   194 				 * defined below. */
   195     Tcl_TcpAcceptProc *acceptProc;
   196 				/* Proc to call on accept. */
   197     ClientData acceptProcData;	/* The data for the accept proc. */
   198 } TcpState;
   199 
   200 /*
   201  * These bits may be ORed together into the "flags" field of a TcpState
   202  * structure.
   203  */
   204 
   205 #define TCP_ASYNC_SOCKET	(1<<0)	/* Asynchronous socket. */
   206 #define TCP_ASYNC_CONNECT	(1<<1)	/* Async connect in progress. */
   207 
   208 /*
   209  * The following defines the maximum length of the listen queue. This is
   210  * the number of outstanding yet-to-be-serviced requests for a connection
   211  * on a server socket, more than this number of outstanding requests and
   212  * the connection request will fail.
   213  */
   214 
   215 #ifndef SOMAXCONN
   216 #   define SOMAXCONN	100
   217 #endif /* SOMAXCONN */
   218 
   219 #if (SOMAXCONN < 100)
   220 #   undef  SOMAXCONN
   221 #   define SOMAXCONN	100
   222 #endif /* SOMAXCONN < 100 */
   223 
   224 /*
   225  * The following defines how much buffer space the kernel should maintain
   226  * for a socket.
   227  */
   228 
   229 #define SOCKET_BUFSIZE	4096
   230 
   231 /*
   232  * Static routines for this file:
   233  */
   234 
   235 static TcpState *	CreateSocket _ANSI_ARGS_((Tcl_Interp *interp,
   236 			    int port, CONST char *host, int server,
   237 			    CONST char *myaddr, int myport, int async));
   238 static int		CreateSocketAddress _ANSI_ARGS_(
   239 			    (struct sockaddr_in *sockaddrPtr,
   240 			    CONST char *host, int port));
   241 static int		FileBlockModeProc _ANSI_ARGS_((
   242 			    ClientData instanceData, int mode));
   243 static int		FileCloseProc _ANSI_ARGS_((ClientData instanceData,
   244 			    Tcl_Interp *interp));
   245 static int		FileGetHandleProc _ANSI_ARGS_((ClientData instanceData,
   246 			    int direction, ClientData *handlePtr));
   247 static int		FileInputProc _ANSI_ARGS_((ClientData instanceData,
   248 			    char *buf, int toRead, int *errorCode));
   249 static int		FileOutputProc _ANSI_ARGS_((
   250 			    ClientData instanceData, CONST char *buf,
   251 			    int toWrite, int *errorCode));
   252 static int		FileSeekProc _ANSI_ARGS_((ClientData instanceData,
   253 			    long offset, int mode, int *errorCode));
   254 #ifdef DEPRECATED
   255 static void             FileThreadActionProc _ANSI_ARGS_ ((
   256 			   ClientData instanceData, int action));
   257 #endif
   258 static Tcl_WideInt	FileWideSeekProc _ANSI_ARGS_((ClientData instanceData,
   259 			    Tcl_WideInt offset, int mode, int *errorCode));
   260 static void		FileWatchProc _ANSI_ARGS_((ClientData instanceData,
   261 			    int mask));
   262 static void		TcpAccept _ANSI_ARGS_((ClientData data, int mask));
   263 static int		TcpBlockModeProc _ANSI_ARGS_((ClientData data,
   264 			    int mode));
   265 static int		TcpCloseProc _ANSI_ARGS_((ClientData instanceData,
   266 			    Tcl_Interp *interp));
   267 static int		TcpGetHandleProc _ANSI_ARGS_((ClientData instanceData,
   268 			    int direction, ClientData *handlePtr));
   269 static int		TcpGetOptionProc _ANSI_ARGS_((ClientData instanceData,
   270 			    Tcl_Interp *interp, CONST char *optionName,
   271 			    Tcl_DString *dsPtr));
   272 static int		TcpInputProc _ANSI_ARGS_((ClientData instanceData,
   273 			    char *buf, int toRead,  int *errorCode));
   274 static int		TcpOutputProc _ANSI_ARGS_((ClientData instanceData,
   275 			    CONST char *buf, int toWrite, int *errorCode));
   276 static void		TcpWatchProc _ANSI_ARGS_((ClientData instanceData,
   277 			    int mask));
   278 #ifdef SUPPORTS_TTY
   279 static int		TtyCloseProc _ANSI_ARGS_((ClientData instanceData,
   280 			    Tcl_Interp *interp));
   281 static void		TtyGetAttributes _ANSI_ARGS_((int fd,
   282 			    TtyAttrs *ttyPtr));
   283 static int		TtyGetOptionProc _ANSI_ARGS_((ClientData instanceData,
   284 			    Tcl_Interp *interp, CONST char *optionName,
   285 			    Tcl_DString *dsPtr));
   286 static FileState *	TtyInit _ANSI_ARGS_((int fd, int initialize));
   287 #if BAD_TIP35_FLUSH
   288 static int		TtyOutputProc _ANSI_ARGS_((ClientData instanceData,
   289 			    CONST char *buf, int toWrite, int *errorCode));
   290 #endif /* BAD_TIP35_FLUSH */
   291 static int		TtyParseMode _ANSI_ARGS_((Tcl_Interp *interp,
   292 			    CONST char *mode, int *speedPtr, int *parityPtr,
   293 			    int *dataPtr, int *stopPtr));
   294 static void		TtySetAttributes _ANSI_ARGS_((int fd,
   295 			    TtyAttrs *ttyPtr));
   296 static int		TtySetOptionProc _ANSI_ARGS_((ClientData instanceData,
   297 			    Tcl_Interp *interp, CONST char *optionName, 
   298 			    CONST char *value));
   299 #endif	/* SUPPORTS_TTY */
   300 static int		WaitForConnect _ANSI_ARGS_((TcpState *statePtr,
   301 			    int *errorCodePtr));
   302 static Tcl_Channel	MakeTcpClientChannelMode _ANSI_ARGS_(
   303 			    (ClientData tcpSocket,
   304 			    int mode));
   305 
   306 
   307 /*
   308  * This structure describes the channel type structure for file based IO:
   309  */
   310 
   311 static Tcl_ChannelType fileChannelType = {
   312     "file",			/* Type name. */
   313     TCL_CHANNEL_VERSION_4,	/* v4 channel */
   314     FileCloseProc,		/* Close proc. */
   315     FileInputProc,		/* Input proc. */
   316     FileOutputProc,		/* Output proc. */
   317     FileSeekProc,		/* Seek proc. */
   318     NULL,			/* Set option proc. */
   319     NULL,			/* Get option proc. */
   320     FileWatchProc,		/* Initialize notifier. */
   321     FileGetHandleProc,		/* Get OS handles out of channel. */
   322     NULL,			/* close2proc. */
   323     FileBlockModeProc,		/* Set blocking or non-blocking mode.*/
   324     NULL,			/* flush proc. */
   325     NULL,			/* handler proc. */
   326     FileWideSeekProc,		/* wide seek proc. */
   327 #ifdef DEPRECATED
   328     FileThreadActionProc,       /* thread actions */
   329 #else
   330     NULL,
   331 #endif
   332 };
   333 
   334 #ifdef SUPPORTS_TTY
   335 /*
   336  * This structure describes the channel type structure for serial IO.
   337  * Note that this type is a subclass of the "file" type.
   338  */
   339 
   340 static Tcl_ChannelType ttyChannelType = {
   341     "tty",			/* Type name. */
   342     TCL_CHANNEL_VERSION_4,	/* v4 channel */
   343     TtyCloseProc,		/* Close proc. */
   344     FileInputProc,		/* Input proc. */
   345 #if BAD_TIP35_FLUSH
   346     TtyOutputProc,		/* Output proc. */
   347 #else /* !BAD_TIP35_FLUSH */
   348     FileOutputProc,		/* Output proc. */
   349 #endif /* BAD_TIP35_FLUSH */
   350     NULL,			/* Seek proc. */
   351     TtySetOptionProc,		/* Set option proc. */
   352     TtyGetOptionProc,		/* Get option proc. */
   353     FileWatchProc,		/* Initialize notifier. */
   354     FileGetHandleProc,		/* Get OS handles out of channel. */
   355     NULL,			/* close2proc. */
   356     FileBlockModeProc,		/* Set blocking or non-blocking mode.*/
   357     NULL,			/* flush proc. */
   358     NULL,			/* handler proc. */
   359     NULL,			/* wide seek proc. */
   360     NULL,			/* thread action proc. */
   361 };
   362 #endif	/* SUPPORTS_TTY */
   363 
   364 /*
   365  * This structure describes the channel type structure for TCP socket
   366  * based IO:
   367  */
   368 
   369 static Tcl_ChannelType tcpChannelType = {
   370     "tcp",			/* Type name. */
   371     TCL_CHANNEL_VERSION_4,	/* v4 channel */
   372     TcpCloseProc,		/* Close proc. */
   373     TcpInputProc,		/* Input proc. */
   374     TcpOutputProc,		/* Output proc. */
   375     NULL,			/* Seek proc. */
   376     NULL,			/* Set option proc. */
   377     TcpGetOptionProc,		/* Get option proc. */
   378     TcpWatchProc,		/* Initialize notifier. */
   379     TcpGetHandleProc,		/* Get OS handles out of channel. */
   380     NULL,			/* close2proc. */
   381     TcpBlockModeProc,		/* Set blocking or non-blocking mode.*/
   382     NULL,			/* flush proc. */
   383     NULL,			/* handler proc. */
   384     NULL,			/* wide seek proc. */
   385     NULL,			/* thread action proc. */
   386 };
   387 
   388 
   389 /*
   390  *----------------------------------------------------------------------
   391  *
   392  * FileBlockModeProc --
   393  *
   394  *	Helper procedure to set blocking and nonblocking modes on a
   395  *	file based channel. Invoked by generic IO level code.
   396  *
   397  * Results:
   398  *	0 if successful, errno when failed.
   399  *
   400  * Side effects:
   401  *	Sets the device into blocking or non-blocking mode.
   402  *
   403  *----------------------------------------------------------------------
   404  */
   405 
   406 	/* ARGSUSED */
   407 static int
   408 FileBlockModeProc(instanceData, mode)
   409     ClientData instanceData;		/* File state. */
   410     int mode;				/* The mode to set. Can be one of
   411 					 * TCL_MODE_BLOCKING or
   412 					 * TCL_MODE_NONBLOCKING. */
   413 {
   414     FileState *fsPtr = (FileState *) instanceData;
   415     int curStatus;
   416 
   417 #ifndef USE_FIONBIO
   418     curStatus = fcntl(fsPtr->fd, F_GETFL);
   419     if (mode == TCL_MODE_BLOCKING) {
   420 	curStatus &= (~(O_NONBLOCK));
   421     } else {
   422 	curStatus |= O_NONBLOCK;
   423     }
   424     if (fcntl(fsPtr->fd, F_SETFL, curStatus) < 0) {
   425 	return errno;
   426     }
   427     curStatus = fcntl(fsPtr->fd, F_GETFL);
   428 #else /* USE_FIONBIO */
   429     if (mode == TCL_MODE_BLOCKING) {
   430 	curStatus = 0;
   431     } else {
   432 	curStatus = 1;
   433     }
   434     if (ioctl(fsPtr->fd, (int) FIONBIO, &curStatus) < 0) {
   435 	return errno;
   436     }
   437 #endif /* !USE_FIONBIO */
   438     return 0;
   439 }
   440 
   441 /*
   442  *----------------------------------------------------------------------
   443  *
   444  * FileInputProc --
   445  *
   446  *	This procedure is invoked from the generic IO level to read
   447  *	input from a file based channel.
   448  *
   449  * Results:
   450  *	The number of bytes read is returned or -1 on error. An output
   451  *	argument contains a POSIX error code if an error occurs, or zero.
   452  *
   453  * Side effects:
   454  *	Reads input from the input device of the channel.
   455  *
   456  *----------------------------------------------------------------------
   457  */
   458 
   459 static int
   460 FileInputProc(instanceData, buf, toRead, errorCodePtr)
   461     ClientData instanceData;		/* File state. */
   462     char *buf;				/* Where to store data read. */
   463     int toRead;				/* How much space is available
   464 					 * in the buffer? */
   465     int *errorCodePtr;			/* Where to store error code. */
   466 {
   467     FileState *fsPtr = (FileState *) instanceData;
   468     int bytesRead;			/* How many bytes were actually
   469 					 * read from the input device? */
   470 
   471     *errorCodePtr = 0;
   472 
   473     /*
   474      * Assume there is always enough input available. This will block
   475      * appropriately, and read will unblock as soon as a short read is
   476      * possible, if the channel is in blocking mode. If the channel is
   477      * nonblocking, the read will never block.
   478      */
   479 
   480     bytesRead = read(fsPtr->fd, buf, (size_t) toRead);
   481     if (bytesRead > -1) {
   482 	return bytesRead;
   483     }
   484     *errorCodePtr = errno;
   485     return -1;
   486 }
   487 
   488 /*
   489  *----------------------------------------------------------------------
   490  *
   491  * FileOutputProc--
   492  *
   493  *	This procedure is invoked from the generic IO level to write
   494  *	output to a file channel.
   495  *
   496  * Results:
   497  *	The number of bytes written is returned or -1 on error. An
   498  *	output argument contains a POSIX error code if an error occurred,
   499  *	or zero.
   500  *
   501  * Side effects:
   502  *	Writes output on the output device of the channel.
   503  *
   504  *----------------------------------------------------------------------
   505  */
   506 
   507 static int
   508 FileOutputProc(instanceData, buf, toWrite, errorCodePtr)
   509     ClientData instanceData;		/* File state. */
   510     CONST char *buf;			/* The data buffer. */
   511     int toWrite;			/* How many bytes to write? */
   512     int *errorCodePtr;			/* Where to store error code. */
   513 {
   514     FileState *fsPtr = (FileState *) instanceData;
   515     int written;
   516 
   517     *errorCodePtr = 0;
   518 
   519     if (toWrite == 0) {
   520 	/*
   521 	 * SF Tcl Bug 465765.
   522 	 * Do not try to write nothing into a file. STREAM based
   523 	 * implementations will considers this as EOF (if there is a
   524 	 * pipe behind the file).
   525 	 */
   526 
   527 	return 0;
   528     }
   529     written = write(fsPtr->fd, buf, (size_t) toWrite);
   530     if (written > -1) {
   531 	return written;
   532     }
   533     *errorCodePtr = errno;
   534     return -1;
   535 }
   536 
   537 /*
   538  *----------------------------------------------------------------------
   539  *
   540  * FileCloseProc --
   541  *
   542  *	This procedure is called from the generic IO level to perform
   543  *	channel-type-specific cleanup when a file based channel is closed.
   544  *
   545  * Results:
   546  *	0 if successful, errno if failed.
   547  *
   548  * Side effects:
   549  *	Closes the device of the channel.
   550  *
   551  *----------------------------------------------------------------------
   552  */
   553 
   554 static int
   555 FileCloseProc(instanceData, interp)
   556     ClientData instanceData;	/* File state. */
   557     Tcl_Interp *interp;		/* For error reporting - unused. */
   558 {
   559     FileState *fsPtr = (FileState *) instanceData;
   560     int errorCode = 0;
   561 #ifdef DEPRECATED
   562     FileState **nextPtrPtr;
   563     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
   564 #endif /* DEPRECATED */
   565     Tcl_DeleteFileHandler(fsPtr->fd);
   566 
   567     /*
   568      * Do not close standard channels while in thread-exit.
   569      */
   570 
   571     if (!TclInThreadExit()
   572 	    || ((fsPtr->fd != 0) && (fsPtr->fd != 1) && (fsPtr->fd != 2))) {
   573 	if (close(fsPtr->fd) < 0) {
   574 	    errorCode = errno;
   575 	}
   576     }
   577     ckfree((char *) fsPtr);
   578     return errorCode;
   579 }
   580 
   581 /*
   582  *----------------------------------------------------------------------
   583  *
   584  * FileSeekProc --
   585  *
   586  *	This procedure is called by the generic IO level to move the
   587  *	access point in a file based channel.
   588  *
   589  * Results:
   590  *	-1 if failed, the new position if successful. An output
   591  *	argument contains the POSIX error code if an error occurred,
   592  *	or zero.
   593  *
   594  * Side effects:
   595  *	Moves the location at which the channel will be accessed in
   596  *	future operations.
   597  *
   598  *----------------------------------------------------------------------
   599  */
   600 
   601 static int
   602 FileSeekProc(instanceData, offset, mode, errorCodePtr)
   603     ClientData instanceData;	/* File state. */
   604     long offset;		/* Offset to seek to. */
   605     int mode;			/* Relative to where should we seek? Can be
   606 				 * one of SEEK_START, SEEK_SET or SEEK_END. */
   607     int *errorCodePtr;		/* To store error code. */
   608 {
   609     FileState *fsPtr = (FileState *) instanceData;
   610     Tcl_WideInt oldLoc, newLoc;
   611 
   612     /*
   613      * Save our current place in case we need to roll-back the seek.
   614      */
   615     oldLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) 0, SEEK_CUR);
   616     if (oldLoc == Tcl_LongAsWide(-1)) {
   617 	/*
   618 	 * Bad things are happening.  Error out...
   619 	 */
   620 	*errorCodePtr = errno;
   621 	return -1;
   622     }
   623  
   624     newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode);
   625  
   626     /*
   627      * Check for expressability in our return type, and roll-back otherwise.
   628      */
   629     if (newLoc > Tcl_LongAsWide(INT_MAX)) {
   630 	*errorCodePtr = EOVERFLOW;
   631 	TclOSseek(fsPtr->fd, (Tcl_SeekOffset) oldLoc, SEEK_SET);
   632 	return -1;
   633     } else {
   634 	*errorCodePtr = (newLoc == Tcl_LongAsWide(-1)) ? errno : 0;
   635     }
   636     return (int) Tcl_WideAsLong(newLoc);
   637 }
   638 
   639 /*
   640  *----------------------------------------------------------------------
   641  *
   642  * FileWideSeekProc --
   643  *
   644  *	This procedure is called by the generic IO level to move the
   645  *	access point in a file based channel, with offsets expressed
   646  *	as wide integers.
   647  *
   648  * Results:
   649  *	-1 if failed, the new position if successful. An output
   650  *	argument contains the POSIX error code if an error occurred,
   651  *	or zero.
   652  *
   653  * Side effects:
   654  *	Moves the location at which the channel will be accessed in
   655  *	future operations.
   656  *
   657  *----------------------------------------------------------------------
   658  */
   659 
   660 static Tcl_WideInt
   661 FileWideSeekProc(instanceData, offset, mode, errorCodePtr)
   662     ClientData instanceData;	/* File state. */
   663     Tcl_WideInt offset;		/* Offset to seek to. */
   664     int mode;			/* Relative to where should we seek? Can be
   665 				 * one of SEEK_START, SEEK_CUR or SEEK_END. */
   666     int *errorCodePtr;		/* To store error code. */
   667 {
   668     FileState *fsPtr = (FileState *) instanceData;
   669     Tcl_WideInt newLoc;
   670 
   671     newLoc = TclOSseek(fsPtr->fd, (Tcl_SeekOffset) offset, mode);
   672 
   673     *errorCodePtr = (newLoc == -1) ? errno : 0;
   674     return newLoc;
   675 }
   676 
   677 /*
   678  *----------------------------------------------------------------------
   679  *
   680  * FileWatchProc --
   681  *
   682  *	Initialize the notifier to watch the fd from this channel.
   683  *
   684  * Results:
   685  *	None.
   686  *
   687  * Side effects:
   688  *	Sets up the notifier so that a future event on the channel will
   689  *	be seen by Tcl.
   690  *
   691  *----------------------------------------------------------------------
   692  */
   693 
   694 static void
   695 FileWatchProc(instanceData, mask)
   696     ClientData instanceData;		/* The file state. */
   697     int mask;				/* Events of interest; an OR-ed
   698 					 * combination of TCL_READABLE,
   699 					 * TCL_WRITABLE and TCL_EXCEPTION. */
   700 {
   701     FileState *fsPtr = (FileState *) instanceData;
   702 
   703     /*
   704      * Make sure we only register for events that are valid on this file.
   705      * Note that we are passing Tcl_NotifyChannel directly to
   706      * Tcl_CreateFileHandler with the channel pointer as the client data.
   707      */
   708 
   709     mask &= fsPtr->validMask;
   710     if (mask) {
   711 	Tcl_CreateFileHandler(fsPtr->fd, mask,
   712 		(Tcl_FileProc *) Tcl_NotifyChannel,
   713 		(ClientData) fsPtr->channel);
   714     } else {
   715 	Tcl_DeleteFileHandler(fsPtr->fd);
   716     }
   717 }
   718 
   719 /*
   720  *----------------------------------------------------------------------
   721  *
   722  * FileGetHandleProc --
   723  *
   724  *	Called from Tcl_GetChannelHandle to retrieve OS handles from
   725  *	a file based channel.
   726  *
   727  * Results:
   728  *	Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
   729  *	there is no handle for the specified direction. 
   730  *
   731  * Side effects:
   732  *	None.
   733  *
   734  *----------------------------------------------------------------------
   735  */
   736 
   737 static int
   738 FileGetHandleProc(instanceData, direction, handlePtr)
   739     ClientData instanceData;	/* The file state. */
   740     int direction;		/* TCL_READABLE or TCL_WRITABLE */
   741     ClientData *handlePtr;	/* Where to store the handle.  */
   742 {
   743     FileState *fsPtr = (FileState *) instanceData;
   744 
   745     if (direction & fsPtr->validMask) {
   746 	*handlePtr = (ClientData) fsPtr->fd;
   747 	return TCL_OK;
   748     } else {
   749 	return TCL_ERROR;
   750     }
   751 }
   752 
   753 #ifdef SUPPORTS_TTY 
   754 
   755 /*
   756  *----------------------------------------------------------------------
   757  *
   758  * TtyCloseProc --
   759  *
   760  *	This procedure is called from the generic IO level to perform
   761  *	channel-type-specific cleanup when a tty based channel is closed.
   762  *
   763  * Results:
   764  *	0 if successful, errno if failed.
   765  *
   766  * Side effects:
   767  *	Closes the device of the channel.
   768  *
   769  *----------------------------------------------------------------------
   770  */
   771 static int
   772 TtyCloseProc(instanceData, interp)
   773     ClientData instanceData;	/* Tty state. */
   774     Tcl_Interp *interp;		/* For error reporting - unused. */
   775 {
   776 #if BAD_TIP35_FLUSH
   777     TtyState *ttyPtr = (TtyState *) instanceData;
   778 #endif /* BAD_TIP35_FLUSH */
   779 #ifdef TTYFLUSH
   780     TTYFLUSH(ttyPtr->fs.fd);
   781 #endif /* TTYFLUSH */
   782 #if 0
   783     /*
   784      * TIP#35 agreed to remove the unsave so that TCL could be used as a 
   785      * simple stty. 
   786      * It would be cleaner to remove all the stuff related to 
   787      *	  TtyState.stateUpdated
   788      *	  TtyState.savedState
   789      * Then the structure TtyState would be the same as FileState.
   790      * IMO this cleanup could better be done for the final 8.4 release
   791      * after nobody complained about the missing unsave. -- schroedter
   792      */
   793     if (ttyPtr->stateUpdated) {
   794 	SETIOSTATE(ttyPtr->fs.fd, &ttyPtr->savedState);
   795     }
   796 #endif
   797     return FileCloseProc(instanceData, interp);
   798 }
   799 
   800 /*
   801  *----------------------------------------------------------------------
   802  *
   803  * TtyOutputProc--
   804  *
   805  *	This procedure is invoked from the generic IO level to write
   806  *	output to a TTY channel.
   807  *
   808  * Results:
   809  *	The number of bytes written is returned or -1 on error. An
   810  *	output argument contains a POSIX error code if an error occurred,
   811  *	or zero.
   812  *
   813  * Side effects:
   814  *	Writes output on the output device of the channel
   815  *	if the channel is not designated to be closed.
   816  *
   817  *----------------------------------------------------------------------
   818  */
   819 
   820 #if BAD_TIP35_FLUSH
   821 static int
   822 TtyOutputProc(instanceData, buf, toWrite, errorCodePtr)
   823     ClientData instanceData;		/* File state. */
   824     CONST char *buf;			/* The data buffer. */
   825     int toWrite;			/* How many bytes to write? */
   826     int *errorCodePtr;			/* Where to store error code. */
   827 {
   828     if (TclInExit()) {
   829 	/*
   830 	 * Do not write data during Tcl exit.
   831 	 * Serial port may block preventing Tcl from exit.
   832 	 */
   833 	return toWrite;
   834     } else {
   835 	return FileOutputProc(instanceData, buf, toWrite, errorCodePtr);
   836     }
   837 }
   838 #endif /* BAD_TIP35_FLUSH */
   839 
   840 #ifdef USE_TERMIOS
   841 /*
   842  *----------------------------------------------------------------------
   843  *
   844  * TtyModemStatusStr --
   845  *
   846  *  Converts a RS232 modem status list of readable flags
   847  *
   848  *----------------------------------------------------------------------
   849  */
   850 static void
   851 TtyModemStatusStr(status, dsPtr)
   852     int status;		   /* RS232 modem status */
   853     Tcl_DString *dsPtr;	   /* Where to store string */
   854 {
   855 #ifdef TIOCM_CTS
   856     Tcl_DStringAppendElement(dsPtr, "CTS");
   857     Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CTS) ? "1" : "0");
   858 #endif /* TIOCM_CTS */
   859 #ifdef TIOCM_DSR
   860     Tcl_DStringAppendElement(dsPtr, "DSR");
   861     Tcl_DStringAppendElement(dsPtr, (status & TIOCM_DSR) ? "1" : "0");
   862 #endif /* TIOCM_DSR */
   863 #ifdef TIOCM_RNG
   864     Tcl_DStringAppendElement(dsPtr, "RING");
   865     Tcl_DStringAppendElement(dsPtr, (status & TIOCM_RNG) ? "1" : "0");
   866 #endif /* TIOCM_RNG */
   867 #ifdef TIOCM_CD
   868     Tcl_DStringAppendElement(dsPtr, "DCD");
   869     Tcl_DStringAppendElement(dsPtr, (status & TIOCM_CD) ? "1" : "0");
   870 #endif /* TIOCM_CD */
   871 }
   872 #endif /* USE_TERMIOS */
   873 
   874 /*
   875  *----------------------------------------------------------------------
   876  *
   877  * TtySetOptionProc --
   878  *
   879  *	Sets an option on a channel.
   880  *
   881  * Results:
   882  *	A standard Tcl result. Also sets the interp's result on error if
   883  *	interp is not NULL.
   884  *
   885  * Side effects:
   886  *	May modify an option on a device.
   887  *	Sets Error message if needed (by calling Tcl_BadChannelOption).
   888  *
   889  *----------------------------------------------------------------------
   890  */
   891 
   892 static int		
   893 TtySetOptionProc(instanceData, interp, optionName, value)
   894     ClientData instanceData;	/* File state. */
   895     Tcl_Interp *interp;		/* For error reporting - can be NULL. */
   896     CONST char *optionName;	/* Which option to set? */
   897     CONST char *value;		/* New value for option. */
   898 {
   899     FileState *fsPtr = (FileState *) instanceData;
   900     unsigned int len, vlen;
   901     TtyAttrs tty;
   902 #ifdef USE_TERMIOS
   903     int flag, control, argc;
   904     CONST char **argv;
   905     IOSTATE iostate;
   906 #endif /* USE_TERMIOS */
   907 
   908     len = strlen(optionName);
   909     vlen = strlen(value);
   910 
   911     /*
   912      * Option -mode baud,parity,databits,stopbits
   913      */
   914     if ((len > 2) && (strncmp(optionName, "-mode", len) == 0)) {
   915 	if (TtyParseMode(interp, value, &tty.baud, &tty.parity, &tty.data,
   916 		&tty.stop) != TCL_OK) {
   917 	    return TCL_ERROR;
   918 	}
   919 	/*
   920 	 * system calls results should be checked there. -- dl
   921 	 */
   922 
   923 	TtySetAttributes(fsPtr->fd, &tty);
   924 	((TtyState *) fsPtr)->stateUpdated = 1;
   925 	return TCL_OK;
   926     }
   927 
   928 #ifdef USE_TERMIOS
   929 
   930     /*
   931      * Option -handshake none|xonxoff|rtscts|dtrdsr
   932      */
   933     if ((len > 1) && (strncmp(optionName, "-handshake", len) == 0)) {
   934 	/*
   935 	 * Reset all handshake options
   936 	 * DTR and RTS are ON by default
   937 	 */
   938 	GETIOSTATE(fsPtr->fd, &iostate);
   939 	iostate.c_iflag &= ~(IXON | IXOFF | IXANY);
   940 #ifdef CRTSCTS
   941 	iostate.c_cflag &= ~CRTSCTS;
   942 #endif /* CRTSCTS */
   943 	if (strncasecmp(value, "NONE", vlen) == 0) {
   944 	    /* leave all handshake options disabled */
   945 	} else if (strncasecmp(value, "XONXOFF", vlen) == 0) {
   946 	    iostate.c_iflag |= (IXON | IXOFF | IXANY);
   947 	} else if (strncasecmp(value, "RTSCTS", vlen) == 0) {
   948 #ifdef CRTSCTS
   949 	    iostate.c_cflag |= CRTSCTS;
   950 #else /* !CRTSTS */
   951 	    UNSUPPORTED_OPTION("-handshake RTSCTS");
   952 	    return TCL_ERROR;
   953 #endif /* CRTSCTS */
   954 	} else if (strncasecmp(value, "DTRDSR", vlen) == 0) {
   955 	    UNSUPPORTED_OPTION("-handshake DTRDSR");
   956 	    return TCL_ERROR;
   957 	} else {
   958 	    if (interp) {
   959 		Tcl_AppendResult(interp, "bad value for -handshake: ",
   960 			"must be one of xonxoff, rtscts, dtrdsr or none",
   961 			(char *) NULL);
   962 	    }
   963 	    return TCL_ERROR;
   964 	}
   965 	SETIOSTATE(fsPtr->fd, &iostate);
   966 	return TCL_OK;
   967     }
   968 
   969     /*
   970      * Option -xchar {\x11 \x13}
   971      */
   972     if ((len > 1) && (strncmp(optionName, "-xchar", len) == 0)) {
   973 	GETIOSTATE(fsPtr->fd, &iostate);
   974 	if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
   975 	    return TCL_ERROR;
   976 	}
   977 	if (argc == 2) {
   978 	    iostate.c_cc[VSTART] = argv[0][0];
   979 	    iostate.c_cc[VSTOP]	 = argv[1][0];
   980 	} else {
   981 	    if (interp) {
   982 		Tcl_AppendResult(interp,
   983 		    "bad value for -xchar: should be a list of two elements",
   984 		    (char *) NULL);
   985 	    }
   986 	    ckfree((char *) argv);
   987 	    return TCL_ERROR;
   988 	}
   989 	SETIOSTATE(fsPtr->fd, &iostate);
   990 	ckfree((char *) argv);
   991 	return TCL_OK;
   992     }
   993 
   994     /*
   995      * Option -timeout msec
   996      */
   997     if ((len > 2) && (strncmp(optionName, "-timeout", len) == 0)) {
   998 	int msec;
   999 
  1000 	GETIOSTATE(fsPtr->fd, &iostate);
  1001 	if (Tcl_GetInt(interp, value, &msec) != TCL_OK) {
  1002 	    return TCL_ERROR;
  1003 	}
  1004 	iostate.c_cc[VMIN]  = 0;
  1005 	iostate.c_cc[VTIME] = (msec == 0) ? 0 : (msec < 100) ? 1 : (msec+50)/100;
  1006 	SETIOSTATE(fsPtr->fd, &iostate);
  1007 	return TCL_OK;
  1008     }
  1009 
  1010     /*
  1011      * Option -ttycontrol {DTR 1 RTS 0 BREAK 0}
  1012      */
  1013     if ((len > 4) && (strncmp(optionName, "-ttycontrol", len) == 0)) {
  1014 	int i;
  1015 	if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
  1016 	    return TCL_ERROR;
  1017 	}
  1018 	if ((argc % 2) == 1) {
  1019 	    if (interp) {
  1020 		Tcl_AppendResult(interp,
  1021 			"bad value for -ttycontrol: should be a list of",
  1022 			"signal,value pairs", (char *) NULL);
  1023 	    }
  1024 	    ckfree((char *) argv);
  1025 	    return TCL_ERROR;
  1026 	}
  1027 
  1028 	GETCONTROL(fsPtr->fd, &control);
  1029 	for (i = 0; i < argc-1; i += 2) {
  1030 	    if (Tcl_GetBoolean(interp, argv[i+1], &flag) == TCL_ERROR) {
  1031 		ckfree((char *) argv);
  1032 		return TCL_ERROR;
  1033 	    }
  1034 	    if (strncasecmp(argv[i], "DTR", strlen(argv[i])) == 0) {
  1035 #ifdef TIOCM_DTR
  1036 		if (flag) {
  1037 		    control |= TIOCM_DTR;
  1038 		} else {
  1039 		    control &= ~TIOCM_DTR;
  1040 		}
  1041 #else /* !TIOCM_DTR */
  1042 		UNSUPPORTED_OPTION("-ttycontrol DTR");
  1043 		ckfree((char *) argv);
  1044 		return TCL_ERROR;
  1045 #endif /* TIOCM_DTR */
  1046 	    } else if (strncasecmp(argv[i], "RTS", strlen(argv[i])) == 0) {
  1047 #ifdef TIOCM_RTS
  1048 		if (flag) {
  1049 		    control |= TIOCM_RTS;
  1050 		} else {
  1051 		    control &= ~TIOCM_RTS;
  1052 		}
  1053 #else /* !TIOCM_RTS*/
  1054 		UNSUPPORTED_OPTION("-ttycontrol RTS");
  1055 		ckfree((char *) argv);
  1056 		return TCL_ERROR;
  1057 #endif /* TIOCM_RTS*/
  1058 	    } else if (strncasecmp(argv[i], "BREAK", strlen(argv[i])) == 0) {
  1059 #ifdef SETBREAK
  1060 		SETBREAK(fsPtr->fd, flag);
  1061 #else /* !SETBREAK */
  1062 		UNSUPPORTED_OPTION("-ttycontrol BREAK");
  1063 		ckfree((char *) argv);
  1064 		return TCL_ERROR;
  1065 #endif /* SETBREAK */
  1066 	    } else {
  1067 		if (interp) {
  1068 		    Tcl_AppendResult(interp, "bad signal \"", argv[i],
  1069 			    "\" for -ttycontrol: must be ",
  1070 			    "DTR, RTS or BREAK", (char *) NULL);
  1071 		}
  1072 		ckfree((char *) argv);
  1073 		return TCL_ERROR;
  1074 	    }
  1075 	} /* -ttycontrol options loop */
  1076 
  1077 	SETCONTROL(fsPtr->fd, &control);
  1078 	ckfree((char *) argv);
  1079 	return TCL_OK;
  1080     }
  1081 
  1082     return Tcl_BadChannelOption(interp, optionName,
  1083 	    "mode handshake timeout ttycontrol xchar ");
  1084 
  1085 #else /* !USE_TERMIOS */
  1086     return Tcl_BadChannelOption(interp, optionName, "mode");
  1087 #endif /* USE_TERMIOS */
  1088 }
  1089 
  1090 /*
  1091  *----------------------------------------------------------------------
  1092  *
  1093  * TtyGetOptionProc --
  1094  *
  1095  *	Gets a mode associated with an IO channel. If the optionName arg
  1096  *	is non NULL, retrieves the value of that option. If the optionName
  1097  *	arg is NULL, retrieves a list of alternating option names and
  1098  *	values for the given channel.
  1099  *
  1100  * Results:
  1101  *	A standard Tcl result. Also sets the supplied DString to the
  1102  *	string value of the option(s) returned.
  1103  *
  1104  * Side effects:
  1105  *	The string returned by this function is in static storage and
  1106  *	may be reused at any time subsequent to the call.
  1107  *	Sets Error message if needed (by calling Tcl_BadChannelOption).
  1108  *
  1109  *----------------------------------------------------------------------
  1110  */
  1111 
  1112 static int		
  1113 TtyGetOptionProc(instanceData, interp, optionName, dsPtr)
  1114     ClientData instanceData;	/* File state. */
  1115     Tcl_Interp *interp;		/* For error reporting - can be NULL. */
  1116     CONST char *optionName;	/* Option to get. */
  1117     Tcl_DString *dsPtr;		/* Where to store value(s). */
  1118 {
  1119     FileState *fsPtr = (FileState *) instanceData;
  1120     unsigned int len;
  1121     char buf[3 * TCL_INTEGER_SPACE + 16];
  1122     TtyAttrs tty;
  1123     int valid = 0;  /* flag if valid option parsed */
  1124 
  1125     if (optionName == NULL) {
  1126 	len = 0;
  1127     } else {
  1128 	len = strlen(optionName);
  1129     }
  1130     if (len == 0) {
  1131 	Tcl_DStringAppendElement(dsPtr, "-mode");
  1132     }
  1133     if (len==0 || (len>2 && strncmp(optionName, "-mode", len)==0)) {
  1134 	valid = 1;
  1135 	TtyGetAttributes(fsPtr->fd, &tty);
  1136 	sprintf(buf, "%d,%c,%d,%d", tty.baud, tty.parity, tty.data, tty.stop);
  1137 	Tcl_DStringAppendElement(dsPtr, buf);
  1138     }
  1139 
  1140 #ifdef USE_TERMIOS
  1141     /*
  1142      * get option -xchar
  1143      */
  1144     if (len == 0) {
  1145 	Tcl_DStringAppendElement(dsPtr, "-xchar");
  1146 	Tcl_DStringStartSublist(dsPtr);
  1147     }
  1148     if (len==0 || (len>1 && strncmp(optionName, "-xchar", len)==0)) {
  1149 	IOSTATE iostate;
  1150 	valid = 1;
  1151 
  1152 	GETIOSTATE(fsPtr->fd, &iostate);
  1153 	sprintf(buf, "%c", iostate.c_cc[VSTART]);
  1154 	Tcl_DStringAppendElement(dsPtr, buf);
  1155 	sprintf(buf, "%c", iostate.c_cc[VSTOP]);
  1156 	Tcl_DStringAppendElement(dsPtr, buf);
  1157     }
  1158     if (len == 0) {
  1159 	Tcl_DStringEndSublist(dsPtr);
  1160     }
  1161 
  1162     /*
  1163      * get option -queue
  1164      * option is readonly and returned by [fconfigure chan -queue]
  1165      * but not returned by unnamed [fconfigure chan]
  1166      */
  1167     if ((len > 1) && (strncmp(optionName, "-queue", len) == 0)) {
  1168 	int inQueue=0, outQueue=0;
  1169 	int inBuffered, outBuffered;
  1170 	valid = 1;
  1171 #ifdef GETREADQUEUE
  1172 	GETREADQUEUE(fsPtr->fd, inQueue);
  1173 #endif /* GETREADQUEUE */
  1174 #ifdef GETWRITEQUEUE
  1175 	GETWRITEQUEUE(fsPtr->fd, outQueue);
  1176 #endif /* GETWRITEQUEUE */
  1177 	inBuffered  = Tcl_InputBuffered(fsPtr->channel);
  1178 	outBuffered = Tcl_OutputBuffered(fsPtr->channel);
  1179 
  1180 	sprintf(buf, "%d", inBuffered+inQueue);
  1181 	Tcl_DStringAppendElement(dsPtr, buf);
  1182 	sprintf(buf, "%d", outBuffered+outQueue);
  1183 	Tcl_DStringAppendElement(dsPtr, buf);
  1184     }
  1185 
  1186     /*
  1187      * get option -ttystatus
  1188      * option is readonly and returned by [fconfigure chan -ttystatus]
  1189      * but not returned by unnamed [fconfigure chan]
  1190      */
  1191     if ((len > 4) && (strncmp(optionName, "-ttystatus", len) == 0)) {
  1192 	int status;
  1193 	valid = 1;
  1194 	GETCONTROL(fsPtr->fd, &status);
  1195 	TtyModemStatusStr(status, dsPtr);
  1196     }
  1197 #endif /* USE_TERMIOS */
  1198 
  1199     if (valid) {
  1200 	return TCL_OK;
  1201     } else {
  1202 	return Tcl_BadChannelOption(interp, optionName,
  1203 #ifdef USE_TERMIOS
  1204 	    "mode queue ttystatus xchar");
  1205 #else /* !USE_TERMIOS */
  1206 	    "mode");
  1207 #endif /* USE_TERMIOS */
  1208     }
  1209 }
  1210 
  1211 #undef DIRECT_BAUD
  1212 #ifdef B4800
  1213 #   if (B4800 == 4800)
  1214 #	define DIRECT_BAUD
  1215 #   endif /* B4800 == 4800 */
  1216 #endif /* B4800 */
  1217 
  1218 #ifdef DIRECT_BAUD
  1219 #   define TtyGetSpeed(baud)   ((unsigned) (baud))
  1220 #   define TtyGetBaud(speed)   ((int) (speed))
  1221 #else /* !DIRECT_BAUD */
  1222 
  1223 static struct {int baud; unsigned long speed;} speeds[] = {
  1224 #ifdef B0
  1225     {0, B0},
  1226 #endif
  1227 #ifdef B50
  1228     {50, B50},
  1229 #endif
  1230 #ifdef B75
  1231     {75, B75},
  1232 #endif
  1233 #ifdef B110
  1234     {110, B110},
  1235 #endif
  1236 #ifdef B134
  1237     {134, B134},
  1238 #endif
  1239 #ifdef B150
  1240     {150, B150},
  1241 #endif
  1242 #ifdef B200
  1243     {200, B200},
  1244 #endif
  1245 #ifdef B300
  1246     {300, B300},
  1247 #endif
  1248 #ifdef B600
  1249     {600, B600},
  1250 #endif
  1251 #ifdef B1200
  1252     {1200, B1200},
  1253 #endif
  1254 #ifdef B1800
  1255     {1800, B1800},
  1256 #endif
  1257 #ifdef B2400
  1258     {2400, B2400},
  1259 #endif
  1260 #ifdef B4800
  1261     {4800, B4800},
  1262 #endif
  1263 #ifdef B9600
  1264     {9600, B9600},
  1265 #endif
  1266 #ifdef B14400
  1267     {14400, B14400},
  1268 #endif
  1269 #ifdef B19200
  1270     {19200, B19200},
  1271 #endif
  1272 #ifdef EXTA
  1273     {19200, EXTA},
  1274 #endif
  1275 #ifdef B28800
  1276     {28800, B28800},
  1277 #endif
  1278 #ifdef B38400
  1279     {38400, B38400},
  1280 #endif
  1281 #ifdef EXTB
  1282     {38400, EXTB},
  1283 #endif
  1284 #ifdef B57600
  1285     {57600, B57600},
  1286 #endif
  1287 #ifdef _B57600
  1288     {57600, _B57600},
  1289 #endif
  1290 #ifdef B76800
  1291     {76800, B76800},
  1292 #endif
  1293 #ifdef B115200
  1294     {115200, B115200},
  1295 #endif
  1296 #ifdef _B115200
  1297     {115200, _B115200},
  1298 #endif
  1299 #ifdef B153600
  1300     {153600, B153600},
  1301 #endif
  1302 #ifdef B230400
  1303     {230400, B230400},
  1304 #endif
  1305 #ifdef B307200
  1306     {307200, B307200},
  1307 #endif
  1308 #ifdef B460800
  1309     {460800, B460800},
  1310 #endif
  1311     {-1, 0}
  1312 };
  1313 
  1314 /*
  1315  *---------------------------------------------------------------------------
  1316  *
  1317  * TtyGetSpeed --
  1318  *
  1319  *	Given a baud rate, get the mask value that should be stored in
  1320  *	the termios, termio, or sgttyb structure in order to select that
  1321  *	baud rate.
  1322  *
  1323  * Results:
  1324  *	As above.
  1325  *
  1326  * Side effects:
  1327  *	None.
  1328  *
  1329  *---------------------------------------------------------------------------
  1330  */
  1331 
  1332 static unsigned long
  1333 TtyGetSpeed(baud)
  1334     int baud;			/* The baud rate to look up. */
  1335 {
  1336     int bestIdx, bestDiff, i, diff;
  1337 
  1338     bestIdx = 0;
  1339     bestDiff = 1000000;
  1340 
  1341     /*
  1342      * If the baud rate does not correspond to one of the known mask values,
  1343      * choose the mask value whose baud rate is closest to the specified
  1344      * baud rate.
  1345      */
  1346 
  1347     for (i = 0; speeds[i].baud >= 0; i++) {
  1348 	diff = speeds[i].baud - baud;
  1349 	if (diff < 0) {
  1350 	    diff = -diff;
  1351 	}
  1352 	if (diff < bestDiff) {
  1353 	    bestIdx = i;
  1354 	    bestDiff = diff;
  1355 	}
  1356     }
  1357     return speeds[bestIdx].speed;
  1358 }
  1359 
  1360 /*
  1361  *---------------------------------------------------------------------------
  1362  *
  1363  * TtyGetBaud --
  1364  *
  1365  *	Given a speed mask value from a termios, termio, or sgttyb
  1366  *	structure, get the baus rate that corresponds to that mask value.
  1367  *
  1368  * Results:
  1369  *	As above.  If the mask value was not recognized, 0 is returned.
  1370  *
  1371  * Side effects:
  1372  *	None.
  1373  *
  1374  *---------------------------------------------------------------------------
  1375  */
  1376 
  1377 static int
  1378 TtyGetBaud(speed)
  1379     unsigned long speed;	/* Speed mask value to look up. */
  1380 {
  1381     int i;
  1382 
  1383     for (i = 0; speeds[i].baud >= 0; i++) {
  1384 	if (speeds[i].speed == speed) {
  1385 	    return speeds[i].baud;
  1386 	}
  1387     }
  1388     return 0;
  1389 }
  1390 
  1391 #endif /* !DIRECT_BAUD */
  1392 
  1393 
  1394 /*
  1395  *---------------------------------------------------------------------------
  1396  *
  1397  * TtyGetAttributes --
  1398  *
  1399  *	Get the current attributes of the specified serial device.
  1400  *
  1401  * Results:
  1402  *	None.
  1403  *
  1404  * Side effects:
  1405  *	None.
  1406  *
  1407  *---------------------------------------------------------------------------
  1408  */
  1409 
  1410 static void
  1411 TtyGetAttributes(fd, ttyPtr)
  1412     int fd;			/* Open file descriptor for serial port to
  1413 				 * be queried. */
  1414     TtyAttrs *ttyPtr;		/* Buffer filled with serial port
  1415 				 * attributes. */
  1416 {
  1417     IOSTATE iostate;
  1418     int baud, parity, data, stop;
  1419 
  1420     GETIOSTATE(fd, &iostate);
  1421 
  1422 #ifdef USE_TERMIOS
  1423     baud = TtyGetBaud(cfgetospeed(&iostate));
  1424 
  1425     parity = 'n';
  1426 #ifdef PAREXT
  1427     switch ((int) (iostate.c_cflag & (PARENB | PARODD | PAREXT))) {
  1428 	case PARENB		      : parity = 'e'; break;
  1429 	case PARENB | PARODD	      : parity = 'o'; break;
  1430 	case PARENB |	       PAREXT : parity = 's'; break;
  1431 	case PARENB | PARODD | PAREXT : parity = 'm'; break;
  1432     }
  1433 #else /* !PAREXT */
  1434     switch ((int) (iostate.c_cflag & (PARENB | PARODD))) {
  1435 	case PARENB		      : parity = 'e'; break;
  1436 	case PARENB | PARODD	      : parity = 'o'; break;
  1437     }
  1438 #endif /* !PAREXT */
  1439 
  1440     data = iostate.c_cflag & CSIZE;
  1441     data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8;
  1442 
  1443     stop = (iostate.c_cflag & CSTOPB) ? 2 : 1;
  1444 #endif /* USE_TERMIOS */
  1445 
  1446 #ifdef USE_TERMIO
  1447     baud = TtyGetBaud(iostate.c_cflag & CBAUD);
  1448 
  1449     parity = 'n';
  1450     switch (iostate.c_cflag & (PARENB | PARODD | PAREXT)) {
  1451 	case PARENB		      : parity = 'e'; break;
  1452 	case PARENB | PARODD	      : parity = 'o'; break;
  1453 	case PARENB |	       PAREXT : parity = 's'; break;
  1454 	case PARENB | PARODD | PAREXT : parity = 'm'; break;
  1455     }
  1456 
  1457     data = iostate.c_cflag & CSIZE;
  1458     data = (data == CS5) ? 5 : (data == CS6) ? 6 : (data == CS7) ? 7 : 8;
  1459 
  1460     stop = (iostate.c_cflag & CSTOPB) ? 2 : 1;
  1461 #endif /* USE_TERMIO */
  1462 
  1463 #ifdef USE_SGTTY
  1464     baud = TtyGetBaud(iostate.sg_ospeed);
  1465 
  1466     parity = 'n';
  1467     if (iostate.sg_flags & EVENP) {
  1468 	parity = 'e';
  1469     } else if (iostate.sg_flags & ODDP) {
  1470 	parity = 'o';
  1471     }
  1472 
  1473     data = (iostate.sg_flags & (EVENP | ODDP)) ? 7 : 8;
  1474 
  1475     stop = 1;
  1476 #endif /* USE_SGTTY */
  1477 
  1478     ttyPtr->baud    = baud;
  1479     ttyPtr->parity  = parity;
  1480     ttyPtr->data    = data;
  1481     ttyPtr->stop    = stop;
  1482 }
  1483 
  1484 /*
  1485  *---------------------------------------------------------------------------
  1486  *
  1487  * TtySetAttributes --
  1488  *
  1489  *	Set the current attributes of the specified serial device. 
  1490  *
  1491  * Results:
  1492  *	None.
  1493  *
  1494  * Side effects:
  1495  *	None.
  1496  *
  1497  *---------------------------------------------------------------------------
  1498  */
  1499 
  1500 static void
  1501 TtySetAttributes(fd, ttyPtr)
  1502     int fd;			/* Open file descriptor for serial port to
  1503 				 * be modified. */
  1504     TtyAttrs *ttyPtr;		/* Buffer containing new attributes for
  1505 				 * serial port. */
  1506 {
  1507     IOSTATE iostate;
  1508 
  1509 #ifdef USE_TERMIOS
  1510     int parity, data, flag;
  1511 
  1512     GETIOSTATE(fd, &iostate);
  1513     cfsetospeed(&iostate, TtyGetSpeed(ttyPtr->baud));
  1514     cfsetispeed(&iostate, TtyGetSpeed(ttyPtr->baud));
  1515 
  1516     flag = 0;
  1517     parity = ttyPtr->parity;
  1518     if (parity != 'n') {
  1519 	flag |= PARENB;
  1520 #ifdef PAREXT
  1521 	iostate.c_cflag &= ~PAREXT;
  1522 	if ((parity == 'm') || (parity == 's')) {
  1523 	    flag |= PAREXT;
  1524 	}
  1525 #endif /* PAREXT */
  1526 	if ((parity == 'm') || (parity == 'o')) {
  1527 	    flag |= PARODD;
  1528 	}
  1529     }
  1530     data = ttyPtr->data;
  1531     flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8;
  1532     if (ttyPtr->stop == 2) {
  1533 	flag |= CSTOPB;
  1534     }
  1535 
  1536     iostate.c_cflag &= ~(PARENB | PARODD | CSIZE | CSTOPB);
  1537     iostate.c_cflag |= flag;
  1538 
  1539 #endif	/* USE_TERMIOS */
  1540 
  1541 #ifdef USE_TERMIO
  1542     int parity, data, flag;
  1543 
  1544     GETIOSTATE(fd, &iostate);
  1545     iostate.c_cflag &= ~CBAUD;
  1546     iostate.c_cflag |= TtyGetSpeed(ttyPtr->baud);
  1547 
  1548     flag = 0;
  1549     parity = ttyPtr->parity;
  1550     if (parity != 'n') {
  1551 	flag |= PARENB;
  1552 	if ((parity == 'm') || (parity == 's')) {
  1553 	    flag |= PAREXT;
  1554 	}
  1555 	if ((parity == 'm') || (parity == 'o')) {
  1556 	    flag |= PARODD;
  1557 	}
  1558     }
  1559     data = ttyPtr->data;
  1560     flag |= (data == 5) ? CS5 : (data == 6) ? CS6 : (data == 7) ? CS7 : CS8;
  1561     if (ttyPtr->stop == 2) {
  1562 	flag |= CSTOPB;
  1563     }
  1564 
  1565     iostate.c_cflag &= ~(PARENB | PARODD | PAREXT | CSIZE | CSTOPB);
  1566     iostate.c_cflag |= flag;
  1567 
  1568 #endif	/* USE_TERMIO */
  1569 
  1570 #ifdef USE_SGTTY
  1571     int parity;
  1572 
  1573     GETIOSTATE(fd, &iostate);
  1574     iostate.sg_ospeed = TtyGetSpeed(ttyPtr->baud);
  1575     iostate.sg_ispeed = TtyGetSpeed(ttyPtr->baud);
  1576 
  1577     parity = ttyPtr->parity;
  1578     if (parity == 'e') {
  1579 	iostate.sg_flags &= ~ODDP;
  1580 	iostate.sg_flags |= EVENP;
  1581     } else if (parity == 'o') {
  1582 	iostate.sg_flags &= ~EVENP;
  1583 	iostate.sg_flags |= ODDP;
  1584     }
  1585 #endif	/* USE_SGTTY */
  1586 
  1587     SETIOSTATE(fd, &iostate);
  1588 }
  1589 
  1590 /*
  1591  *---------------------------------------------------------------------------
  1592  *
  1593  * TtyParseMode --
  1594  *
  1595  *	Parse the "-mode" argument to the fconfigure command.  The argument
  1596  *	is of the form baud,parity,data,stop.
  1597  *
  1598  * Results:
  1599  *	The return value is TCL_OK if the argument was successfully
  1600  *	parsed, TCL_ERROR otherwise.  If TCL_ERROR is returned, an
  1601  *	error message is left in the interp's result (if interp is non-NULL).
  1602  *
  1603  * Side effects:
  1604  *	None.
  1605  *
  1606  *---------------------------------------------------------------------------
  1607  */
  1608 
  1609 static int
  1610 TtyParseMode(interp, mode, speedPtr, parityPtr, dataPtr, stopPtr)
  1611     Tcl_Interp *interp;		/* If non-NULL, interp for error return. */
  1612     CONST char *mode;		/* Mode string to be parsed. */
  1613     int *speedPtr;		/* Filled with baud rate from mode string. */
  1614     int *parityPtr;		/* Filled with parity from mode string. */
  1615     int *dataPtr;		/* Filled with data bits from mode string. */
  1616     int *stopPtr;		/* Filled with stop bits from mode string. */
  1617 {
  1618     int i, end;
  1619     char parity;
  1620     static char *bad = "bad value for -mode";
  1621 
  1622     i = sscanf(mode, "%d,%c,%d,%d%n", speedPtr, &parity, dataPtr,
  1623 	    stopPtr, &end);
  1624     if ((i != 4) || (mode[end] != '\0')) {
  1625 	if (interp != NULL) {
  1626 	    Tcl_AppendResult(interp, bad, ": should be baud,parity,data,stop",
  1627 		    NULL);
  1628 	}
  1629 	return TCL_ERROR;
  1630     }
  1631     /*
  1632      * Only allow setting mark/space parity on platforms that support it
  1633      * Make sure to allow for the case where strchr is a macro.
  1634      * [Bug: 5089]
  1635      */
  1636     if (
  1637 #if defined(PAREXT) || defined(USE_TERMIO)
  1638 	strchr("noems", parity) == NULL
  1639 #else
  1640 	strchr("noe", parity) == NULL
  1641 #endif /* PAREXT|USE_TERMIO */
  1642 	) {
  1643 	if (interp != NULL) {
  1644 	    Tcl_AppendResult(interp, bad,
  1645 #if defined(PAREXT) || defined(USE_TERMIO)
  1646 		    " parity: should be n, o, e, m, or s",
  1647 #else
  1648 		    " parity: should be n, o, or e",
  1649 #endif /* PAREXT|USE_TERMIO */
  1650 		    NULL);
  1651 	}
  1652 	return TCL_ERROR;
  1653     }
  1654     *parityPtr = parity;
  1655     if ((*dataPtr < 5) || (*dataPtr > 8)) {
  1656 	if (interp != NULL) {
  1657 	    Tcl_AppendResult(interp, bad, " data: should be 5, 6, 7, or 8",
  1658 		    NULL);
  1659 	}
  1660 	return TCL_ERROR;
  1661     }
  1662     if ((*stopPtr < 0) || (*stopPtr > 2)) {
  1663 	if (interp != NULL) {
  1664 	    Tcl_AppendResult(interp, bad, " stop: should be 1 or 2", NULL);
  1665 	}
  1666 	return TCL_ERROR;
  1667     }
  1668     return TCL_OK;
  1669 }
  1670 
  1671 /*
  1672  *---------------------------------------------------------------------------
  1673  *
  1674  * TtyInit --
  1675  *
  1676  *	Given file descriptor that refers to a serial port, 
  1677  *	initialize the serial port to a set of sane values so that
  1678  *	Tcl can talk to a device located on the serial port.
  1679  *	Note that no initialization happens if the initialize flag
  1680  *	is not set; this is necessary for the correct handling of
  1681  *	UNIX console TTYs at startup.
  1682  *
  1683  * Results:
  1684  *	A pointer to a FileState suitable for use with Tcl_CreateChannel
  1685  *	and the ttyChannelType structure.
  1686  *
  1687  * Side effects:
  1688  *	Serial device initialized to non-blocking raw mode, similar to
  1689  *	sockets (if initialize flag is non-zero.)  All other modes can
  1690  *	be simulated on top of this in Tcl.
  1691  *
  1692  *---------------------------------------------------------------------------
  1693  */
  1694 
  1695 static FileState *
  1696 TtyInit(fd, initialize)
  1697     int fd;			/* Open file descriptor for serial port to
  1698 				 * be initialized. */
  1699     int initialize;
  1700 {
  1701     TtyState *ttyPtr;
  1702 
  1703     ttyPtr = (TtyState *) ckalloc((unsigned) sizeof(TtyState));
  1704     GETIOSTATE(fd, &ttyPtr->savedState);
  1705     ttyPtr->stateUpdated = 0;
  1706     if (initialize) {
  1707 	IOSTATE iostate = ttyPtr->savedState;
  1708 
  1709 #if defined(USE_TERMIOS) || defined(USE_TERMIO)
  1710 	if (iostate.c_iflag != IGNBRK ||
  1711 		iostate.c_oflag != 0 ||
  1712 		iostate.c_lflag != 0 ||
  1713 		iostate.c_cflag & CREAD ||
  1714 		iostate.c_cc[VMIN] != 1 ||
  1715 		iostate.c_cc[VTIME] != 0) {
  1716 	    ttyPtr->stateUpdated = 1;
  1717 	}
  1718 	iostate.c_iflag = IGNBRK;
  1719 	iostate.c_oflag = 0;
  1720 	iostate.c_lflag = 0;
  1721 	iostate.c_cflag |= CREAD;
  1722 	iostate.c_cc[VMIN] = 1;
  1723 	iostate.c_cc[VTIME] = 0;
  1724 #endif	/* USE_TERMIOS|USE_TERMIO */
  1725 
  1726 #ifdef USE_SGTTY
  1727 	if ((iostate.sg_flags & (EVENP | ODDP)) ||
  1728 		!(iostate.sg_flags & RAW)) {
  1729 	    ttyPtr->stateUpdated = 1;
  1730 	}
  1731 	iostate.sg_flags &= (EVENP | ODDP);
  1732 	iostate.sg_flags |= RAW;
  1733 #endif	/* USE_SGTTY */
  1734 
  1735 	/*
  1736 	 * Only update if we're changing anything to avoid possible
  1737 	 * blocking.
  1738 	 */
  1739 	if (ttyPtr->stateUpdated) {
  1740 	    SETIOSTATE(fd, &iostate);
  1741 	}
  1742     }
  1743 
  1744     return &ttyPtr->fs;
  1745 }
  1746 #endif	/* SUPPORTS_TTY */
  1747 
  1748 /*
  1749  *----------------------------------------------------------------------
  1750  *
  1751  * TclpOpenFileChannel --
  1752  *
  1753  *	Open an file based channel on Unix systems.
  1754  *
  1755  * Results:
  1756  *	The new channel or NULL. If NULL, the output argument
  1757  *	errorCodePtr is set to a POSIX error and an error message is
  1758  *	left in the interp's result if interp is not NULL.
  1759  *
  1760  * Side effects:
  1761  *	May open the channel and may cause creation of a file on the
  1762  *	file system.
  1763  *
  1764  *----------------------------------------------------------------------
  1765  */
  1766 
  1767 Tcl_Channel
  1768 TclpOpenFileChannel(interp, pathPtr, mode, permissions)
  1769     Tcl_Interp *interp;			/* Interpreter for error reporting;
  1770 					 * can be NULL. */
  1771     Tcl_Obj *pathPtr;			/* Name of file to open. */
  1772     int mode;				/* POSIX open mode. */
  1773     int permissions;			/* If the open involves creating a
  1774 					 * file, with what modes to create
  1775 					 * it? */
  1776 {
  1777     int fd, channelPermissions;
  1778     FileState *fsPtr;
  1779     CONST char *native, *translation;
  1780     char channelName[16 + TCL_INTEGER_SPACE];
  1781     Tcl_ChannelType *channelTypePtr;
  1782 #ifdef SUPPORTS_TTY
  1783     int ctl_tty;
  1784 #endif /* SUPPORTS_TTY */
  1785 #ifdef DEPRECATED
  1786     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
  1787 #endif /* DEPRECATED */
  1788 
  1789     switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
  1790 	case O_RDONLY:
  1791 	    channelPermissions = TCL_READABLE;
  1792 	    break;
  1793 	case O_WRONLY:
  1794 	    channelPermissions = TCL_WRITABLE;
  1795 	    break;
  1796 	case O_RDWR:
  1797 	    channelPermissions = (TCL_READABLE | TCL_WRITABLE);
  1798 	    break;
  1799 	default:
  1800 	    /*
  1801 	     * This may occurr if modeString was "", for example.
  1802 	     */
  1803 	    panic("TclpOpenFileChannel: invalid mode value");
  1804 	    return NULL;
  1805     }
  1806 
  1807     native = Tcl_FSGetNativePath(pathPtr);
  1808     if (native == NULL) {
  1809 	return NULL;
  1810     }
  1811     fd = TclOSopen(native, mode, permissions);
  1812 #ifdef SUPPORTS_TTY
  1813     ctl_tty = (strcmp (native, "/dev/tty") == 0);
  1814 #endif /* SUPPORTS_TTY */
  1815 
  1816     if (fd < 0) {
  1817 	if (interp != (Tcl_Interp *) NULL) {
  1818 	    Tcl_AppendResult(interp, "couldn't open \"", 
  1819 		    Tcl_GetString(pathPtr), "\": ",
  1820 		    Tcl_PosixError(interp), (char *) NULL);
  1821 	}
  1822 	return NULL;
  1823     }
  1824 
  1825     /*
  1826      * Set close-on-exec flag on the fd so that child processes will not
  1827      * inherit this fd.
  1828      */
  1829 
  1830     fcntl(fd, F_SETFD, FD_CLOEXEC);
  1831 
  1832     sprintf(channelName, "file%d", fd);
  1833 
  1834 #ifdef SUPPORTS_TTY
  1835     if (!ctl_tty && isatty(fd)) {
  1836 	/*
  1837 	 * Initialize the serial port to a set of sane parameters.
  1838 	 * Especially important if the remote device is set to echo and
  1839 	 * the serial port driver was also set to echo -- as soon as a char
  1840 	 * were sent to the serial port, the remote device would echo it,
  1841 	 * then the serial driver would echo it back to the device, etc.
  1842 	 */
  1843 
  1844 	translation = "auto crlf";
  1845 	channelTypePtr = &ttyChannelType;
  1846 	fsPtr = TtyInit(fd, 1);
  1847     } else 
  1848 #endif	/* SUPPORTS_TTY */
  1849     {
  1850 	translation = NULL;
  1851 	channelTypePtr = &fileChannelType;
  1852 	fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState));
  1853     }
  1854 
  1855 #ifdef DEPRECATED
  1856     if (channelTypePtr == &fileChannelType) {
  1857         /* TIP #218. Removed the code inserting the new structure
  1858 	 * into the global list. This is now handled in the thread
  1859 	 * action callbacks, and only there.
  1860 	 */
  1861         fsPtr->nextPtr = NULL;
  1862     }
  1863 #endif /* DEPRECATED */
  1864     fsPtr->validMask = channelPermissions | TCL_EXCEPTION;
  1865     fsPtr->fd = fd;
  1866 
  1867     fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName,
  1868 	    (ClientData) fsPtr, channelPermissions);
  1869 
  1870     if (translation != NULL) {
  1871 	/*
  1872 	 * Gotcha.  Most modems need a "\r" at the end of the command
  1873 	 * sequence.  If you just send "at\n", the modem will not respond
  1874 	 * with "OK" because it never got a "\r" to actually invoke the
  1875 	 * command.  So, by default, newlines are translated to "\r\n" on
  1876 	 * output to avoid "bug" reports that the serial port isn't working.
  1877 	 */
  1878 
  1879 	if (Tcl_SetChannelOption(interp, fsPtr->channel, "-translation",
  1880 		translation) != TCL_OK) {
  1881 	    Tcl_Close(NULL, fsPtr->channel);
  1882 	    return NULL;
  1883 	}
  1884     }
  1885 
  1886     return fsPtr->channel;
  1887 }
  1888 
  1889 /*
  1890  *----------------------------------------------------------------------
  1891  *
  1892  * Tcl_MakeFileChannel --
  1893  *
  1894  *	Makes a Tcl_Channel from an existing OS level file handle.
  1895  *
  1896  * Results:
  1897  *	The Tcl_Channel created around the preexisting OS level file handle.
  1898  *
  1899  * Side effects:
  1900  *	None.
  1901  *
  1902  *----------------------------------------------------------------------
  1903  */
  1904 
  1905 EXPORT_C Tcl_Channel
  1906 Tcl_MakeFileChannel(handle, mode)
  1907     ClientData handle;		/* OS level handle. */
  1908     int mode;			/* ORed combination of TCL_READABLE and
  1909 				 * TCL_WRITABLE to indicate file mode. */
  1910 {
  1911     FileState *fsPtr;
  1912     char channelName[16 + TCL_INTEGER_SPACE];
  1913     int fd = (int) handle;
  1914     Tcl_ChannelType *channelTypePtr;
  1915 #ifdef DEPRECATED
  1916     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
  1917 #endif /* DEPRECATED */
  1918     struct sockaddr sockaddr;
  1919     socklen_t sockaddrLen = sizeof(sockaddr);
  1920 
  1921     if (mode == 0) {
  1922 	return NULL;
  1923     }
  1924 
  1925 
  1926     /*
  1927      * Look to see if a channel with this fd and the same mode already exists.
  1928      * If the fd is used, but the mode doesn't match, return NULL.
  1929      */
  1930 
  1931 #ifdef DEPRECATED
  1932     for (fsPtr = tsdPtr->firstFilePtr; fsPtr != NULL; fsPtr = fsPtr->nextPtr) {
  1933 	if (fsPtr->fd == fd) {
  1934 	    return ((mode|TCL_EXCEPTION) == fsPtr->validMask) ?
  1935 		    fsPtr->channel : NULL;
  1936 	}
  1937     }
  1938 #endif /* DEPRECATED */
  1939 
  1940     sockaddr.sa_family = AF_UNSPEC;
  1941 
  1942 #ifdef SUPPORTS_TTY
  1943     if (isatty(fd)) {
  1944 	fsPtr = TtyInit(fd, 0);
  1945 	channelTypePtr = &ttyChannelType;
  1946 	sprintf(channelName, "serial%d", fd);
  1947     } else
  1948 #endif /* SUPPORTS_TTY */
  1949     if (getsockname(fd, (struct sockaddr *)&sockaddr, &sockaddrLen) == 0
  1950             && sockaddrLen > 0
  1951             && sockaddr.sa_family == AF_INET) {
  1952         return MakeTcpClientChannelMode((ClientData) fd, mode);
  1953     } else {
  1954         channelTypePtr = &fileChannelType;
  1955         fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState));
  1956         sprintf(channelName, "file%d", fd);
  1957     }
  1958 
  1959 #ifdef DEPRECATED
  1960     if (channelTypePtr == &fileChannelType) {
  1961         fsPtr->nextPtr = tsdPtr->firstFilePtr;
  1962         tsdPtr->firstFilePtr = fsPtr;
  1963     }
  1964 #endif /* DEPRECATED */
  1965     fsPtr->fd = fd;
  1966     fsPtr->validMask = mode | TCL_EXCEPTION;
  1967     fsPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName,
  1968 	    (ClientData) fsPtr, mode);
  1969 
  1970     return fsPtr->channel;
  1971 }
  1972 
  1973 /*
  1974  *----------------------------------------------------------------------
  1975  *
  1976  * TcpBlockModeProc --
  1977  *
  1978  *	This procedure is invoked by the generic IO level to set blocking
  1979  *	and nonblocking mode on a TCP socket based channel.
  1980  *
  1981  * Results:
  1982  *	0 if successful, errno when failed.
  1983  *
  1984  * Side effects:
  1985  *	Sets the device into blocking or nonblocking mode.
  1986  *
  1987  *----------------------------------------------------------------------
  1988  */
  1989 
  1990 	/* ARGSUSED */
  1991 static int
  1992 TcpBlockModeProc(instanceData, mode)
  1993     ClientData instanceData;		/* Socket state. */
  1994     int mode;				/* The mode to set. Can be one of
  1995 					 * TCL_MODE_BLOCKING or
  1996 					 * TCL_MODE_NONBLOCKING. */
  1997 {
  1998     TcpState *statePtr = (TcpState *) instanceData;
  1999     int setting;
  2000 
  2001 #ifndef USE_FIONBIO
  2002     setting = fcntl(statePtr->fd, F_GETFL);
  2003     if (mode == TCL_MODE_BLOCKING) {
  2004 	statePtr->flags &= (~(TCP_ASYNC_SOCKET));
  2005 	setting &= (~(O_NONBLOCK));
  2006     } else {
  2007 	statePtr->flags |= TCP_ASYNC_SOCKET;
  2008 	setting |= O_NONBLOCK;
  2009     }
  2010     if (fcntl(statePtr->fd, F_SETFL, setting) < 0) {
  2011 	return errno;
  2012     }
  2013 #else /* USE_FIONBIO */
  2014     if (mode == TCL_MODE_BLOCKING) {
  2015 	statePtr->flags &= (~(TCP_ASYNC_SOCKET));
  2016 	setting = 0;
  2017 	if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) {
  2018 	    return errno;
  2019 	}
  2020     } else {
  2021 	statePtr->flags |= TCP_ASYNC_SOCKET;
  2022 	setting = 1;
  2023 	if (ioctl(statePtr->fd, (int) FIONBIO, &setting) == -1) {
  2024 	    return errno;
  2025 	}
  2026     }
  2027 #endif /* !USE_FIONBIO */
  2028 
  2029     return 0;
  2030 }
  2031 
  2032 /*
  2033  *----------------------------------------------------------------------
  2034  *
  2035  * WaitForConnect --
  2036  *
  2037  *	Waits for a connection on an asynchronously opened socket to
  2038  *	be completed.
  2039  *
  2040  * Results:
  2041  *	None.
  2042  *
  2043  * Side effects:
  2044  *	The socket is connected after this function returns.
  2045  *
  2046  *----------------------------------------------------------------------
  2047  */
  2048 
  2049 static int
  2050 WaitForConnect(statePtr, errorCodePtr)
  2051     TcpState *statePtr;		/* State of the socket. */
  2052     int *errorCodePtr;		/* Where to store errors? */
  2053 {
  2054     int timeOut;		/* How long to wait. */
  2055     int state;			/* Of calling TclWaitForFile. */
  2056     int flags;			/* fcntl flags for the socket. */
  2057 
  2058     /*
  2059      * If an asynchronous connect is in progress, attempt to wait for it
  2060      * to complete before reading.
  2061      */
  2062 
  2063     if (statePtr->flags & TCP_ASYNC_CONNECT) {
  2064 	if (statePtr->flags & TCP_ASYNC_SOCKET) {
  2065 	    timeOut = 0;
  2066 	} else {
  2067 	    timeOut = -1;
  2068 	}
  2069 	errno = 0;
  2070 	state = TclUnixWaitForFile(statePtr->fd,
  2071 		TCL_WRITABLE | TCL_EXCEPTION, timeOut);
  2072 	if (!(statePtr->flags & TCP_ASYNC_SOCKET)) {
  2073 #ifndef USE_FIONBIO
  2074 	    flags = fcntl(statePtr->fd, F_GETFL);
  2075 	    flags &= (~(O_NONBLOCK));
  2076 	    (void) fcntl(statePtr->fd, F_SETFL, flags);
  2077 #else /* USE_FIONBIO */
  2078 	    flags = 0;
  2079 	    (void) ioctl(statePtr->fd, FIONBIO, &flags);
  2080 #endif /* !USE_FIONBIO */
  2081 	}
  2082 	if (state & TCL_EXCEPTION) {
  2083 	    return -1;
  2084 	}
  2085 	if (state & TCL_WRITABLE) {
  2086 	    statePtr->flags &= (~(TCP_ASYNC_CONNECT));
  2087 	} else if (timeOut == 0) {
  2088 	    *errorCodePtr = errno = EWOULDBLOCK;
  2089 	    return -1;
  2090 	}
  2091     }
  2092     return 0;
  2093 }
  2094 
  2095 /*
  2096  *----------------------------------------------------------------------
  2097  *
  2098  * TcpInputProc --
  2099  *
  2100  *	This procedure is invoked by the generic IO level to read input
  2101  *	from a TCP socket based channel.
  2102  *
  2103  *	NOTE: We cannot share code with FilePipeInputProc because here
  2104  *	we must use recv to obtain the input from the channel, not read.
  2105  *
  2106  * Results:
  2107  *	The number of bytes read is returned or -1 on error. An output
  2108  *	argument contains the POSIX error code on error, or zero if no
  2109  *	error occurred.
  2110  *
  2111  * Side effects:
  2112  *	Reads input from the input device of the channel.
  2113  *
  2114  *----------------------------------------------------------------------
  2115  */
  2116 
  2117 	/* ARGSUSED */
  2118 static int
  2119 TcpInputProc(instanceData, buf, bufSize, errorCodePtr)
  2120     ClientData instanceData;		/* Socket state. */
  2121     char *buf;				/* Where to store data read. */
  2122     int bufSize;			/* How much space is available
  2123 					 * in the buffer? */
  2124     int *errorCodePtr;			/* Where to store error code. */
  2125 {
  2126     TcpState *statePtr = (TcpState *) instanceData;
  2127     int bytesRead, state;
  2128 
  2129     *errorCodePtr = 0;
  2130     state = WaitForConnect(statePtr, errorCodePtr);
  2131     if (state != 0) {
  2132 	return -1;
  2133     }
  2134     bytesRead = recv(statePtr->fd, buf, (size_t) bufSize, 0);
  2135     if (bytesRead > -1) {
  2136 	return bytesRead;
  2137     }
  2138     if (errno == ECONNRESET) {
  2139 	/*
  2140 	 * Turn ECONNRESET into a soft EOF condition.
  2141 	 */
  2142 
  2143 	return 0;
  2144     }
  2145     *errorCodePtr = errno;
  2146     return -1;
  2147 }
  2148 
  2149 /*
  2150  *----------------------------------------------------------------------
  2151  *
  2152  * TcpOutputProc --
  2153  *
  2154  *	This procedure is invoked by the generic IO level to write output
  2155  *	to a TCP socket based channel.
  2156  *
  2157  *	NOTE: We cannot share code with FilePipeOutputProc because here
  2158  *	we must use send, not write, to get reliable error reporting.
  2159  *
  2160  * Results:
  2161  *	The number of bytes written is returned. An output argument is
  2162  *	set to a POSIX error code if an error occurred, or zero.
  2163  *
  2164  * Side effects:
  2165  *	Writes output on the output device of the channel.
  2166  *
  2167  *----------------------------------------------------------------------
  2168  */
  2169 
  2170 static int
  2171 TcpOutputProc(instanceData, buf, toWrite, errorCodePtr)
  2172     ClientData instanceData;		/* Socket state. */
  2173     CONST char *buf;			/* The data buffer. */
  2174     int toWrite;			/* How many bytes to write? */
  2175     int *errorCodePtr;			/* Where to store error code. */
  2176 {
  2177     TcpState *statePtr = (TcpState *) instanceData;
  2178     int written;
  2179     int state;				/* Of waiting for connection. */
  2180 
  2181     *errorCodePtr = 0;
  2182     state = WaitForConnect(statePtr, errorCodePtr);
  2183     if (state != 0) {
  2184 	return -1;
  2185     }
  2186     written = send(statePtr->fd, buf, (size_t) toWrite, 0);
  2187     if (written > -1) {
  2188 	return written;
  2189     }
  2190     *errorCodePtr = errno;
  2191     return -1;
  2192 }
  2193 
  2194 /*
  2195  *----------------------------------------------------------------------
  2196  *
  2197  * TcpCloseProc --
  2198  *
  2199  *	This procedure is invoked by the generic IO level to perform
  2200  *	channel-type-specific cleanup when a TCP socket based channel
  2201  *	is closed.
  2202  *
  2203  * Results:
  2204  *	0 if successful, the value of errno if failed.
  2205  *
  2206  * Side effects:
  2207  *	Closes the socket of the channel.
  2208  *
  2209  *----------------------------------------------------------------------
  2210  */
  2211 
  2212 	/* ARGSUSED */
  2213 static int
  2214 TcpCloseProc(instanceData, interp)
  2215     ClientData instanceData;	/* The socket to close. */
  2216     Tcl_Interp *interp;		/* For error reporting - unused. */
  2217 {
  2218     TcpState *statePtr = (TcpState *) instanceData;
  2219     int errorCode = 0;
  2220 
  2221     /*
  2222      * Delete a file handler that may be active for this socket if this
  2223      * is a server socket - the file handler was created automatically
  2224      * by Tcl as part of the mechanism to accept new client connections.
  2225      * Channel handlers are already deleted in the generic IO channel
  2226      * closing code that called this function, so we do not have to
  2227      * delete them here.
  2228      */
  2229 
  2230     Tcl_DeleteFileHandler(statePtr->fd);
  2231 
  2232     if (close(statePtr->fd) < 0) {
  2233 	errorCode = errno;
  2234     }
  2235     ckfree((char *) statePtr);
  2236 
  2237     return errorCode;
  2238 }
  2239 
  2240 /*
  2241  *----------------------------------------------------------------------
  2242  *
  2243  * TcpGetOptionProc --
  2244  *
  2245  *	Computes an option value for a TCP socket based channel, or a
  2246  *	list of all options and their values.
  2247  *
  2248  *	Note: This code is based on code contributed by John Haxby.
  2249  *
  2250  * Results:
  2251  *	A standard Tcl result. The value of the specified option or a
  2252  *	list of all options and their values is returned in the
  2253  *	supplied DString. Sets Error message if needed.
  2254  *
  2255  * Side effects:
  2256  *	None.
  2257  *
  2258  *----------------------------------------------------------------------
  2259  */
  2260 
  2261 static int
  2262 TcpGetOptionProc(instanceData, interp, optionName, dsPtr)
  2263     ClientData instanceData;	 /* Socket state. */
  2264     Tcl_Interp *interp;		 /* For error reporting - can be NULL. */
  2265     CONST char *optionName;	 /* Name of the option to
  2266 				  * retrieve the value for, or
  2267 				  * NULL to get all options and
  2268 				  * their values. */
  2269     Tcl_DString *dsPtr;		 /* Where to store the computed
  2270 				  * value; initialized by caller. */
  2271 {
  2272     TcpState *statePtr = (TcpState *) instanceData;
  2273     struct sockaddr_in sockname;
  2274     struct sockaddr_in peername;
  2275     struct hostent *hostEntPtr;
  2276     socklen_t size = sizeof(struct sockaddr_in);
  2277     size_t len = 0;
  2278     char buf[TCL_INTEGER_SPACE];
  2279 
  2280     if (optionName != (char *) NULL) {
  2281 	len = strlen(optionName);
  2282     }
  2283 
  2284     if ((len > 1) && (optionName[1] == 'e') &&
  2285 	    (strncmp(optionName, "-error", len) == 0)) {
  2286 	socklen_t optlen = sizeof(int);
  2287 	int err, ret;
  2288 	err = 0;
  2289 
  2290 
  2291 	ret = getsockopt(statePtr->fd, SOL_SOCKET, SO_ERROR,
  2292 		(char *)&err, &optlen);
  2293 	if (ret < 0) {
  2294 	    err = errno;
  2295 	}
  2296 	if (err != 0) {
  2297 	    Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(err), -1);
  2298 	}
  2299 	return TCL_OK;
  2300     }
  2301 
  2302     if ((len == 0) ||
  2303 	    ((len > 1) && (optionName[1] == 'p') &&
  2304 		    (strncmp(optionName, "-peername", len) == 0))) {
  2305 	if (getpeername(statePtr->fd, (struct sockaddr *) &peername,
  2306 		&size) >= 0) {
  2307 	    if (len == 0) {
  2308 		Tcl_DStringAppendElement(dsPtr, "-peername");
  2309 		Tcl_DStringStartSublist(dsPtr);
  2310 	    }
  2311 	    Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
  2312 	    hostEntPtr = TclpGetHostByAddr(			/* INTL: Native. */
  2313 		    (char *) &peername.sin_addr,
  2314 		    sizeof(peername.sin_addr), AF_INET);
  2315 	    if (hostEntPtr != (struct hostent *) NULL) {
  2316 		Tcl_DString ds;
  2317 
  2318 		Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds);
  2319 		Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
  2320 		Tcl_DStringFree(&ds);
  2321 	    } else {
  2322 		Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
  2323 	    }
  2324 	    TclFormatInt(buf, ntohs(peername.sin_port));
  2325 	    Tcl_DStringAppendElement(dsPtr, buf);
  2326 	    if (len == 0) {
  2327 		Tcl_DStringEndSublist(dsPtr);
  2328 	    } else {
  2329 		return TCL_OK;
  2330 	    }
  2331 	} else {
  2332 	    /*
  2333 	     * getpeername failed - but if we were asked for all the options
  2334 	     * (len==0), don't flag an error at that point because it could
  2335 	     * be an fconfigure request on a server socket. (which have
  2336 	     * no peer). same must be done on win&mac.
  2337 	     */
  2338 
  2339 	    if (len) {
  2340 		if (interp) {
  2341 		    Tcl_AppendResult(interp, "can't get peername: ",
  2342 			    Tcl_PosixError(interp), (char *) NULL);
  2343 		}
  2344 		return TCL_ERROR;
  2345 	    }
  2346 	}
  2347     }
  2348 
  2349     if ((len == 0) ||
  2350 	    ((len > 1) && (optionName[1] == 's') &&
  2351 	    (strncmp(optionName, "-sockname", len) == 0))) {
  2352 	if (getsockname(statePtr->fd, (struct sockaddr *) &sockname,
  2353 		&size) >= 0) {
  2354 	    if (len == 0) {
  2355 		Tcl_DStringAppendElement(dsPtr, "-sockname");
  2356 		Tcl_DStringStartSublist(dsPtr);
  2357 	    }
  2358 	    Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
  2359 	    hostEntPtr = TclpGetHostByAddr(			/* INTL: Native. */
  2360 		    (char *) &sockname.sin_addr,
  2361 		    sizeof(sockname.sin_addr), AF_INET);
  2362 	    if (hostEntPtr != (struct hostent *) NULL) {
  2363 		Tcl_DString ds;
  2364 
  2365 		Tcl_ExternalToUtfDString(NULL, hostEntPtr->h_name, -1, &ds);
  2366 		Tcl_DStringAppendElement(dsPtr, Tcl_DStringValue(&ds));
  2367 		Tcl_DStringFree(&ds);
  2368 	    } else {
  2369 		Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
  2370 	    }
  2371 	    TclFormatInt(buf, ntohs(sockname.sin_port));
  2372 	    Tcl_DStringAppendElement(dsPtr, buf);
  2373 	    if (len == 0) {
  2374 		Tcl_DStringEndSublist(dsPtr);
  2375 	    } else {
  2376 		return TCL_OK;
  2377 	    }
  2378 	} else {
  2379 	    if (interp) {
  2380 		Tcl_AppendResult(interp, "can't get sockname: ",
  2381 			Tcl_PosixError(interp), (char *) NULL);
  2382 	    }
  2383 	    return TCL_ERROR;
  2384 	}
  2385     }
  2386 
  2387     if (len > 0) {
  2388 	return Tcl_BadChannelOption(interp, optionName, "peername sockname");
  2389     }
  2390 
  2391     return TCL_OK;
  2392 }
  2393 
  2394 /*
  2395  *----------------------------------------------------------------------
  2396  *
  2397  * TcpWatchProc --
  2398  *
  2399  *	Initialize the notifier to watch the fd from this channel.
  2400  *
  2401  * Results:
  2402  *	None.
  2403  *
  2404  * Side effects:
  2405  *	Sets up the notifier so that a future event on the channel will
  2406  *	be seen by Tcl.
  2407  *
  2408  *----------------------------------------------------------------------
  2409  */
  2410 
  2411 static void
  2412 TcpWatchProc(instanceData, mask)
  2413     ClientData instanceData;		/* The socket state. */
  2414     int mask;				/* Events of interest; an OR-ed
  2415 					 * combination of TCL_READABLE,
  2416 					 * TCL_WRITABLE and TCL_EXCEPTION. */
  2417 {
  2418     TcpState *statePtr = (TcpState *) instanceData;
  2419 
  2420     /*
  2421      * Make sure we don't mess with server sockets since they will never
  2422      * be readable or writable at the Tcl level.  This keeps Tcl scripts
  2423      * from interfering with the -accept behavior.
  2424      */
  2425 
  2426     if (!statePtr->acceptProc) {
  2427 	if (mask) {
  2428 	    Tcl_CreateFileHandler(statePtr->fd, mask,
  2429 		    (Tcl_FileProc *) Tcl_NotifyChannel,
  2430 		    (ClientData) statePtr->channel);
  2431 	} else {
  2432 	    Tcl_DeleteFileHandler(statePtr->fd);
  2433 	}
  2434     }
  2435 }
  2436 
  2437 /*
  2438  *----------------------------------------------------------------------
  2439  *
  2440  * TcpGetHandleProc --
  2441  *
  2442  *	Called from Tcl_GetChannelHandle to retrieve OS handles from inside
  2443  *	a TCP socket based channel.
  2444  *
  2445  * Results:
  2446  *	Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
  2447  *	there is no handle for the specified direction. 
  2448  *
  2449  * Side effects:
  2450  *	None.
  2451  *
  2452  *----------------------------------------------------------------------
  2453  */
  2454 
  2455 	/* ARGSUSED */
  2456 static int
  2457 TcpGetHandleProc(instanceData, direction, handlePtr)
  2458     ClientData instanceData;	/* The socket state. */
  2459     int direction;		/* Not used. */
  2460     ClientData *handlePtr;	/* Where to store the handle.  */
  2461 {
  2462     TcpState *statePtr = (TcpState *) instanceData;
  2463 
  2464     *handlePtr = (ClientData)statePtr->fd;
  2465     return TCL_OK;
  2466 }
  2467 
  2468 /*
  2469  *----------------------------------------------------------------------
  2470  *
  2471  * CreateSocket --
  2472  *
  2473  *	This function opens a new socket in client or server mode
  2474  *	and initializes the TcpState structure.
  2475  *
  2476  * Results:
  2477  *	Returns a new TcpState, or NULL with an error in the interp's
  2478  *	result, if interp is not NULL.
  2479  *
  2480  * Side effects:
  2481  *	Opens a socket.
  2482  *
  2483  *----------------------------------------------------------------------
  2484  */
  2485 
  2486 static TcpState *
  2487 CreateSocket(interp, port, host, server, myaddr, myport, async)
  2488     Tcl_Interp *interp;		/* For error reporting; can be NULL. */
  2489     int port;			/* Port number to open. */
  2490     CONST char *host;		/* Name of host on which to open port.
  2491 				 * NULL implies INADDR_ANY */
  2492     int server;			/* 1 if socket should be a server socket,
  2493 				 * else 0 for a client socket. */
  2494     CONST char *myaddr;		/* Optional client-side address */
  2495     int myport;			/* Optional client-side port */
  2496     int async;			/* If nonzero and creating a client socket,
  2497 				 * attempt to do an async connect. Otherwise
  2498 				 * do a synchronous connect or bind. */
  2499 {
  2500     int status, sock, asyncConnect, curState, origState;
  2501     struct sockaddr_in sockaddr;	/* socket address */
  2502     struct sockaddr_in mysockaddr;	/* Socket address for client */
  2503     TcpState *statePtr;
  2504 
  2505     sock = -1;
  2506     origState = 0;
  2507     if (! CreateSocketAddress(&sockaddr, host, port)) {
  2508 	goto addressError;
  2509     }
  2510     if ((myaddr != NULL || myport != 0) &&
  2511 	    ! CreateSocketAddress(&mysockaddr, myaddr, myport)) {
  2512 	goto addressError;
  2513     }
  2514 
  2515     sock = socket(AF_INET, SOCK_STREAM, 0);
  2516     if (sock < 0) {
  2517 	goto addressError;
  2518     }
  2519 
  2520     /*
  2521      * Set the close-on-exec flag so that the socket will not get
  2522      * inherited by child processes.
  2523      */
  2524 
  2525     fcntl(sock, F_SETFD, FD_CLOEXEC);
  2526 
  2527     /*
  2528      * Set kernel space buffering
  2529      */
  2530 
  2531     TclSockMinimumBuffers(sock, SOCKET_BUFSIZE);
  2532 
  2533     asyncConnect = 0;
  2534     status = 0;
  2535     if (server) {
  2536 	/*
  2537 	 * Set up to reuse server addresses automatically and bind to the
  2538 	 * specified port.
  2539 	 */
  2540 
  2541 	status = 1;
  2542 	(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status,
  2543 		sizeof(status));
  2544 	status = bind(sock, (struct sockaddr *) &sockaddr,
  2545 		sizeof(struct sockaddr));
  2546 	if (status != -1) {
  2547 	    status = listen(sock, SOMAXCONN);
  2548 	} 
  2549     } else {
  2550 	if (myaddr != NULL || myport != 0) { 
  2551 	    curState = 1;
  2552 	    (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  2553 		    (char *) &curState, sizeof(curState));
  2554 	    status = bind(sock, (struct sockaddr *) &mysockaddr,
  2555 		    sizeof(struct sockaddr));
  2556 	    if (status < 0) {
  2557 		goto bindError;
  2558 	    }
  2559 	}
  2560 
  2561 	/*
  2562 	 * Attempt to connect. The connect may fail at present with an
  2563 	 * EINPROGRESS but at a later time it will complete. The caller
  2564 	 * will set up a file handler on the socket if she is interested in
  2565 	 * being informed when the connect completes.
  2566 	 */
  2567 
  2568 	if (async) {
  2569 #ifndef USE_FIONBIO
  2570 	    origState = fcntl(sock, F_GETFL);
  2571 	    curState = origState | O_NONBLOCK;
  2572 	    status = fcntl(sock, F_SETFL, curState);
  2573 #else /* USE_FIONBIO */
  2574 	    curState = 1;
  2575 	    status = ioctl(sock, FIONBIO, &curState);
  2576 #endif /* !USE_FIONBIO */
  2577 	} else {
  2578 	    status = 0;
  2579 	}
  2580 	if (status > -1) {
  2581 	    status = connect(sock, (struct sockaddr *) &sockaddr,
  2582 		    sizeof(sockaddr));
  2583 	    if (status < 0) {
  2584 		if (errno == EINPROGRESS) {
  2585 		    asyncConnect = 1;
  2586 		    status = 0;
  2587 		}
  2588 	    } else {
  2589 		/*
  2590 		 * Here we are if the connect succeeds. In case of an
  2591 		 * asynchronous connect we have to reset the channel to
  2592 		 * blocking mode.  This appears to happen not very often,
  2593 		 * but e.g. on a HP 9000/800 under HP-UX B.11.00 we enter
  2594 		 * this stage. [Bug: 4388]
  2595 		 */
  2596 		if (async) {
  2597 #ifndef USE_FIONBIO
  2598 		    origState = fcntl(sock, F_GETFL);
  2599 		    curState = origState & ~(O_NONBLOCK);
  2600 		    status = fcntl(sock, F_SETFL, curState);
  2601 #else /* USE_FIONBIO */
  2602 		    curState = 0;
  2603 		    status = ioctl(sock, FIONBIO, &curState);
  2604 #endif /* !USE_FIONBIO */
  2605 		}
  2606 	    }
  2607 	}
  2608     }
  2609 
  2610 bindError:
  2611     if (status < 0) {
  2612 	if (interp != NULL) {
  2613 	    Tcl_AppendResult(interp, "couldn't open socket: ",
  2614 		    Tcl_PosixError(interp), (char *) NULL);
  2615 	}
  2616 	if (sock != -1) {
  2617 	    close(sock);
  2618 	}
  2619 	return NULL;
  2620     }
  2621 
  2622     /*
  2623      * Allocate a new TcpState for this socket.
  2624      */
  2625 
  2626     statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
  2627     statePtr->flags = 0;
  2628     if (asyncConnect) {
  2629 	statePtr->flags = TCP_ASYNC_CONNECT;
  2630     }
  2631     statePtr->fd = sock;
  2632 
  2633     return statePtr;
  2634 
  2635 addressError:
  2636     if (sock != -1) {
  2637 	close(sock);
  2638     }
  2639     if (interp != NULL) {
  2640 	Tcl_AppendResult(interp, "couldn't open socket: ",
  2641 		Tcl_PosixError(interp), (char *) NULL);
  2642     }
  2643     return NULL;
  2644 }
  2645 
  2646 /*
  2647  *----------------------------------------------------------------------
  2648  *
  2649  * CreateSocketAddress --
  2650  *
  2651  *	This function initializes a sockaddr structure for a host and port.
  2652  *
  2653  * Results:
  2654  *	1 if the host was valid, 0 if the host could not be converted to
  2655  *	an IP address.
  2656  *
  2657  * Side effects:
  2658  *	Fills in the *sockaddrPtr structure.
  2659  *
  2660  *----------------------------------------------------------------------
  2661  */
  2662 
  2663 static int
  2664 CreateSocketAddress(sockaddrPtr, host, port)
  2665     struct sockaddr_in *sockaddrPtr;	/* Socket address */
  2666     CONST char *host;			/* Host.  NULL implies INADDR_ANY */
  2667     int port;				/* Port number */
  2668 {
  2669     struct hostent *hostent;		/* Host database entry */
  2670     struct in_addr addr;		/* For 64/32 bit madness */
  2671 
  2672 #ifdef __SYMBIAN32__  
  2673 	if (host && !strcmp(host, "localhost")) {
  2674 		char* loc = strstr(host, "localhost");
  2675 		memcpy(loc, "127.0.0.1", 9);
  2676 	}
  2677 #endif	
  2678     (void) memset((VOID *) sockaddrPtr, '\0', sizeof(struct sockaddr_in));
  2679     sockaddrPtr->sin_family = AF_INET;
  2680     sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF));
  2681     if (host == NULL) {
  2682 	addr.s_addr = INADDR_ANY;
  2683     } else {
  2684 	Tcl_DString ds;
  2685 	CONST char *native;
  2686 
  2687 	if (host == NULL) {
  2688 	    native = NULL;
  2689 	} else {
  2690 	    native = Tcl_UtfToExternalDString(NULL, host, -1, &ds);
  2691 	}
  2692 	addr.s_addr = inet_addr(native);		/* INTL: Native. */
  2693 	/*
  2694 	 * This is 0xFFFFFFFF to ensure that it compares as a 32bit -1
  2695 	 * on either 32 or 64 bits systems.
  2696 	 */
  2697 	if (addr.s_addr == 0xFFFFFFFF) {
  2698 	    hostent = TclpGetHostByName(native);		/* INTL: Native. */
  2699 	    if (hostent != (struct hostent *) NULL) {
  2700 		memcpy((VOID *) &addr,
  2701 			(VOID *) hostent->h_addr_list[0],
  2702 			(size_t) hostent->h_length);
  2703 	    } else {
  2704 #ifdef	EHOSTUNREACH
  2705 		errno = EHOSTUNREACH;
  2706 #else /* !EHOSTUNREACH */
  2707 #ifdef ENXIO
  2708 		errno = ENXIO;
  2709 #endif /* ENXIO */
  2710 #endif /* EHOSTUNREACH */
  2711 		if (native != NULL) {
  2712 		    Tcl_DStringFree(&ds);
  2713 		}
  2714 		return 0;	/* error */
  2715 	    }
  2716 	}
  2717 	if (native != NULL) {
  2718 	    Tcl_DStringFree(&ds);
  2719 	}
  2720     }
  2721 
  2722     /*
  2723      * NOTE: On 64 bit machines the assignment below is rumored to not
  2724      * do the right thing. Please report errors related to this if you
  2725      * observe incorrect behavior on 64 bit machines such as DEC Alphas.
  2726      * Should we modify this code to do an explicit memcpy?
  2727      */
  2728 
  2729     sockaddrPtr->sin_addr.s_addr = addr.s_addr;
  2730     return 1;	/* Success. */
  2731 }
  2732 
  2733 /*
  2734  *----------------------------------------------------------------------
  2735  *
  2736  * Tcl_OpenTcpClient --
  2737  *
  2738  *	Opens a TCP client socket and creates a channel around it.
  2739  *
  2740  * Results:
  2741  *	The channel or NULL if failed.	An error message is returned
  2742  *	in the interpreter on failure.
  2743  *
  2744  * Side effects:
  2745  *	Opens a client socket and creates a new channel.
  2746  *
  2747  *----------------------------------------------------------------------
  2748  */
  2749 
  2750 EXPORT_C Tcl_Channel
  2751 Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async)
  2752     Tcl_Interp *interp;			/* For error reporting; can be NULL. */
  2753     int port;				/* Port number to open. */
  2754     CONST char *host;			/* Host on which to open port. */
  2755     CONST char *myaddr;			/* Client-side address */
  2756     int myport;				/* Client-side port */
  2757     int async;				/* If nonzero, attempt to do an
  2758 					 * asynchronous connect. Otherwise
  2759 					 * we do a blocking connect. */
  2760 {
  2761     TcpState *statePtr;
  2762     char channelName[16 + TCL_INTEGER_SPACE];
  2763 
  2764     /*
  2765      * Create a new client socket and wrap it in a channel.
  2766      */
  2767 
  2768     statePtr = CreateSocket(interp, port, host, 0, myaddr, myport, async);
  2769     if (statePtr == NULL) {
  2770 	return NULL;
  2771     }
  2772 
  2773     statePtr->acceptProc = NULL;
  2774     statePtr->acceptProcData = (ClientData) NULL;
  2775 
  2776     sprintf(channelName, "sock%d", statePtr->fd);
  2777 
  2778     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
  2779 	    (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE));
  2780     if (Tcl_SetChannelOption(interp, statePtr->channel, "-translation",
  2781 	    "auto crlf") == TCL_ERROR) {
  2782 	Tcl_Close((Tcl_Interp *) NULL, statePtr->channel);
  2783 	return NULL;
  2784     }
  2785     return statePtr->channel;
  2786 }
  2787 
  2788 /*
  2789  *----------------------------------------------------------------------
  2790  *
  2791  * Tcl_MakeTcpClientChannel --
  2792  *
  2793  *	Creates a Tcl_Channel from an existing client TCP socket.
  2794  *
  2795  * Results:
  2796  *	The Tcl_Channel wrapped around the preexisting TCP socket.
  2797  *
  2798  * Side effects:
  2799  *	None.
  2800  *
  2801  *----------------------------------------------------------------------
  2802  */
  2803 
  2804 EXPORT_C Tcl_Channel
  2805 Tcl_MakeTcpClientChannel(sock)
  2806     ClientData sock;		/* The socket to wrap up into a channel. */
  2807 {
  2808     return MakeTcpClientChannelMode(sock, (TCL_READABLE | TCL_WRITABLE));
  2809 }
  2810 
  2811 /*
  2812  *----------------------------------------------------------------------
  2813  *
  2814  * MakeTcpClientChannelMode --
  2815  *
  2816  *	Creates a Tcl_Channel from an existing client TCP socket
  2817  *	with given mode.
  2818  *
  2819  * Results:
  2820  *	The Tcl_Channel wrapped around the preexisting TCP socket.
  2821  *
  2822  * Side effects:
  2823  *	None.
  2824  *
  2825  *----------------------------------------------------------------------
  2826  */
  2827 
  2828 static Tcl_Channel
  2829 MakeTcpClientChannelMode(sock, mode)
  2830     ClientData sock;		/* The socket to wrap up into a channel. */
  2831     int mode;			/* ORed combination of TCL_READABLE and
  2832 				 * TCL_WRITABLE to indicate file mode. */
  2833 {
  2834     TcpState *statePtr;
  2835     char channelName[16 + TCL_INTEGER_SPACE];
  2836 
  2837     statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
  2838     statePtr->fd = (int) sock;
  2839     statePtr->flags = 0;
  2840     statePtr->acceptProc = NULL;
  2841     statePtr->acceptProcData = (ClientData) NULL;
  2842 
  2843     sprintf(channelName, "sock%d", statePtr->fd);
  2844 
  2845     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
  2846 	    (ClientData) statePtr, mode);
  2847     if (Tcl_SetChannelOption((Tcl_Interp *) NULL, statePtr->channel,
  2848 	    "-translation", "auto crlf") == TCL_ERROR) {
  2849 	Tcl_Close((Tcl_Interp *) NULL, statePtr->channel);
  2850 	return NULL;
  2851     }
  2852     return statePtr->channel;
  2853 }
  2854 
  2855 /*
  2856  *----------------------------------------------------------------------
  2857  *
  2858  * Tcl_OpenTcpServer --
  2859  *
  2860  *	Opens a TCP server socket and creates a channel around it.
  2861  *
  2862  * Results:
  2863  *	The channel or NULL if failed. If an error occurred, an
  2864  *	error message is left in the interp's result if interp is
  2865  *	not NULL.
  2866  *
  2867  * Side effects:
  2868  *	Opens a server socket and creates a new channel.
  2869  *
  2870  *----------------------------------------------------------------------
  2871  */
  2872 
  2873 EXPORT_C Tcl_Channel
  2874 Tcl_OpenTcpServer(interp, port, myHost, acceptProc, acceptProcData)
  2875     Tcl_Interp *interp;			/* For error reporting - may be
  2876 					 * NULL. */
  2877     int port;				/* Port number to open. */
  2878     CONST char *myHost;			/* Name of local host. */
  2879     Tcl_TcpAcceptProc *acceptProc;	/* Callback for accepting connections
  2880 					 * from new clients. */
  2881     ClientData acceptProcData;		/* Data for the callback. */
  2882 {
  2883     TcpState *statePtr;
  2884     char channelName[16 + TCL_INTEGER_SPACE];
  2885 
  2886     /*
  2887      * Create a new client socket and wrap it in a channel.
  2888      */
  2889 
  2890     statePtr = CreateSocket(interp, port, myHost, 1, NULL, 0, 0);
  2891     if (statePtr == NULL) {
  2892 	return NULL;
  2893     }
  2894 
  2895     statePtr->acceptProc = acceptProc;
  2896     statePtr->acceptProcData = acceptProcData;
  2897 
  2898     /*
  2899      * Set up the callback mechanism for accepting connections
  2900      * from new clients.
  2901      */
  2902 
  2903     Tcl_CreateFileHandler(statePtr->fd, TCL_READABLE, TcpAccept,
  2904 	    (ClientData) statePtr);
  2905     sprintf(channelName, "sock%d", statePtr->fd);
  2906     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
  2907 	    (ClientData) statePtr, 0);
  2908     return statePtr->channel;
  2909 }
  2910 
  2911 /*
  2912  *----------------------------------------------------------------------
  2913  *
  2914  * TcpAccept --
  2915  *	Accept a TCP socket connection.	 This is called by the event loop.
  2916  *
  2917  * Results:
  2918  *	None.
  2919  *
  2920  * Side effects:
  2921  *	Creates a new connection socket. Calls the registered callback
  2922  *	for the connection acceptance mechanism.
  2923  *
  2924  *----------------------------------------------------------------------
  2925  */
  2926 
  2927 	/* ARGSUSED */
  2928 static void
  2929 TcpAccept(data, mask)
  2930     ClientData data;			/* Callback token. */
  2931     int mask;				/* Not used. */
  2932 {
  2933     TcpState *sockState;		/* Client data of server socket. */
  2934     int newsock;			/* The new client socket */
  2935     TcpState *newSockState;		/* State for new socket. */
  2936     struct sockaddr_in addr;		/* The remote address */
  2937     socklen_t len;				/* For accept interface */
  2938     char channelName[16 + TCL_INTEGER_SPACE];
  2939 
  2940     sockState = (TcpState *) data;
  2941 
  2942     len = sizeof(struct sockaddr_in);
  2943     newsock = accept(sockState->fd, (struct sockaddr *) &addr, &len);
  2944     if (newsock < 0) {
  2945 	return;
  2946     }
  2947 
  2948     /*
  2949      * Set close-on-exec flag to prevent the newly accepted socket from
  2950      * being inherited by child processes.
  2951      */
  2952 
  2953     (void) fcntl(newsock, F_SETFD, FD_CLOEXEC);
  2954 
  2955     newSockState = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
  2956 
  2957     newSockState->flags = 0;
  2958     newSockState->fd = newsock;
  2959     newSockState->acceptProc = NULL;
  2960     newSockState->acceptProcData = NULL;
  2961 
  2962     sprintf(channelName, "sock%d", newsock);
  2963     newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
  2964 	    (ClientData) newSockState, (TCL_READABLE | TCL_WRITABLE));
  2965 
  2966     Tcl_SetChannelOption(NULL, newSockState->channel, "-translation",
  2967 	    "auto crlf");
  2968 
  2969     if (sockState->acceptProc != NULL) {
  2970 	(*sockState->acceptProc)(sockState->acceptProcData,
  2971 		newSockState->channel, inet_ntoa(addr.sin_addr),
  2972 		ntohs(addr.sin_port));
  2973     }
  2974 }
  2975 
  2976 /*
  2977  *----------------------------------------------------------------------
  2978  *
  2979  * TclpGetDefaultStdChannel --
  2980  *
  2981  *	Creates channels for standard input, standard output or standard
  2982  *	error output if they do not already exist.
  2983  *
  2984  * Results:
  2985  *	Returns the specified default standard channel, or NULL.
  2986  *
  2987  * Side effects:
  2988  *	May cause the creation of a standard channel and the underlying
  2989  *	file.
  2990  *
  2991  *----------------------------------------------------------------------
  2992  */
  2993 
  2994 Tcl_Channel
  2995 TclpGetDefaultStdChannel(type)
  2996     int type;			/* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
  2997 {
  2998     Tcl_Channel channel = NULL;
  2999     int fd = 0;			/* Initializations needed to prevent */
  3000     int mode = 0;		/* compiler warning (used before set). */
  3001     char *bufMode = NULL;
  3002 
  3003     /*
  3004      * Some #def's to make the code a little clearer!
  3005      */
  3006 #define ZERO_OFFSET	((Tcl_SeekOffset) 0)
  3007 #define ERROR_OFFSET	((Tcl_SeekOffset) -1)
  3008 
  3009     switch (type) {
  3010 	case TCL_STDIN:
  3011 	    if ((TclOSseek(0, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
  3012 		    && (errno == EBADF)) {
  3013 		return (Tcl_Channel) NULL;
  3014 	    }
  3015 	    fd = 0;
  3016 	    mode = TCL_READABLE;
  3017 	    bufMode = "line";
  3018 	    break;
  3019 	case TCL_STDOUT:
  3020 	    if ((TclOSseek(1, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
  3021 		    && (errno == EBADF)) {
  3022 		return (Tcl_Channel) NULL;
  3023 	    }
  3024 	    fd = 1;
  3025 	    mode = TCL_WRITABLE;
  3026 	    bufMode = "line";
  3027 	    break;
  3028 	case TCL_STDERR:
  3029 	    if ((TclOSseek(2, ZERO_OFFSET, SEEK_CUR) == ERROR_OFFSET)
  3030 		    && (errno == EBADF)) {
  3031 		return (Tcl_Channel) NULL;
  3032 	    }
  3033 	    fd = 2;
  3034 	    mode = TCL_WRITABLE;
  3035 	    bufMode = "none";
  3036 	    break;
  3037 	default:
  3038 	    panic("TclGetDefaultStdChannel: Unexpected channel type");
  3039 	    break;
  3040     }
  3041 
  3042 #undef ZERO_OFFSET
  3043 #undef ERROR_OFFSET
  3044 
  3045     channel = Tcl_MakeFileChannel((ClientData) fd, mode);
  3046     if (channel == NULL) {
  3047 	return NULL;
  3048     }
  3049 
  3050     /*
  3051      * Set up the normal channel options for stdio handles.
  3052      */
  3053 
  3054     if (Tcl_GetChannelType(channel) == &fileChannelType) {
  3055 	Tcl_SetChannelOption(NULL, channel, "-translation", "auto");
  3056     } else {
  3057 	Tcl_SetChannelOption(NULL, channel, "-translation", "auto crlf");
  3058     }
  3059     Tcl_SetChannelOption(NULL, channel, "-buffering", bufMode);
  3060     return channel;
  3061 }
  3062 
  3063 /*
  3064  *----------------------------------------------------------------------
  3065  *
  3066  * Tcl_GetOpenFile --
  3067  *
  3068  *	Given a name of a channel registered in the given interpreter,
  3069  *	returns a FILE * for it.
  3070  *
  3071  * Results:
  3072  *	A standard Tcl result. If the channel is registered in the given
  3073  *	interpreter and it is managed by the "file" channel driver, and
  3074  *	it is open for the requested mode, then the output parameter
  3075  *	filePtr is set to a FILE * for the underlying file. On error, the
  3076  *	filePtr is not set, TCL_ERROR is returned and an error message is
  3077  *	left in the interp's result.
  3078  *
  3079  * Side effects:
  3080  *	May invoke fdopen to create the FILE * for the requested file.
  3081  *
  3082  *----------------------------------------------------------------------
  3083  */
  3084 
  3085 EXPORT_C int
  3086 Tcl_GetOpenFile(interp, string, forWriting, checkUsage, filePtr)
  3087     Tcl_Interp *interp;		/* Interpreter in which to find file. */
  3088     CONST char *string;		/* String that identifies file. */
  3089     int forWriting;		/* 1 means the file is going to be used
  3090 				 * for writing, 0 means for reading. */
  3091     int checkUsage;		/* 1 means verify that the file was opened
  3092 				 * in a mode that allows the access specified
  3093 				 * by "forWriting". Ignored, we always
  3094 				 * check that the channel is open for the
  3095 				 * requested mode. */
  3096     ClientData *filePtr;	/* Store pointer to FILE structure here. */
  3097 {
  3098     Tcl_Channel chan;
  3099     int chanMode;
  3100     Tcl_ChannelType *chanTypePtr;
  3101     ClientData data;
  3102     int fd;
  3103     FILE *f;
  3104 
  3105     chan = Tcl_GetChannel(interp, string, &chanMode);
  3106     if (chan == (Tcl_Channel) NULL) {
  3107 	return TCL_ERROR;
  3108     }
  3109     if ((forWriting) && ((chanMode & TCL_WRITABLE) == 0)) {
  3110 	Tcl_AppendResult(interp,
  3111 		"\"", string, "\" wasn't opened for writing", (char *) NULL);
  3112 	return TCL_ERROR;
  3113     } else if ((!(forWriting)) && ((chanMode & TCL_READABLE) == 0)) {
  3114 	Tcl_AppendResult(interp,
  3115 		"\"", string, "\" wasn't opened for reading", (char *) NULL);
  3116 	return TCL_ERROR;
  3117     }
  3118 
  3119     /*
  3120      * We allow creating a FILE * out of file based, pipe based and socket
  3121      * based channels. We currently do not allow any other channel types,
  3122      * because it is likely that stdio will not know what to do with them.
  3123      */
  3124 
  3125     chanTypePtr = Tcl_GetChannelType(chan);
  3126     if ((chanTypePtr == &fileChannelType)
  3127 #ifdef SUPPORTS_TTY
  3128 	    || (chanTypePtr == &ttyChannelType)
  3129 #endif /* SUPPORTS_TTY */
  3130 	    || (chanTypePtr == &tcpChannelType)
  3131 	    || (strcmp(chanTypePtr->typeName, "pipe") == 0)) {
  3132 	if (Tcl_GetChannelHandle(chan,
  3133 		(forWriting ? TCL_WRITABLE : TCL_READABLE),
  3134 		(ClientData*) &data) == TCL_OK) {
  3135 	    fd = (int) data;
  3136 
  3137 	    /*
  3138 	     * The call to fdopen below is probably dangerous, since it will
  3139 	     * truncate an existing file if the file is being opened
  3140 	     * for writing....
  3141 	     */
  3142 
  3143 	    f = fdopen(fd, (forWriting ? "w" : "r"));
  3144 	    if (f == NULL) {
  3145 		Tcl_AppendResult(interp, "cannot get a FILE * for \"", string,
  3146 			"\"", (char *) NULL);
  3147 		return TCL_ERROR;
  3148 	    }
  3149 	    *filePtr = (ClientData) f;
  3150 	    return TCL_OK;
  3151 	}
  3152     }
  3153 
  3154     Tcl_AppendResult(interp, "\"", string,
  3155 	    "\" cannot be used to get a FILE *", (char *) NULL);
  3156     return TCL_ERROR;	     
  3157 }
  3158 
  3159 /*
  3160  *----------------------------------------------------------------------
  3161  *
  3162  * TclUnixWaitForFile --
  3163  *
  3164  *	This procedure waits synchronously for a file to become readable
  3165  *	or writable, with an optional timeout.
  3166  *
  3167  * Results:
  3168  *	The return value is an OR'ed combination of TCL_READABLE,
  3169  *	TCL_WRITABLE, and TCL_EXCEPTION, indicating the conditions
  3170  *	that are present on file at the time of the return.  This
  3171  *	procedure will not return until either "timeout" milliseconds
  3172  *	have elapsed or at least one of the conditions given by mask
  3173  *	has occurred for file (a return value of 0 means that a timeout
  3174  *	occurred).  No normal events will be serviced during the
  3175  *	execution of this procedure.
  3176  *
  3177  * Side effects:
  3178  *	Time passes.
  3179  *
  3180  *----------------------------------------------------------------------
  3181  */
  3182 
  3183 int
  3184 TclUnixWaitForFile(fd, mask, timeout)
  3185     int fd;			/* Handle for file on which to wait. */
  3186     int mask;			/* What to wait for: OR'ed combination of
  3187 				 * TCL_READABLE, TCL_WRITABLE, and
  3188 				 * TCL_EXCEPTION. */
  3189     int timeout;		/* Maximum amount of time to wait for one
  3190 				 * of the conditions in mask to occur, in
  3191 				 * milliseconds.  A value of 0 means don't
  3192 				 * wait at all, and a value of -1 means
  3193 				 * wait forever. */
  3194 {
  3195     Tcl_Time abortTime = {0, 0}, now; /* silence gcc 4 warning */
  3196     struct timeval blockTime, *timeoutPtr;
  3197     int index, numFound, result = 0;
  3198     fd_mask bit;
  3199     fd_mask readyMasks[3*MASK_SIZE];
  3200 				/* This array reflects the readable/writable
  3201 				 * conditions that were found to exist by the
  3202 				 * last call to select. */
  3203 
  3204     /*
  3205      * If there is a non-zero finite timeout, compute the time when
  3206      * we give up.
  3207      */
  3208 
  3209     if (timeout > 0) {
  3210 	Tcl_GetTime(&now);
  3211 	abortTime.sec = now.sec + timeout/1000;
  3212 	abortTime.usec = now.usec + (timeout%1000)*1000;
  3213 	if (abortTime.usec >= 1000000) {
  3214 	    abortTime.usec -= 1000000;
  3215 	    abortTime.sec += 1;
  3216 	}
  3217 	timeoutPtr = &blockTime;
  3218     } else if (timeout == 0) {
  3219 	timeoutPtr = &blockTime;
  3220 	blockTime.tv_sec = 0;
  3221 	blockTime.tv_usec = 0;
  3222     } else {
  3223 	timeoutPtr = NULL;
  3224     }
  3225 
  3226     /*
  3227      * Initialize the ready masks and compute the mask offsets.
  3228      */
  3229 
  3230     if (fd >= FD_SETSIZE) {
  3231 	panic("TclWaitForFile can't handle file id %d", fd);
  3232     }
  3233     memset((VOID *) readyMasks, 0, 3*MASK_SIZE*sizeof(fd_mask));
  3234     index = fd/(NBBY*sizeof(fd_mask));
  3235     bit = ((fd_mask) 1) << (fd%(NBBY*sizeof(fd_mask)));
  3236 
  3237     /*
  3238      * Loop in a mini-event loop of our own, waiting for either the
  3239      * file to become ready or a timeout to occur.
  3240      */
  3241 
  3242     while (1) {
  3243 	if (timeout > 0) {
  3244 	    blockTime.tv_sec = abortTime.sec - now.sec;
  3245 	    blockTime.tv_usec = abortTime.usec - now.usec;
  3246 	    if (blockTime.tv_usec < 0) {
  3247 		blockTime.tv_sec -= 1;
  3248 		blockTime.tv_usec += 1000000;
  3249 	    }
  3250 	    if (blockTime.tv_sec < 0) {
  3251 		blockTime.tv_sec = 0;
  3252 		blockTime.tv_usec = 0;
  3253 	    }
  3254 	}
  3255 
  3256 	/*
  3257 	 * Set the appropriate bit in the ready masks for the fd.
  3258 	 */
  3259 
  3260 	if (mask & TCL_READABLE) {
  3261 	    readyMasks[index] |= bit;
  3262 	}
  3263 	if (mask & TCL_WRITABLE) {
  3264 	    (readyMasks+MASK_SIZE)[index] |= bit;
  3265 	}
  3266 	if (mask & TCL_EXCEPTION) {
  3267 	    (readyMasks+2*(MASK_SIZE))[index] |= bit;
  3268 	}
  3269 
  3270 	/*
  3271 	 * Wait for the event or a timeout.
  3272 	 */
  3273 
  3274 	numFound = select(fd+1, (SELECT_MASK *) &readyMasks[0],
  3275 		(SELECT_MASK *) &readyMasks[MASK_SIZE],
  3276 		(SELECT_MASK *) &readyMasks[2*MASK_SIZE], timeoutPtr);
  3277 	if (numFound == 1) {
  3278 	    if (readyMasks[index] & bit) {
  3279 		result |= TCL_READABLE;
  3280 	    }
  3281 	    if ((readyMasks+MASK_SIZE)[index] & bit) {
  3282 		result |= TCL_WRITABLE;
  3283 	    }
  3284 	    if ((readyMasks+2*(MASK_SIZE))[index] & bit) {
  3285 		result |= TCL_EXCEPTION;
  3286 	    }
  3287 	    result &= mask;
  3288 	    if (result) {
  3289 		break;
  3290 	    }
  3291 	}
  3292 	if (timeout == 0) {
  3293 	    break;
  3294 	}
  3295 	if (timeout < 0) {
  3296 	    continue;
  3297 	}
  3298 
  3299 	/*
  3300 	 * The select returned early, so we need to recompute the timeout.
  3301 	 */
  3302 
  3303 	Tcl_GetTime(&now);
  3304 	if ((abortTime.sec < now.sec)
  3305 		|| ((abortTime.sec == now.sec)
  3306 		&& (abortTime.usec <= now.usec))) {
  3307 	    break;
  3308 	}
  3309     }
  3310     return result;
  3311 }
  3312 
  3313 #ifdef DEPRECATED
  3314 /*
  3315  *----------------------------------------------------------------------
  3316  *
  3317  * FileThreadActionProc --
  3318  *
  3319  *	Insert or remove any thread local refs to this channel.
  3320  *
  3321  * Results:
  3322  *	None.
  3323  *
  3324  * Side effects:
  3325  *	Changes thread local list of valid channels.
  3326  *
  3327  *----------------------------------------------------------------------
  3328  */
  3329 
  3330 static void
  3331 FileThreadActionProc (instanceData, action)
  3332      ClientData instanceData;
  3333      int action;
  3334 {
  3335     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
  3336     FileState *fsPtr = (FileState *) instanceData;
  3337 
  3338     if (action == TCL_CHANNEL_THREAD_INSERT) {
  3339         fsPtr->nextPtr       = tsdPtr->firstFilePtr;
  3340 	tsdPtr->firstFilePtr = fsPtr;
  3341     } else {
  3342         FileState **nextPtrPtr;
  3343 	int removed = 0;
  3344 
  3345 	for (nextPtrPtr = &(tsdPtr->firstFilePtr); (*nextPtrPtr) != NULL;
  3346 	     nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
  3347 	    if ((*nextPtrPtr) == fsPtr) {
  3348 	        (*nextPtrPtr) = fsPtr->nextPtr;
  3349 		removed = 1;
  3350 		break;
  3351 	    }
  3352 	}
  3353 
  3354 	/*
  3355 	 * This could happen if the channel was created in one
  3356 	 * thread and then moved to another without updating
  3357 	 * the thread local data in each thread.
  3358 	 */
  3359 
  3360 	if (!removed) {
  3361 	  panic("file info ptr not on thread channel list");
  3362 	}
  3363     }
  3364 }
  3365 #endif /* DEPRECATED */
  3366