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