]> pd.if.org Git - zpackage/blob - zpm-syncfs.c
add where clause argument to findpkg
[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 /* file does not exist */
338 #define D_NOEXIST 0x1
339 /* files are different types */
340 #define D_TYPE 0x2
341 /* metadata is different */
342 #define D_MD 0x4
343 /* content or link target is different */
344 #define D_HASH 0x8
345 /* file to be installed is a directory */
346 #define D_ISDIR  0x10
347 /* path on disk is a directory */
348 #define D_EISDIR 0x20
349 /* usernames different */
350 #define D_UID 0x40
351 /* group names different */
352 #define D_GID 0x80
353 /* file mode is different */
354 #define D_MODE 0x100
355 /* mtimes are different */
356 #define D_MTIME 0x200
357 /* the hash of the file we are supposedly replacing is different than
358  * the the hash of the file on disk
359  */
360 #define D_OHASH 0x400
361 /* an error occurred trying to compare the file (other than it doesn't exist */
362 #define D_ERROR 0x1000
363 /* there was a stat error */
364 #define D_STATERROR 0x2000
365 /* there was an error calling readlink */
366 #define D_RLERROR 0x4000
367
368 /* 1 = file doesn't exist, 2 = file is a directory, target isn't */
369 /* 4 == ftype different */
370 /* 8 = hash different when both are regular files */
371 static unsigned int file_compare(struct nitem *n, struct stat *st) {
372         int etype = 0, stat_type;
373         char ehash[ZPM_HASH_STRLEN+1];
374         unsigned int diff = 0;
375         char link[1024];
376         ssize_t lsize;
377
378         switch (n->ftype) {
379                 case 'd': etype = S_IFDIR; diff |= D_ISDIR ; break;
380                 case 'r': etype = S_IFREG; break;
381                 case 'l': etype = S_IFLNK; break;
382                 default: etype = 0; break;
383         }
384
385         errno = 0;
386         /* new file, so check type, hash, etc */
387         if (lstat(n->dest, st) == 0) {
388                 stat_type = st->st_mode & S_IFMT;
389                 if (stat_type != etype) {
390                         diff |= D_TYPE;
391                 }
392                 if (stat_type == S_IFDIR) {
393                         diff |= D_EISDIR;
394                 }
395
396                 if (n->hash && etype == S_IFREG && stat_type == S_IFREG) {
397                         zpm_hash(n->dest, ehash, 0);
398                         if (strcmp(n->hash, ehash) != 0) {
399                                 diff |= D_HASH;
400                         }
401                         if (n->ohash && strcmp(n->ohash, ehash) != 0) {
402                                 diff |= D_OHASH;
403                         }
404                 }
405                 if (n->hash && etype == S_IFLNK && stat_type == S_IFLNK) {
406                         lsize = readlink(n->dest, link, sizeof link);
407
408                         if (lsize == -1 || lsize == sizeof link) {
409                                 diff |= D_RLERROR;
410                                 diff |= D_ERROR;
411                         } else {
412                                 link[lsize] = 0;
413                                 if (strcmp(n->target, link) != 0) {
414                                         diff |= D_HASH;
415                                 }
416                         }
417                 }
418                 if (n->uid != st->st_uid) {
419                         diff |= D_UID;
420                         diff |= D_MD;
421                 }
422                 if (n->gid != st->st_gid) {
423                         diff |= D_GID;
424                         diff |= D_MD;
425                 }
426                 if (n->mode != (st->st_mode & 07777)) {
427                         diff |= D_MODE;
428                         diff |= D_MD;
429                 }
430         } else {
431                 switch(errno) {
432                         case ENOENT: diff |= D_NOEXIST; break;
433                         default: diff |= (D_STATERROR|D_ERROR); break;
434                 }
435         }
436
437         return diff;
438 }
439
440 static int read_item(struct config *conf, int ncols, char **vals, char **cols,
441                 struct nitem *n) {
442         char *val;
443         struct passwd *pw;
444         struct group *gr;
445         struct nitem zero = { 0 };
446
447         *n = zero;
448
449         val = COL("op");
450         if (!val) {
451                 seterror(conf, "can't determine op");
452                 return 0;
453         }
454         n->opstr = val;
455         n->op = getop(val);
456         if (!n->op) {
457                 seterror(conf, "can't determine op");
458                 return 0;
459         }
460
461         n->path = COL("path");
462         if (!n->path) {
463                 seterror(conf, "no file path");
464                 return 0;
465         }
466         if (strlen(n->path) == 0) {
467                 seterror(conf, "zero length path not allowed");
468                 return 0;
469         }
470
471         /* TODO config to dishonor setuid/setgid */
472         n->dest = COL("dest");
473         if (!n->dest) {
474                 seterror(conf, "no file dest");
475                 return 0;
476         }
477
478         if (strlen(n->dest) == 0) {
479                 seterror(conf, "zero length dest not allowed");
480                 return 0;
481         }
482
483         val = COL("mode");
484
485         if (!val) {
486                 seterror(conf, "can't determine mode");
487                 return 0;
488         }
489
490         n->mode = strtoul(val, NULL, 8);
491
492         val = COL("configuration");
493         if (!val) {
494                 seterror(conf, "can't determine config status");
495                 return 0;
496         }
497         n->configuration = strtoul(val, NULL, 10);
498
499         val = COL("filetype");
500         if (!val || strlen(val) == 0) {
501                 seterror(conf, "can't determine file type");
502                 return 0;
503         }
504         n->ftype = *val;
505
506         /* these can be null */
507         n->ohash = COL("ohash");
508         n->mds = COL("mds");
509         n->omds = COL("omds");
510         n->pkglist = COL("pkglist");
511
512         if (n->ftype == 'r') {
513                 n->hash = COL("hash");
514                 if (!n->hash) {
515                         seterror(conf, "can't get hash");
516                         return 0;
517                 }
518         } else if (n->ftype == 'l') {
519                 n->target = COL("target");
520                 if (!n->target) {
521                         seterror(conf, "can't get target");
522                         return 0;
523                 }
524                 if (strlen(n->target) == 0) {
525                         seterror(conf, "zero length target not allowed");
526                         return 0;
527                 }
528                 n->hash = n->target;
529         }
530
531         if (conf->setuser) {
532                 val = COL("username");
533                 if (!val) {
534                         seterror(conf, "no username");
535                         return 0;
536                 }
537                 pw = getpwnam(val);
538                 if (!pw) {
539                         seterror(conf, "no passwd entry");
540                         return 0;
541                 }
542                 n->uid = pw->pw_uid;
543         } else {
544                 n->uid = geteuid();
545         }
546
547         if (conf->setgroup) {
548                 val = COL("groupname");
549                 if (!val) {
550                         seterror(conf, "no groupname");
551                         return 0;
552                 }
553                 gr = getgrnam(val);
554                 if (!gr) {
555                         seterror(conf, "no group entry");
556                         return 0;
557                 }
558                 n->gid = gr->gr_gid;
559         } else {
560                 n->gid = getegid();
561         }
562
563         errno = 0;
564         double mtime = strtod(COL("mtime"),NULL);
565         if (errno) {
566                 mtime = (double)time(NULL);
567         }
568
569         n->mtime = (time_t)mtime;
570
571         n->times[0].tv_sec = 0;
572         n->times[0].tv_nsec = UTIME_OMIT;
573         n->times[1].tv_sec = (time_t)llrint(floor(mtime));
574         n->times[1].tv_nsec = lrint(floor(fmod(mtime,1.0)*1000000000));
575
576         return 1;
577 }
578
579 static int remove_dir(struct config *conf, char *path) {
580         int rv;
581
582         rv = rmdir(path);
583         if (rv == -1) {
584                 setsyserr(conf, "can't rmdir %s", path);
585                 return 0;
586         }
587         return 1;
588 }
589
590 static int remove_existing(struct config *conf, char *path) {
591         int rv;
592
593         rv = unlink(path);
594         if (rv == -1) {
595                 setsyserr(conf, "can't unlink %s", path);
596                 return 0;
597         }
598         return 1;
599 }
600
601 static int set_md(struct config *conf, struct nitem *item) {
602         int rv;
603         int success = 0;
604
605         if (conf->dryrun) {
606                 printf("chmod %o %s\n", item->mode, item->dest);
607                 if (conf->setuser && conf->setgroup) {
608                         printf("chown %d:%d %s\n", item->uid, item->gid,
609                                         item->dest);
610                 }
611                 printf("mtime %.0f %s\n", (double)item->mtime, item->dest);
612                 fflush(stdout);
613                 return success;
614         }
615
616         rv = chmod(item->dest, item->mode);
617
618         if (rv == -1) {
619                 setsyserr(conf, "can't chmod %o %s", item->mode, item->dest);
620                 return conf->errabort;
621         }
622
623         if (conf->setuser && conf->setgroup) {
624                 rv = chown(item->dest, item->uid, item->gid);
625                 if (rv == -1) {
626                         setsyserr(conf, "can't chown %s", item->dest);
627                         return conf->errabort;
628                 }
629         }
630
631         rv = utimensat(AT_FDCWD, item->dest, item->times, AT_SYMLINK_NOFOLLOW);
632         if (rv == -1) {
633                 setsyserr(conf, "can't set mtime %.0f %s", (double)item->mtime,
634                                 item->dest);
635                 return conf->errabort;
636         }
637         return 0;
638 }
639
640 /* install a file or create a directory or symlink.  path should not exist
641  * at this point.
642  */
643 /* flags: 1 = set md, 2 = create leading dirs, 4 = unlink existing file,
644  * 8 = rmdir existing dir, 16 = return true/false
645  */
646 #define INS_MD 0x1
647 #define INS_CLD 0x2
648 #define INS_UNLINK 0x4
649 #define INS_RMDIR 0x8
650 #define INS_RTF 0x10
651 #define INS_ZPMNEW 0x20
652 static int install(struct config *conf, struct nitem *item, unsigned int flags) {
653         int rv = 1;
654         struct zpm *source;
655
656         int mkleading = (flags & 2);
657         int setmd = (flags & 1);
658         int unlink_file = (flags & 4);
659         int rm_dir = (flags & 8);
660         int failure = conf->errabort;
661         int success = 0;
662
663         if (flags & 16) {
664                 failure = 0;
665                 success = 1;
666         }
667
668         if (conf->dryrun) {
669                 if (unlink_file) {
670                         printf("unlink %s\n", item->dest);
671                 } else if (rm_dir) {
672                         printf("rmdir %s\n", item->dest);
673                 }
674
675                 printf("install %c%o %d:%d %s -> %s\n", item->ftype,
676                                 item->mode, item->uid, item->gid, item->path,
677                                 item->dest);
678                 fflush(stdout);
679                 return success;
680         }
681
682         source = conf->src ? conf->src : conf->log;
683
684         if (unlink_file) {
685                 rv = remove_existing(conf, item->dest);
686         } else if (rm_dir) {
687                 rv = remove_dir(conf, item->dest);
688         }
689
690         if (rv != 1) {
691                 return failure;
692         }
693
694         if (mkleading) {
695                 rv = create_leading_dirs(item->dest);
696                 if (!rv) {
697                         setsyserr(conf, "can't create leading dirs for %s", item->dest);
698                         return failure;
699                 }
700         }
701
702         if (item->ftype == 'r') {
703                 rv = zpm_extract(source, item->hash, item->dest, item->mode);
704                 if (rv == 0) {
705                         seterror(conf, "can't extract %s", item->dest);
706                         return failure;
707                 }
708                 return success;
709         }
710
711         switch (item->ftype) {
712                 case 'd': rv = mkdir(item->dest, item->mode);
713                           break;
714                 case 'l': rv = symlink(item->target, item->dest);
715                           break;
716                 default: /* error */
717                           break;
718         }
719
720         if (rv == -1) {
721                 setsyserr(conf, "installing %s failed", item->dest);
722                 return failure;
723         }
724
725         if (setmd) {
726                 return set_md(conf, item) == 0 ? success : failure;
727         }
728
729         return success;
730 }
731
732 /*
733  *
734  */
735 static int adjust_for_config(struct config *conf, struct nitem *n, unsigned int
736                 diffs) {
737 #if 0
738         if (!n->oldwasconf) {
739                 return 0;
740         }
741 #endif
742         /* TODO what if old was a directory? */
743         if (!n->configuration) {
744                 /* replacing conf with non-conf */
745                 /* absorb file, mark todo */
746                 char hash[ZPM_HASH_STRLEN+1];
747                 if (zpm_import(conf->log, n->dest, 0, hash)) {
748                         zpm_note_add(conf->log, n->pkglist, n->dest, hash,
749                                         "replaced config file with non-config.  zpm-cat %.8s", hash);
750                 } else {
751                         fprintf(stderr, "unable to import existing config file %s\n", n->dest);
752                         return 1;
753                 }
754                 return 0;
755         }
756
757         int sametype = (!(diffs & D_TYPE));
758         int isdir = (diffs & D_ISDIR);
759         int eisdir = (diffs & D_EISDIR);
760
761         /* both old and new are config files */
762         if (isdir && sametype) {
763                 /* both config directories, can only be changing
764                  * metadata, so no adjustment needed
765                  */
766                 return 0;
767         }
768
769         if (isdir) {
770                 char hash[ZPM_HASH_STRLEN+1];
771
772                 /* replacing old file with new directory */
773                 /* absorb, make note */
774                 if (zpm_import(conf->log, n->dest, 0, hash)) {
775                         zpm_note_add(conf->log, n->pkglist, n->dest, hash,
776                                         "replaced config file with config directory.  zpm-cat %.8s", hash);
777                 } else {
778                         fprintf(stderr, "unable to import existing config file %s\n", n->dest);
779                         return -1;
780                 }
781                 return 0;
782         }
783
784         if (eisdir) {
785                 /* replacing old conf directory with a conf file.
786                  * nothing needs to be done, if the directory
787                  * is empty, it's ok to remove.  if it's not empty,
788                  * the install will fail
789                  */
790                 return 0;
791         }
792         
793         /* replacing old file with new file */
794         /* new is same as on disk */
795         if (!(diffs & D_HASH)) {
796                 return 0;
797         }
798
799         /* new is different than on disk, but on disk is same as old */
800         if (!(diffs & D_OHASH)) {
801                 /* ok to do the update, since same as default */
802                 fprintf(stderr, "updating default config %s\n", n->dest);
803                 return 0;
804         }
805
806         /* new is different than on disk, and disk different than old */
807         /* log */
808         zpm_note_add(conf->log, n->pkglist, n->dest, n->hash,
809                         "default config file update.  zpm-cat %.8s", n->hash);
810         /* TODO check for note error */
811         return 1;
812
813 }
814
815 static int install_files(void *f, int ncols, char **vals, char **cols) {
816         struct config *conf = f;
817         struct nitem nitem;
818         struct stat existing;
819         int update = 0;
820
821         /* TODO put the result row in a hash table.  May not actually
822          * be faster
823          */
824         if (!read_item(conf, ncols, vals, cols, &nitem)) {
825                 fprintf(stderr, "can't read item\n");
826                 return conf->errabort;
827         }
828
829         if (conf->verbose && !conf->dryrun) {
830                 fprintf(stderr, "%s '%c' %s\n", nitem.opstr, nitem.ftype,
831                                 nitem.dest);
832         }
833
834         unsigned int diffs = file_compare(&nitem, &existing);
835         if (diffs >= D_ERROR) {
836                 return seterror(conf, "can't check %s", nitem.dest);
837         }
838
839         /* updates:
840          * exist & same type & md same & hash same: do nothing, but warn bug
841          * exist & same type & md diff & hash same: fix md
842          * exist & same type & md same & hash diff: replace
843          * exist & same type & md diff & hash diff: replace & fix
844          * no exist: install and warn
845          * dir & not dir : remove, mkdir
846          * not dir & not dir & diff type: remove, install
847          * not dir & dir : remove dir if empty, error if not empty, install
848          *
849          * installs:
850          * no exist: create leading dirs, install
851          *
852          * exist & same type & md same & hash same & accept or over: do nothing
853          * exist & same & md diff or hash diff & overwrite : update
854          * exist & same & md diff or hash diff & accept : error, can't accept
855          * exist & same & md diff or hash diff & not accept : error
856          *
857          * exist & different type & not overwrite : error
858          * not dir & not dir & overwrite : remove and install
859          * not dir & dir & overwrite: remove empty or error, install
860          * dir & dir & overwrite: fix md
861          * dir & not dir & overwrite: remove and mkdir
862          */
863         int exist = (!(diffs & D_NOEXIST));
864         int sametype = (!(diffs & D_TYPE));
865         int mdsame = (!(diffs & D_MD));
866         int hashsame = (!(diffs & D_HASH));
867         int isdir = (diffs & D_ISDIR);
868         int eisdir = (diffs & D_EISDIR);
869         int accept = conf->absorb;
870         int overwrite = conf->overwrite;
871         int installing = (nitem.op == OP_NEW);
872         update = (nitem.op == OP_UPDATE);
873
874         if (update) {
875                 if (!exist) {
876                         /* warn, it should exist */
877                         fprintf(stderr, "%s missing, installing", nitem.dest);
878                         return install(conf, &nitem, 3);
879                 }
880
881                 switch (adjust_for_config(conf, &nitem, diffs)) {
882                         case -1: return conf->errabort; break;
883                         case 1:
884                         fprintf(stderr, "skipping changed default config file: %s\n", nitem.dest);
885                         return 0; break;
886                         default: break;
887                 }
888
889                 /* file exists in filesystem */
890                 if (sametype) {
891                         if (mdsame && hashsame) {
892                                 /* warn, bug in logic.  This shouldn't occur,
893                                  * because if there is nothing to do, it
894                                  * shouldn't be listed as an update
895                                  */
896                                 /* could be an update.  We're checking against
897                                  * what's actually on disk, not what was
898                                  * expected to have been on disk.  So, if
899                                  * the admin has modified the file, or if
900                                  * it had been installed ignoring the user
901                                  * and group, it might be correct on disk
902                                  * but not as in the local database
903                                  */
904                                 /* TODO detect whether this a logic bug or
905                                  * an on-disk difference
906                                  */
907 #if 0
908                                 fprintf(stderr, "%s should not be an update\n", nitem.dest);
909                                 fprintf(stderr, "old hash: %s\n", nitem.ohash);
910                                 fprintf(stderr, "new hash: %s\n", nitem.hash);
911                                 fprintf(stderr, "old mds: %s\n", nitem.omds);
912                                 fprintf(stderr, "new mds: %s\n", nitem.mds);
913 #endif
914                                 /* do nothing */
915                                 return 0;
916                         }
917                         if (!mdsame && hashsame) {
918                                 /* fix md */
919                                 return set_md(conf, &nitem);
920                         }
921                         if (mdsame && !hashsame) {
922                                 /* install */
923                                 return install(conf, &nitem, 3);
924                         }
925                         if (!mdsame && !hashsame) {
926                                 /* install */
927                                 return install(conf, &nitem, 3);
928                         }
929                 }
930
931                 /* file exists, and is not the same type */
932
933                 if (isdir && !eisdir) {
934                         /* remove existing */
935                         /* mkdir */
936                         return install(conf, &nitem, 7);
937                 }
938                 if (!isdir && eisdir) {
939                         /* remove dir, or error */
940                         /* install */
941                         return install(conf, &nitem, 11);
942                 }
943                 if (!isdir && !isdir) {
944                         /* necessarily !sametype, sametype handled above */
945                         /* remove existing */
946                         /* install */
947                         return install(conf, &nitem, 7);
948                 }
949                 /* error, should not be possible, assert(0)? */
950                 fprintf(stderr,"impossible state: %s:%d\n", __func__, __LINE__);
951         }
952
953         if (installing) {
954                 if (!exist) {
955                         return install(conf, &nitem, 3);
956                 }
957
958                 /* file exists in filesystem */
959                 if (sametype) {
960                         if (mdsame && hashsame && (accept || overwrite)) {
961                                 /* do nothing */
962                                 if (conf->dryrun || conf->verbose) {
963                                         fprintf(stderr, "accepting existing file: %s\n", nitem.dest);
964                                 }
965                                 return 0;
966                         }
967                         if (mdsame && hashsame && !(accept || overwrite)) {
968                                 /* error */
969                                 return seterror(conf, "will not accept or overwrite existing file: %s", 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                                 if (nitem.ftype == 'l') {
980                                         char link[1024];
981                                         ssize_t lsize;
982                                         lsize = readlink(nitem.dest, link, sizeof link);
983                                         if (lsize == -1 || (size_t)lsize >= sizeof link) {
984                                                 return seterror(conf, "%s (linkdiff): expecting %s -> %s, unable to read link", accept ? "existing file not acceptable" : "file exists", nitem.dest, nitem.target, link);
985                                         } else {
986                                                 link[lsize] = 0;
987                                                 /* links must be different */
988                                                 return seterror(conf, "%s (linkdiff): expecting %s -> %s, have -> %s", accept ? "existing file not acceptable" : "file exists", nitem.dest, nitem.target, link);
989                                         }
990                                 } else {
991                                         return seterror(conf, "%s (hashdiff): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
992                                 }
993                         }
994                         if (!mdsame && hashsame && overwrite) {
995                                 /* fix md */
996                                 return set_md(conf, &nitem);
997                         }
998                         if (!mdsame && hashsame && !overwrite) {
999                                 /* accept doesn't matter, since it's
1000                                  * not an acceptable file */
1001                                 /* error */
1002                                 return seterror(conf, "%s (mddiff): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
1003                         }
1004                         if (!mdsame && !hashsame && overwrite) {
1005                                 /* install */
1006                                 return install(conf, &nitem, eisdir ? 11 : 7);
1007                         }
1008                         if (!mdsame && !hashsame && !overwrite) {
1009                                 /* accept doesn't matter, since it's
1010                                  * not an acceptable file */
1011                                 /* error */
1012                                 return seterror(conf, "%s (md+hash): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
1013                         }
1014                         /* TODO error, should be impossible */
1015                         return seterror(conf, "impossible state reached");
1016                 }
1017
1018                 /* file exists, and is not the same type */
1019                 if (!overwrite) {
1020                         /* error */
1021                                 return seterror(conf, "%s (difftype): %s", accept ? "existing file not acceptable" : "file exists", nitem.dest);
1022                 }
1023
1024                 /* not the same type, but ok to overwrite */
1025                 if (!eisdir) {
1026                         /* remove existing */
1027                         return install(conf, &nitem, 7);
1028                 }
1029
1030                 /* existing path is a directory */
1031                 if (isdir) {
1032                         /* fix md */
1033                         /* impossible, if isdir and eisdir, would
1034                          * be same type
1035                          * TODO
1036                          */
1037                         return set_md(conf, &nitem);
1038                 } else {
1039                         /* remove empty dir or error */
1040                         /* install */
1041                         return install(conf, &nitem, 11);
1042                 }
1043                 /* if we get here, we missed a case */
1044                 /* TODO error */
1045                 return seterror(conf, "impossible state 2 reached");
1046         }
1047
1048         /* TODO extra verbose print perms, mtime, etc, probably ls -l
1049          * format
1050          */ 
1051         if (conf->verbose) {
1052                 printf("%s\n", nitem.path);
1053         }
1054
1055         return 0;
1056 }
1057
1058 static void check_conflicts(struct config *conf, char *conflict_type,
1059                 int (callback)(void *, int, char **, char **)) {
1060         int rv;
1061         char *errmsg;
1062         sqlite3_str *s;
1063         char *sql;
1064
1065         s = sqlite3_str_new(conf->log->db);
1066         sqlite3_str_appendall(s, "select *, ");
1067         if (conf->rootdir) {
1068                 sqlite3_str_appendf(s, "printf('%%s/%%s',rtrim(%Q,'/'),ltrim(path,'/'))", conf->rootdir);
1069         } else {
1070                 sqlite3_str_appendf(s, "printf('/%%s', trim(path, '/'))");
1071         }
1072         sqlite3_str_appendall(s, " as dest from syncconflicts");
1073
1074         if (conflict_type) {
1075                 sqlite3_str_appendf(s," where conflict = %Q", conflict_type);
1076         }
1077         if (conf->reverse) {
1078                 sqlite3_str_appendall(s," order by length(path) desc, path desc,pkgid collate vercmp desc, conflict desc");
1079         } else {
1080                 sqlite3_str_appendall(s," order by length(path), path, pkgid collate vercmp, conflict");
1081
1082         }
1083
1084         sql = sqlite3_str_value(s);
1085
1086         rv = zpm_exec(conf->log, sql, callback, conf, &errmsg);
1087
1088         sqlite3_str_finish(s);
1089
1090         if (rv) {
1091                 fprintf(stderr, "exec fail: %s\n", sqlite3_errstr(rv));
1092                 if (errmsg) {
1093                         fprintf(stderr, "database error: %s\n", errmsg);
1094                         conf->errors++;
1095                 }
1096                 if (conf->log->error == 1) {
1097                         fprintf(stderr, "unable to allocate memory\n");
1098                 }
1099                 fprintf(stderr, "zpm_exec failure: %s\n",
1100                                 conf->log->errmsg ? conf->log->errmsg : "unknown");
1101                 conf->errors++;
1102         }
1103         if (conf->log->errmsg) {
1104                 fprintf(stderr, "error: %s\n", conf->log->errmsg);
1105         }
1106         if (conf->errors && conf->exitonerror) {
1107                 zpm_close(conf->log);
1108                 zpm_close(conf->src);
1109                 exit(EXIT_FAILURE);
1110         }
1111         /* TODO final report function in conf var */
1112 }
1113
1114 static void runstage(struct config *conf, char *stage,
1115                 int (callback)(void *, int, char **, char **)) {
1116         int rv;
1117         char *errmsg;
1118         sqlite3_str *s;
1119         char *sql;
1120
1121         s = sqlite3_str_new(conf->log->db);
1122         sqlite3_str_appendall(s, "select *, ");
1123         if (conf->rootdir) {
1124                 sqlite3_str_appendf(s, "printf('%%s/%%s',rtrim(%Q,'/'),ltrim(path,'/'))", conf->rootdir);
1125         } else {
1126                 sqlite3_str_appendf(s, "printf('/%%s', trim(path, '/'))");
1127         }
1128         sqlite3_str_appendall(s, " as dest from syncinfo");
1129
1130         if (stage) {
1131                 sqlite3_str_appendf(s," where op = %Q", stage);
1132         }
1133         if (conf->reverse) {
1134                 sqlite3_str_appendall(s," order by length(path) desc, path desc");
1135         }
1136
1137         sql = sqlite3_str_value(s);
1138
1139         rv = zpm_exec(conf->log, sql, callback, conf, &errmsg);
1140
1141         sqlite3_str_finish(s);
1142
1143         if (rv) {
1144                 fprintf(stderr, "exec fail: %s\n", sqlite3_errstr(rv));
1145                 if (errmsg) {
1146                         fprintf(stderr, "database error: %s\n", errmsg);
1147                         conf->errors++;
1148                 }
1149                 if (conf->log->error == 1) {
1150                         fprintf(stderr, "unable to allocate memory\n");
1151                 }
1152                 fprintf(stderr, "zpm_exec failure: %s\n",
1153                                 conf->log->errmsg ? conf->log->errmsg : "unknown");
1154                 conf->errors++;
1155         }
1156 #if 0
1157         if (conf->log->errmsg) {
1158                 fprintf(stderr, "error: %s\n", conf->log->errmsg);
1159         }
1160 #endif
1161         if (conf->errors && conf->exitonerror) {
1162                 zpm_close(conf->log);
1163                 zpm_close(conf->src);
1164                 exit(EXIT_FAILURE);
1165         }
1166         /* TODO final report function in conf var */
1167 }
1168
1169 int main(int ac, char **av){
1170         struct zpm localdb;
1171         struct zpm pkgdb;
1172         int opt;
1173         char *pkgdbfile = 0, *localdbfile = 0;
1174         char *s;
1175
1176         struct config conf;
1177
1178         conf.errabort = 1;
1179         conf.errors = 0;
1180         conf.conflicts = 0;
1181         conf.verbose = 0;
1182         conf.dryrun = 0;
1183         conf.setuser = 1;
1184         conf.setgroup = 1;
1185         conf.log = 0;
1186         conf.src = 0;
1187         conf.rootdir = 0;
1188         conf.reverse = 0;
1189         conf.overwrite = 0;
1190         conf.absorb = 0;
1191
1192         if (geteuid() != 0) {
1193                 conf.setuser = 0;
1194                 conf.setgroup = 0;
1195         }
1196
1197         localdbfile = ZPM_LOCAL_DB;
1198         if ((s = getenv("ZPMDB"))) {
1199                 /* TODO does this need to be copied ? */
1200                 localdbfile = s;
1201         }
1202
1203         if ((s = getenv("ZPM_ROOT_DIR"))) {
1204                 /* TODO does this need to be copied ? */
1205                 conf.rootdir = s;
1206         }
1207
1208         /*
1209          * -d localdb or ZPMDB * or /var/lib/zpm/zpm.db, or die
1210          * -f 'package database', otherwise regular default of env
1211          *  ZPM_PACKAGE_FILE, or use pkgdb if otherwise not found
1212          * -R root of pkg, will just chdir there
1213          *
1214          *  args are pkgid triple, but will do a pkg find on the pkgdb
1215          */
1216
1217         while ((opt = getopt(ac, av, "f:d:c:nCR:vOA")) != -1) {
1218                 switch (opt) {
1219                         case 'd': localdbfile = optarg; break;
1220                         case 'f': pkgdbfile = optarg; break;
1221                         case 'n': conf.dryrun = 1; break;
1222                         case 'v': conf.verbose++; break;
1223                         case 'C': conf.errabort = 0; break;
1224                         case 'R': conf.rootdir = optarg; break;
1225                         case 'N': conf.setuser = 0; conf.setgroup = 0; break;
1226                         case 'O': conf.overwrite = 1; break;
1227                         case 'A': conf.absorb = 1; break;
1228                         default:
1229                                   usage();
1230                                   exit(EXIT_FAILURE);
1231                                   break;
1232                 }
1233         }
1234
1235         /* verify root dir exists */
1236         if (conf.rootdir && !exists(conf.rootdir, NULL)) {
1237                 fprintf(stderr, "rootdir %s does not exist\n", conf.rootdir);
1238         }
1239
1240         if (!zpm_open(&localdb, localdbfile)) {
1241                 fprintf(stderr, "can't open zpm db %s\n", localdbfile);
1242                 exit(EXIT_FAILURE);
1243         }
1244         conf.log = &localdb;
1245
1246         if (pkgdbfile) {
1247                 if (!zpm_open(&pkgdb, pkgdbfile)) {
1248                         fprintf(stderr, "can't open src db %s\n", localdbfile);
1249                         exit(EXIT_FAILURE);
1250                 } else {
1251                         conf.src = &pkgdb;
1252                 }
1253         }
1254
1255         /* TODO find pkgid from arg */
1256
1257         /* TODO set conf var to finalize error reporting */
1258         if (conf.verbose) {
1259                 fprintf(stderr, "syncing filesystem %s (ldb %s) from %s\n",
1260                                 conf.rootdir ? conf.rootdir : "/",
1261                                 localdbfile, pkgdbfile);
1262         }
1263
1264         conf.errors = 0;
1265         conf.exitonerror = 0;
1266         check_conflicts(&conf, NULL, report_conflicts);
1267
1268         if (conf.conflicts) {
1269                 fprintf(stderr, "%d conflicts reported, aborting sync\n",
1270                                 conf.conflicts);
1271                 conf.errors++;
1272         } else {
1273                 /* no point in running it if we're just going to
1274                  * overwrite everything
1275                  */
1276                 if (!conf.overwrite && !conf.absorb && !conf.dryrun) {
1277                         runstage(&conf, "new", check_existing);
1278                 }
1279
1280                 if (conf.verbose) {
1281                         fprintf(stderr, "beginning %ssync\n", conf.dryrun ?
1282                                         "dryrun " : "");
1283                 }
1284                 /* have to do the removes first otherwise
1285                  * old files may conflict with update file
1286                  * type changes
1287                  */
1288                 if (!conf.errors) {
1289                         conf.exitonerror = conf.dryrun ? 0 : 1;
1290                         conf.errabort = conf.dryrun ? 0 : 1;
1291                         conf.reverse = 1;
1292                         if (conf.verbose) {
1293                                 fprintf(stderr, "removing old files\n");
1294                         }
1295                         runstage(&conf, "remove", remove_files);
1296                         conf.reverse = 0;
1297                         if (conf.verbose) {
1298                                 fprintf(stderr, "updating files\n");
1299                         }
1300                         runstage(&conf, "update", install_files);
1301                         if (conf.verbose) {
1302                                 fprintf(stderr, "installing files\n");
1303                         }
1304                         runstage(&conf, "new", install_files);
1305                 }
1306         }
1307
1308         zpm_close(&localdb);
1309         zpm_close(conf.src);
1310         return conf.errors ? 1 : 0;
1311 }