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 #elif defined (HAVE_ANDROID)
   630       alt_display = "android";
   631 #endif
   632 
   633 #ifdef HAVE_PGTK
   634       display = egetenv ("WAYLAND_DISPLAY");
   635       alt_display = egetenv ("DISPLAY");
   636 #else
   637       display = egetenv ("DISPLAY");
   638 #endif
   639     }
   640 
   641   if (!display)
   642     {
   643       display = alt_display;
   644       alt_display = NULL;
   645     }
   646 
   647   /* A null-string display is invalid.  */
   648   if (display && !display[0])
   649     display = NULL;
   650 
   651   /* If no display is available, new frames are tty frames.  */
   652   if (create_frame && !display)
   653     tty = true;
   654 
   655 #ifdef WINDOWSNT
   656   /* Emacs on Windows does not support graphical and text terminal
   657      frames in the same instance.  So, treat the -t and -c options as
   658      equivalent, and open a new frame on the server's terminal.
   659      Ideally, we would set tty = true only if the server is running in a
   660      console, but alas we don't know that.  As a workaround, always
   661      ask for a tty frame, and let server.el figure it out.  */
   662   if (create_frame)
   663     {
   664       display = NULL;
   665       tty = true;
   666     }
   667 #endif /* WINDOWSNT */
   668 }
   669 
   670 
   671 static _Noreturn void
   672 print_help_and_exit (void)
   673 {
   674   /* Spaces and tabs are significant in this message; they're chosen so the
   675      message aligns properly both in a tty and in a Windows message box.
   676      Please try to preserve them; otherwise the output is very hard to read
   677      when using emacsclientw.  */
   678   message (false,
   679            "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
   680 Tell the Emacs server to visit the specified files.\n\
   681 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
   682 \n\
   683 The following OPTIONS are accepted:\n\
   684 -V, --version           Just print version info and return\n\
   685 -H, --help              Print this usage information message\n\
   686 -nw, -t, --tty          Open a new Emacs frame on the current terminal\n\
   687 -c, --create-frame      Create a new frame instead of trying to\n\
   688                         use the current Emacs frame\n\
   689 -r, --reuse-frame       Create a new frame if none exists, otherwise\n\
   690                         use the current Emacs frame\n\
   691 ", "\
   692 -F ALIST, --frame-parameters=ALIST\n\
   693                         Set the parameters of a new frame\n\
   694 -e, --eval              Evaluate the FILE arguments as ELisp expressions\n\
   695 -n, --no-wait           Don't wait for the server to return\n\
   696 -w, --timeout=SECONDS   Seconds to wait before timing out\n\
   697 -q, --quiet             Don't display messages on success\n\
   698 -u, --suppress-output   Don't display return values from the server\n\
   699 -d DISPLAY, --display=DISPLAY\n\
   700                         Visit the file in the given display\n\
   701 ", "\
   702 --parent-id=ID          Open in parent window ID, via XEmbed\n"
   703 #ifdef SOCKETS_IN_FILE_SYSTEM
   704 "-s SOCKET, --socket-name=SOCKET\n\
   705                         Set filename of the UNIX socket for communication\n"
   706 #endif
   707 "-f SERVER, --server-file=SERVER\n\
   708                         Set filename of the TCP authentication file\n\
   709 -a EDITOR, --alternate-editor=EDITOR\n\
   710                         Editor to fallback to if the server is not running\n"
   711 "                       If EDITOR is the empty string, start Emacs in daemon\n\
   712                         mode and try connecting again\n"
   713 "-T PREFIX, --tramp=PREFIX\n\
   714                         PREFIX to prepend to filenames sent by emacsclient\n\
   715                         for locating files remotely via Tramp\n"
   716 "\n\
   717 Report bugs with M-x report-emacs-bug.\n");
   718   exit (EXIT_SUCCESS);
   719 }
   720 
   721 /* Try to run a different command, or --if no alternate editor is
   722    defined-- exit with an error code.
   723    Uses argv, but gets it from the global variable main_argv.  */
   724 
   725 static _Noreturn void
   726 fail (void)
   727 {
   728   if (alternate_editor)
   729     {
   730       size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
   731       size_t new_argv_size = extra_args_size;
   732       char **new_argv = xmalloc (new_argv_size);
   733       char *s = xstrdup (alternate_editor);
   734       ptrdiff_t toks = 0;
   735 
   736       /* Unpack alternate_editor's space-separated tokens into new_argv.  */
   737       for (char *tok = s; tok != NULL && *tok != '\0';)
   738         {
   739           /* Allocate new token.  */
   740           ++toks;
   741           new_argv = xrealloc (new_argv,
   742                                new_argv_size + toks * sizeof (char *));
   743 
   744           /* Skip leading delimiters, and set separator, skipping any
   745              opening quote.  */
   746           size_t skip = strspn (tok, " \"");
   747           tok += skip;
   748           char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';
   749 
   750           /* Record start of token.  */
   751           new_argv[toks - 1] = tok;
   752 
   753           /* Find end of token and overwrite it with NUL.  */
   754           tok = strchr (tok, sep);
   755           if (tok != NULL)
   756             *tok++ = '\0';
   757         }
   758 
   759       /* Append main_argv arguments to new_argv.  */
   760       memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
   761 
   762       execvp (*new_argv, new_argv);
   763       message (true, "%s: error executing alternate editor \"%s\"\n",
   764                progname, alternate_editor);
   765     }
   766   exit (EXIT_FAILURE);
   767 }
   768 
   769 
   770 #ifdef SOCKETS_IN_FILE_SYSTEM
   771 static void act_on_signals (HSOCKET);
   772 #else
   773 static void act_on_signals (HSOCKET s) {}
   774 static void init_signals (void) {}
   775 #endif
   776 
   777 enum { AUTH_KEY_LENGTH = 64 };
   778 
   779 static void
   780 sock_err_message (const char *function_name)
   781 {
   782 #ifdef WINDOWSNT
   783   /* On Windows, the socket library was historically separate from the
   784      standard C library, so errors are handled differently.  */
   785 
   786   if (w32_window_app () && alternate_editor)
   787     return;
   788 
   789   char *msg = NULL;
   790 
   791   FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
   792                  | FORMAT_MESSAGE_ALLOCATE_BUFFER
   793                  | FORMAT_MESSAGE_ARGUMENT_ARRAY,
   794                  NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
   795 
   796   message (true, "%s: %s: %s\n", progname, function_name, msg);
   797 
   798   LocalFree (msg);
   799 #else
   800   message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
   801 #endif
   802 }
   803 
   804 
   805 /* Send to S the data in *DATA when either
   806    - the data's last byte is '\n', or
   807    - the buffer is full (but this shouldn't happen)
   808    Otherwise, just accumulate the data.  */
   809 static void
   810 send_to_emacs (HSOCKET s, const char *data)
   811 {
   812   enum { SEND_BUFFER_SIZE = 4096 };
   813 
   814   /* Buffer to accumulate data to send in TCP connections.  */
   815   static char send_buffer[SEND_BUFFER_SIZE + 1];
   816 
   817   /* Fill pointer for the send buffer.  */
   818   static int sblen;
   819 
   820   for (ptrdiff_t dlen = strlen (data); dlen != 0; )
   821     {
   822       int part = min (dlen, SEND_BUFFER_SIZE - sblen);
   823       memcpy (&send_buffer[sblen], data, part);
   824       data += part;
   825       sblen += part;
   826 
   827       if (sblen == SEND_BUFFER_SIZE
   828           || (0 < sblen && send_buffer[sblen - 1] == '\n'))
   829         {
   830           int sent;
   831           while ((sent = send (s, send_buffer, sblen, 0)) < 0)
   832             {
   833               if (errno != EINTR)
   834                 {
   835                   message (true, "%s: failed to send %d bytes to socket: %s\n",
   836                            progname, sblen, strerror (errno));
   837                   fail ();
   838                 }
   839               /* Act on signals not requiring communication to Emacs,
   840                  but defer action on the others to avoid confusing the
   841                  communication currently in progress.  */
   842               act_on_signals (INVALID_SOCKET);
   843             }
   844           sblen -= sent;
   845           memmove (send_buffer, &send_buffer[sent], sblen);
   846         }
   847 
   848       dlen -= part;
   849     }
   850 }
   851 
   852 
   853 /* In STR, insert a & before each &, each space, each newline, and
   854    any initial -.  Change spaces to underscores, too, so that the
   855    return value never contains a space.
   856 
   857    Does not change the string.  Outputs the result to S.  */
   858 static void
   859 quote_argument (HSOCKET s, const char *str)
   860 {
   861   char *copy = xmalloc (strlen (str) * 2 + 1);
   862   char *q = copy;
   863   if (*str == '-')
   864     *q++ = '&', *q++ = *str++;
   865   for (; *str; str++)
   866     {
   867       char c = *str;
   868       if (c == ' ')
   869         *q++ = '&', c = '_';
   870       else if (c == '\n')
   871         *q++ = '&', c = 'n';
   872       else if (c == '&')
   873         *q++ = '&';
   874       *q++ = c;
   875     }
   876   *q = 0;
   877 
   878   send_to_emacs (s, copy);
   879 
   880   free (copy);
   881 }
   882 
   883 
   884 /* The inverse of quote_argument.  Remove quoting in string STR by
   885    modifying the addressed string in place.  Return STR.  */
   886 
   887 static char *
   888 unquote_argument (char *str)
   889 {
   890   char const *p = str;
   891   char *q = str;
   892   char c;
   893 
   894   do
   895     {
   896       c = *p++;
   897       if (c == '&')
   898         {
   899           c = *p++;
   900           if (c == '_')
   901             c = ' ';
   902           else if (c == 'n')
   903             c = '\n';
   904         }
   905       *q++ = c;
   906     }
   907   while (c);
   908 
   909   return str;
   910 }
   911 
   912 
   913 #ifdef WINDOWSNT
   914 /* Wrapper to make WSACleanup a cdecl, as required by atexit.  */
   915 void __cdecl close_winsock (void);
   916 void __cdecl
   917 close_winsock (void)
   918 {
   919   WSACleanup ();
   920 }
   921 
   922 /* Initialize the WinSock2 library.  */
   923 void initialize_sockets (void);
   924 void
   925 initialize_sockets (void)
   926 {
   927   WSADATA wsaData;
   928 
   929   if (WSAStartup (MAKEWORD (2, 0), &wsaData))
   930     {
   931       message (true, "%s: error initializing WinSock2\n", progname);
   932       exit (EXIT_FAILURE);
   933     }
   934 
   935   atexit (close_winsock);
   936 }
   937 #endif /* WINDOWSNT */
   938 
   939 
   940 /* If the home directory is HOME, and XDG_CONFIG_HOME's value is XDG,
   941    return the configuration file with basename CONFIG_FILE.  Fail if
   942    the configuration file could not be opened.  */
   943 
   944 static FILE *
   945 open_config (char const *home, char const *xdg, char const *config_file)
   946 {
   947   ptrdiff_t xdgsubdirsize = xdg ? strlen (xdg) + sizeof "/emacs/server/" : 0;
   948   ptrdiff_t homesuffixsizemax = max (sizeof "/.config/emacs/server/",
   949                                      sizeof "/.emacs.d/server/");
   950   ptrdiff_t homesubdirsizemax = home ? strlen (home) + homesuffixsizemax : 0;
   951   char *configname = xmalloc (max (xdgsubdirsize, homesubdirsizemax)
   952                               + strlen (config_file));
   953   FILE *config;
   954 
   955   if (home)
   956     {
   957       strcpy (stpcpy (stpcpy (configname, home), "/.emacs.d/server/"),
   958               config_file);
   959       config = fopen (configname, "rb");
   960     }
   961   else
   962     config = NULL;
   963 
   964   if (! config && (xdg || home))
   965     {
   966       strcpy ((xdg
   967                ? stpcpy (stpcpy (configname, xdg), "/emacs/server/")
   968                : stpcpy (stpcpy (configname, home), "/.config/emacs/server/")),
   969               config_file);
   970       config = fopen (configname, "rb");
   971     }
   972 
   973   free (configname);
   974   return config;
   975 }
   976 
   977 /* Read the information needed to set up a TCP comm channel with
   978    the Emacs server: host, port, and authentication string.  */
   979 
   980 static bool
   981 get_server_config (const char *config_file, struct sockaddr_in *server,
   982                    char *authentication)
   983 {
   984   char dotted[32];
   985   char *port;
   986   FILE *config;
   987 
   988   if (IS_ABSOLUTE_FILE_NAME (config_file))
   989     config = fopen (config_file, "rb");
   990   else
   991     {
   992       char const *xdg = egetenv ("XDG_CONFIG_HOME");
   993       config = open_config (egetenv ("HOME"), xdg, config_file);
   994 #ifdef WINDOWSNT
   995       if (!config)
   996         config = open_config (egetenv ("APPDATA"), xdg, config_file);
   997 #endif
   998     }
   999 
  1000   if (! config)
  1001     return false;
  1002 
  1003   if (fgets (dotted, sizeof dotted, config)
  1004       && (port = strchr (dotted, ':')))
  1005     *port++ = '\0';
  1006   else
  1007     {
  1008       message (true, "%s: invalid configuration info\n", progname);
  1009       exit (EXIT_FAILURE);
  1010     }
  1011 
  1012   memset (server, 0, sizeof *server);
  1013   server->sin_family = AF_INET;
  1014   server->sin_addr.s_addr = inet_addr (dotted);
  1015   server->sin_port = htons (atoi (port));
  1016 
  1017   if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
  1018     {
  1019       message (true, "%s: cannot read authentication info\n", progname);
  1020       exit (EXIT_FAILURE);
  1021     }
  1022 
  1023   fclose (config);
  1024 
  1025   return true;
  1026 }
  1027 
  1028 /* Like socket (DOMAIN, TYPE, PROTOCOL), except arrange for the
  1029    resulting file descriptor to be close-on-exec.  */
  1030 
  1031 static HSOCKET
  1032 cloexec_socket (int domain, int type, int protocol)
  1033 {
  1034 #ifdef SOCK_CLOEXEC
  1035   return socket (domain, type | SOCK_CLOEXEC, protocol);
  1036 #else
  1037   HSOCKET s = socket (domain, type, protocol);
  1038 # ifndef WINDOWSNT
  1039   if (0 <= s)
  1040     fcntl (s, F_SETFD, FD_CLOEXEC);
  1041 # endif
  1042   return s;
  1043 #endif
  1044 }
  1045 
  1046 static HSOCKET
  1047 set_tcp_socket (const char *local_server_file)
  1048 {
  1049   union {
  1050     struct sockaddr_in in;
  1051     struct sockaddr sa;
  1052   } server;
  1053   struct linger l_arg = { .l_onoff = 1, .l_linger = 1 };
  1054   char auth_string[AUTH_KEY_LENGTH + 1];
  1055 
  1056   if (! get_server_config (local_server_file, &server.in, auth_string))
  1057     return INVALID_SOCKET;
  1058 
  1059   if (server.in.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
  1060     message (false, "%s: connected to remote socket at %s\n",
  1061              progname, inet_ntoa (server.in.sin_addr));
  1062 
  1063   /* Open up an AF_INET socket.  */
  1064   HSOCKET s = cloexec_socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1065   if (s < 0)
  1066     {
  1067       /* Since we have an alternate to try out, this is not an error
  1068          yet; popping out a modal dialog at this stage would make -a
  1069          option totally useless for emacsclientw -- the user will
  1070          still get an error message if the alternate editor fails.  */
  1071       sock_err_message ("socket");
  1072       return INVALID_SOCKET;
  1073     }
  1074 
  1075   /* Set up the socket.  */
  1076   if (connect (s, &server.sa, sizeof server.in) != 0)
  1077     {
  1078       sock_err_message ("connect");
  1079       CLOSE_SOCKET (s);
  1080       return INVALID_SOCKET;
  1081     }
  1082 
  1083   /* The cast to 'const char *' is to avoid a compiler warning when
  1084      compiling for MS-Windows sockets.  */
  1085   int ret = setsockopt (s, SOL_SOCKET, SO_LINGER, (const char *) &l_arg, sizeof l_arg);
  1086   if (ret < 0)
  1087     sock_err_message ("setsockopt");
  1088 
  1089   /* Send the authentication.  */
  1090   auth_string[AUTH_KEY_LENGTH] = '\0';
  1091 
  1092   send_to_emacs (s, "-auth ");
  1093   send_to_emacs (s, auth_string);
  1094   send_to_emacs (s, " ");
  1095 
  1096   return s;
  1097 }
  1098 
  1099 
  1100 /* Return true if PREFIX is a prefix of STRING. */
  1101 static bool
  1102 strprefix (const char *prefix, const char *string)
  1103 {
  1104   return !strncmp (prefix, string, strlen (prefix));
  1105 }
  1106 
  1107 /* Get tty name and type.  If successful, store the type into
  1108    *TTY_TYPE and the name into *TTY_NAME, and return true.
  1109    Otherwise, fail if NOABORT is zero, or return false if NOABORT.  */
  1110 
  1111 static bool
  1112 find_tty (const char **tty_type, const char **tty_name, bool noabort)
  1113 {
  1114   const char *type = egetenv ("TERM");
  1115   const char *name = ttyname (STDOUT_FILENO);
  1116 
  1117   if (!name)
  1118     {
  1119       if (noabort)
  1120         return false;
  1121       message (true, "%s: could not get terminal name\n", progname);
  1122       fail ();
  1123     }
  1124 
  1125   if (!type)
  1126     {
  1127       if (noabort)
  1128         return false;
  1129       message (true, "%s: please set the TERM variable to your terminal type\n",
  1130                progname);
  1131       fail ();
  1132     }
  1133 
  1134   const char *inside_emacs = egetenv ("INSIDE_EMACS");
  1135   if (inside_emacs && strstr (inside_emacs, ",term:")
  1136       && strprefix ("eterm", type))
  1137     {
  1138       if (noabort)
  1139         return false;
  1140       /* This causes nasty, MULTI_KBOARD-related input lockouts. */
  1141       message (true, ("%s: opening a frame in an Emacs term buffer"
  1142                       " is not supported\n"),
  1143                progname);
  1144       fail ();
  1145     }
  1146 
  1147   *tty_name = name;
  1148   *tty_type = type;
  1149   return true;
  1150 }
  1151 
  1152 /* Return the process group if in the foreground, the negative of the
  1153    process group if in the background, and zero if there is no
  1154    foreground process group for the controlling terminal.
  1155    Unfortunately, use of this function introduces an unavoidable race,
  1156    since whether the process is in the foreground or background can
  1157    change at any time.  */
  1158 
  1159 static pid_t
  1160 process_grouping (void)
  1161 {
  1162 #ifdef SOCKETS_IN_FILE_SYSTEM
  1163   pid_t tcpgrp = tcgetpgrp (STDOUT_FILENO);
  1164   if (0 <= tcpgrp)
  1165     {
  1166       pid_t pgrp = getpgrp ();
  1167       return tcpgrp == pgrp ? pgrp : -pgrp;
  1168     }
  1169 #endif
  1170   return 0;
  1171 }
  1172 
  1173 #ifdef SOCKETS_IN_FILE_SYSTEM
  1174 
  1175 # include <acl.h>
  1176 
  1177 # ifndef O_PATH
  1178 #  define O_PATH O_SEARCH
  1179 # endif
  1180 
  1181 /* A local socket address.  The union avoids the need to cast.  */
  1182 union local_sockaddr
  1183 {
  1184   struct sockaddr_un un;
  1185   struct sockaddr sa;
  1186 };
  1187 
  1188 /* Relative to the directory DIRFD, connect the socket file named ADDR
  1189    to the socket S.  Return 0 if successful, -1 if DIRFD is not
  1190    AT_FDCWD and DIRFD's permissions would allow a symlink attack, an
  1191    errno otherwise.  */
  1192 
  1193 static int
  1194 connect_socket (int dirfd, char const *addr, int s, uid_t uid)
  1195 {
  1196   int sock_status = 0;
  1197 
  1198   union local_sockaddr server;
  1199   if (sizeof server.un.sun_path <= strlen (addr))
  1200     return ENAMETOOLONG;
  1201   server.un.sun_family = AF_UNIX;
  1202   strcpy (server.un.sun_path, addr);
  1203 
  1204   /* If -1, WDFD is not set yet.  If nonnegative, WDFD is a file
  1205      descriptor for the initial working directory.  Otherwise -1 - WDFD is
  1206      the error number for the initial working directory.  */
  1207   static int wdfd = -1;
  1208 
  1209   if (dirfd != AT_FDCWD)
  1210     {
  1211       /* Fail if DIRFD's permissions are bogus.  */
  1212       struct stat st;
  1213       if (fstat (dirfd, &st) != 0)
  1214         return errno;
  1215       if (st.st_uid != uid || (st.st_mode & (S_IWGRP | S_IWOTH)))
  1216         return -1;
  1217 
  1218       if (wdfd == -1)
  1219         {
  1220           /* Save the initial working directory.  */
  1221           wdfd = open (".", O_PATH | O_CLOEXEC);
  1222           if (wdfd < 0)
  1223             wdfd = -1 - errno;
  1224         }
  1225       if (wdfd < 0)
  1226         return -1 - wdfd;
  1227       if (fchdir (dirfd) != 0)
  1228         return errno;
  1229 
  1230       /* Fail if DIRFD has an ACL, which means its permissions are
  1231          almost surely bogus.  */
  1232       int has_acl = file_has_acl (".", &st);
  1233       if (has_acl)
  1234         sock_status = has_acl < 0 ? errno : -1;
  1235     }
  1236 
  1237   if (!sock_status)
  1238     sock_status = connect (s, &server.sa, sizeof server.un) == 0 ? 0 : errno;
  1239 
  1240   /* Fail immediately if we cannot change back to the initial working
  1241      directory, as that can mess up the rest of execution.  */
  1242   if (dirfd != AT_FDCWD && fchdir (wdfd) != 0)
  1243     {
  1244       message (true, "%s: .: %s\n", progname, strerror (errno));
  1245       exit (EXIT_FAILURE);
  1246     }
  1247 
  1248   return sock_status;
  1249 }
  1250 
  1251 
  1252 /* Signal handlers merely set a flag, to avoid race conditions on
  1253    POSIXish systems.  Non-POSIX platforms lacking sigaction make do
  1254    with traditional calls to 'signal'; races are rare so this usually
  1255    works.  Although this approach may treat multiple deliveries of SIG
  1256    as a single delivery and may act on signals in a different order
  1257    than received, that is OK for emacsclient.  Also, this approach may
  1258    omit output if a printf call is interrupted by a signal, but printf
  1259    output is not that important (emacsclient does not check for printf
  1260    errors, after all) so this is also OK for emacsclient.  */
  1261 
  1262 /* Reinstall for SIG the signal handler HANDLER if needed.  It is
  1263    needed on a non-POSIX or traditional platform where an interrupt
  1264    resets the signal handler to SIG_DFL.  */
  1265 static void
  1266 reinstall_handler_if_needed (int sig, void (*handler) (int))
  1267 {
  1268 # ifndef SA_RESETHAND
  1269   /* This is a platform without POSIX's sigaction.  */
  1270   signal (sig, handler);
  1271 # endif
  1272 }
  1273 
  1274 /* Flags for each signal, and handlers that set the flags.  */
  1275 
  1276 static sig_atomic_t volatile
  1277   got_sigcont, got_sigtstp, got_sigttou, got_sigwinch;
  1278 
  1279 static void
  1280 handle_sigcont (int sig)
  1281 {
  1282   got_sigcont = 1;
  1283   reinstall_handler_if_needed (sig, handle_sigcont);
  1284 }
  1285 static void
  1286 handle_sigtstp (int sig)
  1287 {
  1288   got_sigtstp = 1;
  1289   reinstall_handler_if_needed (sig, handle_sigtstp);
  1290 }
  1291 static void
  1292 handle_sigttou (int sig)
  1293 {
  1294   got_sigttou = 1;
  1295   reinstall_handler_if_needed (sig, handle_sigttou);
  1296 }
  1297 static void
  1298 handle_sigwinch (int sig)
  1299 {
  1300   got_sigwinch = 1;
  1301   reinstall_handler_if_needed (sig, handle_sigwinch);
  1302 }
  1303 
  1304 /* Install for signal SIG the handler HANDLER.  However, if FLAG is
  1305    non-null and if the signal is currently being ignored, do not
  1306    install the handler and keep *FLAG zero.  */
  1307 
  1308 static void
  1309 install_handler (int sig, void (*handler) (int), sig_atomic_t volatile *flag)
  1310 {
  1311 # ifdef SA_RESETHAND
  1312   if (flag)
  1313     {
  1314       struct sigaction oact;
  1315       if (sigaction (sig, NULL, &oact) == 0 && oact.sa_handler == SIG_IGN)
  1316         return;
  1317     }
  1318   struct sigaction act = { .sa_handler = handler };
  1319   sigemptyset (&act.sa_mask);
  1320   sigaction (sig, &act, NULL);
  1321 # else
  1322   void (*ohandler) (int) = signal (sig, handler);
  1323   if (flag)
  1324     {
  1325       if (ohandler == SIG_IGN)
  1326         {
  1327           signal (sig, SIG_IGN);
  1328           /* While HANDLER was mistakenly installed a signal may have
  1329              arrived and set *FLAG, so clear *FLAG now.  */
  1330           *flag = 0;
  1331         }
  1332     }
  1333 # endif
  1334 }
  1335 
  1336 /* Initial installation of signal handlers.  */
  1337 
  1338 static void
  1339 init_signals (void)
  1340 {
  1341   install_handler (SIGCONT, handle_sigcont, &got_sigcont);
  1342   install_handler (SIGTSTP, handle_sigtstp, &got_sigtstp);
  1343   install_handler (SIGTTOU, handle_sigttou, &got_sigttou);
  1344   install_handler (SIGWINCH, handle_sigwinch, &got_sigwinch);
  1345   /* Don't mess with SIGINT and SIGQUIT, as Emacs has no way to
  1346      determine which terminal the signal came from.  C-g is a normal
  1347      input event on secondary terminals.  */
  1348 }
  1349 
  1350 /* Act on delivered tty-related signal SIG that normally has handler
  1351    HANDLER.  EMACS_SOCKET connects to Emacs.  */
  1352 
  1353 static void
  1354 act_on_tty_signal (int sig, void (*handler) (int), HSOCKET emacs_socket)
  1355 {
  1356   /* Notify Emacs that we are going to sleep.  Normally the suspend is
  1357      initiated by Emacs via server-handle-suspend-tty, but if the
  1358      server gets out of sync with reality, we may get a SIGTSTP on
  1359      C-z.  Handling this signal and notifying Emacs about it should
  1360      get things under control again.  */
  1361   send_to_emacs (emacs_socket, "-suspend \n");
  1362 
  1363   /* Execute the default action by temporarily changing handling to
  1364      the default and resignaling.  */
  1365   install_handler (sig, SIG_DFL, NULL);
  1366   raise (sig);
  1367   install_handler (sig, handler, NULL);
  1368 }
  1369 
  1370 /* Act on delivered signals if possible.  If EMACS_SOCKET is valid,
  1371    use it to communicate to Emacs.  */
  1372 
  1373 static void
  1374 act_on_signals (HSOCKET emacs_socket)
  1375 {
  1376   while (true)
  1377     {
  1378       bool took_action = false;
  1379 
  1380       if (emacs_socket != INVALID_SOCKET)
  1381         {
  1382           if (got_sigcont)
  1383             {
  1384               got_sigcont = 0;
  1385               took_action = true;
  1386               pid_t grouping = process_grouping ();
  1387               if (grouping < 0)
  1388                 {
  1389                   if (tty)
  1390                     {
  1391                       /* Cancel the continue.  */
  1392                       kill (grouping, SIGTTIN);
  1393                     }
  1394                 }
  1395               else
  1396                 send_to_emacs (emacs_socket, "-resume \n");
  1397             }
  1398 
  1399           if (got_sigtstp)
  1400             {
  1401               got_sigtstp = 0;
  1402               took_action = true;
  1403               act_on_tty_signal (SIGTSTP, handle_sigtstp, emacs_socket);
  1404             }
  1405           if (got_sigttou)
  1406             {
  1407               got_sigttou = 0;
  1408               took_action = true;
  1409               act_on_tty_signal (SIGTTOU, handle_sigttou, emacs_socket);
  1410             }
  1411         }
  1412 
  1413       if (emacs_pid && got_sigwinch)
  1414         {
  1415           got_sigwinch = 0;
  1416           took_action = true;
  1417           kill (emacs_pid, SIGWINCH);
  1418         }
  1419 
  1420       if (!took_action)
  1421         break;
  1422     }
  1423 }
  1424 
  1425 enum { socknamesize = sizeof ((struct sockaddr_un *) NULL)->sun_path };
  1426 
  1427 /* Given a local socket S, create in *SOCKNAME a name for a local socket
  1428    and connect to that socket.  The first TMPDIRLEN bytes of *SOCKNAME are
  1429    already initialized to be the name of a temporary directory.
  1430    Use UID and SERVER_NAME to concoct the name.  Return 0 if
  1431    successful, -1 if the socket's parent directory is not safe, and an
  1432    errno if there is some other problem.  */
  1433 
  1434 static int
  1435 local_sockname (int s, char sockname[socknamesize], int tmpdirlen,
  1436                 uid_t uid, char const *server_name)
  1437 {
  1438   /* If ! (0 <= TMPDIRLEN && TMPDIRLEN < SOCKNAMESIZE) the truncated
  1439      temporary directory name is already in SOCKNAME, so nothing more
  1440      need be stored.  */
  1441   if (! (0 <= tmpdirlen && tmpdirlen < socknamesize))
  1442     return ENAMETOOLONG;
  1443 
  1444   /* Put the full address name into the buffer, since the caller might
  1445      need it for diagnostics.  But don't overrun the buffer.  */
  1446   uintmax_t uidmax = uid;
  1447   int suffixlen = snprintf (sockname + tmpdirlen, socknamesize - tmpdirlen,
  1448                             "/emacs%"PRIuMAX"/%s", uidmax, server_name);
  1449   if (! (0 <= suffixlen && suffixlen < socknamesize - tmpdirlen))
  1450     return ENAMETOOLONG;
  1451 
  1452   /* Make sure the address's parent directory is not a symlink and is
  1453      this user's directory and does not let others write to it; this
  1454      fends off some symlink attacks.  To avoid races, keep the parent
  1455      directory open while checking.  */
  1456   char *emacsdirend = sockname + tmpdirlen + suffixlen -
  1457     strlen(server_name) - 1;
  1458   *emacsdirend = '\0';
  1459   int dir = open (sockname, O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
  1460   *emacsdirend = '/';
  1461   if (dir < 0)
  1462     return errno;
  1463   int sock_status = connect_socket (dir, server_name, s, uid);
  1464   close (dir);
  1465   return sock_status;
  1466 }
  1467 
  1468 /* Create a local socket for SERVER_NAME and connect it to Emacs.  If
  1469    SERVER_NAME is a file name component, the local socket name
  1470    relative to a well-known location in a temporary directory.
  1471    Otherwise, the local socket name is SERVER_NAME.  */
  1472 
  1473 static HSOCKET
  1474 set_local_socket (char const *server_name)
  1475 {
  1476   union local_sockaddr server;
  1477   int sock_status;
  1478   char *sockname = server.un.sun_path;
  1479   int tmpdirlen = -1;
  1480   int socknamelen = -1;
  1481   uid_t uid = geteuid ();
  1482   bool tmpdir_used = false;
  1483   int s = cloexec_socket (AF_UNIX, SOCK_STREAM, 0);
  1484   if (s < 0)
  1485     {
  1486       message (true, "%s: can't create socket: %s\n",
  1487                progname, strerror (errno));
  1488       fail ();
  1489     }
  1490 
  1491   if (strchr (server_name, '/')
  1492       || (ISSLASH ('\\') && strchr (server_name, '\\')))
  1493     {
  1494       socknamelen = snprintf (sockname, socknamesize, "%s", server_name);
  1495       sock_status = (0 <= socknamelen && socknamelen < socknamesize
  1496                      ? connect_socket (AT_FDCWD, sockname, s, 0)
  1497                      : ENAMETOOLONG);
  1498     }
  1499   else
  1500     {
  1501       /* socket_name is a file name component.  */
  1502       char const *xdg_runtime_dir = egetenv ("XDG_RUNTIME_DIR");
  1503       if (xdg_runtime_dir)
  1504         {
  1505           socknamelen = snprintf (sockname, socknamesize, "%s/emacs/%s",
  1506                                   xdg_runtime_dir, server_name);
  1507           sock_status = (0 <= socknamelen && socknamelen < socknamesize
  1508                          ? connect_socket (AT_FDCWD, sockname, s, 0)
  1509                          : ENAMETOOLONG);
  1510         }
  1511       else
  1512         {
  1513           char const *tmpdir = egetenv ("TMPDIR");
  1514           if (tmpdir)
  1515             tmpdirlen = snprintf (sockname, socknamesize, "%s", tmpdir);
  1516           else
  1517             {
  1518 # ifdef DARWIN_OS
  1519 #  ifndef _CS_DARWIN_USER_TEMP_DIR
  1520 #   define _CS_DARWIN_USER_TEMP_DIR 65537
  1521 #  endif
  1522               size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR,
  1523                                   sockname, socknamesize);
  1524               if (0 < n && n < (size_t) -1)
  1525                 tmpdirlen = min (n - 1, socknamesize);
  1526 # endif
  1527               if (tmpdirlen < 0)
  1528                 tmpdirlen = snprintf (sockname, socknamesize, "/tmp");
  1529             }
  1530           sock_status = local_sockname (s, sockname, tmpdirlen,
  1531                                         uid, server_name);
  1532           tmpdir_used = true;
  1533         }
  1534     }
  1535 
  1536   if (sock_status == 0)
  1537     return s;
  1538 
  1539   if (sock_status == ENAMETOOLONG)
  1540     {
  1541       message (true, "%s: socket-name %s... too long\n", progname, sockname);
  1542       fail ();
  1543     }
  1544 
  1545   if (tmpdir_used)
  1546     {
  1547       /* See whether LOGNAME or USER exist and differ from
  1548          our euid.  If so, look for a socket based on the UID
  1549          associated with the name.  This is reminiscent of the logic
  1550          that init_editfns uses to set the global Vuser_full_name.  */
  1551 
  1552       char const *user_name = egetenv ("LOGNAME");
  1553 
  1554       if (!user_name)
  1555         user_name = egetenv ("USER");
  1556 
  1557       if (user_name)
  1558         {
  1559           struct passwd *pw = getpwnam (user_name);
  1560 
  1561           if (pw && pw->pw_uid != uid)
  1562             {
  1563               /* We're running under su, apparently. */
  1564               sock_status = local_sockname (s, sockname, tmpdirlen,
  1565                                             pw->pw_uid, server_name);
  1566               if (sock_status == 0)
  1567                 return s;
  1568               if (sock_status == ENAMETOOLONG)
  1569                 {
  1570                   message (true, "%s: socket-name %s... too long\n",
  1571                            progname, sockname);
  1572                   exit (EXIT_FAILURE);
  1573                 }
  1574             }
  1575         }
  1576     }
  1577 
  1578   close (s);
  1579 
  1580   if (sock_status == -1)
  1581     message (true,
  1582              "%s: Invalid permissions on parent directory of socket: %s\n",
  1583              progname, sockname);
  1584   else if (sock_status == ENOENT)
  1585     {
  1586       if (tmpdir_used)
  1587         {
  1588           uintmax_t id = uid;
  1589           char sockdirname[socknamesize];
  1590           int sockdirnamelen = snprintf (sockdirname, sizeof sockdirname,
  1591                                          "/run/user/%"PRIuMAX, id);
  1592           if (0 <= sockdirnamelen && sockdirnamelen < sizeof sockdirname
  1593               && faccessat (AT_FDCWD, sockdirname, X_OK, AT_EACCESS) == 0)
  1594             message
  1595               (true,
  1596                ("%s: Should XDG_RUNTIME_DIR='%s' be in the environment?\n"
  1597                 "%s: (Be careful: XDG_RUNTIME_DIR is security-related.)\n"),
  1598                progname, sockdirname, progname);
  1599         }
  1600 
  1601       /* If there's an alternate editor and the user has requested
  1602          --quiet, don't output the warning. */
  1603       if (!quiet || !alternate_editor)
  1604         {
  1605           message (true,
  1606                    ("%s: can't find socket; have you started the server?\n"
  1607                     "%s: To start the server in Emacs,"
  1608                     " type \"M-x server-start\".\n"),
  1609                    progname, progname);
  1610         }
  1611     }
  1612   else
  1613     message (true, "%s: can't connect to %s: %s\n",
  1614              progname, sockname, strerror (sock_status));
  1615 
  1616   return INVALID_SOCKET;
  1617 }
  1618 #endif /* SOCKETS_IN_FILE_SYSTEM */
  1619 
  1620 static HSOCKET
  1621 set_socket (bool no_exit_if_error)
  1622 {
  1623   HSOCKET s;
  1624   const char *local_server_file = server_file;
  1625 
  1626   INITIALIZE ();
  1627 
  1628 #ifdef SOCKETS_IN_FILE_SYSTEM
  1629   if (!socket_name)
  1630     socket_name = egetenv ("EMACS_SOCKET_NAME");
  1631 
  1632   if (socket_name)
  1633     {
  1634       /* Explicit --socket-name argument, or environment variable.  */
  1635       s = set_local_socket (socket_name);
  1636       if (s != INVALID_SOCKET || no_exit_if_error)
  1637         return s;
  1638       message (true, "%s: error accessing socket \"%s\"\n",
  1639                progname, socket_name);
  1640       exit (EXIT_FAILURE);
  1641     }
  1642 #endif
  1643 
  1644   /* Explicit --server-file arg or EMACS_SERVER_FILE variable.  */
  1645   if (!local_server_file)
  1646     local_server_file = egetenv ("EMACS_SERVER_FILE");
  1647 
  1648   if (local_server_file)
  1649     {
  1650       s = set_tcp_socket (local_server_file);
  1651       if (s != INVALID_SOCKET || no_exit_if_error)
  1652         return s;
  1653 
  1654       message (true, "%s: error accessing server file \"%s\"\n",
  1655                progname, local_server_file);
  1656       exit (EXIT_FAILURE);
  1657     }
  1658 
  1659 #ifdef SOCKETS_IN_FILE_SYSTEM
  1660   /* Implicit local socket.  */
  1661   s = set_local_socket ("server");
  1662   if (s != INVALID_SOCKET)
  1663     return s;
  1664 #endif
  1665 
  1666   /* Implicit server file.  */
  1667   s = set_tcp_socket ("server");
  1668   if (s != INVALID_SOCKET || no_exit_if_error)
  1669     return s;
  1670 
  1671   /* No implicit or explicit socket, and no alternate editor.  */
  1672   message (true, "%s: No socket or alternate editor.  Please use:\n\n"
  1673 #ifdef SOCKETS_IN_FILE_SYSTEM
  1674 "\t--socket-name\n"
  1675 #endif
  1676 "\t--server-file      (or environment variable EMACS_SERVER_FILE)\n\
  1677 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
  1678            progname);
  1679   exit (EXIT_FAILURE);
  1680 }
  1681 
  1682 #ifdef HAVE_NTGUI
  1683 FARPROC set_fg;  /* Pointer to AllowSetForegroundWindow.  */
  1684 FARPROC get_wc;  /* Pointer to RealGetWindowClassA.  */
  1685 
  1686 void w32_set_user_model_id (void);
  1687 
  1688 void
  1689 w32_set_user_model_id (void)
  1690 {
  1691   HMODULE shell;
  1692   HRESULT (WINAPI * set_user_model) (const wchar_t * id);
  1693 
  1694   /* On Windows 7 and later, we need to set the user model ID
  1695      to associate emacsclient launched files with Emacs frames
  1696      in the UI.  */
  1697   shell = LoadLibrary ("shell32.dll");
  1698   if (shell)
  1699     {
  1700       set_user_model
  1701         = (void *) GetProcAddress (shell,
  1702                                    "SetCurrentProcessExplicitAppUserModelID");
  1703       /* If the function is defined, then we are running on Windows 7
  1704          or newer, and the UI uses this to group related windows
  1705          together.  Since emacs, runemacs, emacsclient are related, we
  1706          want them grouped even though the executables are different,
  1707          so we need to set a consistent ID between them.  */
  1708       if (set_user_model)
  1709         set_user_model (L"GNU.Emacs");
  1710 
  1711       FreeLibrary (shell);
  1712     }
  1713 }
  1714 
  1715 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
  1716 
  1717 BOOL CALLBACK
  1718 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
  1719 {
  1720   DWORD pid;
  1721   char class[6];
  1722 
  1723   /* Reject any window not of class "Emacs".  */
  1724   if (! get_wc (hWnd, class, sizeof (class))
  1725       || strcmp (class, "Emacs"))
  1726     return TRUE;
  1727 
  1728   /* We only need the process id, not the thread id.  */
  1729   (void) GetWindowThreadProcessId (hWnd, &pid);
  1730 
  1731   /* Not the one we're looking for.  */
  1732   if (pid != (DWORD) emacs_pid) return TRUE;
  1733 
  1734   /* OK, let's raise it.  */
  1735   set_fg (emacs_pid);
  1736 
  1737   /* Stop enumeration.  */
  1738   return FALSE;
  1739 }
  1740 
  1741 /* Search for a window of class "Emacs" and owned by a process with
  1742    process id = emacs_pid.  If found, allow it to grab the focus.  */
  1743 void w32_give_focus (void);
  1744 
  1745 void
  1746 w32_give_focus (void)
  1747 {
  1748   HANDLE user32;
  1749 
  1750   /* It shouldn't happen when dealing with TCP sockets.  */
  1751   if (!emacs_pid) return;
  1752 
  1753   user32 = GetModuleHandle ("user32.dll");
  1754 
  1755   if (!user32)
  1756     return;
  1757 
  1758   /* Modern Windows restrict which processes can set the foreground window.
  1759      emacsclient can allow Emacs to grab the focus by calling the function
  1760      AllowSetForegroundWindow.  Unfortunately, older Windows (W95, W98 and
  1761      NT) lack this function, so we have to check its availability.  */
  1762   if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
  1763       && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
  1764     EnumWindows (w32_find_emacs_process, (LPARAM) 0);
  1765 }
  1766 #endif /* HAVE_NTGUI */
  1767 
  1768 /* Start the emacs daemon and try to connect to it.  */
  1769 
  1770 static HSOCKET
  1771 start_daemon_and_retry_set_socket (void)
  1772 {
  1773 #ifndef WINDOWSNT
  1774   pid_t dpid;
  1775   int status;
  1776 
  1777   dpid = fork ();
  1778 
  1779   if (dpid > 0)
  1780     {
  1781       pid_t w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
  1782 
  1783       if (w < 0 || !WIFEXITED (status) || WEXITSTATUS (status))
  1784         {
  1785           message (true, "Error: Could not start the Emacs daemon\n");
  1786           exit (EXIT_FAILURE);
  1787         }
  1788 
  1789       /* Try connecting, the daemon should have started by now.  */
  1790       if (!quiet)
  1791         message (true,
  1792                  "Emacs daemon should have started, trying to connect again\n");
  1793     }
  1794   else if (dpid < 0)
  1795     {
  1796       fprintf (stderr, "Error: Cannot fork!\n");
  1797       exit (EXIT_FAILURE);
  1798     }
  1799   else
  1800     {
  1801       char emacs[] = "emacs";
  1802       char daemon_option[] = "--daemon";
  1803       char *d_argv[3];
  1804       d_argv[0] = emacs;
  1805       d_argv[1] = daemon_option;
  1806       d_argv[2] = 0;
  1807 # ifdef SOCKETS_IN_FILE_SYSTEM
  1808       if (socket_name != NULL)
  1809         {
  1810           /* Pass  --daemon=socket_name as argument.  */
  1811           const char *deq = "--daemon=";
  1812           char *daemon_arg = xmalloc (strlen (deq)
  1813                                       + strlen (socket_name) + 1);
  1814           strcpy (stpcpy (daemon_arg, deq), socket_name);
  1815           d_argv[1] = daemon_arg;
  1816         }
  1817 # endif
  1818       execvp ("emacs", d_argv);
  1819       message (true, "%s: error starting emacs daemon\n", progname);
  1820       exit (EXIT_FAILURE);
  1821     }
  1822 #else  /* WINDOWSNT */
  1823   DWORD wait_result;
  1824   HANDLE w32_daemon_event;
  1825   STARTUPINFO si;
  1826   PROCESS_INFORMATION pi;
  1827 
  1828   ZeroMemory (&si, sizeof si);
  1829   si.cb = sizeof si;
  1830   ZeroMemory (&pi, sizeof pi);
  1831 
  1832   /* We start Emacs in daemon mode, and then wait for it to signal us
  1833      it is ready to accept client connections, by asserting an event
  1834      whose name is known to the daemon (defined by nt/inc/ms-w32.h).  */
  1835 
  1836   if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
  1837                       CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
  1838     {
  1839       char* msg = NULL;
  1840 
  1841       FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  1842                      | FORMAT_MESSAGE_ALLOCATE_BUFFER
  1843                      | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1844                      NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
  1845       message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
  1846       exit (EXIT_FAILURE);
  1847     }
  1848 
  1849   w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
  1850   if (w32_daemon_event == NULL)
  1851     {
  1852       message (true, "Couldn't create Windows daemon event");
  1853       exit (EXIT_FAILURE);
  1854     }
  1855   if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
  1856       != WAIT_OBJECT_0)
  1857     {
  1858       const char *msg = NULL;
  1859 
  1860       switch (wait_result)
  1861         {
  1862         case WAIT_ABANDONED:
  1863           msg = "The daemon exited unexpectedly";
  1864           break;
  1865         case WAIT_TIMEOUT:
  1866           /* Can't happen due to INFINITE.  */
  1867         default:
  1868         case WAIT_FAILED:
  1869           FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  1870                          | FORMAT_MESSAGE_ALLOCATE_BUFFER
  1871                          | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1872                          NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
  1873           break;
  1874         }
  1875       message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
  1876       exit (EXIT_FAILURE);
  1877     }
  1878   CloseHandle (w32_daemon_event);
  1879 
  1880   /* Try connecting, the daemon should have started by now.  */
  1881   /* It's just a progress message, so don't pop a dialog if this is
  1882      emacsclientw.  */
  1883   if (!quiet && !w32_window_app ())
  1884     message (true,
  1885              "Emacs daemon should have started, trying to connect again\n");
  1886 #endif /* WINDOWSNT */
  1887 
  1888   HSOCKET emacs_socket = set_socket (true);
  1889   if (emacs_socket == INVALID_SOCKET)
  1890     {
  1891       message (true,
  1892                "Error: Cannot connect even after starting the Emacs daemon\n");
  1893       exit (EXIT_FAILURE);
  1894     }
  1895   return emacs_socket;
  1896 }
  1897 
  1898 static void
  1899 set_socket_timeout (HSOCKET socket, int seconds)
  1900 {
  1901   int ret;
  1902 
  1903 #ifndef WINDOWSNT
  1904   struct timeval timeout;
  1905   timeout.tv_sec = seconds;
  1906   timeout.tv_usec = 0;
  1907   ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
  1908 #else
  1909   DWORD timeout;
  1910 
  1911   if (seconds > INT_MAX / 1000)
  1912     timeout = INT_MAX;
  1913   else
  1914     timeout = seconds * 1000;
  1915   ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof timeout);
  1916 #endif
  1917 
  1918   if (ret < 0)
  1919     sock_err_message ("setsockopt");
  1920 }
  1921 
  1922 static bool
  1923 check_socket_timeout (int rl)
  1924 {
  1925 #ifndef WINDOWSNT
  1926   return (rl == -1)
  1927     && (errno == EAGAIN)
  1928     && (errno == EWOULDBLOCK);
  1929 #else
  1930   return (rl == SOCKET_ERROR)
  1931     && (WSAGetLastError() == WSAETIMEDOUT);
  1932 #endif
  1933 }
  1934 
  1935 int
  1936 main (int argc, char **argv)
  1937 {
  1938   main_argc = argc;
  1939   main_argv = argv;
  1940   progname = argv[0] ? argv[0] : "emacsclient";
  1941 
  1942   int rl = 0;
  1943   bool skiplf = true;
  1944   char string[BUFSIZ + 1];
  1945   int exit_status = EXIT_SUCCESS;
  1946 
  1947 #ifdef HAVE_NTGUI
  1948   /* On Windows 7 and later, we need to explicitly associate
  1949      emacsclient with emacs so the UI behaves sensibly.  This
  1950      association does no harm if we're not actually connecting to an
  1951      Emacs using a window display.  */
  1952   w32_set_user_model_id ();
  1953 #endif
  1954 
  1955   /* Process options.  */
  1956   decode_options (argc, argv);
  1957 
  1958   if (! (optind < argc || eval || create_frame))
  1959     {
  1960       message (true, ("%s: file name or argument required\n"
  1961                       "Try '%s --help' for more information\n"),
  1962                progname, progname);
  1963       exit (EXIT_FAILURE);
  1964     }
  1965 
  1966 #ifdef SOCKETS_IN_FILE_SYSTEM
  1967   if (tty)
  1968     {
  1969       pid_t grouping = process_grouping ();
  1970       if (grouping < 0)
  1971         kill (grouping, SIGTTIN);
  1972     }
  1973 #endif
  1974 
  1975   /* If alternate_editor is the empty string, start the emacs daemon
  1976      in case of failure to connect.  */
  1977   bool start_daemon_if_needed = alternate_editor && !alternate_editor[0];
  1978 
  1979   HSOCKET emacs_socket = set_socket (alternate_editor
  1980                                      || start_daemon_if_needed);
  1981   if (emacs_socket == INVALID_SOCKET)
  1982     {
  1983       if (! start_daemon_if_needed)
  1984         fail ();
  1985 
  1986       emacs_socket = start_daemon_and_retry_set_socket ();
  1987     }
  1988 
  1989   char *cwd = get_current_dir_name ();
  1990   if (cwd == 0)
  1991     {
  1992       message (true, "%s: %s\n", progname,
  1993                "Cannot get current working directory");
  1994       fail ();
  1995     }
  1996 
  1997 #ifdef HAVE_NTGUI
  1998   if (display && !strcmp (display, "w32"))
  1999   w32_give_focus ();
  2000 #endif
  2001 
  2002   /* Send over our environment and current directory. */
  2003   if (create_frame)
  2004     {
  2005       for (char *const *e = environ; *e; e++)
  2006         {
  2007           send_to_emacs (emacs_socket, "-env ");
  2008           quote_argument (emacs_socket, *e);
  2009           send_to_emacs (emacs_socket, " ");
  2010         }
  2011     }
  2012   send_to_emacs (emacs_socket, "-dir ");
  2013   if (tramp_prefix)
  2014     quote_argument (emacs_socket, tramp_prefix);
  2015   quote_argument (emacs_socket, cwd);
  2016   free (cwd);
  2017   send_to_emacs (emacs_socket, "/");
  2018   send_to_emacs (emacs_socket, " ");
  2019 
  2020  retry:
  2021   if (nowait)
  2022     send_to_emacs (emacs_socket, "-nowait ");
  2023 
  2024   if (!create_frame || reuse_frame)
  2025     send_to_emacs (emacs_socket, "-current-frame ");
  2026 
  2027   if (display)
  2028     {
  2029       send_to_emacs (emacs_socket, "-display ");
  2030       quote_argument (emacs_socket, display);
  2031       send_to_emacs (emacs_socket, " ");
  2032     }
  2033 
  2034   if (parent_id)
  2035     {
  2036       send_to_emacs (emacs_socket, "-parent-id ");
  2037       quote_argument (emacs_socket, parent_id);
  2038       send_to_emacs (emacs_socket, " ");
  2039     }
  2040 
  2041   if (frame_parameters && create_frame)
  2042     {
  2043       send_to_emacs (emacs_socket, "-frame-parameters ");
  2044       quote_argument (emacs_socket, frame_parameters);
  2045       send_to_emacs (emacs_socket, " ");
  2046     }
  2047 
  2048   /* Unless we are certain we don't want to occupy the tty, send our
  2049      tty information to Emacs.  For example, in daemon mode Emacs may
  2050      need to occupy this tty if no other frame is available.  */
  2051   if (create_frame || !eval)
  2052     {
  2053       const char *tty_type, *tty_name;
  2054 
  2055       if (find_tty (&tty_type, &tty_name, !tty))
  2056         {
  2057           /* Install signal handlers before opening a frame on the
  2058              current tty.  */
  2059           init_signals ();
  2060 
  2061           send_to_emacs (emacs_socket, "-tty ");
  2062           quote_argument (emacs_socket, tty_name);
  2063           send_to_emacs (emacs_socket, " ");
  2064           quote_argument (emacs_socket, tty_type);
  2065           send_to_emacs (emacs_socket, " ");
  2066         }
  2067     }
  2068 
  2069   if (create_frame && !tty)
  2070     send_to_emacs (emacs_socket, "-window-system ");
  2071 
  2072   if (optind < argc)
  2073     {
  2074       for (int i = optind; i < argc; i++)
  2075         {
  2076 
  2077           if (eval)
  2078             {
  2079               /* Don't prepend cwd or anything like that.  */
  2080               send_to_emacs (emacs_socket, "-eval ");
  2081               quote_argument (emacs_socket, argv[i]);
  2082               send_to_emacs (emacs_socket, " ");
  2083               continue;
  2084             }
  2085 
  2086           char *p = argv[i];
  2087           if (*p == '+')
  2088             {
  2089               unsigned char c;
  2090               do
  2091                 c = *++p;
  2092               while (isdigit (c) || c == ':');
  2093 
  2094               if (c == 0)
  2095                 {
  2096                   send_to_emacs (emacs_socket, "-position ");
  2097                   quote_argument (emacs_socket, argv[i]);
  2098                   send_to_emacs (emacs_socket, " ");
  2099                   continue;
  2100                 }
  2101             }
  2102 #ifdef WINDOWSNT
  2103           else if (! IS_ABSOLUTE_FILE_NAME (argv[i])
  2104                    && (isalpha (argv[i][0]) && argv[i][1] == ':'))
  2105             /* Windows can have a different default directory for each
  2106                drive, so the cwd passed via "-dir" is not sufficient
  2107                to account for that.
  2108                If the user uses <drive>:<relpath>, we hence need to be
  2109                careful to expand <relpath> with the default directory
  2110                corresponding to <drive>.  */
  2111             {
  2112               char *filename = xmalloc (MAX_PATH);
  2113               DWORD size;
  2114 
  2115               size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
  2116               if (size > 0 && size < MAX_PATH)
  2117                 argv[i] = filename;
  2118               else
  2119                 free (filename);
  2120             }
  2121 #endif
  2122 
  2123           send_to_emacs (emacs_socket, "-file ");
  2124           if (tramp_prefix && IS_ABSOLUTE_FILE_NAME (argv[i]))
  2125             quote_argument (emacs_socket, tramp_prefix);
  2126           quote_argument (emacs_socket, argv[i]);
  2127           send_to_emacs (emacs_socket, " ");
  2128         }
  2129     }
  2130   else if (eval)
  2131     {
  2132       /* Read expressions interactively.  */
  2133       while (fgets (string, BUFSIZ, stdin))
  2134         {
  2135           send_to_emacs (emacs_socket, "-eval ");
  2136           quote_argument (emacs_socket, string);
  2137         }
  2138       send_to_emacs (emacs_socket, " ");
  2139     }
  2140 
  2141   send_to_emacs (emacs_socket, "\n");
  2142 
  2143   /* Wait for an answer. */
  2144   if (!eval && !tty && !nowait && !quiet && 0 <= process_grouping ())
  2145     {
  2146       printf ("Waiting for Emacs...");
  2147       skiplf = false;
  2148     }
  2149   fflush (stdout);
  2150 
  2151   set_socket_timeout (emacs_socket, timeout > 0 ? timeout : DEFAULT_TIMEOUT);
  2152   bool saw_response = false;
  2153   /* Now, wait for an answer and print any messages.  */
  2154   while (exit_status == EXIT_SUCCESS)
  2155     {
  2156       bool retry = true;
  2157       bool msg_showed = quiet;
  2158       do
  2159         {
  2160           act_on_signals (emacs_socket);
  2161           rl = recv (emacs_socket, string, BUFSIZ, 0);
  2162           retry = check_socket_timeout (rl);
  2163           if (retry && !saw_response)
  2164             {
  2165               if (timeout > 0)
  2166                 {
  2167                   /* Don't retry if we were given a --timeout flag.  */
  2168                   fprintf (stderr, "\nServer not responding; timed out after %ju seconds",
  2169                            timeout);
  2170                   retry = false;
  2171                 }
  2172               else if (!msg_showed)
  2173                 {
  2174                   msg_showed = true;
  2175                   fprintf (stderr, "\nServer not responding; use Ctrl+C to break");
  2176                 }
  2177             }
  2178         }
  2179       while ((rl < 0 && errno == EINTR) || retry);
  2180 
  2181       if (rl <= 0)
  2182         break;
  2183 
  2184       saw_response = true;
  2185       string[rl] = '\0';
  2186 
  2187       /* Loop over all NL-terminated messages.  */
  2188       char *p = string;
  2189       for (char *end_p = p; end_p && *end_p != '\0'; p = end_p)
  2190         {
  2191           end_p = strchr (p, '\n');
  2192           if (end_p != NULL)
  2193             *end_p++ = '\0';
  2194 
  2195           if (strprefix ("-emacs-pid ", p))
  2196             {
  2197               /* -emacs-pid PID: The process id of the Emacs process. */
  2198               emacs_pid = strtoumax (p + strlen ("-emacs-pid"), NULL, 10);
  2199             }
  2200           else if (strprefix ("-window-system-unsupported ", p))
  2201             {
  2202               /* -window-system-unsupported: Emacs was compiled without support
  2203                  for whatever window system we tried.  Try the alternate
  2204                  display, or, failing that, try the terminal.  */
  2205               if (alt_display)
  2206                 {
  2207                   display = alt_display;
  2208                   alt_display = NULL;
  2209                 }
  2210               else
  2211                 {
  2212                   nowait = false;
  2213                   tty = true;
  2214                 }
  2215 
  2216               goto retry;
  2217             }
  2218           else if (strprefix ("-print ", p))
  2219             {
  2220               /* -print STRING: Print STRING on the terminal. */
  2221               if (!suppress_output)
  2222                 {
  2223                   char *str = unquote_argument (p + strlen ("-print "));
  2224                   printf (&"\n%s"[skiplf], str);
  2225                   if (str[0])
  2226                     skiplf = str[strlen (str) - 1] == '\n';
  2227                 }
  2228             }
  2229           else if (strprefix ("-print-nonl ", p))
  2230             {
  2231               /* -print-nonl STRING: Print STRING on the terminal.
  2232                  Used to continue a preceding -print command.  */
  2233               if (!suppress_output)
  2234                 {
  2235                   char *str = unquote_argument (p + strlen ("-print-nonl "));
  2236                   printf ("%s", str);
  2237                   if (str[0])
  2238                     skiplf = str[strlen (str) - 1] == '\n';
  2239                 }
  2240             }
  2241           else if (strprefix ("-error ", p))
  2242             {
  2243               /* -error DESCRIPTION: Signal an error on the terminal. */
  2244               char *str = unquote_argument (p + strlen ("-error "));
  2245               if (!skiplf)
  2246                 printf ("\n");
  2247               message (true, "*ERROR*: %s", str);
  2248               if (str[0])
  2249                 skiplf = str[strlen (str) - 1] == '\n';
  2250               exit_status = EXIT_FAILURE;
  2251             }
  2252 #ifndef WINDOWSNT
  2253           else if (strprefix ("-suspend ", p))
  2254             {
  2255               /* -suspend: Suspend this terminal, i.e., stop the process. */
  2256               if (!skiplf)
  2257                 printf ("\n");
  2258               skiplf = true;
  2259               kill (0, SIGSTOP);
  2260             }
  2261 #endif
  2262           else
  2263             {
  2264               /* Unknown command. */
  2265               printf (&"\n*ERROR*: Unknown message: %s\n"[skiplf], p);
  2266               skiplf = true;
  2267             }
  2268         }
  2269     }
  2270 
  2271   if (!skiplf && 0 <= process_grouping ())
  2272     printf ("\n");
  2273 
  2274   if (rl < 0)
  2275     exit_status = EXIT_FAILURE;
  2276 
  2277   CLOSE_SOCKET (emacs_socket);
  2278   return exit_status;
  2279 }

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