libopkg: run prerm scripts for the old version also on upgrade
[oweals/opkg-lede.git] / libopkg / opkg_install.c
1 /* opkg_install.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 <time.h>
22 #include <signal.h>
23 #include <unistd.h>
24 #include <sys/stat.h>
25
26 #include "pkg.h"
27 #include "pkg_hash.h"
28 #include "pkg_extract.h"
29
30 #include "opkg_install.h"
31 #include "opkg_configure.h"
32 #include "opkg_download.h"
33 #include "opkg_remove.h"
34
35 #include "opkg_utils.h"
36 #include "opkg_message.h"
37 #include "opkg_cmd.h"
38 #include "opkg_defines.h"
39
40 #include "sprintf_alloc.h"
41 #include "file_util.h"
42 #include "xsystem.h"
43 #include "libbb/libbb.h"
44
45 static int
46 satisfy_dependencies_for(pkg_t *pkg)
47 {
48      int i, err;
49      pkg_vec_t *depends = pkg_vec_alloc();
50      pkg_t *dep;
51      char **tmp, **unresolved = NULL;
52      int ndepends;
53
54      ndepends = pkg_hash_fetch_unsatisfied_dependencies(pkg, depends,
55                                                         &unresolved);
56
57      if (unresolved) {
58           opkg_msg(ERROR, "Cannot satisfy the following dependencies for %s:\n",
59                        pkg->name);
60           tmp = unresolved;
61           while (*unresolved) {
62                opkg_message(ERROR, "\t%s", *unresolved);
63                free(*unresolved);
64                unresolved++;
65           }
66           free(tmp);
67           opkg_message(ERROR, "\n");
68           if (! conf->force_depends) {
69                opkg_msg(INFO,
70                             "This could mean that your package list is out of date or that the packages\n"
71                             "mentioned above do not yet exist (try 'opkg update'). To proceed in spite\n"
72                             "of this problem try again with the '-force-depends' option.\n");
73                pkg_vec_free(depends);
74                return -1;
75           }
76      }
77
78      if (ndepends <= 0) {
79           pkg_vec_free(depends);
80           return 0;
81      }
82
83      /* Mark packages as to-be-installed */
84      for (i=0; i < depends->len; i++) {
85           /* Dependencies should be installed the same place as pkg */
86           if (depends->pkgs[i]->dest == NULL) {
87                depends->pkgs[i]->dest = pkg->dest;
88           }
89           depends->pkgs[i]->state_want = SW_INSTALL;
90      }
91
92      for (i = 0; i < depends->len; i++) {
93           dep = depends->pkgs[i];
94           /* The package was uninstalled when we started, but another
95              dep earlier in this loop may have depended on it and pulled
96              it in, so check first. */
97           if ((dep->state_status != SS_INSTALLED)
98               && (dep->state_status != SS_UNPACKED)) {
99                opkg_msg(DEBUG2,"Calling opkg_install_pkg.\n");
100                err = opkg_install_pkg(dep, 0);
101                /* mark this package as having been automatically installed to
102                 * satisfy a dependancy */
103                dep->auto_installed = 1;
104                if (err) {
105                     pkg_vec_free(depends);
106                     return err;
107                }
108           }
109      }
110
111      pkg_vec_free(depends);
112
113      return 0;
114 }
115
116 static int
117 check_conflicts_for(pkg_t *pkg)
118 {
119      int i;
120      pkg_vec_t *conflicts = NULL;
121      message_level_t level;
122
123      if (conf->force_depends) {
124           level = NOTICE;
125      } else {
126           level = ERROR;
127      }
128
129      if (!conf->force_depends)
130           conflicts = pkg_hash_fetch_conflicts(pkg);
131
132      if (conflicts) {
133           opkg_msg(level, "The following packages conflict with %s:\n",
134                        pkg->name);
135           i = 0;
136           while (i < conflicts->len)
137                opkg_msg(level, "\t%s", conflicts->pkgs[i++]->name);
138           opkg_message(level, "\n");
139           pkg_vec_free(conflicts);
140           return -1;
141      }
142      return 0;
143 }
144
145 static int
146 update_file_ownership(pkg_t *new_pkg, pkg_t *old_pkg)
147 {
148      str_list_t *new_list, *old_list;
149      str_list_elt_t *iter, *niter;
150
151      new_list = pkg_get_installed_files(new_pkg);
152      if (new_list == NULL)
153              return -1;
154
155      for (iter = str_list_first(new_list), niter = str_list_next(new_list, iter);
156              iter;
157              iter = niter, niter = str_list_next(new_list, niter)) {
158           char *new_file = (char *)iter->data;
159           pkg_t *owner = file_hash_get_file_owner(new_file);
160           pkg_t *obs = hash_table_get(&conf->obs_file_hash, new_file);
161
162           opkg_msg(DEBUG2, "%s: new_pkg=%s wants file %s, from owner=%s\n",
163                 __func__, new_pkg->name, new_file, owner?owner->name:"<NULL>");
164
165           if (!owner || (owner == old_pkg) || obs)
166                file_hash_set_file_owner(new_file, new_pkg);
167      }
168
169      if (old_pkg) {
170           old_list = pkg_get_installed_files(old_pkg);
171           if (old_list == NULL) {
172                   pkg_free_installed_files(new_pkg);
173                   return -1;
174           }
175
176           for (iter = str_list_first(old_list), niter = str_list_next(old_list, iter);
177                   iter;
178                   iter = niter, niter = str_list_next(old_list, niter)) {
179                char *old_file = (char *)iter->data;
180                pkg_t *owner = file_hash_get_file_owner(old_file);
181                if (!owner || (owner == old_pkg)) {
182                     /* obsolete */
183                     hash_table_insert(&conf->obs_file_hash, old_file, old_pkg);
184                }
185           }
186           pkg_free_installed_files(old_pkg);
187      }
188      pkg_free_installed_files(new_pkg);
189      return 0;
190 }
191
192 static int
193 verify_pkg_installable(pkg_t *pkg)
194 {
195         unsigned long kbs_available, pkg_size_kbs;
196         char *root_dir = NULL;
197         struct stat s;
198
199         if (conf->force_space || pkg->installed_size == 0)
200                 return 0;
201
202         if (pkg->dest)
203         {
204                 if (!strcmp(pkg->dest->name, "root") && conf->overlay_root
205                     && !stat(conf->overlay_root, &s) && (s.st_mode & S_IFDIR))
206                         root_dir = conf->overlay_root;
207                 else
208                         root_dir = pkg->dest->root_dir;
209         }
210
211         if (!root_dir)
212                 root_dir = conf->default_dest->root_dir;
213
214         kbs_available = get_available_kbytes(root_dir);
215
216         pkg_size_kbs = (pkg->installed_size + 1023)/1024;
217
218         if (pkg_size_kbs >= kbs_available) {
219                 opkg_msg(ERROR, "Only have %ldkb available on filesystem %s, "
220                         "pkg %s needs %ld\n",
221                         kbs_available, root_dir, pkg->name, pkg_size_kbs);
222                 return -1;
223         }
224
225      return 0;
226 }
227
228 static int
229 unpack_pkg_control_files(pkg_t *pkg)
230 {
231      int err;
232      char *conffiles_file_name;
233      char *root_dir;
234      FILE *conffiles_file;
235
236      sprintf_alloc(&pkg->tmp_unpack_dir, "%s/%s-XXXXXX", conf->tmp_dir, pkg->name);
237
238      pkg->tmp_unpack_dir = mkdtemp(pkg->tmp_unpack_dir);
239      if (pkg->tmp_unpack_dir == NULL) {
240           opkg_perror(ERROR, "Failed to create temporary directory '%s'",
241                        pkg->tmp_unpack_dir);
242           return -1;
243      }
244
245      err = pkg_extract_control_files_to_dir(pkg, pkg->tmp_unpack_dir);
246      if (err) {
247           return err;
248      }
249
250      /* XXX: CLEANUP: There might be a cleaner place to read in the
251         conffiles. Seems like I should be able to get everything to go
252         through pkg_init_from_file. If so, maybe it would make sense to
253         move all of unpack_pkg_control_files to that function. */
254
255      /* Don't need to re-read conffiles if we already have it */
256      if (!nv_pair_list_empty(&pkg->conffiles)) {
257           return 0;
258      }
259
260      sprintf_alloc(&conffiles_file_name, "%s/conffiles", pkg->tmp_unpack_dir);
261      if (! file_exists(conffiles_file_name)) {
262           free(conffiles_file_name);
263           return 0;
264      }
265
266      conffiles_file = fopen(conffiles_file_name, "r");
267      if (conffiles_file == NULL) {
268           opkg_perror(ERROR, "Failed to open %s", conffiles_file_name);
269           free(conffiles_file_name);
270           return -1;
271      }
272      free(conffiles_file_name);
273
274      while (1) {
275           char *cf_name;
276           char *cf_name_in_dest;
277           int i;
278
279           cf_name = file_read_line_alloc(conffiles_file);
280           if (cf_name == NULL) {
281                break;
282           }
283           if (cf_name[0] == '\0') {
284                continue;
285           }
286           for (i = strlen(cf_name) - 1;
287                (i >= 0) && (cf_name[i] == ' ' || cf_name[i] == '\t');
288                i--
289           ) {
290                cf_name[i] = '\0';
291           }
292
293           /* Prepend dest->root_dir to conffile name.
294              Take pains to avoid multiple slashes. */
295           root_dir = pkg->dest->root_dir;
296           if (conf->offline_root)
297                /* skip the offline_root prefix */
298                root_dir = pkg->dest->root_dir + strlen(conf->offline_root);
299           sprintf_alloc(&cf_name_in_dest, "%s%s", root_dir,
300                         cf_name[0] == '/' ? (cf_name + 1) : cf_name);
301
302           /* Can't get an md5sum now, (file isn't extracted yet).
303              We'll wait until resolve_conffiles */
304           conffile_list_append(&pkg->conffiles, cf_name_in_dest, NULL);
305
306           free(cf_name);
307           free(cf_name_in_dest);
308      }
309
310      fclose(conffiles_file);
311
312      return 0;
313 }
314
315 /*
316  * Remove packages which were auto_installed due to a dependency by old_pkg,
317  * which are no longer a dependency in the new (upgraded) pkg.
318  */
319 static int
320 pkg_remove_orphan_dependent(pkg_t *pkg, pkg_t *old_pkg)
321 {
322         int i, j, k, l, found,r, err = 0;
323         int n_deps;
324         pkg_t *p;
325         struct compound_depend *cd0, *cd1;
326         abstract_pkg_t **dependents;
327
328         int count0 = old_pkg->pre_depends_count +
329                                 old_pkg->depends_count +
330                                 old_pkg->recommends_count +
331                                 old_pkg->suggests_count;
332         int count1 = pkg->pre_depends_count +
333                                 pkg->depends_count +
334                                 pkg->recommends_count +
335                                 pkg->suggests_count;
336
337         for (i=0; i<count0; i++) {
338                 cd0 = &old_pkg->depends[i];
339                 if (cd0->type != DEPEND)
340                         continue;
341                 for (j=0; j<cd0->possibility_count; j++) {
342
343                         found = 0;
344
345                         for (k=0; k<count1; k++) {
346                                 cd1 = &pkg->depends[k];
347                                 if (cd1->type != DEPEND)
348                                         continue;
349                                 for (l=0; l<cd1->possibility_count; l++) {
350                                         if (cd0->possibilities[j]
351                                          == cd1->possibilities[l]) {
352                                                 found = 1;
353                                                 break;
354                                         }
355                                 }
356                                 if (found)
357                                         break;
358                         }
359
360                         if (found)
361                                 continue;
362
363                         /*
364                          * old_pkg has a dependency that pkg does not.
365                          */
366                         p = pkg_hash_fetch_installed_by_name(
367                                         cd0->possibilities[j]->pkg->name);
368
369                         if (!p)
370                                 continue;
371
372                         if (!p->auto_installed)
373                                 continue;
374
375                         n_deps = pkg_has_installed_dependents(p, &dependents);
376                         n_deps--; /* don't count old_pkg */
377
378                         if (n_deps == 0) {
379                                 opkg_msg(NOTICE, "%s was autoinstalled and is "
380                                                 "now orphaned, removing.\n",
381                                                 p->name);
382
383                                 /* p has one installed dependency (old_pkg),
384                                  * which we need to ignore during removal. */
385                                 p->state_flag |= SF_REPLACE;
386
387                                 r = opkg_remove_pkg(p, 0);
388                                 if (!err)
389                                         err = r;
390                         } else
391                                 opkg_msg(INFO, "%s was autoinstalled and is "
392                                                 "still required by %d "
393                                                 "installed packages.\n",
394                                                 p->name, n_deps);
395
396                 }
397         }
398
399         return err;
400 }
401
402 /* returns number of installed replacees */
403 static int
404 pkg_get_installed_replacees(pkg_t *pkg, pkg_vec_t *installed_replacees)
405 {
406      abstract_pkg_t **replaces = pkg->replaces;
407      int replaces_count = pkg->replaces_count;
408      int i, j;
409      for (i = 0; i < replaces_count; i++) {
410           abstract_pkg_t *ab_pkg = replaces[i];
411           pkg_vec_t *pkg_vec = ab_pkg->pkgs;
412           if (pkg_vec) {
413                for (j = 0; j < pkg_vec->len; j++) {
414                     pkg_t *replacee = pkg_vec->pkgs[j];
415                     if (!pkg_conflicts(pkg, replacee))
416                          continue;
417                     if (replacee->state_status == SS_INSTALLED) {
418                          pkg_vec_insert(installed_replacees, replacee);
419                     }
420                }
421           }
422      }
423      return installed_replacees->len;
424 }
425
426 static int
427 pkg_remove_installed_replacees(pkg_vec_t *replacees)
428 {
429      int i;
430      int replaces_count = replacees->len;
431      for (i = 0; i < replaces_count; i++) {
432           pkg_t *replacee = replacees->pkgs[i];
433           int err;
434           replacee->state_flag |= SF_REPLACE; /* flag it so remove won't complain */
435           err = opkg_remove_pkg(replacee, 0);
436           if (err)
437                return err;
438      }
439      return 0;
440 }
441
442 /* to unwind the removal: make sure they are installed */
443 static int
444 pkg_remove_installed_replacees_unwind(pkg_vec_t *replacees)
445 {
446      int i, err;
447      int replaces_count = replacees->len;
448      for (i = 0; i < replaces_count; i++) {
449           pkg_t *replacee = replacees->pkgs[i];
450           if (replacee->state_status != SS_INSTALLED) {
451                opkg_msg(DEBUG2, "Calling opkg_install_pkg.\n");
452                err = opkg_install_pkg(replacee, 0);
453                if (err)
454                     return err;
455           }
456      }
457      return 0;
458 }
459
460 /* compares versions of pkg and old_pkg, returns 0 if OK to proceed with installation of pkg, 1 otherwise */
461 static int
462 opkg_install_check_downgrade(pkg_t *pkg, pkg_t *old_pkg, int message)
463 {
464      if (old_pkg) {
465           char message_out[15];
466           char *old_version = pkg_version_str_alloc(old_pkg);
467           char *new_version = pkg_version_str_alloc(pkg);
468           int cmp = pkg_compare_versions(old_pkg, pkg);
469           int rc = 0;
470
471           memset(message_out,'\x0',15);
472           strncpy (message_out,"Upgrading ",strlen("Upgrading "));
473           if ( (conf->force_downgrade==1) && (cmp > 0) ){     /* We've been asked to allow downgrade  and version is precedent */
474              cmp = -1 ;                                       /* then we force opkg to downgrade */
475              strncpy (message_out,"Downgrading ",strlen("Downgrading "));         /* We need to use a value < 0 because in the 0 case we are asking to */
476                                                               /* reinstall, and some check could fail asking the "force-reinstall" option */
477           }
478
479           if (cmp > 0) {
480               if(!conf->download_only)
481                   opkg_msg(NOTICE,
482                           "Not downgrading package %s on %s from %s to %s.\n",
483                           old_pkg->name, old_pkg->dest->name, old_version, new_version);
484                rc = 1;
485           } else if (cmp < 0) {
486               if(!conf->download_only)
487                   opkg_msg(NOTICE, "%s%s on %s from %s to %s...\n",
488                           message_out, pkg->name, old_pkg->dest->name, old_version, new_version);
489                pkg->dest = old_pkg->dest;
490                rc = 0;
491           } else /* cmp == 0 */ {
492                if(!conf->download_only)
493                    opkg_msg(NOTICE, "%s (%s) already install on %s.\n",
494                         pkg->name, new_version, old_pkg->dest->name);
495                rc = 1;
496           }
497           free(old_version);
498           free(new_version);
499           return rc;
500      } else {
501           char message_out[15] ;
502           memset(message_out,'\x0',15);
503           if ( message )
504                strncpy( message_out,"Upgrading ",strlen("Upgrading ") );
505           else
506                strncpy( message_out,"Installing ",strlen("Installing ") );
507           char *version = pkg_version_str_alloc(pkg);
508
509           if(!conf->download_only)
510                opkg_msg(NOTICE, "%s%s (%s) to %s...\n", message_out,
511                   pkg->name, version, pkg->dest->name);
512           free(version);
513      }
514      return 0;
515 }
516
517
518 static int
519 prerm_upgrade_old_pkg(pkg_t *pkg, pkg_t *old_pkg)
520 {
521      /* DPKG_INCOMPATIBILITY:
522         dpkg does some things here that we don't do yet. Do we care?
523
524         1. If a version of the package is already installed, call
525            old-prerm upgrade new-version
526         2. If the script runs but exits with a non-zero exit status
527            new-prerm failed-upgrade old-version
528            Error unwind, for both the above cases:
529            old-postinst abort-upgrade new-version
530      */
531     int err;
532     char *script_args;
533     char *new_version;
534
535     if (!old_pkg || !pkg)
536         return 0;
537
538     new_version = pkg_version_str_alloc(pkg);
539
540     sprintf_alloc(&script_args, "upgrade %s", new_version);
541     free(new_version);
542     err = pkg_run_script(old_pkg, "prerm", script_args);
543     free(script_args);
544     if (err != 0) {
545         opkg_msg(ERROR, "prerm script for package \"%s\" failed\n",
546                  old_pkg->name);
547         return -1;
548     }
549     return 0;
550 }
551
552 static int
553 prerm_upgrade_old_pkg_unwind(pkg_t *pkg, pkg_t *old_pkg)
554 {
555      /* DPKG_INCOMPATIBILITY:
556         dpkg does some things here that we don't do yet. Do we care?
557         (See prerm_upgrade_old_package for details)
558      */
559      return 0;
560 }
561
562 static int
563 prerm_deconfigure_conflictors(pkg_t *pkg, pkg_vec_t *conflictors)
564 {
565      /* DPKG_INCOMPATIBILITY:
566         dpkg does some things here that we don't do yet. Do we care?
567         2. If a 'conflicting' package is being removed at the same time:
568                 1. If any packages depended on that conflicting package and
569                    --auto-deconfigure is specified, call, for each such package:
570                    deconfigured's-prerm deconfigure \
571                    in-favour package-being-installed version \
572                    removing conflicting-package version
573                 Error unwind:
574                    deconfigured's-postinst abort-deconfigure \
575                    in-favour package-being-installed-but-failed version \
576                    removing conflicting-package version
577
578                    The deconfigured packages are marked as requiring
579                    configuration, so that if --install is used they will be
580                    configured again if possible.
581                 2. To prepare for removal of the conflicting package, call:
582                    conflictor's-prerm remove in-favour package new-version
583                 Error unwind:
584                    conflictor's-postinst abort-remove in-favour package new-version
585      */
586      return 0;
587 }
588
589 static int
590 prerm_deconfigure_conflictors_unwind(pkg_t *pkg, pkg_vec_t *conflictors)
591 {
592      /* DPKG_INCOMPATIBILITY: dpkg does some things here that we don't
593         do yet. Do we care?  (See prerm_deconfigure_conflictors for
594         details) */
595      return 0;
596 }
597
598 static int
599 preinst_configure(pkg_t *pkg, pkg_t *old_pkg)
600 {
601      int err;
602      char *preinst_args;
603
604      if (old_pkg) {
605           char *old_version = pkg_version_str_alloc(old_pkg);
606           sprintf_alloc(&preinst_args, "upgrade %s", old_version);
607           free(old_version);
608      } else if (pkg->state_status == SS_CONFIG_FILES) {
609           char *pkg_version = pkg_version_str_alloc(pkg);
610           sprintf_alloc(&preinst_args, "install %s", pkg_version);
611           free(pkg_version);
612      } else {
613           preinst_args = xstrdup("install");
614      }
615
616      err = pkg_run_script(pkg, "preinst", preinst_args);
617      if (err) {
618           opkg_msg(ERROR, "Aborting installation of %s.\n", pkg->name);
619           return -1;
620      }
621
622      free(preinst_args);
623
624      return 0;
625 }
626
627 static int
628 preinst_configure_unwind(pkg_t *pkg, pkg_t *old_pkg)
629 {
630      /* DPKG_INCOMPATIBILITY:
631         dpkg does the following error unwind, should we?
632         pkg->postrm abort-upgrade old-version
633         OR pkg->postrm abort-install old-version
634         OR pkg->postrm abort-install
635      */
636      return 0;
637 }
638
639 static char *
640 backup_filename_alloc(const char *file_name)
641 {
642      char *backup;
643
644      sprintf_alloc(&backup, "%s%s", file_name, OPKG_BACKUP_SUFFIX);
645
646      return backup;
647 }
648
649
650 static int
651 backup_make_backup(const char *file_name)
652 {
653      int err;
654      char *backup;
655
656      backup = backup_filename_alloc(file_name);
657      err = file_copy(file_name, backup);
658      if (err) {
659           opkg_msg(ERROR, "Failed to copy %s to %s\n",
660                        file_name, backup);
661      }
662
663      free(backup);
664
665      return err;
666 }
667
668 static int
669 backup_exists_for(const char *file_name)
670 {
671      int ret;
672      char *backup;
673
674      backup = backup_filename_alloc(file_name);
675
676      ret = file_exists(backup);
677
678      free(backup);
679
680      return ret;
681 }
682
683 static int
684 backup_remove(const char *file_name)
685 {
686      char *backup;
687
688      backup = backup_filename_alloc(file_name);
689      unlink(backup);
690      free(backup);
691
692      return 0;
693 }
694
695 static int
696 backup_modified_conffiles(pkg_t *pkg, pkg_t *old_pkg)
697 {
698      int err;
699      conffile_list_elt_t *iter;
700      conffile_t *cf;
701
702      if (conf->noaction) return 0;
703
704      /* Backup all modified conffiles */
705      if (old_pkg) {
706           for (iter = nv_pair_list_first(&old_pkg->conffiles); iter; iter = nv_pair_list_next(&old_pkg->conffiles, iter)) {
707                char *cf_name;
708
709                cf = iter->data;
710                cf_name = root_filename_alloc(cf->name);
711
712                /* Don't worry if the conffile is just plain gone */
713                if (file_exists(cf_name) && conffile_has_been_modified(cf)) {
714                     err = backup_make_backup(cf_name);
715                     if (err) {
716                          return err;
717                     }
718                }
719                free(cf_name);
720           }
721      }
722
723      /* Backup all conffiles that were not conffiles in old_pkg */
724      for (iter = nv_pair_list_first(&pkg->conffiles); iter; iter = nv_pair_list_next(&pkg->conffiles, iter)) {
725           char *cf_name;
726           cf = (conffile_t *)iter->data;
727           cf_name = root_filename_alloc(cf->name);
728           /* Ignore if this was a conffile in old_pkg as well */
729           if (pkg_get_conffile(old_pkg, cf->name)) {
730                continue;
731           }
732
733           if (file_exists(cf_name) && (! backup_exists_for(cf_name))) {
734                err = backup_make_backup(cf_name);
735                if (err) {
736                     return err;
737                }
738           }
739           free(cf_name);
740      }
741
742      return 0;
743 }
744
745 static int
746 backup_modified_conffiles_unwind(pkg_t *pkg, pkg_t *old_pkg)
747 {
748      conffile_list_elt_t *iter;
749
750      if (old_pkg) {
751           for (iter = nv_pair_list_first(&old_pkg->conffiles); iter; iter = nv_pair_list_next(&old_pkg->conffiles, iter)) {
752                backup_remove(((nv_pair_t *)iter->data)->name);
753           }
754      }
755
756      for (iter = nv_pair_list_first(&pkg->conffiles); iter; iter = nv_pair_list_next(&pkg->conffiles, iter)) {
757           backup_remove(((nv_pair_t *)iter->data)->name);
758      }
759
760      return 0;
761 }
762
763
764 static int
765 check_data_file_clashes(pkg_t *pkg, pkg_t *old_pkg)
766 {
767      /* DPKG_INCOMPATIBILITY:
768         opkg takes a slightly different approach than dpkg at this
769         point.  dpkg installs each file in the new package while
770         creating a backup for any file that is replaced, (so that it
771         can unwind if necessary).  To avoid complexity and redundant
772         storage, opkg doesn't do any installation until later, (at the
773         point at which dpkg removes the backups.
774
775         But, we do have to check for data file clashes, since after
776         installing a package with a file clash, removing either of the
777         packages involved in the clash has the potential to break the
778         other package.
779      */
780      str_list_t *files_list;
781      str_list_elt_t *iter, *niter;
782      char *filename;
783      int clashes = 0;
784
785      files_list = pkg_get_installed_files(pkg);
786      if (files_list == NULL)
787              return -1;
788
789      for (iter = str_list_first(files_list), niter = str_list_next(files_list, iter);
790              iter;
791              iter = niter, niter = str_list_next(files_list, iter)) {
792           filename = (char *) iter->data;
793           if (file_exists(filename) && (! file_is_dir(filename))) {
794                pkg_t *owner;
795                pkg_t *obs;
796
797                if (backup_exists_for(filename)) {
798                     continue;
799                }
800
801                /* Pre-existing files are OK if force-overwrite was asserted. */
802                if (conf->force_overwrite) {
803                     /* but we need to change who owns this file */
804                     file_hash_set_file_owner(filename, pkg);
805                     continue;
806                }
807
808                owner = file_hash_get_file_owner(filename);
809
810                /* Pre-existing files are OK if owned by the pkg being upgraded. */
811                if (owner && old_pkg) {
812                     if (strcmp(owner->name, old_pkg->name) == 0) {
813                          continue;
814                     }
815                }
816
817                /* Pre-existing files are OK if owned by a package replaced by new pkg. */
818                if (owner) {
819                     opkg_msg(DEBUG2, "Checking replaces for %s in package %s\n",
820                                 filename, owner->name);
821                     if (pkg_replaces(pkg, owner)) {
822                          continue;
823                     }
824 /* If the file that would be installed is owned by the same package, ( as per a reinstall or similar )
825    then it's ok to overwrite. */
826                     if (strcmp(owner->name,pkg->name)==0){
827                          opkg_msg(INFO, "Replacing pre-existing file %s"
828                                         " owned by package %s\n",
829                                         filename, owner->name);
830                          continue;
831                     }
832                }
833
834                /* Pre-existing files are OK if they are obsolete */
835                obs = hash_table_get(&conf->obs_file_hash, filename);
836                if (obs) {
837                     opkg_msg(INFO, "Pre-exiting file %s is obsolete."
838                                    " obs_pkg=%s\n",
839                                     filename, obs->name);
840                     continue;
841                }
842
843                /* We have found a clash. */
844                opkg_msg(ERROR, "Package %s wants to install file %s\n"
845                             "\tBut that file is already provided by package ",
846                             pkg->name, filename);
847                if (owner) {
848                     opkg_message(ERROR, "%s\n", owner->name);
849                } else {
850                     opkg_message(ERROR, "<no package>\n"
851                         "Please move this file out of the way and try again.\n");
852                }
853                clashes++;
854           }
855      }
856      pkg_free_installed_files(pkg);
857
858      return clashes;
859 }
860
861 /*
862  * XXX: This function sucks, as does the below comment.
863  */
864 static int
865 check_data_file_clashes_change(pkg_t *pkg, pkg_t *old_pkg)
866 {
867     /* Basically that's the worst hack I could do to be able to change ownership of
868        file list, but, being that we have no way to unwind the mods, due to structure
869        of hash table, probably is the quickest hack too, whishing it would not slow-up thing too much.
870        What we do here is change the ownership of file in hash if a replace ( or similar events
871        happens )
872        Only the action that are needed to change name should be considered.
873        @@@ To change after 1.0 release.
874      */
875      str_list_t *files_list;
876      str_list_elt_t *iter, *niter;
877
878      char *root_filename = NULL;
879
880      files_list = pkg_get_installed_files(pkg);
881      if (files_list == NULL)
882              return -1;
883
884      for (iter = str_list_first(files_list), niter = str_list_next(files_list, iter);
885              iter;
886              iter = niter, niter = str_list_next(files_list, niter)) {
887           char *filename = (char *) iter->data;
888           if (root_filename) {
889               free(root_filename);
890               root_filename = NULL;
891           }
892           root_filename = root_filename_alloc(filename);
893           if (file_exists(root_filename) && (! file_is_dir(root_filename))) {
894                pkg_t *owner;
895
896                owner = file_hash_get_file_owner(filename);
897
898                if (conf->force_overwrite) {
899                     /* but we need to change who owns this file */
900                     file_hash_set_file_owner(filename, pkg);
901                     continue;
902                }
903
904
905                /* Pre-existing files are OK if owned by a package replaced by new pkg. */
906                if (owner) {
907                     if (pkg_replaces(pkg, owner)) {
908 /* It's now time to change the owner of that file.
909    It has been "replaced" from the new "Replaces", then I need to inform lists file about that.  */
910                          opkg_msg(INFO, "Replacing pre-existing file %s "
911                                          "owned by package %s\n",
912                                          filename, owner->name);
913                          file_hash_set_file_owner(filename, pkg);
914                          continue;
915                     }
916                }
917
918           }
919      }
920      if (root_filename) {
921          free(root_filename);
922          root_filename = NULL;
923      }
924      pkg_free_installed_files(pkg);
925
926      return 0;
927 }
928
929 static int
930 check_data_file_clashes_unwind(pkg_t *pkg, pkg_t *old_pkg)
931 {
932      /* Nothing to do since check_data_file_clashes doesn't change state */
933      return 0;
934 }
935
936 static int
937 postrm_upgrade_old_pkg(pkg_t *pkg, pkg_t *old_pkg)
938 {
939      /* DPKG_INCOMPATIBILITY: dpkg does the following here, should we?
940         1. If the package is being upgraded, call
941            old-postrm upgrade new-version
942         2. If this fails, attempt:
943            new-postrm failed-upgrade old-version
944         Error unwind, for both cases:
945            old-preinst abort-upgrade new-version    */
946     int err;
947     char *script_args;
948     char *new_version;
949
950     if (!old_pkg || !pkg)
951         return 0;
952
953     new_version = pkg_version_str_alloc(pkg);
954
955     sprintf_alloc(&script_args, "upgrade %s", new_version);
956     free(new_version);
957     err = pkg_run_script(old_pkg, "postrm", script_args);
958     free(script_args);
959     if (err != 0) {
960         opkg_msg(ERROR, "postrm script for package \"%s\" failed\n",
961                  old_pkg->name);
962         return -1;
963     }
964     return 0;
965 }
966
967 static int
968 postrm_upgrade_old_pkg_unwind(pkg_t *pkg, pkg_t *old_pkg)
969 {
970      /* DPKG_INCOMPATIBILITY:
971         dpkg does some things here that we don't do yet. Do we care?
972         (See postrm_upgrade_old_pkg for details)
973      */
974     return 0;
975 }
976
977 static int
978 remove_obsolesced_files(pkg_t *pkg, pkg_t *old_pkg)
979 {
980      int err = 0;
981      str_list_t *old_files;
982      str_list_elt_t *of;
983      str_list_t *new_files;
984      str_list_elt_t *nf;
985      hash_table_t new_files_table;
986
987      old_files = pkg_get_installed_files(old_pkg);
988      if (old_files == NULL)
989           return -1;
990
991      new_files = pkg_get_installed_files(pkg);
992      if (new_files == NULL) {
993           pkg_free_installed_files(old_pkg);
994           return -1;
995      }
996
997      new_files_table.entries = NULL;
998      hash_table_init("new_files" , &new_files_table, 20);
999      for (nf = str_list_first(new_files); nf; nf = str_list_next(new_files, nf)) {
1000          if (nf && nf->data)
1001             hash_table_insert(&new_files_table, nf->data, nf->data);
1002      }
1003
1004      for (of = str_list_first(old_files); of; of = str_list_next(old_files, of)) {
1005           pkg_t *owner;
1006           char *old, *new;
1007           old = (char *)of->data;
1008           new = (char *) hash_table_get (&new_files_table, old);
1009           if (new)
1010                continue;
1011
1012           if (file_is_dir(old)) {
1013                continue;
1014           }
1015           owner = file_hash_get_file_owner(old);
1016           if (owner != old_pkg) {
1017                /* in case obsolete file no longer belongs to old_pkg */
1018                continue;
1019           }
1020
1021           /* old file is obsolete */
1022           opkg_msg(NOTICE, "Removing obsolete file %s.\n", old);
1023           if (!conf->noaction) {
1024                err = unlink(old);
1025                if (err) {
1026                     opkg_perror(ERROR, "unlinking %s failed", old);
1027                }
1028           }
1029      }
1030
1031      hash_table_deinit(&new_files_table);
1032      pkg_free_installed_files(old_pkg);
1033      pkg_free_installed_files(pkg);
1034
1035      return err;
1036 }
1037
1038 static int
1039 install_maintainer_scripts(pkg_t *pkg, pkg_t *old_pkg)
1040 {
1041      int ret;
1042      char *prefix;
1043
1044      sprintf_alloc(&prefix, "%s.", pkg->name);
1045      ret = pkg_extract_control_files_to_dir_with_prefix(pkg,
1046                                                         pkg->dest->info_dir,
1047                                                         prefix);
1048      free(prefix);
1049      return ret;
1050 }
1051
1052 static int
1053 remove_disappeared(pkg_t *pkg)
1054 {
1055      /* DPKG_INCOMPATIBILITY:
1056         This is a fairly sophisticated dpkg operation. Shall we
1057         skip it? */
1058
1059      /* Any packages all of whose files have been overwritten during the
1060         installation, and which aren't required for dependencies, are
1061         considered to have been removed. For each such package
1062         1. disappearer's-postrm disappear overwriter overwriter-version
1063         2. The package's maintainer scripts are removed
1064         3. It is noted in the status database as being in a sane state,
1065            namely not installed (any conffiles it may have are ignored,
1066            rather than being removed by dpkg). Note that disappearing
1067            packages do not have their prerm called, because dpkg doesn't
1068            know in advance that the package is going to vanish.
1069      */
1070      return 0;
1071 }
1072
1073 static int
1074 install_data_files(pkg_t *pkg)
1075 {
1076      int err;
1077
1078      /* opkg takes a slightly different approach to data file backups
1079         than dpkg. Rather than removing backups at this point, we
1080         actually do the data file installation now. See comments in
1081         check_data_file_clashes() for more details. */
1082
1083      opkg_msg(INFO, "Extracting data files to %s.\n", pkg->dest->root_dir);
1084      err = pkg_extract_data_files_to_dir(pkg, pkg->dest->root_dir);
1085      if (err) {
1086           return err;
1087      }
1088
1089      /* The "Essential" control field may only be present in the control
1090       * file and not in the Packages list. Ensure we capture it regardless.
1091       *
1092       * XXX: This should be fixed outside of opkg, in the Package list.
1093       */
1094      set_flags_from_control(pkg) ;
1095
1096      opkg_msg(DEBUG, "Calling pkg_write_filelist.\n");
1097      err = pkg_write_filelist(pkg);
1098      if (err)
1099           return err;
1100
1101      /* XXX: FEATURE: opkg should identify any files which existed
1102         before installation and which were overwritten, (see
1103         check_data_file_clashes()). What it must do is remove any such
1104         files from the filelist of the old package which provided the
1105         file. Otherwise, if the old package were removed at some point
1106         it would break the new package. Removing the new package will
1107         also break the old one, but this cannot be helped since the old
1108         package's file has already been deleted. This is the importance
1109         of check_data_file_clashes(), and only allowing opkg to install
1110         a clashing package with a user force. */
1111
1112      return 0;
1113 }
1114
1115 static int
1116 resolve_conffiles(pkg_t *pkg)
1117 {
1118      conffile_list_elt_t *iter;
1119      conffile_t *cf;
1120      char *cf_backup;
1121      char *chksum;
1122
1123      if (conf->noaction) return 0;
1124
1125      for (iter = nv_pair_list_first(&pkg->conffiles); iter; iter = nv_pair_list_next(&pkg->conffiles, iter)) {
1126           char *root_filename;
1127           cf = (conffile_t *)iter->data;
1128           root_filename = root_filename_alloc(cf->name);
1129
1130           /* Might need to initialize the md5sum for each conffile */
1131           if (cf->value == NULL) {
1132                cf->value = file_sha256sum_alloc(root_filename);
1133           }
1134
1135           if (!file_exists(root_filename)) {
1136                free(root_filename);
1137                continue;
1138           }
1139
1140           cf_backup = backup_filename_alloc(root_filename);
1141
1142           if (file_exists(cf_backup)) {
1143               /* Let's compute md5 to test if files are changed */
1144 #ifdef HAVE_MD5
1145               if(cf->value && strlen(cf->value) > 33) {
1146                   chksum = file_sha256sum_alloc(cf_backup);
1147               } else {
1148                   chksum = file_md5sum_alloc(cf_backup);
1149               }
1150 #else
1151               chksum = file_sha256sum_alloc(cf_backup);
1152 #endif
1153               if (chksum && cf->value && strcmp(cf->value,chksum) != 0 ) {
1154                   if (conf->force_maintainer) {
1155                       opkg_msg(NOTICE, "Conffile %s using maintainer's setting.\n",
1156                                       cf_backup);
1157                   } else {
1158                       char *new_conffile;
1159                       sprintf_alloc(&new_conffile, "%s-opkg", root_filename);
1160                       opkg_msg(ERROR, "Existing conffile %s "
1161                            "is different from the conffile in the new package."
1162                            " The new conffile will be placed at %s.\n",
1163                            root_filename, new_conffile);
1164                       rename(root_filename, new_conffile);
1165                       rename(cf_backup, root_filename);
1166                       free(new_conffile);
1167                   }
1168               }
1169               unlink(cf_backup);
1170               if (chksum)
1171                   free(chksum);
1172           }
1173
1174           free(cf_backup);
1175           free(root_filename);
1176      }
1177
1178      return 0;
1179 }
1180
1181
1182 int
1183 opkg_install_by_name(const char *pkg_name)
1184 {
1185      int cmp;
1186      pkg_t *old, *new;
1187      char *old_version, *new_version;
1188
1189      old = pkg_hash_fetch_installed_by_name(pkg_name);
1190      if (old)
1191         opkg_msg(DEBUG2, "Old versions from pkg_hash_fetch %s.\n",
1192                         old->version);
1193
1194      new = pkg_hash_fetch_best_installation_candidate_by_name(pkg_name);
1195      if (new == NULL) {
1196         opkg_msg(NOTICE, "Unknown package '%s'.\n", pkg_name);
1197         return -1;
1198      }
1199
1200      opkg_msg(DEBUG2, "Versions from pkg_hash_fetch:");
1201      if ( old )
1202         opkg_message(DEBUG2, " old %s ", old->version);
1203      opkg_message(DEBUG2, " new %s\n", new->version);
1204
1205      new->state_flag |= SF_USER;
1206      if (old) {
1207           old_version = pkg_version_str_alloc(old);
1208           new_version = pkg_version_str_alloc(new);
1209
1210           cmp = pkg_compare_versions(old, new);
1211           if ( (conf->force_downgrade==1) && (cmp > 0) ){     /* We've been asked to allow downgrade  and version is precedent */
1212              opkg_msg(DEBUG, "Forcing downgrade\n");
1213              cmp = -1 ;                                       /* then we force opkg to downgrade */
1214                                                               /* We need to use a value < 0 because in the 0 case we are asking to */
1215                                                               /* reinstall, and some check could fail asking the "force-reinstall" option */
1216           }
1217           opkg_msg(DEBUG, "Comparing visible versions of pkg %s:"
1218                        "\n\t%s is installed "
1219                        "\n\t%s is available "
1220                        "\n\t%d was comparison result\n",
1221                        pkg_name, old_version, new_version, cmp);
1222           if (cmp == 0) {
1223                opkg_msg(NOTICE,
1224                             "Package %s (%s) installed in %s is up to date.\n",
1225                             old->name, old_version, old->dest->name);
1226                free(old_version);
1227                free(new_version);
1228                return 0;
1229           } else if (cmp > 0) {
1230                opkg_msg(NOTICE,
1231                             "Not downgrading package %s on %s from %s to %s.\n",
1232                             old->name, old->dest->name, old_version, new_version);
1233                free(old_version);
1234                free(new_version);
1235                return 0;
1236           } else if (cmp < 0) {
1237                new->dest = old->dest;
1238                old->state_want = SW_DEINSTALL;
1239           }
1240           free(old_version);
1241           free(new_version);
1242      }
1243
1244      opkg_msg(DEBUG2,"Calling opkg_install_pkg.\n");
1245      return opkg_install_pkg(new, 0);
1246 }
1247
1248 /**
1249  *  @brief Really install a pkg_t
1250  */
1251 int
1252 opkg_install_pkg(pkg_t *pkg, int from_upgrade)
1253 {
1254      int err = 0;
1255      int message = 0;
1256      pkg_t *old_pkg = NULL;
1257      pkg_vec_t *replacees;
1258      abstract_pkg_t *ab_pkg = NULL;
1259      int old_state_flag;
1260      char* file_md5;
1261 #ifdef HAVE_SHA256
1262      char* file_sha256;
1263 #endif
1264      sigset_t newset, oldset;
1265
1266      if ( from_upgrade )
1267         message = 1;            /* Coming from an upgrade, and should change the output message */
1268
1269      opkg_msg(DEBUG2, "Calling pkg_arch_supported.\n");
1270
1271      if (!pkg_arch_supported(pkg)) {
1272           opkg_msg(ERROR, "INTERNAL ERROR: architecture %s for pkg %s is unsupported.\n",
1273                        pkg->architecture, pkg->name);
1274           return -1;
1275      }
1276      if (pkg->state_status == SS_INSTALLED && conf->nodeps == 0) {
1277           err = satisfy_dependencies_for(pkg);
1278           if (err)
1279                   return -1;
1280
1281           opkg_msg(NOTICE, "Package %s is already installed on %s.\n",
1282                        pkg->name, pkg->dest->name);
1283           return 0;
1284      }
1285
1286      if (pkg->dest == NULL) {
1287           pkg->dest = conf->default_dest;
1288      }
1289
1290      old_pkg = pkg_hash_fetch_installed_by_name(pkg->name);
1291
1292      err = opkg_install_check_downgrade(pkg, old_pkg, message);
1293      if (err)
1294              return -1;
1295
1296      pkg->state_want = SW_INSTALL;
1297      if (old_pkg){
1298          old_pkg->state_want = SW_DEINSTALL; /* needed for check_data_file_clashes of dependencies */
1299      }
1300
1301      err = check_conflicts_for(pkg);
1302      if (err)
1303              return -1;
1304
1305      /* this setup is to remove the upgrade scenario in the end when
1306         installing pkg A, A deps B & B deps on A. So both B and A are
1307         installed. Then A's installation is started resulting in an
1308         uncecessary upgrade */
1309      if (pkg->state_status == SS_INSTALLED)
1310              return 0;
1311
1312      err = verify_pkg_installable(pkg);
1313      if (err)
1314              return -1;
1315
1316      if (pkg->local_filename == NULL) {
1317          if(!conf->cache && conf->download_only){
1318              char cwd[4096];
1319              if(getcwd(cwd, sizeof(cwd)) != NULL)
1320                 err = opkg_download_pkg(pkg, cwd);
1321              else
1322                 return -1;
1323          } else {
1324              err = opkg_download_pkg(pkg, conf->tmp_dir);
1325          }
1326           if (err) {
1327                opkg_msg(ERROR, "Failed to download %s. "
1328                                "Perhaps you need to run 'opkg update'?\n",
1329                             pkg->name);
1330                return -1;
1331           }
1332      }
1333
1334      /* check that the repository is valid */
1335      #if defined(HAVE_GPGME) || defined(HAVE_OPENSSL) || defined(HAVE_USIGN)
1336      char *list_file_name, *sig_file_name, *lists_dir;
1337
1338      /* check to ensure the package has come from a repository */
1339      if (conf->check_signature && pkg->src)
1340      {
1341        sprintf_alloc (&lists_dir, "%s",
1342                      (conf->restrict_to_default_dest)
1343                       ? conf->default_dest->lists_dir
1344                       : conf->lists_dir);
1345        sprintf_alloc (&list_file_name, "%s/%s", lists_dir, pkg->src->name);
1346        sprintf_alloc (&sig_file_name, "%s/%s.sig", lists_dir, pkg->src->name);
1347
1348        if (file_exists (sig_file_name))
1349        {
1350          if (opkg_verify_file (list_file_name, sig_file_name)){
1351            opkg_msg(ERROR, "Failed to verify the signature of %s.\n",
1352                            list_file_name);
1353            if (!conf->force_signature)
1354              return -1;
1355          }
1356        }else{
1357          opkg_msg(ERROR, "Signature file is missing for %s. "
1358                          "Perhaps you need to run 'opkg update'?\n",
1359                          pkg->name);
1360          if (!conf->force_signature)
1361            return -1;
1362        }
1363
1364        free (lists_dir);
1365        free (list_file_name);
1366        free (sig_file_name);
1367      }
1368      #endif
1369
1370 #ifdef HAVE_MD5
1371      /* Check for md5 values */
1372      if (pkg->md5sum)
1373      {
1374          file_md5 = file_md5sum_alloc(pkg->local_filename);
1375          if (file_md5 && strcmp(file_md5, pkg->md5sum))
1376          {
1377               if (!conf->force_checksum)
1378               {
1379                   opkg_msg(ERROR, "Package %s md5sum mismatch. "
1380                             "Either the opkg or the package index are corrupt. "
1381                             "Try 'opkg update'.\n",
1382                             pkg->name);
1383                   free(file_md5);
1384                   return -1;
1385               }
1386               else
1387               {
1388                   opkg_msg(NOTICE, "Ignored %s md5sum mismatch.\n", pkg->name);
1389               }
1390          }
1391          if (file_md5)
1392               free(file_md5);
1393      }
1394 #endif
1395
1396 #ifdef HAVE_SHA256
1397      /* Check for sha256 value */
1398      if(pkg->sha256sum)
1399      {
1400          file_sha256 = file_sha256sum_alloc(pkg->local_filename);
1401          if (file_sha256 && strcmp(file_sha256, pkg->sha256sum))
1402          {
1403               if (!conf->force_checksum)
1404               {
1405                   opkg_msg(ERROR,
1406                            "Package %s sha256sum mismatch. "
1407                            "Either the opkg or the package index are corrupt. "
1408                            "Try 'opkg update'.\n",
1409                            pkg->name);
1410                   free(file_sha256);
1411                   return -1;
1412               }
1413               else
1414               {
1415                   opkg_msg(NOTICE,
1416                            "Ignored %s sha256sum mismatch.\n",
1417                            pkg->name);
1418               }
1419          }
1420          if (file_sha256)
1421               free(file_sha256);
1422      }
1423 #endif
1424      if(conf->download_only) {
1425          if (conf->nodeps == 0) {
1426              err = satisfy_dependencies_for(pkg);
1427              if (err)
1428                  return -1;
1429          }
1430          return 0;
1431      }
1432
1433      if (pkg->tmp_unpack_dir == NULL) {
1434           if (unpack_pkg_control_files(pkg) == -1) {
1435                opkg_msg(ERROR, "Failed to unpack control files from %s.\n",
1436                                pkg->local_filename);
1437                return -1;
1438           }
1439      }
1440
1441      err = update_file_ownership(pkg, old_pkg);
1442      if (err)
1443              return -1;
1444
1445      if (conf->nodeps == 0) {
1446           err = satisfy_dependencies_for(pkg);
1447           if (err)
1448                 return -1;
1449           if (pkg->state_status == SS_UNPACKED)
1450                /* Circular dependency has installed it for us. */
1451                 return 0;
1452      }
1453
1454      replacees = pkg_vec_alloc();
1455      pkg_get_installed_replacees(pkg, replacees);
1456
1457      /* this next section we do with SIGINT blocked to prevent inconsistency between opkg database and filesystem */
1458
1459           sigemptyset(&newset);
1460           sigaddset(&newset, SIGINT);
1461           sigprocmask(SIG_BLOCK, &newset, &oldset);
1462
1463           opkg_state_changed++;
1464           pkg->state_flag |= SF_FILELIST_CHANGED;
1465
1466           if (old_pkg) {
1467                pkg_remove_orphan_dependent(pkg, old_pkg);
1468                old_pkg->is_upgrade = 1;
1469                pkg->is_upgrade = 1;
1470           }
1471           /* XXX: BUG: we really should treat replacement more like an upgrade
1472            *      Instead, we're going to remove the replacees
1473            */
1474           err = pkg_remove_installed_replacees(replacees);
1475           if (err)
1476                   goto UNWIND_REMOVE_INSTALLED_REPLACEES;
1477
1478           err = prerm_upgrade_old_pkg(pkg, old_pkg);
1479           if (err)
1480                   goto UNWIND_PRERM_UPGRADE_OLD_PKG;
1481
1482           err = prerm_deconfigure_conflictors(pkg, replacees);
1483           if (err)
1484                   goto UNWIND_PRERM_DECONFIGURE_CONFLICTORS;
1485
1486           err = preinst_configure(pkg, old_pkg);
1487           if (err)
1488                   goto UNWIND_PREINST_CONFIGURE;
1489
1490           err = backup_modified_conffiles(pkg, old_pkg);
1491           if (err)
1492                   goto UNWIND_BACKUP_MODIFIED_CONFFILES;
1493
1494           err = check_data_file_clashes(pkg, old_pkg);
1495           if (err)
1496                   goto UNWIND_CHECK_DATA_FILE_CLASHES;
1497
1498           err = postrm_upgrade_old_pkg(pkg, old_pkg);
1499           if (err)
1500                   goto UNWIND_POSTRM_UPGRADE_OLD_PKG;
1501
1502           if (conf->noaction)
1503                   return 0;
1504
1505           /* point of no return: no unwinding after this */
1506           if (old_pkg) {
1507                old_pkg->state_want = SW_DEINSTALL;
1508
1509                if (old_pkg->state_flag & SF_NOPRUNE) {
1510                     opkg_msg(INFO, "Not removing obsolesced files because "
1511                                     "package %s marked noprune.\n",
1512                                     old_pkg->name);
1513                } else {
1514                     opkg_msg(INFO, "Removing obsolesced files for %s\n",
1515                                     old_pkg->name);
1516                     if (remove_obsolesced_files(pkg, old_pkg)) {
1517                         opkg_msg(ERROR, "Failed to determine "
1518                                         "obsolete files from previously "
1519                                         "installed %s\n", old_pkg->name);
1520                     }
1521                }
1522
1523                /* removing files from old package, to avoid ghost files */
1524                remove_data_files_and_list(old_pkg);
1525                remove_maintainer_scripts(old_pkg);
1526           }
1527
1528
1529           opkg_msg(INFO, "%s maintainer scripts.\n", (pkg->is_upgrade) ? ("Upgrading") : ("Installing"));
1530           if (install_maintainer_scripts(pkg, old_pkg)) {
1531                 opkg_msg(ERROR, "Failed to extract maintainer scripts for %s."
1532                                " Package debris may remain!\n",
1533                                pkg->name);
1534                 goto pkg_is_hosed;
1535           }
1536
1537           /* the following just returns 0 */
1538           remove_disappeared(pkg);
1539
1540           opkg_msg(INFO, "Installing data files for %s.\n", pkg->name);
1541
1542           if (install_data_files(pkg)) {
1543                 opkg_msg(ERROR, "Failed to extract data files for %s. "
1544                                 "Package debris may remain!\n",
1545                                pkg->name);
1546                 goto pkg_is_hosed;
1547           }
1548
1549           err = check_data_file_clashes_change(pkg, old_pkg);
1550           if (err) {
1551                 opkg_msg(ERROR, "check_data_file_clashes_change() failed for "
1552                                "for files belonging to %s.\n",
1553                                pkg->name);
1554           }
1555
1556           opkg_msg(INFO, "Resolving conf files for %s\n", pkg->name);
1557           resolve_conffiles(pkg);
1558
1559           pkg->state_status = SS_UNPACKED;
1560           old_state_flag = pkg->state_flag;
1561           pkg->state_flag &= ~SF_PREFER;
1562           opkg_msg(DEBUG, "pkg=%s old_state_flag=%x state_flag=%x\n",
1563                           pkg->name, old_state_flag, pkg->state_flag);
1564
1565           if (old_pkg)
1566                old_pkg->state_status = SS_NOT_INSTALLED;
1567
1568           time(&pkg->installed_time);
1569
1570           ab_pkg = pkg->parent;
1571           if (ab_pkg)
1572                ab_pkg->state_status = pkg->state_status;
1573
1574           sigprocmask(SIG_UNBLOCK, &newset, &oldset);
1575           pkg_vec_free (replacees);
1576           return 0;
1577
1578
1579      UNWIND_POSTRM_UPGRADE_OLD_PKG:
1580           postrm_upgrade_old_pkg_unwind(pkg, old_pkg);
1581      UNWIND_CHECK_DATA_FILE_CLASHES:
1582           check_data_file_clashes_unwind(pkg, old_pkg);
1583      UNWIND_BACKUP_MODIFIED_CONFFILES:
1584           backup_modified_conffiles_unwind(pkg, old_pkg);
1585      UNWIND_PREINST_CONFIGURE:
1586           preinst_configure_unwind(pkg, old_pkg);
1587      UNWIND_PRERM_DECONFIGURE_CONFLICTORS:
1588           prerm_deconfigure_conflictors_unwind(pkg, replacees);
1589      UNWIND_PRERM_UPGRADE_OLD_PKG:
1590           prerm_upgrade_old_pkg_unwind(pkg, old_pkg);
1591      UNWIND_REMOVE_INSTALLED_REPLACEES:
1592           pkg_remove_installed_replacees_unwind(replacees);
1593
1594 pkg_is_hosed:
1595           sigprocmask(SIG_UNBLOCK, &newset, &oldset);
1596
1597           pkg_vec_free (replacees);
1598           return -1;
1599 }