cc7d2043b752bfe492f61a7db2a6e2b85e45a1a2
[platform/upstream/libsolv.git] / examples / solv.c
1 /*
2  * Copyright (c) 2009, Novell Inc.
3  *
4  * This program is licensed under the BSD license, read LICENSE.BSD
5  * for further information
6  */
7
8 /* solv, a little software installer demoing the sat solver library */
9
10 /* things available in the library but missing from solv:
11  * - vendor policy loading
12  * - soft locks file handling
13  * - multi version handling
14  */
15
16 #define _GNU_SOURCE
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <dirent.h>
21 #include <fnmatch.h>
22 #include <unistd.h>
23 #include <zlib.h>
24 #include <fcntl.h>
25 #include <assert.h>
26 #include <sys/utsname.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <time.h>
30 #include <sys/time.h>
31
32 #include <sys/socket.h>
33 #include <netdb.h>
34 #include <poll.h>
35 #include <errno.h>
36
37 #include "pool.h"
38 #include "poolarch.h"
39 #include "repo.h"
40 #include "evr.h"
41 #include "policy.h"
42 #include "util.h"
43 #include "solver.h"
44 #include "solverdebug.h"
45 #include "chksum.h"
46 #include "repo_solv.h"
47
48 #include "repo_write.h"
49 #include "repo_rpmdb.h"
50 #include "repo_products.h"
51 #include "repo_rpmmd.h"
52 #include "repo_susetags.h"
53 #include "repo_repomdxml.h"
54 #include "repo_updateinfoxml.h"
55 #include "repo_deltainfoxml.h"
56 #include "repo_content.h"
57 #include "pool_fileconflicts.h"
58
59
60 #ifdef FEDORA
61 # define REPOINFO_PATH "/etc/yum.repos.d"
62 #else
63 # define REPOINFO_PATH "/etc/zypp/repos.d"
64 # define PRODUCTS_PATH "/etc/products.d"
65 # define SOFTLOCKS_PATH "/var/lib/zypp/SoftLocks"
66 #endif
67
68 #define SOLVCACHE_PATH "/var/cache/solv"
69
70 #define METADATA_EXPIRE (60 * 90)
71
72 struct repoinfo {
73   Repo *repo;
74
75   char *alias;
76   char *name;
77   int enabled;
78   int autorefresh;
79   char *baseurl;
80   char *metalink;
81   char *mirrorlist;
82   char *path;
83   int type;
84   int pkgs_gpgcheck;
85   int repo_gpgcheck;
86   int priority;
87   int keeppackages;
88   int metadata_expire;
89
90   unsigned char cookie[32];
91   unsigned char extcookie[32];
92 };
93
94 #ifdef FEDORA
95 char *
96 yum_substitute(Pool *pool, char *line)
97 {
98   char *p, *p2;
99
100   p = line;
101   while ((p2 = strchr(p, '$')) != 0)
102     {
103       if (!strncmp(p2, "$releasever", 11))
104         {
105           static char *releaseevr;
106           if (!releaseevr)
107             {
108               Queue q;
109         
110               queue_init(&q);
111               rpm_installedrpmdbids(0, "Providename", "redhat-release", &q);
112               if (q.count)
113                 {
114                   void *handle, *state = 0;
115                   char *p;
116                   handle = rpm_byrpmdbid(q.elements[0], 0, &state);
117                   releaseevr = rpm_query(handle, SOLVABLE_EVR);
118                   rpm_byrpmdbid(0, 0, &state);
119                   if ((p = strchr(releaseevr, '-')) != 0)
120                     *p = 0;
121                 }
122               queue_free(&q);
123               if (!releaseevr)
124                 releaseevr = strdup("?");
125             }
126           *p2 = 0;
127           p = pool_tmpjoin(pool, line, releaseevr, p2 + 11);
128           p2 = p + (p2 - line);
129           line = p;
130           p = p2 + strlen(releaseevr);
131           continue;
132         }
133       if (!strncmp(p2, "$basearch", 9))
134         {
135           static char *basearch;
136           if (!basearch)
137             {
138               struct utsname un;
139               if (uname(&un))
140                 {
141                   perror("uname");
142                   exit(1);
143                 }
144               basearch = strdup(un.machine);
145               if (basearch[0] == 'i' && basearch[1] && !strcmp(basearch + 2, "86"))
146                 basearch[1] = '3';
147             }
148           *p2 = 0;
149           p = pool_tmpjoin(pool, line, basearch, p2 + 9);
150           p2 = p + (p2 - line);
151           line = p;
152           p = p2 + strlen(basearch);
153           continue;
154         }
155       p = p2 + 1;
156     }
157   return line;
158 }
159 #endif
160
161 #define TYPE_UNKNOWN    0
162 #define TYPE_SUSETAGS   1
163 #define TYPE_RPMMD      2
164 #define TYPE_PLAINDIR   3
165
166 static int
167 read_repoinfos_sort(const void *ap, const void *bp)
168 {
169   const struct repoinfo *a = ap;
170   const struct repoinfo *b = bp;
171   return strcmp(a->alias, b->alias);
172 }
173
174 struct repoinfo *
175 read_repoinfos(Pool *pool, const char *reposdir, int *nrepoinfosp)
176 {
177   char buf[4096];
178   char buf2[4096], *kp, *vp, *kpe;
179   DIR *dir;
180   FILE *fp;
181   struct dirent *ent;
182   int l, rdlen;
183   struct repoinfo *repoinfos = 0, *cinfo;
184   int nrepoinfos = 0;
185
186   rdlen = strlen(reposdir);
187   dir = opendir(reposdir);
188   if (!dir)
189     {
190       *nrepoinfosp = 0;
191       return 0;
192     }
193   while ((ent = readdir(dir)) != 0)
194     {
195       l = strlen(ent->d_name);
196       if (l < 6 || rdlen + 2 + l >= sizeof(buf) || strcmp(ent->d_name + l - 5, ".repo") != 0)
197         continue;
198       snprintf(buf, sizeof(buf), "%s/%s", reposdir, ent->d_name);
199       if ((fp = fopen(buf, "r")) == 0)
200         {
201           perror(buf);
202           continue;
203         }
204       cinfo = 0;
205       while(fgets(buf2, sizeof(buf2), fp))
206         {
207           l = strlen(buf2);
208           if (l == 0)
209             continue;
210           while (l && (buf2[l - 1] == '\n' || buf2[l - 1] == ' ' || buf2[l - 1] == '\t'))
211             buf2[--l] = 0;
212           kp = buf2;
213           while (*kp == ' ' || *kp == '\t')
214             kp++;
215           if (!*kp || *kp == '#')
216             continue;
217 #ifdef FEDORA
218           if (strchr(kp, '$'))
219             kp = yum_substitute(pool, kp);
220 #endif
221           if (*kp == '[')
222             {
223               vp = strrchr(kp, ']');
224               if (!vp)
225                 continue;
226               *vp = 0;
227               repoinfos = sat_extend(repoinfos, nrepoinfos, 1, sizeof(*repoinfos), 15);
228               cinfo = repoinfos + nrepoinfos++;
229               memset(cinfo, 0, sizeof(*cinfo));
230               cinfo->alias = strdup(kp + 1);
231               cinfo->type = TYPE_RPMMD;
232               cinfo->autorefresh = 1;
233 #ifndef FEDORA
234               cinfo->repo_gpgcheck = 1;
235 #endif
236               cinfo->metadata_expire = METADATA_EXPIRE;
237               continue;
238             }
239           if (!cinfo)
240             continue;
241           vp = strchr(kp, '=');
242           if (!vp)
243             continue;
244           for (kpe = vp - 1; kpe >= kp; kpe--)
245             if (*kpe != ' ' && *kpe != '\t')
246               break;
247           if (kpe == kp)
248             continue;
249           vp++;
250           while (*vp == ' ' || *vp == '\t')
251             vp++;
252           kpe[1] = 0;
253           if (!strcmp(kp, "name"))
254             cinfo->name = strdup(vp);
255           else if (!strcmp(kp, "enabled"))
256             cinfo->enabled = *vp == '0' ? 0 : 1;
257           else if (!strcmp(kp, "autorefresh"))
258             cinfo->autorefresh = *vp == '0' ? 0 : 1;
259           else if (!strcmp(kp, "gpgcheck"))
260             cinfo->pkgs_gpgcheck = *vp == '0' ? 0 : 1;
261           else if (!strcmp(kp, "repo_gpgcheck"))
262             cinfo->repo_gpgcheck = *vp == '0' ? 0 : 1;
263           else if (!strcmp(kp, "baseurl"))
264             cinfo->baseurl = strdup(vp);
265           else if (!strcmp(kp, "mirrorlist"))
266             {
267               if (strstr(vp, "metalink"))
268                 cinfo->metalink = strdup(vp);
269               else
270                 cinfo->mirrorlist = strdup(vp);
271             }
272           else if (!strcmp(kp, "path"))
273             {
274               if (vp && strcmp(vp, "/") != 0)
275                 cinfo->path = strdup(vp);
276             }
277           else if (!strcmp(kp, "type"))
278             {
279               if (!strcmp(vp, "yast2"))
280                 cinfo->type = TYPE_SUSETAGS;
281               else if (!strcmp(vp, "rpm-md"))
282                 cinfo->type = TYPE_RPMMD;
283               else if (!strcmp(vp, "plaindir"))
284                 cinfo->type = TYPE_PLAINDIR;
285               else
286                 cinfo->type = TYPE_UNKNOWN;
287             }
288           else if (!strcmp(kp, "priority"))
289             cinfo->priority = atoi(vp);
290           else if (!strcmp(kp, "keeppackages"))
291             cinfo->keeppackages = *vp == '0' ? 0 : 1;
292         }
293       fclose(fp);
294       cinfo = 0;
295     }
296   closedir(dir);
297   qsort(repoinfos, nrepoinfos, sizeof(*repoinfos), read_repoinfos_sort);
298   *nrepoinfosp = nrepoinfos;
299   return repoinfos;
300 }
301
302 void
303 free_repoinfos(struct repoinfo *repoinfos, int nrepoinfos)
304 {
305   int i;
306   for (i = 0; i < nrepoinfos; i++)
307     {
308       struct repoinfo *cinfo = repoinfos + i;
309       sat_free(cinfo->name);
310       sat_free(cinfo->alias);
311       sat_free(cinfo->path);
312       sat_free(cinfo->metalink);
313       sat_free(cinfo->mirrorlist);
314       sat_free(cinfo->baseurl);
315     }
316   sat_free(repoinfos);
317 }
318
319 static inline int
320 opentmpfile()
321 {
322   char tmpl[100];
323   int fd;
324
325   strcpy(tmpl, "/var/tmp/solvXXXXXX");
326   fd = mkstemp(tmpl);
327   if (fd < 0)
328     {
329       perror("mkstemp");
330       exit(1);
331     }
332   unlink(tmpl);
333   return fd;
334 }
335
336 static int
337 verify_checksum(int fd, const char *file, const unsigned char *chksum, Id chksumtype)
338 {
339   char buf[1024];
340   unsigned char *sum;
341   void *h;
342   int l;
343
344   h = sat_chksum_create(chksumtype);
345   if (!h)
346     {
347       printf("%s: unknown checksum type\n", file);
348       return 0;
349     }
350   while ((l = read(fd, buf, sizeof(buf))) > 0)
351     sat_chksum_add(h, buf, l);
352   lseek(fd, 0, SEEK_SET);
353   l = 0;
354   sum = sat_chksum_get(h, &l);
355   if (memcmp(sum, chksum, l))
356     {
357       printf("%s: checksum mismatch\n", file);
358       return 0;
359     }
360   return 1;
361 }
362
363 void
364 findfastest(char **urls, int nurls)
365 {
366   int i, j, port;
367   int *socks, qc;
368   struct pollfd *fds;
369   char *p, *p2, *q;
370   char portstr[16];
371   struct addrinfo hints, *result;;
372
373   fds = sat_calloc(nurls, sizeof(*fds));
374   socks = sat_calloc(nurls, sizeof(*socks));
375   for (i = 0; i < nurls; i++)
376     {
377       socks[i] = -1;
378       p = strchr(urls[i], '/');
379       if (!p)
380         continue;
381       if (p[1] != '/')
382         continue;
383       p += 2;
384       q = strchr(p, '/');
385       qc = 0;
386       if (q)
387         {
388           qc = *q;
389           *q = 0;
390         }
391       if ((p2 = strchr(p, '@')) != 0)
392         p = p2 + 1;
393       port = 80;
394       if (!strncmp("https:", urls[i], 6))
395         port = 443;
396       else if (!strncmp("ftp:", urls[i], 4))
397         port = 21;
398       if ((p2 = strrchr(p, ':')) != 0)
399         {
400           port = atoi(p2 + 1);
401           if (q)
402             *q = qc;
403           q = p2;
404           qc = *q;
405           *q = 0;
406         }
407       sprintf(portstr, "%d", port);
408       memset(&hints, 0, sizeof(struct addrinfo));
409       hints.ai_family = AF_UNSPEC;
410       hints.ai_socktype = SOCK_STREAM;
411       hints.ai_flags = AI_NUMERICSERV;
412       result = 0;
413       if (!getaddrinfo(p, portstr, &hints, &result))
414         {
415           socks[i] = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
416           if (socks[i] >= 0)
417             {
418               fcntl(socks[i], F_SETFL, O_NONBLOCK);
419               if (connect(socks[i], result->ai_addr, result->ai_addrlen) == -1)
420                 {
421                   if (errno != EINPROGRESS)
422                     {
423                       close(socks[i]);
424                       socks[i] = -1;
425                     }
426                 }
427             }
428           freeaddrinfo(result);
429         }
430       if (q)
431         *q = qc;
432     }
433   for (;;)
434     {
435       for (i = j = 0; i < nurls; i++)
436         {
437           if (socks[i] < 0)
438             continue;
439           fds[j].fd = socks[i];
440           fds[j].events = POLLOUT;
441           j++;
442         }
443       if (j < 2)
444         {
445           i = j - 1;
446           break;
447         }
448       if (poll(fds, j, 10000) <= 0)
449         {
450           i = -1;       /* something is wrong */
451           break;
452         }
453       for (i = 0; i < j; i++)
454         if ((fds[i].revents & POLLOUT) != 0)
455           {
456             int soe = 0;
457             socklen_t soel = sizeof(int);
458             if (getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, &soe, &soel) == -1 || soe != 0)
459               {
460                 /* connect failed, kill socket */
461                 for (j = 0; j < nurls; j++)
462                   if (socks[j] == fds[i].fd)
463                     {
464                       close(socks[j]);
465                       socks[j] = -1;
466                     }
467                 i = j + 1;
468                 break;
469               }
470             break;      /* horray! */
471           }
472       if (i == j + 1)
473         continue;
474       if (i == j)
475         i = -1;         /* something is wrong, no bit was set */
476       break;
477     }
478   /* now i contains the fastest fd index */
479   if (i >= 0)
480     {
481       for (j = 0; j < nurls; j++)
482         if (socks[j] == fds[i].fd)
483           break;
484       if (j != 0)
485         {
486           char *url0 = urls[0];
487           urls[0] = urls[j];
488           urls[j] = url0;
489         }
490     }
491   for (i = j = 0; i < nurls; i++)
492     if (socks[i] >= 0)
493       close(socks[i]);
494   free(socks);
495   free(fds);
496 }
497
498 char *
499 findmetalinkurl(FILE *fp, unsigned char *chksump, Id *chksumtypep)
500 {
501   char buf[4096], *bp, *ep;
502   char **urls = 0;
503   int nurls = 0;
504   int i;
505
506   if (chksumtypep)
507     *chksumtypep = 0;
508   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
509     {
510       while (*bp == ' ' || *bp == '\t')
511         bp++;
512       if (chksumtypep && !*chksumtypep && !strncmp(bp, "<hash type=\"sha256\">", 20))
513         {
514           int i;
515
516           bp += 20;
517           memset(chksump, 0, 32);
518           for (i = 0; i < 64; i++)
519             {
520               int c = *bp++;
521               if (c >= '0' && c <= '9')
522                 chksump[i / 2] = chksump[i / 2] * 16 + (c - '0');
523               else if (c >= 'a' && c <= 'f')
524                 chksump[i / 2] = chksump[i / 2] * 16 + (c - ('a' - 10));
525               else if (c >= 'A' && c <= 'F')
526                 chksump[i / 2] = chksump[i / 2] * 16 + (c - ('A' - 10));
527               else
528                 break;
529             }
530           if (i == 64)
531             *chksumtypep = REPOKEY_TYPE_SHA256;
532           continue;
533         }
534       if (strncmp(bp, "<url", 4))
535         continue;
536       bp = strchr(bp, '>');
537       if (!bp)
538         continue;
539       bp++;
540       ep = strstr(bp, "repodata/repomd.xml</url>");
541       if (!ep)
542         continue;
543       *ep = 0;
544       if (strncmp(bp, "http", 4))
545         continue;
546       urls = sat_extend(urls, nurls, 1, sizeof(*urls), 15);
547       urls[nurls++] = strdup(bp);
548     }
549   if (nurls)
550     {
551       if (nurls > 1)
552         findfastest(urls, nurls > 5 ? 5 : nurls);
553       bp = urls[0];
554       urls[0] = 0;
555       for (i = 0; i < nurls; i++)
556         sat_free(urls[i]);
557       sat_free(urls);
558       ep = strchr(bp, '/');
559       if ((ep = strchr(ep + 2, '/')) != 0)
560         {
561           *ep = 0;
562           printf("[using mirror %s]\n", bp);
563           *ep = '/';
564         }
565       return bp;
566     }
567   return 0;
568 }
569
570 char *
571 findmirrorlisturl(FILE *fp)
572 {
573   char buf[4096], *bp, *ep;
574   int i, l;
575   char **urls = 0;
576   int nurls = 0;
577
578   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
579     {
580       while (*bp == ' ' || *bp == '\t')
581         bp++;
582       if (!*bp || *bp == '#')
583         continue;
584       l = strlen(bp);
585       while (l > 0 && (bp[l - 1] == ' ' || bp[l - 1] == '\t' || bp[l - 1] == '\n'))
586         bp[--l] = 0;
587       urls = sat_extend(urls, nurls, 1, sizeof(*urls), 15);
588       urls[nurls++] = strdup(bp);
589     }
590   if (nurls)
591     {
592       if (nurls > 1)
593         findfastest(urls, nurls > 5 ? 5 : nurls);
594       bp = urls[0];
595       urls[0] = 0;
596       for (i = 0; i < nurls; i++)
597         sat_free(urls[i]);
598       sat_free(urls);
599       ep = strchr(bp, '/');
600       if ((ep = strchr(ep + 2, '/')) != 0)
601         {
602           *ep = 0;
603           printf("[using mirror %s]\n", bp);
604           *ep = '/';
605         }
606       return bp;
607     }
608   return 0;
609 }
610
611 static ssize_t
612 cookie_gzread(void *cookie, char *buf, size_t nbytes)
613 {
614   return gzread((gzFile *)cookie, buf, nbytes);
615 }
616
617 static int
618 cookie_gzclose(void *cookie)
619 {
620   return gzclose((gzFile *)cookie);
621 }
622
623 FILE *
624 curlfopen(struct repoinfo *cinfo, const char *file, int uncompress, const unsigned char *chksum, Id chksumtype, int *badchecksump)
625 {
626   pid_t pid;
627   int fd, l;
628   int status;
629   char url[4096];
630   const char *baseurl = cinfo->baseurl;
631
632   if (!baseurl)
633     {
634       if (!cinfo->metalink && !cinfo->mirrorlist)
635         return 0;
636       if (file != cinfo->metalink && file != cinfo->mirrorlist)
637         {
638           FILE *fp = curlfopen(cinfo, cinfo->metalink ? cinfo->metalink : cinfo->mirrorlist, 0, 0, 0, 0);
639           unsigned char mlchksum[32];
640           Id mlchksumtype = 0;
641           if (!fp)
642             return 0;
643           if (cinfo->metalink)
644             cinfo->baseurl = findmetalinkurl(fp, mlchksum, &mlchksumtype);
645           else
646             cinfo->baseurl = findmirrorlisturl(fp);
647           fclose(fp);
648           if (!cinfo->baseurl)
649             return 0;
650           if (!chksumtype && mlchksumtype && !strcmp(file, "repodata/repomd.xml"))
651             {
652               chksumtype = mlchksumtype;
653               chksum = mlchksum;
654             }
655           return curlfopen(cinfo, file, uncompress, chksum, chksumtype, badchecksump);
656         }
657       snprintf(url, sizeof(url), "%s", file);
658     }
659   else
660     {
661       l = strlen(baseurl);
662       if (l && baseurl[l - 1] == '/')
663         snprintf(url, sizeof(url), "%s%s", baseurl, file);
664       else
665         snprintf(url, sizeof(url), "%s/%s", baseurl, file);
666     }
667   fd = opentmpfile();
668   // printf("url: %s\n", url);
669   if ((pid = fork()) == (pid_t)-1)
670     {
671       perror("fork");
672       exit(1);
673     }
674   if (pid == 0)
675     {
676       if (fd != 1)
677         {
678           dup2(fd, 1);
679           close(fd);
680         }
681       execlp("curl", "curl", "-f", "-s", "-L", url, (char *)0);
682       perror("curl");
683       _exit(0);
684     }
685   status = 0;
686   while (waitpid(pid, &status, 0) != pid)
687     ;
688   if (lseek(fd, 0, SEEK_END) == 0 && (!status || !chksumtype))
689     {
690       /* empty file */
691       close(fd);
692       return 0;
693     }
694   lseek(fd, 0, SEEK_SET);
695   if (status)
696     {
697       printf("%s: download error %d\n", file, status >> 8 ? status >> 8 : status);
698       if (badchecksump)
699         *badchecksump = 1;
700       close(fd);
701       return 0;
702     }
703   if (chksumtype && !verify_checksum(fd, file, chksum, chksumtype))
704     {
705       if (badchecksump)
706         *badchecksump = 1;
707       close(fd);
708       return 0;
709     }
710   if (uncompress)
711     {
712       char tmpl[100];
713       cookie_io_functions_t cio;
714       gzFile *gzf;
715
716       sprintf(tmpl, "/dev/fd/%d", fd);
717       gzf = gzopen(tmpl, "r");
718       close(fd);
719       if (!gzf)
720         {
721           fprintf(stderr, "could not open /dev/fd/%d, /proc not mounted?\n", fd);
722           exit(1);
723         }
724       memset(&cio, 0, sizeof(cio));
725       cio.read = cookie_gzread;
726       cio.close = cookie_gzclose;
727       return fopencookie(gzf, "r", cio);
728     }
729   fcntl(fd, F_SETFD, FD_CLOEXEC);
730   return fdopen(fd, "r");
731 }
732
733 static void
734 cleanupgpg(char *gpgdir)
735 {
736   char cmd[256];
737   snprintf(cmd, sizeof(cmd), "%s/pubring.gpg", gpgdir);
738   unlink(cmd);
739   snprintf(cmd, sizeof(cmd), "%s/pubring.gpg~", gpgdir);
740   unlink(cmd);
741   snprintf(cmd, sizeof(cmd), "%s/secring.gpg", gpgdir);
742   unlink(cmd);
743   snprintf(cmd, sizeof(cmd), "%s/trustdb.gpg", gpgdir);
744   unlink(cmd);
745   snprintf(cmd, sizeof(cmd), "%s/keys", gpgdir);
746   unlink(cmd);
747   rmdir(gpgdir);
748 }
749
750 int
751 checksig(Pool *sigpool, FILE *fp, FILE *sigfp)
752 {
753   char *gpgdir;
754   char *keysfile;
755   const char *pubkey;
756   char cmd[256];
757   FILE *kfp;
758   Solvable *s;
759   Id p;
760   off_t posfp, possigfp;
761   int r, nkeys;
762
763   gpgdir = mkdtemp(pool_tmpjoin(sigpool, "/var/tmp/solvgpg.XXXXXX", 0, 0));
764   if (!gpgdir)
765     return 0;
766   keysfile = pool_tmpjoin(sigpool, gpgdir, "/keys", 0);
767   if (!(kfp = fopen(keysfile, "w")) )
768     {
769       cleanupgpg(gpgdir);
770       return 0;
771     }
772   nkeys = 0;
773   for (p = 1, s = sigpool->solvables + p; p < sigpool->nsolvables; p++, s++)
774     {
775       if (!s->repo)
776         continue;
777       pubkey = solvable_lookup_str(s, SOLVABLE_DESCRIPTION);
778       if (!pubkey || !*pubkey)
779         continue;
780       if (fwrite(pubkey, strlen(pubkey), 1, kfp) != 1)
781         break;
782       if (fputc('\n', kfp) == EOF)      /* Just in case... */
783         break;
784       nkeys++;
785     }
786   if (fclose(kfp) || !nkeys)
787     {
788       cleanupgpg(gpgdir);
789       return 0;
790     }
791   snprintf(cmd, sizeof(cmd), "gpg2 -q --homedir %s --import %s", gpgdir, keysfile);
792   if (system(cmd))
793     {
794       fprintf(stderr, "key import error\n");
795       cleanupgpg(gpgdir);
796       return 0;
797     }
798   unlink(keysfile);
799   posfp = lseek(fileno(fp), 0, SEEK_CUR);
800   lseek(fileno(fp), 0, SEEK_SET);
801   possigfp = lseek(fileno(sigfp), 0, SEEK_CUR);
802   lseek(fileno(sigfp), 0, SEEK_SET);
803   snprintf(cmd, sizeof(cmd), "gpg -q --homedir %s --verify /dev/fd/%d /dev/fd/%d >/dev/null 2>&1", gpgdir, fileno(sigfp), fileno(fp));
804   fcntl(fileno(fp), F_SETFD, 0);        /* clear CLOEXEC */
805   fcntl(fileno(sigfp), F_SETFD, 0);     /* clear CLOEXEC */
806   r = system(cmd);
807   lseek(fileno(sigfp), possigfp, SEEK_SET);
808   lseek(fileno(fp), posfp, SEEK_SET);
809   fcntl(fileno(fp), F_SETFD, FD_CLOEXEC);
810   fcntl(fileno(sigfp), F_SETFD, FD_CLOEXEC);
811   cleanupgpg(gpgdir);
812   return r == 0 ? 1 : 0;
813 }
814
815 #define CHKSUM_IDENT "1.1"
816
817 void
818 calc_checksum_fp(FILE *fp, Id chktype, unsigned char *out)
819 {
820   char buf[4096];
821   void *h = sat_chksum_create(chktype);
822   int l;
823
824   sat_chksum_add(h, CHKSUM_IDENT, strlen(CHKSUM_IDENT));
825   while ((l = fread(buf, 1, sizeof(buf), fp)) > 0)
826     sat_chksum_add(h, buf, l);
827   rewind(fp);
828   sat_chksum_free(h, out);
829 }
830
831 void
832 calc_checksum_stat(struct stat *stb, Id chktype, unsigned char *out)
833 {
834   void *h = sat_chksum_create(chktype);
835   sat_chksum_add(h, CHKSUM_IDENT, strlen(CHKSUM_IDENT));
836   sat_chksum_add(h, &stb->st_dev, sizeof(stb->st_dev));
837   sat_chksum_add(h, &stb->st_ino, sizeof(stb->st_ino));
838   sat_chksum_add(h, &stb->st_size, sizeof(stb->st_size));
839   sat_chksum_add(h, &stb->st_mtime, sizeof(stb->st_mtime));
840   sat_chksum_free(h, out);
841 }
842
843 void
844 setarch(Pool *pool)
845 {
846   struct utsname un;
847   if (uname(&un))
848     {
849       perror("uname");
850       exit(1);
851     }
852   pool_setarch(pool, un.machine);
853 }
854
855 char *calccachepath(Repo *repo, const char *repoext)
856 {
857   char *q, *p = pool_tmpjoin(repo->pool, SOLVCACHE_PATH, "/", repo->name);
858   if (repoext)
859     {
860       p = pool_tmpjoin(repo->pool, p, "_", repoext);
861       p = pool_tmpjoin(repo->pool, p, ".solvx", 0);
862     }
863   else
864     p = pool_tmpjoin(repo->pool, p, ".solv", 0);
865   q = p + strlen(SOLVCACHE_PATH) + 1;
866   if (*q == '.')
867     *q = '_';
868   for (; *q; q++)
869     if (*q == '/')
870       *q = '_';
871   return p;
872 }
873
874 int
875 usecachedrepo(Repo *repo, const char *repoext, unsigned char *cookie, int mark)
876 {
877   FILE *fp;
878   unsigned char mycookie[32];
879   struct repoinfo *cinfo;
880   int flags;
881
882   cinfo = repo->appdata;
883   if (!(fp = fopen(calccachepath(repo, repoext), "r")))
884     return 0;
885   if (fseek(fp, -sizeof(mycookie), SEEK_END) || fread(mycookie, sizeof(mycookie), 1, fp) != 1)
886     {
887       fclose(fp);
888       return 0;
889     }
890   if (cookie && memcmp(cookie, mycookie, sizeof(mycookie)))
891     {
892       fclose(fp);
893       return 0;
894     }
895   rewind(fp);
896
897   flags = 0;
898   if (repoext)
899     flags = REPO_USE_LOADING|REPO_EXTEND_SOLVABLES;
900   if (repoext && strcmp(repoext, "DL") != 0)
901     flags |= REPO_LOCALPOOL;    /* no local pool for DL so that we can compare IDs */
902
903   if (repo_add_solv_flags(repo, fp, flags))
904     {
905       fclose(fp);
906       return 0;
907     }
908   if (cinfo && !repoext)
909     {
910       /* set the checksum so that we can use it with the stub loads */
911       struct stat stb;
912       if (!fstat(fileno(fp), &stb))
913         {
914           int i;
915
916           stb.st_mtime = 0;
917           calc_checksum_stat(&stb, REPOKEY_TYPE_SHA256, cinfo->extcookie);
918           for (i = 0; i < 32; i++)
919             cinfo->extcookie[i] ^= cinfo->cookie[i];
920         }
921     }
922   if (mark)
923     futimes(fileno(fp), 0);     /* try to set modification time */
924   fclose(fp);
925   return 1;
926 }
927
928 void
929 writecachedrepo(Repo *repo, Repodata *info, const char *repoext, unsigned char *cookie)
930 {
931   Id *addedfileprovides = 0;
932   FILE *fp;
933   int i, fd;
934   char *tmpl;
935   int myinfo = 0;
936   struct repoinfo *cinfo;
937   int onepiece;
938
939   cinfo = repo->appdata;
940   mkdir(SOLVCACHE_PATH, 0755);
941   tmpl = sat_dupjoin(SOLVCACHE_PATH, "/", ".newsolv-XXXXXX");
942   fd = mkstemp(tmpl);
943   if (fd < 0)
944     {
945       free(tmpl);
946       return;
947     }
948   fchmod(fd, 0444);
949   if (!(fp = fdopen(fd, "w")))
950     {
951       close(fd);
952       unlink(tmpl);
953       free(tmpl);
954       return;
955     }
956
957   onepiece = 1;
958   for (i = repo->start; i < repo->end; i++)
959    if (repo->pool->solvables[i].repo != repo)
960      break;
961   if (i < repo->end)
962     onepiece = 0;
963
964   if (!repoext)
965     {
966       if (!info)
967         {
968           info = repo_add_repodata(repo, 0);
969           myinfo = 1;
970         }
971       pool_addfileprovides_ids(repo->pool, 0, &addedfileprovides);
972       if (addedfileprovides && *addedfileprovides)
973         {
974           for (i = 0; addedfileprovides[i]; i++)
975             repodata_add_idarray(info, SOLVID_META, REPOSITORY_ADDEDFILEPROVIDES, addedfileprovides[i]);
976         }
977       sat_free(addedfileprovides);
978       repodata_internalize(info);
979       repo_write(repo, fp, repo_write_stdkeyfilter, 0, 0);
980     }
981   else
982     repodata_write(info, fp, repo_write_stdkeyfilter, 0);
983   if (myinfo)
984     repodata_free(info);
985   if (fwrite(cookie, 32, 1, fp) != 1)
986     {
987       fclose(fp);
988       unlink(tmpl);
989       free(tmpl);
990       return;
991     }
992   if (fclose(fp))
993     {
994       unlink(tmpl);
995       free(tmpl);
996       return;
997     }
998   if (!repoext && cinfo)
999     {
1000       /* set the checksum so that we can use it with the stub loads */
1001       struct stat stb;
1002       if (!stat(tmpl, &stb))
1003         {
1004           int i;
1005
1006           stb.st_mtime = 0;
1007           calc_checksum_stat(&stb, REPOKEY_TYPE_SHA256, cinfo->extcookie);
1008           for (i = 0; i < 32; i++)
1009             cinfo->extcookie[i] ^= cinfo->cookie[i];
1010         }
1011     }
1012   if (onepiece)
1013     {
1014       /* switch to just saved repo to activate paging and save memory */
1015       FILE *fp = fopen(tmpl, "r");
1016       if (fp)
1017         {
1018           if (!repoext)
1019             {
1020               /* main repo */
1021               repo_empty(repo, 1);
1022               if (repo_add_solv_flags(repo, fp, SOLV_ADD_NO_STUBS))
1023                 {
1024                   /* oops, no way to recover from here */
1025                   fprintf(stderr, "internal error\n");
1026                   exit(1);
1027                 }
1028             }
1029           else
1030             {
1031               /* make sure repodata contains complete repo */
1032               /* (this is how repodata_write saves it) */
1033               repodata_extend_block(info, repo->start, repo->end - repo->start);
1034               info->state = REPODATA_LOADING;
1035               /* no need for LOCALPOOL as pool already contains ids */
1036               repo_add_solv_flags(repo, fp, REPO_USE_LOADING|REPO_EXTEND_SOLVABLES);
1037               info->state = REPODATA_AVAILABLE; /* in case the load failed */
1038             }
1039           fclose(fp);
1040         }
1041     }
1042   if (!rename(tmpl, calccachepath(repo, repoext)))
1043     unlink(tmpl);
1044   free(tmpl);
1045 }
1046
1047
1048 static Pool *
1049 read_sigs()
1050 {
1051   Pool *sigpool = pool_create();
1052   Repo *repo = repo_create(sigpool, "rpmdbkeys");
1053   repo_add_rpmdb_pubkeys(repo, 0, 0);
1054   return sigpool;
1055 }
1056
1057
1058 /* repomd helpers */
1059
1060 static inline const char *
1061 repomd_find(Repo *repo, const char *what, const unsigned char **chksump, Id *chksumtypep)
1062 {
1063   Pool *pool = repo->pool;
1064   Dataiterator di;
1065   const char *filename;
1066
1067   filename = 0;
1068   *chksump = 0;
1069   *chksumtypep = 0;
1070   dataiterator_init(&di, pool, repo, SOLVID_META, REPOSITORY_REPOMD_TYPE, what, SEARCH_STRING);
1071   dataiterator_prepend_keyname(&di, REPOSITORY_REPOMD);
1072   if (dataiterator_step(&di))
1073     {
1074       dataiterator_setpos_parent(&di);
1075       filename = pool_lookup_str(pool, SOLVID_POS, REPOSITORY_REPOMD_LOCATION);
1076       *chksump = pool_lookup_bin_checksum(pool, SOLVID_POS, REPOSITORY_REPOMD_CHECKSUM, chksumtypep);
1077     }
1078   dataiterator_free(&di);
1079   if (filename && !*chksumtypep)
1080     {
1081       printf("no %s file checksum!\n", what);
1082       filename = 0;
1083     }
1084   return filename;
1085 }
1086
1087 int
1088 repomd_add_ext(Repo *repo, Repodata *data, const char *what)
1089 {
1090   Pool *pool = repo->pool;
1091   Dataiterator di;
1092   Id chksumtype, handle;
1093   const unsigned char *chksum;
1094   const char *filename;
1095
1096   dataiterator_init(&di, pool, repo, SOLVID_META, REPOSITORY_REPOMD_TYPE, what, SEARCH_STRING);
1097   dataiterator_prepend_keyname(&di, REPOSITORY_REPOMD);
1098   if (!dataiterator_step(&di))
1099     {
1100       dataiterator_free(&di);
1101       return 0;
1102     }
1103   if (!strcmp(what, "prestodelta"))
1104     what = "deltainfo";
1105   dataiterator_setpos_parent(&di);
1106   filename = pool_lookup_str(pool, SOLVID_POS, REPOSITORY_REPOMD_LOCATION);
1107   chksum = pool_lookup_bin_checksum(pool, SOLVID_POS, REPOSITORY_REPOMD_CHECKSUM, &chksumtype);
1108   if (!filename || !chksum)
1109     {
1110       dataiterator_free(&di);
1111       return 0;
1112     }
1113   handle = repodata_new_handle(data);
1114   repodata_set_poolstr(data, handle, REPOSITORY_REPOMD_TYPE, what);
1115   repodata_set_str(data, handle, REPOSITORY_REPOMD_LOCATION, filename);
1116   if (chksumtype)
1117     repodata_set_bin_checksum(data, handle, REPOSITORY_REPOMD_CHECKSUM, chksumtype, chksum);
1118   if (!strcmp(what, "deltainfo"))
1119     {
1120       repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOSITORY_DELTAINFO);
1121       repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_FLEXARRAY);
1122     }
1123   if (!strcmp(what, "filelists"))
1124     {
1125       repodata_add_idarray(data, handle, REPOSITORY_KEYS, SOLVABLE_FILELIST);
1126       repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_DIRSTRARRAY);
1127     }
1128   dataiterator_free(&di);
1129   repodata_add_flexarray(data, SOLVID_META, REPOSITORY_EXTERNAL, handle);
1130   return 1;
1131 }
1132
1133
1134 /* susetags helpers */
1135
1136 static inline const char *
1137 susetags_find(Repo *repo, const char *what, const unsigned char **chksump, Id *chksumtypep)
1138 {
1139   Pool *pool = repo->pool;
1140   Dataiterator di;
1141   const char *filename;
1142
1143   filename = 0;
1144   *chksump = 0;
1145   *chksumtypep = 0;
1146   dataiterator_init(&di, pool, repo, SOLVID_META, SUSETAGS_FILE_NAME, what, SEARCH_STRING);
1147   dataiterator_prepend_keyname(&di, SUSETAGS_FILE);
1148   if (dataiterator_step(&di))
1149     {
1150       dataiterator_setpos_parent(&di);
1151       *chksump = pool_lookup_bin_checksum(pool, SOLVID_POS, SUSETAGS_FILE_CHECKSUM, chksumtypep);
1152       filename = what;
1153     }
1154   dataiterator_free(&di);
1155   if (filename && !*chksumtypep)
1156     {
1157       printf("no %s file checksum!\n", what);
1158       filename = 0;
1159     }
1160   return filename;
1161 }
1162
1163 static Id susetags_langtags[] = {
1164   SOLVABLE_SUMMARY, REPOKEY_TYPE_STR,
1165   SOLVABLE_DESCRIPTION, REPOKEY_TYPE_STR,
1166   SOLVABLE_EULA, REPOKEY_TYPE_STR,
1167   SOLVABLE_MESSAGEINS, REPOKEY_TYPE_STR,
1168   SOLVABLE_MESSAGEDEL, REPOKEY_TYPE_STR,
1169   SOLVABLE_CATEGORY, REPOKEY_TYPE_ID,
1170   0, 0
1171 };
1172
1173 void
1174 susetags_add_ext(Repo *repo, Repodata *data)
1175 {
1176   Pool *pool = repo->pool;
1177   Dataiterator di;
1178   char ext[3];
1179   Id handle, filechksumtype;
1180   const unsigned char *filechksum;
1181   int i;
1182
1183   dataiterator_init(&di, pool, repo, SOLVID_META, SUSETAGS_FILE_NAME, 0, 0);
1184   dataiterator_prepend_keyname(&di, SUSETAGS_FILE);
1185   while (dataiterator_step(&di))
1186     {
1187       if (strncmp(di.kv.str, "packages.", 9) != 0)
1188         continue;
1189       if (!di.kv.str[9] || !di.kv.str[10] || (di.kv.str[11] && di.kv.str[11] != '.'))
1190         continue;
1191       ext[0] = di.kv.str[9];
1192       ext[1] = di.kv.str[10];
1193       ext[2] = 0;
1194       if (!susetags_find(repo, di.kv.str, &filechksum, &filechksumtype))
1195         continue;
1196       handle = repodata_new_handle(data);
1197       repodata_set_str(data, handle, SUSETAGS_FILE_NAME, di.kv.str);
1198       if (filechksumtype)
1199         repodata_set_bin_checksum(data, handle, SUSETAGS_FILE_CHECKSUM, filechksumtype, filechksum);
1200       if (!strcmp(ext, "DU"))
1201         {
1202           repodata_add_idarray(data, handle, REPOSITORY_KEYS, SOLVABLE_DISKUSAGE);
1203           repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_DIRNUMNUMARRAY);
1204         }
1205       if (!strcmp(ext, "FL"))
1206         {
1207           repodata_add_idarray(data, handle, REPOSITORY_KEYS, SOLVABLE_FILELIST);
1208           repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_DIRSTRARRAY);
1209         }
1210       else
1211         {
1212           for (i = 0; susetags_langtags[i]; i += 2)
1213             {
1214               repodata_add_idarray(data, handle, REPOSITORY_KEYS, pool_id2langid(pool, susetags_langtags[i], ext, 1));
1215               repodata_add_idarray(data, handle, REPOSITORY_KEYS, susetags_langtags[i + 1]);
1216             }
1217         }
1218       repodata_add_flexarray(data, SOLVID_META, REPOSITORY_EXTERNAL, handle);
1219     }
1220   dataiterator_free(&di);
1221 }
1222
1223
1224 static inline int
1225 iscompressed(const char *name)
1226 {
1227   int l = strlen(name);
1228   return l > 3 && !strcmp(name + l - 3, ".gz") ? 1 : 0;
1229 }
1230
1231
1232 /* load callback */
1233
1234 int
1235 load_stub(Pool *pool, Repodata *data, void *dp)
1236 {
1237   const char *filename, *descrdir, *repomdtype;
1238   const unsigned char *filechksum;
1239   Id filechksumtype;
1240   struct repoinfo *cinfo;
1241   FILE *fp;
1242   Id defvendor;
1243   char ext[3];
1244
1245   cinfo = data->repo->appdata;
1246
1247   filename = repodata_lookup_str(data, SOLVID_META, SUSETAGS_FILE_NAME);
1248   if (filename)
1249     {
1250       /* susetags load */
1251       ext[0] = filename[9];
1252       ext[1] = filename[10];
1253       ext[2] = 0;
1254 #if 1
1255       printf("[%s:%s", data->repo->name, ext);
1256 #endif
1257       if (usecachedrepo(data->repo, ext, cinfo->extcookie, 0))
1258         {
1259           printf(" cached]\n"); fflush(stdout);
1260           return 1;
1261         }
1262 #if 1
1263       printf(" loading]\n"); fflush(stdout);
1264 #endif
1265       defvendor = repo_lookup_id(data->repo, SOLVID_META, SUSETAGS_DEFAULTVENDOR);
1266       descrdir = repo_lookup_str(data->repo, SOLVID_META, SUSETAGS_DESCRDIR);
1267       if (!descrdir)
1268         descrdir = "suse/setup/descr";
1269       filechksumtype = 0;
1270       filechksum = repodata_lookup_bin_checksum(data, SOLVID_META, SUSETAGS_FILE_CHECKSUM, &filechksumtype);
1271       if ((fp = curlfopen(cinfo, pool_tmpjoin(pool, descrdir, "/", filename), iscompressed(filename), filechksum, filechksumtype, 0)) == 0)
1272         return 0;
1273       repo_add_susetags(data->repo, fp, defvendor, ext, REPO_USE_LOADING|REPO_EXTEND_SOLVABLES);
1274       fclose(fp);
1275       writecachedrepo(data->repo, data, ext, cinfo->extcookie);
1276       return 1;
1277     }
1278
1279   repomdtype = repodata_lookup_str(data, SOLVID_META, REPOSITORY_REPOMD_TYPE);
1280   if (repomdtype)
1281     {
1282       if (!strcmp(repomdtype, "filelists"))
1283         strcpy(ext, "FL");
1284       else if (!strcmp(repomdtype, "deltainfo"))
1285         strcpy(ext, "DL");
1286       else
1287         return 0;
1288 #if 1
1289       printf("[%s:%s", data->repo->name, ext);
1290 #endif
1291       if (usecachedrepo(data->repo, ext, cinfo->extcookie, 0))
1292         {
1293           printf(" cached]\n");fflush(stdout);
1294           return 1;
1295         }
1296       printf(" loading]\n"); fflush(stdout);
1297       filename = repodata_lookup_str(data, SOLVID_META, REPOSITORY_REPOMD_LOCATION);
1298       filechksumtype = 0;
1299       filechksum = repodata_lookup_bin_checksum(data, SOLVID_META, REPOSITORY_REPOMD_CHECKSUM, &filechksumtype);
1300       if ((fp = curlfopen(cinfo, filename, iscompressed(filename), filechksum, filechksumtype, 0)) == 0)
1301         return 0;
1302       if (!strcmp(ext, "FL"))
1303         repo_add_rpmmd(data->repo, fp, ext, REPO_USE_LOADING|REPO_EXTEND_SOLVABLES);
1304       else if (!strcmp(ext, "DL"))
1305         repo_add_deltainfoxml(data->repo, fp, REPO_USE_LOADING);
1306       fclose(fp);
1307       writecachedrepo(data->repo, data, ext, cinfo->extcookie);
1308       return 1;
1309     }
1310
1311   return 0;
1312 }
1313
1314 void
1315 read_repos(Pool *pool, struct repoinfo *repoinfos, int nrepoinfos)
1316 {
1317   Repo *repo;
1318   struct repoinfo *cinfo;
1319   int i;
1320   FILE *fp;
1321   FILE *sigfp;
1322   const char *filename;
1323   const unsigned char *filechksum;
1324   Id filechksumtype;
1325   const char *descrdir;
1326   int defvendor;
1327   struct stat stb;
1328   unsigned char cookie[32];
1329   Pool *sigpool = 0;
1330   Repodata *data;
1331   int badchecksum;
1332   int dorefresh;
1333
1334   repo = repo_create(pool, "@System");
1335   printf("rpm database:");
1336   if (stat("/var/lib/rpm/Packages", &stb))
1337     memset(&stb, 0, sizeof(&stb));
1338   calc_checksum_stat(&stb, REPOKEY_TYPE_SHA256, cookie);
1339   if (usecachedrepo(repo, 0, cookie, 0))
1340     printf(" cached\n");
1341   else
1342     {
1343       FILE *ofp;
1344       printf(" reading\n");
1345       int done = 0;
1346
1347 #ifdef PRODUCTS_PATH
1348       repo_add_products(repo, PRODUCTS_PATH, 0, REPO_NO_INTERNALIZE);
1349 #endif
1350       if ((ofp = fopen(calccachepath(repo, 0), "r")) != 0)
1351         {
1352           Repo *ref = repo_create(pool, "@System.old");
1353           if (!repo_add_solv(ref, ofp))
1354             {
1355               repo_add_rpmdb(repo, ref, 0, REPO_REUSE_REPODATA);
1356               done = 1;
1357             }
1358           fclose(ofp);
1359           repo_free(ref, 1);
1360         }
1361       if (!done)
1362         repo_add_rpmdb(repo, 0, 0, REPO_REUSE_REPODATA);
1363       writecachedrepo(repo, 0, 0, cookie);
1364     }
1365   pool_set_installed(pool, repo);
1366
1367   for (i = 0; i < nrepoinfos; i++)
1368     {
1369       cinfo = repoinfos + i;
1370       if (!cinfo->enabled)
1371         continue;
1372
1373       repo = repo_create(pool, cinfo->alias);
1374       cinfo->repo = repo;
1375       repo->appdata = cinfo;
1376       repo->priority = 99 - cinfo->priority;
1377
1378       dorefresh = cinfo->autorefresh;
1379       if (dorefresh && cinfo->metadata_expire && stat(calccachepath(repo, 0), &stb) == 0)
1380         {
1381           if (cinfo->metadata_expire == -1 || time(0) - stb.st_mtime < cinfo->metadata_expire)
1382             dorefresh = 0;
1383         }
1384       if (!dorefresh && usecachedrepo(repo, 0, 0, 0))
1385         {
1386           printf("repo '%s':", cinfo->alias);
1387           printf(" cached\n");
1388           continue;
1389         }
1390       badchecksum = 0;
1391       switch (cinfo->type)
1392         {
1393         case TYPE_RPMMD:
1394           printf("rpmmd repo '%s':", cinfo->alias);
1395           fflush(stdout);
1396           if ((fp = curlfopen(cinfo, "repodata/repomd.xml", 0, 0, 0, 0)) == 0)
1397             {
1398               printf(" no repomd.xml file, skipped\n");
1399               repo_free(repo, 1);
1400               cinfo->repo = 0;
1401               break;
1402             }
1403           calc_checksum_fp(fp, REPOKEY_TYPE_SHA256, cinfo->cookie);
1404           if (usecachedrepo(repo, 0, cinfo->cookie, 1))
1405             {
1406               printf(" cached\n");
1407               fclose(fp);
1408               break;
1409             }
1410           if (cinfo->repo_gpgcheck)
1411             {
1412               sigfp = curlfopen(cinfo, "repodata/repomd.xml.asc", 0, 0, 0, 0);
1413               if (!sigfp)
1414                 {
1415                   printf(" unsigned, skipped\n");
1416                   fclose(fp);
1417                   break;
1418                 }
1419               if (!sigpool)
1420                 sigpool = read_sigs();
1421               if (!checksig(sigpool, fp, sigfp))
1422                 {
1423                   printf(" checksig failed, skipped\n");
1424                   fclose(sigfp);
1425                   fclose(fp);
1426                   break;
1427                 }
1428               fclose(sigfp);
1429             }
1430           repo_add_repomdxml(repo, fp, 0);
1431           fclose(fp);
1432           printf(" reading\n");
1433           filename = repomd_find(repo, "primary", &filechksum, &filechksumtype);
1434           if (filename && (fp = curlfopen(cinfo, filename, iscompressed(filename), filechksum, filechksumtype, &badchecksum)) != 0)
1435             {
1436               repo_add_rpmmd(repo, fp, 0, 0);
1437               fclose(fp);
1438             }
1439           if (badchecksum)
1440             break;      /* hopeless */
1441
1442           filename = repomd_find(repo, "updateinfo", &filechksum, &filechksumtype);
1443           if (filename && (fp = curlfopen(cinfo, filename, iscompressed(filename), filechksum, filechksumtype, &badchecksum)) != 0)
1444             {
1445               repo_add_updateinfoxml(repo, fp, 0);
1446               fclose(fp);
1447             }
1448
1449           data = repo_add_repodata(repo, 0);
1450           if (!repomd_add_ext(repo, data, "deltainfo"))
1451             repomd_add_ext(repo, data, "prestodelta");
1452           repomd_add_ext(repo, data, "filelists");
1453           repodata_internalize(data);
1454           if (!badchecksum)
1455             writecachedrepo(repo, data, 0, cinfo->cookie);
1456           repodata_create_stubs(repo_last_repodata(repo));
1457           break;
1458
1459         case TYPE_SUSETAGS:
1460           printf("susetags repo '%s':", cinfo->alias);
1461           fflush(stdout);
1462           descrdir = 0;
1463           defvendor = 0;
1464           if ((fp = curlfopen(cinfo, "content", 0, 0, 0, 0)) == 0)
1465             {
1466               printf(" no content file, skipped\n");
1467               repo_free(repo, 1);
1468               cinfo->repo = 0;
1469               break;
1470             }
1471           calc_checksum_fp(fp, REPOKEY_TYPE_SHA256, cinfo->cookie);
1472           if (usecachedrepo(repo, 0, cinfo->cookie, 1))
1473             {
1474               printf(" cached\n");
1475               fclose(fp);
1476               break;
1477             }
1478           if (cinfo->repo_gpgcheck)
1479             {
1480               sigfp = curlfopen(cinfo, "content.asc", 0, 0, 0, 0);
1481               if (!sigfp)
1482                 {
1483                   printf(" unsigned, skipped\n");
1484                   fclose(fp);
1485                   break;
1486                 }
1487               if (sigfp)
1488                 {
1489                   if (!sigpool)
1490                     sigpool = read_sigs();
1491                   if (!checksig(sigpool, fp, sigfp))
1492                     {
1493                       printf(" checksig failed, skipped\n");
1494                       fclose(sigfp);
1495                       fclose(fp);
1496                       break;
1497                     }
1498                   fclose(sigfp);
1499                 }
1500             }
1501           repo_add_content(repo, fp, 0);
1502           fclose(fp);
1503           defvendor = repo_lookup_id(repo, SOLVID_META, SUSETAGS_DEFAULTVENDOR);
1504           descrdir = repo_lookup_str(repo, SOLVID_META, SUSETAGS_DESCRDIR);
1505           if (!descrdir)
1506             descrdir = "suse/setup/descr";
1507           filename = susetags_find(repo, "packages.gz", &filechksum, &filechksumtype);
1508           if (!filename)
1509             filename = susetags_find(repo, "packages", &filechksum, &filechksumtype);
1510           if (!filename)
1511             {
1512               printf(" no packages file entry, skipped\n");
1513               break;
1514             }
1515           printf(" reading\n");
1516           if ((fp = curlfopen(cinfo, pool_tmpjoin(pool, descrdir, "/", filename), iscompressed(filename), filechksum, filechksumtype, &badchecksum)) == 0)
1517             break;      /* hopeless */
1518           repo_add_susetags(repo, fp, defvendor, 0, 0);
1519           fclose(fp);
1520           data = repo_add_repodata(repo, 0);
1521           susetags_add_ext(repo, data);
1522           repodata_internalize(data);
1523           if (!badchecksum)
1524             writecachedrepo(repo, data, 0, cinfo->cookie);
1525           repodata_create_stubs(repo_last_repodata(repo));
1526           break;
1527         default:
1528           printf("unsupported repo '%s': skipped\n", cinfo->alias);
1529           repo_free(repo, 1);
1530           cinfo->repo = 0;
1531           break;
1532         }
1533     }
1534   if (sigpool)
1535     pool_free(sigpool);
1536 }
1537
1538
1539 int
1540 str2archid(Pool *pool, char *arch)
1541 {
1542   Id id;
1543   if (!*arch)
1544     return 0;
1545   id = str2id(pool, arch, 0);
1546   if (id == ARCH_SRC || id == ARCH_NOSRC || id == ARCH_NOARCH)
1547     return id;
1548   if (pool->id2arch && (id > pool->lastarch || !pool->id2arch[id]))
1549     return 0;
1550   return id;
1551 }
1552
1553 int
1554 depglob(Pool *pool, char *name, Queue *job)
1555 {
1556   Id p, pp;
1557   Id id = str2id(pool, name, 0);
1558   int i, match = 0;
1559
1560   if (id)
1561     {
1562       FOR_PROVIDES(p, pp, id)
1563         {
1564           Solvable *s = pool->solvables + p;
1565           match = 1;
1566           if (s->name == id)
1567             {
1568               queue_push2(job, SOLVER_SOLVABLE_NAME, id);
1569               return 1;
1570             }
1571         }
1572       if (match)
1573         {
1574           printf("[using capability match for '%s']\n", name);
1575           queue_push2(job, SOLVER_SOLVABLE_PROVIDES, id);
1576           return 1;
1577         }
1578     }
1579
1580   if (strpbrk(name, "[*?") == 0)
1581     return 0;
1582
1583   /* looks like a name glob. hard work. */
1584   for (p = 1; p < pool->nsolvables; p++)
1585     {
1586       Solvable *s = pool->solvables + p;
1587       if (!s->repo || !pool_installable(pool, s))
1588         continue;
1589       id = s->name;
1590       if (fnmatch(name, id2str(pool, id), 0) == 0)
1591         {
1592           for (i = 0; i < job->count; i += 2)
1593             if (job->elements[i] == SOLVER_SOLVABLE_NAME && job->elements[i + 1] == id)
1594               break;
1595           if (i == job->count)
1596             queue_push2(job, SOLVER_SOLVABLE_NAME, id);
1597           match = 1;
1598         }
1599     }
1600   if (match)
1601     return 1;
1602   /* looks like a dep glob. really hard work. */
1603   for (id = 1; id < pool->ss.nstrings; id++)
1604     {
1605       if (!pool->whatprovides[id])
1606         continue;
1607       if (fnmatch(name, id2str(pool, id), 0) == 0)
1608         {
1609           if (!match)
1610             printf("[using capability match for '%s']\n", name);
1611           for (i = 0; i < job->count; i += 2)
1612             if (job->elements[i] == SOLVER_SOLVABLE_PROVIDES && job->elements[i + 1] == id)
1613               break;
1614           if (i == job->count)
1615             queue_push2(job, SOLVER_SOLVABLE_PROVIDES, id);
1616           match = 1;
1617         }
1618     }
1619   if (match)
1620     return 1;
1621   return 0;
1622 }
1623
1624 void
1625 addrelation(Pool *pool, Queue *job, int flags, Id evr)
1626 {
1627   int i;
1628   for (i = 0; i < job->count; i += 2)
1629     {
1630       if (job->elements[i] != SOLVER_SOLVABLE_NAME && job->elements[i] != SOLVER_SOLVABLE_PROVIDES)
1631         continue;
1632       job->elements[i + 1] = rel2id(pool, job->elements[i + 1], evr, flags, 1);
1633     }
1634 }
1635
1636 int
1637 limitevr(Pool *pool, char *evr, Queue *job, Id archid)
1638 {
1639   Queue mq;
1640   Id p, pp, evrid;
1641   int matched = 0;
1642   int i, j;
1643   Solvable *s;
1644
1645   queue_init(&mq);
1646   for (i = 0; i < job->count; i += 2)
1647     {
1648       queue_empty(&mq);
1649       FOR_JOB_SELECT(p, pp, job->elements[i], job->elements[i + 1])
1650         {
1651           s = pool_id2solvable(pool, p);
1652           if (archid && s->arch != archid)
1653             continue;
1654           if (evrcmp_str(pool, id2str(pool, s->evr), evr, EVRCMP_MATCH) == 0)
1655              queue_push(&mq, p);
1656         }
1657       if (mq.count)
1658         {
1659           if (!matched && i)
1660             {
1661               queue_deleten(job, 0, i);
1662               i = 0;
1663             }
1664           matched = 1;
1665           /* if all solvables have the same evr */
1666           s = pool_id2solvable(pool, mq.elements[0]);
1667           evrid = s->evr;
1668           for (j = 0; j < mq.count; j++)
1669             {
1670               s = pool_id2solvable(pool, mq.elements[j]);
1671               if (s->evr != evrid)
1672                 break;
1673             }
1674           if (j == mq.count && j > 1)
1675             {
1676               prune_to_best_arch(pool, &mq);
1677               // prune_to_highest_prio(pool, &mq);
1678               mq.count = 1;
1679             }
1680           if (mq.count > 1)
1681             {
1682               job->elements[i] = SOLVER_SOLVABLE_ONE_OF;
1683               job->elements[i + 1] = pool_queuetowhatprovides(pool, &mq);
1684             }
1685           else
1686             {
1687               job->elements[i] = SOLVER_SOLVABLE;
1688               job->elements[i + 1] = mq.elements[0];
1689             }
1690         }
1691       else if (matched)
1692         {
1693           queue_deleten(job, i, 2);
1694           i -= 2;
1695         }
1696     }
1697   queue_free(&mq);
1698   if (matched)
1699     return 1;
1700   if (!archid)
1701     {
1702       char *r;
1703       if ((r = strrchr(evr, '.')) != 0 && r[1] && (archid = str2archid(pool, r + 1)) != 0)
1704         {
1705           *r = 0;
1706           if (limitevr(pool, evr, job, archid))
1707             {
1708               *r = '.';
1709               return 1;
1710             }
1711           *r = '.';
1712         }
1713     }
1714   return 0;
1715 }
1716
1717 void
1718 mkselect(Pool *pool, int mode, char *name, Queue *job)
1719 {
1720   char *r, *r2;
1721   Id archid;
1722
1723   if (*name == '/')
1724     {
1725       Dataiterator di;
1726       Queue q;
1727       int match = 0;
1728
1729       queue_init(&q);
1730       dataiterator_init(&di, pool, mode == SOLVER_ERASE ? pool->installed : 0, 0, SOLVABLE_FILELIST, name, SEARCH_STRING|SEARCH_FILES|SEARCH_COMPLETE_FILELIST);
1731       while (dataiterator_step(&di))
1732         {
1733           Solvable *s = pool->solvables + di.solvid;
1734           if (!s->repo || !pool_installable(pool, s))
1735             continue;
1736           queue_push(&q, di.solvid);
1737           dataiterator_skip_solvable(&di);
1738         }
1739       dataiterator_free(&di);
1740       if (q.count)
1741         {
1742           printf("[using file list match for '%s']\n", name);
1743           match = 1;
1744           if (q.count > 1)
1745             queue_push2(job, SOLVER_SOLVABLE_ONE_OF, pool_queuetowhatprovides(pool, &q));
1746           else
1747             queue_push2(job, SOLVER_SOLVABLE, q.elements[0]);
1748         }
1749       queue_free(&q);
1750       if (match)
1751         return;
1752     }
1753   if ((r = strpbrk(name, "<=>")) != 0)
1754     {
1755       /* relation case, support:
1756        * depglob rel
1757        * depglob.rpm rel
1758        */
1759       int rflags = 0;
1760       int nend = r - name;
1761       for (; *r; r++)
1762         {
1763           if (*r == '<')
1764             rflags |= REL_LT;
1765           else if (*r == '=')
1766             rflags |= REL_EQ;
1767           else if (*r == '>')
1768             rflags |= REL_GT;
1769           else
1770             break;
1771         }
1772       while (*r && *r == ' ' && *r == '\t')
1773         r++;
1774       while (nend && (name[nend - 1] == ' ' || name[nend -1 ] == '\t'))
1775         nend--;
1776       name[nend] = 0;
1777       if (!*name || !*r)
1778         {
1779           fprintf(stderr, "bad relation\n");
1780           exit(1);
1781         }
1782       if (depglob(pool, name, job))
1783         {
1784           addrelation(pool, job, rflags, str2id(pool, r, 1));
1785           return;
1786         }
1787       if ((r2 = strrchr(name, '.')) != 0 && r2[1] && (archid = str2archid(pool, r2 + 1)) != 0)
1788         {
1789           *r2 = 0;
1790           if (depglob(pool, name, job))
1791             {
1792               *r2 = '.';
1793               addrelation(pool, job, REL_ARCH, archid);
1794               addrelation(pool, job, rflags, str2id(pool, r, 1));
1795               return;
1796             }
1797           *r2 = '.';
1798         }
1799     }
1800   else
1801     {
1802       /* no relation case, support:
1803        * depglob
1804        * depglob.arch
1805        * depglob-version-release
1806        * depglob-version-release.arch
1807        */
1808       if (depglob(pool, name, job))
1809         return;
1810       archid = 0;
1811       if ((r = strrchr(name, '.')) != 0 && r[1] && (archid = str2archid(pool, r + 1)) != 0)
1812         {
1813           *r = 0;
1814           if (depglob(pool, name, job))
1815             {
1816               *r = '.';
1817               addrelation(pool, job, REL_ARCH, archid);
1818               return;
1819             }
1820           *r = '.';
1821         }
1822       if ((r = strrchr(name, '-')) != 0)
1823         {
1824           *r = 0;
1825           if (depglob(pool, name, job))
1826             {
1827               /* have just the version */
1828               *r = '-';
1829               if (limitevr(pool, r + 1, job, 0))
1830                 return;
1831             }
1832           if ((r2 = strrchr(name, '-')) != 0)
1833             {
1834               *r = '-';
1835               *r2 = 0;
1836               if (depglob(pool, name, job))
1837                 {
1838                   *r2 = '-';
1839                   if (limitevr(pool, r2 + 1, job, 0))
1840                     return;
1841                 }
1842               *r2 = '-';
1843             }
1844           *r = '-';
1845         }
1846     }
1847   fprintf(stderr, "nothing matches '%s'\n", name);
1848   exit(1);
1849 }
1850
1851
1852 int
1853 yesno(const char *str)
1854 {
1855   char inbuf[128], *ip;
1856
1857   for (;;)
1858     {
1859       printf("%s", str);
1860       fflush(stdout);
1861       *inbuf = 0;
1862       if (!(ip = fgets(inbuf, sizeof(inbuf), stdin)))
1863         {
1864           printf("Abort.\n");
1865           exit(1);
1866         }
1867       while (*ip == ' ' || *ip == '\t')
1868         ip++;
1869       if (*ip == 'q')
1870         {
1871           printf("Abort.\n");
1872           exit(1);
1873         }
1874       if (*ip == 'y' || *ip == 'n')
1875         return *ip == 'y' ? 1 : 0;
1876     }
1877 }
1878
1879 struct fcstate {
1880   FILE **newpkgsfps;
1881   Queue *checkq;
1882   int newpkgscnt;
1883   void *rpmdbstate;
1884 };
1885
1886 static void *
1887 fileconflict_cb(Pool *pool, Id p, void *cbdata)
1888 {
1889   struct fcstate *fcstate = cbdata;
1890   Solvable *s;
1891   Id rpmdbid;
1892   int i;
1893   FILE *fp;
1894
1895   if (!p)
1896     {
1897       rpm_byrpmdbid(0, 0, &fcstate->rpmdbstate);
1898       return 0;
1899     }
1900   s = pool_id2solvable(pool, p);
1901   if (pool->installed && s->repo == pool->installed)
1902     {
1903       if (!s->repo->rpmdbid)
1904         return 0;
1905       rpmdbid = s->repo->rpmdbid[p - s->repo->start];
1906       if (!rpmdbid)
1907         return 0;
1908        return rpm_byrpmdbid(rpmdbid, 0, &fcstate->rpmdbstate);
1909     }
1910   for (i = 0; i < fcstate->newpkgscnt; i++)
1911     if (fcstate->checkq->elements[i] == p)
1912       break;
1913   if (i == fcstate->newpkgscnt)
1914     return 0;
1915   fp = fcstate->newpkgsfps[i];
1916   if (!fp)
1917     return 0;
1918   rewind(fp);
1919   return rpm_byfp(fp, solvable2str(pool, s), &fcstate->rpmdbstate);
1920 }
1921
1922 void
1923 runrpm(const char *arg, const char *name, int dupfd3)
1924 {
1925   pid_t pid;
1926   int status;
1927
1928   if ((pid = fork()) == (pid_t)-1)
1929     {
1930       perror("fork");
1931       exit(1);
1932     }
1933   if (pid == 0)
1934     {
1935       if (dupfd3 != -1 && dupfd3 != 3)
1936         {
1937           dup2(dupfd3, 3);
1938           close(dupfd3);
1939         }
1940       if (dupfd3 != -1)
1941         fcntl(3, F_SETFD, 0);   /* clear CLOEXEC */
1942       if (strcmp(arg, "-e") == 0)
1943         execlp("rpm", "rpm", arg, "--nodeps", "--nodigest", "--nosignature", name, (char *)0);
1944       else
1945         execlp("rpm", "rpm", arg, "--force", "--nodeps", "--nodigest", "--nosignature", name, (char *)0);
1946       perror("rpm");
1947       _exit(0);
1948     }
1949   while (waitpid(pid, &status, 0) != pid)
1950     ;
1951   if (status)
1952     {
1953       printf("rpm failed\n");
1954       exit(1);
1955     }
1956 }
1957
1958 static Id
1959 nscallback(Pool *pool, void *data, Id name, Id evr)
1960 {
1961   if (name == NAMESPACE_PRODUCTBUDDY)
1962     {    
1963       /* SUSE specific hack: each product has an associated rpm */
1964       Solvable *s = pool->solvables + evr; 
1965       Id p, pp, cap; 
1966       
1967       cap = str2id(pool, pool_tmpjoin(pool, "product(", id2str(pool, s->name) + 8, ")"), 0);
1968       if (!cap)
1969         return 0;
1970       cap = rel2id(pool, cap, s->evr, REL_EQ, 0);
1971       if (!cap)
1972         return 0;
1973       FOR_PROVIDES(p, pp, cap) 
1974         {
1975           Solvable *ps = pool->solvables + p; 
1976           if (ps->repo == s->repo && ps->arch == s->arch)
1977             break;
1978         }
1979       return p;
1980     }
1981   return 0;
1982 }
1983
1984 #ifdef SOFTLOCKS_PATH
1985
1986 void
1987 addsoftlocks(Pool *pool, Queue *job)
1988 {
1989   FILE *fp;
1990   Id type, id, p, pp;
1991   char *bp, *ep, buf[4096];
1992
1993   if ((fp = fopen(SOFTLOCKS_PATH, "r")) == 0)
1994     return;
1995   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
1996     {
1997       while (*bp == ' ' || *bp == '\t')
1998         bp++;
1999       if (!*bp || *bp == '#')
2000         continue;
2001       for (ep = bp; *ep; ep++)
2002         if (*ep == ' ' || *ep == '\t' || *ep == '\n')
2003           break;
2004       *ep = 0;
2005       type = SOLVER_SOLVABLE_NAME;
2006       if (!strncmp(bp, "provides:", 9) && bp[9])
2007         {
2008           type = SOLVER_SOLVABLE_PROVIDES;
2009           bp += 9;
2010         }
2011       id = str2id(pool, bp, 1);
2012       if (pool->installed)
2013         {
2014           FOR_JOB_SELECT(p, pp, type, id)
2015             if (pool->solvables[p].repo == pool->installed)
2016               break;
2017           if (p)
2018             continue;   /* ignore, as it is already installed */
2019         }
2020       queue_push2(job, SOLVER_LOCK|SOLVER_WEAK|type, id);
2021     }
2022   fclose(fp);
2023 }
2024
2025 #endif
2026
2027 #define MODE_LIST        0
2028 #define MODE_INSTALL     1
2029 #define MODE_ERASE       2
2030 #define MODE_UPDATE      3
2031 #define MODE_DISTUPGRADE 4
2032 #define MODE_VERIFY      5
2033 #define MODE_PATCH       6
2034 #define MODE_INFO        7
2035 #define MODE_REPOLIST    8
2036 #define MODE_SEARCH      9
2037
2038 void
2039 usage(int r)
2040 {
2041   fprintf(stderr, "Usage: solv COMMAND <select>\n");
2042   fprintf(stderr, "\n");
2043   fprintf(stderr, "    distupgrade: replace installed packages with\n");
2044   fprintf(stderr, "                 versions from the repositories\n");
2045   fprintf(stderr, "    erase:       erase installed packages\n");
2046   fprintf(stderr, "    info:        display package information\n");
2047   fprintf(stderr, "    install:     install packages\n");
2048   fprintf(stderr, "    list:        list packages\n");
2049   fprintf(stderr, "    repos:       list enabled repositories\n");
2050   fprintf(stderr, "    search:      search name/summary/description\n");
2051   fprintf(stderr, "    update:      update installed packages\n");
2052   fprintf(stderr, "    verify:      check dependencies of installed packages\n");
2053   fprintf(stderr, "\n");
2054   exit(r);
2055 }
2056
2057 int
2058 main(int argc, char **argv)
2059 {
2060   Pool *pool;
2061   Repo *commandlinerepo = 0;
2062   Id *commandlinepkgs = 0;
2063   Id p, pp;
2064   struct repoinfo *repoinfos;
2065   int nrepoinfos = 0;
2066   int mainmode = 0, mode = 0;
2067   int i, newpkgs;
2068   Queue job, checkq;
2069   Solver *solv = 0;
2070   Transaction *trans;
2071   char inbuf[128], *ip;
2072   int allpkgs = 0;
2073   FILE **newpkgsfps;
2074   struct fcstate fcstate;
2075
2076   argc--;
2077   argv++;
2078   if (!argv[0])
2079     usage(1);
2080   if (!strcmp(argv[0], "install") || !strcmp(argv[0], "in"))
2081     {
2082       mainmode = MODE_INSTALL;
2083       mode = SOLVER_INSTALL;
2084     }
2085   else if (!strcmp(argv[0], "patch"))
2086     {
2087       mainmode = MODE_PATCH;
2088       mode = SOLVER_INSTALL;
2089     }
2090   else if (!strcmp(argv[0], "erase") || !strcmp(argv[0], "rm"))
2091     {
2092       mainmode = MODE_ERASE;
2093       mode = SOLVER_ERASE;
2094     }
2095   else if (!strcmp(argv[0], "list"))
2096     {
2097       mainmode = MODE_LIST;
2098       mode = 0;
2099     }
2100   else if (!strcmp(argv[0], "info"))
2101     {
2102       mainmode = MODE_INFO;
2103       mode = 0;
2104     }
2105   else if (!strcmp(argv[0], "search"))
2106     {
2107       mainmode = MODE_SEARCH;
2108       mode = 0;
2109     }
2110   else if (!strcmp(argv[0], "verify"))
2111     {
2112       mainmode = MODE_VERIFY;
2113       mode = SOLVER_VERIFY;
2114     }
2115   else if (!strcmp(argv[0], "update") || !strcmp(argv[0], "up"))
2116     {
2117       mainmode = MODE_UPDATE;
2118       mode = SOLVER_UPDATE;
2119     }
2120   else if (!strcmp(argv[0], "dist-upgrade") || !strcmp(argv[0], "dup"))
2121     {
2122       mainmode = MODE_DISTUPGRADE;
2123       mode = SOLVER_UPDATE;
2124     }
2125   else if (!strcmp(argv[0], "repos") || !strcmp(argv[0], "repolist") || !strcmp(argv[0], "lr"))
2126     {
2127       mainmode = MODE_REPOLIST;
2128       mode = 0;
2129     }
2130   else
2131     usage(1);
2132
2133   pool = pool_create();
2134 #ifdef FEDORA
2135   pool->obsoleteusescolors = 1;
2136 #endif
2137   pool_setloadcallback(pool, load_stub, 0);
2138   pool->nscallback = nscallback;
2139   // pool_setdebuglevel(pool, 2);
2140   setarch(pool);
2141   repoinfos = read_repoinfos(pool, REPOINFO_PATH, &nrepoinfos);
2142
2143   if (mainmode == MODE_REPOLIST)
2144     {
2145       int j = 1;
2146       for (i = 0; i < nrepoinfos; i++)
2147         {
2148           struct repoinfo *cinfo = repoinfos + i;
2149           if (!cinfo->enabled)
2150             continue;
2151           printf("%d: %-20s %s\n", j++, cinfo->alias, cinfo->name);
2152         }
2153       exit(0);
2154     }
2155
2156   read_repos(pool, repoinfos, nrepoinfos);
2157
2158   if (mainmode == MODE_SEARCH)
2159     {
2160       Dataiterator di;
2161       Map m;
2162       if (argc != 2)
2163         usage(1);
2164       map_init(&m, pool->nsolvables);
2165       dataiterator_init(&di, pool, 0, 0, 0, argv[1], SEARCH_SUBSTRING|SEARCH_NOCASE);
2166       dataiterator_set_keyname(&di, SOLVABLE_NAME);
2167       dataiterator_set_search(&di, 0, 0);
2168       while (dataiterator_step(&di))
2169         MAPSET(&m, di.solvid);
2170       dataiterator_set_keyname(&di, SOLVABLE_SUMMARY);
2171       dataiterator_set_search(&di, 0, 0);
2172       while (dataiterator_step(&di))
2173         MAPSET(&m, di.solvid);
2174       dataiterator_set_keyname(&di, SOLVABLE_DESCRIPTION);
2175       dataiterator_set_search(&di, 0, 0);
2176       while (dataiterator_step(&di))
2177         MAPSET(&m, di.solvid);
2178       dataiterator_free(&di);
2179
2180       for (p = 1; p < pool->nsolvables; p++)
2181         {
2182           Solvable *s = pool_id2solvable(pool, p);
2183           if (!MAPTST(&m, p))
2184             continue;
2185           printf("  - %s: %s\n", solvable2str(pool, s), solvable_lookup_str(s, SOLVABLE_SUMMARY));
2186         }
2187       map_free(&m);
2188       exit(0);
2189     }
2190
2191
2192   if (mainmode == MODE_LIST || mainmode == MODE_INSTALL)
2193     {
2194       for (i = 1; i < argc; i++)
2195         {
2196           int l;
2197           l = strlen(argv[i]);
2198           if (l <= 4 || strcmp(argv[i] + l - 4, ".rpm"))
2199             continue;
2200           if (access(argv[i], R_OK))
2201             {
2202               perror(argv[i]);
2203               exit(1);
2204             }
2205           if (!commandlinepkgs)
2206             commandlinepkgs = sat_calloc(argc, sizeof(Id));
2207           if (!commandlinerepo)
2208             commandlinerepo = repo_create(pool, "@commandline");
2209           repo_add_rpms(commandlinerepo, (const char **)argv + i, 1, REPO_REUSE_REPODATA|REPO_NO_INTERNALIZE);
2210           commandlinepkgs[i] = commandlinerepo->end - 1;
2211         }
2212       if (commandlinerepo)
2213         repo_internalize(commandlinerepo);
2214     }
2215
2216   // FOR_REPOS(i, repo)
2217   //   printf("%s: %d solvables\n", repo->name, repo->nsolvables);
2218   pool_addfileprovides(pool);
2219   pool_createwhatprovides(pool);
2220
2221   queue_init(&job);
2222   for (i = 1; i < argc; i++)
2223     {
2224       Queue job2;
2225       int j;
2226
2227       if (commandlinepkgs && commandlinepkgs[i])
2228         {
2229           queue_push2(&job, SOLVER_SOLVABLE, commandlinepkgs[i]);
2230           continue;
2231         }
2232       queue_init(&job2);
2233       mkselect(pool, mode, argv[i], &job2);
2234       for (j = 0; j < job2.count; j++)
2235         queue_push(&job, job2.elements[j]);
2236       queue_free(&job2);
2237     }
2238
2239   if (!job.count && mainmode != MODE_UPDATE && mainmode != MODE_DISTUPGRADE && mainmode != MODE_VERIFY && mainmode != MODE_PATCH)
2240     {
2241       printf("no package matched\n");
2242       exit(1);
2243     }
2244
2245   if (!job.count)
2246     allpkgs = 1;
2247
2248   if (mainmode == MODE_LIST || mainmode == MODE_INFO)
2249     {
2250       /* list mode, no solver needed */
2251       for (i = 0; i < job.count; i += 2)
2252         {
2253           FOR_JOB_SELECT(p, pp, job.elements[i], job.elements[i + 1])
2254             {
2255               Solvable *s = pool_id2solvable(pool, p);
2256               if (mainmode == MODE_INFO)
2257                 {
2258                   printf("Name:        %s\n", solvable2str(pool, s));
2259                   printf("Repo:        %s\n", s->repo->name);
2260                   printf("Summary:     %s\n", solvable_lookup_str(s, SOLVABLE_SUMMARY));
2261                   printf("Url:         %s\n", solvable_lookup_str(s, SOLVABLE_URL));
2262                   printf("License:     %s\n", solvable_lookup_str(s, SOLVABLE_LICENSE));
2263                   printf("Description:\n%s\n", solvable_lookup_str(s, SOLVABLE_DESCRIPTION));
2264                   printf("\n");
2265                 }
2266               else
2267                 {
2268                   const char *sum = solvable_lookup_str_lang(s, SOLVABLE_SUMMARY, "de");
2269                   printf("  - %s [%s]\n", solvable2str(pool, s), s->repo->name);
2270                   if (sum)
2271                     printf("    %s\n", sum);
2272                 }
2273             }
2274         }
2275       queue_free(&job);
2276       pool_free(pool);
2277       free_repoinfos(repoinfos, nrepoinfos);
2278       sat_free(commandlinepkgs);
2279       exit(0);
2280     }
2281
2282   if (mainmode == MODE_PATCH)
2283     {
2284       int pruneyou = 0;
2285       Map installedmap;
2286       Solvable *s;
2287
2288       map_init(&installedmap, pool->nsolvables);
2289       if (pool->installed)
2290         FOR_REPO_SOLVABLES(pool->installed, p, s)
2291           MAPSET(&installedmap, p);
2292
2293       /* install all patches */
2294       for (p = 1; p < pool->nsolvables; p++)
2295         {
2296           const char *type;
2297           int r;
2298           Id p2;
2299
2300           s = pool->solvables + p;
2301           if (strncmp(id2str(pool, s->name), "patch:", 6) != 0)
2302             continue;
2303           FOR_PROVIDES(p2, pp, s->name)
2304             {
2305               Solvable *s2 = pool->solvables + p2;
2306               if (s2->name != s->name)
2307                 continue;
2308               r = evrcmp(pool, s->evr, s2->evr, EVRCMP_COMPARE);
2309               if (r < 0 || (r == 0 && p > p2))
2310                 break;
2311             }
2312           if (p2)
2313             continue;
2314           type = solvable_lookup_str(s, SOLVABLE_PATCHCATEGORY);
2315           if (type && !strcmp(type, "optional"))
2316             continue;
2317           r = solvable_trivial_installable_map(s, &installedmap, 0);
2318           if (r == -1)
2319             continue;
2320           if (solvable_lookup_bool(s, UPDATE_RESTART) && r == 0)
2321             {
2322               if (!pruneyou++)
2323                 queue_empty(&job);
2324             }
2325           else if (pruneyou)
2326             continue;
2327           queue_push2(&job, SOLVER_SOLVABLE, p);
2328         }
2329       map_free(&installedmap);
2330     }
2331
2332   // add mode
2333   for (i = 0; i < job.count; i += 2)
2334     {
2335       if (mode == SOLVER_UPDATE)
2336         {
2337           /* make update of not installed packages an install */
2338           FOR_JOB_SELECT(p, pp, job.elements[i], job.elements[i + 1])
2339             if (pool->installed && pool->solvables[p].repo == pool->installed)
2340               break;
2341           if (!p)
2342             {
2343               job.elements[i] |= SOLVER_INSTALL;
2344               continue;
2345             }
2346         }
2347       job.elements[i] |= mode;
2348     }
2349
2350   // multiversion test
2351   // queue_push2(&job, SOLVER_NOOBSOLETES|SOLVER_SOLVABLE_NAME, str2id(pool, "kernel-pae", 1));
2352   // queue_push2(&job, SOLVER_NOOBSOLETES|SOLVER_SOLVABLE_NAME, str2id(pool, "kernel-pae-base", 1));
2353   // queue_push2(&job, SOLVER_NOOBSOLETES|SOLVER_SOLVABLE_NAME, str2id(pool, "kernel-pae-extra", 1));
2354
2355 #ifdef SOFTLOCKS_PATH
2356   addsoftlocks(pool, &job);
2357 #endif
2358
2359 rerunsolver:
2360   for (;;)
2361     {
2362       Id problem, solution;
2363       int pcnt, scnt;
2364
2365       solv = solver_create(pool);
2366       solv->ignorealreadyrecommended = 1;
2367       solv->updatesystem = allpkgs && (mainmode == MODE_UPDATE || mainmode == MODE_DISTUPGRADE);
2368       solv->dosplitprovides = solv->updatesystem;
2369       solv->fixsystem = allpkgs && (mainmode == MODE_VERIFY);
2370       if (mainmode == MODE_DISTUPGRADE)
2371         {
2372           solv->distupgrade = 1;
2373           solv->allowdowngrade = 1;
2374           solv->allowarchchange = 1;
2375           solv->allowvendorchange = 1;
2376         }
2377       if (mainmode == MODE_ERASE)
2378         solv->allowuninstall = 1;       /* don't nag */
2379
2380       // queue_push2(&job, SOLVER_DISTUPGRADE, 3);
2381       solver_solve(solv, &job);
2382       if (!solv->problems.count)
2383         break;
2384       pcnt = solver_problem_count(solv);
2385       printf("Found %d problems:\n", pcnt);
2386       for (problem = 1; problem <= pcnt; problem++)
2387         {
2388           int take = 0;
2389           printf("Problem %d:\n", problem);
2390           solver_printprobleminfo(solv, problem);
2391           printf("\n");
2392           scnt = solver_solution_count(solv, problem);
2393           for (solution = 1; solution <= scnt; solution++)
2394             {
2395               printf("Solution %d:\n", solution);
2396               solver_printsolution(solv, problem, solution);
2397               printf("\n");
2398             }
2399           for (;;)
2400             {
2401               printf("Please choose a solution: ");
2402               fflush(stdout);
2403               *inbuf = 0;
2404               if (!(ip = fgets(inbuf, sizeof(inbuf), stdin)))
2405                 {
2406                   printf("Abort.\n");
2407                   exit(1);
2408                 }
2409               while (*ip == ' ' || *ip == '\t')
2410                 ip++;
2411               if (*ip >= '0' && *ip <= '9')
2412                 {
2413                   take = atoi(ip);
2414                   if (take >= 1 && take <= scnt)
2415                     break;
2416                 }
2417               if (*ip == 's')
2418                 {
2419                   take = 0;
2420                   break;
2421                 }
2422               if (*ip == 'q')
2423                 {
2424                   printf("Abort.\n");
2425                   exit(1);
2426                 }
2427             }
2428           if (!take)
2429             continue;
2430           solver_take_solution(solv, problem, take, &job);
2431         }
2432       solver_free(solv);
2433       solv = 0;
2434     }
2435
2436   trans = &solv->trans;
2437   if (!trans->steps.count)
2438     {
2439       printf("Nothing to do.\n");
2440       exit(1);
2441     }
2442   printf("\n");
2443   printf("Transaction summary:\n\n");
2444   solver_printtransaction(solv);
2445
2446 #ifndef FEDORA
2447   if (1)
2448     {
2449       DUChanges duc[4];
2450       int i;
2451
2452       duc[0].path = "/";
2453       duc[1].path = "/usr/share/man";
2454       duc[2].path = "/sbin";
2455       duc[3].path = "/etc";
2456       transaction_calc_duchanges(trans, duc, 4);
2457       for (i = 0; i < 4; i++)
2458         printf("duchanges %s: %d K  %d inodes\n", duc[i].path, duc[i].kbytes, duc[i].files);
2459     }
2460 #endif
2461   printf("install size change: %d K\n", transaction_calc_installsizechange(trans));
2462   printf("\n");
2463
2464   if (!yesno("OK to continue (y/n)? "))
2465     {
2466       printf("Abort.\n");
2467       exit(1);
2468     }
2469
2470   queue_init(&checkq);
2471   newpkgs = transaction_installedresult(trans, &checkq);
2472   newpkgsfps = 0;
2473
2474   if (newpkgs)
2475     {
2476       int downloadsize = 0;
2477       for (i = 0; i < newpkgs; i++)
2478         {
2479           Solvable *s;
2480
2481           p = checkq.elements[i];
2482           s = pool_id2solvable(pool, p);
2483           downloadsize += solvable_lookup_num(s, SOLVABLE_DOWNLOADSIZE, 0);
2484         }
2485       printf("Downloading %d packages, %d K\n", newpkgs, downloadsize);
2486       newpkgsfps = sat_calloc(newpkgs, sizeof(*newpkgsfps));
2487       for (i = 0; i < newpkgs; i++)
2488         {
2489           unsigned int medianr;
2490           char *loc;
2491           Solvable *s;
2492           struct repoinfo *cinfo;
2493           const unsigned char *chksum;
2494           Id chksumtype;
2495           Dataiterator di;
2496
2497           p = checkq.elements[i];
2498           s = pool_id2solvable(pool, p);
2499           if (s->repo == commandlinerepo)
2500             {
2501               loc = solvable_get_location(s, &medianr);
2502               if (!(newpkgsfps[i] = fopen(loc, "r")))
2503                 {
2504                   perror(loc);
2505                   exit(1);
2506                 }
2507               putchar('.');
2508               continue;
2509             }
2510           cinfo = s->repo->appdata;
2511           if (!cinfo)
2512             {
2513               printf("%s: no repository information\n", s->repo->name);
2514               exit(1);
2515             }
2516           loc = solvable_get_location(s, &medianr);
2517           if (!loc)
2518              continue;
2519
2520           if (pool->installed && pool->installed->nsolvables)
2521             {
2522               /* try a delta first */
2523               char *matchname = strdup(id2str(pool, s->name));
2524               dataiterator_init(&di, pool, s->repo, SOLVID_META, DELTA_PACKAGE_NAME, matchname, SEARCH_STRING);
2525               dataiterator_prepend_keyname(&di, REPOSITORY_DELTAINFO);
2526               while (dataiterator_step(&di))
2527                 {
2528                   Id baseevr, op;
2529
2530                   dataiterator_setpos_parent(&di);
2531                   if (pool_lookup_id(pool, SOLVID_POS, DELTA_PACKAGE_EVR) != s->evr ||
2532                       pool_lookup_id(pool, SOLVID_POS, DELTA_PACKAGE_ARCH) != s->arch)
2533                     continue;
2534                   baseevr = pool_lookup_id(pool, SOLVID_POS, DELTA_BASE_EVR);
2535                   FOR_PROVIDES(op, pp, s->name)
2536                     {
2537                       Solvable *os = pool->solvables + op;
2538                       if (os->repo == pool->installed && os->name == s->name && os->arch == s->arch && os->evr == baseevr)
2539                         break;
2540                     }
2541                   if (op && access("/usr/bin/applydeltarpm", X_OK) == 0)
2542                     {
2543                       /* base is installed, run sequence check */
2544                       const char *seqname;
2545                       const char *seqevr;
2546                       const char *seqnum;
2547                       const char *seq;
2548                       const char *dloc;
2549                       FILE *fp;
2550                       char cmd[128];
2551                       int newfd;
2552
2553                       seqname = pool_lookup_str(pool, SOLVID_POS, DELTA_SEQ_NAME);
2554                       seqevr = pool_lookup_str(pool, SOLVID_POS, DELTA_SEQ_EVR);
2555                       seqnum = pool_lookup_str(pool, SOLVID_POS, DELTA_SEQ_NUM);
2556                       seq = pool_tmpjoin(pool, seqname, "-", seqevr);
2557                       seq = pool_tmpjoin(pool, seq, "-", seqnum);
2558 #ifdef FEDORA
2559                       sprintf(cmd, "/usr/bin/applydeltarpm -a %s -c -s ", id2str(pool, s->arch));
2560 #else
2561                       sprintf(cmd, "/usr/bin/applydeltarpm -c -s ");
2562 #endif
2563                       if (system(pool_tmpjoin(pool, cmd, seq, 0)) != 0)
2564                         continue;       /* didn't match */
2565                       /* looks good, download delta */
2566                       chksumtype = 0;
2567                       chksum = pool_lookup_bin_checksum(pool, SOLVID_POS, DELTA_CHECKSUM, &chksumtype);
2568                       if (!chksumtype)
2569                         continue;       /* no way! */
2570                       dloc = pool_lookup_str(pool, SOLVID_POS, DELTA_LOCATION_DIR);
2571                       dloc = pool_tmpjoin(pool, dloc, "/", pool_lookup_str(pool, SOLVID_POS, DELTA_LOCATION_NAME));
2572                       dloc = pool_tmpjoin(pool, dloc, "-", pool_lookup_str(pool, SOLVID_POS, DELTA_LOCATION_EVR));
2573                       dloc = pool_tmpjoin(pool, dloc, ".", pool_lookup_str(pool, SOLVID_POS, DELTA_LOCATION_SUFFIX));
2574                       if ((fp = curlfopen(cinfo, dloc, 0, chksum, chksumtype, 0)) == 0)
2575                         continue;
2576                       /* got it, now reconstruct */
2577                       newfd = opentmpfile();
2578 #ifdef FEDORA
2579                       sprintf(cmd, "applydeltarpm -a %s /dev/fd/%d /dev/fd/%d", id2str(pool, s->arch), fileno(fp), newfd);
2580 #else
2581                       sprintf(cmd, "applydeltarpm /dev/fd/%d /dev/fd/%d", fileno(fp), newfd);
2582 #endif
2583                       fcntl(fileno(fp), F_SETFD, 0);
2584                       if (system(cmd))
2585                         {
2586                           close(newfd);
2587                           fclose(fp);
2588                           continue;
2589                         }
2590                       lseek(newfd, 0, SEEK_SET);
2591                       chksumtype = 0;
2592                       chksum = solvable_lookup_bin_checksum(s, SOLVABLE_CHECKSUM, &chksumtype);
2593                       if (chksumtype && !verify_checksum(newfd, loc, chksum, chksumtype))
2594                         {
2595                           close(newfd);
2596                           fclose(fp);
2597                           continue;
2598                         }
2599                       newpkgsfps[i] = fdopen(newfd, "r");
2600                       fclose(fp);
2601                       break;
2602                     }
2603                 }
2604               dataiterator_free(&di);
2605               sat_free(matchname);
2606             }
2607           
2608           if (newpkgsfps[i])
2609             {
2610               putchar('d');
2611               fflush(stdout);
2612               continue;         /* delta worked! */
2613             }
2614           if (cinfo->type == TYPE_SUSETAGS)
2615             {
2616               const char *datadir = repo_lookup_str(cinfo->repo, SOLVID_META, SUSETAGS_DATADIR);
2617               loc = pool_tmpjoin(pool, datadir ? datadir : "suse", "/", loc);
2618             }
2619           chksumtype = 0;
2620           chksum = solvable_lookup_bin_checksum(s, SOLVABLE_CHECKSUM, &chksumtype);
2621           if ((newpkgsfps[i] = curlfopen(cinfo, loc, 0, chksum, chksumtype, 0)) == 0)
2622             {
2623               printf("\n%s: %s not found in repository\n", s->repo->name, loc);
2624               exit(1);
2625             }
2626           putchar('.');
2627           fflush(stdout);
2628         }
2629       putchar('\n');
2630     }
2631
2632   if (newpkgs)
2633     {
2634       Queue conflicts;
2635
2636       printf("Searching for file conflicts\n");
2637       queue_init(&conflicts);
2638       fcstate.rpmdbstate = 0;
2639       fcstate.newpkgscnt = newpkgs;
2640       fcstate.checkq = &checkq;
2641       fcstate.newpkgsfps = newpkgsfps;
2642       pool_findfileconflicts(pool, &checkq, newpkgs, &conflicts, &fileconflict_cb, &fcstate);
2643       if (conflicts.count)
2644         {
2645           printf("\n");
2646           for (i = 0; i < conflicts.count; i += 5)
2647             printf("file %s of package %s conflicts with package %s\n", id2str(pool, conflicts.elements[i]), solvid2str(pool, conflicts.elements[i + 1]), solvid2str(pool, conflicts.elements[i + 3]));
2648           printf("\n");
2649           if (yesno("Re-run solver (y/n/q)? "))
2650             {
2651               for (i = 0; i < newpkgs; i++)
2652                 if (newpkgsfps[i])
2653                   fclose(newpkgsfps[i]);
2654               newpkgsfps = sat_free(newpkgsfps);
2655               solver_free(solv);
2656               pool_add_fileconflicts_deps(pool, &conflicts);
2657               pool_createwhatprovides(pool);    /* Hmm... */
2658               goto rerunsolver;
2659             }
2660         }
2661       queue_free(&conflicts);
2662     }
2663
2664   printf("Committing transaction:\n\n");
2665   transaction_order(trans, 0);
2666   for (i = 0; i < trans->steps.count; i++)
2667     {
2668       const char *evr, *evrp, *nvra;
2669       Solvable *s;
2670       int j;
2671       FILE *fp;
2672
2673       p = trans->steps.elements[i];
2674       s = pool_id2solvable(pool, p);
2675       Id type = transaction_type(trans, p, SOLVER_TRANSACTION_RPM_ONLY);
2676       switch(type)
2677         {
2678         case SOLVER_TRANSACTION_ERASE:
2679           printf("erase %s\n", solvid2str(pool, p));
2680           if (!s->repo->rpmdbid || !s->repo->rpmdbid[p - s->repo->start])
2681             continue;
2682           /* strip epoch from evr */
2683           evr = evrp = id2str(pool, s->evr);
2684           while (*evrp >= '0' && *evrp <= '9')
2685             evrp++;
2686           if (evrp > evr && evrp[0] == ':' && evrp[1])
2687             evr = evrp + 1;
2688           nvra = pool_tmpjoin(pool, id2str(pool, s->name), "-", evr);
2689           nvra = pool_tmpjoin(pool, nvra, ".", id2str(pool, s->arch));
2690           runrpm("-e", nvra, -1);       /* to bad that --querybynumber doesn't work */
2691           break;
2692         case SOLVER_TRANSACTION_INSTALL:
2693         case SOLVER_TRANSACTION_MULTIINSTALL:
2694           printf("install %s\n", solvid2str(pool, p));
2695           for (j = 0; j < newpkgs; j++)
2696             if (checkq.elements[j] == p)
2697               break;
2698           fp = j < newpkgs ? newpkgsfps[j] : 0;
2699           if (!fp)
2700             continue;
2701           rewind(fp);
2702           lseek(fileno(fp), 0, SEEK_SET);
2703           runrpm(type == SOLVER_TRANSACTION_MULTIINSTALL ? "-i" : "-U", "/dev/fd/3", fileno(fp));
2704           fclose(fp);
2705           newpkgsfps[j] = 0;
2706           break;
2707         default:
2708           break;
2709         }
2710     }
2711
2712   for (i = 0; i < newpkgs; i++)
2713     if (newpkgsfps[i])
2714       fclose(newpkgsfps[i]);
2715   sat_free(newpkgsfps);
2716   queue_free(&checkq);
2717   solver_free(solv);
2718   queue_free(&job);
2719   pool_free(pool);
2720   free_repoinfos(repoinfos, nrepoinfos);
2721   sat_free(commandlinepkgs);
2722   exit(0);
2723 }