utilunix.c 31 KB

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