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