1 /* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * X command server by Flemming Madsen
5 *
6 * Do ":help uganda" in Vim to read copying and usage conditions.
7 * Do ":help credits" in Vim to see a list of people who contributed.
8 * See README.txt for an overview of the Vim source code.
9 *
10 * if_xcmdsrv.c: Functions for passing commands through an X11 display.
11 *
12 */
13
14 #include "vim.h"
15 #include "version.h"
16
17 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
18
19 # ifdef FEAT_X11
20 # include <X11/Intrinsic.h>
21 # include <X11/Xatom.h>
22 # endif
23
24 /*
25 * This file provides procedures that implement the command server
26 * functionality of Vim when in contact with an X11 server.
27 *
28 * Adapted from TCL/TK's send command in tkSend.c of the tk 3.6 distribution.
29 * Adapted for use in Vim by Flemming Madsen. Protocol changed to that of tk 4
30 */
31
32 /*
33 * Copyright (c) 1989-1993 The Regents of the University of California.
34 * All rights reserved.
35 *
36 * Permission is hereby granted, without written agreement and without
37 * license or royalty fees, to use, copy, modify, and distribute this
38 * software and its documentation for any purpose, provided that the
39 * above copyright notice and the following two paragraphs appear in
40 * all copies of this software.
41 *
42 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
43 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
44 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
45 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 *
47 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
48 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
49 * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
50 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
51 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
52 */
53
54
55 /*
56 * When a result is being awaited from a sent command, one of
57 * the following structures is present on a list of all outstanding
58 * sent commands. The information in the structure is used to
59 * process the result when it arrives. You're probably wondering
60 * how there could ever be multiple outstanding sent commands.
61 * This could happen if Vim instances invoke each other recursively.
62 * It's unlikely, but possible.
63 */
64
65 typedef struct PendingCommand
66 {
67 int serial; // Serial number expected in result.
68 int code; // Result Code. 0 is OK
69 char_u *result; // String result for command (malloc'ed).
70 // NULL means command still pending.
71 struct PendingCommand *nextPtr;
72 // Next in list of all outstanding commands.
73 // NULL means end of list.
74 } PendingCommand;
75
76 static PendingCommand *pendingCommands = NULL;
77 // List of all commands currently
78 // being waited for.
79
80 /*
81 * The information below is used for communication between processes
82 * during "send" commands. Each process keeps a private window, never
83 * even mapped, with one property, "Comm". When a command is sent to
84 * an interpreter, the command is appended to the comm property of the
85 * communication window associated with the interp's process. Similarly,
86 * when a result is returned from a sent command, it is also appended
87 * to the comm property.
88 *
89 * Each command and each result takes the form of ASCII text. For a
90 * command, the text consists of a nul character followed by several
91 * nul-terminated ASCII strings. The first string consists of a
92 * single letter:
93 * "c" for an expression
94 * "k" for keystrokes
95 * "r" for reply
96 * "n" for notification.
97 * Subsequent strings have the form "option value" where the following options
98 * are supported:
99 *
100 * -r commWindow serial
101 *
102 * This option means that a response should be sent to the window
103 * whose X identifier is "commWindow" (in hex), and the response should
104 * be identified with the serial number given by "serial" (in decimal).
105 * If this option isn't specified then the send is asynchronous and
106 * no response is sent.
107 *
108 * -n name
109 * "Name" gives the name of the application for which the command is
110 * intended. This option must be present.
111 *
112 * -E encoding
113 * Encoding name used for the text. This is the 'encoding' of the
114 * sender. The receiver may want to do conversion to his 'encoding'.
115 *
116 * -s script
117 * "Script" is the script to be executed. This option must be
118 * present. Taken as a series of keystrokes in a "k" command where
119 * <Key>'s are expanded
120 *
121 * The options may appear in any order. The -n and -s options must be
122 * present, but -r may be omitted for asynchronous RPCs. For compatibility
123 * with future releases that may add new features, there may be additional
124 * options present; as long as they start with a "-" character, they will
125 * be ignored.
126 *
127 * A result also consists of a zero character followed by several null-
128 * terminated ASCII strings. The first string consists of the single
129 * letter "r". Subsequent strings have the form "option value" where
130 * the following options are supported:
131 *
132 * -s serial
133 * Identifies the command for which this is the result. It is the
134 * same as the "serial" field from the -s option in the command. This
135 * option must be present.
136 *
137 * -r result
138 * "Result" is the result string for the script, which may be either
139 * a result or an error message. If this field is omitted then it
140 * defaults to an empty string.
141 *
142 * -c code
143 * 0: for OK. This is the default.
144 * 1: for error: Result is the last error
145 *
146 * -i errorInfo
147 * -e errorCode
148 * Not applicable for Vim
149 *
150 * Options may appear in any order, and only the -s option must be
151 * present. As with commands, there may be additional options besides
152 * these; unknown options are ignored.
153 */
154
155 /*
156 * Maximum size property that can be read at one time by
157 * this module:
158 */
159
160 #define MAX_PROP_WORDS 100000
161
162 struct ServerReply
163 {
164 Window id;
165 garray_T strings;
166 };
167 static garray_T serverReply = { 0, 0, 0, 0, 0 };
168 enum ServerReplyOp { SROP_Find, SROP_Add, SROP_Delete };
169
170 typedef int (*EndCond)(void *);
171
172 struct x_cmdqueue
173 {
174 char_u *propInfo;
175 long_u len;
176 struct x_cmdqueue *next;
177 struct x_cmdqueue *prev;
178 };
179
180 typedef struct x_cmdqueue x_queue_T;
181
182 // dummy node, header for circular queue
183 static x_queue_T head = {NULL, 0, NULL, NULL};
184
185 /*
186 * Forward declarations for procedures defined later in this file:
187 */
188
189 static Window LookupName(Display *dpy, char_u *name, int delete, char_u **loose);
190 static int SendInit(Display *dpy);
191 static int DoRegisterName(Display *dpy, char_u *name);
192 static void DeleteAnyLingerer(Display *dpy, Window w);
193 static int GetRegProp(Display *dpy, char_u **regPropp, long_u *numItemsp, int domsg);
194 static int WaitForPend(void *p);
195 static int WindowValid(Display *dpy, Window w);
196 static void ServerWait(Display *dpy, Window w, EndCond endCond, void *endData, int localLoop, int seconds);
197 static int AppendPropCarefully(Display *display, Window window, Atom property, char_u *value, int length);
198 static int x_error_check(Display *dpy, XErrorEvent *error_event);
199 static int IsSerialName(char_u *name);
200 static void save_in_queue(char_u *buf, long_u len);
201 static void server_parse_message(Display *dpy, char_u *propInfo, long_u numItems);
202
203 // Private variables for the "server" functionality
204 static Atom registryProperty = None;
205 static Atom vimProperty = None;
206 static int got_x_error = FALSE;
207
208 static char_u *empty_prop = (char_u *)""; // empty GetRegProp() result
209
210 /*
211 * Associate an ASCII name with Vim. Try real hard to get a unique one.
212 * Returns FAIL or OK.
213 */
214 int
serverRegisterName(Display * dpy,char_u * name)215 serverRegisterName(
216 Display *dpy, // display to register with
217 char_u *name) // the name that will be used as a base
218 {
219 int i;
220 int res;
221 char_u *p = NULL;
222
223 res = DoRegisterName(dpy, name);
224 if (res < 0)
225 {
226 i = 1;
227 do
228 {
229 if (res < -1 || i >= 1000)
230 {
231 msg_attr(_("Unable to register a command server name"),
232 HL_ATTR(HLF_W));
233 return FAIL;
234 }
235 if (p == NULL)
236 p = alloc(STRLEN(name) + 10);
237 if (p == NULL)
238 {
239 res = -10;
240 continue;
241 }
242 sprintf((char *)p, "%s%d", name, i++);
243 res = DoRegisterName(dpy, p);
244 }
245 while (res < 0)
246 ;
247 vim_free(p);
248 }
249 return OK;
250 }
251
252 static int
DoRegisterName(Display * dpy,char_u * name)253 DoRegisterName(Display *dpy, char_u *name)
254 {
255 Window w;
256 XErrorHandler old_handler;
257 #define MAX_NAME_LENGTH 100
258 char_u propInfo[MAX_NAME_LENGTH + 20];
259
260 if (commProperty == None)
261 {
262 if (SendInit(dpy) < 0)
263 return -2;
264 }
265
266 /*
267 * Make sure the name is unique, and append info about it to
268 * the registry property. It's important to lock the server
269 * here to prevent conflicting changes to the registry property.
270 * WARNING: Do not step through this while debugging, it will hangup the X
271 * server!
272 */
273 XGrabServer(dpy);
274 w = LookupName(dpy, name, FALSE, NULL);
275 if (w != (Window)0)
276 {
277 Status status;
278 int dummyInt;
279 unsigned int dummyUns;
280 Window dummyWin;
281
282 /*
283 * The name is currently registered. See if the commWindow
284 * associated with the name exists. If not, or if the commWindow
285 * is *our* commWindow, then just unregister the old name (this
286 * could happen if an application dies without cleaning up the
287 * registry).
288 */
289 old_handler = XSetErrorHandler(x_error_check);
290 status = XGetGeometry(dpy, w, &dummyWin, &dummyInt, &dummyInt,
291 &dummyUns, &dummyUns, &dummyUns, &dummyUns);
292 (void)XSetErrorHandler(old_handler);
293 if (status != Success && w != commWindow)
294 {
295 XUngrabServer(dpy);
296 XFlush(dpy);
297 return -1;
298 }
299 (void)LookupName(dpy, name, /*delete=*/TRUE, NULL);
300 }
301 sprintf((char *)propInfo, "%x %.*s", (int_u)commWindow,
302 MAX_NAME_LENGTH, name);
303 old_handler = XSetErrorHandler(x_error_check);
304 got_x_error = FALSE;
305 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
306 PropModeAppend, propInfo, STRLEN(propInfo) + 1);
307 XUngrabServer(dpy);
308 XSync(dpy, False);
309 (void)XSetErrorHandler(old_handler);
310
311 if (!got_x_error)
312 {
313 #ifdef FEAT_EVAL
314 set_vim_var_string(VV_SEND_SERVER, name, -1);
315 #endif
316 serverName = vim_strsave(name);
317 need_maketitle = TRUE;
318 return 0;
319 }
320 return -2;
321 }
322
323 #if defined(FEAT_GUI) || defined(PROTO)
324 /*
325 * Clean out new ID from registry and set it as comm win.
326 * Change any registered window ID.
327 */
328 void
serverChangeRegisteredWindow(Display * dpy,Window newwin)329 serverChangeRegisteredWindow(
330 Display *dpy, // Display to register with
331 Window newwin) // Re-register to this ID
332 {
333 char_u propInfo[MAX_NAME_LENGTH + 20];
334
335 commWindow = newwin;
336
337 // Always call SendInit() here, to make sure commWindow is marked as a Vim
338 // window.
339 if (SendInit(dpy) < 0)
340 return;
341
342 // WARNING: Do not step through this while debugging, it will hangup the X
343 // server!
344 XGrabServer(dpy);
345 DeleteAnyLingerer(dpy, newwin);
346 if (serverName != NULL)
347 {
348 // Reinsert name if we was already registered
349 (void)LookupName(dpy, serverName, /*delete=*/TRUE, NULL);
350 sprintf((char *)propInfo, "%x %.*s",
351 (int_u)newwin, MAX_NAME_LENGTH, serverName);
352 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
353 PropModeAppend, (char_u *)propInfo,
354 STRLEN(propInfo) + 1);
355 }
356 XUngrabServer(dpy);
357 }
358 #endif
359
360 /*
361 * Send to an instance of Vim via the X display.
362 * Returns 0 for OK, negative for an error.
363 */
364 int
serverSendToVim(Display * dpy,char_u * name,char_u * cmd,char_u ** result,Window * server,Bool asExpr,int timeout,Bool localLoop,int silent)365 serverSendToVim(
366 Display *dpy, // Where to send.
367 char_u *name, // Where to send.
368 char_u *cmd, // What to send.
369 char_u **result, // Result of eval'ed expression
370 Window *server, // Actual ID of receiving app
371 Bool asExpr, // Interpret as keystrokes or expr ?
372 int timeout, // seconds to wait or zero
373 Bool localLoop, // Throw away everything but result
374 int silent) // don't complain about no server
375 {
376 Window w;
377 char_u *property;
378 int length;
379 int res;
380 static int serial = 0; // Running count of sent commands.
381 // Used to give each command a
382 // different serial number.
383 PendingCommand pending;
384 char_u *loosename = NULL;
385
386 if (result != NULL)
387 *result = NULL;
388 if (name == NULL || *name == NUL)
389 name = (char_u *)"GVIM"; // use a default name
390
391 if (commProperty == None && dpy != NULL)
392 {
393 if (SendInit(dpy) < 0)
394 return -1;
395 }
396
397 // Execute locally if no display or target is ourselves
398 if (dpy == NULL || (serverName != NULL && STRICMP(name, serverName) == 0))
399 return sendToLocalVim(cmd, asExpr, result);
400
401 /*
402 * Bind the server name to a communication window.
403 *
404 * Find any survivor with a serialno attached to the name if the
405 * original registrant of the wanted name is no longer present.
406 *
407 * Delete any lingering names from dead editors.
408 */
409 while (TRUE)
410 {
411 w = LookupName(dpy, name, FALSE, &loosename);
412 // Check that the window is hot
413 if (w != None)
414 {
415 if (!WindowValid(dpy, w))
416 {
417 LookupName(dpy, loosename ? loosename : name,
418 /*DELETE=*/TRUE, NULL);
419 vim_free(loosename);
420 continue;
421 }
422 }
423 break;
424 }
425 if (w == None)
426 {
427 if (!silent)
428 semsg(_(e_noserver), name);
429 return -1;
430 }
431 else if (loosename != NULL)
432 name = loosename;
433 if (server != NULL)
434 *server = w;
435
436 /*
437 * Send the command to target interpreter by appending it to the
438 * comm window in the communication window.
439 * Length must be computed exactly!
440 */
441 length = STRLEN(name) + STRLEN(p_enc) + STRLEN(cmd) + 14;
442 property = alloc(length + 30);
443
444 sprintf((char *)property, "%c%c%c-n %s%c-E %s%c-s %s",
445 0, asExpr ? 'c' : 'k', 0, name, 0, p_enc, 0, cmd);
446 if (name == loosename)
447 vim_free(loosename);
448 // Add a back reference to our comm window
449 serial++;
450 sprintf((char *)property + length, "%c-r %x %d",
451 0, (int_u)commWindow, serial);
452 // Add length of what "-r %x %d" resulted in, skipping the NUL.
453 length += STRLEN(property + length + 1) + 1;
454
455 res = AppendPropCarefully(dpy, w, commProperty, property, length + 1);
456 vim_free(property);
457 if (res < 0)
458 {
459 emsg(_("E248: Failed to send command to the destination program"));
460 return -1;
461 }
462
463 if (!asExpr) // There is no answer for this - Keys are sent async
464 return 0;
465
466 /*
467 * Register the fact that we're waiting for a command to
468 * complete (this is needed by SendEventProc and by
469 * AppendErrorProc to pass back the command's results).
470 */
471 pending.serial = serial;
472 pending.code = 0;
473 pending.result = NULL;
474 pending.nextPtr = pendingCommands;
475 pendingCommands = &pending;
476
477 ServerWait(dpy, w, WaitForPend, &pending, localLoop,
478 timeout > 0 ? timeout : 600);
479
480 /*
481 * Unregister the information about the pending command
482 * and return the result.
483 */
484 if (pendingCommands == &pending)
485 pendingCommands = pending.nextPtr;
486 else
487 {
488 PendingCommand *pcPtr;
489
490 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
491 if (pcPtr->nextPtr == &pending)
492 {
493 pcPtr->nextPtr = pending.nextPtr;
494 break;
495 }
496 }
497 if (result != NULL)
498 *result = pending.result;
499 else
500 vim_free(pending.result);
501
502 return pending.code == 0 ? 0 : -1;
503 }
504
505 static int
WaitForPend(void * p)506 WaitForPend(void *p)
507 {
508 PendingCommand *pending = (PendingCommand *) p;
509 return pending->result != NULL;
510 }
511
512 /*
513 * Return TRUE if window "w" exists and has a "Vim" property on it.
514 */
515 static int
WindowValid(Display * dpy,Window w)516 WindowValid(Display *dpy, Window w)
517 {
518 XErrorHandler old_handler;
519 Atom *plist;
520 int numProp;
521 int i;
522
523 old_handler = XSetErrorHandler(x_error_check);
524 got_x_error = 0;
525 plist = XListProperties(dpy, w, &numProp);
526 XSync(dpy, False);
527 XSetErrorHandler(old_handler);
528 if (plist == NULL || got_x_error)
529 return FALSE;
530
531 for (i = 0; i < numProp; i++)
532 if (plist[i] == vimProperty)
533 {
534 XFree(plist);
535 return TRUE;
536 }
537 XFree(plist);
538 return FALSE;
539 }
540
541 /*
542 * Enter a loop processing X events & polling chars until we see a result
543 */
544 static void
ServerWait(Display * dpy,Window w,EndCond endCond,void * endData,int localLoop,int seconds)545 ServerWait(
546 Display *dpy,
547 Window w,
548 EndCond endCond,
549 void *endData,
550 int localLoop,
551 int seconds)
552 {
553 time_t start;
554 time_t now;
555 XEvent event;
556
557 #define UI_MSEC_DELAY 53
558 #define SEND_MSEC_POLL 500
559 #ifndef HAVE_SELECT
560 struct pollfd fds;
561
562 fds.fd = ConnectionNumber(dpy);
563 fds.events = POLLIN;
564 #else
565 fd_set fds;
566 struct timeval tv;
567
568 tv.tv_sec = 0;
569 tv.tv_usec = SEND_MSEC_POLL * 1000;
570 FD_ZERO(&fds);
571 FD_SET(ConnectionNumber(dpy), &fds);
572 #endif
573
574 time(&start);
575 while (TRUE)
576 {
577 while (XCheckWindowEvent(dpy, commWindow, PropertyChangeMask, &event))
578 serverEventProc(dpy, &event, 1);
579 server_parse_messages();
580
581 if (endCond(endData) != 0)
582 break;
583 if (!WindowValid(dpy, w))
584 break;
585 time(&now);
586 if (seconds >= 0 && (now - start) >= seconds)
587 break;
588
589 #ifdef FEAT_TIMERS
590 check_due_timer();
591 #endif
592
593 // Just look out for the answer without calling back into Vim
594 if (localLoop)
595 {
596 #ifndef HAVE_SELECT
597 if (poll(&fds, 1, SEND_MSEC_POLL) < 0)
598 break;
599 #else
600 if (select(FD_SETSIZE, &fds, NULL, NULL, &tv) < 0)
601 break;
602 #endif
603 }
604 else
605 {
606 if (got_int)
607 break;
608 ui_delay((long)UI_MSEC_DELAY, TRUE);
609 ui_breakcheck();
610 }
611 }
612 }
613
614
615 /*
616 * Fetch a list of all the Vim instance names currently registered for the
617 * display.
618 *
619 * Returns a newline separated list in allocated memory or NULL.
620 */
621 char_u *
serverGetVimNames(Display * dpy)622 serverGetVimNames(Display *dpy)
623 {
624 char_u *regProp;
625 char_u *entry;
626 char_u *p;
627 long_u numItems;
628 int_u w;
629 garray_T ga;
630
631 if (registryProperty == None)
632 {
633 if (SendInit(dpy) < 0)
634 return NULL;
635 }
636
637 /*
638 * Read the registry property.
639 */
640 if (GetRegProp(dpy, ®Prop, &numItems, TRUE) == FAIL)
641 return NULL;
642
643 /*
644 * Scan all of the names out of the property.
645 */
646 ga_init2(&ga, 1, 100);
647 for (p = regProp; (long_u)(p - regProp) < numItems; p++)
648 {
649 entry = p;
650 while (*p != 0 && !isspace(*p))
651 p++;
652 if (*p != 0)
653 {
654 w = None;
655 sscanf((char *)entry, "%x", &w);
656 if (WindowValid(dpy, (Window)w))
657 {
658 ga_concat(&ga, p + 1);
659 ga_concat(&ga, (char_u *)"\n");
660 }
661 while (*p != 0)
662 p++;
663 }
664 }
665 if (regProp != empty_prop)
666 XFree(regProp);
667 ga_append(&ga, NUL);
668 return ga.ga_data;
669 }
670
671 /////////////////////////////////////////////////////////////
672 // Reply stuff
673
674 static struct ServerReply *
ServerReplyFind(Window w,enum ServerReplyOp op)675 ServerReplyFind(Window w, enum ServerReplyOp op)
676 {
677 struct ServerReply *p;
678 struct ServerReply e;
679 int i;
680
681 p = (struct ServerReply *) serverReply.ga_data;
682 for (i = 0; i < serverReply.ga_len; i++, p++)
683 if (p->id == w)
684 break;
685 if (i >= serverReply.ga_len)
686 p = NULL;
687
688 if (p == NULL && op == SROP_Add)
689 {
690 if (serverReply.ga_growsize == 0)
691 ga_init2(&serverReply, sizeof(struct ServerReply), 1);
692 if (ga_grow(&serverReply, 1) == OK)
693 {
694 p = ((struct ServerReply *) serverReply.ga_data)
695 + serverReply.ga_len;
696 e.id = w;
697 ga_init2(&e.strings, 1, 100);
698 mch_memmove(p, &e, sizeof(e));
699 serverReply.ga_len++;
700 }
701 }
702 else if (p != NULL && op == SROP_Delete)
703 {
704 ga_clear(&p->strings);
705 mch_memmove(p, p + 1, (serverReply.ga_len - i - 1) * sizeof(*p));
706 serverReply.ga_len--;
707 }
708
709 return p;
710 }
711
712 /*
713 * Convert string to windowid.
714 * Issue an error if the id is invalid.
715 */
716 Window
serverStrToWin(char_u * str)717 serverStrToWin(char_u *str)
718 {
719 unsigned id = None;
720
721 sscanf((char *)str, "0x%x", &id);
722 if (id == None)
723 semsg(_("E573: Invalid server id used: %s"), str);
724
725 return (Window)id;
726 }
727
728 /*
729 * Send a reply string (notification) to client with id "name".
730 * Return -1 if the window is invalid.
731 */
732 int
serverSendReply(char_u * name,char_u * str)733 serverSendReply(char_u *name, char_u *str)
734 {
735 char_u *property;
736 int length;
737 int res;
738 Display *dpy = X_DISPLAY;
739 Window win = serverStrToWin(name);
740
741 if (commProperty == None)
742 {
743 if (SendInit(dpy) < 0)
744 return -2;
745 }
746 if (!WindowValid(dpy, win))
747 return -1;
748
749 length = STRLEN(p_enc) + STRLEN(str) + 14;
750 if ((property = alloc(length + 30)) != NULL)
751 {
752 sprintf((char *)property, "%cn%c-E %s%c-n %s%c-w %x",
753 0, 0, p_enc, 0, str, 0, (unsigned int)commWindow);
754 // Add length of what "%x" resulted in.
755 length += STRLEN(property + length);
756 res = AppendPropCarefully(dpy, win, commProperty, property, length + 1);
757 vim_free(property);
758 return res;
759 }
760 return -1;
761 }
762
763 static int
WaitForReply(void * p)764 WaitForReply(void *p)
765 {
766 Window *w = (Window *) p;
767
768 return ServerReplyFind(*w, SROP_Find) != NULL;
769 }
770
771 /*
772 * Wait for replies from id (win)
773 * When "timeout" is non-zero wait up to this many seconds.
774 * Return 0 and the malloc'ed string when a reply is available.
775 * Return -1 if the window becomes invalid while waiting.
776 */
777 int
serverReadReply(Display * dpy,Window win,char_u ** str,int localLoop,int timeout)778 serverReadReply(
779 Display *dpy,
780 Window win,
781 char_u **str,
782 int localLoop,
783 int timeout)
784 {
785 int len;
786 char_u *s;
787 struct ServerReply *p;
788
789 ServerWait(dpy, win, WaitForReply, &win, localLoop,
790 timeout > 0 ? timeout : -1);
791
792 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
793 {
794 *str = vim_strsave(p->strings.ga_data);
795 len = STRLEN(*str) + 1;
796 if (len < p->strings.ga_len)
797 {
798 s = (char_u *) p->strings.ga_data;
799 mch_memmove(s, s + len, p->strings.ga_len - len);
800 p->strings.ga_len -= len;
801 }
802 else
803 {
804 // Last string read. Remove from list
805 ga_clear(&p->strings);
806 ServerReplyFind(win, SROP_Delete);
807 }
808 return 0;
809 }
810 return -1;
811 }
812
813 /*
814 * Check for replies from id (win).
815 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
816 */
817 int
serverPeekReply(Display * dpy,Window win,char_u ** str)818 serverPeekReply(Display *dpy, Window win, char_u **str)
819 {
820 struct ServerReply *p;
821
822 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
823 {
824 if (str != NULL)
825 *str = p->strings.ga_data;
826 return 1;
827 }
828 if (!WindowValid(dpy, win))
829 return -1;
830 return 0;
831 }
832
833
834 /*
835 * Initialize the communication channels for sending commands and receiving
836 * results.
837 */
838 static int
SendInit(Display * dpy)839 SendInit(Display *dpy)
840 {
841 XErrorHandler old_handler;
842
843 /*
844 * Create the window used for communication, and set up an
845 * event handler for it.
846 */
847 old_handler = XSetErrorHandler(x_error_check);
848 got_x_error = FALSE;
849
850 if (commProperty == None)
851 commProperty = XInternAtom(dpy, "Comm", False);
852 if (vimProperty == None)
853 vimProperty = XInternAtom(dpy, "Vim", False);
854 if (registryProperty == None)
855 registryProperty = XInternAtom(dpy, "VimRegistry", False);
856
857 if (commWindow == None)
858 {
859 commWindow = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy),
860 getpid(), 0, 10, 10, 0,
861 WhitePixel(dpy, DefaultScreen(dpy)),
862 WhitePixel(dpy, DefaultScreen(dpy)));
863 XSelectInput(dpy, commWindow, PropertyChangeMask);
864 // WARNING: Do not step through this while debugging, it will hangup
865 // the X server!
866 XGrabServer(dpy);
867 DeleteAnyLingerer(dpy, commWindow);
868 XUngrabServer(dpy);
869 }
870
871 // Make window recognizable as a vim window
872 XChangeProperty(dpy, commWindow, vimProperty, XA_STRING,
873 8, PropModeReplace, (char_u *)VIM_VERSION_SHORT,
874 (int)STRLEN(VIM_VERSION_SHORT) + 1);
875
876 XSync(dpy, False);
877 (void)XSetErrorHandler(old_handler);
878
879 return got_x_error ? -1 : 0;
880 }
881
882 /*
883 * Given a server name, see if the name exists in the registry for a
884 * particular display.
885 *
886 * If the given name is registered, return the ID of the window associated
887 * with the name. If the name isn't registered, then return 0.
888 *
889 * Side effects:
890 * If the registry property is improperly formed, then it is deleted.
891 * If "delete" is non-zero, then if the named server is found it is
892 * removed from the registry property.
893 */
894 static Window
LookupName(Display * dpy,char_u * name,int delete,char_u ** loose)895 LookupName(
896 Display *dpy, // Display whose registry to check.
897 char_u *name, // Name of a server.
898 int delete, // If non-zero, delete info about name.
899 char_u **loose) // Do another search matching -999 if not found
900 // Return result here if a match is found
901 {
902 char_u *regProp, *entry;
903 char_u *p;
904 long_u numItems;
905 int_u returnValue;
906
907 /*
908 * Read the registry property.
909 */
910 if (GetRegProp(dpy, ®Prop, &numItems, FALSE) == FAIL)
911 return 0;
912
913 /*
914 * Scan the property for the desired name.
915 */
916 returnValue = (int_u)None;
917 entry = NULL; // Not needed, but eliminates compiler warning.
918 for (p = regProp; (long_u)(p - regProp) < numItems; )
919 {
920 entry = p;
921 while (*p != 0 && !isspace(*p))
922 p++;
923 if (*p != 0 && STRICMP(name, p + 1) == 0)
924 {
925 sscanf((char *)entry, "%x", &returnValue);
926 break;
927 }
928 while (*p != 0)
929 p++;
930 p++;
931 }
932
933 if (loose != NULL && returnValue == (int_u)None && !IsSerialName(name))
934 {
935 for (p = regProp; (long_u)(p - regProp) < numItems; )
936 {
937 entry = p;
938 while (*p != 0 && !isspace(*p))
939 p++;
940 if (*p != 0 && IsSerialName(p + 1)
941 && STRNICMP(name, p + 1, STRLEN(name)) == 0)
942 {
943 sscanf((char *)entry, "%x", &returnValue);
944 *loose = vim_strsave(p + 1);
945 break;
946 }
947 while (*p != 0)
948 p++;
949 p++;
950 }
951 }
952
953 /*
954 * Delete the property, if that is desired (copy down the
955 * remainder of the registry property to overlay the deleted
956 * info, then rewrite the property).
957 */
958 if (delete && returnValue != (int_u)None)
959 {
960 int count;
961
962 while (*p != 0)
963 p++;
964 p++;
965 count = numItems - (p - regProp);
966 if (count > 0)
967 mch_memmove(entry, p, count);
968 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING,
969 8, PropModeReplace, regProp,
970 (int)(numItems - (p - entry)));
971 XSync(dpy, False);
972 }
973
974 if (regProp != empty_prop)
975 XFree(regProp);
976 return (Window)returnValue;
977 }
978
979 /*
980 * Delete any lingering occurrence of window id. We promise that any
981 * occurrence is not ours since it is not yet put into the registry (by us)
982 *
983 * This is necessary in the following scenario:
984 * 1. There is an old windowid for an exit'ed vim in the registry
985 * 2. We get that id for our commWindow but only want to send, not register.
986 * 3. The window will mistakenly be regarded valid because of own commWindow
987 */
988 static void
DeleteAnyLingerer(Display * dpy,Window win)989 DeleteAnyLingerer(
990 Display *dpy, // Display whose registry to check.
991 Window win) // Window to remove
992 {
993 char_u *regProp, *entry = NULL;
994 char_u *p;
995 long_u numItems;
996 int_u wwin;
997
998 /*
999 * Read the registry property.
1000 */
1001 if (GetRegProp(dpy, ®Prop, &numItems, FALSE) == FAIL)
1002 return;
1003
1004 // Scan the property for the window id.
1005 for (p = regProp; (long_u)(p - regProp) < numItems; )
1006 {
1007 if (*p != 0)
1008 {
1009 sscanf((char *)p, "%x", &wwin);
1010 if ((Window)wwin == win)
1011 {
1012 int lastHalf;
1013
1014 // Copy down the remainder to delete entry
1015 entry = p;
1016 while (*p != 0)
1017 p++;
1018 p++;
1019 lastHalf = numItems - (p - regProp);
1020 if (lastHalf > 0)
1021 mch_memmove(entry, p, lastHalf);
1022 numItems = (entry - regProp) + lastHalf;
1023 p = entry;
1024 continue;
1025 }
1026 }
1027 while (*p != 0)
1028 p++;
1029 p++;
1030 }
1031
1032 if (entry != NULL)
1033 {
1034 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty,
1035 XA_STRING, 8, PropModeReplace, regProp,
1036 (int)(p - regProp));
1037 XSync(dpy, False);
1038 }
1039
1040 if (regProp != empty_prop)
1041 XFree(regProp);
1042 }
1043
1044 /*
1045 * Read the registry property. Delete it when it's formatted wrong.
1046 * Return the property in "regPropp". "empty_prop" is used when it doesn't
1047 * exist yet.
1048 * Return OK when successful.
1049 */
1050 static int
GetRegProp(Display * dpy,char_u ** regPropp,long_u * numItemsp,int domsg)1051 GetRegProp(
1052 Display *dpy,
1053 char_u **regPropp,
1054 long_u *numItemsp,
1055 int domsg) // When TRUE give error message.
1056 {
1057 int result, actualFormat;
1058 long_u bytesAfter;
1059 Atom actualType;
1060 XErrorHandler old_handler;
1061
1062 *regPropp = NULL;
1063 old_handler = XSetErrorHandler(x_error_check);
1064 got_x_error = FALSE;
1065
1066 result = XGetWindowProperty(dpy, RootWindow(dpy, 0), registryProperty, 0L,
1067 (long)MAX_PROP_WORDS, False,
1068 XA_STRING, &actualType,
1069 &actualFormat, numItemsp, &bytesAfter,
1070 regPropp);
1071
1072 XSync(dpy, FALSE);
1073 (void)XSetErrorHandler(old_handler);
1074 if (got_x_error)
1075 return FAIL;
1076
1077 if (actualType == None)
1078 {
1079 // No prop yet. Logically equal to the empty list
1080 *numItemsp = 0;
1081 *regPropp = empty_prop;
1082 return OK;
1083 }
1084
1085 // If the property is improperly formed, then delete it.
1086 if (result != Success || actualFormat != 8 || actualType != XA_STRING)
1087 {
1088 if (*regPropp != NULL)
1089 XFree(*regPropp);
1090 XDeleteProperty(dpy, RootWindow(dpy, 0), registryProperty);
1091 if (domsg)
1092 emsg(_("E251: VIM instance registry property is badly formed. Deleted!"));
1093 return FAIL;
1094 }
1095 return OK;
1096 }
1097
1098
1099 /*
1100 * This procedure is invoked by the various X event loops throughout Vims when
1101 * a property changes on the communication window. This procedure reads the
1102 * property and enqueues command requests and responses. If immediate is true,
1103 * it runs the event immediately instead of enqueuing it. Immediate can cause
1104 * unintended behavior and should only be used for code that blocks for a
1105 * response.
1106 */
1107 void
serverEventProc(Display * dpy,XEvent * eventPtr,int immediate)1108 serverEventProc(
1109 Display *dpy,
1110 XEvent *eventPtr, // Information about event.
1111 int immediate) // Run event immediately. Should mostly be 0.
1112 {
1113 char_u *propInfo;
1114 int result, actualFormat;
1115 long_u numItems, bytesAfter;
1116 Atom actualType;
1117
1118 if (eventPtr != NULL)
1119 {
1120 if (eventPtr->xproperty.atom != commProperty
1121 || eventPtr->xproperty.state != PropertyNewValue)
1122 return;
1123 }
1124
1125 /*
1126 * Read the comm property and delete it.
1127 */
1128 propInfo = NULL;
1129 result = XGetWindowProperty(dpy, commWindow, commProperty, 0L,
1130 (long)MAX_PROP_WORDS, True,
1131 XA_STRING, &actualType,
1132 &actualFormat, &numItems, &bytesAfter,
1133 &propInfo);
1134
1135 // If the property doesn't exist or is improperly formed then ignore it.
1136 if (result != Success || actualType != XA_STRING || actualFormat != 8)
1137 {
1138 if (propInfo != NULL)
1139 XFree(propInfo);
1140 return;
1141 }
1142 if (immediate)
1143 server_parse_message(dpy, propInfo, numItems);
1144 else
1145 save_in_queue(propInfo, numItems);
1146 }
1147
1148 /*
1149 * Saves x clientserver commands in a queue so that they can be called when
1150 * vim is idle.
1151 */
1152 static void
save_in_queue(char_u * propInfo,long_u len)1153 save_in_queue(char_u *propInfo, long_u len)
1154 {
1155 x_queue_T *node;
1156
1157 node = ALLOC_ONE(x_queue_T);
1158 if (node == NULL)
1159 return; // out of memory
1160 node->propInfo = propInfo;
1161 node->len = len;
1162
1163 if (head.next == NULL) // initialize circular queue
1164 {
1165 head.next = &head;
1166 head.prev = &head;
1167 }
1168
1169 // insert node at tail of queue
1170 node->next = &head;
1171 node->prev = head.prev;
1172 head.prev->next = node;
1173 head.prev = node;
1174 }
1175
1176 /*
1177 * Parses queued clientserver messages.
1178 */
1179 void
server_parse_messages(void)1180 server_parse_messages(void)
1181 {
1182 x_queue_T *node;
1183
1184 if (!X_DISPLAY)
1185 return; // cannot happen?
1186 while (head.next != NULL && head.next != &head)
1187 {
1188 node = head.next;
1189 head.next = node->next;
1190 node->next->prev = node->prev;
1191 server_parse_message(X_DISPLAY, node->propInfo, node->len);
1192 vim_free(node);
1193 }
1194 }
1195
1196 /*
1197 * Returns a non-zero value if there are clientserver messages waiting
1198 * int the queue.
1199 */
1200 int
server_waiting(void)1201 server_waiting(void)
1202 {
1203 return head.next != NULL && head.next != &head;
1204 }
1205
1206 /*
1207 * Prases a single clientserver message. A single message may contain multiple
1208 * commands.
1209 * "propInfo" will be freed.
1210 */
1211 static void
server_parse_message(Display * dpy,char_u * propInfo,long_u numItems)1212 server_parse_message(
1213 Display *dpy,
1214 char_u *propInfo, // A string containing 0 or more X commands
1215 long_u numItems) // The size of propInfo in bytes.
1216 {
1217 char_u *p;
1218 int code;
1219 char_u *tofree;
1220
1221 /*
1222 * Several commands and results could arrive in the property at
1223 * one time; each iteration through the outer loop handles a
1224 * single command or result.
1225 */
1226 for (p = propInfo; (long_u)(p - propInfo) < numItems; )
1227 {
1228 /*
1229 * Ignore leading NULs; each command or result starts with a
1230 * NUL so that no matter how badly formed a preceding command
1231 * is, we'll be able to tell that a new command/result is
1232 * starting.
1233 */
1234 if (*p == 0)
1235 {
1236 p++;
1237 continue;
1238 }
1239
1240 if ((*p == 'c' || *p == 'k') && (p[1] == 0))
1241 {
1242 Window resWindow;
1243 char_u *name, *script, *serial, *end;
1244 Bool asKeys = *p == 'k';
1245 char_u *enc;
1246
1247 /*
1248 * This is an incoming command from some other application.
1249 * Iterate over all of its options. Stop when we reach
1250 * the end of the property or something that doesn't look
1251 * like an option.
1252 */
1253 p += 2;
1254 name = NULL;
1255 resWindow = None;
1256 serial = (char_u *)"";
1257 script = NULL;
1258 enc = NULL;
1259 while ((long_u)(p - propInfo) < numItems && *p == '-')
1260 {
1261 switch (p[1])
1262 {
1263 case 'r':
1264 end = skipwhite(p + 2);
1265 resWindow = 0;
1266 while (vim_isxdigit(*end))
1267 {
1268 resWindow = 16 * resWindow + (long_u)hex2nr(*end);
1269 ++end;
1270 }
1271 if (end == p + 2 || *end != ' ')
1272 resWindow = None;
1273 else
1274 {
1275 p = serial = end + 1;
1276 clientWindow = resWindow; // Remember in global
1277 }
1278 break;
1279 case 'n':
1280 if (p[2] == ' ')
1281 name = p + 3;
1282 break;
1283 case 's':
1284 if (p[2] == ' ')
1285 script = p + 3;
1286 break;
1287 case 'E':
1288 if (p[2] == ' ')
1289 enc = p + 3;
1290 break;
1291 }
1292 while (*p != 0)
1293 p++;
1294 p++;
1295 }
1296
1297 if (script == NULL || name == NULL)
1298 continue;
1299
1300 if (serverName != NULL && STRICMP(name, serverName) == 0)
1301 {
1302 script = serverConvert(enc, script, &tofree);
1303 if (asKeys)
1304 server_to_input_buf(script);
1305 else
1306 {
1307 char_u *res;
1308
1309 res = eval_client_expr_to_string(script);
1310 if (resWindow != None)
1311 {
1312 garray_T reply;
1313
1314 // Initialize the result property.
1315 ga_init2(&reply, 1, 100);
1316 (void)ga_grow(&reply, 50 + STRLEN(p_enc));
1317 sprintf(reply.ga_data, "%cr%c-E %s%c-s %s%c-r ",
1318 0, 0, p_enc, 0, serial, 0);
1319 reply.ga_len = 14 + STRLEN(p_enc) + STRLEN(serial);
1320
1321 // Evaluate the expression and return the result.
1322 if (res != NULL)
1323 ga_concat(&reply, res);
1324 else
1325 {
1326 ga_concat(&reply, (char_u *)_(e_invexprmsg));
1327 ga_append(&reply, 0);
1328 ga_concat(&reply, (char_u *)"-c 1");
1329 }
1330 ga_append(&reply, NUL);
1331 (void)AppendPropCarefully(dpy, resWindow, commProperty,
1332 reply.ga_data, reply.ga_len);
1333 ga_clear(&reply);
1334 }
1335 vim_free(res);
1336 }
1337 vim_free(tofree);
1338 }
1339 }
1340 else if (*p == 'r' && p[1] == 0)
1341 {
1342 int serial, gotSerial;
1343 char_u *res;
1344 PendingCommand *pcPtr;
1345 char_u *enc;
1346
1347 /*
1348 * This is a reply to some command that we sent out. Iterate
1349 * over all of its options. Stop when we reach the end of the
1350 * property or something that doesn't look like an option.
1351 */
1352 p += 2;
1353 gotSerial = 0;
1354 res = (char_u *)"";
1355 code = 0;
1356 enc = NULL;
1357 while ((long_u)(p - propInfo) < numItems && *p == '-')
1358 {
1359 switch (p[1])
1360 {
1361 case 'r':
1362 if (p[2] == ' ')
1363 res = p + 3;
1364 break;
1365 case 'E':
1366 if (p[2] == ' ')
1367 enc = p + 3;
1368 break;
1369 case 's':
1370 if (sscanf((char *)p + 2, " %d", &serial) == 1)
1371 gotSerial = 1;
1372 break;
1373 case 'c':
1374 if (sscanf((char *)p + 2, " %d", &code) != 1)
1375 code = 0;
1376 break;
1377 }
1378 while (*p != 0)
1379 p++;
1380 p++;
1381 }
1382
1383 if (!gotSerial)
1384 continue;
1385
1386 /*
1387 * Give the result information to anyone who's
1388 * waiting for it.
1389 */
1390 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
1391 {
1392 if (serial != pcPtr->serial || pcPtr->result != NULL)
1393 continue;
1394
1395 pcPtr->code = code;
1396 res = serverConvert(enc, res, &tofree);
1397 if (tofree == NULL)
1398 res = vim_strsave(res);
1399 pcPtr->result = res;
1400 break;
1401 }
1402 }
1403 else if (*p == 'n' && p[1] == 0)
1404 {
1405 Window win = 0;
1406 unsigned int u;
1407 int gotWindow;
1408 char_u *str;
1409 struct ServerReply *r;
1410 char_u *enc;
1411
1412 /*
1413 * This is a (n)otification. Sent with serverreply_send in Vim
1414 * script. Execute any autocommand and save it for later retrieval
1415 */
1416 p += 2;
1417 gotWindow = 0;
1418 str = (char_u *)"";
1419 enc = NULL;
1420 while ((long_u)(p - propInfo) < numItems && *p == '-')
1421 {
1422 switch (p[1])
1423 {
1424 case 'n':
1425 if (p[2] == ' ')
1426 str = p + 3;
1427 break;
1428 case 'E':
1429 if (p[2] == ' ')
1430 enc = p + 3;
1431 break;
1432 case 'w':
1433 if (sscanf((char *)p + 2, " %x", &u) == 1)
1434 {
1435 win = u;
1436 gotWindow = 1;
1437 }
1438 break;
1439 }
1440 while (*p != 0)
1441 p++;
1442 p++;
1443 }
1444
1445 if (!gotWindow)
1446 continue;
1447 str = serverConvert(enc, str, &tofree);
1448 if ((r = ServerReplyFind(win, SROP_Add)) != NULL)
1449 {
1450 ga_concat(&(r->strings), str);
1451 ga_append(&(r->strings), NUL);
1452 }
1453 {
1454 char_u winstr[30];
1455
1456 sprintf((char *)winstr, "0x%x", (unsigned int)win);
1457 apply_autocmds(EVENT_REMOTEREPLY, winstr, str, TRUE, curbuf);
1458 }
1459 vim_free(tofree);
1460 }
1461 else
1462 {
1463 /*
1464 * Didn't recognize this thing. Just skip through the next
1465 * null character and try again.
1466 * Even if we get an 'r'(eply) we will throw it away as we
1467 * never specify (and thus expect) one
1468 */
1469 while (*p != 0)
1470 p++;
1471 p++;
1472 }
1473 }
1474 XFree(propInfo);
1475 }
1476
1477 /*
1478 * Append a given property to a given window, but set up an X error handler so
1479 * that if the append fails this procedure can return an error code rather
1480 * than having Xlib panic.
1481 * Return: 0 for OK, -1 for error
1482 */
1483 static int
AppendPropCarefully(Display * dpy,Window window,Atom property,char_u * value,int length)1484 AppendPropCarefully(
1485 Display *dpy, // Display on which to operate.
1486 Window window, // Window whose property is to be modified.
1487 Atom property, // Name of property.
1488 char_u *value, // Characters to append to property.
1489 int length) // How much to append
1490 {
1491 XErrorHandler old_handler;
1492
1493 old_handler = XSetErrorHandler(x_error_check);
1494 got_x_error = FALSE;
1495 XChangeProperty(dpy, window, property, XA_STRING, 8,
1496 PropModeAppend, value, length);
1497 XSync(dpy, False);
1498 (void) XSetErrorHandler(old_handler);
1499 return got_x_error ? -1 : 0;
1500 }
1501
1502
1503 /*
1504 * Another X Error handler, just used to check for errors.
1505 */
1506 static int
x_error_check(Display * dpy UNUSED,XErrorEvent * error_event UNUSED)1507 x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
1508 {
1509 got_x_error = TRUE;
1510 return 0;
1511 }
1512
1513 /*
1514 * Check if "str" looks like it had a serial number appended.
1515 * Actually just checks if the name ends in a digit.
1516 */
1517 static int
IsSerialName(char_u * str)1518 IsSerialName(char_u *str)
1519 {
1520 int len = STRLEN(str);
1521
1522 return (len > 1 && vim_isdigit(str[len - 1]));
1523 }
1524 #endif // FEAT_CLIENTSERVER
1525