emacsclient.c 42 KB

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