Debian Codegraph @

pTk/mTk/tclGeneric/tclIO.c

raw symbols SCIP
1 /*
2 * tclIO.c --
3 *
4 * This file provides the generic portions (those that are the same on
5 * all platforms and for all channel types) of Tcl's IO facilities.
6 *
7 * Copyright (c) 1998-2000 Ajuba Solutions
8 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
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: tclIO.c,v 1.61.2.2 2003/04/11 17:35:33 andreas_kupries Exp $
14 */
15
16 #include "tclInt.h"
17 #include "tclPort.h"
18 #include "tclIO.h"
19 #include <assert.h>
20
21
22 /*
23 * All static variables used in this file are collected into a single
24 * instance of the following structure. For multi-threaded implementations,
25 * there is one instance of this structure for each thread.
26 *
27 * Notice that different structures with the same name appear in other
28 * files. The structure defined below is used in this file only.
29 */
30
31 typedef struct ThreadSpecificData {
32
33 /*
34 * This variable holds the list of nested ChannelHandlerEventProc
35 * invocations.
36 */
37 NextChannelHandler *nestedHandlerPtr;
38
39 /*
40 * List of all channels currently open, indexed by ChannelState,
41 * as only one ChannelState exists per set of stacked channels.
42 */
43 ChannelState *firstCSPtr;
44 #ifdef oldcode
45 /*
46 * Has a channel exit handler been created yet?
47 */
48 int channelExitHandlerCreated;
49
50 /*
51 * Has the channel event source been created and registered with the
52 * notifier?
53 */
54 int channelEventSourceCreated;
55 #endif
56 /*
57 * Static variables to hold channels for stdin, stdout and stderr.
58 */
59 Tcl_Channel stdinChannel;
60 int stdinInitialized;
61 Tcl_Channel stdoutChannel;
62 int stdoutInitialized;
63 Tcl_Channel stderrChannel;
64 int stderrInitialized;
65
66 } ThreadSpecificData;
67
68 static Tcl_ThreadDataKey dataKey;
69
70 /*
71 * Static functions in this file:
72 */
73
74 static ChannelBuffer * AllocChannelBuffer _ANSI_ARGS_((int length));
75 static void ChannelTimerProc _ANSI_ARGS_((
76 ClientData clientData));
77 static int CheckChannelErrors _ANSI_ARGS_((ChannelState *statePtr,
78 int direction));
79 static int CheckFlush _ANSI_ARGS_((Channel *chanPtr,
80 ChannelBuffer *bufPtr, int newlineFlag));
81 static int CheckForDeadChannel _ANSI_ARGS_((Tcl_Interp *interp,
82 ChannelState *statePtr));
83 static void CheckForStdChannelsBeingClosed _ANSI_ARGS_((
84 Tcl_Channel chan));
85 static void CleanupChannelHandlers _ANSI_ARGS_((
86 Tcl_Interp *interp, Channel *chanPtr));
87 static int CloseChannel _ANSI_ARGS_((Tcl_Interp *interp,
88 Channel *chanPtr, int errorCode));
89 static void CommonGetsCleanup _ANSI_ARGS_((Channel *chanPtr,
90 Tcl_Encoding encoding));
91 static int CopyAndTranslateBuffer _ANSI_ARGS_((
92 ChannelState *statePtr, char *result,
93 int space));
94 static int CopyBuffer _ANSI_ARGS_((
95 Channel *chanPtr, char *result, int space));
96 static int CopyData _ANSI_ARGS_((CopyState *csPtr, int mask));
97 static void CopyEventProc _ANSI_ARGS_((ClientData clientData,
98 int mask));
99 static void CreateScriptRecord _ANSI_ARGS_((
100 Tcl_Interp *interp, Channel *chanPtr,
101 int mask, Tcl_Obj *scriptPtr));
102 static void DeleteChannelTable _ANSI_ARGS_((
103 ClientData clientData, Tcl_Interp *interp));
104 static void DeleteScriptRecord _ANSI_ARGS_((Tcl_Interp *interp,
105 Channel *chanPtr, int mask));
106 static int DetachChannel _ANSI_ARGS_((Tcl_Interp *interp,
107 Tcl_Channel chan));
108 static void DiscardInputQueued _ANSI_ARGS_((ChannelState *statePtr,
109 int discardSavedBuffers));
110 static void DiscardOutputQueued _ANSI_ARGS_((
111 ChannelState *chanPtr));
112 static int DoRead _ANSI_ARGS_((Channel *chanPtr, char *srcPtr,
113 int slen));
114 static int DoWrite _ANSI_ARGS_((Channel *chanPtr, CONST char *src,
115 int srcLen));
116 static int DoReadChars _ANSI_ARGS_ ((Channel* chan,
117 Tcl_Obj* objPtr, int toRead, int appendFlag));
118 static int DoWriteChars _ANSI_ARGS_ ((Channel* chan,
119 CONST char* src, int len));
120 static int FilterInputBytes _ANSI_ARGS_((Channel *chanPtr,
121 GetsState *statePtr));
122 static int FlushChannel _ANSI_ARGS_((Tcl_Interp *interp,
123 Channel *chanPtr, int calledFromAsyncFlush));
124 static Tcl_HashTable * GetChannelTable _ANSI_ARGS_((Tcl_Interp *interp));
125 static int GetInput _ANSI_ARGS_((Channel *chanPtr));
126 static int HaveVersion _ANSI_ARGS_((Tcl_ChannelType *typePtr,
127 Tcl_ChannelTypeVersion minimumVersion));
128 static void PeekAhead _ANSI_ARGS_((Channel *chanPtr,
129 char **dstEndPtr, GetsState *gsPtr));
130 static int ReadBytes _ANSI_ARGS_((ChannelState *statePtr,
131 Tcl_Obj *objPtr, int charsLeft,
132 int *offsetPtr));
133 static int ReadChars _ANSI_ARGS_((ChannelState *statePtr,
134 Tcl_Obj *objPtr, int charsLeft,
135 int *offsetPtr, int *factorPtr));
136 static void RecycleBuffer _ANSI_ARGS_((ChannelState *statePtr,
137 ChannelBuffer *bufPtr, int mustDiscard));
138 static int StackSetBlockMode _ANSI_ARGS_((Channel *chanPtr,
139 int mode));
140 static int SetBlockMode _ANSI_ARGS_((Tcl_Interp *interp,
141 Channel *chanPtr, int mode));
142 static void StopCopy _ANSI_ARGS_((CopyState *csPtr));
143 static int TranslateInputEOL _ANSI_ARGS_((ChannelState *statePtr,
144 char *dst, CONST char *src,
145 int *dstLenPtr, int *srcLenPtr));
146 static int TranslateOutputEOL _ANSI_ARGS_((ChannelState *statePtr,
147 char *dst, CONST char *src,
148 int *dstLenPtr, int *srcLenPtr));
149 static void UpdateInterest _ANSI_ARGS_((Channel *chanPtr));
150 static int WriteBytes _ANSI_ARGS_((Channel *chanPtr,
151 CONST char *src, int srcLen));
152 static int WriteChars _ANSI_ARGS_((Channel *chanPtr,
153 CONST char *src, int srcLen));
154
155
156 /*
157 *---------------------------------------------------------------------------
158 *
159 * TclInitIOSubsystem --
160 *
161 * Initialize all resources used by this subsystem on a per-process
162 * basis.
163 *
164 * Results:
165 * None.
166 *
167 * Side effects:
168 * Depends on the memory subsystems.
169 *
170 *---------------------------------------------------------------------------
171 */
172
173 void
174 TclInitIOSubsystem()
175 {
176 /*
177 * By fetching thread local storage we take care of
178 * allocating it for each thread.
179 */
180 (void) TCL_TSD_INIT(&dataKey);
181 }
182
183 /*
184 *-------------------------------------------------------------------------
185 *
186 * TclFinalizeIOSubsystem --
187 *
188 * Releases all resources used by this subsystem on a per-process
189 * basis. Closes all extant channels that have not already been
190 * closed because they were not owned by any interp.
191 *
192 * Results:
193 * None.
194 *
195 * Side effects:
196 * Depends on encoding and memory subsystems.
197 *
198 *-------------------------------------------------------------------------
199 */
200
201 /* ARGSUSED */
202 void
203 TclFinalizeIOSubsystem()
204 {
205 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
206 Channel *chanPtr; /* Iterates over open channels. */
207 ChannelState *nextCSPtr; /* Iterates over open channels. */
208 ChannelState *statePtr; /* state of channel stack */
209
210 for (statePtr = tsdPtr->firstCSPtr; statePtr != (ChannelState *) NULL;
211 statePtr = nextCSPtr) {
212 chanPtr = statePtr->topChanPtr;
213 nextCSPtr = statePtr->nextCSPtr;
214
215 /*
216 * Set the channel back into blocking mode to ensure that we wait
217 * for all data to flush out.
218 */
219
220 (void) Tcl_SetChannelOption(NULL, (Tcl_Channel) chanPtr,
221 "-blocking", "on");
222
223 if ((chanPtr == (Channel *) tsdPtr->stdinChannel) ||
224 (chanPtr == (Channel *) tsdPtr->stdoutChannel) ||
225 (chanPtr == (Channel *) tsdPtr->stderrChannel)) {
226
227 /*
228 * Decrement the refcount which was earlier artificially bumped
229 * up to keep the channel from being closed.
230 */
231
232 statePtr->refCount--;
233 }
234
235 if (statePtr->refCount <= 0) {
236
237 /*
238 * Close it only if the refcount indicates that the channel is not
239 * referenced from any interpreter. If it is, that interpreter will
240 * close the channel when it gets destroyed.
241 */
242
243 (void) Tcl_Close((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);
244
245 } else {
246
247 /*
248 * The refcount is greater than zero, so flush the channel.
249 */
250
251 Tcl_Flush((Tcl_Channel) chanPtr);
252
253 /*
254 * Call the device driver to actually close the underlying
255 * device for this channel.
256 */
257
258 if (chanPtr->typePtr->closeProc != TCL_CLOSE2PROC) {
259 (chanPtr->typePtr->closeProc)(chanPtr->instanceData,
260 (Tcl_Interp *) NULL);
261 } else {
262 (chanPtr->typePtr->close2Proc)(chanPtr->instanceData,
263 (Tcl_Interp *) NULL, 0);
264 }
265
266 /*
267 * Finally, we clean up the fields in the channel data structure
268 * since all of them have been deleted already. We mark the
269 * channel with CHANNEL_DEAD to prevent any further IO operations
270 * on it.
271 */
272
273 chanPtr->instanceData = (ClientData) NULL;
274 statePtr->flags |= CHANNEL_DEAD;
275 }
276 }
277 }
278
279
280 /*
281 *----------------------------------------------------------------------
282 *
283 * Tcl_SetStdChannel --
284 *
285 * This function is used to change the channels that are used
286 * for stdin/stdout/stderr in new interpreters.
287 *
288 * Results:
289 * None
290 *
291 * Side effects:
292 * None.
293 *
294 *----------------------------------------------------------------------
295 */
296
297 void
298 Tcl_SetStdChannel(channel, type)
299 Tcl_Channel channel;
300 int type; /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
301 {
302 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
303 switch (type) {
304 case TCL_STDIN:
305 tsdPtr->stdinInitialized = 1;
306 tsdPtr->stdinChannel = channel;
307 break;
308 case TCL_STDOUT:
309 tsdPtr->stdoutInitialized = 1;
310 tsdPtr->stdoutChannel = channel;
311 break;
312 case TCL_STDERR:
313 tsdPtr->stderrInitialized = 1;
314 tsdPtr->stderrChannel = channel;
315 break;
316 }
317 }
318
319 /*
320 *----------------------------------------------------------------------
321 *
322 * Tcl_GetStdChannel --
323 *
324 * Returns the specified standard channel.
325 *
326 * Results:
327 * Returns the specified standard channel, or NULL.
328 *
329 * Side effects:
330 * May cause the creation of a standard channel and the underlying
331 * file.
332 *
333 *----------------------------------------------------------------------
334 */
335 Tcl_Channel
336 Tcl_GetStdChannel(type)
337 int type; /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
338 {
339 Tcl_Channel channel = NULL;
340 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
341
342 /*
343 * If the channels were not created yet, create them now and
344 * store them in the static variables.
345 */
346
347 switch (type) {
348 case TCL_STDIN:
349 if (!tsdPtr->stdinInitialized) {
350 tsdPtr->stdinChannel = TclpGetDefaultStdChannel(TCL_STDIN);
351 tsdPtr->stdinInitialized = 1;
352
353 /*
354 * Artificially bump the refcount to ensure that the channel
355 * is only closed on exit.
356 *
357 * NOTE: Must only do this if stdinChannel is not NULL. It
358 * can be NULL in situations where Tcl is unable to connect
359 * to the standard input.
360 */
361
362 if (tsdPtr->stdinChannel != (Tcl_Channel) NULL) {
363 (void) Tcl_RegisterChannel((Tcl_Interp *) NULL,
364 tsdPtr->stdinChannel);
365 }
366 }
367 channel = tsdPtr->stdinChannel;
368 break;
369 case TCL_STDOUT:
370 if (!tsdPtr->stdoutInitialized) {
371 tsdPtr->stdoutChannel = TclpGetDefaultStdChannel(TCL_STDOUT);
372 tsdPtr->stdoutInitialized = 1;
373 if (tsdPtr->stdoutChannel != (Tcl_Channel) NULL) {
374 (void) Tcl_RegisterChannel((Tcl_Interp *) NULL,
375 tsdPtr->stdoutChannel);
376 }
377 }
378 channel = tsdPtr->stdoutChannel;
379 break;
380 case TCL_STDERR:
381 if (!tsdPtr->stderrInitialized) {
382 tsdPtr->stderrChannel = TclpGetDefaultStdChannel(TCL_STDERR);
383 tsdPtr->stderrInitialized = 1;
384 if (tsdPtr->stderrChannel != (Tcl_Channel) NULL) {
385 (void) Tcl_RegisterChannel((Tcl_Interp *) NULL,
386 tsdPtr->stderrChannel);
387 }
388 }
389 channel = tsdPtr->stderrChannel;
390 break;
391 }
392 return channel;
393 }
394
395
396 /*
397 *----------------------------------------------------------------------
398 *
399 * Tcl_CreateCloseHandler
400 *
401 * Creates a close callback which will be called when the channel is
402 * closed.
403 *
404 * Results:
405 * None.
406 *
407 * Side effects:
408 * Causes the callback to be called in the future when the channel
409 * will be closed.
410 *
411 *----------------------------------------------------------------------
412 */
413
414 void
415 Tcl_CreateCloseHandler(chan, proc, clientData)
416 Tcl_Channel chan; /* The channel for which to create the
417 * close callback. */
418 Tcl_CloseProc *proc; /* The callback routine to call when the
419 * channel will be closed. */
420 ClientData clientData; /* Arbitrary data to pass to the
421 * close callback. */
422 {
423 ChannelState *statePtr;
424 CloseCallback *cbPtr;
425
426 statePtr = ((Channel *) chan)->state;
427
428 cbPtr = (CloseCallback *) ckalloc((unsigned) sizeof(CloseCallback));
429 cbPtr->proc = proc;
430 cbPtr->clientData = clientData;
431
432 cbPtr->nextPtr = statePtr->closeCbPtr;
433 statePtr->closeCbPtr = cbPtr;
434 }
435
436 /*
437 *----------------------------------------------------------------------
438 *
439 * Tcl_DeleteCloseHandler --
440 *
441 * Removes a callback that would have been called on closing
442 * the channel. If there is no matching callback then this
443 * function has no effect.
444 *
445 * Results:
446 * None.
447 *
448 * Side effects:
449 * The callback will not be called in the future when the channel
450 * is eventually closed.
451 *
452 *----------------------------------------------------------------------
453 */
454
455 void
456 Tcl_DeleteCloseHandler(chan, proc, clientData)
457 Tcl_Channel chan; /* The channel for which to cancel the
458 * close callback. */
459 Tcl_CloseProc *proc; /* The procedure for the callback to
460 * remove. */
461 ClientData clientData; /* The callback data for the callback
462 * to remove. */
463 {
464 ChannelState *statePtr;
465 CloseCallback *cbPtr, *cbPrevPtr;
466
467 statePtr = ((Channel *) chan)->state;
468 for (cbPtr = statePtr->closeCbPtr, cbPrevPtr = (CloseCallback *) NULL;
469 cbPtr != (CloseCallback *) NULL;
470 cbPtr = cbPtr->nextPtr) {
471 if ((cbPtr->proc == proc) && (cbPtr->clientData == clientData)) {
472 if (cbPrevPtr == (CloseCallback *) NULL) {
473 statePtr->closeCbPtr = cbPtr->nextPtr;
474 }
475 ckfree((char *) cbPtr);
476 break;
477 } else {
478 cbPrevPtr = cbPtr;
479 }
480 }
481 }
482
483 /*
484 *----------------------------------------------------------------------
485 *
486 * GetChannelTable --
487 *
488 * Gets and potentially initializes the channel table for an
489 * interpreter. If it is initializing the table it also inserts
490 * channels for stdin, stdout and stderr if the interpreter is
491 * trusted.
492 *
493 * Results:
494 * A pointer to the hash table created, for use by the caller.
495 *
496 * Side effects:
497 * Initializes the channel table for an interpreter. May create
498 * channels for stdin, stdout and stderr.
499 *
500 *----------------------------------------------------------------------
501 */
502
503 static Tcl_HashTable *
504 GetChannelTable(interp)
505 Tcl_Interp *interp;
506 {
507 Tcl_HashTable *hTblPtr; /* Hash table of channels. */
508 Tcl_Channel stdinChan, stdoutChan, stderrChan;
509
510 hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
511 if (hTblPtr == (Tcl_HashTable *) NULL) {
512 hTblPtr = (Tcl_HashTable *) ckalloc((unsigned) sizeof(Tcl_HashTable));
513 Tcl_InitHashTable(hTblPtr, TCL_STRING_KEYS);
514
515 (void) Tcl_SetAssocData(interp, "tclIO",
516 (Tcl_InterpDeleteProc *) DeleteChannelTable,
517 (ClientData) hTblPtr);
518
519 /*
520 * If the interpreter is trusted (not "safe"), insert channels
521 * for stdin, stdout and stderr (possibly creating them in the
522 * process).
523 */
524
525 if (Tcl_IsSafe(interp) == 0) {
526 stdinChan = Tcl_GetStdChannel(TCL_STDIN);
527 if (stdinChan != NULL) {
528 Tcl_RegisterChannel(interp, stdinChan);
529 }
530 stdoutChan = Tcl_GetStdChannel(TCL_STDOUT);
531 if (stdoutChan != NULL) {
532 Tcl_RegisterChannel(interp, stdoutChan);
533 }
534 stderrChan = Tcl_GetStdChannel(TCL_STDERR);
535 if (stderrChan != NULL) {
536 Tcl_RegisterChannel(interp, stderrChan);
537 }
538 }
539
540 }
541 return hTblPtr;
542 }
543
544 /*
545 *----------------------------------------------------------------------
546 *
547 * DeleteChannelTable --
548 *
549 * Deletes the channel table for an interpreter, closing any open
550 * channels whose refcount reaches zero. This procedure is invoked
551 * when an interpreter is deleted, via the AssocData cleanup
552 * mechanism.
553 *
554 * Results:
555 * None.
556 *
557 * Side effects:
558 * Deletes the hash table of channels. May close channels. May flush
559 * output on closed channels. Removes any channeEvent handlers that were
560 * registered in this interpreter.
561 *
562 *----------------------------------------------------------------------
563 */
564
565 static void
566 DeleteChannelTable(clientData, interp)
567 ClientData clientData; /* The per-interpreter data structure. */
568 Tcl_Interp *interp; /* The interpreter being deleted. */
569 {
570 Tcl_HashTable *hTblPtr; /* The hash table. */
571 Tcl_HashSearch hSearch; /* Search variable. */
572 Tcl_HashEntry *hPtr; /* Search variable. */
573 Channel *chanPtr; /* Channel being deleted. */
574 ChannelState *statePtr; /* State of Channel being deleted. */
575 EventScriptRecord *sPtr, *prevPtr, *nextPtr;
576 /* Variables to loop over all channel events
577 * registered, to delete the ones that refer
578 * to the interpreter being deleted. */
579
580 /*
581 * Delete all the registered channels - this will close channels whose
582 * refcount reaches zero.
583 */
584
585 hTblPtr = (Tcl_HashTable *) clientData;
586 for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
587 hPtr != (Tcl_HashEntry *) NULL;
588 hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch)) {
589
590 chanPtr = (Channel *) Tcl_GetHashValue(hPtr);
591 statePtr = chanPtr->state;
592
593 /*
594 * Remove any fileevents registered in this interpreter.
595 */
596
597 for (sPtr = statePtr->scriptRecordPtr,
598 prevPtr = (EventScriptRecord *) NULL;
599 sPtr != (EventScriptRecord *) NULL;
600 sPtr = nextPtr) {
601 nextPtr = sPtr->nextPtr;
602 if (sPtr->interp == interp) {
603 if (prevPtr == (EventScriptRecord *) NULL) {
604 statePtr->scriptRecordPtr = nextPtr;
605 } else {
606 prevPtr->nextPtr = nextPtr;
607 }
608
609 Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
610 TclChannelEventScriptInvoker, (ClientData) sPtr);
611
612 Tcl_DecrRefCount(sPtr->scriptPtr);
613 ckfree((char *) sPtr);
614 } else {
615 prevPtr = sPtr;
616 }
617 }
618
619 /*
620 * Cannot call Tcl_UnregisterChannel because that procedure calls
621 * Tcl_GetAssocData to get the channel table, which might already
622 * be inaccessible from the interpreter structure. Instead, we
623 * emulate the behavior of Tcl_UnregisterChannel directly here.
624 */
625
626 Tcl_DeleteHashEntry(hPtr);
627 statePtr->refCount--;
628 if (statePtr->refCount <= 0) {
629 if (!(statePtr->flags & BG_FLUSH_SCHEDULED)) {
630 (void) Tcl_Close(interp, (Tcl_Channel) chanPtr);
631 }
632 }
633 }
634 Tcl_DeleteHashTable(hTblPtr);
635 ckfree((char *) hTblPtr);
636 }
637
638 /*
639 *----------------------------------------------------------------------
640 *
641 * CheckForStdChannelsBeingClosed --
642 *
643 * Perform special handling for standard channels being closed. When
644 * given a standard channel, if the refcount is now 1, it means that
645 * the last reference to the standard channel is being explicitly
646 * closed. Now bump the refcount artificially down to 0, to ensure the
647 * normal handling of channels being closed will occur. Also reset the
648 * static pointer to the channel to NULL, to avoid dangling references.
649 *
650 * Results:
651 * None.
652 *
653 * Side effects:
654 * Manipulates the refcount on standard channels. May smash the global
655 * static pointer to a standard channel.
656 *
657 *----------------------------------------------------------------------
658 */
659
660 static void
661 CheckForStdChannelsBeingClosed(chan)
662 Tcl_Channel chan;
663 {
664 ChannelState *statePtr = ((Channel *) chan)->state;
665 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
666
667 if ((chan == tsdPtr->stdinChannel) && (tsdPtr->stdinInitialized)) {
668 if (statePtr->refCount < 2) {
669 statePtr->refCount = 0;
670 tsdPtr->stdinChannel = NULL;
671 return;
672 }
673 } else if ((chan == tsdPtr->stdoutChannel)
674 && (tsdPtr->stdoutInitialized)) {
675 if (statePtr->refCount < 2) {
676 statePtr->refCount = 0;
677 tsdPtr->stdoutChannel = NULL;
678 return;
679 }
680 } else if ((chan == tsdPtr->stderrChannel)
681 && (tsdPtr->stderrInitialized)) {
682 if (statePtr->refCount < 2) {
683 statePtr->refCount = 0;
684 tsdPtr->stderrChannel = NULL;
685 return;
686 }
687 }
688 }
689
690 /*
691 *----------------------------------------------------------------------
692 *
693 * Tcl_IsStandardChannel --
694 *
695 * Test if the given channel is a standard channel. No attempt
696 * is made to check if the channel or the standard channels
697 * are initialized or otherwise valid.
698 *
699 * Results:
700 * Returns 1 if true, 0 if false.
701 *
702 * Side effects:
703 * None.
704 *
705 *----------------------------------------------------------------------
706 */
707 int
708 Tcl_IsStandardChannel(chan)
709 Tcl_Channel chan; /* Channel to check. */
710 {
711 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
712
713 if ((chan == tsdPtr->stdinChannel)
714 || (chan == tsdPtr->stdoutChannel)
715 || (chan == tsdPtr->stderrChannel)) {
716 return 1;
717 } else {
718 return 0;
719 }
720 }
721
722 /*
723 *----------------------------------------------------------------------
724 *
725 * Tcl_RegisterChannel --
726 *
727 * Adds an already-open channel to the channel table of an interpreter.
728 * If the interpreter passed as argument is NULL, it only increments
729 * the channel refCount.
730 *
731 * Results:
732 * None.
733 *
734 * Side effects:
735 * May increment the reference count of a channel.
736 *
737 *----------------------------------------------------------------------
738 */
739
740 void
741 Tcl_RegisterChannel(interp, chan)
742 Tcl_Interp *interp; /* Interpreter in which to add the channel. */
743 Tcl_Channel chan; /* The channel to add to this interpreter
744 * channel table. */
745 {
746 Tcl_HashTable *hTblPtr; /* Hash table of channels. */
747 Tcl_HashEntry *hPtr; /* Search variable. */
748 int new; /* Is the hash entry new or does it exist? */
749 Channel *chanPtr; /* The actual channel. */
750 ChannelState *statePtr; /* State of the actual channel. */
751
752 /*
753 * Always (un)register bottom-most channel in the stack. This makes
754 * management of the channel list easier because no manipulation is
755 * necessary during (un)stack operation.
756 */
757 chanPtr = ((Channel *) chan)->state->bottomChanPtr;
758 statePtr = chanPtr->state;
759
760 if (statePtr->channelName == (CONST char *) NULL) {
761 panic("Tcl_RegisterChannel: channel without name");
762 }
763 if (interp != (Tcl_Interp *) NULL) {
764 hTblPtr = GetChannelTable(interp);
765 hPtr = Tcl_CreateHashEntry(hTblPtr, statePtr->channelName, &new);
766 if (new == 0) {
767 if (chan == (Tcl_Channel) Tcl_GetHashValue(hPtr)) {
768 return;
769 }
770
771 panic("Tcl_RegisterChannel: duplicate channel names");
772 }
773 Tcl_SetHashValue(hPtr, (ClientData) chanPtr);
774 }
775 statePtr->refCount++;
776 }
777
778 /*
779 *----------------------------------------------------------------------
780 *
781 * Tcl_UnregisterChannel --
782 *
783 * Deletes the hash entry for a channel associated with an interpreter.
784 * If the interpreter given as argument is NULL, it only decrements the
785 * reference count. (This all happens in the Tcl_DetachChannel helper
786 * function).
787 *
788 * Finally, if the reference count of the channel drops to zero,
789 * it is deleted.
790 *
791 * Results:
792 * A standard Tcl result.
793 *
794 * Side effects:
795 * Calls Tcl_DetachChannel which deletes the hash entry for a channel
796 * associated with an interpreter.
797 *
798 * May delete the channel, which can have a variety of consequences,
799 * especially if we are forced to close the channel.
800 *
801 *----------------------------------------------------------------------
802 */
803
804 int
805 Tcl_UnregisterChannel(interp, chan)
806 Tcl_Interp *interp; /* Interpreter in which channel is defined. */
807 Tcl_Channel chan; /* Channel to delete. */
808 {
809 ChannelState *statePtr; /* State of the real channel. */
810
811 if (DetachChannel(interp, chan) != TCL_OK) {
812 return TCL_OK;
813 }
814
815 statePtr = ((Channel *) chan)->state->bottomChanPtr->state;
816
817 /*
818 * Perform special handling for standard channels being closed. If the
819 * refCount is now 1 it means that the last reference to the standard
820 * channel is being explicitly closed, so bump the refCount down
821 * artificially to 0. This will ensure that the channel is actually
822 * closed, below. Also set the static pointer to NULL for the channel.
823 */
824
825 CheckForStdChannelsBeingClosed(chan);
826
827 /*
828 * If the refCount reached zero, close the actual channel.
829 */
830
831 if (statePtr->refCount <= 0) {
832
833 /*
834 * Ensure that if there is another buffer, it gets flushed
835 * whether or not we are doing a background flush.
836 */
837
838 if ((statePtr->curOutPtr != NULL) &&
839 (statePtr->curOutPtr->nextAdded >
840 statePtr->curOutPtr->nextRemoved)) {
841 statePtr->flags |= BUFFER_READY;
842 }
843 Tcl_Preserve((ClientData)statePtr);
844 if (!(statePtr->flags & BG_FLUSH_SCHEDULED)) {
845 /* We don't want to re-enter Tcl_Close */
846 if (!(statePtr->flags & CHANNEL_CLOSED)) {
847 if (Tcl_Close(interp, chan) != TCL_OK) {
848 statePtr->flags |= CHANNEL_CLOSED;
849 Tcl_Release((ClientData)statePtr);
850 return TCL_ERROR;
851 }
852 }
853 }
854 statePtr->flags |= CHANNEL_CLOSED;
855 Tcl_Release((ClientData)statePtr);
856 }
857 return TCL_OK;
858 }
859
860 /*
861 *----------------------------------------------------------------------
862 *
863 * Tcl_DetachChannel --
864 *
865 * Deletes the hash entry for a channel associated with an interpreter.
866 * If the interpreter given as argument is NULL, it only decrements the
867 * reference count. Even if the ref count drops to zero, the
868 * channel is NOT closed or cleaned up. This allows a channel to
869 * be detached from an interpreter and left in the same state it
870 * was in when it was originally returned by 'Tcl_OpenFileChannel',
871 * for example.
872 *
873 * This function cannot be used on the standard channels, and
874 * will return TCL_ERROR if that is attempted.
875 *
876 * This function should only be necessary for special purposes
877 * in which you need to generate a pristine channel from one
878 * that has already been used. All ordinary purposes will almost
879 * always want to use Tcl_UnregisterChannel instead.
880 *
881 * Provided the channel is not attached to any other interpreter,
882 * it can then be closed with Tcl_Close, rather than with
883 * Tcl_UnregisterChannel.
884 *
885 * Results:
886 * A standard Tcl result. If the channel is not currently registered
887 * with the given interpreter, TCL_ERROR is returned, otherwise
888 * TCL_OK. However no error messages are left in the interp's result.
889 *
890 * Side effects:
891 * Deletes the hash entry for a channel associated with an
892 * interpreter.
893 *
894 *----------------------------------------------------------------------
895 */
896
897 int
898 Tcl_DetachChannel(interp, chan)
899 Tcl_Interp *interp; /* Interpreter in which channel is defined. */
900 Tcl_Channel chan; /* Channel to delete. */
901 {
902 if (Tcl_IsStandardChannel(chan)) {
903 return TCL_ERROR;
904 }
905
906 return DetachChannel(interp, chan);
907 }
908
909 /*
910 *----------------------------------------------------------------------
911 *
912 * DetachChannel --
913 *
914 * Deletes the hash entry for a channel associated with an interpreter.
915 * If the interpreter given as argument is NULL, it only decrements the
916 * reference count. Even if the ref count drops to zero, the
917 * channel is NOT closed or cleaned up. This allows a channel to
918 * be detached from an interpreter and left in the same state it
919 * was in when it was originally returned by 'Tcl_OpenFileChannel',
920 * for example.
921 *
922 * Results:
923 * A standard Tcl result. If the channel is not currently registered
924 * with the given interpreter, TCL_ERROR is returned, otherwise
925 * TCL_OK. However no error messages are left in the interp's result.
926 *
927 * Side effects:
928 * Deletes the hash entry for a channel associated with an
929 * interpreter.
930 *
931 *----------------------------------------------------------------------
932 */
933
934 static int
935 DetachChannel(interp, chan)
936 Tcl_Interp *interp; /* Interpreter in which channel is defined. */
937 Tcl_Channel chan; /* Channel to delete. */
938 {
939 Tcl_HashTable *hTblPtr; /* Hash table of channels. */
940 Tcl_HashEntry *hPtr; /* Search variable. */
941 Channel *chanPtr; /* The real IO channel. */
942 ChannelState *statePtr; /* State of the real channel. */
943
944 /*
945 * Always (un)register bottom-most channel in the stack. This makes
946 * management of the channel list easier because no manipulation is
947 * necessary during (un)stack operation.
948 */
949 chanPtr = ((Channel *) chan)->state->bottomChanPtr;
950 statePtr = chanPtr->state;
951
952 if (interp != (Tcl_Interp *) NULL) {
953 hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
954 if (hTblPtr == (Tcl_HashTable *) NULL) {
955 return TCL_ERROR;
956 }
957 hPtr = Tcl_FindHashEntry(hTblPtr, statePtr->channelName);
958 if (hPtr == (Tcl_HashEntry *) NULL) {
959 return TCL_ERROR;
960 }
961 if ((Channel *) Tcl_GetHashValue(hPtr) != chanPtr) {
962 return TCL_ERROR;
963 }
964 Tcl_DeleteHashEntry(hPtr);
965
966 /*
967 * Remove channel handlers that refer to this interpreter, so that they
968 * will not be present if the actual close is delayed and more events
969 * happen on the channel. This may occur if the channel is shared
970 * between several interpreters, or if the channel has async
971 * flushing active.
972 */
973
974 CleanupChannelHandlers(interp, chanPtr);
975 }
976
977 statePtr->refCount--;
978
979 return TCL_OK;
980 }
981
982
983 /*
984 *---------------------------------------------------------------------------
985 *
986 * Tcl_GetChannel --
987 *
988 * Finds an existing Tcl_Channel structure by name in a given
989 * interpreter. This function is public because it is used by
990 * channel-type-specific functions.
991 *
992 * Results:
993 * A Tcl_Channel or NULL on failure. If failed, interp's result
994 * object contains an error message. *modePtr is filled with the
995 * modes in which the channel was opened.
996 *
997 * Side effects:
998 * None.
999 *
1000 *---------------------------------------------------------------------------
1001 */
1002
1003 Tcl_Channel
1004 Tcl_GetChannel(interp, chanName, modePtr)
1005 Tcl_Interp *interp; /* Interpreter in which to find or create
1006 * the channel. */
1007 CONST char *chanName; /* The name of the channel. */
1008 int *modePtr; /* Where to store the mode in which the
1009 * channel was opened? Will contain an ORed
1010 * combination of TCL_READABLE and
1011 * TCL_WRITABLE, if non-NULL. */
1012 {
1013 Channel *chanPtr; /* The actual channel. */
1014 Tcl_HashTable *hTblPtr; /* Hash table of channels. */
1015 Tcl_HashEntry *hPtr; /* Search variable. */
1016 CONST char *name; /* Translated name. */
1017
1018 /*
1019 * Substitute "stdin", etc. Note that even though we immediately
1020 * find the channel using Tcl_GetStdChannel, we still need to look
1021 * it up in the specified interpreter to ensure that it is present
1022 * in the channel table. Otherwise, safe interpreters would always
1023 * have access to the standard channels.
1024 */
1025
1026 name = chanName;
1027 if ((chanName[0] == 's') && (chanName[1] == 't')) {
1028 chanPtr = NULL;
1029 if (strcmp(chanName, "stdin") == 0) {
1030 chanPtr = (Channel *) Tcl_GetStdChannel(TCL_STDIN);
1031 } else if (strcmp(chanName, "stdout") == 0) {
1032 chanPtr = (Channel *) Tcl_GetStdChannel(TCL_STDOUT);
1033 } else if (strcmp(chanName, "stderr") == 0) {
1034 chanPtr = (Channel *) Tcl_GetStdChannel(TCL_STDERR);
1035 }
1036 if (chanPtr != NULL) {
1037 name = chanPtr->state->channelName;
1038 }
1039 }
1040
1041 hTblPtr = GetChannelTable(interp);
1042 hPtr = Tcl_FindHashEntry(hTblPtr, name);
1043 if (hPtr == (Tcl_HashEntry *) NULL) {
1044 Tcl_AppendResult(interp, "can not find channel named \"",
1045 chanName, "\"", (char *) NULL);
1046 return NULL;
1047 }
1048
1049 /*
1050 * Always return bottom-most channel in the stack. This one lives
1051 * the longest - other channels may go away unnoticed.
1052 * The other APIs compensate where necessary to retrieve the
1053 * topmost channel again.
1054 */
1055 chanPtr = (Channel *) Tcl_GetHashValue(hPtr);
1056 chanPtr = chanPtr->state->bottomChanPtr;
1057 if (modePtr != NULL) {
1058 *modePtr = (chanPtr->state->flags & (TCL_READABLE|TCL_WRITABLE));
1059 }
1060
1061 return (Tcl_Channel) chanPtr;
1062 }
1063
1064 /*
1065 *----------------------------------------------------------------------
1066 *
1067 * Tcl_CreateChannel --
1068 *
1069 * Creates a new entry in the hash table for a Tcl_Channel
1070 * record.
1071 *
1072 * Results:
1073 * Returns the new Tcl_Channel.
1074 *
1075 * Side effects:
1076 * Creates a new Tcl_Channel instance and inserts it into the
1077 * hash table.
1078 *
1079 *----------------------------------------------------------------------
1080 */
1081
1082 Tcl_Channel
1083 Tcl_CreateChannel(typePtr, chanName, instanceData, mask)
1084 Tcl_ChannelType *typePtr; /* The channel type record. */
1085 CONST char *chanName; /* Name of channel to record. */
1086 ClientData instanceData; /* Instance specific data. */
1087 int mask; /* TCL_READABLE & TCL_WRITABLE to indicate
1088 * if the channel is readable, writable. */
1089 {
1090 Channel *chanPtr; /* The channel structure newly created. */
1091 ChannelState *statePtr; /* The stack-level independent state info
1092 * for the channel. */
1093 CONST char *name;
1094 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1095
1096 /*
1097 * With the change of the Tcl_ChannelType structure to use a version in
1098 * 8.3.2+, we have to make sure that our assumption that the structure
1099 * remains a binary compatible size is true.
1100 *
1101 * If this assertion fails on some system, then it can be removed
1102 * only if the user recompiles code with older channel drivers in
1103 * the new system as well.
1104 */
1105
1106 assert(sizeof(Tcl_ChannelTypeVersion) == sizeof(Tcl_DriverBlockModeProc*));
1107
1108 /*
1109 * JH: We could subsequently memset these to 0 to avoid the
1110 * numerous assignments to 0/NULL below.
1111 */
1112 chanPtr = (Channel *) ckalloc((unsigned) sizeof(Channel));
1113 statePtr = (ChannelState *) ckalloc((unsigned) sizeof(ChannelState));
1114 chanPtr->state = statePtr;
1115
1116 chanPtr->instanceData = instanceData;
1117 chanPtr->typePtr = typePtr;
1118
1119 /*
1120 * Set all the bits that are part of the stack-independent state
1121 * information for the channel.
1122 */
1123
1124 if (chanName != (char *) NULL) {
1125 char *tmp = ckalloc((unsigned) (strlen(chanName) + 1));
1126 statePtr->channelName = tmp;
1127 strcpy(tmp, chanName);
1128 } else {
1129 panic("Tcl_CreateChannel: NULL channel name");
1130 }
1131
1132 statePtr->flags = mask;
1133
1134 /*
1135 * Set the channel to system default encoding.
1136 */
1137
1138 statePtr->encoding = NULL;
1139 name = Tcl_GetEncodingName(NULL);
1140 if (strcmp(name, "binary") != 0) {
1141 statePtr->encoding = Tcl_GetEncoding(NULL, name);
1142 }
1143 statePtr->inputEncodingState = NULL;
1144 statePtr->inputEncodingFlags = TCL_ENCODING_START;
1145 statePtr->outputEncodingState = NULL;
1146 statePtr->outputEncodingFlags = TCL_ENCODING_START;
1147
1148 /*
1149 * Set the channel up initially in AUTO input translation mode to
1150 * accept "\n", "\r" and "\r\n". Output translation mode is set to
1151 * a platform specific default value. The eofChar is set to 0 for both
1152 * input and output, so that Tcl does not look for an in-file EOF
1153 * indicator (e.g. ^Z) and does not append an EOF indicator to files.
1154 */
1155
1156 statePtr->inputTranslation = TCL_TRANSLATE_AUTO;
1157 statePtr->outputTranslation = TCL_PLATFORM_TRANSLATION;
1158 statePtr->inEofChar = 0;
1159 statePtr->outEofChar = 0;
1160
1161 statePtr->unreportedError = 0;
1162 statePtr->refCount = 0;
1163 statePtr->closeCbPtr = (CloseCallback *) NULL;
1164 statePtr->curOutPtr = (ChannelBuffer *) NULL;
1165 statePtr->outQueueHead = (ChannelBuffer *) NULL;
1166 statePtr->outQueueTail = (ChannelBuffer *) NULL;
1167 statePtr->saveInBufPtr = (ChannelBuffer *) NULL;
1168 statePtr->inQueueHead = (ChannelBuffer *) NULL;
1169 statePtr->inQueueTail = (ChannelBuffer *) NULL;
1170 statePtr->chPtr = (ChannelHandler *) NULL;
1171 statePtr->interestMask = 0;
1172 statePtr->scriptRecordPtr = (EventScriptRecord *) NULL;
1173 statePtr->bufSize = CHANNELBUFFER_DEFAULT_SIZE;
1174 statePtr->timer = NULL;
1175 statePtr->csPtr = NULL;
1176
1177 statePtr->outputStage = NULL;
1178 if ((statePtr->encoding != NULL) && (statePtr->flags & TCL_WRITABLE)) {
1179 statePtr->outputStage = (char *)
1180 ckalloc((unsigned) (statePtr->bufSize + 2));
1181 }
1182
1183 /*
1184 * As we are creating the channel, it is obviously the top for now
1185 */
1186 statePtr->topChanPtr = chanPtr;
1187 statePtr->bottomChanPtr = chanPtr;
1188 chanPtr->downChanPtr = (Channel *) NULL;
1189 chanPtr->upChanPtr = (Channel *) NULL;
1190 chanPtr->inQueueHead = (ChannelBuffer*) NULL;
1191 chanPtr->inQueueTail = (ChannelBuffer*) NULL;
1192
1193 /*
1194 * Link the channel into the list of all channels; create an on-exit
1195 * handler if there is not one already, to close off all the channels
1196 * in the list on exit.
1197 *
1198 * JH: Could call Tcl_SpliceChannel, but need to avoid NULL check.
1199 */
1200
1201 statePtr->nextCSPtr = tsdPtr->firstCSPtr;
1202 tsdPtr->firstCSPtr = statePtr;
1203
1204 /*
1205 * TIP #10. Mark the current thread as the one managing the new
1206 * channel. Note: 'Tcl_GetCurrentThread' returns sensible
1207 * values even for a non-threaded core.
1208 */
1209
1210 statePtr->managingThread = Tcl_GetCurrentThread ();
1211
1212 /*
1213 * Install this channel in the first empty standard channel slot, if
1214 * the channel was previously closed explicitly.
1215 */
1216
1217 if ((tsdPtr->stdinChannel == NULL) &&
1218 (tsdPtr->stdinInitialized == 1)) {
1219 Tcl_SetStdChannel((Tcl_Channel) chanPtr, TCL_STDIN);
1220 Tcl_RegisterChannel((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);
1221 } else if ((tsdPtr->stdoutChannel == NULL) &&
1222 (tsdPtr->stdoutInitialized == 1)) {
1223 Tcl_SetStdChannel((Tcl_Channel) chanPtr, TCL_STDOUT);
1224 Tcl_RegisterChannel((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);
1225 } else if ((tsdPtr->stderrChannel == NULL) &&
1226 (tsdPtr->stderrInitialized == 1)) {
1227 Tcl_SetStdChannel((Tcl_Channel) chanPtr, TCL_STDERR);
1228 Tcl_RegisterChannel((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);
1229 }
1230 return (Tcl_Channel) chanPtr;
1231 }
1232
1233 /*
1234 *----------------------------------------------------------------------
1235 *
1236 * Tcl_StackChannel --
1237 *
1238 * Replaces an entry in the hash table for a Tcl_Channel
1239 * record. The replacement is a new channel with same name,
1240 * it supercedes the replaced channel. Input and output of
1241 * the superceded channel is now going through the newly
1242 * created channel and allows the arbitrary filtering/manipulation
1243 * of the dataflow.
1244 *
1245 * Andreas Kupries <[email protected]>, 12/13/1998
1246 * "Trf-Patch for filtering channels"
1247 *
1248 * Results:
1249 * Returns the new Tcl_Channel, which actually contains the
1250 * saved information about prevChan.
1251 *
1252 * Side effects:
1253 * A new channel structure is allocated and linked below
1254 * the existing channel. The channel operations and client
1255 * data of the existing channel are copied down to the newly
1256 * created channel, and the current channel has its operations
1257 * replaced by the new typePtr.
1258 *
1259 *----------------------------------------------------------------------
1260 */
1261
1262 Tcl_Channel
1263 Tcl_StackChannel(interp, typePtr, instanceData, mask, prevChan)
1264 Tcl_Interp *interp; /* The interpreter we are working in */
1265 Tcl_ChannelType *typePtr; /* The channel type record for the new
1266 * channel. */
1267 ClientData instanceData; /* Instance specific data for the new
1268 * channel. */
1269 int mask; /* TCL_READABLE & TCL_WRITABLE to indicate
1270 * if the channel is readable, writable. */
1271 Tcl_Channel prevChan; /* The channel structure to replace */
1272 {
1273 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1274 Channel *chanPtr, *prevChanPtr;
1275 ChannelState *statePtr;
1276
1277 /*
1278 * Find the given channel in the list of all channels.
1279 * If we don't find it, then it was never registered correctly.
1280 *
1281 * This operation should occur at the top of a channel stack.
1282 */
1283
1284 statePtr = (ChannelState *) tsdPtr->firstCSPtr;
1285 prevChanPtr = ((Channel *) prevChan)->state->topChanPtr;
1286
1287 while (statePtr->topChanPtr != prevChanPtr) {
1288 statePtr = statePtr->nextCSPtr;
1289 }
1290
1291 if (statePtr == NULL) {
1292 Tcl_AppendResult(interp, "couldn't find state for channel \"",
1293 Tcl_GetChannelName(prevChan), "\"", (char *) NULL);
1294 return (Tcl_Channel) NULL;
1295 }
1296
1297 /*
1298 * Here we check if the given "mask" matches the "flags"
1299 * of the already existing channel.
1300 *
1301 * | - | R | W | RW |
1302 * --+---+---+---+----+ <=> 0 != (chan->mask & prevChan->mask)
1303 * - | | | | |
1304 * R | | + | | + | The superceding channel is allowed to
1305 * W | | | + | + | restrict the capabilities of the
1306 * RW| | + | + | + | superceded one !
1307 * --+---+---+---+----+
1308 */
1309
1310 if ((mask & (statePtr->flags & (TCL_READABLE | TCL_WRITABLE))) == 0) {
1311 Tcl_AppendResult(interp,
1312 "reading and writing both disallowed for channel \"",
1313 Tcl_GetChannelName(prevChan), "\"", (char *) NULL);
1314 return (Tcl_Channel) NULL;
1315 }
1316
1317 /*
1318 * Flush the buffers. This ensures that any data still in them
1319 * at this time is not handled by the new transformation. Restrict
1320 * this to writable channels. Take care to hide a possible bg-copy
1321 * in progress from Tcl_Flush and the CheckForChannelErrors inside.
1322 */
1323
1324 if ((mask & TCL_WRITABLE) != 0) {
1325 CopyState *csPtr;
1326
1327 csPtr = statePtr->csPtr;
1328 statePtr->csPtr = (CopyState*) NULL;
1329
1330 if (Tcl_Flush((Tcl_Channel) prevChanPtr) != TCL_OK) {
1331 statePtr->csPtr = csPtr;
1332 Tcl_AppendResult(interp, "could not flush channel \"",
1333 Tcl_GetChannelName(prevChan), "\"", (char *) NULL);
1334 return (Tcl_Channel) NULL;
1335 }
1336
1337 statePtr->csPtr = csPtr;
1338 }
1339 /*
1340 * Discard any input in the buffers. They are not yet read by the
1341 * user of the channel, so they have to go through the new
1342 * transformation before reading. As the buffers contain the
1343 * untransformed form their contents are not only useless but actually
1344 * distorts our view of the system.
1345 *
1346 * To preserve the information without having to read them again and
1347 * to avoid problems with the location in the channel (seeking might
1348 * be impossible) we move the buffers from the common state structure
1349 * into the channel itself. We use the buffers in the channel below
1350 * the new transformation to hold the data. In the future this allows
1351 * us to write transformations which pre-read data and push the unused
1352 * part back when they are going away.
1353 */
1354
1355 if (((mask & TCL_READABLE) != 0) &&
1356 (statePtr->inQueueHead != (ChannelBuffer*) NULL)) {
1357 /*
1358 * Remark: It is possible that the channel buffers contain data from
1359 * some earlier push-backs.
1360 */
1361
1362 statePtr->inQueueTail->nextPtr = prevChanPtr->inQueueHead;
1363 prevChanPtr->inQueueHead = statePtr->inQueueHead;
1364
1365 if (prevChanPtr->inQueueTail == (ChannelBuffer*) NULL) {
1366 prevChanPtr->inQueueTail = statePtr->inQueueTail;
1367 }
1368
1369 statePtr->inQueueHead = (ChannelBuffer*) NULL;
1370 statePtr->inQueueTail = (ChannelBuffer*) NULL;
1371 }
1372
1373 chanPtr = (Channel *) ckalloc((unsigned) sizeof(Channel));
1374
1375 /*
1376 * Save some of the current state into the new structure,
1377 * reinitialize the parts which will stay with the transformation.
1378 *
1379 * Remarks:
1380 */
1381
1382 chanPtr->state = statePtr;
1383 chanPtr->instanceData = instanceData;
1384 chanPtr->typePtr = typePtr;
1385 chanPtr->downChanPtr = prevChanPtr;
1386 chanPtr->upChanPtr = (Channel *) NULL;
1387 chanPtr->inQueueHead = (ChannelBuffer*) NULL;
1388 chanPtr->inQueueTail = (ChannelBuffer*) NULL;
1389
1390 /*
1391 * Place new block at the head of a possibly existing list of previously
1392 * stacked channels.
1393 */
1394
1395 prevChanPtr->upChanPtr = chanPtr;
1396 statePtr->topChanPtr = chanPtr;
1397
1398 return (Tcl_Channel) chanPtr;
1399 }
1400
1401 /*
1402 *----------------------------------------------------------------------
1403 *
1404 * Tcl_UnstackChannel --
1405 *
1406 * Unstacks an entry in the hash table for a Tcl_Channel
1407 * record. This is the reverse to 'Tcl_StackChannel'.
1408 *
1409 * Results:
1410 * A standard Tcl result.
1411 *
1412 * Side effects:
1413 * If TCL_ERROR is returned, the posix error code will be set
1414 * with Tcl_SetErrno.
1415 *
1416 *----------------------------------------------------------------------
1417 */
1418
1419 int
1420 Tcl_UnstackChannel (interp, chan)
1421 Tcl_Interp *interp; /* The interpreter we are working in */
1422 Tcl_Channel chan; /* The channel to unstack */
1423 {
1424 Channel *chanPtr = (Channel *) chan;
1425 ChannelState *statePtr = chanPtr->state;
1426 int result = 0;
1427
1428 /*
1429 * This operation should occur at the top of a channel stack.
1430 */
1431
1432 chanPtr = statePtr->topChanPtr;
1433
1434 if (chanPtr->downChanPtr != (Channel *) NULL) {
1435 /*
1436 * Instead of manipulating the per-thread / per-interp list/hashtable
1437 * of registered channels we wind down the state of the transformation,
1438 * and then restore the state of underlying channel into the old
1439 * structure.
1440 */
1441 Channel *downChanPtr = chanPtr->downChanPtr;
1442
1443 /*
1444 * Flush the buffers. This ensures that any data still in them
1445 * at this time _is_ handled by the transformation we are unstacking
1446 * right now. Restrict this to writable channels. Take care to hide
1447 * a possible bg-copy in progress from Tcl_Flush and the
1448 * CheckForChannelErrors inside.
1449 */
1450
1451 if (statePtr->flags & TCL_WRITABLE) {
1452 CopyState* csPtr;
1453
1454 csPtr = statePtr->csPtr;
1455 statePtr->csPtr = (CopyState*) NULL;
1456
1457 if (Tcl_Flush((Tcl_Channel) chanPtr) != TCL_OK) {
1458 statePtr->csPtr = csPtr;
1459 Tcl_AppendResult(interp, "could not flush channel \"",
1460 Tcl_GetChannelName((Tcl_Channel) chanPtr), "\"",
1461 (char *) NULL);
1462 return TCL_ERROR;
1463 }
1464
1465 statePtr->csPtr = csPtr;
1466 }
1467
1468 /*
1469 * Anything in the input queue and the push-back buffers of
1470 * the transformation going away is transformed data, but not
1471 * yet read. As unstacking means that the caller does not want
1472 * to see transformed data any more we have to discard these
1473 * bytes. To avoid writing an analogue to 'DiscardInputQueued'
1474 * we move the information in the push back buffers to the
1475 * input queue and then call 'DiscardInputQueued' on that.
1476 */
1477
1478 if (((statePtr->flags & TCL_READABLE) != 0) &&
1479 ((statePtr->inQueueHead != (ChannelBuffer*) NULL) ||
1480 (chanPtr->inQueueHead != (ChannelBuffer*) NULL))) {
1481
1482 if ((statePtr->inQueueHead != (ChannelBuffer*) NULL) &&
1483 (chanPtr->inQueueHead != (ChannelBuffer*) NULL)) {
1484 statePtr->inQueueTail->nextPtr = chanPtr->inQueueHead;
1485 statePtr->inQueueTail = chanPtr->inQueueTail;
1486 statePtr->inQueueHead = statePtr->inQueueTail;
1487
1488 } else if (chanPtr->inQueueHead != (ChannelBuffer*) NULL) {
1489 statePtr->inQueueHead = chanPtr->inQueueHead;
1490 statePtr->inQueueTail = chanPtr->inQueueTail;
1491 }
1492
1493 chanPtr->inQueueHead = (ChannelBuffer*) NULL;
1494 chanPtr->inQueueTail = (ChannelBuffer*) NULL;
1495
1496 DiscardInputQueued (statePtr, 0);
1497 }
1498
1499 statePtr->topChanPtr = downChanPtr;
1500 downChanPtr->upChanPtr = (Channel *) NULL;
1501
1502 /*
1503 * Leave this link intact for closeproc
1504 * chanPtr->downChanPtr = (Channel *) NULL;
1505 */
1506
1507 /*
1508 * Close and free the channel driver state.
1509 */
1510
1511 if (chanPtr->typePtr->closeProc != TCL_CLOSE2PROC) {
1512 result = (chanPtr->typePtr->closeProc)(chanPtr->instanceData,
1513 interp);
1514 } else {
1515 result = (chanPtr->typePtr->close2Proc)(chanPtr->instanceData,
1516 interp, 0);
1517 }
1518
1519 chanPtr->typePtr = NULL;
1520 /*
1521 * AK: Tcl_NotifyChannel may hold a reference to this block of memory
1522 */
1523 Tcl_EventuallyFree((ClientData) chanPtr, TCL_DYNAMIC);
1524 UpdateInterest(downChanPtr);
1525
1526 if (result != 0) {
1527 Tcl_SetErrno(result);
1528 return TCL_ERROR;
1529 }
1530 } else {
1531 /*
1532 * This channel does not cover another one.
1533 * Simply do a close, if necessary.
1534 */
1535
1536 if (statePtr->refCount <= 0) {
1537 if (Tcl_Close(interp, chan) != TCL_OK) {
1538 return TCL_ERROR;
1539 }
1540 }
1541 }
1542
1543 return TCL_OK;
1544 }
1545
1546 /*
1547 *----------------------------------------------------------------------
1548 *
1549 * Tcl_GetStackedChannel --
1550 *
1551 * Determines whether the specified channel is stacked upon another.
1552 *
1553 * Results:
1554 * NULL if the channel is not stacked upon another one, or a reference
1555 * to the channel it is stacked upon. This reference can be used in
1556 * queries, but modification is not allowed.
1557 *
1558 * Side effects:
1559 * None.
1560 *
1561 *----------------------------------------------------------------------
1562 */
1563
1564 Tcl_Channel
1565 Tcl_GetStackedChannel(chan)
1566 Tcl_Channel chan;
1567 {
1568 Channel *chanPtr = (Channel *) chan; /* The actual channel. */
1569
1570 return (Tcl_Channel) chanPtr->downChanPtr;
1571 }
1572
1573 /*
1574 *----------------------------------------------------------------------
1575 *
1576 * Tcl_GetTopChannel --
1577 *
1578 * Returns the top channel of a channel stack.
1579 *
1580 * Results:
1581 * NULL if the channel is not stacked upon another one, or a reference
1582 * to the channel it is stacked upon. This reference can be used in
1583 * queries, but modification is not allowed.
1584 *
1585 * Side effects:
1586 * None.
1587 *
1588 *----------------------------------------------------------------------
1589 */
1590
1591 Tcl_Channel
1592 Tcl_GetTopChannel(chan)
1593 Tcl_Channel chan;
1594 {
1595 Channel *chanPtr = (Channel *) chan; /* The actual channel. */
1596
1597 return (Tcl_Channel) chanPtr->state->topChanPtr;
1598 }
1599
1600 /*
1601 *----------------------------------------------------------------------
1602 *
1603 * Tcl_GetChannelInstanceData --
1604 *
1605 * Returns the client data associated with a channel.
1606 *
1607 * Results:
1608 * The client data.
1609 *
1610 * Side effects:
1611 * None.
1612 *
1613 *----------------------------------------------------------------------
1614 */
1615
1616 ClientData
1617 Tcl_GetChannelInstanceData(chan)
1618 Tcl_Channel chan; /* Channel for which to return client data. */
1619 {
1620 Channel *chanPtr = (Channel *) chan; /* The actual channel. */
1621
1622 return chanPtr->instanceData;
1623 }
1624
1625 /*
1626 *----------------------------------------------------------------------
1627 *
1628 * Tcl_GetChannelThread --
1629 *
1630 * Given a channel structure, returns the thread managing it.
1631 * TIP #10
1632 *
1633 * Results:
1634 * Returns the id of the thread managing the channel.
1635 *
1636 * Side effects:
1637 * None.
1638 *
1639 *----------------------------------------------------------------------
1640 */
1641
1642 Tcl_ThreadId
1643 Tcl_GetChannelThread(chan)
1644 Tcl_Channel chan; /* The channel to return managing thread for. */
1645 {
1646 Channel *chanPtr = (Channel *) chan; /* The actual channel. */
1647
1648 return chanPtr->state->managingThread;
1649 }
1650
1651 /*
1652 *----------------------------------------------------------------------
1653 *
1654 * Tcl_GetChannelType --
1655 *
1656 * Given a channel structure, returns the channel type structure.
1657 *
1658 * Results:
1659 * Returns a pointer to the channel type structure.
1660 *
1661 * Side effects:
1662 * None.
1663 *
1664 *----------------------------------------------------------------------
1665 */
1666
1667 Tcl_ChannelType *
1668 Tcl_GetChannelType(chan)
1669 Tcl_Channel chan; /* The channel to return type for. */
1670 {
1671 Channel *chanPtr = (Channel *) chan; /* The actual channel. */
1672
1673 return chanPtr->typePtr;
1674 }
1675
1676 /*
1677 *----------------------------------------------------------------------
1678 *
1679 * Tcl_GetChannelMode --
1680 *
1681 * Computes a mask indicating whether the channel is open for
1682 * reading and writing.
1683 *
1684 * Results:
1685 * An OR-ed combination of TCL_READABLE and TCL_WRITABLE.
1686 *
1687 * Side effects:
1688 * None.
1689 *
1690 *----------------------------------------------------------------------
1691 */
1692
1693 int
1694 Tcl_GetChannelMode(chan)
1695 Tcl_Channel chan; /* The channel for which the mode is
1696 * being computed. */
1697 {
1698 ChannelState *statePtr = ((Channel *) chan)->state;
1699 /* State of actual channel. */
1700
1701 return (statePtr->flags & (TCL_READABLE | TCL_WRITABLE));
1702 }
1703
1704 /*
1705 *----------------------------------------------------------------------
1706 *
1707 * Tcl_GetChannelName --
1708 *
1709 * Returns the string identifying the channel name.
1710 *
1711 * Results:
1712 * The string containing the channel name. This memory is
1713 * owned by the generic layer and should not be modified by
1714 * the caller.
1715 *
1716 * Side effects:
1717 * None.
1718 *
1719 *----------------------------------------------------------------------
1720 */
1721
1722 CONST char *
1723 Tcl_GetChannelName(chan)
1724 Tcl_Channel chan; /* The channel for which to return the name. */
1725 {
1726 ChannelState *statePtr; /* State of actual channel. */
1727
1728 statePtr = ((Channel *) chan)->state;
1729 return statePtr->channelName;
1730 }
1731
1732 /*
1733 *----------------------------------------------------------------------
1734 *
1735 * Tcl_GetChannelHandle --
1736 *
1737 * Returns an OS handle associated with a channel.
1738 *
1739 * Results:
1740 * Returns TCL_OK and places the handle in handlePtr, or returns
1741 * TCL_ERROR on failure.
1742 *
1743 * Side effects:
1744 * None.
1745 *
1746 *----------------------------------------------------------------------
1747 */
1748
1749 int
1750 Tcl_GetChannelHandle(chan, direction, handlePtr)
1751 Tcl_Channel chan; /* The channel to get file from. */
1752 int direction; /* TCL_WRITABLE or TCL_READABLE. */
1753 ClientData *handlePtr; /* Where to store handle */
1754 {
1755 Channel *chanPtr; /* The actual channel. */
1756 ClientData handle;
1757 int result;
1758
1759 chanPtr = ((Channel *) chan)->state->bottomChanPtr;
1760 result = (chanPtr->typePtr->getHandleProc)(chanPtr->instanceData,
1761 direction, &handle);
1762 if (handlePtr) {
1763 *handlePtr = handle;
1764 }
1765 return result;
1766 }
1767
1768 /*
1769 *---------------------------------------------------------------------------
1770 *
1771 * AllocChannelBuffer --
1772 *
1773 * A channel buffer has BUFFER_PADDING bytes extra at beginning to
1774 * hold any bytes of a native-encoding character that got split by
1775 * the end of the previous buffer and need to be moved to the
1776 * beginning of the next buffer to make a contiguous string so it
1777 * can be converted to UTF-8.
1778 *
1779 * A channel buffer has BUFFER_PADDING bytes extra at the end to
1780 * hold any bytes of a native-encoding character (generated from a
1781 * UTF-8 character) that overflow past the end of the buffer and
1782 * need to be moved to the next buffer.
1783 *
1784 * Results:
1785 * A newly allocated channel buffer.
1786 *
1787 * Side effects:
1788 * None.
1789 *
1790 *---------------------------------------------------------------------------
1791 */
1792
1793 static ChannelBuffer *
1794 AllocChannelBuffer(length)
1795 int length; /* Desired length of channel buffer. */
1796 {
1797 ChannelBuffer *bufPtr;
1798 int n;
1799
1800 n = length + CHANNELBUFFER_HEADER_SIZE + BUFFER_PADDING + BUFFER_PADDING;
1801 bufPtr = (ChannelBuffer *) ckalloc((unsigned) n);
1802 bufPtr->nextAdded = BUFFER_PADDING;
1803 bufPtr->nextRemoved = BUFFER_PADDING;
1804 bufPtr->bufLength = length + BUFFER_PADDING;
1805 bufPtr->nextPtr = (ChannelBuffer *) NULL;
1806 return bufPtr;
1807 }
1808
1809 /*
1810 *----------------------------------------------------------------------
1811 *
1812 * RecycleBuffer --
1813 *
1814 * Helper function to recycle input and output buffers. Ensures
1815 * that two input buffers are saved (one in the input queue and
1816 * another in the saveInBufPtr field) and that curOutPtr is set
1817 * to a buffer. Only if these conditions are met is the buffer
1818 * freed to the OS.
1819 *
1820 * Results:
1821 * None.
1822 *
1823 * Side effects:
1824 * May free a buffer to the OS.
1825 *
1826 *----------------------------------------------------------------------
1827 */
1828
1829 static void
1830 RecycleBuffer(statePtr, bufPtr, mustDiscard)
1831 ChannelState *statePtr; /* ChannelState in which to recycle buffers. */
1832 ChannelBuffer *bufPtr; /* The buffer to recycle. */
1833 int mustDiscard; /* If nonzero, free the buffer to the
1834 * OS, always. */
1835 {
1836 /*
1837 * Do we have to free the buffer to the OS?
1838 */
1839
1840 if (mustDiscard) {
1841 ckfree((char *) bufPtr);
1842 return;
1843 }
1844
1845 /*
1846 * Only save buffers which are at least as big as the requested
1847 * buffersize for the channel. This is to honor dynamic changes
1848 * of the buffersize made by the user.
1849 */
1850
1851 if ((bufPtr->bufLength - BUFFER_PADDING) < statePtr->bufSize) {
1852 ckfree((char *) bufPtr);
1853 return;
1854 }
1855
1856 /*
1857 * Only save buffers for the input queue if the channel is readable.
1858 */
1859
1860 if (statePtr->flags & TCL_READABLE) {
1861 if (statePtr->inQueueHead == (ChannelBuffer *) NULL) {
1862 statePtr->inQueueHead = bufPtr;
1863 statePtr->inQueueTail = bufPtr;
1864 goto keepit;
1865 }
1866 if (statePtr->saveInBufPtr == (ChannelBuffer *) NULL) {
1867 statePtr->saveInBufPtr = bufPtr;
1868 goto keepit;
1869 }
1870 }
1871
1872 /*
1873 * Only save buffers for the output queue if the channel is writable.
1874 */
1875
1876 if (statePtr->flags & TCL_WRITABLE) {
1877 if (statePtr->curOutPtr == (ChannelBuffer *) NULL) {
1878 statePtr->curOutPtr = bufPtr;
1879 goto keepit;
1880 }
1881 }
1882
1883 /*
1884 * If we reached this code we return the buffer to the OS.
1885 */
1886
1887 ckfree((char *) bufPtr);
1888 return;
1889
1890 keepit:
1891 bufPtr->nextRemoved = BUFFER_PADDING;
1892 bufPtr->nextAdded = BUFFER_PADDING;
1893 bufPtr->nextPtr = (ChannelBuffer *) NULL;
1894 }
1895
1896 /*
1897 *----------------------------------------------------------------------
1898 *
1899 * DiscardOutputQueued --
1900 *
1901 * Discards all output queued in the output queue of a channel.
1902 *
1903 * Results:
1904 * None.
1905 *
1906 * Side effects:
1907 * Recycles buffers.
1908 *
1909 *----------------------------------------------------------------------
1910 */
1911
1912 static void
1913 DiscardOutputQueued(statePtr)
1914 ChannelState *statePtr; /* ChannelState for which to discard output. */
1915 {
1916 ChannelBuffer *bufPtr;
1917
1918 while (statePtr->outQueueHead != (ChannelBuffer *) NULL) {
1919 bufPtr = statePtr->outQueueHead;
1920 statePtr->outQueueHead = bufPtr->nextPtr;
1921 RecycleBuffer(statePtr, bufPtr, 0);
1922 }
1923 statePtr->outQueueHead = (ChannelBuffer *) NULL;
1924 statePtr->outQueueTail = (ChannelBuffer *) NULL;
1925 }
1926
1927 /*
1928 *----------------------------------------------------------------------
1929 *
1930 * CheckForDeadChannel --
1931 *
1932 * This function checks is a given channel is Dead.
1933 * (A channel that has been closed but not yet deallocated.)
1934 *
1935 * Results:
1936 * True (1) if channel is Dead, False (0) if channel is Ok
1937 *
1938 * Side effects:
1939 * None
1940 *
1941 *----------------------------------------------------------------------
1942 */
1943
1944 static int
1945 CheckForDeadChannel(interp, statePtr)
1946 Tcl_Interp *interp; /* For error reporting (can be NULL) */
1947 ChannelState *statePtr; /* The channel state to check. */
1948 {
1949 if (statePtr->flags & CHANNEL_DEAD) {
1950 Tcl_SetErrno(EINVAL);
1951 if (interp) {
1952 Tcl_AppendResult(interp,
1953 "unable to access channel: invalid channel",
1954 (char *) NULL);
1955 }
1956 return 1;
1957 }
1958 return 0;
1959 }
1960
1961 /*
1962 *----------------------------------------------------------------------
1963 *
1964 * FlushChannel --
1965 *
1966 * This function flushes as much of the queued output as is possible
1967 * now. If calledFromAsyncFlush is nonzero, it is being called in an
1968 * event handler to flush channel output asynchronously.
1969 *
1970 * Results:
1971 * 0 if successful, else the error code that was returned by the
1972 * channel type operation.
1973 *
1974 * Side effects:
1975 * May produce output on a channel. May block indefinitely if the
1976 * channel is synchronous. May schedule an async flush on the channel.
1977 * May recycle memory for buffers in the output queue.
1978 *
1979 *----------------------------------------------------------------------
1980 */
1981
1982 static int
1983 FlushChannel(interp, chanPtr, calledFromAsyncFlush)
1984 Tcl_Interp *interp; /* For error reporting during close. */
1985 Channel *chanPtr; /* The channel to flush on. */
1986 int calledFromAsyncFlush; /* If nonzero then we are being
1987 * called from an asynchronous
1988 * flush callback. */
1989 {
1990 ChannelState *statePtr = chanPtr->state;
1991 /* State of the channel stack. */
1992 ChannelBuffer *bufPtr; /* Iterates over buffered output
1993 * queue. */
1994 int toWrite; /* Amount of output data in current
1995 * buffer available to be written. */
1996 int written; /* Amount of output data actually
1997 * written in current round. */
1998 int errorCode = 0; /* Stores POSIX error codes from
1999 * channel driver operations. */
2000 int wroteSome = 0; /* Set to one if any data was
2001 * written to the driver. */
2002
2003 /*
2004 * Prevent writing on a dead channel -- a channel that has been closed
2005 * but not yet deallocated. This can occur if the exit handler for the
2006 * channel deallocation runs before all channels are deregistered in
2007 * all interpreters.
2008 */
2009
2010 if (CheckForDeadChannel(interp, statePtr)) return -1;
2011
2012 /*
2013 * Loop over the queued buffers and attempt to flush as
2014 * much as possible of the queued output to the channel.
2015 */
2016
2017 while (1) {
2018
2019 /*
2020 * If the queue is empty and there is a ready current buffer, OR if
2021 * the current buffer is full, then move the current buffer to the
2022 * queue.
2023 */
2024
2025 if (((statePtr->curOutPtr != (ChannelBuffer *) NULL) &&
2026 (statePtr->curOutPtr->nextAdded == statePtr->curOutPtr->bufLength))
2027 || ((statePtr->flags & BUFFER_READY) &&
2028 (statePtr->outQueueHead == (ChannelBuffer *) NULL))) {
2029 statePtr->flags &= (~(BUFFER_READY));
2030 statePtr->curOutPtr->nextPtr = (ChannelBuffer *) NULL;
2031 if (statePtr->outQueueHead == (ChannelBuffer *) NULL) {
2032 statePtr->outQueueHead = statePtr->curOutPtr;
2033 } else {
2034 statePtr->outQueueTail->nextPtr = statePtr->curOutPtr;
2035 }
2036 statePtr->outQueueTail = statePtr->curOutPtr;
2037 statePtr->curOutPtr = (ChannelBuffer *) NULL;
2038 }
2039 bufPtr = statePtr->outQueueHead;
2040
2041 /*
2042 * If we are not being called from an async flush and an async
2043 * flush is active, we just return without producing any output.
2044 */
2045
2046 if ((!calledFromAsyncFlush) &&
2047 (statePtr->flags & BG_FLUSH_SCHEDULED)) {
2048 return 0;
2049 }
2050
2051 /*
2052 * If the output queue is still empty, break out of the while loop.
2053 */
2054
2055 if (bufPtr == (ChannelBuffer *) NULL) {
2056 break; /* Out of the "while (1)". */
2057 }
2058
2059 /*
2060 * Produce the output on the channel.
2061 */
2062
2063 toWrite = bufPtr->nextAdded - bufPtr->nextRemoved;
2064 written = (chanPtr->typePtr->outputProc) (chanPtr->instanceData,
2065 bufPtr->buf + bufPtr->nextRemoved, toWrite,
2066 &errorCode);
2067
2068 /*
2069 * If the write failed completely attempt to start the asynchronous
2070 * flush mechanism and break out of this loop - do not attempt to
2071 * write any more output at this time.
2072 */
2073
2074 if (written < 0) {
2075
2076 /*
2077 * If the last attempt to write was interrupted, simply retry.
2078 */
2079
2080 if (errorCode == EINTR) {
2081 errorCode = 0;
2082 continue;
2083 }
2084
2085 /*
2086 * If the channel is non-blocking and we would have blocked,
2087 * start a background flushing handler and break out of the loop.
2088 */
2089
2090 if ((errorCode == EWOULDBLOCK) || (errorCode == EAGAIN)) {
2091 /*
2092 * This used to check for CHANNEL_NONBLOCKING, and panic
2093 * if the channel was blocking. However, it appears
2094 * that setting stdin to -blocking 0 has some effect on
2095 * the stdout when it's a tty channel (dup'ed underneath)
2096 */
2097 if (!(statePtr->flags & BG_FLUSH_SCHEDULED)) {
2098 statePtr->flags |= BG_FLUSH_SCHEDULED;
2099 UpdateInterest(chanPtr);
2100 }
2101 errorCode = 0;
2102 break;
2103 }
2104
2105 /*
2106 * Decide whether to report the error upwards or defer it.
2107 */
2108
2109 if (calledFromAsyncFlush) {
2110 if (statePtr->unreportedError == 0) {
2111 statePtr->unreportedError = errorCode;
2112 }
2113 } else {
2114 Tcl_SetErrno(errorCode);
2115 if (interp != NULL) {
2116
2117 /*
2118 * Casting away CONST here is safe because the
2119 * TCL_VOLATILE flag guarantees CONST treatment
2120 * of the Posix error string.
2121 */
2122
2123 Tcl_SetResult(interp,
2124 (char *) Tcl_PosixError(interp), TCL_VOLATILE);
2125 }
2126 }
2127
2128 /*
2129 * When we get an error we throw away all the output
2130 * currently queued.
2131 */
2132
2133 DiscardOutputQueued(statePtr);
2134 continue;
2135 } else {
2136 wroteSome = 1;
2137 }
2138
2139 bufPtr->nextRemoved += written;
2140
2141 /*
2142 * If this buffer is now empty, recycle it.
2143 */
2144
2145 if (bufPtr->nextRemoved == bufPtr->nextAdded) {
2146 statePtr->outQueueHead = bufPtr->nextPtr;
2147 if (statePtr->outQueueHead == (ChannelBuffer *) NULL) {
2148 statePtr->outQueueTail = (ChannelBuffer *) NULL;
2149 }
2150 RecycleBuffer(statePtr, bufPtr, 0);
2151 }
2152 } /* Closes "while (1)". */
2153
2154 /*
2155 * If we wrote some data while flushing in the background, we are done.
2156 * We can't finish the background flush until we run out of data and
2157 * the channel becomes writable again. This ensures that all of the
2158 * pending data has been flushed at the system level.
2159 */
2160
2161 if (statePtr->flags & BG_FLUSH_SCHEDULED) {
2162 if (wroteSome) {
2163 return errorCode;
2164 } else if (statePtr->outQueueHead == (ChannelBuffer *) NULL) {
2165 statePtr->flags &= (~(BG_FLUSH_SCHEDULED));
2166 (chanPtr->typePtr->watchProc)(chanPtr->instanceData,
2167 statePtr->interestMask);
2168 }
2169 }
2170
2171 /*
2172 * If the channel is flagged as closed, delete it when the refCount
2173 * drops to zero, the output queue is empty and there is no output
2174 * in the current output buffer.
2175 */
2176
2177 if ((statePtr->flags & CHANNEL_CLOSED) && (statePtr->refCount <= 0) &&
2178 (statePtr->outQueueHead == (ChannelBuffer *) NULL) &&
2179 ((statePtr->curOutPtr == (ChannelBuffer *) NULL) ||
2180 (statePtr->curOutPtr->nextAdded ==
2181 statePtr->curOutPtr->nextRemoved))) {
2182 return CloseChannel(interp, chanPtr, errorCode);
2183 }
2184 return errorCode;
2185 }
2186
2187 /*
2188 *----------------------------------------------------------------------
2189 *
2190 * CloseChannel --
2191 *
2192 * Utility procedure to close a channel and free associated resources.
2193 *
2194 * If the channel was stacked, then the it will copy the necessary
2195 * elements of the NEXT channel into the TOP channel, in essence
2196 * unstacking the channel. The NEXT channel will then be freed.
2197 *
2198 * If the channel was not stacked, then we will free all the bits
2199 * for the TOP channel, including the data structure itself.
2200 *
2201 * Results:
2202 * 1 if the channel was stacked, 0 otherwise.
2203 *
2204 * Side effects:
2205 * May close the actual channel; may free memory.
2206 * May change the value of errno.
2207 *
2208 *----------------------------------------------------------------------
2209 */
2210
2211 static int
2212 CloseChannel(interp, chanPtr, errorCode)
2213 Tcl_Interp *interp; /* For error reporting. */
2214 Channel *chanPtr; /* The channel to close. */
2215 int errorCode; /* Status of operation so far. */
2216 {
2217 int result = 0; /* Of calling driver close
2218 * operation. */
2219 ChannelState *statePtr; /* state of the channel stack. */
2220 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2221
2222 if (chanPtr == NULL) {
2223 return result;
2224 }
2225 statePtr = chanPtr->state;
2226
2227 /*
2228 * No more input can be consumed so discard any leftover input.
2229 */
2230
2231 DiscardInputQueued(statePtr, 1);
2232
2233 /*
2234 * Discard a leftover buffer in the current output buffer field.
2235 */
2236
2237 if (statePtr->curOutPtr != (ChannelBuffer *) NULL) {
2238 ckfree((char *) statePtr->curOutPtr);
2239 statePtr->curOutPtr = (ChannelBuffer *) NULL;
2240 }
2241
2242 /*
2243 * The caller guarantees that there are no more buffers
2244 * queued for output.
2245 */
2246
2247 if (statePtr->outQueueHead != (ChannelBuffer *) NULL) {
2248 panic("TclFlush, closed channel: queued output left");
2249 }
2250
2251 /*
2252 * If the EOF character is set in the channel, append that to the
2253 * output device.
2254 */
2255
2256 if ((statePtr->outEofChar != 0) && (statePtr->flags & TCL_WRITABLE)) {
2257 int dummy;
2258 char c;
2259
2260 c = (char) statePtr->outEofChar;
2261 (chanPtr->typePtr->outputProc) (chanPtr->instanceData, &c, 1, &dummy);
2262 }
2263
2264 /*
2265 * Remove this channel from of the list of all channels.
2266 */
2267 Tcl_CutChannel((Tcl_Channel) chanPtr);
2268
2269 /*
2270 * Close and free the channel driver state.
2271 */
2272
2273 if (chanPtr->typePtr->closeProc != TCL_CLOSE2PROC) {
2274 result = (chanPtr->typePtr->closeProc)(chanPtr->instanceData, interp);
2275 } else {
2276 result = (chanPtr->typePtr->close2Proc)(chanPtr->instanceData, interp,
2277 0);
2278 }
2279
2280 /*
2281 * Some resources can be cleared only if the bottom channel
2282 * in a stack is closed. All the other channels in the stack
2283 * are not allowed to remove.
2284 */
2285
2286 if (chanPtr == statePtr->bottomChanPtr) {
2287 if (statePtr->channelName != (char *) NULL) {
2288 ckfree((char *) statePtr->channelName);
2289 statePtr->channelName = NULL;
2290 }
2291
2292 Tcl_FreeEncoding(statePtr->encoding);
2293 if (statePtr->outputStage != NULL) {
2294 ckfree((char *) statePtr->outputStage);
2295 statePtr->outputStage = (char *) NULL;
2296 }
2297 }
2298
2299 /*
2300 * If we are being called synchronously, report either
2301 * any latent error on the channel or the current error.
2302 */
2303
2304 if (statePtr->unreportedError != 0) {
2305 errorCode = statePtr->unreportedError;
2306 }
2307 if (errorCode == 0) {
2308 errorCode = result;
2309 if (errorCode != 0) {
2310 Tcl_SetErrno(errorCode);
2311 }
2312 }
2313
2314 /*
2315 * Cancel any outstanding timer.
2316 */
2317
2318 Tcl_DeleteTimerHandler(statePtr->timer);
2319
2320 /*
2321 * Mark the channel as deleted by clearing the type structure.
2322 */
2323
2324 if (chanPtr->downChanPtr != (Channel *) NULL) {
2325 Channel *downChanPtr = chanPtr->downChanPtr;
2326
2327 statePtr->nextCSPtr = tsdPtr->firstCSPtr;
2328 tsdPtr->firstCSPtr = statePtr;
2329
2330 statePtr->topChanPtr = downChanPtr;
2331 downChanPtr->upChanPtr = (Channel *) NULL;
2332 chanPtr->typePtr = NULL;
2333
2334 Tcl_EventuallyFree((ClientData) chanPtr, TCL_DYNAMIC);
2335 return Tcl_Close(interp, (Tcl_Channel) downChanPtr);
2336 }
2337
2338 /*
2339 * There is only the TOP Channel, so we free the remaining
2340 * pointers we have and then ourselves. Since this is the
2341 * last of the channels in the stack, make sure to free the
2342 * ChannelState structure associated with it. We use
2343 * Tcl_EventuallyFree to allow for any last
2344 */
2345 chanPtr->typePtr = NULL;
2346
2347 Tcl_EventuallyFree((ClientData) statePtr, TCL_DYNAMIC);
2348 Tcl_EventuallyFree((ClientData) chanPtr, TCL_DYNAMIC);
2349
2350 return errorCode;
2351 }
2352
2353 /*
2354 *----------------------------------------------------------------------
2355 *
2356 * Tcl_CutChannel --
2357 *
2358 * Removes a channel from the (thread-)global list of all channels
2359 * (in that thread). This is actually the statePtr for the stack
2360 * of channel.
2361 *
2362 * Results:
2363 * Nothing.
2364 *
2365 * Side effects:
2366 * Resets the field 'nextCSPtr' of the specified channel state to NULL.
2367 *
2368 * NOTE:
2369 * The channel to splice out of the list must not be referenced
2370 * in any interpreter. This is something this procedure cannot
2371 * check (despite the refcount) because the caller usually wants
2372 * fiddle with the channel (like transfering it to a different
2373 * thread) and thus keeps the refcount artifically high to prevent
2374 * its destruction.
2375 *
2376 *----------------------------------------------------------------------
2377 */
2378
2379 void
2380 Tcl_CutChannel(chan)
2381 Tcl_Channel chan; /* The channel being removed. Must
2382 * not be referenced in any
2383 * interpreter. */
2384 {
2385 ThreadSpecificData* tsdPtr = TCL_TSD_INIT(&dataKey);
2386 ChannelState *prevCSPtr; /* Preceding channel state in list of
2387 * all states - used to splice a
2388 * channel out of the list on close. */
2389 ChannelState *statePtr = ((Channel *) chan)->state;
2390 /* state of the channel stack. */
2391
2392 /*
2393 * Remove this channel from of the list of all channels
2394 * (in the current thread).
2395 */
2396
2397 if (tsdPtr->firstCSPtr && (statePtr == tsdPtr->firstCSPtr)) {
2398 tsdPtr->firstCSPtr = statePtr->nextCSPtr;
2399 } else {
2400 for (prevCSPtr = tsdPtr->firstCSPtr;
2401 prevCSPtr && (prevCSPtr->nextCSPtr != statePtr);
2402 prevCSPtr = prevCSPtr->nextCSPtr) {
2403 /* Empty loop body. */
2404 }
2405 if (prevCSPtr == (ChannelState *) NULL) {
2406 panic("FlushChannel: damaged channel list");
2407 }
2408 prevCSPtr->nextCSPtr = statePtr->nextCSPtr;
2409 }
2410
2411 statePtr->nextCSPtr = (ChannelState *) NULL;
2412
2413 TclpCutFileChannel(chan);
2414 }
2415
2416 /*
2417 *----------------------------------------------------------------------
2418 *
2419 * Tcl_SpliceChannel --
2420 *
2421 * Adds a channel to the (thread-)global list of all channels
2422 * (in that thread). Expects that the field 'nextChanPtr' in
2423 * the channel is set to NULL.
2424 *
2425 * Results:
2426 * Nothing.
2427 *
2428 * Side effects:
2429 * Nothing.
2430 *
2431 * NOTE:
2432 * The channel to add to the list must not be referenced in any
2433 * interpreter. This is something this procedure cannot check
2434 * (despite the refcount) because the caller usually wants figgle
2435 * with the channel (like transfering it to a different thread)
2436 * and thus keeps the refcount artifically high to prevent its
2437 * destruction.
2438 *
2439 *----------------------------------------------------------------------
2440 */
2441
2442 void
2443 Tcl_SpliceChannel(chan)
2444 Tcl_Channel chan; /* The channel being added. Must
2445 * not be referenced in any
2446 * interpreter. */
2447 {
2448 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2449 ChannelState *statePtr = ((Channel *) chan)->state;
2450
2451 if (statePtr->nextCSPtr != (ChannelState *) NULL) {
2452 panic("Tcl_SpliceChannel: trying to add channel used in different list");
2453 }
2454
2455 statePtr->nextCSPtr = tsdPtr->firstCSPtr;
2456 tsdPtr->firstCSPtr = statePtr;
2457
2458 /*
2459 * TIP #10. Mark the current thread as the new one managing this
2460 * channel. Note: 'Tcl_GetCurrentThread' returns sensible
2461 * values even for a non-threaded core.
2462 */
2463
2464 statePtr->managingThread = Tcl_GetCurrentThread ();
2465
2466 TclpSpliceFileChannel(chan);
2467 }
2468
2469 /*
2470 *----------------------------------------------------------------------
2471 *
2472 * Tcl_Close --
2473 *
2474 * Closes a channel.
2475 *
2476 * Results:
2477 * A standard Tcl result.
2478 *
2479 * Side effects:
2480 * Closes the channel if this is the last reference.
2481 *
2482 * NOTE:
2483 * Tcl_Close removes the channel as far as the user is concerned.
2484 * However, it may continue to exist for a while longer if it has
2485 * a background flush scheduled. The device itself is eventually
2486 * closed and the channel record removed, in CloseChannel, above.
2487 *
2488 *----------------------------------------------------------------------
2489 */
2490
2491 /* ARGSUSED */
2492 int
2493 Tcl_Close(interp, chan)
2494 Tcl_Interp *interp; /* Interpreter for errors. */
2495 Tcl_Channel chan; /* The channel being closed. Must
2496 * not be referenced in any
2497 * interpreter. */
2498 {
2499 CloseCallback *cbPtr; /* Iterate over close callbacks
2500 * for this channel. */
2501 Channel *chanPtr; /* The real IO channel. */
2502 ChannelState *statePtr; /* State of real IO channel. */
2503 int result; /* Of calling FlushChannel. */
2504
2505 if (chan == (Tcl_Channel) NULL) {
2506 return TCL_OK;
2507 }
2508
2509 /*
2510 * Perform special handling for standard channels being closed. If the
2511 * refCount is now 1 it means that the last reference to the standard
2512 * channel is being explicitly closed, so bump the refCount down
2513 * artificially to 0. This will ensure that the channel is actually
2514 * closed, below. Also set the static pointer to NULL for the channel.
2515 */
2516
2517 CheckForStdChannelsBeingClosed(chan);
2518
2519 /*
2520 * This operation should occur at the top of a channel stack.
2521 */
2522
2523 chanPtr = (Channel *) chan;
2524 statePtr = chanPtr->state;
2525 chanPtr = statePtr->topChanPtr;
2526
2527 if (statePtr->refCount > 0) {
2528 panic("called Tcl_Close on channel with refCount > 0");
2529 }
2530
2531 /*
2532 * When the channel has an escape sequence driven encoding such as
2533 * iso2022, the terminated escape sequence must write to the buffer.
2534 */
2535 if ((statePtr->encoding != NULL) && (statePtr->curOutPtr != NULL)
2536 && (CheckChannelErrors(statePtr, TCL_WRITABLE) == 0)) {
2537 statePtr->outputEncodingFlags |= TCL_ENCODING_END;
2538 WriteChars(chanPtr, "", 0);
2539 }
2540
2541 Tcl_ClearChannelHandlers(chan);
2542
2543 /*
2544 * Invoke the registered close callbacks and delete their records.
2545 */
2546
2547 while (statePtr->closeCbPtr != (CloseCallback *) NULL) {
2548 cbPtr = statePtr->closeCbPtr;
2549 statePtr->closeCbPtr = cbPtr->nextPtr;
2550 (cbPtr->proc) (cbPtr->clientData);
2551 ckfree((char *) cbPtr);
2552 }
2553
2554 /*
2555 * Ensure that the last output buffer will be flushed.
2556 */
2557
2558 if ((statePtr->curOutPtr != (ChannelBuffer *) NULL) &&
2559 (statePtr->curOutPtr->nextAdded > statePtr->curOutPtr->nextRemoved)) {
2560 statePtr->flags |= BUFFER_READY;
2561 }
2562
2563 /*
2564 * If this channel supports it, close the read side, since we don't need it
2565 * anymore and this will help avoid deadlocks on some channel types.
2566 */
2567
2568 if (chanPtr->typePtr->closeProc == TCL_CLOSE2PROC) {
2569 result = (chanPtr->typePtr->close2Proc)(chanPtr->instanceData, interp,
2570 TCL_CLOSE_READ);
2571 } else {
2572 result = 0;
2573 }
2574
2575 /*
2576 * The call to FlushChannel will flush any queued output and invoke
2577 * the close function of the channel driver, or it will set up the
2578 * channel to be flushed and closed asynchronously.
2579 */
2580
2581 statePtr->flags |= CHANNEL_CLOSED;
2582 if ((FlushChannel(interp, chanPtr, 0) != 0) || (result != 0)) {
2583 return TCL_ERROR;
2584 }
2585 return TCL_OK;
2586 }
2587
2588 /*
2589 *----------------------------------------------------------------------
2590 *
2591 * Tcl_ClearChannelHandlers --
2592 *
2593 * Removes all channel handlers and event scripts from the channel,
2594 * cancels all background copies involving the channel and any interest
2595 * in events.
2596 *
2597 * Results:
2598 * None.
2599 *
2600 * Side effects:
2601 * See above. Deallocates memory.
2602 *
2603 *----------------------------------------------------------------------
2604 */
2605
2606 void
2607 Tcl_ClearChannelHandlers (channel)
2608 Tcl_Channel channel;
2609 {
2610 ChannelHandler *chPtr, *chNext; /* Iterate over channel handlers. */
2611 EventScriptRecord *ePtr, *eNextPtr; /* Iterate over eventscript records. */
2612 Channel *chanPtr; /* The real IO channel. */
2613 ChannelState *statePtr; /* State of real IO channel. */
2614 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2615 NextChannelHandler *nhPtr;
2616
2617 /*
2618 * This operation should occur at the top of a channel stack.
2619 */
2620
2621 chanPtr = (Channel *) channel;
2622 statePtr = chanPtr->state;
2623 chanPtr = statePtr->topChanPtr;
2624
2625 /*
2626 * Remove any references to channel handlers for this channel that
2627 * may be about to be invoked.
2628 */
2629
2630 for (nhPtr = tsdPtr->nestedHandlerPtr;
2631 nhPtr != (NextChannelHandler *) NULL;
2632 nhPtr = nhPtr->nestedHandlerPtr) {
2633 if (nhPtr->nextHandlerPtr &&
2634 (nhPtr->nextHandlerPtr->chanPtr == chanPtr)) {
2635 nhPtr->nextHandlerPtr = NULL;
2636 }
2637 }
2638
2639 /*
2640 * Remove all the channel handler records attached to the channel
2641 * itself.
2642 */
2643
2644 for (chPtr = statePtr->chPtr;
2645 chPtr != (ChannelHandler *) NULL;
2646 chPtr = chNext) {
2647 chNext = chPtr->nextPtr;
2648 ckfree((char *) chPtr);
2649 }
2650 statePtr->chPtr = (ChannelHandler *) NULL;
2651
2652 /*
2653 * Cancel any pending copy operation.
2654 */
2655
2656 StopCopy(statePtr->csPtr);
2657
2658 /*
2659 * Must set the interest mask now to 0, otherwise infinite loops
2660 * will occur if Tcl_DoOneEvent is called before the channel is
2661 * finally deleted in FlushChannel. This can happen if the channel
2662 * has a background flush active.
2663 */
2664
2665 statePtr->interestMask = 0;
2666
2667 /*
2668 * Remove any EventScript records for this channel.
2669 */
2670
2671 for (ePtr = statePtr->scriptRecordPtr;
2672 ePtr != (EventScriptRecord *) NULL;
2673 ePtr = eNextPtr) {
2674 eNextPtr = ePtr->nextPtr;
2675 Tcl_DecrRefCount(ePtr->scriptPtr);
2676 ckfree((char *) ePtr);
2677 }
2678 statePtr->scriptRecordPtr = (EventScriptRecord *) NULL;
2679 }
2680
2681 /*
2682 *----------------------------------------------------------------------
2683 *
2684 * Tcl_Write --
2685 *
2686 * Puts a sequence of bytes into an output buffer, may queue the
2687 * buffer for output if it gets full, and also remembers whether the
2688 * current buffer is ready e.g. if it contains a newline and we are in
2689 * line buffering mode. Compensates stacking, i.e. will redirect the
2690 * data from the specified channel to the topmost channel in a stack.
2691 *
2692 * No encoding conversions are applied to the bytes being read.
2693 *
2694 * Results:
2695 * The number of bytes written or -1 in case of error. If -1,
2696 * Tcl_GetErrno will return the error code.
2697 *
2698 * Side effects:
2699 * May buffer up output and may cause output to be produced on the
2700 * channel.
2701 *
2702 *----------------------------------------------------------------------
2703 */
2704
2705 int
2706 Tcl_Write(chan, src, srcLen)
2707 Tcl_Channel chan; /* The channel to buffer output for. */
2708 CONST char *src; /* Data to queue in output buffer. */
2709 int srcLen; /* Length of data in bytes, or < 0 for
2710 * strlen(). */
2711 {
2712 /*
2713 * Always use the topmost channel of the stack
2714 */
2715 Channel *chanPtr;
2716 ChannelState *statePtr; /* state info for channel */
2717
2718 statePtr = ((Channel *) chan)->state;
2719 chanPtr = statePtr->topChanPtr;
2720
2721 if (CheckChannelErrors(statePtr, TCL_WRITABLE) != 0) {
2722 return -1;
2723 }
2724
2725 if (srcLen < 0) {
2726 srcLen = strlen(src);
2727 }
2728 return DoWrite(chanPtr, src, srcLen);
2729 }
2730
2731 /*
2732 *----------------------------------------------------------------------
2733 *
2734 * Tcl_WriteRaw --
2735 *
2736 * Puts a sequence of bytes into an output buffer, may queue the
2737 * buffer for output if it gets full, and also remembers whether the
2738 * current buffer is ready e.g. if it contains a newline and we are in
2739 * line buffering mode. Writes directly to the driver of the channel,
2740 * does not compensate for stacking.
2741 *
2742 * No encoding conversions are applied to the bytes being read.
2743 *
2744 * Results:
2745 * The number of bytes written or -1 in case of error. If -1,
2746 * Tcl_GetErrno will return the error code.
2747 *
2748 * Side effects:
2749 * May buffer up output and may cause output to be produced on the
2750 * channel.
2751 *
2752 *----------------------------------------------------------------------
2753 */
2754
2755 int
2756 Tcl_WriteRaw(chan, src, srcLen)
2757 Tcl_Channel chan; /* The channel to buffer output for. */
2758 CONST char *src; /* Data to queue in output buffer. */
2759 int srcLen; /* Length of data in bytes, or < 0 for
2760 * strlen(). */
2761 {
2762 Channel *chanPtr = ((Channel *) chan);
2763 ChannelState *statePtr = chanPtr->state; /* state info for channel */
2764 int errorCode, written;
2765
2766 if (CheckChannelErrors(statePtr, TCL_WRITABLE | CHANNEL_RAW_MODE) != 0) {
2767 return -1;
2768 }
2769
2770 if (srcLen < 0) {
2771 srcLen = strlen(src);
2772 }
2773
2774 /*
2775 * Go immediately to the driver, do all the error handling by ourselves.
2776 * The code was stolen from 'FlushChannel'.
2777 */
2778
2779 written = (chanPtr->typePtr->outputProc) (chanPtr->instanceData,
2780 src, srcLen, &errorCode);
2781
2782 if (written < 0) {
2783 Tcl_SetErrno(errorCode);
2784 }
2785
2786 return written;
2787 }
2788
2789 /*
2790 *---------------------------------------------------------------------------
2791 *
2792 * Tcl_WriteChars --
2793 *
2794 * Takes a sequence of UTF-8 characters and converts them for output
2795 * using the channel's current encoding, may queue the buffer for
2796 * output if it gets full, and also remembers whether the current
2797 * buffer is ready e.g. if it contains a newline and we are in
2798 * line buffering mode. Compensates stacking, i.e. will redirect the
2799 * data from the specified channel to the topmost channel in a stack.
2800 *
2801 * Results:
2802 * The number of bytes written or -1 in case of error. If -1,
2803 * Tcl_GetErrno will return the error code.
2804 *
2805 * Side effects:
2806 * May buffer up output and may cause output to be produced on the
2807 * channel.
2808 *
2809 *----------------------------------------------------------------------
2810 */
2811
2812 int
2813 Tcl_WriteChars(chan, src, len)
2814 Tcl_Channel chan; /* The channel to buffer output for. */
2815 CONST char *src; /* UTF-8 characters to queue in output buffer. */
2816 int len; /* Length of string in bytes, or < 0 for
2817 * strlen(). */
2818 {
2819 ChannelState *statePtr; /* state info for channel */
2820
2821 statePtr = ((Channel *) chan)->state;
2822
2823 if (CheckChannelErrors(statePtr, TCL_WRITABLE) != 0) {
2824 return -1;
2825 }
2826
2827 return DoWriteChars ((Channel*) chan, src, len);
2828 }
2829
2830 /*
2831 *---------------------------------------------------------------------------
2832 *
2833 * DoWriteChars --
2834 *
2835 * Takes a sequence of UTF-8 characters and converts them for output
2836 * using the channel's current encoding, may queue the buffer for
2837 * output if it gets full, and also remembers whether the current
2838 * buffer is ready e.g. if it contains a newline and we are in
2839 * line buffering mode. Compensates stacking, i.e. will redirect the
2840 * data from the specified channel to the topmost channel in a stack.
2841 *
2842 * Results:
2843 * The number of bytes written or -1 in case of error. If -1,
2844 * Tcl_GetErrno will return the error code.
2845 *
2846 * Side effects:
2847 * May buffer up output and may cause output to be produced on the
2848 * channel.
2849 *
2850 *----------------------------------------------------------------------
2851 */
2852
2853 static int
2854 DoWriteChars(chanPtr, src, len)
2855 Channel* chanPtr; /* The channel to buffer output for. */
2856 CONST char *src; /* UTF-8 characters to queue in output buffer. */
2857 int len; /* Length of string in bytes, or < 0 for
2858 * strlen(). */
2859 {
2860 /*
2861 * Always use the topmost channel of the stack
2862 */
2863 ChannelState *statePtr; /* state info for channel */
2864
2865 statePtr = chanPtr->state;
2866 chanPtr = statePtr->topChanPtr;
2867
2868 if (len < 0) {
2869 len = strlen(src);
2870 }
2871 if (statePtr->encoding == NULL) {
2872 /*
2873 * Inefficient way to convert UTF-8 to byte-array, but the
2874 * code parallels the way it is done for objects.
2875 */
2876
2877 Tcl_Obj *objPtr;
2878 int result;
2879
2880 objPtr = Tcl_NewStringObj(src, len);
2881 src = (char *) Tcl_GetByteArrayFromObj(objPtr, &len);
2882 result = WriteBytes(chanPtr, src, len);
2883 Tcl_DecrRefCount(objPtr);
2884 return result;
2885 }
2886 return WriteChars(chanPtr, src, len);
2887 }
2888
2889 /*
2890 *---------------------------------------------------------------------------
2891 *
2892 * Tcl_WriteObj --
2893 *
2894 * Takes the Tcl object and queues its contents for output. If the
2895 * encoding of the channel is NULL, takes the byte-array representation
2896 * of the object and queues those bytes for output. Otherwise, takes
2897 * the characters in the UTF-8 (string) representation of the object
2898 * and converts them for output using the channel's current encoding.
2899 * May flush internal buffers to output if one becomes full or is ready
2900 * for some other reason, e.g. if it contains a newline and the channel
2901 * is in line buffering mode.
2902 *
2903 * Results:
2904 * The number of bytes written or -1 in case of error. If -1,
2905 * Tcl_GetErrno() will return the error code.
2906 *
2907 * Side effects:
2908 * May buffer up output and may cause output to be produced on the
2909 * channel.
2910 *
2911 *----------------------------------------------------------------------
2912 */
2913
2914 int
2915 Tcl_WriteObj(chan, objPtr)
2916 Tcl_Channel chan; /* The channel to buffer output for. */
2917 Tcl_Obj *objPtr; /* The object to write. */
2918 {
2919 /*
2920 * Always use the topmost channel of the stack
2921 */
2922 Channel *chanPtr;
2923 ChannelState *statePtr; /* state info for channel */
2924 char *src;
2925 int srcLen;
2926
2927 statePtr = ((Channel *) chan)->state;
2928 chanPtr = statePtr->topChanPtr;
2929
2930 if (CheckChannelErrors(statePtr, TCL_WRITABLE) != 0) {
2931 return -1;
2932 }
2933 if (statePtr->encoding == NULL) {
2934 src = (char *) Tcl_GetByteArrayFromObj(objPtr, &srcLen);
2935 return WriteBytes(chanPtr, src, srcLen);
2936 } else {
2937 src = Tcl_GetStringFromObj(objPtr, &srcLen);
2938 return WriteChars(chanPtr, src, srcLen);
2939 }
2940 }
2941
2942 /*
2943 *----------------------------------------------------------------------
2944 *
2945 * WriteBytes --
2946 *
2947 * Write a sequence of bytes into an output buffer, may queue the
2948 * buffer for output if it gets full, and also remembers whether the
2949 * current buffer is ready e.g. if it contains a newline and we are in
2950 * line buffering mode.
2951 *
2952 * Results:
2953 * The number of bytes written or -1 in case of error. If -1,
2954 * Tcl_GetErrno will return the error code.
2955 *
2956 * Side effects:
2957 * May buffer up output and may cause output to be produced on the
2958 * channel.
2959 *
2960 *----------------------------------------------------------------------
2961 */
2962
2963 static int
2964 WriteBytes(chanPtr, src, srcLen)
2965 Channel *chanPtr; /* The channel to buffer output for. */
2966 CONST char *src; /* Bytes to write. */
2967 int srcLen; /* Number of bytes to write. */
2968 {
2969 ChannelState *statePtr = chanPtr->state; /* state info for channel */
2970 ChannelBuffer *bufPtr;
2971 char *dst;
2972 int dstMax, sawLF, savedLF, total, dstLen, toWrite;
2973
2974 total = 0;
2975 sawLF = 0;
2976 savedLF = 0;
2977
2978 /*
2979 * Loop over all bytes in src, storing them in output buffer with
2980 * proper EOL translation.
2981 */
2982
2983 while (srcLen + savedLF > 0) {
2984 bufPtr = statePtr->curOutPtr;
2985 if (bufPtr == NULL) {
2986 bufPtr = AllocChannelBuffer(statePtr->bufSize);
2987 statePtr->curOutPtr = bufPtr;
2988 }
2989 dst = bufPtr->buf + bufPtr->nextAdded;
2990 dstMax = bufPtr->bufLength - bufPtr->nextAdded;
2991 dstLen = dstMax;
2992
2993 toWrite = dstLen;
2994 if (toWrite > srcLen) {
2995 toWrite = srcLen;
2996 }
2997
2998 if (savedLF) {
2999 /*
3000 * A '\n' was left over from last call to TranslateOutputEOL()
3001 * and we need to store it in this buffer. If the channel is
3002 * line-based, we will need to flush it.
3003 */
3004
3005 *dst++ = '\n';
3006 dstLen--;
3007 sawLF++;
3008 }
3009 sawLF += TranslateOutputEOL(statePtr, dst, src, &dstLen, &toWrite);
3010 dstLen += savedLF;
3011 savedLF = 0;
3012
3013 if (dstLen > dstMax) {
3014 savedLF = 1;
3015 dstLen = dstMax;
3016 }
3017 bufPtr->nextAdded += dstLen;
3018 if (CheckFlush(chanPtr, bufPtr, sawLF) != 0) {
3019 return -1;
3020 }
3021 total += dstLen;
3022 src += toWrite;
3023 srcLen -= toWrite;
3024 sawLF = 0;
3025 }
3026 return total;
3027 }
3028
3029 /*
3030 *----------------------------------------------------------------------
3031 *
3032 * WriteChars --
3033 *
3034 * Convert UTF-8 bytes to the channel's external encoding and
3035 * write the produced bytes into an output buffer, may queue the
3036 * buffer for output if it gets full, and also remembers whether the
3037 * current buffer is ready e.g. if it contains a newline and we are in
3038 * line buffering mode.
3039 *
3040 * Results:
3041 * The number of bytes written or -1 in case of error. If -1,
3042 * Tcl_GetErrno will return the error code.
3043 *
3044 * Side effects:
3045 * May buffer up output and may cause output to be produced on the
3046 * channel.
3047 *
3048 *----------------------------------------------------------------------
3049 */
3050
3051 static int
3052 WriteChars(chanPtr, src, srcLen)
3053 Channel *chanPtr; /* The channel to buffer output for. */
3054 CONST char *src; /* UTF-8 string to write. */
3055 int srcLen; /* Length of UTF-8 string in bytes. */
3056 {
3057 ChannelState *statePtr = chanPtr->state; /* state info for channel */
3058 ChannelBuffer *bufPtr;
3059 char *dst, *stage;
3060 int saved, savedLF, sawLF, total, dstLen, stageMax, dstWrote;
3061 int stageLen, toWrite, stageRead, endEncoding, result;
3062 int consumedSomething;
3063 Tcl_Encoding encoding;
3064 char safe[BUFFER_PADDING];
3065
3066 total = 0;
3067 sawLF = 0;
3068 savedLF = 0;
3069 saved = 0;
3070 encoding = statePtr->encoding;
3071
3072 /*
3073 * Write the terminated escape sequence even if srcLen is 0.
3074 */
3075
3076 endEncoding = ((statePtr->outputEncodingFlags & TCL_ENCODING_END) != 0);
3077
3078 /*
3079 * Loop over all UTF-8 characters in src, storing them in staging buffer
3080 * with proper EOL translation.
3081 */
3082
3083 consumedSomething = 1;
3084 while (consumedSomething && (srcLen + savedLF + endEncoding > 0)) {
3085 consumedSomething = 0;
3086 stage = statePtr->outputStage;
3087 stageMax = statePtr->bufSize;
3088 stageLen = stageMax;
3089
3090 toWrite = stageLen;
3091 if (toWrite > srcLen) {
3092 toWrite = srcLen;
3093 }
3094
3095 if (savedLF) {
3096 /*
3097 * A '\n' was left over from last call to TranslateOutputEOL()
3098 * and we need to store it in the staging buffer. If the
3099 * channel is line-based, we will need to flush the output
3100 * buffer (after translating the staging buffer).
3101 */
3102
3103 *stage++ = '\n';
3104 stageLen--;
3105 sawLF++;
3106 }
3107 sawLF += TranslateOutputEOL(statePtr, stage, src, &stageLen, &toWrite);
3108
3109 stage -= savedLF;
3110 stageLen += savedLF;
3111 savedLF = 0;
3112
3113 if (stageLen > stageMax) {
3114 savedLF = 1;
3115 stageLen = stageMax;
3116 }
3117 src += toWrite;
3118 srcLen -= toWrite;
3119
3120 /*
3121 * Loop over all UTF-8 characters in staging buffer, converting them
3122 * to external encoding, storing them in output buffer.
3123 */
3124
3125 while (stageLen + saved + endEncoding > 0) {
3126 bufPtr = statePtr->curOutPtr;
3127 if (bufPtr == NULL) {
3128 bufPtr = AllocChannelBuffer(statePtr->bufSize);
3129 statePtr->curOutPtr = bufPtr;
3130 }
3131 dst = bufPtr->buf + bufPtr->nextAdded;
3132 dstLen = bufPtr->bufLength - bufPtr->nextAdded;
3133
3134 if (saved != 0) {
3135 /*
3136 * Here's some translated bytes left over from the last
3137 * buffer that we need to stick at the beginning of this
3138 * buffer.
3139 */
3140
3141 memcpy((VOID *) dst, (VOID *) safe, (size_t) saved);
3142 bufPtr->nextAdded += saved;
3143 dst += saved;
3144 dstLen -= saved;
3145 saved = 0;
3146 }
3147
3148 result = Tcl_UtfToExternal(NULL, encoding, stage, stageLen,
3149 statePtr->outputEncodingFlags,
3150 &statePtr->outputEncodingState, dst,
3151 dstLen + BUFFER_PADDING, &stageRead, &dstWrote, NULL);
3152
3153 /* Fix for SF #506297, reported by Martin Forssen
3154 * <[email protected]>.
3155 *
3156 * The encoding chosen in the script exposing the bug writes out
3157 * three intro characters when TCL_ENCODING_START is set, but does
3158 * not consume any input as TCL_ENCODING_END is cleared. As some
3159 * output was generated the enclosing loop calls UtfToExternal
3160 * again, again with START set. Three more characters in the out
3161 * and still no use of input ... To break this infinite loop we
3162 * remove TCL_ENCODING_START from the set of flags after the first
3163 * call (no condition is required, the later calls remove an unset
3164 * flag, which is a no-op). This causes the subsequent calls to
3165 * UtfToExternal to consume and convert the actual input.
3166 */
3167
3168 statePtr->outputEncodingFlags &= ~TCL_ENCODING_START;
3169 /*
3170 * The following code must be executed only when result is not 0.
3171 */
3172 if (result && ((stageRead + dstWrote) == 0)) {
3173 /*
3174 * We have an incomplete UTF-8 character at the end of the
3175 * staging buffer. It will get moved to the beginning of the
3176 * staging buffer followed by more bytes from src.
3177 */
3178
3179 src -= stageLen;
3180 srcLen += stageLen;
3181 stageLen = 0;
3182 savedLF = 0;
3183 break;
3184 }
3185 bufPtr->nextAdded += dstWrote;
3186 if (bufPtr->nextAdded > bufPtr->bufLength) {
3187 /*
3188 * When translating from UTF-8 to external encoding, we
3189 * allowed the translation to produce a character that
3190 * crossed the end of the output buffer, so that we would
3191 * get a completely full buffer before flushing it. The
3192 * extra bytes will be moved to the beginning of the next
3193 * buffer.
3194 */
3195
3196 saved = bufPtr->nextAdded - bufPtr->bufLength;
3197 memcpy((VOID *) safe, (VOID *) (dst + dstLen), (size_t) saved);
3198 bufPtr->nextAdded = bufPtr->bufLength;
3199 }
3200 if (CheckFlush(chanPtr, bufPtr, sawLF) != 0) {
3201 return -1;
3202 }
3203
3204 total += dstWrote;
3205 stage += stageRead;
3206 stageLen -= stageRead;
3207 sawLF = 0;
3208
3209 consumedSomething = 1;
3210
3211 /*
3212 * If all translated characters are written to the buffer,
3213 * endEncoding is set to 0 because the escape sequence may be
3214 * output.
3215 */
3216
3217 if ((stageLen + saved == 0) && (result == 0)) {
3218 endEncoding = 0;
3219 }
3220 }
3221 }
3222
3223 /* If nothing was written and it happened because there was no progress
3224 * in the UTF conversion, we throw an error.
3225 */
3226
3227 if (!consumedSomething && (total == 0)) {
3228 Tcl_SetErrno (EINVAL);
3229 return -1;
3230 }
3231 return total;
3232 }
3233
3234 /*
3235 *---------------------------------------------------------------------------
3236 *
3237 * TranslateOutputEOL --
3238 *
3239 * Helper function for WriteBytes() and WriteChars(). Converts the
3240 * '\n' characters in the source buffer into the appropriate EOL
3241 * form specified by the output translation mode.
3242 *
3243 * EOL translation stops either when the source buffer is empty
3244 * or the output buffer is full.
3245 *
3246 * When converting to CRLF mode and there is only 1 byte left in
3247 * the output buffer, this routine stores the '\r' in the last
3248 * byte and then stores the '\n' in the byte just past the end of the
3249 * buffer. The caller is responsible for passing in a buffer that
3250 * is large enough to hold the extra byte.
3251 *
3252 * Results:
3253 * The return value is 1 if a '\n' was translated from the source
3254 * buffer, or 0 otherwise -- this can be used by the caller to
3255 * decide to flush a line-based channel even though the channel
3256 * buffer is not full.
3257 *
3258 * *dstLenPtr is filled with how many bytes of the output buffer
3259 * were used. As mentioned above, this can be one more that
3260 * the output buffer's specified length if a CRLF was stored.
3261 *
3262 * *srcLenPtr is filled with how many bytes of the source buffer
3263 * were consumed.
3264 *
3265 * Side effects:
3266 * It may be obvious, but bears mentioning that when converting
3267 * in CRLF mode (which requires two bytes of storage in the output
3268 * buffer), the number of bytes consumed from the source buffer
3269 * will be less than the number of bytes stored in the output buffer.
3270 *
3271 *---------------------------------------------------------------------------
3272 */
3273
3274 static int
3275 TranslateOutputEOL(statePtr, dst, src, dstLenPtr, srcLenPtr)
3276 ChannelState *statePtr; /* Channel being read, for translation and
3277 * buffering modes. */
3278 char *dst; /* Output buffer filled with UTF-8 chars by
3279 * applying appropriate EOL translation to
3280 * source characters. */
3281 CONST char *src; /* Source UTF-8 characters. */
3282 int *dstLenPtr; /* On entry, the maximum length of output
3283 * buffer in bytes. On exit, the number of
3284 * bytes actually used in output buffer. */
3285 int *srcLenPtr; /* On entry, the length of source buffer.
3286 * On exit, the number of bytes read from
3287 * the source buffer. */
3288 {
3289 char *dstEnd;
3290 int srcLen, newlineFound;
3291
3292 newlineFound = 0;
3293 srcLen = *srcLenPtr;
3294
3295 switch (statePtr->outputTranslation) {
3296 case TCL_TRANSLATE_LF: {
3297 for (dstEnd = dst + srcLen; dst < dstEnd; ) {
3298 if (*src == '\n') {
3299 newlineFound = 1;
3300 }
3301 *dst++ = *src++;
3302 }
3303 *dstLenPtr = srcLen;
3304 break;
3305 }
3306 case TCL_TRANSLATE_CR: {
3307 for (dstEnd = dst + srcLen; dst < dstEnd;) {
3308 if (*src == '\n') {
3309 *dst++ = '\r';
3310 newlineFound = 1;
3311 src++;
3312 } else {
3313 *dst++ = *src++;
3314 }
3315 }
3316 *dstLenPtr = srcLen;
3317 break;
3318 }
3319 case TCL_TRANSLATE_CRLF: {
3320 /*
3321 * Since this causes the number of bytes to grow, we
3322 * start off trying to put 'srcLen' bytes into the
3323 * output buffer, but allow it to store more bytes, as
3324 * long as there's still source bytes and room in the
3325 * output buffer.
3326 */
3327
3328 char *dstStart, *dstMax;
3329 CONST char *srcStart;
3330
3331 dstStart = dst;
3332 dstMax = dst + *dstLenPtr;
3333
3334 srcStart = src;
3335
3336 if (srcLen < *dstLenPtr) {
3337 dstEnd = dst + srcLen;
3338 } else {
3339 dstEnd = dst + *dstLenPtr;
3340 }
3341 while (dst < dstEnd) {
3342 if (*src == '\n') {
3343 if (dstEnd < dstMax) {
3344 dstEnd++;
3345 }
3346 *dst++ = '\r';
3347 newlineFound = 1;
3348 }
3349 *dst++ = *src++;
3350 }
3351 *srcLenPtr = src - srcStart;
3352 *dstLenPtr = dst - dstStart;
3353 break;
3354 }
3355 default: {
3356 break;
3357 }
3358 }
3359 return newlineFound;
3360 }
3361
3362 /*
3363 *---------------------------------------------------------------------------
3364 *
3365 * CheckFlush --
3366 *
3367 * Helper function for WriteBytes() and WriteChars(). If the
3368 * channel buffer is ready to be flushed, flush it.
3369 *
3370 * Results:
3371 * The return value is -1 if there was a problem flushing the
3372 * channel buffer, or 0 otherwise.
3373 *
3374 * Side effects:
3375 * The buffer will be recycled if it is flushed.
3376 *
3377 *---------------------------------------------------------------------------
3378 */
3379
3380 static int
3381 CheckFlush(chanPtr, bufPtr, newlineFlag)
3382 Channel *chanPtr; /* Channel being read, for buffering mode. */
3383 ChannelBuffer *bufPtr; /* Channel buffer to possibly flush. */
3384 int newlineFlag; /* Non-zero if a the channel buffer
3385 * contains a newline. */
3386 {
3387 ChannelState *statePtr = chanPtr->state; /* state info for channel */
3388 /*
3389 * The current buffer is ready for output:
3390 * 1. if it is full.
3391 * 2. if it contains a newline and this channel is line-buffered.
3392 * 3. if it contains any output and this channel is unbuffered.
3393 */
3394
3395 if ((statePtr->flags & BUFFER_READY) == 0) {
3396 if (bufPtr->nextAdded == bufPtr->bufLength) {
3397 statePtr->flags |= BUFFER_READY;
3398 } else if (statePtr->flags & CHANNEL_LINEBUFFERED) {
3399 if (newlineFlag != 0) {
3400 statePtr->flags |= BUFFER_READY;
3401 }
3402 } else if (statePtr->flags & CHANNEL_UNBUFFERED) {
3403 statePtr->flags |= BUFFER_READY;
3404 }
3405 }
3406 if (statePtr->flags & BUFFER_READY) {
3407 if (FlushChannel(NULL, chanPtr, 0) != 0) {
3408 return -1;
3409 }
3410 }
3411 return 0;
3412 }
3413
3414 /*
3415 *---------------------------------------------------------------------------
3416 *
3417 * Tcl_Gets --
3418 *
3419 * Reads a complete line of input from the channel into a Tcl_DString.
3420 *
3421 * Results:
3422 * Length of line read (in characters) or -1 if error, EOF, or blocked.
3423 * If -1, use Tcl_GetErrno() to retrieve the POSIX error code for the
3424 * error or condition that occurred.
3425 *
3426 * Side effects:
3427 * May flush output on the channel. May cause input to be consumed
3428 * from the channel.
3429 *
3430 *---------------------------------------------------------------------------
3431 */
3432
3433 int
3434 Tcl_Gets(chan, lineRead)
3435 Tcl_Channel chan; /* Channel from which to read. */
3436 Tcl_DString *lineRead; /* The line read will be appended to this
3437 * DString as UTF-8 characters. The caller
3438 * must have initialized it and is responsible
3439 * for managing the storage. */
3440 {
3441 Tcl_Obj *objPtr;
3442 int charsStored, length;
3443 char *string;
3444
3445 objPtr = Tcl_NewObj();
3446 charsStored = Tcl_GetsObj(chan, objPtr);
3447 if (charsStored > 0) {
3448 string = Tcl_GetStringFromObj(objPtr, &length);
3449 Tcl_DStringAppend(lineRead, string, length);
3450 }
3451 Tcl_DecrRefCount(objPtr);
3452 return charsStored;
3453 }
3454
3455 /*
3456 *---------------------------------------------------------------------------
3457 *
3458 * Tcl_GetsObj --
3459 *
3460 * Accumulate input from the input channel until end-of-line or
3461 * end-of-file has been seen. Bytes read from the input channel
3462 * are converted to UTF-8 using the encoding specified by the
3463 * channel.
3464 *
3465 * Results:
3466 * Number of characters accumulated in the object or -1 if error,
3467 * blocked, or EOF. If -1, use Tcl_GetErrno() to retrieve the
3468 * POSIX error code for the error or condition that occurred.
3469 *
3470 * Side effects:
3471 * Consumes input from the channel.
3472 *
3473 * On reading EOF, leave channel pointing at EOF char.
3474 * On reading EOL, leave channel pointing after EOL, but don't
3475 * return EOL in dst buffer.
3476 *
3477 *---------------------------------------------------------------------------
3478 */
3479
3480 int
3481 Tcl_GetsObj(chan, objPtr)
3482 Tcl_Channel chan; /* Channel from which to read. */
3483 Tcl_Obj *objPtr; /* The line read will be appended to this
3484 * object as UTF-8 characters. */
3485 {
3486 GetsState gs;
3487 Channel *chanPtr = (Channel *) chan;
3488 ChannelState *statePtr = chanPtr->state; /* state info for channel */
3489 ChannelBuffer *bufPtr;
3490 int inEofChar, skip, copiedTotal, oldLength, oldFlags, oldRemoved;
3491 Tcl_Encoding encoding;
3492 char *dst, *dstEnd, *eol, *eof;
3493 Tcl_EncodingState oldState;
3494
3495 /*
3496 * This operation should occur at the top of a channel stack.
3497 */
3498
3499 chanPtr = statePtr->topChanPtr;
3500
3501 if (CheckChannelErrors(statePtr, TCL_READABLE) != 0) {
3502 copiedTotal = -1;
3503 goto done;
3504 }
3505
3506 bufPtr = statePtr->inQueueHead;
3507 encoding = statePtr->encoding;
3508
3509 /*
3510 * Preserved so we can restore the channel's state in case we don't
3511 * find a newline in the available input.
3512 */
3513
3514 Tcl_GetStringFromObj(objPtr, &oldLength);
3515 oldFlags = statePtr->inputEncodingFlags;
3516 oldState = statePtr->inputEncodingState;
3517 oldRemoved = BUFFER_PADDING;
3518 if (bufPtr != NULL) {
3519 oldRemoved = bufPtr->nextRemoved;
3520 }
3521
3522 /*
3523 * If there is no encoding, use "iso8859-1" -- Tcl_GetsObj() doesn't
3524 * produce ByteArray objects. To avoid circularity problems,
3525 * "iso8859-1" is builtin to Tcl.
3526 */
3527
3528 if (encoding == NULL) {
3529 encoding = Tcl_GetEncoding(NULL, "iso8859-1");
3530 }
3531
3532 /*
3533 * Object used by FilterInputBytes to keep track of how much data has
3534 * been consumed from the channel buffers.
3535 */
3536
3537 gs.objPtr = objPtr;
3538 gs.dstPtr = &dst;
3539 gs.encoding = encoding;
3540 gs.bufPtr = bufPtr;
3541 gs.state = oldState;
3542 gs.rawRead = 0;
3543 gs.bytesWrote = 0;
3544 gs.charsWrote = 0;
3545 gs.totalChars = 0;
3546
3547 dst = objPtr->bytes + oldLength;
3548 dstEnd = dst;
3549
3550 skip = 0;
3551 eof = NULL;
3552 inEofChar = statePtr->inEofChar;
3553
3554 while (1) {
3555 if (dst >= dstEnd) {
3556 if (FilterInputBytes(chanPtr, &gs) != 0) {
3557 goto restore;
3558 }
3559 dstEnd = dst + gs.bytesWrote;
3560 }
3561
3562 /*
3563 * Remember if EOF char is seen, then look for EOL anyhow, because
3564 * the EOL might be before the EOF char.
3565 */
3566
3567 if (inEofChar != '\0') {
3568 for (eol = dst; eol < dstEnd; eol++) {
3569 if (*eol == inEofChar) {
3570 dstEnd = eol;
3571 eof = eol;
3572 break;
3573 }
3574 }
3575 }
3576
3577 /*
3578 * On EOL, leave current file position pointing after the EOL, but
3579 * don't store the EOL in the output string.
3580 */
3581
3582 switch (statePtr->inputTranslation) {
3583 case TCL_TRANSLATE_LF: {
3584 for (eol = dst; eol < dstEnd; eol++) {
3585 if (*eol == '\n') {
3586 skip = 1;
3587 goto goteol;
3588 }
3589 }
3590 break;
3591 }
3592 case TCL_TRANSLATE_CR: {
3593 for (eol = dst; eol < dstEnd; eol++) {
3594 if (*eol == '\r') {
3595 skip = 1;
3596 goto goteol;
3597 }
3598 }
3599 break;
3600 }
3601 case TCL_TRANSLATE_CRLF: {
3602 for (eol = dst; eol < dstEnd; eol++) {
3603 if (*eol == '\r') {
3604 eol++;
3605 if (eol >= dstEnd) {
3606 int offset;
3607
3608 offset = eol - objPtr->bytes;
3609 dst = dstEnd;
3610 if (FilterInputBytes(chanPtr, &gs) != 0) {
3611 goto restore;
3612 }
3613 dstEnd = dst + gs.bytesWrote;
3614 eol = objPtr->bytes + offset;
3615 if (eol >= dstEnd) {
3616 skip = 0;
3617 goto goteol;
3618 }
3619 }
3620 if (*eol == '\n') {
3621 eol--;
3622 skip = 2;
3623 goto goteol;
3624 }
3625 }
3626 }
3627 break;
3628 }
3629 case TCL_TRANSLATE_AUTO: {
3630 eol = dst;
3631 skip = 1;
3632 if (statePtr->flags & INPUT_SAW_CR) {
3633 statePtr->flags &= ~INPUT_SAW_CR;
3634 if (*eol == '\n') {
3635 /*
3636 * Skip the raw bytes that make up the '\n'.
3637 */
3638
3639 char tmp[1 + TCL_UTF_MAX];
3640 int rawRead;
3641
3642 bufPtr = gs.bufPtr;
3643 Tcl_ExternalToUtf(NULL, gs.encoding,
3644 bufPtr->buf + bufPtr->nextRemoved,
3645 gs.rawRead, statePtr->inputEncodingFlags,
3646 &gs.state, tmp, 1 + TCL_UTF_MAX, &rawRead,
3647 NULL, NULL);
3648 bufPtr->nextRemoved += rawRead;
3649 gs.rawRead -= rawRead;
3650 gs.bytesWrote--;
3651 gs.charsWrote--;
3652 memmove(dst, dst + 1, (size_t) (dstEnd - dst));
3653 dstEnd--;
3654 }
3655 }
3656 for (eol = dst; eol < dstEnd; eol++) {
3657 if (*eol == '\r') {
3658 eol++;
3659 if (eol == dstEnd) {
3660 /*
3661 * If buffer ended on \r, peek ahead to see if a
3662 * \n is available.
3663 */
3664
3665 int offset;
3666
3667 offset = eol - objPtr->bytes;
3668 dst = dstEnd;
3669 PeekAhead(chanPtr, &dstEnd, &gs);
3670 eol = objPtr->bytes + offset;
3671 if (eol >= dstEnd) {
3672 eol--;
3673 statePtr->flags |= INPUT_SAW_CR;
3674 goto goteol;
3675 }
3676 }
3677 if (*eol == '\n') {
3678 skip++;
3679 }
3680 eol--;
3681 goto goteol;
3682 } else if (*eol == '\n') {
3683 goto goteol;
3684 }
3685 }
3686 }
3687 }
3688 if (eof != NULL) {
3689 /*
3690 * EOF character was seen. On EOF, leave current file position
3691 * pointing at the EOF character, but don't store the EOF
3692 * character in the output string.
3693 */
3694
3695 dstEnd = eof;
3696 statePtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);
3697 statePtr->inputEncodingFlags |= TCL_ENCODING_END;
3698 }
3699 if (statePtr->flags & CHANNEL_EOF) {
3700 skip = 0;
3701 eol = dstEnd;
3702 if (eol == objPtr->bytes + oldLength) {
3703 /*
3704 * If we didn't append any bytes before encountering EOF,
3705 * caller needs to see -1.
3706 */
3707
3708 Tcl_SetObjLength(objPtr, oldLength);
3709 CommonGetsCleanup(chanPtr, encoding);
3710 copiedTotal = -1;
3711 goto done;
3712 }
3713 goto goteol;
3714 }
3715 dst = dstEnd;
3716 }
3717
3718 /*
3719 * Found EOL or EOF, but the output buffer may now contain too many
3720 * UTF-8 characters. We need to know how many raw bytes correspond to
3721 * the number of UTF-8 characters we want, plus how many raw bytes
3722 * correspond to the character(s) making up EOL (if any), so we can
3723 * remove the correct number of bytes from the channel buffer.
3724 */
3725
3726 goteol:
3727 bufPtr = gs.bufPtr;
3728 statePtr->inputEncodingState = gs.state;
3729 Tcl_ExternalToUtf(NULL, gs.encoding, bufPtr->buf + bufPtr->nextRemoved,
3730 gs.rawRead, statePtr->inputEncodingFlags,
3731 &statePtr->inputEncodingState, dst,
3732 eol - dst + skip + TCL_UTF_MAX, &gs.rawRead, NULL,
3733 &gs.charsWrote);
3734 bufPtr->nextRemoved += gs.rawRead;
3735
3736 /*
3737 * Recycle all the emptied buffers.
3738 */
3739
3740 Tcl_SetObjLength(objPtr, eol - objPtr->bytes);
3741 CommonGetsCleanup(chanPtr, encoding);
3742 statePtr->flags &= ~CHANNEL_BLOCKED;
3743 copiedTotal = gs.totalChars + gs.charsWrote - skip;
3744 goto done;
3745
3746 /*
3747 * Couldn't get a complete line. This only happens if we get a error
3748 * reading from the channel or we are non-blocking and there wasn't
3749 * an EOL or EOF in the data available.
3750 */
3751
3752 restore:
3753 bufPtr = statePtr->inQueueHead;
3754 bufPtr->nextRemoved = oldRemoved;
3755
3756 for (bufPtr = bufPtr->nextPtr; bufPtr != NULL; bufPtr = bufPtr->nextPtr) {
3757 bufPtr->nextRemoved = BUFFER_PADDING;
3758 }
3759 CommonGetsCleanup(chanPtr, encoding);
3760
3761 statePtr->inputEncodingState = oldState;
3762 statePtr->inputEncodingFlags = oldFlags;
3763 Tcl_SetObjLength(objPtr, oldLength);
3764
3765 /*
3766 * We didn't get a complete line so we need to indicate to UpdateInterest
3767 * that the gets blocked. It will wait for more data instead of firing
3768 * a timer, avoiding a busy wait. This is where we are assuming that the
3769 * next operation is a gets. No more file events will be delivered on
3770 * this channel until new data arrives or some operation is performed
3771 * on the channel (e.g. gets, read, fconfigure) that changes the blocking
3772 * state. Note that this means a file event will not be delivered even
3773 * though a read would be able to consume the buffered data.
3774 */
3775
3776 statePtr->flags |= CHANNEL_NEED_MORE_DATA;
3777 copiedTotal = -1;
3778
3779 done:
3780 /*
3781 * Update the notifier state so we don't block while there is still
3782 * data in the buffers.
3783 */
3784
3785 UpdateInterest(chanPtr);
3786 return copiedTotal;
3787 }
3788
3789 /*
3790 *---------------------------------------------------------------------------
3791 *
3792 * FilterInputBytes --
3793 *
3794 * Helper function for Tcl_GetsObj. Produces UTF-8 characters from
3795 * raw bytes read from the channel.
3796 *
3797 * Consumes available bytes from channel buffers. When channel
3798 * buffers are exhausted, reads more bytes from channel device into
3799 * a new channel buffer. It is the caller's responsibility to
3800 * free the channel buffers that have been exhausted.
3801 *
3802 * Results:
3803 * The return value is -1 if there was an error reading from the
3804 * channel, 0 otherwise.
3805 *
3806 * Side effects:
3807 * Status object keeps track of how much data from channel buffers
3808 * has been consumed and where UTF-8 bytes should be stored.
3809 *
3810 *---------------------------------------------------------------------------
3811 */
3812
3813 static int
3814 FilterInputBytes(chanPtr, gsPtr)
3815 Channel *chanPtr; /* Channel to read. */
3816 GetsState *gsPtr; /* Current state of gets operation. */
3817 {
3818 ChannelState *statePtr = chanPtr->state; /* state info for channel */
3819 ChannelBuffer *bufPtr;
3820 char *raw, *rawStart, *rawEnd;
3821 char *dst;
3822 int offset, toRead, dstNeeded, spaceLeft, result, rawLen, length;
3823 Tcl_Obj *objPtr;
3824 #define ENCODING_LINESIZE 20 /* Lower bound on how many bytes to convert
3825 * at a time. Since we don't know a priori
3826 * how many bytes of storage this many source
3827 * bytes will use, we actually need at least
3828 * ENCODING_LINESIZE * TCL_MAX_UTF bytes of
3829 * room. */
3830
3831 objPtr = gsPtr->objPtr;
3832
3833 /*
3834 * Subtract the number of bytes that were removed from channel buffer
3835 * during last call.
3836 */
3837
3838 bufPtr = gsPtr->bufPtr;
3839 if (bufPtr != NULL) {
3840 bufPtr->nextRemoved += gsPtr->rawRead;
3841 if (bufPtr->nextRemoved >= bufPtr->nextAdded) {
3842 bufPtr = bufPtr->nextPtr;
3843 }
3844 }
3845 gsPtr->totalChars += gsPtr->charsWrote;
3846
3847 if ((bufPtr == NULL) || (bufPtr->nextAdded == BUFFER_PADDING)) {
3848 /*
3849 * All channel buffers were exhausted and the caller still hasn't
3850 * seen EOL. Need to read more bytes from the channel device.
3851 * Side effect is to allocate another channel buffer.
3852 */
3853
3854 read:
3855 if (statePtr->flags & CHANNEL_BLOCKED) {
3856 if (statePtr->flags & CHANNEL_NONBLOCKING) {
3857 gsPtr->charsWrote = 0;
3858 gsPtr->rawRead = 0;
3859 return -1;
3860 }
3861 statePtr->flags &= ~CHANNEL_BLOCKED;
3862 }
3863 if (GetInput(chanPtr) != 0) {
3864 gsPtr->charsWrote = 0;
3865 gsPtr->rawRead = 0;
3866 return -1;
3867 }
3868 bufPtr = statePtr->inQueueTail;
3869 gsPtr->bufPtr = bufPtr;
3870 }
3871
3872 /*
3873 * Convert some of the bytes from the channel buffer to UTF-8. Space in
3874 * objPtr's string rep is used to hold the UTF-8 characters. Grow the
3875 * string rep if we need more space.
3876 */
3877
3878 rawStart = bufPtr->buf + bufPtr->nextRemoved;
3879 raw = rawStart;
3880 rawEnd = bufPtr->buf + bufPtr->nextAdded;
3881 rawLen = rawEnd - rawStart;
3882
3883 dst = *gsPtr->dstPtr;
3884 offset = dst - objPtr->bytes;
3885 toRead = ENCODING_LINESIZE;
3886 if (toRead > rawLen) {
3887 toRead = rawLen;
3888 }
3889 dstNeeded = toRead * TCL_UTF_MAX + 1;
3890 spaceLeft = objPtr->length - offset - TCL_UTF_MAX - 1;
3891 if (dstNeeded > spaceLeft) {
3892 length = offset * 2;
3893 if (offset < dstNeeded) {
3894 length = offset + dstNeeded;
3895 }
3896 length += TCL_UTF_MAX + 1;
3897 Tcl_SetObjLength(objPtr, length);
3898 spaceLeft = length - offset;
3899 dst = objPtr->bytes + offset;
3900 *gsPtr->dstPtr = dst;
3901 }
3902 gsPtr->state = statePtr->inputEncodingState;
3903 result = Tcl_ExternalToUtf(NULL, gsPtr->encoding, raw, rawLen,
3904 statePtr->inputEncodingFlags, &statePtr->inputEncodingState,
3905 dst, spaceLeft, &gsPtr->rawRead, &gsPtr->bytesWrote,
3906 &gsPtr->charsWrote);
3907
3908 /*
3909 * Make sure that if we go through 'gets', that we reset the
3910 * TCL_ENCODING_START flag still. [Bug #523988]
3911 */
3912 statePtr->inputEncodingFlags &= ~TCL_ENCODING_START;
3913
3914 if (result == TCL_CONVERT_MULTIBYTE) {
3915 /*
3916 * The last few bytes in this channel buffer were the start of a
3917 * multibyte sequence. If this buffer was full, then move them to
3918 * the next buffer so the bytes will be contiguous.
3919 */
3920
3921 ChannelBuffer *nextPtr;
3922 int extra;
3923
3924 nextPtr = bufPtr->nextPtr;
3925 if (bufPtr->nextAdded < bufPtr->bufLength) {
3926 if (gsPtr->rawRead > 0) {
3927 /*
3928 * Some raw bytes were converted to UTF-8. Fall through,
3929 * returning those UTF-8 characters because a EOL might be
3930 * present in them.
3931 */
3932 } else if (statePtr->flags & CHANNEL_EOF) {
3933 /*
3934 * There was a partial character followed by EOF on the
3935 * device. Fall through, returning that nothing was found.
3936 */
3937
3938 bufPtr->nextRemoved = bufPtr->nextAdded;
3939 } else {
3940 /*
3941 * There are no more cached raw bytes left. See if we can
3942 * get some more.
3943 */
3944
3945 goto read;
3946 }
3947 } else {
3948 if (nextPtr == NULL) {
3949 nextPtr = AllocChannelBuffer(statePtr->bufSize);
3950 bufPtr->nextPtr = nextPtr;
3951 statePtr->inQueueTail = nextPtr;
3952 }
3953 extra = rawLen - gsPtr->rawRead;
3954 memcpy((VOID *) (nextPtr->buf + BUFFER_PADDING - extra),
3955 (VOID *) (raw + gsPtr->rawRead), (size_t) extra);
3956 nextPtr->nextRemoved -= extra;
3957 bufPtr->nextAdded -= extra;
3958 }
3959 }
3960
3961 gsPtr->bufPtr = bufPtr;
3962 return 0;
3963 }
3964
3965 /*
3966 *---------------------------------------------------------------------------
3967 *
3968 * PeekAhead --
3969 *
3970 * Helper function used by Tcl_GetsObj(). Called when we've seen a
3971 * \r at the end of the UTF-8 string and want to look ahead one
3972 * character to see if it is a \n.
3973 *
3974 * Results:
3975 * *gsPtr->dstPtr is filled with a pointer to the start of the range of
3976 * UTF-8 characters that were found by peeking and *dstEndPtr is filled
3977 * with a pointer to the bytes just after the end of the range.
3978 *
3979 * Side effects:
3980 * If no more raw bytes were available in one of the channel buffers,
3981 * tries to perform a non-blocking read to get more bytes from the
3982 * channel device.
3983 *
3984 *---------------------------------------------------------------------------
3985 */
3986
3987 static void
3988 PeekAhead(chanPtr, dstEndPtr, gsPtr)
3989 Channel *chanPtr; /* The channel to read. */
3990 char **dstEndPtr; /* Filled with pointer to end of new range
3991 * of UTF-8 characters. */
3992 GetsState *gsPtr; /* Current state of gets operation. */
3993 {
3994 ChannelState *statePtr = chanPtr->state; /* state info for channel */
3995 ChannelBuffer *bufPtr;
3996 Tcl_DriverBlockModeProc *blockModeProc;
3997 int bytesLeft;
3998
3999 bufPtr = gsPtr->bufPtr;
4000
4001 /*
4002 * If there's any more raw input that's still buffered, we'll peek into
4003 * that. Otherwise, only get more data from the channel driver if it
4004 * looks like there might actually be more data. The assumption is that
4005 * if the channel buffer is filled right up to the end, then there
4006 * might be more data to read.
4007 */
4008
4009 blockModeProc = NULL;
4010 if (bufPtr->nextPtr == NULL) {
4011 bytesLeft = bufPtr->nextAdded - (bufPtr->nextRemoved + gsPtr->rawRead);
4012 if (bytesLeft == 0) {
4013 if (bufPtr->nextAdded < bufPtr->bufLength) {
4014 /*
4015 * Don't peek ahead if last read was short read.
4016 */
4017
4018 goto cleanup;
4019 }
4020 if ((statePtr->flags & CHANNEL_NONBLOCKING) == 0) {
4021 blockModeProc = Tcl_ChannelBlockModeProc(chanPtr->typePtr);
4022 if (blockModeProc == NULL) {
4023 /*
4024 * Don't peek ahead if cannot set non-blocking mode.
4025 */
4026
4027 goto cleanup;
4028 }
4029 StackSetBlockMode(chanPtr, TCL_MODE_NONBLOCKING);
4030 }
4031 }
4032 }
4033 if (FilterInputBytes(chanPtr, gsPtr) == 0) {
4034 *dstEndPtr = *gsPtr->dstPtr + gsPtr->bytesWrote;
4035 }
4036 if (blockModeProc != NULL) {
4037 StackSetBlockMode(chanPtr, TCL_MODE_BLOCKING);
4038 }
4039 return;
4040
4041 cleanup:
4042 bufPtr->nextRemoved += gsPtr->rawRead;
4043 gsPtr->rawRead = 0;
4044 gsPtr->totalChars += gsPtr->charsWrote;
4045 gsPtr->bytesWrote = 0;
4046 gsPtr->charsWrote = 0;
4047 }
4048
4049 /*
4050 *---------------------------------------------------------------------------
4051 *
4052 * CommonGetsCleanup --
4053 *
4054 * Helper function for Tcl_GetsObj() to restore the channel after
4055 * a "gets" operation.
4056 *
4057 * Results:
4058 * None.
4059 *
4060 * Side effects:
4061 * Encoding may be freed.
4062 *
4063 *---------------------------------------------------------------------------
4064 */
4065
4066 static void
4067 CommonGetsCleanup(chanPtr, encoding)
4068 Channel *chanPtr;
4069 Tcl_Encoding encoding;
4070 {
4071 ChannelState *statePtr = chanPtr->state; /* state info for channel */
4072 ChannelBuffer *bufPtr, *nextPtr;
4073
4074 bufPtr = statePtr->inQueueHead;
4075 for ( ; bufPtr != NULL; bufPtr = nextPtr) {
4076 nextPtr = bufPtr->nextPtr;
4077 if (bufPtr->nextRemoved < bufPtr->nextAdded) {
4078 break;
4079 }
4080 RecycleBuffer(statePtr, bufPtr, 0);
4081 }
4082 statePtr->inQueueHead = bufPtr;
4083 if (bufPtr == NULL) {
4084 statePtr->inQueueTail = NULL;
4085 } else {
4086 /*
4087 * If any multi-byte characters were split across channel buffer
4088 * boundaries, the split-up bytes were moved to the next channel
4089 * buffer by FilterInputBytes(). Move the bytes back to their
4090 * original buffer because the caller could change the channel's
4091 * encoding which could change the interpretation of whether those
4092 * bytes really made up multi-byte characters after all.
4093 */
4094
4095 nextPtr = bufPtr->nextPtr;
4096 for ( ; nextPtr != NULL; nextPtr = bufPtr->nextPtr) {
4097 int extra;
4098
4099 extra = bufPtr->bufLength - bufPtr->nextAdded;
4100 if (extra > 0) {
4101 memcpy((VOID *) (bufPtr->buf + bufPtr->nextAdded),
4102 (VOID *) (nextPtr->buf + BUFFER_PADDING - extra),
4103 (size_t) extra);
4104 bufPtr->nextAdded += extra;
4105 nextPtr->nextRemoved = BUFFER_PADDING;
4106 }
4107 bufPtr = nextPtr;
4108 }
4109 }
4110 if (statePtr->encoding == NULL) {
4111 Tcl_FreeEncoding(encoding);
4112 }
4113 }
4114
4115 /*
4116 *----------------------------------------------------------------------
4117 *
4118 * Tcl_Read --
4119 *
4120 * Reads a given number of bytes from a channel. EOL and EOF
4121 * translation is done on the bytes being read, so the the number
4122 * of bytes consumed from the channel may not be equal to the
4123 * number of bytes stored in the destination buffer.
4124 *
4125 * No encoding conversions are applied to the bytes being read.
4126 *
4127 * Results:
4128 * The number of bytes read, or -1 on error. Use Tcl_GetErrno()
4129 * to retrieve the error code for the error that occurred.
4130 *
4131 * Side effects:
4132 * May cause input to be buffered.
4133 *
4134 *----------------------------------------------------------------------
4135 */
4136
4137 int
4138 Tcl_Read(chan, dst, bytesToRead)
4139 Tcl_Channel chan; /* The channel from which to read. */
4140 char *dst; /* Where to store input read. */
4141 int bytesToRead; /* Maximum number of bytes to read. */
4142 {
4143 Channel *chanPtr = (Channel *) chan;
4144 ChannelState *statePtr = chanPtr->state; /* state info for channel */
4145
4146 /*
4147 * This operation should occur at the top of a channel stack.
4148 */
4149
4150 chanPtr = statePtr->topChanPtr;
4151
4152 if (CheckChannelErrors(statePtr, TCL_READABLE) != 0) {
4153 return -1;
4154 }
4155
4156 return DoRead(chanPtr, dst, bytesToRead);
4157 }
4158
4159 /*
4160 *----------------------------------------------------------------------
4161 *
4162 * Tcl_ReadRaw --
4163 *
4164 * Reads a given number of bytes from a channel. EOL and EOF
4165 * translation is done on the bytes being read, so the the number
4166 * of bytes consumed from the channel may not be equal to the
4167 * number of bytes stored in the destination buffer.
4168 *
4169 * No encoding conversions are applied to the bytes being read.
4170 *
4171 * Results:
4172 * The number of bytes read, or -1 on error. Use Tcl_GetErrno()
4173 * to retrieve the error code for the error that occurred.
4174 *
4175 * Side effects:
4176 * May cause input to be buffered.
4177 *
4178 *----------------------------------------------------------------------
4179 */
4180
4181 int
4182 Tcl_ReadRaw(chan, bufPtr, bytesToRead)
4183 Tcl_Channel chan; /* The channel from which to read. */
4184 char *bufPtr; /* Where to store input read. */
4185 int bytesToRead; /* Maximum number of bytes to read. */
4186 {
4187 Channel *chanPtr = (Channel *) chan;
4188 ChannelState *statePtr = chanPtr->state; /* state info for channel */
4189 int nread, result;
4190 int copied, copiedNow;
4191
4192 /*
4193 * The check below does too much because it will reject a call to this
4194 * function with a channel which is part of an 'fcopy'. But we have to
4195 * allow this here or else the chaining in the transformation drivers
4196 * will fail with 'file busy' error instead of retrieving and
4197 * transforming the data to copy.
4198 *
4199 * We let the check procedure now believe that there is no fcopy in
4200 * progress. A better solution than this might be an additional flag
4201 * argument to switch off specific checks.
4202 */
4203
4204 if (CheckChannelErrors(statePtr, TCL_READABLE | CHANNEL_RAW_MODE) != 0) {
4205 return -1;
4206 }
4207
4208 /*
4209 * Check for information in the push-back buffers. If there is
4210 * some, use it. Go to the driver only if there is none (anymore)
4211 * and the caller requests more bytes.
4212 */
4213
4214 for (copied = 0; copied < bytesToRead; copied += copiedNow) {
4215 copiedNow = CopyBuffer(chanPtr, bufPtr + copied,
4216 bytesToRead - copied);
4217 if (copiedNow == 0) {
4218 if (statePtr->flags & CHANNEL_EOF) {
4219 goto done;
4220 }
4221 if (statePtr->flags & CHANNEL_BLOCKED) {
4222 if (statePtr->flags & CHANNEL_NONBLOCKING) {
4223 goto done;
4224 }
4225 statePtr->flags &= (~(CHANNEL_BLOCKED));
4226 }
4227
4228 if ((statePtr->flags & CHANNEL_TIMER_FEV) &&
4229 (statePtr->flags & CHANNEL_NONBLOCKING)) {
4230 nread = -1;
4231 result = EWOULDBLOCK;
4232 } else {
4233 /*
4234 * Now go to the driver to get as much as is possible to
4235 * fill the remaining request. Do all the error handling
4236 * by ourselves. The code was stolen from 'GetInput' and
4237 * slightly adapted (different return value here).
4238 *
4239 * The case of 'bytesToRead == 0' at this point cannot happen.
4240 */
4241
4242 nread = (chanPtr->typePtr->inputProc)(chanPtr->instanceData,
4243 bufPtr + copied, bytesToRead - copied, &result);
4244 }
4245 if (nread > 0) {
4246 /*
4247 * If we get a short read, signal up that we may be
4248 * BLOCKED. We should avoid calling the driver because
4249 * on some platforms we will block in the low level
4250 * reading code even though the channel is set into
4251 * nonblocking mode.
4252 */
4253
4254 if (nread < (bytesToRead - copied)) {
4255 statePtr->flags |= CHANNEL_BLOCKED;
4256 }
4257 } else if (nread == 0) {
4258 statePtr->flags |= CHANNEL_EOF;
4259 statePtr->inputEncodingFlags |= TCL_ENCODING_END;
4260 } else if (nread < 0) {
4261 if ((result == EWOULDBLOCK) || (result == EAGAIN)) {
4262 if (copied > 0) {
4263 /*
4264 * Information that was copied earlier has precedence
4265 * over EAGAIN/WOULDBLOCK handling.
4266 */
4267 return copied;
4268 }
4269
4270 statePtr->flags |= CHANNEL_BLOCKED;
4271 result = EAGAIN;
4272 }
4273
4274 Tcl_SetErrno(result);
4275 return -1;
4276 }
4277
4278 return copied + nread;
4279 }
4280 }
4281
4282 done:
4283 return copied;
4284 }
4285
4286 /*
4287 *---------------------------------------------------------------------------
4288 *
4289 * Tcl_ReadChars --
4290 *
4291 * Reads from the channel until the requested number of characters
4292 * have been seen, EOF is seen, or the channel would block. EOL
4293 * and EOF translation is done. If reading binary data, the raw
4294 * bytes are wrapped in a Tcl byte array object. Otherwise, the raw
4295 * bytes are converted to UTF-8 using the channel's current encoding
4296 * and stored in a Tcl string object.
4297 *
4298 * Results:
4299 * The number of characters read, or -1 on error. Use Tcl_GetErrno()
4300 * to retrieve the error code for the error that occurred.
4301 *
4302 * Side effects:
4303 * May cause input to be buffered.
4304 *
4305 *---------------------------------------------------------------------------
4306 */
4307
4308 int
4309 Tcl_ReadChars(chan, objPtr, toRead, appendFlag)
4310 Tcl_Channel chan; /* The channel to read. */
4311 Tcl_Obj *objPtr; /* Input data is stored in this object. */
4312 int toRead; /* Maximum number of characters to store,
4313 * or -1 to read all available data (up to EOF
4314 * or when channel blocks). */
4315 int appendFlag; /* If non-zero, data read from the channel
4316 * will be appended to the object. Otherwise,
4317 * the data will replace the existing contents
4318 * of the object. */
4319
4320 {
4321 Channel* chanPtr = (Channel *) chan;
4322 ChannelState* statePtr = chanPtr->state; /* state info for channel */
4323
4324 /*
4325 * This operation should occur at the top of a channel stack.
4326 */
4327
4328 chanPtr = statePtr->topChanPtr;
4329
4330 if (CheckChannelErrors(statePtr, TCL_READABLE) != 0) {
4331 /*
4332 * Update the notifier state so we don't block while there is still
4333 * data in the buffers.
4334 */
4335 UpdateInterest(chanPtr);
4336 return -1;
4337 }
4338
4339 return DoReadChars (chanPtr, objPtr, toRead, appendFlag);
4340 }
4341 /*
4342 *---------------------------------------------------------------------------
4343 *
4344 * DoReadChars --
4345 *
4346 * Reads from the channel until the requested number of characters
4347 * have been seen, EOF is seen, or the channel would block. EOL
4348 * and EOF translation is done. If reading binary data, the raw
4349 * bytes are wrapped in a Tcl byte array object. Otherwise, the raw
4350 * bytes are converted to UTF-8 using the channel's current encoding
4351 * and stored in a Tcl string object.
4352 *
4353 * Results:
4354 * The number of characters read, or -1 on error. Use Tcl_GetErrno()
4355 * to retrieve the error code for the error that occurred.
4356 *
4357 * Side effects:
4358 * May cause input to be buffered.
4359 *
4360 *---------------------------------------------------------------------------
4361 */
4362
4363 static int
4364 DoReadChars(chanPtr, objPtr, toRead, appendFlag)
4365 Channel* chanPtr; /* The channel to read. */
4366 Tcl_Obj *objPtr; /* Input data is stored in this object. */
4367 int toRead; /* Maximum number of characters to store,
4368 * or -1 to read all available data (up to EOF
4369 * or when channel blocks). */
4370 int appendFlag; /* If non-zero, data read from the channel
4371 * will be appended to the object. Otherwise,
4372 * the data will replace the existing contents
4373 * of the object. */
4374
4375 {
4376 ChannelState *statePtr = chanPtr->state; /* state info for channel */
4377 ChannelBuffer *bufPtr;
4378 int offset, factor, copied, copiedNow, result;
4379 Tcl_Encoding encoding;
4380 #define UTF_EXPANSION_FACTOR 1024
4381
4382 /*
4383 * This operation should occur at the top of a channel stack.
4384 */
4385
4386 chanPtr = statePtr->topChanPtr;
4387 encoding = statePtr->encoding;
4388 factor = UTF_EXPANSION_FACTOR;
4389
4390 if (appendFlag == 0) {
4391 if (encoding == NULL) {
4392 Tcl_SetByteArrayLength(objPtr, 0);
4393 } else {
4394 Tcl_SetObjLength(objPtr, 0);
4395 /*
4396 * We're going to access objPtr->bytes directly, so
4397 * we must ensure that this is actually a string
4398 * object (otherwise it might have been pure Unicode).
4399 */
4400 Tcl_GetString(objPtr);
4401 }
4402 offset = 0;
4403 } else {
4404 if (encoding == NULL) {
4405 Tcl_GetByteArrayFromObj(objPtr, &offset);
4406 } else {
4407 Tcl_GetStringFromObj(objPtr, &offset);
4408 }
4409 }
4410
4411 for (copied = 0; (unsigned) toRead > 0; ) {
4412 copiedNow = -1;
4413 if (statePtr->inQueueHead != NULL) {
4414 if (encoding == NULL) {
4415 copiedNow = ReadBytes(statePtr, objPtr, toRead, &offset);
4416 } else {
4417 copiedNow = ReadChars(statePtr, objPtr, toRead, &offset,
4418 &factor);
4419 }
4420
4421 /*
4422 * If the current buffer is empty recycle it.
4423 */
4424
4425 bufPtr = statePtr->inQueueHead;
4426 if (bufPtr->nextRemoved == bufPtr->nextAdded) {
4427 ChannelBuffer *nextPtr;
4428
4429 nextPtr = bufPtr->nextPtr;
4430 RecycleBuffer(statePtr, bufPtr, 0);
4431 statePtr->inQueueHead = nextPtr;
4432 if (nextPtr == NULL) {
4433 statePtr->inQueueTail = NULL;
4434 }
4435 }
4436 }
4437 if (copiedNow < 0) {
4438 if (statePtr->flags & CHANNEL_EOF) {
4439 break;
4440 }
4441 if (statePtr->flags & CHANNEL_BLOCKED) {
4442 if (statePtr->flags & CHANNEL_NONBLOCKING) {
4443 break;
4444 }
4445 statePtr->flags &= ~CHANNEL_BLOCKED;
4446 }
4447 result = GetInput(chanPtr);
4448 if (result != 0) {
4449 if (result == EAGAIN) {
4450 break;
4451 }
4452 copied = -1;
4453 goto done;
4454 }
4455 } else {
4456 copied += copiedNow;
4457 toRead -= copiedNow;
4458 }
4459 }
4460 statePtr->flags &= ~CHANNEL_BLOCKED;
4461 if (encoding == NULL) {
4462 Tcl_SetByteArrayLength(objPtr, offset);
4463 } else {
4464 Tcl_SetObjLength(objPtr, offset);
4465 }
4466
4467 done:
4468 /*
4469 * Update the notifier state so we don't block while there is still
4470 * data in the buffers.
4471 */
4472
4473 UpdateInterest(chanPtr);
4474 return copied;
4475 }
4476 /*
4477 *---------------------------------------------------------------------------
4478 *
4479 * ReadBytes --
4480 *
4481 * Reads from the channel until the requested number of bytes have
4482 * been seen, EOF is seen, or the channel would block. Bytes from
4483 * the channel are stored in objPtr as a ByteArray object. EOL
4484 * and EOF translation are done.
4485 *
4486 * 'bytesToRead' can safely be a very large number because
4487 * space is only allocated to hold data read from the channel
4488 * as needed.
4489 *
4490 * Results:
4491 * The return value is the number of bytes appended to the object
4492 * and *offsetPtr is filled with the total number of bytes in the
4493 * object (greater than the return value if there were already bytes
4494 * in the object).
4495 *
4496 * Side effects:
4497 * None.
4498 *
4499 *---------------------------------------------------------------------------
4500 */
4501
4502 static int
4503 ReadBytes(statePtr, objPtr, bytesToRead, offsetPtr)
4504 ChannelState *statePtr; /* State of the channel to read. */
4505 Tcl_Obj *objPtr; /* Input data is appended to this ByteArray
4506 * object. Its length is how much space
4507 * has been allocated to hold data, not how
4508 * many bytes of data have been stored in the
4509 * object. */
4510 int bytesToRead; /* Maximum number of bytes to store,
4511 * or < 0 to get all available bytes.
4512 * Bytes are obtained from the first
4513 * buffer in the queue -- even if this number
4514 * is larger than the number of bytes
4515 * available in the first buffer, only the
4516 * bytes from the first buffer are
4517 * returned. */
4518 int *offsetPtr; /* On input, contains how many bytes of
4519 * objPtr have been used to hold data. On
4520 * output, filled with how many bytes are now
4521 * being used. */
4522 {
4523 int toRead, srcLen, offset, length, srcRead, dstWrote;
4524 ChannelBuffer *bufPtr;
4525 char *src, *dst;
4526
4527 offset = *offsetPtr;
4528
4529 bufPtr = statePtr->inQueueHead;
4530 src = bufPtr->buf + bufPtr->nextRemoved;
4531 srcLen = bufPtr->nextAdded - bufPtr->nextRemoved;
4532
4533 toRead = bytesToRead;
4534 if ((unsigned) toRead > (unsigned) srcLen) {
4535 toRead = srcLen;
4536 }
4537
4538 dst = (char *) Tcl_GetByteArrayFromObj(objPtr, &length);
4539 if (toRead > length - offset - 1) {
4540 /*
4541 * Double the existing size of the object or make enough room to
4542 * hold all the characters we may get from the source buffer,
4543 * whichever is larger.
4544 */
4545
4546 length = offset * 2;
4547 if (offset < toRead) {
4548 length = offset + toRead + 1;
4549 }
4550 dst = (char *) Tcl_SetByteArrayLength(objPtr, length);
4551 }
4552 dst += offset;
4553
4554 if (statePtr->flags & INPUT_NEED_NL) {
4555 statePtr->flags &= ~INPUT_NEED_NL;
4556 if ((srcLen == 0) || (*src != '\n')) {
4557 *dst = '\r';
4558 *offsetPtr += 1;
4559 return 1;
4560 }
4561 *dst++ = '\n';
4562 src++;
4563 srcLen--;
4564 toRead--;
4565 }
4566
4567 srcRead = srcLen;
4568 dstWrote = toRead;
4569 if (TranslateInputEOL(statePtr, dst, src, &dstWrote, &srcRead) != 0) {
4570 if (dstWrote == 0) {
4571 return -1;
4572 }
4573 }
4574 bufPtr->nextRemoved += srcRead;
4575 *offsetPtr += dstWrote;
4576 return dstWrote;
4577 }
4578
4579 /*
4580 *---------------------------------------------------------------------------
4581 *
4582 * ReadChars --
4583 *
4584 * Reads from the channel until the requested number of UTF-8
4585 * characters have been seen, EOF is seen, or the channel would
4586 * block. Raw bytes from the channel are converted to UTF-8
4587 * and stored in objPtr. EOL and EOF translation is done.
4588 *
4589 * 'charsToRead' can safely be a very large number because
4590 * space is only allocated to hold data read from the channel
4591 * as needed.
4592 *
4593 * Results:
4594 * The return value is the number of characters appended to
4595 * the object, *offsetPtr is filled with the number of bytes that
4596 * were appended, and *factorPtr is filled with the expansion
4597 * factor used to guess how many bytes of UTF-8 to allocate to
4598 * hold N source bytes.
4599 *
4600 * Side effects:
4601 * None.
4602 *
4603 *---------------------------------------------------------------------------
4604 */
4605
4606 static int
4607 ReadChars(statePtr, objPtr, charsToRead, offsetPtr, factorPtr)
4608 ChannelState *statePtr; /* State of channel to read. */
4609 Tcl_Obj *objPtr; /* Input data is appended to this object.
4610 * objPtr->length is how much space has been
4611 * allocated to hold data, not how many bytes
4612 * of data have been stored in the object. */
4613 int charsToRead; /* Maximum number of characters to store,
4614 * or -1 to get all available characters.
4615 * Characters are obtained from the first
4616 * buffer in the queue -- even if this number
4617 * is larger than the number of characters
4618 * available in the first buffer, only the
4619 * characters from the first buffer are
4620 * returned. */
4621 int *offsetPtr; /* On input, contains how many bytes of
4622 * objPtr have been used to hold data. On
4623 * output, filled with how many bytes are now
4624 * being used. */
4625 int *factorPtr; /* On input, contains a guess of how many
4626 * bytes need to be allocated to hold the
4627 * result of converting N source bytes to
4628 * UTF-8. On output, contains another guess
4629 * based on the data seen so far. */
4630 {
4631 int toRead, factor, offset, spaceLeft, length, srcLen, dstNeeded;
4632 int srcRead, dstWrote, numChars, dstRead;
4633 ChannelBuffer *bufPtr;
4634 char *src, *dst;
4635 Tcl_EncodingState oldState;
4636
4637 factor = *factorPtr;
4638 offset = *offsetPtr;
4639
4640 bufPtr = statePtr->inQueueHead;
4641 src = bufPtr->buf + bufPtr->nextRemoved;
4642 srcLen = bufPtr->nextAdded - bufPtr->nextRemoved;
4643
4644 toRead = charsToRead;
4645 if ((unsigned)toRead > (unsigned)srcLen) {
4646 toRead = srcLen;
4647 }
4648
4649 /*
4650 * 'factor' is how much we guess that the bytes in the source buffer
4651 * will expand when converted to UTF-8 chars. This guess comes from
4652 * analyzing how many characters were produced by the previous
4653 * pass.
4654 */
4655
4656 dstNeeded = toRead * factor / UTF_EXPANSION_FACTOR;
4657 spaceLeft = objPtr->length - offset - TCL_UTF_MAX - 1;
4658
4659 if (dstNeeded > spaceLeft) {
4660 /*
4661 * Double the existing size of the object or make enough room to
4662 * hold all the characters we want from the source buffer,
4663 * whichever is larger.
4664 */
4665
4666 length = offset * 2;
4667 if (offset < dstNeeded) {
4668 length = offset + dstNeeded;
4669 }
4670 spaceLeft = length - offset;
4671 length += TCL_UTF_MAX + 1;
4672 Tcl_SetObjLength(objPtr, length);
4673 }
4674 if (toRead == srcLen) {
4675 /*
4676 * Want to convert the whole buffer in one pass. If we have
4677 * enough space, convert it using all available space in object
4678 * rather than using the factor.
4679 */
4680
4681 dstNeeded = spaceLeft;
4682 }
4683 dst = objPtr->bytes + offset;
4684
4685 oldState = statePtr->inputEncodingState;
4686 if (statePtr->flags & INPUT_NEED_NL) {
4687 /*
4688 * We want a '\n' because the last character we saw was '\r'.
4689 */
4690
4691 statePtr->flags &= ~INPUT_NEED_NL;
4692 Tcl_ExternalToUtf(NULL, statePtr->encoding, src, srcLen,
4693 statePtr->inputEncodingFlags, &statePtr->inputEncodingState,
4694 dst, TCL_UTF_MAX + 1, &srcRead, &dstWrote, &numChars);
4695 if ((dstWrote > 0) && (*dst == '\n')) {
4696 /*
4697 * The next char was a '\n'. Consume it and produce a '\n'.
4698 */
4699
4700 bufPtr->nextRemoved += srcRead;
4701 } else {
4702 /*
4703 * The next char was not a '\n'. Produce a '\r'.
4704 */
4705
4706 *dst = '\r';
4707 }
4708 statePtr->inputEncodingFlags &= ~TCL_ENCODING_START;
4709 *offsetPtr += 1;
4710 return 1;
4711 }
4712
4713 Tcl_ExternalToUtf(NULL, statePtr->encoding, src, srcLen,
4714 statePtr->inputEncodingFlags, &statePtr->inputEncodingState, dst,
4715 dstNeeded + TCL_UTF_MAX, &srcRead, &dstWrote, &numChars);
4716 if (srcRead == 0) {
4717 /*
4718 * Not enough bytes in src buffer to make a complete char. Copy
4719 * the bytes to the next buffer to make a new contiguous string,
4720 * then tell the caller to fill the buffer with more bytes.
4721 */
4722
4723 ChannelBuffer *nextPtr;
4724
4725 nextPtr = bufPtr->nextPtr;
4726 if (nextPtr == NULL) {
4727 if (srcLen > 0) {
4728 /*
4729 * There isn't enough data in the buffers to complete the next
4730 * character, so we need to wait for more data before the next
4731 * file event can be delivered.
4732 *
4733 * SF #478856.
4734 *
4735 * The exception to this is if the input buffer was
4736 * completely empty before we tried to convert its
4737 * contents. Nothing in, nothing out, and no incomplete
4738 * character data. The conversion before the current one
4739 * was complete.
4740 */
4741
4742 statePtr->flags |= CHANNEL_NEED_MORE_DATA;
4743 }
4744 return -1;
4745 }
4746 nextPtr->nextRemoved -= srcLen;
4747 memcpy((VOID *) (nextPtr->buf + nextPtr->nextRemoved), (VOID *) src,
4748 (size_t) srcLen);
4749 RecycleBuffer(statePtr, bufPtr, 0);
4750 statePtr->inQueueHead = nextPtr;
4751 return ReadChars(statePtr, objPtr, charsToRead, offsetPtr, factorPtr);
4752 }
4753
4754 dstRead = dstWrote;
4755 if (TranslateInputEOL(statePtr, dst, dst, &dstWrote, &dstRead) != 0) {
4756 /*
4757 * Hit EOF char. How many bytes of src correspond to where the
4758 * EOF was located in dst? Run the conversion again with an
4759 * output buffer just big enough to hold the data so we can
4760 * get the correct value for srcRead.
4761 */
4762
4763 if (dstWrote == 0) {
4764 return -1;
4765 }
4766 statePtr->inputEncodingState = oldState;
4767 Tcl_ExternalToUtf(NULL, statePtr->encoding, src, srcLen,
4768 statePtr->inputEncodingFlags, &statePtr->inputEncodingState,
4769 dst, dstRead + TCL_UTF_MAX, &srcRead, &dstWrote, &numChars);
4770 TranslateInputEOL(statePtr, dst, dst, &dstWrote, &dstRead);
4771 }
4772
4773 /*
4774 * The number of characters that we got may be less than the number
4775 * that we started with because "\r\n" sequences may have been
4776 * turned into just '\n' in dst.
4777 */
4778
4779 numChars -= (dstRead - dstWrote);
4780
4781 if ((unsigned) numChars > (unsigned) toRead) {
4782 /*
4783 * Got too many chars.
4784 */
4785
4786 CONST char *eof;
4787
4788 eof = Tcl_UtfAtIndex(dst, toRead);
4789 statePtr->inputEncodingState = oldState;
4790 Tcl_ExternalToUtf(NULL, statePtr->encoding, src, srcLen,
4791 statePtr->inputEncodingFlags, &statePtr->inputEncodingState,
4792 dst, eof - dst + TCL_UTF_MAX, &srcRead, &dstWrote, &numChars);
4793 dstRead = dstWrote;
4794 TranslateInputEOL(statePtr, dst, dst, &dstWrote, &dstRead);
4795 numChars -= (dstRead - dstWrote);
4796 }
4797 statePtr->inputEncodingFlags &= ~TCL_ENCODING_START;
4798
4799 bufPtr->nextRemoved += srcRead;
4800 if (dstWrote > srcRead + 1) {
4801 *factorPtr = dstWrote * UTF_EXPANSION_FACTOR / srcRead;
4802 }
4803 *offsetPtr += dstWrote;
4804 return numChars;
4805 }
4806
4807 /*
4808 *---------------------------------------------------------------------------
4809 *
4810 * TranslateInputEOL --
4811 *
4812 * Perform input EOL and EOF translation on the source buffer,
4813 * leaving the translated result in the destination buffer.
4814 *
4815 * Results:
4816 * The return value is 1 if the EOF character was found when copying
4817 * bytes to the destination buffer, 0 otherwise.
4818 *
4819 * Side effects:
4820 * None.
4821 *
4822 *---------------------------------------------------------------------------
4823 */
4824
4825 static int
4826 TranslateInputEOL(statePtr, dstStart, srcStart, dstLenPtr, srcLenPtr)
4827 ChannelState *statePtr; /* Channel being read, for EOL translation
4828 * and EOF character. */
4829 char *dstStart; /* Output buffer filled with chars by
4830 * applying appropriate EOL translation to
4831 * source characters. */
4832 CONST char *srcStart; /* Source characters. */
4833 int *dstLenPtr; /* On entry, the maximum length of output
4834 * buffer in bytes; must be <= *srcLenPtr. On
4835 * exit, the number of bytes actually used in
4836 * output buffer. */
4837 int *srcLenPtr; /* On entry, the length of source buffer.
4838 * On exit, the number of bytes read from
4839 * the source buffer. */
4840 {
4841 int dstLen, srcLen, inEofChar;
4842 CONST char *eof;
4843
4844 dstLen = *dstLenPtr;
4845
4846 eof = NULL;
4847 inEofChar = statePtr->inEofChar;
4848 if (inEofChar != '\0') {
4849 /*
4850 * Find EOF in translated buffer then compress out the EOL. The
4851 * source buffer may be much longer than the destination buffer --
4852 * we only want to return EOF if the EOF has been copied to the
4853 * destination buffer.
4854 */
4855
4856 CONST char *src, *srcMax;
4857
4858 srcMax = srcStart + *srcLenPtr;
4859 for (src = srcStart; src < srcMax; src++) {
4860 if (*src == inEofChar) {
4861 eof = src;
4862 srcLen = src - srcStart;
4863 if (srcLen < dstLen) {
4864 dstLen = srcLen;
4865 }
4866 *srcLenPtr = srcLen;
4867 break;
4868 }
4869 }
4870 }
4871 switch (statePtr->inputTranslation) {
4872 case TCL_TRANSLATE_LF: {
4873 if (dstStart != srcStart) {
4874 memcpy((VOID *) dstStart, (VOID *) srcStart, (size_t) dstLen);
4875 }
4876 srcLen = dstLen;
4877 break;
4878 }
4879 case TCL_TRANSLATE_CR: {
4880 char *dst, *dstEnd;
4881
4882 if (dstStart != srcStart) {
4883 memcpy((VOID *) dstStart, (VOID *) srcStart, (size_t) dstLen);
4884 }
4885 dstEnd = dstStart + dstLen;
4886 for (dst = dstStart; dst < dstEnd; dst++) {
4887 if (*dst == '\r') {
4888 *dst = '\n';
4889 }
4890 }
4891 srcLen = dstLen;
4892 break;
4893 }
4894 case TCL_TRANSLATE_CRLF: {
4895 char *dst;
4896 CONST char *src, *srcEnd, *srcMax;
4897
4898 dst = dstStart;
4899 src = srcStart;
4900 srcEnd = srcStart + dstLen;
4901 srcMax = srcStart + *srcLenPtr;
4902
4903 for ( ; src < srcEnd; ) {
4904 if (*src == '\r') {
4905 src++;
4906 if (src >= srcMax) {
4907 statePtr->flags |= INPUT_NEED_NL;
4908 } else if (*src == '\n') {
4909 *dst++ = *src++;
4910 } else {
4911 *dst++ = '\r';
4912 }
4913 } else {
4914 *dst++ = *src++;
4915 }
4916 }
4917 srcLen = src - srcStart;
4918 dstLen = dst - dstStart;
4919 break;
4920 }
4921 case TCL_TRANSLATE_AUTO: {
4922 char *dst;
4923 CONST char *src, *srcEnd, *srcMax;
4924
4925 dst = dstStart;
4926 src = srcStart;
4927 srcEnd = srcStart + dstLen;
4928 srcMax = srcStart + *srcLenPtr;
4929
4930 if ((statePtr->flags & INPUT_SAW_CR) && (src < srcMax)) {
4931 if (*src == '\n') {
4932 src++;
4933 }
4934 statePtr->flags &= ~INPUT_SAW_CR;
4935 }
4936 for ( ; src < srcEnd; ) {
4937 if (*src == '\r') {
4938 src++;
4939 if (src >= srcMax) {
4940 statePtr->flags |= INPUT_SAW_CR;
4941 } else if (*src == '\n') {
4942 if (srcEnd < srcMax) {
4943 srcEnd++;
4944 }
4945 src++;
4946 }
4947 *dst++ = '\n';
4948 } else {
4949 *dst++ = *src++;
4950 }
4951 }
4952 srcLen = src - srcStart;
4953 dstLen = dst - dstStart;
4954 break;
4955 }
4956 default: { /* lint. */
4957 return 0;
4958 }
4959 }
4960 *dstLenPtr = dstLen;
4961
4962 if ((eof != NULL) && (srcStart + srcLen >= eof)) {
4963 /*
4964 * EOF character was seen in EOL translated range. Leave current
4965 * file position pointing at the EOF character, but don't store the
4966 * EOF character in the output string.
4967 */
4968
4969 statePtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);
4970 statePtr->inputEncodingFlags |= TCL_ENCODING_END;
4971 statePtr->flags &= ~(INPUT_SAW_CR | INPUT_NEED_NL);
4972 return 1;
4973 }
4974
4975 *srcLenPtr = srcLen;
4976 return 0;
4977 }
4978
4979 /*
4980 *----------------------------------------------------------------------
4981 *
4982 * Tcl_Ungets --
4983 *
4984 * Causes the supplied string to be added to the input queue of
4985 * the channel, at either the head or tail of the queue.
4986 *
4987 * Results:
4988 * The number of bytes stored in the channel, or -1 on error.
4989 *
4990 * Side effects:
4991 * Adds input to the input queue of a channel.
4992 *
4993 *----------------------------------------------------------------------
4994 */
4995
4996 int
4997 Tcl_Ungets(chan, str, len, atEnd)
4998 Tcl_Channel chan; /* The channel for which to add the input. */
4999 CONST char *str; /* The input itself. */
5000 int len; /* The length of the input. */
5001 int atEnd; /* If non-zero, add at end of queue; otherwise
5002 * add at head of queue. */
5003 {
5004 Channel *chanPtr; /* The real IO channel. */
5005 ChannelState *statePtr; /* State of actual channel. */
5006 ChannelBuffer *bufPtr; /* Buffer to contain the data. */
5007 int i, flags;
5008
5009 chanPtr = (Channel *) chan;
5010 statePtr = chanPtr->state;
5011
5012 /*
5013 * This operation should occur at the top of a channel stack.
5014 */
5015
5016 chanPtr = statePtr->topChanPtr;
5017
5018 /*
5019 * CheckChannelErrors clears too many flag bits in this one case.
5020 */
5021
5022 flags = statePtr->flags;
5023 if (CheckChannelErrors(statePtr, TCL_READABLE) != 0) {
5024 len = -1;
5025 goto done;
5026 }
5027 statePtr->flags = flags;
5028
5029 /*
5030 * If we have encountered a sticky EOF, just punt without storing.
5031 * (sticky EOF is set if we have seen the input eofChar, to prevent
5032 * reading beyond the eofChar). Otherwise, clear the EOF flags, and
5033 * clear the BLOCKED bit. We want to discover these conditions anew
5034 * in each operation.
5035 */
5036
5037 if (statePtr->flags & CHANNEL_STICKY_EOF) {
5038 goto done;
5039 }
5040 statePtr->flags &= (~(CHANNEL_BLOCKED | CHANNEL_EOF));
5041
5042 bufPtr = AllocChannelBuffer(len);
5043 for (i = 0; i < len; i++) {
5044 bufPtr->buf[i] = str[i];
5045 }
5046 bufPtr->nextAdded += len;
5047
5048 if (statePtr->inQueueHead == (ChannelBuffer *) NULL) {
5049 bufPtr->nextPtr = (ChannelBuffer *) NULL;
5050 statePtr->inQueueHead = bufPtr;
5051 statePtr->inQueueTail = bufPtr;
5052 } else if (atEnd) {
5053 bufPtr->nextPtr = (ChannelBuffer *) NULL;
5054 statePtr->inQueueTail->nextPtr = bufPtr;
5055 statePtr->inQueueTail = bufPtr;
5056 } else {
5057 bufPtr->nextPtr = statePtr->inQueueHead;
5058 statePtr->inQueueHead = bufPtr;
5059 }
5060
5061 done:
5062 /*
5063 * Update the notifier state so we don't block while there is still
5064 * data in the buffers.
5065 */
5066
5067 UpdateInterest(chanPtr);
5068 return len;
5069 }
5070
5071 /*
5072 *----------------------------------------------------------------------
5073 *
5074 * Tcl_Flush --
5075 *
5076 * Flushes output data on a channel.
5077 *
5078 * Results:
5079 * A standard Tcl result.
5080 *
5081 * Side effects:
5082 * May flush output queued on this channel.
5083 *
5084 *----------------------------------------------------------------------
5085 */
5086
5087 int
5088 Tcl_Flush(chan)
5089 Tcl_Channel chan; /* The Channel to flush. */
5090 {
5091 int result; /* Of calling FlushChannel. */
5092 Channel *chanPtr = (Channel *) chan; /* The actual channel. */
5093 ChannelState *statePtr = chanPtr->state; /* State of actual channel. */
5094
5095 /*
5096 * This operation should occur at the top of a channel stack.
5097 */
5098
5099 chanPtr = statePtr->topChanPtr;
5100
5101 if (CheckChannelErrors(statePtr, TCL_WRITABLE) != 0) {
5102 return -1;
5103 }
5104
5105 /*
5106 * Force current output buffer to be output also.
5107 */
5108
5109 if ((statePtr->curOutPtr != NULL)
5110 && (statePtr->curOutPtr->nextAdded > 0)) {
5111 statePtr->flags |= BUFFER_READY;
5112 }
5113
5114 result = FlushChannel(NULL, chanPtr, 0);
5115 if (result != 0) {
5116 return TCL_ERROR;
5117 }
5118
5119 return TCL_OK;
5120 }
5121
5122 /*
5123 *----------------------------------------------------------------------
5124 *
5125 * DiscardInputQueued --
5126 *
5127 * Discards any input read from the channel but not yet consumed
5128 * by Tcl reading commands.
5129 *
5130 * Results:
5131 * None.
5132 *
5133 * Side effects:
5134 * May discard input from the channel. If discardLastBuffer is zero,
5135 * leaves one buffer in place for back-filling.
5136 *
5137 *----------------------------------------------------------------------
5138 */
5139
5140 static void
5141 DiscardInputQueued(statePtr, discardSavedBuffers)
5142 ChannelState *statePtr; /* Channel on which to discard
5143 * the queued input. */
5144 int discardSavedBuffers; /* If non-zero, discard all buffers including
5145 * last one. */
5146 {
5147 ChannelBuffer *bufPtr, *nxtPtr; /* Loop variables. */
5148
5149 bufPtr = statePtr->inQueueHead;
5150 statePtr->inQueueHead = (ChannelBuffer *) NULL;
5151 statePtr->inQueueTail = (ChannelBuffer *) NULL;
5152 for (; bufPtr != (ChannelBuffer *) NULL; bufPtr = nxtPtr) {
5153 nxtPtr = bufPtr->nextPtr;
5154 RecycleBuffer(statePtr, bufPtr, discardSavedBuffers);
5155 }
5156
5157 /*
5158 * If discardSavedBuffers is nonzero, must also discard any previously
5159 * saved buffer in the saveInBufPtr field.
5160 */
5161
5162 if (discardSavedBuffers) {
5163 if (statePtr->saveInBufPtr != (ChannelBuffer *) NULL) {
5164 ckfree((char *) statePtr->saveInBufPtr);
5165 statePtr->saveInBufPtr = (ChannelBuffer *) NULL;
5166 }
5167 }
5168 }
5169
5170 /*
5171 *---------------------------------------------------------------------------
5172 *
5173 * GetInput --
5174 *
5175 * Reads input data from a device into a channel buffer.
5176 *
5177 * Results:
5178 * The return value is the Posix error code if an error occurred while
5179 * reading from the file, or 0 otherwise.
5180 *
5181 * Side effects:
5182 * Reads from the underlying device.
5183 *
5184 *---------------------------------------------------------------------------
5185 */
5186
5187 static int
5188 GetInput(chanPtr)
5189 Channel *chanPtr; /* Channel to read input from. */
5190 {
5191 int toRead; /* How much to read? */
5192 int result; /* Of calling driver. */
5193 int nread; /* How much was read from channel? */
5194 ChannelBuffer *bufPtr; /* New buffer to add to input queue. */
5195 ChannelState *statePtr = chanPtr->state; /* state info for channel */
5196
5197 /*
5198 * Prevent reading from a dead channel -- a channel that has been closed
5199 * but not yet deallocated, which can happen if the exit handler for
5200 * channel cleanup has run but the channel is still registered in some
5201 * interpreter.
5202 */
5203
5204 if (CheckForDeadChannel(NULL, statePtr)) {
5205 return EINVAL;
5206 }
5207
5208 /*
5209 * First check for more buffers in the pushback area of the
5210 * topmost channel in the stack and use them. They can be the
5211 * result of a transformation which went away without reading all
5212 * the information placed in the area when it was stacked.
5213 *
5214 * Two possibilities for the state: No buffers in it, or a single
5215 * empty buffer. In the latter case we can recycle it now.
5216 */
5217
5218 if (chanPtr->inQueueHead != (ChannelBuffer*) NULL) {
5219 if (statePtr->inQueueHead != (ChannelBuffer*) NULL) {
5220 RecycleBuffer(statePtr, statePtr->inQueueHead, 0);
5221 statePtr->inQueueHead = (ChannelBuffer*) NULL;
5222 }
5223
5224 statePtr->inQueueHead = chanPtr->inQueueHead;
5225 statePtr->inQueueTail = chanPtr->inQueueTail;
5226 chanPtr->inQueueHead = (ChannelBuffer*) NULL;
5227 chanPtr->inQueueTail = (ChannelBuffer*) NULL;
5228 return 0;
5229 }
5230
5231 /*
5232 * Nothing in the pushback area, fall back to the usual handling
5233 * (driver, etc.)
5234 */
5235
5236 /*
5237 * See if we can fill an existing buffer. If we can, read only
5238 * as much as will fit in it. Otherwise allocate a new buffer,
5239 * add it to the input queue and attempt to fill it to the max.
5240 */
5241
5242 bufPtr = statePtr->inQueueTail;
5243 if ((bufPtr != NULL) && (bufPtr->nextAdded < bufPtr->bufLength)) {
5244 toRead = bufPtr->bufLength - bufPtr->nextAdded;
5245 } else {
5246 bufPtr = statePtr->saveInBufPtr;
5247 statePtr->saveInBufPtr = NULL;
5248
5249 /*
5250 * Check the actual buffersize against the requested
5251 * buffersize. Buffers which are smaller than requested are
5252 * squashed. This is done to honor dynamic changes of the
5253 * buffersize made by the user.
5254 */
5255
5256 if ((bufPtr != NULL) && ((bufPtr->bufLength - BUFFER_PADDING) < statePtr->bufSize)) {
5257 ckfree((char *) bufPtr);
5258 bufPtr = NULL;
5259 }
5260
5261 if (bufPtr == NULL) {
5262 bufPtr = AllocChannelBuffer(statePtr->bufSize);
5263 }
5264 bufPtr->nextPtr = (ChannelBuffer *) NULL;
5265
5266 /* SF #427196: Use the actual size of the buffer to determine
5267 * the number of bytes to read from the channel and not the
5268 * size for new buffers. They can be different if the
5269 * buffersize was changed between reads.
5270 *
5271 * Note: This affects performance negatively if the buffersize
5272 * was extended but this small buffer is reused for all
5273 * subsequent reads. The system never uses buffers with the
5274 * requested bigger size in that case. An adjunct patch could
5275 * try and delete all unused buffers it encounters and which
5276 * are smaller than the formally requested buffersize.
5277 */
5278
5279 toRead = bufPtr->bufLength - bufPtr->nextAdded;
5280
5281 if (statePtr->inQueueTail == NULL) {
5282 statePtr->inQueueHead = bufPtr;
5283 } else {
5284 statePtr->inQueueTail->nextPtr = bufPtr;
5285 }
5286 statePtr->inQueueTail = bufPtr;
5287 }
5288
5289 /*
5290 * If EOF is set, we should avoid calling the driver because on some
5291 * platforms it is impossible to read from a device after EOF.
5292 */
5293
5294 if (statePtr->flags & CHANNEL_EOF) {
5295 return 0;
5296 }
5297
5298 if ((statePtr->flags & CHANNEL_TIMER_FEV) &&
5299 (statePtr->flags & CHANNEL_NONBLOCKING)) {
5300 nread = -1;
5301 result = EWOULDBLOCK;
5302 } else {
5303 nread = (chanPtr->typePtr->inputProc)(chanPtr->instanceData,
5304 bufPtr->buf + bufPtr->nextAdded, toRead, &result);
5305 }
5306
5307 if (nread > 0) {
5308 bufPtr->nextAdded += nread;
5309
5310 /*
5311 * If we get a short read, signal up that we may be BLOCKED. We
5312 * should avoid calling the driver because on some platforms we
5313 * will block in the low level reading code even though the
5314 * channel is set into nonblocking mode.
5315 */
5316
5317 if (nread < toRead) {
5318 statePtr->flags |= CHANNEL_BLOCKED;
5319 }
5320 } else if (nread == 0) {
5321 statePtr->flags |= CHANNEL_EOF;
5322 statePtr->inputEncodingFlags |= TCL_ENCODING_END;
5323 } else if (nread < 0) {
5324 if ((result == EWOULDBLOCK) || (result == EAGAIN)) {
5325 statePtr->flags |= CHANNEL_BLOCKED;
5326 result = EAGAIN;
5327 }
5328 Tcl_SetErrno(result);
5329 return result;
5330 }
5331 return 0;
5332 }
5333
5334 /*
5335 *----------------------------------------------------------------------
5336 *
5337 * Tcl_Seek --
5338 *
5339 * Implements seeking on Tcl Channels. This is a public function
5340 * so that other C facilities may be implemented on top of it.
5341 *
5342 * Results:
5343 * The new access point or -1 on error. If error, use Tcl_GetErrno()
5344 * to retrieve the POSIX error code for the error that occurred.
5345 *
5346 * Side effects:
5347 * May flush output on the channel. May discard queued input.
5348 *
5349 *----------------------------------------------------------------------
5350 */
5351
5352 Tcl_WideInt
5353 Tcl_Seek(chan, offset, mode)
5354 Tcl_Channel chan; /* The channel on which to seek. */
5355 Tcl_WideInt offset; /* Offset to seek to. */
5356 int mode; /* Relative to which location to seek? */
5357 {
5358 Channel *chanPtr = (Channel *) chan; /* The real IO channel. */
5359 ChannelState *statePtr = chanPtr->state; /* state info for channel */
5360 int inputBuffered, outputBuffered;
5361 /* # bytes held in buffers. */
5362 int result; /* Of device driver operations. */
5363 Tcl_WideInt curPos; /* Position on the device. */
5364 int wasAsync; /* Was the channel nonblocking before the
5365 * seek operation? If so, must restore to
5366 * nonblocking mode after the seek. */
5367
5368 if (CheckChannelErrors(statePtr, TCL_WRITABLE | TCL_READABLE) != 0) {
5369 return Tcl_LongAsWide(-1);
5370 }
5371
5372 /*
5373 * Disallow seek on dead channels -- channels that have been closed but
5374 * not yet been deallocated. Such channels can be found if the exit
5375 * handler for channel cleanup has run but the channel is still
5376 * registered in an interpreter.
5377 */
5378
5379 if (CheckForDeadChannel(NULL, statePtr)) {
5380 return Tcl_LongAsWide(-1);
5381 }
5382
5383 /*
5384 * This operation should occur at the top of a channel stack.
5385 */
5386
5387 chanPtr = statePtr->topChanPtr;
5388
5389 /*
5390 * Disallow seek on channels whose type does not have a seek procedure
5391 * defined. This means that the channel does not support seeking.
5392 */
5393
5394 if (chanPtr->typePtr->seekProc == (Tcl_DriverSeekProc *) NULL) {
5395 Tcl_SetErrno(EINVAL);
5396 return Tcl_LongAsWide(-1);
5397 }
5398
5399 /*
5400 * Compute how much input and output is buffered. If both input and
5401 * output is buffered, cannot compute the current position.
5402 */
5403
5404 inputBuffered = Tcl_InputBuffered(chan);
5405 outputBuffered = Tcl_OutputBuffered(chan);
5406
5407 if ((inputBuffered != 0) && (outputBuffered != 0)) {
5408 Tcl_SetErrno(EFAULT);
5409 return Tcl_LongAsWide(-1);
5410 }
5411
5412 /*
5413 * If we are seeking relative to the current position, compute the
5414 * corrected offset taking into account the amount of unread input.
5415 */
5416
5417 if (mode == SEEK_CUR) {
5418 offset -= inputBuffered;
5419 }
5420
5421 /*
5422 * Discard any queued input - this input should not be read after
5423 * the seek.
5424 */
5425
5426 DiscardInputQueued(statePtr, 0);
5427
5428 /*
5429 * Reset EOF and BLOCKED flags. We invalidate them by moving the
5430 * access point. Also clear CR related flags.
5431 */
5432
5433 statePtr->flags &=
5434 (~(CHANNEL_EOF | CHANNEL_STICKY_EOF | CHANNEL_BLOCKED | INPUT_SAW_CR));
5435
5436 /*
5437 * If the channel is in asynchronous output mode, switch it back
5438 * to synchronous mode and cancel any async flush that may be
5439 * scheduled. After the flush, the channel will be put back into
5440 * asynchronous output mode.
5441 */
5442
5443 wasAsync = 0;
5444 if (statePtr->flags & CHANNEL_NONBLOCKING) {
5445 wasAsync = 1;
5446 result = StackSetBlockMode(chanPtr, TCL_MODE_BLOCKING);
5447 if (result != 0) {
5448 return Tcl_LongAsWide(-1);
5449 }
5450 statePtr->flags &= (~(CHANNEL_NONBLOCKING));
5451 if (statePtr->flags & BG_FLUSH_SCHEDULED) {
5452 statePtr->flags &= (~(BG_FLUSH_SCHEDULED));
5453 }
5454 }
5455
5456 /*
5457 * If the flush fails we cannot recover the original position. In
5458 * that case the seek is not attempted because we do not know where
5459 * the access position is - instead we return the error. FlushChannel
5460 * has already called Tcl_SetErrno() to report the error upwards.
5461 * If the flush succeeds we do the seek also.
5462 */
5463
5464 if (FlushChannel(NULL, chanPtr, 0) != 0) {
5465 curPos = -1;
5466 } else {
5467
5468 /*
5469 * Now seek to the new position in the channel as requested by the
5470 * caller. Note that we prefer the wideSeekProc if that is
5471 * available and non-NULL...
5472 */
5473
5474 if (HaveVersion(chanPtr->typePtr, TCL_CHANNEL_VERSION_3) &&
5475 chanPtr->typePtr->wideSeekProc != NULL) {
5476 curPos = (chanPtr->typePtr->wideSeekProc) (chanPtr->instanceData,
5477 offset, mode, &result);
5478 } else if (offset < Tcl_LongAsWide(LONG_MIN) ||
5479 offset > Tcl_LongAsWide(LONG_MAX)) {
5480 Tcl_SetErrno(EOVERFLOW);
5481 curPos = Tcl_LongAsWide(-1);
5482 } else {
5483 curPos = Tcl_LongAsWide((chanPtr->typePtr->seekProc) (
5484 chanPtr->instanceData, Tcl_WideAsLong(offset), mode,
5485 &result));
5486 if (curPos == Tcl_LongAsWide(-1)) {
5487 Tcl_SetErrno(result);
5488 }
5489 }
5490 }
5491
5492 /*
5493 * Restore to nonblocking mode if that was the previous behavior.
5494 *
5495 * NOTE: Even if there was an async flush active we do not restore
5496 * it now because we already flushed all the queued output, above.
5497 */
5498
5499 if (wasAsync) {
5500 statePtr->flags |= CHANNEL_NONBLOCKING;
5501 result = StackSetBlockMode(chanPtr, TCL_MODE_NONBLOCKING);
5502 if (result != 0) {
5503 return Tcl_LongAsWide(-1);
5504 }
5505 }
5506
5507 return curPos;
5508 }
5509
5510 /*
5511 *----------------------------------------------------------------------
5512 *
5513 * Tcl_Tell --
5514 *
5515 * Returns the position of the next character to be read/written on
5516 * this channel.
5517 *
5518 * Results:
5519 * A nonnegative integer on success, -1 on failure. If failed,
5520 * use Tcl_GetErrno() to retrieve the POSIX error code for the
5521 * error that occurred.
5522 *
5523 * Side effects:
5524 * None.
5525 *
5526 *----------------------------------------------------------------------
5527 */
5528
5529 Tcl_WideInt
5530 Tcl_Tell(chan)
5531 Tcl_Channel chan; /* The channel to return pos for. */
5532 {
5533 Channel *chanPtr = (Channel *) chan; /* The real IO channel. */
5534 ChannelState *statePtr = chanPtr->state; /* state info for channel */
5535 int inputBuffered, outputBuffered; /* # bytes held in buffers. */
5536 int result; /* Of calling device driver. */
5537 Tcl_WideInt curPos; /* Position on device. */
5538
5539 if (CheckChannelErrors(statePtr, TCL_WRITABLE | TCL_READABLE) != 0) {
5540 return Tcl_LongAsWide(-1);
5541 }
5542
5543 /*
5544 * Disallow tell on dead channels -- channels that have been closed but
5545 * not yet been deallocated. Such channels can be found if the exit
5546 * handler for channel cleanup has run but the channel is still
5547 * registered in an interpreter.
5548 */
5549
5550 if (CheckForDeadChannel(NULL, statePtr)) {
5551 return Tcl_LongAsWide(-1);
5552 }
5553
5554 /*
5555 * This operation should occur at the top of a channel stack.
5556 */
5557
5558 chanPtr = statePtr->topChanPtr;
5559
5560 /*
5561 * Disallow tell on channels whose type does not have a seek procedure
5562 * defined. This means that the channel does not support seeking.
5563 */
5564
5565 if (chanPtr->typePtr->seekProc == (Tcl_DriverSeekProc *) NULL) {
5566 Tcl_SetErrno(EINVAL);
5567 return Tcl_LongAsWide(-1);
5568 }
5569
5570 /*
5571 * Compute how much input and output is buffered. If both input and
5572 * output is buffered, cannot compute the current position.
5573 */
5574
5575 inputBuffered = Tcl_InputBuffered(chan);
5576 outputBuffered = Tcl_OutputBuffered(chan);
5577
5578 if ((inputBuffered != 0) && (outputBuffered != 0)) {
5579 Tcl_SetErrno(EFAULT);
5580 return Tcl_LongAsWide(-1);
5581 }
5582
5583 /*
5584 * Get the current position in the device and compute the position
5585 * where the next character will be read or written. Note that we
5586 * prefer the wideSeekProc if that is available and non-NULL...
5587 */
5588
5589 if (HaveVersion(chanPtr->typePtr, TCL_CHANNEL_VERSION_3) &&
5590 chanPtr->typePtr->wideSeekProc != NULL) {
5591 curPos = (chanPtr->typePtr->wideSeekProc) (chanPtr->instanceData,
5592 Tcl_LongAsWide(0), SEEK_CUR, &result);
5593 } else {
5594 curPos = Tcl_LongAsWide((chanPtr->typePtr->seekProc) (
5595 chanPtr->instanceData, 0, SEEK_CUR, &result));
5596 }
5597 if (curPos == Tcl_LongAsWide(-1)) {
5598 Tcl_SetErrno(result);
5599 return Tcl_LongAsWide(-1);
5600 }
5601 if (inputBuffered != 0) {
5602 return curPos - inputBuffered;
5603 }
5604 return curPos + outputBuffered;
5605 }
5606
5607 /*
5608 *---------------------------------------------------------------------------
5609 *
5610 * Tcl_SeekOld, Tcl_TellOld --
5611 *
5612 * Backward-compatability versions of the seek/tell interface that
5613 * do not support 64-bit offsets. This interface is not documented
5614 * or expected to be supported indefinitely.
5615 *
5616 * Results:
5617 * As for Tcl_Seek and Tcl_Tell respectively, except truncated to
5618 * whatever value will fit in an 'int'.
5619 *
5620 * Side effects:
5621 * As for Tcl_Seek and Tcl_Tell respectively.
5622 *
5623 *---------------------------------------------------------------------------
5624 */
5625
5626 int
5627 Tcl_SeekOld(chan, offset, mode)
5628 Tcl_Channel chan; /* The channel on which to seek. */
5629 int offset; /* Offset to seek to. */
5630 int mode; /* Relative to which location to seek? */
5631 {
5632 Tcl_WideInt wOffset, wResult;
5633
5634 wOffset = Tcl_LongAsWide((long)offset);
5635 wResult = Tcl_Seek(chan, wOffset, mode);
5636 return (int)Tcl_WideAsLong(wResult);
5637 }
5638
5639 int
5640 Tcl_TellOld(chan)
5641 Tcl_Channel chan; /* The channel to return pos for. */
5642 {
5643 Tcl_WideInt wResult;
5644
5645 wResult = Tcl_Tell(chan);
5646 return (int)Tcl_WideAsLong(wResult);
5647 }
5648
5649 /*
5650 *---------------------------------------------------------------------------
5651 *
5652 * CheckChannelErrors --
5653 *
5654 * See if the channel is in an ready state and can perform the
5655 * desired operation.
5656 *
5657 * Results:
5658 * The return value is 0 if the channel is OK, otherwise the
5659 * return value is -1 and errno is set to indicate the error.
5660 *
5661 * Side effects:
5662 * May clear the EOF and/or BLOCKED bits if reading from channel.
5663 *
5664 *---------------------------------------------------------------------------
5665 */
5666
5667 static int
5668 CheckChannelErrors(statePtr, flags)
5669 ChannelState *statePtr; /* Channel to check. */
5670 int flags; /* Test if channel supports desired operation:
5671 * TCL_READABLE, TCL_WRITABLE. Also indicates
5672 * Raw read or write for special close
5673 * processing*/
5674 {
5675 int direction = flags & (TCL_READABLE|TCL_WRITABLE);
5676
5677 /*
5678 * Check for unreported error.
5679 */
5680
5681 if (statePtr->unreportedError != 0) {
5682 Tcl_SetErrno(statePtr->unreportedError);
5683 statePtr->unreportedError = 0;
5684 return -1;
5685 }
5686
5687 /*
5688 * Only the raw read and write operations are allowed during close
5689 * in order to drain data from stacked channels.
5690 */
5691
5692 if ((statePtr->flags & CHANNEL_CLOSED) &&
5693 ((flags & CHANNEL_RAW_MODE) == 0)) {
5694 Tcl_SetErrno(EACCES);
5695 return -1;
5696 }
5697
5698 /*
5699 * Fail if the channel is not opened for desired operation.
5700 */
5701
5702 if ((statePtr->flags & direction) == 0) {
5703 Tcl_SetErrno(EACCES);
5704 return -1;
5705 }
5706
5707 /*
5708 * Fail if the channel is in the middle of a background copy.
5709 *
5710 * Don't do this tests for raw channels here or else the chaining in the
5711 * transformation drivers will fail with 'file busy' error instead of
5712 * retrieving and transforming the data to copy.
5713 */
5714
5715 if ((statePtr->csPtr != NULL) && ((flags & CHANNEL_RAW_MODE) == 0)) {
5716 Tcl_SetErrno(EBUSY);
5717 return -1;
5718 }
5719
5720 if (direction == TCL_READABLE) {
5721 /*
5722 * If we have not encountered a sticky EOF, clear the EOF bit
5723 * (sticky EOF is set if we have seen the input eofChar, to prevent
5724 * reading beyond the eofChar). Also, always clear the BLOCKED bit.
5725 * We want to discover these conditions anew in each operation.
5726 */
5727
5728 if ((statePtr->flags & CHANNEL_STICKY_EOF) == 0) {
5729 statePtr->flags &= ~CHANNEL_EOF;
5730 }
5731 statePtr->flags &= ~(CHANNEL_BLOCKED | CHANNEL_NEED_MORE_DATA);
5732 }
5733
5734 return 0;
5735 }
5736
5737 /*
5738 *----------------------------------------------------------------------
5739 *
5740 * Tcl_Eof --
5741 *
5742 * Returns 1 if the channel is at EOF, 0 otherwise.
5743 *
5744 * Results:
5745 * 1 or 0, always.
5746 *
5747 * Side effects:
5748 * None.
5749 *
5750 *----------------------------------------------------------------------
5751 */
5752
5753 int
5754 Tcl_Eof(chan)
5755 Tcl_Channel chan; /* Does this channel have EOF? */
5756 {
5757 ChannelState *statePtr = ((Channel *) chan)->state;
5758 /* State of real channel structure. */
5759
5760 return ((statePtr->flags & CHANNEL_STICKY_EOF) ||
5761 ((statePtr->flags & CHANNEL_EOF) &&
5762 (Tcl_InputBuffered(chan) == 0))) ? 1 : 0;
5763 }
5764
5765 /*
5766 *----------------------------------------------------------------------
5767 *
5768 * Tcl_InputBlocked --
5769 *
5770 * Returns 1 if input is blocked on this channel, 0 otherwise.
5771 *
5772 * Results:
5773 * 0 or 1, always.
5774 *
5775 * Side effects:
5776 * None.
5777 *
5778 *----------------------------------------------------------------------
5779 */
5780
5781 int
5782 Tcl_InputBlocked(chan)
5783 Tcl_Channel chan; /* Is this channel blocked? */
5784 {
5785 ChannelState *statePtr = ((Channel *) chan)->state;
5786 /* State of real channel structure. */
5787
5788 return (statePtr->flags & CHANNEL_BLOCKED) ? 1 : 0;
5789 }
5790
5791 /*
5792 *----------------------------------------------------------------------
5793 *
5794 * Tcl_InputBuffered --
5795 *
5796 * Returns the number of bytes of input currently buffered in the
5797 * common internal buffer of a channel.
5798 *
5799 * Results:
5800 * The number of input bytes buffered, or zero if the channel is not
5801 * open for reading.
5802 *
5803 * Side effects:
5804 * None.
5805 *
5806 *----------------------------------------------------------------------
5807 */
5808
5809 int
5810 Tcl_InputBuffered(chan)
5811 Tcl_Channel chan; /* The channel to query. */
5812 {
5813 ChannelState *statePtr = ((Channel *) chan)->state;
5814 /* State of real channel structure. */
5815 ChannelBuffer *bufPtr;
5816 int bytesBuffered;
5817
5818 for (bytesBuffered = 0, bufPtr = statePtr->inQueueHead;
5819 bufPtr != (ChannelBuffer *) NULL;
5820 bufPtr = bufPtr->nextPtr) {
5821 bytesBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
5822 }
5823
5824 /*
5825 * Don't forget the bytes in the topmost pushback area.
5826 */
5827
5828 for (bufPtr = statePtr->topChanPtr->inQueueHead;
5829 bufPtr != (ChannelBuffer *) NULL;
5830 bufPtr = bufPtr->nextPtr) {
5831 bytesBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
5832 }
5833
5834 return bytesBuffered;
5835 }
5836
5837 /*
5838 *----------------------------------------------------------------------
5839 *
5840 * Tcl_OutputBuffered --
5841 *
5842 * Returns the number of bytes of output currently buffered in the
5843 * common internal buffer of a channel.
5844 *
5845 * Results:
5846 * The number of output bytes buffered, or zero if the channel is not
5847 * open for writing.
5848 *
5849 * Side effects:
5850 * None.
5851 *
5852 *----------------------------------------------------------------------
5853 */
5854
5855 int
5856 Tcl_OutputBuffered(chan)
5857 Tcl_Channel chan; /* The channel to query. */
5858 {
5859 ChannelState *statePtr = ((Channel *) chan)->state;
5860 /* State of real channel structure. */
5861 ChannelBuffer *bufPtr;
5862 int bytesBuffered;
5863
5864 for (bytesBuffered = 0, bufPtr = statePtr->outQueueHead;
5865 bufPtr != (ChannelBuffer *) NULL;
5866 bufPtr = bufPtr->nextPtr) {
5867 bytesBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
5868 }
5869 if ((statePtr->curOutPtr != (ChannelBuffer *) NULL) &&
5870 (statePtr->curOutPtr->nextAdded > statePtr->curOutPtr->nextRemoved)) {
5871 statePtr->flags |= BUFFER_READY;
5872 bytesBuffered +=
5873 (statePtr->curOutPtr->nextAdded - statePtr->curOutPtr->nextRemoved);
5874 }
5875
5876 return bytesBuffered;
5877 }
5878
5879 /*
5880 *----------------------------------------------------------------------
5881 *
5882 * Tcl_ChannelBuffered --
5883 *
5884 * Returns the number of bytes of input currently buffered in the
5885 * internal buffer (push back area) of a channel.
5886 *
5887 * Results:
5888 * The number of input bytes buffered, or zero if the channel is not
5889 * open for reading.
5890 *
5891 * Side effects:
5892 * None.
5893 *
5894 *----------------------------------------------------------------------
5895 */
5896
5897 int
5898 Tcl_ChannelBuffered(chan)
5899 Tcl_Channel chan; /* The channel to query. */
5900 {
5901 Channel *chanPtr = (Channel *) chan;
5902 /* real channel structure. */
5903 ChannelBuffer *bufPtr;
5904 int bytesBuffered;
5905
5906 for (bytesBuffered = 0, bufPtr = chanPtr->inQueueHead;
5907 bufPtr != (ChannelBuffer *) NULL;
5908 bufPtr = bufPtr->nextPtr) {
5909 bytesBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
5910 }
5911
5912 return bytesBuffered;
5913 }
5914
5915 /*
5916 *----------------------------------------------------------------------
5917 *
5918 * Tcl_SetChannelBufferSize --
5919 *
5920 * Sets the size of buffers to allocate to store input or output
5921 * in the channel. The size must be between 10 bytes and 1 MByte.
5922 *
5923 * Results:
5924 * None.
5925 *
5926 * Side effects:
5927 * Sets the size of buffers subsequently allocated for this channel.
5928 *
5929 *----------------------------------------------------------------------
5930 */
5931
5932 void
5933 Tcl_SetChannelBufferSize(chan, sz)
5934 Tcl_Channel chan; /* The channel whose buffer size
5935 * to set. */
5936 int sz; /* The size to set. */
5937 {
5938 ChannelState *statePtr; /* State of real channel structure. */
5939
5940 /*
5941 * If the buffer size is smaller than 10 bytes or larger than one MByte,
5942 * do not accept the requested size and leave the current buffer size.
5943 */
5944
5945 if (sz < 10) {
5946 return;
5947 }
5948 if (sz > (1024 * 1024)) {
5949 return;
5950 }
5951
5952 statePtr = ((Channel *) chan)->state;
5953 statePtr->bufSize = sz;
5954
5955 if (statePtr->outputStage != NULL) {
5956 ckfree((char *) statePtr->outputStage);
5957 statePtr->outputStage = NULL;
5958 }
5959 if ((statePtr->encoding != NULL) && (statePtr->flags & TCL_WRITABLE)) {
5960 statePtr->outputStage = (char *)
5961 ckalloc((unsigned) (statePtr->bufSize + 2));
5962 }
5963 }
5964
5965 /*
5966 *----------------------------------------------------------------------
5967 *
5968 * Tcl_GetChannelBufferSize --
5969 *
5970 * Retrieves the size of buffers to allocate for this channel.
5971 *
5972 * Results:
5973 * The size.
5974 *
5975 * Side effects:
5976 * None.
5977 *
5978 *----------------------------------------------------------------------
5979 */
5980
5981 int
5982 Tcl_GetChannelBufferSize(chan)
5983 Tcl_Channel chan; /* The channel for which to find the
5984 * buffer size. */
5985 {
5986 ChannelState *statePtr = ((Channel *) chan)->state;
5987 /* State of real channel structure. */
5988
5989 return statePtr->bufSize;
5990 }
5991
5992 /*
5993 *----------------------------------------------------------------------
5994 *
5995 * Tcl_BadChannelOption --
5996 *
5997 * This procedure generates a "bad option" error message in an
5998 * (optional) interpreter. It is used by channel drivers when
5999 * a invalid Set/Get option is requested. Its purpose is to concatenate
6000 * the generic options list to the specific ones and factorize
6001 * the generic options error message string.
6002 *
6003 * Results:
6004 * TCL_ERROR.
6005 *
6006 * Side effects:
6007 * An error message is generated in interp's result object to
6008 * indicate that a command was invoked with the a bad option
6009 * The message has the form
6010 * bad option "blah": should be one of
6011 * <...generic options...>+<...specific options...>
6012 * "blah" is the optionName argument and "<specific options>"
6013 * is a space separated list of specific option words.
6014 * The function takes good care of inserting minus signs before
6015 * each option, commas after, and an "or" before the last option.
6016 *
6017 *----------------------------------------------------------------------
6018 */
6019
6020 int
6021 Tcl_BadChannelOption(interp, optionName, optionList)
6022 Tcl_Interp *interp; /* Current interpreter. (can be NULL)*/
6023 CONST char *optionName; /* 'bad option' name */
6024 CONST char *optionList; /* Specific options list to append
6025 * to the standard generic options.
6026 * can be NULL for generic options
6027 * only.
6028 */
6029 {
6030 if (interp) {
6031 CONST char *genericopt =
6032 "blocking buffering buffersize encoding eofchar translation";
6033 CONST char **argv;
6034 int argc, i;
6035 Tcl_DString ds;
6036
6037 Tcl_DStringInit(&ds);
6038 Tcl_DStringAppend(&ds, genericopt, -1);
6039 if (optionList && (*optionList)) {
6040 Tcl_DStringAppend(&ds, " ", 1);
6041 Tcl_DStringAppend(&ds, optionList, -1);
6042 }
6043 if (Tcl_SplitList(interp, Tcl_DStringValue(&ds),
6044 &argc, &argv) != TCL_OK) {
6045 panic("malformed option list in channel driver");
6046 }
6047 Tcl_ResetResult(interp);
6048 Tcl_AppendResult(interp, "bad option \"", optionName,
6049 "\": should be one of ", (char *) NULL);
6050 argc--;
6051 for (i = 0; i < argc; i++) {
6052 Tcl_AppendResult(interp, "-", argv[i], ", ", (char *) NULL);
6053 }
6054 Tcl_AppendResult(interp, "or -", argv[i], (char *) NULL);
6055 Tcl_DStringFree(&ds);
6056 ckfree((char *) argv);
6057 }
6058 Tcl_SetErrno(EINVAL);
6059 return TCL_ERROR;
6060 }
6061
6062 /*
6063 *----------------------------------------------------------------------
6064 *
6065 * Tcl_GetChannelOption --
6066 *
6067 * Gets a mode associated with an IO channel. If the optionName arg
6068 * is non NULL, retrieves the value of that option. If the optionName
6069 * arg is NULL, retrieves a list of alternating option names and
6070 * values for the given channel.
6071 *
6072 * Results:
6073 * A standard Tcl result. Also sets the supplied DString to the
6074 * string value of the option(s) returned.
6075 *
6076 * Side effects:
6077 * None.
6078 *
6079 *----------------------------------------------------------------------
6080 */
6081
6082 int
6083 Tcl_GetChannelOption(interp, chan, optionName, dsPtr)
6084 Tcl_Interp *interp; /* For error reporting - can be NULL. */
6085 Tcl_Channel chan; /* Channel on which to get option. */
6086 CONST char *optionName; /* Option to get. */
6087 Tcl_DString *dsPtr; /* Where to store value(s). */
6088 {
6089 size_t len; /* Length of optionName string. */
6090 char optionVal[128]; /* Buffer for sprintf. */
6091 Channel *chanPtr = (Channel *) chan;
6092 ChannelState *statePtr = chanPtr->state; /* state info for channel */
6093 int flags;
6094
6095 /*
6096 * Disallow options on dead channels -- channels that have been closed but
6097 * not yet been deallocated. Such channels can be found if the exit
6098 * handler for channel cleanup has run but the channel is still
6099 * registered in an interpreter.
6100 */
6101
6102 if (CheckForDeadChannel(interp, statePtr)) {
6103 return TCL_ERROR;
6104 }
6105
6106 /*
6107 * This operation should occur at the top of a channel stack.
6108 */
6109
6110 chanPtr = statePtr->topChanPtr;
6111
6112 /*
6113 * If we are in the middle of a background copy, use the saved flags.
6114 */
6115
6116 if (statePtr->csPtr) {
6117 if (chanPtr == statePtr->csPtr->readPtr) {
6118 flags = statePtr->csPtr->readFlags;
6119 } else {
6120 flags = statePtr->csPtr->writeFlags;
6121 }
6122 } else {
6123 flags = statePtr->flags;
6124 }
6125
6126 /*
6127 * If the optionName is NULL it means that we want a list of all
6128 * options and values.
6129 */
6130
6131 if (optionName == (char *) NULL) {
6132 len = 0;
6133 } else {
6134 len = strlen(optionName);
6135 }
6136
6137 if ((len == 0) || ((len > 2) && (optionName[1] == 'b') &&
6138 (strncmp(optionName, "-blocking", len) == 0))) {
6139 if (len == 0) {
6140 Tcl_DStringAppendElement(dsPtr, "-blocking");
6141 }
6142 Tcl_DStringAppendElement(dsPtr,
6143 (flags & CHANNEL_NONBLOCKING) ? "0" : "1");
6144 if (len > 0) {
6145 return TCL_OK;
6146 }
6147 }
6148 if ((len == 0) || ((len > 7) && (optionName[1] == 'b') &&
6149 (strncmp(optionName, "-buffering", len) == 0))) {
6150 if (len == 0) {
6151 Tcl_DStringAppendElement(dsPtr, "-buffering");
6152 }
6153 if (flags & CHANNEL_LINEBUFFERED) {
6154 Tcl_DStringAppendElement(dsPtr, "line");
6155 } else if (flags & CHANNEL_UNBUFFERED) {
6156 Tcl_DStringAppendElement(dsPtr, "none");
6157 } else {
6158 Tcl_DStringAppendElement(dsPtr, "full");
6159 }
6160 if (len > 0) {
6161 return TCL_OK;
6162 }
6163 }
6164 if ((len == 0) || ((len > 7) && (optionName[1] == 'b') &&
6165 (strncmp(optionName, "-buffersize", len) == 0))) {
6166 if (len == 0) {
6167 Tcl_DStringAppendElement(dsPtr, "-buffersize");
6168 }
6169 TclFormatInt(optionVal, statePtr->bufSize);
6170 Tcl_DStringAppendElement(dsPtr, optionVal);
6171 if (len > 0) {
6172 return TCL_OK;
6173 }
6174 }
6175 if ((len == 0) ||
6176 ((len > 2) && (optionName[1] == 'e') &&
6177 (strncmp(optionName, "-encoding", len) == 0))) {
6178 if (len == 0) {
6179 Tcl_DStringAppendElement(dsPtr, "-encoding");
6180 }
6181 if (statePtr->encoding == NULL) {
6182 Tcl_DStringAppendElement(dsPtr, "binary");
6183 } else {
6184 Tcl_DStringAppendElement(dsPtr,
6185 Tcl_GetEncodingName(statePtr->encoding));
6186 }
6187 if (len > 0) {
6188 return TCL_OK;
6189 }
6190 }
6191 if ((len == 0) ||
6192 ((len > 2) && (optionName[1] == 'e') &&
6193 (strncmp(optionName, "-eofchar", len) == 0))) {
6194 if (len == 0) {
6195 Tcl_DStringAppendElement(dsPtr, "-eofchar");
6196 }
6197 if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
6198 (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
6199 Tcl_DStringStartSublist(dsPtr);
6200 }
6201 if (flags & TCL_READABLE) {
6202 if (statePtr->inEofChar == 0) {
6203 Tcl_DStringAppendElement(dsPtr, "");
6204 } else {
6205 char buf[4];
6206
6207 sprintf(buf, "%c", statePtr->inEofChar);
6208 Tcl_DStringAppendElement(dsPtr, buf);
6209 }
6210 }
6211 if (flags & TCL_WRITABLE) {
6212 if (statePtr->outEofChar == 0) {
6213 Tcl_DStringAppendElement(dsPtr, "");
6214 } else {
6215 char buf[4];
6216
6217 sprintf(buf, "%c", statePtr->outEofChar);
6218 Tcl_DStringAppendElement(dsPtr, buf);
6219 }
6220 }
6221 if ( !(flags & (TCL_READABLE|TCL_WRITABLE))) {
6222 /* Not readable or writable (server socket) */
6223 Tcl_DStringAppendElement(dsPtr, "");
6224 }
6225 if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
6226 (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
6227 Tcl_DStringEndSublist(dsPtr);
6228 }
6229 if (len > 0) {
6230 return TCL_OK;
6231 }
6232 }
6233 if ((len == 0) ||
6234 ((len > 1) && (optionName[1] == 't') &&
6235 (strncmp(optionName, "-translation", len) == 0))) {
6236 if (len == 0) {
6237 Tcl_DStringAppendElement(dsPtr, "-translation");
6238 }
6239 if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
6240 (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
6241 Tcl_DStringStartSublist(dsPtr);
6242 }
6243 if (flags & TCL_READABLE) {
6244 if (statePtr->inputTranslation == TCL_TRANSLATE_AUTO) {
6245 Tcl_DStringAppendElement(dsPtr, "auto");
6246 } else if (statePtr->inputTranslation == TCL_TRANSLATE_CR) {
6247 Tcl_DStringAppendElement(dsPtr, "cr");
6248 } else if (statePtr->inputTranslation == TCL_TRANSLATE_CRLF) {
6249 Tcl_DStringAppendElement(dsPtr, "crlf");
6250 } else {
6251 Tcl_DStringAppendElement(dsPtr, "lf");
6252 }
6253 }
6254 if (flags & TCL_WRITABLE) {
6255 if (statePtr->outputTranslation == TCL_TRANSLATE_AUTO) {
6256 Tcl_DStringAppendElement(dsPtr, "auto");
6257 } else if (statePtr->outputTranslation == TCL_TRANSLATE_CR) {
6258 Tcl_DStringAppendElement(dsPtr, "cr");
6259 } else if (statePtr->outputTranslation == TCL_TRANSLATE_CRLF) {
6260 Tcl_DStringAppendElement(dsPtr, "crlf");
6261 } else {
6262 Tcl_DStringAppendElement(dsPtr, "lf");
6263 }
6264 }
6265 if ( !(flags & (TCL_READABLE|TCL_WRITABLE))) {
6266 /* Not readable or writable (server socket) */
6267 Tcl_DStringAppendElement(dsPtr, "auto");
6268 }
6269 if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
6270 (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
6271 Tcl_DStringEndSublist(dsPtr);
6272 }
6273 if (len > 0) {
6274 return TCL_OK;
6275 }
6276 }
6277 if (chanPtr->typePtr->getOptionProc != (Tcl_DriverGetOptionProc *) NULL) {
6278 /*
6279 * let the driver specific handle additional options
6280 * and result code and message.
6281 */
6282
6283 return (chanPtr->typePtr->getOptionProc) (chanPtr->instanceData,
6284 interp, optionName, dsPtr);
6285 } else {
6286 /*
6287 * no driver specific options case.
6288 */
6289
6290 if (len == 0) {
6291 return TCL_OK;
6292 }
6293 return Tcl_BadChannelOption(interp, optionName, NULL);
6294 }
6295 }
6296
6297 /*
6298 *---------------------------------------------------------------------------
6299 *
6300 * Tcl_SetChannelOption --
6301 *
6302 * Sets an option on a channel.
6303 *
6304 * Results:
6305 * A standard Tcl result. On error, sets interp's result object
6306 * if interp is not NULL.
6307 *
6308 * Side effects:
6309 * May modify an option on a device.
6310 *
6311 *---------------------------------------------------------------------------
6312 */
6313
6314 int
6315 Tcl_SetChannelOption(interp, chan, optionName, newValue)
6316 Tcl_Interp *interp; /* For error reporting - can be NULL. */
6317 Tcl_Channel chan; /* Channel on which to set mode. */
6318 CONST char *optionName; /* Which option to set? */
6319 CONST char *newValue; /* New value for option. */
6320 {
6321 Channel *chanPtr = (Channel *) chan; /* The real IO channel. */
6322 ChannelState *statePtr = chanPtr->state; /* state info for channel */
6323 size_t len; /* Length of optionName string. */
6324 int argc;
6325 CONST char **argv;
6326
6327 /*
6328 * If the channel is in the middle of a background copy, fail.
6329 */
6330
6331 if (statePtr->csPtr) {
6332 if (interp) {
6333 Tcl_AppendResult(interp,
6334 "unable to set channel options: background copy in progress",
6335 (char *) NULL);
6336 }
6337 return TCL_ERROR;
6338 }
6339
6340 /*
6341 * Disallow options on dead channels -- channels that have been closed but
6342 * not yet been deallocated. Such channels can be found if the exit
6343 * handler for channel cleanup has run but the channel is still
6344 * registered in an interpreter.
6345 */
6346
6347 if (CheckForDeadChannel(NULL, statePtr)) {
6348 return TCL_ERROR;
6349 }
6350
6351 /*
6352 * This operation should occur at the top of a channel stack.
6353 */
6354
6355 chanPtr = statePtr->topChanPtr;
6356
6357 len = strlen(optionName);
6358
6359 if ((len > 2) && (optionName[1] == 'b') &&
6360 (strncmp(optionName, "-blocking", len) == 0)) {
6361 int newMode;
6362 if (Tcl_GetBoolean(interp, newValue, &newMode) == TCL_ERROR) {
6363 return TCL_ERROR;
6364 }
6365 if (newMode) {
6366 newMode = TCL_MODE_BLOCKING;
6367 } else {
6368 newMode = TCL_MODE_NONBLOCKING;
6369 }
6370 return SetBlockMode(interp, chanPtr, newMode);
6371 } else if ((len > 7) && (optionName[1] == 'b') &&
6372 (strncmp(optionName, "-buffering", len) == 0)) {
6373 len = strlen(newValue);
6374 if ((newValue[0] == 'f') && (strncmp(newValue, "full", len) == 0)) {
6375 statePtr->flags &=
6376 (~(CHANNEL_UNBUFFERED|CHANNEL_LINEBUFFERED));
6377 } else if ((newValue[0] == 'l') &&
6378 (strncmp(newValue, "line", len) == 0)) {
6379 statePtr->flags &= (~(CHANNEL_UNBUFFERED));
6380 statePtr->flags |= CHANNEL_LINEBUFFERED;
6381 } else if ((newValue[0] == 'n') &&
6382 (strncmp(newValue, "none", len) == 0)) {
6383 statePtr->flags &= (~(CHANNEL_LINEBUFFERED));
6384 statePtr->flags |= CHANNEL_UNBUFFERED;
6385 } else {
6386 if (interp) {
6387 Tcl_AppendResult(interp, "bad value for -buffering: ",
6388 "must be one of full, line, or none",
6389 (char *) NULL);
6390 return TCL_ERROR;
6391 }
6392 }
6393 return TCL_OK;
6394 } else if ((len > 7) && (optionName[1] == 'b') &&
6395 (strncmp(optionName, "-buffersize", len) == 0)) {
6396 statePtr->bufSize = atoi(newValue); /* INTL: "C", UTF safe. */
6397 if ((statePtr->bufSize < 10) || (statePtr->bufSize > (1024 * 1024))) {
6398 statePtr->bufSize = CHANNELBUFFER_DEFAULT_SIZE;
6399 }
6400 } else if ((len > 2) && (optionName[1] == 'e') &&
6401 (strncmp(optionName, "-encoding", len) == 0)) {
6402 Tcl_Encoding encoding;
6403
6404 if ((newValue[0] == '\0') || (strcmp(newValue, "binary") == 0)) {
6405 encoding = NULL;
6406 } else {
6407 encoding = Tcl_GetEncoding(interp, newValue);
6408 if (encoding == NULL) {
6409 return TCL_ERROR;
6410 }
6411 }
6412 /*
6413 * When the channel has an escape sequence driven encoding such as
6414 * iso2022, the terminated escape sequence must write to the buffer.
6415 */
6416 if ((statePtr->encoding != NULL) && (statePtr->curOutPtr != NULL)
6417 && (CheckChannelErrors(statePtr, TCL_WRITABLE) == 0)) {
6418 statePtr->outputEncodingFlags |= TCL_ENCODING_END;
6419 WriteChars(chanPtr, "", 0);
6420 }
6421 Tcl_FreeEncoding(statePtr->encoding);
6422 statePtr->encoding = encoding;
6423 statePtr->inputEncodingState = NULL;
6424 statePtr->inputEncodingFlags = TCL_ENCODING_START;
6425 statePtr->outputEncodingState = NULL;
6426 statePtr->outputEncodingFlags = TCL_ENCODING_START;
6427 statePtr->flags &= ~CHANNEL_NEED_MORE_DATA;
6428 UpdateInterest(chanPtr);
6429 } else if ((len > 2) && (optionName[1] == 'e') &&
6430 (strncmp(optionName, "-eofchar", len) == 0)) {
6431 if (Tcl_SplitList(interp, newValue, &argc, &argv) == TCL_ERROR) {
6432 return TCL_ERROR;
6433 }
6434 if (argc == 0) {
6435 statePtr->inEofChar = 0;
6436 statePtr->outEofChar = 0;
6437 } else if (argc == 1) {
6438 if (statePtr->flags & TCL_WRITABLE) {
6439 statePtr->outEofChar = (int) argv[0][0];
6440 }
6441 if (statePtr->flags & TCL_READABLE) {
6442 statePtr->inEofChar = (int) argv[0][0];
6443 }
6444 } else if (argc != 2) {
6445 if (interp) {
6446 Tcl_AppendResult(interp,
6447 "bad value for -eofchar: should be a list of zero,",
6448 " one, or two elements", (char *) NULL);
6449 }
6450 ckfree((char *) argv);
6451 return TCL_ERROR;
6452 } else {
6453 if (statePtr->flags & TCL_READABLE) {
6454 statePtr->inEofChar = (int) argv[0][0];
6455 }
6456 if (statePtr->flags & TCL_WRITABLE) {
6457 statePtr->outEofChar = (int) argv[1][0];
6458 }
6459 }
6460 if (argv != NULL) {
6461 ckfree((char *) argv);
6462 }
6463 return TCL_OK;
6464 } else if ((len > 1) && (optionName[1] == 't') &&
6465 (strncmp(optionName, "-translation", len) == 0)) {
6466 CONST char *readMode, *writeMode;
6467
6468 if (Tcl_SplitList(interp, newValue, &argc, &argv) == TCL_ERROR) {
6469 return TCL_ERROR;
6470 }
6471
6472 if (argc == 1) {
6473 readMode = (statePtr->flags & TCL_READABLE) ? argv[0] : NULL;
6474 writeMode = (statePtr->flags & TCL_WRITABLE) ? argv[0] : NULL;
6475 } else if (argc == 2) {
6476 readMode = (statePtr->flags & TCL_READABLE) ? argv[0] : NULL;
6477 writeMode = (statePtr->flags & TCL_WRITABLE) ? argv[1] : NULL;
6478 } else {
6479 if (interp) {
6480 Tcl_AppendResult(interp,
6481 "bad value for -translation: must be a one or two",
6482 " element list", (char *) NULL);
6483 }
6484 ckfree((char *) argv);
6485 return TCL_ERROR;
6486 }
6487
6488 if (readMode) {
6489 TclEolTranslation translation;
6490 if (*readMode == '\0') {
6491 translation = statePtr->inputTranslation;
6492 } else if (strcmp(readMode, "auto") == 0) {
6493 translation = TCL_TRANSLATE_AUTO;
6494 } else if (strcmp(readMode, "binary") == 0) {
6495 translation = TCL_TRANSLATE_LF;
6496 statePtr->inEofChar = 0;
6497 Tcl_FreeEncoding(statePtr->encoding);
6498 statePtr->encoding = NULL;
6499 } else if (strcmp(readMode, "lf") == 0) {
6500 translation = TCL_TRANSLATE_LF;
6501 } else if (strcmp(readMode, "cr") == 0) {
6502 translation = TCL_TRANSLATE_CR;
6503 } else if (strcmp(readMode, "crlf") == 0) {
6504 translation = TCL_TRANSLATE_CRLF;
6505 } else if (strcmp(readMode, "platform") == 0) {
6506 translation = TCL_PLATFORM_TRANSLATION;
6507 } else {
6508 if (interp) {
6509 Tcl_AppendResult(interp,
6510 "bad value for -translation: ",
6511 "must be one of auto, binary, cr, lf, crlf,",
6512 " or platform", (char *) NULL);
6513 }
6514 ckfree((char *) argv);
6515 return TCL_ERROR;
6516 }
6517
6518 /*
6519 * Reset the EOL flags since we need to look at any buffered
6520 * data to see if the new translation mode allows us to
6521 * complete the line.
6522 */
6523
6524 if (translation != statePtr->inputTranslation) {
6525 statePtr->inputTranslation = translation;
6526 statePtr->flags &= ~(INPUT_SAW_CR);
6527 statePtr->flags &= ~(CHANNEL_NEED_MORE_DATA);
6528 UpdateInterest(chanPtr);
6529 }
6530 }
6531 if (writeMode) {
6532 if (*writeMode == '\0') {
6533 /* Do nothing. */
6534 } else if (strcmp(writeMode, "auto") == 0) {
6535 /*
6536 * This is a hack to get TCP sockets to produce output
6537 * in CRLF mode if they are being set into AUTO mode.
6538 * A better solution for achieving this effect will be
6539 * coded later.
6540 */
6541
6542 if (strcmp(Tcl_ChannelName(chanPtr->typePtr), "tcp") == 0) {
6543 statePtr->outputTranslation = TCL_TRANSLATE_CRLF;
6544 } else {
6545 statePtr->outputTranslation = TCL_PLATFORM_TRANSLATION;
6546 }
6547 } else if (strcmp(writeMode, "binary") == 0) {
6548 statePtr->outEofChar = 0;
6549 statePtr->outputTranslation = TCL_TRANSLATE_LF;
6550 Tcl_FreeEncoding(statePtr->encoding);
6551 statePtr->encoding = NULL;
6552 } else if (strcmp(writeMode, "lf") == 0) {
6553 statePtr->outputTranslation = TCL_TRANSLATE_LF;
6554 } else if (strcmp(writeMode, "cr") == 0) {
6555 statePtr->outputTranslation = TCL_TRANSLATE_CR;
6556 } else if (strcmp(writeMode, "crlf") == 0) {
6557 statePtr->outputTranslation = TCL_TRANSLATE_CRLF;
6558 } else if (strcmp(writeMode, "platform") == 0) {
6559 statePtr->outputTranslation = TCL_PLATFORM_TRANSLATION;
6560 } else {
6561 if (interp) {
6562 Tcl_AppendResult(interp,
6563 "bad value for -translation: ",
6564 "must be one of auto, binary, cr, lf, crlf,",
6565 " or platform", (char *) NULL);
6566 }
6567 ckfree((char *) argv);
6568 return TCL_ERROR;
6569 }
6570 }
6571 ckfree((char *) argv);
6572 return TCL_OK;
6573 } else if (chanPtr->typePtr->setOptionProc != NULL) {
6574 return (*chanPtr->typePtr->setOptionProc)(chanPtr->instanceData,
6575 interp, optionName, newValue);
6576 } else {
6577 return Tcl_BadChannelOption(interp, optionName, (char *) NULL);
6578 }
6579
6580 /*
6581 * If bufsize changes, need to get rid of old utility buffer.
6582 */
6583
6584 if (statePtr->saveInBufPtr != NULL) {
6585 RecycleBuffer(statePtr, statePtr->saveInBufPtr, 1);
6586 statePtr->saveInBufPtr = NULL;
6587 }
6588 if (statePtr->inQueueHead != NULL) {
6589 if ((statePtr->inQueueHead->nextPtr == NULL)
6590 && (statePtr->inQueueHead->nextAdded ==
6591 statePtr->inQueueHead->nextRemoved)) {
6592 RecycleBuffer(statePtr, statePtr->inQueueHead, 1);
6593 statePtr->inQueueHead = NULL;
6594 statePtr->inQueueTail = NULL;
6595 }
6596 }
6597
6598 /*
6599 * If encoding or bufsize changes, need to update output staging buffer.
6600 */
6601
6602 if (statePtr->outputStage != NULL) {
6603 ckfree((char *) statePtr->outputStage);
6604 statePtr->outputStage = NULL;
6605 }
6606 if ((statePtr->encoding != NULL) && (statePtr->flags & TCL_WRITABLE)) {
6607 statePtr->outputStage = (char *)
6608 ckalloc((unsigned) (statePtr->bufSize + 2));
6609 }
6610 return TCL_OK;
6611 }
6612
6613 /*
6614 *----------------------------------------------------------------------
6615 *
6616 * CleanupChannelHandlers --
6617 *
6618 * Removes channel handlers that refer to the supplied interpreter,
6619 * so that if the actual channel is not closed now, these handlers
6620 * will not run on subsequent events on the channel. This would be
6621 * erroneous, because the interpreter no longer has a reference to
6622 * this channel.
6623 *
6624 * Results:
6625 * None.
6626 *
6627 * Side effects:
6628 * Removes channel handlers.
6629 *
6630 *----------------------------------------------------------------------
6631 */
6632
6633 static void
6634 CleanupChannelHandlers(interp, chanPtr)
6635 Tcl_Interp *interp;
6636 Channel *chanPtr;
6637 {
6638 ChannelState *statePtr = chanPtr->state; /* state info for channel */
6639 EventScriptRecord *sPtr, *prevPtr, *nextPtr;
6640
6641 /*
6642 * Remove fileevent records on this channel that refer to the
6643 * given interpreter.
6644 */
6645
6646 for (sPtr = statePtr->scriptRecordPtr,
6647 prevPtr = (EventScriptRecord *) NULL;
6648 sPtr != (EventScriptRecord *) NULL;
6649 sPtr = nextPtr) {
6650 nextPtr = sPtr->nextPtr;
6651 if (sPtr->interp == interp) {
6652 if (prevPtr == (EventScriptRecord *) NULL) {
6653 statePtr->scriptRecordPtr = nextPtr;
6654 } else {
6655 prevPtr->nextPtr = nextPtr;
6656 }
6657
6658 Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
6659 TclChannelEventScriptInvoker, (ClientData) sPtr);
6660
6661 Tcl_DecrRefCount(sPtr->scriptPtr);
6662 ckfree((char *) sPtr);
6663 } else {
6664 prevPtr = sPtr;
6665 }
6666 }
6667 }
6668
6669 /*
6670 *----------------------------------------------------------------------
6671 *
6672 * Tcl_NotifyChannel --
6673 *
6674 * This procedure is called by a channel driver when a driver
6675 * detects an event on a channel. This procedure is responsible
6676 * for actually handling the event by invoking any channel
6677 * handler callbacks.
6678 *
6679 * Results:
6680 * None.
6681 *
6682 * Side effects:
6683 * Whatever the channel handler callback procedure does.
6684 *
6685 *----------------------------------------------------------------------
6686 */
6687
6688 void
6689 Tcl_NotifyChannel(channel, mask)
6690 Tcl_Channel channel; /* Channel that detected an event. */
6691 int mask; /* OR'ed combination of TCL_READABLE,
6692 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
6693 * which events were detected. */
6694 {
6695 Channel *chanPtr = (Channel *) channel;
6696 ChannelState *statePtr = chanPtr->state; /* state info for channel */
6697 ChannelHandler *chPtr;
6698 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
6699 NextChannelHandler nh;
6700 Channel* upChanPtr;
6701 Tcl_ChannelType* upTypePtr;
6702
6703 /*
6704 * In contrast to the other API functions this procedure walks towards
6705 * the top of a stack and not down from it.
6706 *
6707 * The channel calling this procedure is the one who generated the event,
6708 * and thus does not take part in handling it. IOW, its HandlerProc is
6709 * not called, instead we begin with the channel above it.
6710 *
6711 * This behaviour also allows the transformation channels to
6712 * generate their own events and pass them upward.
6713 */
6714
6715 while (mask && (chanPtr->upChanPtr != ((Channel*) NULL))) {
6716 Tcl_DriverHandlerProc* upHandlerProc;
6717
6718 upChanPtr = chanPtr->upChanPtr;
6719 upTypePtr = upChanPtr->typePtr;
6720 upHandlerProc = Tcl_ChannelHandlerProc(upTypePtr);
6721 if (upHandlerProc != NULL) {
6722 mask = (*upHandlerProc) (upChanPtr->instanceData, mask);
6723 }
6724
6725 /* ELSE:
6726 * Ignore transformations which are unable to handle the event
6727 * coming from below. Assume that they don't change the mask and
6728 * pass it on.
6729 */
6730
6731 chanPtr = upChanPtr;
6732 }
6733
6734 channel = (Tcl_Channel) chanPtr;
6735
6736 /*
6737 * Here we have either reached the top of the stack or the mask is
6738 * empty. We break out of the procedure if it is the latter.
6739 */
6740
6741 if (!mask) {
6742 return;
6743 }
6744
6745 /*
6746 * We are now above the topmost channel in a stack and have events
6747 * left. Now call the channel handlers as usual.
6748 *
6749 * Preserve the channel struct in case the script closes it.
6750 */
6751
6752 Tcl_Preserve((ClientData) channel);
6753 Tcl_Preserve((ClientData) statePtr);
6754
6755 /*
6756 * If we are flushing in the background, be sure to call FlushChannel
6757 * for writable events. Note that we have to discard the writable
6758 * event so we don't call any write handlers before the flush is
6759 * complete.
6760 */
6761
6762 if ((statePtr->flags & BG_FLUSH_SCHEDULED) && (mask & TCL_WRITABLE)) {
6763 FlushChannel(NULL, chanPtr, 1);
6764 mask &= ~TCL_WRITABLE;
6765 }
6766
6767 /*
6768 * Add this invocation to the list of recursive invocations of
6769 * ChannelHandlerEventProc.
6770 */
6771
6772 nh.nextHandlerPtr = (ChannelHandler *) NULL;
6773 nh.nestedHandlerPtr = tsdPtr->nestedHandlerPtr;
6774 tsdPtr->nestedHandlerPtr = &nh;
6775
6776 for (chPtr = statePtr->chPtr; chPtr != (ChannelHandler *) NULL; ) {
6777 /*
6778 * If this channel handler is interested in any of the events that
6779 * have occurred on the channel, invoke its procedure.
6780 */
6781
6782 if ((chPtr->mask & mask) != 0) {
6783 nh.nextHandlerPtr = chPtr->nextPtr;
6784 (*(chPtr->proc))(chPtr->clientData, mask);
6785 chPtr = nh.nextHandlerPtr;
6786 } else {
6787 chPtr = chPtr->nextPtr;
6788 }
6789 }
6790
6791 /*
6792 * Update the notifier interest, since it may have changed after
6793 * invoking event handlers. Skip that if the channel was deleted
6794 * in the call to the channel handler.
6795 */
6796
6797 if (chanPtr->typePtr != NULL) {
6798 UpdateInterest(chanPtr);
6799 }
6800
6801 Tcl_Release((ClientData) statePtr);
6802 Tcl_Release((ClientData) channel);
6803
6804 tsdPtr->nestedHandlerPtr = nh.nestedHandlerPtr;
6805 }
6806
6807 /*
6808 *----------------------------------------------------------------------
6809 *
6810 * UpdateInterest --
6811 *
6812 * Arrange for the notifier to call us back at appropriate times
6813 * based on the current state of the channel.
6814 *
6815 * Results:
6816 * None.
6817 *
6818 * Side effects:
6819 * May schedule a timer or driver handler.
6820 *
6821 *----------------------------------------------------------------------
6822 */
6823
6824 static void
6825 UpdateInterest(chanPtr)
6826 Channel *chanPtr; /* Channel to update. */
6827 {
6828 ChannelState *statePtr = chanPtr->state; /* state info for channel */
6829 int mask = statePtr->interestMask;
6830
6831 /*
6832 * If there are flushed buffers waiting to be written, then
6833 * we need to watch for the channel to become writable.
6834 */
6835
6836 if (statePtr->flags & BG_FLUSH_SCHEDULED) {
6837 mask |= TCL_WRITABLE;
6838 }
6839
6840 /*
6841 * If there is data in the input queue, and we aren't waiting for more
6842 * data, then we need to schedule a timer so we don't block in the
6843 * notifier. Also, cancel the read interest so we don't get duplicate
6844 * events.
6845 */
6846
6847 if (mask & TCL_READABLE) {
6848 if (!(statePtr->flags & CHANNEL_NEED_MORE_DATA)
6849 && (statePtr->inQueueHead != (ChannelBuffer *) NULL)
6850 && (statePtr->inQueueHead->nextRemoved <
6851 statePtr->inQueueHead->nextAdded)) {
6852 mask &= ~TCL_READABLE;
6853
6854 /*
6855 * Andreas Kupries, April 11, 2003
6856 *
6857 * Some operating systems (Solaris 2.6 and higher (but not
6858 * Solaris 2.5, go figure)) generate READABLE and
6859 * EXCEPTION events when select()'ing [*] on a plain file,
6860 * even if EOF was not yet reached. This is a problem in
6861 * the following situation:
6862 *
6863 * - An extension asks to get both READABLE and EXCEPTION
6864 * events.
6865 * - It reads data into a buffer smaller than the buffer
6866 * used by Tcl itself.
6867 * - It does not process all events in the event queue, but
6868 * only only one, at least in some situations.
6869 *
6870 * In that case we can get into a situation where
6871 *
6872 * - Tcl drops READABLE here, because it has data in its own
6873 * buffers waiting to be read by the extension.
6874 * - A READABLE event is syntesized via timer.
6875 * - The OS still reports the EXCEPTION condition on the file.
6876 * - And the extension gets the EXCPTION event first, and
6877 * handles this as EOF.
6878 *
6879 * End result ==> Premature end of reading from a file.
6880 *
6881 * The concrete example is 'Expect', and its [expect]
6882 * command (and at the C-level, deep in the bowels of
6883 * Expect, 'exp_get_next_event'. See marker 'SunOS' for
6884 * commentary in that function too).
6885 *
6886 * [*] As the Tcl notifier does. See also for marker
6887 * 'SunOS' in file 'exp_event.c' of Expect.
6888 *
6889 * Our solution here is to drop the interest in the
6890 * EXCEPTION events too. This compiles on all platforms,
6891 * and also passes the testsuite on all of them.
6892 */
6893
6894 mask &= ~TCL_EXCEPTION;
6895
6896 if (!statePtr->timer) {
6897 statePtr->timer = Tcl_CreateTimerHandler(0, ChannelTimerProc,
6898 (ClientData) chanPtr);
6899 }
6900 }
6901 }
6902 (chanPtr->typePtr->watchProc)(chanPtr->instanceData, mask);
6903 }
6904
6905 /*
6906 *----------------------------------------------------------------------
6907 *
6908 * ChannelTimerProc --
6909 *
6910 * Timer handler scheduled by UpdateInterest to monitor the
6911 * channel buffers until they are empty.
6912 *
6913 * Results:
6914 * None.
6915 *
6916 * Side effects:
6917 * May invoke channel handlers.
6918 *
6919 *----------------------------------------------------------------------
6920 */
6921
6922 static void
6923 ChannelTimerProc(clientData)
6924 ClientData clientData;
6925 {
6926 Channel *chanPtr = (Channel *) clientData;
6927 ChannelState *statePtr = chanPtr->state; /* state info for channel */
6928
6929 if (!(statePtr->flags & CHANNEL_NEED_MORE_DATA)
6930 && (statePtr->interestMask & TCL_READABLE)
6931 && (statePtr->inQueueHead != (ChannelBuffer *) NULL)
6932 && (statePtr->inQueueHead->nextRemoved <
6933 statePtr->inQueueHead->nextAdded)) {
6934 /*
6935 * Restart the timer in case a channel handler reenters the
6936 * event loop before UpdateInterest gets called by Tcl_NotifyChannel.
6937 */
6938
6939 statePtr->timer = Tcl_CreateTimerHandler(0, ChannelTimerProc,
6940 (ClientData) chanPtr);
6941
6942 /* Set the TIMER flag to notify the higher levels that the
6943 * driver might have no data for us. We do this only if we are
6944 * in non-blocking mode and the driver has no BlockModeProc
6945 * because only then we really don't know if the driver will
6946 * block or not. A similar test is done in "PeekAhead".
6947 */
6948
6949 if ((statePtr->flags & CHANNEL_NONBLOCKING) &&
6950 (Tcl_ChannelBlockModeProc(chanPtr->typePtr) == NULL)) {
6951 statePtr->flags |= CHANNEL_TIMER_FEV;
6952 }
6953 Tcl_Preserve((ClientData) statePtr);
6954 Tcl_NotifyChannel((Tcl_Channel)chanPtr, TCL_READABLE);
6955
6956 statePtr->flags &= ~CHANNEL_TIMER_FEV;
6957 Tcl_Release((ClientData) statePtr);
6958 } else {
6959 statePtr->timer = NULL;
6960 UpdateInterest(chanPtr);
6961 }
6962 }
6963
6964 /*
6965 *----------------------------------------------------------------------
6966 *
6967 * Tcl_CreateChannelHandler --
6968 *
6969 * Arrange for a given procedure to be invoked whenever the
6970 * channel indicated by the chanPtr arg becomes readable or
6971 * writable.
6972 *
6973 * Results:
6974 * None.
6975 *
6976 * Side effects:
6977 * From now on, whenever the I/O channel given by chanPtr becomes
6978 * ready in the way indicated by mask, proc will be invoked.
6979 * See the manual entry for details on the calling sequence
6980 * to proc. If there is already an event handler for chan, proc
6981 * and clientData, then the mask will be updated.
6982 *
6983 *----------------------------------------------------------------------
6984 */
6985
6986 void
6987 Tcl_CreateChannelHandler(chan, mask, proc, clientData)
6988 Tcl_Channel chan; /* The channel to create the handler for. */
6989 int mask; /* OR'ed combination of TCL_READABLE,
6990 * TCL_WRITABLE, and TCL_EXCEPTION:
6991 * indicates conditions under which
6992 * proc should be called. Use 0 to
6993 * disable a registered handler. */
6994 Tcl_ChannelProc *proc; /* Procedure to call for each
6995 * selected event. */
6996 ClientData clientData; /* Arbitrary data to pass to proc. */
6997 {
6998 ChannelHandler *chPtr;
6999 Channel *chanPtr = (Channel *) chan;
7000 ChannelState *statePtr = chanPtr->state; /* state info for channel */
7001
7002 /*
7003 * Check whether this channel handler is not already registered. If
7004 * it is not, create a new record, else reuse existing record (smash
7005 * current values).
7006 */
7007
7008 for (chPtr = statePtr->chPtr;
7009 chPtr != (ChannelHandler *) NULL;
7010 chPtr = chPtr->nextPtr) {
7011 if ((chPtr->chanPtr == chanPtr) && (chPtr->proc == proc) &&
7012 (chPtr->clientData == clientData)) {
7013 break;
7014 }
7015 }
7016 if (chPtr == (ChannelHandler *) NULL) {
7017 chPtr = (ChannelHandler *) ckalloc((unsigned) sizeof(ChannelHandler));
7018 chPtr->mask = 0;
7019 chPtr->proc = proc;
7020 chPtr->clientData = clientData;
7021 chPtr->chanPtr = chanPtr;
7022 chPtr->nextPtr = statePtr->chPtr;
7023 statePtr->chPtr = chPtr;
7024 }
7025
7026 /*
7027 * The remainder of the initialization below is done regardless of
7028 * whether or not this is a new record or a modification of an old
7029 * one.
7030 */
7031
7032 chPtr->mask = mask;
7033
7034 /*
7035 * Recompute the interest mask for the channel - this call may actually
7036 * be disabling an existing handler.
7037 */
7038
7039 statePtr->interestMask = 0;
7040 for (chPtr = statePtr->chPtr;
7041 chPtr != (ChannelHandler *) NULL;
7042 chPtr = chPtr->nextPtr) {
7043 statePtr->interestMask |= chPtr->mask;
7044 }
7045
7046 UpdateInterest(statePtr->topChanPtr);
7047 }
7048
7049 /*
7050 *----------------------------------------------------------------------
7051 *
7052 * Tcl_DeleteChannelHandler --
7053 *
7054 * Cancel a previously arranged callback arrangement for an IO
7055 * channel.
7056 *
7057 * Results:
7058 * None.
7059 *
7060 * Side effects:
7061 * If a callback was previously registered for this chan, proc and
7062 * clientData , it is removed and the callback will no longer be called
7063 * when the channel becomes ready for IO.
7064 *
7065 *----------------------------------------------------------------------
7066 */
7067
7068 void
7069 Tcl_DeleteChannelHandler(chan, proc, clientData)
7070 Tcl_Channel chan; /* The channel for which to remove the
7071 * callback. */
7072 Tcl_ChannelProc *proc; /* The procedure in the callback to delete. */
7073 ClientData clientData; /* The client data in the callback
7074 * to delete. */
7075
7076 {
7077 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
7078 ChannelHandler *chPtr, *prevChPtr;
7079 Channel *chanPtr = (Channel *) chan;
7080 ChannelState *statePtr = chanPtr->state; /* state info for channel */
7081 NextChannelHandler *nhPtr;
7082
7083 /*
7084 * Find the entry and the previous one in the list.
7085 */
7086
7087 for (prevChPtr = (ChannelHandler *) NULL, chPtr = statePtr->chPtr;
7088 chPtr != (ChannelHandler *) NULL;
7089 chPtr = chPtr->nextPtr) {
7090 if ((chPtr->chanPtr == chanPtr) && (chPtr->clientData == clientData)
7091 && (chPtr->proc == proc)) {
7092 break;
7093 }
7094 prevChPtr = chPtr;
7095 }
7096
7097 /*
7098 * If not found, return without doing anything.
7099 */
7100
7101 if (chPtr == (ChannelHandler *) NULL) {
7102 return;
7103 }
7104
7105 /*
7106 * If ChannelHandlerEventProc is about to process this handler, tell it to
7107 * process the next one instead - we are going to delete *this* one.
7108 */
7109
7110 for (nhPtr = tsdPtr->nestedHandlerPtr;
7111 nhPtr != (NextChannelHandler *) NULL;
7112 nhPtr = nhPtr->nestedHandlerPtr) {
7113 if (nhPtr->nextHandlerPtr == chPtr) {
7114 nhPtr->nextHandlerPtr = chPtr->nextPtr;
7115 }
7116 }
7117
7118 /*
7119 * Splice it out of the list of channel handlers.
7120 */
7121
7122 if (prevChPtr == (ChannelHandler *) NULL) {
7123 statePtr->chPtr = chPtr->nextPtr;
7124 } else {
7125 prevChPtr->nextPtr = chPtr->nextPtr;
7126 }
7127 ckfree((char *) chPtr);
7128
7129 /*
7130 * Recompute the interest list for the channel, so that infinite loops
7131 * will not result if Tcl_DeleteChannelHandler is called inside an
7132 * event.
7133 */
7134
7135 statePtr->interestMask = 0;
7136 for (chPtr = statePtr->chPtr;
7137 chPtr != (ChannelHandler *) NULL;
7138 chPtr = chPtr->nextPtr) {
7139 statePtr->interestMask |= chPtr->mask;
7140 }
7141
7142 UpdateInterest(statePtr->topChanPtr);
7143 }
7144
7145 /*
7146 *----------------------------------------------------------------------
7147 *
7148 * DeleteScriptRecord --
7149 *
7150 * Delete a script record for this combination of channel, interp
7151 * and mask.
7152 *
7153 * Results:
7154 * None.
7155 *
7156 * Side effects:
7157 * Deletes a script record and cancels a channel event handler.
7158 *
7159 *----------------------------------------------------------------------
7160 */
7161
7162 static void
7163 DeleteScriptRecord(interp, chanPtr, mask)
7164 Tcl_Interp *interp; /* Interpreter in which script was to be
7165 * executed. */
7166 Channel *chanPtr; /* The channel for which to delete the
7167 * script record (if any). */
7168 int mask; /* Events in mask must exactly match mask
7169 * of script to delete. */
7170 {
7171 ChannelState *statePtr = chanPtr->state; /* state info for channel */
7172 EventScriptRecord *esPtr, *prevEsPtr;
7173
7174 for (esPtr = statePtr->scriptRecordPtr,
7175 prevEsPtr = (EventScriptRecord *) NULL;
7176 esPtr != (EventScriptRecord *) NULL;
7177 prevEsPtr = esPtr, esPtr = esPtr->nextPtr) {
7178 if ((esPtr->interp == interp) && (esPtr->mask == mask)) {
7179 if (esPtr == statePtr->scriptRecordPtr) {
7180 statePtr->scriptRecordPtr = esPtr->nextPtr;
7181 } else {
7182 prevEsPtr->nextPtr = esPtr->nextPtr;
7183 }
7184
7185 Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
7186 TclChannelEventScriptInvoker, (ClientData) esPtr);
7187
7188 Tcl_DecrRefCount(esPtr->scriptPtr);
7189 ckfree((char *) esPtr);
7190
7191 break;
7192 }
7193 }
7194 }
7195
7196 /*
7197 *----------------------------------------------------------------------
7198 *
7199 * CreateScriptRecord --
7200 *
7201 * Creates a record to store a script to be executed when a specific
7202 * event fires on a specific channel.
7203 *
7204 * Results:
7205 * None.
7206 *
7207 * Side effects:
7208 * Causes the script to be stored for later execution.
7209 *
7210 *----------------------------------------------------------------------
7211 */
7212
7213 static void
7214 CreateScriptRecord(interp, chanPtr, mask, scriptPtr)
7215 Tcl_Interp *interp; /* Interpreter in which to execute
7216 * the stored script. */
7217 Channel *chanPtr; /* Channel for which script is to
7218 * be stored. */
7219 int mask; /* Set of events for which script
7220 * will be invoked. */
7221 Tcl_Obj *scriptPtr; /* Pointer to script object. */
7222 {
7223 ChannelState *statePtr = chanPtr->state; /* state info for channel */
7224 EventScriptRecord *esPtr;
7225
7226 for (esPtr = statePtr->scriptRecordPtr;
7227 esPtr != (EventScriptRecord *) NULL;
7228 esPtr = esPtr->nextPtr) {
7229 if ((esPtr->interp == interp) && (esPtr->mask == mask)) {
7230 Tcl_DecrRefCount(esPtr->scriptPtr);
7231 esPtr->scriptPtr = (Tcl_Obj *) NULL;
7232 break;
7233 }
7234 }
7235 if (esPtr == (EventScriptRecord *) NULL) {
7236 esPtr = (EventScriptRecord *) ckalloc((unsigned)
7237 sizeof(EventScriptRecord));
7238 Tcl_CreateChannelHandler((Tcl_Channel) chanPtr, mask,
7239 TclChannelEventScriptInvoker, (ClientData) esPtr);
7240 esPtr->nextPtr = statePtr->scriptRecordPtr;
7241 statePtr->scriptRecordPtr = esPtr;
7242 }
7243 esPtr->chanPtr = chanPtr;
7244 esPtr->interp = interp;
7245 esPtr->mask = mask;
7246 Tcl_IncrRefCount(scriptPtr);
7247 esPtr->scriptPtr = scriptPtr;
7248 }
7249
7250 /*
7251 *----------------------------------------------------------------------
7252 *
7253 * TclChannelEventScriptInvoker --
7254 *
7255 * Invokes a script scheduled by "fileevent" for when the channel
7256 * becomes ready for IO. This function is invoked by the channel
7257 * handler which was created by the Tcl "fileevent" command.
7258 *
7259 * Results:
7260 * None.
7261 *
7262 * Side effects:
7263 * Whatever the script does.
7264 *
7265 *----------------------------------------------------------------------
7266 */
7267
7268 void
7269 TclChannelEventScriptInvoker(clientData, mask)
7270 ClientData clientData; /* The script+interp record. */
7271 int mask; /* Not used. */
7272 {
7273 Tcl_Interp *interp; /* Interpreter in which to eval the script. */
7274 Channel *chanPtr; /* The channel for which this handler is
7275 * registered. */
7276 EventScriptRecord *esPtr; /* The event script + interpreter to eval it
7277 * in. */
7278 int result; /* Result of call to eval script. */
7279
7280 esPtr = (EventScriptRecord *) clientData;
7281 chanPtr = esPtr->chanPtr;
7282 mask = esPtr->mask;
7283 interp = esPtr->interp;
7284
7285 /*
7286 * We must preserve the interpreter so we can report errors on it
7287 * later. Note that we do not need to preserve the channel because
7288 * that is done by Tcl_NotifyChannel before calling channel handlers.
7289 */
7290
7291 Tcl_Preserve((ClientData) interp);
7292 result = Tcl_EvalObjEx(interp, esPtr->scriptPtr, TCL_EVAL_GLOBAL);
7293
7294 /*
7295 * On error, cause a background error and remove the channel handler
7296 * and the script record.
7297 *
7298 * NOTE: Must delete channel handler before causing the background error
7299 * because the background error may want to reinstall the handler.
7300 */
7301
7302 if (result != TCL_OK) {
7303 if (chanPtr->typePtr != NULL) {
7304 DeleteScriptRecord(interp, chanPtr, mask);
7305 }
7306 Tcl_BackgroundError(interp);
7307 }
7308 Tcl_Release((ClientData) interp);
7309 }
7310
7311 /*
7312 *----------------------------------------------------------------------
7313 *
7314 * Tcl_FileEventObjCmd --
7315 *
7316 * This procedure implements the "fileevent" Tcl command. See the
7317 * user documentation for details on what it does. This command is
7318 * based on the Tk command "fileevent" which in turn is based on work
7319 * contributed by Mark Diekhans.
7320 *
7321 * Results:
7322 * A standard Tcl result.
7323 *
7324 * Side effects:
7325 * May create a channel handler for the specified channel.
7326 *
7327 *----------------------------------------------------------------------
7328 */
7329
7330 /* ARGSUSED */
7331 int
7332 Tcl_FileEventObjCmd(clientData, interp, objc, objv)
7333 ClientData clientData; /* Not used. */
7334 Tcl_Interp *interp; /* Interpreter in which the channel
7335 * for which to create the handler
7336 * is found. */
7337 int objc; /* Number of arguments. */
7338 Tcl_Obj *CONST objv[]; /* Argument objects. */
7339 {
7340 Channel *chanPtr; /* The channel to create
7341 * the handler for. */
7342 ChannelState *statePtr; /* state info for channel */
7343 Tcl_Channel chan; /* The opaque type for the channel. */
7344 char *chanName;
7345 int modeIndex; /* Index of mode argument. */
7346 int mask;
7347 static CONST char *modeOptions[] = {"readable", "writable", NULL};
7348 static int maskArray[] = {TCL_READABLE, TCL_WRITABLE};
7349
7350 if ((objc != 3) && (objc != 4)) {
7351 Tcl_WrongNumArgs(interp, 1, objv, "channelId event ?script?");
7352 return TCL_ERROR;
7353 }
7354 if (Tcl_GetIndexFromObj(interp, objv[2], modeOptions, "event name", 0,
7355 &modeIndex) != TCL_OK) {
7356 return TCL_ERROR;
7357 }
7358 mask = maskArray[modeIndex];
7359
7360 chanName = Tcl_GetString(objv[1]);
7361 chan = Tcl_GetChannel(interp, chanName, NULL);
7362 if (chan == (Tcl_Channel) NULL) {
7363 return TCL_ERROR;
7364 }
7365 chanPtr = (Channel *) chan;
7366 statePtr = chanPtr->state;
7367 if ((statePtr->flags & mask) == 0) {
7368 Tcl_AppendResult(interp, "channel is not ",
7369 (mask == TCL_READABLE) ? "readable" : "writable",
7370 (char *) NULL);
7371 return TCL_ERROR;
7372 }
7373
7374 /*
7375 * If we are supposed to return the script, do so.
7376 */
7377
7378 if (objc == 3) {
7379 EventScriptRecord *esPtr;
7380 for (esPtr = statePtr->scriptRecordPtr;
7381 esPtr != (EventScriptRecord *) NULL;
7382 esPtr = esPtr->nextPtr) {
7383 if ((esPtr->interp == interp) && (esPtr->mask == mask)) {
7384 Tcl_SetObjResult(interp, esPtr->scriptPtr);
7385 break;
7386 }
7387 }
7388 return TCL_OK;
7389 }
7390
7391 /*
7392 * If we are supposed to delete a stored script, do so.
7393 */
7394
7395 if (*(Tcl_GetString(objv[3])) == '\0') {
7396 DeleteScriptRecord(interp, chanPtr, mask);
7397 return TCL_OK;
7398 }
7399
7400 /*
7401 * Make the script record that will link between the event and the
7402 * script to invoke. This also creates a channel event handler which
7403 * will evaluate the script in the supplied interpreter.
7404 */
7405
7406 CreateScriptRecord(interp, chanPtr, mask, objv[3]);
7407
7408 return TCL_OK;
7409 }
7410
7411 /*
7412 *----------------------------------------------------------------------
7413 *
7414 * TclCopyChannel --
7415 *
7416 * This routine copies data from one channel to another, either
7417 * synchronously or asynchronously. If a command script is
7418 * supplied, the operation runs in the background. The script
7419 * is invoked when the copy completes. Otherwise the function
7420 * waits until the copy is completed before returning.
7421 *
7422 * Results:
7423 * A standard Tcl result.
7424 *
7425 * Side effects:
7426 * May schedule a background copy operation that causes both
7427 * channels to be marked busy.
7428 *
7429 *----------------------------------------------------------------------
7430 */
7431
7432 int
7433 TclCopyChannel(interp, inChan, outChan, toRead, cmdPtr)
7434 Tcl_Interp *interp; /* Current interpreter. */
7435 Tcl_Channel inChan; /* Channel to read from. */
7436 Tcl_Channel outChan; /* Channel to write to. */
7437 int toRead; /* Amount of data to copy, or -1 for all. */
7438 Tcl_Obj *cmdPtr; /* Pointer to script to execute or NULL. */
7439 {
7440 Channel *inPtr = (Channel *) inChan;
7441 Channel *outPtr = (Channel *) outChan;
7442 ChannelState *inStatePtr, *outStatePtr;
7443 int readFlags, writeFlags;
7444 CopyState *csPtr;
7445 int nonBlocking = (cmdPtr) ? CHANNEL_NONBLOCKING : 0;
7446
7447 inStatePtr = inPtr->state;
7448 outStatePtr = outPtr->state;
7449
7450 if (inStatePtr->csPtr) {
7451 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "channel \"",
7452 Tcl_GetChannelName(inChan), "\" is busy", NULL);
7453 return TCL_ERROR;
7454 }
7455 if (outStatePtr->csPtr) {
7456 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "channel \"",
7457 Tcl_GetChannelName(outChan), "\" is busy", NULL);
7458 return TCL_ERROR;
7459 }
7460
7461 readFlags = inStatePtr->flags;
7462 writeFlags = outStatePtr->flags;
7463
7464 /*
7465 * Set up the blocking mode appropriately. Background copies need
7466 * non-blocking channels. Foreground copies need blocking channels.
7467 * If there is an error, restore the old blocking mode.
7468 */
7469
7470 if (nonBlocking != (readFlags & CHANNEL_NONBLOCKING)) {
7471 if (SetBlockMode(interp, inPtr,
7472 nonBlocking ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING)
7473 != TCL_OK) {
7474 return TCL_ERROR;
7475 }
7476 }
7477 if (inPtr != outPtr) {
7478 if (nonBlocking != (writeFlags & CHANNEL_NONBLOCKING)) {
7479 if (SetBlockMode(NULL, outPtr,
7480 nonBlocking ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING)
7481 != TCL_OK) {
7482 if (nonBlocking != (readFlags & CHANNEL_NONBLOCKING)) {
7483 SetBlockMode(NULL, inPtr,
7484 (readFlags & CHANNEL_NONBLOCKING)
7485 ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING);
7486 return TCL_ERROR;
7487 }
7488 }
7489 }
7490 }
7491
7492 /*
7493 * Make sure the output side is unbuffered.
7494 */
7495
7496 outStatePtr->flags = (outStatePtr->flags & ~(CHANNEL_LINEBUFFERED))
7497 | CHANNEL_UNBUFFERED;
7498
7499 /*
7500 * Allocate a new CopyState to maintain info about the current copy in
7501 * progress. This structure will be deallocated when the copy is
7502 * completed.
7503 */
7504
7505 csPtr = (CopyState*) ckalloc(sizeof(CopyState) + inStatePtr->bufSize);
7506 csPtr->bufSize = inStatePtr->bufSize;
7507 csPtr->readPtr = inPtr;
7508 csPtr->writePtr = outPtr;
7509 csPtr->readFlags = readFlags;
7510 csPtr->writeFlags = writeFlags;
7511 csPtr->toRead = toRead;
7512 csPtr->total = 0;
7513 csPtr->interp = interp;
7514 if (cmdPtr) {
7515 Tcl_IncrRefCount(cmdPtr);
7516 }
7517 csPtr->cmdPtr = cmdPtr;
7518 inStatePtr->csPtr = csPtr;
7519 outStatePtr->csPtr = csPtr;
7520
7521 /*
7522 * Start copying data between the channels.
7523 */
7524
7525 return CopyData(csPtr, 0);
7526 }
7527
7528 /*
7529 *----------------------------------------------------------------------
7530 *
7531 * CopyData --
7532 *
7533 * This function implements the lowest level of the copying
7534 * mechanism for TclCopyChannel.
7535 *
7536 * Results:
7537 * Returns TCL_OK on success, else TCL_ERROR.
7538 *
7539 * Side effects:
7540 * Moves data between channels, may create channel handlers.
7541 *
7542 *----------------------------------------------------------------------
7543 */
7544
7545 static int
7546 CopyData(csPtr, mask)
7547 CopyState *csPtr; /* State of copy operation. */
7548 int mask; /* Current channel event flags. */
7549 {
7550 Tcl_Interp *interp;
7551 Tcl_Obj *cmdPtr, *errObj = NULL, *bufObj = NULL;
7552 Tcl_Channel inChan, outChan;
7553 ChannelState *inStatePtr, *outStatePtr;
7554 int result = TCL_OK, size, total, sizeb;
7555 char* buffer;
7556
7557 int inBinary, outBinary, sameEncoding; /* Encoding control */
7558 int underflow; /* input underflow */
7559
7560 inChan = (Tcl_Channel) csPtr->readPtr;
7561 outChan = (Tcl_Channel) csPtr->writePtr;
7562 inStatePtr = csPtr->readPtr->state;
7563 outStatePtr = csPtr->writePtr->state;
7564 interp = csPtr->interp;
7565 cmdPtr = csPtr->cmdPtr;
7566
7567 /*
7568 * Copy the data the slow way, using the translation mechanism.
7569 *
7570 * Note: We have make sure that we use the topmost channel in a stack
7571 * for the copying. The caller uses Tcl_GetChannel to access it, and
7572 * thus gets the bottom of the stack.
7573 */
7574
7575 inBinary = (inStatePtr->encoding == NULL);
7576 outBinary = (outStatePtr->encoding == NULL);
7577 sameEncoding = (inStatePtr->encoding == outStatePtr->encoding);
7578
7579 if (!(inBinary || sameEncoding)) {
7580 bufObj = Tcl_NewObj ();
7581 Tcl_IncrRefCount (bufObj);
7582 }
7583
7584 while (csPtr->toRead != 0) {
7585 /*
7586 * Check for unreported background errors.
7587 */
7588
7589 if (inStatePtr->unreportedError != 0) {
7590 Tcl_SetErrno(inStatePtr->unreportedError);
7591 inStatePtr->unreportedError = 0;
7592 goto readError;
7593 }
7594 if (outStatePtr->unreportedError != 0) {
7595 Tcl_SetErrno(outStatePtr->unreportedError);
7596 outStatePtr->unreportedError = 0;
7597 goto writeError;
7598 }
7599
7600 /*
7601 * Read up to bufSize bytes.
7602 */
7603
7604 if ((csPtr->toRead == -1) || (csPtr->toRead > csPtr->bufSize)) {
7605 sizeb = csPtr->bufSize;
7606 } else {
7607 sizeb = csPtr->toRead;
7608 }
7609
7610 if (inBinary || sameEncoding) {
7611 size = DoRead(inStatePtr->topChanPtr, csPtr->buffer, sizeb);
7612 } else {
7613 size = DoReadChars(inStatePtr->topChanPtr, bufObj, sizeb, 0 /* No append */);
7614 }
7615 underflow = (size >= 0) && (size < sizeb); /* input underflow */
7616
7617 if (size < 0) {
7618 readError:
7619 errObj = Tcl_NewObj();
7620 Tcl_AppendStringsToObj(errObj, "error reading \"",
7621 Tcl_GetChannelName(inChan), "\": ",
7622 Tcl_PosixError(interp), (char *) NULL);
7623 break;
7624 } else if (underflow) {
7625 /*
7626 * We had an underflow on the read side. If we are at EOF,
7627 * then the copying is done, otherwise set up a channel
7628 * handler to detect when the channel becomes readable again.
7629 */
7630
7631 if ((size == 0) && Tcl_Eof(inChan)) {
7632 break;
7633 }
7634 if (! Tcl_Eof(inChan) && !(mask & TCL_READABLE)) {
7635 if (mask & TCL_WRITABLE) {
7636 Tcl_DeleteChannelHandler(outChan, CopyEventProc,
7637 (ClientData) csPtr);
7638 }
7639 Tcl_CreateChannelHandler(inChan, TCL_READABLE,
7640 CopyEventProc, (ClientData) csPtr);
7641 }
7642 if (size == 0) {
7643 if (bufObj != (Tcl_Obj*) NULL) {
7644 Tcl_DecrRefCount (bufObj);
7645 bufObj = (Tcl_Obj*) NULL;
7646 }
7647 return TCL_OK;
7648 }
7649 }
7650
7651 /*
7652 * Now write the buffer out.
7653 */
7654
7655 if (inBinary || sameEncoding) {
7656 buffer = csPtr->buffer;
7657 sizeb = size;
7658 } else {
7659 buffer = Tcl_GetStringFromObj (bufObj, &sizeb);
7660 }
7661
7662 if (outBinary || sameEncoding) {
7663 sizeb = DoWrite(outStatePtr->topChanPtr, buffer, sizeb);
7664 } else {
7665 sizeb = DoWriteChars(outStatePtr->topChanPtr, buffer, sizeb);
7666 }
7667
7668 if (inBinary || sameEncoding) {
7669 /* Both read and write counted bytes */
7670 size = sizeb;
7671 } /* else : Read counted characters, write counted bytes, i.e. size != sizeb */
7672
7673 if (sizeb < 0) {
7674 writeError:
7675 errObj = Tcl_NewObj();
7676 Tcl_AppendStringsToObj(errObj, "error writing \"",
7677 Tcl_GetChannelName(outChan), "\": ",
7678 Tcl_PosixError(interp), (char *) NULL);
7679 break;
7680 }
7681
7682 /*
7683 * Update the current byte count. Do it now so the count is
7684 * valid before a return or break takes us out of the loop.
7685 * The invariant at the top of the loop should be that
7686 * csPtr->toRead holds the number of bytes left to copy.
7687 */
7688
7689 if (csPtr->toRead != -1) {
7690 csPtr->toRead -= size;
7691 }
7692 csPtr->total += size;
7693
7694 /*
7695 * Break loop if EOF && (size>0)
7696 */
7697
7698 if (Tcl_Eof(inChan)) {
7699 break;
7700 }
7701
7702 /*
7703 * Check to see if the write is happening in the background. If so,
7704 * stop copying and wait for the channel to become writable again.
7705 * After input underflow we already installed a readable handler
7706 * therefore we don't need a writable handler.
7707 */
7708
7709 if ( ! underflow && (outStatePtr->flags & BG_FLUSH_SCHEDULED) ) {
7710 if (!(mask & TCL_WRITABLE)) {
7711 if (mask & TCL_READABLE) {
7712 Tcl_DeleteChannelHandler(inChan, CopyEventProc,
7713 (ClientData) csPtr);
7714 }
7715 Tcl_CreateChannelHandler(outChan, TCL_WRITABLE,
7716 CopyEventProc, (ClientData) csPtr);
7717 }
7718 if (bufObj != (Tcl_Obj*) NULL) {
7719 Tcl_DecrRefCount (bufObj);
7720 bufObj = (Tcl_Obj*) NULL;
7721 }
7722 return TCL_OK;
7723 }
7724
7725 /*
7726 * For background copies, we only do one buffer per invocation so
7727 * we don't starve the rest of the system.
7728 */
7729
7730 if (cmdPtr) {
7731 /*
7732 * The first time we enter this code, there won't be a
7733 * channel handler established yet, so do it here.
7734 */
7735
7736 if (mask == 0) {
7737 Tcl_CreateChannelHandler(outChan, TCL_WRITABLE,
7738 CopyEventProc, (ClientData) csPtr);
7739 }
7740 if (bufObj != (Tcl_Obj*) NULL) {
7741 Tcl_DecrRefCount (bufObj);
7742 bufObj = (Tcl_Obj*) NULL;
7743 }
7744 return TCL_OK;
7745 }
7746 } /* while */
7747
7748 if (bufObj != (Tcl_Obj*) NULL) {
7749 Tcl_DecrRefCount (bufObj);
7750 bufObj = (Tcl_Obj*) NULL;
7751 }
7752
7753 /*
7754 * Make the callback or return the number of bytes transferred.
7755 * The local total is used because StopCopy frees csPtr.
7756 */
7757
7758 total = csPtr->total;
7759 if (cmdPtr) {
7760 /*
7761 * Get a private copy of the command so we can mutate it
7762 * by adding arguments. Note that StopCopy frees our saved
7763 * reference to the original command obj.
7764 */
7765
7766 cmdPtr = Tcl_DuplicateObj(cmdPtr);
7767 Tcl_IncrRefCount(cmdPtr);
7768 StopCopy(csPtr);
7769 Tcl_Preserve((ClientData) interp);
7770
7771 Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(total));
7772 if (errObj) {
7773 Tcl_ListObjAppendElement(interp, cmdPtr, errObj);
7774 }
7775 if (Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL) != TCL_OK) {
7776 Tcl_BackgroundError(interp);
7777 result = TCL_ERROR;
7778 }
7779 Tcl_DecrRefCount(cmdPtr);
7780 Tcl_Release((ClientData) interp);
7781 } else {
7782 StopCopy(csPtr);
7783 if (errObj) {
7784 Tcl_SetObjResult(interp, errObj);
7785 result = TCL_ERROR;
7786 } else {
7787 Tcl_ResetResult(interp);
7788 Tcl_SetIntObj(Tcl_GetObjResult(interp), total);
7789 }
7790 }
7791 return result;
7792 }
7793
7794 /*
7795 *----------------------------------------------------------------------
7796 *
7797 * DoRead --
7798 *
7799 * Reads a given number of bytes from a channel.
7800 *
7801 * No encoding conversions are applied to the bytes being read.
7802 *
7803 * Results:
7804 * The number of characters read, or -1 on error. Use Tcl_GetErrno()
7805 * to retrieve the error code for the error that occurred.
7806 *
7807 * Side effects:
7808 * May cause input to be buffered.
7809 *
7810 *----------------------------------------------------------------------
7811 */
7812
7813 static int
7814 DoRead(chanPtr, bufPtr, toRead)
7815 Channel *chanPtr; /* The channel from which to read. */
7816 char *bufPtr; /* Where to store input read. */
7817 int toRead; /* Maximum number of bytes to read. */
7818 {
7819 ChannelState *statePtr = chanPtr->state; /* state info for channel */
7820 int copied; /* How many characters were copied into
7821 * the result string? */
7822 int copiedNow; /* How many characters were copied from
7823 * the current input buffer? */
7824 int result; /* Of calling GetInput. */
7825
7826 /*
7827 * If we have not encountered a sticky EOF, clear the EOF bit. Either
7828 * way clear the BLOCKED bit. We want to discover these anew during
7829 * each operation.
7830 */
7831
7832 if (!(statePtr->flags & CHANNEL_STICKY_EOF)) {
7833 statePtr->flags &= ~CHANNEL_EOF;
7834 }
7835 statePtr->flags &= ~(CHANNEL_BLOCKED | CHANNEL_NEED_MORE_DATA);
7836
7837 for (copied = 0; copied < toRead; copied += copiedNow) {
7838 copiedNow = CopyAndTranslateBuffer(statePtr, bufPtr + copied,
7839 toRead - copied);
7840 if (copiedNow == 0) {
7841 if (statePtr->flags & CHANNEL_EOF) {
7842 goto done;
7843 }
7844 if (statePtr->flags & CHANNEL_BLOCKED) {
7845 if (statePtr->flags & CHANNEL_NONBLOCKING) {
7846 goto done;
7847 }
7848 statePtr->flags &= (~(CHANNEL_BLOCKED));
7849 }
7850 result = GetInput(chanPtr);
7851 if (result != 0) {
7852 if (result != EAGAIN) {
7853 copied = -1;
7854 }
7855 goto done;
7856 }
7857 }
7858 }
7859
7860 statePtr->flags &= (~(CHANNEL_BLOCKED));
7861
7862 done:
7863 /*
7864 * Update the notifier state so we don't block while there is still
7865 * data in the buffers.
7866 */
7867
7868 UpdateInterest(chanPtr);
7869 return copied;
7870 }
7871
7872 /*
7873 *----------------------------------------------------------------------
7874 *
7875 * CopyAndTranslateBuffer --
7876 *
7877 * Copy at most one buffer of input to the result space, doing
7878 * eol translations according to mode in effect currently.
7879 *
7880 * Results:
7881 * Number of bytes stored in the result buffer (as opposed to the
7882 * number of bytes read from the channel). May return
7883 * zero if no input is available to be translated.
7884 *
7885 * Side effects:
7886 * Consumes buffered input. May deallocate one buffer.
7887 *
7888 *----------------------------------------------------------------------
7889 */
7890
7891 static int
7892 CopyAndTranslateBuffer(statePtr, result, space)
7893 ChannelState *statePtr; /* Channel state from which to read input. */
7894 char *result; /* Where to store the copied input. */
7895 int space; /* How many bytes are available in result
7896 * to store the copied input? */
7897 {
7898 ChannelBuffer *bufPtr; /* The buffer from which to copy bytes. */
7899 int bytesInBuffer; /* How many bytes are available to be
7900 * copied in the current input buffer? */
7901 int copied; /* How many characters were already copied
7902 * into the destination space? */
7903 int i; /* Iterates over the copied input looking
7904 * for the input eofChar. */
7905
7906 /*
7907 * If there is no input at all, return zero. The invariant is that either
7908 * there is no buffer in the queue, or if the first buffer is empty, it
7909 * is also the last buffer (and thus there is no input in the queue).
7910 * Note also that if the buffer is empty, we leave it in the queue.
7911 */
7912
7913 if (statePtr->inQueueHead == (ChannelBuffer *) NULL) {
7914 return 0;
7915 }
7916 bufPtr = statePtr->inQueueHead;
7917 bytesInBuffer = bufPtr->nextAdded - bufPtr->nextRemoved;
7918
7919 copied = 0;
7920 switch (statePtr->inputTranslation) {
7921 case TCL_TRANSLATE_LF: {
7922 if (bytesInBuffer == 0) {
7923 return 0;
7924 }
7925
7926 /*
7927 * Copy the current chunk into the result buffer.
7928 */
7929
7930 if (bytesInBuffer < space) {
7931 space = bytesInBuffer;
7932 }
7933 memcpy((VOID *) result,
7934 (VOID *) (bufPtr->buf + bufPtr->nextRemoved),
7935 (size_t) space);
7936 bufPtr->nextRemoved += space;
7937 copied = space;
7938 break;
7939 }
7940 case TCL_TRANSLATE_CR: {
7941 char *end;
7942
7943 if (bytesInBuffer == 0) {
7944 return 0;
7945 }
7946
7947 /*
7948 * Copy the current chunk into the result buffer, then
7949 * replace all \r with \n.
7950 */
7951
7952 if (bytesInBuffer < space) {
7953 space = bytesInBuffer;
7954 }
7955 memcpy((VOID *) result,
7956 (VOID *) (bufPtr->buf + bufPtr->nextRemoved),
7957 (size_t) space);
7958 bufPtr->nextRemoved += space;
7959 copied = space;
7960
7961 for (end = result + copied; result < end; result++) {
7962 if (*result == '\r') {
7963 *result = '\n';
7964 }
7965 }
7966 break;
7967 }
7968 case TCL_TRANSLATE_CRLF: {
7969 char *src, *end, *dst;
7970 int curByte;
7971
7972 /*
7973 * If there is a held-back "\r" at EOF, produce it now.
7974 */
7975
7976 if (bytesInBuffer == 0) {
7977 if ((statePtr->flags & (INPUT_SAW_CR | CHANNEL_EOF)) ==
7978 (INPUT_SAW_CR | CHANNEL_EOF)) {
7979 result[0] = '\r';
7980 statePtr->flags &= ~INPUT_SAW_CR;
7981 return 1;
7982 }
7983 return 0;
7984 }
7985
7986 /*
7987 * Copy the current chunk and replace "\r\n" with "\n"
7988 * (but not standalone "\r"!).
7989 */
7990
7991 if (bytesInBuffer < space) {
7992 space = bytesInBuffer;
7993 }
7994 memcpy((VOID *) result,
7995 (VOID *) (bufPtr->buf + bufPtr->nextRemoved),
7996 (size_t) space);
7997 bufPtr->nextRemoved += space;
7998 copied = space;
7999
8000 end = result + copied;
8001 dst = result;
8002 for (src = result; src < end; src++) {
8003 curByte = *src;
8004 if (curByte == '\n') {
8005 statePtr->flags &= ~INPUT_SAW_CR;
8006 } else if (statePtr->flags & INPUT_SAW_CR) {
8007 statePtr->flags &= ~INPUT_SAW_CR;
8008 *dst = '\r';
8009 dst++;
8010 }
8011 if (curByte == '\r') {
8012 statePtr->flags |= INPUT_SAW_CR;
8013 } else {
8014 *dst = (char) curByte;
8015 dst++;
8016 }
8017 }
8018 copied = dst - result;
8019 break;
8020 }
8021 case TCL_TRANSLATE_AUTO: {
8022 char *src, *end, *dst;
8023 int curByte;
8024
8025 if (bytesInBuffer == 0) {
8026 return 0;
8027 }
8028
8029 /*
8030 * Loop over the current buffer, converting "\r" and "\r\n"
8031 * to "\n".
8032 */
8033
8034 if (bytesInBuffer < space) {
8035 space = bytesInBuffer;
8036 }
8037 memcpy((VOID *) result,
8038 (VOID *) (bufPtr->buf + bufPtr->nextRemoved),
8039 (size_t) space);
8040 bufPtr->nextRemoved += space;
8041 copied = space;
8042
8043 end = result + copied;
8044 dst = result;
8045 for (src = result; src < end; src++) {
8046 curByte = *src;
8047 if (curByte == '\r') {
8048 statePtr->flags |= INPUT_SAW_CR;
8049 *dst = '\n';
8050 dst++;
8051 } else {
8052 if ((curByte != '\n') ||
8053 !(statePtr->flags & INPUT_SAW_CR)) {
8054 *dst = (char) curByte;
8055 dst++;
8056 }
8057 statePtr->flags &= ~INPUT_SAW_CR;
8058 }
8059 }
8060 copied = dst - result;
8061 break;
8062 }
8063 default: {
8064 panic("unknown eol translation mode");
8065 }
8066 }
8067
8068 /*
8069 * If an in-stream EOF character is set for this channel, check that
8070 * the input we copied so far does not contain the EOF char. If it does,
8071 * copy only up to and excluding that character.
8072 */
8073
8074 if (statePtr->inEofChar != 0) {
8075 for (i = 0; i < copied; i++) {
8076 if (result[i] == (char) statePtr->inEofChar) {
8077 /*
8078 * Set sticky EOF so that no further input is presented
8079 * to the caller.
8080 */
8081
8082 statePtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);
8083 statePtr->inputEncodingFlags |= TCL_ENCODING_END;
8084 copied = i;
8085 break;
8086 }
8087 }
8088 }
8089
8090 /*
8091 * If the current buffer is empty recycle it.
8092 */
8093
8094 if (bufPtr->nextRemoved == bufPtr->nextAdded) {
8095 statePtr->inQueueHead = bufPtr->nextPtr;
8096 if (statePtr->inQueueHead == (ChannelBuffer *) NULL) {
8097 statePtr->inQueueTail = (ChannelBuffer *) NULL;
8098 }
8099 RecycleBuffer(statePtr, bufPtr, 0);
8100 }
8101
8102 /*
8103 * Return the number of characters copied into the result buffer.
8104 * This may be different from the number of bytes consumed, because
8105 * of EOL translations.
8106 */
8107
8108 return copied;
8109 }
8110
8111 /*
8112 *----------------------------------------------------------------------
8113 *
8114 * CopyBuffer --
8115 *
8116 * Copy at most one buffer of input to the result space.
8117 *
8118 * Results:
8119 * Number of bytes stored in the result buffer. May return
8120 * zero if no input is available.
8121 *
8122 * Side effects:
8123 * Consumes buffered input. May deallocate one buffer.
8124 *
8125 *----------------------------------------------------------------------
8126 */
8127
8128 static int
8129 CopyBuffer(chanPtr, result, space)
8130 Channel *chanPtr; /* Channel from which to read input. */
8131 char *result; /* Where to store the copied input. */
8132 int space; /* How many bytes are available in result
8133 * to store the copied input? */
8134 {
8135 ChannelBuffer *bufPtr; /* The buffer from which to copy bytes. */
8136 int bytesInBuffer; /* How many bytes are available to be
8137 * copied in the current input buffer? */
8138 int copied; /* How many characters were already copied
8139 * into the destination space? */
8140
8141 /*
8142 * If there is no input at all, return zero. The invariant is that
8143 * either there is no buffer in the queue, or if the first buffer
8144 * is empty, it is also the last buffer (and thus there is no
8145 * input in the queue). Note also that if the buffer is empty, we
8146 * don't leave it in the queue, but recycle it.
8147 */
8148
8149 if (chanPtr->inQueueHead == (ChannelBuffer *) NULL) {
8150 return 0;
8151 }
8152 bufPtr = chanPtr->inQueueHead;
8153 bytesInBuffer = bufPtr->nextAdded - bufPtr->nextRemoved;
8154
8155 copied = 0;
8156
8157 if (bytesInBuffer == 0) {
8158 RecycleBuffer(chanPtr->state, bufPtr, 0);
8159 chanPtr->inQueueHead = (ChannelBuffer*) NULL;
8160 chanPtr->inQueueTail = (ChannelBuffer*) NULL;
8161 return 0;
8162 }
8163
8164 /*
8165 * Copy the current chunk into the result buffer.
8166 */
8167
8168 if (bytesInBuffer < space) {
8169 space = bytesInBuffer;
8170 }
8171
8172 memcpy((VOID *) result,
8173 (VOID *) (bufPtr->buf + bufPtr->nextRemoved),
8174 (size_t) space);
8175 bufPtr->nextRemoved += space;
8176 copied = space;
8177
8178 /*
8179 * We don't care about in-stream EOF characters here as the data
8180 * read here may still flow through one or more transformations,
8181 * i.e. is not in its final state yet.
8182 */
8183
8184 /*
8185 * If the current buffer is empty recycle it.
8186 */
8187
8188 if (bufPtr->nextRemoved == bufPtr->nextAdded) {
8189 chanPtr->inQueueHead = bufPtr->nextPtr;
8190 if (chanPtr->inQueueHead == (ChannelBuffer *) NULL) {
8191 chanPtr->inQueueTail = (ChannelBuffer *) NULL;
8192 }
8193 RecycleBuffer(chanPtr->state, bufPtr, 0);
8194 }
8195
8196 /*
8197 * Return the number of characters copied into the result buffer.
8198 */
8199
8200 return copied;
8201 }
8202
8203 /*
8204 *----------------------------------------------------------------------
8205 *
8206 * DoWrite --
8207 *
8208 * Puts a sequence of characters into an output buffer, may queue the
8209 * buffer for output if it gets full, and also remembers whether the
8210 * current buffer is ready e.g. if it contains a newline and we are in
8211 * line buffering mode.
8212 *
8213 * Results:
8214 * The number of bytes written or -1 in case of error. If -1,
8215 * Tcl_GetErrno will return the error code.
8216 *
8217 * Side effects:
8218 * May buffer up output and may cause output to be produced on the
8219 * channel.
8220 *
8221 *----------------------------------------------------------------------
8222 */
8223
8224 static int
8225 DoWrite(chanPtr, src, srcLen)
8226 Channel *chanPtr; /* The channel to buffer output for. */
8227 CONST char *src; /* Data to write. */
8228 int srcLen; /* Number of bytes to write. */
8229 {
8230 ChannelState *statePtr = chanPtr->state; /* state info for channel */
8231 ChannelBuffer *outBufPtr; /* Current output buffer. */
8232 int foundNewline; /* Did we find a newline in output? */
8233 char *dPtr;
8234 CONST char *sPtr; /* Search variables for newline. */
8235 int crsent; /* In CRLF eol translation mode,
8236 * remember the fact that a CR was
8237 * output to the channel without
8238 * its following NL. */
8239 int i; /* Loop index for newline search. */
8240 int destCopied; /* How many bytes were used in this
8241 * destination buffer to hold the
8242 * output? */
8243 int totalDestCopied; /* How many bytes total were
8244 * copied to the channel buffer? */
8245 int srcCopied; /* How many bytes were copied from
8246 * the source string? */
8247 char *destPtr; /* Where in line to copy to? */
8248
8249 /*
8250 * If we are in network (or windows) translation mode, record the fact
8251 * that we have not yet sent a CR to the channel.
8252 */
8253
8254 crsent = 0;
8255
8256 /*
8257 * Loop filling buffers and flushing them until all output has been
8258 * consumed.
8259 */
8260
8261 srcCopied = 0;
8262 totalDestCopied = 0;
8263
8264 while (srcLen > 0) {
8265
8266 /*
8267 * Make sure there is a current output buffer to accept output.
8268 */
8269
8270 if (statePtr->curOutPtr == (ChannelBuffer *) NULL) {
8271 statePtr->curOutPtr = AllocChannelBuffer(statePtr->bufSize);
8272 }
8273
8274 outBufPtr = statePtr->curOutPtr;
8275
8276 destCopied = outBufPtr->bufLength - outBufPtr->nextAdded;
8277 if (destCopied > srcLen) {
8278 destCopied = srcLen;
8279 }
8280
8281 destPtr = outBufPtr->buf + outBufPtr->nextAdded;
8282 switch (statePtr->outputTranslation) {
8283 case TCL_TRANSLATE_LF:
8284 srcCopied = destCopied;
8285 memcpy((VOID *) destPtr, (VOID *) src, (size_t) destCopied);
8286 break;
8287 case TCL_TRANSLATE_CR:
8288 srcCopied = destCopied;
8289 memcpy((VOID *) destPtr, (VOID *) src, (size_t) destCopied);
8290 for (dPtr = destPtr; dPtr < destPtr + destCopied; dPtr++) {
8291 if (*dPtr == '\n') {
8292 *dPtr = '\r';
8293 }
8294 }
8295 break;
8296 case TCL_TRANSLATE_CRLF:
8297 for (srcCopied = 0, dPtr = destPtr, sPtr = src;
8298 dPtr < destPtr + destCopied;
8299 dPtr++, sPtr++, srcCopied++) {
8300 if (*sPtr == '\n') {
8301 if (crsent) {
8302 *dPtr = '\n';
8303 crsent = 0;
8304 } else {
8305 *dPtr = '\r';
8306 crsent = 1;
8307 sPtr--, srcCopied--;
8308 }
8309 } else {
8310 *dPtr = *sPtr;
8311 }
8312 }
8313 break;
8314 case TCL_TRANSLATE_AUTO:
8315 panic("Tcl_Write: AUTO output translation mode not supported");
8316 default:
8317 panic("Tcl_Write: unknown output translation mode");
8318 }
8319
8320 /*
8321 * The current buffer is ready for output if it is full, or if it
8322 * contains a newline and this channel is line-buffered, or if it
8323 * contains any output and this channel is unbuffered.
8324 */
8325
8326 outBufPtr->nextAdded += destCopied;
8327 if (!(statePtr->flags & BUFFER_READY)) {
8328 if (outBufPtr->nextAdded == outBufPtr->bufLength) {
8329 statePtr->flags |= BUFFER_READY;
8330 } else if (statePtr->flags & CHANNEL_LINEBUFFERED) {
8331 for (sPtr = src, i = 0, foundNewline = 0;
8332 (i < srcCopied) && (!foundNewline);
8333 i++, sPtr++) {
8334 if (*sPtr == '\n') {
8335 foundNewline = 1;
8336 break;
8337 }
8338 }
8339 if (foundNewline) {
8340 statePtr->flags |= BUFFER_READY;
8341 }
8342 } else if (statePtr->flags & CHANNEL_UNBUFFERED) {
8343 statePtr->flags |= BUFFER_READY;
8344 }
8345 }
8346
8347 totalDestCopied += srcCopied;
8348 src += srcCopied;
8349 srcLen -= srcCopied;
8350
8351 if (statePtr->flags & BUFFER_READY) {
8352 if (FlushChannel(NULL, chanPtr, 0) != 0) {
8353 return -1;
8354 }
8355 }
8356 } /* Closes "while" */
8357
8358 return totalDestCopied;
8359 }
8360
8361 /*
8362 *----------------------------------------------------------------------
8363 *
8364 * CopyEventProc --
8365 *
8366 * This routine is invoked as a channel event handler for
8367 * the background copy operation. It is just a trivial wrapper
8368 * around the CopyData routine.
8369 *
8370 * Results:
8371 * None.
8372 *
8373 * Side effects:
8374 * None.
8375 *
8376 *----------------------------------------------------------------------
8377 */
8378
8379 static void
8380 CopyEventProc(clientData, mask)
8381 ClientData clientData;
8382 int mask;
8383 {
8384 (void) CopyData((CopyState *)clientData, mask);
8385 }
8386
8387 /*
8388 *----------------------------------------------------------------------
8389 *
8390 * StopCopy --
8391 *
8392 * This routine halts a copy that is in progress.
8393 *
8394 * Results:
8395 * None.
8396 *
8397 * Side effects:
8398 * Removes any pending channel handlers and restores the blocking
8399 * and buffering modes of the channels. The CopyState is freed.
8400 *
8401 *----------------------------------------------------------------------
8402 */
8403
8404 static void
8405 StopCopy(csPtr)
8406 CopyState *csPtr; /* State for bg copy to stop . */
8407 {
8408 ChannelState *inStatePtr, *outStatePtr;
8409 int nonBlocking;
8410
8411 if (!csPtr) {
8412 return;
8413 }
8414
8415 inStatePtr = csPtr->readPtr->state;
8416 outStatePtr = csPtr->writePtr->state;
8417
8418 /*
8419 * Restore the old blocking mode and output buffering mode.
8420 */
8421
8422 nonBlocking = (csPtr->readFlags & CHANNEL_NONBLOCKING);
8423 if (nonBlocking != (inStatePtr->flags & CHANNEL_NONBLOCKING)) {
8424 SetBlockMode(NULL, csPtr->readPtr,
8425 nonBlocking ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING);
8426 }
8427 if (csPtr->readPtr != csPtr->writePtr) {
8428 nonBlocking = (csPtr->writeFlags & CHANNEL_NONBLOCKING);
8429 if (nonBlocking != (outStatePtr->flags & CHANNEL_NONBLOCKING)) {
8430 SetBlockMode(NULL, csPtr->writePtr,
8431 nonBlocking ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING);
8432 }
8433 }
8434 outStatePtr->flags &= ~(CHANNEL_LINEBUFFERED | CHANNEL_UNBUFFERED);
8435 outStatePtr->flags |=
8436 csPtr->writeFlags & (CHANNEL_LINEBUFFERED | CHANNEL_UNBUFFERED);
8437
8438 if (csPtr->cmdPtr) {
8439 Tcl_DeleteChannelHandler((Tcl_Channel)csPtr->readPtr, CopyEventProc,
8440 (ClientData)csPtr);
8441 if (csPtr->readPtr != csPtr->writePtr) {
8442 Tcl_DeleteChannelHandler((Tcl_Channel)csPtr->writePtr,
8443 CopyEventProc, (ClientData)csPtr);
8444 }
8445 Tcl_DecrRefCount(csPtr->cmdPtr);
8446 }
8447 inStatePtr->csPtr = NULL;
8448 outStatePtr->csPtr = NULL;
8449 ckfree((char*) csPtr);
8450 }
8451
8452 /*
8453 *----------------------------------------------------------------------
8454 *
8455 * StackSetBlockMode --
8456 *
8457 * This function sets the blocking mode for a channel, iterating
8458 * through each channel in a stack and updates the state flags.
8459 *
8460 * Results:
8461 * 0 if OK, result code from failed blockModeProc otherwise.
8462 *
8463 * Side effects:
8464 * Modifies the blocking mode of the channel and possibly generates
8465 * an error.
8466 *
8467 *----------------------------------------------------------------------
8468 */
8469
8470 static int
8471 StackSetBlockMode(chanPtr, mode)
8472 Channel *chanPtr; /* Channel to modify. */
8473 int mode; /* One of TCL_MODE_BLOCKING or
8474 * TCL_MODE_NONBLOCKING. */
8475 {
8476 int result = 0;
8477 Tcl_DriverBlockModeProc *blockModeProc;
8478
8479 /*
8480 * Start at the top of the channel stack
8481 */
8482
8483 chanPtr = chanPtr->state->topChanPtr;
8484 while (chanPtr != (Channel *) NULL) {
8485 blockModeProc = Tcl_ChannelBlockModeProc(chanPtr->typePtr);
8486 if (blockModeProc != NULL) {
8487 result = (*blockModeProc) (chanPtr->instanceData, mode);
8488 if (result != 0) {
8489 Tcl_SetErrno(result);
8490 return result;
8491 }
8492 }
8493 chanPtr = chanPtr->downChanPtr;
8494 }
8495 return 0;
8496 }
8497
8498 /*
8499 *----------------------------------------------------------------------
8500 *
8501 * SetBlockMode --
8502 *
8503 * This function sets the blocking mode for a channel and updates
8504 * the state flags.
8505 *
8506 * Results:
8507 * A standard Tcl result.
8508 *
8509 * Side effects:
8510 * Modifies the blocking mode of the channel and possibly generates
8511 * an error.
8512 *
8513 *----------------------------------------------------------------------
8514 */
8515
8516 static int
8517 SetBlockMode(interp, chanPtr, mode)
8518 Tcl_Interp *interp; /* Interp for error reporting. */
8519 Channel *chanPtr; /* Channel to modify. */
8520 int mode; /* One of TCL_MODE_BLOCKING or
8521 * TCL_MODE_NONBLOCKING. */
8522 {
8523 ChannelState *statePtr = chanPtr->state; /* state info for channel */
8524 int result = 0;
8525
8526 result = StackSetBlockMode(chanPtr, mode);
8527 if (result != 0) {
8528 if (interp != (Tcl_Interp *) NULL) {
8529 Tcl_AppendResult(interp, "error setting blocking mode: ",
8530 Tcl_PosixError(interp), (char *) NULL);
8531 }
8532 return TCL_ERROR;
8533 }
8534 if (mode == TCL_MODE_BLOCKING) {
8535 statePtr->flags &= (~(CHANNEL_NONBLOCKING | BG_FLUSH_SCHEDULED));
8536 } else {
8537 statePtr->flags |= CHANNEL_NONBLOCKING;
8538 }
8539 return TCL_OK;
8540 }
8541
8542 /*
8543 *----------------------------------------------------------------------
8544 *
8545 * Tcl_GetChannelNames --
8546 *
8547 * Return the names of all open channels in the interp.
8548 *
8549 * Results:
8550 * TCL_OK or TCL_ERROR.
8551 *
8552 * Side effects:
8553 * Interp result modified with list of channel names.
8554 *
8555 *----------------------------------------------------------------------
8556 */
8557
8558 int
8559 Tcl_GetChannelNames(interp)
8560 Tcl_Interp *interp; /* Interp for error reporting. */
8561 {
8562 return Tcl_GetChannelNamesEx(interp, (char *) NULL);
8563 }
8564
8565 /*
8566 *----------------------------------------------------------------------
8567 *
8568 * Tcl_GetChannelNamesEx --
8569 *
8570 * Return the names of open channels in the interp filtered
8571 * filtered through a pattern. If pattern is NULL, it returns
8572 * all the open channels.
8573 *
8574 * Results:
8575 * TCL_OK or TCL_ERROR.
8576 *
8577 * Side effects:
8578 * Interp result modified with list of channel names.
8579 *
8580 *----------------------------------------------------------------------
8581 */
8582
8583 int
8584 Tcl_GetChannelNamesEx(interp, pattern)
8585 Tcl_Interp *interp; /* Interp for error reporting. */
8586 CONST char *pattern; /* pattern to filter on. */
8587 {
8588 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
8589 ChannelState *statePtr;
8590 CONST char *name; /* name for channel */
8591 Tcl_Obj *resultPtr; /* pointer to result object */
8592 Tcl_HashTable *hTblPtr; /* Hash table of channels. */
8593 Tcl_HashEntry *hPtr; /* Search variable. */
8594 Tcl_HashSearch hSearch; /* Search variable. */
8595
8596 if (interp == (Tcl_Interp *) NULL) {
8597 return TCL_OK;
8598 }
8599
8600 /*
8601 * Get the channel table that stores the channels registered
8602 * for this interpreter.
8603 */
8604 hTblPtr = GetChannelTable(interp);
8605 resultPtr = Tcl_GetObjResult(interp);
8606
8607 for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
8608 hPtr != (Tcl_HashEntry *) NULL;
8609 hPtr = Tcl_NextHashEntry(&hSearch)) {
8610
8611 statePtr = ((Channel *) Tcl_GetHashValue(hPtr))->state;
8612 if (statePtr->topChanPtr == (Channel *) tsdPtr->stdinChannel) {
8613 name = "stdin";
8614 } else if (statePtr->topChanPtr == (Channel *) tsdPtr->stdoutChannel) {
8615 name = "stdout";
8616 } else if (statePtr->topChanPtr == (Channel *) tsdPtr->stderrChannel) {
8617 name = "stderr";
8618 } else {
8619 /*
8620 * This is also stored in Tcl_GetHashKey(hTblPtr, hPtr),
8621 * but it's simpler to just grab the name from the statePtr.
8622 */
8623 name = statePtr->channelName;
8624 }
8625
8626 if (((pattern == NULL) || Tcl_StringMatch(name, pattern)) &&
8627 (Tcl_ListObjAppendElement(interp, resultPtr,
8628 Tcl_NewStringObj(name, -1)) != TCL_OK)) {
8629 return TCL_ERROR;
8630 }
8631 }
8632 return TCL_OK;
8633 }
8634
8635 /*
8636 *----------------------------------------------------------------------
8637 *
8638 * Tcl_IsChannelRegistered --
8639 *
8640 * Checks whether the channel is associated with the interp.
8641 * See also Tcl_RegisterChannel and Tcl_UnregisterChannel.
8642 *
8643 * Results:
8644 * 0 if the channel is not registered in the interpreter, 1 else.
8645 *
8646 * Side effects:
8647 * None.
8648 *
8649 *----------------------------------------------------------------------
8650 */
8651
8652 int
8653 Tcl_IsChannelRegistered (interp, chan)
8654 Tcl_Interp* interp; /* The interp to query of the channel */
8655 Tcl_Channel chan; /* The channel to check */
8656 {
8657 Tcl_HashTable *hTblPtr; /* Hash table of channels. */
8658 Tcl_HashEntry *hPtr; /* Search variable. */
8659 Channel *chanPtr; /* The real IO channel. */
8660 ChannelState *statePtr; /* State of the real channel. */
8661
8662 /*
8663 * Always check bottom-most channel in the stack. This is the one
8664 * that gets registered.
8665 */
8666 chanPtr = ((Channel *) chan)->state->bottomChanPtr;
8667 statePtr = chanPtr->state;
8668
8669 hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
8670 if (hTblPtr == (Tcl_HashTable *) NULL) {
8671 return 0;
8672 }
8673 hPtr = Tcl_FindHashEntry(hTblPtr, statePtr->channelName);
8674 if (hPtr == (Tcl_HashEntry *) NULL) {
8675 return 0;
8676 }
8677 if ((Channel *) Tcl_GetHashValue(hPtr) != chanPtr) {
8678 return 0;
8679 }
8680
8681 return 1;
8682 }
8683
8684 /*
8685 *----------------------------------------------------------------------
8686 *
8687 * Tcl_IsChannelShared --
8688 *
8689 * Checks whether the channel is shared by multiple interpreters.
8690 *
8691 * Results:
8692 * A boolean value (0 = Not shared, 1 = Shared).
8693 *
8694 * Side effects:
8695 * None.
8696 *
8697 *----------------------------------------------------------------------
8698 */
8699
8700 int
8701 Tcl_IsChannelShared (chan)
8702 Tcl_Channel chan; /* The channel to query */
8703 {
8704 ChannelState *statePtr = ((Channel *) chan)->state;
8705 /* State of real channel structure. */
8706
8707 return ((statePtr->refCount > 1) ? 1 : 0);
8708 }
8709
8710 /*
8711 *----------------------------------------------------------------------
8712 *
8713 * Tcl_IsChannelExisting --
8714 *
8715 * Checks whether a channel of the given name exists in the
8716 * (thread)-global list of all channels.
8717 * See Tcl_GetChannelNamesEx for function exposed at the Tcl level.
8718 *
8719 * Results:
8720 * A boolean value (0 = Does not exist, 1 = Does exist).
8721 *
8722 * Side effects:
8723 * None.
8724 *
8725 *----------------------------------------------------------------------
8726 */
8727
8728 int
8729 Tcl_IsChannelExisting(chanName)
8730 CONST char* chanName; /* The name of the channel to look for. */
8731 {
8732 ChannelState *statePtr;
8733 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
8734 CONST char *name;
8735 int chanNameLen;
8736
8737 chanNameLen = strlen(chanName);
8738 for (statePtr = tsdPtr->firstCSPtr;
8739 statePtr != NULL;
8740 statePtr = statePtr->nextCSPtr) {
8741 if (statePtr->topChanPtr == (Channel *) tsdPtr->stdinChannel) {
8742 name = "stdin";
8743 } else if (statePtr->topChanPtr == (Channel *) tsdPtr->stdoutChannel) {
8744 name = "stdout";
8745 } else if (statePtr->topChanPtr == (Channel *) tsdPtr->stderrChannel) {
8746 name = "stderr";
8747 } else {
8748 name = statePtr->channelName;
8749 }
8750
8751 if ((*chanName == *name) &&
8752 (memcmp(name, chanName, (size_t) chanNameLen) == 0)) {
8753 return 1;
8754 }
8755 }
8756
8757 return 0;
8758 }
8759
8760 /*
8761 *----------------------------------------------------------------------
8762 *
8763 * Tcl_ChannelName --
8764 *
8765 * Return the name of the channel type.
8766 *
8767 * Results:
8768 * A pointer the name of the channel type.
8769 *
8770 * Side effects:
8771 * None.
8772 *
8773 *----------------------------------------------------------------------
8774 */
8775
8776 CONST char *
8777 Tcl_ChannelName(chanTypePtr)
8778 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8779 {
8780 return chanTypePtr->typeName;
8781 }
8782
8783 /*
8784 *----------------------------------------------------------------------
8785 *
8786 * Tcl_ChannelVersion --
8787 *
8788 * Return the of version of the channel type.
8789 *
8790 * Results:
8791 * One of the TCL_CHANNEL_VERSION_* constants from tcl.h
8792 *
8793 * Side effects:
8794 * None.
8795 *
8796 *----------------------------------------------------------------------
8797 */
8798
8799 Tcl_ChannelTypeVersion
8800 Tcl_ChannelVersion(chanTypePtr)
8801 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8802 {
8803 if (chanTypePtr->version == TCL_CHANNEL_VERSION_2) {
8804 return TCL_CHANNEL_VERSION_2;
8805 } else if (chanTypePtr->version == TCL_CHANNEL_VERSION_3) {
8806 return TCL_CHANNEL_VERSION_3;
8807 } else {
8808 /*
8809 * In <v2 channel versions, the version field is occupied
8810 * by the Tcl_DriverBlockModeProc
8811 */
8812 return TCL_CHANNEL_VERSION_1;
8813 }
8814 }
8815
8816 /*
8817 *----------------------------------------------------------------------
8818 *
8819 * HaveVersion --
8820 *
8821 * Return whether a channel type is (at least) of a given version.
8822 *
8823 * Results:
8824 * True if the minimum version is exceeded by the version actually
8825 * present.
8826 *
8827 * Side effects:
8828 * None.
8829 *
8830 *----------------------------------------------------------------------
8831 */
8832
8833 static int
8834 HaveVersion(chanTypePtr, minimumVersion)
8835 Tcl_ChannelType *chanTypePtr;
8836 Tcl_ChannelTypeVersion minimumVersion;
8837 {
8838 Tcl_ChannelTypeVersion actualVersion = Tcl_ChannelVersion(chanTypePtr);
8839
8840 return ((int)actualVersion) >= ((int)minimumVersion);
8841 }
8842
8843 /*
8844 *----------------------------------------------------------------------
8845 *
8846 * Tcl_ChannelBlockModeProc --
8847 *
8848 * Return the Tcl_DriverBlockModeProc of the channel type.
8849 *
8850 * Results:
8851 * A pointer to the proc.
8852 *
8853 * Side effects:
8854 * None.
8855 *
8856 *---------------------------------------------------------------------- */
8857
8858 Tcl_DriverBlockModeProc *
8859 Tcl_ChannelBlockModeProc(chanTypePtr)
8860 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8861 {
8862 if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_2)) {
8863 return chanTypePtr->blockModeProc;
8864 } else {
8865 /*
8866 * The v1 structure had the blockModeProc in a different place.
8867 */
8868 return (Tcl_DriverBlockModeProc *) (chanTypePtr->version);
8869 }
8870 }
8871
8872 /*
8873 *----------------------------------------------------------------------
8874 *
8875 * Tcl_ChannelCloseProc --
8876 *
8877 * Return the Tcl_DriverCloseProc of the channel type.
8878 *
8879 * Results:
8880 * A pointer to the proc.
8881 *
8882 * Side effects:
8883 * None.
8884 *
8885 *----------------------------------------------------------------------
8886 */
8887
8888 Tcl_DriverCloseProc *
8889 Tcl_ChannelCloseProc(chanTypePtr)
8890 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8891 {
8892 return chanTypePtr->closeProc;
8893 }
8894
8895 /*
8896 *----------------------------------------------------------------------
8897 *
8898 * Tcl_ChannelClose2Proc --
8899 *
8900 * Return the Tcl_DriverClose2Proc of the channel type.
8901 *
8902 * Results:
8903 * A pointer to the proc.
8904 *
8905 * Side effects:
8906 * None.
8907 *
8908 *----------------------------------------------------------------------
8909 */
8910
8911 Tcl_DriverClose2Proc *
8912 Tcl_ChannelClose2Proc(chanTypePtr)
8913 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8914 {
8915 return chanTypePtr->close2Proc;
8916 }
8917
8918 /*
8919 *----------------------------------------------------------------------
8920 *
8921 * Tcl_ChannelInputProc --
8922 *
8923 * Return the Tcl_DriverInputProc of the channel type.
8924 *
8925 * Results:
8926 * A pointer to the proc.
8927 *
8928 * Side effects:
8929 * None.
8930 *
8931 *----------------------------------------------------------------------
8932 */
8933
8934 Tcl_DriverInputProc *
8935 Tcl_ChannelInputProc(chanTypePtr)
8936 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8937 {
8938 return chanTypePtr->inputProc;
8939 }
8940
8941 /*
8942 *----------------------------------------------------------------------
8943 *
8944 * Tcl_ChannelOutputProc --
8945 *
8946 * Return the Tcl_DriverOutputProc of the channel type.
8947 *
8948 * Results:
8949 * A pointer to the proc.
8950 *
8951 * Side effects:
8952 * None.
8953 *
8954 *----------------------------------------------------------------------
8955 */
8956
8957 Tcl_DriverOutputProc *
8958 Tcl_ChannelOutputProc(chanTypePtr)
8959 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8960 {
8961 return chanTypePtr->outputProc;
8962 }
8963
8964 /*
8965 *----------------------------------------------------------------------
8966 *
8967 * Tcl_ChannelSeekProc --
8968 *
8969 * Return the Tcl_DriverSeekProc of the channel type.
8970 *
8971 * Results:
8972 * A pointer to the proc.
8973 *
8974 * Side effects:
8975 * None.
8976 *
8977 *----------------------------------------------------------------------
8978 */
8979
8980 Tcl_DriverSeekProc *
8981 Tcl_ChannelSeekProc(chanTypePtr)
8982 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
8983 {
8984 return chanTypePtr->seekProc;
8985 }
8986
8987 /*
8988 *----------------------------------------------------------------------
8989 *
8990 * Tcl_ChannelSetOptionProc --
8991 *
8992 * Return the Tcl_DriverSetOptionProc of the channel type.
8993 *
8994 * Results:
8995 * A pointer to the proc.
8996 *
8997 * Side effects:
8998 * None.
8999 *
9000 *----------------------------------------------------------------------
9001 */
9002
9003 Tcl_DriverSetOptionProc *
9004 Tcl_ChannelSetOptionProc(chanTypePtr)
9005 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
9006 {
9007 return chanTypePtr->setOptionProc;
9008 }
9009
9010 /*
9011 *----------------------------------------------------------------------
9012 *
9013 * Tcl_ChannelGetOptionProc --
9014 *
9015 * Return the Tcl_DriverGetOptionProc of the channel type.
9016 *
9017 * Results:
9018 * A pointer to the proc.
9019 *
9020 * Side effects:
9021 * None.
9022 *
9023 *----------------------------------------------------------------------
9024 */
9025
9026 Tcl_DriverGetOptionProc *
9027 Tcl_ChannelGetOptionProc(chanTypePtr)
9028 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
9029 {
9030 return chanTypePtr->getOptionProc;
9031 }
9032
9033 /*
9034 *----------------------------------------------------------------------
9035 *
9036 * Tcl_ChannelWatchProc --
9037 *
9038 * Return the Tcl_DriverWatchProc of the channel type.
9039 *
9040 * Results:
9041 * A pointer to the proc.
9042 *
9043 * Side effects:
9044 * None.
9045 *
9046 *----------------------------------------------------------------------
9047 */
9048
9049 Tcl_DriverWatchProc *
9050 Tcl_ChannelWatchProc(chanTypePtr)
9051 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
9052 {
9053 return chanTypePtr->watchProc;
9054 }
9055
9056 /*
9057 *----------------------------------------------------------------------
9058 *
9059 * Tcl_ChannelGetHandleProc --
9060 *
9061 * Return the Tcl_DriverGetHandleProc of the channel type.
9062 *
9063 * Results:
9064 * A pointer to the proc.
9065 *
9066 * Side effects:
9067 * None.
9068 *
9069 *----------------------------------------------------------------------
9070 */
9071
9072 Tcl_DriverGetHandleProc *
9073 Tcl_ChannelGetHandleProc(chanTypePtr)
9074 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
9075 {
9076 return chanTypePtr->getHandleProc;
9077 }
9078
9079 /*
9080 *----------------------------------------------------------------------
9081 *
9082 * Tcl_ChannelFlushProc --
9083 *
9084 * Return the Tcl_DriverFlushProc of the channel type.
9085 *
9086 * Results:
9087 * A pointer to the proc.
9088 *
9089 * Side effects:
9090 * None.
9091 *
9092 *----------------------------------------------------------------------
9093 */
9094
9095 Tcl_DriverFlushProc *
9096 Tcl_ChannelFlushProc(chanTypePtr)
9097 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
9098 {
9099 if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_2)) {
9100 return chanTypePtr->flushProc;
9101 } else {
9102 return NULL;
9103 }
9104 }
9105
9106 /*
9107 *----------------------------------------------------------------------
9108 *
9109 * Tcl_ChannelHandlerProc --
9110 *
9111 * Return the Tcl_DriverHandlerProc of the channel type.
9112 *
9113 * Results:
9114 * A pointer to the proc.
9115 *
9116 * Side effects:
9117 * None.
9118 *
9119 *----------------------------------------------------------------------
9120 */
9121
9122 Tcl_DriverHandlerProc *
9123 Tcl_ChannelHandlerProc(chanTypePtr)
9124 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
9125 {
9126 if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_2)) {
9127 return chanTypePtr->handlerProc;
9128 } else {
9129 return NULL;
9130 }
9131 }
9132
9133 /*
9134 *----------------------------------------------------------------------
9135 *
9136 * Tcl_ChannelWideSeekProc --
9137 *
9138 * Return the Tcl_DriverWideSeekProc of the channel type.
9139 *
9140 * Results:
9141 * A pointer to the proc.
9142 *
9143 * Side effects:
9144 * None.
9145 *
9146 *----------------------------------------------------------------------
9147 */
9148
9149 Tcl_DriverWideSeekProc *
9150 Tcl_ChannelWideSeekProc(chanTypePtr)
9151 Tcl_ChannelType *chanTypePtr; /* Pointer to channel type. */
9152 {
9153 if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_3)) {
9154 return chanTypePtr->wideSeekProc;
9155 } else {
9156 return NULL;
9157 }
9158 }