utilunix.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /*
  2. Various utilities - Unix variants
  3. Copyright (C) 1994-2024
  4. Free Software Foundation, Inc.
  5. Written by:
  6. Miguel de Icaza, 1994, 1995, 1996
  7. Janne Kukonlehto, 1994, 1995, 1996
  8. Dugan Porter, 1994, 1995, 1996
  9. Jakub Jelinek, 1994, 1995, 1996
  10. Mauricio Plaza, 1994, 1995, 1996
  11. Andrew Borodin <aborodin@vmail.ru> 2010-2024
  12. The mc_realpath routine is mostly from uClibc package, written
  13. by Rick Sladkey <jrs@world.std.com>
  14. This file is part of the Midnight Commander.
  15. The Midnight Commander is free software: you can redistribute it
  16. and/or modify it under the terms of the GNU General Public License as
  17. published by the Free Software Foundation, either version 3 of the License,
  18. or (at your option) any later version.
  19. The Midnight Commander is distributed in the hope that it will be useful,
  20. but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. GNU General Public License for more details.
  23. You should have received a copy of the GNU General Public License
  24. along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. */
  26. /** \file utilunix.c
  27. * \brief Source: various utilities - Unix variant
  28. */
  29. #include <config.h>
  30. #include <ctype.h>
  31. #include <errno.h>
  32. #include <limits.h>
  33. #include <signal.h>
  34. #include <stdarg.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #ifdef HAVE_SYS_PARAM_H
  39. #include <sys/param.h>
  40. #endif
  41. #include <sys/types.h>
  42. #include <sys/stat.h>
  43. #ifdef HAVE_SYS_SELECT_H
  44. #include <sys/select.h>
  45. #endif
  46. #include <sys/wait.h>
  47. #include <pwd.h>
  48. #include <grp.h>
  49. #include "lib/global.h"
  50. #include "lib/unixcompat.h"
  51. #include "lib/vfs/vfs.h" /* VFS_ENCODING_PREFIX */
  52. #include "lib/strutil.h" /* str_move(), str_tokenize() */
  53. #include "lib/util.h"
  54. #include "lib/widget.h" /* message() */
  55. #include "lib/vfs/xdirentry.h"
  56. #ifdef HAVE_CHARSET
  57. #include "lib/charsets.h"
  58. #endif
  59. /*** global variables ****************************************************************************/
  60. struct sigaction startup_handler;
  61. /*** file scope macro definitions ****************************************************************/
  62. #define UID_CACHE_SIZE 200
  63. #define GID_CACHE_SIZE 30
  64. /*** file scope type declarations ****************************************************************/
  65. typedef struct
  66. {
  67. int index;
  68. char *string;
  69. } int_cache;
  70. typedef enum
  71. {
  72. FORK_ERROR = -1,
  73. FORK_CHILD,
  74. FORK_PARENT,
  75. } my_fork_state_t;
  76. typedef struct
  77. {
  78. struct sigaction intr;
  79. struct sigaction quit;
  80. struct sigaction stop;
  81. } my_system_sigactions_t;
  82. /*** forward declarations (file scope functions) *************************************************/
  83. /*** file scope variables ************************************************************************/
  84. static int_cache uid_cache[UID_CACHE_SIZE];
  85. static int_cache gid_cache[GID_CACHE_SIZE];
  86. /* --------------------------------------------------------------------------------------------- */
  87. /*** file scope functions ************************************************************************/
  88. /* --------------------------------------------------------------------------------------------- */
  89. static char *
  90. i_cache_match (int id, int_cache *cache, int size)
  91. {
  92. int i;
  93. for (i = 0; i < size; i++)
  94. if (cache[i].index == id)
  95. return cache[i].string;
  96. return 0;
  97. }
  98. /* --------------------------------------------------------------------------------------------- */
  99. static void
  100. i_cache_add (int id, int_cache *cache, int size, char *text, int *last)
  101. {
  102. g_free (cache[*last].string);
  103. cache[*last].string = g_strdup (text);
  104. cache[*last].index = id;
  105. *last = ((*last) + 1) % size;
  106. }
  107. /* --------------------------------------------------------------------------------------------- */
  108. static my_fork_state_t
  109. my_fork (void)
  110. {
  111. pid_t pid;
  112. pid = fork ();
  113. if (pid < 0)
  114. {
  115. fprintf (stderr, "\n\nfork () = -1\n");
  116. return FORK_ERROR;
  117. }
  118. if (pid == 0)
  119. return FORK_CHILD;
  120. while (TRUE)
  121. {
  122. int status = 0;
  123. if (waitpid (pid, &status, 0) > 0)
  124. return WEXITSTATUS (status) == 0 ? FORK_PARENT : FORK_ERROR;
  125. if (errno != EINTR)
  126. return FORK_ERROR;
  127. }
  128. }
  129. /* --------------------------------------------------------------------------------------------- */
  130. static void
  131. my_system__save_sigaction_handlers (my_system_sigactions_t *sigactions)
  132. {
  133. struct sigaction ignore;
  134. memset (&ignore, 0, sizeof (ignore));
  135. ignore.sa_handler = SIG_IGN;
  136. sigemptyset (&ignore.sa_mask);
  137. sigaction (SIGINT, &ignore, &sigactions->intr);
  138. sigaction (SIGQUIT, &ignore, &sigactions->quit);
  139. /* Restore the original SIGTSTP handler, we don't want ncurses' */
  140. /* handler messing the screen after the SIGCONT */
  141. sigaction (SIGTSTP, &startup_handler, &sigactions->stop);
  142. }
  143. /* --------------------------------------------------------------------------------------------- */
  144. static void
  145. my_system__restore_sigaction_handlers (my_system_sigactions_t *sigactions)
  146. {
  147. sigaction (SIGINT, &sigactions->intr, NULL);
  148. sigaction (SIGQUIT, &sigactions->quit, NULL);
  149. sigaction (SIGTSTP, &sigactions->stop, NULL);
  150. }
  151. /* --------------------------------------------------------------------------------------------- */
  152. static GPtrArray *
  153. my_system_make_arg_array (int flags, const char *shell)
  154. {
  155. GPtrArray *args_array;
  156. if ((flags & EXECUTE_AS_SHELL) != 0)
  157. {
  158. args_array = g_ptr_array_new ();
  159. g_ptr_array_add (args_array, (gpointer) shell);
  160. g_ptr_array_add (args_array, (gpointer) "-c");
  161. }
  162. else if (shell == NULL || *shell == '\0')
  163. {
  164. args_array = g_ptr_array_new ();
  165. g_ptr_array_add (args_array, NULL);
  166. }
  167. else
  168. args_array = str_tokenize (shell);
  169. return args_array;
  170. }
  171. /* --------------------------------------------------------------------------------------------- */
  172. static void
  173. mc_pread_stream (mc_pipe_stream_t *ps, const fd_set *fds)
  174. {
  175. size_t buf_len;
  176. ssize_t read_len;
  177. if (!FD_ISSET (ps->fd, fds))
  178. {
  179. ps->len = MC_PIPE_STREAM_UNREAD;
  180. return;
  181. }
  182. buf_len = (size_t) ps->len;
  183. if (buf_len >= MC_PIPE_BUFSIZE)
  184. buf_len = ps->null_term ? MC_PIPE_BUFSIZE - 1 : MC_PIPE_BUFSIZE;
  185. do
  186. {
  187. read_len = read (ps->fd, ps->buf, buf_len);
  188. }
  189. while (read_len < 0 && errno == EINTR);
  190. if (read_len < 0)
  191. {
  192. /* reading error */
  193. ps->len = MC_PIPE_ERROR_READ;
  194. ps->error = errno;
  195. }
  196. else if (read_len == 0)
  197. /* EOF */
  198. ps->len = MC_PIPE_STREAM_EOF;
  199. else
  200. {
  201. /* success */
  202. ps->len = read_len;
  203. if (ps->null_term)
  204. ps->buf[(size_t) ps->len] = '\0';
  205. }
  206. ps->pos = 0;
  207. }
  208. /* --------------------------------------------------------------------------------------------- */
  209. /*** public functions ****************************************************************************/
  210. /* --------------------------------------------------------------------------------------------- */
  211. const char *
  212. get_owner (uid_t uid)
  213. {
  214. struct passwd *pwd;
  215. char *name;
  216. static uid_t uid_last;
  217. name = i_cache_match ((int) uid, uid_cache, UID_CACHE_SIZE);
  218. if (name != NULL)
  219. return name;
  220. pwd = getpwuid (uid);
  221. if (pwd != NULL)
  222. {
  223. i_cache_add ((int) uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, (int *) &uid_last);
  224. return pwd->pw_name;
  225. }
  226. else
  227. {
  228. static char ibuf[10];
  229. g_snprintf (ibuf, sizeof (ibuf), "%d", (int) uid);
  230. return ibuf;
  231. }
  232. }
  233. /* --------------------------------------------------------------------------------------------- */
  234. const char *
  235. get_group (gid_t gid)
  236. {
  237. struct group *grp;
  238. char *name;
  239. static gid_t gid_last;
  240. name = i_cache_match ((int) gid, gid_cache, GID_CACHE_SIZE);
  241. if (name != NULL)
  242. return name;
  243. grp = getgrgid (gid);
  244. if (grp != NULL)
  245. {
  246. i_cache_add ((int) gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, (int *) &gid_last);
  247. return grp->gr_name;
  248. }
  249. else
  250. {
  251. static char gbuf[10];
  252. g_snprintf (gbuf, sizeof (gbuf), "%d", (int) gid);
  253. return gbuf;
  254. }
  255. }
  256. /* --------------------------------------------------------------------------------------------- */
  257. /* Since ncurses uses a handler that automatically refreshes the */
  258. /* screen after a SIGCONT, and we don't want this behavior when */
  259. /* spawning a child, we save the original handler here */
  260. void
  261. save_stop_handler (void)
  262. {
  263. sigaction (SIGTSTP, NULL, &startup_handler);
  264. }
  265. /* --------------------------------------------------------------------------------------------- */
  266. /**
  267. * Wrapper for _exit() system call.
  268. * The _exit() function has gcc's attribute 'noreturn', and this is reason why we can't
  269. * mock the call.
  270. *
  271. * @param status exit code
  272. */
  273. void
  274. /* __attribute__ ((noreturn)) */
  275. my_exit (int status)
  276. {
  277. _exit (status);
  278. }
  279. /* --------------------------------------------------------------------------------------------- */
  280. /**
  281. * Call external programs.
  282. *
  283. * @parameter flags addition conditions for running external programs.
  284. * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  285. * Shell (or command) will be found in paths described in PATH variable
  286. * (if shell parameter doesn't begin from path delimiter)
  287. * @parameter command Command for shell (or first parameter for command, if flags contain EXECUTE_AS_SHELL)
  288. * @return 0 if successful, -1 otherwise
  289. */
  290. int
  291. my_system (int flags, const char *shell, const char *command)
  292. {
  293. return my_systeml (flags, shell, command, NULL);
  294. }
  295. /* --------------------------------------------------------------------------------------------- */
  296. /**
  297. * Call external programs with various parameters number.
  298. *
  299. * @parameter flags addition conditions for running external programs.
  300. * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  301. * Shell (or command) will be found in paths described in PATH variable
  302. * (if shell parameter doesn't begin from path delimiter)
  303. * @parameter ... Command for shell with addition parameters for shell
  304. * (or parameters for command, if flags contain EXECUTE_AS_SHELL).
  305. * Should be NULL terminated.
  306. * @return 0 if successful, -1 otherwise
  307. */
  308. int
  309. my_systeml (int flags, const char *shell, ...)
  310. {
  311. GPtrArray *args_array;
  312. int status = 0;
  313. va_list vargs;
  314. char *one_arg;
  315. args_array = g_ptr_array_new ();
  316. va_start (vargs, shell);
  317. while ((one_arg = va_arg (vargs, char *)) != NULL)
  318. g_ptr_array_add (args_array, one_arg);
  319. va_end (vargs);
  320. g_ptr_array_add (args_array, NULL);
  321. status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
  322. g_ptr_array_free (args_array, TRUE);
  323. return status;
  324. }
  325. /* --------------------------------------------------------------------------------------------- */
  326. /**
  327. * Call external programs with array of strings as parameters.
  328. *
  329. * @parameter command command to run. Command will be found in paths described in PATH variable
  330. * (if command parameter doesn't begin from path delimiter)
  331. * @parameter argv Array of strings (NULL-terminated) with parameters for command
  332. * @return 0 if successful, -1 otherwise
  333. */
  334. int
  335. my_systemv (const char *command, char *const argv[])
  336. {
  337. my_fork_state_t fork_state;
  338. int status = 0;
  339. my_system_sigactions_t sigactions;
  340. my_system__save_sigaction_handlers (&sigactions);
  341. fork_state = my_fork ();
  342. switch (fork_state)
  343. {
  344. case FORK_ERROR:
  345. status = -1;
  346. break;
  347. case FORK_CHILD:
  348. {
  349. signal (SIGINT, SIG_DFL);
  350. signal (SIGQUIT, SIG_DFL);
  351. signal (SIGTSTP, SIG_DFL);
  352. signal (SIGCHLD, SIG_DFL);
  353. execvp (command, argv);
  354. my_exit (127); /* Exec error */
  355. }
  356. MC_FALLTHROUGH;
  357. /* no break here, or unreachable-code warning by no returning my_exit() */
  358. default:
  359. status = 0;
  360. break;
  361. }
  362. my_system__restore_sigaction_handlers (&sigactions);
  363. return status;
  364. }
  365. /* --------------------------------------------------------------------------------------------- */
  366. /**
  367. * Call external programs with flags and with array of strings as parameters.
  368. *
  369. * @parameter flags addition conditions for running external programs.
  370. * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  371. * Shell (or command) will be found in paths described in PATH variable
  372. * (if shell parameter doesn't begin from path delimiter)
  373. * @parameter argv Array of strings (NULL-terminated) with parameters for command
  374. * @return 0 if successful, -1 otherwise
  375. */
  376. int
  377. my_systemv_flags (int flags, const char *command, char *const argv[])
  378. {
  379. const char *execute_name;
  380. GPtrArray *args_array;
  381. int status = 0;
  382. args_array = my_system_make_arg_array (flags, command);
  383. execute_name = g_ptr_array_index (args_array, 0);
  384. for (; argv != NULL && *argv != NULL; argv++)
  385. g_ptr_array_add (args_array, *argv);
  386. g_ptr_array_add (args_array, NULL);
  387. status = my_systemv (execute_name, (char *const *) args_array->pdata);
  388. g_ptr_array_free (args_array, TRUE);
  389. return status;
  390. }
  391. /* --------------------------------------------------------------------------------------------- */
  392. /**
  393. * Create pipe and run child process.
  394. *
  395. * @parameter command command line of child process
  396. * @parameter read_out do or don't read the stdout of child process
  397. * @parameter read_err do or don't read the stderr of child process
  398. * @parameter error contains pointer to object to handle error code and message
  399. *
  400. * @return newly created object of mc_pipe_t class in success, NULL otherwise
  401. */
  402. mc_pipe_t *
  403. mc_popen (const char *command, gboolean read_out, gboolean read_err, GError **error)
  404. {
  405. mc_pipe_t *p;
  406. const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
  407. p = g_try_new (mc_pipe_t, 1);
  408. if (p == NULL)
  409. {
  410. mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
  411. _("Cannot create pipe descriptor"));
  412. goto ret_err;
  413. }
  414. p->out.fd = -1;
  415. p->err.fd = -1;
  416. if (!g_spawn_async_with_pipes
  417. (NULL, (gchar **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO, NULL,
  418. NULL, &p->child_pid, NULL, read_out ? &p->out.fd : NULL, read_err ? &p->err.fd : NULL,
  419. error))
  420. {
  421. mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
  422. _("Cannot create pipe streams"));
  423. goto ret_err;
  424. }
  425. p->out.buf[0] = '\0';
  426. p->out.len = MC_PIPE_BUFSIZE;
  427. p->out.null_term = FALSE;
  428. p->err.buf[0] = '\0';
  429. p->err.len = MC_PIPE_BUFSIZE;
  430. p->err.null_term = FALSE;
  431. return p;
  432. ret_err:
  433. g_free (p);
  434. return NULL;
  435. }
  436. /* --------------------------------------------------------------------------------------------- */
  437. /**
  438. * Read stdout and stderr of pipe asynchronously.
  439. *
  440. * @parameter p pipe descriptor
  441. *
  442. * The lengths of read data contain in p->out.len and p->err.len.
  443. *
  444. * Before read, p->xxx.len is an input. It defines the number of data to read.
  445. * Should not be greater than MC_PIPE_BUFSIZE.
  446. *
  447. * After read, p->xxx.len is an output and contains the following:
  448. * p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
  449. * p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
  450. * p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
  451. * p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
  452. *
  453. * @parameter error contains pointer to object to handle error code and message
  454. */
  455. void
  456. mc_pread (mc_pipe_t *p, GError **error)
  457. {
  458. gboolean read_out, read_err;
  459. fd_set fds;
  460. int maxfd = 0;
  461. int res;
  462. if (error != NULL)
  463. *error = NULL;
  464. read_out = p->out.fd >= 0;
  465. read_err = p->err.fd >= 0;
  466. if (!read_out && !read_err)
  467. {
  468. p->out.len = MC_PIPE_STREAM_UNREAD;
  469. p->err.len = MC_PIPE_STREAM_UNREAD;
  470. return;
  471. }
  472. FD_ZERO (&fds);
  473. if (read_out)
  474. {
  475. FD_SET (p->out.fd, &fds);
  476. maxfd = p->out.fd;
  477. }
  478. if (read_err)
  479. {
  480. FD_SET (p->err.fd, &fds);
  481. maxfd = MAX (maxfd, p->err.fd);
  482. }
  483. /* no timeout */
  484. res = select (maxfd + 1, &fds, NULL, NULL, NULL);
  485. if (res < 0 && errno != EINTR)
  486. {
  487. mc_propagate_error (error, MC_PIPE_ERROR_READ,
  488. _
  489. ("Unexpected error in select() reading data from a child process:\n%s"),
  490. unix_error_string (errno));
  491. return;
  492. }
  493. if (read_out)
  494. mc_pread_stream (&p->out, &fds);
  495. else
  496. p->out.len = MC_PIPE_STREAM_UNREAD;
  497. if (read_err)
  498. mc_pread_stream (&p->err, &fds);
  499. else
  500. p->err.len = MC_PIPE_STREAM_UNREAD;
  501. }
  502. /* --------------------------------------------------------------------------------------------- */
  503. /**
  504. * Reads a line from @stream. Reading stops after an EOL or a newline. If a newline is read,
  505. * it is appended to the line.
  506. *
  507. * @stream mc_pipe_stream_t object
  508. *
  509. * @return newly created GString or NULL in case of EOL;
  510. */
  511. GString *
  512. mc_pstream_get_string (mc_pipe_stream_t *ps)
  513. {
  514. char *s;
  515. size_t size, i;
  516. gboolean escape = FALSE;
  517. g_return_val_if_fail (ps != NULL, NULL);
  518. if (ps->len < 0)
  519. return NULL;
  520. size = ps->len - ps->pos;
  521. if (size == 0)
  522. return NULL;
  523. s = ps->buf + ps->pos;
  524. if (s[0] == '\0')
  525. return NULL;
  526. /* find '\0' or unescaped '\n' */
  527. for (i = 0; i < size && !(s[i] == '\0' || (s[i] == '\n' && !escape)); i++)
  528. escape = s[i] == '\\' ? !escape : FALSE;
  529. if (i != size && s[i] == '\n')
  530. i++;
  531. ps->pos += i;
  532. return g_string_new_len (s, i);
  533. }
  534. /* --------------------------------------------------------------------------------------------- */
  535. /**
  536. * Close pipe and destroy pipe descriptor.
  537. *
  538. * @parameter p pipe descriptor
  539. * @parameter error contains pointer to object to handle error code and message
  540. */
  541. void
  542. mc_pclose (mc_pipe_t *p, GError **error)
  543. {
  544. int res;
  545. if (p == NULL)
  546. {
  547. mc_replace_error (error, MC_PIPE_ERROR_READ, "%s",
  548. _("Cannot close pipe descriptor (p == NULL)"));
  549. return;
  550. }
  551. if (p->out.fd >= 0)
  552. res = close (p->out.fd);
  553. if (p->err.fd >= 0)
  554. res = close (p->err.fd);
  555. do
  556. {
  557. int status;
  558. res = waitpid (p->child_pid, &status, 0);
  559. }
  560. while (res < 0 && errno == EINTR);
  561. if (res < 0)
  562. mc_replace_error (error, MC_PIPE_ERROR_READ, _("Unexpected error in waitpid():\n%s"),
  563. unix_error_string (errno));
  564. g_free (p);
  565. }
  566. /* --------------------------------------------------------------------------------------------- */
  567. /**
  568. * Perform tilde expansion if possible.
  569. *
  570. * @param directory pointer to the path
  571. *
  572. * @return newly allocated string, even if it's unchanged.
  573. */
  574. char *
  575. tilde_expand (const char *directory)
  576. {
  577. struct passwd *passwd;
  578. const char *p, *q;
  579. if (*directory != '~')
  580. return g_strdup (directory);
  581. p = directory + 1;
  582. /* d = "~" or d = "~/" */
  583. if (*p == '\0' || IS_PATH_SEP (*p))
  584. {
  585. passwd = getpwuid (geteuid ());
  586. q = IS_PATH_SEP (*p) ? p + 1 : "";
  587. }
  588. else
  589. {
  590. q = strchr (p, PATH_SEP);
  591. if (q == NULL)
  592. passwd = getpwnam (p);
  593. else
  594. {
  595. char *name;
  596. name = g_strndup (p, q - p);
  597. passwd = getpwnam (name);
  598. q++;
  599. g_free (name);
  600. }
  601. }
  602. /* If we can't figure the user name, leave tilde unexpanded */
  603. if (passwd == NULL)
  604. return g_strdup (directory);
  605. return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
  606. }
  607. /* --------------------------------------------------------------------------------------------- */
  608. /**
  609. * Canonicalize path.
  610. *
  611. * @param path path to file
  612. * @param flags canonicalization flags
  613. *
  614. * All modifications of @path are made in place.
  615. * Well formed UNC paths are modified only in the local part.
  616. */
  617. void
  618. canonicalize_pathname_custom (char *path, canon_path_flags_t flags)
  619. {
  620. char *p, *s;
  621. char *lpath = path; /* path without leading UNC part */
  622. const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
  623. /* Detect and preserve UNC paths: //server/... */
  624. if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
  625. {
  626. for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
  627. ;
  628. if (IS_PATH_SEP (p[0]) && p > path + 2)
  629. lpath = p;
  630. }
  631. if (lpath[0] == '\0' || lpath[1] == '\0')
  632. return;
  633. if ((flags & CANON_PATH_JOINSLASHES) != 0)
  634. {
  635. /* Collapse multiple slashes */
  636. for (p = lpath; *p != '\0'; p++)
  637. if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
  638. {
  639. s = p + 1;
  640. while (IS_PATH_SEP (*(++s)))
  641. ;
  642. str_move (p + 1, s);
  643. }
  644. /* Collapse "/./" -> "/" */
  645. for (p = lpath; *p != '\0';)
  646. if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
  647. str_move (p, p + 2);
  648. else
  649. p++;
  650. }
  651. if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
  652. {
  653. size_t len;
  654. /* Remove trailing slashes */
  655. for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
  656. {
  657. if (p >= lpath + url_delim_len - 1
  658. && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  659. break;
  660. *p = '\0';
  661. }
  662. /* Remove leading "./" */
  663. if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
  664. {
  665. if (lpath[2] == '\0')
  666. {
  667. lpath[1] = '\0';
  668. return;
  669. }
  670. str_move (lpath, lpath + 2);
  671. }
  672. /* Remove trailing "/" or "/." */
  673. len = strlen (lpath);
  674. if (len < 2)
  675. return;
  676. if (IS_PATH_SEP (lpath[len - 1])
  677. && (len < url_delim_len
  678. || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
  679. url_delim_len) != 0))
  680. lpath[len - 1] = '\0';
  681. else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
  682. {
  683. if (len == 2)
  684. {
  685. lpath[1] = '\0';
  686. return;
  687. }
  688. lpath[len - 2] = '\0';
  689. }
  690. }
  691. /* Collapse "/.." with the previous part of path */
  692. if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
  693. {
  694. #ifdef HAVE_CHARSET
  695. const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
  696. #endif /* HAVE_CHARSET */
  697. for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
  698. {
  699. if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
  700. || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
  701. {
  702. p++;
  703. continue;
  704. }
  705. /* search for the previous token */
  706. s = p - 1;
  707. if (s >= lpath + url_delim_len - 2
  708. && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  709. {
  710. s -= (url_delim_len - 2);
  711. while (s >= lpath && !IS_PATH_SEP (*s--))
  712. ;
  713. }
  714. while (s >= lpath)
  715. {
  716. if (s - url_delim_len > lpath
  717. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  718. {
  719. char *vfs_prefix = s - url_delim_len;
  720. vfs_class *vclass;
  721. while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
  722. ;
  723. if (IS_PATH_SEP (*vfs_prefix))
  724. vfs_prefix++;
  725. *(s - url_delim_len) = '\0';
  726. vclass = vfs_prefix_to_class (vfs_prefix);
  727. *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
  728. if (vclass != NULL && (vclass->flags & VFSF_REMOTE) != 0)
  729. {
  730. s = vfs_prefix;
  731. continue;
  732. }
  733. }
  734. if (IS_PATH_SEP (*s))
  735. break;
  736. s--;
  737. }
  738. s++;
  739. /* If the previous token is "..", we cannot collapse it */
  740. if (s[0] == '.' && s[1] == '.' && s + 2 == p)
  741. {
  742. p += 3;
  743. continue;
  744. }
  745. if (p[3] != '\0')
  746. {
  747. if (s == lpath && IS_PATH_SEP (*s))
  748. {
  749. /* "/../foo" -> "/foo" */
  750. str_move (s + 1, p + 4);
  751. }
  752. else
  753. {
  754. /* "token/../foo" -> "foo" */
  755. #ifdef HAVE_CHARSET
  756. if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  757. && (is_supported_encoding (s + enc_prefix_len)))
  758. /* special case: remove encoding */
  759. str_move (s, p + 1);
  760. else
  761. #endif /* HAVE_CHARSET */
  762. str_move (s, p + 4);
  763. }
  764. p = s > lpath ? s - 1 : s;
  765. continue;
  766. }
  767. /* trailing ".." */
  768. if (s == lpath)
  769. {
  770. /* "token/.." -> "." */
  771. if (!IS_PATH_SEP (lpath[0]))
  772. lpath[0] = '.';
  773. lpath[1] = '\0';
  774. }
  775. else
  776. {
  777. /* "foo/token/.." -> "foo" */
  778. if (s == lpath + 1)
  779. s[0] = '\0';
  780. #ifdef HAVE_CHARSET
  781. else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  782. && (is_supported_encoding (s + enc_prefix_len)))
  783. {
  784. /* special case: remove encoding */
  785. s[0] = '.';
  786. s[1] = '.';
  787. s[2] = '\0';
  788. /* search for the previous token */
  789. /* IS_PATH_SEP (s[-1]) */
  790. for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
  791. ;
  792. if (p >= lpath)
  793. continue;
  794. }
  795. #endif /* HAVE_CHARSET */
  796. else
  797. {
  798. if (s >= lpath + url_delim_len
  799. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  800. *s = '\0';
  801. else
  802. s[-1] = '\0';
  803. }
  804. }
  805. break;
  806. }
  807. }
  808. }
  809. /* --------------------------------------------------------------------------------------------- */
  810. char *
  811. mc_realpath (const char *path, char *resolved_path)
  812. {
  813. #ifdef HAVE_CHARSET
  814. const char *p = path;
  815. gboolean absolute_path = FALSE;
  816. if (IS_PATH_SEP (*p))
  817. {
  818. absolute_path = TRUE;
  819. p++;
  820. }
  821. /* ignore encoding: skip "#enc:" */
  822. if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
  823. {
  824. p += strlen (VFS_ENCODING_PREFIX);
  825. p = strchr (p, PATH_SEP);
  826. if (p != NULL)
  827. {
  828. if (!absolute_path && p[1] != '\0')
  829. p++;
  830. path = p;
  831. }
  832. }
  833. #endif /* HAVE_CHARSET */
  834. #ifdef HAVE_REALPATH
  835. return realpath (path, resolved_path);
  836. #else
  837. {
  838. char copy_path[PATH_MAX];
  839. char got_path[PATH_MAX];
  840. char *new_path = got_path;
  841. char *max_path;
  842. #ifdef S_IFLNK
  843. char link_path[PATH_MAX];
  844. int readlinks = 0;
  845. int n;
  846. #endif /* S_IFLNK */
  847. /* Make a copy of the source path since we may need to modify it. */
  848. if (strlen (path) >= PATH_MAX - 2)
  849. {
  850. errno = ENAMETOOLONG;
  851. return NULL;
  852. }
  853. strcpy (copy_path, path);
  854. path = copy_path;
  855. max_path = copy_path + PATH_MAX - 2;
  856. /* If it's a relative pathname use getwd for starters. */
  857. if (!IS_PATH_SEP (*path))
  858. {
  859. new_path = g_get_current_dir ();
  860. if (new_path == NULL)
  861. strcpy (got_path, "");
  862. else
  863. {
  864. g_snprintf (got_path, sizeof (got_path), "%s", new_path);
  865. g_free (new_path);
  866. new_path = got_path;
  867. }
  868. new_path += strlen (got_path);
  869. if (!IS_PATH_SEP (new_path[-1]))
  870. *new_path++ = PATH_SEP;
  871. }
  872. else
  873. {
  874. *new_path++ = PATH_SEP;
  875. path++;
  876. }
  877. /* Expand each slash-separated pathname component. */
  878. while (*path != '\0')
  879. {
  880. /* Ignore stray "/". */
  881. if (IS_PATH_SEP (*path))
  882. {
  883. path++;
  884. continue;
  885. }
  886. if (*path == '.')
  887. {
  888. /* Ignore ".". */
  889. if (path[1] == '\0' || IS_PATH_SEP (path[1]))
  890. {
  891. path++;
  892. continue;
  893. }
  894. if (path[1] == '.')
  895. {
  896. if (path[2] == '\0' || IS_PATH_SEP (path[2]))
  897. {
  898. path += 2;
  899. /* Ignore ".." at root. */
  900. if (new_path == got_path + 1)
  901. continue;
  902. /* Handle ".." by backing up. */
  903. while (!IS_PATH_SEP ((--new_path)[-1]))
  904. ;
  905. continue;
  906. }
  907. }
  908. }
  909. /* Safely copy the next pathname component. */
  910. while (*path != '\0' && !IS_PATH_SEP (*path))
  911. {
  912. if (path > max_path)
  913. {
  914. errno = ENAMETOOLONG;
  915. return NULL;
  916. }
  917. *new_path++ = *path++;
  918. }
  919. #ifdef S_IFLNK
  920. /* Protect against infinite loops. */
  921. if (readlinks++ > MAXSYMLINKS)
  922. {
  923. errno = ELOOP;
  924. return NULL;
  925. }
  926. /* See if latest pathname component is a symlink. */
  927. *new_path = '\0';
  928. n = readlink (got_path, link_path, PATH_MAX - 1);
  929. if (n < 0)
  930. {
  931. /* EINVAL means the file exists but isn't a symlink. */
  932. if (errno != EINVAL)
  933. {
  934. /* Make sure it's null terminated. */
  935. *new_path = '\0';
  936. strcpy (resolved_path, got_path);
  937. return NULL;
  938. }
  939. }
  940. else
  941. {
  942. /* Note: readlink doesn't add the null byte. */
  943. link_path[n] = '\0';
  944. if (IS_PATH_SEP (*link_path))
  945. /* Start over for an absolute symlink. */
  946. new_path = got_path;
  947. else
  948. /* Otherwise back up over this component. */
  949. while (!IS_PATH_SEP (*(--new_path)))
  950. ;
  951. /* Safe sex check. */
  952. if (strlen (path) + n >= PATH_MAX - 2)
  953. {
  954. errno = ENAMETOOLONG;
  955. return NULL;
  956. }
  957. /* Insert symlink contents into path. */
  958. strcat (link_path, path);
  959. strcpy (copy_path, link_path);
  960. path = copy_path;
  961. }
  962. #endif /* S_IFLNK */
  963. *new_path++ = PATH_SEP;
  964. }
  965. /* Delete trailing slash but don't whomp a lone slash. */
  966. if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
  967. new_path--;
  968. /* Make sure it's null terminated. */
  969. *new_path = '\0';
  970. strcpy (resolved_path, got_path);
  971. return resolved_path;
  972. }
  973. #endif /* HAVE_REALPATH */
  974. }
  975. /* --------------------------------------------------------------------------------------------- */
  976. /**
  977. * Return the index of the permissions triplet
  978. *
  979. */
  980. int
  981. get_user_permissions (struct stat *st)
  982. {
  983. static gboolean initialized = FALSE;
  984. static gid_t *groups;
  985. static int ngroups;
  986. static uid_t uid;
  987. int i;
  988. if (!initialized)
  989. {
  990. uid = geteuid ();
  991. ngroups = getgroups (0, NULL);
  992. if (ngroups == -1)
  993. ngroups = 0; /* ignore errors */
  994. /* allocate space for one element in addition to what
  995. * will be filled by getgroups(). */
  996. groups = g_new (gid_t, ngroups + 1);
  997. if (ngroups != 0)
  998. {
  999. ngroups = getgroups (ngroups, groups);
  1000. if (ngroups == -1)
  1001. ngroups = 0; /* ignore errors */
  1002. }
  1003. /* getgroups() may or may not return the effective group ID,
  1004. * so we always include it at the end of the list. */
  1005. groups[ngroups++] = getegid ();
  1006. initialized = TRUE;
  1007. }
  1008. if (st->st_uid == uid || uid == 0)
  1009. return 0;
  1010. for (i = 0; i < ngroups; i++)
  1011. if (st->st_gid == groups[i])
  1012. return 1;
  1013. return 2;
  1014. }
  1015. /* --------------------------------------------------------------------------------------------- */
  1016. /**
  1017. * Build filename from arguments.
  1018. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1019. */
  1020. char *
  1021. mc_build_filenamev (const char *first_element, va_list args)
  1022. {
  1023. gboolean absolute;
  1024. const char *element = first_element;
  1025. GString *path;
  1026. char *ret;
  1027. if (first_element == NULL)
  1028. return NULL;
  1029. absolute = IS_PATH_SEP (*first_element);
  1030. path = g_string_new (absolute ? PATH_SEP_STR : "");
  1031. do
  1032. {
  1033. if (*element == '\0')
  1034. element = va_arg (args, char *);
  1035. else
  1036. {
  1037. char *tmp_element;
  1038. const char *start;
  1039. tmp_element = g_strdup (element);
  1040. element = va_arg (args, char *);
  1041. canonicalize_pathname (tmp_element);
  1042. start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
  1043. g_string_append (path, start);
  1044. if (!IS_PATH_SEP (path->str[path->len - 1]) && element != NULL)
  1045. g_string_append_c (path, PATH_SEP);
  1046. g_free (tmp_element);
  1047. }
  1048. }
  1049. while (element != NULL);
  1050. ret = g_string_free (path, FALSE);
  1051. canonicalize_pathname (ret);
  1052. return ret;
  1053. }
  1054. /* --------------------------------------------------------------------------------------------- */
  1055. /**
  1056. * Build filename from arguments.
  1057. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1058. */
  1059. char *
  1060. mc_build_filename (const char *first_element, ...)
  1061. {
  1062. va_list args;
  1063. char *ret;
  1064. if (first_element == NULL)
  1065. return NULL;
  1066. va_start (args, first_element);
  1067. ret = mc_build_filenamev (first_element, args);
  1068. va_end (args);
  1069. return ret;
  1070. }
  1071. /* --------------------------------------------------------------------------------------------- */