utilunix.c 38 KB

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