emacsclient.c 45 KB

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