util.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865
  1. /* Various utilities
  2. Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
  3. 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
  4. Written 1994, 1995, 1996 by:
  5. Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
  6. Jakub Jelinek, Mauricio Plaza.
  7. The file_date routine is mostly from GNU's fileutils package,
  8. written by Richard Stallman and David MacKenzie.
  9. This program is free software; you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation; either version 2 of the License, or
  12. (at your option) any later version.
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License
  18. along with this program; if not, write to the Free Software
  19. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  20. /** \file
  21. * \brief Source: various utilities
  22. */
  23. #include <config.h>
  24. #include <ctype.h>
  25. #include <limits.h>
  26. #include <stdarg.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <fcntl.h>
  31. #include <sys/time.h>
  32. #include <sys/types.h>
  33. #include <sys/stat.h>
  34. #include <unistd.h>
  35. #include "lib/global.h"
  36. #include "lib/tty/win.h" /* xterm_flag */
  37. #include "lib/search.h"
  38. #include "lib/mcconfig.h"
  39. #include "lib/timefmt.h"
  40. #include "lib/fileloc.h"
  41. #include "lib/vfs/mc-vfs/vfs.h"
  42. #include "lib/strutil.h"
  43. #include "src/filegui.h"
  44. #include "src/file.h" /* copy_file_file() */
  45. #ifndef HAVE_CHARSET
  46. #include "src/main.h" /* eight_bit_clean */
  47. #endif
  48. /*** global variables ****************************************************************************/
  49. int easy_patterns = 1;
  50. char *user_recent_timeformat = NULL; /* time format string for recent dates */
  51. char *user_old_timeformat = NULL; /* time format string for older dates */
  52. /*** file scope macro definitions ****************************************************************/
  53. #define ismode(n,m) ((n & m) == m)
  54. /* Number of attempts to create a temporary file */
  55. #ifndef TMP_MAX
  56. #define TMP_MAX 16384
  57. #endif /* !TMP_MAX */
  58. #define TMP_SUFFIX ".tmp"
  59. #define ASCII_A (0x40 + 1)
  60. #define ASCII_Z (0x40 + 26)
  61. #define ASCII_a (0x60 + 1)
  62. #define ASCII_z (0x60 + 26)
  63. /*** file scope type declarations ****************************************************************/
  64. /*** file scope variables ************************************************************************/
  65. /*
  66. * Cache variable for the i18n_checktimelength function,
  67. * initially set to a clearly invalid value to show that
  68. * it hasn't been initialized yet.
  69. */
  70. static size_t i18n_timelength_cache = MAX_I18NTIMELENGTH + 1;
  71. /*** file scope functions ************************************************************************/
  72. /* --------------------------------------------------------------------------------------------- */
  73. static inline int
  74. is_7bit_printable (unsigned char c)
  75. {
  76. return (c > 31 && c < 127);
  77. }
  78. /* --------------------------------------------------------------------------------------------- */
  79. static inline int
  80. is_iso_printable (unsigned char c)
  81. {
  82. return ((c > 31 && c < 127) || c >= 160);
  83. }
  84. /* --------------------------------------------------------------------------------------------- */
  85. static inline int
  86. is_8bit_printable (unsigned char c)
  87. {
  88. /* "Full 8 bits output" doesn't work on xterm */
  89. if (xterm_flag)
  90. return is_iso_printable (c);
  91. return (c > 31 && c != 127 && c != 155);
  92. }
  93. /* --------------------------------------------------------------------------------------------- */
  94. static char *
  95. resolve_symlinks (const char *path)
  96. {
  97. char *buf, *buf2, *q, *r, c;
  98. int len;
  99. struct stat mybuf;
  100. const char *p;
  101. if (*path != PATH_SEP)
  102. return NULL;
  103. r = buf = g_malloc (MC_MAXPATHLEN);
  104. buf2 = g_malloc (MC_MAXPATHLEN);
  105. *r++ = PATH_SEP;
  106. *r = 0;
  107. p = path;
  108. for (;;)
  109. {
  110. q = strchr (p + 1, PATH_SEP);
  111. if (!q)
  112. {
  113. q = strchr (p + 1, 0);
  114. if (q == p + 1)
  115. break;
  116. }
  117. c = *q;
  118. *q = 0;
  119. if (mc_lstat (path, &mybuf) < 0)
  120. {
  121. g_free (buf);
  122. g_free (buf2);
  123. *q = c;
  124. return NULL;
  125. }
  126. if (!S_ISLNK (mybuf.st_mode))
  127. strcpy (r, p + 1);
  128. else
  129. {
  130. len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
  131. if (len < 0)
  132. {
  133. g_free (buf);
  134. g_free (buf2);
  135. *q = c;
  136. return NULL;
  137. }
  138. buf2[len] = 0;
  139. if (*buf2 == PATH_SEP)
  140. strcpy (buf, buf2);
  141. else
  142. strcpy (r, buf2);
  143. }
  144. canonicalize_pathname (buf);
  145. r = strchr (buf, 0);
  146. if (!*r || *(r - 1) != PATH_SEP)
  147. {
  148. *r++ = PATH_SEP;
  149. *r = 0;
  150. }
  151. *q = c;
  152. p = q;
  153. if (!c)
  154. break;
  155. }
  156. if (!*buf)
  157. strcpy (buf, PATH_SEP_STR);
  158. else if (*(r - 1) == PATH_SEP && r != buf + 1)
  159. *(r - 1) = 0;
  160. g_free (buf2);
  161. return buf;
  162. }
  163. /* --------------------------------------------------------------------------------------------- */
  164. static gboolean
  165. mc_util_write_backup_content (const char *from_file_name, const char *to_file_name)
  166. {
  167. FILE *backup_fd;
  168. char *contents;
  169. gsize length;
  170. gboolean ret1 = TRUE;
  171. if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
  172. return FALSE;
  173. backup_fd = fopen (to_file_name, "w");
  174. if (backup_fd == NULL)
  175. {
  176. g_free (contents);
  177. return FALSE;
  178. }
  179. if (fwrite ((const void *) contents, 1, length, backup_fd) != length)
  180. ret1 = FALSE;
  181. {
  182. int ret2;
  183. ret2 = fflush (backup_fd);
  184. ret2 = fclose (backup_fd);
  185. }
  186. g_free (contents);
  187. return ret1;
  188. }
  189. /* --------------------------------------------------------------------------------------------- */
  190. /*** public functions ****************************************************************************/
  191. /* --------------------------------------------------------------------------------------------- */
  192. extern void
  193. str_replace (char *s, char from, char to)
  194. {
  195. for (; *s != '\0'; s++)
  196. {
  197. if (*s == from)
  198. *s = to;
  199. }
  200. }
  201. /* --------------------------------------------------------------------------------------------- */
  202. int
  203. is_printable (int c)
  204. {
  205. c &= 0xff;
  206. #ifdef HAVE_CHARSET
  207. /* "Display bits" is ignored, since the user controls the output
  208. by setting the output codepage */
  209. return is_8bit_printable (c);
  210. #else
  211. if (!eight_bit_clean)
  212. return is_7bit_printable (c);
  213. if (full_eight_bits)
  214. {
  215. return is_8bit_printable (c);
  216. }
  217. else
  218. return is_iso_printable (c);
  219. #endif /* !HAVE_CHARSET */
  220. }
  221. /* --------------------------------------------------------------------------------------------- */
  222. /**
  223. * Calculates the message dimensions (lines and columns)
  224. *
  225. */
  226. void
  227. msglen (const char *text, int *lines, int *columns)
  228. {
  229. int nlines = 1; /* even the empty string takes one line */
  230. int ncolumns = 0;
  231. int colindex = 0;
  232. for (; *text != '\0'; text++)
  233. {
  234. if (*text == '\n')
  235. {
  236. nlines++;
  237. colindex = 0;
  238. }
  239. else
  240. {
  241. colindex++;
  242. if (colindex > ncolumns)
  243. ncolumns = colindex;
  244. }
  245. }
  246. *lines = nlines;
  247. *columns = ncolumns;
  248. }
  249. /* --------------------------------------------------------------------------------------------- */
  250. /**
  251. * Copy from s to d, and trim the beginning if necessary, and prepend
  252. * "..." in this case. The destination string can have at most len
  253. * bytes, not counting trailing 0.
  254. */
  255. char *
  256. trim (const char *s, char *d, int len)
  257. {
  258. int source_len;
  259. /* Sanity check */
  260. len = max (len, 0);
  261. source_len = strlen (s);
  262. if (source_len > len)
  263. {
  264. /* Cannot fit the whole line */
  265. if (len <= 3)
  266. {
  267. /* We only have room for the dots */
  268. memset (d, '.', len);
  269. d[len] = 0;
  270. return d;
  271. }
  272. else
  273. {
  274. /* Begin with ... and add the rest of the source string */
  275. memset (d, '.', 3);
  276. strcpy (d + 3, s + 3 + source_len - len);
  277. }
  278. }
  279. else
  280. /* We can copy the whole line */
  281. strcpy (d, s);
  282. return d;
  283. }
  284. /* --------------------------------------------------------------------------------------------- */
  285. /**
  286. * Quote the filename for the purpose of inserting it into the command
  287. * line. If quote_percent is 1, replace "%" with "%%" - the percent is
  288. * processed by the mc command line.
  289. */
  290. char *
  291. name_quote (const char *s, int quote_percent)
  292. {
  293. char *ret, *d;
  294. d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
  295. if (*s == '-')
  296. {
  297. *d++ = '.';
  298. *d++ = '/';
  299. }
  300. for (; *s; s++, d++)
  301. {
  302. switch (*s)
  303. {
  304. case '%':
  305. if (quote_percent)
  306. *d++ = '%';
  307. break;
  308. case '\'':
  309. case '\\':
  310. case '\r':
  311. case '\n':
  312. case '\t':
  313. case '"':
  314. case ';':
  315. case ' ':
  316. case '?':
  317. case '|':
  318. case '[':
  319. case ']':
  320. case '{':
  321. case '}':
  322. case '<':
  323. case '>':
  324. case '`':
  325. case '!':
  326. case '$':
  327. case '&':
  328. case '*':
  329. case '(':
  330. case ')':
  331. *d++ = '\\';
  332. break;
  333. case '~':
  334. case '#':
  335. if (d == ret)
  336. *d++ = '\\';
  337. break;
  338. }
  339. *d = *s;
  340. }
  341. *d = '\0';
  342. return ret;
  343. }
  344. /* --------------------------------------------------------------------------------------------- */
  345. char *
  346. fake_name_quote (const char *s, int quote_percent)
  347. {
  348. (void) quote_percent;
  349. return g_strdup (s);
  350. }
  351. /* --------------------------------------------------------------------------------------------- */
  352. /**
  353. * Remove the middle part of the string to fit given length.
  354. * Use "~" to show where the string was truncated.
  355. * Return static buffer, no need to free() it.
  356. */
  357. const char *
  358. name_trunc (const char *txt, size_t trunc_len)
  359. {
  360. return str_trunc (txt, trunc_len);
  361. }
  362. /* --------------------------------------------------------------------------------------------- */
  363. /**
  364. * path_trunc() is the same as name_trunc() above but
  365. * it deletes possible password from path for security
  366. * reasons.
  367. */
  368. const char *
  369. path_trunc (const char *path, size_t trunc_len)
  370. {
  371. char *secure_path = strip_password (g_strdup (path), 1);
  372. const char *ret = str_trunc (secure_path, trunc_len);
  373. g_free (secure_path);
  374. return ret;
  375. }
  376. /* --------------------------------------------------------------------------------------------- */
  377. const char *
  378. size_trunc (double size, gboolean use_si)
  379. {
  380. static char x[BUF_TINY];
  381. long int divisor = 1;
  382. const char *xtra = "";
  383. if (size > 999999999L)
  384. {
  385. divisor = use_si ? 1000 : 1024;
  386. xtra = use_si ? "k" : "K";
  387. if (size / divisor > 999999999L)
  388. {
  389. divisor = use_si ? (1000 * 1000) : (1024 * 1024);
  390. xtra = use_si ? "m" : "M";
  391. }
  392. }
  393. g_snprintf (x, sizeof (x), "%.0f%s", (size / divisor), xtra);
  394. return x;
  395. }
  396. /* --------------------------------------------------------------------------------------------- */
  397. const char *
  398. size_trunc_sep (double size, gboolean use_si)
  399. {
  400. static char x[60];
  401. int count;
  402. const char *p, *y;
  403. char *d;
  404. p = y = size_trunc (size, use_si);
  405. p += strlen (p) - 1;
  406. d = x + sizeof (x) - 1;
  407. *d-- = 0;
  408. while (p >= y && isalpha ((unsigned char) *p))
  409. *d-- = *p--;
  410. for (count = 0; p >= y; count++)
  411. {
  412. if (count == 3)
  413. {
  414. *d-- = ',';
  415. count = 0;
  416. }
  417. *d-- = *p--;
  418. }
  419. d++;
  420. if (*d == ',')
  421. d++;
  422. return d;
  423. }
  424. /* --------------------------------------------------------------------------------------------- */
  425. /**
  426. * Print file SIZE to BUFFER, but don't exceed LEN characters,
  427. * not including trailing 0. BUFFER should be at least LEN+1 long.
  428. * This function is called for every file on panels, so avoid
  429. * floating point by any means.
  430. *
  431. * Units: size units (filesystem sizes are 1K blocks)
  432. * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
  433. */
  434. void
  435. size_trunc_len (char *buffer, unsigned int len, off_t size, int units, gboolean use_si)
  436. {
  437. /* Avoid taking power for every file. */
  438. static const off_t power10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
  439. 1000000000
  440. };
  441. static const char *const suffix[] = { "", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL };
  442. static const char *const suffix_lc[] = { "", "k", "m", "g", "t", "p", "e", "z", "y", NULL };
  443. int j = 0;
  444. int size_remain;
  445. if (len == 0)
  446. len = 9;
  447. /*
  448. * recalculate from 1024 base to 1000 base if units>0
  449. * We can't just multiply by 1024 - that might cause overflow
  450. * if off_t type is too small
  451. */
  452. if (units && use_si)
  453. {
  454. for (j = 0; j < units; j++)
  455. {
  456. size_remain = ((size % 125) * 1024) / 1000; /* size mod 125, recalculated */
  457. size = size / 125; /* 128/125 = 1024/1000 */
  458. size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
  459. size += size_remain; /* Re-add remainder lost by division/multiplication */
  460. }
  461. }
  462. for (j = units; suffix[j] != NULL; j++)
  463. {
  464. if (size == 0)
  465. {
  466. if (j == units)
  467. {
  468. /* Empty files will print "0" even with minimal width. */
  469. g_snprintf (buffer, len + 1, "0");
  470. break;
  471. }
  472. /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
  473. g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
  474. (j > 1) ? (use_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
  475. break;
  476. }
  477. if (size < power10[len - (j > 0)])
  478. {
  479. g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size,
  480. use_si ? suffix_lc[j] : suffix[j]);
  481. break;
  482. }
  483. /* Powers of 1000 or 1024, with rounding. */
  484. if (use_si)
  485. size = (size + 500) / 1000;
  486. else
  487. size = (size + 512) >> 10;
  488. }
  489. }
  490. /* --------------------------------------------------------------------------------------------- */
  491. int
  492. is_exe (mode_t mode)
  493. {
  494. if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
  495. return 1;
  496. return 0;
  497. }
  498. /* --------------------------------------------------------------------------------------------- */
  499. const char *
  500. string_perm (mode_t mode_bits)
  501. {
  502. static char mode[11];
  503. strcpy (mode, "----------");
  504. if (S_ISDIR (mode_bits))
  505. mode[0] = 'd';
  506. if (S_ISCHR (mode_bits))
  507. mode[0] = 'c';
  508. if (S_ISBLK (mode_bits))
  509. mode[0] = 'b';
  510. if (S_ISLNK (mode_bits))
  511. mode[0] = 'l';
  512. if (S_ISFIFO (mode_bits))
  513. mode[0] = 'p';
  514. if (S_ISNAM (mode_bits))
  515. mode[0] = 'n';
  516. if (S_ISSOCK (mode_bits))
  517. mode[0] = 's';
  518. if (S_ISDOOR (mode_bits))
  519. mode[0] = 'D';
  520. if (ismode (mode_bits, S_IXOTH))
  521. mode[9] = 'x';
  522. if (ismode (mode_bits, S_IWOTH))
  523. mode[8] = 'w';
  524. if (ismode (mode_bits, S_IROTH))
  525. mode[7] = 'r';
  526. if (ismode (mode_bits, S_IXGRP))
  527. mode[6] = 'x';
  528. if (ismode (mode_bits, S_IWGRP))
  529. mode[5] = 'w';
  530. if (ismode (mode_bits, S_IRGRP))
  531. mode[4] = 'r';
  532. if (ismode (mode_bits, S_IXUSR))
  533. mode[3] = 'x';
  534. if (ismode (mode_bits, S_IWUSR))
  535. mode[2] = 'w';
  536. if (ismode (mode_bits, S_IRUSR))
  537. mode[1] = 'r';
  538. #ifdef S_ISUID
  539. if (ismode (mode_bits, S_ISUID))
  540. mode[3] = (mode[3] == 'x') ? 's' : 'S';
  541. #endif /* S_ISUID */
  542. #ifdef S_ISGID
  543. if (ismode (mode_bits, S_ISGID))
  544. mode[6] = (mode[6] == 'x') ? 's' : 'S';
  545. #endif /* S_ISGID */
  546. #ifdef S_ISVTX
  547. if (ismode (mode_bits, S_ISVTX))
  548. mode[9] = (mode[9] == 'x') ? 't' : 'T';
  549. #endif /* S_ISVTX */
  550. return mode;
  551. }
  552. /* --------------------------------------------------------------------------------------------- */
  553. /**
  554. * p: string which might contain an url with a password (this parameter is
  555. * modified in place).
  556. * has_prefix = 0: The first parameter is an url without a prefix
  557. * (user[:pass]@]machine[:port][remote-dir). Delete
  558. * the password.
  559. * has_prefix = 1: Search p for known url prefixes. If found delete
  560. * the password from the url.
  561. * Caveat: only the first url is found
  562. */
  563. char *
  564. strip_password (char *p, int has_prefix)
  565. {
  566. static const struct
  567. {
  568. const char *name;
  569. size_t len;
  570. } prefixes[] =
  571. {
  572. /* *INDENT-OFF* */
  573. { "/#ftp:", 6 },
  574. { "ftp://", 6 },
  575. { "/#smb:", 6 },
  576. { "smb://", 6 },
  577. { "/#sh:", 5 },
  578. { "sh://", 5 },
  579. { "ssh://", 6 }
  580. /* *INDENT-ON* */
  581. };
  582. char *at, *inner_colon, *dir;
  583. size_t i;
  584. char *result = p;
  585. for (i = 0; i < sizeof (prefixes) / sizeof (prefixes[0]); i++)
  586. {
  587. char *q;
  588. if (has_prefix)
  589. {
  590. q = strstr (p, prefixes[i].name);
  591. if (q == NULL)
  592. continue;
  593. else
  594. p = q + prefixes[i].len;
  595. }
  596. dir = strchr (p, PATH_SEP);
  597. if (dir != NULL)
  598. *dir = '\0';
  599. /* search for any possible user */
  600. at = strrchr (p, '@');
  601. if (dir)
  602. *dir = PATH_SEP;
  603. /* We have a username */
  604. if (at)
  605. {
  606. inner_colon = memchr (p, ':', at - p);
  607. if (inner_colon)
  608. memmove (inner_colon, at, strlen (at) + 1);
  609. }
  610. break;
  611. }
  612. return (result);
  613. }
  614. /* --------------------------------------------------------------------------------------------- */
  615. const char *
  616. strip_home_and_password (const char *dir)
  617. {
  618. size_t len;
  619. static char newdir[MC_MAXPATHLEN];
  620. len = strlen (home_dir);
  621. if (home_dir != NULL && strncmp (dir, home_dir, len) == 0 &&
  622. (dir[len] == PATH_SEP || dir[len] == '\0'))
  623. {
  624. newdir[0] = '~';
  625. g_strlcpy (&newdir[1], &dir[len], sizeof (newdir) - 1);
  626. return newdir;
  627. }
  628. /* We do not strip homes in /#ftp tree, I do not like ~'s there
  629. (see ftpfs.c why) */
  630. g_strlcpy (newdir, dir, sizeof (newdir));
  631. strip_password (newdir, 1);
  632. return newdir;
  633. }
  634. /* --------------------------------------------------------------------------------------------- */
  635. const char *
  636. extension (const char *filename)
  637. {
  638. const char *d = strrchr (filename, '.');
  639. return (d != NULL) ? d + 1 : "";
  640. }
  641. /* --------------------------------------------------------------------------------------------- */
  642. int
  643. exist_file (const char *name)
  644. {
  645. return access (name, R_OK) == 0;
  646. }
  647. /* --------------------------------------------------------------------------------------------- */
  648. int
  649. check_for_default (const char *default_file, const char *file)
  650. {
  651. if (!exist_file (file))
  652. {
  653. FileOpContext *ctx;
  654. FileOpTotalContext *tctx;
  655. if (!exist_file (default_file))
  656. return -1;
  657. ctx = file_op_context_new (OP_COPY);
  658. tctx = file_op_total_context_new ();
  659. file_op_context_create_ui (ctx, 0, FALSE);
  660. copy_file_file (tctx, ctx, default_file, file);
  661. file_op_total_context_destroy (tctx);
  662. file_op_context_destroy (ctx);
  663. }
  664. return 0;
  665. }
  666. /* --------------------------------------------------------------------------------------------- */
  667. char *
  668. load_file (const char *filename)
  669. {
  670. FILE *data_file;
  671. struct stat s;
  672. char *data;
  673. long read_size;
  674. data_file = fopen (filename, "r");
  675. if (data_file == NULL)
  676. {
  677. return 0;
  678. }
  679. if (fstat (fileno (data_file), &s) != 0)
  680. {
  681. fclose (data_file);
  682. return 0;
  683. }
  684. data = g_malloc (s.st_size + 1);
  685. read_size = fread (data, 1, s.st_size, data_file);
  686. data[read_size] = 0;
  687. fclose (data_file);
  688. if (read_size > 0)
  689. return data;
  690. else
  691. {
  692. g_free (data);
  693. return 0;
  694. }
  695. }
  696. /* --------------------------------------------------------------------------------------------- */
  697. char *
  698. load_mc_home_file (const char *from, const char *filename, char **allocated_filename)
  699. {
  700. char *hintfile_base, *hintfile;
  701. char *lang;
  702. char *data;
  703. hintfile_base = g_build_filename (from, filename, (char *) NULL);
  704. lang = guess_message_value ();
  705. hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
  706. data = load_file (hintfile);
  707. if (data == NULL)
  708. {
  709. /* Fall back to the two-letter language code */
  710. if (lang[0] != '\0' && lang[1] != '\0')
  711. lang[2] = '\0';
  712. g_free (hintfile);
  713. hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
  714. data = load_file (hintfile);
  715. if (data == NULL)
  716. {
  717. g_free (hintfile);
  718. hintfile = hintfile_base;
  719. data = load_file (hintfile_base);
  720. }
  721. }
  722. g_free (lang);
  723. if (hintfile != hintfile_base)
  724. g_free (hintfile_base);
  725. if (allocated_filename != NULL)
  726. *allocated_filename = hintfile;
  727. else
  728. g_free (hintfile);
  729. return data;
  730. }
  731. /* --------------------------------------------------------------------------------------------- */
  732. /**
  733. * Check strftime() results. Some systems (i.e. Solaris) have different
  734. * short-month and month name sizes for different locales
  735. */
  736. size_t
  737. i18n_checktimelength (void)
  738. {
  739. size_t length = 0;
  740. const time_t testtime = time (NULL);
  741. struct tm *lt = localtime (&testtime);
  742. if (i18n_timelength_cache <= MAX_I18NTIMELENGTH)
  743. return i18n_timelength_cache;
  744. if (lt == NULL)
  745. {
  746. /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
  747. length = str_term_width1 (_(INVALID_TIME_TEXT));
  748. }
  749. else
  750. {
  751. char buf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
  752. /* We are interested in the longest possible date */
  753. lt->tm_sec = lt->tm_min = lt->tm_hour = lt->tm_mday = 10;
  754. /* Loop through all months to find out the longest one */
  755. for (lt->tm_mon = 0; lt->tm_mon < 12; lt->tm_mon++)
  756. {
  757. strftime (buf, sizeof (buf) - 1, user_recent_timeformat, lt);
  758. length = max ((size_t) str_term_width1 (buf), length);
  759. strftime (buf, sizeof (buf) - 1, user_old_timeformat, lt);
  760. length = max ((size_t) str_term_width1 (buf), length);
  761. }
  762. length = max ((size_t) str_term_width1 (_(INVALID_TIME_TEXT)), length);
  763. }
  764. /* Don't handle big differences. Use standard value (email bug, please) */
  765. if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
  766. length = STD_I18NTIMELENGTH;
  767. /* Save obtained value to the cache */
  768. i18n_timelength_cache = length;
  769. return i18n_timelength_cache;
  770. }
  771. /* --------------------------------------------------------------------------------------------- */
  772. const char *
  773. file_date (time_t when)
  774. {
  775. static char timebuf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
  776. time_t current_time = time ((time_t) 0);
  777. const char *fmt;
  778. if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
  779. || current_time < when - 60L * 60L) /* In the future. */
  780. /* The file is fairly old or in the future.
  781. POSIX says the cutoff is 6 months old;
  782. approximate this by 6*30 days.
  783. Allow a 1 hour slop factor for what is considered "the future",
  784. to allow for NFS server/client clock disagreement.
  785. Show the year instead of the time of day. */
  786. fmt = user_old_timeformat;
  787. else
  788. fmt = user_recent_timeformat;
  789. FMT_LOCALTIME (timebuf, sizeof (timebuf), fmt, when);
  790. return timebuf;
  791. }
  792. /* --------------------------------------------------------------------------------------------- */
  793. const char *
  794. extract_line (const char *s, const char *top)
  795. {
  796. static char tmp_line[BUF_MEDIUM];
  797. char *t = tmp_line;
  798. while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line) - 1 && s < top)
  799. *t++ = *s++;
  800. *t = 0;
  801. return tmp_line;
  802. }
  803. /* --------------------------------------------------------------------------------------------- */
  804. /**
  805. * The basename routine
  806. */
  807. const char *
  808. x_basename (const char *s)
  809. {
  810. const char *where;
  811. return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
  812. }
  813. /* --------------------------------------------------------------------------------------------- */
  814. const char *
  815. unix_error_string (int error_num)
  816. {
  817. static char buffer[BUF_LARGE];
  818. gchar *strerror_currentlocale;
  819. strerror_currentlocale = g_locale_from_utf8 (g_strerror (error_num), -1, NULL, NULL, NULL);
  820. g_snprintf (buffer, sizeof (buffer), "%s (%d)", strerror_currentlocale, error_num);
  821. g_free (strerror_currentlocale);
  822. return buffer;
  823. }
  824. /* --------------------------------------------------------------------------------------------- */
  825. const char *
  826. skip_separators (const char *s)
  827. {
  828. const char *su = s;
  829. for (; *su; str_cnext_char (&su))
  830. if (*su != ' ' && *su != '\t' && *su != ',')
  831. break;
  832. return su;
  833. }
  834. /* --------------------------------------------------------------------------------------------- */
  835. const char *
  836. skip_numbers (const char *s)
  837. {
  838. const char *su = s;
  839. for (; *su; str_cnext_char (&su))
  840. if (!str_isdigit (su))
  841. break;
  842. return su;
  843. }
  844. /* --------------------------------------------------------------------------------------------- */
  845. /**
  846. * Remove all control sequences from the argument string. We define
  847. * "control sequence", in a sort of pidgin BNF, as follows:
  848. *
  849. * control-seq = Esc non-'['
  850. * | Esc '[' (0 or more digits or ';' or '?') (any other char)
  851. *
  852. * This scheme works for all the terminals described in my termcap /
  853. * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
  854. * terminals. If I hear from a single person who uses such a terminal
  855. * with MC, I'll be glad to add support for it. (Dugan)
  856. * Non-printable characters are also removed.
  857. */
  858. char *
  859. strip_ctrl_codes (char *s)
  860. {
  861. char *w; /* Current position where the stripped data is written */
  862. char *r; /* Current position where the original data is read */
  863. char *n;
  864. if (!s)
  865. return 0;
  866. for (w = s, r = s; *r;)
  867. {
  868. if (*r == ESC_CHAR)
  869. {
  870. /* Skip the control sequence's arguments */ ;
  871. /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
  872. if (*(++r) == '[' || *r == '(')
  873. {
  874. /* strchr() matches trailing binary 0 */
  875. while (*(++r) && strchr ("0123456789;?", *r));
  876. }
  877. else if (*r == ']')
  878. {
  879. /*
  880. * Skip xterm's OSC (Operating System Command)
  881. * http://www.xfree86.org/current/ctlseqs.html
  882. * OSC P s ; P t ST
  883. * OSC P s ; P t BEL
  884. */
  885. char *new_r = r;
  886. for (; *new_r; ++new_r)
  887. {
  888. switch (*new_r)
  889. {
  890. /* BEL */
  891. case '\a':
  892. r = new_r;
  893. goto osc_out;
  894. case ESC_CHAR:
  895. /* ST */
  896. if (*(new_r + 1) == '\\')
  897. {
  898. r = new_r + 1;
  899. goto osc_out;
  900. }
  901. }
  902. }
  903. osc_out:;
  904. }
  905. /*
  906. * Now we are at the last character of the sequence.
  907. * Skip it unless it's binary 0.
  908. */
  909. if (*r)
  910. r++;
  911. continue;
  912. }
  913. n = str_get_next_char (r);
  914. if (str_isprint (r))
  915. {
  916. memmove (w, r, n - r);
  917. w += n - r;
  918. }
  919. r = n;
  920. }
  921. *w = 0;
  922. return s;
  923. }
  924. /* --------------------------------------------------------------------------------------------- */
  925. enum compression_type
  926. get_compression_type (int fd, const char *name)
  927. {
  928. unsigned char magic[16];
  929. size_t str_len;
  930. /* Read the magic signature */
  931. if (mc_read (fd, (char *) magic, 4) != 4)
  932. return COMPRESSION_NONE;
  933. /* GZIP_MAGIC and OLD_GZIP_MAGIC */
  934. if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236))
  935. {
  936. return COMPRESSION_GZIP;
  937. }
  938. /* PKZIP_MAGIC */
  939. if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003 && magic[3] == 004)
  940. {
  941. /* Read compression type */
  942. mc_lseek (fd, 8, SEEK_SET);
  943. if (mc_read (fd, (char *) magic, 2) != 2)
  944. return COMPRESSION_NONE;
  945. /* Gzip can handle only deflated (8) or stored (0) files */
  946. if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
  947. return COMPRESSION_NONE;
  948. /* Compatible with gzip */
  949. return COMPRESSION_GZIP;
  950. }
  951. /* PACK_MAGIC and LZH_MAGIC and compress magic */
  952. if (magic[0] == 037 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235))
  953. {
  954. /* Compatible with gzip */
  955. return COMPRESSION_GZIP;
  956. }
  957. /* BZIP and BZIP2 files */
  958. if ((magic[0] == 'B') && (magic[1] == 'Z') && (magic[3] >= '1') && (magic[3] <= '9'))
  959. {
  960. switch (magic[2])
  961. {
  962. case '0':
  963. return COMPRESSION_BZIP;
  964. case 'h':
  965. return COMPRESSION_BZIP2;
  966. }
  967. }
  968. /* Support for LZMA (only utils format with magic in header).
  969. * This is the default format of LZMA utils 4.32.1 and later. */
  970. if (mc_read (fd, (char *) magic + 4, 2) != 2)
  971. return COMPRESSION_NONE;
  972. /* LZMA utils format */
  973. if (magic[0] == 0xFF
  974. && magic[1] == 'L'
  975. && magic[2] == 'Z' && magic[3] == 'M' && magic[4] == 'A' && magic[5] == 0x00)
  976. return COMPRESSION_LZMA;
  977. /* XZ compression magic */
  978. if (magic[0] == 0xFD
  979. && magic[1] == 0x37
  980. && magic[2] == 0x7A && magic[3] == 0x58 && magic[4] == 0x5A && magic[5] == 0x00)
  981. return COMPRESSION_XZ;
  982. str_len = strlen (name);
  983. /* HACK: we must belive to extention of LZMA file :) ... */
  984. if ((str_len > 5 && strcmp (&name[str_len - 5], ".lzma") == 0) ||
  985. (str_len > 4 && strcmp (&name[str_len - 4], ".tlz") == 0))
  986. return COMPRESSION_LZMA;
  987. return COMPRESSION_NONE;
  988. }
  989. /* --------------------------------------------------------------------------------------------- */
  990. const char *
  991. decompress_extension (int type)
  992. {
  993. switch (type)
  994. {
  995. case COMPRESSION_GZIP:
  996. return "#ugz";
  997. case COMPRESSION_BZIP:
  998. return "#ubz";
  999. case COMPRESSION_BZIP2:
  1000. return "#ubz2";
  1001. case COMPRESSION_LZMA:
  1002. return "#ulzma";
  1003. case COMPRESSION_XZ:
  1004. return "#uxz";
  1005. }
  1006. /* Should never reach this place */
  1007. fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
  1008. return 0;
  1009. }
  1010. /* --------------------------------------------------------------------------------------------- */
  1011. /* Hooks */
  1012. void
  1013. add_hook (Hook ** hook_list, void (*hook_fn) (void *), void *data)
  1014. {
  1015. Hook *new_hook = g_new (Hook, 1);
  1016. new_hook->hook_fn = hook_fn;
  1017. new_hook->next = *hook_list;
  1018. new_hook->hook_data = data;
  1019. *hook_list = new_hook;
  1020. }
  1021. /* --------------------------------------------------------------------------------------------- */
  1022. void
  1023. execute_hooks (Hook * hook_list)
  1024. {
  1025. Hook *new_hook = 0;
  1026. Hook *p;
  1027. /* We copy the hook list first so tahat we let the hook
  1028. * function call delete_hook
  1029. */
  1030. while (hook_list)
  1031. {
  1032. add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
  1033. hook_list = hook_list->next;
  1034. }
  1035. p = new_hook;
  1036. while (new_hook)
  1037. {
  1038. (*new_hook->hook_fn) (new_hook->hook_data);
  1039. new_hook = new_hook->next;
  1040. }
  1041. for (hook_list = p; hook_list;)
  1042. {
  1043. p = hook_list;
  1044. hook_list = hook_list->next;
  1045. g_free (p);
  1046. }
  1047. }
  1048. /* --------------------------------------------------------------------------------------------- */
  1049. void
  1050. delete_hook (Hook ** hook_list, void (*hook_fn) (void *))
  1051. {
  1052. Hook *current, *new_list, *next;
  1053. new_list = 0;
  1054. for (current = *hook_list; current; current = next)
  1055. {
  1056. next = current->next;
  1057. if (current->hook_fn == hook_fn)
  1058. g_free (current);
  1059. else
  1060. add_hook (&new_list, current->hook_fn, current->hook_data);
  1061. }
  1062. *hook_list = new_list;
  1063. }
  1064. /* --------------------------------------------------------------------------------------------- */
  1065. int
  1066. hook_present (Hook * hook_list, void (*hook_fn) (void *))
  1067. {
  1068. Hook *p;
  1069. for (p = hook_list; p; p = p->next)
  1070. if (p->hook_fn == hook_fn)
  1071. return 1;
  1072. return 0;
  1073. }
  1074. /* --------------------------------------------------------------------------------------------- */
  1075. void
  1076. wipe_password (char *passwd)
  1077. {
  1078. char *p = passwd;
  1079. if (!p)
  1080. return;
  1081. for (; *p; p++)
  1082. *p = 0;
  1083. g_free (passwd);
  1084. }
  1085. /* --------------------------------------------------------------------------------------------- */
  1086. /**
  1087. * Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key
  1088. * @returns a newly allocated string
  1089. */
  1090. char *
  1091. convert_controls (const char *p)
  1092. {
  1093. char *valcopy = g_strdup (p);
  1094. char *q;
  1095. /* Parse the escape special character */
  1096. for (q = valcopy; *p;)
  1097. {
  1098. if (*p == '\\')
  1099. {
  1100. p++;
  1101. if ((*p == 'e') || (*p == 'E'))
  1102. {
  1103. p++;
  1104. *q++ = ESC_CHAR;
  1105. }
  1106. }
  1107. else
  1108. {
  1109. if (*p == '^')
  1110. {
  1111. p++;
  1112. if (*p == '^')
  1113. *q++ = *p++;
  1114. else
  1115. {
  1116. char c = (*p | 0x20);
  1117. if (c >= 'a' && c <= 'z')
  1118. {
  1119. *q++ = c - 'a' + 1;
  1120. p++;
  1121. }
  1122. else if (*p)
  1123. p++;
  1124. }
  1125. }
  1126. else
  1127. *q++ = *p++;
  1128. }
  1129. }
  1130. *q = 0;
  1131. return valcopy;
  1132. }
  1133. /* --------------------------------------------------------------------------------------------- */
  1134. /**
  1135. * Finds out a relative path from first to second, i.e. goes as many ..
  1136. * as needed up in first and then goes down using second
  1137. */
  1138. char *
  1139. diff_two_paths (const char *first, const char *second)
  1140. {
  1141. char *p, *q, *r, *s, *buf = NULL;
  1142. int i, j, prevlen = -1, currlen;
  1143. char *my_first = NULL, *my_second = NULL;
  1144. my_first = resolve_symlinks (first);
  1145. if (my_first == NULL)
  1146. return NULL;
  1147. my_second = resolve_symlinks (second);
  1148. if (my_second == NULL)
  1149. {
  1150. g_free (my_first);
  1151. return NULL;
  1152. }
  1153. for (j = 0; j < 2; j++)
  1154. {
  1155. p = my_first;
  1156. q = my_second;
  1157. for (;;)
  1158. {
  1159. r = strchr (p, PATH_SEP);
  1160. s = strchr (q, PATH_SEP);
  1161. if (!r || !s)
  1162. break;
  1163. *r = 0;
  1164. *s = 0;
  1165. if (strcmp (p, q))
  1166. {
  1167. *r = PATH_SEP;
  1168. *s = PATH_SEP;
  1169. break;
  1170. }
  1171. else
  1172. {
  1173. *r = PATH_SEP;
  1174. *s = PATH_SEP;
  1175. }
  1176. p = r + 1;
  1177. q = s + 1;
  1178. }
  1179. p--;
  1180. for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
  1181. currlen = (i + 1) * 3 + strlen (q) + 1;
  1182. if (j)
  1183. {
  1184. if (currlen < prevlen)
  1185. g_free (buf);
  1186. else
  1187. {
  1188. g_free (my_first);
  1189. g_free (my_second);
  1190. return buf;
  1191. }
  1192. }
  1193. p = buf = g_malloc (currlen);
  1194. prevlen = currlen;
  1195. for (; i >= 0; i--, p += 3)
  1196. strcpy (p, "../");
  1197. strcpy (p, q);
  1198. }
  1199. g_free (my_first);
  1200. g_free (my_second);
  1201. return buf;
  1202. }
  1203. /* --------------------------------------------------------------------------------------------- */
  1204. /**
  1205. * If filename is NULL, then we just append PATH_SEP to the dir
  1206. */
  1207. char *
  1208. concat_dir_and_file (const char *dir, const char *file)
  1209. {
  1210. int i = strlen (dir);
  1211. if (dir[i - 1] == PATH_SEP)
  1212. return g_strconcat (dir, file, (char *) NULL);
  1213. else
  1214. return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
  1215. }
  1216. /* --------------------------------------------------------------------------------------------- */
  1217. /**
  1218. * Append text to GList, remove all entries with the same text
  1219. */
  1220. GList *
  1221. list_append_unique (GList * list, char *text)
  1222. {
  1223. GList *lc_link;
  1224. /*
  1225. * Go to the last position and traverse the list backwards
  1226. * starting from the second last entry to make sure that we
  1227. * are not removing the current link.
  1228. */
  1229. list = g_list_append (list, text);
  1230. list = g_list_last (list);
  1231. lc_link = g_list_previous (list);
  1232. while (lc_link != NULL)
  1233. {
  1234. GList *newlink;
  1235. newlink = g_list_previous (lc_link);
  1236. if (strcmp ((char *) lc_link->data, text) == 0)
  1237. {
  1238. GList *tmp;
  1239. g_free (lc_link->data);
  1240. tmp = g_list_remove_link (list, lc_link);
  1241. g_list_free_1 (lc_link);
  1242. }
  1243. lc_link = newlink;
  1244. }
  1245. return list;
  1246. }
  1247. /* --------------------------------------------------------------------------------------------- */
  1248. /* Following code heavily borrows from libiberty, mkstemps.c */
  1249. /*
  1250. * Arguments:
  1251. * pname (output) - pointer to the name of the temp file (needs g_free).
  1252. * NULL if the function fails.
  1253. * prefix - part of the filename before the random part.
  1254. * Prepend $TMPDIR or /tmp if there are no path separators.
  1255. * suffix - if not NULL, part of the filename after the random part.
  1256. *
  1257. * Result:
  1258. * handle of the open file or -1 if couldn't open any.
  1259. */
  1260. int
  1261. mc_mkstemps (char **pname, const char *prefix, const char *suffix)
  1262. {
  1263. static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1264. static unsigned long value;
  1265. struct timeval tv;
  1266. char *tmpbase;
  1267. char *tmpname;
  1268. char *XXXXXX;
  1269. int count;
  1270. if (strchr (prefix, PATH_SEP) == NULL)
  1271. {
  1272. /* Add prefix first to find the position of XXXXXX */
  1273. tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
  1274. }
  1275. else
  1276. {
  1277. tmpbase = g_strdup (prefix);
  1278. }
  1279. tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
  1280. *pname = tmpname;
  1281. XXXXXX = &tmpname[strlen (tmpbase)];
  1282. g_free (tmpbase);
  1283. /* Get some more or less random data. */
  1284. gettimeofday (&tv, NULL);
  1285. value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
  1286. for (count = 0; count < TMP_MAX; ++count)
  1287. {
  1288. unsigned long v = value;
  1289. int fd;
  1290. /* Fill in the random bits. */
  1291. XXXXXX[0] = letters[v % 62];
  1292. v /= 62;
  1293. XXXXXX[1] = letters[v % 62];
  1294. v /= 62;
  1295. XXXXXX[2] = letters[v % 62];
  1296. v /= 62;
  1297. XXXXXX[3] = letters[v % 62];
  1298. v /= 62;
  1299. XXXXXX[4] = letters[v % 62];
  1300. v /= 62;
  1301. XXXXXX[5] = letters[v % 62];
  1302. fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, S_IRUSR | S_IWUSR);
  1303. if (fd >= 0)
  1304. {
  1305. /* Successfully created. */
  1306. return fd;
  1307. }
  1308. /* This is a random value. It is only necessary that the next
  1309. TMP_MAX values generated by adding 7777 to VALUE are different
  1310. with (module 2^32). */
  1311. value += 7777;
  1312. }
  1313. /* Unsuccessful. Free the filename. */
  1314. g_free (tmpname);
  1315. *pname = NULL;
  1316. return -1;
  1317. }
  1318. /* --------------------------------------------------------------------------------------------- */
  1319. /**
  1320. * Read and restore position for the given filename.
  1321. * If there is no stored data, return line 1 and col 0.
  1322. */
  1323. void
  1324. load_file_position (const char *filename, long *line, long *column, off_t * offset,
  1325. GArray ** bookmarks)
  1326. {
  1327. char *fn;
  1328. FILE *f;
  1329. char buf[MC_MAXPATHLEN + 100];
  1330. const size_t len = strlen (filename);
  1331. /* defaults */
  1332. *line = 1;
  1333. *column = 0;
  1334. *offset = 0;
  1335. /* open file with positions */
  1336. fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
  1337. f = fopen (fn, "r");
  1338. g_free (fn);
  1339. if (f == NULL)
  1340. return;
  1341. /* prepare array for serialized bookmarks */
  1342. *bookmarks = g_array_sized_new (FALSE, FALSE, sizeof (size_t), MAX_SAVED_BOOKMARKS);
  1343. while (fgets (buf, sizeof (buf), f) != NULL)
  1344. {
  1345. const char *p;
  1346. gchar **pos_tokens;
  1347. /* check if the filename matches the beginning of string */
  1348. if (strncmp (buf, filename, len) != 0)
  1349. continue;
  1350. /* followed by single space */
  1351. if (buf[len] != ' ')
  1352. continue;
  1353. /* and string without spaces */
  1354. p = &buf[len + 1];
  1355. if (strchr (p, ' ') != NULL)
  1356. continue;
  1357. pos_tokens = g_strsplit (p, ";", 3 + MAX_SAVED_BOOKMARKS);
  1358. if (pos_tokens[0] == NULL)
  1359. {
  1360. *line = 1;
  1361. *column = 0;
  1362. *offset = 0;
  1363. }
  1364. else
  1365. {
  1366. *line = strtol (pos_tokens[0], NULL, 10);
  1367. if (pos_tokens[1] == NULL)
  1368. {
  1369. *column = 0;
  1370. *offset = 0;
  1371. }
  1372. else
  1373. {
  1374. *column = strtol (pos_tokens[1], NULL, 10);
  1375. if (pos_tokens[2] == NULL)
  1376. *offset = 0;
  1377. else
  1378. {
  1379. size_t i;
  1380. *offset = strtoll (pos_tokens[2], NULL, 10);
  1381. for (i = 0; i < MAX_SAVED_BOOKMARKS && pos_tokens[3 + i] != NULL; i++)
  1382. {
  1383. size_t val;
  1384. val = strtoul (pos_tokens[3 + i], NULL, 10);
  1385. g_array_append_val (*bookmarks, val);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. g_strfreev (pos_tokens);
  1391. }
  1392. fclose (f);
  1393. }
  1394. /* --------------------------------------------------------------------------------------------- */
  1395. /**
  1396. * Save position for the given file
  1397. */
  1398. void
  1399. save_file_position (const char *filename, long line, long column, off_t offset, GArray * bookmarks)
  1400. {
  1401. static size_t filepos_max_saved_entries = 0;
  1402. char *fn, *tmp_fn;
  1403. FILE *f, *tmp_f;
  1404. char buf[MC_MAXPATHLEN + 100];
  1405. size_t i;
  1406. const size_t len = strlen (filename);
  1407. gboolean src_error = FALSE;
  1408. if (filepos_max_saved_entries == 0)
  1409. filepos_max_saved_entries = mc_config_get_int (mc_main_config, CONFIG_APP_SECTION,
  1410. "filepos_max_saved_entries", 1024);
  1411. fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
  1412. if (fn == NULL)
  1413. goto early_error;
  1414. mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
  1415. /* open file */
  1416. f = fopen (fn, "w");
  1417. if (f == NULL)
  1418. goto open_target_error;
  1419. tmp_fn = g_strdup_printf ("%s" TMP_SUFFIX, fn);
  1420. tmp_f = fopen (tmp_fn, "r");
  1421. if (tmp_f == NULL)
  1422. {
  1423. src_error = TRUE;
  1424. goto open_source_error;
  1425. }
  1426. /* put the new record */
  1427. if (line != 1 || column != 0 || bookmarks != NULL)
  1428. {
  1429. if (fprintf (f, "%s %ld;%ld;%ju", filename, line, column, offset) < 0)
  1430. goto write_position_error;
  1431. if (bookmarks != NULL)
  1432. for (i = 0; i < bookmarks->len && i < MAX_SAVED_BOOKMARKS; i++)
  1433. if (fprintf (f, ";%zu", g_array_index (bookmarks, size_t, i)) < 0)
  1434. goto write_position_error;
  1435. if (fprintf (f, "\n") < 0)
  1436. goto write_position_error;
  1437. }
  1438. i = 1;
  1439. while (fgets (buf, sizeof (buf), tmp_f) != NULL)
  1440. {
  1441. if (buf[len] == ' ' && strncmp (buf, filename, len) == 0
  1442. && strchr (&buf[len + 1], ' ') == NULL)
  1443. continue;
  1444. fprintf (f, "%s", buf);
  1445. if (++i > filepos_max_saved_entries)
  1446. break;
  1447. }
  1448. write_position_error:
  1449. fclose (tmp_f);
  1450. open_source_error:
  1451. g_free (tmp_fn);
  1452. fclose (f);
  1453. if (src_error)
  1454. mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
  1455. else
  1456. mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
  1457. open_target_error:
  1458. g_free (fn);
  1459. early_error:
  1460. g_array_free (bookmarks, TRUE);
  1461. }
  1462. /* --------------------------------------------------------------------------------------------- */
  1463. extern const char *
  1464. cstrcasestr (const char *haystack, const char *needle)
  1465. {
  1466. char *nee = str_create_search_needle (needle, 0);
  1467. const char *result = str_search_first (haystack, nee, 0);
  1468. str_release_search_needle (nee, 0);
  1469. return result;
  1470. }
  1471. /* --------------------------------------------------------------------------------------------- */
  1472. const char *
  1473. cstrstr (const char *haystack, const char *needle)
  1474. {
  1475. return strstr (haystack, needle);
  1476. }
  1477. /* --------------------------------------------------------------------------------------------- */
  1478. extern char *
  1479. str_unconst (const char *s)
  1480. {
  1481. return (char *) s;
  1482. }
  1483. /* --------------------------------------------------------------------------------------------- */
  1484. extern int
  1485. ascii_alpha_to_cntrl (int ch)
  1486. {
  1487. if ((ch >= ASCII_A && ch <= ASCII_Z) || (ch >= ASCII_a && ch <= ASCII_z))
  1488. {
  1489. ch &= 0x1f;
  1490. }
  1491. return ch;
  1492. }
  1493. /* --------------------------------------------------------------------------------------------- */
  1494. const char *
  1495. Q_ (const char *s)
  1496. {
  1497. const char *result, *sep;
  1498. result = _(s);
  1499. sep = strchr (result, '|');
  1500. return (sep != NULL) ? sep + 1 : result;
  1501. }
  1502. /* --------------------------------------------------------------------------------------------- */
  1503. gboolean
  1504. mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
  1505. {
  1506. struct stat stat_buf;
  1507. char *backup_path;
  1508. gboolean ret;
  1509. if (!exist_file (file_name))
  1510. return FALSE;
  1511. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1512. if (backup_path == NULL)
  1513. return FALSE;
  1514. ret = mc_util_write_backup_content (file_name, backup_path);
  1515. if (ret)
  1516. {
  1517. /* Backup file will have same ownership with main file. */
  1518. if (stat (file_name, &stat_buf) == 0)
  1519. chmod (backup_path, stat_buf.st_mode);
  1520. else
  1521. chmod (backup_path, S_IRUSR | S_IWUSR);
  1522. }
  1523. g_free (backup_path);
  1524. return ret;
  1525. }
  1526. /* --------------------------------------------------------------------------------------------- */
  1527. gboolean
  1528. mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
  1529. {
  1530. gboolean ret;
  1531. char *backup_path;
  1532. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1533. if (backup_path == NULL)
  1534. return FALSE;
  1535. ret = mc_util_write_backup_content (backup_path, file_name);
  1536. g_free (backup_path);
  1537. return ret;
  1538. }
  1539. /* --------------------------------------------------------------------------------------------- */
  1540. gboolean
  1541. mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
  1542. {
  1543. char *backup_path;
  1544. backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
  1545. if (backup_path == NULL)
  1546. return FALSE;
  1547. if (exist_file (backup_path))
  1548. mc_unlink (backup_path);
  1549. g_free (backup_path);
  1550. return TRUE;
  1551. }
  1552. /* --------------------------------------------------------------------------------------------- */
  1553. /**
  1554. * partly taken from dcigettext.c, returns "" for default locale
  1555. * value should be freed by calling function g_free()
  1556. */
  1557. char *
  1558. guess_message_value (void)
  1559. {
  1560. static const char *const var[] = {
  1561. /* Setting of LC_ALL overwrites all other. */
  1562. /* Do not use LANGUAGE for check user locale and drowing hints */
  1563. "LC_ALL",
  1564. /* Next comes the name of the desired category. */
  1565. "LC_MESSAGES",
  1566. /* Last possibility is the LANG environment variable. */
  1567. "LANG",
  1568. /* NULL exit loops */
  1569. NULL
  1570. };
  1571. unsigned i = 0;
  1572. const char *locale = NULL;
  1573. while (var[i] != NULL)
  1574. {
  1575. locale = getenv (var[i]);
  1576. if (locale != NULL && locale[0] != '\0')
  1577. break;
  1578. i++;
  1579. }
  1580. if (locale == NULL)
  1581. locale = "";
  1582. return g_strdup (locale);
  1583. }
  1584. /* --------------------------------------------------------------------------------------------- */