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