Doxygen annotations for config files.
[tools/librpm-tizen.git] / lib / rpminstall.c
1 /** \ingroup rpmcli
2  * \file lib/rpminstall.c
3  */
4
5 #include "system.h"
6
7 #include <rpmlib.h>
8 #include <rpmmacro.h>
9 #include <rpmurl.h>
10
11 #include "manifest.h"
12 #include "misc.h"
13 #include "debug.h"
14
15 /*@access rpmTransactionSet@*/  /* XXX compared with NULL */
16 /*@access Header@*/             /* XXX compared with NULL */
17 /*@access FD_t@*/               /* XXX compared with NULL */
18
19 /**
20  * Wrapper to free(3), hides const compilation noise, permit NULL, return NULL.
21  * @param this          memory to free
22  * @retval              NULL always
23  */
24 static /*@null@*/ void * _free(/*@only@*/ /*@null@*/ const void * this) {
25     if (this)   free((void *)this);
26     return NULL;
27 }
28
29 /* Define if you want percentage progress in the hash bars when
30  * writing to a tty (ordinary hash bars otherwise) --claudio
31  */
32 #define FANCY_HASH
33
34 static int hashesPrinted = 0;
35
36 #ifdef FANCY_HASH
37 static int packagesTotal = 0;
38 static int progressTotal = 0;
39 static int progressCurrent = 0;
40 #endif
41
42 /**
43  */
44 static void printHash(const unsigned long amount, const unsigned long total)
45 {
46     int hashesNeeded;
47     int hashesTotal = 50;
48
49 #ifdef FANCY_HASH
50     if (isatty (STDOUT_FILENO))
51         hashesTotal = 44;
52 #endif
53
54     if (hashesPrinted != hashesTotal) {
55         hashesNeeded = hashesTotal * (total ? (((float) amount) / total) : 1);
56         while (hashesNeeded > hashesPrinted) {
57 #ifdef FANCY_HASH
58             if (isatty (STDOUT_FILENO)) {
59                 int i;
60                 for (i = 0; i < hashesPrinted; i++) putchar ('#');
61                 for (; i < hashesTotal; i++) putchar (' ');
62                 printf ("(%3d%%)",
63                         (int)(100 * (total ? (((float) amount) / total) : 1)));
64                 for (i = 0; i < (hashesTotal + 6); i++) putchar ('\b');
65             } else
66 #endif
67             fprintf(stdout, "#");
68
69             hashesPrinted++;
70         }
71         fflush(stdout);
72         hashesPrinted = hashesNeeded;
73
74         if (hashesPrinted == hashesTotal) {
75 #ifdef FANCY_HASH
76             int i;
77             progressCurrent++;
78             for (i = 1; i < hashesPrinted; i++) putchar ('#');
79             printf (" [%3d%%]\n", (int)(100 * (progressTotal ?
80                         (((float) progressCurrent) / progressTotal) : 1)));
81 #else
82             fprintf (stdout, "\n");
83 #endif
84         }
85         fflush(stdout);
86     }
87 }
88
89 /**
90  */
91 static void * showProgress(const void * arg, const rpmCallbackType what,
92                            const unsigned long amount,
93                            const unsigned long total,
94                            const void * pkgKey, void * data)
95 {
96     Header h = (Header) arg;
97     char * s;
98     int flags = (int) ((long)data);
99     void * rc = NULL;
100     const char * filename = pkgKey;
101     static FD_t fd;
102
103     switch (what) {
104     case RPMCALLBACK_INST_OPEN_FILE:
105         fd = Fopen(filename, "r.ufdio");
106         if (fd)
107             fd = fdLink(fd, "persist (showProgress)");
108         return fd;
109         /*@notreached@*/ break;
110
111     case RPMCALLBACK_INST_CLOSE_FILE:
112         fd = fdFree(fd, "persist (showProgress)");
113         if (fd) {
114             Fclose(fd);
115             fd = NULL;
116         }
117         break;
118
119     case RPMCALLBACK_INST_START:
120         hashesPrinted = 0;
121         if (!(flags & INSTALL_LABEL))
122             break;
123         if (flags & INSTALL_HASH) {
124             s = headerSprintf(h, "%{NAME}", rpmTagTable, rpmHeaderFormats,NULL);
125 #ifdef FANCY_HASH
126             if (isatty (STDOUT_FILENO))
127                 fprintf(stdout, "%4d:%-23.23s", progressCurrent + 1, s);
128             else
129 #else
130                 fprintf(stdout, "%-28s", s);
131 #endif
132             fflush(stdout);
133         } else {
134             s = headerSprintf(h, "%{NAME}-%{VERSION}-%{RELEASE}",
135                                   rpmTagTable, rpmHeaderFormats, NULL);
136             fprintf(stdout, "%s\n", s);
137             fflush(stdout);
138         }
139         s = _free(s);
140         break;
141
142     case RPMCALLBACK_TRANS_PROGRESS:
143     case RPMCALLBACK_INST_PROGRESS:
144         if (flags & INSTALL_PERCENT)
145             fprintf(stdout, "%%%% %f\n", (total
146                                 ? ((float) ((((float) amount) / total) * 100))
147                                 : 100.0));
148         else if (flags & INSTALL_HASH)
149             printHash(amount, total);
150         fflush(stdout);
151         break;
152
153     case RPMCALLBACK_TRANS_START:
154         hashesPrinted = 0;
155 #ifdef FANCY_HASH
156         progressTotal = 1;
157         progressCurrent = 0;
158 #endif
159         if (!(flags & INSTALL_LABEL))
160             break;
161         if (flags & INSTALL_HASH)
162             fprintf(stdout, "%-28s", _("Preparing..."));
163         else
164             printf("%s\n", _("Preparing packages for installation..."));
165         fflush(stdout);
166         break;
167
168     case RPMCALLBACK_TRANS_STOP:
169         if (flags & INSTALL_HASH)
170             printHash(1, 1);    /* Fixes "preparing..." progress bar */
171 #ifdef FANCY_HASH
172         progressTotal = packagesTotal;
173         progressCurrent = 0;
174 #endif
175         break;
176
177     case RPMCALLBACK_UNINST_PROGRESS:
178     case RPMCALLBACK_UNINST_START:
179     case RPMCALLBACK_UNINST_STOP:
180         /* ignore */
181         break;
182     }
183
184     return rc;
185 }       
186
187 /** @todo Generalize --freshen policies. */
188 int rpmInstall(const char * rootdir, const char ** fileArgv,
189                 rpmtransFlags transFlags,
190                 rpmInstallInterfaceFlags interfaceFlags,
191                 rpmprobFilterFlags probFilter,
192                 rpmRelocation * relocations)
193 {
194     rpmTransactionSet ts = NULL;
195     int notifyFlags = interfaceFlags | (rpmIsVerbose() ? INSTALL_LABEL : 0 );
196     rpmdb db = NULL;
197     const char ** pkgURL = NULL;
198     char * pkgState = NULL;
199     const char ** fnp;
200     const char * fileURL = NULL;
201     int numPkgs = 0;
202     int numRPMS = 0;
203     int numSRPMS = 0;
204     int numFailed = 0;
205     int stopInstall = 0;
206     int dbIsOpen = 0;
207     rpmRelocation * defaultReloc = relocations;
208     const char ** sourceURL = NULL;
209     int prevx;
210     int pkgx;
211     const char ** argv = NULL;
212     int argc = 0;
213     const char ** av = NULL;
214     int ac = 0;
215     Header h;
216     FD_t fd;
217     int rc;
218     int i;
219
220     while (defaultReloc && defaultReloc->oldPath)
221         defaultReloc++;
222     if (defaultReloc && !defaultReloc->newPath) defaultReloc = NULL;
223
224     /* Build fully globbed list of arguments in argv[argc]. */
225     for (fnp = fileArgv; *fnp; fnp++) {
226         av = _free(av);
227         ac = 0;
228         rc = rpmGlob(*fnp, &ac, &av);
229         if (rc || ac == 0) continue;
230
231         if (argc == 0)
232             argv = xmalloc((argc+2) * sizeof(*argv));
233         else
234             argv = xrealloc(argv, (argc+2) * sizeof(*argv));
235         memcpy(argv+argc, av, ac * sizeof(*av));
236         argc += ac;
237         argv[argc] = NULL;
238     }
239     av = _free(av);
240
241     numPkgs = 0;
242     prevx = 0;
243     pkgx = 0;
244
245 restart:
246     /* Allocate sufficient storage for next set of args. */
247     if (pkgx >= numPkgs) {
248         numPkgs = pkgx + argc;
249         pkgURL = (pkgURL == NULL)
250             ? xmalloc( (numPkgs + 1) * sizeof(*pkgURL))
251             : xrealloc(pkgURL, (numPkgs + 1) * sizeof(*pkgURL));
252         memset(pkgURL + pkgx, 0, ((argc + 1) * sizeof(*pkgURL)));
253         pkgState = (pkgState == NULL)
254             ? xmalloc( (numPkgs + 1) * sizeof(*pkgState))
255             : xrealloc(pkgState, (numPkgs + 1) * sizeof(*pkgState));
256         memset(pkgState + pkgx, 0, ((argc + 1) * sizeof(*pkgState)));
257     }
258
259     /* Retrieve next set of args, cache on local storage. */
260     for (i = 0; i < argc; i++) {
261         fileURL = _free(fileURL);
262         fileURL = argv[i];
263         argv[i] = NULL;
264
265         switch (urlIsURL(fileURL)) {
266         case URL_IS_FTP:
267         case URL_IS_HTTP:
268         {   const char *tfn;
269
270             if (rpmIsVerbose())
271                 fprintf(stdout, _("Retrieving %s\n"), fileURL);
272
273             {   char tfnbuf[64];
274                 strcpy(tfnbuf, "rpm-xfer.XXXXXX");
275                 /*@-unrecog@*/ mktemp(tfnbuf) /*@=unrecog@*/;
276                 tfn = rpmGenPath(rootdir, "%{_tmppath}/", tfnbuf);
277             }
278
279             /* XXX undefined %{name}/%{version}/%{release} here */
280             /* XXX %{_tmpdir} does not exist */
281             rpmMessage(RPMMESS_DEBUG, _(" ... as %s\n"), tfn);
282             rc = urlGetFile(fileURL, tfn);
283             if (rc < 0) {
284                 rpmMessage(RPMMESS_ERROR,
285                         _("skipping %s - transfer failed - %s\n"),
286                         fileURL, ftpStrerror(rc));
287                 numFailed++;
288                 pkgURL[pkgx] = NULL;
289                 tfn = _free(tfn);
290                 break;
291             }
292             pkgState[pkgx] = 1;
293             pkgURL[pkgx] = tfn;
294             pkgx++;
295         }   break;
296         case URL_IS_PATH:
297         default:
298             pkgURL[pkgx] = fileURL;
299             fileURL = NULL;
300             pkgx++;
301             break;
302         }
303     }
304     fileURL = _free(fileURL);
305
306     if (numFailed) goto exit;
307
308     /* Continue processing file arguments, building transaction set. */
309     for (fnp = pkgURL+prevx; *fnp; fnp++, prevx++) {
310         const char * fileName;
311         rpmRC rpmrc;
312         int isSource;
313
314         rpmMessage(RPMMESS_DEBUG, "============== %s\n", *fnp);
315         (void) urlPath(*fnp, &fileName);
316
317         /* Try to read the header from a package file. */
318         fd = Fopen(*fnp, "r.ufdio");
319         if (fd == NULL || Ferror(fd)) {
320             rpmError(RPMERR_OPEN, _("open of %s failed: %s\n"), *fnp,
321                         Fstrerror(fd));
322             if (fd) Fclose(fd);
323             numFailed++; *fnp = NULL;
324             continue;
325         }
326
327         rpmrc = rpmReadPackageHeader(fd, &h, &isSource, NULL, NULL);
328         Fclose(fd);
329
330         if (rpmrc == RPMRC_FAIL || rpmrc == RPMRC_SHORTREAD) {
331             numFailed++; *fnp = NULL;
332             continue;
333         }
334         if ((rpmrc == RPMRC_OK || rpmrc == RPMRC_BADSIZE) && isSource) {
335             rpmMessage(RPMMESS_DEBUG, "\tadded source rpm[%d]\n", numSRPMS);
336                 sourceURL = (sourceURL == NULL)
337                     ? xmalloc( (numSRPMS + 2) * sizeof(*sourceURL))
338                     : xrealloc(sourceURL, (numSRPMS + 2) * sizeof(*sourceURL));
339             sourceURL[numSRPMS++] = *fnp;
340             *fnp = NULL;
341             continue;
342         }
343         if (rpmrc == RPMRC_OK || rpmrc == RPMRC_BADSIZE) {
344             if (!dbIsOpen) {
345                 int mode = (transFlags & RPMTRANS_FLAG_TEST)
346                                 ? O_RDONLY : (O_RDWR | O_CREAT);
347
348                 if (rpmdbOpen(rootdir, &db, mode, 0644)) {
349                     const char *dn;
350                     dn = rpmGetPath( (rootdir ? rootdir : ""),
351                                         "%{_dbpath}", NULL);
352                     rpmMessage(RPMMESS_ERROR,
353                                 _("cannot open Packages database in %s\n"), dn);
354                     dn = _free(dn);
355                     numFailed++; *fnp = NULL;
356                     break;
357                 }
358                 ts = rpmtransCreateSet(db, rootdir);
359                 dbIsOpen = 1;
360             }
361
362             if (defaultReloc) {
363                 const char ** paths;
364                 int pft;
365                 int c;
366
367                 if (headerGetEntry(h, RPMTAG_PREFIXES, &pft,
368                                        (void **) &paths, &c) && (c == 1)) {
369                     defaultReloc->oldPath = xstrdup(paths[0]);
370                     paths = headerFreeData(paths, pft);
371                 } else {
372                     const char * name;
373                     headerNVR(h, &name, NULL, NULL);
374                     rpmMessage(RPMMESS_ERROR,
375                                _("package %s is not relocateable\n"), name);
376                     numFailed++;
377                     goto exit;
378                     /*@notreached@*/
379                 }
380             }
381
382             /* On --freshen, verify package is installed and newer */
383             if (interfaceFlags & INSTALL_FRESHEN) {
384                 rpmdbMatchIterator mi;
385                 const char * name;
386                 Header oldH;
387                 int count;
388
389                 headerNVR(h, &name, NULL, NULL);
390                 mi = rpmdbInitIterator(db, RPMTAG_NAME, name, 0);
391                 count = rpmdbGetIteratorCount(mi);
392                 while ((oldH = rpmdbNextIterator(mi)) != NULL) {
393                     if (rpmVersionCompare(oldH, h) < 0)
394                         continue;
395                     /* same or newer package already installed */
396                     count = 0;
397                     break;
398                 }
399                 rpmdbFreeIterator(mi);
400                 if (count == 0) {
401                     headerFree(h);
402                     continue;
403                     break;      /* XXX out of switch */
404                 }
405                 /* Package is newer than those currently installed. */
406             }
407
408             rc = rpmtransAddPackage(ts, h, NULL, fileName,
409                                (interfaceFlags & INSTALL_UPGRADE) != 0,
410                                relocations);
411             headerFree(h);      /* XXX reference held by transaction set */
412             if (defaultReloc)
413                 defaultReloc->oldPath = _free(defaultReloc->oldPath);
414
415             switch(rc) {
416             case 0:
417                 rpmMessage(RPMMESS_DEBUG, "\tadded binary rpm[%d]\n", numRPMS);
418                 break;
419             case 1:
420                 rpmMessage(RPMMESS_ERROR,
421                             _("error reading from file %s\n"), *fnp);
422                 numFailed++;
423                 goto exit;
424                 /*@notreached@*/ break;
425             case 2:
426                 rpmMessage(RPMMESS_ERROR,
427                             _("file %s requires a newer version of RPM\n"),
428                             *fnp);
429                 numFailed++;
430                 goto exit;
431                 /*@notreached@*/ break;
432             }
433
434             numRPMS++;
435             continue;
436         }
437
438         if (rpmrc != RPMRC_BADMAGIC) {
439             rpmMessage(RPMMESS_ERROR, _("%s cannot be installed\n"), *fnp);
440             numFailed++; *fnp = NULL;
441             break;
442         }
443
444         /* Try to read a package manifest. */
445         fd = Fopen(*fnp, "r.fpio");
446         if (fd == NULL || Ferror(fd)) {
447             rpmError(RPMERR_OPEN, _("open of %s failed: %s\n"), *fnp,
448                         Fstrerror(fd));
449             if (fd) Fclose(fd);
450             numFailed++; *fnp = NULL;
451             break;
452         }
453
454         /* Read list of packages from manifest. */
455         rc = rpmReadPackageManifest(fd, &argc, &argv);
456         if (rc)
457             rpmError(RPMERR_MANIFEST, _("%s: read manifest failed: %s\n"),
458                         fileURL, Fstrerror(fd));
459         Fclose(fd);
460
461         /* If successful, restart the query loop. */
462         if (rc == 0) {
463             prevx++;
464             goto restart;
465         }
466
467         numFailed++; *fnp = NULL;
468         break;
469     }
470
471     rpmMessage(RPMMESS_DEBUG, _("found %d source and %d binary packages\n"),
472                 numSRPMS, numRPMS);
473
474     if (numFailed) goto exit;
475
476     if (numRPMS && !(interfaceFlags & INSTALL_NODEPS)) {
477         struct rpmDependencyConflict * conflicts;
478         int numConflicts;
479
480         if (rpmdepCheck(ts, &conflicts, &numConflicts)) {
481             numFailed = numPkgs;
482             stopInstall = 1;
483         }
484
485         if (!stopInstall && conflicts) {
486             rpmMessage(RPMMESS_ERROR, _("failed dependencies:\n"));
487             printDepProblems(stderr, conflicts, numConflicts);
488             rpmdepFreeConflicts(conflicts, numConflicts);
489             numFailed = numPkgs;
490             stopInstall = 1;
491         }
492     }
493
494     if (numRPMS && !(interfaceFlags & INSTALL_NOORDER)) {
495         if (rpmdepOrder(ts)) {
496             numFailed = numPkgs;
497             stopInstall = 1;
498         }
499     }
500
501     if (numRPMS && !stopInstall) {
502         rpmProblemSet probs = NULL;
503
504 #ifdef FANCY_HASH
505         packagesTotal = numRPMS;
506 #endif
507         rpmMessage(RPMMESS_DEBUG, _("installing binary packages\n"));
508         rc = rpmRunTransactions(ts, showProgress, (void *) ((long)notifyFlags),
509                                     NULL, &probs, transFlags, probFilter);
510
511         if (rc < 0) {
512             numFailed += numRPMS;
513         } else if (rc > 0) {
514             numFailed += rc;
515             rpmProblemSetPrint(stderr, probs);
516         }
517
518         if (probs) rpmProblemSetFree(probs);
519     }
520
521     if (numSRPMS && !stopInstall) {
522         for (i = 0; i < numSRPMS; i++) {
523             fd = Fopen(sourceURL[i], "r.ufdio");
524             if (fd == NULL || Ferror(fd)) {
525                 rpmMessage(RPMMESS_ERROR, _("cannot open file %s: %s\n"),
526                            sourceURL[i], Fstrerror(fd));
527                 if (fd) Fclose(fd);
528                 continue;
529             }
530
531             if (!(transFlags & RPMTRANS_FLAG_TEST)) {
532                 rpmRC rpmrc = rpmInstallSourcePackage(rootdir, fd, NULL,
533                         showProgress, (void *) ((long)notifyFlags), NULL);
534                 if (rpmrc != RPMRC_OK) numFailed++;
535             }
536
537             Fclose(fd);
538         }
539     }
540
541 exit:
542     if (ts) rpmtransFree(ts);
543     for (i = 0; i < numPkgs; i++) {
544         if (pkgState[i] == 1)
545             Unlink(pkgURL[i]);
546         pkgURL[i] = _free(pkgURL[i]);
547     }
548     pkgState = _free(pkgState);
549     pkgURL = _free(pkgURL);
550     if (dbIsOpen) rpmdbClose(db);
551     return numFailed;
552 }
553
554 int rpmErase(const char * rootdir, const char ** argv,
555                 rpmtransFlags transFlags,
556                 rpmEraseInterfaceFlags interfaceFlags)
557 {
558     rpmdb db;
559     int mode;
560     int count;
561     const char ** arg;
562     int numFailed = 0;
563     rpmTransactionSet ts;
564     struct rpmDependencyConflict * conflicts;
565     int numConflicts;
566     int stopUninstall = 0;
567     int numPackages = 0;
568     rpmProblemSet probs;
569
570     if (transFlags & RPMTRANS_FLAG_TEST)
571         mode = O_RDONLY;
572     else
573         mode = O_RDWR | O_EXCL;
574         
575     if (rpmdbOpen(rootdir, &db, mode, 0644)) {
576         const char *dn;
577         dn = rpmGetPath( (rootdir ? rootdir : ""), "%{_dbpath}", NULL);
578         rpmMessage(RPMMESS_ERROR, _("cannot open %s/packages.rpm\n"), dn);
579         dn = _free(dn);
580         return -1;
581     }
582
583     ts = rpmtransCreateSet(db, rootdir);
584     for (arg = argv; *arg; arg++) {
585         rpmdbMatchIterator mi;
586
587         /* XXX HACK to get rpmdbFindByLabel out of the API */
588         mi = rpmdbInitIterator(db, RPMDBI_LABEL, *arg, 0);
589         count = rpmdbGetIteratorCount(mi);
590         if (count <= 0) {
591             rpmMessage(RPMMESS_ERROR, _("package %s is not installed\n"), *arg);
592             numFailed++;
593         } else if (!(count == 1 || (interfaceFlags & UNINSTALL_ALLMATCHES))) {
594             rpmMessage(RPMMESS_ERROR, _("\"%s\" specifies multiple packages\n"),
595                         *arg);
596             numFailed++;
597         } else {
598             Header h;   /* XXX iterator owns the reference */
599             while ((h = rpmdbNextIterator(mi)) != NULL) {
600                 unsigned int recOffset = rpmdbGetIteratorOffset(mi);
601                 if (recOffset) {
602                     rpmtransRemovePackage(ts, recOffset);
603                     numPackages++;
604                 }
605             }
606         }
607         rpmdbFreeIterator(mi);
608     }
609
610     if (!(interfaceFlags & UNINSTALL_NODEPS)) {
611         if (rpmdepCheck(ts, &conflicts, &numConflicts)) {
612             numFailed = numPackages;
613             stopUninstall = 1;
614         }
615
616         if (!stopUninstall && conflicts) {
617             rpmMessage(RPMMESS_ERROR, _("removing these packages would break "
618                               "dependencies:\n"));
619             printDepProblems(stderr, conflicts, numConflicts);
620             rpmdepFreeConflicts(conflicts, numConflicts);
621             numFailed += numPackages;
622             stopUninstall = 1;
623         }
624     }
625
626     if (!stopUninstall) {
627         transFlags |= RPMTRANS_FLAG_REVERSE;
628         numFailed += rpmRunTransactions(ts, NULL, NULL, NULL, &probs,
629                                         transFlags, 0);
630     }
631
632     rpmtransFree(ts);
633     rpmdbClose(db);
634
635     return numFailed;
636 }
637
638 int rpmInstallSource(const char * rootdir, const char * arg,
639                 const char ** specFile, char ** cookie)
640 {
641     FD_t fd;
642     int rc;
643
644     fd = Fopen(arg, "r.ufdio");
645     if (fd == NULL || Ferror(fd)) {
646         rpmMessage(RPMMESS_ERROR, _("cannot open %s: %s\n"), arg, Fstrerror(fd));
647         if (fd) Fclose(fd);
648         return 1;
649     }
650
651     if (rpmIsVerbose())
652         fprintf(stdout, _("Installing %s\n"), arg);
653
654     {   rpmRC rpmrc = rpmInstallSourcePackage(rootdir, fd, specFile, NULL, NULL,
655                                  cookie);
656         rc = (rpmrc == RPMRC_OK ? 0 : 1);
657     }
658     if (rc != 0) {
659         rpmMessage(RPMMESS_ERROR, _("%s cannot be installed\n"), arg);
660         if (specFile && *specFile)
661             *specFile = _free(*specFile);
662         if (cookie && *cookie)
663             *cookie = _free(*cookie);
664     }
665
666     Fclose(fd);
667
668     return rc;
669 }