Debian Codegraph @

pTk/mTk/tclUnix/tclUnixChan.c

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