root/lib-src/emacsclient.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. xmalloc
  2. xrealloc
  3. xstrdup
  4. get_current_dir_name
  5. w32_get_resource
  6. w32_getenv
  7. w32_window_app
  8. w32_execvp
  9. ttyname
  10. message
  11. decode_options
  12. print_help_and_exit
  13. fail
  14. act_on_signals
  15. init_signals
  16. sock_err_message
  17. send_to_emacs
  18. quote_argument
  19. unquote_argument
  20. close_winsock
  21. initialize_sockets
  22. open_config
  23. get_server_config
  24. cloexec_socket
  25. set_tcp_socket
  26. strprefix
  27. find_tty
  28. process_grouping
  29. connect_socket
  30. reinstall_handler_if_needed
  31. handle_sigcont
  32. handle_sigtstp
  33. handle_sigttou
  34. handle_sigwinch
  35. install_handler
  36. init_signals
  37. act_on_tty_signal
  38. act_on_signals
  39. local_sockname
  40. set_local_socket
  41. set_socket
  42. w32_set_user_model_id
  43. w32_find_emacs_process
  44. w32_give_focus
  45. start_daemon_and_retry_set_socket
  46. set_socket_timeout
  47. check_socket_timeout
  48. main

     1 /* Client process that communicates with GNU Emacs acting as server.
     2 
     3 Copyright (C) 1986-2023 Free Software Foundation, Inc.
     4 
     5 This file is part of GNU Emacs.
     6 
     7 GNU Emacs is free software: you can redistribute it and/or modify
     8 it under the terms of the GNU General Public License as published by
     9 the Free Software Foundation, either version 3 of the License, or (at
    10 your option) any later version.
    11 
    12 GNU Emacs is distributed in the hope that it will be useful,
    13 but WITHOUT ANY WARRANTY; without even the implied warranty of
    14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    15 GNU General Public License for more details.
    16 
    17 You should have received a copy of the GNU General Public License
    18 along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
    19 
    20 
    21 #include <config.h>
    22 
    23 #ifdef WINDOWSNT
    24 
    25 /* ms-w32.h defines these, which disables sockets altogether!  */
    26 # undef _WINSOCKAPI_
    27 # undef _WINSOCK_H
    28 
    29 # include <malloc.h>
    30 # include <windows.h>
    31 # include <commctrl.h>
    32 # include <io.h>
    33 # include <winsock2.h>
    34 
    35 # define HSOCKET SOCKET
    36 # define CLOSE_SOCKET closesocket
    37 # define INITIALIZE() initialize_sockets ()
    38 
    39 char *w32_getenv (const char *);
    40 # define egetenv(VAR) w32_getenv (VAR)
    41 
    42 # undef signal
    43 
    44 #else /* !WINDOWSNT */
    45 
    46 # ifdef HAVE_NTGUI
    47 #  include <windows.h>
    48 # endif
    49 
    50 # include "syswait.h"
    51 
    52 # include <arpa/inet.h>
    53 # include <fcntl.h>
    54 # include <netinet/in.h>
    55 # include <sys/socket.h>
    56 # include <sys/un.h>
    57 
    58 # define SOCKETS_IN_FILE_SYSTEM
    59 
    60 # define INVALID_SOCKET (-1)
    61 # define HSOCKET int
    62 # define CLOSE_SOCKET close
    63 # define INITIALIZE()
    64 
    65 # define egetenv(VAR) getenv (VAR)
    66 
    67 #endif /* !WINDOWSNT */
    68 
    69 #define DEFAULT_TIMEOUT (30)
    70 
    71 #include <ctype.h>
    72 #include <errno.h>
    73 #include <getopt.h>
    74 #include <inttypes.h>
    75 #include <pwd.h>
    76 #include <signal.h>
    77 #include <stdarg.h>
    78 #include <stddef.h>
    79 #include <stdint.h>
    80 #include <stdlib.h>
    81 #include <string.h>
    82 #include <sys/stat.h>
    83 #include <unistd.h>
    84 
    85 #include <attribute.h>
    86 #include <filename.h>
    87 #include <intprops.h>
    88 #include <min-max.h>
    89 #include <pathmax.h>
    90 #include <unlocked-io.h>
    91 
    92 /* Work around GCC bug 88251.  */
    93 #if GNUC_PREREQ (7, 0, 0)
    94 # pragma GCC diagnostic ignored "-Wformat-truncation=2"
    95 #endif
    96 
    97 
    98 /* Name used to invoke this program.  */
    99 static char const *progname;
   100 
   101 /* The first argument to main.  */
   102 static int main_argc;
   103 
   104 /* The second argument to main.  */
   105 static char *const *main_argv;
   106 
   107 /* True means don't wait for a response from Emacs.  --no-wait.  */
   108 static bool nowait;
   109 
   110 /* True means don't print messages for successful operations.  --quiet.  */
   111 static bool quiet;
   112 
   113 /* True means don't print values returned from emacs. --suppress-output.  */
   114 static bool suppress_output;
   115 
   116 /* True means args are expressions to be evaluated.  --eval.  */
   117 static bool eval;
   118 
   119 /* True means open a new frame.  --create-frame etc.  */
   120 static bool create_frame;
   121 
   122 /* True means reuse a frame if it already exists.  */
   123 static bool reuse_frame;
   124 
   125 /* The display on which Emacs should work.  --display.  */
   126 static char const *display;
   127 
   128 /* The alternate display we should try if Emacs does not support display.  */
   129 static char const *alt_display;
   130 
   131 /* The parent window ID, if we are opening a frame via XEmbed.  */
   132 static char *parent_id;
   133 
   134 /* True means open a new Emacs frame on the current terminal.  */
   135 static bool tty;
   136 
   137 /* If non-NULL, the name of an editor to fallback to if the server
   138    is not running.  --alternate-editor.   */
   139 static char *alternate_editor;
   140 
   141 #ifdef SOCKETS_IN_FILE_SYSTEM
   142 /* If non-NULL, the filename of the UNIX socket.  */
   143 static char const *socket_name;
   144 #endif
   145 
   146 /* If non-NULL, the filename of the authentication file.  */
   147 static char const *server_file;
   148 
   149 /* Seconds to wait before timing out (0 means wait forever).  */
   150 static uintmax_t timeout;
   151 
   152 /* If non-NULL, the tramp prefix emacs must use to find the files.  */
   153 static char const *tramp_prefix;
   154 
   155 /* If nonzero, PID of the Emacs server process.  */
   156 static pid_t emacs_pid;
   157 
   158 /* If non-NULL, a string that should form a frame parameter alist to
   159    be used for the new frame.  */
   160 static char const *frame_parameters;
   161 
   162 static _Noreturn void print_help_and_exit (void);
   163 
   164 /* Long command-line options.  */
   165 
   166 static struct option const longopts[] =
   167 {
   168   { "no-wait",  no_argument,       NULL, 'n' },
   169   { "quiet",    no_argument,       NULL, 'q' },
   170   { "suppress-output", no_argument, NULL, 'u' },
   171   { "eval",     no_argument,       NULL, 'e' },
   172   { "help",     no_argument,       NULL, 'H' },
   173   { "version",  no_argument,       NULL, 'V' },
   174   { "tty",      no_argument,       NULL, 't' },
   175   { "nw",       no_argument,       NULL, 't' },
   176   { "create-frame", no_argument,   NULL, 'c' },
   177   { "reuse-frame", no_argument,   NULL, 'r' },
   178   { "alternate-editor", required_argument, NULL, 'a' },
   179   { "frame-parameters", required_argument, NULL, 'F' },
   180 #ifdef SOCKETS_IN_FILE_SYSTEM
   181   { "socket-name",      required_argument, NULL, 's' },
   182 #endif
   183   { "server-file",      required_argument, NULL, 'f' },
   184   { "display",  required_argument, NULL, 'd' },
   185   { "parent-id", required_argument, NULL, 'p' },
   186   { "timeout",  required_argument, NULL, 'w' },
   187   { "tramp",    required_argument, NULL, 'T' },
   188   { 0, 0, 0, 0 }
   189 };
   190 
   191 /* Short options, in the same order as the corresponding long options.
   192    There is no '-p' short option.  */
   193 static char const shortopts[] =
   194   "nqueHVtca:F:w:"
   195 #ifdef SOCKETS_IN_FILE_SYSTEM
   196   "s:"
   197 #endif
   198   "f:d:T:";
   199 
   200 
   201 /* Like malloc but get fatal error if memory is exhausted.  */
   202 
   203 static void * ATTRIBUTE_MALLOC
   204 xmalloc (size_t size)
   205 {
   206   void *result = malloc (size);
   207   if (result == NULL)
   208     {
   209       perror ("malloc");
   210       exit (EXIT_FAILURE);
   211     }
   212   return result;
   213 }
   214 
   215 /* Like realloc but get fatal error if memory is exhausted.  */
   216 
   217 static void *
   218 xrealloc (void *ptr, size_t size)
   219 {
   220   void *result = realloc (ptr, size);
   221   if (result == NULL)
   222     {
   223       perror ("realloc");
   224       exit (EXIT_FAILURE);
   225     }
   226   return result;
   227 }
   228 
   229 /* Like strdup but get a fatal error if memory is exhausted. */
   230 
   231 static char * ATTRIBUTE_MALLOC
   232 xstrdup (const char *s)
   233 {
   234   char *result = strdup (s);
   235   if (result == NULL)
   236     {
   237       perror ("strdup");
   238       exit (EXIT_FAILURE);
   239     }
   240   return result;
   241 }
   242 
   243 /* From sysdep.c */
   244 #if !defined HAVE_GET_CURRENT_DIR_NAME || defined BROKEN_GET_CURRENT_DIR_NAME
   245 
   246 char *get_current_dir_name (void);
   247 
   248 /* Return the current working directory.  Returns NULL on errors.
   249    Any other returned value must be freed with free.  This is used
   250    only when get_current_dir_name is not defined on the system.  */
   251 char *
   252 get_current_dir_name (void)
   253 {
   254   /* The maximum size of a directory name, including the terminating NUL.
   255      Leave room so that the caller can append a trailing slash.  */
   256   ptrdiff_t dirsize_max = min (PTRDIFF_MAX, SIZE_MAX) - 1;
   257 
   258   /* The maximum size of a buffer for a file name, including the
   259      terminating NUL.  This is bounded by PATH_MAX, if available.  */
   260   ptrdiff_t bufsize_max = dirsize_max;
   261 #ifdef PATH_MAX
   262   bufsize_max = min (bufsize_max, PATH_MAX);
   263 #endif
   264 
   265   struct stat dotstat, pwdstat;
   266   size_t pwdlen;
   267   /* If PWD is accurate, use it instead of calling getcwd.  PWD is
   268      sometimes a nicer name, and using it may avoid a fatal error if a
   269      parent directory is searchable but not readable.  */
   270   char const *pwd = egetenv ("PWD");
   271   if (pwd
   272       && (pwdlen = strnlen (pwd, bufsize_max)) < bufsize_max
   273       && IS_DIRECTORY_SEP (pwd[pwdlen && IS_DEVICE_SEP (pwd[1]) ? 2 : 0])
   274       && stat (pwd, &pwdstat) == 0
   275       && stat (".", &dotstat) == 0
   276       && dotstat.st_ino == pwdstat.st_ino
   277       && dotstat.st_dev == pwdstat.st_dev)
   278     return strdup (pwd);
   279   else
   280     {
   281       ptrdiff_t buf_size = min (bufsize_max, 1024);
   282       for (;;)
   283         {
   284           char *buf = malloc (buf_size);
   285           if (!buf)
   286             return NULL;
   287           if (getcwd (buf, buf_size) == buf)
   288             return buf;
   289           free (buf);
   290           if (errno != ERANGE || buf_size == bufsize_max)
   291             return NULL;
   292           buf_size = buf_size <= bufsize_max / 2 ? 2 * buf_size : bufsize_max;
   293         }
   294     }
   295 }
   296 #endif
   297 
   298 #ifdef WINDOWSNT
   299 
   300 # define REG_ROOT "SOFTWARE\\GNU\\Emacs"
   301 
   302 char *w32_get_resource (HKEY, const char *, LPDWORD);
   303 
   304 /* Retrieve an environment variable from the Emacs subkeys of the registry.
   305    Return NULL if the variable was not found, or it was empty.
   306    This code is based on w32_get_resource (w32.c).  */
   307 char *
   308 w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
   309 {
   310   HKEY hrootkey = NULL;
   311   char *result = NULL;
   312   DWORD cbData;
   313 
   314   if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey)
   315       == ERROR_SUCCESS)
   316     {
   317       if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData)
   318           == ERROR_SUCCESS)
   319         {
   320           result = xmalloc (cbData);
   321 
   322           if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE) result,
   323                                 &cbData)
   324                != ERROR_SUCCESS)
   325               || *result == 0)
   326             {
   327               free (result);
   328               result = NULL;
   329             }
   330         }
   331 
   332       RegCloseKey (hrootkey);
   333     }
   334 
   335   return result;
   336 }
   337 
   338 /*
   339   getenv wrapper for Windows
   340 
   341   Value is allocated on the heap, and can be free'd.
   342 
   343   This is needed to duplicate Emacs's behavior, which is to look for
   344   environment variables in the registry if they don't appear in the
   345   environment.  */
   346 char *
   347 w32_getenv (const char *envvar)
   348 {
   349   char *value;
   350   DWORD dwType;
   351 
   352   if ((value = getenv (envvar)))
   353     /* Found in the environment.  strdup it, because values returned
   354        by getenv cannot be free'd.  */
   355     return xstrdup (value);
   356 
   357   if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
   358       ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
   359     {
   360       /* "w32console" is what Emacs on Windows uses for tty-type under -nw.  */
   361       if (strcmp (envvar, "TERM") == 0)
   362         return xstrdup ("w32console");
   363       /* Found neither in the environment nor in the registry.  */
   364       return NULL;
   365     }
   366 
   367   if (dwType == REG_SZ)
   368     /* Registry; no need to expand.  */
   369     return value;
   370 
   371   if (dwType == REG_EXPAND_SZ)
   372     {
   373       DWORD size;
   374 
   375       if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
   376         {
   377           char *buffer = xmalloc (size);
   378           if (ExpandEnvironmentStrings (value, buffer, size))
   379             {
   380               /* Found and expanded.  */
   381               free (value);
   382               return buffer;
   383             }
   384 
   385           /* Error expanding.  */
   386           free (buffer);
   387         }
   388     }
   389 
   390   /* Not the right type, or not correctly expanded.  */
   391   free (value);
   392   return NULL;
   393 }
   394 
   395 int w32_window_app (void);
   396 
   397 int
   398 w32_window_app (void)
   399 {
   400   static int window_app = -1;
   401   char szTitle[MAX_PATH];
   402 
   403   if (window_app < 0)
   404     {
   405       /* Checking for STDOUT does not work; it's a valid handle also in
   406          nonconsole apps.  Testing for the console title seems to work. */
   407       window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
   408       if (window_app)
   409         InitCommonControls ();
   410     }
   411 
   412   return window_app;
   413 }
   414 
   415 /* execvp wrapper for Windows.  Quotes arguments with embedded spaces.
   416 
   417   This is necessary due to the broken implementation of exec* routines in
   418   the Microsoft libraries: they concatenate the arguments together without
   419   quoting special characters, and pass the result to CreateProcess, with
   420   predictably bad results.  By contrast, POSIX execvp passes the arguments
   421   directly into the argv array of the child process.  */
   422 
   423 int w32_execvp (const char *, char **);
   424 
   425 int
   426 w32_execvp (const char *path, char **argv)
   427 {
   428   int i;
   429 
   430   /* Required to allow a .BAT script as alternate editor.  */
   431   argv[0] = (char *) alternate_editor;
   432 
   433   for (i = 0; argv[i]; i++)
   434     if (strchr (argv[i], ' '))
   435       {
   436         char *quoted = alloca (strlen (argv[i]) + 3);
   437         sprintf (quoted, "\"%s\"", argv[i]);
   438         argv[i] = quoted;
   439       }
   440 
   441   return execvp (path, argv);
   442 }
   443 
   444 # undef execvp
   445 # define execvp w32_execvp
   446 
   447 /* Emulation of ttyname for Windows.  */
   448 const char *ttyname (int);
   449 const char *
   450 ttyname (int fd)
   451 {
   452   return "CONOUT$";
   453 }
   454 
   455 #endif /* WINDOWSNT */
   456 
   457 /* Display a normal or error message.
   458    On Windows, use a message box if compiled as a Windows app.  */
   459 static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
   460 static void
   461 message (bool is_error, const char *format, ...)
   462 {
   463   va_list args;
   464 
   465   va_start (args, format);
   466 
   467 #ifdef WINDOWSNT
   468   if (w32_window_app ())
   469     {
   470       char msg[2048];
   471       vsnprintf (msg, sizeof msg, format, args);
   472       msg[sizeof msg - 1] = '\0';
   473 
   474       if (is_error)
   475         MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
   476       else
   477         MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
   478     }
   479   else
   480 #endif
   481     {
   482       FILE *f = is_error ? stderr : stdout;
   483 
   484       vfprintf (f, format, args);
   485       fflush (f);
   486     }
   487 
   488   va_end (args);
   489 }
   490 
   491 /* Decode the options from argv and argc.
   492    The global variable 'optind' will say how many arguments we used up.  */
   493 
   494 static void
   495 decode_options (int argc, char **argv)
   496 {
   497   alternate_editor = egetenv ("ALTERNATE_EDITOR");
   498   tramp_prefix = egetenv ("EMACSCLIENT_TRAMP");
   499 
   500   while (true)
   501     {
   502       int opt = getopt_long_only (argc, argv, shortopts, longopts, NULL);
   503       if (opt < 0)
   504         break;
   505 
   506       char* endptr;
   507       switch (opt)
   508         {
   509         case 0:
   510           /* If getopt returns 0, then it has already processed a
   511              long-named option.  We should do nothing.  */
   512           break;
   513 
   514         case 'a':
   515           alternate_editor = optarg;
   516           break;
   517 
   518 #ifdef SOCKETS_IN_FILE_SYSTEM
   519         case 's':
   520           socket_name = optarg;
   521           break;
   522 #endif
   523 
   524         case 'f':
   525           server_file = optarg;
   526           break;
   527 
   528           /* We used to disallow this argument in w32, but it seems better
   529              to allow it, for the occasional case where the user is
   530              connecting with a w32 client to a server compiled with X11
   531              support.  */
   532         case 'd':
   533           display = optarg;
   534           break;
   535 
   536         case 'n':
   537           nowait = true;
   538           break;
   539 
   540         case 'w':
   541           timeout = strtoumax (optarg, &endptr, 10);
   542           if (timeout <= 0 ||
   543               ((timeout == INTMAX_MAX || timeout == INTMAX_MIN)
   544                && errno == ERANGE))
   545             {
   546               fprintf (stderr, "Invalid timeout: \"%s\"\n", optarg);
   547               exit (EXIT_FAILURE);
   548             }
   549           break;
   550 
   551         case 'e':
   552           eval = true;
   553           break;
   554 
   555         case 'q':
   556           quiet = true;
   557           break;
   558 
   559         case 'u':
   560           suppress_output = true;
   561           break;
   562 
   563         case 'V':
   564           message (false, "emacsclient %s\n", PACKAGE_VERSION);
   565           exit (EXIT_SUCCESS);
   566           break;
   567 
   568         case 't':
   569           tty = true;
   570           create_frame = true;
   571           reuse_frame = false;
   572           break;
   573 
   574         case 'c':
   575           create_frame = true;
   576           break;
   577 
   578         case 'r':
   579           create_frame = true;
   580           if (!tty)
   581             reuse_frame = true;
   582           break;
   583 
   584         case 'p':
   585           parent_id = optarg;
   586           create_frame = true;
   587           break;
   588 
   589         case 'H':
   590           print_help_and_exit ();
   591           break;
   592 
   593         case 'F':
   594           frame_parameters = optarg;
   595           break;
   596 
   597         case 'T':
   598           tramp_prefix = optarg;
   599           break;
   600 
   601         default:
   602           message (true, "Try '%s --help' for more information\n", progname);
   603           exit (EXIT_FAILURE);
   604           break;
   605         }
   606     }
   607 
   608   /* If the -c option is used (without -t) and no --display argument
   609      is provided, try $DISPLAY.
   610      Without the -c option, we used to set 'display' to $DISPLAY by
   611      default, but this changed the default behavior and is sometimes
   612      inconvenient.  So we force users to use "--display $DISPLAY" if
   613      they want Emacs to connect to their current display.
   614 
   615      Some window systems have a notion of default display not
   616      reflected in the DISPLAY variable.  If the user didn't give us an
   617      explicit display, try this platform-specific after trying the
   618      display in DISPLAY (if any).  */
   619   if (create_frame && !tty && !display)
   620     {
   621       /* Set these here so we use a default_display only when the user
   622          didn't give us an explicit display.  */
   623 #if defined (NS_IMPL_COCOA)
   624       alt_display = "ns";
   625 #elif defined (HAVE_NTGUI)
   626       alt_display = "w32";
   627 #elif defined (HAVE_HAIKU)
   628       alt_display = "be";
   629 #endif
   630 
   631 #ifdef HAVE_PGTK
   632       display = egetenv ("WAYLAND_DISPLAY");
   633       alt_display = egetenv ("DISPLAY");
   634 #else
   635       display = egetenv ("DISPLAY");
   636 #endif
   637     }
   638 
   639   if (!display)
   640     {
   641       display = alt_display;
   642       alt_display = NULL;
   643     }
   644 
   645   /* A null-string display is invalid.  */
   646   if (display && !display[0])
   647     display = NULL;
   648 
   649   /* If no display is available, new frames are tty frames.  */
   650   if (create_frame && !display)
   651     tty = true;
   652 
   653 #ifdef WINDOWSNT
   654   /* Emacs on Windows does not support graphical and text terminal
   655      frames in the same instance.  So, treat the -t and -c options as
   656      equivalent, and open a new frame on the server's terminal.
   657      Ideally, we would set tty = true only if the server is running in a
   658      console, but alas we don't know that.  As a workaround, always
   659      ask for a tty frame, and let server.el figure it out.  */
   660   if (create_frame)
   661     {
   662       display = NULL;
   663       tty = true;
   664     }
   665 #endif /* WINDOWSNT */
   666 }
   667 
   668 
   669 static _Noreturn void
   670 print_help_and_exit (void)
   671 {
   672   /* Spaces and tabs are significant in this message; they're chosen so the
   673      message aligns properly both in a tty and in a Windows message box.
   674      Please try to preserve them; otherwise the output is very hard to read
   675      when using emacsclientw.  */
   676   message (false,
   677            "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
   678 Tell the Emacs server to visit the specified files.\n\
   679 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
   680 \n\
   681 The following OPTIONS are accepted:\n\
   682 -V, --version           Just print version info and return\n\
   683 -H, --help              Print this usage information message\n\
   684 -nw, -t, --tty          Open a new Emacs frame on the current terminal\n\
   685 -c, --create-frame      Create a new frame instead of trying to\n\
   686                         use the current Emacs frame\n\
   687 -r, --reuse-frame       Create a new frame if none exists, otherwise\n\
   688                         use the current Emacs frame\n\
   689 ", "\
   690 -F ALIST, --frame-parameters=ALIST\n\
   691                         Set the parameters of a new frame\n\
   692 -e, --eval              Evaluate the FILE arguments as ELisp expressions\n\
   693 -n, --no-wait           Don't wait for the server to return\n\
   694 -w, --timeout=SECONDS   Seconds to wait before timing out\n\
   695 -q, --quiet             Don't display messages on success\n\
   696 -u, --suppress-output   Don't display return values from the server\n\
   697 -d DISPLAY, --display=DISPLAY\n\
   698                         Visit the file in the given display\n\
   699 ", "\
   700 --parent-id=ID          Open in parent window ID, via XEmbed\n"
   701 #ifdef SOCKETS_IN_FILE_SYSTEM
   702 "-s SOCKET, --socket-name=SOCKET\n\
   703                         Set filename of the UNIX socket for communication\n"
   704 #endif
   705 "-f SERVER, --server-file=SERVER\n\
   706                         Set filename of the TCP authentication file\n\
   707 -a EDITOR, --alternate-editor=EDITOR\n\
   708                         Editor to fallback to if the server is not running\n"
   709 "                       If EDITOR is the empty string, start Emacs in daemon\n\
   710                         mode and try connecting again\n"
   711 "-T PREFIX, --tramp=PREFIX\n\
   712                         PREFIX to prepend to filenames sent by emacsclient\n\
   713                         for locating files remotely via Tramp\n"
   714 "\n\
   715 Report bugs with M-x report-emacs-bug.\n");
   716   exit (EXIT_SUCCESS);
   717 }
   718 
   719 /* Try to run a different command, or --if no alternate editor is
   720    defined-- exit with an error code.
   721    Uses argv, but gets it from the global variable main_argv.  */
   722 
   723 static _Noreturn void
   724 fail (void)
   725 {
   726   if (alternate_editor)
   727     {
   728       size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
   729       size_t new_argv_size = extra_args_size;
   730       char **new_argv = xmalloc (new_argv_size);
   731       char *s = xstrdup (alternate_editor);
   732       ptrdiff_t toks = 0;
   733 
   734       /* Unpack alternate_editor's space-separated tokens into new_argv.  */
   735       for (char *tok = s; tok != NULL && *tok != '\0';)
   736         {
   737           /* Allocate new token.  */
   738           ++toks;
   739           new_argv = xrealloc (new_argv,
   740                                new_argv_size + toks * sizeof (char *));
   741 
   742           /* Skip leading delimiters, and set separator, skipping any
   743              opening quote.  */
   744           size_t skip = strspn (tok, " \"");
   745           tok += skip;
   746           char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';
   747 
   748           /* Record start of token.  */
   749           new_argv[toks - 1] = tok;
   750 
   751           /* Find end of token and overwrite it with NUL.  */
   752           tok = strchr (tok, sep);
   753           if (tok != NULL)
   754             *tok++ = '\0';
   755         }
   756 
   757       /* Append main_argv arguments to new_argv.  */
   758       memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
   759 
   760       execvp (*new_argv, new_argv);
   761       message (true, "%s: error executing alternate editor \"%s\"\n",
   762                progname, alternate_editor);
   763     }
   764   exit (EXIT_FAILURE);
   765 }
   766 
   767 
   768 #ifdef SOCKETS_IN_FILE_SYSTEM
   769 static void act_on_signals (HSOCKET);
   770 #else
   771 static void act_on_signals (HSOCKET s) {}
   772 static void init_signals (void) {}
   773 #endif
   774 
   775 enum { AUTH_KEY_LENGTH = 64 };
   776 
   777 static void
   778 sock_err_message (const char *function_name)
   779 {
   780 #ifdef WINDOWSNT
   781   /* On Windows, the socket library was historically separate from the
   782      standard C library, so errors are handled differently.  */
   783 
   784   if (w32_window_app () && alternate_editor)
   785     return;
   786 
   787   char *msg = NULL;
   788 
   789   FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
   790                  | FORMAT_MESSAGE_ALLOCATE_BUFFER
   791                  | FORMAT_MESSAGE_ARGUMENT_ARRAY,
   792                  NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
   793 
   794   message (true, "%s: %s: %s\n", progname, function_name, msg);
   795 
   796   LocalFree (msg);
   797 #else
   798   message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
   799 #endif
   800 }
   801 
   802 
   803 /* Send to S the data in *DATA when either
   804    - the data's last byte is '\n', or
   805    - the buffer is full (but this shouldn't happen)
   806    Otherwise, just accumulate the data.  */
   807 static void
   808 send_to_emacs (HSOCKET s, const char *data)
   809 {
   810   enum { SEND_BUFFER_SIZE = 4096 };
   811 
   812   /* Buffer to accumulate data to send in TCP connections.  */
   813   static char send_buffer[SEND_BUFFER_SIZE + 1];
   814 
   815   /* Fill pointer for the send buffer.  */
   816   static int sblen;
   817 
   818   for (ptrdiff_t dlen = strlen (data); dlen != 0; )
   819     {
   820       int part = min (dlen, SEND_BUFFER_SIZE - sblen);
   821       memcpy (&send_buffer[sblen], data, part);
   822       data += part;
   823       sblen += part;
   824 
   825       if (sblen == SEND_BUFFER_SIZE
   826           || (0 < sblen && send_buffer[sblen - 1] == '\n'))
   827         {
   828           int sent;
   829           while ((sent = send (s, send_buffer, sblen, 0)) < 0)
   830             {
   831               if (errno != EINTR)
   832                 {
   833                   message (true, "%s: failed to send %d bytes to socket: %s\n",
   834                            progname, sblen, strerror (errno));
   835                   fail ();
   836                 }
   837               /* Act on signals not requiring communication to Emacs,
   838                  but defer action on the others to avoid confusing the
   839                  communication currently in progress.  */
   840               act_on_signals (INVALID_SOCKET);
   841             }
   842           sblen -= sent;
   843           memmove (send_buffer, &send_buffer[sent], sblen);
   844         }
   845 
   846       dlen -= part;
   847     }
   848 }
   849 
   850 
   851 /* In STR, insert a & before each &, each space, each newline, and
   852    any initial -.  Change spaces to underscores, too, so that the
   853    return value never contains a space.
   854 
   855    Does not change the string.  Outputs the result to S.  */
   856 static void
   857 quote_argument (HSOCKET s, const char *str)
   858 {
   859   char *copy = xmalloc (strlen (str) * 2 + 1);
   860   char *q = copy;
   861   if (*str == '-')
   862     *q++ = '&', *q++ = *str++;
   863   for (; *str; str++)
   864     {
   865       char c = *str;
   866       if (c == ' ')
   867         *q++ = '&', c = '_';
   868       else if (c == '\n')
   869         *q++ = '&', c = 'n';
   870       else if (c == '&')
   871         *q++ = '&';
   872       *q++ = c;
   873     }
   874   *q = 0;
   875 
   876   send_to_emacs (s, copy);
   877 
   878   free (copy);
   879 }
   880 
   881 
   882 /* The inverse of quote_argument.  Remove quoting in string STR by
   883    modifying the addressed string in place.  Return STR.  */
   884 
   885 static char *
   886 unquote_argument (char *str)
   887 {
   888   char const *p = str;
   889   char *q = str;
   890   char c;
   891 
   892   do
   893     {
   894       c = *p++;
   895       if (c == '&')
   896         {
   897           c = *p++;
   898           if (c == '_')
   899             c = ' ';
   900           else if (c == 'n')
   901             c = '\n';
   902         }
   903       *q++ = c;
   904     }
   905   while (c);
   906 
   907   return str;
   908 }
   909 
   910 
   911 #ifdef WINDOWSNT
   912 /* Wrapper to make WSACleanup a cdecl, as required by atexit.  */
   913 void __cdecl close_winsock (void);
   914 void __cdecl
   915 close_winsock (void)
   916 {
   917   WSACleanup ();
   918 }
   919 
   920 /* Initialize the WinSock2 library.  */
   921 void initialize_sockets (void);
   922 void
   923 initialize_sockets (void)
   924 {
   925   WSADATA wsaData;
   926 
   927   if (WSAStartup (MAKEWORD (2, 0), &wsaData))
   928     {
   929       message (true, "%s: error initializing WinSock2\n", progname);
   930       exit (EXIT_FAILURE);
   931     }
   932 
   933   atexit (close_winsock);
   934 }
   935 #endif /* WINDOWSNT */
   936 
   937 
   938 /* If the home directory is HOME, and XDG_CONFIG_HOME's value is XDG,
   939    return the configuration file with basename CONFIG_FILE.  Fail if
   940    the configuration file could not be opened.  */
   941 
   942 static FILE *
   943 open_config (char const *home, char const *xdg, char const *config_file)
   944 {
   945   ptrdiff_t xdgsubdirsize = xdg ? strlen (xdg) + sizeof "/emacs/server/" : 0;
   946   ptrdiff_t homesuffixsizemax = max (sizeof "/.config/emacs/server/",
   947                                      sizeof "/.emacs.d/server/");
   948   ptrdiff_t homesubdirsizemax = home ? strlen (home) + homesuffixsizemax : 0;
   949   char *configname = xmalloc (max (xdgsubdirsize, homesubdirsizemax)
   950                               + strlen (config_file));
   951   FILE *config;
   952 
   953   if (home)
   954     {
   955       strcpy (stpcpy (stpcpy (configname, home), "/.emacs.d/server/"),
   956               config_file);
   957       config = fopen (configname, "rb");
   958     }
   959   else
   960     config = NULL;
   961 
   962   if (! config && (xdg || home))
   963     {
   964       strcpy ((xdg
   965                ? stpcpy (stpcpy (configname, xdg), "/emacs/server/")
   966                : stpcpy (stpcpy (configname, home), "/.config/emacs/server/")),
   967               config_file);
   968       config = fopen (configname, "rb");
   969     }
   970 
   971   free (configname);
   972   return config;
   973 }
   974 
   975 /* Read the information needed to set up a TCP comm channel with
   976    the Emacs server: host, port, and authentication string.  */
   977 
   978 static bool
   979 get_server_config (const char *config_file, struct sockaddr_in *server,
   980                    char *authentication)
   981 {
   982   char dotted[32];
   983   char *port;
   984   FILE *config;
   985 
   986   if (IS_ABSOLUTE_FILE_NAME (config_file))
   987     config = fopen (config_file, "rb");
   988   else
   989     {
   990       char const *xdg = egetenv ("XDG_CONFIG_HOME");
   991       config = open_config (egetenv ("HOME"), xdg, config_file);
   992 #ifdef WINDOWSNT
   993       if (!config)
   994         config = open_config (egetenv ("APPDATA"), xdg, config_file);
   995 #endif
   996     }
   997 
   998   if (! config)
   999     return false;
  1000 
  1001   if (fgets (dotted, sizeof dotted, config)
  1002       && (port = strchr (dotted, ':')))
  1003     *port++ = '\0';
  1004   else
  1005     {
  1006       message (true, "%s: invalid configuration info\n", progname);
  1007       exit (EXIT_FAILURE);
  1008     }
  1009 
  1010   memset (server, 0, sizeof *server);
  1011   server->sin_family = AF_INET;
  1012   server->sin_addr.s_addr = inet_addr (dotted);
  1013   server->sin_port = htons (atoi (port));
  1014 
  1015   if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
  1016     {
  1017       message (true, "%s: cannot read authentication info\n", progname);
  1018       exit (EXIT_FAILURE);
  1019     }
  1020 
  1021   fclose (config);
  1022 
  1023   return true;
  1024 }
  1025 
  1026 /* Like socket (DOMAIN, TYPE, PROTOCOL), except arrange for the
  1027    resulting file descriptor to be close-on-exec.  */
  1028 
  1029 static HSOCKET
  1030 cloexec_socket (int domain, int type, int protocol)
  1031 {
  1032 #ifdef SOCK_CLOEXEC
  1033   return socket (domain, type | SOCK_CLOEXEC, protocol);
  1034 #else
  1035   HSOCKET s = socket (domain, type, protocol);
  1036 # ifndef WINDOWSNT
  1037   if (0 <= s)
  1038     fcntl (s, F_SETFD, FD_CLOEXEC);
  1039 # endif
  1040   return s;
  1041 #endif
  1042 }
  1043 
  1044 static HSOCKET
  1045 set_tcp_socket (const char *local_server_file)
  1046 {
  1047   union {
  1048     struct sockaddr_in in;
  1049     struct sockaddr sa;
  1050   } server;
  1051   struct linger l_arg = { .l_onoff = 1, .l_linger = 1 };
  1052   char auth_string[AUTH_KEY_LENGTH + 1];
  1053 
  1054   if (! get_server_config (local_server_file, &server.in, auth_string))
  1055     return INVALID_SOCKET;
  1056 
  1057   if (server.in.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
  1058     message (false, "%s: connected to remote socket at %s\n",
  1059              progname, inet_ntoa (server.in.sin_addr));
  1060 
  1061   /* Open up an AF_INET socket.  */
  1062   HSOCKET s = cloexec_socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1063   if (s < 0)
  1064     {
  1065       /* Since we have an alternate to try out, this is not an error
  1066          yet; popping out a modal dialog at this stage would make -a
  1067          option totally useless for emacsclientw -- the user will
  1068          still get an error message if the alternate editor fails.  */
  1069       sock_err_message ("socket");
  1070       return INVALID_SOCKET;
  1071     }
  1072 
  1073   /* Set up the socket.  */
  1074   if (connect (s, &server.sa, sizeof server.in) != 0)
  1075     {
  1076       sock_err_message ("connect");
  1077       CLOSE_SOCKET (s);
  1078       return INVALID_SOCKET;
  1079     }
  1080 
  1081   /* The cast to 'const char *' is to avoid a compiler warning when
  1082      compiling for MS-Windows sockets.  */
  1083   int ret = setsockopt (s, SOL_SOCKET, SO_LINGER, (const char *) &l_arg, sizeof l_arg);
  1084   if (ret < 0)
  1085     sock_err_message ("setsockopt");
  1086 
  1087   /* Send the authentication.  */
  1088   auth_string[AUTH_KEY_LENGTH] = '\0';
  1089 
  1090   send_to_emacs (s, "-auth ");
  1091   send_to_emacs (s, auth_string);
  1092   send_to_emacs (s, " ");
  1093 
  1094   return s;
  1095 }
  1096 
  1097 
  1098 /* Return true if PREFIX is a prefix of STRING. */
  1099 static bool
  1100 strprefix (const char *prefix, const char *string)
  1101 {
  1102   return !strncmp (prefix, string, strlen (prefix));
  1103 }
  1104 
  1105 /* Get tty name and type.  If successful, store the type into
  1106    *TTY_TYPE and the name into *TTY_NAME, and return true.
  1107    Otherwise, fail if NOABORT is zero, or return false if NOABORT.  */
  1108 
  1109 static bool
  1110 find_tty (const char **tty_type, const char **tty_name, bool noabort)
  1111 {
  1112   const char *type = egetenv ("TERM");
  1113   const char *name = ttyname (STDOUT_FILENO);
  1114 
  1115   if (!name)
  1116     {
  1117       if (noabort)
  1118         return false;
  1119       message (true, "%s: could not get terminal name\n", progname);
  1120       fail ();
  1121     }
  1122 
  1123   if (!type)
  1124     {
  1125       if (noabort)
  1126         return false;
  1127       message (true, "%s: please set the TERM variable to your terminal type\n",
  1128                progname);
  1129       fail ();
  1130     }
  1131 
  1132   const char *inside_emacs = egetenv ("INSIDE_EMACS");
  1133   if (inside_emacs && strstr (inside_emacs, ",term:")
  1134       && strprefix ("eterm", type))
  1135     {
  1136       if (noabort)
  1137         return false;
  1138       /* This causes nasty, MULTI_KBOARD-related input lockouts. */
  1139       message (true, ("%s: opening a frame in an Emacs term buffer"
  1140                       " is not supported\n"),
  1141                progname);
  1142       fail ();
  1143     }
  1144 
  1145   *tty_name = name;
  1146   *tty_type = type;
  1147   return true;
  1148 }
  1149 
  1150 /* Return the process group if in the foreground, the negative of the
  1151    process group if in the background, and zero if there is no
  1152    foreground process group for the controlling terminal.
  1153    Unfortunately, use of this function introduces an unavoidable race,
  1154    since whether the process is in the foreground or background can
  1155    change at any time.  */
  1156 
  1157 static pid_t
  1158 process_grouping (void)
  1159 {
  1160 #ifdef SOCKETS_IN_FILE_SYSTEM
  1161   pid_t tcpgrp = tcgetpgrp (STDOUT_FILENO);
  1162   if (0 <= tcpgrp)
  1163     {
  1164       pid_t pgrp = getpgrp ();
  1165       return tcpgrp == pgrp ? pgrp : -pgrp;
  1166     }
  1167 #endif
  1168   return 0;
  1169 }
  1170 
  1171 #ifdef SOCKETS_IN_FILE_SYSTEM
  1172 
  1173 # include <acl.h>
  1174 
  1175 # ifndef O_PATH
  1176 #  define O_PATH O_SEARCH
  1177 # endif
  1178 
  1179 /* A local socket address.  The union avoids the need to cast.  */
  1180 union local_sockaddr
  1181 {
  1182   struct sockaddr_un un;
  1183   struct sockaddr sa;
  1184 };
  1185 
  1186 /* Relative to the directory DIRFD, connect the socket file named ADDR
  1187    to the socket S.  Return 0 if successful, -1 if DIRFD is not
  1188    AT_FDCWD and DIRFD's permissions would allow a symlink attack, an
  1189    errno otherwise.  */
  1190 
  1191 static int
  1192 connect_socket (int dirfd, char const *addr, int s, uid_t uid)
  1193 {
  1194   int sock_status = 0;
  1195 
  1196   union local_sockaddr server;
  1197   if (sizeof server.un.sun_path <= strlen (addr))
  1198     return ENAMETOOLONG;
  1199   server.un.sun_family = AF_UNIX;
  1200   strcpy (server.un.sun_path, addr);
  1201 
  1202   /* If -1, WDFD is not set yet.  If nonnegative, WDFD is a file
  1203      descriptor for the initial working directory.  Otherwise -1 - WDFD is
  1204      the error number for the initial working directory.  */
  1205   static int wdfd = -1;
  1206 
  1207   if (dirfd != AT_FDCWD)
  1208     {
  1209       /* Fail if DIRFD's permissions are bogus.  */
  1210       struct stat st;
  1211       if (fstat (dirfd, &st) != 0)
  1212         return errno;
  1213       if (st.st_uid != uid || (st.st_mode & (S_IWGRP | S_IWOTH)))
  1214         return -1;
  1215 
  1216       if (wdfd == -1)
  1217         {
  1218           /* Save the initial working directory.  */
  1219           wdfd = open (".", O_PATH | O_CLOEXEC);
  1220           if (wdfd < 0)
  1221             wdfd = -1 - errno;
  1222         }
  1223       if (wdfd < 0)
  1224         return -1 - wdfd;
  1225       if (fchdir (dirfd) != 0)
  1226         return errno;
  1227 
  1228       /* Fail if DIRFD has an ACL, which means its permissions are
  1229          almost surely bogus.  */
  1230       int has_acl = file_has_acl (".", &st);
  1231       if (has_acl)
  1232         sock_status = has_acl < 0 ? errno : -1;
  1233     }
  1234 
  1235   if (!sock_status)
  1236     sock_status = connect (s, &server.sa, sizeof server.un) == 0 ? 0 : errno;
  1237 
  1238   /* Fail immediately if we cannot change back to the initial working
  1239      directory, as that can mess up the rest of execution.  */
  1240   if (dirfd != AT_FDCWD && fchdir (wdfd) != 0)
  1241     {
  1242       message (true, "%s: .: %s\n", progname, strerror (errno));
  1243       exit (EXIT_FAILURE);
  1244     }
  1245 
  1246   return sock_status;
  1247 }
  1248 
  1249 
  1250 /* Signal handlers merely set a flag, to avoid race conditions on
  1251    POSIXish systems.  Non-POSIX platforms lacking sigaction make do
  1252    with traditional calls to 'signal'; races are rare so this usually
  1253    works.  Although this approach may treat multiple deliveries of SIG
  1254    as a single delivery and may act on signals in a different order
  1255    than received, that is OK for emacsclient.  Also, this approach may
  1256    omit output if a printf call is interrupted by a signal, but printf
  1257    output is not that important (emacsclient does not check for printf
  1258    errors, after all) so this is also OK for emacsclient.  */
  1259 
  1260 /* Reinstall for SIG the signal handler HANDLER if needed.  It is
  1261    needed on a non-POSIX or traditional platform where an interrupt
  1262    resets the signal handler to SIG_DFL.  */
  1263 static void
  1264 reinstall_handler_if_needed (int sig, void (*handler) (int))
  1265 {
  1266 # ifndef SA_RESETHAND
  1267   /* This is a platform without POSIX's sigaction.  */
  1268   signal (sig, handler);
  1269 # endif
  1270 }
  1271 
  1272 /* Flags for each signal, and handlers that set the flags.  */
  1273 
  1274 static sig_atomic_t volatile
  1275   got_sigcont, got_sigtstp, got_sigttou, got_sigwinch;
  1276 
  1277 static void
  1278 handle_sigcont (int sig)
  1279 {
  1280   got_sigcont = 1;
  1281   reinstall_handler_if_needed (sig, handle_sigcont);
  1282 }
  1283 static void
  1284 handle_sigtstp (int sig)
  1285 {
  1286   got_sigtstp = 1;
  1287   reinstall_handler_if_needed (sig, handle_sigtstp);
  1288 }
  1289 static void
  1290 handle_sigttou (int sig)
  1291 {
  1292   got_sigttou = 1;
  1293   reinstall_handler_if_needed (sig, handle_sigttou);
  1294 }
  1295 static void
  1296 handle_sigwinch (int sig)
  1297 {
  1298   got_sigwinch = 1;
  1299   reinstall_handler_if_needed (sig, handle_sigwinch);
  1300 }
  1301 
  1302 /* Install for signal SIG the handler HANDLER.  However, if FLAG is
  1303    non-null and if the signal is currently being ignored, do not
  1304    install the handler and keep *FLAG zero.  */
  1305 
  1306 static void
  1307 install_handler (int sig, void (*handler) (int), sig_atomic_t volatile *flag)
  1308 {
  1309 # ifdef SA_RESETHAND
  1310   if (flag)
  1311     {
  1312       struct sigaction oact;
  1313       if (sigaction (sig, NULL, &oact) == 0 && oact.sa_handler == SIG_IGN)
  1314         return;
  1315     }
  1316   struct sigaction act = { .sa_handler = handler };
  1317   sigemptyset (&act.sa_mask);
  1318   sigaction (sig, &act, NULL);
  1319 # else
  1320   void (*ohandler) (int) = signal (sig, handler);
  1321   if (flag)
  1322     {
  1323       if (ohandler == SIG_IGN)
  1324         {
  1325           signal (sig, SIG_IGN);
  1326           /* While HANDLER was mistakenly installed a signal may have
  1327              arrived and set *FLAG, so clear *FLAG now.  */
  1328           *flag = 0;
  1329         }
  1330     }
  1331 # endif
  1332 }
  1333 
  1334 /* Initial installation of signal handlers.  */
  1335 
  1336 static void
  1337 init_signals (void)
  1338 {
  1339   install_handler (SIGCONT, handle_sigcont, &got_sigcont);
  1340   install_handler (SIGTSTP, handle_sigtstp, &got_sigtstp);
  1341   install_handler (SIGTTOU, handle_sigttou, &got_sigttou);
  1342   install_handler (SIGWINCH, handle_sigwinch, &got_sigwinch);
  1343   /* Don't mess with SIGINT and SIGQUIT, as Emacs has no way to
  1344      determine which terminal the signal came from.  C-g is a normal
  1345      input event on secondary terminals.  */
  1346 }
  1347 
  1348 /* Act on delivered tty-related signal SIG that normally has handler
  1349    HANDLER.  EMACS_SOCKET connects to Emacs.  */
  1350 
  1351 static void
  1352 act_on_tty_signal (int sig, void (*handler) (int), HSOCKET emacs_socket)
  1353 {
  1354   /* Notify Emacs that we are going to sleep.  Normally the suspend is
  1355      initiated by Emacs via server-handle-suspend-tty, but if the
  1356      server gets out of sync with reality, we may get a SIGTSTP on
  1357      C-z.  Handling this signal and notifying Emacs about it should
  1358      get things under control again.  */
  1359   send_to_emacs (emacs_socket, "-suspend \n");
  1360 
  1361   /* Execute the default action by temporarily changing handling to
  1362      the default and resignaling.  */
  1363   install_handler (sig, SIG_DFL, NULL);
  1364   raise (sig);
  1365   install_handler (sig, handler, NULL);
  1366 }
  1367 
  1368 /* Act on delivered signals if possible.  If EMACS_SOCKET is valid,
  1369    use it to communicate to Emacs.  */
  1370 
  1371 static void
  1372 act_on_signals (HSOCKET emacs_socket)
  1373 {
  1374   while (true)
  1375     {
  1376       bool took_action = false;
  1377 
  1378       if (emacs_socket != INVALID_SOCKET)
  1379         {
  1380           if (got_sigcont)
  1381             {
  1382               got_sigcont = 0;
  1383               took_action = true;
  1384               pid_t grouping = process_grouping ();
  1385               if (grouping < 0)
  1386                 {
  1387                   if (tty)
  1388                     {
  1389                       /* Cancel the continue.  */
  1390                       kill (grouping, SIGTTIN);
  1391                     }
  1392                 }
  1393               else
  1394                 send_to_emacs (emacs_socket, "-resume \n");
  1395             }
  1396 
  1397           if (got_sigtstp)
  1398             {
  1399               got_sigtstp = 0;
  1400               took_action = true;
  1401               act_on_tty_signal (SIGTSTP, handle_sigtstp, emacs_socket);
  1402             }
  1403           if (got_sigttou)
  1404             {
  1405               got_sigttou = 0;
  1406               took_action = true;
  1407               act_on_tty_signal (SIGTTOU, handle_sigttou, emacs_socket);
  1408             }
  1409         }
  1410 
  1411       if (emacs_pid && got_sigwinch)
  1412         {
  1413           got_sigwinch = 0;
  1414           took_action = true;
  1415           kill (emacs_pid, SIGWINCH);
  1416         }
  1417 
  1418       if (!took_action)
  1419         break;
  1420     }
  1421 }
  1422 
  1423 enum { socknamesize = sizeof ((struct sockaddr_un *) NULL)->sun_path };
  1424 
  1425 /* Given a local socket S, create in *SOCKNAME a name for a local socket
  1426    and connect to that socket.  The first TMPDIRLEN bytes of *SOCKNAME are
  1427    already initialized to be the name of a temporary directory.
  1428    Use UID and SERVER_NAME to concoct the name.  Return 0 if
  1429    successful, -1 if the socket's parent directory is not safe, and an
  1430    errno if there is some other problem.  */
  1431 
  1432 static int
  1433 local_sockname (int s, char sockname[socknamesize], int tmpdirlen,
  1434                 uid_t uid, char const *server_name)
  1435 {
  1436   /* If ! (0 <= TMPDIRLEN && TMPDIRLEN < SOCKNAMESIZE) the truncated
  1437      temporary directory name is already in SOCKNAME, so nothing more
  1438      need be stored.  */
  1439   if (! (0 <= tmpdirlen && tmpdirlen < socknamesize))
  1440     return ENAMETOOLONG;
  1441 
  1442   /* Put the full address name into the buffer, since the caller might
  1443      need it for diagnostics.  But don't overrun the buffer.  */
  1444   uintmax_t uidmax = uid;
  1445   int suffixlen = snprintf (sockname + tmpdirlen, socknamesize - tmpdirlen,
  1446                             "/emacs%"PRIuMAX"/%s", uidmax, server_name);
  1447   if (! (0 <= suffixlen && suffixlen < socknamesize - tmpdirlen))
  1448     return ENAMETOOLONG;
  1449 
  1450   /* Make sure the address's parent directory is not a symlink and is
  1451      this user's directory and does not let others write to it; this
  1452      fends off some symlink attacks.  To avoid races, keep the parent
  1453      directory open while checking.  */
  1454   char *emacsdirend = sockname + tmpdirlen + suffixlen -
  1455     strlen(server_name) - 1;
  1456   *emacsdirend = '\0';
  1457   int dir = open (sockname, O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
  1458   *emacsdirend = '/';
  1459   if (dir < 0)
  1460     return errno;
  1461   int sock_status = connect_socket (dir, server_name, s, uid);
  1462   close (dir);
  1463   return sock_status;
  1464 }
  1465 
  1466 /* Create a local socket for SERVER_NAME and connect it to Emacs.  If
  1467    SERVER_NAME is a file name component, the local socket name
  1468    relative to a well-known location in a temporary directory.
  1469    Otherwise, the local socket name is SERVER_NAME.  */
  1470 
  1471 static HSOCKET
  1472 set_local_socket (char const *server_name)
  1473 {
  1474   union local_sockaddr server;
  1475   int sock_status;
  1476   char *sockname = server.un.sun_path;
  1477   int tmpdirlen = -1;
  1478   int socknamelen = -1;
  1479   uid_t uid = geteuid ();
  1480   bool tmpdir_used = false;
  1481   int s = cloexec_socket (AF_UNIX, SOCK_STREAM, 0);
  1482   if (s < 0)
  1483     {
  1484       message (true, "%s: can't create socket: %s\n",
  1485                progname, strerror (errno));
  1486       fail ();
  1487     }
  1488 
  1489   if (strchr (server_name, '/')
  1490       || (ISSLASH ('\\') && strchr (server_name, '\\')))
  1491     {
  1492       socknamelen = snprintf (sockname, socknamesize, "%s", server_name);
  1493       sock_status = (0 <= socknamelen && socknamelen < socknamesize
  1494                      ? connect_socket (AT_FDCWD, sockname, s, 0)
  1495                      : ENAMETOOLONG);
  1496     }
  1497   else
  1498     {
  1499       /* socket_name is a file name component.  */
  1500       char const *xdg_runtime_dir = egetenv ("XDG_RUNTIME_DIR");
  1501       if (xdg_runtime_dir)
  1502         {
  1503           socknamelen = snprintf (sockname, socknamesize, "%s/emacs/%s",
  1504                                   xdg_runtime_dir, server_name);
  1505           sock_status = (0 <= socknamelen && socknamelen < socknamesize
  1506                          ? connect_socket (AT_FDCWD, sockname, s, 0)
  1507                          : ENAMETOOLONG);
  1508         }
  1509       else
  1510         {
  1511           char const *tmpdir = egetenv ("TMPDIR");
  1512           if (tmpdir)
  1513             tmpdirlen = snprintf (sockname, socknamesize, "%s", tmpdir);
  1514           else
  1515             {
  1516 # ifdef DARWIN_OS
  1517 #  ifndef _CS_DARWIN_USER_TEMP_DIR
  1518 #   define _CS_DARWIN_USER_TEMP_DIR 65537
  1519 #  endif
  1520               size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR,
  1521                                   sockname, socknamesize);
  1522               if (0 < n && n < (size_t) -1)
  1523                 tmpdirlen = min (n - 1, socknamesize);
  1524 # endif
  1525               if (tmpdirlen < 0)
  1526                 tmpdirlen = snprintf (sockname, socknamesize, "/tmp");
  1527             }
  1528           sock_status = local_sockname (s, sockname, tmpdirlen,
  1529                                         uid, server_name);
  1530           tmpdir_used = true;
  1531         }
  1532     }
  1533 
  1534   if (sock_status == 0)
  1535     return s;
  1536 
  1537   if (sock_status == ENAMETOOLONG)
  1538     {
  1539       message (true, "%s: socket-name %s... too long\n", progname, sockname);
  1540       fail ();
  1541     }
  1542 
  1543   if (tmpdir_used)
  1544     {
  1545       /* See whether LOGNAME or USER exist and differ from
  1546          our euid.  If so, look for a socket based on the UID
  1547          associated with the name.  This is reminiscent of the logic
  1548          that init_editfns uses to set the global Vuser_full_name.  */
  1549 
  1550       char const *user_name = egetenv ("LOGNAME");
  1551 
  1552       if (!user_name)
  1553         user_name = egetenv ("USER");
  1554 
  1555       if (user_name)
  1556         {
  1557           struct passwd *pw = getpwnam (user_name);
  1558 
  1559           if (pw && pw->pw_uid != uid)
  1560             {
  1561               /* We're running under su, apparently. */
  1562               sock_status = local_sockname (s, sockname, tmpdirlen,
  1563                                             pw->pw_uid, server_name);
  1564               if (sock_status == 0)
  1565                 return s;
  1566               if (sock_status == ENAMETOOLONG)
  1567                 {
  1568                   message (true, "%s: socket-name %s... too long\n",
  1569                            progname, sockname);
  1570                   exit (EXIT_FAILURE);
  1571                 }
  1572             }
  1573         }
  1574     }
  1575 
  1576   close (s);
  1577 
  1578   if (sock_status == -1)
  1579     message (true,
  1580              "%s: Invalid permissions on parent directory of socket: %s\n",
  1581              progname, sockname);
  1582   else if (sock_status == ENOENT)
  1583     {
  1584       if (tmpdir_used)
  1585         {
  1586           uintmax_t id = uid;
  1587           char sockdirname[socknamesize];
  1588           int sockdirnamelen = snprintf (sockdirname, sizeof sockdirname,
  1589                                          "/run/user/%"PRIuMAX, id);
  1590           if (0 <= sockdirnamelen && sockdirnamelen < sizeof sockdirname
  1591               && faccessat (AT_FDCWD, sockdirname, X_OK, AT_EACCESS) == 0)
  1592             message
  1593               (true,
  1594                ("%s: Should XDG_RUNTIME_DIR='%s' be in the environment?\n"
  1595                 "%s: (Be careful: XDG_RUNTIME_DIR is security-related.)\n"),
  1596                progname, sockdirname, progname);
  1597         }
  1598 
  1599       /* If there's an alternate editor and the user has requested
  1600          --quiet, don't output the warning. */
  1601       if (!quiet || !alternate_editor)
  1602         {
  1603           message (true,
  1604                    ("%s: can't find socket; have you started the server?\n"
  1605                     "%s: To start the server in Emacs,"
  1606                     " type \"M-x server-start\".\n"),
  1607                    progname, progname);
  1608         }
  1609     }
  1610   else
  1611     message (true, "%s: can't connect to %s: %s\n",
  1612              progname, sockname, strerror (sock_status));
  1613 
  1614   return INVALID_SOCKET;
  1615 }
  1616 #endif /* SOCKETS_IN_FILE_SYSTEM */
  1617 
  1618 static HSOCKET
  1619 set_socket (bool no_exit_if_error)
  1620 {
  1621   HSOCKET s;
  1622   const char *local_server_file = server_file;
  1623 
  1624   INITIALIZE ();
  1625 
  1626 #ifdef SOCKETS_IN_FILE_SYSTEM
  1627   if (!socket_name)
  1628     socket_name = egetenv ("EMACS_SOCKET_NAME");
  1629 
  1630   if (socket_name)
  1631     {
  1632       /* Explicit --socket-name argument, or environment variable.  */
  1633       s = set_local_socket (socket_name);
  1634       if (s != INVALID_SOCKET || no_exit_if_error)
  1635         return s;
  1636       message (true, "%s: error accessing socket \"%s\"\n",
  1637                progname, socket_name);
  1638       exit (EXIT_FAILURE);
  1639     }
  1640 #endif
  1641 
  1642   /* Explicit --server-file arg or EMACS_SERVER_FILE variable.  */
  1643   if (!local_server_file)
  1644     local_server_file = egetenv ("EMACS_SERVER_FILE");
  1645 
  1646   if (local_server_file)
  1647     {
  1648       s = set_tcp_socket (local_server_file);
  1649       if (s != INVALID_SOCKET || no_exit_if_error)
  1650         return s;
  1651 
  1652       message (true, "%s: error accessing server file \"%s\"\n",
  1653                progname, local_server_file);
  1654       exit (EXIT_FAILURE);
  1655     }
  1656 
  1657 #ifdef SOCKETS_IN_FILE_SYSTEM
  1658   /* Implicit local socket.  */
  1659   s = set_local_socket ("server");
  1660   if (s != INVALID_SOCKET)
  1661     return s;
  1662 #endif
  1663 
  1664   /* Implicit server file.  */
  1665   s = set_tcp_socket ("server");
  1666   if (s != INVALID_SOCKET || no_exit_if_error)
  1667     return s;
  1668 
  1669   /* No implicit or explicit socket, and no alternate editor.  */
  1670   message (true, "%s: No socket or alternate editor.  Please use:\n\n"
  1671 #ifdef SOCKETS_IN_FILE_SYSTEM
  1672 "\t--socket-name\n"
  1673 #endif
  1674 "\t--server-file      (or environment variable EMACS_SERVER_FILE)\n\
  1675 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
  1676            progname);
  1677   exit (EXIT_FAILURE);
  1678 }
  1679 
  1680 #ifdef HAVE_NTGUI
  1681 FARPROC set_fg;  /* Pointer to AllowSetForegroundWindow.  */
  1682 FARPROC get_wc;  /* Pointer to RealGetWindowClassA.  */
  1683 
  1684 void w32_set_user_model_id (void);
  1685 
  1686 void
  1687 w32_set_user_model_id (void)
  1688 {
  1689   HMODULE shell;
  1690   HRESULT (WINAPI * set_user_model) (const wchar_t * id);
  1691 
  1692   /* On Windows 7 and later, we need to set the user model ID
  1693      to associate emacsclient launched files with Emacs frames
  1694      in the UI.  */
  1695   shell = LoadLibrary ("shell32.dll");
  1696   if (shell)
  1697     {
  1698       set_user_model
  1699         = (void *) GetProcAddress (shell,
  1700                                    "SetCurrentProcessExplicitAppUserModelID");
  1701       /* If the function is defined, then we are running on Windows 7
  1702          or newer, and the UI uses this to group related windows
  1703          together.  Since emacs, runemacs, emacsclient are related, we
  1704          want them grouped even though the executables are different,
  1705          so we need to set a consistent ID between them.  */
  1706       if (set_user_model)
  1707         set_user_model (L"GNU.Emacs");
  1708 
  1709       FreeLibrary (shell);
  1710     }
  1711 }
  1712 
  1713 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
  1714 
  1715 BOOL CALLBACK
  1716 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
  1717 {
  1718   DWORD pid;
  1719   char class[6];
  1720 
  1721   /* Reject any window not of class "Emacs".  */
  1722   if (! get_wc (hWnd, class, sizeof (class))
  1723       || strcmp (class, "Emacs"))
  1724     return TRUE;
  1725 
  1726   /* We only need the process id, not the thread id.  */
  1727   (void) GetWindowThreadProcessId (hWnd, &pid);
  1728 
  1729   /* Not the one we're looking for.  */
  1730   if (pid != (DWORD) emacs_pid) return TRUE;
  1731 
  1732   /* OK, let's raise it.  */
  1733   set_fg (emacs_pid);
  1734 
  1735   /* Stop enumeration.  */
  1736   return FALSE;
  1737 }
  1738 
  1739 /* Search for a window of class "Emacs" and owned by a process with
  1740    process id = emacs_pid.  If found, allow it to grab the focus.  */
  1741 void w32_give_focus (void);
  1742 
  1743 void
  1744 w32_give_focus (void)
  1745 {
  1746   HANDLE user32;
  1747 
  1748   /* It shouldn't happen when dealing with TCP sockets.  */
  1749   if (!emacs_pid) return;
  1750 
  1751   user32 = GetModuleHandle ("user32.dll");
  1752 
  1753   if (!user32)
  1754     return;
  1755 
  1756   /* Modern Windows restrict which processes can set the foreground window.
  1757      emacsclient can allow Emacs to grab the focus by calling the function
  1758      AllowSetForegroundWindow.  Unfortunately, older Windows (W95, W98 and
  1759      NT) lack this function, so we have to check its availability.  */
  1760   if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
  1761       && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
  1762     EnumWindows (w32_find_emacs_process, (LPARAM) 0);
  1763 }
  1764 #endif /* HAVE_NTGUI */
  1765 
  1766 /* Start the emacs daemon and try to connect to it.  */
  1767 
  1768 static HSOCKET
  1769 start_daemon_and_retry_set_socket (void)
  1770 {
  1771 #ifndef WINDOWSNT
  1772   pid_t dpid;
  1773   int status;
  1774 
  1775   dpid = fork ();
  1776 
  1777   if (dpid > 0)
  1778     {
  1779       pid_t w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
  1780 
  1781       if (w < 0 || !WIFEXITED (status) || WEXITSTATUS (status))
  1782         {
  1783           message (true, "Error: Could not start the Emacs daemon\n");
  1784           exit (EXIT_FAILURE);
  1785         }
  1786 
  1787       /* Try connecting, the daemon should have started by now.  */
  1788       if (!quiet)
  1789         message (true,
  1790                  "Emacs daemon should have started, trying to connect again\n");
  1791     }
  1792   else if (dpid < 0)
  1793     {
  1794       fprintf (stderr, "Error: Cannot fork!\n");
  1795       exit (EXIT_FAILURE);
  1796     }
  1797   else
  1798     {
  1799       char emacs[] = "emacs";
  1800       char daemon_option[] = "--daemon";
  1801       char *d_argv[3];
  1802       d_argv[0] = emacs;
  1803       d_argv[1] = daemon_option;
  1804       d_argv[2] = 0;
  1805 # ifdef SOCKETS_IN_FILE_SYSTEM
  1806       if (socket_name != NULL)
  1807         {
  1808           /* Pass  --daemon=socket_name as argument.  */
  1809           const char *deq = "--daemon=";
  1810           char *daemon_arg = xmalloc (strlen (deq)
  1811                                       + strlen (socket_name) + 1);
  1812           strcpy (stpcpy (daemon_arg, deq), socket_name);
  1813           d_argv[1] = daemon_arg;
  1814         }
  1815 # endif
  1816       execvp ("emacs", d_argv);
  1817       message (true, "%s: error starting emacs daemon\n", progname);
  1818       exit (EXIT_FAILURE);
  1819     }
  1820 #else  /* WINDOWSNT */
  1821   DWORD wait_result;
  1822   HANDLE w32_daemon_event;
  1823   STARTUPINFO si;
  1824   PROCESS_INFORMATION pi;
  1825 
  1826   ZeroMemory (&si, sizeof si);
  1827   si.cb = sizeof si;
  1828   ZeroMemory (&pi, sizeof pi);
  1829 
  1830   /* We start Emacs in daemon mode, and then wait for it to signal us
  1831      it is ready to accept client connections, by asserting an event
  1832      whose name is known to the daemon (defined by nt/inc/ms-w32.h).  */
  1833 
  1834   if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
  1835                       CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
  1836     {
  1837       char* msg = NULL;
  1838 
  1839       FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  1840                      | FORMAT_MESSAGE_ALLOCATE_BUFFER
  1841                      | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1842                      NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
  1843       message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
  1844       exit (EXIT_FAILURE);
  1845     }
  1846 
  1847   w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
  1848   if (w32_daemon_event == NULL)
  1849     {
  1850       message (true, "Couldn't create Windows daemon event");
  1851       exit (EXIT_FAILURE);
  1852     }
  1853   if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
  1854       != WAIT_OBJECT_0)
  1855     {
  1856       const char *msg = NULL;
  1857 
  1858       switch (wait_result)
  1859         {
  1860         case WAIT_ABANDONED:
  1861           msg = "The daemon exited unexpectedly";
  1862           break;
  1863         case WAIT_TIMEOUT:
  1864           /* Can't happen due to INFINITE.  */
  1865         default:
  1866         case WAIT_FAILED:
  1867           FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  1868                          | FORMAT_MESSAGE_ALLOCATE_BUFFER
  1869                          | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1870                          NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
  1871           break;
  1872         }
  1873       message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
  1874       exit (EXIT_FAILURE);
  1875     }
  1876   CloseHandle (w32_daemon_event);
  1877 
  1878   /* Try connecting, the daemon should have started by now.  */
  1879   /* It's just a progress message, so don't pop a dialog if this is
  1880      emacsclientw.  */
  1881   if (!quiet && !w32_window_app ())
  1882     message (true,
  1883              "Emacs daemon should have started, trying to connect again\n");
  1884 #endif /* WINDOWSNT */
  1885 
  1886   HSOCKET emacs_socket = set_socket (true);
  1887   if (emacs_socket == INVALID_SOCKET)
  1888     {
  1889       message (true,
  1890                "Error: Cannot connect even after starting the Emacs daemon\n");
  1891       exit (EXIT_FAILURE);
  1892     }
  1893   return emacs_socket;
  1894 }
  1895 
  1896 static void
  1897 set_socket_timeout (HSOCKET socket, int seconds)
  1898 {
  1899   int ret;
  1900 
  1901 #ifndef WINDOWSNT
  1902   struct timeval timeout;
  1903   timeout.tv_sec = seconds;
  1904   timeout.tv_usec = 0;
  1905   ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
  1906 #else
  1907   DWORD timeout;
  1908 
  1909   if (seconds > INT_MAX / 1000)
  1910     timeout = INT_MAX;
  1911   else
  1912     timeout = seconds * 1000;
  1913   ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof timeout);
  1914 #endif
  1915 
  1916   if (ret < 0)
  1917     sock_err_message ("setsockopt");
  1918 }
  1919 
  1920 static bool
  1921 check_socket_timeout (int rl)
  1922 {
  1923 #ifndef WINDOWSNT
  1924   return (rl == -1)
  1925     && (errno == EAGAIN)
  1926     && (errno == EWOULDBLOCK);
  1927 #else
  1928   return (rl == SOCKET_ERROR)
  1929     && (WSAGetLastError() == WSAETIMEDOUT);
  1930 #endif
  1931 }
  1932 
  1933 int
  1934 main (int argc, char **argv)
  1935 {
  1936   main_argc = argc;
  1937   main_argv = argv;
  1938   progname = argv[0] ? argv[0] : "emacsclient";
  1939 
  1940   int rl = 0;
  1941   bool skiplf = true;
  1942   char string[BUFSIZ + 1];
  1943   int exit_status = EXIT_SUCCESS;
  1944 
  1945 #ifdef HAVE_NTGUI
  1946   /* On Windows 7 and later, we need to explicitly associate
  1947      emacsclient with emacs so the UI behaves sensibly.  This
  1948      association does no harm if we're not actually connecting to an
  1949      Emacs using a window display.  */
  1950   w32_set_user_model_id ();
  1951 #endif
  1952 
  1953   /* Process options.  */
  1954   decode_options (argc, argv);
  1955 
  1956   if (! (optind < argc || eval || create_frame))
  1957     {
  1958       message (true, ("%s: file name or argument required\n"
  1959                       "Try '%s --help' for more information\n"),
  1960                progname, progname);
  1961       exit (EXIT_FAILURE);
  1962     }
  1963 
  1964 #ifdef SOCKETS_IN_FILE_SYSTEM
  1965   if (tty)
  1966     {
  1967       pid_t grouping = process_grouping ();
  1968       if (grouping < 0)
  1969         kill (grouping, SIGTTIN);
  1970     }
  1971 #endif
  1972 
  1973   /* If alternate_editor is the empty string, start the emacs daemon
  1974      in case of failure to connect.  */
  1975   bool start_daemon_if_needed = alternate_editor && !alternate_editor[0];
  1976 
  1977   HSOCKET emacs_socket = set_socket (alternate_editor
  1978                                      || start_daemon_if_needed);
  1979   if (emacs_socket == INVALID_SOCKET)
  1980     {
  1981       if (! start_daemon_if_needed)
  1982         fail ();
  1983 
  1984       emacs_socket = start_daemon_and_retry_set_socket ();
  1985     }
  1986 
  1987   char *cwd = get_current_dir_name ();
  1988   if (cwd == 0)
  1989     {
  1990       message (true, "%s: %s\n", progname,
  1991                "Cannot get current working directory");
  1992       fail ();
  1993     }
  1994 
  1995 #ifdef HAVE_NTGUI
  1996   if (display && !strcmp (display, "w32"))
  1997   w32_give_focus ();
  1998 #endif
  1999 
  2000   /* Send over our environment and current directory. */
  2001   if (create_frame)
  2002     {
  2003       for (char *const *e = environ; *e; e++)
  2004         {
  2005           send_to_emacs (emacs_socket, "-env ");
  2006           quote_argument (emacs_socket, *e);
  2007           send_to_emacs (emacs_socket, " ");
  2008         }
  2009     }
  2010   send_to_emacs (emacs_socket, "-dir ");
  2011   if (tramp_prefix)
  2012     quote_argument (emacs_socket, tramp_prefix);
  2013   quote_argument (emacs_socket, cwd);
  2014   free (cwd);
  2015   send_to_emacs (emacs_socket, "/");
  2016   send_to_emacs (emacs_socket, " ");
  2017 
  2018  retry:
  2019   if (nowait)
  2020     send_to_emacs (emacs_socket, "-nowait ");
  2021 
  2022   if (!create_frame || reuse_frame)
  2023     send_to_emacs (emacs_socket, "-current-frame ");
  2024 
  2025   if (display)
  2026     {
  2027       send_to_emacs (emacs_socket, "-display ");
  2028       quote_argument (emacs_socket, display);
  2029       send_to_emacs (emacs_socket, " ");
  2030     }
  2031 
  2032   if (parent_id)
  2033     {
  2034       send_to_emacs (emacs_socket, "-parent-id ");
  2035       quote_argument (emacs_socket, parent_id);
  2036       send_to_emacs (emacs_socket, " ");
  2037     }
  2038 
  2039   if (frame_parameters && create_frame)
  2040     {
  2041       send_to_emacs (emacs_socket, "-frame-parameters ");
  2042       quote_argument (emacs_socket, frame_parameters);
  2043       send_to_emacs (emacs_socket, " ");
  2044     }
  2045 
  2046   /* Unless we are certain we don't want to occupy the tty, send our
  2047      tty information to Emacs.  For example, in daemon mode Emacs may
  2048      need to occupy this tty if no other frame is available.  */
  2049   if (create_frame || !eval)
  2050     {
  2051       const char *tty_type, *tty_name;
  2052 
  2053       if (find_tty (&tty_type, &tty_name, !tty))
  2054         {
  2055           /* Install signal handlers before opening a frame on the
  2056              current tty.  */
  2057           init_signals ();
  2058 
  2059           send_to_emacs (emacs_socket, "-tty ");
  2060           quote_argument (emacs_socket, tty_name);
  2061           send_to_emacs (emacs_socket, " ");
  2062           quote_argument (emacs_socket, tty_type);
  2063           send_to_emacs (emacs_socket, " ");
  2064         }
  2065     }
  2066 
  2067   if (create_frame && !tty)
  2068     send_to_emacs (emacs_socket, "-window-system ");
  2069 
  2070   if (optind < argc)
  2071     {
  2072       for (int i = optind; i < argc; i++)
  2073         {
  2074 
  2075           if (eval)
  2076             {
  2077               /* Don't prepend cwd or anything like that.  */
  2078               send_to_emacs (emacs_socket, "-eval ");
  2079               quote_argument (emacs_socket, argv[i]);
  2080               send_to_emacs (emacs_socket, " ");
  2081               continue;
  2082             }
  2083 
  2084           char *p = argv[i];
  2085           if (*p == '+')
  2086             {
  2087               unsigned char c;
  2088               do
  2089                 c = *++p;
  2090               while (isdigit (c) || c == ':');
  2091 
  2092               if (c == 0)
  2093                 {
  2094                   send_to_emacs (emacs_socket, "-position ");
  2095                   quote_argument (emacs_socket, argv[i]);
  2096                   send_to_emacs (emacs_socket, " ");
  2097                   continue;
  2098                 }
  2099             }
  2100 #ifdef WINDOWSNT
  2101           else if (! IS_ABSOLUTE_FILE_NAME (argv[i])
  2102                    && (isalpha (argv[i][0]) && argv[i][1] == ':'))
  2103             /* Windows can have a different default directory for each
  2104                drive, so the cwd passed via "-dir" is not sufficient
  2105                to account for that.
  2106                If the user uses <drive>:<relpath>, we hence need to be
  2107                careful to expand <relpath> with the default directory
  2108                corresponding to <drive>.  */
  2109             {
  2110               char *filename = xmalloc (MAX_PATH);
  2111               DWORD size;
  2112 
  2113               size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
  2114               if (size > 0 && size < MAX_PATH)
  2115                 argv[i] = filename;
  2116               else
  2117                 free (filename);
  2118             }
  2119 #endif
  2120 
  2121           send_to_emacs (emacs_socket, "-file ");
  2122           if (tramp_prefix && IS_ABSOLUTE_FILE_NAME (argv[i]))
  2123             quote_argument (emacs_socket, tramp_prefix);
  2124           quote_argument (emacs_socket, argv[i]);
  2125           send_to_emacs (emacs_socket, " ");
  2126         }
  2127     }
  2128   else if (eval)
  2129     {
  2130       /* Read expressions interactively.  */
  2131       while (fgets (string, BUFSIZ, stdin))
  2132         {
  2133           send_to_emacs (emacs_socket, "-eval ");
  2134           quote_argument (emacs_socket, string);
  2135         }
  2136       send_to_emacs (emacs_socket, " ");
  2137     }
  2138 
  2139   send_to_emacs (emacs_socket, "\n");
  2140 
  2141   /* Wait for an answer. */
  2142   if (!eval && !tty && !nowait && !quiet && 0 <= process_grouping ())
  2143     {
  2144       printf ("Waiting for Emacs...");
  2145       skiplf = false;
  2146     }
  2147   fflush (stdout);
  2148 
  2149   set_socket_timeout (emacs_socket, timeout > 0 ? timeout : DEFAULT_TIMEOUT);
  2150   bool saw_response = false;
  2151   /* Now, wait for an answer and print any messages.  */
  2152   while (exit_status == EXIT_SUCCESS)
  2153     {
  2154       bool retry = true;
  2155       bool msg_showed = quiet;
  2156       do
  2157         {
  2158           act_on_signals (emacs_socket);
  2159           rl = recv (emacs_socket, string, BUFSIZ, 0);
  2160           retry = check_socket_timeout (rl);
  2161           if (retry && !saw_response)
  2162             {
  2163               if (timeout > 0)
  2164                 {
  2165                   /* Don't retry if we were given a --timeout flag.  */
  2166                   fprintf (stderr, "\nServer not responding; timed out after %ju seconds",
  2167                            timeout);
  2168                   retry = false;
  2169                 }
  2170               else if (!msg_showed)
  2171                 {
  2172                   msg_showed = true;
  2173                   fprintf (stderr, "\nServer not responding; use Ctrl+C to break");
  2174                 }
  2175             }
  2176         }
  2177       while ((rl < 0 && errno == EINTR) || retry);
  2178 
  2179       if (rl <= 0)
  2180         break;
  2181 
  2182       saw_response = true;
  2183       string[rl] = '\0';
  2184 
  2185       /* Loop over all NL-terminated messages.  */
  2186       char *p = string;
  2187       for (char *end_p = p; end_p && *end_p != '\0'; p = end_p)
  2188         {
  2189           end_p = strchr (p, '\n');
  2190           if (end_p != NULL)
  2191             *end_p++ = '\0';
  2192 
  2193           if (strprefix ("-emacs-pid ", p))
  2194             {
  2195               /* -emacs-pid PID: The process id of the Emacs process. */
  2196               emacs_pid = strtoumax (p + strlen ("-emacs-pid"), NULL, 10);
  2197             }
  2198           else if (strprefix ("-window-system-unsupported ", p))
  2199             {
  2200               /* -window-system-unsupported: Emacs was compiled without support
  2201                  for whatever window system we tried.  Try the alternate
  2202                  display, or, failing that, try the terminal.  */
  2203               if (alt_display)
  2204                 {
  2205                   display = alt_display;
  2206                   alt_display = NULL;
  2207                 }
  2208               else
  2209                 {
  2210                   nowait = false;
  2211                   tty = true;
  2212                 }
  2213 
  2214               goto retry;
  2215             }
  2216           else if (strprefix ("-print ", p))
  2217             {
  2218               /* -print STRING: Print STRING on the terminal. */
  2219               if (!suppress_output)
  2220                 {
  2221                   char *str = unquote_argument (p + strlen ("-print "));
  2222                   printf (&"\n%s"[skiplf], str);
  2223                   if (str[0])
  2224                     skiplf = str[strlen (str) - 1] == '\n';
  2225                 }
  2226             }
  2227           else if (strprefix ("-print-nonl ", p))
  2228             {
  2229               /* -print-nonl STRING: Print STRING on the terminal.
  2230                  Used to continue a preceding -print command.  */
  2231               if (!suppress_output)
  2232                 {
  2233                   char *str = unquote_argument (p + strlen ("-print-nonl "));
  2234                   printf ("%s", str);
  2235                   if (str[0])
  2236                     skiplf = str[strlen (str) - 1] == '\n';
  2237                 }
  2238             }
  2239           else if (strprefix ("-error ", p))
  2240             {
  2241               /* -error DESCRIPTION: Signal an error on the terminal. */
  2242               char *str = unquote_argument (p + strlen ("-error "));
  2243               if (!skiplf)
  2244                 printf ("\n");
  2245               message (true, "*ERROR*: %s", str);
  2246               if (str[0])
  2247                 skiplf = str[strlen (str) - 1] == '\n';
  2248               exit_status = EXIT_FAILURE;
  2249             }
  2250 #ifndef WINDOWSNT
  2251           else if (strprefix ("-suspend ", p))
  2252             {
  2253               /* -suspend: Suspend this terminal, i.e., stop the process. */
  2254               if (!skiplf)
  2255                 printf ("\n");
  2256               skiplf = true;
  2257               kill (0, SIGSTOP);
  2258             }
  2259 #endif
  2260           else
  2261             {
  2262               /* Unknown command. */
  2263               printf (&"\n*ERROR*: Unknown message: %s\n"[skiplf], p);
  2264               skiplf = true;
  2265             }
  2266         }
  2267     }
  2268 
  2269   if (!skiplf && 0 <= process_grouping ())
  2270     printf ("\n");
  2271 
  2272   if (rl < 0)
  2273     exit_status = EXIT_FAILURE;
  2274 
  2275   CLOSE_SOCKET (emacs_socket);
  2276   return exit_status;
  2277 }

/* [<][>][^][v][top][bottom][index][help] */