util.c 42 KB

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