emacsclient.c 45 KB

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