Debian Codegraph @

generic/tclIOCmd.c

raw
1 /*
2 * tclIOCmd.c --
3 *
4 * Contains the definitions of most of the Tcl commands relating to IO.
5 *
6 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
7 *
8 * See the file "license.terms" for information on usage and redistribution of
9 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
10 */
11
12 #include "tclInt.h"
13
14 /*
15 * Callback structure for accept callback in a TCP server.
16 */
17
18 typedef struct AcceptCallback {
19 char *script; /* Script to invoke. */
20 Tcl_Interp *interp; /* Interpreter in which to run it. */
21 } AcceptCallback;
22
23 /*
24 * Thread local storage used to maintain a per-thread stdout channel obj.
25 * It must be per-thread because of std channel limitations.
26 */
27
28 typedef struct ThreadSpecificData {
29 int initialized; /* Set to 1 when the module is initialized. */
30 Tcl_Obj *stdoutObjPtr; /* Cached stdout channel Tcl_Obj */
31 } ThreadSpecificData;
32
33 static Tcl_ThreadDataKey dataKey;
34
35 /*
36 * Static functions for this file:
37 */
38
39 static void FinalizeIOCmdTSD(ClientData clientData);
40 static void AcceptCallbackProc(ClientData callbackData,
41 Tcl_Channel chan, char *address, int port);
42 static int ChanPendingObjCmd(ClientData unused,
43 Tcl_Interp *interp, int objc,
44 Tcl_Obj *const objv[]);
45 static int ChanTruncateObjCmd(ClientData dummy,
46 Tcl_Interp *interp, int objc,
47 Tcl_Obj *const objv[]);
48 static void RegisterTcpServerInterpCleanup(Tcl_Interp *interp,
49 AcceptCallback *acceptCallbackPtr);
50 static void TcpAcceptCallbacksDeleteProc(ClientData clientData,
51 Tcl_Interp *interp);
52 static void TcpServerCloseProc(ClientData callbackData);
53 static void UnregisterTcpServerInterpCleanupProc(
54 Tcl_Interp *interp,
55 AcceptCallback *acceptCallbackPtr);
56
57 /*
58 *----------------------------------------------------------------------
59 *
60 * FinalizeIOCmdTSD --
61 *
62 * Release the storage associated with the per-thread cache.
63 *
64 * Results:
65 * None.
66 *
67 * Side effects:
68 * None.
69 *
70 *----------------------------------------------------------------------
71 */
72
73 static void
74 FinalizeIOCmdTSD(
75 ClientData clientData) /* Not used. */
76 {
77 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
78
79 if (tsdPtr->stdoutObjPtr != NULL) {
80 Tcl_DecrRefCount(tsdPtr->stdoutObjPtr);
81 tsdPtr->stdoutObjPtr = NULL;
82 }
83 tsdPtr->initialized = 0;
84 }
85
86 /*
87 *----------------------------------------------------------------------
88 *
89 * Tcl_PutsObjCmd --
90 *
91 * This function is invoked to process the "puts" Tcl command. See the
92 * user documentation for details on what it does.
93 *
94 * Results:
95 * A standard Tcl result.
96 *
97 * Side effects:
98 * Produces output on a channel.
99 *
100 *----------------------------------------------------------------------
101 */
102
103 /* ARGSUSED */
104 int
105 Tcl_PutsObjCmd(
106 ClientData dummy, /* Not used. */
107 Tcl_Interp *interp, /* Current interpreter. */
108 int objc, /* Number of arguments. */
109 Tcl_Obj *const objv[]) /* Argument objects. */
110 {
111 Tcl_Channel chan; /* The channel to puts on. */
112 Tcl_Obj *string; /* String to write. */
113 Tcl_Obj *chanObjPtr = NULL; /* channel object. */
114 int newline; /* Add a newline at end? */
115 int result; /* Result of puts operation. */
116 int mode; /* Mode in which channel is opened. */
117 ThreadSpecificData *tsdPtr;
118
119 switch (objc) {
120 case 2: /* [puts $x] */
121 string = objv[1];
122 newline = 1;
123 break;
124
125 case 3: /* [puts -nonewline $x] or [puts $chan $x] */
126 if (strcmp(TclGetString(objv[1]), "-nonewline") == 0) {
127 newline = 0;
128 } else {
129 newline = 1;
130 chanObjPtr = objv[1];
131 }
132 string = objv[2];
133 break;
134
135 case 4: /* [puts -nonewline $chan $x] or
136 * [puts $chan $x nonewline] */
137 newline = 0;
138 if (strcmp(TclGetString(objv[1]), "-nonewline") == 0) {
139 chanObjPtr = objv[2];
140 string = objv[3];
141 break;
142 } else if (strcmp(TclGetString(objv[3]), "nonewline") == 0) {
143 /*
144 * The code below provides backwards compatibility with an old
145 * form of the command that is no longer recommended or
146 * documented. See also [Bug #3151675]. Will be removed in Tcl 9,
147 * maybe even earlier.
148 */
149
150 chanObjPtr = objv[1];
151 string = objv[2];
152 break;
153 }
154 /* Fall through */
155 default: /* [puts] or
156 * [puts some bad number of arguments...] */
157 Tcl_WrongNumArgs(interp, 1, objv, "?-nonewline? ?channelId? string");
158 return TCL_ERROR;
159 }
160
161 if (chanObjPtr == NULL) {
162 tsdPtr = TCL_TSD_INIT(&dataKey);
163
164 if (!tsdPtr->initialized) {
165 tsdPtr->initialized = 1;
166 TclNewLiteralStringObj(tsdPtr->stdoutObjPtr, "stdout");
167 Tcl_IncrRefCount(tsdPtr->stdoutObjPtr);
168 Tcl_CreateThreadExitHandler(FinalizeIOCmdTSD, NULL);
169 }
170 chanObjPtr = tsdPtr->stdoutObjPtr;
171 }
172 if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
173 return TCL_ERROR;
174 }
175 if (!(mode & TCL_WRITABLE)) {
176 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
177 "channel \"%s\" wasn't opened for writing",
178 TclGetString(chanObjPtr)));
179 return TCL_ERROR;
180 }
181
182 TclChannelPreserve(chan);
183 result = Tcl_WriteObj(chan, string);
184 if (result < 0) {
185 goto error;
186 }
187 if (newline != 0) {
188 result = Tcl_WriteChars(chan, "\n", 1);
189 if (result < 0) {
190 goto error;
191 }
192 }
193 TclChannelRelease(chan);
194 return TCL_OK;
195
196 /*
197 * TIP #219.
198 * Capture error messages put by the driver into the bypass area and put
199 * them into the regular interpreter result. Fall back to the regular
200 * message if nothing was found in the bypass.
201 */
202
203 error:
204 if (!TclChanCaughtErrorBypass(interp, chan)) {
205 Tcl_SetObjResult(interp, Tcl_ObjPrintf("error writing \"%s\": %s",
206 TclGetString(chanObjPtr), Tcl_PosixError(interp)));
207 }
208 TclChannelRelease(chan);
209 return TCL_ERROR;
210 }
211
212 /*
213 *----------------------------------------------------------------------
214 *
215 * Tcl_FlushObjCmd --
216 *
217 * This function is called to process the Tcl "flush" command. See the
218 * user documentation for details on what it does.
219 *
220 * Results:
221 * A standard Tcl result.
222 *
223 * Side effects:
224 * May cause output to appear on the specified channel.
225 *
226 *----------------------------------------------------------------------
227 */
228
229 /* ARGSUSED */
230 int
231 Tcl_FlushObjCmd(
232 ClientData dummy, /* Not used. */
233 Tcl_Interp *interp, /* Current interpreter. */
234 int objc, /* Number of arguments. */
235 Tcl_Obj *const objv[]) /* Argument objects. */
236 {
237 Tcl_Obj *chanObjPtr;
238 Tcl_Channel chan; /* The channel to flush on. */
239 int mode;
240
241 if (objc != 2) {
242 Tcl_WrongNumArgs(interp, 1, objv, "channelId");
243 return TCL_ERROR;
244 }
245 chanObjPtr = objv[1];
246 if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
247 return TCL_ERROR;
248 }
249 if (!(mode & TCL_WRITABLE)) {
250 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
251 "channel \"%s\" wasn't opened for writing",
252 TclGetString(chanObjPtr)));
253 return TCL_ERROR;
254 }
255
256 TclChannelPreserve(chan);
257 if (Tcl_Flush(chan) != TCL_OK) {
258 /*
259 * TIP #219.
260 * Capture error messages put by the driver into the bypass area and
261 * put them into the regular interpreter result. Fall back to the
262 * regular message if nothing was found in the bypass.
263 */
264
265 if (!TclChanCaughtErrorBypass(interp, chan)) {
266 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
267 "error flushing \"%s\": %s",
268 TclGetString(chanObjPtr), Tcl_PosixError(interp)));
269 }
270 TclChannelRelease(chan);
271 return TCL_ERROR;
272 }
273 TclChannelRelease(chan);
274 return TCL_OK;
275 }
276
277 /*
278 *----------------------------------------------------------------------
279 *
280 * Tcl_GetsObjCmd --
281 *
282 * This function is called to process the Tcl "gets" command. See the
283 * user documentation for details on what it does.
284 *
285 * Results:
286 * A standard Tcl result.
287 *
288 * Side effects:
289 * May consume input from channel.
290 *
291 *----------------------------------------------------------------------
292 */
293
294 /* ARGSUSED */
295 int
296 Tcl_GetsObjCmd(
297 ClientData dummy, /* Not used. */
298 Tcl_Interp *interp, /* Current interpreter. */
299 int objc, /* Number of arguments. */
300 Tcl_Obj *const objv[]) /* Argument objects. */
301 {
302 Tcl_Channel chan; /* The channel to read from. */
303 int lineLen; /* Length of line just read. */
304 int mode; /* Mode in which channel is opened. */
305 Tcl_Obj *linePtr, *chanObjPtr;
306 int code = TCL_OK;
307
308 if ((objc != 2) && (objc != 3)) {
309 Tcl_WrongNumArgs(interp, 1, objv, "channelId ?varName?");
310 return TCL_ERROR;
311 }
312 chanObjPtr = objv[1];
313 if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
314 return TCL_ERROR;
315 }
316 if (!(mode & TCL_READABLE)) {
317 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
318 "channel \"%s\" wasn't opened for reading",
319 TclGetString(chanObjPtr)));
320 return TCL_ERROR;
321 }
322
323 TclChannelPreserve(chan);
324 TclNewObj(linePtr);
325 lineLen = Tcl_GetsObj(chan, linePtr);
326 if (lineLen < 0) {
327 if (!Tcl_Eof(chan) && !Tcl_InputBlocked(chan)) {
328 Tcl_DecrRefCount(linePtr);
329
330 /*
331 * TIP #219.
332 * Capture error messages put by the driver into the bypass area
333 * and put them into the regular interpreter result. Fall back to
334 * the regular message if nothing was found in the bypass.
335 */
336
337 if (!TclChanCaughtErrorBypass(interp, chan)) {
338 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
339 "error reading \"%s\": %s",
340 TclGetString(chanObjPtr), Tcl_PosixError(interp)));
341 }
342 code = TCL_ERROR;
343 goto done;
344 }
345 lineLen = -1;
346 }
347 if (objc == 3) {
348 if (Tcl_ObjSetVar2(interp, objv[2], NULL, linePtr,
349 TCL_LEAVE_ERR_MSG) == NULL) {
350 code = TCL_ERROR;
351 goto done;
352 }
353 Tcl_SetObjResult(interp, Tcl_NewIntObj(lineLen));
354 } else {
355 Tcl_SetObjResult(interp, linePtr);
356 }
357 done:
358 TclChannelRelease(chan);
359 return code;
360 }
361
362 /*
363 *----------------------------------------------------------------------
364 *
365 * Tcl_ReadObjCmd --
366 *
367 * This function is invoked to process the Tcl "read" command. See the
368 * user documentation for details on what it does.
369 *
370 * Results:
371 * A standard Tcl result.
372 *
373 * Side effects:
374 * May consume input from channel.
375 *
376 *----------------------------------------------------------------------
377 */
378
379 /* ARGSUSED */
380 int
381 Tcl_ReadObjCmd(
382 ClientData dummy, /* Not used. */
383 Tcl_Interp *interp, /* Current interpreter. */
384 int objc, /* Number of arguments. */
385 Tcl_Obj *const objv[]) /* Argument objects. */
386 {
387 Tcl_Channel chan; /* The channel to read from. */
388 int newline, i; /* Discard newline at end? */
389 int toRead; /* How many bytes to read? */
390 int charactersRead; /* How many characters were read? */
391 int mode; /* Mode in which channel is opened. */
392 Tcl_Obj *resultPtr, *chanObjPtr;
393
394 if ((objc != 2) && (objc != 3)) {
395 Interp *iPtr;
396
397 argerror:
398 iPtr = (Interp *) interp;
399 Tcl_WrongNumArgs(interp, 1, objv, "channelId ?numChars?");
400
401 /*
402 * Do not append directly; that makes ensembles using this command as
403 * a subcommand produce the wrong message.
404 */
405
406 iPtr->flags |= INTERP_ALTERNATE_WRONG_ARGS;
407 Tcl_WrongNumArgs(interp, 1, objv, "?-nonewline? channelId");
408 return TCL_ERROR;
409 }
410
411 i = 1;
412 newline = 0;
413 if (strcmp(TclGetString(objv[1]), "-nonewline") == 0) {
414 newline = 1;
415 i++;
416 }
417
418 if (i == objc) {
419 goto argerror;
420 }
421
422 chanObjPtr = objv[i];
423 if (TclGetChannelFromObj(interp, chanObjPtr, &chan, &mode, 0) != TCL_OK) {
424 return TCL_ERROR;
425 }
426 if (!(mode & TCL_READABLE)) {
427 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
428 "channel \"%s\" wasn't opened for reading",
429 TclGetString(chanObjPtr)));
430 return TCL_ERROR;
431 }
432 i++; /* Consumed channel name. */
433
434 /*
435 * Compute how many bytes to read.
436 */
437
438 toRead = -1;
439 if (i < objc) {
440 if ((TclGetIntFromObj(interp, objv[i], &toRead) != TCL_OK)
441 || (toRead < 0)) {
442 /*
443 * The code below provides backwards compatibility with an old
444 * form of the command that is no longer recommended or
445 * documented. See also [Bug #3151675]. Will be removed in Tcl 9,
446 * maybe even earlier.
447 */
448
449 if (strcmp(TclGetString(objv[i]), "nonewline") != 0) {
450 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
451 "expected non-negative integer but got \"%s\"",
452 TclGetString(objv[i])));
453 Tcl_SetErrorCode(interp, "TCL", "VALUE", "NUMBER", (char *)NULL);
454 return TCL_ERROR;
455 }
456 newline = 1;
457 }
458 }
459
460 TclNewObj(resultPtr);
461 Tcl_IncrRefCount(resultPtr);
462 TclChannelPreserve(chan);
463 charactersRead = Tcl_ReadChars(chan, resultPtr, toRead, 0);
464 if (charactersRead < 0) {
465 /*
466 * TIP #219.
467 * Capture error messages put by the driver into the bypass area and
468 * put them into the regular interpreter result. Fall back to the
469 * regular message if nothing was found in the bypass.
470 */
471
472 if (!TclChanCaughtErrorBypass(interp, chan)) {
473 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
474 "error reading \"%s\": %s",
475 TclGetString(chanObjPtr), Tcl_PosixError(interp)));
476 }
477 TclChannelRelease(chan);
478 Tcl_DecrRefCount(resultPtr);
479 return TCL_ERROR;
480 }
481
482 /*
483 * If requested, remove the last newline in the channel if at EOF.
484 */
485
486 if ((charactersRead > 0) && (newline != 0)) {
487 const char *result;
488 int length;
489
490 result = TclGetStringFromObj(resultPtr, &length);
491 if (result[length - 1] == '\n') {
492 Tcl_SetObjLength(resultPtr, length - 1);
493 }
494 }
495 Tcl_SetObjResult(interp, resultPtr);
496 TclChannelRelease(chan);
497 Tcl_DecrRefCount(resultPtr);
498 return TCL_OK;
499 }
500
501 /*
502 *----------------------------------------------------------------------
503 *
504 * Tcl_SeekObjCmd --
505 *
506 * This function is invoked to process the Tcl "seek" command. See the
507 * user documentation for details on what it does.
508 *
509 * Results:
510 * A standard Tcl result.
511 *
512 * Side effects:
513 * Moves the position of the access point on the specified channel. May
514 * flush queued output.
515 *
516 *----------------------------------------------------------------------
517 */
518
519 /* ARGSUSED */
520 int
521 Tcl_SeekObjCmd(
522 ClientData clientData, /* Not used. */
523 Tcl_Interp *interp, /* Current interpreter. */
524 int objc, /* Number of arguments. */
525 Tcl_Obj *const objv[]) /* Argument objects. */
526 {
527 Tcl_Channel chan; /* The channel to tell on. */
528 Tcl_WideInt offset; /* Where to seek? */
529 int mode; /* How to seek? */
530 Tcl_WideInt result; /* Of calling Tcl_Seek. */
531 int optionIndex;
532 static const char *const originOptions[] = {
533 "start", "current", "end", NULL
534 };
535 static const int modeArray[] = {SEEK_SET, SEEK_CUR, SEEK_END};
536
537 if ((objc != 3) && (objc != 4)) {
538 Tcl_WrongNumArgs(interp, 1, objv, "channelId offset ?origin?");
539 return TCL_ERROR;
540 }
541 if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
542 return TCL_ERROR;
543 }
544 if (Tcl_GetWideIntFromObj(interp, objv[2], &offset) != TCL_OK) {
545 return TCL_ERROR;
546 }
547 mode = SEEK_SET;
548 if (objc == 4) {
549 if (Tcl_GetIndexFromObj(interp, objv[3], originOptions, "origin", 0,
550 &optionIndex) != TCL_OK) {
551 return TCL_ERROR;
552 }
553 mode = modeArray[optionIndex];
554 }
555
556 TclChannelPreserve(chan);
557 result = Tcl_Seek(chan, offset, mode);
558 if (result == Tcl_LongAsWide(-1)) {
559 /*
560 * TIP #219.
561 * Capture error messages put by the driver into the bypass area and
562 * put them into the regular interpreter result. Fall back to the
563 * regular message if nothing was found in the bypass.
564 */
565
566 if (!TclChanCaughtErrorBypass(interp, chan)) {
567 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
568 "error during seek on \"%s\": %s",
569 TclGetString(objv[1]), Tcl_PosixError(interp)));
570 }
571 TclChannelRelease(chan);
572 return TCL_ERROR;
573 }
574 TclChannelRelease(chan);
575 return TCL_OK;
576 }
577
578 /*
579 *----------------------------------------------------------------------
580 *
581 * Tcl_TellObjCmd --
582 *
583 * This function is invoked to process the Tcl "tell" command. See the
584 * user documentation for details on what it does.
585 *
586 * Results:
587 * A standard Tcl result.
588 *
589 * Side effects:
590 * None.
591 *
592 *----------------------------------------------------------------------
593 */
594
595 /* ARGSUSED */
596 int
597 Tcl_TellObjCmd(
598 ClientData clientData, /* Not used. */
599 Tcl_Interp *interp, /* Current interpreter. */
600 int objc, /* Number of arguments. */
601 Tcl_Obj *const objv[]) /* Argument objects. */
602 {
603 Tcl_Channel chan; /* The channel to tell on. */
604 Tcl_WideInt newLoc;
605 int code;
606
607 if (objc != 2) {
608 Tcl_WrongNumArgs(interp, 1, objv, "channelId");
609 return TCL_ERROR;
610 }
611
612 /*
613 * Try to find a channel with the right name and permissions in the IO
614 * channel table of this interpreter.
615 */
616
617 if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
618 return TCL_ERROR;
619 }
620
621 TclChannelPreserve(chan);
622 newLoc = Tcl_Tell(chan);
623
624 /*
625 * TIP #219.
626 * Capture error messages put by the driver into the bypass area and put
627 * them into the regular interpreter result.
628 */
629
630
631 code = TclChanCaughtErrorBypass(interp, chan);
632 TclChannelRelease(chan);
633 if (code) {
634 return TCL_ERROR;
635 }
636
637 Tcl_SetObjResult(interp, Tcl_NewWideIntObj(newLoc));
638 return TCL_OK;
639 }
640
641 /*
642 *----------------------------------------------------------------------
643 *
644 * Tcl_CloseObjCmd --
645 *
646 * This function is invoked to process the Tcl "close" command. See the
647 * user documentation for details on what it does.
648 *
649 * Results:
650 * A standard Tcl result.
651 *
652 * Side effects:
653 * May discard queued input; may flush queued output.
654 *
655 *----------------------------------------------------------------------
656 */
657
658 /* ARGSUSED */
659 int
660 Tcl_CloseObjCmd(
661 ClientData clientData, /* Not used. */
662 Tcl_Interp *interp, /* Current interpreter. */
663 int objc, /* Number of arguments. */
664 Tcl_Obj *const objv[]) /* Argument objects. */
665 {
666 Tcl_Channel chan; /* The channel to close. */
667 static const char *const dirOptions[] = {
668 "read", "write", NULL
669 };
670 static const int dirArray[] = {TCL_CLOSE_READ, TCL_CLOSE_WRITE};
671
672 if ((objc != 2) && (objc != 3)) {
673 Tcl_WrongNumArgs(interp, 1, objv, "channelId ?direction?");
674 return TCL_ERROR;
675 }
676
677 if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
678 return TCL_ERROR;
679 }
680
681 if (objc == 3) {
682 int index, dir;
683
684 /*
685 * Get direction requested to close, and check syntax.
686 */
687
688 if (Tcl_GetIndexFromObj(interp, objv[2], dirOptions, "direction", 0,
689 &index) != TCL_OK) {
690 return TCL_ERROR;
691 }
692 dir = dirArray[index];
693
694 /*
695 * Check direction against channel mode. It is an error if we try to
696 * close a direction not supported by the channel (already closed, or
697 * never opened for that direction).
698 */
699
700 if (!(dir & Tcl_GetChannelMode(chan))) {
701 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
702 "Half-close of %s-side not possible, side not opened"
703 " or already closed", dirOptions[index]));
704 return TCL_ERROR;
705 }
706
707 /*
708 * Special handling is needed if and only if the channel mode supports
709 * more than the direction to close. Because if the close the last
710 * direction supported we can and will go through the regular
711 * process.
712 */
713
714 if ((Tcl_GetChannelMode(chan) &
715 (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) != dir) {
716 return Tcl_CloseEx(interp, chan, dir);
717 }
718 }
719
720 if (Tcl_UnregisterChannel(interp, chan) != TCL_OK) {
721 /*
722 * If there is an error message and it ends with a newline, remove the
723 * newline. This is done for command pipeline channels where the error
724 * output from the subprocesses is stored in interp's result.
725 *
726 * NOTE: This is likely to not have any effect on regular error
727 * messages produced by drivers during the closing of a channel,
728 * because the Tcl convention is that such error messages do not have
729 * a terminating newline.
730 */
731
732 Tcl_Obj *resultPtr = Tcl_GetObjResult(interp);
733 const char *string;
734 int len;
735
736 if (Tcl_IsShared(resultPtr)) {
737 resultPtr = Tcl_DuplicateObj(resultPtr);
738 Tcl_SetObjResult(interp, resultPtr);
739 }
740 string = TclGetStringFromObj(resultPtr, &len);
741 if ((len > 0) && (string[len - 1] == '\n')) {
742 Tcl_SetObjLength(resultPtr, len - 1);
743 }
744 return TCL_ERROR;
745 }
746
747 return TCL_OK;
748 }
749
750 /*
751 *----------------------------------------------------------------------
752 *
753 * Tcl_FconfigureObjCmd --
754 *
755 * This function is invoked to process the Tcl "fconfigure" command. See
756 * the user documentation for details on what it does.
757 *
758 * Results:
759 * A standard Tcl result.
760 *
761 * Side effects:
762 * May modify the behavior of an IO channel.
763 *
764 *----------------------------------------------------------------------
765 */
766
767 /* ARGSUSED */
768 int
769 Tcl_FconfigureObjCmd(
770 ClientData clientData, /* Not used. */
771 Tcl_Interp *interp, /* Current interpreter. */
772 int objc, /* Number of arguments. */
773 Tcl_Obj *const objv[]) /* Argument objects. */
774 {
775 const char *optionName, *valueName;
776 Tcl_Channel chan; /* The channel to set a mode on. */
777 int i; /* Iterate over arg-value pairs. */
778
779 if ((objc < 2) || (((objc % 2) == 1) && (objc != 3))) {
780 Tcl_WrongNumArgs(interp, 1, objv, "channelId ?-option value ...?");
781 return TCL_ERROR;
782 }
783
784 if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
785 return TCL_ERROR;
786 }
787
788 if (objc == 2) {
789 Tcl_DString ds; /* DString to hold result of calling
790 * Tcl_GetChannelOption. */
791
792 Tcl_DStringInit(&ds);
793 if (Tcl_GetChannelOption(interp, chan, NULL, &ds) != TCL_OK) {
794 Tcl_DStringFree(&ds);
795 return TCL_ERROR;
796 }
797 Tcl_DStringResult(interp, &ds);
798 return TCL_OK;
799 } else if (objc == 3) {
800 Tcl_DString ds; /* DString to hold result of calling
801 * Tcl_GetChannelOption. */
802
803 Tcl_DStringInit(&ds);
804 optionName = TclGetString(objv[2]);
805 if (Tcl_GetChannelOption(interp, chan, optionName, &ds) != TCL_OK) {
806 Tcl_DStringFree(&ds);
807 return TCL_ERROR;
808 }
809 Tcl_DStringResult(interp, &ds);
810 return TCL_OK;
811 }
812
813 for (i = 3; i < objc; i += 2) {
814 optionName = TclGetString(objv[i-1]);
815 valueName = TclGetString(objv[i]);
816 if (Tcl_SetChannelOption(interp, chan, optionName, valueName)
817 != TCL_OK) {
818 return TCL_ERROR;
819 }
820 }
821
822 return TCL_OK;
823 }
824
825 /*
826 *---------------------------------------------------------------------------
827 *
828 * Tcl_EofObjCmd --
829 *
830 * This function is invoked to process the Tcl "eof" command. See the
831 * user documentation for details on what it does.
832 *
833 * Results:
834 * A standard Tcl result.
835 *
836 * Side effects:
837 * Sets interp's result to boolean true or false depending on whether the
838 * specified channel has an EOF condition.
839 *
840 *---------------------------------------------------------------------------
841 */
842
843 /* ARGSUSED */
844 int
845 Tcl_EofObjCmd(
846 ClientData unused, /* Not used. */
847 Tcl_Interp *interp, /* Current interpreter. */
848 int objc, /* Number of arguments. */
849 Tcl_Obj *const objv[]) /* Argument objects. */
850 {
851 Tcl_Channel chan;
852
853 if (objc != 2) {
854 Tcl_WrongNumArgs(interp, 1, objv, "channelId");
855 return TCL_ERROR;
856 }
857
858 if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
859 return TCL_ERROR;
860 }
861
862 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_Eof(chan)));
863 return TCL_OK;
864 }
865
866 /*
867 *----------------------------------------------------------------------
868 *
869 * Tcl_ExecObjCmd --
870 *
871 * This function is invoked to process the "exec" Tcl command. See the
872 * user documentation for details on what it does.
873 *
874 * Results:
875 * A standard Tcl result.
876 *
877 * Side effects:
878 * See the user documentation.
879 *
880 *----------------------------------------------------------------------
881 */
882
883 /* ARGSUSED */
884 int
885 Tcl_ExecObjCmd(
886 ClientData dummy, /* Not used. */
887 Tcl_Interp *interp, /* Current interpreter. */
888 int objc, /* Number of arguments. */
889 Tcl_Obj *const objv[]) /* Argument objects. */
890 {
891 Tcl_Obj *resultPtr;
892 const char **argv; /* An array for the string arguments. Stored
893 * on the _Tcl_ stack. */
894 const char *string;
895 Tcl_Channel chan;
896 int argc, background, i, index, keepNewline, result, skip, length;
897 int ignoreStderr;
898 static const char *const options[] = {
899 "-ignorestderr", "-keepnewline", "--", NULL
900 };
901 enum options {
902 EXEC_IGNORESTDERR, EXEC_KEEPNEWLINE, EXEC_LAST
903 };
904
905 /*
906 * Check for any leading option arguments.
907 */
908
909 keepNewline = 0;
910 ignoreStderr = 0;
911 for (skip = 1; skip < objc; skip++) {
912 string = TclGetString(objv[skip]);
913 if (string[0] != '-') {
914 break;
915 }
916 if (Tcl_GetIndexFromObj(interp, objv[skip], options, "option",
917 TCL_EXACT, &index) != TCL_OK) {
918 return TCL_ERROR;
919 }
920 if (index == EXEC_KEEPNEWLINE) {
921 keepNewline = 1;
922 } else if (index == EXEC_IGNORESTDERR) {
923 ignoreStderr = 1;
924 } else {
925 skip++;
926 break;
927 }
928 }
929 if (objc <= skip) {
930 Tcl_WrongNumArgs(interp, 1, objv, "?-option ...? arg ?arg ...?");
931 return TCL_ERROR;
932 }
933
934 /*
935 * See if the command is to be run in background.
936 */
937
938 background = 0;
939 string = TclGetString(objv[objc - 1]);
940 if ((string[0] == '&') && (string[1] == '\0')) {
941 objc--;
942 background = 1;
943 }
944
945 /*
946 * Create the string argument array "argv". Make sure argv is large enough
947 * to hold the argc arguments plus 1 extra for the zero end-of-argv word.
948 */
949
950 argc = objc - skip;
951 argv = (const char **)TclStackAlloc(interp, (unsigned)(argc + 1) * sizeof(char *));
952
953 /*
954 * Copy the string conversions of each (post option) object into the
955 * argument vector.
956 */
957
958 for (i = 0; i < argc; i++) {
959 argv[i] = TclGetString(objv[i + skip]);
960 }
961 argv[argc] = NULL;
962 chan = Tcl_OpenCommandChannel(interp, argc, argv, (background ? 0 :
963 ignoreStderr ? TCL_STDOUT : TCL_STDOUT|TCL_STDERR));
964
965 /*
966 * Free the argv array.
967 */
968
969 TclStackFree(interp, (void *) argv);
970
971 if (chan == NULL) {
972 return TCL_ERROR;
973 }
974
975 if (background) {
976 /*
977 * Store the list of PIDs from the pipeline in interp's result and
978 * detach the PIDs (instead of waiting for them).
979 */
980
981 TclGetAndDetachPids(interp, chan);
982 if (Tcl_Close(interp, chan) != TCL_OK) {
983 return TCL_ERROR;
984 }
985 return TCL_OK;
986 }
987
988 TclNewObj(resultPtr);
989 if (Tcl_GetChannelHandle(chan, TCL_READABLE, NULL) == TCL_OK) {
990 if (Tcl_ReadChars(chan, resultPtr, -1, 0) < 0) {
991 /*
992 * TIP #219.
993 * Capture error messages put by the driver into the bypass area
994 * and put them into the regular interpreter result. Fall back to
995 * the regular message if nothing was found in the bypass.
996 */
997
998 if (!TclChanCaughtErrorBypass(interp, chan)) {
999 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1000 "error reading output from command: %s",
1001 Tcl_PosixError(interp)));
1002 Tcl_DecrRefCount(resultPtr);
1003 }
1004 return TCL_ERROR;
1005 }
1006 }
1007
1008 /*
1009 * If the process produced anything on stderr, it will have been returned
1010 * in the interpreter result. It needs to be appended to the result
1011 * string.
1012 */
1013
1014 result = Tcl_Close(interp, chan);
1015 Tcl_AppendObjToObj(resultPtr, Tcl_GetObjResult(interp));
1016
1017 /*
1018 * If the last character of the result is a newline, then remove the
1019 * newline character.
1020 */
1021
1022 if (keepNewline == 0) {
1023 string = TclGetStringFromObj(resultPtr, &length);
1024 if ((length > 0) && (string[length - 1] == '\n')) {
1025 Tcl_SetObjLength(resultPtr, length - 1);
1026 }
1027 }
1028 Tcl_SetObjResult(interp, resultPtr);
1029
1030 return result;
1031 }
1032
1033 /*
1034 *---------------------------------------------------------------------------
1035 *
1036 * Tcl_FblockedObjCmd --
1037 *
1038 * This function is invoked to process the Tcl "fblocked" command. See
1039 * the user documentation for details on what it does.
1040 *
1041 * Results:
1042 * A standard Tcl result.
1043 *
1044 * Side effects:
1045 * Sets interp's result to boolean true or false depending on whether the
1046 * preceding input operation on the channel would have blocked.
1047 *
1048 *---------------------------------------------------------------------------
1049 */
1050
1051 /* ARGSUSED */
1052 int
1053 Tcl_FblockedObjCmd(
1054 ClientData unused, /* Not used. */
1055 Tcl_Interp *interp, /* Current interpreter. */
1056 int objc, /* Number of arguments. */
1057 Tcl_Obj *const objv[]) /* Argument objects. */
1058 {
1059 Tcl_Channel chan;
1060 int mode;
1061
1062 if (objc != 2) {
1063 Tcl_WrongNumArgs(interp, 1, objv, "channelId");
1064 return TCL_ERROR;
1065 }
1066
1067 if (TclGetChannelFromObj(interp, objv[1], &chan, &mode, 0) != TCL_OK) {
1068 return TCL_ERROR;
1069 }
1070 if (!(mode & TCL_READABLE)) {
1071 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1072 "channel \"%s\" wasn't opened for reading",
1073 TclGetString(objv[1])));
1074 return TCL_ERROR;
1075 }
1076
1077 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_InputBlocked(chan)));
1078 return TCL_OK;
1079 }
1080
1081 /*
1082 *----------------------------------------------------------------------
1083 *
1084 * Tcl_OpenObjCmd --
1085 *
1086 * This function is invoked to process the "open" Tcl command. See the
1087 * user documentation for details on what it does.
1088 *
1089 * Results:
1090 * A standard Tcl result.
1091 *
1092 * Side effects:
1093 * See the user documentation.
1094 *
1095 *----------------------------------------------------------------------
1096 */
1097
1098 /* ARGSUSED */
1099 int
1100 Tcl_OpenObjCmd(
1101 ClientData notUsed, /* Not used. */
1102 Tcl_Interp *interp, /* Current interpreter. */
1103 int objc, /* Number of arguments. */
1104 Tcl_Obj *const objv[]) /* Argument objects. */
1105 {
1106 int pipeline, prot;
1107 const char *modeString, *what;
1108 Tcl_Channel chan;
1109
1110 if ((objc < 2) || (objc > 4)) {
1111 Tcl_WrongNumArgs(interp, 1, objv, "fileName ?access? ?permissions?");
1112 return TCL_ERROR;
1113 }
1114 prot = 0666;
1115 if (objc == 2) {
1116 modeString = "r";
1117 } else {
1118 modeString = TclGetString(objv[2]);
1119 if (objc == 4) {
1120 const char *permString = TclGetString(objv[3]);
1121 int code = TCL_ERROR;
1122 int scanned = TclParseAllWhiteSpace(permString, -1);
1123
1124 /*
1125 * Support legacy octal numbers.
1126 */
1127
1128 if ((permString[scanned] == '0')
1129 && (permString[scanned+1] >= '0')
1130 && (permString[scanned+1] <= '7')) {
1131 Tcl_Obj *permObj;
1132
1133 TclNewLiteralStringObj(permObj, "0o");
1134 Tcl_AppendToObj(permObj, permString+scanned+1, -1);
1135 code = TclGetIntFromObj(NULL, permObj, &prot);
1136 Tcl_DecrRefCount(permObj);
1137 }
1138
1139 if ((code == TCL_ERROR)
1140 && TclGetIntFromObj(interp, objv[3], &prot) != TCL_OK) {
1141 return TCL_ERROR;
1142 }
1143 }
1144 }
1145
1146 pipeline = 0;
1147 what = TclGetString(objv[1]);
1148 if (what[0] == '|') {
1149 pipeline = 1;
1150 }
1151
1152 /*
1153 * Open the file or create a process pipeline.
1154 */
1155
1156 if (!pipeline) {
1157 chan = Tcl_FSOpenFileChannel(interp, objv[1], modeString, prot);
1158 } else {
1159 int mode, seekFlag, cmdObjc, binary;
1160 const char **cmdArgv;
1161
1162 if (Tcl_SplitList(interp, what+1, &cmdObjc, &cmdArgv) != TCL_OK) {
1163 return TCL_ERROR;
1164 }
1165
1166 mode = TclGetOpenModeEx(interp, modeString, &seekFlag, &binary);
1167 if (mode == -1) {
1168 chan = NULL;
1169 } else {
1170 int flags = TCL_STDERR | TCL_ENFORCE_MODE;
1171
1172 switch (mode & O_ACCMODE) {
1173 case O_RDONLY:
1174 flags |= TCL_STDOUT;
1175 break;
1176 case O_WRONLY:
1177 flags |= TCL_STDIN;
1178 break;
1179 case O_RDWR:
1180 flags |= (TCL_STDIN | TCL_STDOUT);
1181 break;
1182 default:
1183 Tcl_Panic("Tcl_OpenCmd: invalid mode value");
1184 break;
1185 }
1186 chan = Tcl_OpenCommandChannel(interp, cmdObjc, cmdArgv, flags);
1187 if (binary && chan) {
1188 Tcl_SetChannelOption(interp, chan, "-translation", "binary");
1189 }
1190 }
1191 ckfree(cmdArgv);
1192 }
1193 if (chan == NULL) {
1194 return TCL_ERROR;
1195 }
1196 Tcl_RegisterChannel(interp, chan);
1197 Tcl_SetObjResult(interp, Tcl_NewStringObj(Tcl_GetChannelName(chan), -1));
1198 return TCL_OK;
1199 }
1200
1201 /*
1202 *----------------------------------------------------------------------
1203 *
1204 * TcpAcceptCallbacksDeleteProc --
1205 *
1206 * Assocdata cleanup routine called when an interpreter is being deleted
1207 * to set the interp field of all the accept callback records registered
1208 * with the interpreter to NULL. This will prevent the interpreter from
1209 * being used in the future to eval accept scripts.
1210 *
1211 * Results:
1212 * None.
1213 *
1214 * Side effects:
1215 * Deallocates memory and sets the interp field of all the accept
1216 * callback records to NULL to prevent this interpreter from being used
1217 * subsequently to eval accept scripts.
1218 *
1219 *----------------------------------------------------------------------
1220 */
1221
1222 /* ARGSUSED */
1223 static void
1224 TcpAcceptCallbacksDeleteProc(
1225 ClientData clientData, /* Data which was passed when the assocdata
1226 * was registered. */
1227 Tcl_Interp *interp) /* Interpreter being deleted - not used. */
1228 {
1229 Tcl_HashTable *hTblPtr = (Tcl_HashTable *)clientData;
1230 Tcl_HashEntry *hPtr;
1231 Tcl_HashSearch hSearch;
1232
1233 for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
1234 hPtr != NULL; hPtr = Tcl_NextHashEntry(&hSearch)) {
1235 AcceptCallback *acceptCallbackPtr = (AcceptCallback *)Tcl_GetHashValue(hPtr);
1236
1237 acceptCallbackPtr->interp = NULL;
1238 }
1239 Tcl_DeleteHashTable(hTblPtr);
1240 ckfree(hTblPtr);
1241 }
1242
1243 /*
1244 *----------------------------------------------------------------------
1245 *
1246 * RegisterTcpServerInterpCleanup --
1247 *
1248 * Registers an accept callback record to have its interp field set to
1249 * NULL when the interpreter is deleted.
1250 *
1251 * Results:
1252 * None.
1253 *
1254 * Side effects:
1255 * When, in the future, the interpreter is deleted, the interp field of
1256 * the accept callback data structure will be set to NULL. This will
1257 * prevent attempts to eval the accept script in a deleted interpreter.
1258 *
1259 *----------------------------------------------------------------------
1260 */
1261
1262 static void
1263 RegisterTcpServerInterpCleanup(
1264 Tcl_Interp *interp, /* Interpreter for which we want to be
1265 * informed of deletion. */
1266 AcceptCallback *acceptCallbackPtr)
1267 /* The accept callback record whose interp
1268 * field we want set to NULL when the
1269 * interpreter is deleted. */
1270 {
1271 Tcl_HashTable *hTblPtr; /* Hash table for accept callback records to
1272 * smash when the interpreter will be
1273 * deleted. */
1274 Tcl_HashEntry *hPtr; /* Entry for this record. */
1275 int isNew; /* Is the entry new? */
1276
1277 hTblPtr = (Tcl_HashTable *)Tcl_GetAssocData(interp, "tclTCPAcceptCallbacks", NULL);
1278
1279 if (hTblPtr == NULL) {
1280 hTblPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
1281 Tcl_InitHashTable(hTblPtr, TCL_ONE_WORD_KEYS);
1282 Tcl_SetAssocData(interp, "tclTCPAcceptCallbacks",
1283 TcpAcceptCallbacksDeleteProc, hTblPtr);
1284 }
1285
1286 hPtr = Tcl_CreateHashEntry(hTblPtr, acceptCallbackPtr, &isNew);
1287 if (!isNew) {
1288 Tcl_Panic("RegisterTcpServerCleanup: damaged accept record table");
1289 }
1290 Tcl_SetHashValue(hPtr, acceptCallbackPtr);
1291 }
1292
1293 /*
1294 *----------------------------------------------------------------------
1295 *
1296 * UnregisterTcpServerInterpCleanupProc --
1297 *
1298 * Unregister a previously registered accept callback record. The interp
1299 * field of this record will no longer be set to NULL in the future when
1300 * the interpreter is deleted.
1301 *
1302 * Results:
1303 * None.
1304 *
1305 * Side effects:
1306 * Prevents the interp field of the accept callback record from being set
1307 * to NULL in the future when the interpreter is deleted.
1308 *
1309 *----------------------------------------------------------------------
1310 */
1311
1312 static void
1313 UnregisterTcpServerInterpCleanupProc(
1314 Tcl_Interp *interp, /* Interpreter in which the accept callback
1315 * record was registered. */
1316 AcceptCallback *acceptCallbackPtr)
1317 /* The record for which to delete the
1318 * registration. */
1319 {
1320 Tcl_HashTable *hTblPtr;
1321 Tcl_HashEntry *hPtr;
1322
1323 hTblPtr = (Tcl_HashTable *)Tcl_GetAssocData(interp, "tclTCPAcceptCallbacks", NULL);
1324 if (hTblPtr == NULL) {
1325 return;
1326 }
1327
1328 hPtr = Tcl_FindHashEntry(hTblPtr, (char *) acceptCallbackPtr);
1329 if (hPtr != NULL) {
1330 Tcl_DeleteHashEntry(hPtr);
1331 }
1332 }
1333
1334 /*
1335 *----------------------------------------------------------------------
1336 *
1337 * AcceptCallbackProc --
1338 *
1339 * This callback is invoked by the TCP channel driver when it accepts a
1340 * new connection from a client on a server socket.
1341 *
1342 * Results:
1343 * None.
1344 *
1345 * Side effects:
1346 * Whatever the script does.
1347 *
1348 *----------------------------------------------------------------------
1349 */
1350
1351 static void
1352 AcceptCallbackProc(
1353 ClientData callbackData, /* The data stored when the callback was
1354 * created in the call to
1355 * Tcl_OpenTcpServer. */
1356 Tcl_Channel chan, /* Channel for the newly accepted
1357 * connection. */
1358 char *address, /* Address of client that was accepted. */
1359 int port) /* Port of client that was accepted. */
1360 {
1361 AcceptCallback *acceptCallbackPtr = (AcceptCallback *)callbackData;
1362
1363 /*
1364 * Check if the callback is still valid; the interpreter may have gone
1365 * away, this is signalled by setting the interp field of the callback
1366 * data to NULL.
1367 */
1368
1369 if (acceptCallbackPtr->interp != NULL) {
1370 char portBuf[TCL_INTEGER_SPACE];
1371 char *script = acceptCallbackPtr->script;
1372 Tcl_Interp *interp = acceptCallbackPtr->interp;
1373 int result;
1374
1375 Tcl_Preserve(script);
1376 Tcl_Preserve(interp);
1377
1378 TclFormatInt(portBuf, port);
1379 Tcl_RegisterChannel(interp, chan);
1380
1381 /*
1382 * Artificially bump the refcount to protect the channel from being
1383 * deleted while the script is being evaluated.
1384 */
1385
1386 Tcl_RegisterChannel(NULL, chan);
1387
1388 result = Tcl_VarEval(interp, script, " ", Tcl_GetChannelName(chan),
1389 " ", address, " ", portBuf, (char *)NULL);
1390 if (result != TCL_OK) {
1391 Tcl_BackgroundException(interp, result);
1392 Tcl_UnregisterChannel(interp, chan);
1393 }
1394
1395 /*
1396 * Decrement the artificially bumped refcount. After this it is not
1397 * safe anymore to use "chan", because it may now be deleted.
1398 */
1399
1400 Tcl_UnregisterChannel(NULL, chan);
1401
1402 Tcl_Release(interp);
1403 Tcl_Release(script);
1404 } else {
1405 /*
1406 * The interpreter has been deleted, so there is no useful way to use
1407 * the client socket - just close it.
1408 */
1409
1410 Tcl_Close(NULL, chan);
1411 }
1412 }
1413
1414 /*
1415 *----------------------------------------------------------------------
1416 *
1417 * TcpServerCloseProc --
1418 *
1419 * This callback is called when the TCP server channel for which it was
1420 * registered is being closed. It informs the interpreter in which the
1421 * accept script is evaluated (if that interpreter still exists) that
1422 * this channel no longer needs to be informed if the interpreter is
1423 * deleted.
1424 *
1425 * Results:
1426 * None.
1427 *
1428 * Side effects:
1429 * In the future, if the interpreter is deleted this channel will no
1430 * longer be informed.
1431 *
1432 *----------------------------------------------------------------------
1433 */
1434
1435 static void
1436 TcpServerCloseProc(
1437 ClientData callbackData) /* The data passed in the call to
1438 * Tcl_CreateCloseHandler. */
1439 {
1440 AcceptCallback *acceptCallbackPtr = (AcceptCallback *)callbackData;
1441 /* The actual data. */
1442
1443 if (acceptCallbackPtr->interp != NULL) {
1444 UnregisterTcpServerInterpCleanupProc(acceptCallbackPtr->interp,
1445 acceptCallbackPtr);
1446 }
1447 Tcl_EventuallyFree(acceptCallbackPtr->script, TCL_DYNAMIC);
1448 ckfree(acceptCallbackPtr);
1449 }
1450
1451 /*
1452 *----------------------------------------------------------------------
1453 *
1454 * Tcl_SocketObjCmd --
1455 *
1456 * This function is invoked to process the "socket" Tcl command. See the
1457 * user documentation for details on what it does.
1458 *
1459 * Results:
1460 * A standard Tcl result.
1461 *
1462 * Side effects:
1463 * Creates a socket based channel.
1464 *
1465 *----------------------------------------------------------------------
1466 */
1467
1468 int
1469 Tcl_SocketObjCmd(
1470 ClientData notUsed, /* Not used. */
1471 Tcl_Interp *interp, /* Current interpreter. */
1472 int objc, /* Number of arguments. */
1473 Tcl_Obj *const objv[]) /* Argument objects. */
1474 {
1475 static const char *const socketOptions[] = {
1476 "-async", "-myaddr", "-myport", "-server", NULL
1477 };
1478 enum socketOptions {
1479 SKT_ASYNC, SKT_MYADDR, SKT_MYPORT, SKT_SERVER
1480 };
1481 int optionIndex, a, server = 0, port, myport = 0, async = 0;
1482 const char *host, *script = NULL, *myaddr = NULL;
1483 Tcl_Channel chan;
1484
1485 if (TclpHasSockets(interp) != TCL_OK) {
1486 return TCL_ERROR;
1487 }
1488
1489 for (a = 1; a < objc; a++) {
1490 const char *arg = TclGetString(objv[a]);
1491
1492 if (arg[0] != '-') {
1493 break;
1494 }
1495 if (Tcl_GetIndexFromObj(interp, objv[a], socketOptions, "option",
1496 TCL_EXACT, &optionIndex) != TCL_OK) {
1497 return TCL_ERROR;
1498 }
1499 switch ((enum socketOptions) optionIndex) {
1500 case SKT_ASYNC:
1501 if (server == 1) {
1502 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1503 "cannot set -async option for server sockets", -1));
1504 return TCL_ERROR;
1505 }
1506 async = 1;
1507 break;
1508 case SKT_MYADDR:
1509 a++;
1510 if (a >= objc) {
1511 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1512 "no argument given for -myaddr option", -1));
1513 return TCL_ERROR;
1514 }
1515 myaddr = TclGetString(objv[a]);
1516 break;
1517 case SKT_MYPORT: {
1518 const char *myPortName;
1519
1520 a++;
1521 if (a >= objc) {
1522 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1523 "no argument given for -myport option", -1));
1524 return TCL_ERROR;
1525 }
1526 myPortName = TclGetString(objv[a]);
1527 if (TclSockGetPort(interp, myPortName, "tcp", &myport) != TCL_OK) {
1528 return TCL_ERROR;
1529 }
1530 break;
1531 }
1532 case SKT_SERVER:
1533 if (async == 1) {
1534 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1535 "cannot set -async option for server sockets", -1));
1536 return TCL_ERROR;
1537 }
1538 server = 1;
1539 a++;
1540 if (a >= objc) {
1541 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1542 "no argument given for -server option", -1));
1543 return TCL_ERROR;
1544 }
1545 script = TclGetString(objv[a]);
1546 break;
1547 default:
1548 Tcl_Panic("Tcl_SocketObjCmd: bad option index to SocketOptions");
1549 }
1550 }
1551 if (server) {
1552 host = myaddr; /* NULL implies INADDR_ANY */
1553 if (myport != 0) {
1554 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1555 "option -myport is not valid for servers", -1));
1556 return TCL_ERROR;
1557 }
1558 } else if (a < objc) {
1559 host = TclGetString(objv[a]);
1560 a++;
1561 } else {
1562 Interp *iPtr;
1563
1564 wrongNumArgs:
1565 iPtr = (Interp *) interp;
1566 Tcl_WrongNumArgs(interp, 1, objv,
1567 "?-myaddr addr? ?-myport myport? ?-async? host port");
1568 iPtr->flags |= INTERP_ALTERNATE_WRONG_ARGS;
1569 Tcl_WrongNumArgs(interp, 1, objv,
1570 "-server command ?-myaddr addr? port");
1571 return TCL_ERROR;
1572 }
1573
1574 if (a == objc-1) {
1575 if (TclSockGetPort(interp, TclGetString(objv[a]), "tcp",
1576 &port) != TCL_OK) {
1577 return TCL_ERROR;
1578 }
1579 } else {
1580 goto wrongNumArgs;
1581 }
1582
1583 if (server) {
1584 AcceptCallback *acceptCallbackPtr = (AcceptCallback *)
1585 ckalloc(sizeof(AcceptCallback));
1586 unsigned len = strlen(script) + 1;
1587 char *copyScript = (char *)ckalloc(len);
1588
1589 memcpy(copyScript, script, len);
1590 acceptCallbackPtr->script = copyScript;
1591 acceptCallbackPtr->interp = interp;
1592 chan = Tcl_OpenTcpServer(interp, port, host, AcceptCallbackProc,
1593 acceptCallbackPtr);
1594 if (chan == NULL) {
1595 ckfree(copyScript);
1596 ckfree(acceptCallbackPtr);
1597 return TCL_ERROR;
1598 }
1599
1600 /*
1601 * Register with the interpreter to let us know when the interpreter
1602 * is deleted (by having the callback set the interp field of the
1603 * acceptCallbackPtr's structure to NULL). This is to avoid trying to
1604 * eval the script in a deleted interpreter.
1605 */
1606
1607 RegisterTcpServerInterpCleanup(interp, acceptCallbackPtr);
1608
1609 /*
1610 * Register a close callback. This callback will inform the
1611 * interpreter (if it still exists) that this channel does not need to
1612 * be informed when the interpreter is deleted.
1613 */
1614
1615 Tcl_CreateCloseHandler(chan, TcpServerCloseProc, acceptCallbackPtr);
1616 } else {
1617 chan = Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async);
1618 if (chan == NULL) {
1619 return TCL_ERROR;
1620 }
1621 }
1622
1623 Tcl_RegisterChannel(interp, chan);
1624 Tcl_SetObjResult(interp, Tcl_NewStringObj(Tcl_GetChannelName(chan), -1));
1625 return TCL_OK;
1626 }
1627
1628 /*
1629 *----------------------------------------------------------------------
1630 *
1631 * Tcl_FcopyObjCmd --
1632 *
1633 * This function is invoked to process the "fcopy" Tcl command. See the
1634 * user documentation for details on what it does.
1635 *
1636 * Results:
1637 * A standard Tcl result.
1638 *
1639 * Side effects:
1640 * Moves data between two channels and possibly sets up a background copy
1641 * handler.
1642 *
1643 *----------------------------------------------------------------------
1644 */
1645
1646 int
1647 Tcl_FcopyObjCmd(
1648 ClientData dummy, /* Not used. */
1649 Tcl_Interp *interp, /* Current interpreter. */
1650 int objc, /* Number of arguments. */
1651 Tcl_Obj *const objv[]) /* Argument objects. */
1652 {
1653 Tcl_Channel inChan, outChan;
1654 int mode, i, index;
1655 Tcl_WideInt toRead;
1656 Tcl_Obj *cmdPtr;
1657 static const char *const switches[] = { "-size", "-command", NULL };
1658 enum { FcopySize, FcopyCommand };
1659
1660 if ((objc < 3) || (objc > 7) || (objc == 4) || (objc == 6)) {
1661 Tcl_WrongNumArgs(interp, 1, objv,
1662 "input output ?-size size? ?-command callback?");
1663 return TCL_ERROR;
1664 }
1665
1666 /*
1667 * Parse the channel arguments and verify that they are readable or
1668 * writable, as appropriate.
1669 */
1670
1671 if (TclGetChannelFromObj(interp, objv[1], &inChan, &mode, 0) != TCL_OK) {
1672 return TCL_ERROR;
1673 }
1674 if (!(mode & TCL_READABLE)) {
1675 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1676 "channel \"%s\" wasn't opened for reading",
1677 TclGetString(objv[1])));
1678 return TCL_ERROR;
1679 }
1680 if (TclGetChannelFromObj(interp, objv[2], &outChan, &mode, 0) != TCL_OK) {
1681 return TCL_ERROR;
1682 }
1683 if (!(mode & TCL_WRITABLE)) {
1684 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1685 "channel \"%s\" wasn't opened for writing",
1686 TclGetString(objv[2])));
1687 return TCL_ERROR;
1688 }
1689
1690 toRead = -1;
1691 cmdPtr = NULL;
1692 for (i = 3; i < objc; i += 2) {
1693 if (Tcl_GetIndexFromObj(interp, objv[i], switches, "option", 0,
1694 &index) != TCL_OK) {
1695 return TCL_ERROR;
1696 }
1697 switch (index) {
1698 case FcopySize:
1699 if (Tcl_GetWideIntFromObj(interp, objv[i+1], &toRead) != TCL_OK) {
1700 return TCL_ERROR;
1701 }
1702 if (toRead < 0) {
1703 /*
1704 * Handle all negative sizes like -1, meaning 'copy all'. By
1705 * resetting toRead we avoid changes in the core copying
1706 * functions (which explicitly check for -1 and crash on any
1707 * other negative value).
1708 */
1709
1710 toRead = -1;
1711 }
1712 break;
1713 case FcopyCommand:
1714 cmdPtr = objv[i+1];
1715 break;
1716 }
1717 }
1718
1719 return TclCopyChannel(interp, inChan, outChan, toRead, cmdPtr);
1720 }
1721
1722 /*
1723 *---------------------------------------------------------------------------
1724 *
1725 * ChanPendingObjCmd --
1726 *
1727 * This function is invoked to process the Tcl "chan pending" command
1728 * (TIP #287). See the user documentation for details on what it does.
1729 *
1730 * Results:
1731 * A standard Tcl result.
1732 *
1733 * Side effects:
1734 * Sets interp's result to the number of bytes of buffered input or
1735 * output (depending on whether the first argument is "input" or
1736 * "output"), or -1 if the channel wasn't opened for that mode.
1737 *
1738 *---------------------------------------------------------------------------
1739 */
1740
1741 /* ARGSUSED */
1742 static int
1743 ChanPendingObjCmd(
1744 ClientData unused, /* Not used. */
1745 Tcl_Interp *interp, /* Current interpreter. */
1746 int objc, /* Number of arguments. */
1747 Tcl_Obj *const objv[]) /* Argument objects. */
1748 {
1749 Tcl_Channel chan;
1750 int index, mode;
1751 static const char *const options[] = {"input", "output", NULL};
1752 enum options {PENDING_INPUT, PENDING_OUTPUT};
1753
1754 if (objc != 3) {
1755 Tcl_WrongNumArgs(interp, 1, objv, "mode channelId");
1756 return TCL_ERROR;
1757 }
1758
1759 if (Tcl_GetIndexFromObj(interp, objv[1], options, "mode", 0,
1760 &index) != TCL_OK) {
1761 return TCL_ERROR;
1762 }
1763
1764 if (TclGetChannelFromObj(interp, objv[2], &chan, &mode, 0) != TCL_OK) {
1765 return TCL_ERROR;
1766 }
1767
1768 switch ((enum options) index) {
1769 case PENDING_INPUT:
1770 if (!(mode & TCL_READABLE)) {
1771 Tcl_SetObjResult(interp, Tcl_NewIntObj(-1));
1772 } else {
1773 Tcl_SetObjResult(interp, Tcl_NewIntObj(Tcl_InputBuffered(chan)));
1774 }
1775 break;
1776 case PENDING_OUTPUT:
1777 if (!(mode & TCL_WRITABLE)) {
1778 Tcl_SetObjResult(interp, Tcl_NewIntObj(-1));
1779 } else {
1780 Tcl_SetObjResult(interp, Tcl_NewIntObj(Tcl_OutputBuffered(chan)));
1781 }
1782 break;
1783 }
1784 return TCL_OK;
1785 }
1786
1787 /*
1788 *----------------------------------------------------------------------
1789 *
1790 * ChanTruncateObjCmd --
1791 *
1792 * This function is invoked to process the "chan truncate" Tcl command.
1793 * See the user documentation for details on what it does.
1794 *
1795 * Results:
1796 * A standard Tcl result.
1797 *
1798 * Side effects:
1799 * Truncates a channel (or rather a file underlying a channel).
1800 *
1801 *----------------------------------------------------------------------
1802 */
1803
1804 static int
1805 ChanTruncateObjCmd(
1806 ClientData dummy, /* Not used. */
1807 Tcl_Interp *interp, /* Current interpreter. */
1808 int objc, /* Number of arguments. */
1809 Tcl_Obj *const objv[]) /* Argument objects. */
1810 {
1811 Tcl_Channel chan;
1812 Tcl_WideInt length;
1813
1814 if ((objc < 2) || (objc > 3)) {
1815 Tcl_WrongNumArgs(interp, 1, objv, "channelId ?length?");
1816 return TCL_ERROR;
1817 }
1818 if (TclGetChannelFromObj(interp, objv[1], &chan, NULL, 0) != TCL_OK) {
1819 return TCL_ERROR;
1820 }
1821
1822 if (objc == 3) {
1823 /*
1824 * User is supplying an explicit length.
1825 */
1826
1827 if (Tcl_GetWideIntFromObj(interp, objv[2], &length) != TCL_OK) {
1828 return TCL_ERROR;
1829 }
1830 if (length < 0) {
1831 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1832 "cannot truncate to negative length of file", -1));
1833 return TCL_ERROR;
1834 }
1835 } else {
1836 /*
1837 * User wants to truncate to the current file position.
1838 */
1839
1840 length = Tcl_Tell(chan);
1841 if (length == Tcl_WideAsLong(-1)) {
1842 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1843 "could not determine current location in \"%s\": %s",
1844 TclGetString(objv[1]), Tcl_PosixError(interp)));
1845 return TCL_ERROR;
1846 }
1847 }
1848
1849 if (Tcl_TruncateChannel(chan, length) != TCL_OK) {
1850 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1851 "error during truncate on \"%s\": %s",
1852 TclGetString(objv[1]), Tcl_PosixError(interp)));
1853 return TCL_ERROR;
1854 }
1855
1856 return TCL_OK;
1857 }
1858
1859 /*
1860 *----------------------------------------------------------------------
1861 *
1862 * ChanPipeObjCmd --
1863 *
1864 * This function is invoked to process the "chan pipe" Tcl command.
1865 * See the user documentation for details on what it does.
1866 *
1867 * Results:
1868 * A standard Tcl result.
1869 *
1870 * Side effects:
1871 * Creates a pair of Tcl channels wrapping both ends of a new
1872 * anonymous pipe.
1873 *
1874 *----------------------------------------------------------------------
1875 */
1876
1877 static int
1878 ChanPipeObjCmd(
1879 ClientData dummy, /* Not used. */
1880 Tcl_Interp *interp, /* Current interpreter. */
1881 int objc, /* Number of arguments. */
1882 Tcl_Obj *const objv[]) /* Argument objects. */
1883 {
1884 Tcl_Channel rchan, wchan;
1885 const char *channelNames[2];
1886 Tcl_Obj *resultPtr;
1887
1888 if (objc != 1) {
1889 Tcl_WrongNumArgs(interp, 1, objv, "");
1890 return TCL_ERROR;
1891 }
1892
1893 if (Tcl_CreatePipe(interp, &rchan, &wchan, 0) != TCL_OK) {
1894 return TCL_ERROR;
1895 }
1896
1897 channelNames[0] = Tcl_GetChannelName(rchan);
1898 channelNames[1] = Tcl_GetChannelName(wchan);
1899
1900 TclNewObj(resultPtr);
1901 Tcl_ListObjAppendElement(NULL, resultPtr,
1902 Tcl_NewStringObj(channelNames[0], -1));
1903 Tcl_ListObjAppendElement(NULL, resultPtr,
1904 Tcl_NewStringObj(channelNames[1], -1));
1905 Tcl_SetObjResult(interp, resultPtr);
1906
1907 return TCL_OK;
1908 }
1909
1910 /*
1911 *----------------------------------------------------------------------
1912 *
1913 * TclChannelNamesCmd --
1914 *
1915 * This function is invoked to process the "chan names" and "file
1916 * channels" Tcl commands. See the user documentation for details on
1917 * what they do.
1918 *
1919 * Results:
1920 * A standard Tcl result.
1921 *
1922 * Side effects:
1923 * None.
1924 *
1925 *----------------------------------------------------------------------
1926 */
1927
1928 int
1929 TclChannelNamesCmd(
1930 ClientData clientData,
1931 Tcl_Interp *interp,
1932 int objc,
1933 Tcl_Obj *const objv[])
1934 {
1935 if (objc < 1 || objc > 2) {
1936 Tcl_WrongNumArgs(interp, 1, objv, "?pattern?");
1937 return TCL_ERROR;
1938 }
1939 return Tcl_GetChannelNamesEx(interp,
1940 ((objc == 1) ? NULL : TclGetString(objv[1])));
1941 }
1942
1943 /*
1944 *----------------------------------------------------------------------
1945 *
1946 * TclInitChanCmd --
1947 *
1948 * This function is invoked to create the "chan" Tcl command. See the
1949 * user documentation for details on what it does.
1950 *
1951 * Results:
1952 * A Tcl command handle.
1953 *
1954 * Side effects:
1955 * None (since nothing is byte-compiled).
1956 *
1957 *----------------------------------------------------------------------
1958 */
1959
1960 Tcl_Command
1961 TclInitChanCmd(
1962 Tcl_Interp *interp)
1963 {
1964 /*
1965 * Most commands are plugged directly together, but some are done via
1966 * alias-like rewriting; [chan configure] is this way for security reasons
1967 * (want overwriting of [fconfigure] to control that nicely), and [chan
1968 * names] because the functionality isn't available as a separate command
1969 * function at the moment.
1970 */
1971 static const EnsembleImplMap initMap[] = {
1972 {"blocked", Tcl_FblockedObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
1973 {"close", Tcl_CloseObjCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0},
1974 {"copy", Tcl_FcopyObjCmd, NULL, NULL, NULL, 0},
1975 {"create", TclChanCreateObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #219 */
1976 {"eof", Tcl_EofObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
1977 {"event", Tcl_FileEventObjCmd, TclCompileBasic2Or3ArgCmd, NULL, NULL, 0},
1978 {"flush", Tcl_FlushObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
1979 {"gets", Tcl_GetsObjCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0},
1980 {"names", TclChannelNamesCmd, TclCompileBasic0Or1ArgCmd, NULL, NULL, 0},
1981 {"pending", ChanPendingObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #287 */
1982 {"pipe", ChanPipeObjCmd, TclCompileBasic0ArgCmd, NULL, NULL, 0}, /* TIP #304 */
1983 {"pop", TclChanPopObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0}, /* TIP #230 */
1984 {"postevent", TclChanPostEventObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #219 */
1985 {"push", TclChanPushObjCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0}, /* TIP #230 */
1986 {"puts", Tcl_PutsObjCmd, NULL, NULL, NULL, 0},
1987 {"read", Tcl_ReadObjCmd, NULL, NULL, NULL, 0},
1988 {"seek", Tcl_SeekObjCmd, TclCompileBasic2Or3ArgCmd, NULL, NULL, 0},
1989 {"tell", Tcl_TellObjCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
1990 {"truncate", ChanTruncateObjCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0}, /* TIP #208 */
1991 {NULL, NULL, NULL, NULL, NULL, 0}
1992 };
1993 static const char *const extras[] = {
1994 "configure", "::fconfigure",
1995 NULL
1996 };
1997 Tcl_Command ensemble;
1998 Tcl_Obj *mapObj;
1999 int i;
2000
2001 ensemble = TclMakeEnsemble(interp, "chan", initMap);
2002 Tcl_GetEnsembleMappingDict(NULL, ensemble, &mapObj);
2003 for (i=0 ; extras[i] ; i+=2) {
2004 /*
2005 * Can assume that reference counts are all incremented.
2006 */
2007
2008 TclDictPutString(NULL, mapObj, extras[i], extras[i + 1]);
2009 }
2010 Tcl_SetEnsembleMappingDict(interp, ensemble, mapObj);
2011 return ensemble;
2012 }
2013
2014 /*
2015 * Local Variables:
2016 * mode: c
2017 * c-basic-offset: 4
2018 * fill-column: 78
2019 * End:
2020 */