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