util.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. /*
  2. * Utility routines used in rsync.
  3. *
  4. * Copyright (C) 1996-2000 Andrew Tridgell
  5. * Copyright (C) 1996 Paul Mackerras
  6. * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
  7. * Copyright (C) 2003-2009 Wayne Davison
  8. *
  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 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program; if not, visit the http://fsf.org website.
  21. */
  22. #include "rsync.h"
  23. #include "ifuncs.h"
  24. extern int verbose;
  25. extern int module_id;
  26. extern int modify_window;
  27. extern int relative_paths;
  28. extern int preserve_times;
  29. extern int human_readable;
  30. extern int preserve_xattrs;
  31. extern char *module_dir;
  32. extern unsigned int module_dirlen;
  33. extern mode_t orig_umask;
  34. extern char *partial_dir;
  35. extern struct filter_list_struct daemon_filter_list;
  36. int sanitize_paths = 0;
  37. char curr_dir[MAXPATHLEN];
  38. unsigned int curr_dir_len;
  39. int curr_dir_depth; /* This is only set for a sanitizing daemon. */
  40. /* Set a fd into nonblocking mode. */
  41. void set_nonblocking(int fd)
  42. {
  43. int val;
  44. if ((val = fcntl(fd, F_GETFL)) == -1)
  45. return;
  46. if (!(val & NONBLOCK_FLAG)) {
  47. val |= NONBLOCK_FLAG;
  48. fcntl(fd, F_SETFL, val);
  49. }
  50. }
  51. /* Set a fd into blocking mode. */
  52. void set_blocking(int fd)
  53. {
  54. int val;
  55. if ((val = fcntl(fd, F_GETFL)) == -1)
  56. return;
  57. if (val & NONBLOCK_FLAG) {
  58. val &= ~NONBLOCK_FLAG;
  59. fcntl(fd, F_SETFL, val);
  60. }
  61. }
  62. /**
  63. * Create a file descriptor pair - like pipe() but use socketpair if
  64. * possible (because of blocking issues on pipes).
  65. *
  66. * Always set non-blocking.
  67. */
  68. int fd_pair(int fd[2])
  69. {
  70. int ret;
  71. #ifdef HAVE_SOCKETPAIR
  72. ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
  73. #else
  74. ret = pipe(fd);
  75. #endif
  76. if (ret == 0) {
  77. set_nonblocking(fd[0]);
  78. set_nonblocking(fd[1]);
  79. }
  80. return ret;
  81. }
  82. void print_child_argv(const char *prefix, char **cmd)
  83. {
  84. rprintf(FCLIENT, "%s ", prefix);
  85. for (; *cmd; cmd++) {
  86. /* Look for characters that ought to be quoted. This
  87. * is not a great quoting algorithm, but it's
  88. * sufficient for a log message. */
  89. if (strspn(*cmd, "abcdefghijklmnopqrstuvwxyz"
  90. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  91. "0123456789"
  92. ",.-_=+@/") != strlen(*cmd)) {
  93. rprintf(FCLIENT, "\"%s\" ", *cmd);
  94. } else {
  95. rprintf(FCLIENT, "%s ", *cmd);
  96. }
  97. }
  98. rprintf(FCLIENT, "\n");
  99. }
  100. NORETURN void out_of_memory(const char *str)
  101. {
  102. rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
  103. exit_cleanup(RERR_MALLOC);
  104. }
  105. NORETURN void overflow_exit(const char *str)
  106. {
  107. rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i());
  108. exit_cleanup(RERR_MALLOC);
  109. }
  110. /* This returns 0 for success, 1 for a symlink if symlink time-setting
  111. * is not possible, or -1 for any other error. */
  112. int set_modtime(const char *fname, time_t modtime, mode_t mode)
  113. {
  114. static int switch_step = 0;
  115. if (verbose > 2) {
  116. rprintf(FINFO, "set modtime of %s to (%ld) %s",
  117. fname, (long)modtime,
  118. asctime(localtime(&modtime)));
  119. }
  120. switch (switch_step) {
  121. #ifdef HAVE_UTIMENSAT
  122. #include "case_N.h"
  123. if (do_utimensat(fname, modtime, 0) == 0)
  124. break;
  125. if (errno != ENOSYS)
  126. return -1;
  127. switch_step++;
  128. /* FALLTHROUGH */
  129. #endif
  130. #ifdef HAVE_LUTIMES
  131. #include "case_N.h"
  132. if (do_lutimes(fname, modtime, 0) == 0)
  133. break;
  134. if (errno != ENOSYS)
  135. return -1;
  136. switch_step++;
  137. /* FALLTHROUGH */
  138. #endif
  139. #include "case_N.h"
  140. switch_step++;
  141. if (preserve_times & PRESERVE_LINK_TIMES) {
  142. preserve_times &= ~PRESERVE_LINK_TIMES;
  143. if (S_ISLNK(mode))
  144. return 1;
  145. }
  146. /* FALLTHROUGH */
  147. #include "case_N.h"
  148. #ifdef HAVE_UTIMES
  149. if (do_utimes(fname, modtime, 0) == 0)
  150. break;
  151. #else
  152. if (do_utime(fname, modtime, 0) == 0)
  153. break;
  154. #endif
  155. return -1;
  156. }
  157. return 0;
  158. }
  159. /* This creates a new directory with default permissions. Since there
  160. * might be some directory-default permissions affecting this, we can't
  161. * force the permissions directly using the original umask and mkdir(). */
  162. int mkdir_defmode(char *fname)
  163. {
  164. int ret;
  165. umask(orig_umask);
  166. ret = do_mkdir(fname, ACCESSPERMS);
  167. umask(0);
  168. return ret;
  169. }
  170. /* Create any necessary directories in fname. Any missing directories are
  171. * created with default permissions. */
  172. int create_directory_path(char *fname)
  173. {
  174. char *p;
  175. int ret = 0;
  176. while (*fname == '/')
  177. fname++;
  178. while (strncmp(fname, "./", 2) == 0)
  179. fname += 2;
  180. umask(orig_umask);
  181. p = fname;
  182. while ((p = strchr(p,'/')) != NULL) {
  183. *p = '\0';
  184. if (do_mkdir(fname, ACCESSPERMS) < 0 && errno != EEXIST)
  185. ret = -1;
  186. *p++ = '/';
  187. }
  188. umask(0);
  189. return ret;
  190. }
  191. /**
  192. * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
  193. * interrupted.
  194. *
  195. * @retval len upon success
  196. *
  197. * @retval <0 write's (negative) error code
  198. *
  199. * Derived from GNU C's cccp.c.
  200. */
  201. int full_write(int desc, const char *ptr, size_t len)
  202. {
  203. int total_written;
  204. total_written = 0;
  205. while (len > 0) {
  206. int written = write(desc, ptr, len);
  207. if (written < 0) {
  208. if (errno == EINTR)
  209. continue;
  210. return written;
  211. }
  212. total_written += written;
  213. ptr += written;
  214. len -= written;
  215. }
  216. return total_written;
  217. }
  218. /**
  219. * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
  220. * interrupted.
  221. *
  222. * @retval >0 the actual number of bytes read
  223. *
  224. * @retval 0 for EOF
  225. *
  226. * @retval <0 for an error.
  227. *
  228. * Derived from GNU C's cccp.c. */
  229. static int safe_read(int desc, char *ptr, size_t len)
  230. {
  231. int n_chars;
  232. if (len == 0)
  233. return len;
  234. do {
  235. n_chars = read(desc, ptr, len);
  236. } while (n_chars < 0 && errno == EINTR);
  237. return n_chars;
  238. }
  239. /* Copy a file. If ofd < 0, copy_file unlinks and opens the "dest" file.
  240. * Otherwise, it just writes to and closes the provided file descriptor.
  241. * In either case, if --xattrs are being preserved, the dest file will
  242. * have its xattrs set from the source file.
  243. *
  244. * This is used in conjunction with the --temp-dir, --backup, and
  245. * --copy-dest options. */
  246. int copy_file(const char *source, const char *dest, int ofd,
  247. mode_t mode, int create_bak_dir)
  248. {
  249. int ifd;
  250. char buf[1024 * 8];
  251. int len; /* Number of bytes read into `buf'. */
  252. if ((ifd = do_open(source, O_RDONLY, 0)) < 0) {
  253. int save_errno = errno;
  254. rsyserr(FERROR_XFER, errno, "open %s", full_fname(source));
  255. errno = save_errno;
  256. return -1;
  257. }
  258. if (ofd < 0) {
  259. if (robust_unlink(dest) && errno != ENOENT) {
  260. int save_errno = errno;
  261. rsyserr(FERROR_XFER, errno, "unlink %s", full_fname(dest));
  262. errno = save_errno;
  263. return -1;
  264. }
  265. if ((ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode)) < 0) {
  266. int save_errno = errno ? errno : EINVAL; /* 0 paranoia */
  267. if (create_bak_dir && errno == ENOENT && make_bak_dir(dest) == 0) {
  268. if ((ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode)) < 0)
  269. save_errno = errno ? errno : save_errno;
  270. else
  271. save_errno = 0;
  272. }
  273. if (save_errno) {
  274. rsyserr(FERROR_XFER, save_errno, "open %s", full_fname(dest));
  275. close(ifd);
  276. errno = save_errno;
  277. return -1;
  278. }
  279. }
  280. }
  281. while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
  282. if (full_write(ofd, buf, len) < 0) {
  283. int save_errno = errno;
  284. rsyserr(FERROR_XFER, errno, "write %s", full_fname(dest));
  285. close(ifd);
  286. close(ofd);
  287. errno = save_errno;
  288. return -1;
  289. }
  290. }
  291. if (len < 0) {
  292. int save_errno = errno;
  293. rsyserr(FERROR_XFER, errno, "read %s", full_fname(source));
  294. close(ifd);
  295. close(ofd);
  296. errno = save_errno;
  297. return -1;
  298. }
  299. if (close(ifd) < 0) {
  300. rsyserr(FWARNING, errno, "close failed on %s",
  301. full_fname(source));
  302. }
  303. if (close(ofd) < 0) {
  304. int save_errno = errno;
  305. rsyserr(FERROR_XFER, errno, "close failed on %s",
  306. full_fname(dest));
  307. errno = save_errno;
  308. return -1;
  309. }
  310. #ifdef SUPPORT_XATTRS
  311. if (preserve_xattrs)
  312. copy_xattrs(source, dest);
  313. #endif
  314. return 0;
  315. }
  316. /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
  317. #define MAX_RENAMES_DIGITS 3
  318. #define MAX_RENAMES 1000
  319. /**
  320. * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
  321. * rename to <path>/.rsyncNNN instead.
  322. *
  323. * Note that successive rsync runs will shuffle the filenames around a
  324. * bit as long as the file is still busy; this is because this function
  325. * does not know if the unlink call is due to a new file coming in, or
  326. * --delete trying to remove old .rsyncNNN files, hence it renames it
  327. * each time.
  328. **/
  329. int robust_unlink(const char *fname)
  330. {
  331. #ifndef ETXTBSY
  332. return do_unlink(fname);
  333. #else
  334. static int counter = 1;
  335. int rc, pos, start;
  336. char path[MAXPATHLEN];
  337. rc = do_unlink(fname);
  338. if (rc == 0 || errno != ETXTBSY)
  339. return rc;
  340. if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
  341. pos = MAXPATHLEN - 1;
  342. while (pos > 0 && path[pos-1] != '/')
  343. pos--;
  344. pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
  345. if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
  346. errno = ETXTBSY;
  347. return -1;
  348. }
  349. /* start where the last one left off to reduce chance of clashes */
  350. start = counter;
  351. do {
  352. snprintf(&path[pos], MAX_RENAMES_DIGITS+1, "%03d", counter);
  353. if (++counter >= MAX_RENAMES)
  354. counter = 1;
  355. } while ((rc = access(path, 0)) == 0 && counter != start);
  356. if (verbose > 0) {
  357. rprintf(FWARNING, "renaming %s to %s because of text busy\n",
  358. fname, path);
  359. }
  360. /* maybe we should return rename()'s exit status? Nah. */
  361. if (do_rename(fname, path) != 0) {
  362. errno = ETXTBSY;
  363. return -1;
  364. }
  365. return 0;
  366. #endif
  367. }
  368. /* Returns 0 on successful rename, 1 if we successfully copied the file
  369. * across filesystems, -2 if copy_file() failed, and -1 on other errors.
  370. * If partialptr is not NULL and we need to do a copy, copy the file into
  371. * the active partial-dir instead of over the destination file. */
  372. int robust_rename(const char *from, const char *to, const char *partialptr,
  373. int mode)
  374. {
  375. int tries = 4;
  376. while (tries--) {
  377. if (do_rename(from, to) == 0)
  378. return 0;
  379. switch (errno) {
  380. #ifdef ETXTBSY
  381. case ETXTBSY:
  382. if (robust_unlink(to) != 0) {
  383. errno = ETXTBSY;
  384. return -1;
  385. }
  386. errno = ETXTBSY;
  387. break;
  388. #endif
  389. case EXDEV:
  390. if (partialptr) {
  391. if (!handle_partial_dir(partialptr,PDIR_CREATE))
  392. return -2;
  393. to = partialptr;
  394. }
  395. if (copy_file(from, to, -1, mode, 0) != 0)
  396. return -2;
  397. do_unlink(from);
  398. return 1;
  399. default:
  400. return -1;
  401. }
  402. }
  403. return -1;
  404. }
  405. static pid_t all_pids[10];
  406. static int num_pids;
  407. /** Fork and record the pid of the child. **/
  408. pid_t do_fork(void)
  409. {
  410. pid_t newpid = fork();
  411. if (newpid != 0 && newpid != -1) {
  412. all_pids[num_pids++] = newpid;
  413. }
  414. return newpid;
  415. }
  416. /**
  417. * Kill all children.
  418. *
  419. * @todo It would be kind of nice to make sure that they are actually
  420. * all our children before we kill them, because their pids may have
  421. * been recycled by some other process. Perhaps when we wait for a
  422. * child, we should remove it from this array. Alternatively we could
  423. * perhaps use process groups, but I think that would not work on
  424. * ancient Unix versions that don't support them.
  425. **/
  426. void kill_all(int sig)
  427. {
  428. int i;
  429. for (i = 0; i < num_pids; i++) {
  430. /* Let's just be a little careful where we
  431. * point that gun, hey? See kill(2) for the
  432. * magic caused by negative values. */
  433. pid_t p = all_pids[i];
  434. if (p == getpid())
  435. continue;
  436. if (p <= 0)
  437. continue;
  438. kill(p, sig);
  439. }
  440. }
  441. /** Turn a user name into a uid */
  442. int name_to_uid(const char *name, uid_t *uid_p)
  443. {
  444. struct passwd *pass;
  445. if (!name || !*name)
  446. return 0;
  447. if (!(pass = getpwnam(name)))
  448. return 0;
  449. *uid_p = pass->pw_uid;
  450. return 1;
  451. }
  452. /** Turn a group name into a gid */
  453. int name_to_gid(const char *name, gid_t *gid_p)
  454. {
  455. struct group *grp;
  456. if (!name || !*name)
  457. return 0;
  458. if (!(grp = getgrnam(name)))
  459. return 0;
  460. *gid_p = grp->gr_gid;
  461. return 1;
  462. }
  463. /** Lock a byte range in a open file */
  464. int lock_range(int fd, int offset, int len)
  465. {
  466. struct flock lock;
  467. lock.l_type = F_WRLCK;
  468. lock.l_whence = SEEK_SET;
  469. lock.l_start = offset;
  470. lock.l_len = len;
  471. lock.l_pid = 0;
  472. return fcntl(fd,F_SETLK,&lock) == 0;
  473. }
  474. #define ENSURE_MEMSPACE(buf, type, sz, req) \
  475. if ((req) > sz && !(buf = realloc_array(buf, type, sz = MAX(sz * 2, req)))) \
  476. out_of_memory("glob_expand")
  477. static inline void call_glob_match(const char *name, int len, int from_glob,
  478. char *arg, int abpos, int fbpos);
  479. static struct glob_data {
  480. char *arg_buf, *filt_buf, **argv;
  481. int absize, fbsize, maxargs, argc;
  482. } glob;
  483. static void glob_match(char *arg, int abpos, int fbpos)
  484. {
  485. int len;
  486. char *slash;
  487. while (*arg == '.' && arg[1] == '/') {
  488. if (fbpos < 0) {
  489. ENSURE_MEMSPACE(glob.filt_buf, char, glob.fbsize, glob.absize);
  490. memcpy(glob.filt_buf, glob.arg_buf, abpos + 1);
  491. fbpos = abpos;
  492. }
  493. ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, abpos + 3);
  494. glob.arg_buf[abpos++] = *arg++;
  495. glob.arg_buf[abpos++] = *arg++;
  496. glob.arg_buf[abpos] = '\0';
  497. }
  498. if ((slash = strchr(arg, '/')) != NULL) {
  499. *slash = '\0';
  500. len = slash - arg;
  501. } else
  502. len = strlen(arg);
  503. if (strpbrk(arg, "*?[")) {
  504. struct dirent *di;
  505. DIR *d;
  506. if (!(d = opendir(abpos ? glob.arg_buf : ".")))
  507. return;
  508. while ((di = readdir(d)) != NULL) {
  509. char *dname = d_name(di);
  510. if (dname[0] == '.' && (dname[1] == '\0'
  511. || (dname[1] == '.' && dname[2] == '\0')))
  512. continue;
  513. if (!wildmatch(arg, dname))
  514. continue;
  515. call_glob_match(dname, strlen(dname), 1,
  516. slash ? arg + len + 1 : NULL,
  517. abpos, fbpos);
  518. }
  519. closedir(d);
  520. } else {
  521. call_glob_match(arg, len, 0,
  522. slash ? arg + len + 1 : NULL,
  523. abpos, fbpos);
  524. }
  525. if (slash)
  526. *slash = '/';
  527. }
  528. static inline void call_glob_match(const char *name, int len, int from_glob,
  529. char *arg, int abpos, int fbpos)
  530. {
  531. char *use_buf;
  532. ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, abpos + len + 2);
  533. memcpy(glob.arg_buf + abpos, name, len);
  534. abpos += len;
  535. glob.arg_buf[abpos] = '\0';
  536. if (fbpos >= 0) {
  537. ENSURE_MEMSPACE(glob.filt_buf, char, glob.fbsize, fbpos + len + 2);
  538. memcpy(glob.filt_buf + fbpos, name, len);
  539. fbpos += len;
  540. glob.filt_buf[fbpos] = '\0';
  541. use_buf = glob.filt_buf;
  542. } else
  543. use_buf = glob.arg_buf;
  544. if (from_glob || (arg && len)) {
  545. STRUCT_STAT st;
  546. int is_dir;
  547. if (do_stat(glob.arg_buf, &st) != 0)
  548. return;
  549. is_dir = S_ISDIR(st.st_mode) != 0;
  550. if (arg && !is_dir)
  551. return;
  552. if (daemon_filter_list.head
  553. && check_filter(&daemon_filter_list, FLOG, use_buf, is_dir) < 0)
  554. return;
  555. }
  556. if (arg) {
  557. glob.arg_buf[abpos++] = '/';
  558. glob.arg_buf[abpos] = '\0';
  559. if (fbpos >= 0) {
  560. glob.filt_buf[fbpos++] = '/';
  561. glob.filt_buf[fbpos] = '\0';
  562. }
  563. glob_match(arg, abpos, fbpos);
  564. } else {
  565. ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, glob.argc + 1);
  566. if (!(glob.argv[glob.argc++] = strdup(glob.arg_buf)))
  567. out_of_memory("glob_match");
  568. }
  569. }
  570. /* This routine performs wild-card expansion of the pathname in "arg". Any
  571. * daemon-excluded files/dirs will not be matched by the wildcards. Returns 0
  572. * if a wild-card string is the only returned item (due to matching nothing). */
  573. int glob_expand(const char *arg, char ***argv_p, int *argc_p, int *maxargs_p)
  574. {
  575. int ret, save_argc;
  576. char *s;
  577. if (!arg) {
  578. if (glob.filt_buf)
  579. free(glob.filt_buf);
  580. free(glob.arg_buf);
  581. memset(&glob, 0, sizeof glob);
  582. return -1;
  583. }
  584. if (sanitize_paths)
  585. s = sanitize_path(NULL, arg, "", 0, SP_KEEP_DOT_DIRS);
  586. else {
  587. s = strdup(arg);
  588. if (!s)
  589. out_of_memory("glob_expand");
  590. clean_fname(s, CFN_KEEP_DOT_DIRS
  591. | CFN_KEEP_TRAILING_SLASH
  592. | CFN_COLLAPSE_DOT_DOT_DIRS);
  593. }
  594. ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, MAXPATHLEN);
  595. *glob.arg_buf = '\0';
  596. glob.argc = save_argc = *argc_p;
  597. glob.argv = *argv_p;
  598. glob.maxargs = *maxargs_p;
  599. ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, 100);
  600. glob_match(s, 0, -1);
  601. /* The arg didn't match anything, so add the failed arg to the list. */
  602. if (glob.argc == save_argc) {
  603. ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, glob.argc + 1);
  604. glob.argv[glob.argc++] = s;
  605. ret = 0;
  606. } else {
  607. free(s);
  608. ret = 1;
  609. }
  610. *maxargs_p = glob.maxargs;
  611. *argv_p = glob.argv;
  612. *argc_p = glob.argc;
  613. return ret;
  614. }
  615. /* This routine is only used in daemon mode. */
  616. void glob_expand_module(char *base1, char *arg, char ***argv_p, int *argc_p, int *maxargs_p)
  617. {
  618. char *p, *s;
  619. char *base = base1;
  620. int base_len = strlen(base);
  621. if (!arg || !*arg)
  622. return;
  623. if (strncmp(arg, base, base_len) == 0)
  624. arg += base_len;
  625. if (!(arg = strdup(arg)))
  626. out_of_memory("glob_expand_module");
  627. if (asprintf(&base," %s/", base1) <= 0)
  628. out_of_memory("glob_expand_module");
  629. base_len++;
  630. for (s = arg; *s; s = p + base_len) {
  631. if ((p = strstr(s, base)) != NULL)
  632. *p = '\0'; /* split it at this point */
  633. glob_expand(s, argv_p, argc_p, maxargs_p);
  634. if (!p)
  635. break;
  636. }
  637. free(arg);
  638. free(base);
  639. }
  640. /**
  641. * Convert a string to lower case
  642. **/
  643. void strlower(char *s)
  644. {
  645. while (*s) {
  646. if (isUpper(s))
  647. *s = toLower(s);
  648. s++;
  649. }
  650. }
  651. /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them. (If
  652. * p1 ends with a '/', no extra '/' is inserted.) Returns the length of both
  653. * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
  654. * string fits into destsize. */
  655. size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
  656. {
  657. size_t len = strlcpy(dest, p1, destsize);
  658. if (len < destsize - 1) {
  659. if (!len || dest[len-1] != '/')
  660. dest[len++] = '/';
  661. if (len < destsize - 1)
  662. len += strlcpy(dest + len, p2, destsize - len);
  663. else {
  664. dest[len] = '\0';
  665. len += strlen(p2);
  666. }
  667. }
  668. else
  669. len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
  670. return len;
  671. }
  672. /* Join any number of strings together, putting them in "dest". The return
  673. * value is the length of all the strings, regardless of whether the null-
  674. * terminated whole fits in destsize. Your list of string pointers must end
  675. * with a NULL to indicate the end of the list. */
  676. size_t stringjoin(char *dest, size_t destsize, ...)
  677. {
  678. va_list ap;
  679. size_t len, ret = 0;
  680. const char *src;
  681. va_start(ap, destsize);
  682. while (1) {
  683. if (!(src = va_arg(ap, const char *)))
  684. break;
  685. len = strlen(src);
  686. ret += len;
  687. if (destsize > 1) {
  688. if (len >= destsize)
  689. len = destsize - 1;
  690. memcpy(dest, src, len);
  691. destsize -= len;
  692. dest += len;
  693. }
  694. }
  695. *dest = '\0';
  696. va_end(ap);
  697. return ret;
  698. }
  699. int count_dir_elements(const char *p)
  700. {
  701. int cnt = 0, new_component = 1;
  702. while (*p) {
  703. if (*p++ == '/')
  704. new_component = (*p != '.' || (p[1] != '/' && p[1] != '\0'));
  705. else if (new_component) {
  706. new_component = 0;
  707. cnt++;
  708. }
  709. }
  710. return cnt;
  711. }
  712. /* Turns multiple adjacent slashes into a single slash (possible exception:
  713. * the preserving of two leading slashes at the start), drops all leading or
  714. * interior "." elements unless CFN_KEEP_DOT_DIRS is flagged. Will also drop
  715. * a trailing '.' after a '/' if CFN_DROP_TRAILING_DOT_DIR is flagged, removes
  716. * a trailing slash (perhaps after removing the aforementioned dot) unless
  717. * CFN_KEEP_TRAILING_SLASH is flagged, and will also collapse ".." elements
  718. * (except at the start) if CFN_COLLAPSE_DOT_DOT_DIRS is flagged. If the
  719. * resulting name would be empty, returns ".". */
  720. unsigned int clean_fname(char *name, int flags)
  721. {
  722. char *limit = name - 1, *t = name, *f = name;
  723. int anchored;
  724. if (!name)
  725. return 0;
  726. if ((anchored = *f == '/') != 0) {
  727. *t++ = *f++;
  728. #ifdef __CYGWIN__
  729. /* If there are exactly 2 slashes at the start, preserve
  730. * them. Would break daemon excludes unless the paths are
  731. * really treated differently, so used this sparingly. */
  732. if (*f == '/' && f[1] != '/')
  733. *t++ = *f++;
  734. #endif
  735. } else if (flags & CFN_KEEP_DOT_DIRS && *f == '.' && f[1] == '/') {
  736. *t++ = *f++;
  737. *t++ = *f++;
  738. }
  739. while (*f) {
  740. /* discard extra slashes */
  741. if (*f == '/') {
  742. f++;
  743. continue;
  744. }
  745. if (*f == '.') {
  746. /* discard interior "." dirs */
  747. if (f[1] == '/' && !(flags & CFN_KEEP_DOT_DIRS)) {
  748. f += 2;
  749. continue;
  750. }
  751. if (f[1] == '\0' && flags & CFN_DROP_TRAILING_DOT_DIR)
  752. break;
  753. /* collapse ".." dirs */
  754. if (flags & CFN_COLLAPSE_DOT_DOT_DIRS
  755. && f[1] == '.' && (f[2] == '/' || !f[2])) {
  756. char *s = t - 1;
  757. if (s == name && anchored) {
  758. f += 2;
  759. continue;
  760. }
  761. while (s > limit && *--s != '/') {}
  762. if (s != t - 1 && (s < name || *s == '/')) {
  763. t = s + 1;
  764. f += 2;
  765. continue;
  766. }
  767. limit = t + 2;
  768. }
  769. }
  770. while (*f && (*t++ = *f++) != '/') {}
  771. }
  772. if (t > name+anchored && t[-1] == '/' && !(flags & CFN_KEEP_TRAILING_SLASH))
  773. t--;
  774. if (t == name)
  775. *t++ = '.';
  776. *t = '\0';
  777. return t - name;
  778. }
  779. /* Make path appear as if a chroot had occurred. This handles a leading
  780. * "/" (either removing it or expanding it) and any leading or embedded
  781. * ".." components that attempt to escape past the module's top dir.
  782. *
  783. * If dest is NULL, a buffer is allocated to hold the result. It is legal
  784. * to call with the dest and the path (p) pointing to the same buffer, but
  785. * rootdir will be ignored to avoid expansion of the string.
  786. *
  787. * The rootdir string contains a value to use in place of a leading slash.
  788. * Specify NULL to get the default of "module_dir".
  789. *
  790. * The depth var is a count of how many '..'s to allow at the start of the
  791. * path.
  792. *
  793. * We also clean the path in a manner similar to clean_fname() but with a
  794. * few differences:
  795. *
  796. * Turns multiple adjacent slashes into a single slash, gets rid of "." dir
  797. * elements (INCLUDING a trailing dot dir), PRESERVES a trailing slash, and
  798. * ALWAYS collapses ".." elements (except for those at the start of the
  799. * string up to "depth" deep). If the resulting name would be empty,
  800. * change it into a ".". */
  801. char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
  802. int flags)
  803. {
  804. char *start, *sanp;
  805. int rlen = 0, drop_dot_dirs = !relative_paths || !(flags & SP_KEEP_DOT_DIRS);
  806. if (dest != p) {
  807. int plen = strlen(p);
  808. if (*p == '/') {
  809. if (!rootdir)
  810. rootdir = module_dir;
  811. rlen = strlen(rootdir);
  812. depth = 0;
  813. p++;
  814. }
  815. if (dest) {
  816. if (rlen + plen + 1 >= MAXPATHLEN)
  817. return NULL;
  818. } else if (!(dest = new_array(char, rlen + plen + 1)))
  819. out_of_memory("sanitize_path");
  820. if (rlen) {
  821. memcpy(dest, rootdir, rlen);
  822. if (rlen > 1)
  823. dest[rlen++] = '/';
  824. }
  825. }
  826. if (drop_dot_dirs) {
  827. while (*p == '.' && p[1] == '/')
  828. p += 2;
  829. }
  830. start = sanp = dest + rlen;
  831. /* This loop iterates once per filename component in p, pointing at
  832. * the start of the name (past any prior slash) for each iteration. */
  833. while (*p) {
  834. /* discard leading or extra slashes */
  835. if (*p == '/') {
  836. p++;
  837. continue;
  838. }
  839. if (drop_dot_dirs) {
  840. if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
  841. /* skip "." component */
  842. p++;
  843. continue;
  844. }
  845. }
  846. if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
  847. /* ".." component followed by slash or end */
  848. if (depth <= 0 || sanp != start) {
  849. p += 2;
  850. if (sanp != start) {
  851. /* back up sanp one level */
  852. --sanp; /* now pointing at slash */
  853. while (sanp > start && sanp[-1] != '/')
  854. sanp--;
  855. }
  856. continue;
  857. }
  858. /* allow depth levels of .. at the beginning */
  859. depth--;
  860. /* move the virtual beginning to leave the .. alone */
  861. start = sanp + 3;
  862. }
  863. /* copy one component through next slash */
  864. while (*p && (*sanp++ = *p++) != '/') {}
  865. }
  866. if (sanp == dest) {
  867. /* ended up with nothing, so put in "." component */
  868. *sanp++ = '.';
  869. }
  870. *sanp = '\0';
  871. return dest;
  872. }
  873. /* Like chdir(), but it keeps track of the current directory (in the
  874. * global "curr_dir"), and ensures that the path size doesn't overflow.
  875. * Also cleans the path using the clean_fname() function. */
  876. int change_dir(const char *dir, int set_path_only)
  877. {
  878. static int initialised;
  879. unsigned int len;
  880. if (!initialised) {
  881. initialised = 1;
  882. if (getcwd(curr_dir, sizeof curr_dir - 1) == NULL) {
  883. rsyserr(FERROR, errno, "getcwd()");
  884. exit_cleanup(RERR_FILESELECT);
  885. }
  886. curr_dir_len = strlen(curr_dir);
  887. }
  888. if (!dir) /* this call was probably just to initialize */
  889. return 0;
  890. len = strlen(dir);
  891. if (len == 1 && *dir == '.')
  892. return 1;
  893. if (*dir == '/') {
  894. if (len >= sizeof curr_dir) {
  895. errno = ENAMETOOLONG;
  896. return 0;
  897. }
  898. if (!set_path_only && chdir(dir))
  899. return 0;
  900. memcpy(curr_dir, dir, len + 1);
  901. } else {
  902. if (curr_dir_len + 1 + len >= sizeof curr_dir) {
  903. errno = ENAMETOOLONG;
  904. return 0;
  905. }
  906. if (!(curr_dir_len && curr_dir[curr_dir_len-1] == '/'))
  907. curr_dir[curr_dir_len++] = '/';
  908. memcpy(curr_dir + curr_dir_len, dir, len + 1);
  909. if (!set_path_only && chdir(curr_dir)) {
  910. curr_dir[curr_dir_len] = '\0';
  911. return 0;
  912. }
  913. }
  914. curr_dir_len = clean_fname(curr_dir, CFN_COLLAPSE_DOT_DOT_DIRS);
  915. if (sanitize_paths) {
  916. if (module_dirlen > curr_dir_len)
  917. module_dirlen = curr_dir_len;
  918. curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
  919. }
  920. if (verbose >= 5 && !set_path_only)
  921. rprintf(FINFO, "[%s] change_dir(%s)\n", who_am_i(), curr_dir);
  922. return 1;
  923. }
  924. /* This will make a relative path absolute and clean it up via clean_fname().
  925. * Returns the string, which might be newly allocated, or NULL on error. */
  926. char *normalize_path(char *path, BOOL force_newbuf, unsigned int *len_ptr)
  927. {
  928. unsigned int len;
  929. if (*path != '/') { /* Make path absolute. */
  930. int len = strlen(path);
  931. if (curr_dir_len + 1 + len >= sizeof curr_dir)
  932. return NULL;
  933. curr_dir[curr_dir_len] = '/';
  934. memcpy(curr_dir + curr_dir_len + 1, path, len + 1);
  935. if (!(path = strdup(curr_dir)))
  936. out_of_memory("normalize_path");
  937. curr_dir[curr_dir_len] = '\0';
  938. } else if (force_newbuf) {
  939. if (!(path = strdup(path)))
  940. out_of_memory("normalize_path");
  941. }
  942. len = clean_fname(path, CFN_COLLAPSE_DOT_DOT_DIRS | CFN_DROP_TRAILING_DOT_DIR);
  943. if (len_ptr)
  944. *len_ptr = len;
  945. return path;
  946. }
  947. /**
  948. * Return a quoted string with the full pathname of the indicated filename.
  949. * The string " (in MODNAME)" may also be appended. The returned pointer
  950. * remains valid until the next time full_fname() is called.
  951. **/
  952. char *full_fname(const char *fn)
  953. {
  954. static char *result = NULL;
  955. char *m1, *m2, *m3;
  956. char *p1, *p2;
  957. if (result)
  958. free(result);
  959. if (*fn == '/')
  960. p1 = p2 = "";
  961. else {
  962. p1 = curr_dir + module_dirlen;
  963. for (p2 = p1; *p2 == '/'; p2++) {}
  964. if (*p2)
  965. p2 = "/";
  966. }
  967. if (module_id >= 0) {
  968. m1 = " (in ";
  969. m2 = lp_name(module_id);
  970. m3 = ")";
  971. } else
  972. m1 = m2 = m3 = "";
  973. if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) <= 0)
  974. out_of_memory("full_fname");
  975. return result;
  976. }
  977. static char partial_fname[MAXPATHLEN];
  978. char *partial_dir_fname(const char *fname)
  979. {
  980. char *t = partial_fname;
  981. int sz = sizeof partial_fname;
  982. const char *fn;
  983. if ((fn = strrchr(fname, '/')) != NULL) {
  984. fn++;
  985. if (*partial_dir != '/') {
  986. int len = fn - fname;
  987. strncpy(t, fname, len); /* safe */
  988. t += len;
  989. sz -= len;
  990. }
  991. } else
  992. fn = fname;
  993. if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
  994. return NULL;
  995. if (daemon_filter_list.head) {
  996. t = strrchr(partial_fname, '/');
  997. *t = '\0';
  998. if (check_filter(&daemon_filter_list, FLOG, partial_fname, 1) < 0)
  999. return NULL;
  1000. *t = '/';
  1001. if (check_filter(&daemon_filter_list, FLOG, partial_fname, 0) < 0)
  1002. return NULL;
  1003. }
  1004. return partial_fname;
  1005. }
  1006. /* If no --partial-dir option was specified, we don't need to do anything
  1007. * (the partial-dir is essentially '.'), so just return success. */
  1008. int handle_partial_dir(const char *fname, int create)
  1009. {
  1010. char *fn, *dir;
  1011. if (fname != partial_fname)
  1012. return 1;
  1013. if (!create && *partial_dir == '/')
  1014. return 1;
  1015. if (!(fn = strrchr(partial_fname, '/')))
  1016. return 1;
  1017. *fn = '\0';
  1018. dir = partial_fname;
  1019. if (create) {
  1020. STRUCT_STAT st;
  1021. int statret = do_lstat(dir, &st);
  1022. if (statret == 0 && !S_ISDIR(st.st_mode)) {
  1023. if (do_unlink(dir) < 0) {
  1024. *fn = '/';
  1025. return 0;
  1026. }
  1027. statret = -1;
  1028. }
  1029. if (statret < 0 && do_mkdir(dir, 0700) < 0) {
  1030. *fn = '/';
  1031. return 0;
  1032. }
  1033. } else
  1034. do_rmdir(dir);
  1035. *fn = '/';
  1036. return 1;
  1037. }
  1038. /* Determine if a symlink points outside the current directory tree.
  1039. * This is considered "unsafe" because e.g. when mirroring somebody
  1040. * else's machine it might allow them to establish a symlink to
  1041. * /etc/passwd, and then read it through a web server.
  1042. *
  1043. * Returns 1 if unsafe, 0 if safe.
  1044. *
  1045. * Null symlinks and absolute symlinks are always unsafe.
  1046. *
  1047. * Basically here we are concerned with symlinks whose target contains
  1048. * "..", because this might cause us to walk back up out of the
  1049. * transferred directory. We are not allowed to go back up and
  1050. * reenter.
  1051. *
  1052. * "dest" is the target of the symlink in question.
  1053. *
  1054. * "src" is the top source directory currently applicable at the level
  1055. * of the referenced symlink. This is usually the symlink's full path
  1056. * (including its name), as referenced from the root of the transfer. */
  1057. int unsafe_symlink(const char *dest, const char *src)
  1058. {
  1059. const char *name, *slash;
  1060. int depth = 0;
  1061. /* all absolute and null symlinks are unsafe */
  1062. if (!dest || !*dest || *dest == '/')
  1063. return 1;
  1064. /* find out what our safety margin is */
  1065. for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
  1066. /* ".." segment starts the count over. "." segment is ignored. */
  1067. if (*name == '.' && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))) {
  1068. if (name[1] == '.')
  1069. depth = 0;
  1070. } else
  1071. depth++;
  1072. while (slash[1] == '/') slash++; /* just in case src isn't clean */
  1073. }
  1074. if (*name == '.' && name[1] == '.' && name[2] == '\0')
  1075. depth = 0;
  1076. for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
  1077. if (*name == '.' && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))) {
  1078. if (name[1] == '.') {
  1079. /* if at any point we go outside the current directory
  1080. then stop - it is unsafe */
  1081. if (--depth < 0)
  1082. return 1;
  1083. }
  1084. } else
  1085. depth++;
  1086. while (slash[1] == '/') slash++;
  1087. }
  1088. if (*name == '.' && name[1] == '.' && name[2] == '\0')
  1089. depth--;
  1090. return depth < 0;
  1091. }
  1092. #define HUMANIFY(mult) \
  1093. do { \
  1094. if (num >= mult || num <= -mult) { \
  1095. double dnum = (double)num / mult; \
  1096. char units; \
  1097. if (num < 0) \
  1098. dnum = -dnum; \
  1099. if (dnum < mult) \
  1100. units = 'K'; \
  1101. else if ((dnum /= mult) < mult) \
  1102. units = 'M'; \
  1103. else { \
  1104. dnum /= mult; \
  1105. units = 'G'; \
  1106. } \
  1107. if (num < 0) \
  1108. dnum = -dnum; \
  1109. snprintf(bufs[n], sizeof bufs[0], "%.2f%c", dnum, units); \
  1110. return bufs[n]; \
  1111. } \
  1112. } while (0)
  1113. /* Return the int64 number as a string. If the --human-readable option was
  1114. * specified, we may output the number in K, M, or G units. We can return
  1115. * up to 4 buffers at a time. */
  1116. char *human_num(int64 num)
  1117. {
  1118. static char bufs[4][128]; /* more than enough room */
  1119. static unsigned int n;
  1120. char *s;
  1121. int negated;
  1122. n = (n + 1) % (sizeof bufs / sizeof bufs[0]);
  1123. if (human_readable) {
  1124. if (human_readable == 1)
  1125. HUMANIFY(1000);
  1126. else
  1127. HUMANIFY(1024);
  1128. }
  1129. s = bufs[n] + sizeof bufs[0] - 1;
  1130. *s = '\0';
  1131. if (!num)
  1132. *--s = '0';
  1133. if (num < 0) {
  1134. /* A maximum-size negated number can't fit as a positive,
  1135. * so do one digit in negated form to start us off. */
  1136. *--s = (char)(-(num % 10)) + '0';
  1137. num = -(num / 10);
  1138. negated = 1;
  1139. } else
  1140. negated = 0;
  1141. while (num) {
  1142. *--s = (char)(num % 10) + '0';
  1143. num /= 10;
  1144. }
  1145. if (negated)
  1146. *--s = '-';
  1147. return s;
  1148. }
  1149. /* Return the double number as a string. If the --human-readable option was
  1150. * specified, we may output the number in K, M, or G units. We use a buffer
  1151. * from human_num() to return our result. */
  1152. char *human_dnum(double dnum, int decimal_digits)
  1153. {
  1154. char *buf = human_num(dnum);
  1155. int len = strlen(buf);
  1156. if (isDigit(buf + len - 1)) {
  1157. /* There's extra room in buf prior to the start of the num. */
  1158. buf -= decimal_digits + 2;
  1159. snprintf(buf, len + decimal_digits + 3, "%.*f", decimal_digits, dnum);
  1160. }
  1161. return buf;
  1162. }
  1163. /* Return the date and time as a string. Some callers tweak returned buf. */
  1164. char *timestring(time_t t)
  1165. {
  1166. static char TimeBuf[200];
  1167. struct tm *tm = localtime(&t);
  1168. char *p;
  1169. #ifdef HAVE_STRFTIME
  1170. strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
  1171. #else
  1172. strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
  1173. #endif
  1174. if ((p = strchr(TimeBuf, '\n')) != NULL)
  1175. *p = '\0';
  1176. return TimeBuf;
  1177. }
  1178. /**
  1179. * Sleep for a specified number of milliseconds.
  1180. *
  1181. * Always returns TRUE. (In the future it might return FALSE if
  1182. * interrupted.)
  1183. **/
  1184. int msleep(int t)
  1185. {
  1186. int tdiff = 0;
  1187. struct timeval tval, t1, t2;
  1188. gettimeofday(&t1, NULL);
  1189. while (tdiff < t) {
  1190. tval.tv_sec = (t-tdiff)/1000;
  1191. tval.tv_usec = 1000*((t-tdiff)%1000);
  1192. errno = 0;
  1193. select(0,NULL,NULL, NULL, &tval);
  1194. gettimeofday(&t2, NULL);
  1195. tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
  1196. (t2.tv_usec - t1.tv_usec)/1000;
  1197. }
  1198. return True;
  1199. }
  1200. /* Determine if two time_t values are equivalent (either exact, or in
  1201. * the modification timestamp window established by --modify-window).
  1202. *
  1203. * @retval 0 if the times should be treated as the same
  1204. *
  1205. * @retval +1 if the first is later
  1206. *
  1207. * @retval -1 if the 2nd is later
  1208. **/
  1209. int cmp_time(time_t file1, time_t file2)
  1210. {
  1211. if (file2 > file1) {
  1212. if (file2 - file1 <= modify_window)
  1213. return 0;
  1214. return -1;
  1215. }
  1216. if (file1 - file2 <= modify_window)
  1217. return 0;
  1218. return 1;
  1219. }
  1220. #ifdef __INSURE__XX
  1221. #include <dlfcn.h>
  1222. /**
  1223. This routine is a trick to immediately catch errors when debugging
  1224. with insure. A xterm with a gdb is popped up when insure catches
  1225. a error. It is Linux specific.
  1226. **/
  1227. int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
  1228. {
  1229. static int (*fn)();
  1230. int ret;
  1231. char *cmd;
  1232. asprintf(&cmd, "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'",
  1233. getpid(), getpid(), getpid());
  1234. if (!fn) {
  1235. static void *h;
  1236. h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
  1237. fn = dlsym(h, "_Insure_trap_error");
  1238. }
  1239. ret = fn(a1, a2, a3, a4, a5, a6);
  1240. system(cmd);
  1241. free(cmd);
  1242. return ret;
  1243. }
  1244. #endif
  1245. #define MALLOC_MAX 0x40000000
  1246. void *_new_array(unsigned long num, unsigned int size, int use_calloc)
  1247. {
  1248. if (num >= MALLOC_MAX/size)
  1249. return NULL;
  1250. return use_calloc ? calloc(num, size) : malloc(num * size);
  1251. }
  1252. void *_realloc_array(void *ptr, unsigned int size, size_t num)
  1253. {
  1254. if (num >= MALLOC_MAX/size)
  1255. return NULL;
  1256. if (!ptr)
  1257. return malloc(size * num);
  1258. return realloc(ptr, size * num);
  1259. }
  1260. /* Take a filename and filename length and return the most significant
  1261. * filename suffix we can find. This ignores suffixes such as "~",
  1262. * ".bak", ".orig", ".~1~", etc. */
  1263. const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
  1264. {
  1265. const char *suf, *s;
  1266. BOOL had_tilde;
  1267. int s_len;
  1268. /* One or more dots at the start aren't a suffix. */
  1269. while (fn_len && *fn == '.') fn++, fn_len--;
  1270. /* Ignore the ~ in a "foo~" filename. */
  1271. if (fn_len > 1 && fn[fn_len-1] == '~')
  1272. fn_len--, had_tilde = True;
  1273. else
  1274. had_tilde = False;
  1275. /* Assume we don't find an suffix. */
  1276. suf = "";
  1277. *len_ptr = 0;
  1278. /* Find the last significant suffix. */
  1279. for (s = fn + fn_len; fn_len > 1; ) {
  1280. while (*--s != '.' && s != fn) {}
  1281. if (s == fn)
  1282. break;
  1283. s_len = fn_len - (s - fn);
  1284. fn_len = s - fn;
  1285. if (s_len == 4) {
  1286. if (strcmp(s+1, "bak") == 0
  1287. || strcmp(s+1, "old") == 0)
  1288. continue;
  1289. } else if (s_len == 5) {
  1290. if (strcmp(s+1, "orig") == 0)
  1291. continue;
  1292. } else if (s_len > 2 && had_tilde
  1293. && s[1] == '~' && isDigit(s + 2))
  1294. continue;
  1295. *len_ptr = s_len;
  1296. suf = s;
  1297. if (s_len == 1)
  1298. break;
  1299. /* Determine if the suffix is all digits. */
  1300. for (s++, s_len--; s_len > 0; s++, s_len--) {
  1301. if (!isDigit(s))
  1302. return suf;
  1303. }
  1304. /* An all-digit suffix may not be that signficant. */
  1305. s = suf;
  1306. }
  1307. return suf;
  1308. }
  1309. /* This is an implementation of the Levenshtein distance algorithm. It
  1310. * was implemented to avoid needing a two-dimensional matrix (to save
  1311. * memory). It was also tweaked to try to factor in the ASCII distance
  1312. * between changed characters as a minor distance quantity. The normal
  1313. * Levenshtein units of distance (each signifying a single change between
  1314. * the two strings) are defined as a "UNIT". */
  1315. #define UNIT (1 << 16)
  1316. uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
  1317. {
  1318. uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
  1319. int32 cost;
  1320. int i1, i2;
  1321. if (!len1 || !len2) {
  1322. if (!len1) {
  1323. s1 = s2;
  1324. len1 = len2;
  1325. }
  1326. for (i1 = 0, cost = 0; i1 < len1; i1++)
  1327. cost += s1[i1];
  1328. return (int32)len1 * UNIT + cost;
  1329. }
  1330. for (i2 = 0; i2 < len2; i2++)
  1331. a[i2] = (i2+1) * UNIT;
  1332. for (i1 = 0; i1 < len1; i1++) {
  1333. diag = i1 * UNIT;
  1334. above = (i1+1) * UNIT;
  1335. for (i2 = 0; i2 < len2; i2++) {
  1336. left = a[i2];
  1337. if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
  1338. if (cost < 0)
  1339. cost = UNIT - cost;
  1340. else
  1341. cost = UNIT + cost;
  1342. }
  1343. diag_inc = diag + cost;
  1344. left_inc = left + UNIT + *((uchar*)s1+i1);
  1345. above_inc = above + UNIT + *((uchar*)s2+i2);
  1346. a[i2] = above = left < above
  1347. ? (left_inc < diag_inc ? left_inc : diag_inc)
  1348. : (above_inc < diag_inc ? above_inc : diag_inc);
  1349. diag = left;
  1350. }
  1351. }
  1352. return a[len2-1];
  1353. }
  1354. #define BB_SLOT_SIZE (16*1024) /* Desired size in bytes */
  1355. #define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
  1356. #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
  1357. struct bitbag {
  1358. uint32 **bits;
  1359. int slot_cnt;
  1360. };
  1361. struct bitbag *bitbag_create(int max_ndx)
  1362. {
  1363. struct bitbag *bb = new(struct bitbag);
  1364. bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
  1365. if (!(bb->bits = (uint32**)calloc(bb->slot_cnt, sizeof (uint32*))))
  1366. out_of_memory("bitbag_create");
  1367. return bb;
  1368. }
  1369. void bitbag_set_bit(struct bitbag *bb, int ndx)
  1370. {
  1371. int slot = ndx / BB_PER_SLOT_BITS;
  1372. ndx %= BB_PER_SLOT_BITS;
  1373. if (!bb->bits[slot]) {
  1374. if (!(bb->bits[slot] = (uint32*)calloc(BB_PER_SLOT_INTS, 4)))
  1375. out_of_memory("bitbag_set_bit");
  1376. }
  1377. bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
  1378. }
  1379. #if 0 /* not needed yet */
  1380. void bitbag_clear_bit(struct bitbag *bb, int ndx)
  1381. {
  1382. int slot = ndx / BB_PER_SLOT_BITS;
  1383. ndx %= BB_PER_SLOT_BITS;
  1384. if (!bb->bits[slot])
  1385. return;
  1386. bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
  1387. }
  1388. int bitbag_check_bit(struct bitbag *bb, int ndx)
  1389. {
  1390. int slot = ndx / BB_PER_SLOT_BITS;
  1391. ndx %= BB_PER_SLOT_BITS;
  1392. if (!bb->bits[slot])
  1393. return 0;
  1394. return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
  1395. }
  1396. #endif
  1397. /* Call this with -1 to start checking from 0. Returns -1 at the end. */
  1398. int bitbag_next_bit(struct bitbag *bb, int after)
  1399. {
  1400. uint32 bits, mask;
  1401. int i, ndx = after + 1;
  1402. int slot = ndx / BB_PER_SLOT_BITS;
  1403. ndx %= BB_PER_SLOT_BITS;
  1404. mask = (1u << (ndx % 32)) - 1;
  1405. for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
  1406. if (!bb->bits[slot])
  1407. continue;
  1408. for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
  1409. if (!(bits = bb->bits[slot][i] & ~mask))
  1410. continue;
  1411. /* The xor magic figures out the lowest enabled bit in
  1412. * bits, and the switch quickly computes log2(bit). */
  1413. switch (bits ^ (bits & (bits-1))) {
  1414. #define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
  1415. LOG2(0); LOG2(1); LOG2(2); LOG2(3);
  1416. LOG2(4); LOG2(5); LOG2(6); LOG2(7);
  1417. LOG2(8); LOG2(9); LOG2(10); LOG2(11);
  1418. LOG2(12); LOG2(13); LOG2(14); LOG2(15);
  1419. LOG2(16); LOG2(17); LOG2(18); LOG2(19);
  1420. LOG2(20); LOG2(21); LOG2(22); LOG2(23);
  1421. LOG2(24); LOG2(25); LOG2(26); LOG2(27);
  1422. LOG2(28); LOG2(29); LOG2(30); LOG2(31);
  1423. }
  1424. return -1; /* impossible... */
  1425. }
  1426. }
  1427. return -1;
  1428. }
  1429. void flist_ndx_push(flist_ndx_list *lp, int ndx)
  1430. {
  1431. struct flist_ndx_item *item;
  1432. if (!(item = new(struct flist_ndx_item)))
  1433. out_of_memory("flist_ndx_push");
  1434. item->next = NULL;
  1435. item->ndx = ndx;
  1436. if (lp->tail)
  1437. lp->tail->next = item;
  1438. else
  1439. lp->head = item;
  1440. lp->tail = item;
  1441. }
  1442. int flist_ndx_pop(flist_ndx_list *lp)
  1443. {
  1444. struct flist_ndx_item *next;
  1445. int ndx;
  1446. if (!lp->head)
  1447. return -1;
  1448. ndx = lp->head->ndx;
  1449. next = lp->head->next;
  1450. free(lp->head);
  1451. lp->head = next;
  1452. if (!next)
  1453. lp->tail = NULL;
  1454. return ndx;
  1455. }
  1456. void *expand_item_list(item_list *lp, size_t item_size,
  1457. const char *desc, int incr)
  1458. {
  1459. /* First time through, 0 <= 0, so list is expanded. */
  1460. if (lp->malloced <= lp->count) {
  1461. void *new_ptr;
  1462. size_t new_size = lp->malloced;
  1463. if (incr < 0)
  1464. new_size += -incr; /* increase slowly */
  1465. else if (new_size < (size_t)incr)
  1466. new_size += incr;
  1467. else
  1468. new_size *= 2;
  1469. if (new_size < lp->malloced)
  1470. overflow_exit("expand_item_list");
  1471. /* Using _realloc_array() lets us pass the size, not a type. */
  1472. new_ptr = _realloc_array(lp->items, item_size, new_size);
  1473. if (verbose >= 4) {
  1474. rprintf(FINFO, "[%s] expand %s to %.0f bytes, did%s move\n",
  1475. who_am_i(), desc, (double)new_size * item_size,
  1476. new_ptr == lp->items ? " not" : "");
  1477. }
  1478. if (!new_ptr)
  1479. out_of_memory("expand_item_list");
  1480. lp->items = new_ptr;
  1481. lp->malloced = new_size;
  1482. }
  1483. return (char*)lp->items + (lp->count++ * item_size);
  1484. }