]> pd.if.org Git - zpackage/blob - zpm-syncfs.c
add tests and code for config file updates
[zpackage] / zpm-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 <limits.h>
9 #include <errno.h>
10 #include <ctype.h>
11 #include <pwd.h>
12 #include <grp.h>
13 #include <math.h>
14 #include <stdarg.h>
15 #include <time.h>
16
17 /* needed for S_IFMT and AT_FDCWD */
18 #include <fcntl.h>
19
20 #include <string.h>
21
22 #include "sqlite3.h"
23 #include "zpm.h"
24
25 struct config {
26         struct zpm *log; /* logging db will be attached as "log" */
27         struct zpm *src;
28         char *dbfile;
29         char *rootdir;
30         int errabort, errors, verbose, dryrun, conflicts;
31         int setuser, setgroup;
32         int reverse, exitonerror;
33         int overwrite, absorb;
34 };
35
36 struct nitem {
37         int op;
38         char *opstr;
39         uid_t uid;
40         gid_t gid;
41         char *dest;
42         char *path;
43         char *hash, *ohash;
44         char *mds, *omds;
45         char *target;
46         char *pkglist; /* space separated */
47         time_t mtime;
48         mode_t mode;
49         int ftype;
50         int configuration;
51         struct timespec times[2];
52 };
53
54 static void usage() {
55         printf("usage: zpm $scriptname [-fncC] args ...\n");
56 }
57
58 static int seterror(struct config *conf, char *msgfmt, ...) {
59         char msg[1024];
60         va_list ap;
61
62         conf->errors++;
63
64         va_start(ap, msgfmt);
65         vsnprintf(msg, sizeof msg, msgfmt, ap);
66         va_end(ap);
67
68         msg[1023] = 0;
69         if (conf->log->errmsg) {
70                 free(conf->log->errmsg);
71         }
72
73         conf->log->errmsg = strdup(msg);
74
75         if (conf->verbose) {
76                 fprintf(stderr, "%s\n", msg);
77         }
78
79         return conf->errabort;
80 }
81
82 static int setsyserr(struct config *conf, char *msgfmt, ...) {
83         char msg[1024];
84         va_list ap;
85         int printed;
86
87         conf->errors++;
88
89         va_start(ap, msgfmt);
90         printed = vsnprintf(msg, sizeof msg, msgfmt, ap);
91         va_end(ap);
92
93         if (printed < 1) {
94                 /* nothing we can really do */
95                 return conf->errabort;
96         }
97
98         if ((size_t)printed < sizeof msg) {
99                 snprintf(msg+printed, sizeof msg - printed, ": %s",
100                                 strerror(errno));
101         }
102
103         msg[1023] = 0;
104         if (conf->log->errmsg) {
105                 free(conf->log->errmsg);
106         }
107
108         conf->log->errmsg = strdup(msg);
109
110         if (conf->verbose) {
111                 fprintf(stderr, "%s\n", msg);
112         }
113
114         return conf->errabort;
115 }
116
117 static int exists(char *path, mode_t *mode) {
118         struct stat st;
119
120         if (lstat(path, &st) == -1) {
121                 return 0;
122         }
123         if (mode) *mode = st.st_mode;
124         return 1;
125 }
126
127 /* TODO maintain a list of already created directories */
128 static int create_leading_dirs(char *path) {
129         char *delim, *s;
130         int ch = 0;
131         char pcopy[ZPM_PATH_MAX];
132         struct stat st;
133         
134         strcpy(pcopy, path);
135
136         delim = strrchr(pcopy, '/');
137         if (!delim) return 1; /* not an error, but no leading dirs */
138
139         /* cut off last component */
140         *delim = 0;
141
142         s = pcopy;
143         do {
144                 while (*s == '/') {
145                         s++;
146                 }
147
148                 delim = strchr(s, '/');
149                 if (delim) {
150                         ch = *delim;
151                         *delim = 0;
152                 }
153
154                 /* try to create the directory, if it exists
155                  * and is a directory or a symlink, that's ok
156                  * should be (eventually) a symlink to a directory
157                  * so we want stat here, not lstat
158                  */
159                 if (mkdir(pcopy, 0755) == -1) {
160                         switch (errno) {
161                                 case EEXIST:
162                                         if (stat(pcopy, &st) == -1) {
163                                                 /* can't stat? */
164                                                 return 0;
165                                         }
166                                         switch (st.st_mode & S_IFMT) {
167                                                 case S_IFDIR:
168                                                         break;
169                                                 default:
170                                                         return 0;
171                                         }
172                                         break;
173                                 default:
174                                         return 0;
175                         }
176                 }
177                 if (delim) {
178                         *delim = ch;
179                 }
180                 s = delim;
181         } while (delim);
182         
183         return 1;
184 }
185
186 static char *column(char *col, int ncols, char **vals, char **cols) {
187         int i = 0;
188         char *val = NULL;
189
190         for (i=0; i < ncols; i++) {
191 //              fprintf(stderr, "checking '%s' = '%s'\n", cols[i], vals[i]);
192                 
193                 if (!strcmp(col, cols[i])) {
194                         val = vals[i];
195                         break;
196                 }
197         }
198         return val;
199 }
200
201 #define COL(x) column(x, ncols, vals, cols)
202 #define SYSERR(x) do { conf->log->error = 2; return conf->errabort; } while (0)
203
204
205 static char *ops[] = { "new", "remove", "update", 0 };
206
207 enum op {
208         OP_NEW = 1,
209         OP_REMOVE = 2,
210         OP_UPDATE = 3
211 };
212
213 static int getop(char *opstr) {
214         int i;
215
216         if (!opstr) return 0;
217         for (i=0;ops[i];i++) {
218                 if (!strcmp(opstr, ops[i])) {
219                         return i+1;
220                 }
221         }
222         return 0;
223 }
224
225 static int report_conflicts(void *f, int ncols, char **vals, char **cols) {
226         struct config *conf = f;
227         char *path, *hash, *pkg, *conflict_type, *mds;
228
229         pkg = COL("pkgid");
230         path = COL("path");
231         conflict_type = COL("conflict");
232         if (!strcmp(conflict_type, "hash")) {
233                 hash = COL("hash");
234                 fprintf(stderr, "hash conflict: package %s path %s hash %.8s\n",
235                                 pkg, path, hash);
236         } else
237         if (!strcmp(conflict_type, "md")) {
238                 mds = COL("mds");
239                 fprintf(stderr, "md conflict: package %s path %s md %s\n",
240                                 pkg, path, mds);
241         } else {
242                 fprintf(stderr, "%s conflict: package %s path %s\n",
243                                 conflict_type, pkg, path);
244         }
245
246         conf->conflicts++;
247         return 0;
248 }
249
250 static int check_existing(void *f, int ncols, char **vals, char **cols) {
251         struct config *conf = f;
252         char *path;
253         struct stat st;
254
255         path = COL("dest");
256         if (!path) {
257                 return seterror(conf, "no path");
258         }
259
260         if (conf->dryrun) {
261                 printf("checkfor %s\n", path);
262                 fflush(stdout);
263                 return 0;
264         }
265
266         if (conf->verbose) {
267                 fprintf(stderr, "check for existing %s\n", path);
268         }
269
270         if (lstat(path, &st) == 0) {
271                 fprintf(stderr, "%s exists\n", path);
272                 conf->errors++;
273         } else {
274                 switch(errno) {
275                         /* not an error, file shouldn't exist*/
276                         case ENOENT: break;
277                         default:
278                                 fprintf(stderr, "unable to check %s: %s\n",
279                                                 path, strerror(errno));
280                                 conf->errors++;
281                                 break;
282                 }
283         }
284         return 0;
285 }
286
287 static int remove_files(void *f, int ncols, char **vals, char **cols) {
288         struct config *conf = f;
289         char *dest;
290         struct stat st;
291         int flags = 0;
292
293         dest = COL("dest");
294         if (!dest) return seterror(conf,"no file dest");
295
296         if (conf->dryrun) {
297                 char *ftype = COL("filetype");
298                 int t = *ftype;
299
300                 switch(t) {
301                         case 'd': printf("rmdir %s\n", dest); break;
302                         default: printf("unlink %s\n", dest); break;
303                 }
304                 fflush(stdout);
305                 return 0;
306         }
307
308         if (lstat(dest, &st) == -1) {
309                 return seterror(conf,"can't stat");
310         }
311
312         if (S_ISDIR(st.st_mode)) {
313                 flags = AT_REMOVEDIR;
314         }
315         /* TODO check that expected filetype matches actual filetype */
316
317         if (conf->verbose) {
318                 fprintf(stderr, "%s(%s)\n", flags ? "rmdir" : "unlink", dest);
319         }
320
321         errno = 0;
322
323         if (unlinkat(AT_FDCWD, dest, flags) == -1) {
324                 switch (errno) {
325                         case ENOENT:
326                                 break;
327                         default:
328                                 return seterror(conf, "can't unlink");
329                 }
330         }
331         
332         return 0;
333 }
334
335 #define MARK fprintf(stderr, "%s %d: mark\n", __func__, __LINE__)
336
337 #define D_NOEXIST 0x1
338 #define D_TYPE 0x2
339 #define D_MD 0x4
340 #define D_HASH 0x8
341 #define D_ISDIR  0x10
342 #define D_EISDIR 0x20
343 #define D_UID 0x40
344 #define D_GID 0x80
345 #define D_MODE 0x100
346 #define D_MTIME 0x200
347 #define D_OHASH 0x400
348 #define D_ERROR 0x1000
349 #define D_STATERROR 0x2000
350 #define D_RLERROR 0x4000
351
352 /* 1 = file doesn't exist, 2 = file is a directory, target isn't */
353 /* 4 == ftype different */
354 /* 8 = hash different when both are regular files */
355 static unsigned int file_compare(struct nitem *n, struct stat *st) {
356         int etype = 0, stat_type;
357         char ehash[ZPM_HASH_STRLEN+1];
358         unsigned int diff = 0;
359         char link[1024];
360         ssize_t lsize;
361
362         switch (n->ftype) {
363                 case 'd': etype = S_IFDIR; diff |= D_ISDIR ; break;
364                 case 'r': etype = S_IFREG; break;
365                 case 'l': etype = S_IFLNK; break;
366                 default: etype = 0; break;
367         }
368
369         errno = 0;
370         /* new file, so check type, hash, etc */
371         if (lstat(n->dest, st) == 0) {
372                 stat_type = st->st_mode & S_IFMT;
373                 if (stat_type != etype) {
374                         diff |= D_TYPE;
375                 }
376                 if (stat_type == S_IFDIR) {
377                         diff |= D_EISDIR;
378                 }
379
380                 if (n->hash && etype == S_IFREG && stat_type == S_IFREG) {
381                         zpm_hash(n->dest, ehash, 0);
382                         if (strcmp(n->hash, ehash) != 0) {
383                                 diff |= D_HASH;
384                         }
385                         if (n->ohash && strcmp(n->ohash, ehash) != 0) {
386                                 diff |= D_OHASH;
387                         }
388                 }
389                 if (n->hash && etype == S_IFLNK && stat_type == S_IFLNK) {
390                         lsize = readlink(n->dest, link, sizeof link);
391                         if (lsize == -1 || lsize == sizeof link) {
392                                 diff |= D_RLERROR;
393                                 diff |= D_ERROR;
394                         } else if (strcmp(n->target, link) != 0) {
395                                 diff |= D_HASH;
396                         }
397                 }
398                 if (n->uid != st->st_uid) {
399                         diff |= D_UID;
400                         diff |= D_MD;
401                 }
402                 if (n->gid != st->st_gid) {
403                         diff |= D_GID;
404                         diff |= D_MD;
405                 }
406                 if (n->mode != (st->st_mode & 07777)) {
407                         diff |= D_MODE;
408                         diff |= D_MD;
409                 }
410         } else {
411                 switch(errno) {
412                         case ENOENT: diff |= D_NOEXIST; break;
413                         default: diff |= (D_STATERROR|D_ERROR); break;
414                 }
415         }
416
417         return diff;
418 }
419
420 static int read_item(struct config *conf, int ncols, char **vals, char **cols,
421                 struct nitem *n) {
422         char *val;
423         struct passwd *pw;
424         struct group *gr;
425         struct nitem zero = { 0 };
426
427         *n = zero;
428
429         val = COL("op");
430         if (!val) {
431                 seterror(conf, "can't determine op");
432                 return 0;
433         }
434         n->opstr = val;
435         n->op = getop(val);
436         if (!n->op) {
437                 seterror(conf, "can't determine op");
438                 return 0;
439         }
440
441         n->path = COL("path");
442         if (!n->path) {
443                 seterror(conf, "no file path");
444                 return 0;
445         }
446         if (strlen(n->path) == 0) {
447                 seterror(conf, "zero length path not allowed");
448                 return 0;
449         }
450
451         /* TODO config to dishonor setuid/setgid */
452         n->dest = COL("dest");
453         if (!n->dest) {
454                 seterror(conf, "no file dest");
455                 return 0;
456         }
457
458         if (strlen(n->dest) == 0) {
459                 seterror(conf, "zero length dest not allowed");
460                 return 0;
461         }
462
463         val = COL("mode");
464
465         if (!val) {
466                 seterror(conf, "can't determine mode");
467                 return 0;
468         }
469
470         n->mode = strtoul(val, NULL, 8);
471
472         val = COL("configuration");
473         if (!val) {
474                 seterror(conf, "can't determine config status");
475                 return 0;
476         }
477         n->configuration = strtoul(val, NULL, 10);
478
479         val = COL("filetype");
480         if (!val || strlen(val) == 0) {
481                 seterror(conf, "can't determine file type");
482                 return 0;
483         }
484         n->ftype = *val;
485
486         /* these can be null */
487         n->ohash = COL("ohash");
488         n->mds = COL("mds");
489         n->omds = COL("omds");
490         n->pkglist = COL("pkglist");
491
492         if (n->ftype == 'r') {
493                 n->hash = COL("hash");
494                 if (!n->hash) {
495                         seterror(conf, "can't get hash");
496                         return 0;
497                 }
498         } else if (n->ftype == 'l') {
499                 n->target = COL("target");
500                 if (!n->target) {
501                         seterror(conf, "can't get target");
502                         return 0;
503                 }
504                 if (strlen(n->target) == 0) {
505                         seterror(conf, "zero length target not allowed");
506                         return 0;
507                 }
508                 n->hash = n->target;
509         }
510
511         if (conf->setuser) {
512                 val = COL("username");
513                 if (!val) {
514                         seterror(conf, "no username");
515                         return 0;
516                 }
517                 pw = getpwnam(val);
518                 if (!pw) {
519                         seterror(conf, "no passwd entry");
520                         return 0;
521                 }
522                 n->uid = pw->pw_uid;
523         } else {
524                 n->uid = geteuid();
525         }
526
527         if (conf->setgroup) {
528                 val = COL("groupname");
529                 if (!val) {
530                         seterror(conf, "no groupname");
531                         return 0;
532                 }
533                 gr = getgrnam(val);
534                 if (!gr) {
535                         seterror(conf, "no group entry");
536                         return 0;
537                 }
538                 n->gid = gr->gr_gid;
539         } else {
540                 n->gid = getegid();
541         }
542
543         errno = 0;
544         double mtime = strtod(COL("mtime"),NULL);
545         if (errno) {
546                 mtime = (double)time(NULL);
547         }
548
549         n->mtime = (time_t)mtime;
550
551         n->times[0].tv_sec = 0;
552         n->times[0].tv_nsec = UTIME_OMIT;
553         n->times[1].tv_sec = (time_t)llrint(floor(mtime));
554         n->times[1].tv_nsec = lrint(floor(fmod(mtime,1.0)*1000000000));
555
556         return 1;
557 }
558
559 static int remove_dir(struct config *conf, char *path) {
560         int rv;
561
562         rv = rmdir(path);
563         if (rv == -1) {
564                 setsyserr(conf, "can't rmdir %s", path);
565                 return 0;
566         }
567         return 1;
568 }
569
570 static int remove_existing(struct config *conf, char *path) {
571         int rv;
572
573         rv = unlink(path);
574         if (rv == -1) {
575                 setsyserr(conf, "can't unlink %s", path);
576                 return 0;
577         }
578         return 1;
579 }
580
581 static int set_md(struct config *conf, struct nitem *item) {
582         int rv;
583         int success = 0;
584
585         if (conf->dryrun) {
586                 printf("chmod %o %s\n", item->mode, item->dest);
587                 if (conf->setuser && conf->setgroup) {
588                         printf("chown %d:%d %s\n", item->uid, item->gid,
589                                         item->dest);
590                 }
591                 printf("mtime %.0f %s\n", (double)item->mtime, item->dest);
592                 fflush(stdout);
593                 return success;
594         }
595
596         rv = chmod(item->dest, item->mode);
597
598         if (rv == -1) {
599                 setsyserr(conf, "can't chmod %o %s", item->mode, item->dest);
600                 return conf->errabort;
601         }
602
603         if (conf->setuser && conf->setgroup) {
604                 rv = chown(item->dest, item->uid, item->gid);
605                 if (rv == -1) {
606                         setsyserr(conf, "can't chown %s", item->dest);
607                         return conf->errabort;
608                 }
609         }
610
611         rv = utimensat(AT_FDCWD, item->dest, item->times, AT_SYMLINK_NOFOLLOW);
612         if (rv == -1) {
613                 setsyserr(conf, "can't set mtime %.0f %s", (double)item->mtime,
614                                 item->dest);
615                 return conf->errabort;
616         }
617         return 0;
618 }
619
620 /* install a file or create a directory or symlink.  path should not exist
621  * at this point.
622  */
623 /* flags: 1 = set md, 2 = create leading dirs, 4 = unlink existing file,
624  * 8 = rmdir existing dir, 16 = return true/false
625  */
626 #define INS_MD 0x1
627 #define INS_CLD 0x2
628 #define INS_UNLINK 0x4
629 #define INS_RMDIR 0x8
630 #define INS_RTF 0x10
631 #define INS_ZPMNEW 0x20
632 static int install(struct config *conf, struct nitem *item, unsigned int flags) {
633         int rv = 1;
634         struct zpm *source;
635
636         int mkleading = (flags & 2);
637         int setmd = (flags & 1);
638         int unlink_file = (flags & 4);
639         int rm_dir = (flags & 8);
640         int failure = conf->errabort;
641         int success = 0;
642
643         if (flags & 16) {
644                 failure = 0;
645                 success = 1;
646         }
647
648         if (conf->dryrun) {
649                 if (unlink_file) {
650                         printf("unlink %s\n", item->dest);
651                 } else if (rm_dir) {
652                         printf("rmdir %s\n", item->dest);
653                 }
654
655                 printf("install %c%o %d:%d %s -> %s\n", item->ftype,
656                                 item->mode, item->uid, item->gid, item->path,
657                                 item->dest);
658                 fflush(stdout);
659                 return success;
660         }
661
662         source = conf->src ? conf->src : conf->log;
663
664         if (unlink_file) {
665                 rv = remove_existing(conf, item->dest);
666         } else if (rm_dir) {
667                 rv = remove_dir(conf, item->dest);
668         }
669
670         if (rv != 1) {
671                 return failure;
672         }
673
674         if (mkleading) {
675                 rv = create_leading_dirs(item->dest);
676                 if (!rv) {
677                         setsyserr(conf, "can't create leading dirs for %s", item->dest);
678                         return failure;
679                 }
680         }
681
682         if (item->ftype == 'r') {
683                 rv = zpm_extract(source, item->hash, item->dest, item->mode);
684                 if (rv == 0) {
685                         seterror(conf, "can't extract %s", item->dest);
686                         return failure;
687                 }
688                 return success;
689         }
690
691         switch (item->ftype) {
692                 case 'd': rv = mkdir(item->dest, item->mode);
693                           break;
694                 case 'l': rv = symlink(item->target, item->dest);
695                           break;
696                 default: /* error */
697                           break;
698         }
699
700         if (rv == -1) {
701                 setsyserr(conf, "installing %s failed", item->dest);
702                 return failure;
703         }
704
705         if (setmd) {
706                 return set_md(conf, item) == 0 ? success : failure;
707         }
708
709         return success;
710 }
711
712 /*
713  *
714  */
715 static int adjust_for_config(struct config *conf, struct nitem *n, unsigned int
716                 diffs) {
717 #if 0
718         if (!n->oldwasconf) {
719                 return 0;
720         }
721 #endif
722         /* TODO what if old was a directory? */
723         if (!n->configuration) {
724                 /* replacing conf with non-conf */
725                 /* absorb file, mark todo */
726                 char hash[ZPM_HASH_STRLEN+1];
727                 if (zpm_import(conf->log, n->dest, 0, hash)) {
728                         zpm_note_add(conf->log, n->pkglist, n->dest, hash,
729                                         "replaced config file with non-config.  zpm-cat %.8s", hash);
730                 } else {
731                         fprintf(stderr, "unable to import existing config file %s\n", n->dest);
732                         return 1;
733                 }
734                 return 0;
735         }
736
737         int sametype = (!(diffs & D_TYPE));
738         int isdir = (diffs & D_ISDIR);
739         int eisdir = (diffs & D_EISDIR);
740
741         /* both old and new are config files */
742         if (isdir && sametype) {
743                 /* both config directories, can only be changing
744                  * metadata, so no adjustment needed
745                  */
746                 return 0;
747         }
748
749         if (isdir) {
750                 char hash[ZPM_HASH_STRLEN+1];
751
752                 /* replacing old file with new directory */
753                 /* absorb, make note */
754                 if (zpm_import(conf->log, n->dest, 0, hash)) {
755                         zpm_note_add(conf->log, n->pkglist, n->dest, hash,
756                                         "replaced config file with config directory.  zpm-cat %.8s", hash);
757                 } else {
758                         fprintf(stderr, "unable to import existing config file %s\n", n->dest);
759                         return -1;
760                 }
761                 return 0;
762         }
763
764         if (eisdir) {
765                 /* replacing old conf directory with a conf file.
766                  * nothing needs to be done, if the directory
767                  * is empty, it's ok to remove.  if it's not empty,
768                  * the install will fail
769                  */
770                 return 0;
771         }
772         
773         /* replacing old file with new file */
774         /* new is same as on disk */
775         if (!(diffs & D_HASH)) {
776                 return 0;
777         }
778
779         /* new is different than on disk, but on disk is same as old */
780         if (!(diffs & D_OHASH)) {
781                 /* ok to do the update, since same as default */
782                 fprintf(stderr, "updating default config %s\n", n->dest);
783                 return 0;
784         }
785
786         /* new is different than on disk, and disk different than old */
787         /* log */
788         zpm_note_add(conf->log, n->pkglist, n->dest, n->hash,
789                         "default config file update.  zpm-cat %.8s", n->hash);
790         /* TODO check for note error */
791         return 1;
792
793 }
794
795 static int install_files(void *f, int ncols, char **vals, char **cols) {
796         struct config *conf = f;
797         struct nitem nitem;
798         struct stat existing;
799         int update = 0;
800
801         /* TODO put the result row in a hash table.  May not actually
802          * be faster
803          */
804         if (!read_item(conf, ncols, vals, cols, &nitem)) {
805                 fprintf(stderr, "can't read item\n");
806                 return conf->errabort;
807         }
808
809         if (conf->verbose && !conf->dryrun) {
810                 fprintf(stderr, "%s '%c' %s\n", nitem.opstr, nitem.ftype,
811                                 nitem.dest);
812         }
813
814         unsigned int diffs = file_compare(&nitem, &existing);
815         if (diffs >= D_ERROR) {
816                 return seterror(conf, "can't check %s", nitem.dest);
817         }
818
819         /* updates:
820          * exist & same type & md same & hash same: do nothing, but warn bug
821          * exist & same type & md diff & hash same: fix md
822          * exist & same type & md same & hash diff: replace
823          * exist & same type & md diff & hash diff: replace & fix
824          * no exist: install and warn
825          * dir & not dir : remove, mkdir
826          * not dir & not dir & diff type: remove, install
827          * not dir & dir : remove dir if empty, error if not empty, install
828          *
829          * installs:
830          * no exist: create leading dirs, install
831          *
832          * exist & same type & md same & hash same & accept or over: do nothing
833          * exist & same & md diff or hash diff & overwrite : update
834          * exist & same & md diff or hash diff & accept : error, can't accept
835          * exist & same & md diff or hash diff & not accept : error
836          *
837          * exist & different type & not overwrite : error
838          * not dir & not dir & overwrite : remove and install
839          * not dir & dir & overwrite: remove empty or error, install
840          * dir & dir & overwrite: fix md
841          * dir & not dir & overwrite: remove and mkdir
842          */
843         int exist = (!(diffs & D_NOEXIST));
844         int sametype = (!(diffs & D_TYPE));
845         int mdsame = (!(diffs & D_MD));
846         int hashsame = (!(diffs & D_HASH));
847         int isdir = (diffs & D_ISDIR);
848         int eisdir = (diffs & D_EISDIR);
849         int accept = conf->absorb;
850         int overwrite = conf->overwrite;
851         int installing = (nitem.op == OP_NEW);
852         update = (nitem.op == OP_UPDATE);
853
854         if (update) {
855                 if (!exist) {
856                         /* warn, it should exist */
857                         fprintf(stderr, "%s missing, installing", nitem.dest);
858                         return install(conf, &nitem, 3);
859                 }
860
861                 switch (adjust_for_config(conf, &nitem, diffs)) {
862                         case -1: return conf->errabort; break;
863                         case 1:
864                         fprintf(stderr, "skipping changed default config file: %s\n", nitem.dest);
865                         return 0; break;
866                         default: break;
867                 }
868
869                 /* file exists in filesystem */
870                 if (sametype) {
871                         if (mdsame && hashsame) {
872                                 /* warn, bug in logic.  This shouldn't occur,
873                                  * because if there is nothing to do, it
874                                  * shouldn't be listed as an update
875                                  */
876                                 /* could be an update.  We're checking against
877                                  * what's actually on disk, not what was
878                                  * expected to have been on disk.  So, if
879                                  * the admin has modified the file, or if
880                                  * it had been installed ignoring the user
881                                  * and group, it might be correct on disk
882                                  * but not as in the local database
883                                  */
884                                 /* TODO detect whether this a logic bug or
885                                  * an on-disk difference
886                                  */
887 #if 0
888                                 fprintf(stderr, "%s should not be an update\n", nitem.dest);
889                                 fprintf(stderr, "old hash: %s\n", nitem.ohash);
890                                 fprintf(stderr, "new hash: %s\n", nitem.hash);
891                                 fprintf(stderr, "old mds: %s\n", nitem.omds);
892                                 fprintf(stderr, "new mds: %s\n", nitem.mds);
893 #endif
894                                 /* do nothing */
895                                 return 0;
896                         }
897                         if (!mdsame && hashsame) {
898                                 /* fix md */
899                                 return set_md(conf, &nitem);
900                         }
901                         if (mdsame && !hashsame) {
902                                 /* install */
903                                 return install(conf, &nitem, 3);
904                         }
905                         if (!mdsame && !hashsame) {
906                                 /* install */
907                                 return install(conf, &nitem, 3);
908                         }
909                 }
910
911                 /* file exists, and is not the same type */
912
913                 if (isdir && !eisdir) {
914                         /* remove existing */
915                         /* mkdir */
916                         return install(conf, &nitem, 7);
917                 }
918                 if (!isdir && eisdir) {
919                         /* remove dir, or error */
920                         /* install */
921                         return install(conf, &nitem, 11);
922                 }
923                 if (!isdir && !isdir) {
924                         /* necessarily !sametype, sametype handled above */
925                         /* remove existing */
926                         /* install */
927                         return install(conf, &nitem, 7);
928                 }
929                 /* error, should not be possible, assert(0)? */
930                 fprintf(stderr,"impossible state: %s:%d\n", __func__, __LINE__);
931         }
932
933         if (installing) {
934                 if (!exist) {
935                         return install(conf, &nitem, 3);
936                 }
937
938                 /* file exists in filesystem */
939                 if (sametype) {
940                         if (mdsame && hashsame && (accept || overwrite)) {
941                                 /* do nothing */
942                                 if (conf->dryrun || conf->verbose) {
943                                         fprintf(stderr, "accepting existing file: %s\n", nitem.dest);
944                                 }
945                                 return 0;
946                         }
947                         if (mdsame && hashsame && !(accept || overwrite)) {
948                                 /* error */
949                                 return seterror(conf, "will not accept or overwrite existing file: %s", nitem.dest);
950                         }
951                         if (mdsame && !hashsame && overwrite) {
952                                 /* install */
953                                 return install(conf, &nitem, eisdir ? 11 : 7);
954                         }
955                         if (mdsame && !hashsame && !overwrite) {
956                                 /* accept doesn't matter, since it's
957                                  * not an acceptable file */
958                                 /* error */
959                                 return seterror(conf, "%s (hashdiff): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
960                         }
961                         if (!mdsame && hashsame && overwrite) {
962                                 /* fix md */
963                                 return set_md(conf, &nitem);
964                         }
965                         if (!mdsame && hashsame && !overwrite) {
966                                 /* accept doesn't matter, since it's
967                                  * not an acceptable file */
968                                 /* error */
969                                 return seterror(conf, "%s (mddiff): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
970                         }
971                         if (!mdsame && !hashsame && overwrite) {
972                                 /* install */
973                                 return install(conf, &nitem, eisdir ? 11 : 7);
974                         }
975                         if (!mdsame && !hashsame && !overwrite) {
976                                 /* accept doesn't matter, since it's
977                                  * not an acceptable file */
978                                 /* error */
979                                 return seterror(conf, "%s (md+hash): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
980                         }
981                         /* TODO error, should be impossible */
982                         return seterror(conf, "impossible state reached");
983                 }
984
985                 /* file exists, and is not the same type */
986                 if (!overwrite) {
987                         /* error */
988                                 return seterror(conf, "%s (difftype): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
989                 }
990
991                 /* not the same type, but ok to overwrite */
992                 if (!eisdir) {
993                         /* remove existing */
994                         return install(conf, &nitem, 7);
995                 }
996
997                 /* existing path is a directory */
998                 if (isdir) {
999                         /* fix md */
1000                         /* impossible, if isdir and eisdir, would
1001                          * be same type
1002                          * TODO
1003                          */
1004                         return set_md(conf, &nitem);
1005                 } else {
1006                         /* remove empty dir or error */
1007                         /* install */
1008                         return install(conf, &nitem, 11);
1009                 }
1010                 /* if we get here, we missed a case */
1011                 /* TODO error */
1012                 return seterror(conf, "impossible state 2 reached");
1013         }
1014
1015         /* TODO extra verbose print perms, mtime, etc, probably ls -l
1016          * format
1017          */ 
1018         if (conf->verbose) {
1019                 printf("%s\n", nitem.path);
1020         }
1021
1022         return 0;
1023 }
1024
1025 static void check_conflicts(struct config *conf, char *conflict_type,
1026                 int (callback)(void *, int, char **, char **)) {
1027         int rv;
1028         char *errmsg;
1029         sqlite3_str *s;
1030         char *sql;
1031
1032         s = sqlite3_str_new(conf->log->db);
1033         sqlite3_str_appendall(s, "select *, ");
1034         if (conf->rootdir) {
1035                 sqlite3_str_appendf(s, "printf('%%s/%%s',rtrim(%Q,'/'),ltrim(path,'/'))", conf->rootdir);
1036         } else {
1037                 sqlite3_str_appendf(s, "printf('/%%s', trim(path, '/'))");
1038         }
1039         sqlite3_str_appendall(s, " as dest from syncconflicts");
1040
1041         if (conflict_type) {
1042                 sqlite3_str_appendf(s," where conflict = %Q", conflict_type);
1043         }
1044         if (conf->reverse) {
1045                 sqlite3_str_appendall(s," order by length(path) desc, path desc,pkgid collate vercmp desc, conflict desc");
1046         } else {
1047                 sqlite3_str_appendall(s," order by length(path), path, pkgid collate vercmp, conflict");
1048
1049         }
1050
1051         sql = sqlite3_str_value(s);
1052
1053         rv = zpm_exec(conf->log, sql, callback, conf, &errmsg);
1054
1055         sqlite3_str_finish(s);
1056
1057         if (rv) {
1058                 fprintf(stderr, "exec fail: %s\n", sqlite3_errstr(rv));
1059                 if (errmsg) {
1060                         fprintf(stderr, "database error: %s\n", errmsg);
1061                         conf->errors++;
1062                 }
1063                 if (conf->log->error == 1) {
1064                         fprintf(stderr, "unable to allocate memory\n");
1065                 }
1066                 fprintf(stderr, "zpm_exec failure: %s\n",
1067                                 conf->log->errmsg ? conf->log->errmsg : "unknown");
1068                 conf->errors++;
1069         }
1070         if (conf->log->errmsg) {
1071                 fprintf(stderr, "error: %s\n", conf->log->errmsg);
1072         }
1073         if (conf->errors && conf->exitonerror) {
1074                 zpm_close(conf->log);
1075                 zpm_close(conf->src);
1076                 exit(EXIT_FAILURE);
1077         }
1078         /* TODO final report function in conf var */
1079 }
1080
1081 static void runstage(struct config *conf, char *stage,
1082                 int (callback)(void *, int, char **, char **)) {
1083         int rv;
1084         char *errmsg;
1085         sqlite3_str *s;
1086         char *sql;
1087
1088         s = sqlite3_str_new(conf->log->db);
1089         sqlite3_str_appendall(s, "select *, ");
1090         if (conf->rootdir) {
1091                 sqlite3_str_appendf(s, "printf('%%s/%%s',rtrim(%Q,'/'),ltrim(path,'/'))", conf->rootdir);
1092         } else {
1093                 sqlite3_str_appendf(s, "printf('/%%s', trim(path, '/'))");
1094         }
1095         sqlite3_str_appendall(s, " as dest from syncinfo");
1096
1097         if (stage) {
1098                 sqlite3_str_appendf(s," where op = %Q", stage);
1099         }
1100         if (conf->reverse) {
1101                 sqlite3_str_appendall(s," order by length(path) desc, path desc");
1102         }
1103
1104         sql = sqlite3_str_value(s);
1105
1106         rv = zpm_exec(conf->log, sql, callback, conf, &errmsg);
1107
1108         sqlite3_str_finish(s);
1109
1110         if (rv) {
1111                 fprintf(stderr, "exec fail: %s\n", sqlite3_errstr(rv));
1112                 if (errmsg) {
1113                         fprintf(stderr, "database error: %s\n", errmsg);
1114                         conf->errors++;
1115                 }
1116                 if (conf->log->error == 1) {
1117                         fprintf(stderr, "unable to allocate memory\n");
1118                 }
1119                 fprintf(stderr, "zpm_exec failure: %s\n",
1120                                 conf->log->errmsg ? conf->log->errmsg : "unknown");
1121                 conf->errors++;
1122         }
1123 #if 0
1124         if (conf->log->errmsg) {
1125                 fprintf(stderr, "error: %s\n", conf->log->errmsg);
1126         }
1127 #endif
1128         if (conf->errors && conf->exitonerror) {
1129                 zpm_close(conf->log);
1130                 zpm_close(conf->src);
1131                 exit(EXIT_FAILURE);
1132         }
1133         /* TODO final report function in conf var */
1134 }
1135
1136 int main(int ac, char **av){
1137         struct zpm localdb;
1138         struct zpm pkgdb;
1139         int opt;
1140         char *pkgdbfile = 0, *localdbfile = 0;
1141         char *s;
1142
1143         struct config conf;
1144
1145         conf.errabort = 1;
1146         conf.errors = 0;
1147         conf.conflicts = 0;
1148         conf.verbose = 0;
1149         conf.dryrun = 0;
1150         conf.setuser = 1;
1151         conf.setgroup = 1;
1152         conf.log = 0;
1153         conf.src = 0;
1154         conf.rootdir = 0;
1155         conf.reverse = 0;
1156         conf.overwrite = 0;
1157         conf.absorb = 0;
1158
1159         if (geteuid() != 0) {
1160                 conf.setuser = 0;
1161                 conf.setgroup = 0;
1162         }
1163
1164         localdbfile = ZPM_LOCAL_DB;
1165         if ((s = getenv("ZPMDB"))) {
1166                 /* TODO does this need to be copied ? */
1167                 localdbfile = s;
1168         }
1169
1170         if ((s = getenv("ZPM_ROOT_DIR"))) {
1171                 /* TODO does this need to be copied ? */
1172                 conf.rootdir = s;
1173         }
1174
1175         /*
1176          * -d localdb or ZPMDB * or /var/lib/zpm/zpm.db, or die
1177          * -f 'package database', otherwise regular default of env
1178          *  ZPM_PACKAGE_FILE, or use pkgdb if otherwise not found
1179          * -R root of pkg, will just chdir there
1180          *
1181          *  args are pkgid triple, but will do a pkg find on the pkgdb
1182          */
1183
1184         while ((opt = getopt(ac, av, "f:d:c:nCR:vOA")) != -1) {
1185                 switch (opt) {
1186                         case 'd': localdbfile = optarg; break;
1187                         case 'f': pkgdbfile = optarg; break;
1188                         case 'n': conf.dryrun = 1; break;
1189                         case 'v': conf.verbose++; break;
1190                         case 'C': conf.errabort = 0; break;
1191                         case 'R': conf.rootdir = optarg; break;
1192                         case 'N': conf.setuser = 0; conf.setgroup = 0; break;
1193                         case 'O': conf.overwrite = 1; break;
1194                         case 'A': conf.absorb = 1; break;
1195                         default:
1196                                   usage();
1197                                   exit(EXIT_FAILURE);
1198                                   break;
1199                 }
1200         }
1201
1202         /* verify root dir exists */
1203         if (conf.rootdir && !exists(conf.rootdir, NULL)) {
1204                 fprintf(stderr, "rootdir %s does not exist\n", conf.rootdir);
1205         }
1206
1207         if (!zpm_open(&localdb, localdbfile)) {
1208                 fprintf(stderr, "can't open zpm db %s\n", localdbfile);
1209                 exit(EXIT_FAILURE);
1210         }
1211         conf.log = &localdb;
1212
1213         if (pkgdbfile) {
1214                 if (!zpm_open(&pkgdb, pkgdbfile)) {
1215                         fprintf(stderr, "can't open src db %s\n", localdbfile);
1216                         exit(EXIT_FAILURE);
1217                 } else {
1218                         conf.src = &pkgdb;
1219                 }
1220         }
1221
1222         /* TODO find pkgid from arg */
1223
1224         /* TODO set conf var to finalize error reporting */
1225         if (conf.verbose) {
1226                 fprintf(stderr, "syncing filesystem %s (ldb %s) from %s\n",
1227                                 conf.rootdir ? conf.rootdir : "/",
1228                                 localdbfile, pkgdbfile);
1229         }
1230
1231         conf.errors = 0;
1232         conf.exitonerror = 0;
1233         check_conflicts(&conf, NULL, report_conflicts);
1234
1235         if (conf.conflicts) {
1236                 fprintf(stderr, "%d conflicts reported, aborting sync\n",
1237                                 conf.conflicts);
1238                 conf.errors++;
1239         } else {
1240                 /* no point in running it if we're just going to
1241                  * overwrite everything
1242                  */
1243                 if (!conf.overwrite && !conf.absorb && !conf.dryrun) {
1244                         runstage(&conf, "new", check_existing);
1245                 }
1246
1247                 if (conf.verbose) {
1248                         fprintf(stderr, "beginning %ssync\n", conf.dryrun ?
1249                                         "dryrun " : "");
1250                 }
1251                 /* have to do the removes first otherwise
1252                  * old files may conflict with update file
1253                  * type changes
1254                  */
1255                 if (!conf.errors) {
1256                         conf.exitonerror = conf.dryrun ? 0 : 1;
1257                         conf.errabort = conf.dryrun ? 0 : 1;
1258                         conf.reverse = 1;
1259                         if (conf.verbose) {
1260                                 fprintf(stderr, "removing old files\n");
1261                         }
1262                         runstage(&conf, "remove", remove_files);
1263                         conf.reverse = 0;
1264                         if (conf.verbose) {
1265                                 fprintf(stderr, "updating files\n");
1266                         }
1267                         runstage(&conf, "update", install_files);
1268                         if (conf.verbose) {
1269                                 fprintf(stderr, "installing files\n");
1270                         }
1271                         runstage(&conf, "new", install_files);
1272                 }
1273         }
1274
1275         zpm_close(&localdb);
1276         zpm_close(conf.src);
1277         return conf.errors ? 1 : 0;
1278 }