emacsclient.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  1. /* Client process that communicates with GNU Emacs acting as server.
  2. Copyright (C) 1986-1987, 1994, 1999-2016 Free Software Foundation, Inc.
  3. This file is part of GNU Emacs.
  4. GNU Emacs is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or (at
  7. your option) any later version.
  8. GNU Emacs is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. #ifdef WINDOWSNT
  16. /* ms-w32.h defines these, which disables sockets altogether! */
  17. # undef _WINSOCKAPI_
  18. # undef _WINSOCK_H
  19. # include <malloc.h>
  20. # include <stdlib.h>
  21. # include <windows.h>
  22. # include <commctrl.h>
  23. # include <io.h>
  24. # include <winsock2.h>
  25. # define NO_SOCKETS_IN_FILE_SYSTEM
  26. # define HSOCKET SOCKET
  27. # define CLOSE_SOCKET closesocket
  28. # define INITIALIZE() (initialize_sockets ())
  29. char *w32_getenv (const char *);
  30. #define egetenv(VAR) w32_getenv(VAR)
  31. #else /* !WINDOWSNT */
  32. # ifdef HAVE_NTGUI
  33. # include <windows.h>
  34. # endif /* HAVE_NTGUI */
  35. # include "syswait.h"
  36. # ifdef HAVE_INET_SOCKETS
  37. # include <netinet/in.h>
  38. # ifdef HAVE_SOCKETS
  39. # include <sys/types.h>
  40. # include <sys/socket.h>
  41. # include <sys/un.h>
  42. # endif /* HAVE_SOCKETS */
  43. # endif
  44. # include <arpa/inet.h>
  45. # define INVALID_SOCKET -1
  46. # define HSOCKET int
  47. # define CLOSE_SOCKET close
  48. # define INITIALIZE()
  49. #define egetenv(VAR) getenv(VAR)
  50. #endif /* !WINDOWSNT */
  51. #undef signal
  52. #include <stdarg.h>
  53. #include <ctype.h>
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <getopt.h>
  58. #include <unistd.h>
  59. #include <pwd.h>
  60. #include <sys/stat.h>
  61. #include <signal.h>
  62. #include <errno.h>
  63. #ifndef VERSION
  64. #define VERSION "unspecified"
  65. #endif
  66. #ifndef EXIT_SUCCESS
  67. #define EXIT_SUCCESS 0
  68. #endif
  69. #ifndef EXIT_FAILURE
  70. #define EXIT_FAILURE 1
  71. #endif
  72. /* Additional space when allocating buffers for filenames, etc. */
  73. #define EXTRA_SPACE 100
  74. #ifdef min
  75. #undef min
  76. #endif
  77. #define min(x, y) (((x) < (y)) ? (x) : (y))
  78. /* Name used to invoke this program. */
  79. const char *progname;
  80. /* The second argument to main. */
  81. char **main_argv;
  82. /* Nonzero means don't wait for a response from Emacs. --no-wait. */
  83. int nowait = 0;
  84. /* Nonzero means don't print messages for successful operations. --quiet. */
  85. int quiet = 0;
  86. /* Nonzero means args are expressions to be evaluated. --eval. */
  87. int eval = 0;
  88. /* Nonzero means don't open a new frame. Inverse of --create-frame. */
  89. int current_frame = 1;
  90. /* The display on which Emacs should work. --display. */
  91. const char *display = NULL;
  92. /* The alternate display we should try if Emacs does not support display. */
  93. const char *alt_display = NULL;
  94. /* The parent window ID, if we are opening a frame via XEmbed. */
  95. char *parent_id = NULL;
  96. /* Nonzero means open a new Emacs frame on the current terminal. */
  97. int tty = 0;
  98. /* If non-NULL, the name of an editor to fallback to if the server
  99. is not running. --alternate-editor. */
  100. const char *alternate_editor = NULL;
  101. /* If non-NULL, the filename of the UNIX socket. */
  102. const char *socket_name = NULL;
  103. /* If non-NULL, the filename of the authentication file. */
  104. const char *server_file = NULL;
  105. /* PID of the Emacs server process. */
  106. int emacs_pid = 0;
  107. /* If non-NULL, a string that should form a frame parameter alist to
  108. be used for the new frame. */
  109. const char *frame_parameters = NULL;
  110. static _Noreturn void print_help_and_exit (void);
  111. struct option longopts[] =
  112. {
  113. { "no-wait", no_argument, NULL, 'n' },
  114. { "quiet", no_argument, NULL, 'q' },
  115. { "eval", no_argument, NULL, 'e' },
  116. { "help", no_argument, NULL, 'H' },
  117. { "version", no_argument, NULL, 'V' },
  118. { "tty", no_argument, NULL, 't' },
  119. { "nw", no_argument, NULL, 't' },
  120. { "create-frame", no_argument, NULL, 'c' },
  121. { "alternate-editor", required_argument, NULL, 'a' },
  122. { "frame-parameters", required_argument, NULL, 'F' },
  123. #ifndef NO_SOCKETS_IN_FILE_SYSTEM
  124. { "socket-name", required_argument, NULL, 's' },
  125. #endif
  126. { "server-file", required_argument, NULL, 'f' },
  127. { "display", required_argument, NULL, 'd' },
  128. { "parent-id", required_argument, NULL, 'p' },
  129. { 0, 0, 0, 0 }
  130. };
  131. /* Like malloc but get fatal error if memory is exhausted. */
  132. static void *
  133. xmalloc (size_t size)
  134. {
  135. void *result = malloc (size);
  136. if (result == NULL)
  137. {
  138. perror ("malloc");
  139. exit (EXIT_FAILURE);
  140. }
  141. return result;
  142. }
  143. /* From sysdep.c */
  144. #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
  145. char *get_current_dir_name (void);
  146. /* Return the current working directory. Returns NULL on errors.
  147. Any other returned value must be freed with free. This is used
  148. only when get_current_dir_name is not defined on the system. */
  149. char*
  150. get_current_dir_name (void)
  151. {
  152. char *buf;
  153. const char *pwd;
  154. struct stat dotstat, pwdstat;
  155. /* If PWD is accurate, use it instead of calling getcwd. PWD is
  156. sometimes a nicer name, and using it may avoid a fatal error if a
  157. parent directory is searchable but not readable. */
  158. if ((pwd = egetenv ("PWD")) != 0
  159. && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
  160. && stat (pwd, &pwdstat) == 0
  161. && stat (".", &dotstat) == 0
  162. && dotstat.st_ino == pwdstat.st_ino
  163. && dotstat.st_dev == pwdstat.st_dev
  164. #ifdef MAXPATHLEN
  165. && strlen (pwd) < MAXPATHLEN
  166. #endif
  167. )
  168. {
  169. buf = (char *) xmalloc (strlen (pwd) + 1);
  170. strcpy (buf, pwd);
  171. }
  172. else
  173. {
  174. size_t buf_size = 1024;
  175. for (;;)
  176. {
  177. int tmp_errno;
  178. buf = malloc (buf_size);
  179. if (! buf)
  180. break;
  181. if (getcwd (buf, buf_size) == buf)
  182. break;
  183. tmp_errno = errno;
  184. free (buf);
  185. if (tmp_errno != ERANGE)
  186. {
  187. errno = tmp_errno;
  188. return NULL;
  189. }
  190. buf_size *= 2;
  191. if (! buf_size)
  192. {
  193. errno = ENOMEM;
  194. return NULL;
  195. }
  196. }
  197. }
  198. return buf;
  199. }
  200. #endif
  201. #ifdef WINDOWSNT
  202. /* Like strdup but get a fatal error if memory is exhausted. */
  203. char *xstrdup (const char *);
  204. char *
  205. xstrdup (const char *s)
  206. {
  207. char *result = strdup (s);
  208. if (result == NULL)
  209. {
  210. perror ("strdup");
  211. exit (EXIT_FAILURE);
  212. }
  213. return result;
  214. }
  215. #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
  216. char *w32_get_resource (HKEY, const char *, LPDWORD);
  217. /* Retrieve an environment variable from the Emacs subkeys of the registry.
  218. Return NULL if the variable was not found, or it was empty.
  219. This code is based on w32_get_resource (w32.c). */
  220. char *
  221. w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
  222. {
  223. HKEY hrootkey = NULL;
  224. char *result = NULL;
  225. DWORD cbData;
  226. if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
  227. {
  228. if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
  229. {
  230. result = (char *) xmalloc (cbData);
  231. if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE)result, &cbData) != ERROR_SUCCESS)
  232. || (*result == 0))
  233. {
  234. free (result);
  235. result = NULL;
  236. }
  237. }
  238. RegCloseKey (hrootkey);
  239. }
  240. return result;
  241. }
  242. /*
  243. getenv wrapper for Windows
  244. Value is allocated on the heap, and can be free'd.
  245. This is needed to duplicate Emacs's behavior, which is to look for
  246. environment variables in the registry if they don't appear in the
  247. environment. */
  248. char *
  249. w32_getenv (const char *envvar)
  250. {
  251. char *value;
  252. DWORD dwType;
  253. if ((value = getenv (envvar)))
  254. /* Found in the environment. strdup it, because values returned
  255. by getenv cannot be free'd. */
  256. return xstrdup (value);
  257. if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
  258. ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
  259. {
  260. /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
  261. if (strcmp (envvar, "TERM") == 0)
  262. return xstrdup ("w32console");
  263. /* Found neither in the environment nor in the registry. */
  264. return NULL;
  265. }
  266. if (dwType == REG_SZ)
  267. /* Registry; no need to expand. */
  268. return value;
  269. if (dwType == REG_EXPAND_SZ)
  270. {
  271. DWORD size;
  272. if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
  273. {
  274. char *buffer = (char *) xmalloc (size);
  275. if (ExpandEnvironmentStrings (value, buffer, size))
  276. {
  277. /* Found and expanded. */
  278. free (value);
  279. return buffer;
  280. }
  281. /* Error expanding. */
  282. free (buffer);
  283. }
  284. }
  285. /* Not the right type, or not correctly expanded. */
  286. free (value);
  287. return NULL;
  288. }
  289. int w32_window_app (void);
  290. int
  291. w32_window_app (void)
  292. {
  293. static int window_app = -1;
  294. char szTitle[MAX_PATH];
  295. if (window_app < 0)
  296. {
  297. /* Checking for STDOUT does not work; it's a valid handle also in
  298. nonconsole apps. Testing for the console title seems to work. */
  299. window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
  300. if (window_app)
  301. InitCommonControls ();
  302. }
  303. return window_app;
  304. }
  305. /* execvp wrapper for Windows. Quotes arguments with embedded spaces.
  306. This is necessary due to the broken implementation of exec* routines in
  307. the Microsoft libraries: they concatenate the arguments together without
  308. quoting special characters, and pass the result to CreateProcess, with
  309. predictably bad results. By contrast, POSIX execvp passes the arguments
  310. directly into the argv array of the child process. */
  311. int w32_execvp (const char *, char **);
  312. int
  313. w32_execvp (const char *path, char **argv)
  314. {
  315. int i;
  316. /* Required to allow a .BAT script as alternate editor. */
  317. argv[0] = (char *) alternate_editor;
  318. for (i = 0; argv[i]; i++)
  319. if (strchr (argv[i], ' '))
  320. {
  321. char *quoted = alloca (strlen (argv[i]) + 3);
  322. sprintf (quoted, "\"%s\"", argv[i]);
  323. argv[i] = quoted;
  324. }
  325. return execvp (path, argv);
  326. }
  327. #undef execvp
  328. #define execvp w32_execvp
  329. /* Emulation of ttyname for Windows. */
  330. const char *ttyname (int);
  331. const char *
  332. ttyname (int fd)
  333. {
  334. return "CONOUT$";
  335. }
  336. #endif /* WINDOWSNT */
  337. /* Display a normal or error message.
  338. On Windows, use a message box if compiled as a Windows app. */
  339. static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
  340. static void
  341. message (bool is_error, const char *format, ...)
  342. {
  343. va_list args;
  344. va_start (args, format);
  345. #ifdef WINDOWSNT
  346. if (w32_window_app ())
  347. {
  348. char msg[2048];
  349. vsnprintf (msg, sizeof msg, format, args);
  350. msg[sizeof msg - 1] = '\0';
  351. if (is_error)
  352. MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
  353. else
  354. MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
  355. }
  356. else
  357. #endif
  358. {
  359. FILE *f = is_error ? stderr : stdout;
  360. vfprintf (f, format, args);
  361. fflush (f);
  362. }
  363. va_end (args);
  364. }
  365. /* Decode the options from argv and argc.
  366. The global variable `optind' will say how many arguments we used up. */
  367. static void
  368. decode_options (int argc, char **argv)
  369. {
  370. alternate_editor = egetenv ("ALTERNATE_EDITOR");
  371. while (1)
  372. {
  373. int opt = getopt_long_only (argc, argv,
  374. #ifndef NO_SOCKETS_IN_FILE_SYSTEM
  375. "VHneqa:s:f:d:F:tc",
  376. #else
  377. "VHneqa:f:d:F:tc",
  378. #endif
  379. longopts, 0);
  380. if (opt == EOF)
  381. break;
  382. switch (opt)
  383. {
  384. case 0:
  385. /* If getopt returns 0, then it has already processed a
  386. long-named option. We should do nothing. */
  387. break;
  388. case 'a':
  389. alternate_editor = optarg;
  390. break;
  391. #ifndef NO_SOCKETS_IN_FILE_SYSTEM
  392. case 's':
  393. socket_name = optarg;
  394. break;
  395. #endif
  396. case 'f':
  397. server_file = optarg;
  398. break;
  399. /* We used to disallow this argument in w32, but it seems better
  400. to allow it, for the occasional case where the user is
  401. connecting with a w32 client to a server compiled with X11
  402. support. */
  403. case 'd':
  404. display = optarg;
  405. break;
  406. case 'n':
  407. nowait = 1;
  408. break;
  409. case 'e':
  410. eval = 1;
  411. break;
  412. case 'q':
  413. quiet = 1;
  414. break;
  415. case 'V':
  416. message (false, "emacsclient %s\n", VERSION);
  417. exit (EXIT_SUCCESS);
  418. break;
  419. case 't':
  420. tty = 1;
  421. current_frame = 0;
  422. break;
  423. case 'c':
  424. current_frame = 0;
  425. break;
  426. case 'p':
  427. parent_id = optarg;
  428. current_frame = 0;
  429. break;
  430. case 'H':
  431. print_help_and_exit ();
  432. break;
  433. case 'F':
  434. frame_parameters = optarg;
  435. break;
  436. default:
  437. message (true, "Try '%s --help' for more information\n", progname);
  438. exit (EXIT_FAILURE);
  439. break;
  440. }
  441. }
  442. /* If the -c option is used (without -t) and no --display argument
  443. is provided, try $DISPLAY.
  444. Without the -c option, we used to set `display' to $DISPLAY by
  445. default, but this changed the default behavior and is sometimes
  446. inconvenient. So we force users to use "--display $DISPLAY" if
  447. they want Emacs to connect to their current display.
  448. Some window systems have a notion of default display not
  449. reflected in the DISPLAY variable. If the user didn't give us an
  450. explicit display, try this platform-specific after trying the
  451. display in DISPLAY (if any). */
  452. if (!current_frame && !tty && !display)
  453. {
  454. /* Set these here so we use a default_display only when the user
  455. didn't give us an explicit display. */
  456. #if defined (NS_IMPL_COCOA)
  457. alt_display = "ns";
  458. #elif defined (HAVE_NTGUI)
  459. alt_display = "w32";
  460. #endif
  461. display = egetenv ("DISPLAY");
  462. }
  463. if (!display)
  464. {
  465. display = alt_display;
  466. alt_display = NULL;
  467. }
  468. /* A null-string display is invalid. */
  469. if (display && strlen (display) == 0)
  470. display = NULL;
  471. /* If no display is available, new frames are tty frames. */
  472. if (!current_frame && !display)
  473. tty = 1;
  474. #ifdef WINDOWSNT
  475. /* Emacs on Windows does not support graphical and text terminal
  476. frames in the same instance. So, treat the -t and -c options as
  477. equivalent, and open a new frame on the server's terminal.
  478. Ideally, we would only set tty = 1 when the serve is running in a
  479. console, but alas we don't know that. As a workaround, always
  480. ask for a tty frame, and let server.el figure it out. */
  481. if (!current_frame)
  482. {
  483. display = NULL;
  484. tty = 1;
  485. }
  486. #endif /* WINDOWSNT */
  487. }
  488. static _Noreturn void
  489. print_help_and_exit (void)
  490. {
  491. /* Spaces and tabs are significant in this message; they're chosen so the
  492. message aligns properly both in a tty and in a Windows message box.
  493. Please try to preserve them; otherwise the output is very hard to read
  494. when using emacsclientw. */
  495. message (false,
  496. "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
  497. Tell the Emacs server to visit the specified files.\n\
  498. Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
  499. \n\
  500. The following OPTIONS are accepted:\n\
  501. -V, --version Just print version info and return\n\
  502. -H, --help Print this usage information message\n\
  503. -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
  504. -c, --create-frame Create a new frame instead of trying to\n\
  505. use the current Emacs frame\n\
  506. ", "\
  507. -F ALIST, --frame-parameters=ALIST\n\
  508. Set the parameters of a new frame\n\
  509. -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
  510. -n, --no-wait Don't wait for the server to return\n\
  511. -q, --quiet Don't display messages on success\n\
  512. -d DISPLAY, --display=DISPLAY\n\
  513. Visit the file in the given display\n\
  514. ", "\
  515. --parent-id=ID Open in parent window ID, via XEmbed\n"
  516. #ifndef NO_SOCKETS_IN_FILE_SYSTEM
  517. "-s SOCKET, --socket-name=SOCKET\n\
  518. Set filename of the UNIX socket for communication\n"
  519. #endif
  520. "-f SERVER, --server-file=SERVER\n\
  521. Set filename of the TCP authentication file\n\
  522. -a EDITOR, --alternate-editor=EDITOR\n\
  523. Editor to fallback to if the server is not running\n"
  524. " If EDITOR is the empty string, start Emacs in daemon\n\
  525. mode and try connecting again\n"
  526. "\n\
  527. Report bugs with M-x report-emacs-bug.\n");
  528. exit (EXIT_SUCCESS);
  529. }
  530. /* Try to run a different command, or --if no alternate editor is
  531. defined-- exit with an errorcode.
  532. Uses argv, but gets it from the global variable main_argv. */
  533. static _Noreturn void
  534. fail (void)
  535. {
  536. if (alternate_editor)
  537. {
  538. int i = optind - 1;
  539. execvp (alternate_editor, main_argv + i);
  540. message (true, "%s: error executing alternate editor \"%s\"\n",
  541. progname, alternate_editor);
  542. }
  543. exit (EXIT_FAILURE);
  544. }
  545. #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
  546. int
  547. main (int argc, char **argv)
  548. {
  549. main_argv = argv;
  550. progname = argv[0];
  551. message (true, "%s: Sorry, the Emacs server is supported only\n"
  552. "on systems with Berkeley sockets.\n",
  553. argv[0]);
  554. fail ();
  555. }
  556. #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
  557. #define AUTH_KEY_LENGTH 64
  558. #define SEND_BUFFER_SIZE 4096
  559. /* Buffer to accumulate data to send in TCP connections. */
  560. char send_buffer[SEND_BUFFER_SIZE + 1];
  561. int sblen = 0; /* Fill pointer for the send buffer. */
  562. /* Socket used to communicate with the Emacs server process. */
  563. HSOCKET emacs_socket = 0;
  564. /* On Windows, the socket library was historically separate from the
  565. standard C library, so errors are handled differently. */
  566. static void
  567. sock_err_message (const char *function_name)
  568. {
  569. #ifdef WINDOWSNT
  570. char* msg = NULL;
  571. FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  572. | FORMAT_MESSAGE_ALLOCATE_BUFFER
  573. | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  574. NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
  575. message (true, "%s: %s: %s\n", progname, function_name, msg);
  576. LocalFree (msg);
  577. #else
  578. message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
  579. #endif
  580. }
  581. /* Let's send the data to Emacs when either
  582. - the data ends in "\n", or
  583. - the buffer is full (but this shouldn't happen)
  584. Otherwise, we just accumulate it. */
  585. static void
  586. send_to_emacs (HSOCKET s, const char *data)
  587. {
  588. size_t dlen;
  589. if (!data)
  590. return;
  591. dlen = strlen (data);
  592. while (*data)
  593. {
  594. size_t part = min (dlen, SEND_BUFFER_SIZE - sblen);
  595. memcpy (&send_buffer[sblen], data, part);
  596. data += part;
  597. sblen += part;
  598. if (sblen == SEND_BUFFER_SIZE
  599. || (sblen > 0 && send_buffer[sblen-1] == '\n'))
  600. {
  601. int sent = send (s, send_buffer, sblen, 0);
  602. if (sent < 0)
  603. {
  604. message (true, "%s: failed to send %d bytes to socket: %s\n",
  605. progname, sblen, strerror (errno));
  606. fail ();
  607. }
  608. if (sent != sblen)
  609. memmove (send_buffer, &send_buffer[sent], sblen - sent);
  610. sblen -= sent;
  611. }
  612. dlen -= part;
  613. }
  614. }
  615. /* In STR, insert a & before each &, each space, each newline, and
  616. any initial -. Change spaces to underscores, too, so that the
  617. return value never contains a space.
  618. Does not change the string. Outputs the result to S. */
  619. static void
  620. quote_argument (HSOCKET s, const char *str)
  621. {
  622. char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
  623. const char *p;
  624. char *q;
  625. p = str;
  626. q = copy;
  627. while (*p)
  628. {
  629. if (*p == ' ')
  630. {
  631. *q++ = '&';
  632. *q++ = '_';
  633. p++;
  634. }
  635. else if (*p == '\n')
  636. {
  637. *q++ = '&';
  638. *q++ = 'n';
  639. p++;
  640. }
  641. else
  642. {
  643. if (*p == '&' || (*p == '-' && p == str))
  644. *q++ = '&';
  645. *q++ = *p++;
  646. }
  647. }
  648. *q++ = 0;
  649. send_to_emacs (s, copy);
  650. free (copy);
  651. }
  652. /* The inverse of quote_argument. Removes quoting in string STR by
  653. modifying the string in place. Returns STR. */
  654. static char *
  655. unquote_argument (char *str)
  656. {
  657. char *p, *q;
  658. if (! str)
  659. return str;
  660. p = str;
  661. q = str;
  662. while (*p)
  663. {
  664. if (*p == '&')
  665. {
  666. p++;
  667. if (*p == '&')
  668. *p = '&';
  669. else if (*p == '_')
  670. *p = ' ';
  671. else if (*p == 'n')
  672. *p = '\n';
  673. else if (*p == '-')
  674. *p = '-';
  675. }
  676. *q++ = *p++;
  677. }
  678. *q = 0;
  679. return str;
  680. }
  681. static int
  682. file_name_absolute_p (const char *filename)
  683. {
  684. /* Sanity check, it shouldn't happen. */
  685. if (! filename) return false;
  686. /* /xxx is always an absolute path. */
  687. if (filename[0] == '/') return true;
  688. /* Empty filenames (which shouldn't happen) are relative. */
  689. if (filename[0] == '\0') return false;
  690. #ifdef WINDOWSNT
  691. /* X:\xxx is always absolute. */
  692. if (isalpha ((unsigned char) filename[0])
  693. && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
  694. return true;
  695. /* Both \xxx and \\xxx\yyy are absolute. */
  696. if (filename[0] == '\\') return true;
  697. #endif
  698. return false;
  699. }
  700. #ifdef WINDOWSNT
  701. /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
  702. void __cdecl close_winsock (void);
  703. void __cdecl
  704. close_winsock (void)
  705. {
  706. WSACleanup ();
  707. }
  708. /* Initialize the WinSock2 library. */
  709. void initialize_sockets (void);
  710. void
  711. initialize_sockets (void)
  712. {
  713. WSADATA wsaData;
  714. if (WSAStartup (MAKEWORD (2, 0), &wsaData))
  715. {
  716. message (true, "%s: error initializing WinSock2\n", progname);
  717. exit (EXIT_FAILURE);
  718. }
  719. atexit (close_winsock);
  720. }
  721. #endif /* WINDOWSNT */
  722. /* Read the information needed to set up a TCP comm channel with
  723. the Emacs server: host, port, and authentication string. */
  724. static int
  725. get_server_config (const char *config_file, struct sockaddr_in *server,
  726. char *authentication)
  727. {
  728. char dotted[32];
  729. char *port;
  730. FILE *config = NULL;
  731. if (file_name_absolute_p (config_file))
  732. config = fopen (config_file, "rb");
  733. else
  734. {
  735. const char *home = egetenv ("HOME");
  736. if (home)
  737. {
  738. char *path = xmalloc (strlen (home) + strlen (config_file)
  739. + EXTRA_SPACE);
  740. char *z = stpcpy (path, home);
  741. z = stpcpy (z, "/.emacs.d/server/");
  742. strcpy (z, config_file);
  743. config = fopen (path, "rb");
  744. free (path);
  745. }
  746. #ifdef WINDOWSNT
  747. if (!config && (home = egetenv ("APPDATA")))
  748. {
  749. char *path = xmalloc (strlen (home) + strlen (config_file)
  750. + EXTRA_SPACE);
  751. char *z = stpcpy (path, home);
  752. z = stpcpy (z, "/.emacs.d/server/");
  753. strcpy (z, config_file);
  754. config = fopen (path, "rb");
  755. free (path);
  756. }
  757. #endif
  758. }
  759. if (! config)
  760. return false;
  761. if (fgets (dotted, sizeof dotted, config)
  762. && (port = strchr (dotted, ':')))
  763. *port++ = '\0';
  764. else
  765. {
  766. message (true, "%s: invalid configuration info\n", progname);
  767. exit (EXIT_FAILURE);
  768. }
  769. server->sin_family = AF_INET;
  770. server->sin_addr.s_addr = inet_addr (dotted);
  771. server->sin_port = htons (atoi (port));
  772. if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
  773. {
  774. message (true, "%s: cannot read authentication info\n", progname);
  775. exit (EXIT_FAILURE);
  776. }
  777. fclose (config);
  778. return true;
  779. }
  780. static HSOCKET
  781. set_tcp_socket (const char *local_server_file)
  782. {
  783. HSOCKET s;
  784. struct sockaddr_in server;
  785. struct linger l_arg = {1, 1};
  786. char auth_string[AUTH_KEY_LENGTH + 1];
  787. if (! get_server_config (local_server_file, &server, auth_string))
  788. return INVALID_SOCKET;
  789. if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
  790. message (false, "%s: connected to remote socket at %s\n",
  791. progname, inet_ntoa (server.sin_addr));
  792. /* Open up an AF_INET socket. */
  793. if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
  794. {
  795. /* Since we have an alternate to try out, this is not an error
  796. yet; popping out a modal dialog at this stage would make -a
  797. option totally useless for emacsclientw -- the user will
  798. still get an error message if the alternate editor fails. */
  799. #ifdef WINDOWSNT
  800. if(!(w32_window_app () && alternate_editor))
  801. #endif
  802. sock_err_message ("socket");
  803. return INVALID_SOCKET;
  804. }
  805. /* Set up the socket. */
  806. if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
  807. {
  808. #ifdef WINDOWSNT
  809. if(!(w32_window_app () && alternate_editor))
  810. #endif
  811. sock_err_message ("connect");
  812. return INVALID_SOCKET;
  813. }
  814. setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
  815. /* Send the authentication. */
  816. auth_string[AUTH_KEY_LENGTH] = '\0';
  817. send_to_emacs (s, "-auth ");
  818. send_to_emacs (s, auth_string);
  819. send_to_emacs (s, " ");
  820. return s;
  821. }
  822. /* Returns 1 if PREFIX is a prefix of STRING. */
  823. static int
  824. strprefix (const char *prefix, const char *string)
  825. {
  826. return !strncmp (prefix, string, strlen (prefix));
  827. }
  828. /* Get tty name and type. If successful, return the type in TTY_TYPE
  829. and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
  830. is zero, or return 0 if NOABORT is non-zero. */
  831. static int
  832. find_tty (const char **tty_type, const char **tty_name, int noabort)
  833. {
  834. const char *type = egetenv ("TERM");
  835. const char *name = ttyname (fileno (stdout));
  836. if (!name)
  837. {
  838. if (noabort)
  839. return 0;
  840. else
  841. {
  842. message (true, "%s: could not get terminal name\n", progname);
  843. fail ();
  844. }
  845. }
  846. if (!type)
  847. {
  848. if (noabort)
  849. return 0;
  850. else
  851. {
  852. message (true, "%s: please set the TERM variable to your terminal type\n",
  853. progname);
  854. fail ();
  855. }
  856. }
  857. if (strcmp (type, "eterm") == 0)
  858. {
  859. if (noabort)
  860. return 0;
  861. else
  862. {
  863. /* This causes nasty, MULTI_KBOARD-related input lockouts. */
  864. message (true, "%s: opening a frame in an Emacs term buffer"
  865. " is not supported\n", progname);
  866. fail ();
  867. }
  868. }
  869. *tty_name = name;
  870. *tty_type = type;
  871. return 1;
  872. }
  873. #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
  874. /* Three possibilities:
  875. 2 - can't be `stat'ed (sets errno)
  876. 1 - isn't owned by us
  877. 0 - success: none of the above */
  878. static int
  879. socket_status (const char *name)
  880. {
  881. struct stat statbfr;
  882. if (stat (name, &statbfr) == -1)
  883. return 2;
  884. if (statbfr.st_uid != geteuid ())
  885. return 1;
  886. return 0;
  887. }
  888. /* A signal handler that passes the signal to the Emacs process.
  889. Useful for SIGWINCH. */
  890. static void
  891. pass_signal_to_emacs (int signalnum)
  892. {
  893. int old_errno = errno;
  894. if (emacs_pid)
  895. kill (emacs_pid, signalnum);
  896. signal (signalnum, pass_signal_to_emacs);
  897. errno = old_errno;
  898. }
  899. /* Signal handler for SIGCONT; notify the Emacs process that it can
  900. now resume our tty frame. */
  901. static void
  902. handle_sigcont (int signalnum)
  903. {
  904. int old_errno = errno;
  905. pid_t pgrp = getpgrp ();
  906. pid_t tcpgrp = tcgetpgrp (1);
  907. if (tcpgrp == pgrp)
  908. {
  909. /* We are in the foreground. */
  910. send_to_emacs (emacs_socket, "-resume \n");
  911. }
  912. else if (0 <= tcpgrp && tty)
  913. {
  914. /* We are in the background; cancel the continue. */
  915. kill (-pgrp, SIGTTIN);
  916. }
  917. signal (signalnum, handle_sigcont);
  918. errno = old_errno;
  919. }
  920. /* Signal handler for SIGTSTP; notify the Emacs process that we are
  921. going to sleep. Normally the suspend is initiated by Emacs via
  922. server-handle-suspend-tty, but if the server gets out of sync with
  923. reality, we may get a SIGTSTP on C-z. Handling this signal and
  924. notifying Emacs about it should get things under control again. */
  925. static void
  926. handle_sigtstp (int signalnum)
  927. {
  928. int old_errno = errno;
  929. sigset_t set;
  930. if (emacs_socket)
  931. send_to_emacs (emacs_socket, "-suspend \n");
  932. /* Unblock this signal and call the default handler by temporarily
  933. changing the handler and resignaling. */
  934. sigprocmask (SIG_BLOCK, NULL, &set);
  935. sigdelset (&set, signalnum);
  936. signal (signalnum, SIG_DFL);
  937. raise (signalnum);
  938. sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
  939. signal (signalnum, handle_sigtstp);
  940. errno = old_errno;
  941. }
  942. /* Set up signal handlers before opening a frame on the current tty. */
  943. static void
  944. init_signals (void)
  945. {
  946. /* Set up signal handlers. */
  947. signal (SIGWINCH, pass_signal_to_emacs);
  948. /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
  949. deciding which terminal the signal came from. C-g is now a
  950. normal input event on secondary terminals. */
  951. #if 0
  952. signal (SIGINT, pass_signal_to_emacs);
  953. signal (SIGQUIT, pass_signal_to_emacs);
  954. #endif
  955. signal (SIGCONT, handle_sigcont);
  956. signal (SIGTSTP, handle_sigtstp);
  957. signal (SIGTTOU, handle_sigtstp);
  958. }
  959. static HSOCKET
  960. set_local_socket (const char *local_socket_name)
  961. {
  962. HSOCKET s;
  963. struct sockaddr_un server;
  964. /* Open up an AF_UNIX socket in this person's home directory. */
  965. if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
  966. {
  967. message (true, "%s: socket: %s\n", progname, strerror (errno));
  968. return INVALID_SOCKET;
  969. }
  970. server.sun_family = AF_UNIX;
  971. {
  972. int sock_status;
  973. int saved_errno;
  974. const char *server_name = local_socket_name;
  975. const char *tmpdir = NULL;
  976. char *tmpdir_storage = NULL;
  977. char *socket_name_storage = NULL;
  978. if (!strchr (local_socket_name, '/') && !strchr (local_socket_name, '\\'))
  979. {
  980. /* socket_name is a file name component. */
  981. long uid = geteuid ();
  982. tmpdir = egetenv ("TMPDIR");
  983. if (!tmpdir)
  984. {
  985. #ifdef DARWIN_OS
  986. #ifndef _CS_DARWIN_USER_TEMP_DIR
  987. #define _CS_DARWIN_USER_TEMP_DIR 65537
  988. #endif
  989. size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
  990. if (n > 0)
  991. {
  992. tmpdir = tmpdir_storage = xmalloc (n);
  993. confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir_storage, n);
  994. }
  995. else
  996. #endif
  997. tmpdir = "/tmp";
  998. }
  999. socket_name_storage =
  1000. xmalloc (strlen (tmpdir) + strlen (server_name) + EXTRA_SPACE);
  1001. char *z = stpcpy (socket_name_storage, tmpdir);
  1002. z += sprintf (z, "/emacs%ld/", uid);
  1003. strcpy (z, server_name);
  1004. local_socket_name = socket_name_storage;
  1005. }
  1006. if (strlen (local_socket_name) < sizeof (server.sun_path))
  1007. strcpy (server.sun_path, local_socket_name);
  1008. else
  1009. {
  1010. message (true, "%s: socket-name %s too long\n",
  1011. progname, local_socket_name);
  1012. fail ();
  1013. }
  1014. /* See if the socket exists, and if it's owned by us. */
  1015. sock_status = socket_status (server.sun_path);
  1016. saved_errno = errno;
  1017. if (sock_status && tmpdir)
  1018. {
  1019. /* Failing that, see if LOGNAME or USER exist and differ from
  1020. our euid. If so, look for a socket based on the UID
  1021. associated with the name. This is reminiscent of the logic
  1022. that init_editfns uses to set the global Vuser_full_name. */
  1023. const char *user_name = egetenv ("LOGNAME");
  1024. if (!user_name)
  1025. user_name = egetenv ("USER");
  1026. if (user_name)
  1027. {
  1028. struct passwd *pw = getpwnam (user_name);
  1029. if (pw && (pw->pw_uid != geteuid ()))
  1030. {
  1031. /* We're running under su, apparently. */
  1032. long uid = pw->pw_uid;
  1033. char *user_socket_name
  1034. = xmalloc (strlen (tmpdir) + strlen (server_name)
  1035. + EXTRA_SPACE);
  1036. char *z = stpcpy (user_socket_name, tmpdir);
  1037. z += sprintf (z, "/emacs%ld/", uid);
  1038. strcpy (z, server_name);
  1039. if (strlen (user_socket_name) < sizeof (server.sun_path))
  1040. strcpy (server.sun_path, user_socket_name);
  1041. else
  1042. {
  1043. message (true, "%s: socket-name %s too long\n",
  1044. progname, user_socket_name);
  1045. exit (EXIT_FAILURE);
  1046. }
  1047. free (user_socket_name);
  1048. sock_status = socket_status (server.sun_path);
  1049. saved_errno = errno;
  1050. }
  1051. else
  1052. errno = saved_errno;
  1053. }
  1054. }
  1055. free (socket_name_storage);
  1056. free (tmpdir_storage);
  1057. switch (sock_status)
  1058. {
  1059. case 1:
  1060. /* There's a socket, but it isn't owned by us. This is OK if
  1061. we are root. */
  1062. if (0 != geteuid ())
  1063. {
  1064. message (true, "%s: Invalid socket owner\n", progname);
  1065. return INVALID_SOCKET;
  1066. }
  1067. break;
  1068. case 2:
  1069. /* `stat' failed */
  1070. if (saved_errno == ENOENT)
  1071. message (true,
  1072. "%s: can't find socket; have you started the server?\n\
  1073. To start the server in Emacs, type \"M-x server-start\".\n",
  1074. progname);
  1075. else
  1076. message (true, "%s: can't stat %s: %s\n",
  1077. progname, server.sun_path, strerror (saved_errno));
  1078. return INVALID_SOCKET;
  1079. }
  1080. }
  1081. if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
  1082. < 0)
  1083. {
  1084. message (true, "%s: connect: %s\n", progname, strerror (errno));
  1085. return INVALID_SOCKET;
  1086. }
  1087. return s;
  1088. }
  1089. #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
  1090. static HSOCKET
  1091. set_socket (int no_exit_if_error)
  1092. {
  1093. HSOCKET s;
  1094. const char *local_server_file = server_file;
  1095. INITIALIZE ();
  1096. #ifndef NO_SOCKETS_IN_FILE_SYSTEM
  1097. /* Explicit --socket-name argument. */
  1098. if (socket_name)
  1099. {
  1100. s = set_local_socket (socket_name);
  1101. if ((s != INVALID_SOCKET) || no_exit_if_error)
  1102. return s;
  1103. message (true, "%s: error accessing socket \"%s\"\n",
  1104. progname, socket_name);
  1105. exit (EXIT_FAILURE);
  1106. }
  1107. #endif
  1108. /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
  1109. if (!local_server_file)
  1110. local_server_file = egetenv ("EMACS_SERVER_FILE");
  1111. if (local_server_file)
  1112. {
  1113. s = set_tcp_socket (local_server_file);
  1114. if ((s != INVALID_SOCKET) || no_exit_if_error)
  1115. return s;
  1116. message (true, "%s: error accessing server file \"%s\"\n",
  1117. progname, local_server_file);
  1118. exit (EXIT_FAILURE);
  1119. }
  1120. #ifndef NO_SOCKETS_IN_FILE_SYSTEM
  1121. /* Implicit local socket. */
  1122. s = set_local_socket ("server");
  1123. if (s != INVALID_SOCKET)
  1124. return s;
  1125. #endif
  1126. /* Implicit server file. */
  1127. s = set_tcp_socket ("server");
  1128. if ((s != INVALID_SOCKET) || no_exit_if_error)
  1129. return s;
  1130. /* No implicit or explicit socket, and no alternate editor. */
  1131. message (true, "%s: No socket or alternate editor. Please use:\n\n"
  1132. #ifndef NO_SOCKETS_IN_FILE_SYSTEM
  1133. "\t--socket-name\n"
  1134. #endif
  1135. "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
  1136. \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
  1137. progname);
  1138. exit (EXIT_FAILURE);
  1139. }
  1140. #ifdef HAVE_NTGUI
  1141. FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
  1142. FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
  1143. void w32_set_user_model_id (void);
  1144. void
  1145. w32_set_user_model_id (void)
  1146. {
  1147. HMODULE shell;
  1148. HRESULT (WINAPI * set_user_model) (const wchar_t * id);
  1149. /* On Windows 7 and later, we need to set the user model ID
  1150. to associate emacsclient launched files with Emacs frames
  1151. in the UI. */
  1152. shell = LoadLibrary ("shell32.dll");
  1153. if (shell)
  1154. {
  1155. set_user_model
  1156. = (void *) GetProcAddress (shell,
  1157. "SetCurrentProcessExplicitAppUserModelID");
  1158. /* If the function is defined, then we are running on Windows 7
  1159. or newer, and the UI uses this to group related windows
  1160. together. Since emacs, runemacs, emacsclient are related, we
  1161. want them grouped even though the executables are different,
  1162. so we need to set a consistent ID between them. */
  1163. if (set_user_model)
  1164. set_user_model (L"GNU.Emacs");
  1165. FreeLibrary (shell);
  1166. }
  1167. }
  1168. BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
  1169. BOOL CALLBACK
  1170. w32_find_emacs_process (HWND hWnd, LPARAM lParam)
  1171. {
  1172. DWORD pid;
  1173. char class[6];
  1174. /* Reject any window not of class "Emacs". */
  1175. if (! get_wc (hWnd, class, sizeof (class))
  1176. || strcmp (class, "Emacs"))
  1177. return TRUE;
  1178. /* We only need the process id, not the thread id. */
  1179. (void) GetWindowThreadProcessId (hWnd, &pid);
  1180. /* Not the one we're looking for. */
  1181. if (pid != (DWORD) emacs_pid) return TRUE;
  1182. /* OK, let's raise it. */
  1183. set_fg (emacs_pid);
  1184. /* Stop enumeration. */
  1185. return FALSE;
  1186. }
  1187. /* Search for a window of class "Emacs" and owned by a process with
  1188. process id = emacs_pid. If found, allow it to grab the focus. */
  1189. void w32_give_focus (void);
  1190. void
  1191. w32_give_focus (void)
  1192. {
  1193. HANDLE user32;
  1194. /* It shouldn't happen when dealing with TCP sockets. */
  1195. if (!emacs_pid) return;
  1196. user32 = GetModuleHandle ("user32.dll");
  1197. if (!user32)
  1198. return;
  1199. /* Modern Windows restrict which processes can set the foreground window.
  1200. emacsclient can allow Emacs to grab the focus by calling the function
  1201. AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
  1202. NT) lack this function, so we have to check its availability. */
  1203. if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
  1204. && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
  1205. EnumWindows (w32_find_emacs_process, (LPARAM) 0);
  1206. }
  1207. #endif /* HAVE_NTGUI */
  1208. /* Start the emacs daemon and try to connect to it. */
  1209. static void
  1210. start_daemon_and_retry_set_socket (void)
  1211. {
  1212. #ifndef WINDOWSNT
  1213. pid_t dpid;
  1214. int status;
  1215. dpid = fork ();
  1216. if (dpid > 0)
  1217. {
  1218. pid_t w;
  1219. w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
  1220. if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
  1221. {
  1222. message (true, "Error: Could not start the Emacs daemon\n");
  1223. exit (EXIT_FAILURE);
  1224. }
  1225. /* Try connecting, the daemon should have started by now. */
  1226. message (true, "Emacs daemon should have started, trying to connect again\n");
  1227. if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
  1228. {
  1229. message (true, "Error: Cannot connect even after starting the Emacs daemon\n");
  1230. exit (EXIT_FAILURE);
  1231. }
  1232. }
  1233. else if (dpid < 0)
  1234. {
  1235. fprintf (stderr, "Error: Cannot fork!\n");
  1236. exit (EXIT_FAILURE);
  1237. }
  1238. else
  1239. {
  1240. char emacs[] = "emacs";
  1241. char daemon_option[] = "--daemon";
  1242. char *d_argv[3];
  1243. d_argv[0] = emacs;
  1244. d_argv[1] = daemon_option;
  1245. d_argv[2] = 0;
  1246. if (socket_name != NULL)
  1247. {
  1248. /* Pass --daemon=socket_name as argument. */
  1249. const char *deq = "--daemon=";
  1250. char *daemon_arg = xmalloc (strlen (deq)
  1251. + strlen (socket_name) + 1);
  1252. strcpy (stpcpy (daemon_arg, deq), socket_name);
  1253. d_argv[1] = daemon_arg;
  1254. }
  1255. execvp ("emacs", d_argv);
  1256. message (true, "%s: error starting emacs daemon\n", progname);
  1257. }
  1258. #else /* WINDOWSNT */
  1259. DWORD wait_result;
  1260. HANDLE w32_daemon_event;
  1261. STARTUPINFO si;
  1262. PROCESS_INFORMATION pi;
  1263. ZeroMemory (&si, sizeof si);
  1264. si.cb = sizeof si;
  1265. ZeroMemory (&pi, sizeof pi);
  1266. /* We start Emacs in daemon mode, and then wait for it to signal us
  1267. it is ready to accept client connections, by asserting an event
  1268. whose name is known to the daemon (defined by nt/inc/ms-w32.h). */
  1269. if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
  1270. CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
  1271. {
  1272. char* msg = NULL;
  1273. FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  1274. | FORMAT_MESSAGE_ALLOCATE_BUFFER
  1275. | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1276. NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
  1277. message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
  1278. exit (EXIT_FAILURE);
  1279. }
  1280. w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
  1281. if (w32_daemon_event == NULL)
  1282. {
  1283. message (true, "Couldn't create Windows daemon event");
  1284. exit (EXIT_FAILURE);
  1285. }
  1286. if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
  1287. != WAIT_OBJECT_0)
  1288. {
  1289. const char *msg = NULL;
  1290. switch (wait_result)
  1291. {
  1292. case WAIT_ABANDONED:
  1293. msg = "The daemon exited unexpectedly";
  1294. break;
  1295. case WAIT_TIMEOUT:
  1296. /* Can't happen due to INFINITE. */
  1297. default:
  1298. case WAIT_FAILED:
  1299. FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
  1300. | FORMAT_MESSAGE_ALLOCATE_BUFFER
  1301. | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1302. NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
  1303. break;
  1304. }
  1305. message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
  1306. exit (EXIT_FAILURE);
  1307. }
  1308. CloseHandle (w32_daemon_event);
  1309. /* Try connecting, the daemon should have started by now. */
  1310. /* It's just a progress message, so don't pop a dialog if this is
  1311. emacsclientw. */
  1312. if (!w32_window_app ())
  1313. message (true,
  1314. "Emacs daemon should have started, trying to connect again\n");
  1315. if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
  1316. {
  1317. message (true,
  1318. "Error: Cannot connect even after starting the Emacs daemon\n");
  1319. exit (EXIT_FAILURE);
  1320. }
  1321. #endif /* WINDOWSNT */
  1322. }
  1323. int
  1324. main (int argc, char **argv)
  1325. {
  1326. int rl = 0, needlf = 0;
  1327. char *cwd, *str;
  1328. char string[BUFSIZ+1];
  1329. int start_daemon_if_needed;
  1330. int exit_status = EXIT_SUCCESS;
  1331. main_argv = argv;
  1332. progname = argv[0];
  1333. #ifdef HAVE_NTGUI
  1334. /* On Windows 7 and later, we need to explicitly associate
  1335. emacsclient with emacs so the UI behaves sensibly. This
  1336. association does no harm if we're not actually connecting to an
  1337. Emacs using a window display. */
  1338. w32_set_user_model_id ();
  1339. #endif /* HAVE_NTGUI */
  1340. /* Process options. */
  1341. decode_options (argc, argv);
  1342. if ((argc - optind < 1) && !eval && current_frame)
  1343. {
  1344. message (true, "%s: file name or argument required\n"
  1345. "Try '%s --help' for more information\n",
  1346. progname, progname);
  1347. exit (EXIT_FAILURE);
  1348. }
  1349. #ifndef WINDOWSNT
  1350. if (tty)
  1351. {
  1352. pid_t pgrp = getpgrp ();
  1353. pid_t tcpgrp = tcgetpgrp (1);
  1354. if (0 <= tcpgrp && tcpgrp != pgrp)
  1355. kill (-pgrp, SIGTTIN);
  1356. }
  1357. #endif /* !WINDOWSNT */
  1358. /* If alternate_editor is the empty string, start the emacs daemon
  1359. in case of failure to connect. */
  1360. start_daemon_if_needed = (alternate_editor
  1361. && (alternate_editor[0] == '\0'));
  1362. emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
  1363. if (emacs_socket == INVALID_SOCKET)
  1364. {
  1365. if (! start_daemon_if_needed)
  1366. fail ();
  1367. start_daemon_and_retry_set_socket ();
  1368. }
  1369. cwd = get_current_dir_name ();
  1370. if (cwd == 0)
  1371. {
  1372. message (true, "%s: %s\n", progname,
  1373. "Cannot get current working directory");
  1374. fail ();
  1375. }
  1376. #ifdef HAVE_NTGUI
  1377. if (display && !strcmp (display, "w32"))
  1378. w32_give_focus ();
  1379. #endif /* HAVE_NTGUI */
  1380. /* Send over our environment and current directory. */
  1381. if (!current_frame)
  1382. {
  1383. int i;
  1384. for (i = 0; environ[i]; i++)
  1385. {
  1386. send_to_emacs (emacs_socket, "-env ");
  1387. quote_argument (emacs_socket, environ[i]);
  1388. send_to_emacs (emacs_socket, " ");
  1389. }
  1390. }
  1391. send_to_emacs (emacs_socket, "-dir ");
  1392. quote_argument (emacs_socket, cwd);
  1393. send_to_emacs (emacs_socket, "/");
  1394. send_to_emacs (emacs_socket, " ");
  1395. retry:
  1396. if (nowait)
  1397. send_to_emacs (emacs_socket, "-nowait ");
  1398. if (current_frame)
  1399. send_to_emacs (emacs_socket, "-current-frame ");
  1400. if (display)
  1401. {
  1402. send_to_emacs (emacs_socket, "-display ");
  1403. quote_argument (emacs_socket, display);
  1404. send_to_emacs (emacs_socket, " ");
  1405. }
  1406. if (parent_id)
  1407. {
  1408. send_to_emacs (emacs_socket, "-parent-id ");
  1409. quote_argument (emacs_socket, parent_id);
  1410. send_to_emacs (emacs_socket, " ");
  1411. }
  1412. if (frame_parameters && !current_frame)
  1413. {
  1414. send_to_emacs (emacs_socket, "-frame-parameters ");
  1415. quote_argument (emacs_socket, frame_parameters);
  1416. send_to_emacs (emacs_socket, " ");
  1417. }
  1418. /* Unless we are certain we don't want to occupy the tty, send our
  1419. tty information to Emacs. For example, in daemon mode Emacs may
  1420. need to occupy this tty if no other frame is available. */
  1421. if (!current_frame || !eval)
  1422. {
  1423. const char *tty_type, *tty_name;
  1424. if (find_tty (&tty_type, &tty_name, !tty))
  1425. {
  1426. #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
  1427. init_signals ();
  1428. #endif
  1429. send_to_emacs (emacs_socket, "-tty ");
  1430. quote_argument (emacs_socket, tty_name);
  1431. send_to_emacs (emacs_socket, " ");
  1432. quote_argument (emacs_socket, tty_type);
  1433. send_to_emacs (emacs_socket, " ");
  1434. }
  1435. }
  1436. if (!current_frame && !tty)
  1437. send_to_emacs (emacs_socket, "-window-system ");
  1438. if ((argc - optind > 0))
  1439. {
  1440. int i;
  1441. for (i = optind; i < argc; i++)
  1442. {
  1443. if (eval)
  1444. {
  1445. /* Don't prepend cwd or anything like that. */
  1446. send_to_emacs (emacs_socket, "-eval ");
  1447. quote_argument (emacs_socket, argv[i]);
  1448. send_to_emacs (emacs_socket, " ");
  1449. continue;
  1450. }
  1451. if (*argv[i] == '+')
  1452. {
  1453. char *p = argv[i] + 1;
  1454. while (isdigit ((unsigned char) *p) || *p == ':') p++;
  1455. if (*p == 0)
  1456. {
  1457. send_to_emacs (emacs_socket, "-position ");
  1458. quote_argument (emacs_socket, argv[i]);
  1459. send_to_emacs (emacs_socket, " ");
  1460. continue;
  1461. }
  1462. }
  1463. #ifdef WINDOWSNT
  1464. else if (! file_name_absolute_p (argv[i])
  1465. && (isalpha (argv[i][0]) && argv[i][1] == ':'))
  1466. /* Windows can have a different default directory for each
  1467. drive, so the cwd passed via "-dir" is not sufficient
  1468. to account for that.
  1469. If the user uses <drive>:<relpath>, we hence need to be
  1470. careful to expand <relpath> with the default directory
  1471. corresponding to <drive>. */
  1472. {
  1473. char *filename = (char *) xmalloc (MAX_PATH);
  1474. DWORD size;
  1475. size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
  1476. if (size > 0 && size < MAX_PATH)
  1477. argv[i] = filename;
  1478. else
  1479. free (filename);
  1480. }
  1481. #endif
  1482. send_to_emacs (emacs_socket, "-file ");
  1483. quote_argument (emacs_socket, argv[i]);
  1484. send_to_emacs (emacs_socket, " ");
  1485. }
  1486. }
  1487. else if (eval)
  1488. {
  1489. /* Read expressions interactively. */
  1490. while ((str = fgets (string, BUFSIZ, stdin)))
  1491. {
  1492. send_to_emacs (emacs_socket, "-eval ");
  1493. quote_argument (emacs_socket, str);
  1494. }
  1495. send_to_emacs (emacs_socket, " ");
  1496. }
  1497. send_to_emacs (emacs_socket, "\n");
  1498. /* Wait for an answer. */
  1499. if (!eval && !tty && !nowait && !quiet)
  1500. {
  1501. printf ("Waiting for Emacs...");
  1502. needlf = 2;
  1503. }
  1504. fflush (stdout);
  1505. while (fdatasync (1) != 0 && errno == EINTR)
  1506. continue;
  1507. /* Now, wait for an answer and print any messages. */
  1508. while (exit_status == EXIT_SUCCESS)
  1509. {
  1510. char *p, *end_p;
  1511. do
  1512. {
  1513. errno = 0;
  1514. rl = recv (emacs_socket, string, BUFSIZ, 0);
  1515. }
  1516. /* If we receive a signal (e.g. SIGWINCH, which we pass
  1517. through to Emacs), on some OSes we get EINTR and must retry. */
  1518. while (rl < 0 && errno == EINTR);
  1519. if (rl <= 0)
  1520. break;
  1521. string[rl] = '\0';
  1522. /* Loop over all NL-terminated messages. */
  1523. for (end_p = p = string; end_p != NULL && *end_p != '\0'; p = end_p)
  1524. {
  1525. end_p = strchr (p, '\n');
  1526. if (end_p != NULL)
  1527. *end_p++ = '\0';
  1528. if (strprefix ("-emacs-pid ", p))
  1529. {
  1530. /* -emacs-pid PID: The process id of the Emacs process. */
  1531. emacs_pid = strtol (p + strlen ("-emacs-pid"), NULL, 10);
  1532. }
  1533. else if (strprefix ("-window-system-unsupported ", p))
  1534. {
  1535. /* -window-system-unsupported: Emacs was compiled without support
  1536. for whatever window system we tried. Try the alternate
  1537. display, or, failing that, try the terminal. */
  1538. if (alt_display)
  1539. {
  1540. display = alt_display;
  1541. alt_display = NULL;
  1542. }
  1543. else
  1544. {
  1545. nowait = 0;
  1546. tty = 1;
  1547. }
  1548. goto retry;
  1549. }
  1550. else if (strprefix ("-print ", p))
  1551. {
  1552. /* -print STRING: Print STRING on the terminal. */
  1553. str = unquote_argument (p + strlen ("-print "));
  1554. if (needlf)
  1555. printf ("\n");
  1556. printf ("%s", str);
  1557. needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
  1558. }
  1559. else if (strprefix ("-print-nonl ", p))
  1560. {
  1561. /* -print-nonl STRING: Print STRING on the terminal.
  1562. Used to continue a preceding -print command. */
  1563. str = unquote_argument (p + strlen ("-print-nonl "));
  1564. printf ("%s", str);
  1565. needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
  1566. }
  1567. else if (strprefix ("-error ", p))
  1568. {
  1569. /* -error DESCRIPTION: Signal an error on the terminal. */
  1570. str = unquote_argument (p + strlen ("-error "));
  1571. if (needlf)
  1572. printf ("\n");
  1573. fprintf (stderr, "*ERROR*: %s", str);
  1574. needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
  1575. exit_status = EXIT_FAILURE;
  1576. }
  1577. #ifdef SIGSTOP
  1578. else if (strprefix ("-suspend ", p))
  1579. {
  1580. /* -suspend: Suspend this terminal, i.e., stop the process. */
  1581. if (needlf)
  1582. printf ("\n");
  1583. needlf = 0;
  1584. kill (0, SIGSTOP);
  1585. }
  1586. #endif
  1587. else
  1588. {
  1589. /* Unknown command. */
  1590. if (needlf)
  1591. printf ("\n");
  1592. needlf = 0;
  1593. printf ("*ERROR*: Unknown message: %s\n", p);
  1594. }
  1595. }
  1596. }
  1597. if (needlf)
  1598. printf ("\n");
  1599. fflush (stdout);
  1600. while (fdatasync (1) != 0 && errno == EINTR)
  1601. continue;
  1602. if (rl < 0)
  1603. exit_status = EXIT_FAILURE;
  1604. CLOSE_SOCKET (emacs_socket);
  1605. return exit_status;
  1606. }
  1607. #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */