- beautify
[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 missing:
11  * - repository data caching
12  * - signature verification
13  */
14
15 #define _GNU_SOURCE
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <dirent.h>
20 #include <unistd.h>
21 #include <zlib.h>
22 #include <fcntl.h>
23 #include <sys/utsname.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26
27 #include "pool.h"
28 #include "poolarch.h"
29 #include "repo.h"
30 #include "util.h"
31 #include "solver.h"
32 #include "solverdebug.h"
33
34 #include "repo_rpmdb.h"
35 #include "repo_rpmmd.h"
36 #include "repo_susetags.h"
37 #include "repo_repomdxml.h"
38 #include "pool_fileconflicts.h"
39
40
41 struct repoinfo {
42   Repo *repo;
43
44   char *alias;
45   char *name;
46   int enabled;
47   int autorefresh;
48   char *baseurl;
49   char *path;
50   int type;
51   int priority;
52   int keeppackages;
53 };
54
55 #define TYPE_UNKNOWN 0
56 #define TYPE_SUSETAGS 1
57 #define TYPE_RPMMD 2
58
59 struct repoinfo *
60 read_repoinfos(Pool *pool, const char *reposdir, int *nrepoinfosp)
61 {
62   char buf[4096];
63   char buf2[4096], *kp, *vp, *kpe;
64   DIR *dir;
65   FILE *fp;
66   struct dirent *ent;
67   int l, rdlen;
68   struct repoinfo *repoinfos = 0, *cinfo;
69   int nrepoinfos = 0;
70
71   rdlen = strlen(reposdir);
72   dir = opendir(reposdir);
73   if (!dir)
74     {
75       *nrepoinfosp = 0;
76       return 0;
77     }
78   while ((ent = readdir(dir)) != 0)
79     {
80       l = strlen(ent->d_name);
81       if (l < 6 || rdlen + 2 + l >= sizeof(buf) || strcmp(ent->d_name + l - 5, ".repo") != 0)
82         continue;
83       snprintf(buf, sizeof(buf), "%s/%s", reposdir, ent->d_name);
84       if ((fp = fopen(buf, "r")) == 0)
85         {
86           perror(buf);
87           continue;
88         }
89       cinfo = 0;
90       while(fgets(buf2, sizeof(buf2), fp))
91         {
92           l = strlen(buf2);
93           if (l == 0)
94             continue;
95           while (buf2[l - 1] == '\n' || buf2[l - 1] == ' ' || buf2[l - 1] == '\t')
96             buf2[--l] = 0;
97           kp = buf2;
98           while (*kp == ' ' || *kp == '\t')
99             kp++;
100           if (!*kp || *kp == '#')
101             continue;
102           if (!cinfo)
103             {
104               if (*kp != '[')
105                 continue;
106               vp = strrchr(kp, ']');
107               if (!vp)
108                 continue;
109               *vp = 0;
110               repoinfos = sat_extend(repoinfos, nrepoinfos, 1, sizeof(*repoinfos), 15);
111               cinfo = repoinfos + nrepoinfos++;
112               memset(cinfo, 0, sizeof(*cinfo));
113               cinfo->alias = strdup(kp + 1);
114               continue;
115             }
116           vp = strchr(kp, '=');
117           if (!vp)
118             continue;
119           for (kpe = vp - 1; kpe >= kp; kpe--)
120             if (*kpe != ' ' && *kpe != '\t')
121               break;
122           if (kpe == kp)
123             continue;
124           vp++;
125           while (*vp == ' ' || *vp == '\t')
126             vp++;
127           kpe[1] = 0;
128           if (!strcmp(kp, "name"))
129             cinfo->name = strdup(vp);
130           else if (!strcmp(kp, "enabled"))
131             cinfo->enabled = *vp == '0' ? 0 : 1;
132           else if (!strcmp(kp, "autorefresh"))
133             cinfo->autorefresh = *vp == '0' ? 0 : 1;
134           else if (!strcmp(kp, "baseurl"))
135             cinfo->baseurl = strdup(vp);
136           else if (!strcmp(kp, "path"))
137             cinfo->path = strdup(vp);
138           else if (!strcmp(kp, "type"))
139             {
140               if (!strcmp(vp, "yast2"))
141                 cinfo->type = TYPE_SUSETAGS;
142               else if (!strcmp(vp, "rpm-md"))
143                 cinfo->type = TYPE_RPMMD;
144               else
145                 cinfo->type = TYPE_UNKNOWN;
146             }
147           else if (!strcmp(kp, "priority"))
148             cinfo->priority = atoi(vp);
149           else if (!strcmp(kp, "keeppackages"))
150             cinfo->keeppackages = *vp == '0' ? 0 : 1;
151         }
152       fclose(fp);
153       if (cinfo->type == TYPE_SUSETAGS && cinfo->baseurl)
154         {
155           char *old = cinfo->baseurl;
156           cinfo->baseurl = sat_malloc(5 + strlen(old) + 1);
157           sprintf(cinfo->baseurl, "%s/suse", old);
158           free(old);
159         }
160       cinfo = 0;
161     }
162   closedir(dir);
163   *nrepoinfosp = nrepoinfos;
164   return repoinfos;
165 }
166
167 static ssize_t
168 cookie_gzread(void *cookie, char *buf, size_t nbytes)
169 {
170   return gzread((gzFile *)cookie, buf, nbytes);
171 }
172
173 static int
174 cookie_gzclose(void *cookie)
175 {
176   return gzclose((gzFile *)cookie);
177 }
178
179 FILE *
180 myfopen(const char *fn)
181 {
182   cookie_io_functions_t cio;
183   char *suf;
184   gzFile *gzf;
185
186   if (!fn)
187     return 0;
188   suf = strrchr(fn, '.');
189   if (!suf || strcmp(suf, ".gz") != 0)
190     return fopen(fn, "r");
191   gzf = gzopen(fn, "r");
192   if (!gzf)
193     return 0;
194   memset(&cio, 0, sizeof(cio));
195   cio.read = cookie_gzread;
196   cio.close = cookie_gzclose;
197   return  fopencookie(gzf, "r", cio);
198 }
199
200 FILE *
201 curlfopen(char *baseurl, char *file, int uncompress)
202 {
203   pid_t pid;
204   int fd, l;
205   int status;
206   char tmpl[100];
207   char url[4096];
208
209   l = strlen(baseurl);
210   if (l && baseurl[l - 1] == '/')
211     snprintf(url, sizeof(url), "%s%s", baseurl, file);
212   else
213     snprintf(url, sizeof(url), "%s/%s", baseurl, file);
214   strcpy(tmpl, "/var/tmp/solvXXXXXX");
215   fd = mkstemp(tmpl);
216   if (fd < 0)
217     {
218       perror("mkstemp");
219       exit(1);
220     }
221   unlink(tmpl);
222   if ((pid = fork()) == (pid_t)-1)
223     {
224       perror("fork");
225       exit(1);
226     }
227   if (pid == 0)
228     {
229       if (fd != 1)
230         {
231           dup2(fd, 1);
232           close(fd);
233         }
234       execlp("curl", "curl", "-s", "-L", url, (char *)0);
235       perror("curl");
236       _exit(0);
237     }
238   while (waitpid(pid, &status, 0) != pid)
239     ;
240   lseek(fd, 0, SEEK_SET);
241   if (uncompress)
242     {
243       cookie_io_functions_t cio;
244       gzFile *gzf;
245
246       sprintf(tmpl, "/dev/fd/%d", fd);
247       gzf = gzopen(tmpl, "r");
248       close(fd);
249       if (!gzf)
250         return 0;
251       memset(&cio, 0, sizeof(cio));
252       cio.read = cookie_gzread;
253       cio.close = cookie_gzclose;
254       return fopencookie(gzf, "r", cio);
255     }
256   fcntl(fd, F_SETFD, FD_CLOEXEC);
257   return fdopen(fd, "r");
258 }
259
260 void
261 setarch(Pool *pool)
262 {
263   struct utsname un;
264   if (uname(&un))
265     {
266       perror("uname");
267       exit(1);
268     }
269   pool_setarch(pool, un.machine);
270 }
271
272 void
273 read_repos(Pool *pool, struct repoinfo *repoinfos, int nrepoinfos)
274 {
275   Repo *repo;
276   struct repoinfo *cinfo;
277   int i;
278   FILE *fp;
279
280   printf("reading rpm database\n");
281   repo = repo_create(pool, "@System");
282   repo_add_rpmdb(repo, 0, 0, 0);
283   pool_set_installed(pool, repo);
284   for (i = 0; i < nrepoinfos; i++)
285     {
286       cinfo = repoinfos + i;
287       if (!cinfo->enabled)
288         continue;
289       switch (cinfo->type)
290         {
291         case TYPE_RPMMD:
292           printf("reading rpmmd repo '%s'\n", cinfo->alias);
293           if ((fp = curlfopen(cinfo->baseurl, "repodata/repomd.xml", 0)) == 0)
294             break;
295           repo = repo_create(pool, cinfo->alias);
296           cinfo->repo = repo;
297           repo->appdata = cinfo;
298           repo_add_repomdxml(repo, fp, 0);
299           fclose(fp);
300           if ((fp = curlfopen(cinfo->baseurl, "repodata/primary.xml.gz", 1)) == 0)
301             continue;
302           repo_add_rpmmd(repo, fp, 0, 0);
303           fclose(fp);
304           break;
305         case TYPE_SUSETAGS:
306           printf("reading susetags repo '%s'\n", cinfo->alias);
307           if ((fp = curlfopen(cinfo->baseurl, "setup/descr/packages.gz", 1)) == 0)
308             break;
309           repo = repo_create(pool, cinfo->alias);
310           cinfo->repo = repo;
311           repo->appdata = cinfo;
312           repo_add_susetags(repo, fp, 0, 0, 0);
313           fclose(fp);
314           break;
315         default:
316           printf("skipping unknown repo '%s'\n", cinfo->alias);
317           break;
318         }
319     }
320 }
321
322 void
323 mkselect(Pool *pool, const char *arg, int flags, Queue *out)
324 {
325   Id id, p, pp;
326   Id type = 0;
327   const char *r, *r2;
328
329   id = str2id(pool, arg, 0);
330   if (id)
331     {
332       FOR_PROVIDES(p, pp, id)
333         {
334           Solvable *s = pool_id2solvable(pool, p);
335           if (s->name == id)
336             {
337               type = SOLVER_SOLVABLE_NAME;
338               break;
339             }
340           type = SOLVER_SOLVABLE_PROVIDES;
341         }
342     }
343   if (!type)
344     {
345       /* did not find a solvable, see if it's a relation */
346       if ((r = strpbrk(arg, "<=>")) != 0)
347         {
348           Id rid, rname, revr;
349           int rflags = 0;
350           for (r2 = r; r2 > arg && (r2[-1] == ' ' || r2[-1] == '\t'); )
351             r2--;
352           rname = r2 > arg ? strn2id(pool, arg, r2 - arg, 1) : 0;
353           for (; *r; r++)
354             {
355               if (*r == '<')
356                 rflags |= REL_LT;
357               else if (*r == '=')
358                 rflags |= REL_EQ;
359               else if (*r == '>')
360                 rflags |= REL_GT;
361               else
362                 break;
363             }
364           while (*r == ' ' || *r == '\t')
365             r++;
366           revr = *r ? str2id(pool, r, 1) : 0;
367           rid = rname && revr ? rel2id(pool, rname, revr, rflags, 1) : 0;
368           if (rid)
369             {
370               FOR_PROVIDES(p, pp, rid)
371                 {
372                   Solvable *s = pool_id2solvable(pool, p);
373                   if (pool_match_nevr(pool, s, rid))
374                     {
375                       type = SOLVER_SOLVABLE_NAME;
376                       break;
377                     }
378                   type = SOLVER_SOLVABLE_PROVIDES;
379                 }
380             }
381           if (type)
382             id = rid;
383         }
384     }
385   if (type)
386     {
387       queue_push(out, type);
388       queue_push(out, id);
389     }
390 }
391
392 int
393 yesno(const char *str)
394 {
395   char inbuf[128], *ip;
396
397   for (;;)
398     {
399       printf("%s", str);
400       fflush(stdout);
401       *inbuf = 0;
402       if (!(ip = fgets(inbuf, sizeof(inbuf), stdin)))
403         {
404           printf("Abort.\n");
405           exit(1);
406         }
407       while (*ip == ' ' || *ip == '\t')
408         ip++;
409       if (*ip == 'q')
410         {
411           printf("Abort.\n");
412           exit(1);
413         }
414       if (*ip == 'y' || *ip == 'n')
415         return *ip == 'y' ? 1 : 0;
416     }
417 }
418
419 struct fcstate {
420   FILE **newpkgsfps;
421   Queue *checkq;
422   int newpkgscnt;
423   void *rpmdbstate;
424 };
425
426 static void *
427 fc_cb(Pool *pool, Id p, void *cbdata)
428 {
429   struct fcstate *fcstate = cbdata;
430   Solvable *s;
431   Id rpmdbid;
432   int i;
433   FILE *fp;
434
435   if (!p)
436     {
437       rpm_byrpmdbid(0, 0, &fcstate->rpmdbstate);
438       return 0;
439     }
440   s = pool_id2solvable(pool, p);
441   if (pool->installed && s->repo == pool->installed)
442     {
443       if (!s->repo->rpmdbid)
444         return 0;
445       rpmdbid = s->repo->rpmdbid[p - s->repo->start];
446       if (!rpmdbid)
447         return 0;
448        return rpm_byrpmdbid(rpmdbid, 0, &fcstate->rpmdbstate);
449     }
450   for (i = 0; i < fcstate->newpkgscnt; i++)
451     if (fcstate->checkq->elements[i] == p)
452       break;
453   if (i == fcstate->newpkgscnt)
454     return 0;
455   fp = fcstate->newpkgsfps[i];
456   rewind(fp);
457   return rpm_byfp(fp, solvable2str(pool, s), &fcstate->rpmdbstate);
458 }
459
460 void
461 runrpm(const char *arg, const char *name, int dupfd3)
462 {
463   pid_t pid;
464   int status;
465
466   if ((pid = fork()) == (pid_t)-1)
467     {
468       perror("fork");
469       exit(1);
470     }
471   if (pid == 0)
472     {
473       if (dupfd3 != -1 && dupfd3 != 3)
474         {
475           dup2(dupfd3, 3);
476           close(dupfd3);
477         }
478       if (dupfd3 != -1)
479         fcntl(3, F_SETFD, 0);   /* clear CLOEXEC */
480       if (strcmp(arg, "-e") == 0)
481         execlp("rpm", "rpm", arg, "--nodeps", "--nodigest", "--nosignature", name, (char *)0);
482       else
483         execlp("rpm", "rpm", arg, "--force", "--nodeps", "--nodigest", "--nosignature", name, (char *)0);
484       perror("rpm");
485       _exit(0);
486     }
487   while (waitpid(pid, &status, 0) != pid)
488     ;
489   if (status)
490     {
491       printf("rpm failed\n");
492       exit(1);
493     }
494 }
495
496 int
497 main(int argc, char **argv)
498 {
499   Pool *pool;
500   Id p, pp;
501   struct repoinfo *repoinfos;
502   int nrepoinfos = 0;
503   int i, mode, newpkgs;
504   Queue job, checkq;
505   Solver *solv = 0;
506   Transaction *trans;
507   char inbuf[128], *ip;
508   int updateall = 0;
509   FILE **newpkgsfps;
510   struct fcstate fcstate;
511
512   if (!strcmp(argv[1], "install") || !strcmp(argv[1], "in"))
513     mode = SOLVER_INSTALL;
514   else if (!strcmp(argv[1], "erase") || !strcmp(argv[1], "rm"))
515     mode = SOLVER_ERASE;
516   else if (!strcmp(argv[1], "show"))
517     mode = 0;
518   else if (!strcmp(argv[1], "update") || !strcmp(argv[1], "up"))
519     mode = SOLVER_UPDATE;
520   else
521     {
522       fprintf(stderr, "Usage: solv install|erase|update|show <select>\n");
523       exit(1);
524     }
525
526   pool = pool_create();
527   // pool_setdebuglevel(pool, 2);
528   setarch(pool);
529   repoinfos = read_repoinfos(pool, "/etc/zypp/repos.d", &nrepoinfos);
530   read_repos(pool, repoinfos, nrepoinfos);
531   // FOR_REPOS(i, repo)
532   //   printf("%s: %d solvables\n", repo->name, repo->nsolvables);
533   pool_addfileprovides(pool);
534   pool_createwhatprovides(pool);
535
536   queue_init(&job);
537   for (i = 2; i < argc; i++)
538     mkselect(pool, argv[i], 0, &job);
539   if (!job.count && mode == SOLVER_UPDATE)
540     updateall = 1;
541   else if (!job.count)
542     {
543       printf("nothing matched\n");
544       exit(1);
545     }
546
547   if (!mode)
548     {
549       /* show mode, no solver needed */
550       for (i = 0; i < job.count; i += 2)
551         {
552           FOR_JOB_SELECT(p, pp, job.elements[i], job.elements[i + 1])
553             {
554               Solvable *s = pool_id2solvable(pool, p);
555               printf("  - %s [%s]\n", solvable2str(pool, s), s->repo->name);
556             }
557         }
558       exit(0);
559     }
560
561   // add mode
562   for (i = 0; i < job.count; i += 2)
563     job.elements[i] |= mode;
564
565 rerunsolver:
566   for (;;)
567     {
568       Id problem, solution;
569       int pcnt, scnt;
570
571       solv = solver_create(pool);
572       solv->ignorealreadyrecommended = 1;
573       solv->updatesystem = updateall;
574       solver_solve(solv, &job);
575       if (!solv->problems.count)
576         break;
577       pcnt = solver_problem_count(solv);
578       printf("Found %d problems:\n", pcnt);
579       for (problem = 1; problem <= pcnt; problem++)
580         {
581           int take = 0;
582           printf("Problem %d:\n", problem);
583           solver_printprobleminfo(solv, problem);
584           printf("\n");
585           scnt = solver_solution_count(solv, problem);
586           for (solution = 1; solution <= pcnt; solution++)
587             {
588               printf("Solution %d:\n", solution);
589               solver_printsolution(solv, problem, solution);
590               printf("\n");
591             }
592           for (;;)
593             {
594               printf("Please choose a solution: ");
595               fflush(stdout);
596               *inbuf = 0;
597               if (!(ip = fgets(inbuf, sizeof(inbuf), stdin)))
598                 {
599                   printf("Abort.\n");
600                   exit(1);
601                 }
602               while (*ip == ' ' || *ip == '\t')
603                 ip++;
604               if (*ip >= '0' && *ip <= '9')
605                 {
606                   take = atoi(ip);
607                   if (take >= 1 && take <= solution)
608                     break;
609                 }
610               if (*ip == 's')
611                 {
612                   take = 0;
613                   break;
614                 }
615               if (*ip == 'q')
616                 {
617                   printf("Abort.\n");
618                   exit(1);
619                 }
620             }
621           if (!take)
622             continue;
623           solver_take_solution(solv, problem, take, &job);
624         }
625       solver_free(solv);
626       solv = 0;
627     }
628   if (!solv->trans.steps.count)
629     {
630       printf("Nothing to do.\n");
631       exit(1);
632     }
633   printf("\n");
634   printf("Transaction summary:\n\n");
635   solver_printtransaction(solv);
636   if (!yesno("OK to continue (y/n)? "))
637     {
638       printf("Abort.\n");
639       exit(1);
640     }
641
642   trans = &solv->trans;
643   queue_init(&checkq);
644   newpkgs = transaction_installedresult(trans, &checkq);
645   newpkgsfps = 0;
646
647   if (newpkgs)
648     {
649       printf("Downloading %d packages\n", newpkgs);
650       newpkgsfps = sat_calloc(newpkgs, sizeof(*newpkgsfps));
651       for (i = 0; i < newpkgs; i++)
652         {
653           unsigned int medianr;
654           char *loc;
655           Solvable *s;
656           struct repoinfo *cinfo;
657
658           p = checkq.elements[i];
659           s = pool_id2solvable(pool, p);
660           cinfo = s->repo->appdata;
661           if (!cinfo)
662             {
663               printf("%s: no repository information\n", s->repo->name);
664               exit(1);
665             }
666           loc = solvable_get_location(s, &medianr);
667           if ((newpkgsfps[i] = curlfopen(cinfo->baseurl, loc, 0)) == 0)
668             {
669               printf("%s: %s not found\n", s->repo->name, loc);
670               exit(1);
671             }
672         }
673     }
674
675   if (newpkgs)
676     {
677       Queue conflicts;
678
679       printf("Searching for file conflicts\n");
680       queue_init(&conflicts);
681       fcstate.rpmdbstate = 0;
682       fcstate.newpkgscnt = newpkgs;
683       fcstate.checkq = &checkq;
684       fcstate.newpkgsfps = newpkgsfps;
685       pool_findfileconflicts(pool, &checkq, newpkgs, &conflicts, &fc_cb, &fcstate);
686       if (conflicts.count)
687         {
688           printf("\n");
689           for (i = 0; i < conflicts.count; i += 5)
690             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]));
691           printf("\n");
692           if (yesno("Re-run solver (y/n/q)? "))
693             {
694               for (i = 0; i < newpkgs; i++)
695                 fclose(newpkgsfps[i]);
696               newpkgsfps = sat_free(newpkgsfps);
697               solver_free(solv);
698               pool_add_fileconflicts_deps(pool, &conflicts);
699               pool_createwhatprovides(pool);    /* Hmm... */
700               goto rerunsolver;
701             }
702         }
703       queue_free(&conflicts);
704     }
705
706   printf("Committing transaction:\n\n");
707   transaction_order(trans, 0);
708   for (i = 0; i < trans->steps.count; i++)
709     {
710       char rpmname[256];
711       const char *evr, *evrp;
712       Solvable *s;
713       int j;
714       FILE *fp;
715
716       p = trans->steps.elements[i];
717       s = pool_id2solvable(pool, p);
718       Id type = transaction_type(trans, p, SOLVER_TRANSACTION_RPM_ONLY);
719       switch(type)
720         {
721         case SOLVER_TRANSACTION_ERASE:
722           printf("erase %s\n", solvid2str(pool, p));
723           if (strlen(solvid2str(pool, p)) > 255)
724             continue;
725           evr = evrp = id2str(pool, s->evr);
726           while (*evrp >= '0' && *evrp <= '9')
727             evrp++;
728           if (evrp > evr && evrp[0] == ':' && evrp[1])
729             evr = evrp + 1;
730           sprintf(rpmname, "%s-%s.%s", id2str(pool, s->name), evr, id2str(pool, s->arch));
731           runrpm("-e", rpmname, -1);
732           break;
733         case SOLVER_TRANSACTION_INSTALL:
734         case SOLVER_TRANSACTION_MULTIINSTALL:
735           printf("install %s\n", solvid2str(pool, p));
736           for (j = 0; j < newpkgs; j++)
737             if (checkq.elements[j] == p)
738               break;
739           fp = j < newpkgs ? newpkgsfps[j] : 0;
740           rewind(fp);
741           lseek(fileno(fp), 0, SEEK_SET);
742           runrpm(type == SOLVER_TRANSACTION_MULTIINSTALL ? "-i" : "-U", "/dev/fd/3", fileno(fp));
743           fclose(fp);
744           newpkgsfps[j] = 0;
745           break;
746         default:
747           break;
748         }
749     }
750
751   for (i = 0; i < newpkgs; i++)
752     if (newpkgsfps[i])
753       fclose(newpkgsfps[i]);
754   sat_free(newpkgsfps);
755   queue_free(&checkq);
756   solver_free(solv);
757   queue_free(&job);
758   pool_free(pool);
759   exit(0);
760 }