utilunix.c 29 KB

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