utilunix.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. /*
  2. Various utilities - Unix variants
  3. Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
  4. 2004, 2005, 2007, 2011
  5. The Free Software Foundation, Inc.
  6. Written by:
  7. Miguel de Icaza, 1994, 1995, 1996
  8. Janne Kukonlehto, 1994, 1995, 1996
  9. Dugan Porter, 1994, 1995, 1996
  10. Jakub Jelinek, 1994, 1995, 1996
  11. Mauricio Plaza, 1994, 1995, 1996
  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. #include <fcntl.h>
  39. #ifdef HAVE_SYS_PARAM_H
  40. #include <sys/param.h>
  41. #endif
  42. #include <sys/types.h>
  43. #include <sys/stat.h>
  44. #include <sys/wait.h>
  45. #ifdef HAVE_SYS_IOCTL_H
  46. #include <sys/ioctl.h>
  47. #endif
  48. #ifdef HAVE_GET_PROCESS_STATS
  49. #include <sys/procstats.h>
  50. #endif
  51. #include <unistd.h>
  52. #include <pwd.h>
  53. #include <grp.h>
  54. #include "lib/global.h"
  55. #include "lib/vfs/vfs.h" /* VFS_ENCODING_PREFIX */
  56. #include "lib/strutil.h" /* str_move() */
  57. #include "lib/util.h"
  58. #include "lib/widget.h" /* message() */
  59. #include "lib/vfs/xdirentry.h"
  60. #ifdef HAVE_CHARSET
  61. #include "lib/charsets.h"
  62. #endif
  63. #include "utilunix.h"
  64. /*** global variables ****************************************************************************/
  65. struct sigaction startup_handler;
  66. /*** file scope macro definitions ****************************************************************/
  67. #define UID_CACHE_SIZE 200
  68. #define GID_CACHE_SIZE 30
  69. /* Pipes are guaranteed to be able to hold at least 4096 bytes */
  70. /* More than that would be unportable */
  71. #define MAX_PIPE_SIZE 4096
  72. /*** file scope type declarations ****************************************************************/
  73. typedef struct
  74. {
  75. int index;
  76. char *string;
  77. } int_cache;
  78. /*** file scope variables ************************************************************************/
  79. static int_cache uid_cache[UID_CACHE_SIZE];
  80. static int_cache gid_cache[GID_CACHE_SIZE];
  81. static int error_pipe[2]; /* File descriptors of error pipe */
  82. static int old_error; /* File descriptor of old standard error */
  83. /*** file scope functions ************************************************************************/
  84. /* --------------------------------------------------------------------------------------------- */
  85. static char *
  86. i_cache_match (int id, int_cache * cache, int size)
  87. {
  88. int i;
  89. for (i = 0; i < size; i++)
  90. if (cache[i].index == id)
  91. return cache[i].string;
  92. return 0;
  93. }
  94. /* --------------------------------------------------------------------------------------------- */
  95. static void
  96. i_cache_add (int id, int_cache * cache, int size, char *text, int *last)
  97. {
  98. g_free (cache[*last].string);
  99. cache[*last].string = g_strdup (text);
  100. cache[*last].index = id;
  101. *last = ((*last) + 1) % size;
  102. }
  103. /* --------------------------------------------------------------------------------------------- */
  104. /*** public functions ****************************************************************************/
  105. /* --------------------------------------------------------------------------------------------- */
  106. char *
  107. get_owner (int uid)
  108. {
  109. struct passwd *pwd;
  110. static char ibuf[10];
  111. char *name;
  112. static int uid_last;
  113. name = i_cache_match (uid, uid_cache, UID_CACHE_SIZE);
  114. if (name != NULL)
  115. return name;
  116. pwd = getpwuid (uid);
  117. if (pwd != NULL)
  118. {
  119. i_cache_add (uid, uid_cache, UID_CACHE_SIZE, pwd->pw_name, &uid_last);
  120. return pwd->pw_name;
  121. }
  122. else
  123. {
  124. g_snprintf (ibuf, sizeof (ibuf), "%d", uid);
  125. return ibuf;
  126. }
  127. }
  128. /* --------------------------------------------------------------------------------------------- */
  129. char *
  130. get_group (int gid)
  131. {
  132. struct group *grp;
  133. static char gbuf[10];
  134. char *name;
  135. static int gid_last;
  136. name = i_cache_match (gid, gid_cache, GID_CACHE_SIZE);
  137. if (name != NULL)
  138. return name;
  139. grp = getgrgid (gid);
  140. if (grp != NULL)
  141. {
  142. i_cache_add (gid, gid_cache, GID_CACHE_SIZE, grp->gr_name, &gid_last);
  143. return grp->gr_name;
  144. }
  145. else
  146. {
  147. g_snprintf (gbuf, sizeof (gbuf), "%d", gid);
  148. return gbuf;
  149. }
  150. }
  151. /* --------------------------------------------------------------------------------------------- */
  152. /* Since ncurses uses a handler that automatically refreshes the */
  153. /* screen after a SIGCONT, and we don't want this behavior when */
  154. /* spawning a child, we save the original handler here */
  155. void
  156. save_stop_handler (void)
  157. {
  158. sigaction (SIGTSTP, NULL, &startup_handler);
  159. }
  160. /* --------------------------------------------------------------------------------------------- */
  161. int
  162. my_system (int flags, const char *shell, const char *command)
  163. {
  164. struct sigaction ignore, save_intr, save_quit, save_stop;
  165. pid_t pid;
  166. int status = 0;
  167. ignore.sa_handler = SIG_IGN;
  168. sigemptyset (&ignore.sa_mask);
  169. ignore.sa_flags = 0;
  170. sigaction (SIGINT, &ignore, &save_intr);
  171. sigaction (SIGQUIT, &ignore, &save_quit);
  172. /* Restore the original SIGTSTP handler, we don't want ncurses' */
  173. /* handler messing the screen after the SIGCONT */
  174. sigaction (SIGTSTP, &startup_handler, &save_stop);
  175. pid = fork ();
  176. if (pid < 0)
  177. {
  178. fprintf (stderr, "\n\nfork () = -1\n");
  179. status = -1;
  180. }
  181. else if (pid == 0)
  182. {
  183. signal (SIGINT, SIG_DFL);
  184. signal (SIGQUIT, SIG_DFL);
  185. signal (SIGTSTP, SIG_DFL);
  186. signal (SIGCHLD, SIG_DFL);
  187. if (flags & EXECUTE_AS_SHELL)
  188. execl (shell, shell, "-c", command, (char *) NULL);
  189. else
  190. {
  191. gchar **shell_tokens;
  192. const gchar *only_cmd;
  193. shell_tokens = g_strsplit (shell, " ", 2);
  194. if (shell_tokens == NULL)
  195. only_cmd = shell;
  196. else
  197. only_cmd = (*shell_tokens != NULL) ? *shell_tokens : shell;
  198. execlp (only_cmd, shell, command, (char *) NULL);
  199. /*
  200. execlp will replace current process,
  201. therefore no sence in call of g_strfreev().
  202. But this keeped for estetic reason :)
  203. */
  204. g_strfreev (shell_tokens);
  205. }
  206. _exit (127); /* Exec error */
  207. }
  208. else
  209. {
  210. while (TRUE)
  211. {
  212. if (waitpid (pid, &status, 0) > 0)
  213. {
  214. status = WEXITSTATUS (status);
  215. break;
  216. }
  217. if (errno != EINTR)
  218. {
  219. status = -1;
  220. break;
  221. }
  222. }
  223. }
  224. sigaction (SIGINT, &save_intr, NULL);
  225. sigaction (SIGQUIT, &save_quit, NULL);
  226. sigaction (SIGTSTP, &save_stop, NULL);
  227. return status;
  228. }
  229. /* --------------------------------------------------------------------------------------------- */
  230. /**
  231. * Perform tilde expansion if possible.
  232. *
  233. * @param directory pointer to the path
  234. *
  235. * @return newly allocated string, even if it's unchanged.
  236. */
  237. char *
  238. tilde_expand (const char *directory)
  239. {
  240. struct passwd *passwd;
  241. const char *p, *q;
  242. char *name;
  243. if (*directory != '~')
  244. return g_strdup (directory);
  245. p = directory + 1;
  246. /* d = "~" or d = "~/" */
  247. if (!(*p) || (*p == PATH_SEP))
  248. {
  249. passwd = getpwuid (geteuid ());
  250. q = (*p == PATH_SEP) ? p + 1 : "";
  251. }
  252. else
  253. {
  254. q = strchr (p, PATH_SEP);
  255. if (!q)
  256. {
  257. passwd = getpwnam (p);
  258. }
  259. else
  260. {
  261. name = g_strndup (p, q - p);
  262. passwd = getpwnam (name);
  263. q++;
  264. g_free (name);
  265. }
  266. }
  267. /* If we can't figure the user name, leave tilde unexpanded */
  268. if (!passwd)
  269. return g_strdup (directory);
  270. return g_strconcat (passwd->pw_dir, PATH_SEP_STR, q, (char *) NULL);
  271. }
  272. /* --------------------------------------------------------------------------------------------- */
  273. /**
  274. * Creates a pipe to hold standard error for a later analysis.
  275. * The pipe can hold 4096 bytes. Make sure no more is written
  276. * or a deadlock might occur.
  277. */
  278. void
  279. open_error_pipe (void)
  280. {
  281. if (pipe (error_pipe) < 0)
  282. {
  283. message (D_NORMAL, _("Warning"), _("Pipe failed"));
  284. }
  285. old_error = dup (2);
  286. if (old_error < 0 || close (2) || dup (error_pipe[1]) != 2)
  287. {
  288. message (D_NORMAL, _("Warning"), _("Dup failed"));
  289. close (error_pipe[0]);
  290. error_pipe[0] = -1;
  291. }
  292. else
  293. {
  294. /*
  295. * Settng stderr in nonblocking mode as we close it earlier, than
  296. * program stops. We try to read some error at program startup,
  297. * but we should not block on it.
  298. *
  299. * TODO: make piped stdin/stderr poll()/select()able to get rid
  300. * of following hack.
  301. */
  302. int fd_flags;
  303. fd_flags = fcntl (error_pipe[0], F_GETFL, NULL);
  304. if (fd_flags != -1)
  305. {
  306. fd_flags |= O_NONBLOCK;
  307. if (fcntl (error_pipe[0], F_SETFL, fd_flags) == -1)
  308. {
  309. /* TODO: handle it somehow */
  310. }
  311. }
  312. }
  313. /* we never write there */
  314. close (error_pipe[1]);
  315. error_pipe[1] = -1;
  316. }
  317. /* --------------------------------------------------------------------------------------------- */
  318. /**
  319. * Close a pipe
  320. *
  321. * @param error '-1' - ignore errors, '0' - display warning, '1' - display error
  322. * @param text is prepended to the error message from the pipe
  323. *
  324. * @return not 0 if an error was displayed
  325. */
  326. int
  327. close_error_pipe (int error, const char *text)
  328. {
  329. const char *title;
  330. char msg[MAX_PIPE_SIZE];
  331. int len = 0;
  332. /* already closed */
  333. if (error_pipe[0] == -1)
  334. return 0;
  335. if (error < 0 || (error > 0 && (error & D_ERROR) != 0))
  336. title = MSG_ERROR;
  337. else
  338. title = _("Warning");
  339. if (old_error >= 0)
  340. {
  341. if (dup2 (old_error, 2) == -1)
  342. {
  343. if (error < 0)
  344. error = D_ERROR;
  345. message (error, MSG_ERROR, _("Error dup'ing old error pipe"));
  346. return 1;
  347. }
  348. close (old_error);
  349. len = read (error_pipe[0], msg, MAX_PIPE_SIZE - 1);
  350. if (len >= 0)
  351. msg[len] = 0;
  352. close (error_pipe[0]);
  353. error_pipe[0] = -1;
  354. }
  355. if (error < 0)
  356. return 0; /* Just ignore error message */
  357. if (text == NULL)
  358. {
  359. if (len <= 0)
  360. return 0; /* Nothing to show */
  361. /* Show message from pipe */
  362. message (error, title, "%s", msg);
  363. }
  364. else
  365. {
  366. /* Show given text and possible message from pipe */
  367. message (error, title, "%s\n%s", text, msg);
  368. }
  369. return 1;
  370. }
  371. /* --------------------------------------------------------------------------------------------- */
  372. /**
  373. * Canonicalize path, and return a new path. Do everything in place.
  374. * The new path differs from path in:
  375. * Multiple `/'s are collapsed to a single `/'.
  376. * Leading `./'s and trailing `/.'s are removed.
  377. * Trailing `/'s are removed.
  378. * Non-leading `../'s and trailing `..'s are handled by removing
  379. * portions of the path.
  380. * Well formed UNC paths are modified only in the local part.
  381. */
  382. void
  383. custom_canonicalize_pathname (char *path, CANON_PATH_FLAGS flags)
  384. {
  385. char *p, *s;
  386. size_t len;
  387. char *lpath = path; /* path without leading UNC part */
  388. const size_t url_delim_len = strlen (VFS_PATH_URL_DELIMITER);
  389. /* Detect and preserve UNC paths: //server/... */
  390. if ((flags & CANON_PATH_GUARDUNC) && path[0] == PATH_SEP && path[1] == PATH_SEP)
  391. {
  392. p = path + 2;
  393. while (p[0] && p[0] != '/')
  394. p++;
  395. if (p[0] == '/' && p > path + 2)
  396. lpath = p;
  397. }
  398. if (!lpath[0] || !lpath[1])
  399. return;
  400. if (flags & CANON_PATH_JOINSLASHES)
  401. {
  402. /* Collapse multiple slashes */
  403. p = lpath;
  404. while (*p)
  405. {
  406. if (p[0] == PATH_SEP && p[1] == PATH_SEP && (p == lpath || *(p - 1) != ':'))
  407. {
  408. s = p + 1;
  409. while (*(++s) == PATH_SEP);
  410. str_move (p + 1, s);
  411. }
  412. p++;
  413. }
  414. }
  415. if (flags & CANON_PATH_JOINSLASHES)
  416. {
  417. /* Collapse "/./" -> "/" */
  418. p = lpath;
  419. while (*p)
  420. {
  421. if (p[0] == PATH_SEP && p[1] == '.' && p[2] == PATH_SEP)
  422. str_move (p, p + 2);
  423. else
  424. p++;
  425. }
  426. }
  427. if (flags & CANON_PATH_REMSLASHDOTS)
  428. {
  429. /* Remove trailing slashes */
  430. p = lpath + strlen (lpath) - 1;
  431. while (p > lpath && *p == PATH_SEP)
  432. {
  433. if (p >= lpath - (url_delim_len + 1)
  434. && strncmp (p - url_delim_len + 1, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  435. break;
  436. *p-- = 0;
  437. }
  438. /* Remove leading "./" */
  439. if (lpath[0] == '.' && lpath[1] == PATH_SEP)
  440. {
  441. if (lpath[2] == 0)
  442. {
  443. lpath[1] = 0;
  444. return;
  445. }
  446. else
  447. {
  448. str_move (lpath, lpath + 2);
  449. }
  450. }
  451. /* Remove trailing "/" or "/." */
  452. len = strlen (lpath);
  453. if (len < 2)
  454. return;
  455. if (lpath[len - 1] == PATH_SEP
  456. && (len < url_delim_len
  457. || strncmp (lpath + len - url_delim_len, VFS_PATH_URL_DELIMITER,
  458. url_delim_len) != 0))
  459. {
  460. lpath[len - 1] = '\0';
  461. }
  462. else
  463. {
  464. if (lpath[len - 1] == '.' && lpath[len - 2] == PATH_SEP)
  465. {
  466. if (len == 2)
  467. {
  468. lpath[1] = '\0';
  469. return;
  470. }
  471. else
  472. {
  473. lpath[len - 2] = '\0';
  474. }
  475. }
  476. }
  477. }
  478. if (flags & CANON_PATH_REMDOUBLEDOTS)
  479. {
  480. #ifdef HAVE_CHARSET
  481. const size_t enc_prefix_len = strlen (VFS_ENCODING_PREFIX);
  482. #endif /* HAVE_CHARSET */
  483. /* Collapse "/.." with the previous part of path */
  484. p = lpath;
  485. while (p[0] && p[1] && p[2])
  486. {
  487. if ((p[0] != PATH_SEP || p[1] != '.' || p[2] != '.') || (p[3] != PATH_SEP && p[3] != 0))
  488. {
  489. p++;
  490. continue;
  491. }
  492. /* search for the previous token */
  493. s = p - 1;
  494. if (s >= lpath + url_delim_len - 2
  495. && strncmp (s - url_delim_len + 2, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  496. {
  497. s -= (url_delim_len - 2);
  498. while (s >= lpath && *s-- != PATH_SEP);
  499. }
  500. while (s >= lpath)
  501. {
  502. if (s - url_delim_len > lpath
  503. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  504. {
  505. char *vfs_prefix = s - url_delim_len;
  506. struct vfs_class *vclass;
  507. while (vfs_prefix > lpath && *--vfs_prefix != PATH_SEP);
  508. if (*vfs_prefix == PATH_SEP)
  509. vfs_prefix++;
  510. *(s - url_delim_len) = '\0';
  511. vclass = vfs_prefix_to_class (vfs_prefix);
  512. *(s - url_delim_len) = *VFS_PATH_URL_DELIMITER;
  513. if (vclass != NULL)
  514. {
  515. struct vfs_s_subclass *sub = (struct vfs_s_subclass *) vclass->data;
  516. if (sub != NULL && sub->flags & VFS_S_REMOTE)
  517. {
  518. s = vfs_prefix;
  519. continue;
  520. }
  521. }
  522. }
  523. if (*s == PATH_SEP)
  524. break;
  525. s--;
  526. }
  527. s++;
  528. /* If the previous token is "..", we cannot collapse it */
  529. if (s[0] == '.' && s[1] == '.' && s + 2 == p)
  530. {
  531. p += 3;
  532. continue;
  533. }
  534. if (p[3] != 0)
  535. {
  536. if (s == lpath && *s == PATH_SEP)
  537. {
  538. /* "/../foo" -> "/foo" */
  539. str_move (s + 1, p + 4);
  540. }
  541. else
  542. {
  543. /* "token/../foo" -> "foo" */
  544. #ifdef HAVE_CHARSET
  545. if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  546. && (is_supported_encoding (s + enc_prefix_len)))
  547. /* special case: remove encoding */
  548. str_move (s, p + 1);
  549. else
  550. #endif /* HAVE_CHARSET */
  551. str_move (s, p + 4);
  552. }
  553. p = (s > lpath) ? s - 1 : s;
  554. continue;
  555. }
  556. /* trailing ".." */
  557. if (s == lpath)
  558. {
  559. /* "token/.." -> "." */
  560. if (lpath[0] != PATH_SEP)
  561. {
  562. lpath[0] = '.';
  563. }
  564. lpath[1] = 0;
  565. }
  566. else
  567. {
  568. /* "foo/token/.." -> "foo" */
  569. if (s == lpath + 1)
  570. s[0] = 0;
  571. #ifdef HAVE_CHARSET
  572. else if ((strncmp (s, VFS_ENCODING_PREFIX, enc_prefix_len) == 0)
  573. && (is_supported_encoding (s + enc_prefix_len)))
  574. {
  575. /* special case: remove encoding */
  576. s[0] = '.';
  577. s[1] = '.';
  578. s[2] = '\0';
  579. /* search for the previous token */
  580. /* s[-1] == PATH_SEP */
  581. p = s - 1;
  582. while (p >= lpath && *p != PATH_SEP)
  583. p--;
  584. if (p != NULL)
  585. continue;
  586. }
  587. #endif /* HAVE_CHARSET */
  588. else
  589. {
  590. if (s >= lpath + url_delim_len
  591. && strncmp (s - url_delim_len, VFS_PATH_URL_DELIMITER, url_delim_len) == 0)
  592. *s = '\0';
  593. else
  594. s[-1] = '\0';
  595. }
  596. break;
  597. }
  598. break;
  599. }
  600. }
  601. }
  602. /* --------------------------------------------------------------------------------------------- */
  603. void
  604. canonicalize_pathname (char *path)
  605. {
  606. custom_canonicalize_pathname (path, CANON_PATH_ALL);
  607. }
  608. /* --------------------------------------------------------------------------------------------- */
  609. #ifdef HAVE_GET_PROCESS_STATS
  610. int
  611. gettimeofday (struct timeval *tp, void *tzp)
  612. {
  613. return get_process_stats (tp, PS_SELF, 0, 0);
  614. }
  615. #endif /* HAVE_GET_PROCESS_STATS */
  616. /* --------------------------------------------------------------------------------------------- */
  617. #ifndef HAVE_REALPATH
  618. char *
  619. mc_realpath (const char *path, char *resolved_path)
  620. {
  621. char copy_path[PATH_MAX];
  622. char link_path[PATH_MAX];
  623. char got_path[PATH_MAX];
  624. char *new_path = got_path;
  625. char *max_path;
  626. int readlinks = 0;
  627. int n;
  628. /* Make a copy of the source path since we may need to modify it. */
  629. if (strlen (path) >= PATH_MAX - 2)
  630. {
  631. errno = ENAMETOOLONG;
  632. return NULL;
  633. }
  634. strcpy (copy_path, path);
  635. path = copy_path;
  636. max_path = copy_path + PATH_MAX - 2;
  637. /* If it's a relative pathname use getwd for starters. */
  638. if (*path != '/')
  639. {
  640. new_path = g_get_current_dir ();
  641. if (new_path == NULL)
  642. {
  643. strcpy (got_path, "");
  644. }
  645. else
  646. {
  647. g_snprintf (got_path, PATH_MAX, "%s", new_path);
  648. g_free (new_path);
  649. new_path = got_path;
  650. }
  651. new_path += strlen (got_path);
  652. if (new_path[-1] != '/')
  653. *new_path++ = '/';
  654. }
  655. else
  656. {
  657. *new_path++ = '/';
  658. path++;
  659. }
  660. /* Expand each slash-separated pathname component. */
  661. while (*path != '\0')
  662. {
  663. /* Ignore stray "/". */
  664. if (*path == '/')
  665. {
  666. path++;
  667. continue;
  668. }
  669. if (*path == '.')
  670. {
  671. /* Ignore ".". */
  672. if (path[1] == '\0' || path[1] == '/')
  673. {
  674. path++;
  675. continue;
  676. }
  677. if (path[1] == '.')
  678. {
  679. if (path[2] == '\0' || path[2] == '/')
  680. {
  681. path += 2;
  682. /* Ignore ".." at root. */
  683. if (new_path == got_path + 1)
  684. continue;
  685. /* Handle ".." by backing up. */
  686. while ((--new_path)[-1] != '/');
  687. continue;
  688. }
  689. }
  690. }
  691. /* Safely copy the next pathname component. */
  692. while (*path != '\0' && *path != '/')
  693. {
  694. if (path > max_path)
  695. {
  696. errno = ENAMETOOLONG;
  697. return NULL;
  698. }
  699. *new_path++ = *path++;
  700. }
  701. #ifdef S_IFLNK
  702. /* Protect against infinite loops. */
  703. if (readlinks++ > MAXSYMLINKS)
  704. {
  705. errno = ELOOP;
  706. return NULL;
  707. }
  708. /* See if latest pathname component is a symlink. */
  709. *new_path = '\0';
  710. n = readlink (got_path, link_path, PATH_MAX - 1);
  711. if (n < 0)
  712. {
  713. /* EINVAL means the file exists but isn't a symlink. */
  714. if (errno != EINVAL)
  715. {
  716. /* Make sure it's null terminated. */
  717. *new_path = '\0';
  718. strcpy (resolved_path, got_path);
  719. return NULL;
  720. }
  721. }
  722. else
  723. {
  724. /* Note: readlink doesn't add the null byte. */
  725. link_path[n] = '\0';
  726. if (*link_path == '/')
  727. /* Start over for an absolute symlink. */
  728. new_path = got_path;
  729. else
  730. /* Otherwise back up over this component. */
  731. while (*(--new_path) != '/');
  732. /* Safe sex check. */
  733. if (strlen (path) + n >= PATH_MAX - 2)
  734. {
  735. errno = ENAMETOOLONG;
  736. return NULL;
  737. }
  738. /* Insert symlink contents into path. */
  739. strcat (link_path, path);
  740. strcpy (copy_path, link_path);
  741. path = copy_path;
  742. }
  743. #endif /* S_IFLNK */
  744. *new_path++ = '/';
  745. }
  746. /* Delete trailing slash but don't whomp a lone slash. */
  747. if (new_path != got_path + 1 && new_path[-1] == '/')
  748. new_path--;
  749. /* Make sure it's null terminated. */
  750. *new_path = '\0';
  751. strcpy (resolved_path, got_path);
  752. return resolved_path;
  753. }
  754. #endif /* HAVE_REALPATH */
  755. /* --------------------------------------------------------------------------------------------- */
  756. /**
  757. * Return the index of the permissions triplet
  758. *
  759. */
  760. int
  761. get_user_permissions (struct stat *st)
  762. {
  763. static gboolean initialized = FALSE;
  764. static gid_t *groups;
  765. static int ngroups;
  766. static uid_t uid;
  767. int i;
  768. if (!initialized)
  769. {
  770. uid = geteuid ();
  771. ngroups = getgroups (0, NULL);
  772. if (ngroups == -1)
  773. ngroups = 0; /* ignore errors */
  774. /* allocate space for one element in addition to what
  775. * will be filled by getgroups(). */
  776. groups = g_new (gid_t, ngroups + 1);
  777. if (ngroups != 0)
  778. {
  779. ngroups = getgroups (ngroups, groups);
  780. if (ngroups == -1)
  781. ngroups = 0; /* ignore errors */
  782. }
  783. /* getgroups() may or may not return the effective group ID,
  784. * so we always include it at the end of the list. */
  785. groups[ngroups++] = getegid ();
  786. initialized = TRUE;
  787. }
  788. if (st->st_uid == uid || uid == 0)
  789. return 0;
  790. for (i = 0; i < ngroups; i++)
  791. {
  792. if (st->st_gid == groups[i])
  793. return 1;
  794. }
  795. return 2;
  796. }
  797. /* --------------------------------------------------------------------------------------------- */
  798. /**
  799. * Build filename from arguments.
  800. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  801. */
  802. char *
  803. mc_build_filenamev (const char *first_element, va_list args)
  804. {
  805. gboolean absolute;
  806. const char *element = first_element;
  807. GString *path;
  808. char *ret;
  809. if (element == NULL)
  810. return NULL;
  811. path = g_string_new ("");
  812. absolute = (*first_element != '\0' && *first_element == PATH_SEP);
  813. do
  814. {
  815. if (*element == '\0')
  816. element = va_arg (args, char *);
  817. else
  818. {
  819. char *tmp_element;
  820. size_t len;
  821. const char *start;
  822. tmp_element = g_strdup (element);
  823. element = va_arg (args, char *);
  824. canonicalize_pathname (tmp_element);
  825. len = strlen (tmp_element);
  826. start = (tmp_element[0] == PATH_SEP) ? tmp_element + 1 : tmp_element;
  827. g_string_append (path, start);
  828. if (tmp_element[len - 1] != PATH_SEP && element != NULL)
  829. g_string_append_c (path, PATH_SEP);
  830. g_free (tmp_element);
  831. }
  832. }
  833. while (element != NULL);
  834. if (absolute)
  835. g_string_prepend_c (path, PATH_SEP);
  836. ret = g_string_free (path, FALSE);
  837. canonicalize_pathname (ret);
  838. return ret;
  839. }
  840. /* --------------------------------------------------------------------------------------------- */
  841. /**
  842. * Build filename from arguments.
  843. * Like to g_build_filename(), but respect VFS_PATH_URL_DELIMITER
  844. */
  845. char *
  846. mc_build_filename (const char *first_element, ...)
  847. {
  848. va_list args;
  849. char *ret;
  850. if (first_element == NULL)
  851. return NULL;
  852. va_start (args, first_element);
  853. ret = mc_build_filenamev (first_element, args);
  854. va_end (args);
  855. return ret;
  856. }
  857. /* --------------------------------------------------------------------------------------------- */