utilunix.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  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
  288. * EXECUTE_AS_SHELL)
  289. * @return 0 if successful, -1 otherwise
  290. */
  291. int
  292. my_system (int flags, const char *shell, const char *command)
  293. {
  294. return my_systeml (flags, shell, command, NULL);
  295. }
  296. /* --------------------------------------------------------------------------------------------- */
  297. /**
  298. * Call external programs with various parameters number.
  299. *
  300. * @parameter flags addition conditions for running external programs.
  301. * @parameter shell shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  302. * Shell (or command) will be found in paths described in PATH variable
  303. * (if shell parameter doesn't begin from path delimiter)
  304. * @parameter ... Command for shell with addition parameters for shell
  305. * (or parameters for command, if flags contain EXECUTE_AS_SHELL).
  306. * Should be NULL terminated.
  307. * @return 0 if successful, -1 otherwise
  308. */
  309. int
  310. my_systeml (int flags, const char *shell, ...)
  311. {
  312. GPtrArray *args_array;
  313. int status = 0;
  314. va_list vargs;
  315. char *one_arg;
  316. args_array = g_ptr_array_new ();
  317. va_start (vargs, shell);
  318. while ((one_arg = va_arg (vargs, char *)) != NULL)
  319. g_ptr_array_add (args_array, one_arg);
  320. va_end (vargs);
  321. g_ptr_array_add (args_array, NULL);
  322. status = my_systemv_flags (flags, shell, (char *const *) args_array->pdata);
  323. g_ptr_array_free (args_array, TRUE);
  324. return status;
  325. }
  326. /* --------------------------------------------------------------------------------------------- */
  327. /**
  328. * Call external programs with array of strings as parameters.
  329. *
  330. * @parameter command command to run. Command will be found in paths described in PATH variable
  331. * (if command parameter doesn't begin from path delimiter)
  332. * @parameter argv Array of strings (NULL-terminated) with parameters for command
  333. * @return 0 if successful, -1 otherwise
  334. */
  335. int
  336. my_systemv (const char *command, char *const argv[])
  337. {
  338. my_fork_state_t fork_state;
  339. int status = 0;
  340. my_system_sigactions_t sigactions;
  341. my_system__save_sigaction_handlers (&sigactions);
  342. fork_state = my_fork ();
  343. switch (fork_state)
  344. {
  345. case FORK_ERROR:
  346. status = -1;
  347. break;
  348. case FORK_CHILD:
  349. {
  350. signal (SIGINT, SIG_DFL);
  351. signal (SIGQUIT, SIG_DFL);
  352. signal (SIGTSTP, SIG_DFL);
  353. signal (SIGCHLD, SIG_DFL);
  354. execvp (command, argv);
  355. my_exit (127); /* Exec error */
  356. }
  357. MC_FALLTHROUGH;
  358. /* no break here, or unreachable-code warning by no returning my_exit() */
  359. default:
  360. status = 0;
  361. break;
  362. }
  363. my_system__restore_sigaction_handlers (&sigactions);
  364. return status;
  365. }
  366. /* --------------------------------------------------------------------------------------------- */
  367. /**
  368. * Call external programs with flags and with array of strings as parameters.
  369. *
  370. * @parameter flags addition conditions for running external programs.
  371. * @parameter command shell (if flags contain EXECUTE_AS_SHELL), command to run otherwise.
  372. * Shell (or command) will be found in paths described in PATH variable
  373. * (if shell parameter doesn't begin from path delimiter)
  374. * @parameter argv Array of strings (NULL-terminated) with parameters for command
  375. * @return 0 if successful, -1 otherwise
  376. */
  377. int
  378. my_systemv_flags (int flags, const char *command, char *const argv[])
  379. {
  380. const char *execute_name;
  381. GPtrArray *args_array;
  382. int status = 0;
  383. args_array = my_system_make_arg_array (flags, command);
  384. execute_name = g_ptr_array_index (args_array, 0);
  385. for (; argv != NULL && *argv != NULL; argv++)
  386. g_ptr_array_add (args_array, *argv);
  387. g_ptr_array_add (args_array, NULL);
  388. status = my_systemv (execute_name, (char *const *) args_array->pdata);
  389. g_ptr_array_free (args_array, TRUE);
  390. return status;
  391. }
  392. /* --------------------------------------------------------------------------------------------- */
  393. /**
  394. * Create pipe and run child process.
  395. *
  396. * @parameter command command line of child process
  397. * @parameter read_out do or don't read the stdout of child process
  398. * @parameter read_err do or don't read the stderr of child process
  399. * @parameter error contains pointer to object to handle error code and message
  400. *
  401. * @return newly created object of mc_pipe_t class in success, NULL otherwise
  402. */
  403. mc_pipe_t *
  404. mc_popen (const char *command, gboolean read_out, gboolean read_err, GError **error)
  405. {
  406. mc_pipe_t *p;
  407. const char *const argv[] = { "/bin/sh", "sh", "-c", command, NULL };
  408. p = g_try_new (mc_pipe_t, 1);
  409. if (p == NULL)
  410. {
  411. mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE, "%s",
  412. _ ("Cannot create pipe descriptor"));
  413. goto ret_err;
  414. }
  415. p->out.fd = -1;
  416. p->err.fd = -1;
  417. if (!g_spawn_async_with_pipes (NULL, (gchar **) argv, NULL,
  418. G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_FILE_AND_ARGV_ZERO, NULL,
  419. NULL, &p->child_pid, NULL, read_out ? &p->out.fd : NULL,
  420. read_err ? &p->err.fd : NULL, error))
  421. {
  422. mc_replace_error (error, MC_PIPE_ERROR_CREATE_PIPE_STREAM, "%s",
  423. _ ("Cannot create pipe streams"));
  424. goto ret_err;
  425. }
  426. p->out.buf[0] = '\0';
  427. p->out.len = MC_PIPE_BUFSIZE;
  428. p->out.null_term = FALSE;
  429. p->err.buf[0] = '\0';
  430. p->err.len = MC_PIPE_BUFSIZE;
  431. p->err.null_term = FALSE;
  432. return p;
  433. ret_err:
  434. g_free (p);
  435. return NULL;
  436. }
  437. /* --------------------------------------------------------------------------------------------- */
  438. /**
  439. * Read stdout and stderr of pipe asynchronously.
  440. *
  441. * @parameter p pipe descriptor
  442. *
  443. * The lengths of read data contain in p->out.len and p->err.len.
  444. *
  445. * Before read, p->xxx.len is an input. It defines the number of data to read.
  446. * Should not be greater than MC_PIPE_BUFSIZE.
  447. *
  448. * After read, p->xxx.len is an output and contains the following:
  449. * p->xxx.len > 0: an actual length of read data stored in p->xxx.buf;
  450. * p->xxx.len == MC_PIPE_STREAM_EOF: EOF of stream p->xxx;
  451. * p->xxx.len == MC_PIPE_STREAM_UNREAD: stream p->xxx was not read;
  452. * p->xxx.len == MC_PIPE_ERROR_READ: reading error, and p->xxx.errno is set appropriately.
  453. *
  454. * @parameter error contains pointer to object to handle error code and message
  455. */
  456. void
  457. mc_pread (mc_pipe_t *p, GError **error)
  458. {
  459. gboolean read_out, read_err;
  460. fd_set fds;
  461. int maxfd = 0;
  462. int res;
  463. if (error != NULL)
  464. *error = NULL;
  465. read_out = p->out.fd >= 0;
  466. read_err = p->err.fd >= 0;
  467. if (!read_out && !read_err)
  468. {
  469. p->out.len = MC_PIPE_STREAM_UNREAD;
  470. p->err.len = MC_PIPE_STREAM_UNREAD;
  471. return;
  472. }
  473. FD_ZERO (&fds);
  474. if (read_out)
  475. {
  476. FD_SET (p->out.fd, &fds);
  477. maxfd = p->out.fd;
  478. }
  479. if (read_err)
  480. {
  481. FD_SET (p->err.fd, &fds);
  482. maxfd = MAX (maxfd, p->err.fd);
  483. }
  484. /* no timeout */
  485. res = select (maxfd + 1, &fds, NULL, NULL, NULL);
  486. if (res < 0 && errno != EINTR)
  487. {
  488. mc_propagate_error (
  489. error, MC_PIPE_ERROR_READ,
  490. _ ("Unexpected error in select() reading data from a child process:\n%s"),
  491. unix_error_string (errno));
  492. return;
  493. }
  494. if (read_out)
  495. mc_pread_stream (&p->out, &fds);
  496. else
  497. p->out.len = MC_PIPE_STREAM_UNREAD;
  498. if (read_err)
  499. mc_pread_stream (&p->err, &fds);
  500. else
  501. p->err.len = MC_PIPE_STREAM_UNREAD;
  502. }
  503. /* --------------------------------------------------------------------------------------------- */
  504. /**
  505. * Reads a line from @stream. Reading stops after an EOL or a newline. If a newline is read,
  506. * it is appended to the line.
  507. *
  508. * @stream mc_pipe_stream_t object
  509. *
  510. * @return newly created GString or NULL in case of EOL;
  511. */
  512. GString *
  513. mc_pstream_get_string (mc_pipe_stream_t *ps)
  514. {
  515. char *s;
  516. size_t size, i;
  517. gboolean escape = FALSE;
  518. g_return_val_if_fail (ps != NULL, NULL);
  519. if (ps->len < 0)
  520. return NULL;
  521. size = ps->len - ps->pos;
  522. if (size == 0)
  523. return NULL;
  524. s = ps->buf + ps->pos;
  525. if (s[0] == '\0')
  526. return NULL;
  527. /* find '\0' or unescaped '\n' */
  528. for (i = 0; i < size && !(s[i] == '\0' || (s[i] == '\n' && !escape)); i++)
  529. escape = s[i] == '\\' ? !escape : FALSE;
  530. if (i != size && s[i] == '\n')
  531. i++;
  532. ps->pos += i;
  533. return g_string_new_len (s, i);
  534. }
  535. /* --------------------------------------------------------------------------------------------- */
  536. /**
  537. * Close pipe and destroy pipe descriptor.
  538. *
  539. * @parameter p pipe descriptor
  540. * @parameter error contains pointer to object to handle error code and message
  541. */
  542. void
  543. mc_pclose (mc_pipe_t *p, GError **error)
  544. {
  545. int res;
  546. if (p == NULL)
  547. {
  548. mc_replace_error (error, MC_PIPE_ERROR_READ, "%s",
  549. _ ("Cannot close pipe descriptor (p == NULL)"));
  550. return;
  551. }
  552. if (p->out.fd >= 0)
  553. res = close (p->out.fd);
  554. if (p->err.fd >= 0)
  555. res = close (p->err.fd);
  556. do
  557. {
  558. int status;
  559. res = waitpid (p->child_pid, &status, 0);
  560. }
  561. while (res < 0 && errno == EINTR);
  562. if (res < 0)
  563. mc_replace_error (error, MC_PIPE_ERROR_READ, _ ("Unexpected error in waitpid():\n%s"),
  564. unix_error_string (errno));
  565. g_free (p);
  566. }
  567. /* --------------------------------------------------------------------------------------------- */
  568. /**
  569. * Perform tilde expansion if possible.
  570. *
  571. * @param directory pointer to the path
  572. *
  573. * @return newly allocated string, even if it's unchanged.
  574. */
  575. char *
  576. tilde_expand (const char *directory)
  577. {
  578. struct passwd *passwd;
  579. const char *p, *q;
  580. if (*directory != '~')
  581. return g_strdup (directory);
  582. p = directory + 1;
  583. /* d = "~" or d = "~/" */
  584. if (*p == '\0' || IS_PATH_SEP (*p))
  585. {
  586. passwd = getpwuid (geteuid ());
  587. q = IS_PATH_SEP (*p) ? p + 1 : "";
  588. }
  589. else
  590. {
  591. q = strchr (p, PATH_SEP);
  592. if (q == NULL)
  593. passwd = getpwnam (p);
  594. else
  595. {
  596. char *name;
  597. name = g_strndup (p, q - p);
  598. passwd = getpwnam (name);
  599. q++;
  600. g_free (name);
  601. }
  602. }
  603. /* If we can't figure the user name, leave tilde unexpanded */
  604. if (passwd == NULL)
  605. return g_strdup (directory);
  606. return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
  607. }
  608. /* --------------------------------------------------------------------------------------------- */
  609. /**
  610. * Canonicalize path.
  611. *
  612. * @param path path to file
  613. * @param flags canonicalization flags
  614. *
  615. * All modifications of @path are made in place.
  616. * Well formed UNC paths are modified only in the local part.
  617. */
  618. void
  619. canonicalize_pathname_custom (char *path, canon_path_flags_t flags)
  620. {
  621. char *p, *s;
  622. char *lpath = path; /* path without leading UNC part */
  623. const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
  624. /* Detect and preserve UNC paths: //server/... */
  625. if ((flags & CANON_PATH_GUARDUNC) != 0 && IS_PATH_SEP (path[0]) && IS_PATH_SEP (path[1]))
  626. {
  627. for (p = path + 2; p[0] != '\0' && !IS_PATH_SEP (p[0]); p++)
  628. ;
  629. if (IS_PATH_SEP (p[0]) && p > path + 2)
  630. lpath = p;
  631. }
  632. if (lpath[0] == '\0' || lpath[1] == '\0')
  633. return;
  634. if ((flags & CANON_PATH_JOINSLASHES) != 0)
  635. {
  636. /* Collapse multiple slashes */
  637. for (p = lpath; *p != '\0'; p++)
  638. if (IS_PATH_SEP (p[0]) && IS_PATH_SEP (p[1]) && (p == lpath || *(p - 1) != ':'))
  639. {
  640. s = p + 1;
  641. while (IS_PATH_SEP (*(++s)))
  642. ;
  643. str_move (p + 1, s);
  644. }
  645. /* Collapse "/./" -> "/" */
  646. for (p = lpath; *p != '\0';)
  647. if (IS_PATH_SEP (p[0]) && p[1] == '.' && IS_PATH_SEP (p[2]))
  648. str_move (p, p + 2);
  649. else
  650. p++;
  651. }
  652. if ((flags & CANON_PATH_REMSLASHDOTS) != 0)
  653. {
  654. size_t len;
  655. /* Remove trailing slashes */
  656. for (p = lpath + strlen (lpath) - 1; p > lpath && IS_PATH_SEP (*p); p--)
  657. {
  658. if (p >= lpath + url_delim_len - 1
  659. && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  660. break;
  661. *p = '\0';
  662. }
  663. /* Remove leading "./" */
  664. if (lpath[0] == '.' && IS_PATH_SEP (lpath[1]))
  665. {
  666. if (lpath[2] == '\0')
  667. {
  668. lpath[1] = '\0';
  669. return;
  670. }
  671. str_move (lpath, lpath + 2);
  672. }
  673. /* Remove trailing "/" or "/." */
  674. len = strlen (lpath);
  675. if (len < 2)
  676. return;
  677. if (IS_PATH_SEP (lpath[len - 1])
  678. && (len < url_delim_len
  679. || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len)
  680. != 0))
  681. lpath[len - 1] = '\0';
  682. else if (lpath[len - 1] == '.' && IS_PATH_SEP (lpath[len - 2]))
  683. {
  684. if (len == 2)
  685. {
  686. lpath[1] = '\0';
  687. return;
  688. }
  689. lpath[len - 2] = '\0';
  690. }
  691. }
  692. /* Collapse "/.." with the previous part of path */
  693. if ((flags & CANON_PATH_REMDOUBLEDOTS) != 0)
  694. {
  695. #ifdef HAVE_CHARSET
  696. const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
  697. #endif /* HAVE_CHARSET */
  698. for (p = lpath; p[0] != '\0' && p[1] != '\0' && p[2] != '\0';)
  699. {
  700. if (!IS_PATH_SEP (p[0]) || p[1] != '.' || p[2] != '.'
  701. || (!IS_PATH_SEP (p[3]) && p[3] != '\0'))
  702. {
  703. p++;
  704. continue;
  705. }
  706. /* search for the previous token */
  707. s = p - 1;
  708. if (s >= lpath + url_delim_len - 2
  709. && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  710. {
  711. s -= (url_delim_len - 2);
  712. while (s >= lpath && !IS_PATH_SEP (*s--))
  713. ;
  714. }
  715. while (s >= lpath)
  716. {
  717. if (s - url_delim_len > lpath
  718. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  719. {
  720. char *vfs_prefix = s - url_delim_len;
  721. vfs_class *vclass;
  722. while (vfs_prefix > lpath && !IS_PATH_SEP (*--vfs_prefix))
  723. ;
  724. if (IS_PATH_SEP (*vfs_prefix))
  725. vfs_prefix++;
  726. *(s - url_delim_len) = '\0';
  727. vclass = vfs_prefix_to_class (vfs_prefix);
  728. *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
  729. if (vclass != NULL && (vclass->flags & VFSF_REMOTE) != 0)
  730. {
  731. s = vfs_prefix;
  732. continue;
  733. }
  734. }
  735. if (IS_PATH_SEP (*s))
  736. break;
  737. s--;
  738. }
  739. s++;
  740. /* If the previous token is "..", we cannot collapse it */
  741. if (s[0] == '.' && s[1] == '.' && s + 2 == p)
  742. {
  743. p += 3;
  744. continue;
  745. }
  746. if (p[3] != '\0')
  747. {
  748. if (s == lpath && IS_PATH_SEP (*s))
  749. {
  750. /* "/../foo" -> "/foo" */
  751. str_move (s + 1, p + 4);
  752. }
  753. else
  754. {
  755. /* "token/../foo" -> "foo" */
  756. #ifdef HAVE_CHARSET
  757. if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  758. && (is_supported_encoding (s + enc_prefix_len)))
  759. /* special case: remove encoding */
  760. str_move (s, p + 1);
  761. else
  762. #endif /* HAVE_CHARSET */
  763. str_move (s, p + 4);
  764. }
  765. p = s > lpath ? s - 1 : s;
  766. continue;
  767. }
  768. /* trailing ".." */
  769. if (s == lpath)
  770. {
  771. /* "token/.." -> "." */
  772. if (!IS_PATH_SEP (lpath[0]))
  773. lpath[0] = '.';
  774. lpath[1] = '\0';
  775. }
  776. else
  777. {
  778. /* "foo/token/.." -> "foo" */
  779. if (s == lpath + 1)
  780. s[0] = '\0';
  781. #ifdef HAVE_CHARSET
  782. else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  783. && (is_supported_encoding (s + enc_prefix_len)))
  784. {
  785. /* special case: remove encoding */
  786. s[0] = '.';
  787. s[1] = '.';
  788. s[2] = '\0';
  789. /* search for the previous token */
  790. /* IS_PATH_SEP (s[-1]) */
  791. for (p = s - 1; p >= lpath && !IS_PATH_SEP (*p); p--)
  792. ;
  793. if (p >= lpath)
  794. continue;
  795. }
  796. #endif /* HAVE_CHARSET */
  797. else
  798. {
  799. if (s >= lpath + url_delim_len
  800. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  801. *s = '\0';
  802. else
  803. s[-1] = '\0';
  804. }
  805. }
  806. break;
  807. }
  808. }
  809. }
  810. /* --------------------------------------------------------------------------------------------- */
  811. char *
  812. mc_realpath (const char *path, char *resolved_path)
  813. {
  814. #ifdef HAVE_CHARSET
  815. const char *p = path;
  816. gboolean absolute_path = FALSE;
  817. if (IS_PATH_SEP (*p))
  818. {
  819. absolute_path = TRUE;
  820. p++;
  821. }
  822. /* ignore encoding: skip "#enc:" */
  823. if (g_str_has_prefix (p, VFS_ENCODING_PREFIX))
  824. {
  825. p += strlen (VFS_ENCODING_PREFIX);
  826. p = strchr (p, PATH_SEP);
  827. if (p != NULL)
  828. {
  829. if (!absolute_path && p[1] != '\0')
  830. p++;
  831. path = p;
  832. }
  833. }
  834. #endif /* HAVE_CHARSET */
  835. #ifdef HAVE_REALPATH
  836. return realpath (path, resolved_path);
  837. #else
  838. {
  839. char copy_path[PATH_MAX];
  840. char got_path[PATH_MAX];
  841. char *new_path = got_path;
  842. char *max_path;
  843. #ifdef S_IFLNK
  844. char link_path[PATH_MAX];
  845. int readlinks = 0;
  846. int n;
  847. #endif /* S_IFLNK */
  848. /* Make a copy of the source path since we may need to modify it. */
  849. if (strlen (path) >= PATH_MAX - 2)
  850. {
  851. errno = ENAMETOOLONG;
  852. return NULL;
  853. }
  854. strcpy (copy_path, path);
  855. path = copy_path;
  856. max_path = copy_path + PATH_MAX - 2;
  857. /* If it's a relative pathname use getwd for starters. */
  858. if (!IS_PATH_SEP (*path))
  859. {
  860. new_path = g_get_current_dir ();
  861. if (new_path == NULL)
  862. strcpy (got_path, "");
  863. else
  864. {
  865. g_snprintf (got_path, sizeof (got_path), "%s", new_path);
  866. g_free (new_path);
  867. new_path = got_path;
  868. }
  869. new_path += strlen (got_path);
  870. if (!IS_PATH_SEP (new_path[-1]))
  871. *new_path++ = PATH_SEP;
  872. }
  873. else
  874. {
  875. *new_path++ = PATH_SEP;
  876. path++;
  877. }
  878. /* Expand each slash-separated pathname component. */
  879. while (*path != '\0')
  880. {
  881. /* Ignore stray "/". */
  882. if (IS_PATH_SEP (*path))
  883. {
  884. path++;
  885. continue;
  886. }
  887. if (*path == '.')
  888. {
  889. /* Ignore ".". */
  890. if (path[1] == '\0' || IS_PATH_SEP (path[1]))
  891. {
  892. path++;
  893. continue;
  894. }
  895. if (path[1] == '.')
  896. {
  897. if (path[2] == '\0' || IS_PATH_SEP (path[2]))
  898. {
  899. path += 2;
  900. /* Ignore ".." at root. */
  901. if (new_path == got_path + 1)
  902. continue;
  903. /* Handle ".." by backing up. */
  904. while (!IS_PATH_SEP ((--new_path)[-1]))
  905. ;
  906. continue;
  907. }
  908. }
  909. }
  910. /* Safely copy the next pathname component. */
  911. while (*path != '\0' && !IS_PATH_SEP (*path))
  912. {
  913. if (path > max_path)
  914. {
  915. errno = ENAMETOOLONG;
  916. return NULL;
  917. }
  918. *new_path++ = *path++;
  919. }
  920. #ifdef S_IFLNK
  921. /* Protect against infinite loops. */
  922. if (readlinks++ > MAXSYMLINKS)
  923. {
  924. errno = ELOOP;
  925. return NULL;
  926. }
  927. /* See if latest pathname component is a symlink. */
  928. *new_path = '\0';
  929. n = readlink (got_path, link_path, PATH_MAX - 1);
  930. if (n < 0)
  931. {
  932. /* EINVAL means the file exists but isn't a symlink. */
  933. if (errno != EINVAL)
  934. {
  935. /* Make sure it's null terminated. */
  936. *new_path = '\0';
  937. strcpy (resolved_path, got_path);
  938. return NULL;
  939. }
  940. }
  941. else
  942. {
  943. /* Note: readlink doesn't add the null byte. */
  944. link_path[n] = '\0';
  945. if (IS_PATH_SEP (*link_path))
  946. /* Start over for an absolute symlink. */
  947. new_path = got_path;
  948. else
  949. /* Otherwise back up over this component. */
  950. while (!IS_PATH_SEP (*(--new_path)))
  951. ;
  952. /* Safe sex check. */
  953. if (strlen (path) + n >= PATH_MAX - 2)
  954. {
  955. errno = ENAMETOOLONG;
  956. return NULL;
  957. }
  958. /* Insert symlink contents into path. */
  959. strcat (link_path, path);
  960. strcpy (copy_path, link_path);
  961. path = copy_path;
  962. }
  963. #endif /* S_IFLNK */
  964. *new_path++ = PATH_SEP;
  965. }
  966. /* Delete trailing slash but don't whomp a lone slash. */
  967. if (new_path != got_path + 1 && IS_PATH_SEP (new_path[-1]))
  968. new_path--;
  969. /* Make sure it's null terminated. */
  970. *new_path = '\0';
  971. strcpy (resolved_path, got_path);
  972. return resolved_path;
  973. }
  974. #endif /* HAVE_REALPATH */
  975. }
  976. /* --------------------------------------------------------------------------------------------- */
  977. /**
  978. * Return the index of the permissions triplet
  979. *
  980. */
  981. int
  982. get_user_permissions (struct stat *st)
  983. {
  984. static gboolean initialized = FALSE;
  985. static gid_t *groups;
  986. static int ngroups;
  987. static uid_t uid;
  988. int i;
  989. if (!initialized)
  990. {
  991. uid = geteuid ();
  992. ngroups = getgroups (0, NULL);
  993. if (ngroups == -1)
  994. ngroups = 0; /* ignore errors */
  995. /* allocate space for one element in addition to what
  996. * will be filled by getgroups(). */
  997. groups = g_new (gid_t, ngroups + 1);
  998. if (ngroups != 0)
  999. {
  1000. ngroups = getgroups (ngroups, groups);
  1001. if (ngroups == -1)
  1002. ngroups = 0; /* ignore errors */
  1003. }
  1004. /* getgroups() may or may not return the effective group ID,
  1005. * so we always include it at the end of the list. */
  1006. groups[ngroups++] = getegid ();
  1007. initialized = TRUE;
  1008. }
  1009. if (st->st_uid == uid || uid == 0)
  1010. return 0;
  1011. for (i = 0; i < ngroups; i++)
  1012. if (st->st_gid == groups[i])
  1013. return 1;
  1014. return 2;
  1015. }
  1016. /* --------------------------------------------------------------------------------------------- */
  1017. /**
  1018. * Build filename from arguments.
  1019. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1020. */
  1021. char *
  1022. mc_build_filenamev (const char *first_element, va_list args)
  1023. {
  1024. gboolean absolute;
  1025. const char *element = first_element;
  1026. GString *path;
  1027. char *ret;
  1028. if (first_element == NULL)
  1029. return NULL;
  1030. absolute = IS_PATH_SEP (*first_element);
  1031. path = g_string_new (absolute ? PATH_SEP_STR : "");
  1032. do
  1033. {
  1034. if (*element == '\0')
  1035. element = va_arg (args, char *);
  1036. else
  1037. {
  1038. char *tmp_element;
  1039. const char *start;
  1040. tmp_element = g_strdup (element);
  1041. element = va_arg (args, char *);
  1042. canonicalize_pathname (tmp_element);
  1043. start = IS_PATH_SEP (tmp_element[0]) ? tmp_element + 1 : tmp_element;
  1044. g_string_append (path, start);
  1045. if (!IS_PATH_SEP (path->str[path->len - 1]) && element != NULL)
  1046. g_string_append_c (path, PATH_SEP);
  1047. g_free (tmp_element);
  1048. }
  1049. }
  1050. while (element != NULL);
  1051. ret = g_string_free (path, FALSE);
  1052. canonicalize_pathname (ret);
  1053. return ret;
  1054. }
  1055. /* --------------------------------------------------------------------------------------------- */
  1056. /**
  1057. * Build filename from arguments.
  1058. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  1059. */
  1060. char *
  1061. mc_build_filename (const char *first_element, ...)
  1062. {
  1063. va_list args;
  1064. char *ret;
  1065. if (first_element == NULL)
  1066. return NULL;
  1067. va_start (args, first_element);
  1068. ret = mc_build_filenamev (first_element, args);
  1069. va_end (args);
  1070. return ret;
  1071. }
  1072. /* --------------------------------------------------------------------------------------------- */