Minor cleanup/simplification.
[oweals/opkg-lede.git] / libopkg / pkg.c
1 /* pkg.c - the opkg package management system
2
3    Carl D. Worth
4
5    Copyright (C) 2001 University of Southern California
6
7    This program is free software; you can redistribute it and/or
8    modify it under the terms of the GNU General Public License as
9    published by the Free Software Foundation; either version 2, or (at
10    your option) any later version.
11
12    This program is distributed in the hope that it will be useful, but
13    WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    General Public License for more details.
16 */
17
18 #include "config.h"
19
20 #include <stdio.h>
21 #include <string.h>
22 #include <ctype.h>
23 #include <unistd.h>
24
25 #include "pkg.h"
26
27 #include "pkg_parse.h"
28 #include "pkg_extract.h"
29 #include "opkg_message.h"
30 #include "opkg_utils.h"
31
32 #include "libbb/libbb.h"
33 #include "sprintf_alloc.h"
34 #include "file_util.h"
35 #include "xsystem.h"
36 #include "opkg_conf.h"
37
38 typedef struct enum_map enum_map_t;
39 struct enum_map
40 {
41      unsigned int value;
42      const char *str;
43 };
44
45 static const enum_map_t pkg_state_want_map[] = {
46      { SW_UNKNOWN, "unknown"},
47      { SW_INSTALL, "install"},
48      { SW_DEINSTALL, "deinstall"},
49      { SW_PURGE, "purge"}
50 };
51
52 static const enum_map_t pkg_state_flag_map[] = {
53      { SF_OK, "ok"},
54      { SF_REINSTREQ, "reinstreq"},
55      { SF_HOLD, "hold"},
56      { SF_REPLACE, "replace"},
57      { SF_NOPRUNE, "noprune"},
58      { SF_PREFER, "prefer"},
59      { SF_OBSOLETE, "obsolete"},
60      { SF_USER, "user"},
61 };
62
63 static const enum_map_t pkg_state_status_map[] = {
64      { SS_NOT_INSTALLED, "not-installed" },
65      { SS_UNPACKED, "unpacked" },
66      { SS_HALF_CONFIGURED, "half-configured" },
67      { SS_INSTALLED, "installed" },
68      { SS_HALF_INSTALLED, "half-installed" },
69      { SS_CONFIG_FILES, "config-files" },
70      { SS_POST_INST_FAILED, "post-inst-failed" },
71      { SS_REMOVAL_FAILED, "removal-failed" }
72 };
73
74 static void
75 pkg_init(pkg_t *pkg)
76 {
77      pkg->name = NULL;
78      pkg->epoch = 0;
79      pkg->version = NULL;
80      pkg->revision = NULL;
81      pkg->dest = NULL;
82      pkg->src = NULL;
83      pkg->architecture = NULL;
84      pkg->maintainer = NULL;
85      pkg->section = NULL;
86      pkg->description = NULL;
87      pkg->state_want = SW_UNKNOWN;
88      pkg->state_flag = SF_OK;
89      pkg->state_status = SS_NOT_INSTALLED;
90      pkg->depends_str = NULL;
91      pkg->provides_str = NULL;
92      pkg->depends_count = 0;
93      pkg->depends = NULL;
94      pkg->suggests_str = NULL;
95      pkg->recommends_str = NULL;
96      pkg->suggests_count = 0;
97      pkg->recommends_count = 0;
98      
99      active_list_init(&pkg->list);
100
101      pkg->conflicts = NULL;
102      pkg->conflicts_count = 0;
103
104      pkg->replaces = NULL;
105      pkg->replaces_count = 0;
106     
107      pkg->pre_depends_count = 0;
108      pkg->pre_depends_str = NULL;
109      pkg->provides_count = 0;
110      pkg->provides = NULL;
111      pkg->filename = NULL;
112      pkg->local_filename = NULL;
113      pkg->tmp_unpack_dir = NULL;
114      pkg->md5sum = NULL;
115 #if defined HAVE_SHA256
116      pkg->sha256sum = NULL;
117 #endif
118      pkg->size = 0;
119      pkg->installed_size = 0;
120      pkg->priority = NULL;
121      pkg->source = NULL;
122      conffile_list_init(&pkg->conffiles);
123      pkg->installed_files = NULL;
124      pkg->installed_files_ref_cnt = 0;
125      pkg->essential = 0;
126      pkg->provided_by_hand = 0;
127 }
128
129 pkg_t *
130 pkg_new(void)
131 {
132      pkg_t *pkg;
133
134      pkg = xcalloc(1, sizeof(pkg_t));
135      pkg_init(pkg);
136
137      return pkg;
138 }
139
140 static void
141 compound_depend_deinit(compound_depend_t *depends)
142 {
143     int i;
144     for (i = 0; i < depends->possibility_count; i++)
145     {
146         depend_t *d;
147         d = depends->possibilities[i];
148         free (d->version);
149         free (d);
150     }
151     free (depends->possibilities);
152 }
153
154 void
155 pkg_deinit(pkg_t *pkg)
156 {
157         int i;
158
159         if (pkg->name)
160                 free(pkg->name);
161         pkg->name = NULL;
162
163         pkg->epoch = 0;
164
165         if (pkg->version)
166                 free(pkg->version);
167         pkg->version = NULL;
168         /* revision shares storage with version, so don't free */
169         pkg->revision = NULL;
170
171         /* owned by opkg_conf_t */
172         pkg->dest = NULL;
173         /* owned by opkg_conf_t */
174         pkg->src = NULL;
175
176         if (pkg->architecture)
177                 free(pkg->architecture);
178         pkg->architecture = NULL;
179
180         if (pkg->maintainer)
181                 free(pkg->maintainer);
182         pkg->maintainer = NULL;
183
184         if (pkg->section)
185                 free(pkg->section);
186         pkg->section = NULL;
187
188         if (pkg->description)
189                 free(pkg->description);
190         pkg->description = NULL;
191         
192         pkg->state_want = SW_UNKNOWN;
193         pkg->state_flag = SF_OK;
194         pkg->state_status = SS_NOT_INSTALLED;
195
196         active_list_clear(&pkg->list);
197
198         if (pkg->replaces)
199                 free (pkg->replaces);
200         pkg->replaces = NULL;
201
202         if (pkg->depends) {
203                 int count = pkg->pre_depends_count
204                                 + pkg->depends_count
205                                 + pkg->recommends_count
206                                 + pkg->suggests_count;
207
208                 for (i=0; i<count; i++)
209                         compound_depend_deinit (&pkg->depends[i]);
210                 free (pkg->depends);
211         }
212
213         if (pkg->conflicts) {
214                 for (i=0; i<pkg->conflicts_count; i++)
215                         compound_depend_deinit (&pkg->conflicts[i]);
216                 free (pkg->conflicts);
217         }
218
219         if (pkg->provides)
220                 free (pkg->provides);
221
222         pkg->pre_depends_count = 0;
223         pkg->provides_count = 0;
224         
225         if (pkg->filename)
226                 free(pkg->filename);
227         pkg->filename = NULL;
228         
229         if (pkg->local_filename)
230                 free(pkg->local_filename);
231         pkg->local_filename = NULL;
232
233      /* CLEANUP: It'd be nice to pullin the cleanup function from
234         opkg_install.c here. See comment in
235         opkg_install.c:cleanup_temporary_files */
236         if (pkg->tmp_unpack_dir)
237                 free(pkg->tmp_unpack_dir);
238         pkg->tmp_unpack_dir = NULL;
239
240         if (pkg->md5sum)
241                 free(pkg->md5sum);
242         pkg->md5sum = NULL;
243
244 #if defined HAVE_SHA256
245         if (pkg->sha256sum)
246                 free(pkg->sha256sum);
247         pkg->sha256sum = NULL;
248 #endif
249
250         if (pkg->priority)
251                 free(pkg->priority);
252         pkg->priority = NULL;
253
254         if (pkg->source)
255                 free(pkg->source);
256         pkg->source = NULL;
257
258         conffile_list_deinit(&pkg->conffiles);
259
260         /* XXX: QUESTION: Is forcing this to 1 correct? I suppose so,
261         since if they are calling deinit, they should know. Maybe do an
262         assertion here instead? */
263         pkg->installed_files_ref_cnt = 1;
264         pkg_free_installed_files(pkg);
265         pkg->essential = 0;
266
267         if (pkg->tags)
268                 free (pkg->tags);
269         pkg->tags = NULL;
270 }
271
272 int
273 pkg_init_from_file(pkg_t *pkg, const char *filename)
274 {
275         int fd, err = 0;
276         FILE *control_file;
277         char *control_path, *tmp;
278
279         pkg_init(pkg);
280
281         pkg->local_filename = xstrdup(filename);
282
283         tmp = xstrdup(filename);
284         sprintf_alloc(&control_path, "%s/%s.control.XXXXXX", 
285                         conf->tmp_dir,
286                         basename(tmp));
287         free(tmp);
288         fd = mkstemp(control_path);
289         if (fd == -1) {
290                 opkg_perror(ERROR, "Failed to make temp file %s", control_path);
291                 err = -1;
292                 goto err0;
293         }
294
295         control_file = fdopen(fd, "r+");
296         if (control_file == NULL) {
297                 opkg_perror(ERROR, "Failed to fdopen %s", control_path);
298                 close(fd);
299                 err = -1;
300                 goto err1;
301         }
302
303         err = pkg_extract_control_file_to_stream(pkg, control_file);
304         if (err) {
305                 opkg_msg(ERROR, "Failed to extract control file from %s.\n",
306                                 filename);
307                 goto err2;
308         }
309
310         rewind(control_file);
311
312         if ((err = pkg_parse_from_stream(pkg, control_file, 0))) {
313                 if (err == 1) {
314                         opkg_msg(ERROR, "Malformed package file %s.\n",
315                                 filename);
316                 }
317                 err = -1;
318         }
319
320 err2:
321         fclose(control_file);
322 err1:
323         unlink(control_path);
324 err0:
325         free(control_path);
326
327         return err;
328 }
329
330 /* Merge any new information in newpkg into oldpkg */
331 int
332 pkg_merge(pkg_t *oldpkg, pkg_t *newpkg)
333 {
334      if (oldpkg == newpkg) {
335           return 0;
336      }
337
338      if (!oldpkg->auto_installed)
339           oldpkg->auto_installed = newpkg->auto_installed;
340
341      if (!oldpkg->src)
342           oldpkg->src = newpkg->src;
343      if (!oldpkg->dest)
344           oldpkg->dest = newpkg->dest;
345      if (!oldpkg->architecture)
346           oldpkg->architecture = xstrdup(newpkg->architecture);
347      if (!oldpkg->arch_priority)
348           oldpkg->arch_priority = newpkg->arch_priority;
349      if (!oldpkg->section)
350           oldpkg->section = xstrdup(newpkg->section);
351      if(!oldpkg->maintainer)
352           oldpkg->maintainer = xstrdup(newpkg->maintainer);
353      if(!oldpkg->description)
354           oldpkg->description = xstrdup(newpkg->description);
355
356      if (!oldpkg->depends_count && !oldpkg->pre_depends_count && !oldpkg->recommends_count && !oldpkg->suggests_count) {
357           oldpkg->depends_count = newpkg->depends_count;
358           newpkg->depends_count = 0;
359
360           oldpkg->depends = newpkg->depends;
361           newpkg->depends = NULL;
362
363           oldpkg->pre_depends_count = newpkg->pre_depends_count;
364           newpkg->pre_depends_count = 0;
365
366           oldpkg->recommends_count = newpkg->recommends_count;
367           newpkg->recommends_count = 0;
368
369           oldpkg->suggests_count = newpkg->suggests_count;
370           newpkg->suggests_count = 0;
371      }
372
373      if (oldpkg->provides_count <= 1) {
374           oldpkg->provides_count = newpkg->provides_count;
375           newpkg->provides_count = 0;
376
377           if (!oldpkg->provides) {
378                 oldpkg->provides = newpkg->provides;
379                 newpkg->provides = NULL;
380           }
381      }
382
383      if (!oldpkg->conflicts_count) {
384           oldpkg->conflicts_count = newpkg->conflicts_count;
385           newpkg->conflicts_count = 0;
386
387           oldpkg->conflicts = newpkg->conflicts;
388           newpkg->conflicts = NULL;
389      }
390
391      if (!oldpkg->replaces_count) {
392           oldpkg->replaces_count = newpkg->replaces_count;
393           newpkg->replaces_count = 0;
394
395           oldpkg->replaces = newpkg->replaces;
396           newpkg->replaces = NULL;
397      }
398
399      if (!oldpkg->filename)
400           oldpkg->filename = xstrdup(newpkg->filename);
401      if (!oldpkg->local_filename)
402           oldpkg->local_filename = xstrdup(newpkg->local_filename);
403      if (!oldpkg->tmp_unpack_dir)
404           oldpkg->tmp_unpack_dir = xstrdup(newpkg->tmp_unpack_dir);
405      if (!oldpkg->md5sum)
406           oldpkg->md5sum = xstrdup(newpkg->md5sum);
407 #if defined HAVE_SHA256
408      if (!oldpkg->sha256sum)
409           oldpkg->sha256sum = xstrdup(newpkg->sha256sum);
410 #endif
411      if (!oldpkg->size)
412           oldpkg->size = newpkg->size;
413      if (!oldpkg->installed_size)
414           oldpkg->installed_size = newpkg->installed_size;
415      if (!oldpkg->priority)
416           oldpkg->priority = xstrdup(newpkg->priority);
417      if (!oldpkg->source)
418           oldpkg->source = xstrdup(newpkg->source);
419
420      if (nv_pair_list_empty(&oldpkg->conffiles)){
421           list_splice_init(&newpkg->conffiles.head, &oldpkg->conffiles.head);
422      }
423
424      if (!oldpkg->installed_files){
425           oldpkg->installed_files = newpkg->installed_files;
426           oldpkg->installed_files_ref_cnt = newpkg->installed_files_ref_cnt;
427           newpkg->installed_files = NULL;
428      }
429
430      if (!oldpkg->essential)
431           oldpkg->essential = newpkg->essential;
432
433      return 0;
434 }
435
436 static void
437 abstract_pkg_init(abstract_pkg_t *ab_pkg)
438 {
439      ab_pkg->provided_by = abstract_pkg_vec_alloc();
440      ab_pkg->dependencies_checked = 0;
441      ab_pkg->state_status = SS_NOT_INSTALLED;
442 }
443
444 abstract_pkg_t *
445 abstract_pkg_new(void)
446 {
447      abstract_pkg_t * ab_pkg;
448
449      ab_pkg = xcalloc(1, sizeof(abstract_pkg_t));
450      abstract_pkg_init(ab_pkg);
451
452      return ab_pkg;
453 }
454
455 void
456 set_flags_from_control(pkg_t *pkg){
457      char *file_name;
458      FILE *fp;
459
460      sprintf_alloc(&file_name,"%s/%s.control", pkg->dest->info_dir, pkg->name);
461
462      fp = fopen(file_name, "r");
463      if (fp == NULL) {
464              opkg_perror(ERROR, "Failed to open %s");
465              free(file_name);
466              return;
467      }
468
469      free(file_name);
470
471      if (pkg_parse_from_stream(pkg, fp, PFM_ALL ^ PFM_ESSENTIAL)) {
472         opkg_msg(DEBUG, "Unable to read control file for %s. May be empty.\n",
473                         pkg->name);
474      }
475
476      fclose(fp);
477
478      return;
479 }
480
481 static const char *
482 pkg_state_want_to_str(pkg_state_want_t sw)
483 {
484      int i;
485
486      for (i=0; i < ARRAY_SIZE(pkg_state_want_map); i++) {
487           if (pkg_state_want_map[i].value == sw) {
488                return pkg_state_want_map[i].str;
489           }
490      }
491
492      opkg_msg(ERROR, "Internal error: state_want=%d\n", sw);
493      return "<STATE_WANT_UNKNOWN>";
494 }
495
496 pkg_state_want_t
497 pkg_state_want_from_str(char *str)
498 {
499      int i;
500
501      for (i=0; i < ARRAY_SIZE(pkg_state_want_map); i++) {
502           if (strcmp(str, pkg_state_want_map[i].str) == 0) {
503                return pkg_state_want_map[i].value;
504           }
505      }
506
507      opkg_msg(ERROR, "Internal error: state_want=%s\n", str);
508      return SW_UNKNOWN;
509 }
510
511 static char *
512 pkg_state_flag_to_str(pkg_state_flag_t sf)
513 {
514         int i;
515         unsigned int len;
516         char *str;
517
518         /* clear the temporary flags before converting to string */
519         sf &= SF_NONVOLATILE_FLAGS;
520
521         if (sf == 0)
522                 return xstrdup("ok");
523
524         len = 0;
525         for (i=0; i < ARRAY_SIZE(pkg_state_flag_map); i++) {
526                 if (sf & pkg_state_flag_map[i].value)
527                         len += strlen(pkg_state_flag_map[i].str) + 1;
528         }
529
530         str = xmalloc(len+1);
531         str[0] = '\0';
532
533         for (i=0; i < ARRAY_SIZE(pkg_state_flag_map); i++) {
534                 if (sf & pkg_state_flag_map[i].value) {
535                         strncat(str, pkg_state_flag_map[i].str, len);
536                         strncat(str, ",", len);
537                 }
538         }
539
540         len = strlen(str);
541         str[len-1] = '\0'; /* squash last comma */
542
543         return str;
544 }
545
546 pkg_state_flag_t
547 pkg_state_flag_from_str(const char *str)
548 {
549      int i;
550      int sf = SF_OK;
551      const char *sfname;
552      unsigned int sfname_len;
553
554      if (strcmp(str, "ok") == 0) {
555           return SF_OK;
556      }
557      for (i=0; i < ARRAY_SIZE(pkg_state_flag_map); i++) {
558           sfname = pkg_state_flag_map[i].str;
559           sfname_len = strlen(sfname);
560           if (strncmp(str, sfname, sfname_len) == 0) {
561                sf |= pkg_state_flag_map[i].value;
562                str += sfname_len;
563                if (str[0] == ',') {
564                     str++;
565                } else {
566                     break;
567                }
568           }
569      }
570
571      return sf;
572 }
573
574 static const char *
575 pkg_state_status_to_str(pkg_state_status_t ss)
576 {
577      int i;
578
579      for (i=0; i < ARRAY_SIZE(pkg_state_status_map); i++) {
580           if (pkg_state_status_map[i].value == ss) {
581                return pkg_state_status_map[i].str;
582           }
583      }
584
585      opkg_msg(ERROR, "Internal error: state_status=%d\n", ss);
586      return "<STATE_STATUS_UNKNOWN>";
587 }
588
589 pkg_state_status_t
590 pkg_state_status_from_str(const char *str)
591 {
592      int i;
593
594      for (i=0; i < ARRAY_SIZE(pkg_state_status_map); i++) {
595           if (strcmp(str, pkg_state_status_map[i].str) == 0) {
596                return pkg_state_status_map[i].value;
597           }
598      }
599
600      opkg_msg(ERROR, "Internal error: state_status=%s\n", str);
601      return SS_NOT_INSTALLED;
602 }
603
604 void
605 pkg_formatted_field(FILE *fp, pkg_t *pkg, const char *field)
606 {
607      int i, j;
608      char *str;
609      int depends_count = pkg->pre_depends_count +
610                          pkg->depends_count +
611                          pkg->recommends_count +
612                          pkg->suggests_count;
613
614      if (strlen(field) < PKG_MINIMUM_FIELD_NAME_LEN) {
615           goto UNKNOWN_FMT_FIELD;
616      }
617
618      switch (field[0])
619      {
620      case 'a':
621      case 'A':
622           if (strcasecmp(field, "Architecture") == 0) {
623                if (pkg->architecture) {
624                    fprintf(fp, "Architecture: %s\n", pkg->architecture);
625                }
626           } else if (strcasecmp(field, "Auto-Installed") == 0) {
627                 if (pkg->auto_installed)
628                     fprintf(fp, "Auto-Installed: yes\n");
629           } else {
630                goto UNKNOWN_FMT_FIELD;
631           }
632           break;
633      case 'c':
634      case 'C':
635           if (strcasecmp(field, "Conffiles") == 0) {
636                conffile_list_elt_t *iter;
637
638                if (nv_pair_list_empty(&pkg->conffiles))
639                     return;
640
641                fprintf(fp, "Conffiles:\n");
642                for (iter = nv_pair_list_first(&pkg->conffiles); iter; iter = nv_pair_list_next(&pkg->conffiles, iter)) {
643                     if (((conffile_t *)iter->data)->name && ((conffile_t *)iter->data)->value) {
644                          fprintf(fp, " %s %s\n", 
645                                  ((conffile_t *)iter->data)->name, 
646                                  ((conffile_t *)iter->data)->value);
647                     }
648                }
649           } else if (strcasecmp(field, "Conflicts") == 0) {
650                struct depend *cdep;
651                if (pkg->conflicts_count) {
652                     fprintf(fp, "Conflicts:");
653                     for(i = 0; i < pkg->conflicts_count; i++) {
654                         cdep = pkg->conflicts[i].possibilities[0];
655                         fprintf(fp, "%s %s", i == 0 ? "" : ",",
656                                 cdep->pkg->name);
657                         if (cdep->version) {
658                                 fprintf(fp, " (%s%s)",
659                                         constraint_to_str(cdep->constraint),
660                                         cdep->version);
661                         }
662                     }
663                     fprintf(fp, "\n");
664                }
665           } else {
666                goto UNKNOWN_FMT_FIELD;
667           }
668           break;
669      case 'd':
670      case 'D':
671           if (strcasecmp(field, "Depends") == 0) {
672                if (pkg->depends_count) {
673                     fprintf(fp, "Depends:");
674                     for (j=0, i=0; i<depends_count; i++) {
675                         if (pkg->depends[i].type != DEPEND)
676                                 continue;
677                         str = pkg_depend_str(pkg, i);
678                         fprintf(fp, "%s %s", j == 0 ? "" : ",", str);
679                         free(str);
680                         j++;
681                     }
682                     fprintf(fp, "\n");
683                }
684           } else if (strcasecmp(field, "Description") == 0) {
685                if (pkg->description) {
686                    fprintf(fp, "Description: %s\n", pkg->description);
687                }
688           } else {
689                goto UNKNOWN_FMT_FIELD;
690           }
691           break;
692      case 'e':
693      case 'E':
694           if (pkg->essential) {
695               fprintf(fp, "Essential: yes\n");
696           }
697           break;
698      case 'f':
699      case 'F':
700           if (pkg->filename) {
701               fprintf(fp, "Filename: %s\n", pkg->filename);
702           }
703           break;
704      case 'i':
705      case 'I':
706           if (strcasecmp(field, "Installed-Size") == 0) {
707                fprintf(fp, "Installed-Size: %ld\n", pkg->installed_size);
708           } else if (strcasecmp(field, "Installed-Time") == 0 && pkg->installed_time) {
709                fprintf(fp, "Installed-Time: %lu\n", pkg->installed_time);
710           }
711           break;
712      case 'm':
713      case 'M':
714           if (strcasecmp(field, "Maintainer") == 0) {
715                if (pkg->maintainer) {
716                    fprintf(fp, "maintainer: %s\n", pkg->maintainer);
717                }
718           } else if (strcasecmp(field, "MD5sum") == 0) {
719                if (pkg->md5sum) {
720                    fprintf(fp, "MD5Sum: %s\n", pkg->md5sum);
721                }
722           } else {
723                goto UNKNOWN_FMT_FIELD;
724           }
725           break;
726      case 'p':
727      case 'P':
728           if (strcasecmp(field, "Package") == 0) {
729                fprintf(fp, "Package: %s\n", pkg->name);
730           } else if (strcasecmp(field, "Priority") == 0) {
731                fprintf(fp, "Priority: %s\n", pkg->priority);
732           } else if (strcasecmp(field, "Provides") == 0) {
733                if (pkg->provides_count) {
734                   fprintf(fp, "Provides:");
735                   for(i = 1; i < pkg->provides_count; i++) {
736                       fprintf(fp, "%s %s", i == 1 ? "" : ",",
737                                       pkg->provides[i]->name);
738                   }
739                   fprintf(fp, "\n");
740                }
741           } else {
742                goto UNKNOWN_FMT_FIELD;
743           }
744           break;
745      case 'r':
746      case 'R':
747           if (strcasecmp (field, "Replaces") == 0) {
748                if (pkg->replaces_count) {
749                     fprintf(fp, "Replaces:");
750                     for (i = 0; i < pkg->replaces_count; i++) {
751                         fprintf(fp, "%s %s", i == 0 ? "" : ",",
752                                         pkg->replaces[i]->name);
753                     }
754                     fprintf(fp, "\n");
755                }
756           } else if (strcasecmp (field, "Recommends") == 0) {
757                if (pkg->recommends_count) {
758                     fprintf(fp, "Recommends:");
759                     for (j=0, i=0; i<depends_count; i++) {
760                         if (pkg->depends[i].type != RECOMMEND)
761                                 continue;
762                         str = pkg_depend_str(pkg, i);
763                         fprintf(fp, "%s %s", j == 0 ? "" : ",", str);
764                         free(str);
765                         j++;
766                     }
767                     fprintf(fp, "\n");
768                }
769           } else {
770                goto UNKNOWN_FMT_FIELD;
771           }
772           break;
773      case 's':
774      case 'S':
775           if (strcasecmp(field, "Section") == 0) {
776                if (pkg->section) {
777                    fprintf(fp, "Section: %s\n", pkg->section);
778                }
779 #if defined HAVE_SHA256
780           } else if (strcasecmp(field, "SHA256sum") == 0) {
781                if (pkg->sha256sum) {
782                    fprintf(fp, "SHA256sum: %s\n", pkg->sha256sum);
783                }
784 #endif
785           } else if (strcasecmp(field, "Size") == 0) {
786                if (pkg->size) {
787                    fprintf(fp, "Size: %ld\n", pkg->size);
788                }
789           } else if (strcasecmp(field, "Source") == 0) {
790                if (pkg->source) {
791                    fprintf(fp, "Source: %s\n", pkg->source);
792                }
793           } else if (strcasecmp(field, "Status") == 0) {
794                char *pflag = pkg_state_flag_to_str(pkg->state_flag);
795                fprintf(fp, "Status: %s %s %s\n",
796                                pkg_state_want_to_str(pkg->state_want),
797                                pflag,
798                                pkg_state_status_to_str(pkg->state_status));
799                free(pflag);
800           } else if (strcasecmp(field, "Suggests") == 0) {
801                if (pkg->suggests_count) {
802                     fprintf(fp, "Suggests:");
803                     for (j=0, i=0; i<depends_count; i++) {
804                         if (pkg->depends[i].type != SUGGEST)
805                                 continue;
806                         str = pkg_depend_str(pkg, i);
807                         fprintf(fp, "%s %s", j == 0 ? "" : ",", str);
808                         free(str);
809                         j++;
810                     }
811                     fprintf(fp, "\n");
812                }
813           } else {
814                goto UNKNOWN_FMT_FIELD;
815           }
816           break;
817      case 't':
818      case 'T':
819           if (strcasecmp(field, "Tags") == 0) {
820                if (pkg->tags) {
821                    fprintf(fp, "Tags: %s\n", pkg->tags);
822                }
823           }
824           break;
825      case 'v':
826      case 'V':
827           {
828                char *version = pkg_version_str_alloc(pkg);
829                if (version == NULL)
830                     return;
831                fprintf(fp, "Version: %s\n", version);
832                free(version);
833           }
834           break;
835      default:
836           goto UNKNOWN_FMT_FIELD;
837      }
838
839      return;
840
841 UNKNOWN_FMT_FIELD:
842      opkg_msg(ERROR, "Internal error: field=%s\n", field);
843 }
844
845 void
846 pkg_formatted_info(FILE *fp, pkg_t *pkg)
847 {
848         pkg_formatted_field(fp, pkg, "Package");
849         pkg_formatted_field(fp, pkg, "Version");
850         pkg_formatted_field(fp, pkg, "Depends");
851         pkg_formatted_field(fp, pkg, "Recommends");
852         pkg_formatted_field(fp, pkg, "Suggests");
853         pkg_formatted_field(fp, pkg, "Provides");
854         pkg_formatted_field(fp, pkg, "Replaces");
855         pkg_formatted_field(fp, pkg, "Conflicts");
856         pkg_formatted_field(fp, pkg, "Status");
857         pkg_formatted_field(fp, pkg, "Section");
858         pkg_formatted_field(fp, pkg, "Essential");
859         pkg_formatted_field(fp, pkg, "Architecture");
860         pkg_formatted_field(fp, pkg, "Maintainer");
861         pkg_formatted_field(fp, pkg, "MD5sum");
862         pkg_formatted_field(fp, pkg, "Size");
863         pkg_formatted_field(fp, pkg, "Filename");
864         pkg_formatted_field(fp, pkg, "Conffiles");
865         pkg_formatted_field(fp, pkg, "Source");
866         pkg_formatted_field(fp, pkg, "Description");
867         pkg_formatted_field(fp, pkg, "Installed-Time");
868         pkg_formatted_field(fp, pkg, "Tags");
869         fputs("\n", fp);
870 }
871
872 void
873 pkg_print_status(pkg_t * pkg, FILE * file)
874 {
875      if (pkg == NULL) {
876           return;
877      }
878
879      pkg_formatted_field(file, pkg, "Package");
880      pkg_formatted_field(file, pkg, "Version");
881      pkg_formatted_field(file, pkg, "Depends");
882      pkg_formatted_field(file, pkg, "Recommends");
883      pkg_formatted_field(file, pkg, "Suggests");
884      pkg_formatted_field(file, pkg, "Provides");
885      pkg_formatted_field(file, pkg, "Replaces");
886      pkg_formatted_field(file, pkg, "Conflicts");
887      pkg_formatted_field(file, pkg, "Status");
888      pkg_formatted_field(file, pkg, "Essential");
889      pkg_formatted_field(file, pkg, "Architecture");
890      pkg_formatted_field(file, pkg, "Conffiles");
891      pkg_formatted_field(file, pkg, "Installed-Time");
892      pkg_formatted_field(file, pkg, "Auto-Installed");
893      fputs("\n", file);
894 }
895
896 /*
897  * libdpkg - Debian packaging suite library routines
898  * vercmp.c - comparison of version numbers
899  *
900  * Copyright (C) 1995 Ian Jackson <iwj10@cus.cam.ac.uk>
901  */
902
903 /* assume ascii; warning: evaluates x multiple times! */
904 #define order(x) ((x) == '~' ? -1 \
905                 : isdigit((x)) ? 0 \
906                 : !(x) ? 0 \
907                 : isalpha((x)) ? (x) \
908                 : (x) + 256)
909
910 static int
911 verrevcmp(const char *val, const char *ref) {
912   if (!val) val= "";
913   if (!ref) ref= "";
914
915   while (*val || *ref) {
916     int first_diff= 0;
917
918     while ( (*val && !isdigit(*val)) || (*ref && !isdigit(*ref)) ) {
919       int vc= order(*val), rc= order(*ref);
920       if (vc != rc) return vc - rc;
921       val++; ref++;
922     }
923
924     while ( *val == '0' ) val++;
925     while ( *ref == '0' ) ref++;
926     while (isdigit(*val) && isdigit(*ref)) {
927       if (!first_diff) first_diff= *val - *ref;
928       val++; ref++;
929     }
930     if (isdigit(*val)) return 1;
931     if (isdigit(*ref)) return -1;
932     if (first_diff) return first_diff;
933   }
934   return 0;
935 }
936
937 int
938 pkg_compare_versions(const pkg_t *pkg, const pkg_t *ref_pkg)
939 {
940      int r;
941
942      if (pkg->epoch > ref_pkg->epoch) {
943           return 1;
944      }
945
946      if (pkg->epoch < ref_pkg->epoch) {
947           return -1;
948      }
949
950      r = verrevcmp(pkg->version, ref_pkg->version);
951      if (r) {
952           return r;
953      }
954
955      r = verrevcmp(pkg->revision, ref_pkg->revision);
956      if (r) {
957           return r;
958      }
959
960      return r;
961 }
962
963
964 int
965 pkg_version_satisfied(pkg_t *it, pkg_t *ref, const char *op)
966 {
967      int r;
968
969      r = pkg_compare_versions(it, ref);
970
971      if (strcmp(op, "<=") == 0 || strcmp(op, "<") == 0) {
972           return r <= 0;
973      }
974
975      if (strcmp(op, ">=") == 0 || strcmp(op, ">") == 0) {
976           return r >= 0;
977      }
978
979      if (strcmp(op, "<<") == 0) {
980           return r < 0;
981      }
982
983      if (strcmp(op, ">>") == 0) {
984           return r > 0;
985      }
986
987      if (strcmp(op, "=") == 0) {
988           return r == 0;
989      }
990
991      opkg_msg(ERROR, "Unknown operator: %s.\n", op);
992      return 0;
993 }
994
995 int
996 pkg_name_version_and_architecture_compare(const void *p1, const void *p2)
997 {
998      const pkg_t *a = *(const pkg_t**) p1;
999      const pkg_t *b = *(const pkg_t**) p2;
1000      int namecmp;
1001      int vercmp;
1002      if (!a->name || !b->name) {
1003        opkg_msg(ERROR, "Internal error: a->name=%p, b->name=%p.\n",
1004                a->name, b->name);
1005        return 0;
1006      }
1007        
1008      namecmp = strcmp(a->name, b->name);
1009      if (namecmp)
1010           return namecmp;
1011      vercmp = pkg_compare_versions(a, b);
1012      if (vercmp)
1013           return vercmp;
1014      if (!a->arch_priority || !b->arch_priority) {
1015        opkg_msg(ERROR, "Internal error: a->arch_priority=%i b->arch_priority=%i.\n",
1016                a->arch_priority, b->arch_priority);
1017        return 0;
1018      }
1019      if (a->arch_priority > b->arch_priority)
1020           return 1;
1021      if (a->arch_priority < b->arch_priority)
1022           return -1;
1023      return 0;
1024 }
1025
1026 int
1027 abstract_pkg_name_compare(const void *p1, const void *p2)
1028 {
1029      const abstract_pkg_t *a = *(const abstract_pkg_t **)p1;
1030      const abstract_pkg_t *b = *(const abstract_pkg_t **)p2;
1031      if (!a->name || !b->name) {
1032        opkg_msg(ERROR, "Internal error: a->name=%p b->name=%p.\n",
1033                a->name, b->name);
1034        return 0;
1035      }
1036      return strcmp(a->name, b->name);
1037 }
1038
1039
1040 char *
1041 pkg_version_str_alloc(pkg_t *pkg)
1042 {
1043         char *version;
1044
1045         if (pkg->epoch) {
1046                 if (pkg->revision)
1047                         sprintf_alloc(&version, "%d:%s-%s",
1048                                 pkg->epoch, pkg->version, pkg->revision);
1049                 else
1050                         sprintf_alloc(&version, "%d:%s",
1051                                 pkg->epoch, pkg->version);
1052         } else {
1053                 if (pkg->revision)
1054                         sprintf_alloc(&version, "%s-%s",
1055                                 pkg->version, pkg->revision);
1056                 else
1057                         version = xstrdup(pkg->version);
1058         }
1059
1060         return version;
1061 }
1062
1063 /*
1064  * XXX: this should be broken into two functions
1065  */
1066 str_list_t *
1067 pkg_get_installed_files(pkg_t *pkg)
1068 {
1069      int err, fd;
1070      char *list_file_name = NULL;
1071      FILE *list_file = NULL;
1072      char *line;
1073      char *installed_file_name;
1074      unsigned int rootdirlen = 0;
1075      int list_from_package;
1076
1077      pkg->installed_files_ref_cnt++;
1078
1079      if (pkg->installed_files) {
1080           return pkg->installed_files;
1081      }
1082
1083      pkg->installed_files = str_list_alloc();
1084
1085      /*
1086       * For installed packages, look at the package.list file in the database.
1087       * For uninstalled packages, get the file list directly from the package.
1088       */
1089      if (pkg->state_status == SS_NOT_INSTALLED || pkg->dest == NULL)
1090              list_from_package = 1;
1091      else
1092              list_from_package = 0;
1093
1094      if (list_from_package) {
1095           if (pkg->local_filename == NULL) {
1096                return pkg->installed_files;
1097           }
1098           /* XXX: CLEANUP: Maybe rewrite this to avoid using a temporary
1099              file. In other words, change deb_extract so that it can
1100              simply return the file list as a char *[] rather than
1101              insisting on writing it to a FILE * as it does now. */
1102           sprintf_alloc(&list_file_name, "%s/%s.list.XXXXXX",
1103                                           conf->tmp_dir, pkg->name);
1104           fd = mkstemp(list_file_name);
1105           if (fd == -1) {
1106                opkg_perror(ERROR, "Failed to make temp file %s.",
1107                                list_file_name);
1108                free(list_file_name);
1109                return pkg->installed_files;
1110           }
1111           list_file = fdopen(fd, "r+");
1112           if (list_file == NULL) {
1113                opkg_perror(ERROR, "Failed to fdopen temp file %s.",
1114                                list_file_name);
1115                close(fd);
1116                unlink(list_file_name);
1117                free(list_file_name);
1118                return pkg->installed_files;
1119           }
1120           err = pkg_extract_data_file_names_to_stream(pkg, list_file);
1121           if (err) {
1122                opkg_msg(ERROR, "Error extracting file list from %s.\n",
1123                                pkg->local_filename);
1124                fclose(list_file);
1125                unlink(list_file_name);
1126                free(list_file_name);
1127                str_list_deinit(pkg->installed_files);
1128                pkg->installed_files = NULL;
1129                return NULL;
1130           }
1131           rewind(list_file);
1132      } else {
1133           sprintf_alloc(&list_file_name, "%s/%s.list",
1134                         pkg->dest->info_dir, pkg->name);
1135           list_file = fopen(list_file_name, "r");
1136           if (list_file == NULL) {
1137                opkg_perror(ERROR, "Failed to open %s",
1138                        list_file_name);
1139                free(list_file_name);
1140                return pkg->installed_files;
1141           }
1142           free(list_file_name);
1143      }
1144
1145      if (conf->offline_root)
1146           rootdirlen = strlen(conf->offline_root);
1147
1148      while (1) {
1149           char *file_name;
1150         
1151           line = file_read_line_alloc(list_file);
1152           if (line == NULL) {
1153                break;
1154           }
1155           file_name = line;
1156
1157           if (list_from_package) {
1158                if (*file_name == '.') {
1159                     file_name++;
1160                }
1161                if (*file_name == '/') {
1162                     file_name++;
1163                }
1164                sprintf_alloc(&installed_file_name, "%s%s",
1165                                pkg->dest->root_dir, file_name);
1166           } else {
1167                if (conf->offline_root &&
1168                        strncmp(conf->offline_root, file_name, rootdirlen)) {
1169                     sprintf_alloc(&installed_file_name, "%s%s",
1170                                     conf->offline_root, file_name);
1171                } else {
1172                     // already contains root_dir as header -> ABSOLUTE
1173                     sprintf_alloc(&installed_file_name, "%s", file_name);
1174                }
1175           }
1176           str_list_append(pkg->installed_files, installed_file_name);
1177           free(installed_file_name);
1178           free(line);
1179      }
1180
1181      fclose(list_file);
1182
1183      if (list_from_package) {
1184           unlink(list_file_name);
1185           free(list_file_name);
1186      }
1187
1188      return pkg->installed_files;
1189 }
1190
1191 /* XXX: CLEANUP: This function and it's counterpart,
1192    (pkg_get_installed_files), do not match our init/deinit naming
1193    convention. Nor the alloc/free convention. But, then again, neither
1194    of these conventions currrently fit the way these two functions
1195    work. */
1196 void
1197 pkg_free_installed_files(pkg_t *pkg)
1198 {
1199      pkg->installed_files_ref_cnt--;
1200
1201      if (pkg->installed_files_ref_cnt > 0)
1202           return;
1203
1204      if (pkg->installed_files) {
1205          str_list_purge(pkg->installed_files);
1206      }
1207
1208      pkg->installed_files = NULL;
1209 }
1210
1211 void
1212 pkg_remove_installed_files_list(pkg_t *pkg)
1213 {
1214         char *list_file_name;
1215
1216         sprintf_alloc(&list_file_name, "%s/%s.list",
1217                 pkg->dest->info_dir, pkg->name);
1218
1219         if (!conf->noaction)
1220                 (void)unlink(list_file_name);
1221
1222         free(list_file_name);
1223 }
1224
1225 conffile_t *
1226 pkg_get_conffile(pkg_t *pkg, const char *file_name)
1227 {
1228      conffile_list_elt_t *iter;
1229      conffile_t *conffile;
1230
1231      if (pkg == NULL) {
1232           return NULL;
1233      }
1234
1235      for (iter = nv_pair_list_first(&pkg->conffiles); iter; iter = nv_pair_list_next(&pkg->conffiles, iter)) {
1236           conffile = (conffile_t *)iter->data;
1237
1238           if (strcmp(conffile->name, file_name) == 0) {
1239                return conffile;
1240           }
1241      }
1242
1243      return NULL;
1244 }
1245
1246 int
1247 pkg_run_script(pkg_t *pkg, const char *script, const char *args)
1248 {
1249      int err;
1250      char *path;
1251      char *cmd;
1252
1253      if (conf->noaction)
1254              return 0;
1255
1256      /* XXX: FEATURE: When conf->offline_root is set, we should run the
1257         maintainer script within a chroot environment. */
1258      if (conf->offline_root) {
1259           opkg_msg(INFO, "Offline root mode: not running %s.%s.\n",
1260                           pkg->name, script);
1261           return 0;
1262      }
1263
1264      /* Installed packages have scripts in pkg->dest->info_dir, uninstalled packages
1265         have scripts in pkg->tmp_unpack_dir. */
1266      if (pkg->state_status == SS_INSTALLED || pkg->state_status == SS_UNPACKED) {
1267           if (pkg->dest == NULL) {
1268                opkg_msg(ERROR, "Internal error: %s has a NULL dest.\n",
1269                        pkg->name);
1270                return -1;
1271           }
1272           sprintf_alloc(&path, "%s/%s.%s", pkg->dest->info_dir, pkg->name, script);
1273      } else {
1274           if (pkg->tmp_unpack_dir == NULL) {
1275                opkg_msg(ERROR, "Internal error: %s has a NULL tmp_unpack_dir.\n",
1276                        pkg->name);
1277                return -1;
1278           }
1279           sprintf_alloc(&path, "%s/%s", pkg->tmp_unpack_dir, script);
1280      }
1281
1282      opkg_msg(INFO, "Running script %s.\n", path);
1283
1284      setenv("PKG_ROOT",
1285             pkg->dest ? pkg->dest->root_dir : conf->default_dest->root_dir, 1);
1286
1287      if (! file_exists(path)) {
1288           free(path);
1289           return 0;
1290      }
1291
1292      sprintf_alloc(&cmd, "%s %s", path, args);
1293      free(path);
1294      {
1295           const char *argv[] = {"sh", "-c", cmd, NULL};
1296           err = xsystem(argv);
1297      }
1298      free(cmd);
1299
1300      if (err) {
1301           opkg_msg(ERROR, "%s script returned status %d.\n", script, err);
1302           return err;
1303      }
1304
1305      return 0;
1306 }
1307
1308 int
1309 pkg_arch_supported(pkg_t *pkg)
1310 {
1311      nv_pair_list_elt_t *l;
1312
1313      if (!pkg->architecture)
1314           return 1;
1315
1316      list_for_each_entry(l , &conf->arch_list.head, node) {
1317           nv_pair_t *nv = (nv_pair_t *)l->data;
1318           if (strcmp(nv->name, pkg->architecture) == 0) {
1319                opkg_msg(DEBUG, "Arch %s (priority %s) supported for pkg %s.\n",
1320                                nv->name, nv->value, pkg->name);
1321                return 1;
1322           }
1323      }
1324
1325      opkg_msg(DEBUG, "Arch %s unsupported for pkg %s.\n",
1326                      pkg->architecture, pkg->name);
1327      return 0;
1328 }
1329
1330 void
1331 pkg_info_preinstall_check(void)
1332 {
1333      int i;
1334      pkg_vec_t *installed_pkgs = pkg_vec_alloc();
1335
1336      /* update the file owner data structure */
1337      opkg_msg(INFO, "Updating file owner list.\n");
1338      pkg_hash_fetch_all_installed(installed_pkgs);
1339      for (i = 0; i < installed_pkgs->len; i++) {
1340           pkg_t *pkg = installed_pkgs->pkgs[i];
1341           str_list_t *installed_files = pkg_get_installed_files(pkg); /* this causes installed_files to be cached */
1342           str_list_elt_t *iter, *niter;
1343           if (installed_files == NULL) {
1344                opkg_msg(ERROR, "Failed to determine installed "
1345                                "files for pkg %s.\n", pkg->name);
1346                break;
1347           }
1348           for (iter = str_list_first(installed_files), niter = str_list_next(installed_files, iter); 
1349                   iter; 
1350                   iter = niter, niter = str_list_next(installed_files, iter)) {
1351                char *installed_file = (char *) iter->data;
1352                file_hash_set_file_owner(installed_file, pkg);
1353           }
1354           pkg_free_installed_files(pkg);
1355      }
1356      pkg_vec_free(installed_pkgs);
1357 }
1358
1359 struct pkg_write_filelist_data {
1360      pkg_t *pkg;
1361      FILE *stream;
1362 };
1363
1364 static void
1365 pkg_write_filelist_helper(const char *key, void *entry_, void *data_)
1366 {
1367      struct pkg_write_filelist_data *data = data_;
1368      pkg_t *entry = entry_;
1369      if (entry == data->pkg) {
1370           fprintf(data->stream, "%s\n", key);
1371      }
1372 }
1373
1374 int
1375 pkg_write_filelist(pkg_t *pkg)
1376 {
1377         struct pkg_write_filelist_data data;
1378         char *list_file_name;
1379
1380         sprintf_alloc(&list_file_name, "%s/%s.list",
1381                         pkg->dest->info_dir, pkg->name);
1382
1383         opkg_msg(INFO, "Creating %s file for pkg %s.\n",
1384                         list_file_name, pkg->name);
1385
1386         data.stream = fopen(list_file_name, "w");
1387         if (!data.stream) {
1388                 opkg_perror(ERROR, "Failed to open %s",
1389                         list_file_name);
1390                 free(list_file_name);
1391                 return -1;
1392         }
1393
1394         data.pkg = pkg;
1395         hash_table_foreach(&conf->file_hash, pkg_write_filelist_helper, &data);
1396         fclose(data.stream);
1397         free(list_file_name);
1398
1399         pkg->state_flag &= ~SF_FILELIST_CHANGED;
1400
1401         return 0;
1402 }
1403
1404 int
1405 pkg_write_changed_filelists(void)
1406 {
1407         pkg_vec_t *installed_pkgs = pkg_vec_alloc();
1408         int i, err, ret = 0;
1409
1410         if (conf->noaction)
1411                 return 0;
1412
1413         opkg_msg(INFO, "Saving changed filelists.\n");
1414
1415         pkg_hash_fetch_all_installed(installed_pkgs);
1416         for (i = 0; i < installed_pkgs->len; i++) {
1417                 pkg_t *pkg = installed_pkgs->pkgs[i];
1418                 if (pkg->state_flag & SF_FILELIST_CHANGED) {
1419                         err = pkg_write_filelist(pkg);
1420                         if (err)
1421                                 ret = -1;
1422                 }
1423         }
1424
1425         pkg_vec_free (installed_pkgs);
1426
1427         return ret;
1428 }