Debian Codegraph @

pTk/mTk/unix/tkUnixSend.c

raw symbols SCIP
1 /*
2 * tkUnixSend.c --
3 *
4 * This file provides procedures that implement the "send"
5 * command, allowing commands to be passed from interpreter
6 * to interpreter.
7 *
8 * Copyright (c) 1989-1994 The Regents of the University of California.
9 * Copyright (c) 1994-1996 Sun Microsystems, Inc.
10 * Copyright (c) 1998-1999 by Scriptics Corporation.
11 *
12 * See the file "license.terms" for information on usage and redistribution
13 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 *
15 * RCS: @(#) $Id: tkUnixSend.c,v 1.11 2002/08/13 16:20:49 rmax Exp $
16 */
17
18 #include "tkPort.h"
19 #include "tkInt.h"
20 #include "tkUnixInt.h"
21
22 /*
23 * The following structure is used to keep track of the interpreters
24 * registered by this process.
25 */
26
27 typedef struct RegisteredInterp {
28 char *name; /* Interpreter's name (malloc-ed). */
29 Tcl_Interp *interp; /* Interpreter associated with name. NULL
30 * means that the application was unregistered
31 * or deleted while a send was in progress
32 * to it. */
33 TkDisplay *dispPtr; /* Display for the application. Needed
34 * because we may need to unregister the
35 * interpreter after its main window has
36 * been deleted. */
37 struct RegisteredInterp *nextPtr;
38 /* Next in list of names associated
39 * with interps in this process.
40 * NULL means end of list. */
41 } RegisteredInterp;
42
43 /*
44 * A registry of all interpreters for a display is kept in a
45 * property "InterpRegistry" on the root window of the display.
46 * It is organized as a series of zero or more concatenated strings
47 * (in no particular order), each of the form
48 * window space name '\0'
49 * where "window" is the hex id of the comm. window to use to talk
50 * to an interpreter named "name".
51 *
52 * When the registry is being manipulated by an application (e.g. to
53 * add or remove an entry), it is loaded into memory using a structure
54 * of the following type:
55 */
56
57 typedef struct NameRegistry {
58 TkDisplay *dispPtr; /* Display from which the registry was
59 * read. */
60 int locked; /* Non-zero means that the display was
61 * locked when the property was read in. */
62 int modified; /* Non-zero means that the property has
63 * been modified, so it needs to be written
64 * out when the NameRegistry is closed. */
65 unsigned long propLength; /* Length of the property, in bytes. */
66 char *property; /* The contents of the property, or NULL
67 * if none. See format description above;
68 * this is *not* terminated by the first
69 * null character. Dynamically allocated. */
70 int allocedByX; /* Non-zero means must free property with
71 * XFree; zero means use ckfree. */
72 } NameRegistry;
73
74 /*
75 * When a result is being awaited from a sent command, one of
76 * the following structures is present on a list of all outstanding
77 * sent commands. The information in the structure is used to
78 * process the result when it arrives. You're probably wondering
79 * how there could ever be multiple outstanding sent commands.
80 * This could happen if interpreters invoke each other recursively.
81 * It's unlikely, but possible.
82 */
83
84 typedef struct PendingCommand {
85 int serial; /* Serial number expected in
86 * result. */
87 TkDisplay *dispPtr; /* Display being used for communication. */
88 CONST char *target; /* Name of interpreter command is
89 * being sent to. */
90 Window commWindow; /* Target's communication window. */
91 Tcl_Interp *interp; /* Interpreter from which the send
92 * was invoked. */
93 int code; /* Tcl return code for command
94 * will be stored here. */
95 char *result; /* String result for command (malloc'ed),
96 * or NULL. */
97 char *errorInfo; /* Information for "errorInfo" variable,
98 * or NULL (malloc'ed). */
99 char *errorCode; /* Information for "errorCode" variable,
100 * or NULL (malloc'ed). */
101 int gotResponse; /* 1 means a response has been received,
102 * 0 means the command is still outstanding. */
103 struct PendingCommand *nextPtr;
104 /* Next in list of all outstanding
105 * commands. NULL means end of
106 * list. */
107 } PendingCommand;
108
109 typedef struct ThreadSpecificData {
110 PendingCommand *pendingCommands;
111 /* List of all commands currently
112 * being waited for. */
113 RegisteredInterp *interpListPtr;
114 /* List of all interpreters registered
115 * in the current process. */
116 } ThreadSpecificData;
117 static Tcl_ThreadDataKey dataKey;
118
119 /*
120 * The information below is used for communication between processes
121 * during "send" commands. Each process keeps a private window, never
122 * even mapped, with one property, "Comm". When a command is sent to
123 * an interpreter, the command is appended to the comm property of the
124 * communication window associated with the interp's process. Similarly,
125 * when a result is returned from a sent command, it is also appended
126 * to the comm property.
127 *
128 * Each command and each result takes the form of ASCII text. For a
129 * command, the text consists of a zero character followed by several
130 * null-terminated ASCII strings. The first string consists of the
131 * single letter "c". Subsequent strings have the form "option value"
132 * where the following options are supported:
133 *
134 * -r commWindow serial
135 *
136 * This option means that a response should be sent to the window
137 * whose X identifier is "commWindow" (in hex), and the response should
138 * be identified with the serial number given by "serial" (in decimal).
139 * If this option isn't specified then the send is asynchronous and
140 * no response is sent.
141 *
142 * -n name
143 * "Name" gives the name of the application for which the command is
144 * intended. This option must be present.
145 *
146 * -s script
147 *
148 * "Script" is the script to be executed. This option must be present.
149 *
150 * The options may appear in any order. The -n and -s options must be
151 * present, but -r may be omitted for asynchronous RPCs. For compatibility
152 * with future releases that may add new features, there may be additional
153 * options present; as long as they start with a "-" character, they will
154 * be ignored.
155 *
156 * A result also consists of a zero character followed by several null-
157 * terminated ASCII strings. The first string consists of the single
158 * letter "r". Subsequent strings have the form "option value" where
159 * the following options are supported:
160 *
161 * -s serial
162 *
163 * Identifies the command for which this is the result. It is the
164 * same as the "serial" field from the -s option in the command. This
165 * option must be present.
166 *
167 * -c code
168 *
169 * "Code" is the completion code for the script, in decimal. If the
170 * code is omitted it defaults to TCL_OK.
171 *
172 * -r result
173 *
174 * "Result" is the result string for the script, which may be either
175 * a result or an error message. If this field is omitted then it
176 * defaults to an empty string.
177 *
178 * -i errorInfo
179 *
180 * "ErrorInfo" gives a string with which to initialize the errorInfo
181 * variable. This option may be omitted; it is ignored unless the
182 * completion code is TCL_ERROR.
183 *
184 * -e errorCode
185 *
186 * "ErrorCode" gives a string with with to initialize the errorCode
187 * variable. This option may be omitted; it is ignored unless the
188 * completion code is TCL_ERROR.
189 *
190 * Options may appear in any order, and only the -s option must be
191 * present. As with commands, there may be additional options besides
192 * these; unknown options are ignored.
193 */
194
195 /*
196 * The following variable is the serial number that was used in the
197 * last "send" command. It is exported only for testing purposes.
198 */
199
200 int tkSendSerial = 0;
201
202 /*
203 * Maximum size property that can be read at one time by
204 * this module:
205 */
206
207 #define MAX_PROP_WORDS 100000
208
209 /*
210 * The following variable can be set while debugging to do things like
211 * skip locking the server.
212 */
213
214 static int sendDebug = 0;
215
216 /*
217 * Forward declarations for procedures defined later in this file:
218 */
219
220 static int AppendErrorProc _ANSI_ARGS_((ClientData clientData,
221 XErrorEvent *errorPtr));
222 static void AppendPropCarefully _ANSI_ARGS_((Display *display,
223 Window window, Atom property, char *value,
224 int length, PendingCommand *pendingPtr));
225 static void DeleteProc _ANSI_ARGS_((ClientData clientData));
226 static void RegAddName _ANSI_ARGS_((NameRegistry *regPtr,
227 CONST char *name, Window commWindow));
228 static void RegClose _ANSI_ARGS_((NameRegistry *regPtr));
229 static void RegDeleteName _ANSI_ARGS_((NameRegistry *regPtr,
230 CONST char *name));
231 static Window RegFindName _ANSI_ARGS_((NameRegistry *regPtr,
232 CONST char *name));
233 static NameRegistry * RegOpen _ANSI_ARGS_((Tcl_Interp *interp,
234 TkDisplay *dispPtr, int lock));
235 static void SendEventProc _ANSI_ARGS_((ClientData clientData,
236 XEvent *eventPtr));
237 static int SendInit _ANSI_ARGS_((Tcl_Interp *interp,
238 TkDisplay *dispPtr));
239 static Tk_RestrictAction SendRestrictProc _ANSI_ARGS_((ClientData clientData,
240 XEvent *eventPtr));
241 static int ServerSecure _ANSI_ARGS_((TkDisplay *dispPtr));
242 static void UpdateCommWindow _ANSI_ARGS_((TkDisplay *dispPtr));
243 static int ValidateName _ANSI_ARGS_((TkDisplay *dispPtr,
244 CONST char *name, Window commWindow, int oldOK));
245
246 /*
247 *----------------------------------------------------------------------
248 *
249 * RegOpen --
250 *
251 * This procedure loads the name registry for a display into
252 * memory so that it can be manipulated.
253 *
254 * Results:
255 * The return value is a pointer to the loaded registry.
256 *
257 * Side effects:
258 * If "lock" is set then the server will be locked. It is the
259 * caller's responsibility to call RegClose when finished with
260 * the registry, so that we can write back the registry if
261 * needed, unlock the server if needed, and free memory.
262 *
263 *----------------------------------------------------------------------
264 */
265
266 static NameRegistry *
267 RegOpen(interp, dispPtr, lock)
268 Tcl_Interp *interp; /* Interpreter to use for error reporting
269 * (errors cause a panic so in fact no
270 * error is ever returned, but the interpreter
271 * is needed anyway). */
272 TkDisplay *dispPtr; /* Display whose name registry is to be
273 * opened. */
274 int lock; /* Non-zero means lock the window server
275 * when opening the registry, so no-one
276 * else can use the registry until we
277 * close it. */
278 {
279 NameRegistry *regPtr;
280 int result, actualFormat;
281 unsigned long bytesAfter;
282 Atom actualType;
283
284 if (dispPtr->commTkwin == NULL) {
285 SendInit(interp, dispPtr);
286 }
287
288 regPtr = (NameRegistry *) ckalloc(sizeof(NameRegistry));
289 regPtr->dispPtr = dispPtr;
290 regPtr->locked = 0;
291 regPtr->modified = 0;
292 regPtr->allocedByX = 1;
293
294 if (lock && !sendDebug) {
295 XGrabServer(dispPtr->display);
296 regPtr->locked = 1;
297 }
298
299 /*
300 * Read the registry property.
301 */
302
303 result = XGetWindowProperty(dispPtr->display,
304 RootWindow(dispPtr->display, 0),
305 dispPtr->registryProperty, 0, MAX_PROP_WORDS,
306 False, XA_STRING, &actualType, &actualFormat,
307 &regPtr->propLength, &bytesAfter,
308 (unsigned char **) &regPtr->property);
309
310 if (actualType == None) {
311 regPtr->propLength = 0;
312 regPtr->property = NULL;
313 } else if ((result != Success) || (actualFormat != 8)
314 || (actualType != XA_STRING)) {
315 /*
316 * The property is improperly formed; delete it.
317 */
318
319 if (regPtr->property != NULL) {
320 XFree(regPtr->property);
321 regPtr->propLength = 0;
322 regPtr->property = NULL;
323 }
324 XDeleteProperty(dispPtr->display,
325 RootWindow(dispPtr->display, 0),
326 dispPtr->registryProperty);
327 }
328
329 /*
330 * Xlib placed an extra null byte after the end of the property, just
331 * to make sure that it is always NULL-terminated. Be sure to include
332 * this byte in our count if it's needed to ensure null termination
333 * (note: as of 8/95 I'm no longer sure why this code is needed; seems
334 * like it shouldn't be).
335 */
336
337 if ((regPtr->propLength > 0)
338 && (regPtr->property[regPtr->propLength-1] != 0)) {
339 regPtr->propLength++;
340 }
341 return regPtr;
342 }
343
344 /*
345 *----------------------------------------------------------------------
346 *
347 * RegFindName --
348 *
349 * Given an open name registry, this procedure finds an entry
350 * with a given name, if there is one, and returns information
351 * about that entry.
352 *
353 * Results:
354 * The return value is the X identifier for the comm window for
355 * the application named "name", or None if there is no such
356 * entry in the registry.
357 *
358 * Side effects:
359 * None.
360 *
361 *----------------------------------------------------------------------
362 */
363
364 static Window
365 RegFindName(regPtr, name)
366 NameRegistry *regPtr; /* Pointer to a registry opened with a
367 * previous call to RegOpen. */
368 CONST char *name; /* Name of an application. */
369 {
370 char *p, *entry;
371 unsigned int id;
372
373 for (p = regPtr->property; (p-regPtr->property) < (int) regPtr->propLength; ) {
374 entry = p;
375 while ((*p != 0) && (!isspace(UCHAR(*p)))) {
376 p++;
377 }
378 if ((*p != 0) && (strcmp(name, p+1) == 0)) {
379 if (sscanf(entry, "%x", &id) == 1) {
380 /*
381 * Must cast from an unsigned int to a Window in case we
382 * are on a 64-bit architecture.
383 */
384
385 return (Window) id;
386 }
387 }
388 while (*p != 0) {
389 p++;
390 }
391 p++;
392 }
393 return None;
394 }
395
396 /*
397 *----------------------------------------------------------------------
398 *
399 * RegDeleteName --
400 *
401 * This procedure deletes the entry for a given name from
402 * an open registry.
403 *
404 * Results:
405 * None.
406 *
407 * Side effects:
408 * If there used to be an entry named "name" in the registry,
409 * then it is deleted and the registry is marked as modified
410 * so it will be written back when closed.
411 *
412 *----------------------------------------------------------------------
413 */
414
415 static void
416 RegDeleteName(regPtr, name)
417 NameRegistry *regPtr; /* Pointer to a registry opened with a
418 * previous call to RegOpen. */
419 CONST char *name; /* Name of an application. */
420 {
421 char *p, *entry, *entryName;
422 int count;
423
424 for (p = regPtr->property; (p-regPtr->property) < (int) regPtr->propLength; ) {
425 entry = p;
426 while ((*p != 0) && (!isspace(UCHAR(*p)))) {
427 p++;
428 }
429 if (*p != 0) {
430 p++;
431 }
432 entryName = p;
433 while (*p != 0) {
434 p++;
435 }
436 p++;
437 if ((strcmp(name, entryName) == 0)) {
438 /*
439 * Found the matching entry. Copy everything after it
440 * down on top of it.
441 */
442
443 count = regPtr->propLength - (p - regPtr->property);
444 if (count > 0) {
445 char *src, *dst;
446
447 for (src = p, dst = entry; count > 0; src++, dst++, count--) {
448 *dst = *src;
449 }
450 }
451 regPtr->propLength -= p - entry;
452 regPtr->modified = 1;
453 return;
454 }
455 }
456 }
457
458 /*
459 *----------------------------------------------------------------------
460 *
461 * RegAddName --
462 *
463 * Add a new entry to an open registry.
464 *
465 * Results:
466 * None.
467 *
468 * Side effects:
469 * The open registry is expanded; it is marked as modified so that
470 * it will be written back when closed.
471 *
472 *----------------------------------------------------------------------
473 */
474
475 static void
476 RegAddName(regPtr, name, commWindow)
477 NameRegistry *regPtr; /* Pointer to a registry opened with a
478 * previous call to RegOpen. */
479 CONST char *name; /* Name of an application. The caller
480 * must ensure that this name isn't
481 * already registered. */
482 Window commWindow; /* X identifier for comm. window of
483 * application. */
484 {
485 char id[30];
486 char *newProp;
487 int idLength, newBytes;
488
489 sprintf(id, "%x ", (unsigned int) commWindow);
490 idLength = strlen(id);
491 newBytes = idLength + strlen(name) + 1;
492 newProp = (char *) ckalloc((unsigned) (regPtr->propLength + newBytes));
493 strcpy(newProp, id);
494 strcpy(newProp+idLength, name);
495 if (regPtr->property != NULL) {
496 memcpy((VOID *) (newProp + newBytes), (VOID *) regPtr->property,
497 regPtr->propLength);
498 if (regPtr->allocedByX) {
499 XFree(regPtr->property);
500 } else {
501 ckfree(regPtr->property);
502 }
503 }
504 regPtr->modified = 1;
505 regPtr->propLength += newBytes;
506 regPtr->property = newProp;
507 regPtr->allocedByX = 0;
508 }
509
510 /*
511 *----------------------------------------------------------------------
512 *
513 * RegClose --
514 *
515 * This procedure is called to end a series of operations on
516 * a name registry.
517 *
518 * Results:
519 * None.
520 *
521 * Side effects:
522 * The registry is written back if it has been modified, and the
523 * X server is unlocked if it was locked. Memory for the
524 * registry is freed, so the caller should never use regPtr
525 * again.
526 *
527 *----------------------------------------------------------------------
528 */
529
530 static void
531 RegClose(regPtr)
532 NameRegistry *regPtr; /* Pointer to a registry opened with a
533 * previous call to RegOpen. */
534 {
535 if (regPtr->modified) {
536 if (!regPtr->locked && !sendDebug) {
537 panic("The name registry was modified without being locked!");
538 }
539 XChangeProperty(regPtr->dispPtr->display,
540 RootWindow(regPtr->dispPtr->display, 0),
541 regPtr->dispPtr->registryProperty, XA_STRING, 8,
542 PropModeReplace, (unsigned char *) regPtr->property,
543 (int) regPtr->propLength);
544 }
545
546 if (regPtr->locked) {
547 XUngrabServer(regPtr->dispPtr->display);
548 }
549
550 /*
551 * After ungrabbing the server, it's important to flush the output
552 * immediately so that the server sees the ungrab command. Otherwise
553 * we might do something else that needs to communicate with the
554 * server (such as invoking a subprocess that needs to do I/O to
555 * the screen); if the ungrab command is still sitting in our
556 * output buffer, we could deadlock.
557 */
558
559 XFlush(regPtr->dispPtr->display);
560
561 if (regPtr->property != NULL) {
562 if (regPtr->allocedByX) {
563 XFree(regPtr->property);
564 } else {
565 ckfree(regPtr->property);
566 }
567 }
568 ckfree((char *) regPtr);
569 }
570
571 /*
572 *----------------------------------------------------------------------
573 *
574 * ValidateName --
575 *
576 * This procedure checks to see if an entry in the registry
577 * is still valid.
578 *
579 * Results:
580 * The return value is 1 if the given commWindow exists and its
581 * name is "name". Otherwise 0 is returned.
582 *
583 * Side effects:
584 * None.
585 *
586 *----------------------------------------------------------------------
587 */
588
589 static int
590 ValidateName(dispPtr, name, commWindow, oldOK)
591 TkDisplay *dispPtr; /* Display for which to perform the
592 * validation. */
593 CONST char *name; /* The name of an application. */
594 Window commWindow; /* X identifier for the application's
595 * comm. window. */
596 int oldOK; /* Non-zero means that we should consider
597 * an application to be valid even if it
598 * looks like an old-style (pre-4.0) one;
599 * 0 means consider these invalid. */
600 {
601 int result, actualFormat, argc, i;
602 unsigned long length, bytesAfter;
603 Atom actualType;
604 char *property;
605 Tk_ErrorHandler handler;
606 Tcl_Obj **objv;
607
608 property = NULL;
609
610 /*
611 * Ignore X errors when reading the property (e.g., the window
612 * might not exist). If an error occurs, result will be some
613 * value other than Success.
614 */
615
616 handler = Tk_CreateErrorHandler(dispPtr->display, -1, -1, -1,
617 (Tk_ErrorProc *) NULL, (ClientData) NULL);
618 result = XGetWindowProperty(dispPtr->display, commWindow,
619 dispPtr->appNameProperty, 0, MAX_PROP_WORDS,
620 False, XA_STRING, &actualType, &actualFormat,
621 &length, &bytesAfter, (unsigned char **) &property);
622
623 if ((result == Success) && (actualType == None)) {
624 XWindowAttributes atts;
625
626 /*
627 * The comm. window exists but the property we're looking for
628 * doesn't exist. This probably means that the application
629 * comes from an older version of Tk (< 4.0) that didn't set the
630 * property; if this is the case, then assume for compatibility's
631 * sake that everything's OK. However, it's also possible that
632 * some random application has re-used the window id for something
633 * totally unrelated. Check a few characteristics of the window,
634 * such as its dimensions and mapped state, to be sure that it
635 * still "smells" like a commWindow.
636 */
637
638 if (!oldOK
639 || !XGetWindowAttributes(dispPtr->display, commWindow, &atts)
640 || (atts.width != 1) || (atts.height != 1)
641 || (atts.map_state != IsUnmapped)) {
642 result = 0;
643 } else {
644 result = 1;
645 }
646 } else if ((result == Success) && (actualFormat == 8)
647 && (actualType == XA_STRING)) {
648 Tcl_Obj *temp = Tcl_NewStringObj(property,strlen(property));
649 result = 0;
650 if (Tcl_ListObjGetElements((Tcl_Interp *) NULL, temp, &argc, &objv)
651 == TCL_OK) {
652 for (i = 0; i < argc; i++) {
653 if (strcmp(Tcl_GetStringFromObj(objv[i],NULL), name) == 0) {
654 result = 1;
655 break;
656 }
657 }
658 }
659 Tcl_DecrRefCount(temp);
660 } else {
661 result = 0;
662 }
663 Tk_DeleteErrorHandler(handler);
664 if (property != NULL) {
665 XFree(property);
666 }
667 return result;
668 }
669
670 /*
671 *----------------------------------------------------------------------
672 *
673 * ServerSecure --
674 *
675 * Check whether a server is secure enough for us to trust
676 * Tcl scripts arriving via that server.
677 *
678 * Results:
679 * The return value is 1 if the server is secure, which means
680 * that host-style authentication is turned on but there are
681 * no hosts in the enabled list. This means that some other
682 * form of authorization (presumably more secure, such as xauth)
683 * is in use.
684 *
685 * Side effects:
686 * None.
687 *
688 *----------------------------------------------------------------------
689 */
690
691 static int
692 ServerSecure(dispPtr)
693 TkDisplay *dispPtr; /* Display to check. */
694 {
695 #ifdef TK_NO_SECURITY
696 return 1;
697 #else
698 XHostAddress *addrPtr;
699 int numHosts, secure;
700 Bool enabled;
701
702 secure = 0;
703 addrPtr = XListHosts(dispPtr->display, &numHosts, &enabled);
704 if (enabled && (numHosts == 0)) {
705 secure = 1;
706 }
707 if (addrPtr != NULL) {
708 XFree((char *) addrPtr);
709 }
710 return secure;
711 #endif /* TK_NO_SECURITY */
712 }
713
714 /*
715 *--------------------------------------------------------------
716 *
717 * Tk_SetAppName --
718 *
719 * This procedure is called to associate an ASCII name with a Tk
720 * application. If the application has already been named, the
721 * name replaces the old one.
722 *
723 * Results:
724 * The return value is the name actually given to the application.
725 * This will normally be the same as name, but if name was already
726 * in use for an application then a name of the form "name #2" will
727 * be chosen, with a high enough number to make the name unique.
728 *
729 * Side effects:
730 * Registration info is saved, thereby allowing the "send" command
731 * to be used later to invoke commands in the application. In
732 * addition, the "send" command is created in the application's
733 * interpreter. The registration will be removed automatically
734 * if the interpreter is deleted or the "send" command is removed.
735 *
736 *--------------------------------------------------------------
737 */
738
739 CONST char *
740 Tk_SetAppName(tkwin, name)
741 Tk_Window tkwin; /* Token for any window in the application
742 * to be named: it is just used to identify
743 * the application and the display. */
744 CONST char *name; /* The name that will be used to
745 * refer to the interpreter in later
746 * "send" commands. Must be globally
747 * unique. */
748 {
749 RegisteredInterp *riPtr, *riPtr2;
750 Window w;
751 TkWindow *winPtr = (TkWindow *) tkwin;
752 TkDisplay *dispPtr = winPtr->dispPtr;
753 NameRegistry *regPtr;
754 Tcl_Interp *interp;
755 CONST char *actualName;
756 Tcl_DString dString;
757 int offset, i;
758 char *copy = NULL;
759 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
760 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
761
762 interp = winPtr->mainPtr->interp;
763 if (dispPtr->commTkwin == NULL) {
764 SendInit(interp, winPtr->dispPtr);
765 }
766
767 /*
768 * See if the application is already registered; if so, remove its
769 * current name from the registry.
770 */
771
772 regPtr = RegOpen(interp, winPtr->dispPtr, 1);
773 for (riPtr = tsdPtr->interpListPtr; ; riPtr = riPtr->nextPtr) {
774 if (riPtr == NULL) {
775
776 /*
777 * This interpreter isn't currently registered; create
778 * the data structure that will be used to register it locally,
779 * plus add the "send" command to the interpreter.
780 */
781
782 riPtr = (RegisteredInterp *) ckalloc(sizeof(RegisteredInterp));
783 riPtr->interp = interp;
784 riPtr->dispPtr = winPtr->dispPtr;
785 riPtr->nextPtr = tsdPtr->interpListPtr;
786 tsdPtr->interpListPtr = riPtr;
787 riPtr->name = NULL;
788 Tcl_CreateObjCommand(interp, "send", Tk_SendCmd, (ClientData) riPtr,
789 DeleteProc);
790 if (Tcl_IsSafe(interp)) {
791 Tcl_HideCommand(interp, "send", "send");
792 }
793 break;
794 }
795 if (riPtr->interp == interp) {
796 /*
797 * The interpreter is currently registered; remove it from
798 * the name registry.
799 */
800
801 if (riPtr->name) {
802 RegDeleteName(regPtr, riPtr->name);
803 ckfree(riPtr->name);
804 }
805 break;
806 }
807 }
808
809 /*
810 * Pick a name to use for the application. Use "name" if it's not
811 * already in use. Otherwise add a suffix such as " #2", trying
812 * larger and larger numbers until we eventually find one that is
813 * unique.
814 */
815
816 actualName = name;
817 offset = 0; /* Needed only to avoid "used before
818 * set" compiler warnings. */
819 for (i = 1; ; i++) {
820 if (i > 1) {
821 if (i == 2) {
822 Tcl_DStringInit(&dString);
823 Tcl_DStringAppend(&dString, name, -1);
824 Tcl_DStringAppend(&dString, " #", 2);
825 offset = Tcl_DStringLength(&dString);
826 Tcl_DStringSetLength(&dString, offset+TCL_INTEGER_SPACE);
827 actualName = Tcl_DStringValue(&dString);
828 }
829 sprintf(Tcl_DStringValue(&dString) + offset, "%d", i);
830 }
831 w = RegFindName(regPtr, actualName);
832 if (w == None) {
833 break;
834 }
835
836 /*
837 * The name appears to be in use already, but double-check to
838 * be sure (perhaps the application died without removing its
839 * name from the registry?).
840 */
841
842 if (w == Tk_WindowId(dispPtr->commTkwin)) {
843 for (riPtr2 = tsdPtr->interpListPtr; riPtr2 != NULL;
844 riPtr2 = riPtr2->nextPtr) {
845 if ((riPtr2->interp != interp) &&
846 (strcmp(riPtr2->name, actualName) == 0)) {
847 goto nextSuffix;
848 }
849 }
850 RegDeleteName(regPtr, actualName);
851 break;
852 } else if (!ValidateName(winPtr->dispPtr, actualName, w, 1)) {
853 RegDeleteName(regPtr, actualName);
854 break;
855 }
856 nextSuffix:
857 continue;
858 }
859
860 /*
861 * We've now got a name to use. Store it in the name registry and
862 * in the local entry for this application, plus put it in a property
863 * on the commWindow.
864 */
865
866 RegAddName(regPtr, actualName, Tk_WindowId(dispPtr->commTkwin));
867 RegClose(regPtr);
868 riPtr->name = (char *) ckalloc((unsigned) (strlen(actualName) + 1));
869 strcpy(riPtr->name, actualName);
870 if (actualName != name) {
871 Tcl_DStringFree(&dString);
872 }
873 UpdateCommWindow(dispPtr);
874
875 return riPtr->name;
876 }
877
878 /*
879 *--------------------------------------------------------------
880 *
881 * Tk_SendCmd --
882 *
883 * This procedure is invoked to process the "send" Tcl command.
884 * See the user documentation for details on what it does.
885 *
886 * Results:
887 * A standard Tcl result.
888 *
889 * Side effects:
890 * See the user documentation.
891 *
892 *--------------------------------------------------------------
893 */
894
895 int
896 Tk_SendCmd(clientData, interp, argc, argv)
897 ClientData clientData; /* Information about sender (only
898 * dispPtr field is used). */
899 Tcl_Interp *interp; /* Current interpreter. */
900 int argc; /* Number of arguments. */
901 CONST char **argv; /* Argument strings. */
902 {
903 TkWindow *winPtr;
904 Window commWindow;
905 PendingCommand pending;
906 register RegisteredInterp *riPtr;
907 CONST char *destName;
908 int result, c, async, i, firstArg;
909 size_t length;
910 Tk_RestrictProc *prevRestrictProc;
911 ClientData prevArg;
912 TkDisplay *dispPtr;
913 Tcl_Time timeout;
914 NameRegistry *regPtr;
915 Tcl_DString request;
916 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
917 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
918 Tcl_Interp *localInterp; /* Used when the interpreter to
919 * send the command to is within
920 * the same process. */
921
922 /*
923 * Process options, if any.
924 */
925
926 async = 0;
927 winPtr = (TkWindow *) Tk_MainWindow(interp);
928 if (winPtr == NULL) {
929 return TCL_ERROR;
930 }
931 for (i = 1; i < (argc-1); ) {
932 if (argv[i][0] != '-') {
933 break;
934 }
935 c = argv[i][1];
936 length = strlen(argv[i]);
937 if ((c == 'a') && (strncmp(argv[i], "-async", length) == 0)) {
938 async = 1;
939 i++;
940 } else if ((c == 'd') && (strncmp(argv[i], "-displayof",
941 length) == 0)) {
942 winPtr = (TkWindow *) Tk_NameToWindow(interp, argv[i+1],
943 (Tk_Window) winPtr);
944 if (winPtr == NULL) {
945 return TCL_ERROR;
946 }
947 i += 2;
948 } else if (strcmp(argv[i], "--") == 0) {
949 i++;
950 break;
951 } else {
952 Tcl_AppendResult(interp, "bad option \"", argv[i],
953 "\": must be -async, -displayof, or --", (char *) NULL);
954 return TCL_ERROR;
955 }
956 }
957
958 if (argc < (i+2)) {
959 Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
960 " ?options? interpName arg ?arg ...?\"", (char *) NULL);
961 return TCL_ERROR;
962 }
963 destName = argv[i];
964 firstArg = i+1;
965
966 dispPtr = winPtr->dispPtr;
967 if (dispPtr->commTkwin == NULL) {
968 SendInit(interp, winPtr->dispPtr);
969 }
970
971 /*
972 * See if the target interpreter is local. If so, execute
973 * the command directly without going through the X server.
974 * The only tricky thing is passing the result from the target
975 * interpreter to the invoking interpreter. Watch out: they
976 * could be the same!
977 */
978
979 for (riPtr = tsdPtr->interpListPtr; riPtr != NULL;
980 riPtr = riPtr->nextPtr) {
981 if ((riPtr->dispPtr != dispPtr)
982 || (strcmp(riPtr->name, destName) != 0)) {
983 continue;
984 }
985 Tcl_Preserve((ClientData) riPtr);
986 localInterp = riPtr->interp;
987 Tcl_Preserve((ClientData) localInterp);
988 if (firstArg == (argc-1)) {
989 result = Tcl_GlobalEval(localInterp, argv[firstArg]);
990 } else {
991 Tcl_DStringInit(&request);
992 Tcl_DStringAppend(&request, argv[firstArg], -1);
993 for (i = firstArg+1; i < argc; i++) {
994 Tcl_DStringAppend(&request, " ", 1);
995 Tcl_DStringAppend(&request, argv[i], -1);
996 }
997 result = Tcl_GlobalEval(localInterp, Tcl_DStringValue(&request));
998 Tcl_DStringFree(&request);
999 }
1000 if (interp != localInterp) {
1001 if (result == TCL_ERROR) {
1002 Tcl_Obj *errorObjPtr;
1003
1004 /*
1005 * An error occurred, so transfer error information from the
1006 * destination interpreter back to our interpreter. Must clear
1007 * interp's result before calling Tcl_AddErrorInfo, since
1008 * Tcl_AddErrorInfo will store the interp's result in errorInfo
1009 * before appending riPtr's $errorInfo; we've already got
1010 * everything we need in riPtr's $errorInfo.
1011 */
1012
1013 Tcl_ResetResult(interp);
1014 Tcl_AddErrorInfo(interp, Tcl_GetVar2(localInterp,
1015 "errorInfo", (char *) NULL, TCL_GLOBAL_ONLY));
1016 errorObjPtr = Tcl_GetVar2Ex(localInterp, "errorCode", NULL,
1017 TCL_GLOBAL_ONLY);
1018 Tcl_SetObjErrorCode(interp, errorObjPtr);
1019 }
1020 Tcl_SetObjResult(interp, Tcl_GetObjResult(localInterp));
1021 Tcl_ResetResult(localInterp);
1022 }
1023 Tcl_Release((ClientData) riPtr);
1024 Tcl_Release((ClientData) localInterp);
1025 return result;
1026 }
1027
1028 /*
1029 * Bind the interpreter name to a communication window.
1030 */
1031
1032 regPtr = RegOpen(interp, winPtr->dispPtr, 0);
1033 commWindow = RegFindName(regPtr, destName);
1034 RegClose(regPtr);
1035 if (commWindow == None) {
1036 Tcl_AppendResult(interp, "no application named \"",
1037 destName, "\"", (char *) NULL);
1038 return TCL_ERROR;
1039 }
1040
1041 /*
1042 * Send the command to the target interpreter by appending it to the
1043 * comm window in the communication window.
1044 */
1045
1046 tkSendSerial++;
1047 Tcl_DStringInit(&request);
1048 Tcl_DStringAppend(&request, "\0c\0-n ", 6);
1049 Tcl_DStringAppend(&request, destName, -1);
1050 if (!async) {
1051 char buffer[TCL_INTEGER_SPACE * 2];
1052
1053 sprintf(buffer, "%x %d",
1054 (unsigned int) Tk_WindowId(dispPtr->commTkwin),
1055 tkSendSerial);
1056 Tcl_DStringAppend(&request, "\0-r ", 4);
1057 Tcl_DStringAppend(&request, buffer, -1);
1058 }
1059 Tcl_DStringAppend(&request, "\0-s ", 4);
1060 Tcl_DStringAppend(&request, argv[firstArg], -1);
1061 for (i = firstArg+1; i < argc; i++) {
1062 Tcl_DStringAppend(&request, " ", 1);
1063 Tcl_DStringAppend(&request, argv[i], -1);
1064 }
1065 (void) AppendPropCarefully(dispPtr->display, commWindow,
1066 dispPtr->commProperty, Tcl_DStringValue(&request),
1067 Tcl_DStringLength(&request) + 1,
1068 (async) ? (PendingCommand *) NULL : &pending);
1069 Tcl_DStringFree(&request);
1070 if (async) {
1071 /*
1072 * This is an asynchronous send: return immediately without
1073 * waiting for a response.
1074 */
1075
1076 return TCL_OK;
1077 }
1078
1079 /*
1080 * Register the fact that we're waiting for a command to complete
1081 * (this is needed by SendEventProc and by AppendErrorProc to pass
1082 * back the command's results). Set up a timeout handler so that
1083 * we can check during long sends to make sure that the destination
1084 * application is still alive.
1085 */
1086
1087 pending.serial = tkSendSerial;
1088 pending.dispPtr = dispPtr;
1089 pending.target = destName;
1090 pending.commWindow = commWindow;
1091 pending.interp = interp;
1092 pending.result = NULL;
1093 pending.errorInfo = NULL;
1094 pending.errorCode = NULL;
1095 pending.gotResponse = 0;
1096 pending.nextPtr = tsdPtr->pendingCommands;
1097 tsdPtr->pendingCommands = &pending;
1098
1099 /*
1100 * Enter a loop processing X events until the result comes
1101 * in or the target is declared to be dead. While waiting
1102 * for a result, look only at send-related events so that
1103 * the send is synchronous with respect to other events in
1104 * the application.
1105 */
1106
1107 prevRestrictProc = Tk_RestrictEvents(SendRestrictProc,
1108 (ClientData) NULL, &prevArg);
1109 Tcl_GetTime(&timeout);
1110 timeout.sec += 2;
1111 while (!pending.gotResponse) {
1112 if (!TkUnixDoOneXEvent(&timeout)) {
1113 /*
1114 * An unusually long amount of time has elapsed during the
1115 * processing of a sent command. Check to make sure that the
1116 * target application still exists. If it does, reset the timeout.
1117 */
1118
1119 if (!ValidateName(pending.dispPtr, pending.target,
1120 pending.commWindow, 0)) {
1121 char *msg;
1122 if (ValidateName(pending.dispPtr, pending.target,
1123 pending.commWindow, 1)) {
1124 msg = "target application died or uses a Tk version before 4.0";
1125 } else {
1126 msg = "target application died";
1127 }
1128 pending.code = TCL_ERROR;
1129 pending.result = (char *) ckalloc((unsigned) (strlen(msg) + 1));
1130 strcpy(pending.result, msg);
1131 pending.gotResponse = 1;
1132 } else {
1133 Tcl_GetTime(&timeout);
1134 timeout.sec += 2;
1135 }
1136 }
1137 }
1138 (void) Tk_RestrictEvents(prevRestrictProc, prevArg, &prevArg);
1139
1140 /*
1141 * Unregister the information about the pending command
1142 * and return the result.
1143 */
1144
1145 if (tsdPtr->pendingCommands != &pending) {
1146 panic("Tk_SendCmd: corrupted send stack");
1147 }
1148 tsdPtr->pendingCommands = pending.nextPtr;
1149 if (pending.errorInfo != NULL) {
1150 /*
1151 * Special trick: must clear the interp's result before calling
1152 * Tcl_AddErrorInfo, since Tcl_AddErrorInfo will store the interp's
1153 * result in errorInfo before appending pending.errorInfo; we've
1154 * already got everything we need in pending.errorInfo.
1155 */
1156
1157 Tcl_ResetResult(interp);
1158 Tcl_AddErrorInfo(interp, pending.errorInfo);
1159 ckfree(pending.errorInfo);
1160 }
1161 if (pending.errorCode != NULL) {
1162 Tcl_Obj *errorObjPtr;
1163 errorObjPtr = Tcl_NewStringObj(pending.errorCode, -1);
1164 Tcl_SetObjErrorCode(interp, errorObjPtr);
1165 ckfree(pending.errorCode);
1166 }
1167 Tcl_SetResult(interp, pending.result, TCL_VOLATILE);
1168 return pending.code;
1169 }
1170
1171 /*
1172 *----------------------------------------------------------------------
1173 *
1174 * TkGetInterpNames --
1175 *
1176 * This procedure is invoked to fetch a list of all the
1177 * interpreter names currently registered for the display
1178 * of a particular window.
1179 *
1180 * Results:
1181 * A standard Tcl return value. The interp's result will be set
1182 * to hold a list of all the interpreter names defined for
1183 * tkwin's display. If an error occurs, then TCL_ERROR
1184 * is returned and the interp's result will hold an error message.
1185 *
1186 * Side effects:
1187 * None.
1188 *
1189 *----------------------------------------------------------------------
1190 */
1191
1192 int
1193 TkGetInterpNames(interp, tkwin)
1194 Tcl_Interp *interp; /* Interpreter for returning a result. */
1195 Tk_Window tkwin; /* Window whose display is to be used
1196 * for the lookup. */
1197 {
1198 TkWindow *winPtr = (TkWindow *) tkwin;
1199 char *p, *entry, *entryName;
1200 NameRegistry *regPtr;
1201 Window commWindow;
1202 int count;
1203 unsigned int id;
1204
1205 /*
1206 * Read the registry property, then scan through all of its entries.
1207 * Validate each entry to be sure that its application still exists.
1208 */
1209
1210 regPtr = RegOpen(interp, winPtr->dispPtr, 1);
1211 for (p = regPtr->property; (p-regPtr->property) < (int) regPtr->propLength; ) {
1212 entry = p;
1213 if (sscanf(p, "%x",(unsigned int *) &id) != 1) {
1214 commWindow = None;
1215 } else {
1216 commWindow = id;
1217 }
1218 while ((*p != 0) && (!isspace(UCHAR(*p)))) {
1219 p++;
1220 }
1221 if (*p != 0) {
1222 p++;
1223 }
1224 entryName = p;
1225 while (*p != 0) {
1226 p++;
1227 }
1228 p++;
1229 if (ValidateName(winPtr->dispPtr, entryName, commWindow, 1)) {
1230 /*
1231 * The application still exists; add its name to the result.
1232 */
1233
1234 Tcl_AppendElement(interp, entryName);
1235 } else {
1236 /*
1237 * This name is bogus (perhaps the application died without
1238 * cleaning up its entry in the registry?). Delete the name.
1239 */
1240
1241 count = regPtr->propLength - (p - regPtr->property);
1242 if (count > 0) {
1243 char *src, *dst;
1244
1245 for (src = p, dst = entry; count > 0; src++, dst++, count--) {
1246 *dst = *src;
1247 }
1248 }
1249 regPtr->propLength -= p - entry;
1250 regPtr->modified = 1;
1251 p = entry;
1252 }
1253 }
1254 RegClose(regPtr);
1255 return TCL_OK;
1256 }
1257
1258 /*
1259 *--------------------------------------------------------------
1260 *
1261 * TkSendCleanup --
1262 *
1263 * This procedure is called to free resources used by the
1264 * communication channels for sending commands and
1265 * receiving results.
1266 *
1267 * Results:
1268 * None.
1269 *
1270 * Side effects:
1271 * Frees various data structures and windows.
1272 *
1273 *--------------------------------------------------------------
1274 */
1275
1276 void
1277 TkSendCleanup(dispPtr)
1278 TkDisplay *dispPtr;
1279 {
1280 if (dispPtr->commTkwin != NULL) {
1281 Tk_DeleteEventHandler(dispPtr->commTkwin, PropertyChangeMask,
1282 SendEventProc, (ClientData) dispPtr);
1283 Tk_DestroyWindow(dispPtr->commTkwin);
1284 Tcl_Release((ClientData) dispPtr->commTkwin);
1285 dispPtr->commTkwin = NULL;
1286 }
1287 }
1288
1289 /*
1290 *--------------------------------------------------------------
1291 *
1292 * SendInit --
1293 *
1294 * This procedure is called to initialize the
1295 * communication channels for sending commands and
1296 * receiving results.
1297 *
1298 * Results:
1299 * None.
1300 *
1301 * Side effects:
1302 * Sets up various data structures and windows.
1303 *
1304 *--------------------------------------------------------------
1305 */
1306
1307 static int
1308 SendInit(interp, dispPtr)
1309 Tcl_Interp *interp; /* Interpreter to use for error reporting
1310 * (no errors are ever returned, but the
1311 * interpreter is needed anyway). */
1312 TkDisplay *dispPtr; /* Display to initialize. */
1313 {
1314 XSetWindowAttributes atts;
1315
1316 /*
1317 * Create the window used for communication, and set up an
1318 * event handler for it.
1319 */
1320
1321 dispPtr->commTkwin = Tk_CreateWindow(interp, (Tk_Window) NULL,
1322 "_comm", DisplayString(dispPtr->display));
1323 if (dispPtr->commTkwin == NULL) {
1324 panic("Tk_CreateWindow failed in SendInit!");
1325 }
1326 Tcl_Preserve((ClientData) dispPtr->commTkwin);
1327 atts.override_redirect = True;
1328 Tk_ChangeWindowAttributes(dispPtr->commTkwin,
1329 CWOverrideRedirect, &atts);
1330 Tk_CreateEventHandler(dispPtr->commTkwin, PropertyChangeMask,
1331 SendEventProc, (ClientData) dispPtr);
1332 Tk_MakeWindowExist(dispPtr->commTkwin);
1333
1334 /*
1335 * Get atoms used as property names.
1336 */
1337
1338 dispPtr->commProperty = Tk_InternAtom(dispPtr->commTkwin, "Comm");
1339 dispPtr->registryProperty = Tk_InternAtom(dispPtr->commTkwin,
1340 "InterpRegistry");
1341 dispPtr->appNameProperty = Tk_InternAtom(dispPtr->commTkwin,
1342 "TK_APPLICATION");
1343
1344 return TCL_OK;
1345 }
1346
1347 /*
1348 *--------------------------------------------------------------
1349 *
1350 * SendEventProc --
1351 *
1352 * This procedure is invoked automatically by the toolkit
1353 * event manager when a property changes on the communication
1354 * window. This procedure reads the property and handles
1355 * command requests and responses.
1356 *
1357 * Results:
1358 * None.
1359 *
1360 * Side effects:
1361 * If there are command requests in the property, they
1362 * are executed. If there are responses in the property,
1363 * their information is saved for the (ostensibly waiting)
1364 * "send" commands. The property is deleted.
1365 *
1366 *--------------------------------------------------------------
1367 */
1368
1369 static void
1370 SendEventProc(clientData, eventPtr)
1371 ClientData clientData; /* Display information. */
1372 XEvent *eventPtr; /* Information about event. */
1373 {
1374 TkDisplay *dispPtr = (TkDisplay *) clientData;
1375 char *propInfo;
1376 register char *p;
1377 int result, actualFormat;
1378 unsigned long numItems, bytesAfter;
1379 Atom actualType;
1380 Tcl_Interp *remoteInterp; /* Interp in which to execute the command. */
1381 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1382 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1383
1384 if ((eventPtr->xproperty.atom != dispPtr->commProperty)
1385 || (eventPtr->xproperty.state != PropertyNewValue)) {
1386 return;
1387 }
1388
1389 /*
1390 * Read the comm property and delete it.
1391 */
1392
1393 propInfo = NULL;
1394 result = XGetWindowProperty(dispPtr->display,
1395 Tk_WindowId(dispPtr->commTkwin),
1396 dispPtr->commProperty, 0, MAX_PROP_WORDS, True,
1397 XA_STRING, &actualType, &actualFormat,
1398 &numItems, &bytesAfter, (unsigned char **) &propInfo);
1399
1400 /*
1401 * If the property doesn't exist or is improperly formed
1402 * then ignore it.
1403 */
1404
1405 if ((result != Success) || (actualType != XA_STRING)
1406 || (actualFormat != 8)) {
1407 if (propInfo != NULL) {
1408 XFree(propInfo);
1409 }
1410 return;
1411 }
1412
1413 /*
1414 * Several commands and results could arrive in the property at
1415 * one time; each iteration through the outer loop handles a
1416 * single command or result.
1417 */
1418
1419 for (p = propInfo; (p-propInfo) < (int) numItems; ) {
1420 /*
1421 * Ignore leading NULLs; each command or result starts with a
1422 * NULL so that no matter how badly formed a preceding command
1423 * is, we'll be able to tell that a new command/result is
1424 * starting.
1425 */
1426
1427 if (*p == 0) {
1428 p++;
1429 continue;
1430 }
1431
1432 if ((*p == 'c') && (p[1] == 0)) {
1433 Window commWindow;
1434 char *interpName, *script, *serial, *end;
1435 Tcl_DString reply;
1436 RegisteredInterp *riPtr;
1437
1438 /*
1439 *----------------------------------------------------------
1440 * This is an incoming command from some other application.
1441 * Iterate over all of its options. Stop when we reach
1442 * the end of the property or something that doesn't look
1443 * like an option.
1444 *----------------------------------------------------------
1445 */
1446
1447 p += 2;
1448 interpName = NULL;
1449 commWindow = None;
1450 serial = "";
1451 script = NULL;
1452 while (((p-propInfo) < (int) numItems) && (*p == '-')) {
1453 switch (p[1]) {
1454 case 'r':
1455 commWindow = (Window) strtoul(p+2, &end, 16);
1456 if ((end == p+2) || (*end != ' ')) {
1457 commWindow = None;
1458 } else {
1459 p = serial = end+1;
1460 }
1461 break;
1462 case 'n':
1463 if (p[2] == ' ') {
1464 interpName = p+3;
1465 }
1466 break;
1467 case 's':
1468 if (p[2] == ' ') {
1469 script = p+3;
1470 }
1471 break;
1472 }
1473 while (*p != 0) {
1474 p++;
1475 }
1476 p++;
1477 }
1478
1479 if ((script == NULL) || (interpName == NULL)) {
1480 continue;
1481 }
1482
1483 /*
1484 * Initialize the result property, so that we're ready at any
1485 * time if we need to return an error.
1486 */
1487
1488 if (commWindow != None) {
1489 Tcl_DStringInit(&reply);
1490 Tcl_DStringAppend(&reply, "\0r\0-s ", 6);
1491 Tcl_DStringAppend(&reply, serial, -1);
1492 Tcl_DStringAppend(&reply, "\0-r ", 4);
1493 }
1494
1495 if (!ServerSecure(dispPtr)) {
1496 if (commWindow != None) {
1497 Tcl_DStringAppend(&reply, "X server insecure (must use xauth-style authorization); command ignored", -1);
1498 }
1499 result = TCL_ERROR;
1500 goto returnResult;
1501 }
1502
1503 /*
1504 * Locate the application, then execute the script.
1505 */
1506
1507 for (riPtr = tsdPtr->interpListPtr; ; riPtr = riPtr->nextPtr) {
1508 if (riPtr == NULL) {
1509 if (commWindow != None) {
1510 Tcl_DStringAppend(&reply,
1511 "receiver never heard of interpreter \"", -1);
1512 Tcl_DStringAppend(&reply, interpName, -1);
1513 Tcl_DStringAppend(&reply, "\"", 1);
1514 }
1515 result = TCL_ERROR;
1516 goto returnResult;
1517 }
1518 if (strcmp(riPtr->name, interpName) == 0) {
1519 break;
1520 }
1521 }
1522 Tcl_Preserve((ClientData) riPtr);
1523
1524 /*
1525 * We must protect the interpreter because the script may
1526 * enter another event loop, which might call Tcl_DeleteInterp.
1527 */
1528
1529 remoteInterp = riPtr->interp;
1530 Tcl_Preserve((ClientData) remoteInterp);
1531
1532 result = Tcl_GlobalEval(remoteInterp, script);
1533
1534 /*
1535 * The call to Tcl_Release may have released the interpreter
1536 * which will cause the "send" command for that interpreter
1537 * to be deleted. The command deletion callback will set the
1538 * riPtr->interp field to NULL, hence the check below for NULL.
1539 */
1540
1541 if (commWindow != None) {
1542 Tcl_DStringAppend(&reply, Tcl_GetStringResult(remoteInterp),
1543 -1);
1544 if (result == TCL_ERROR) {
1545 CONST char *varValue;
1546
1547 varValue = Lang_GetErrorInfo(remoteInterp);
1548 if (varValue != NULL) {
1549 Tcl_DStringAppend(&reply, "\0-i ", 4);
1550 Tcl_DStringAppend(&reply, varValue, -1);
1551 }
1552 varValue = Lang_GetErrorCode(remoteInterp);
1553 if (varValue != NULL) {
1554 Tcl_DStringAppend(&reply, "\0-e ", 4);
1555 Tcl_DStringAppend(&reply, varValue, -1);
1556 }
1557 }
1558 }
1559 Tcl_Release((ClientData) remoteInterp);
1560 Tcl_Release((ClientData) riPtr);
1561
1562 /*
1563 * Return the result to the sender if a commWindow was
1564 * specified (if none was specified then this is an asynchronous
1565 * call). Right now reply has everything but the completion
1566 * code, but it needs the NULL to terminate the current option.
1567 */
1568
1569 returnResult:
1570 if (commWindow != None) {
1571 if (result != TCL_OK) {
1572 char buffer[TCL_INTEGER_SPACE];
1573
1574 sprintf(buffer, "%d", result);
1575 Tcl_DStringAppend(&reply, "\0-c ", 4);
1576 Tcl_DStringAppend(&reply, buffer, -1);
1577 }
1578 (void) AppendPropCarefully(dispPtr->display, commWindow,
1579 dispPtr->commProperty, Tcl_DStringValue(&reply),
1580 Tcl_DStringLength(&reply) + 1,
1581 (PendingCommand *) NULL);
1582 XFlush(dispPtr->display);
1583 Tcl_DStringFree(&reply);
1584 }
1585 } else if ((*p == 'r') && (p[1] == 0)) {
1586 int serial, code, gotSerial;
1587 char *errorInfo, *errorCode, *resultString;
1588 PendingCommand *pcPtr;
1589
1590 /*
1591 *----------------------------------------------------------
1592 * This is a reply to some command that we sent out. Iterate
1593 * over all of its options. Stop when we reach the end of the
1594 * property or something that doesn't look like an option.
1595 *----------------------------------------------------------
1596 */
1597
1598 p += 2;
1599 code = TCL_OK;
1600 gotSerial = 0;
1601 errorInfo = NULL;
1602 errorCode = NULL;
1603 resultString = "";
1604 while (((p-propInfo) < (int) numItems) && (*p == '-')) {
1605 switch (p[1]) {
1606 case 'c':
1607 if (sscanf(p+2, " %d", &code) != 1) {
1608 code = TCL_OK;
1609 }
1610 break;
1611 case 'e':
1612 if (p[2] == ' ') {
1613 errorCode = p+3;
1614 }
1615 break;
1616 case 'i':
1617 if (p[2] == ' ') {
1618 errorInfo = p+3;
1619 }
1620 break;
1621 case 'r':
1622 if (p[2] == ' ') {
1623 resultString = p+3;
1624 }
1625 break;
1626 case 's':
1627 if (sscanf(p+2, " %d", &serial) == 1) {
1628 gotSerial = 1;
1629 }
1630 break;
1631 }
1632 while (*p != 0) {
1633 p++;
1634 }
1635 p++;
1636 }
1637
1638 if (!gotSerial) {
1639 continue;
1640 }
1641
1642 /*
1643 * Give the result information to anyone who's
1644 * waiting for it.
1645 */
1646
1647 for (pcPtr = tsdPtr->pendingCommands; pcPtr != NULL;
1648 pcPtr = pcPtr->nextPtr) {
1649 if ((serial != pcPtr->serial) || (pcPtr->result != NULL)) {
1650 continue;
1651 }
1652 pcPtr->code = code;
1653 if (resultString != NULL) {
1654 pcPtr->result = (char *) ckalloc((unsigned)
1655 (strlen(resultString) + 1));
1656 strcpy(pcPtr->result, resultString);
1657 }
1658 if (code == TCL_ERROR) {
1659 if (errorInfo != NULL) {
1660 pcPtr->errorInfo = (char *) ckalloc((unsigned)
1661 (strlen(errorInfo) + 1));
1662 strcpy(pcPtr->errorInfo, errorInfo);
1663 }
1664 if (errorCode != NULL) {
1665 pcPtr->errorCode = (char *) ckalloc((unsigned)
1666 (strlen(errorCode) + 1));
1667 strcpy(pcPtr->errorCode, errorCode);
1668 }
1669 }
1670 pcPtr->gotResponse = 1;
1671 break;
1672 }
1673 } else {
1674 /*
1675 * Didn't recognize this thing. Just skip through the next
1676 * null character and try again.
1677 */
1678
1679 while (*p != 0) {
1680 p++;
1681 }
1682 p++;
1683 }
1684 }
1685 XFree(propInfo);
1686 }
1687
1688 /*
1689 *--------------------------------------------------------------
1690 *
1691 * AppendPropCarefully --
1692 *
1693 * Append a given property to a given window, but set up
1694 * an X error handler so that if the append fails this
1695 * procedure can return an error code rather than having
1696 * Xlib panic.
1697 *
1698 * Results:
1699 * None.
1700 *
1701 * Side effects:
1702 * The given property on the given window is appended to.
1703 * If this operation fails and if pendingPtr is non-NULL,
1704 * then the pending operation is marked as complete with
1705 * an error.
1706 *
1707 *--------------------------------------------------------------
1708 */
1709
1710 static void
1711 AppendPropCarefully(display, window, property, value, length, pendingPtr)
1712 Display *display; /* Display on which to operate. */
1713 Window window; /* Window whose property is to
1714 * be modified. */
1715 Atom property; /* Name of property. */
1716 char *value; /* Characters to append to property. */
1717 int length; /* Number of bytes to append. */
1718 PendingCommand *pendingPtr; /* Pending command to mark complete
1719 * if an error occurs during the
1720 * property op. NULL means just
1721 * ignore the error. */
1722 {
1723 Tk_ErrorHandler handler;
1724
1725 handler = Tk_CreateErrorHandler(display, -1, -1, -1, AppendErrorProc,
1726 (ClientData) pendingPtr);
1727 XChangeProperty(display, window, property, XA_STRING, 8,
1728 PropModeAppend, (unsigned char *) value, length);
1729 Tk_DeleteErrorHandler(handler);
1730 }
1731
1732 /*
1733 * The procedure below is invoked if an error occurs during
1734 * the XChangeProperty operation above.
1735 */
1736
1737 /* ARGSUSED */
1738 static int
1739 AppendErrorProc(clientData, errorPtr)
1740 ClientData clientData; /* Command to mark complete, or NULL. */
1741 XErrorEvent *errorPtr; /* Information about error. */
1742 {
1743 PendingCommand *pendingPtr = (PendingCommand *) clientData;
1744 register PendingCommand *pcPtr;
1745 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1746 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1747
1748 if (pendingPtr == NULL) {
1749 return 0;
1750 }
1751
1752 /*
1753 * Make sure this command is still pending.
1754 */
1755
1756 for (pcPtr = tsdPtr->pendingCommands; pcPtr != NULL;
1757 pcPtr = pcPtr->nextPtr) {
1758 if ((pcPtr == pendingPtr) && (pcPtr->result == NULL)) {
1759 pcPtr->result = (char *) ckalloc((unsigned)
1760 (strlen(pcPtr->target) + 50));
1761 sprintf(pcPtr->result, "no application named \"%s\"",
1762 pcPtr->target);
1763 pcPtr->code = TCL_ERROR;
1764 pcPtr->gotResponse = 1;
1765 break;
1766 }
1767 }
1768 return 0;
1769 }
1770
1771 /*
1772 *--------------------------------------------------------------
1773 *
1774 * DeleteProc --
1775 *
1776 * This procedure is invoked by Tcl when the "send" command
1777 * is deleted in an interpreter. It unregisters the interpreter.
1778 *
1779 * Results:
1780 * None.
1781 *
1782 * Side effects:
1783 * The interpreter given by riPtr is unregistered.
1784 *
1785 *--------------------------------------------------------------
1786 */
1787
1788 static void
1789 DeleteProc(clientData)
1790 ClientData clientData; /* Info about registration, passed
1791 * as ClientData. */
1792 {
1793 RegisteredInterp *riPtr = (RegisteredInterp *) clientData;
1794 register RegisteredInterp *riPtr2;
1795 NameRegistry *regPtr;
1796 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1797 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1798
1799 regPtr = RegOpen(riPtr->interp, riPtr->dispPtr, 1);
1800 RegDeleteName(regPtr, riPtr->name);
1801 RegClose(regPtr);
1802
1803 if (tsdPtr->interpListPtr == riPtr) {
1804 tsdPtr->interpListPtr = riPtr->nextPtr;
1805 } else {
1806 for (riPtr2 = tsdPtr->interpListPtr; riPtr2 != NULL;
1807 riPtr2 = riPtr2->nextPtr) {
1808 if (riPtr2->nextPtr == riPtr) {
1809 riPtr2->nextPtr = riPtr->nextPtr;
1810 break;
1811 }
1812 }
1813 }
1814 ckfree((char *) riPtr->name);
1815 riPtr->interp = NULL;
1816 UpdateCommWindow(riPtr->dispPtr);
1817 Tcl_EventuallyFree((ClientData) riPtr, TCL_DYNAMIC);
1818 }
1819
1820 /*
1821 *----------------------------------------------------------------------
1822 *
1823 * SendRestrictProc --
1824 *
1825 * This procedure filters incoming events when a "send" command
1826 * is outstanding. It defers all events except those containing
1827 * send commands and results.
1828 *
1829 * Results:
1830 * False is returned except for property-change events on a
1831 * commWindow.
1832 *
1833 * Side effects:
1834 * None.
1835 *
1836 *----------------------------------------------------------------------
1837 */
1838
1839 /* ARGSUSED */
1840 static Tk_RestrictAction
1841 SendRestrictProc(clientData, eventPtr)
1842 ClientData clientData; /* Not used. */
1843 register XEvent *eventPtr; /* Event that just arrived. */
1844 {
1845 TkDisplay *dispPtr;
1846
1847 if (eventPtr->type != PropertyNotify) {
1848 return TK_DEFER_EVENT;
1849 }
1850 for (dispPtr = TkGetDisplayList(); dispPtr != NULL;
1851 dispPtr = dispPtr->nextPtr) {
1852 if ((eventPtr->xany.display == dispPtr->display)
1853 && (eventPtr->xproperty.window
1854 == Tk_WindowId(dispPtr->commTkwin))) {
1855 return TK_PROCESS_EVENT;
1856 }
1857 }
1858 return TK_DEFER_EVENT;
1859 }
1860
1861 /*
1862 *----------------------------------------------------------------------
1863 *
1864 * UpdateCommWindow --
1865 *
1866 * This procedure updates the list of application names stored
1867 * on our commWindow. It is typically called when interpreters
1868 * are registered and unregistered.
1869 *
1870 * Results:
1871 * None.
1872 *
1873 * Side effects:
1874 * The TK_APPLICATION property on the comm window is updated.
1875 *
1876 *----------------------------------------------------------------------
1877 */
1878
1879 static void
1880 UpdateCommWindow(dispPtr)
1881 TkDisplay *dispPtr; /* Display whose commWindow is to be
1882 * updated. */
1883 {
1884 Tcl_DString names;
1885 RegisteredInterp *riPtr;
1886 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1887 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
1888
1889 Tcl_DStringInit(&names);
1890 for (riPtr = tsdPtr->interpListPtr; riPtr != NULL;
1891 riPtr = riPtr->nextPtr) {
1892 Tcl_DStringAppendElement(&names, riPtr->name);
1893 }
1894 XChangeProperty(dispPtr->display, Tk_WindowId(dispPtr->commTkwin),
1895 dispPtr->appNameProperty, XA_STRING, 8, PropModeReplace,
1896 (unsigned char *) Tcl_DStringValue(&names),
1897 Tcl_DStringLength(&names));
1898 Tcl_DStringFree(&names);
1899 }
1900
1901
1902