home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / tk42r2s.zip / tk4.2 / os2 / tkSend.c < prev    next >
C/C++ Source or Header  |  1998-01-28  |  56KB  |  1,868 lines

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