]> pd.if.org Git - zpackage/blob - src/syncfs.c
cleanups
[zpackage] / src / syncfs.c
1 #define _POSIX_C_SOURCE 200809L
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8 #include <dirent.h>
9 #include <limits.h>
10 #include <errno.h>
11 #include <ctype.h>
12 #include <pwd.h>
13 #include <grp.h>
14 #include <math.h>
15 #include <stdarg.h>
16 #include <time.h>
17
18 /* needed for S_IFMT and AT_FDCWD */
19 #include <fcntl.h>
20
21 #include <string.h>
22
23 #include "sqlite3.h"
24 #include "zpm.h"
25
26 struct config {
27         struct zpm *log; /* logging db will be attached as "log" */
28         struct zpm *src;
29         char *dbfile;
30         char *rootdir;
31         int errabort, errors, verbose, dryrun, conflicts;
32         int setuser, setgroup;
33         int reverse, exitonerror;
34         int overwrite, accept, acceptdir, ignoredirmd;
35         unsigned long ops_total, ops_completed;
36         unsigned long ops_remove, ops_remove_completed;
37         unsigned long ops_update, ops_update_completed;
38         unsigned long ops_install, ops_install_completed;
39         int progress; /* type of progress meter */
40 };
41
42 struct nitem {
43         int op;
44         char *opstr;
45         uid_t uid;
46         gid_t gid;
47         char *dest;
48         char *path;
49         char *hash, *ohash;
50         char *mds, *omds;
51         char *target;
52         char *pkglist; /* space separated */
53         time_t mtime;
54         mode_t mode;
55         int ftype;
56         int configuration, oldwasconf;
57         struct timespec times[2];
58 };
59
60 static void usage() {
61         printf("usage: zpm $scriptname [-fncC] args ...\n");
62 }
63
64 static void warn(char *fmt, ...) {
65         va_list args;
66
67         va_start(args, fmt);
68         vfprintf(stderr, fmt, args);
69         va_end(args);
70         fprintf(stderr, "\n");
71 }
72
73 static void pdots(int len, int ch, int was, int now, int total) {
74         was = len * was / total;
75         if (now > total) {
76                 now = total;
77         }
78         now = len * now / total;
79         while (was++ < now) {
80                 putchar(ch);
81         }
82         fflush(stdout);
83 }
84
85 static int seterror(struct config *conf, char *msgfmt, ...) {
86         char msg[1024];
87         va_list ap;
88
89         conf->errors++;
90
91         va_start(ap, msgfmt);
92         vsnprintf(msg, sizeof msg, msgfmt, ap);
93         va_end(ap);
94
95         msg[1023] = 0;
96         if (conf->log->errmsg) {
97                 free(conf->log->errmsg);
98         }
99
100         conf->log->errmsg = strdup(msg);
101
102         if (conf->verbose) {
103                 fprintf(stderr, "%s\n", msg);
104         }
105
106         return conf->errabort;
107 }
108
109 static int setsyserr(struct config *conf, char *msgfmt, ...) {
110         char msg[1024];
111         va_list ap;
112         int printed;
113
114         conf->errors++;
115
116         va_start(ap, msgfmt);
117         printed = vsnprintf(msg, sizeof msg, msgfmt, ap);
118         va_end(ap);
119
120         if (printed < 1) {
121                 /* nothing we can really do */
122                 return conf->errabort;
123         }
124
125         if ((size_t)printed < sizeof msg) {
126                 snprintf(msg+printed, sizeof msg - printed, ": %s",
127                                 strerror(errno));
128         }
129
130         msg[1023] = 0;
131         if (conf->log->errmsg) {
132                 free(conf->log->errmsg);
133         }
134
135         conf->log->errmsg = strdup(msg);
136
137         if (conf->verbose) {
138                 fprintf(stderr, "%s\n", msg);
139         }
140
141         return conf->errabort;
142 }
143
144 static int exists(char *path, mode_t *mode) {
145         struct stat st;
146
147         if (lstat(path, &st) == -1) {
148                 return 0;
149         }
150         if (mode) *mode = st.st_mode;
151         return 1;
152 }
153
154 /* TODO maintain a list of already created directories */
155 static int create_leading_dirs(char *path) {
156         char *delim, *s;
157         int ch = 0;
158         char pcopy[ZPM_PATH_MAX];
159         struct stat st;
160         
161         strcpy(pcopy, path);
162
163         delim = strrchr(pcopy, '/');
164         if (!delim) return 1; /* not an error, but no leading dirs */
165
166         /* cut off last component */
167         *delim = 0;
168
169         s = pcopy;
170         do {
171                 while (*s == '/') {
172                         s++;
173                 }
174
175                 delim = strchr(s, '/');
176                 if (delim) {
177                         ch = *delim;
178                         *delim = 0;
179                 }
180
181                 /* try to create the directory, if it exists
182                  * and is a directory or a symlink, that's ok
183                  * should be (eventually) a symlink to a directory
184                  * so we want stat here, not lstat
185                  */
186                 if (mkdir(pcopy, 0755) == -1) {
187                         switch (errno) {
188                                 case EEXIST:
189                                         if (stat(pcopy, &st) == -1) {
190                                                 /* can't stat? */
191                                                 return 0;
192                                         }
193                                         switch (st.st_mode & S_IFMT) {
194                                                 case S_IFDIR:
195                                                         break;
196                                                 default:
197                                                         return 0;
198                                         }
199                                         break;
200                                 default:
201                                         return 0;
202                         }
203                 }
204                 if (delim) {
205                         *delim = ch;
206                 }
207                 s = delim;
208         } while (delim);
209         
210         return 1;
211 }
212
213 static char *column(char *col, int ncols, char **vals, char **cols) {
214         int i = 0;
215         char *val = NULL;
216
217         for (i=0; i < ncols; i++) {
218 //              fprintf(stderr, "checking '%s' = '%s'\n", cols[i], vals[i]);
219                 
220                 if (!strcmp(col, cols[i])) {
221                         val = vals[i];
222                         break;
223                 }
224         }
225         return val;
226 }
227
228 #define COL(x) column(x, ncols, vals, cols)
229 #define SYSERR(x) do { conf->log->error = 2; return conf->errabort; } while (0)
230
231
232 /* TODO handle other ops properly */
233 static char *ops[] = { "new", "remove", "update", 0 };
234
235 enum op {
236         OP_NEW = 1,
237         OP_REMOVE = 2,
238         OP_UPDATE = 3
239 };
240
241 static int getop(char *opstr) {
242         int i;
243
244         if (!opstr) return 0;
245         for (i=0;ops[i];i++) {
246                 if (!strcmp(opstr, ops[i])) {
247                         return i+1;
248                 }
249         }
250         return 0;
251 }
252
253 static int report_conflicts(void *f, int ncols, char **vals, char **cols) {
254         struct config *conf = f;
255         char *path, *hash, *pkg, *conflict_type, *mds;
256
257         pkg = COL("pkgid");
258         path = COL("path");
259         conflict_type = COL("conflict");
260         if (!strcmp(conflict_type, "hash")) {
261                 hash = COL("hash");
262                 fprintf(stderr, "hash conflict: package %s path %s hash %.8s\n",
263                                 pkg, path, hash);
264         } else
265         if (!strcmp(conflict_type, "md")) {
266                 mds = COL("mds");
267                 fprintf(stderr, "md conflict: package %s path %s md %s\n",
268                                 pkg, path, mds);
269         } else {
270                 fprintf(stderr, "%s conflict: package %s path %s\n",
271                                 conflict_type, pkg, path);
272         }
273
274         conf->conflicts++;
275         return 0;
276 }
277
278 static int read_item(struct config *conf, int ncols, char **vals, char **cols,
279                 struct nitem *n) {
280         char *val;
281         long lval;
282         struct passwd *pw;
283         struct group *gr;
284         struct nitem zero = { 0 };
285
286         *n = zero;
287
288         val = COL("op");
289         if (!val) {
290                 seterror(conf, "can't determine op");
291                 return 0;
292         }
293         n->opstr = val;
294         n->op = getop(val);
295         if (!n->op) {
296                 seterror(conf, "can't determine op");
297                 return 0;
298         }
299
300         n->path = COL("path");
301         if (!n->path) {
302                 seterror(conf, "no file path");
303                 return 0;
304         }
305         if (strlen(n->path) == 0) {
306                 seterror(conf, "zero length path not allowed");
307                 return 0;
308         }
309
310         /* TODO config to dishonor setuid/setgid */
311         n->dest = COL("dest");
312         if (!n->dest) {
313                 seterror(conf, "no file dest");
314                 return 0;
315         }
316
317         if (strlen(n->dest) == 0) {
318                 seterror(conf, "zero length dest not allowed");
319                 return 0;
320         }
321
322         val = COL("mode");
323
324         if (!val) {
325                 seterror(conf, "can't determine mode");
326                 return 0;
327         }
328
329         n->mode = strtoul(val, NULL, 8);
330
331         val = COL("configuration");
332         if (!val) {
333                 seterror(conf, "can't determine config status");
334                 return 0;
335         }
336         lval = strtol(val, NULL, 10);
337
338         n->configuration = ((lval & 1) != 0);
339         n->oldwasconf = ((lval & 2) != 0);
340
341         val = COL("filetype");
342         if (!val || strlen(val) == 0) {
343                 seterror(conf, "can't determine file type");
344                 return 0;
345         }
346         n->ftype = *val;
347
348         /* these can be null */
349         n->ohash = COL("ohash");
350         n->mds = COL("mds");
351         n->omds = COL("omds");
352         n->pkglist = COL("pkglist");
353
354         if (n->ftype == 'r') {
355                 n->hash = COL("hash");
356                 if (!n->hash) {
357                         seterror(conf, "can't get hash");
358                         return 0;
359                 }
360         } else if (n->ftype == 'l') {
361                 n->target = COL("target");
362                 if (!n->target) {
363                         seterror(conf, "can't get target");
364                         return 0;
365                 }
366                 if (strlen(n->target) == 0) {
367                         seterror(conf, "zero length target not allowed");
368                         return 0;
369                 }
370                 n->hash = n->target;
371         }
372
373         if (conf->setuser) {
374                 val = COL("username");
375                 if (!val) {
376                         seterror(conf, "no username");
377                         return 0;
378                 }
379                 pw = getpwnam(val);
380                 if (!pw) {
381                         seterror(conf, "no passwd entry");
382                         return 0;
383                 }
384                 n->uid = pw->pw_uid;
385         } else {
386                 n->uid = geteuid();
387         }
388
389         if (conf->setgroup) {
390                 val = COL("groupname");
391                 if (!val) {
392                         seterror(conf, "no groupname");
393                         return 0;
394                 }
395                 gr = getgrnam(val);
396                 if (!gr) {
397                         seterror(conf, "no group entry for %s", val);
398                         return 0;
399                 }
400                 n->gid = gr->gr_gid;
401         } else {
402                 n->gid = getegid();
403         }
404
405         errno = 0;
406         double mtime = strtod(COL("mtime"),NULL);
407         if (errno) {
408                 mtime = (double)time(NULL);
409         }
410
411         n->mtime = (time_t)mtime;
412
413         n->times[0].tv_sec = 0;
414         n->times[0].tv_nsec = UTIME_OMIT;
415         n->times[1].tv_sec = (time_t)llrint(floor(mtime));
416         n->times[1].tv_nsec = lrint(floor(fmod(mtime,1.0)*1000000000));
417
418         return 1;
419 }
420
421 /* file does not exist */
422 #define D_NOEXIST 0x1
423 /* files are different types */
424 #define D_TYPE 0x2
425 /* metadata is different */
426 #define D_MD 0x4
427 /* content or link target is different */
428 #define D_HASH 0x8
429 /* file to be installed is a directory */
430 #define D_ISDIR  0x10
431 /* path on disk is a directory */
432 #define D_EISDIR 0x20
433 /* usernames different */
434 #define D_UID 0x40
435 /* group names different */
436 #define D_GID 0x80
437 /* file mode is different */
438 #define D_MODE 0x100
439 /* mtimes are different */
440 #define D_MTIME 0x200
441 /* the hash of the file we are supposedly replacing is different than
442  * the the hash of the file on disk
443  */
444 #define D_OHASH 0x400
445 /* file exists, and is a directory, and is empty */
446 #define D_ISEMPTY 0x800
447 /* an error occurred trying to compare the file (other than it doesn't exist */
448 #define D_ERROR 0x1000
449 /* there was a stat error */
450 #define D_STATERROR 0x2000
451 /* there was an error calling readlink */
452 #define D_RLERROR 0x4000
453
454 static int dir_is_empty(char *path) {
455         DIR *dir;
456         struct dirent *dp;
457         int empty;
458
459         dir = opendir(path);
460         if (!dir) {
461                 return -1;
462         }
463
464         dp = readdir(dir);
465         if (dp) {
466                 empty = 0;
467         } else {
468                 empty = 1;
469         }
470         closedir(dir);
471
472         return empty;
473 }
474
475 /* 1 = file doesn't exist, 2 = file is a directory, target isn't */
476 /* 4 == ftype different */
477 /* 8 = hash different when both are regular files */
478 static unsigned int file_compare(struct nitem *n, struct stat *st) {
479         int etype = 0, stat_type;
480         char ehash[ZPM_HASH_STRLEN+1];
481         unsigned int diff = 0;
482         char link[1024];
483         ssize_t lsize;
484
485         switch (n->ftype) {
486                 case 'd': etype = S_IFDIR; diff |= D_ISDIR ; break;
487                 case 'r': etype = S_IFREG; break;
488                 case 'l': etype = S_IFLNK; break;
489                 default: etype = 0; break;
490         }
491
492         errno = 0;
493         /* new file, so check type, hash, etc */
494         if (lstat(n->dest, st) == 0) {
495                 stat_type = st->st_mode & S_IFMT;
496                 if (stat_type != etype) {
497                         diff |= D_TYPE;
498                 }
499                 if (stat_type == S_IFDIR) {
500                         diff |= D_EISDIR;
501                         if (dir_is_empty(n->dest)) {
502                                 diff |= D_ISEMPTY;
503                         }
504                 }
505
506                 if (n->hash && etype == S_IFREG && stat_type == S_IFREG) {
507                         zpm_hash(n->dest, ehash, 0);
508                         if (strcmp(n->hash, ehash) != 0) {
509                                 diff |= D_HASH;
510                         }
511                         if (n->ohash && strcmp(n->ohash, ehash) != 0) {
512                                 diff |= D_OHASH;
513                         }
514                 }
515                 if (n->hash && etype == S_IFLNK && stat_type == S_IFLNK) {
516                         lsize = readlink(n->dest, link, sizeof link);
517
518                         if (lsize == -1 || lsize == sizeof link) {
519                                 diff |= D_RLERROR;
520                                 diff |= D_ERROR;
521                         } else {
522                                 link[lsize] = 0;
523                                 if (strcmp(n->target, link) != 0) {
524                                         diff |= D_HASH;
525                                 }
526                         }
527                 }
528                 if (n->uid != st->st_uid) {
529                         diff |= D_UID;
530                         diff |= D_MD;
531                 }
532                 if (n->gid != st->st_gid) {
533                         diff |= D_GID;
534                         diff |= D_MD;
535                 }
536                 if (n->mode != (st->st_mode & 07777)) {
537                         diff |= D_MODE;
538                         diff |= D_MD;
539                 }
540         } else {
541                 switch(errno) {
542                         case ENOENT: diff |= D_NOEXIST; break;
543                         default: diff |= (D_STATERROR|D_ERROR); break;
544                 }
545         }
546
547         return diff;
548 }
549
550
551 /* 0 = not acceptable
552  * 1 = accept and create/update/remove
553  * 2 = accept as is
554  * 3 = remove and overwrite
555  * 4 = update metadata
556  */
557 static int acceptable(struct config *conf, unsigned int diffs, int op) {
558         int exist = (!(diffs & D_NOEXIST));
559         int sametype = (!(diffs & D_TYPE));
560         int mdsame = (!(diffs & D_MD));
561         int hashsame = (!(diffs & D_HASH));
562         int isdir = (diffs & D_ISDIR);
563
564         if (!exist) {
565                 return op == OP_REMOVE ? 2 : 1;
566         }
567
568         if (op == OP_UPDATE) {
569                 return sametype ? 4 : 3;
570         }
571
572         if (op == OP_REMOVE) {
573                 return 1;
574         }
575
576         /* the hard cases, should be installing new, but already exists */
577
578         if (!sametype) {
579                 return conf->overwrite ? 3 : 0;
580         }
581
582         if (mdsame && (conf->accept || conf->overwrite)) {
583                 return 1;
584         }
585
586         if (isdir) {
587                 if (mdsame || conf->ignoredirmd) {
588                         return conf->acceptdir ? 2 : 0;
589                 }
590                 if (conf->overwrite) {
591                         return 4;
592                 }
593         }
594
595         if (hashsame && (conf->accept || conf->overwrite)) {
596                 return 1;
597         }
598
599         return conf->overwrite ? 3 : 0;
600 }
601
602 static int check_existing(void *f, int ncols, char **vals, char **cols) {
603         struct config *conf = f;
604         struct stat st;
605         struct nitem nitem;
606
607         if (!read_item(conf, ncols, vals, cols, &nitem)) {
608                 fprintf(stderr, "can't read item\n");
609                 return conf->errabort;
610         }
611
612         if (conf->verbose > 1) {
613                 fprintf(stderr, "check for existing %s\n", nitem.path);
614         }
615
616         if (lstat(nitem.path, &st) == -1) {
617                 switch(errno) {
618                         /* not an error, file shouldn't exist*/
619                         case ENOENT: break;
620                         default:
621                                 fprintf(stderr, "unable to check %s: %s\n",
622                                                 nitem.path, strerror(errno));
623                                 conf->errors++;
624                                 break;
625                 }
626                 return 0;
627         }
628
629         unsigned int diffs = file_compare(&nitem, &st);
630         int sametype = (!(diffs & D_TYPE));
631
632         if (diffs >= D_ERROR) {
633                 return seterror(conf, "can't check %s", nitem.dest);
634         }
635
636         if (sametype && nitem.configuration) {
637                 return 0;
638         }
639
640         int action = acceptable(conf, diffs, nitem.op);
641         if (!action) {
642                 if (conf->accept) {
643                         fprintf(stderr, "%s exists and is not acceptable\n", nitem.path);
644                 } else {
645                         fprintf(stderr, "%s exists\n", nitem.path);
646                 }
647                 conf->errors++;
648         }
649
650         return 0;
651 }
652
653 static void update_progress(struct config *conf, char *op, char *path) {
654         if (!conf->verbose) {
655                 return;
656         }
657
658         if (conf->progress == 0) {
659                 pdots(50, '.', conf->ops_completed-1, conf->ops_completed, conf->ops_total);
660         } else if (conf->progress == 1) {
661                 size_t len = strlen(path);
662                 int offset = 0;
663                 if (len > 50) {
664                         offset = len-50;
665                 }
666                 printf("\r%lu/%lu %.10s %.50s\n", conf->ops_completed,
667                                 conf->ops_total, op, path+offset);
668         } else if (conf->progress == 2) {
669                 printf("%lu/%lu %s %s\n", conf->ops_completed,
670                                 conf->ops_total, op, path);
671         }
672         fflush(stdout);
673 }
674
675 static int remove_files(void *f, int ncols, char **vals, char **cols) {
676         struct config *conf = f;
677         char *dest;
678         struct stat st;
679         int flags = 0;
680
681         conf->ops_completed++;
682
683         dest = COL("dest");
684         char *ftype = COL("filetype");
685
686         if (!dest) return seterror(conf,"no file dest");
687         if (!ftype) return seterror(conf,"no file type");
688
689         update_progress(conf, *ftype == 'd' ? "rmdir" : "unlink", dest);
690
691         if (conf->dryrun) {
692                 return 0;
693         }
694
695         errno = 0;
696
697         if (lstat(dest, &st) == -1) {
698                 switch (errno) {
699                         case ENOENT:
700                                 if (conf->verbose > 1) {
701                                         fprintf(stderr, "expected file not found: '%s'\n", dest);
702                                 }
703                                 break;
704                         default:
705                                 return seterror(conf, "can't stat %s: %s", dest, strerror(errno));
706                 }
707                 return 0;
708         }
709
710         if (S_ISDIR(st.st_mode)) {
711                 flags = AT_REMOVEDIR;
712         }
713         /* TODO check that expected filetype matches actual filetype */
714         /* alternatively, just use the expected type, skip the stat,
715          * and let it fail if the type is wrong
716          */
717
718         errno = 0;
719
720         if (unlinkat(AT_FDCWD, dest, flags) == -1) {
721                 switch (errno) {
722                         case ENOENT:
723                                 break;
724                         case ENOTEMPTY: /* fall through */
725                         case EEXIST:
726                                 fprintf(stderr, "expected empty directory: %s\n", dest);
727                                 break;
728                         default:
729                                 return seterror(conf, "can't unlink %s: %s", dest, strerror(errno));
730                 }
731         }
732         
733         return 0;
734 }
735
736 #define MARK fprintf(stderr, "%s %d: mark\n", __func__, __LINE__)
737
738 static int remove_dir(struct config *conf, char *path) {
739         int rv;
740
741         rv = rmdir(path);
742         if (rv == -1) {
743                 setsyserr(conf, "can't rmdir %s", path);
744                 return 0;
745         }
746         return 1;
747 }
748
749 static int remove_existing(struct config *conf, char *path) {
750         int rv;
751
752         rv = unlink(path);
753         if (rv == -1) {
754                 setsyserr(conf, "can't unlink %s", path);
755                 return 0;
756         }
757         return 1;
758 }
759
760 static int set_md(struct config *conf, struct nitem *item) {
761         int rv;
762         int success = 0;
763
764         if (conf->dryrun) {
765                 if (item->ftype != 'l') {
766                         printf("chmod %o %s\n", item->mode, item->dest);
767                 }
768                 if (conf->setuser && conf->setgroup) {
769                         printf("lchown %d:%d %s\n", item->uid, item->gid,
770                                         item->dest);
771                 }
772                 printf("mtime %.0f %s\n", (double)item->mtime, item->dest);
773                 fflush(stdout);
774                 return success;
775         }
776
777         if (conf->setuser && conf->setgroup) {
778                 rv = lchown(item->dest, item->uid, item->gid);
779                 if (rv == -1) {
780                         setsyserr(conf, "can't lchown %s", item->dest);
781                         return conf->errabort;
782                 }
783         }
784
785         /* have to chmod after the chown, setuid bits may (and will)
786          * be cleared after a chown
787          */
788         /* can't chmod a symlink */
789         if (item->ftype != 'l') {
790                 rv = chmod(item->dest, item->mode);
791
792                 if (rv == -1) {
793                         setsyserr(conf, "can't chmod %o %s", item->mode, item->dest);
794                         return conf->errabort;
795                 }
796         }
797
798         rv = utimensat(AT_FDCWD, item->dest, item->times, AT_SYMLINK_NOFOLLOW);
799         if (rv == -1) {
800                 setsyserr(conf, "can't set mtime %.0f %s", (double)item->mtime,
801                                 item->dest);
802                 return conf->errabort;
803         }
804         return 0;
805 }
806
807 /* install a file or create a directory or symlink.  path should not exist
808  * at this point.
809  */
810 /* flags: 1 = set md, 2 = create leading dirs, 4 = unlink existing file,
811  * 8 = rmdir existing dir, 16 = return true/false
812  */
813 #define INS_MD 0x1
814 #define INS_CLD 0x2
815 #define INS_UNLINK 0x4
816 #define INS_RMDIR 0x8
817 #define INS_RTF 0x10
818 #define INS_ZPMNEW 0x20
819 static int install(struct config *conf, struct nitem *item, unsigned int flags) {
820         int rv = 1;
821         struct zpm *source;
822
823         int mkleading = (flags & 2);
824         int setmd = (flags & 1);
825         int unlink_file = (flags & 4);
826         int rm_dir = (flags & 8);
827         int failure = conf->errabort;
828         int success = 0;
829
830         if (flags & INS_RTF) {
831                 failure = 0;
832                 success = 1;
833         }
834
835         if (conf->dryrun) {
836                 if (unlink_file) {
837                         printf("unlink %s\n", item->dest);
838                 } else if (rm_dir) {
839                         printf("rmdir %s\n", item->dest);
840                 }
841
842                 printf("install %c%o %d:%d %s", item->ftype,
843                                 item->mode, item->uid, item->gid,
844                                 item->dest);
845                 if (item->ftype == 'l') {
846                         printf(" -> %s", item->target);
847                 }
848                 printf("\n");
849                 fflush(stdout);
850                 return success;
851         }
852
853         source = conf->src ? conf->src : conf->log;
854
855         if (mkleading) {
856                 rv = create_leading_dirs(item->dest);
857                 if (!rv) {
858                         setsyserr(conf, "can't create leading dirs for %s", item->dest);
859                         return failure;
860                 }
861         }
862
863         if (unlink_file) {
864                 rv = remove_existing(conf, item->dest);
865         } else if (rm_dir) {
866                 rv = remove_dir(conf, item->dest);
867         }
868
869         if (rv != 1) {
870                 return failure;
871         }
872
873         errno = 0;
874         switch (item->ftype) {
875                 case 'r': rv = zpm_extract(source, item->hash, item->dest, item->mode);
876                           if (rv == 0) rv = -1;
877                           break;
878                 case 'd': rv = mkdir(item->dest, item->mode);
879                           break;
880                 case 'l': rv = symlink(item->target, item->dest);
881                           break;
882                 default: /* error */
883                           break;
884         }
885
886         if (rv == -1) {
887                 switch (item->ftype) {
888                         case 'r':
889                                 seterror(conf, "can't extract %s", item->dest);
890                                 break;
891                         case 'd':
892                                 setsyserr(conf, "install mkdir(\"%s\") failed", item->dest);
893                                 break;
894                         case 'l':
895                                 setsyserr(conf, "install symlink(\"%s\") failed", item->dest);
896                                 break;
897                 }
898                 setsyserr(conf, "installing %s failed", item->dest);
899                 return failure;
900         }
901
902         if (setmd) {
903                 return set_md(conf, item) == 0 ? success : failure;
904         }
905
906         return success;
907 }
908
909 static int save_config_file(struct config *conf, struct nitem *n, char *msgfmt) {
910         char hash[ZPM_HASH_STRLEN+1];
911
912         if (!msgfmt) {
913                 msgfmt = "saved config file %.8s";
914         }
915
916         if (zpm_import(conf->log, n->dest, 0, hash)) {
917                 zpm_note_add(conf->log, n->pkglist, n->path, hash, msgfmt, hash);
918         } else {
919                 warn("unable to import existing config file %s", n->dest);
920                 conf->errors++;
921                 return 0;
922         }
923         return 1;
924 }
925
926 #if 0
927 /*
928  * figure out what the difference is for a config file, only called
929  * for an update of a configuration file
930  * return -1 on an error
931  * return 1 if the new file should not be installed
932  * return 0 if the new file should be installed
933  */
934 static int adjust_for_config(struct nitem *n, unsigned int diffs) {
935
936         if (!n->oldwasconf) {
937                 return 0;
938         }
939
940         int sametype = (!(diffs & D_TYPE));
941         int isdir = (diffs & D_ISDIR);
942         int eisdir = (diffs & D_EISDIR);
943         
944         /* what if old was a directory? */
945         if (!n->configuration) {
946                 /* replacing conf with non-conf */
947                 /* absorb file, mark todo */
948                 return 0;
949         }
950
951         /* both old and new are config files */
952         if (isdir && sametype) {
953                 /* both config directories, can only be changing
954                  * metadata, so no adjustment needed
955                  */
956                 return 0;
957         }
958
959         if (isdir) {
960                 return 0;
961         }
962
963         if (eisdir) {
964                 /* replacing old conf directory with a conf file.
965                  * nothing needs to be done, if the directory
966                  * is empty, it's ok to remove.  if it's not empty,
967                  * the install will fail
968                  */
969                 return 0;
970         }
971         
972         /* replacing old file with new file */
973         /* new is same as on disk */
974         if (!(diffs & D_HASH)) {
975                 return 0;
976         }
977
978         /* new is different than on disk, but on disk is same as old */
979         if (!(diffs & D_OHASH)) {
980                 return 0;
981         }
982
983         return 1;
984
985 }
986 #endif
987
988 static int config_handler(void *f, int ncols, char **vals, char **cols) {
989         struct config *conf = f;
990         struct nitem nitem;
991         struct stat existing;
992         char *save = 0;
993         char *note = 0;
994         char *notehash = 0;
995         int update = 0;
996
997         if (!read_item(conf, ncols, vals, cols, &nitem)) {
998                 fprintf(stderr, "can't read item\n");
999                 conf->errors++;
1000                 return conf->errabort;
1001         }
1002
1003         unsigned int diffs = file_compare(&nitem, &existing);
1004         if (diffs >= D_ERROR) {
1005                 return seterror(conf, "can't check %s", nitem.dest);
1006         }
1007
1008         int exist = (!(diffs & D_NOEXIST));
1009         int sametype = (!(diffs & D_TYPE));
1010         //int mdsame = (!(diffs & D_MD));
1011         int hashsame = (!(diffs & D_HASH));
1012         int oldhashsame = (!(diffs & D_OHASH));
1013         int isdir = (diffs & D_ISDIR);
1014         int eisdir = (diffs & D_EISDIR);
1015         update = (nitem.op == OP_UPDATE);
1016
1017         notehash = nitem.hash;
1018
1019         /* if the file doesn't exist in the system, nothing to do */
1020         /* could possibly note if we expected it, but the regular handling
1021          * should do that
1022          */
1023         if (!exist) {
1024                 return 0;
1025         }
1026
1027         if (nitem.op == OP_UPDATE && !nitem.oldwasconf) {
1028                 /* possibly save anyway */
1029                 return 0;
1030         }
1031
1032         /* so, old was conf, and something exists in the filesystem */
1033
1034         if (!sametype) {
1035                 warn("won't %s %s%s, %s exists",
1036                                 nitem.op == OP_NEW ? "install" : nitem.opstr,
1037                                 nitem.path,
1038                                 isdir ? "/" : "",
1039                                 eisdir ? "directory" : "file"
1040                     );
1041                 conf->errors++;
1042                 return conf->errabort;
1043         }
1044
1045         /* all below are same type of file */
1046         /* what about sametype, but old was different type */
1047
1048         if (isdir) {
1049                 return 0;
1050         }
1051
1052         /* save or note cases */
1053
1054         if (nitem.op == OP_REMOVE) {
1055                 save ="saved removed config file %.8s";
1056         } else 
1057
1058         if (nitem.op == OP_UPDATE) {
1059                 if (!nitem.configuration) {
1060                         /* replacing config with non-config */
1061                         save = "replacing configuration file %.8s with non-configuration file";
1062                 } else if (oldhashsame) {
1063                         /* config file hasn't changed from old default,
1064                          * so go ahead and install the new one
1065                          */
1066                         save = "replaced old default config (%.8s) with new one.";
1067                         notehash = nitem.ohash;
1068                 } else {
1069                         note = "kept existing config file.  new default version is %.8s";
1070                         save = 0;
1071                 }
1072         } else
1073
1074         if (nitem.op == OP_NEW && !hashsame) {
1075                 note = "config file already existed.  would have installed %.8s";
1076                 save = 0;
1077         }
1078
1079         /*
1080          * save files, add notes
1081          */
1082         if (!conf->dryrun) {
1083                 if (save) {
1084                         warn("saving config file: %s (root %s)", nitem.path, conf->rootdir ? conf->rootdir : "/");
1085                         save_config_file(conf, &nitem, save);
1086                 }
1087                 if (note) {
1088                         fprintf(stderr, "%s (%s) '%s' ", nitem.pkglist,
1089                                         nitem.hash, nitem.path);
1090                         fprintf(stderr, note, nitem.hash);
1091                         fprintf(stderr, "\n");
1092
1093                         zpm_note_add(conf->log, nitem.pkglist, nitem.path,
1094                                         nitem.hash, note, nitem.hash);
1095                 }
1096         } else {
1097                 if (save) {
1098                         fprintf(stderr, "dry run: %s %s: ", nitem.pkglist,
1099                                         nitem.path);
1100                         warn(save, notehash);
1101                 }
1102                 if (note) {
1103                         fprintf(stderr, "dry run: %s %s: ", nitem.pkglist,
1104                                         nitem.path);
1105                         warn(note, notehash);
1106                 }
1107
1108         }
1109
1110         return 0;
1111 }
1112
1113 static void handle_config_files(struct config *conf) {
1114         int rv;
1115         char *errmsg;
1116         sqlite3_str *s;
1117         char *sql;
1118
1119         s = sqlite3_str_new(conf->log->db);
1120         sqlite3_str_appendall(s, "select *, ");
1121         if (conf->rootdir) {
1122                 sqlite3_str_appendf(s, "printf('%%s/%%s',rtrim(%Q,'/'),ltrim(path,'/'))", conf->rootdir);
1123         } else {
1124                 sqlite3_str_appendf(s, "printf('/%%s', trim(path, '/'))");
1125         }
1126         sqlite3_str_appendall(s, " as dest from syncinfo");
1127
1128         sqlite3_str_appendall(s," where configuration > 0 and op in ('new','update','remove')");
1129
1130         if (conf->reverse) {
1131                 sqlite3_str_appendall(s," order by length(path) desc, path desc");
1132         }
1133
1134         sql = sqlite3_str_value(s);
1135
1136         rv = zpm_exec(conf->log, sql, config_handler, conf, &errmsg);
1137
1138         sqlite3_str_finish(s);
1139
1140         if (rv) {
1141                 fprintf(stderr, "exec fail: %s\n", sqlite3_errstr(rv));
1142                 if (errmsg) {
1143                         fprintf(stderr, "database error: %s\n", errmsg);
1144                         conf->errors++;
1145                 }
1146                 if (conf->log->error == 1) {
1147                         fprintf(stderr, "unable to allocate memory\n");
1148                 }
1149                 fprintf(stderr, "zpm_exec failure: %s\n",
1150                                 conf->log->errmsg ? conf->log->errmsg : "unknown");
1151                 conf->errors++;
1152         }
1153
1154         if (conf->errors && conf->exitonerror) {
1155                 zpm_close(conf->log);
1156                 zpm_close(conf->src);
1157                 exit(EXIT_FAILURE);
1158         }
1159 }
1160
1161 static int install_files(void *f, int ncols, char **vals, char **cols) {
1162         struct config *conf = f;
1163         struct nitem nitem;
1164         struct stat existing;
1165         int update = 0;
1166
1167         /* put the result row in a hash table?  May not actually
1168          * be faster
1169          */
1170         if (!read_item(conf, ncols, vals, cols, &nitem)) {
1171                 fprintf(stderr, "can't read item\n");
1172                 return conf->errabort;
1173         }
1174
1175 #if 0
1176         int64_t used, high;
1177         used = sqlite3_memory_used()/1024/1024;
1178         high = sqlite3_memory_highwater(0)/1024/1024;
1179         fprintf(stderr, "memory = %ld MB / %ld MB\n", used, high);
1180 #endif
1181         char action[40];
1182         sprintf(action, "%.8s %c", nitem.opstr, nitem.ftype);
1183         conf->ops_completed++;
1184         update_progress(conf, action, nitem.dest);
1185
1186         unsigned int diffs = file_compare(&nitem, &existing);
1187         if (diffs >= D_ERROR) {
1188                 return seterror(conf, "can't check %s", nitem.dest);
1189         }
1190
1191         /* updates:
1192          * exist & same type & md same & hash same: do nothing, but warn bug
1193          * exist & same type & md diff & hash same: fix md
1194          * exist & same type & md same & hash diff: replace
1195          * exist & same type & md diff & hash diff: replace & fix
1196          * no exist: install and warn
1197          * dir & not dir : remove, mkdir
1198          * not dir & not dir & diff type: remove, install
1199          * not dir & dir : remove dir if empty, error if not empty, install
1200          *
1201          * installs:
1202          * no exist: create leading dirs, install
1203          *
1204          * exist & same type & md same & hash same & accept or over: do nothing
1205          * exist & same & md diff or hash diff & overwrite : update
1206          * exist & same & md diff or hash diff & accept : error, can't accept
1207          * exist & same & md diff or hash diff & not accept : error
1208          *
1209          * exist & different type & not overwrite : error
1210          * not dir & not dir & overwrite : remove and install
1211          * not dir & dir & overwrite: remove empty or error, install
1212          * dir & dir & overwrite: fix md
1213          * dir & not dir & overwrite: remove and mkdir
1214          */
1215         int exist = (!(diffs & D_NOEXIST));
1216         int sametype = (!(diffs & D_TYPE));
1217         int mdsame = (!(diffs & D_MD));
1218         int hashsame = (!(diffs & D_HASH));
1219         int ohashsame = (!(diffs & D_OHASH));
1220         int isdir = (diffs & D_ISDIR);
1221         int eisdir = (diffs & D_EISDIR);
1222         int accept = conf->accept;
1223         int overwrite = conf->overwrite;
1224         int installing = (nitem.op == OP_NEW);
1225         update = (nitem.op == OP_UPDATE);
1226
1227         /* if a config file doesn't exist on disk, go ahead and do
1228          * whatever you were going to do, this logic here just
1229          * needs to determine if we should skip what we were going to do
1230          *
1231          * if the old item was a configuration item and the new one isn't, it
1232          * will have been saved earlier, so we can just go ahead.  so we only
1233          * test for an existing file, where the item is a configuration file
1234          */
1235         if (nitem.configuration && exist) {
1236                 if (!sametype && !conf->overwrite) {
1237                         return seterror(conf, "configuration file exists with different type: %s", nitem.dest);
1238                 }
1239
1240                 if (conf->accept) {
1241                         return 0;
1242                 }
1243
1244                 if (isdir && !mdsame) return 0;
1245                 if (!isdir && !ohashsame) return 0;
1246         }
1247
1248         if (update) {
1249                 if (!exist) {
1250                         /* warn, it should exist */
1251                         fprintf(stderr, "%s missing, installing\n", nitem.dest);
1252                         return install(conf, &nitem, 3);
1253                 }
1254
1255                 /* file exists in filesystem */
1256                 if (sametype) {
1257                         if (mdsame && hashsame) {
1258                                 /* warn, bug in logic.  This shouldn't occur,
1259                                  * because if there is nothing to do, it
1260                                  * shouldn't be listed as an update
1261                                  */
1262                                 /* could be an update.  We're checking against
1263                                  * what's actually on disk, not what was
1264                                  * expected to have been on disk.  So, if
1265                                  * the admin has modified the file, or if
1266                                  * it had been installed ignoring the user
1267                                  * and group, it might be correct on disk
1268                                  * but not as in the local database
1269                                  */
1270
1271                                 /* TODO detect whether this a logic bug or
1272                                  * an on-disk difference
1273                                  */
1274 #if 0
1275                                 fprintf(stderr, "%s should not be an update\n", nitem.dest);
1276                                 fprintf(stderr, "old hash: %s\n", nitem.ohash);
1277                                 fprintf(stderr, "new hash: %s\n", nitem.hash);
1278                                 fprintf(stderr, "old mds: %s\n", nitem.omds);
1279                                 fprintf(stderr, "new mds: %s\n", nitem.mds);
1280 #endif
1281                                 /* do nothing */
1282                                 return 0;
1283                         }
1284                         if (!mdsame && hashsame) {
1285                                 /* fix md */
1286                                 return set_md(conf, &nitem);
1287                         }
1288
1289                         if (!hashsame) {
1290                                 /* doesn't matter on the md */
1291                                 int flags = INS_MD | INS_CLD;
1292                                 if (nitem.ftype == 'l') {
1293                                         flags |= INS_UNLINK;
1294                                 }
1295                                 return install(conf, &nitem, flags);
1296                         }
1297                 }
1298
1299                 /* file exists, and is not the same type */
1300
1301                 if (isdir && !eisdir) {
1302                         /* remove existing */
1303                         /* mkdir */
1304                         return install(conf, &nitem, 7);
1305                 }
1306                 if (!isdir && eisdir) {
1307                         /* remove dir, or error */
1308                         /* install */
1309                         return install(conf, &nitem, 11);
1310                 }
1311                 if (!isdir && !isdir) {
1312                         /* necessarily !sametype, sametype handled above */
1313                         /* remove existing */
1314                         /* install */
1315                         return install(conf, &nitem, 7);
1316                 }
1317                 /* error, should not be possible, assert(0)? */
1318                 fprintf(stderr,"impossible state: %s:%d\n", __func__, __LINE__);
1319         }
1320
1321         if (installing) {
1322                 if (!exist) {
1323                         return install(conf, &nitem, 3);
1324                 }
1325
1326                 /* file exists in filesystem */
1327                 if (sametype) {
1328                         if (mdsame && hashsame && (accept || overwrite)) {
1329                                 /* do nothing */
1330                                 if (conf->dryrun || conf->verbose > 1) {
1331                                         fprintf(stderr, "accept %s: %s\n",
1332                                                         eisdir ? "directory" : "file", nitem.dest);
1333                                 }
1334                                 return 0;
1335                         }
1336
1337                         if (mdsame && isdir && conf->acceptdir) {
1338                                 return 0;
1339                         }
1340
1341                         if (!mdsame && isdir && conf->ignoredirmd) {
1342                                 if (conf->verbose > 1) {
1343                                         fprintf(stderr, "ignoring directory metadata difference: %s\n", nitem.dest);
1344                                 }
1345                                 return 0;
1346                         }
1347
1348                         if (mdsame && hashsame && !(accept || overwrite)) {
1349                                 /* error */
1350                                 return seterror(conf, "file exists: %s", nitem.dest);
1351                         }
1352
1353                         if (mdsame && !hashsame && overwrite) {
1354                                 /* install */
1355                                 return install(conf, &nitem, eisdir ? 11 : 7);
1356                         }
1357
1358                         if (nitem.configuration && accept) {
1359                                 /* accept a changed config file */
1360                                 if (conf->dryrun || conf->verbose) {
1361                                         fprintf(stderr, "accept %smodified config %s: %s\n", (!mdsame || !hashsame) ? "" : "un", 
1362                                                         eisdir ? "directory" : "file", nitem.dest);
1363                                 }
1364                                 return 0;
1365                         }
1366
1367                         if (mdsame && !hashsame && !overwrite) {
1368                                 /* accept doesn't matter, since it's
1369                                  * not an acceptable file */
1370                                 /* error */
1371                                 if (nitem.ftype == 'l') {
1372                                         char link[1024];
1373                                         ssize_t lsize;
1374                                         lsize = readlink(nitem.dest, link, sizeof link);
1375                                         if (lsize == -1 || (size_t)lsize >= sizeof link) {
1376                                                 return seterror(conf, "%s (linkdiff): expecting %s -> %s, unable to read link", accept ? "existing file not acceptable" : "file exists", nitem.dest, nitem.target, link);
1377                                         } else {
1378                                                 link[lsize] = 0;
1379                                                 /* links must be different */
1380                                                 return seterror(conf, "%s (linkdiff): expecting %s -> %s, have -> %s", accept ? "existing file not acceptable" : "file exists", nitem.dest, nitem.target, link);
1381                                         }
1382                                 } else {
1383                                         return seterror(conf, "%s (hashdiff): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
1384                                 }
1385                         }
1386                         if (!mdsame && hashsame && overwrite) {
1387                                 /* fix md */
1388                                 return set_md(conf, &nitem);
1389                         }
1390                         if (!mdsame && hashsame && !overwrite) {
1391                                 /* accept doesn't matter, since it's
1392                                  * not an acceptable file */
1393                                 /* error */
1394                                 return seterror(conf, "%s (mddiff): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
1395                         }
1396                         if (!mdsame && !hashsame && overwrite) {
1397                                 /* install */
1398                                 return install(conf, &nitem, eisdir ? 11 : 7);
1399                         }
1400                         if (!mdsame && !hashsame && !overwrite) {
1401                                 /* accept doesn't matter, since it's
1402                                  * not an acceptable file */
1403                                 /* error */
1404                                 return seterror(conf, "%s (md+hash): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
1405                         }
1406                         /* error, should be impossible */
1407                         return seterror(conf, "impossible state reached");
1408                 }
1409
1410                 /* file exists, and is not the same type */
1411                 if (!overwrite) {
1412                         /* error */
1413                                 return seterror(conf, "%s (difftype): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
1414                 }
1415
1416                 /* not the same type, but ok to overwrite */
1417                 if (!eisdir) {
1418                         /* remove existing */
1419                         return install(conf, &nitem, 7);
1420                 }
1421
1422                 /* existing path is a directory */
1423                 if (isdir) {
1424                         /* fix md */
1425                         /* impossible, if isdir and eisdir, would be same type
1426                          */
1427                         return set_md(conf, &nitem);
1428                 } else {
1429                         /* remove empty dir or error */
1430                         /* install */
1431                         return install(conf, &nitem, 11);
1432                 }
1433                 /* if we get here, we missed a case */
1434                 return seterror(conf, "impossible state 2 reached");
1435         }
1436
1437         /* TODO extra verbose print perms, mtime, etc, probably ls -l format
1438          */ 
1439         if (conf->verbose) {
1440                 printf("%s\n", nitem.path);
1441         }
1442
1443         return 0;
1444 }
1445
1446 static void check_conflicts(struct config *conf, char *conflict_type,
1447                 int (callback)(void *, int, char **, char **)) {
1448         int rv;
1449         char *errmsg;
1450         sqlite3_str *s;
1451         char *sql;
1452
1453         s = sqlite3_str_new(conf->log->db);
1454         sqlite3_str_appendall(s, "select *, ");
1455         if (conf->rootdir) {
1456                 sqlite3_str_appendf(s, "printf('%%s/%%s',rtrim(%Q,'/'),ltrim(path,'/'))", conf->rootdir);
1457         } else {
1458                 sqlite3_str_appendf(s, "printf('/%%s', trim(path, '/'))");
1459         }
1460         sqlite3_str_appendall(s, " as dest from syncconflicts");
1461
1462         if (conflict_type) {
1463                 sqlite3_str_appendf(s," where conflict = %Q", conflict_type);
1464         }
1465         if (conf->reverse) {
1466                 sqlite3_str_appendall(s," order by length(path) desc, path desc,pkgid collate vercmp desc, conflict desc");
1467         } else {
1468                 sqlite3_str_appendall(s," order by length(path), path, pkgid collate vercmp, conflict");
1469
1470         }
1471
1472         sql = sqlite3_str_value(s);
1473
1474         rv = zpm_exec(conf->log, sql, callback, conf, &errmsg);
1475
1476         sqlite3_str_finish(s);
1477
1478         if (rv) {
1479                 fprintf(stderr, "exec fail: %s\n", sqlite3_errstr(rv));
1480                 if (errmsg) {
1481                         fprintf(stderr, "database error: %s\n", errmsg);
1482                         conf->errors++;
1483                 }
1484                 if (conf->log->error == 1) {
1485                         fprintf(stderr, "unable to allocate memory\n");
1486                 }
1487                 fprintf(stderr, "zpm_exec failure: %s\n",
1488                                 conf->log->errmsg ? conf->log->errmsg : "unknown");
1489                 conf->errors++;
1490         }
1491         if (conf->log->errmsg) {
1492                 fprintf(stderr, "error: %s\n", conf->log->errmsg);
1493         }
1494         if (conf->errors && conf->exitonerror) {
1495                 zpm_close(conf->log);
1496                 zpm_close(conf->src);
1497                 exit(EXIT_FAILURE);
1498         }
1499         /* TODO final report function in conf var */
1500 }
1501
1502 static void runstage(struct config *conf, char *stage,
1503                 int (callback)(void *, int, char **, char **)) {
1504         int rv;
1505         char *errmsg;
1506         sqlite3_str *s;
1507         char *sql;
1508
1509         s = sqlite3_str_new(conf->log->db);
1510         sqlite3_str_appendall(s, "select *, ");
1511         if (conf->rootdir) {
1512                 sqlite3_str_appendf(s, "printf('%%s/%%s',rtrim(%Q,'/'),ltrim(path,'/'))", conf->rootdir);
1513         } else {
1514                 sqlite3_str_appendf(s, "printf('/%%s', trim(path, '/'))");
1515         }
1516         sqlite3_str_appendall(s, " as dest from syncinfo");
1517
1518         if (stage) {
1519                 sqlite3_str_appendf(s," where op = %Q", stage);
1520         }
1521         if (conf->reverse) {
1522                 sqlite3_str_appendall(s," order by length(path) desc, path desc");
1523         }
1524
1525         sql = sqlite3_str_value(s);
1526
1527         rv = zpm_exec(conf->log, sql, callback, conf, &errmsg);
1528
1529         sqlite3_str_finish(s);
1530
1531         if (rv) {
1532                 fprintf(stderr, "exec fail: %s\n", sqlite3_errstr(rv));
1533                 if (errmsg) {
1534                         fprintf(stderr, "database error: %s\n", errmsg);
1535                         conf->errors++;
1536                 }
1537                 if (conf->log->error == 1) {
1538                         fprintf(stderr, "unable to allocate memory\n");
1539                 }
1540                 fprintf(stderr, "zpm_exec failure: %s\n",
1541                                 conf->log->errmsg ? conf->log->errmsg : "unknown");
1542                 conf->errors++;
1543         }
1544 #if 0
1545         if (conf->log->errmsg) {
1546                 fprintf(stderr, "error: %s\n", conf->log->errmsg);
1547         }
1548 #endif
1549         if (conf->errors && conf->exitonerror) {
1550                 zpm_close(conf->log);
1551                 zpm_close(conf->src);
1552                 exit(EXIT_FAILURE);
1553         }
1554         /* TODO final report function in conf var */
1555 }
1556
1557 static void count_ops(struct config *conf) {
1558         conf->ops_remove = zpm_db_int(conf->log, "select count(*) from syncinfo where op = 'remove'");
1559         conf->ops_update = zpm_db_int(conf->log, "select count(*) from syncinfo where op = 'update'");
1560         conf->ops_install = zpm_db_int(conf->log, "select count(*) from syncinfo where op = 'new'");
1561         conf->ops_total = conf->ops_remove + conf->ops_update + conf->ops_install;
1562 }
1563
1564 int main(int ac, char **av) {
1565         struct zpm localdb;
1566         struct zpm pkgdb;
1567         int opt;
1568         char *pkgdbfile = 0, *localdbfile = 0;
1569         char *s;
1570
1571         struct config conf = { 0 };
1572
1573         conf.errabort = 1;
1574         conf.errors = 0;
1575         conf.conflicts = 0;
1576         conf.verbose = 1;
1577         conf.dryrun = 0;
1578         conf.setuser = 1;
1579         conf.setgroup = 1;
1580         conf.log = 0;
1581         conf.src = 0;
1582         conf.rootdir = 0;
1583         conf.reverse = 0;
1584         conf.overwrite = 0;
1585         conf.accept = 0;
1586         conf.acceptdir = 1;
1587
1588         if (geteuid() != 0) {
1589                 conf.setuser = 0;
1590                 conf.setgroup = 0;
1591         }
1592
1593         localdbfile = ZPM_LOCAL_DB;
1594         if ((s = getenv("ZPMDB"))) {
1595                 localdbfile = s;
1596         }
1597
1598         if ((s = getenv("ZPM_ROOT_DIR"))) {
1599                 conf.rootdir = s;
1600         }
1601
1602         /*
1603          * -d localdb or ZPMDB * or /var/lib/zpm/zpm.db, or die
1604          * -f 'package database', otherwise regular default of env
1605          *  ZPM_PACKAGE_FILE, or use pkgdb if otherwise not found
1606          * -R root of pkg, will just chdir there
1607          *
1608          *  args are pkgid triple, but will do a pkg find on the pkgdb
1609          */
1610
1611         while ((opt = getopt(ac, av, "f:d:c:nCR:vqOAMDp")) != -1) {
1612                 switch (opt) {
1613                         case 'd': localdbfile = optarg; break;
1614                         case 'f': pkgdbfile = optarg; break;
1615                         case 'n': conf.dryrun = 1; break;
1616                         case 'v': conf.verbose++; break;
1617                         case 'q': conf.verbose--; break;
1618                         case 'C': conf.errabort = 0; break;
1619                         case 'R': conf.rootdir = optarg; break;
1620                         case 'N': conf.setuser = 0; conf.setgroup = 0; break;
1621                         case 'O': conf.overwrite = 1; break;
1622                         case 'A': conf.accept = 1; break;
1623                         case 'M': conf.ignoredirmd = 1;
1624                         case 'D': conf.acceptdir = 0;
1625                         case 'p': conf.progress++;
1626                         default:
1627                                   usage();
1628                                   exit(EXIT_FAILURE);
1629                                   break;
1630                 }
1631         }
1632
1633         /* verify root dir exists */
1634         if (conf.rootdir && !exists(conf.rootdir, NULL)) {
1635                 fprintf(stderr, "rootdir %s does not exist\n", conf.rootdir);
1636         }
1637
1638         if (!zpm_open(&localdb, localdbfile)) {
1639                 fprintf(stderr, "can't open zpm db %s\n", localdbfile);
1640                 exit(EXIT_FAILURE);
1641         }
1642         conf.log = &localdb;
1643
1644         if (pkgdbfile) {
1645                 /* TODO open read-only */
1646                 if (!zpm_open(&pkgdb, pkgdbfile)) {
1647                         fprintf(stderr, "can't open src db %s\n", localdbfile);
1648                         exit(EXIT_FAILURE);
1649                 } else {
1650                         conf.src = &pkgdb;
1651                 }
1652         }
1653
1654         /* TODO set conf var to finalize error reporting */
1655         if (conf.verbose) {
1656                 fprintf(stderr, "syncing filesystem %s (ldb %s)\n",
1657                                 conf.rootdir ? conf.rootdir : "/",
1658                                 localdbfile);
1659         }
1660
1661         conf.errors = 0;
1662         conf.exitonerror = 0;
1663         check_conflicts(&conf, NULL, report_conflicts);
1664
1665         if (conf.conflicts) {
1666                 fprintf(stderr, "%d conflicts reported, aborting sync\n",
1667                                 conf.conflicts);
1668                 conf.errors++;
1669         } else {
1670                 /* no point in running it if we're just going to
1671                  * overwrite everything
1672                  */
1673                 if (!conf.overwrite && !conf.accept && !conf.dryrun) {
1674                         runstage(&conf, "new", check_existing);
1675                 }
1676
1677                 if (conf.verbose) {
1678                         fprintf(stderr, "beginning %ssync\n", conf.dryrun ?
1679                                         "dryrun " : "");
1680                 }
1681
1682                 if (!conf.errors) {
1683                         handle_config_files(&conf);
1684                 }
1685
1686                 /* have to do the removes first otherwise
1687                  * old files may conflict with update file
1688                  * type changes
1689                  */
1690                 if (!conf.errors) {
1691                         conf.exitonerror = conf.dryrun ? 0 : 1;
1692                         conf.errabort = conf.dryrun ? 0 : 1;
1693                         count_ops(&conf);
1694                         fprintf(stderr, "file ops: %lu\n", conf.ops_total);
1695                         if (conf.ops_remove > 0) {
1696                                 if (conf.verbose) {
1697                                         fprintf(stderr, "removing %lu file%s\n", conf.ops_remove, conf.ops_remove > 1 ? "s" : "");
1698                                 }
1699                                 conf.reverse = 1;
1700                                 conf.ops_completed = 0;
1701                                 conf.ops_total = conf.ops_remove;
1702                                 runstage(&conf, "remove", remove_files);
1703                                 if (conf.verbose && conf.progress < 2) {
1704                                         fprintf(stderr, " done\n");
1705                                         fflush(stderr);
1706                                 }
1707                         }
1708
1709                         if (conf.ops_update > 0) {
1710                                 if (conf.verbose) {
1711                                         fprintf(stderr, "updating %lu file%s\n", conf.ops_update, conf.ops_update > 1 ? "s" : "");
1712                                 }
1713                                 conf.reverse = 0;
1714                                 conf.ops_completed = 0;
1715                                 conf.ops_total = conf.ops_update;
1716                                 runstage(&conf, "update", install_files);
1717                                 if (conf.verbose && conf.progress < 2) {
1718                                         fprintf(stderr, " done\n");
1719                                         fflush(stderr);
1720                                 }
1721                         }
1722
1723                         if (conf.ops_install > 0) {
1724                                 if (conf.verbose) {
1725                                         fprintf(stderr, "installing %lu file%s\n", conf.ops_install, conf.ops_install > 1 ? "s" : "");
1726                                 }
1727                                 conf.reverse = 0;
1728                                 conf.ops_completed = 0;
1729                                 conf.ops_total = conf.ops_install;
1730                                 runstage(&conf, "new", install_files);
1731                                 if (conf.verbose && conf.progress < 2) {
1732                                         fprintf(stderr, " done\n");
1733                                         fflush(stderr);
1734                                 }
1735                         }
1736                 }
1737         }
1738
1739         zpm_close(&localdb);
1740         zpm_close(conf.src);
1741         return conf.errors ? 1 : 0;
1742 }