refactor solv demo a bit
[platform/upstream/libsolv.git] / examples / solv.c
1 /*
2  * Copyright (c) 2009-2013, 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 it does:
11  * - understands globs for package names / dependencies
12  * - understands .arch suffix
13  * - installation of commandline packages
14  * - repository data caching
15  * - on demand loading of secondary repository data
16  * - gpg and checksum verification
17  * - file conflicts
18  * - deltarpm support
19  * - fastestmirror implementation
20  *
21  * things available in the library but missing from solv:
22  * - vendor policy loading
23  * - soft locks file handling
24  * - multi version handling
25  */
26
27 #define _GNU_SOURCE
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <dirent.h>
32 #include <fnmatch.h>
33 #include <unistd.h>
34 #include <zlib.h>
35 #include <fcntl.h>
36 #include <assert.h>
37 #include <sys/utsname.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <time.h>
41 #include <sys/time.h>
42 #include <sys/dir.h>
43 #include <sys/stat.h>
44
45 #include <sys/socket.h>
46 #include <netdb.h>
47 #include <poll.h>
48 #include <errno.h>
49
50 #include "pool.h"
51 #include "poolarch.h"
52 #include "repo.h"
53 #include "evr.h"
54 #include "policy.h"
55 #include "util.h"
56 #include "solver.h"
57 #include "solverdebug.h"
58 #include "chksum.h"
59 #include "repo_solv.h"
60 #include "selection.h"
61
62 #include "repo_write.h"
63 #ifdef ENABLE_RPMDB
64 #include "repo_rpmdb.h"
65 #include "pool_fileconflicts.h"
66 #endif
67 #ifdef ENABLE_DEBIAN
68 #include "repo_deb.h"
69 #endif
70 #ifdef ENABLE_RPMMD
71 #include "repo_rpmmd.h"
72 #include "repo_repomdxml.h"
73 #include "repo_updateinfoxml.h"
74 #include "repo_deltainfoxml.h"
75 #endif
76 #ifdef ENABLE_SUSEREPO
77 #include "repo_products.h"
78 #include "repo_susetags.h"
79 #include "repo_content.h"
80 #endif
81 #include "solv_xfopen.h"
82
83 #ifdef FEDORA
84 # define REPOINFO_PATH "/etc/yum.repos.d"
85 #endif
86 #ifdef SUSE
87 # define REPOINFO_PATH "/etc/zypp/repos.d"
88 # define PRODUCTS_PATH "/etc/products.d"
89 # define SOFTLOCKS_PATH "/var/lib/zypp/SoftLocks"
90 #endif
91
92 #define SOLVCACHE_PATH "/var/cache/solv"
93
94 #define METADATA_EXPIRE (60 * 15)
95
96 struct repoinfo {
97   Repo *repo;
98
99   char *alias;
100   char *name;
101   int enabled;
102   int autorefresh;
103   char *baseurl;
104   char *metalink;
105   char *mirrorlist;
106   char *path;
107   int type;
108   int pkgs_gpgcheck;
109   int repo_gpgcheck;
110   int priority;
111   int keeppackages;
112   int metadata_expire;
113   char **components;
114   int ncomponents;
115
116   unsigned char cookie[32];
117   unsigned char extcookie[32];
118   int incomplete;
119 };
120
121 #ifdef FEDORA
122 char *
123 yum_substitute(Pool *pool, char *line)
124 {
125   char *p, *p2;
126   static char *releaseevr;
127   static char *basearch;
128
129   if (!line)
130     {
131       solv_free(releaseevr);
132       releaseevr = 0;
133       solv_free(basearch);
134       basearch = 0;
135       return 0;
136     }
137   p = line;
138   while ((p2 = strchr(p, '$')) != 0)
139     {
140       if (!strncmp(p2, "$releasever", 11))
141         {
142           if (!releaseevr)
143             {
144               Queue q;
145               const char *rootdir = pool_get_rootdir(pool);
146         
147               queue_init(&q);
148               rpm_installedrpmdbids(rootdir, "Providename", "redhat-release", &q);
149               if (q.count)
150                 {
151                   void *handle, *state = 0;
152                   char *p;
153                   handle = rpm_byrpmdbid(q.elements[0], rootdir, &state);
154                   releaseevr = rpm_query(handle, SOLVABLE_EVR);
155                   rpm_byrpmdbid(0, 0, &state);
156                   if ((p = strchr(releaseevr, '-')) != 0)
157                     *p = 0;
158                 }
159               queue_free(&q);
160               if (!releaseevr)
161                 {
162                   fprintf(stderr, "no installed package provides 'redhat-release', cannot determine $releasever\n");
163                   exit(1);
164                 }
165             }
166           *p2 = 0;
167           p = pool_tmpjoin(pool, line, releaseevr, p2 + 11);
168           p2 = p + (p2 - line);
169           line = p;
170           p = p2 + strlen(releaseevr);
171           continue;
172         }
173       if (!strncmp(p2, "$basearch", 9))
174         {
175           if (!basearch)
176             {
177               struct utsname un;
178               if (uname(&un))
179                 {
180                   perror("uname");
181                   exit(1);
182                 }
183               basearch = strdup(un.machine);
184               if (basearch[0] == 'i' && basearch[1] && !strcmp(basearch + 2, "86"))
185                 basearch[1] = '3';
186             }
187           *p2 = 0;
188           p = pool_tmpjoin(pool, line, basearch, p2 + 9);
189           p2 = p + (p2 - line);
190           line = p;
191           p = p2 + strlen(basearch);
192           continue;
193         }
194       p = p2 + 1;
195     }
196   return line;
197 }
198 #endif
199
200 #define TYPE_UNKNOWN    0
201 #define TYPE_SUSETAGS   1
202 #define TYPE_RPMMD      2
203 #define TYPE_PLAINDIR   3
204 #define TYPE_DEBIAN     4
205
206 #ifndef NOSYSTEM
207 static int
208 read_repoinfos_sort(const void *ap, const void *bp)
209 {
210   const struct repoinfo *a = ap;
211   const struct repoinfo *b = bp;
212   return strcmp(a->alias, b->alias);
213 }
214 #endif
215
216 #if defined(SUSE) || defined(FEDORA)
217
218 struct repoinfo *
219 read_repoinfos(Pool *pool, int *nrepoinfosp)
220 {
221   const char *reposdir = REPOINFO_PATH;
222   char buf[4096];
223   char buf2[4096], *kp, *vp, *kpe;
224   DIR *dir;
225   FILE *fp;
226   struct dirent *ent;
227   int l, rdlen;
228   struct repoinfo *repoinfos = 0, *cinfo;
229   int nrepoinfos = 0;
230
231   rdlen = strlen(reposdir);
232   dir = opendir(reposdir);
233   if (!dir)
234     {
235       *nrepoinfosp = 0;
236       return 0;
237     }
238   while ((ent = readdir(dir)) != 0)
239     {
240       if (ent->d_name[0] == '.')
241         continue;
242       l = strlen(ent->d_name);
243       if (l < 6 || rdlen + 2 + l >= sizeof(buf) || strcmp(ent->d_name + l - 5, ".repo") != 0)
244         continue;
245       snprintf(buf, sizeof(buf), "%s/%s", reposdir, ent->d_name);
246       if ((fp = fopen(buf, "r")) == 0)
247         {
248           perror(buf);
249           continue;
250         }
251       cinfo = 0;
252       while(fgets(buf2, sizeof(buf2), fp))
253         {
254           l = strlen(buf2);
255           if (l == 0)
256             continue;
257           while (l && (buf2[l - 1] == '\n' || buf2[l - 1] == ' ' || buf2[l - 1] == '\t'))
258             buf2[--l] = 0;
259           kp = buf2;
260           while (*kp == ' ' || *kp == '\t')
261             kp++;
262           if (!*kp || *kp == '#')
263             continue;
264 #ifdef FEDORA
265           if (strchr(kp, '$'))
266             kp = yum_substitute(pool, kp);
267 #endif
268           if (*kp == '[')
269             {
270               vp = strrchr(kp, ']');
271               if (!vp)
272                 continue;
273               *vp = 0;
274               repoinfos = solv_extend(repoinfos, nrepoinfos, 1, sizeof(*repoinfos), 15);
275               cinfo = repoinfos + nrepoinfos++;
276               memset(cinfo, 0, sizeof(*cinfo));
277               cinfo->alias = strdup(kp + 1);
278               cinfo->type = TYPE_RPMMD;
279               cinfo->autorefresh = 1;
280               cinfo->priority = 99;
281 #ifndef FEDORA
282               cinfo->repo_gpgcheck = 1;
283 #endif
284               cinfo->metadata_expire = METADATA_EXPIRE;
285               continue;
286             }
287           if (!cinfo)
288             continue;
289           vp = strchr(kp, '=');
290           if (!vp)
291             continue;
292           for (kpe = vp - 1; kpe >= kp; kpe--)
293             if (*kpe != ' ' && *kpe != '\t')
294               break;
295           if (kpe == kp)
296             continue;
297           vp++;
298           while (*vp == ' ' || *vp == '\t')
299             vp++;
300           kpe[1] = 0;
301           if (!strcmp(kp, "name"))
302             cinfo->name = strdup(vp);
303           else if (!strcmp(kp, "enabled"))
304             cinfo->enabled = *vp == '0' ? 0 : 1;
305           else if (!strcmp(kp, "autorefresh"))
306             cinfo->autorefresh = *vp == '0' ? 0 : 1;
307           else if (!strcmp(kp, "gpgcheck"))
308             cinfo->pkgs_gpgcheck = *vp == '0' ? 0 : 1;
309           else if (!strcmp(kp, "repo_gpgcheck"))
310             cinfo->repo_gpgcheck = *vp == '0' ? 0 : 1;
311           else if (!strcmp(kp, "baseurl"))
312             cinfo->baseurl = strdup(vp);
313           else if (!strcmp(kp, "mirrorlist"))
314             {
315               if (strstr(vp, "metalink"))
316                 cinfo->metalink = strdup(vp);
317               else
318                 cinfo->mirrorlist = strdup(vp);
319             }
320           else if (!strcmp(kp, "path"))
321             {
322               if (vp && strcmp(vp, "/") != 0)
323                 cinfo->path = strdup(vp);
324             }
325           else if (!strcmp(kp, "type"))
326             {
327               if (!strcmp(vp, "yast2"))
328                 cinfo->type = TYPE_SUSETAGS;
329               else if (!strcmp(vp, "rpm-md"))
330                 cinfo->type = TYPE_RPMMD;
331               else if (!strcmp(vp, "plaindir"))
332                 cinfo->type = TYPE_PLAINDIR;
333               else
334                 cinfo->type = TYPE_UNKNOWN;
335             }
336           else if (!strcmp(kp, "priority"))
337             cinfo->priority = atoi(vp);
338           else if (!strcmp(kp, "keeppackages"))
339             cinfo->keeppackages = *vp == '0' ? 0 : 1;
340         }
341       fclose(fp);
342       cinfo = 0;
343     }
344   closedir(dir);
345   qsort(repoinfos, nrepoinfos, sizeof(*repoinfos), read_repoinfos_sort);
346   *nrepoinfosp = nrepoinfos;
347   return repoinfos;
348 }
349
350 #endif
351
352 #ifdef DEBIAN
353
354 struct repoinfo *
355 read_repoinfos(Pool *pool, int *nrepoinfosp)
356 {
357   FILE *fp;
358   char buf[4096];
359   char buf2[4096];
360   int l;
361   char *kp, *url, *distro;
362   struct repoinfo *repoinfos = 0, *cinfo;
363   int nrepoinfos = 0;
364   DIR *dir = 0;
365   struct dirent *ent;
366
367   fp = fopen("/etc/apt/sources.list", "r");
368   while (1)
369     {
370       if (!fp)
371         {
372           if (!dir)
373             {
374               dir = opendir("/etc/apt/sources.list.d");
375               if (!dir)
376                 break;
377             }
378           if ((ent = readdir(dir)) == 0)
379             {
380               closedir(dir);
381               break;
382             }
383           if (ent->d_name[0] == '.')
384             continue;
385           l = strlen(ent->d_name);
386           if (l < 5 || strcmp(ent->d_name + l - 5, ".list") != 0)
387             continue;
388           snprintf(buf, sizeof(buf), "%s/%s", "/etc/apt/sources.list.d", ent->d_name);
389           if (!(fp = fopen(buf, "r")))
390             continue;
391         }
392       while(fgets(buf2, sizeof(buf2), fp))
393         {
394           l = strlen(buf2);
395           if (l == 0)
396             continue;
397           while (l && (buf2[l - 1] == '\n' || buf2[l - 1] == ' ' || buf2[l - 1] == '\t'))
398             buf2[--l] = 0;
399           kp = buf2;
400           while (*kp == ' ' || *kp == '\t')
401             kp++;
402           if (!*kp || *kp == '#')
403             continue;
404           if (strncmp(kp, "deb", 3) != 0)
405             continue;
406           kp += 3;
407           if (*kp != ' ' && *kp != '\t')
408             continue;
409           while (*kp == ' ' || *kp == '\t')
410             kp++;
411           if (!*kp)
412             continue;
413           url = kp;
414           while (*kp && *kp != ' ' && *kp != '\t')
415             kp++;
416           if (*kp)
417             *kp++ = 0;
418           while (*kp == ' ' || *kp == '\t')
419             kp++;
420           if (!*kp)
421             continue;
422           distro = kp;
423           while (*kp && *kp != ' ' && *kp != '\t')
424             kp++;
425           if (*kp)
426             *kp++ = 0;
427           while (*kp == ' ' || *kp == '\t')
428             kp++;
429           if (!*kp)
430             continue;
431           repoinfos = solv_extend(repoinfos, nrepoinfos, 1, sizeof(*repoinfos), 15);
432           cinfo = repoinfos + nrepoinfos++;
433           memset(cinfo, 0, sizeof(*cinfo));
434           cinfo->baseurl = strdup(url);
435           cinfo->alias = solv_dupjoin(url, "/", distro);
436           cinfo->name = strdup(distro);
437           cinfo->type = TYPE_DEBIAN;
438           cinfo->enabled = 1;
439           cinfo->autorefresh = 1;
440           cinfo->repo_gpgcheck = 1;
441           cinfo->metadata_expire = METADATA_EXPIRE;
442           while (*kp)
443             {
444               char *compo;
445               while (*kp == ' ' || *kp == '\t')
446                 kp++;
447               if (!*kp)
448                 break;
449               compo = kp;
450               while (*kp && *kp != ' ' && *kp != '\t')
451                 kp++;
452               if (*kp)
453                 *kp++ = 0;
454               cinfo->components = solv_extend(cinfo->components, cinfo->ncomponents, 1, sizeof(*cinfo->components), 15);
455               cinfo->components[cinfo->ncomponents++] = strdup(compo);
456             }
457         }
458       fclose(fp);
459       fp = 0;
460     }
461   qsort(repoinfos, nrepoinfos, sizeof(*repoinfos), read_repoinfos_sort);
462   *nrepoinfosp = nrepoinfos;
463   return repoinfos;
464 }
465
466 #endif
467
468 #ifdef NOSYSTEM
469 struct repoinfo *
470 read_repoinfos(Pool *pool, int *nrepoinfosp)
471 {
472   *nrepoinfosp = 0;
473   return 0;
474 }
475 #endif
476
477
478 void
479 free_repoinfos(struct repoinfo *repoinfos, int nrepoinfos)
480 {
481   int i, j;
482   for (i = 0; i < nrepoinfos; i++)
483     {
484       struct repoinfo *cinfo = repoinfos + i;
485       solv_free(cinfo->name);
486       solv_free(cinfo->alias);
487       solv_free(cinfo->path);
488       solv_free(cinfo->metalink);
489       solv_free(cinfo->mirrorlist);
490       solv_free(cinfo->baseurl);
491       for (j = 0; j < cinfo->ncomponents; j++)
492         solv_free(cinfo->components[j]);
493       solv_free(cinfo->components);
494     }
495   solv_free(repoinfos);
496 }
497
498 static inline int
499 opentmpfile()
500 {
501   char tmpl[100];
502   int fd;
503
504   strcpy(tmpl, "/var/tmp/solvXXXXXX");
505   fd = mkstemp(tmpl);
506   if (fd < 0)
507     {
508       perror("mkstemp");
509       exit(1);
510     }
511   unlink(tmpl);
512   return fd;
513 }
514
515 static int
516 verify_checksum(int fd, const char *file, const unsigned char *chksum, Id chksumtype)
517 {
518   char buf[1024];
519   const unsigned char *sum;
520   void *h;
521   int l;
522
523   h = solv_chksum_create(chksumtype);
524   if (!h)
525     {
526       printf("%s: unknown checksum type\n", file);
527       return 0;
528     }
529   while ((l = read(fd, buf, sizeof(buf))) > 0)
530     solv_chksum_add(h, buf, l);
531   lseek(fd, 0, SEEK_SET);
532   l = 0;
533   sum = solv_chksum_get(h, &l);
534   if (memcmp(sum, chksum, l))
535     {
536       printf("%s: checksum mismatch\n", file);
537       solv_chksum_free(h, 0);
538       return 0;
539     }
540   solv_chksum_free(h, 0);
541   return 1;
542 }
543
544 void
545 findfastest(char **urls, int nurls)
546 {
547   int i, j, port;
548   int *socks, qc;
549   struct pollfd *fds;
550   char *p, *p2, *q;
551   char portstr[16];
552   struct addrinfo hints, *result;;
553
554   fds = solv_calloc(nurls, sizeof(*fds));
555   socks = solv_calloc(nurls, sizeof(*socks));
556   for (i = 0; i < nurls; i++)
557     {
558       socks[i] = -1;
559       p = strchr(urls[i], '/');
560       if (!p)
561         continue;
562       if (p[1] != '/')
563         continue;
564       p += 2;
565       q = strchr(p, '/');
566       qc = 0;
567       if (q)
568         {
569           qc = *q;
570           *q = 0;
571         }
572       if ((p2 = strchr(p, '@')) != 0)
573         p = p2 + 1;
574       port = 80;
575       if (!strncmp("https:", urls[i], 6))
576         port = 443;
577       else if (!strncmp("ftp:", urls[i], 4))
578         port = 21;
579       if ((p2 = strrchr(p, ':')) != 0)
580         {
581           port = atoi(p2 + 1);
582           if (q)
583             *q = qc;
584           q = p2;
585           qc = *q;
586           *q = 0;
587         }
588       sprintf(portstr, "%d", port);
589       memset(&hints, 0, sizeof(struct addrinfo));
590       hints.ai_family = AF_UNSPEC;
591       hints.ai_socktype = SOCK_STREAM;
592       hints.ai_flags = AI_NUMERICSERV;
593       result = 0;
594       if (!getaddrinfo(p, portstr, &hints, &result))
595         {
596           socks[i] = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
597           if (socks[i] >= 0)
598             {
599               fcntl(socks[i], F_SETFL, O_NONBLOCK);
600               if (connect(socks[i], result->ai_addr, result->ai_addrlen) == -1)
601                 {
602                   if (errno != EINPROGRESS)
603                     {
604                       close(socks[i]);
605                       socks[i] = -1;
606                     }
607                 }
608             }
609           freeaddrinfo(result);
610         }
611       if (q)
612         *q = qc;
613     }
614   for (;;)
615     {
616       for (i = j = 0; i < nurls; i++)
617         {
618           if (socks[i] < 0)
619             continue;
620           fds[j].fd = socks[i];
621           fds[j].events = POLLOUT;
622           j++;
623         }
624       if (j < 2)
625         {
626           i = j - 1;
627           break;
628         }
629       if (poll(fds, j, 10000) <= 0)
630         {
631           i = -1;       /* something is wrong */
632           break;
633         }
634       for (i = 0; i < j; i++)
635         if ((fds[i].revents & POLLOUT) != 0)
636           {
637             int soe = 0;
638             socklen_t soel = sizeof(int);
639             if (getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, &soe, &soel) == -1 || soe != 0)
640               {
641                 /* connect failed, kill socket */
642                 for (j = 0; j < nurls; j++)
643                   if (socks[j] == fds[i].fd)
644                     {
645                       close(socks[j]);
646                       socks[j] = -1;
647                     }
648                 i = j + 1;
649                 break;
650               }
651             break;      /* horray! */
652           }
653       if (i == j + 1)
654         continue;
655       if (i == j)
656         i = -1;         /* something is wrong, no bit was set */
657       break;
658     }
659   /* now i contains the fastest fd index */
660   if (i >= 0)
661     {
662       for (j = 0; j < nurls; j++)
663         if (socks[j] == fds[i].fd)
664           break;
665       if (j != 0)
666         {
667           char *url0 = urls[0];
668           urls[0] = urls[j];
669           urls[j] = url0;
670         }
671     }
672   for (i = j = 0; i < nurls; i++)
673     if (socks[i] >= 0)
674       close(socks[i]);
675   free(socks);
676   free(fds);
677 }
678
679 char *
680 findmetalinkurl(FILE *fp, unsigned char *chksump, Id *chksumtypep)
681 {
682   char buf[4096], *bp, *ep;
683   char **urls = 0;
684   int nurls = 0;
685   int i;
686
687   if (chksumtypep)
688     *chksumtypep = 0;
689   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
690     {
691       while (*bp == ' ' || *bp == '\t')
692         bp++;
693       if (chksumtypep && !*chksumtypep && !strncmp(bp, "<hash type=\"sha256\">", 20))
694         {
695           bp += 20;
696           if (solv_hex2bin((const char **)&bp, chksump, 32) == 32)
697             *chksumtypep = REPOKEY_TYPE_SHA256;
698           continue;
699         }
700       if (strncmp(bp, "<url", 4))
701         continue;
702       bp = strchr(bp, '>');
703       if (!bp)
704         continue;
705       bp++;
706       ep = strstr(bp, "repodata/repomd.xml</url>");
707       if (!ep)
708         continue;
709       *ep = 0;
710       if (strncmp(bp, "http", 4))
711         continue;
712       urls = solv_extend(urls, nurls, 1, sizeof(*urls), 15);
713       urls[nurls++] = strdup(bp);
714     }
715   if (nurls)
716     {
717       if (nurls > 1)
718         findfastest(urls, nurls > 5 ? 5 : nurls);
719       bp = urls[0];
720       urls[0] = 0;
721       for (i = 0; i < nurls; i++)
722         solv_free(urls[i]);
723       solv_free(urls);
724       ep = strchr(bp, '/');
725       if ((ep = strchr(ep + 2, '/')) != 0)
726         {
727           *ep = 0;
728           printf("[using mirror %s]\n", bp);
729           *ep = '/';
730         }
731       return bp;
732     }
733   return 0;
734 }
735
736 char *
737 findmirrorlisturl(FILE *fp)
738 {
739   char buf[4096], *bp, *ep;
740   int i, l;
741   char **urls = 0;
742   int nurls = 0;
743
744   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
745     {
746       while (*bp == ' ' || *bp == '\t')
747         bp++;
748       if (!*bp || *bp == '#')
749         continue;
750       l = strlen(bp);
751       while (l > 0 && (bp[l - 1] == ' ' || bp[l - 1] == '\t' || bp[l - 1] == '\n'))
752         bp[--l] = 0;
753       urls = solv_extend(urls, nurls, 1, sizeof(*urls), 15);
754       urls[nurls++] = strdup(bp);
755     }
756   if (nurls)
757     {
758       if (nurls > 1)
759         findfastest(urls, nurls > 5 ? 5 : nurls);
760       bp = urls[0];
761       urls[0] = 0;
762       for (i = 0; i < nurls; i++)
763         solv_free(urls[i]);
764       solv_free(urls);
765       ep = strchr(bp, '/');
766       if ((ep = strchr(ep + 2, '/')) != 0)
767         {
768           *ep = 0;
769           printf("[using mirror %s]\n", bp);
770           *ep = '/';
771         }
772       return bp;
773     }
774   return 0;
775 }
776
777 static inline int
778 iscompressed(const char *name)
779 {
780   return solv_xfopen_iscompressed(name) != 0;
781 }
782
783 FILE *
784 curlfopen(struct repoinfo *cinfo, const char *file, int uncompress, const unsigned char *chksum, Id chksumtype, int markincomplete)
785 {
786   FILE *fp;
787   pid_t pid;
788   int fd, l;
789   int status;
790   char url[4096];
791   const char *baseurl = cinfo->baseurl;
792
793   if (!baseurl)
794     {
795       if (!cinfo->metalink && !cinfo->mirrorlist)
796         return 0;
797       if (file != cinfo->metalink && file != cinfo->mirrorlist)
798         {
799           unsigned char mlchksum[32];
800           Id mlchksumtype;
801           fp = curlfopen(cinfo, cinfo->metalink ? cinfo->metalink : cinfo->mirrorlist, 0, 0, 0, 0);
802           mlchksumtype = 0;
803           if (!fp)
804             return 0;
805           if (cinfo->metalink)
806             cinfo->baseurl = findmetalinkurl(fp, mlchksum, &mlchksumtype);
807           else
808             cinfo->baseurl = findmirrorlisturl(fp);
809           fclose(fp);
810           if (!cinfo->baseurl)
811             return 0;
812 #ifdef FEDORA
813           if (strchr(cinfo->baseurl, '$'))
814             {
815               char *b = yum_substitute(cinfo->repo->pool, cinfo->baseurl);
816               free(cinfo->baseurl);
817               cinfo->baseurl = strdup(b);
818             }
819 #endif
820           if (!chksumtype && mlchksumtype && !strcmp(file, "repodata/repomd.xml"))
821             {
822               chksumtype = mlchksumtype;
823               chksum = mlchksum;
824             }
825           return curlfopen(cinfo, file, uncompress, chksum, chksumtype, markincomplete);
826         }
827       snprintf(url, sizeof(url), "%s", file);
828     }
829   else
830     {
831       l = strlen(baseurl);
832       if (l && baseurl[l - 1] == '/')
833         snprintf(url, sizeof(url), "%s%s", baseurl, file);
834       else
835         snprintf(url, sizeof(url), "%s/%s", baseurl, file);
836     }
837   fd = opentmpfile();
838   // printf("url: %s\n", url);
839   if ((pid = fork()) == (pid_t)-1)
840     {
841       perror("fork");
842       exit(1);
843     }
844   if (pid == 0)
845     {
846       if (fd != 1)
847         {
848           dup2(fd, 1);
849           close(fd);
850         }
851       execlp("curl", "curl", "-f", "-s", "-L", url, (char *)0);
852       perror("curl");
853       _exit(0);
854     }
855   status = 0;
856   while (waitpid(pid, &status, 0) != pid)
857     ;
858   if (lseek(fd, 0, SEEK_END) == 0 && (!status || !chksumtype))
859     {
860       /* empty file */
861       close(fd);
862       return 0;
863     }
864   lseek(fd, 0, SEEK_SET);
865   if (status)
866     {
867       printf("%s: download error %d\n", file, status >> 8 ? status >> 8 : status);
868       if (markincomplete)
869         cinfo->incomplete = 1;
870       close(fd);
871       return 0;
872     }
873   if (chksumtype && !verify_checksum(fd, file, chksum, chksumtype))
874     {
875       if (markincomplete)
876         cinfo->incomplete = 1;
877       close(fd);
878       return 0;
879     }
880   fcntl(fd, F_SETFD, FD_CLOEXEC);
881   if (uncompress)
882     {
883       if (solv_xfopen_iscompressed(file) < 0)
884         {
885           printf("%s: unsupported compression\n", file);
886           if (markincomplete)
887             cinfo->incomplete = 1;
888           close(fd);
889           return 0;
890         }
891       fp = solv_xfopen_fd(file, fd, "r");
892     }
893   else
894     fp = fdopen(fd, "r");
895   if (!fp)
896     close(fd);
897   return fp;
898 }
899
900 #ifndef DEBIAN
901
902 static void
903 cleanupgpg(char *gpgdir)
904 {
905   char cmd[256];
906   snprintf(cmd, sizeof(cmd), "%s/pubring.gpg", gpgdir);
907   unlink(cmd);
908   snprintf(cmd, sizeof(cmd), "%s/pubring.gpg~", gpgdir);
909   unlink(cmd);
910   snprintf(cmd, sizeof(cmd), "%s/secring.gpg", gpgdir);
911   unlink(cmd);
912   snprintf(cmd, sizeof(cmd), "%s/trustdb.gpg", gpgdir);
913   unlink(cmd);
914   snprintf(cmd, sizeof(cmd), "%s/keys", gpgdir);
915   unlink(cmd);
916   rmdir(gpgdir);
917 }
918
919 int
920 checksig(Pool *sigpool, FILE *fp, FILE *sigfp)
921 {
922   char *gpgdir;
923   char *keysfile;
924   const char *pubkey;
925   char cmd[256];
926   FILE *kfp;
927   Solvable *s;
928   Id p;
929   off_t posfp, possigfp;
930   int r, nkeys;
931
932   gpgdir = mkdtemp(pool_tmpjoin(sigpool, "/var/tmp/solvgpg.XXXXXX", 0, 0));
933   if (!gpgdir)
934     return 0;
935   keysfile = pool_tmpjoin(sigpool, gpgdir, "/keys", 0);
936   if (!(kfp = fopen(keysfile, "w")) )
937     {
938       cleanupgpg(gpgdir);
939       return 0;
940     }
941   nkeys = 0;
942   for (p = 1, s = sigpool->solvables + p; p < sigpool->nsolvables; p++, s++)
943     {
944       if (!s->repo)
945         continue;
946       pubkey = solvable_lookup_str(s, SOLVABLE_DESCRIPTION);
947       if (!pubkey || !*pubkey)
948         continue;
949       if (fwrite(pubkey, strlen(pubkey), 1, kfp) != 1)
950         break;
951       if (fputc('\n', kfp) == EOF)      /* Just in case... */
952         break;
953       nkeys++;
954     }
955   if (fclose(kfp) || !nkeys)
956     {
957       cleanupgpg(gpgdir);
958       return 0;
959     }
960   snprintf(cmd, sizeof(cmd), "gpg2 -q --homedir %s --import %s", gpgdir, keysfile);
961   if (system(cmd))
962     {
963       fprintf(stderr, "key import error\n");
964       cleanupgpg(gpgdir);
965       return 0;
966     }
967   unlink(keysfile);
968   posfp = lseek(fileno(fp), 0, SEEK_CUR);
969   lseek(fileno(fp), 0, SEEK_SET);
970   possigfp = lseek(fileno(sigfp), 0, SEEK_CUR);
971   lseek(fileno(sigfp), 0, SEEK_SET);
972   snprintf(cmd, sizeof(cmd), "gpg -q --homedir %s --verify /dev/fd/%d /dev/fd/%d >/dev/null 2>&1", gpgdir, fileno(sigfp), fileno(fp));
973   fcntl(fileno(fp), F_SETFD, 0);        /* clear CLOEXEC */
974   fcntl(fileno(sigfp), F_SETFD, 0);     /* clear CLOEXEC */
975   r = system(cmd);
976   lseek(fileno(sigfp), possigfp, SEEK_SET);
977   lseek(fileno(fp), posfp, SEEK_SET);
978   fcntl(fileno(fp), F_SETFD, FD_CLOEXEC);
979   fcntl(fileno(sigfp), F_SETFD, FD_CLOEXEC);
980   cleanupgpg(gpgdir);
981   return r == 0 ? 1 : 0;
982 }
983
984 #else
985
986 static int
987 checksig(Pool *sigpool, FILE *fp, FILE *sigfp)
988 {
989   char cmd[256];
990   int r;
991
992   snprintf(cmd, sizeof(cmd), "gpgv -q --keyring /etc/apt/trusted.gpg /dev/fd/%d /dev/fd/%d >/dev/null 2>&1", fileno(sigfp), fileno(fp));
993   fcntl(fileno(fp), F_SETFD, 0);        /* clear CLOEXEC */
994   fcntl(fileno(sigfp), F_SETFD, 0);     /* clear CLOEXEC */
995   r = system(cmd);
996   fcntl(fileno(fp), F_SETFD, FD_CLOEXEC);
997   fcntl(fileno(sigfp), F_SETFD, FD_CLOEXEC);
998   return r == 0 ? 1 : 0;
999 }
1000
1001 #endif
1002
1003 static Pool *
1004 read_sigs()
1005 {
1006   Pool *sigpool = pool_create();
1007 #if defined(ENABLE_RPMDB_PUBKEY)
1008   Repo *repo = repo_create(sigpool, "rpmdbkeys");
1009   repo_add_rpmdb_pubkeys(repo, 0);
1010 #endif
1011   return sigpool;
1012 }
1013
1014 static int
1015 downloadchecksig(struct repoinfo *cinfo, FILE *fp, const char *sigurl, Pool **sigpool)
1016 {
1017   FILE *sigfp;
1018   sigfp = curlfopen(cinfo, sigurl, 0, 0, 0, 0);
1019   if (!sigfp)
1020     {
1021       printf(" unsigned, skipped\n");
1022       return 0;
1023     }
1024   if (!*sigpool)
1025     *sigpool = read_sigs();
1026   if (!checksig(*sigpool, fp, sigfp))
1027     {
1028       printf(" checksig failed, skipped\n");
1029       fclose(sigfp);
1030       return 0;
1031     }
1032   fclose(sigfp);
1033   return 1;
1034 }
1035
1036 #define CHKSUM_IDENT "1.1"
1037
1038 void
1039 calc_checksum_fp(FILE *fp, Id chktype, unsigned char *out)
1040 {
1041   char buf[4096];
1042   void *h = solv_chksum_create(chktype);
1043   int l;
1044
1045   solv_chksum_add(h, CHKSUM_IDENT, strlen(CHKSUM_IDENT));
1046   while ((l = fread(buf, 1, sizeof(buf), fp)) > 0)
1047     solv_chksum_add(h, buf, l);
1048   rewind(fp);
1049   solv_chksum_free(h, out);
1050 }
1051
1052 void
1053 calc_checksum_stat(struct stat *stb, Id chktype, unsigned char *cookie, unsigned char *out)
1054 {
1055   void *h = solv_chksum_create(chktype);
1056   solv_chksum_add(h, CHKSUM_IDENT, strlen(CHKSUM_IDENT));
1057   if (cookie)
1058     solv_chksum_add(h, cookie, 32);
1059   solv_chksum_add(h, &stb->st_dev, sizeof(stb->st_dev));
1060   solv_chksum_add(h, &stb->st_ino, sizeof(stb->st_ino));
1061   solv_chksum_add(h, &stb->st_size, sizeof(stb->st_size));
1062   solv_chksum_add(h, &stb->st_mtime, sizeof(stb->st_mtime));
1063   solv_chksum_free(h, out);
1064 }
1065
1066 void
1067 setarch(Pool *pool)
1068 {
1069   struct utsname un;
1070   if (uname(&un))
1071     {
1072       perror("uname");
1073       exit(1);
1074     }
1075   pool_setarch(pool, un.machine);
1076 }
1077
1078 char *
1079 calccachepath(Repo *repo, const char *repoext)
1080 {
1081   char *q, *p = pool_tmpjoin(repo->pool, SOLVCACHE_PATH, "/", repo->name);
1082   if (repoext)
1083     {
1084       p = pool_tmpappend(repo->pool, p, "_", repoext);
1085       p = pool_tmpappend(repo->pool, p, ".solvx", 0);
1086     }
1087   else
1088     p = pool_tmpappend(repo->pool, p, ".solv", 0);
1089   q = p + strlen(SOLVCACHE_PATH) + 1;
1090   if (*q == '.')
1091     *q = '_';
1092   for (; *q; q++)
1093     if (*q == '/')
1094       *q = '_';
1095   return p;
1096 }
1097
1098 int
1099 usecachedrepo(Repo *repo, const char *repoext, unsigned char *cookie, int mark)
1100 {
1101   FILE *fp;
1102   unsigned char mycookie[32];
1103   unsigned char myextcookie[32];
1104   struct repoinfo *cinfo;
1105   int flags;
1106
1107   cinfo = repo->appdata;
1108   if (!(fp = fopen(calccachepath(repo, repoext), "r")))
1109     return 0;
1110   if (fseek(fp, -sizeof(mycookie), SEEK_END) || fread(mycookie, sizeof(mycookie), 1, fp) != 1)
1111     {
1112       fclose(fp);
1113       return 0;
1114     }
1115   if (cookie && memcmp(cookie, mycookie, sizeof(mycookie)))
1116     {
1117       fclose(fp);
1118       return 0;
1119     }
1120   if (cinfo && !repoext)
1121     {
1122       if (fseek(fp, -sizeof(mycookie) * 2, SEEK_END) || fread(myextcookie, sizeof(myextcookie), 1, fp) != 1)
1123         {
1124           fclose(fp);
1125           return 0;
1126         }
1127     }
1128   rewind(fp);
1129
1130   flags = 0;
1131   if (repoext)
1132     {
1133       flags = REPO_USE_LOADING|REPO_EXTEND_SOLVABLES;
1134       if (strcmp(repoext, "DL") != 0)
1135         flags |= REPO_LOCALPOOL;        /* no local pool for DL so that we can compare IDs */
1136     }
1137
1138   if (repo_add_solv(repo, fp, flags))
1139     {
1140       fclose(fp);
1141       return 0;
1142     }
1143   if (cinfo && !repoext)
1144     {
1145       memcpy(cinfo->cookie, mycookie, sizeof(mycookie));
1146       memcpy(cinfo->extcookie, myextcookie, sizeof(myextcookie));
1147     }
1148   if (mark)
1149     futimens(fileno(fp), 0);    /* try to set modification time */
1150   fclose(fp);
1151   return 1;
1152 }
1153
1154 void
1155 writecachedrepo(Repo *repo, Repodata *info, const char *repoext, unsigned char *cookie)
1156 {
1157   FILE *fp;
1158   int i, fd;
1159   char *tmpl;
1160   struct repoinfo *cinfo;
1161   int onepiece;
1162
1163   cinfo = repo->appdata;
1164   if (cinfo && cinfo->incomplete)
1165     return;
1166   mkdir(SOLVCACHE_PATH, 0755);
1167   /* use dupjoin instead of tmpjoin because tmpl must survive repo_write */
1168   tmpl = solv_dupjoin(SOLVCACHE_PATH, "/", ".newsolv-XXXXXX");
1169   fd = mkstemp(tmpl);
1170   if (fd < 0)
1171     {
1172       free(tmpl);
1173       return;
1174     }
1175   fchmod(fd, 0444);
1176   if (!(fp = fdopen(fd, "w")))
1177     {
1178       close(fd);
1179       unlink(tmpl);
1180       free(tmpl);
1181       return;
1182     }
1183
1184   onepiece = 1;
1185   for (i = repo->start; i < repo->end; i++)
1186    if (repo->pool->solvables[i].repo != repo)
1187      break;
1188   if (i < repo->end)
1189     onepiece = 0;
1190
1191   if (!info)
1192     repo_write(repo, fp);
1193   else if (repoext)
1194     repodata_write(info, fp);
1195   else
1196     {
1197       int oldnrepodata = repo->nrepodata;
1198       repo->nrepodata = oldnrepodata > 2 ? 2 : oldnrepodata;    /* XXX: do this right */
1199       repo_write(repo, fp);
1200       repo->nrepodata = oldnrepodata;
1201       onepiece = 0;
1202     }
1203
1204   if (!repoext && cinfo)
1205     {
1206       if (!cinfo->extcookie[0])
1207         {
1208           /* create the ext cookie and append it */
1209           /* we just need some unique ID */
1210           struct stat stb;
1211           if (!fstat(fileno(fp), &stb))
1212             memset(&stb, 0, sizeof(stb));
1213           calc_checksum_stat(&stb, REPOKEY_TYPE_SHA256, cookie, cinfo->extcookie);
1214           if (cinfo->extcookie[0] == 0)
1215             cinfo->extcookie[0] = 1;
1216         }
1217       if (fwrite(cinfo->extcookie, 32, 1, fp) != 1)
1218         {
1219           fclose(fp);
1220           unlink(tmpl);
1221           free(tmpl);
1222           return;
1223         }
1224     }
1225   /* append our cookie describing the metadata state */
1226   if (fwrite(cookie, 32, 1, fp) != 1)
1227     {
1228       fclose(fp);
1229       unlink(tmpl);
1230       free(tmpl);
1231       return;
1232     }
1233   if (fclose(fp))
1234     {
1235       unlink(tmpl);
1236       free(tmpl);
1237       return;
1238     }
1239   if (onepiece)
1240     {
1241       /* switch to just saved repo to activate paging and save memory */
1242       FILE *fp = fopen(tmpl, "r");
1243       if (fp)
1244         {
1245           if (!repoext)
1246             {
1247               /* main repo */
1248               repo_empty(repo, 1);
1249               if (repo_add_solv(repo, fp, SOLV_ADD_NO_STUBS))
1250                 {
1251                   /* oops, no way to recover from here */
1252                   fprintf(stderr, "internal error\n");
1253                   exit(1);
1254                 }
1255             }
1256           else
1257             {
1258               int flags = REPO_USE_LOADING|REPO_EXTEND_SOLVABLES;
1259               /* make sure repodata contains complete repo */
1260               /* (this is how repodata_write saves it) */
1261               repodata_extend_block(info, repo->start, repo->end - repo->start);
1262               info->state = REPODATA_LOADING;
1263               if (strcmp(repoext, "DL") != 0)
1264                 flags |= REPO_LOCALPOOL;
1265               repo_add_solv(repo, fp, flags);
1266               info->state = REPODATA_AVAILABLE; /* in case the load failed */
1267             }
1268           fclose(fp);
1269         }
1270     }
1271   if (!rename(tmpl, calccachepath(repo, repoext)))
1272     unlink(tmpl);
1273   free(tmpl);
1274 }
1275
1276
1277 #ifdef ENABLE_RPMMD
1278 /* repomd helpers */
1279
1280 static inline const char *
1281 repomd_find(Repo *repo, const char *what, const unsigned char **chksump, Id *chksumtypep)
1282 {
1283   Pool *pool = repo->pool;
1284   Dataiterator di;
1285   const char *filename;
1286
1287   filename = 0;
1288   *chksump = 0;
1289   *chksumtypep = 0;
1290   dataiterator_init(&di, pool, repo, SOLVID_META, REPOSITORY_REPOMD_TYPE, what, SEARCH_STRING);
1291   dataiterator_prepend_keyname(&di, REPOSITORY_REPOMD);
1292   if (dataiterator_step(&di))
1293     {
1294       dataiterator_setpos_parent(&di);
1295       filename = pool_lookup_str(pool, SOLVID_POS, REPOSITORY_REPOMD_LOCATION);
1296       *chksump = pool_lookup_bin_checksum(pool, SOLVID_POS, REPOSITORY_REPOMD_CHECKSUM, chksumtypep);
1297     }
1298   dataiterator_free(&di);
1299   if (filename && !*chksumtypep)
1300     {
1301       printf("no %s file checksum!\n", what);
1302       filename = 0;
1303     }
1304   return filename;
1305 }
1306
1307 int
1308 repomd_add_ext(Repo *repo, Repodata *data, const char *what)
1309 {
1310   Id chksumtype, handle;
1311   const unsigned char *chksum;
1312   const char *filename;
1313
1314   filename = repomd_find(repo, what, &chksum, &chksumtype);
1315   if (!filename)
1316     return 0;
1317   if (!strcmp(what, "prestodelta"))
1318     what = "deltainfo";
1319   handle = repodata_new_handle(data);
1320   repodata_set_poolstr(data, handle, REPOSITORY_REPOMD_TYPE, what);
1321   repodata_set_str(data, handle, REPOSITORY_REPOMD_LOCATION, filename);
1322   repodata_set_bin_checksum(data, handle, REPOSITORY_REPOMD_CHECKSUM, chksumtype, chksum);
1323   if (!strcmp(what, "deltainfo"))
1324     {
1325       repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOSITORY_DELTAINFO);
1326       repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_FLEXARRAY);
1327     }
1328   if (!strcmp(what, "filelists"))
1329     {
1330       repodata_add_idarray(data, handle, REPOSITORY_KEYS, SOLVABLE_FILELIST);
1331       repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_DIRSTRARRAY);
1332     }
1333   repodata_add_flexarray(data, SOLVID_META, REPOSITORY_EXTERNAL, handle);
1334   return 1;
1335 }
1336
1337 int
1338 repomd_load_ext(Repo *repo, Repodata *data)
1339 {
1340   const char *filename, *repomdtype;
1341   char ext[3];
1342   FILE *fp;
1343   struct repoinfo *cinfo;
1344   const unsigned char *filechksum;
1345   Id filechksumtype;
1346   int r = 0;
1347
1348   cinfo = repo->appdata;
1349   repomdtype = repodata_lookup_str(data, SOLVID_META, REPOSITORY_REPOMD_TYPE);
1350   if (!repomdtype)
1351     return 0;
1352   if (!strcmp(repomdtype, "filelists"))
1353     strcpy(ext, "FL");
1354   else if (!strcmp(repomdtype, "deltainfo"))
1355     strcpy(ext, "DL");
1356   else
1357     return 0;
1358   printf("[%s:%s", repo->name, ext);
1359   if (usecachedrepo(repo, ext, cinfo->extcookie, 0))
1360     {
1361       printf(" cached]\n"); fflush(stdout);
1362       return 1;
1363     }
1364   printf(" fetching]\n"); fflush(stdout);
1365   filename = repodata_lookup_str(data, SOLVID_META, REPOSITORY_REPOMD_LOCATION);
1366   filechksumtype = 0;
1367   filechksum = repodata_lookup_bin_checksum(data, SOLVID_META, REPOSITORY_REPOMD_CHECKSUM, &filechksumtype);
1368   if ((fp = curlfopen(cinfo, filename, iscompressed(filename), filechksum, filechksumtype, 0)) == 0)
1369     return 0;
1370   if (!strcmp(ext, "FL"))
1371     r = repo_add_rpmmd(repo, fp, ext, REPO_USE_LOADING|REPO_EXTEND_SOLVABLES|REPO_LOCALPOOL);
1372   else if (!strcmp(ext, "DL"))
1373     r = repo_add_deltainfoxml(repo, fp, REPO_USE_LOADING);
1374   fclose(fp);
1375   if (r)
1376     {
1377       printf("%s\n", pool_errstr(repo->pool));
1378       return 0;
1379     }
1380   writecachedrepo(repo, data, ext, cinfo->extcookie);
1381   return 1;
1382 }
1383
1384 #endif
1385
1386
1387 #ifdef ENABLE_SUSEREPO
1388 /* susetags helpers */
1389
1390 static inline const char *
1391 susetags_find(Repo *repo, const char *what, const unsigned char **chksump, Id *chksumtypep)
1392 {
1393   Pool *pool = repo->pool;
1394   Dataiterator di;
1395   const char *filename;
1396
1397   filename = 0;
1398   *chksump = 0;
1399   *chksumtypep = 0;
1400   dataiterator_init(&di, pool, repo, SOLVID_META, SUSETAGS_FILE_NAME, what, SEARCH_STRING);
1401   dataiterator_prepend_keyname(&di, SUSETAGS_FILE);
1402   if (dataiterator_step(&di))
1403     {
1404       dataiterator_setpos_parent(&di);
1405       *chksump = pool_lookup_bin_checksum(pool, SOLVID_POS, SUSETAGS_FILE_CHECKSUM, chksumtypep);
1406       filename = what;
1407     }
1408   dataiterator_free(&di);
1409   if (filename && !*chksumtypep)
1410     {
1411       printf("no %s file checksum!\n", what);
1412       filename = 0;
1413     }
1414   return filename;
1415 }
1416
1417 static Id susetags_langtags[] = {
1418   SOLVABLE_SUMMARY, REPOKEY_TYPE_STR,
1419   SOLVABLE_DESCRIPTION, REPOKEY_TYPE_STR,
1420   SOLVABLE_EULA, REPOKEY_TYPE_STR,
1421   SOLVABLE_MESSAGEINS, REPOKEY_TYPE_STR,
1422   SOLVABLE_MESSAGEDEL, REPOKEY_TYPE_STR,
1423   SOLVABLE_CATEGORY, REPOKEY_TYPE_ID,
1424   0, 0
1425 };
1426
1427 void
1428 susetags_add_ext(Repo *repo, Repodata *data)
1429 {
1430   Pool *pool = repo->pool;
1431   Dataiterator di;
1432   char ext[3];
1433   Id handle, filechksumtype;
1434   const unsigned char *filechksum;
1435   int i;
1436
1437   dataiterator_init(&di, pool, repo, SOLVID_META, SUSETAGS_FILE_NAME, 0, 0);
1438   dataiterator_prepend_keyname(&di, SUSETAGS_FILE);
1439   while (dataiterator_step(&di))
1440     {
1441       if (strncmp(di.kv.str, "packages.", 9) != 0)
1442         continue;
1443       if (!strcmp(di.kv.str + 9, "gz"))
1444         continue;
1445       if (!di.kv.str[9] || !di.kv.str[10] || (di.kv.str[11] && di.kv.str[11] != '.'))
1446         continue;
1447       ext[0] = di.kv.str[9];
1448       ext[1] = di.kv.str[10];
1449       ext[2] = 0;
1450       if (!strcmp(ext, "en"))
1451         continue;
1452       if (!susetags_find(repo, di.kv.str, &filechksum, &filechksumtype))
1453         continue;
1454       handle = repodata_new_handle(data);
1455       repodata_set_str(data, handle, SUSETAGS_FILE_NAME, di.kv.str);
1456       if (filechksumtype)
1457         repodata_set_bin_checksum(data, handle, SUSETAGS_FILE_CHECKSUM, filechksumtype, filechksum);
1458       if (!strcmp(ext, "DU"))
1459         {
1460           repodata_add_idarray(data, handle, REPOSITORY_KEYS, SOLVABLE_DISKUSAGE);
1461           repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_DIRNUMNUMARRAY);
1462         }
1463       else if (!strcmp(ext, "FL"))
1464         {
1465           repodata_add_idarray(data, handle, REPOSITORY_KEYS, SOLVABLE_FILELIST);
1466           repodata_add_idarray(data, handle, REPOSITORY_KEYS, REPOKEY_TYPE_DIRSTRARRAY);
1467         }
1468       else
1469         {
1470           for (i = 0; susetags_langtags[i]; i += 2)
1471             {
1472               repodata_add_idarray(data, handle, REPOSITORY_KEYS, pool_id2langid(pool, susetags_langtags[i], ext, 1));
1473               repodata_add_idarray(data, handle, REPOSITORY_KEYS, susetags_langtags[i + 1]);
1474             }
1475         }
1476       repodata_add_flexarray(data, SOLVID_META, REPOSITORY_EXTERNAL, handle);
1477     }
1478   dataiterator_free(&di);
1479 }
1480
1481 int
1482 susetags_load_ext(Repo *repo, Repodata *data)
1483 {
1484   const char *filename, *descrdir;
1485   Id defvendor;
1486   char ext[3];
1487   FILE *fp;
1488   struct repoinfo *cinfo;
1489   const unsigned char *filechksum;
1490   Id filechksumtype;
1491   int flags;
1492
1493   cinfo = repo->appdata;
1494   filename = repodata_lookup_str(data, SOLVID_META, SUSETAGS_FILE_NAME);
1495   if (!filename)
1496     return 0;
1497   /* susetags load */
1498   ext[0] = filename[9];
1499   ext[1] = filename[10];
1500   ext[2] = 0;
1501   printf("[%s:%s", repo->name, ext);
1502   if (usecachedrepo(repo, ext, cinfo->extcookie, 0))
1503     {
1504       printf(" cached]\n"); fflush(stdout);
1505       return 1;
1506     }
1507   printf(" fetching]\n"); fflush(stdout);
1508   defvendor = repo_lookup_id(repo, SOLVID_META, SUSETAGS_DEFAULTVENDOR);
1509   descrdir = repo_lookup_str(repo, SOLVID_META, SUSETAGS_DESCRDIR);
1510   if (!descrdir)
1511     descrdir = "suse/setup/descr";
1512   filechksumtype = 0;
1513   filechksum = repodata_lookup_bin_checksum(data, SOLVID_META, SUSETAGS_FILE_CHECKSUM, &filechksumtype);
1514   if ((fp = curlfopen(cinfo, pool_tmpjoin(repo->pool, descrdir, "/", filename), iscompressed(filename), filechksum, filechksumtype, 0)) == 0)
1515     return 0;
1516   flags = REPO_USE_LOADING|REPO_EXTEND_SOLVABLES;
1517   if (strcmp(ext, "DL") != 0)
1518     flags |= REPO_LOCALPOOL;
1519   if (repo_add_susetags(repo, fp, defvendor, ext, flags))
1520     {
1521       fclose(fp);
1522       printf("%s\n", pool_errstr(repo->pool));
1523       return 0;
1524     }
1525   fclose(fp);
1526   writecachedrepo(repo, data, ext, cinfo->extcookie);
1527   return 1;
1528 }
1529 #endif
1530
1531
1532
1533 /* load callback */
1534
1535 int
1536 load_stub(Pool *pool, Repodata *data, void *dp)
1537 {
1538   struct repoinfo *cinfo = data->repo->appdata;
1539   switch (cinfo->type)
1540     {
1541 #ifdef ENABLE_SUSEREPO
1542     case TYPE_SUSETAGS:
1543       return susetags_load_ext(data->repo, data);
1544 #endif
1545 #ifdef ENABLE_RPMMD
1546     case TYPE_RPMMD:
1547       return repomd_load_ext(data->repo, data);
1548 #endif
1549     default:
1550       return 0;
1551     }
1552 }
1553
1554 static unsigned char installedcookie[32];
1555
1556 #ifdef ENABLE_DEBIAN
1557
1558 const char *
1559 debian_find_component(struct repoinfo *cinfo, FILE *fp, char *comp, const unsigned char **chksump, Id *chksumtypep)
1560 {
1561   char buf[4096];
1562   Id chksumtype;
1563   unsigned char *chksum;
1564   Id curchksumtype;
1565   int l, compl;
1566   char *ch, *fn, *bp;
1567   char *filename;
1568   static char *basearch;
1569   char *binarydir;
1570   int lbinarydir;
1571
1572   if (!basearch)
1573     {
1574       struct utsname un;
1575       if (uname(&un))
1576         {
1577           perror("uname");
1578           exit(1);
1579         }
1580       basearch = strdup(un.machine);
1581       if (basearch[0] == 'i' && basearch[1] && !strcmp(basearch + 2, "86"))
1582         basearch[1] = '3';
1583     }
1584   binarydir = solv_dupjoin("binary-", basearch, "/");
1585   lbinarydir = strlen(binarydir);
1586   compl = strlen(comp);
1587   rewind(fp);
1588   curchksumtype = 0;
1589   filename = 0;
1590   chksum = solv_malloc(32);
1591   chksumtype = 0;
1592   while(fgets(buf, sizeof(buf), fp))
1593     {
1594       l = strlen(buf);
1595       if (l == 0)
1596         continue;
1597       while (l && (buf[l - 1] == '\n' || buf[l - 1] == ' ' || buf[l - 1] == '\t'))
1598         buf[--l] = 0;
1599       if (!strncasecmp(buf, "MD5Sum:", 7))
1600         {
1601           curchksumtype = REPOKEY_TYPE_MD5;
1602           continue;
1603         }
1604       if (!strncasecmp(buf, "SHA1:", 5))
1605         {
1606           curchksumtype = REPOKEY_TYPE_SHA1;
1607           continue;
1608         }
1609       if (!strncasecmp(buf, "SHA256:", 7))
1610         {
1611           curchksumtype = REPOKEY_TYPE_SHA256;
1612           continue;
1613         }
1614       if (!curchksumtype)
1615         continue;
1616       bp = buf;
1617       if (*bp++ != ' ')
1618         {
1619           curchksumtype = 0;
1620           continue;
1621         }
1622       ch = bp;
1623       while (*bp && *bp != ' ' && *bp != '\t')
1624         bp++;
1625       if (!*bp)
1626         continue;
1627       *bp++ = 0;
1628       while (*bp == ' ' || *bp == '\t')
1629         bp++;
1630       while (*bp && *bp != ' ' && *bp != '\t')
1631         bp++;
1632       if (!*bp)
1633         continue;
1634       while (*bp == ' ' || *bp == '\t')
1635         bp++;
1636       fn = bp;
1637       if (strncmp(fn, comp, compl) != 0 || fn[compl] != '/')
1638         continue;
1639       bp += compl + 1;
1640       if (strncmp(bp, binarydir, lbinarydir))
1641         continue;
1642       bp += lbinarydir;
1643       if (!strcmp(bp, "Packages") || !strcmp(bp, "Packages.gz"))
1644         {
1645           unsigned char curchksum[32];
1646           int curl;
1647           if (filename && !strcmp(bp, "Packages"))
1648             continue;
1649           curl = solv_chksum_len(curchksumtype);
1650           if (!curl || (chksumtype && solv_chksum_len(chksumtype) > curl))
1651             continue;
1652           if (solv_hex2bin((const char **)&ch, curchksum, sizeof(curchksum)) != curl)
1653             continue;
1654           solv_free(filename);
1655           filename = strdup(fn);
1656           chksumtype = curchksumtype;
1657           memcpy(chksum, curchksum, curl);
1658         }
1659     }
1660   free(binarydir);
1661   if (filename)
1662     {
1663       fn = solv_dupjoin("/", filename, 0);
1664       solv_free(filename);
1665       filename = solv_dupjoin("dists/", cinfo->name, fn);
1666       solv_free(fn);
1667     }
1668   if (!chksumtype)
1669     chksum = solv_free(chksum);
1670   *chksump = chksum;
1671   *chksumtypep = chksumtype;
1672   return filename;
1673 }
1674 #endif
1675
1676 void
1677 read_repos(Pool *pool, struct repoinfo *repoinfos, int nrepoinfos)
1678 {
1679   Repo *repo;
1680   struct repoinfo *cinfo;
1681   int i;
1682   FILE *fp;
1683   const char *filename;
1684   const unsigned char *filechksum;
1685   Id filechksumtype;
1686 #ifdef ENABLE_SUSEREPO
1687   const char *descrdir;
1688   int defvendor;
1689 #endif
1690   struct stat stb;
1691   Pool *sigpool = 0;
1692 #if defined(ENABLE_SUSEREPO) || defined(ENABLE_RPMMD)
1693   Repodata *data;
1694 #endif
1695   int dorefresh;
1696 #if defined(ENABLE_DEBIAN)
1697   FILE *fpr;
1698   int j;
1699 #endif
1700
1701   repo = repo_create(pool, "@System");
1702 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
1703   printf("rpm database:");
1704   if (stat(pool_prepend_rootdir_tmp(pool, "/var/lib/rpm/Packages"), &stb))
1705     memset(&stb, 0, sizeof(stb));
1706 #endif
1707 #if defined(ENABLE_DEBIAN) && defined(DEBIAN)
1708   printf("dpgk database:");
1709   if (stat(pool_prepend_rootdir_tmp(pool, "/var/lib/dpkg/status"), &stb))
1710     memset(&stb, 0, sizeof(stb));
1711 #endif
1712 #ifdef NOSYSTEM
1713   printf("no installed database:");
1714   memset(&stb, 0, sizeof(stb));
1715 #endif
1716   calc_checksum_stat(&stb, REPOKEY_TYPE_SHA256, 0, installedcookie);
1717   if (usecachedrepo(repo, 0, installedcookie, 0))
1718     printf(" cached\n");
1719   else
1720     {
1721 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
1722       FILE *ofp;
1723       Repo *ref = 0;
1724 #endif
1725       printf(" reading\n");
1726
1727 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
1728 # if defined(ENABLE_SUSEREPO) && defined(PRODUCTS_PATH)
1729       if (repo_add_products(repo, PRODUCTS_PATH, REPO_NO_INTERNALIZE | REPO_USE_ROOTDIR))
1730         {
1731           fprintf(stderr, "product reading failed: %s\n", pool_errstr(pool));
1732           exit(1);
1733         }
1734 # endif
1735       if ((ofp = fopen(calccachepath(repo, 0), "r")) != 0)
1736         {
1737           ref = repo_create(pool, "@System.old");
1738           if (repo_add_solv(ref, ofp, 0))
1739             {
1740               repo_free(ref, 1);
1741               ref = 0;
1742             }
1743           fclose(ofp);
1744         }
1745       if (repo_add_rpmdb(repo, ref, REPO_REUSE_REPODATA | REPO_USE_ROOTDIR))
1746         {
1747           fprintf(stderr, "installed db: %s\n", pool_errstr(pool));
1748           exit(1);
1749         }
1750       if (ref)
1751         repo_free(ref, 1);
1752 #endif
1753 #if defined(ENABLE_DEBIAN) && defined(DEBIAN)
1754       if (repo_add_debdb(repo, REPO_REUSE_REPODATA | REPO_USE_ROOTDIR))
1755         {
1756           fprintf(stderr, "installed db: %s\n", pool_errstr(pool));
1757           exit(1);
1758         }
1759 #endif
1760       writecachedrepo(repo, 0, 0, installedcookie);
1761     }
1762   pool_set_installed(pool, repo);
1763
1764   for (i = 0; i < nrepoinfos; i++)
1765     {
1766       cinfo = repoinfos + i;
1767       if (!cinfo->enabled)
1768         continue;
1769
1770       repo = repo_create(pool, cinfo->alias);
1771       cinfo->repo = repo;
1772       repo->appdata = cinfo;
1773       repo->priority = 99 - cinfo->priority;
1774
1775       dorefresh = cinfo->autorefresh;
1776       if (dorefresh && cinfo->metadata_expire && stat(calccachepath(repo, 0), &stb) == 0)
1777         {
1778           if (cinfo->metadata_expire == -1 || time(0) - stb.st_mtime < cinfo->metadata_expire)
1779             dorefresh = 0;
1780         }
1781       if (!dorefresh && usecachedrepo(repo, 0, 0, 0))
1782         {
1783           printf("repo '%s':", cinfo->alias);
1784           printf(" cached\n");
1785           continue;
1786         }
1787       switch (cinfo->type)
1788         {
1789 #ifdef ENABLE_RPMMD
1790         case TYPE_RPMMD:
1791           printf("rpmmd repo '%s':", cinfo->alias);
1792           fflush(stdout);
1793           if ((fp = curlfopen(cinfo, "repodata/repomd.xml", 0, 0, 0, 0)) == 0)
1794             {
1795               printf(" no repomd.xml file, skipped\n");
1796               repo_free(repo, 1);
1797               cinfo->repo = 0;
1798               break;
1799             }
1800           calc_checksum_fp(fp, REPOKEY_TYPE_SHA256, cinfo->cookie);
1801           if (usecachedrepo(repo, 0, cinfo->cookie, 1))
1802             {
1803               printf(" cached\n");
1804               fclose(fp);
1805               break;
1806             }
1807           if (cinfo->repo_gpgcheck && !downloadchecksig(cinfo, fp, "repodata/repomd.xml.asc", &sigpool))
1808             {
1809               fclose(fp);
1810               break;
1811             }
1812           if (repo_add_repomdxml(repo, fp, 0))
1813             {
1814               printf("repomd.xml: %s\n", pool_errstr(pool));
1815               fclose(fp);
1816               break;    /* hopeless */
1817             }
1818           fclose(fp);
1819           printf(" fetching\n");
1820           filename = repomd_find(repo, "primary", &filechksum, &filechksumtype);
1821           if (filename && (fp = curlfopen(cinfo, filename, iscompressed(filename), filechksum, filechksumtype, 1)) != 0)
1822             {
1823               if (repo_add_rpmmd(repo, fp, 0, 0))
1824                 {
1825                   printf("primary: %s\n", pool_errstr(pool));
1826                   cinfo->incomplete = 1;
1827                 }
1828               fclose(fp);
1829             }
1830           if (cinfo->incomplete)
1831             break;      /* hopeless */
1832
1833           filename = repomd_find(repo, "updateinfo", &filechksum, &filechksumtype);
1834           if (filename && (fp = curlfopen(cinfo, filename, iscompressed(filename), filechksum, filechksumtype, 1)) != 0)
1835             {
1836               if (repo_add_updateinfoxml(repo, fp, 0))
1837                 {
1838                   printf("updateinfo: %s\n", pool_errstr(pool));
1839                   cinfo->incomplete = 1;
1840                 }
1841               fclose(fp);
1842             }
1843
1844           data = repo_add_repodata(repo, 0);
1845           if (!repomd_add_ext(repo, data, "deltainfo"))
1846             repomd_add_ext(repo, data, "prestodelta");
1847           repomd_add_ext(repo, data, "filelists");
1848           repodata_internalize(data);
1849           if (!cinfo->incomplete)
1850             writecachedrepo(repo, 0, 0, cinfo->cookie);
1851           repodata_create_stubs(repo_last_repodata(repo));
1852           break;
1853 #endif
1854
1855 #ifdef ENABLE_SUSEREPO
1856         case TYPE_SUSETAGS:
1857           printf("susetags repo '%s':", cinfo->alias);
1858           fflush(stdout);
1859           descrdir = 0;
1860           defvendor = 0;
1861           if ((fp = curlfopen(cinfo, "content", 0, 0, 0, 0)) == 0)
1862             {
1863               printf(" no content file, skipped\n");
1864               repo_free(repo, 1);
1865               cinfo->repo = 0;
1866               break;
1867             }
1868           calc_checksum_fp(fp, REPOKEY_TYPE_SHA256, cinfo->cookie);
1869           if (usecachedrepo(repo, 0, cinfo->cookie, 1))
1870             {
1871               printf(" cached\n");
1872               fclose(fp);
1873               break;
1874             }
1875           if (cinfo->repo_gpgcheck && !downloadchecksig(cinfo, fp, "content.asc", &sigpool))
1876             {
1877               fclose(fp);
1878               break;
1879             }
1880           if (repo_add_content(repo, fp, 0))
1881             {
1882               printf("content: %s\n", pool_errstr(pool));
1883               fclose(fp);
1884               break;    /* hopeless */
1885             }
1886           fclose(fp);
1887           defvendor = repo_lookup_id(repo, SOLVID_META, SUSETAGS_DEFAULTVENDOR);
1888           descrdir = repo_lookup_str(repo, SOLVID_META, SUSETAGS_DESCRDIR);
1889           if (!descrdir)
1890             descrdir = "suse/setup/descr";
1891           filename = susetags_find(repo, "packages.gz", &filechksum, &filechksumtype);
1892           if (!filename)
1893             filename = susetags_find(repo, "packages", &filechksum, &filechksumtype);
1894           if (!filename)
1895             {
1896               printf(" no packages file entry, skipped\n");
1897               break;
1898             }
1899           printf(" fetching\n");
1900           if ((fp = curlfopen(cinfo, pool_tmpjoin(pool, descrdir, "/", filename), iscompressed(filename), filechksum, filechksumtype, 1)) == 0)
1901             break;      /* hopeless */
1902           if (repo_add_susetags(repo, fp, defvendor, 0, REPO_NO_INTERNALIZE|SUSETAGS_RECORD_SHARES))
1903             {
1904               printf("packages: %s\n", pool_errstr(pool));
1905               fclose(fp);
1906               cinfo->incomplete = 1;
1907               break;    /* hopeless */
1908             }
1909           fclose(fp);
1910           /* add default language */
1911           filename = susetags_find(repo, "packages.en.gz", &filechksum, &filechksumtype);
1912           if (!filename)
1913             filename = susetags_find(repo, "packages.en", &filechksum, &filechksumtype);
1914           if (filename)
1915             {
1916               if ((fp = curlfopen(cinfo, pool_tmpjoin(pool, descrdir, "/", filename), iscompressed(filename), filechksum, filechksumtype, 1)) != 0)
1917                 {
1918                   if (repo_add_susetags(repo, fp, defvendor, 0, REPO_NO_INTERNALIZE|REPO_REUSE_REPODATA|REPO_EXTEND_SOLVABLES))
1919                     {
1920                       printf("packages.en: %s\n", pool_errstr(pool));
1921                       cinfo->incomplete = 1;
1922                     }
1923                   fclose(fp);
1924                 }
1925             }
1926           filename = susetags_find(repo, "patterns", &filechksum, &filechksumtype);
1927           if (filename)
1928             {
1929               if ((fp = curlfopen(cinfo, pool_tmpjoin(pool, descrdir, "/", filename), iscompressed(filename), filechksum, filechksumtype, 1)) != 0)
1930                 {
1931                   char pbuf[256];
1932                   while (fgets(pbuf, sizeof(pbuf), fp))
1933                     {
1934                       int l = strlen(pbuf);
1935                       FILE *fp2;
1936                       if (l && pbuf[l - 1] == '\n')
1937                         pbuf[--l] = 0;
1938                       if (!*pbuf || *pbuf == '.' || strchr(pbuf, '/') != 0)
1939                         continue;
1940                       filename = susetags_find(repo, pbuf, &filechksum, &filechksumtype);
1941                       if (filename && (fp2 = curlfopen(cinfo, pool_tmpjoin(pool, descrdir, "/", filename), iscompressed(filename), filechksum, filechksumtype, 1)) != 0)
1942                         {
1943                           if (repo_add_susetags(repo, fp2, defvendor, 0, REPO_NO_INTERNALIZE))
1944                             {
1945                               printf("%s: %s\n", pbuf, pool_errstr(pool));
1946                               cinfo->incomplete = 1;
1947                             }
1948                           fclose(fp2);
1949                         }
1950                     }
1951                   fclose(fp);
1952                 }
1953             }
1954           repo_internalize(repo);
1955           data = repo_add_repodata(repo, 0);
1956           susetags_add_ext(repo, data);
1957           repodata_internalize(data);
1958           if (!cinfo->incomplete)
1959             writecachedrepo(repo, 0, 0, cinfo->cookie);
1960           repodata_create_stubs(repo_last_repodata(repo));
1961           break;
1962 #endif
1963
1964 #if defined(ENABLE_DEBIAN)
1965         case TYPE_DEBIAN:
1966           printf("debian repo '%s':", cinfo->alias);
1967           fflush(stdout);
1968           filename = solv_dupjoin("dists/", cinfo->name, "/Release");
1969           if ((fpr = curlfopen(cinfo, filename, 0, 0, 0, 0)) == 0)
1970             {
1971               printf(" no Release file, skipped\n");
1972               repo_free(repo, 1);
1973               cinfo->repo = 0;
1974               free((char *)filename);
1975               break;
1976             }
1977           solv_free((char *)filename);
1978           if (cinfo->repo_gpgcheck)
1979             {
1980               filename = solv_dupjoin("dists/", cinfo->name, "/Release.gpg");
1981               if (!downloadchecksig(cinfo, fpr, filename, &sigpool))
1982                 {
1983                   fclose(fpr);
1984                   solv_free((char *)filename);
1985                   break;
1986                 }
1987               solv_free((char *)filename);
1988             }
1989           calc_checksum_fp(fpr, REPOKEY_TYPE_SHA256, cinfo->cookie);
1990           if (usecachedrepo(repo, 0, cinfo->cookie, 1))
1991             {
1992               printf(" cached\n");
1993               fclose(fpr);
1994               break;
1995             }
1996           printf(" fetching\n");
1997           for (j = 0; j < cinfo->ncomponents; j++)
1998             {
1999               if (!(filename = debian_find_component(cinfo, fpr, cinfo->components[j], &filechksum, &filechksumtype)))
2000                 {
2001                   printf("[component %s not found]\n", cinfo->components[j]);
2002                   continue;
2003                 }
2004               if ((fp = curlfopen(cinfo, filename, iscompressed(filename), filechksum, filechksumtype, 1)) != 0)
2005                 {
2006                   if (repo_add_debpackages(repo, fp, 0))
2007                     {
2008                       printf("component %s: %s\n", cinfo->components[j], pool_errstr(pool));
2009                       cinfo->incomplete = 1;
2010                     }
2011                   fclose(fp);
2012                 }
2013               solv_free((char *)filechksum);
2014               solv_free((char *)filename);
2015             }
2016           fclose(fpr);
2017           if (!cinfo->incomplete)
2018             writecachedrepo(repo, 0, 0, cinfo->cookie);
2019           break;
2020 #endif
2021
2022         default:
2023           printf("unsupported repo '%s': skipped\n", cinfo->alias);
2024           repo_free(repo, 1);
2025           cinfo->repo = 0;
2026           break;
2027         }
2028     }
2029   if (sigpool)
2030     pool_free(sigpool);
2031 }
2032
2033 int
2034 yesno(const char *str)
2035 {
2036   char inbuf[128], *ip;
2037
2038   for (;;)
2039     {
2040       printf("%s", str);
2041       fflush(stdout);
2042       *inbuf = 0;
2043       if (!(ip = fgets(inbuf, sizeof(inbuf), stdin)))
2044         {
2045           printf("Abort.\n");
2046           exit(1);
2047         }
2048       while (*ip == ' ' || *ip == '\t')
2049         ip++;
2050       if (*ip == 'q')
2051         {
2052           printf("Abort.\n");
2053           exit(1);
2054         }
2055       if (*ip == 'y' || *ip == 'n')
2056         return *ip == 'y' ? 1 : 0;
2057     }
2058 }
2059
2060 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
2061
2062 struct fcstate {
2063   FILE **newpkgsfps;
2064   Queue *checkq;
2065   int newpkgscnt;
2066   void *rpmdbstate;
2067 };
2068
2069 static void *
2070 fileconflict_cb(Pool *pool, Id p, void *cbdata)
2071 {
2072   struct fcstate *fcstate = cbdata;
2073   Solvable *s;
2074   Id rpmdbid;
2075   int i;
2076   FILE *fp;
2077
2078   if (!p)
2079     {
2080       rpm_byrpmdbid(0, 0, &fcstate->rpmdbstate);
2081       return 0;
2082     }
2083   s = pool_id2solvable(pool, p);
2084   if (pool->installed && s->repo == pool->installed)
2085     {
2086       if (!s->repo->rpmdbid)
2087         return 0;
2088       rpmdbid = s->repo->rpmdbid[p - s->repo->start];
2089       if (!rpmdbid)
2090         return 0;
2091        return rpm_byrpmdbid(rpmdbid, 0, &fcstate->rpmdbstate);
2092     }
2093   for (i = 0; i < fcstate->newpkgscnt; i++)
2094     if (fcstate->checkq->elements[i] == p)
2095       break;
2096   if (i == fcstate->newpkgscnt)
2097     return 0;
2098   fp = fcstate->newpkgsfps[i];
2099   if (!fp)
2100     return 0;
2101   rewind(fp);
2102   return rpm_byfp(fp, pool_solvable2str(pool, s), &fcstate->rpmdbstate);
2103 }
2104
2105
2106 void
2107 runrpm(const char *arg, const char *name, int dupfd3, const char *rootdir)
2108 {
2109   pid_t pid;
2110   int status;
2111
2112   if ((pid = fork()) == (pid_t)-1)
2113     {
2114       perror("fork");
2115       exit(1);
2116     }
2117   if (pid == 0)
2118     {
2119       if (!rootdir)
2120         rootdir = "/";
2121       if (dupfd3 != -1 && dupfd3 != 3)
2122         {
2123           dup2(dupfd3, 3);
2124           close(dupfd3);
2125         }
2126       if (dupfd3 != -1)
2127         fcntl(3, F_SETFD, 0);   /* clear CLOEXEC */
2128       if (strcmp(arg, "-e") == 0)
2129         execlp("rpm", "rpm", arg, "--nodeps", "--nodigest", "--nosignature", "--root", rootdir, name, (char *)0);
2130       else
2131         execlp("rpm", "rpm", arg, "--force", "--nodeps", "--nodigest", "--nosignature", "--root", rootdir, name, (char *)0);
2132       perror("rpm");
2133       _exit(0);
2134     }
2135   while (waitpid(pid, &status, 0) != pid)
2136     ;
2137   if (status)
2138     {
2139       printf("rpm failed\n");
2140       exit(1);
2141     }
2142 }
2143
2144 #endif
2145
2146 #if defined(ENABLE_DEBIAN) && defined(DEBIAN)
2147
2148 void
2149 rundpkg(const char *arg, const char *name, int dupfd3, const char *rootdir)
2150 {
2151   pid_t pid;
2152   int status;
2153
2154   if ((pid = fork()) == (pid_t)-1)
2155     {
2156       perror("fork");
2157       exit(1);
2158     }
2159   if (pid == 0)
2160     {
2161       if (!rootdir)
2162         rootdir = "/";
2163       if (dupfd3 != -1 && dupfd3 != 3)
2164         {
2165           dup2(dupfd3, 3);
2166           close(dupfd3);
2167         }
2168       if (dupfd3 != -1)
2169         fcntl(3, F_SETFD, 0);   /* clear CLOEXEC */
2170       if (strcmp(arg, "--install") == 0)
2171         execlp("dpkg", "dpkg", "--install", "--root", rootdir, "--force", "all", name, (char *)0);
2172       else
2173         execlp("dpkg", "dpkg", "--remove", "--root", rootdir, "--force", "all", name, (char *)0);
2174       perror("dpkg");
2175       _exit(0);
2176     }
2177   while (waitpid(pid, &status, 0) != pid)
2178     ;
2179   if (status)
2180     {
2181       printf("dpkg failed\n");
2182       exit(1);
2183     }
2184 }
2185
2186 #endif
2187
2188 #ifdef SUSE
2189 static Id
2190 nscallback(Pool *pool, void *data, Id name, Id evr)
2191 {
2192   if (name == NAMESPACE_PRODUCTBUDDY)
2193     {
2194       /* SUSE specific hack: each product has an associated rpm */
2195       Solvable *s = pool->solvables + evr;
2196       Id p, pp, cap;
2197       Id bestp = 0;
2198
2199       cap = pool_str2id(pool, pool_tmpjoin(pool, "product(", pool_id2str(pool, s->name) + 8, ")"), 0);
2200       if (!cap)
2201         return 0;
2202       cap = pool_rel2id(pool, cap, s->evr, REL_EQ, 0);
2203       if (!cap)
2204         return 0;
2205       FOR_PROVIDES(p, pp, cap)
2206         {
2207           Solvable *ps = pool->solvables + p;
2208           if (ps->repo == s->repo && ps->arch == s->arch)
2209             if (!bestp || pool_evrcmp(pool, pool->solvables[bestp].evr, ps->evr, EVRCMP_COMPARE) < 0)
2210               bestp = p;
2211         }
2212       return bestp;
2213     }
2214 #if 0
2215   if (name == NAMESPACE_LANGUAGE)
2216     {
2217       if (!strcmp(pool_id2str(pool, evr), "ja"))
2218         return 1;
2219       if (!strcmp(pool_id2str(pool, evr), "de"))
2220         return 1;
2221       if (!strcmp(pool_id2str(pool, evr), "en"))
2222         return 1;
2223       if (!strcmp(pool_id2str(pool, evr), "en_US"))
2224         return 1;
2225     }
2226 #endif
2227   return 0;
2228 }
2229 #endif
2230
2231 #ifdef SOFTLOCKS_PATH
2232 void
2233 addsoftlocks(Pool *pool, Queue *job)
2234 {
2235   FILE *fp;
2236   Id type, id, p, pp;
2237   char *bp, *ep, buf[4096];
2238
2239   if ((fp = fopen(SOFTLOCKS_PATH, "r")) == 0)
2240     return;
2241   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
2242     {
2243       while (*bp == ' ' || *bp == '\t')
2244         bp++;
2245       if (!*bp || *bp == '#')
2246         continue;
2247       for (ep = bp; *ep; ep++)
2248         if (*ep == ' ' || *ep == '\t' || *ep == '\n')
2249           break;
2250       *ep = 0;
2251       type = SOLVER_SOLVABLE_NAME;
2252       if (!strncmp(bp, "provides:", 9) && bp[9])
2253         {
2254           type = SOLVER_SOLVABLE_PROVIDES;
2255           bp += 9;
2256         }
2257       id = pool_str2id(pool, bp, 1);
2258       if (pool->installed)
2259         {
2260           FOR_JOB_SELECT(p, pp, type, id)
2261             if (pool->solvables[p].repo == pool->installed)
2262               break;
2263           if (p)
2264             continue;   /* ignore, as it is already installed */
2265         }
2266       queue_push2(job, SOLVER_LOCK|SOLVER_WEAK|type, id);
2267     }
2268   fclose(fp);
2269 }
2270 #endif
2271
2272
2273 #if defined(ENABLE_RPMDB)
2274
2275 static void
2276 rewrite_repos(Pool *pool, Queue *addedfileprovides, Queue *addedfileprovides_inst)
2277 {
2278   Repo *repo;
2279   Repodata *data;
2280   Map providedids;
2281   Queue fileprovidesq;
2282   int i, j, n;
2283   struct repoinfo *cinfo;
2284
2285   map_init(&providedids, pool->ss.nstrings);
2286   queue_init(&fileprovidesq);
2287   for (i = 0; i < addedfileprovides->count; i++)
2288     MAPSET(&providedids, addedfileprovides->elements[i]);
2289   FOR_REPOS(i, repo)
2290     {
2291       /* make sure all repodatas but the first are extensions */
2292       if (repo->nrepodata < 2)
2293         continue;
2294       cinfo = repo->appdata;
2295       if (cinfo && cinfo->incomplete)
2296         continue;
2297       data = repo_id2repodata(repo, 1);
2298       if (data->loadcallback)
2299         continue;
2300       for (j = 2; j < repo->nrepodata; j++)
2301         {
2302           Repodata *edata = repo_id2repodata(repo, j);
2303           if (!edata->loadcallback)
2304             break;
2305         }
2306       if (j < repo->nrepodata)
2307         continue;       /* found a non-externsion repodata, can't rewrite  */
2308       if (repodata_lookup_idarray(data, SOLVID_META, REPOSITORY_ADDEDFILEPROVIDES, &fileprovidesq))
2309         {
2310           if (repo == pool->installed && addedfileprovides_inst)
2311             {
2312               for (j = 0; j < addedfileprovides->count; j++)
2313                 MAPCLR(&providedids, addedfileprovides->elements[j]);
2314               for (j = 0; j < addedfileprovides_inst->count; j++)
2315                 MAPSET(&providedids, addedfileprovides_inst->elements[j]);
2316             }
2317           n = 0;
2318           for (j = 0; j < fileprovidesq.count; j++)
2319             if (MAPTST(&providedids, fileprovidesq.elements[j]))
2320               n++;
2321           if (repo == pool->installed && addedfileprovides_inst)
2322             {
2323               for (j = 0; j < addedfileprovides_inst->count; j++)
2324                 MAPCLR(&providedids, addedfileprovides_inst->elements[j]);
2325               for (j = 0; j < addedfileprovides->count; j++)
2326                 MAPSET(&providedids, addedfileprovides->elements[j]);
2327               if (n == addedfileprovides_inst->count)
2328                 continue;       /* nothing new added */
2329             }
2330           else if (n == addedfileprovides->count)
2331             continue;   /* nothing new added */
2332         }
2333       repodata_set_idarray(data, SOLVID_META, REPOSITORY_ADDEDFILEPROVIDES, repo == pool->installed && addedfileprovides_inst ? addedfileprovides_inst : addedfileprovides);
2334       repodata_internalize(data);
2335       writecachedrepo(repo, data, 0, cinfo ? cinfo->cookie : installedcookie);
2336     }
2337   queue_free(&fileprovidesq);
2338   map_free(&providedids);
2339 }
2340
2341 static void
2342 addfileprovides(Pool *pool)
2343 {
2344   Queue addedfileprovides;
2345   Queue addedfileprovides_inst;
2346
2347   queue_init(&addedfileprovides);
2348   queue_init(&addedfileprovides_inst);
2349   pool_addfileprovides_queue(pool, &addedfileprovides, &addedfileprovides_inst);
2350   if (addedfileprovides.count || addedfileprovides_inst.count)
2351     rewrite_repos(pool, &addedfileprovides, &addedfileprovides_inst);
2352   queue_free(&addedfileprovides);
2353   queue_free(&addedfileprovides_inst);
2354 }
2355
2356 #endif
2357
2358 #if defined(SUSE) || defined(FEDORA)
2359 static void
2360 add_patchjobs(Pool *pool, Queue *job)
2361 {
2362   Id p, pp;
2363   int pruneyou = 0;
2364   Map installedmap, multiversionmap;
2365   Solvable *s;
2366
2367   map_init(&multiversionmap, 0);
2368   map_init(&installedmap, pool->nsolvables);
2369   solver_calculate_multiversionmap(pool, job, &multiversionmap);
2370   if (pool->installed)
2371     FOR_REPO_SOLVABLES(pool->installed, p, s)
2372       MAPSET(&installedmap, p);
2373
2374   /* install all patches */
2375   for (p = 1; p < pool->nsolvables; p++)
2376     {
2377       const char *type;
2378       int r;
2379       Id p2;
2380
2381       s = pool->solvables + p;
2382       if (strncmp(pool_id2str(pool, s->name), "patch:", 6) != 0)
2383         continue;
2384       FOR_PROVIDES(p2, pp, s->name)
2385         {
2386           Solvable *s2 = pool->solvables + p2;
2387           if (s2->name != s->name)
2388             continue;
2389           r = pool_evrcmp(pool, s->evr, s2->evr, EVRCMP_COMPARE);
2390           if (r < 0 || (r == 0 && p > p2))
2391             break;
2392         }
2393       if (p2)
2394         continue;
2395       type = solvable_lookup_str(s, SOLVABLE_PATCHCATEGORY);
2396       if (type && !strcmp(type, "optional"))
2397         continue;
2398       r = solvable_trivial_installable_map(s, &installedmap, 0, &multiversionmap);
2399       if (r == -1)
2400         continue;
2401       if (solvable_lookup_bool(s, UPDATE_RESTART) && r == 0)
2402         {
2403           if (!pruneyou++)
2404             queue_empty(job);
2405         }
2406       else if (pruneyou)
2407         continue;
2408       queue_push2(job, SOLVER_SOLVABLE, p);
2409     }
2410   map_free(&installedmap);
2411   map_free(&multiversionmap);
2412 }
2413 #endif
2414
2415 #ifdef SUSE
2416 static void
2417 showdiskusagechanges(Transaction *trans)
2418 {
2419   DUChanges duc[4];
2420   int i;
2421
2422   /* XXX: use mountpoints here */
2423   duc[0].path = "/";
2424   duc[1].path = "/usr/share/man";
2425   duc[2].path = "/sbin";
2426   duc[3].path = "/etc";
2427   transaction_calc_duchanges(trans, duc, 4);
2428   for (i = 0; i < 4; i++)
2429     printf("duchanges %s: %d K  %d inodes\n", duc[i].path, duc[i].kbytes, duc[i].files);
2430 }
2431 #endif
2432
2433 #if defined(ENABLE_RPMDB)
2434 static FILE *
2435 trydeltadownload(Solvable *s, struct repoinfo *cinfo, const char *loc)
2436 {
2437   Pool *pool = s->repo->pool;
2438   Dataiterator di;
2439   Id pp;
2440   const unsigned char *chksum;
2441   Id chksumtype;
2442   FILE *retfp = 0;
2443   char *matchname = strdup(pool_id2str(pool, s->name));
2444
2445   dataiterator_init(&di, pool, s->repo, SOLVID_META, DELTA_PACKAGE_NAME, matchname, SEARCH_STRING);
2446   dataiterator_prepend_keyname(&di, REPOSITORY_DELTAINFO);
2447   while (dataiterator_step(&di))
2448     {
2449       Id baseevr, op;
2450
2451       dataiterator_setpos_parent(&di);
2452       if (pool_lookup_id(pool, SOLVID_POS, DELTA_PACKAGE_EVR) != s->evr ||
2453           pool_lookup_id(pool, SOLVID_POS, DELTA_PACKAGE_ARCH) != s->arch)
2454         continue;
2455       baseevr = pool_lookup_id(pool, SOLVID_POS, DELTA_BASE_EVR);
2456       FOR_PROVIDES(op, pp, s->name)
2457         {
2458           Solvable *os = pool->solvables + op;
2459           if (os->repo == pool->installed && os->name == s->name && os->arch == s->arch && os->evr == baseevr)
2460             break;
2461         }
2462       if (op && access("/usr/bin/applydeltarpm", X_OK) == 0)
2463         {
2464           /* base is installed, run sequence check */
2465           const char *seq;
2466           const char *dloc;
2467           const char *archstr;
2468           FILE *fp;
2469           char cmd[128];
2470           int newfd;
2471
2472           archstr = pool_id2str(pool, s->arch);
2473           if (strlen(archstr) > 10 || strchr(archstr, '\'') != 0)
2474             continue;
2475
2476           seq = pool_tmpjoin(pool, pool_lookup_str(pool, SOLVID_POS, DELTA_SEQ_NAME), "-", pool_lookup_str(pool, SOLVID_POS, DELTA_SEQ_EVR));
2477           seq = pool_tmpappend(pool, seq, "-", pool_lookup_str(pool, SOLVID_POS, DELTA_SEQ_NUM));
2478           if (strchr(seq, '\'') != 0)
2479             continue;
2480 #ifdef FEDORA
2481           sprintf(cmd, "/usr/bin/applydeltarpm -a '%s' -c -s '", archstr);
2482 #else
2483           sprintf(cmd, "/usr/bin/applydeltarpm -c -s '");
2484 #endif
2485           if (system(pool_tmpjoin(pool, cmd, seq, "'")) != 0)
2486             continue;   /* didn't match */
2487           /* looks good, download delta */
2488           chksumtype = 0;
2489           chksum = pool_lookup_bin_checksum(pool, SOLVID_POS, DELTA_CHECKSUM, &chksumtype);
2490           if (!chksumtype)
2491             continue;   /* no way! */
2492           dloc = pool_lookup_deltalocation(pool, SOLVID_POS, 0);
2493           if (!dloc)
2494             continue;
2495 #ifdef ENABLE_SUSEREPO
2496           if (cinfo->type == TYPE_SUSETAGS)
2497             {
2498               const char *datadir = repo_lookup_str(cinfo->repo, SOLVID_META, SUSETAGS_DATADIR);
2499               dloc = pool_tmpjoin(pool, datadir ? datadir : "suse", "/", dloc);
2500             }
2501 #endif
2502           if ((fp = curlfopen(cinfo, dloc, 0, chksum, chksumtype, 0)) == 0)
2503             continue;
2504           /* got it, now reconstruct */
2505           newfd = opentmpfile();
2506 #ifdef FEDORA
2507           sprintf(cmd, "applydeltarpm -a '%s' /dev/fd/%d /dev/fd/%d", archstr, fileno(fp), newfd);
2508 #else
2509           sprintf(cmd, "applydeltarpm /dev/fd/%d /dev/fd/%d", fileno(fp), newfd);
2510 #endif
2511           fcntl(fileno(fp), F_SETFD, 0);
2512           if (system(cmd))
2513             {
2514               close(newfd);
2515               fclose(fp);
2516               continue;
2517             }
2518           lseek(newfd, 0, SEEK_SET);
2519           chksumtype = 0;
2520           chksum = solvable_lookup_bin_checksum(s, SOLVABLE_CHECKSUM, &chksumtype);
2521           if (chksumtype && !verify_checksum(newfd, loc, chksum, chksumtype))
2522             {
2523               close(newfd);
2524               fclose(fp);
2525               continue;
2526             }
2527           retfp = fdopen(newfd, "r");
2528           fclose(fp);
2529           break;
2530         }
2531     }
2532   dataiterator_free(&di);
2533   solv_free(matchname);
2534   return retfp;
2535 }
2536 #endif
2537
2538
2539 #define MODE_LIST        0
2540 #define MODE_INSTALL     1
2541 #define MODE_ERASE       2
2542 #define MODE_UPDATE      3
2543 #define MODE_DISTUPGRADE 4
2544 #define MODE_VERIFY      5
2545 #define MODE_PATCH       6
2546 #define MODE_INFO        7
2547 #define MODE_REPOLIST    8
2548 #define MODE_SEARCH      9
2549
2550 void
2551 usage(int r)
2552 {
2553   fprintf(stderr, "Usage: solv COMMAND <select>\n");
2554   fprintf(stderr, "\n");
2555   fprintf(stderr, "    dist-upgrade: replace installed packages with\n");
2556   fprintf(stderr, "                  versions from the repositories\n");
2557   fprintf(stderr, "    erase:        erase installed packages\n");
2558   fprintf(stderr, "    info:         display package information\n");
2559   fprintf(stderr, "    install:      install packages\n");
2560   fprintf(stderr, "    list:         list packages\n");
2561   fprintf(stderr, "    repos:        list enabled repositories\n");
2562   fprintf(stderr, "    search:       search name/summary/description\n");
2563   fprintf(stderr, "    update:       update installed packages\n");
2564   fprintf(stderr, "    verify:       check dependencies of installed packages\n");
2565 #if defined(SUSE) || defined(FEDORA)
2566   fprintf(stderr, "    patch:        install newest patches\n");
2567 #endif
2568   fprintf(stderr, "\n");
2569   exit(r);
2570 }
2571
2572 int
2573 main(int argc, char **argv)
2574 {
2575   Pool *pool;
2576   Repo *commandlinerepo = 0;
2577   Id *commandlinepkgs = 0;
2578   Id p;
2579   struct repoinfo *repoinfos;
2580   int nrepoinfos = 0;
2581   int mainmode = 0, mode = 0;
2582   int i, newpkgs;
2583   Queue job, checkq;
2584   Solver *solv = 0;
2585   Transaction *trans;
2586   FILE **newpkgsfps;
2587   Queue repofilter;
2588   int cleandeps = 0;
2589   int forcebest = 0;
2590   char *rootdir = 0;
2591
2592   argc--;
2593   argv++;
2594   if (!argv[0])
2595     usage(1);
2596   if (!strcmp(argv[0], "install") || !strcmp(argv[0], "in"))
2597     {
2598       mainmode = MODE_INSTALL;
2599       mode = SOLVER_INSTALL;
2600     }
2601 #if defined(SUSE) || defined(FEDORA)
2602   else if (!strcmp(argv[0], "patch"))
2603     {
2604       mainmode = MODE_PATCH;
2605       mode = SOLVER_INSTALL;
2606     }
2607 #endif
2608   else if (!strcmp(argv[0], "erase") || !strcmp(argv[0], "rm"))
2609     {
2610       mainmode = MODE_ERASE;
2611       mode = SOLVER_ERASE;
2612     }
2613   else if (!strcmp(argv[0], "list"))
2614     {
2615       mainmode = MODE_LIST;
2616       mode = 0;
2617     }
2618   else if (!strcmp(argv[0], "info"))
2619     {
2620       mainmode = MODE_INFO;
2621       mode = 0;
2622     }
2623   else if (!strcmp(argv[0], "search") || !strcmp(argv[0], "se"))
2624     {
2625       mainmode = MODE_SEARCH;
2626       mode = 0;
2627     }
2628   else if (!strcmp(argv[0], "verify"))
2629     {
2630       mainmode = MODE_VERIFY;
2631       mode = SOLVER_VERIFY;
2632     }
2633   else if (!strcmp(argv[0], "update") || !strcmp(argv[0], "up"))
2634     {
2635       mainmode = MODE_UPDATE;
2636       mode = SOLVER_UPDATE;
2637     }
2638   else if (!strcmp(argv[0], "dist-upgrade") || !strcmp(argv[0], "dup"))
2639     {
2640       mainmode = MODE_DISTUPGRADE;
2641       mode = SOLVER_DISTUPGRADE;
2642     }
2643   else if (!strcmp(argv[0], "repos") || !strcmp(argv[0], "repolist") || !strcmp(argv[0], "lr"))
2644     {
2645       mainmode = MODE_REPOLIST;
2646       mode = 0;
2647     }
2648   else
2649     usage(1);
2650
2651   for (;;)
2652     {
2653       if (argc > 2 && !strcmp(argv[1], "--root"))
2654         {
2655           rootdir = argv[2];
2656           argc -= 2;
2657           argv += 2;
2658         }
2659
2660       else if (argc > 1 && !strcmp(argv[1], "--clean"))
2661         {
2662           cleandeps = 1;
2663           argc--;
2664           argv++;
2665         }
2666       else if (argc > 1 && !strcmp(argv[1], "--best"))
2667         {
2668           forcebest = 1;
2669           argc--;
2670           argv++;
2671         }
2672       else
2673         break;
2674     }
2675
2676   pool = pool_create();
2677   pool_set_rootdir(pool, rootdir);
2678
2679 #if 0
2680   {
2681     const char *langs[] = {"de_DE", "de", "en"};
2682     pool_set_languages(pool, langs, sizeof(langs)/sizeof(*langs));
2683   }
2684 #endif
2685
2686   pool_setloadcallback(pool, load_stub, 0);
2687 #ifdef SUSE
2688   pool->nscallback = nscallback;
2689 #endif
2690   // pool_setdebuglevel(pool, 2);
2691   setarch(pool);
2692   repoinfos = read_repoinfos(pool, &nrepoinfos);
2693
2694   if (mainmode == MODE_REPOLIST)
2695     {
2696       int j = 1;
2697       for (i = 0; i < nrepoinfos; i++)
2698         {
2699           struct repoinfo *cinfo = repoinfos + i;
2700           if (!cinfo->enabled)
2701             continue;
2702           printf("%d: %-20s %s (prio %d)\n", j++, cinfo->alias, cinfo->name, cinfo->priority);
2703         }
2704       exit(0);
2705     }
2706
2707   read_repos(pool, repoinfos, nrepoinfos);
2708
2709   /* setup repofilter */
2710   queue_init(&repofilter);
2711   while (argc > 2 && !strcmp(argv[1], "-r"))
2712     {
2713       const char *rname = argv[2], *rp;
2714       Id repoid = 0;
2715       for (rp = rname; *rp; rp++)
2716         if (*rp <= '0' || *rp >= '9')
2717           break;
2718       if (!*rp)
2719         {
2720           /* repo specified by number */
2721           int rnum = atoi(rname);
2722           for (i = 0; i < nrepoinfos; i++)
2723             {
2724               struct repoinfo *cinfo = repoinfos + i;
2725               if (!cinfo->enabled)
2726                 continue;
2727               if (--rnum == 0)
2728                 repoid = cinfo->repo->repoid;
2729             }
2730         }
2731       else
2732         {
2733           /* repo specified by alias */
2734           Repo *repo;
2735           FOR_REPOS(i, repo)
2736             {
2737               if (!strcasecmp(rname, repo->name))
2738                 repoid = repo->repoid;
2739             }
2740         }
2741       if (!repoid)
2742         {
2743           fprintf(stderr, "%s: no such repo\n", rname);
2744           exit(1);
2745         }
2746       /* SETVENDOR is actually wrong but useful */
2747       queue_push2(&repofilter, SOLVER_SOLVABLE_REPO | SOLVER_SETREPO | SOLVER_SETVENDOR, repoid);
2748       argc -= 2;
2749       argv += 2;
2750     }
2751
2752   if (mainmode == MODE_SEARCH)
2753     {
2754       Queue sel, q;
2755       Dataiterator di;
2756       if (argc != 2)
2757         usage(1);
2758       pool_createwhatprovides(pool);
2759       queue_init(&sel);
2760       dataiterator_init(&di, pool, 0, 0, 0, argv[1], SEARCH_SUBSTRING|SEARCH_NOCASE);
2761       dataiterator_set_keyname(&di, SOLVABLE_NAME);
2762       dataiterator_set_search(&di, 0, 0);
2763       while (dataiterator_step(&di))
2764         queue_push2(&sel, SOLVER_SOLVABLE, di.solvid);
2765       dataiterator_set_keyname(&di, SOLVABLE_SUMMARY);
2766       dataiterator_set_search(&di, 0, 0);
2767       while (dataiterator_step(&di))
2768         queue_push2(&sel, SOLVER_SOLVABLE, di.solvid);
2769       dataiterator_set_keyname(&di, SOLVABLE_DESCRIPTION);
2770       dataiterator_set_search(&di, 0, 0);
2771       while (dataiterator_step(&di))
2772         queue_push2(&sel, SOLVER_SOLVABLE, di.solvid);
2773       dataiterator_free(&di);
2774       if (repofilter.count)
2775         selection_filter(pool, &sel, &repofilter);
2776         
2777       queue_init(&q);
2778       selection_solvables(pool, &sel, &q);
2779       queue_free(&sel);
2780       for (i = 0; i < q.count; i++)
2781         {
2782           Solvable *s = pool_id2solvable(pool, q.elements[i]);
2783           printf("  - %s [%s]: %s\n", pool_solvable2str(pool, s), s->repo->name, solvable_lookup_str(s, SOLVABLE_SUMMARY));
2784         }
2785       queue_free(&q);
2786       exit(0);
2787     }
2788
2789   /* process command line packages */
2790   if (mainmode == MODE_LIST || mainmode == MODE_INSTALL)
2791     {
2792       for (i = 1; i < argc; i++)
2793         {
2794           int l;
2795           l = strlen(argv[i]);
2796 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
2797           if (l <= 4 || strcmp(argv[i] + l - 4, ".rpm"))
2798             continue;
2799 #endif
2800 #if defined(ENABLE_DEBIAN) && defined(DEBIAN)
2801           if (l <= 4 || strcmp(argv[i] + l - 4, ".deb"))
2802             continue;
2803 #endif
2804           if (access(argv[i], R_OK))
2805             {
2806               perror(argv[i]);
2807               exit(1);
2808             }
2809           if (!commandlinepkgs)
2810             commandlinepkgs = solv_calloc(argc, sizeof(Id));
2811           if (!commandlinerepo)
2812             commandlinerepo = repo_create(pool, "@commandline");
2813           p = 0;
2814 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
2815           p = repo_add_rpm(commandlinerepo, (const char *)argv[i], REPO_REUSE_REPODATA|REPO_NO_INTERNALIZE);
2816 #endif
2817 #if defined(ENABLE_DEBIAN) && defined(DEBIAN)
2818           p = repo_add_deb(commandlinerepo, (const char *)argv[i], REPO_REUSE_REPODATA|REPO_NO_INTERNALIZE);
2819 #endif
2820           if (!p)
2821             {
2822               fprintf(stderr, "could not add '%s'\n", argv[i]);
2823               exit(1);
2824             }
2825           commandlinepkgs[i] = p;
2826         }
2827       if (commandlinerepo)
2828         repo_internalize(commandlinerepo);
2829     }
2830
2831   // FOR_REPOS(i, repo)
2832   //   printf("%s: %d solvables\n", repo->name, repo->nsolvables);
2833
2834 #if defined(ENABLE_RPMDB)
2835   addfileprovides(pool);
2836 #endif
2837   pool_createwhatprovides(pool);
2838
2839   queue_init(&job);
2840   for (i = 1; i < argc; i++)
2841     {
2842       Queue job2;
2843       int j, flags, rflags;
2844
2845       if (commandlinepkgs && commandlinepkgs[i])
2846         {
2847           queue_push2(&job, SOLVER_SOLVABLE, commandlinepkgs[i]);
2848           continue;
2849         }
2850       queue_init(&job2);
2851       flags = SELECTION_NAME|SELECTION_PROVIDES|SELECTION_GLOB;
2852       flags |= SELECTION_CANON|SELECTION_DOTARCH|SELECTION_REL;
2853       if (mode == MODE_LIST)
2854         flags |= SELECTION_WITH_SOURCE;
2855       if (argv[i][0] == '/')
2856         flags |= SELECTION_FILELIST | (mode == MODE_ERASE ? SELECTION_INSTALLED_ONLY : 0);
2857       rflags = selection_make(pool, &job2, argv[i], flags);
2858       if (repofilter.count)
2859         selection_filter(pool, &job2, &repofilter);
2860       if (!job2.count)
2861         {
2862           flags |= SELECTION_NOCASE;
2863           rflags = selection_make(pool, &job2, argv[i], flags);
2864           if (repofilter.count)
2865             selection_filter(pool, &job2, &repofilter);
2866           if (job2.count)
2867             printf("[ignoring case for '%s']\n", argv[i]);
2868         }
2869       if (!job2.count)
2870         {
2871           fprintf(stderr, "nothing matches '%s'\n", argv[i]);
2872           exit(1);
2873         }
2874       if (rflags & SELECTION_FILELIST)
2875         printf("[using file list match for '%s']\n", argv[i]);
2876       if (rflags & SELECTION_PROVIDES)
2877         printf("[using capability match for '%s']\n", argv[i]);
2878       for (j = 0; j < job2.count; j++)
2879         queue_push(&job, job2.elements[j]);
2880       queue_free(&job2);
2881     }
2882
2883   if (!job.count && (mainmode == MODE_UPDATE || mainmode == MODE_DISTUPGRADE || mainmode == MODE_VERIFY || repofilter.count))
2884     {
2885       queue_push2(&job, SOLVER_SOLVABLE_ALL, 0);
2886       if (repofilter.count)
2887         selection_filter(pool, &job, &repofilter);
2888     }
2889   queue_free(&repofilter);
2890
2891   if (!job.count && mainmode != MODE_PATCH)
2892     {
2893       printf("no package matched\n");
2894       exit(1);
2895     }
2896
2897   if (mainmode == MODE_LIST || mainmode == MODE_INFO)
2898     {
2899       /* list mode, no solver needed */
2900       Queue q;
2901       queue_init(&q);
2902       for (i = 0; i < job.count; i += 2)
2903         {
2904           int j;
2905           queue_empty(&q);
2906           pool_job2solvables(pool, &q, job.elements[i], job.elements[i + 1]);
2907           for (j = 0; j < q.count; j++)
2908             {
2909               Solvable *s = pool_id2solvable(pool, q.elements[j]);
2910               if (mainmode == MODE_INFO)
2911                 {
2912                   const char *str;
2913                   printf("Name:        %s\n", pool_solvable2str(pool, s));
2914                   printf("Repo:        %s\n", s->repo->name);
2915                   printf("Summary:     %s\n", solvable_lookup_str(s, SOLVABLE_SUMMARY));
2916                   str = solvable_lookup_str(s, SOLVABLE_URL);
2917                   if (str)
2918                     printf("Url:         %s\n", str);
2919                   str = solvable_lookup_str(s, SOLVABLE_LICENSE);
2920                   if (str)
2921                     printf("License:     %s\n", str);
2922                   printf("Description:\n%s\n", solvable_lookup_str(s, SOLVABLE_DESCRIPTION));
2923                   printf("\n");
2924                 }
2925               else
2926                 {
2927 #if 1
2928                   const char *sum = solvable_lookup_str_lang(s, SOLVABLE_SUMMARY, "de", 1);
2929 #else
2930                   const char *sum = solvable_lookup_str_poollang(s, SOLVABLE_SUMMARY);
2931 #endif
2932                   printf("  - %s [%s]\n", pool_solvable2str(pool, s), s->repo->name);
2933                   if (sum)
2934                     printf("    %s\n", sum);
2935                 }
2936             }
2937         }
2938       queue_free(&q);
2939       queue_free(&job);
2940       pool_free(pool);
2941       free_repoinfos(repoinfos, nrepoinfos);
2942       solv_free(commandlinepkgs);
2943 #ifdef FEDORA
2944       yum_substitute(pool, 0);
2945 #endif
2946       exit(0);
2947     }
2948
2949 #if defined(SUSE) || defined(FEDORA)
2950   if (mainmode == MODE_PATCH)
2951     add_patchjobs(pool, &job);
2952 #endif
2953
2954   // add mode
2955   for (i = 0; i < job.count; i += 2)
2956     {
2957       job.elements[i] |= mode;
2958       if (mode == SOLVER_UPDATE && pool_isemptyupdatejob(pool, job.elements[i], job.elements[i + 1]))
2959         job.elements[i] ^= SOLVER_UPDATE ^ SOLVER_INSTALL;
2960       if (cleandeps)
2961         job.elements[i] |= SOLVER_CLEANDEPS;
2962       if (forcebest)
2963         job.elements[i] |= SOLVER_FORCEBEST;
2964     }
2965
2966   // multiversion test
2967   // queue_push2(&job, SOLVER_MULTIVERSION|SOLVER_SOLVABLE_NAME, pool_str2id(pool, "kernel-pae", 1));
2968   // queue_push2(&job, SOLVER_MULTIVERSION|SOLVER_SOLVABLE_NAME, pool_str2id(pool, "kernel-pae-base", 1));
2969   // queue_push2(&job, SOLVER_MULTIVERSION|SOLVER_SOLVABLE_NAME, pool_str2id(pool, "kernel-pae-extra", 1));
2970 #if 0
2971   queue_push2(&job, SOLVER_INSTALL|SOLVER_SOLVABLE_PROVIDES, pool_rel2id(pool, NAMESPACE_LANGUAGE, 0, REL_NAMESPACE, 1));
2972   queue_push2(&job, SOLVER_ERASE|SOLVER_CLEANDEPS|SOLVER_SOLVABLE_PROVIDES, pool_rel2id(pool, NAMESPACE_LANGUAGE, 0, REL_NAMESPACE, 1));
2973 #endif
2974
2975 #ifdef SOFTLOCKS_PATH
2976   addsoftlocks(pool, &job);
2977 #endif
2978
2979 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
2980 rerunsolver:
2981 #endif
2982   solv = solver_create(pool);
2983   solver_set_flag(solv, SOLVER_FLAG_SPLITPROVIDES, 1);
2984 #ifdef FEDORA
2985   solver_set_flag(solv, SOLVER_FLAG_ALLOW_VENDORCHANGE, 1);
2986 #endif
2987   if (mainmode == MODE_ERASE)
2988     solver_set_flag(solv, SOLVER_FLAG_ALLOW_UNINSTALL, 1);      /* don't nag */
2989   solver_set_flag(solv, SOLVER_FLAG_BEST_OBEY_POLICY, 1);
2990
2991   for (;;)
2992     {
2993       Id problem, solution;
2994       int pcnt, scnt;
2995
2996       if (!solver_solve(solv, &job))
2997         break;
2998       pcnt = solver_problem_count(solv);
2999       printf("Found %d problems:\n", pcnt);
3000       for (problem = 1; problem <= pcnt; problem++)
3001         {
3002           int take = 0;
3003           printf("Problem %d/%d:\n", problem, pcnt);
3004           solver_printprobleminfo(solv, problem);
3005           printf("\n");
3006           scnt = solver_solution_count(solv, problem);
3007           for (solution = 1; solution <= scnt; solution++)
3008             {
3009               printf("Solution %d:\n", solution);
3010               solver_printsolution(solv, problem, solution);
3011               printf("\n");
3012             }
3013           for (;;)
3014             {
3015               char inbuf[128], *ip;
3016               printf("Please choose a solution: ");
3017               fflush(stdout);
3018               *inbuf = 0;
3019               if (!(ip = fgets(inbuf, sizeof(inbuf), stdin)))
3020                 {
3021                   printf("Abort.\n");
3022                   exit(1);
3023                 }
3024               while (*ip == ' ' || *ip == '\t')
3025                 ip++;
3026               if (*ip >= '0' && *ip <= '9')
3027                 {
3028                   take = atoi(ip);
3029                   if (take >= 1 && take <= scnt)
3030                     break;
3031                 }
3032               if (*ip == 's')
3033                 {
3034                   take = 0;
3035                   break;
3036                 }
3037               if (*ip == 'q')
3038                 {
3039                   printf("Abort.\n");
3040                   exit(1);
3041                 }
3042             }
3043           if (!take)
3044             continue;
3045           solver_take_solution(solv, problem, take, &job);
3046         }
3047     }
3048
3049   trans = solver_create_transaction(solv);
3050   if (!trans->steps.count)
3051     {
3052       printf("Nothing to do.\n");
3053       transaction_free(trans);
3054       solver_free(solv);
3055       queue_free(&job);
3056       pool_free(pool);
3057       free_repoinfos(repoinfos, nrepoinfos);
3058       solv_free(commandlinepkgs);
3059 #ifdef FEDORA
3060       yum_substitute(pool, 0);
3061 #endif
3062       exit(1);
3063     }
3064
3065   /* display transaction to the user and ask for confirmation */
3066   printf("\n");
3067   printf("Transaction summary:\n\n");
3068   transaction_print(trans);
3069 #if defined(SUSE)
3070   showdiskusagechanges(trans);
3071 #endif
3072   printf("install size change: %d K\n", transaction_calc_installsizechange(trans));
3073   printf("\n");
3074
3075   if (!yesno("OK to continue (y/n)? "))
3076     {
3077       printf("Abort.\n");
3078       transaction_free(trans);
3079       solver_free(solv);
3080       queue_free(&job);
3081       pool_free(pool);
3082       free_repoinfos(repoinfos, nrepoinfos);
3083       solv_free(commandlinepkgs);
3084 #ifdef FEDORA
3085       yum_substitute(pool, 0);
3086 #endif
3087       exit(1);
3088     }
3089
3090   /* download all new packages */
3091   queue_init(&checkq);
3092   newpkgs = transaction_installedresult(trans, &checkq);
3093   newpkgsfps = 0;
3094   if (newpkgs)
3095     {
3096       int downloadsize = 0;
3097       for (i = 0; i < newpkgs; i++)
3098         {
3099           Solvable *s;
3100
3101           p = checkq.elements[i];
3102           s = pool_id2solvable(pool, p);
3103           downloadsize += solvable_lookup_sizek(s, SOLVABLE_DOWNLOADSIZE, 0);
3104         }
3105       printf("Downloading %d packages, %d K\n", newpkgs, downloadsize);
3106       newpkgsfps = solv_calloc(newpkgs, sizeof(*newpkgsfps));
3107       for (i = 0; i < newpkgs; i++)
3108         {
3109           unsigned int medianr;
3110           const char *loc;
3111           Solvable *s;
3112           struct repoinfo *cinfo;
3113           const unsigned char *chksum;
3114           Id chksumtype;
3115
3116           p = checkq.elements[i];
3117           s = pool_id2solvable(pool, p);
3118           if (s->repo == commandlinerepo)
3119             {
3120               loc = solvable_lookup_location(s, &medianr);
3121               if (!(newpkgsfps[i] = fopen(loc, "r")))
3122                 {
3123                   perror(loc);
3124                   exit(1);
3125                 }
3126               putchar('.');
3127               continue;
3128             }
3129           cinfo = s->repo->appdata;
3130           if (!cinfo)
3131             {
3132               printf("%s: no repository information\n", s->repo->name);
3133               exit(1);
3134             }
3135           loc = solvable_lookup_location(s, &medianr);
3136           if (!loc)
3137              continue;
3138 #if defined(ENABLE_RPMDB)
3139           if (pool->installed && pool->installed->nsolvables)
3140             {
3141               if ((newpkgsfps[i] = trydeltadownload(s, cinfo, loc)) != 0)
3142                 {
3143                   putchar('d');
3144                   fflush(stdout);
3145                   continue;             /* delta worked! */
3146                 }
3147             }
3148 #endif
3149 #ifdef ENABLE_SUSEREPO
3150           if (cinfo->type == TYPE_SUSETAGS)
3151             {
3152               const char *datadir = repo_lookup_str(cinfo->repo, SOLVID_META, SUSETAGS_DATADIR);
3153               loc = pool_tmpjoin(pool, datadir ? datadir : "suse", "/", loc);
3154             }
3155 #endif
3156           chksumtype = 0;
3157           chksum = solvable_lookup_bin_checksum(s, SOLVABLE_CHECKSUM, &chksumtype);
3158           if ((newpkgsfps[i] = curlfopen(cinfo, loc, 0, chksum, chksumtype, 0)) == 0)
3159             {
3160               printf("\n%s: %s not found in repository\n", s->repo->name, loc);
3161               exit(1);
3162             }
3163           putchar('.');
3164           fflush(stdout);
3165         }
3166       putchar('\n');
3167     }
3168
3169 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
3170   /* check for file conflicts */
3171   if (newpkgs)
3172     {
3173       Queue conflicts;
3174       struct fcstate fcstate;
3175
3176       printf("Searching for file conflicts\n");
3177       queue_init(&conflicts);
3178       fcstate.rpmdbstate = 0;
3179       fcstate.newpkgscnt = newpkgs;
3180       fcstate.checkq = &checkq;
3181       fcstate.newpkgsfps = newpkgsfps;
3182       pool_findfileconflicts(pool, &checkq, newpkgs, &conflicts, &fileconflict_cb, &fcstate);
3183       if (conflicts.count)
3184         {
3185           printf("\n");
3186           for (i = 0; i < conflicts.count; i += 6)
3187             printf("file %s of package %s conflicts with package %s\n", pool_id2str(pool, conflicts.elements[i]), pool_solvid2str(pool, conflicts.elements[i + 1]), pool_solvid2str(pool, conflicts.elements[i + 4]));
3188           printf("\n");
3189           if (yesno("Re-run solver (y/n/q)? "))
3190             {
3191               for (i = 0; i < newpkgs; i++)
3192                 if (newpkgsfps[i])
3193                   fclose(newpkgsfps[i]);
3194               newpkgsfps = solv_free(newpkgsfps);
3195               solver_free(solv);
3196               solv = 0;
3197               pool_add_fileconflicts_deps(pool, &conflicts);
3198               goto rerunsolver;
3199             }
3200         }
3201       queue_free(&conflicts);
3202     }
3203 #endif
3204
3205   /* and finally commit the transaction */
3206   printf("Committing transaction:\n\n");
3207   transaction_order(trans, 0);
3208   for (i = 0; i < trans->steps.count; i++)
3209     {
3210 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
3211       const char *evr, *evrp, *nvra;
3212 #endif
3213       Solvable *s;
3214       int j;
3215       FILE *fp;
3216       Id type;
3217
3218       p = trans->steps.elements[i];
3219       s = pool_id2solvable(pool, p);
3220       type = transaction_type(trans, p, SOLVER_TRANSACTION_RPM_ONLY);
3221       switch(type)
3222         {
3223         case SOLVER_TRANSACTION_ERASE:
3224           printf("erase %s\n", pool_solvid2str(pool, p));
3225 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
3226           if (!s->repo->rpmdbid || !s->repo->rpmdbid[p - s->repo->start])
3227             continue;
3228           /* strip epoch from evr */
3229           evr = evrp = pool_id2str(pool, s->evr);
3230           while (*evrp >= '0' && *evrp <= '9')
3231             evrp++;
3232           if (evrp > evr && evrp[0] == ':' && evrp[1])
3233             evr = evrp + 1;
3234           nvra = pool_tmpjoin(pool, pool_id2str(pool, s->name), "-", evr);
3235           nvra = pool_tmpappend(pool, nvra, ".", pool_id2str(pool, s->arch));
3236           runrpm("-e", nvra, -1, rootdir);      /* too bad that --querybynumber doesn't work */
3237 #endif
3238 #if defined(ENABLE_DEBIAN) && defined(DEBIAN)
3239           rundpkg("--remove", pool_id2str(pool, s->name), 0, rootdir);
3240 #endif
3241           break;
3242         case SOLVER_TRANSACTION_INSTALL:
3243         case SOLVER_TRANSACTION_MULTIINSTALL:
3244           printf("install %s\n", pool_solvid2str(pool, p));
3245           for (j = 0; j < newpkgs; j++)
3246             if (checkq.elements[j] == p)
3247               break;
3248           fp = j < newpkgs ? newpkgsfps[j] : 0;
3249           if (!fp)
3250             continue;
3251           rewind(fp);
3252           lseek(fileno(fp), 0, SEEK_SET);
3253 #if defined(ENABLE_RPMDB) && (defined(SUSE) || defined(FEDORA))
3254           runrpm(type == SOLVER_TRANSACTION_MULTIINSTALL ? "-i" : "-U", "/dev/fd/3", fileno(fp), rootdir);
3255 #endif
3256 #if defined(ENABLE_DEBIAN) && defined(DEBIAN)
3257           rundpkg("--install", "/dev/fd/3", fileno(fp), rootdir);
3258 #endif
3259           fclose(fp);
3260           newpkgsfps[j] = 0;
3261           break;
3262         default:
3263           break;
3264         }
3265     }
3266
3267   for (i = 0; i < newpkgs; i++)
3268     if (newpkgsfps[i])
3269       fclose(newpkgsfps[i]);
3270   solv_free(newpkgsfps);
3271   queue_free(&checkq);
3272   transaction_free(trans);
3273   solver_free(solv);
3274   queue_free(&job);
3275   pool_free(pool);
3276   free_repoinfos(repoinfos, nrepoinfos);
3277   solv_free(commandlinepkgs);
3278 #ifdef FEDORA
3279   yum_substitute(pool, 0);
3280 #endif
3281   exit(0);
3282 }