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