just whitespace
[platform/upstream/busybox.git] / archival / dpkg.c
1 /*
2  *  Mini dpkg implementation for busybox.
3  *  This is not meant as a replacement for dpkg
4  *
5  *  Written By Glenn McGrath with the help of others
6  *  Copyright (C) 2001 by Glenn McGrath
7  *
8  *  Started life as a busybox implementation of udpkg
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU Library General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  */
24
25 /*
26  * Known difference between busybox dpkg and the official dpkg that i don't
27  * consider important, its worth keeping a note of differences anyway, just to
28  * make it easier to maintain.
29  *  - The first value for the Confflile: field isnt placed on a new line.
30  *  - When installing a package the Status: field is placed at the end of the
31  *      section, rather than just after the Package: field.
32  *
33  * Bugs that need to be fixed
34  *  - (unknown, please let me know when you find any)
35  *
36  */
37
38 #include <fcntl.h>
39 #include <getopt.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include "unarchive.h"
44 #include "busybox.h"
45
46 /* NOTE: If you vary HASH_PRIME sizes be aware,
47  * 1) Tweaking these will have a big effect on how much memory this program uses.
48  * 2) For computational efficiency these hash tables should be at least 20%
49  *    larger than the maximum number of elements stored in it.
50  * 3) All _HASH_PRIME's must be a prime number or chaos is assured, if your looking
51  *    for a prime, try http://www.utm.edu/research/primes/lists/small/10000.txt
52  * 4) If you go bigger than 15 bits you may get into trouble (untested) as its
53  *    sometimes cast to an unsigned int, if you go to 16 bit you will overlap
54  *    int's and chaos is assured, 16381 is the max prime for 14 bit field
55  */
56
57 /* NAME_HASH_PRIME, Stores package names and versions,
58  * I estimate it should be at least 50% bigger than PACKAGE_HASH_PRIME,
59  * as there a lot of duplicate version numbers */
60 #define NAME_HASH_PRIME 16381
61 static char *name_hashtable[NAME_HASH_PRIME + 1];
62
63 /* PACKAGE_HASH_PRIME, Maximum number of unique packages,
64  * It must not be smaller than STATUS_HASH_PRIME,
65  * Currently only packages from status_hashtable are stored in here, but in
66  * future this may be used to store packages not only from a status file,
67  * but an available_hashtable, and even multiple packages files.
68  * Package can be stored more than once if they have different versions.
69  * e.g. The same package may have different versions in the status file
70  *      and available file */
71 #define PACKAGE_HASH_PRIME 10007
72 typedef struct edge_s {
73         unsigned int operator:3;
74         unsigned int type:4;
75         unsigned int name:14;
76         unsigned int version:14;
77 } edge_t;
78
79 typedef struct common_node_s {
80         unsigned int name:14;
81         unsigned int version:14;
82         unsigned int num_of_edges:14;
83         edge_t **edge;
84 } common_node_t;
85 static common_node_t *package_hashtable[PACKAGE_HASH_PRIME + 1];
86
87 /* Currently it doesnt store packages that have state-status of not-installed
88  * So it only really has to be the size of the maximum number of packages
89  * likely to be installed at any one time, so there is a bit of leeway here */
90 #define STATUS_HASH_PRIME 8191
91 typedef struct status_node_s {
92         unsigned int package:14;        /* has to fit PACKAGE_HASH_PRIME */
93         unsigned int status:14;         /* has to fit STATUS_HASH_PRIME */
94 } status_node_t;
95 static status_node_t *status_hashtable[STATUS_HASH_PRIME + 1];
96
97 /* Even numbers are for 'extras', like ored dependencies or null */
98 enum edge_type_e {
99         EDGE_NULL = 0,
100         EDGE_PRE_DEPENDS = 1,
101         EDGE_OR_PRE_DEPENDS = 2,
102         EDGE_DEPENDS = 3,
103         EDGE_OR_DEPENDS = 4,
104         EDGE_REPLACES = 5,
105         EDGE_PROVIDES = 7,
106         EDGE_CONFLICTS = 9,
107         EDGE_SUGGESTS = 11,
108         EDGE_RECOMMENDS = 13,
109         EDGE_ENHANCES = 15
110 };
111 enum operator_e {
112         VER_NULL = 0,
113         VER_EQUAL = 1,
114         VER_LESS = 2,
115         VER_LESS_EQUAL = 3,
116         VER_MORE = 4,
117         VER_MORE_EQUAL = 5,
118         VER_ANY = 6
119 };
120
121 enum dpkg_opt_e {
122         dpkg_opt_purge = 1,
123         dpkg_opt_remove = 2,
124         dpkg_opt_unpack = 4,
125         dpkg_opt_configure = 8,
126         dpkg_opt_install = 16,
127         dpkg_opt_package_name = 32,
128         dpkg_opt_filename = 64,
129         dpkg_opt_list_installed = 128,
130         dpkg_opt_force_ignore_depends = 256
131 };
132
133 typedef struct deb_file_s {
134         char *control_file;
135         char *filename;
136         unsigned int package:14;
137 } deb_file_t;
138
139
140 static void make_hash(const char *key, unsigned int *start, unsigned int *decrement, const int hash_prime)
141 {
142         unsigned long int hash_num = key[0];
143         int len = strlen(key);
144         int i;
145
146         /* Maybe i should have uses a "proper" hashing algorithm here instead
147          * of making one up myself, seems to be working ok though. */
148         for(i = 1; i < len; i++) {
149                 /* shifts the ascii based value and adds it to previous value
150                  * shift amount is mod 24 because long int is 32 bit and data
151                  * to be shifted is 8, don't want to shift data to where it has
152                  * no effect*/
153                 hash_num += ((key[i] + key[i-1]) << ((key[i] * i) % 24));
154         }
155         *start = (unsigned int) hash_num % hash_prime;
156         *decrement = (unsigned int) 1 + (hash_num % (hash_prime - 1));
157 }
158
159 /* this adds the key to the hash table */
160 static int search_name_hashtable(const char *key)
161 {
162         unsigned int probe_address = 0;
163         unsigned int probe_decrement = 0;
164 //      char *temp;
165
166         make_hash(key, &probe_address, &probe_decrement, NAME_HASH_PRIME);
167         while(name_hashtable[probe_address] != NULL) {
168                 if (strcmp(name_hashtable[probe_address], key) == 0) {
169                         return(probe_address);
170                 } else {
171                         probe_address -= probe_decrement;
172                         if ((int)probe_address < 0) {
173                                 probe_address += NAME_HASH_PRIME;
174                         }
175                 }
176         }
177         name_hashtable[probe_address] = bb_xstrdup(key);
178         return(probe_address);
179 }
180
181 /* this DOESNT add the key to the hashtable
182  * TODO make it consistent with search_name_hashtable
183  */
184 static unsigned int search_status_hashtable(const char *key)
185 {
186         unsigned int probe_address = 0;
187         unsigned int probe_decrement = 0;
188
189         make_hash(key, &probe_address, &probe_decrement, STATUS_HASH_PRIME);
190         while(status_hashtable[probe_address] != NULL) {
191                 if (strcmp(key, name_hashtable[package_hashtable[status_hashtable[probe_address]->package]->name]) == 0) {
192                         break;
193                 } else {
194                         probe_address -= probe_decrement;
195                         if ((int)probe_address < 0) {
196                                 probe_address += STATUS_HASH_PRIME;
197                         }
198                 }
199         }
200         return(probe_address);
201 }
202
203 /* Need to rethink version comparison, maybe the official dpkg has something i can use ? */
204 static int version_compare_part(const char *version1, const char *version2)
205 {
206         int upstream_len1 = 0;
207         int upstream_len2 = 0;
208         char *name1_char;
209         char *name2_char;
210         int len1 = 0;
211         int len2 = 0;
212         int tmp_int;
213         int ver_num1;
214         int ver_num2;
215         int ret;
216
217         if (version1 == NULL) {
218                 version1 = bb_xstrdup("");
219         }
220         if (version2 == NULL) {
221                 version2 = bb_xstrdup("");
222         }
223         upstream_len1 = strlen(version1);
224         upstream_len2 = strlen(version2);
225
226         while ((len1 < upstream_len1) || (len2 < upstream_len2)) {
227                 /* Compare non-digit section */
228                 tmp_int = strcspn(&version1[len1], "0123456789");
229                 name1_char = bb_xstrndup(&version1[len1], tmp_int);
230                 len1 += tmp_int;
231                 tmp_int = strcspn(&version2[len2], "0123456789");
232                 name2_char = bb_xstrndup(&version2[len2], tmp_int);
233                 len2 += tmp_int;
234                 tmp_int = strcmp(name1_char, name2_char);
235                 free(name1_char);
236                 free(name2_char);
237                 if (tmp_int != 0) {
238                         ret = tmp_int;
239                         goto cleanup_version_compare_part;
240                 }
241
242                 /* Compare digits */
243                 tmp_int = strspn(&version1[len1], "0123456789");
244                 name1_char = bb_xstrndup(&version1[len1], tmp_int);
245                 len1 += tmp_int;
246                 tmp_int = strspn(&version2[len2], "0123456789");
247                 name2_char = bb_xstrndup(&version2[len2], tmp_int);
248                 len2 += tmp_int;
249                 ver_num1 = atoi(name1_char);
250                 ver_num2 = atoi(name2_char);
251                 free(name1_char);
252                 free(name2_char);
253                 if (ver_num1 < ver_num2) {
254                         ret = -1;
255                         goto cleanup_version_compare_part;
256                 }
257                 else if (ver_num1 > ver_num2) {
258                         ret = 1;
259                         goto cleanup_version_compare_part;
260                 }
261         }
262         ret = 0;
263 cleanup_version_compare_part:
264         return(ret);
265 }
266
267 /* if ver1 < ver2 return -1,
268  * if ver1 = ver2 return 0,
269  * if ver1 > ver2 return 1,
270  */
271 static int version_compare(const unsigned int ver1, const unsigned int ver2)
272 {
273         char *ch_ver1 = name_hashtable[ver1];
274         char *ch_ver2 = name_hashtable[ver2];
275
276         char epoch1, epoch2;
277         char *deb_ver1, *deb_ver2;
278         char *ver1_ptr, *ver2_ptr;
279         char *upstream_ver1;
280         char *upstream_ver2;
281         int result;
282
283         /* Compare epoch */
284         if (ch_ver1[1] == ':') {
285                 epoch1 = ch_ver1[0];
286                 ver1_ptr = strchr(ch_ver1, ':') + 1;
287         } else {
288                 epoch1 = '0';
289                 ver1_ptr = ch_ver1;
290         }
291         if (ch_ver2[1] == ':') {
292                 epoch2 = ch_ver2[0];
293                 ver2_ptr = strchr(ch_ver2, ':') + 1;
294         } else {
295                 epoch2 = '0';
296                 ver2_ptr = ch_ver2;
297         }
298         if (epoch1 < epoch2) {
299                 return(-1);
300         }
301         else if (epoch1 > epoch2) {
302                 return(1);
303         }
304
305         /* Compare upstream version */
306         upstream_ver1 = bb_xstrdup(ver1_ptr);
307         upstream_ver2 = bb_xstrdup(ver2_ptr);
308
309         /* Chop off debian version, and store for later use */
310         deb_ver1 = strrchr(upstream_ver1, '-');
311         deb_ver2 = strrchr(upstream_ver2, '-');
312         if (deb_ver1) {
313                 deb_ver1[0] = '\0';
314                 deb_ver1++;
315         }
316         if (deb_ver2) {
317                 deb_ver2[0] = '\0';
318                 deb_ver2++;
319         }
320         result = version_compare_part(upstream_ver1, upstream_ver2);
321
322         free(upstream_ver1);
323         free(upstream_ver2);
324
325         if (result != 0) {
326                 return(result);
327         }
328
329         /* Compare debian versions */
330         return(version_compare_part(deb_ver1, deb_ver2));
331 }
332
333 static int test_version(const unsigned int version1, const unsigned int version2, const unsigned int operator)
334 {
335         const int version_result = version_compare(version1, version2);
336         switch(operator) {
337                 case (VER_ANY):
338                         return(TRUE);
339                 case (VER_EQUAL):
340                         if (version_result == 0) {
341                                 return(TRUE);
342                         }
343                         break;
344                 case (VER_LESS):
345                         if (version_result < 0) {
346                                 return(TRUE);
347                         }
348                         break;
349                 case (VER_LESS_EQUAL):
350                         if (version_result <= 0) {
351                                 return(TRUE);
352                         }
353                         break;
354                 case (VER_MORE):
355                         if (version_result > 0) {
356                                 return(TRUE);
357                         }
358                         break;
359                 case (VER_MORE_EQUAL):
360                         if (version_result >= 0) {
361                                 return(TRUE);
362                         }
363                         break;
364         }
365         return(FALSE);
366 }
367
368
369 static int search_package_hashtable(const unsigned int name, const unsigned int version, const unsigned int operator)
370 {
371         unsigned int probe_address = 0;
372         unsigned int probe_decrement = 0;
373
374         make_hash(name_hashtable[name], &probe_address, &probe_decrement, PACKAGE_HASH_PRIME);
375         while(package_hashtable[probe_address] != NULL) {
376                 if (package_hashtable[probe_address]->name == name) {
377                         if (operator == VER_ANY) {
378                                 return(probe_address);
379                         }
380                         if (test_version(package_hashtable[probe_address]->version, version, operator)) {
381                                 return(probe_address);
382                         }
383                 }
384                 probe_address -= probe_decrement;
385                 if ((int)probe_address < 0) {
386                         probe_address += PACKAGE_HASH_PRIME;
387                 }
388         }
389         return(probe_address);
390 }
391
392 /*
393  * This function searches through the entire package_hashtable looking
394  * for a package which provides "needle". It returns the index into
395  * the package_hashtable for the providing package.
396  *
397  * needle is the index into name_hashtable of the package we are
398  * looking for.
399  *
400  * start_at is the index in the package_hashtable to start looking
401  * at. If start_at is -1 then start at the beginning. This is to allow
402  * for repeated searches since more than one package might provide
403  * needle.
404  *
405  * FIXME: I don't think this is very efficient, but I thought I'd keep
406  * it simple for now until it proves to be a problem.
407  */
408 static int search_for_provides(int needle, int start_at) {
409         int i, j;
410         common_node_t *p;
411         for (i = start_at + 1; i < PACKAGE_HASH_PRIME; i++) {
412                 p = package_hashtable[i];
413                 if ( p == NULL ) continue;
414                 for(j = 0; j < p->num_of_edges; j++)
415                         if ( p->edge[j]->type == EDGE_PROVIDES && p->edge[j]->name == needle )
416                                 return i;
417         }
418         return -1;
419 }
420
421 /*
422  * Add an edge to a node
423  */
424 static void add_edge_to_node(common_node_t *node, edge_t *edge)
425 {
426         node->num_of_edges++;
427         node->edge = xrealloc(node->edge, sizeof(edge_t) * (node->num_of_edges + 1));
428         node->edge[node->num_of_edges - 1] = edge;
429 }
430
431 /*
432  * Create one new node and one new edge for every dependency.
433  *
434  * Dependencies which contain multiple alternatives are represented as
435  * an EDGE_OR_PRE_DEPENDS or EDGE_OR_DEPENDS node, followed by a
436  * number of EDGE_PRE_DEPENDS or EDGE_DEPENDS nodes. The name field of
437  * the OR edge contains the full dependency string while the version
438  * field contains the number of EDGE nodes which follow as part of
439  * this alternative.
440  */
441 static void add_split_dependencies(common_node_t *parent_node, const char *whole_line, unsigned int edge_type)
442 {
443         char *line = bb_xstrdup(whole_line);
444         char *line2;
445         char *line_ptr1 = NULL;
446         char *line_ptr2 = NULL;
447         char *field;
448         char *field2;
449         char *version;
450         edge_t *edge;
451         edge_t *or_edge;
452         int offset_ch;
453
454         field = strtok_r(line, ",", &line_ptr1);
455         do {
456                 /* skip leading spaces */
457                 field += strspn(field, " ");
458                 line2 = bb_xstrdup(field);
459                 field2 = strtok_r(line2, "|", &line_ptr2);
460                 if ( (edge_type == EDGE_DEPENDS || edge_type == EDGE_PRE_DEPENDS) &&
461                      (strcmp(field, field2) != 0)) {
462                         or_edge = (edge_t *)xmalloc(sizeof(edge_t));
463                         or_edge->type = edge_type + 1;
464                 } else {
465                         or_edge = NULL;
466                 }
467
468                 if ( or_edge ) {
469                         or_edge->name = search_name_hashtable(field);
470                         or_edge->version = 0; // tracks the number of altenatives
471
472                         add_edge_to_node(parent_node, or_edge);
473                 }
474
475                 do {
476                         edge = (edge_t *) xmalloc(sizeof(edge_t));
477                         edge->type = edge_type;
478
479                         /* Skip any extra leading spaces */
480                         field2 += strspn(field2, " ");
481
482                         /* Get dependency version info */
483                         version = strchr(field2, '(');
484                         if (version == NULL) {
485                                 edge->operator = VER_ANY;
486                                 /* Get the versions hash number, adding it if the number isnt already in there */
487                                 edge->version = search_name_hashtable("ANY");
488                         } else {
489                                 /* Skip leading ' ' or '(' */
490                                 version += strspn(field2, " ");
491                                 version += strspn(version, "(");
492                                 /* Calculate length of any operator characters */
493                                 offset_ch = strspn(version, "<=>");
494                                 /* Determine operator */
495                                 if (offset_ch > 0) {
496                                         if (strncmp(version, "=", offset_ch) == 0) {
497                                                 edge->operator = VER_EQUAL;
498                                         }
499                                         else if (strncmp(version, "<<", offset_ch) == 0) {
500                                                 edge->operator = VER_LESS;
501                                         }
502                                         else if (strncmp(version, "<=", offset_ch) == 0) {
503                                                 edge->operator = VER_LESS_EQUAL;
504                                         }
505                                         else if (strncmp(version, ">>", offset_ch) == 0) {
506                                                 edge->operator = VER_MORE;
507                                         }
508                                         else if (strncmp(version, ">=", offset_ch) == 0) {
509                                                 edge->operator = VER_MORE_EQUAL;
510                                         } else {
511                                                 bb_error_msg_and_die("Illegal operator\n");
512                                         }
513                                 }
514                                 /* skip to start of version numbers */
515                                 version += offset_ch;
516                                 version += strspn(version, " ");
517
518                                 /* Truncate version at trailing ' ' or ')' */
519                                 version[strcspn(version, " )")] = '\0';
520                                 /* Get the versions hash number, adding it if the number isnt already in there */
521                                 edge->version = search_name_hashtable(version);
522                         }
523
524                         /* Get the dependency name */
525                         field2[strcspn(field2, " (")] = '\0';
526                         edge->name = search_name_hashtable(field2);
527
528                         if ( or_edge )
529                                 or_edge->version++;
530
531                         add_edge_to_node(parent_node, edge);
532                 } while ((field2 = strtok_r(NULL, "|", &line_ptr2)) != NULL);
533                 free(line2);
534         } while ((field = strtok_r(NULL, ",", &line_ptr1)) != NULL);
535         free(line);
536
537         return;
538 }
539
540 static void free_package(common_node_t *node)
541 {
542         unsigned short i;
543         if (node) {
544                 for (i = 0; i < node->num_of_edges; i++) {
545                         free(node->edge[i]);
546                 }
547                 if ( node->edge )
548                         free(node->edge);
549                 free(node);
550         }
551 }
552
553 static unsigned int fill_package_struct(char *control_buffer)
554 {
555         common_node_t *new_node = (common_node_t *) xcalloc(1, sizeof(common_node_t));
556         const char *field_names[] = { "Package", "Version", "Pre-Depends", "Depends",
557                 "Replaces", "Provides", "Conflicts", "Suggests", "Recommends", "Enhances", 0};
558         char *field_name;
559         char *field_value;
560         int field_start = 0;
561         int num = -1;
562         int buffer_length = strlen(control_buffer);
563
564         new_node->version = search_name_hashtable("unknown");
565         while (field_start < buffer_length) {
566                 unsigned short field_num;
567
568                 field_start += read_package_field(&control_buffer[field_start],
569                                 &field_name, &field_value);
570
571                 if (field_name == NULL) {
572                         goto fill_package_struct_cleanup; /* Oh no, the dreaded goto statement ! */
573                 }
574
575                 field_num = compare_string_array(field_names, field_name);
576                 switch(field_num) {
577                         case 0: /* Package */
578                                 new_node->name = search_name_hashtable(field_value);
579                                 break;
580                         case 1: /* Version */
581                                 new_node->version = search_name_hashtable(field_value);
582                                 break;
583                         case 2: /* Pre-Depends */
584                                 add_split_dependencies(new_node, field_value, EDGE_PRE_DEPENDS);
585                                 break;
586                         case 3: /* Depends */
587                                 add_split_dependencies(new_node, field_value, EDGE_DEPENDS);
588                                 break;
589                         case 4: /* Replaces */
590                                 add_split_dependencies(new_node, field_value, EDGE_REPLACES);
591                                 break;
592                         case 5: /* Provides */
593                                 add_split_dependencies(new_node, field_value, EDGE_PROVIDES);
594                                 break;
595                         case 6: /* Conflicts */
596                                 add_split_dependencies(new_node, field_value, EDGE_CONFLICTS);
597                                 break;
598                         case 7: /* Suggests */
599                                 add_split_dependencies(new_node, field_value, EDGE_SUGGESTS);
600                                 break;
601                         case 8: /* Recommends */
602                                 add_split_dependencies(new_node, field_value, EDGE_RECOMMENDS);
603                                 break;
604                         case 9: /* Enhances */
605                                 add_split_dependencies(new_node, field_value, EDGE_ENHANCES);
606                                 break;
607                 }
608 fill_package_struct_cleanup:
609                 free(field_name);
610                 free(field_value);
611         }
612
613         if (new_node->version == search_name_hashtable("unknown")) {
614                 free_package(new_node);
615                 return(-1);
616         }
617         num = search_package_hashtable(new_node->name, new_node->version, VER_EQUAL);
618         if (package_hashtable[num] == NULL) {
619                 package_hashtable[num] = new_node;
620         } else {
621                 free_package(new_node);
622         }
623         return(num);
624 }
625
626 /* if num = 1, it returns the want status, 2 returns flag, 3 returns status */
627 static unsigned int get_status(const unsigned int status_node, const int num)
628 {
629         char *status_string = name_hashtable[status_hashtable[status_node]->status];
630         char *state_sub_string;
631         unsigned int state_sub_num;
632         int len;
633         int i;
634
635         /* set tmp_string to point to the start of the word number */
636         for (i = 1; i < num; i++) {
637                 /* skip past a word */
638                 status_string += strcspn(status_string, " ");
639                 /* skip past the separating spaces */
640                 status_string += strspn(status_string, " ");
641         }
642         len = strcspn(status_string, " \n\0");
643         state_sub_string = bb_xstrndup(status_string, len);
644         state_sub_num = search_name_hashtable(state_sub_string);
645         free(state_sub_string);
646         return(state_sub_num);
647 }
648
649 static void set_status(const unsigned int status_node_num, const char *new_value, const int position)
650 {
651         const unsigned int new_value_len = strlen(new_value);
652         const unsigned int new_value_num = search_name_hashtable(new_value);
653         unsigned int want = get_status(status_node_num, 1);
654         unsigned int flag = get_status(status_node_num, 2);
655         unsigned int status = get_status(status_node_num, 3);
656         int want_len = strlen(name_hashtable[want]);
657         int flag_len = strlen(name_hashtable[flag]);
658         int status_len = strlen(name_hashtable[status]);
659         char *new_status;
660
661         switch (position) {
662                 case (1):
663                         want = new_value_num;
664                         want_len = new_value_len;
665                         break;
666                 case (2):
667                         flag = new_value_num;
668                         flag_len = new_value_len;
669                         break;
670                 case (3):
671                         status = new_value_num;
672                         status_len = new_value_len;
673                         break;
674                 default:
675                         bb_error_msg_and_die("DEBUG ONLY: this shouldnt happen");
676         }
677
678         new_status = (char *) xmalloc(want_len + flag_len + status_len + 3);
679         sprintf(new_status, "%s %s %s", name_hashtable[want], name_hashtable[flag], name_hashtable[status]);
680         status_hashtable[status_node_num]->status = search_name_hashtable(new_status);
681         free(new_status);
682         return;
683 }
684
685 static const char *describe_status(int status_num) {
686         int status_want, status_state ;
687         if ( status_hashtable[status_num] == NULL || status_hashtable[status_num]->status == 0 )
688                 return "is not installed or flagged to be installed\n";
689
690         status_want = get_status(status_num, 1);
691         status_state = get_status(status_num, 3);
692
693         if ( status_state == search_name_hashtable("installed") ) {
694                 if ( status_want == search_name_hashtable("install") )
695                         return "is installed";
696                 if ( status_want == search_name_hashtable("deinstall") )
697                         return "is marked to be removed";
698                 if ( status_want == search_name_hashtable("purge") )
699                         return "is marked to be purged";
700         }
701         if ( status_want ==  search_name_hashtable("unknown") )
702                 return "is in an indeterminate state";
703         if ( status_want == search_name_hashtable("install") )
704                 return "is marked to be installed";
705
706         return "is not installed or flagged to be installed";
707 }
708
709
710 static void index_status_file(const char *filename)
711 {
712         FILE *status_file;
713         char *control_buffer;
714         char *status_line;
715         status_node_t *status_node = NULL;
716         unsigned int status_num;
717
718         status_file = bb_xfopen(filename, "r");
719         while ((control_buffer = fgets_str(status_file, "\n\n")) != NULL) {
720                 const unsigned int package_num = fill_package_struct(control_buffer);
721                 if (package_num != -1) {
722                         status_node = xmalloc(sizeof(status_node_t));
723                         /* fill_package_struct doesnt handle the status field */
724                         status_line = strstr(control_buffer, "Status:");
725                         if (status_line != NULL) {
726                                 status_line += 7;
727                                 status_line += strspn(status_line, " \n\t");
728                                 status_line = bb_xstrndup(status_line, strcspn(status_line, "\n\0"));
729                                 status_node->status = search_name_hashtable(status_line);
730                                 free(status_line);
731                         }
732                         status_node->package = package_num;
733                         status_num = search_status_hashtable(name_hashtable[package_hashtable[status_node->package]->name]);
734                         status_hashtable[status_num] = status_node;
735                 }
736                 free(control_buffer);
737         }
738         fclose(status_file);
739         return;
740 }
741
742 #if 0 /* this code is no longer used */
743 char *get_depends_field(common_node_t *package, const int depends_type)
744 {
745         char *depends = NULL;
746         char *old_sep = (char *)xcalloc(1, 3);
747         char *new_sep = (char *)xcalloc(1, 3);
748         int line_size = 0;
749         int depends_size;
750
751         int i;
752
753         for (i = 0; i < package->num_of_edges; i++) {
754                 if ((package->edge[i]->type == EDGE_OR_PRE_DEPENDS) ||
755                         (package->edge[i]->type == EDGE_OR_DEPENDS)) {
756                 }
757
758                 if ((package->edge[i]->type == depends_type) ||
759                         (package->edge[i]->type == depends_type + 1)) {
760                         /* Check if its the first time through */
761
762                         depends_size = 8 + strlen(name_hashtable[package->edge[i]->name])
763                                 + strlen(name_hashtable[package->edge[i]->version]);
764                         line_size += depends_size;
765                         depends = (char *) xrealloc(depends, line_size + 1);
766
767                         /* Check to see if this dependency is the type we are looking for
768                          * +1 to check for 'extra' types, e.g. ored dependecies */
769                         strcpy(old_sep, new_sep);
770                         if (package->edge[i]->type == depends_type) {
771                                 strcpy(new_sep, ", ");
772                         }
773                         else if (package->edge[i]->type == depends_type + 1) {
774                                 strcpy(new_sep, "| ");
775                         }
776
777                         if (depends_size == line_size) {
778                                 strcpy(depends, "");
779                         } else {
780                                 if ((strcmp(old_sep, "| ") == 0) && (strcmp(new_sep, "| ") == 0)) {
781                                         strcat(depends, " | ");
782                                 } else {
783                                         strcat(depends, ", ");
784                                 }
785                         }
786
787                         strcat(depends, name_hashtable[package->edge[i]->name]);
788                         if (strcmp(name_hashtable[package->edge[i]->version], "NULL") != 0) {
789                                 if (package->edge[i]->operator == VER_EQUAL) {
790                                         strcat(depends, " (= ");
791                                 }
792                                 else if (package->edge[i]->operator == VER_LESS) {
793                                         strcat(depends, " (<< ");
794                                 }
795                                 else if (package->edge[i]->operator == VER_LESS_EQUAL) {
796                                         strcat(depends, " (<= ");
797                                 }
798                                 else if (package->edge[i]->operator == VER_MORE) {
799                                         strcat(depends, " (>> ");
800                                 }
801                                 else if (package->edge[i]->operator == VER_MORE_EQUAL) {
802                                         strcat(depends, " (>= ");
803                                 } else {
804                                         strcat(depends, " (");
805                                 }
806                                 strcat(depends, name_hashtable[package->edge[i]->version]);
807                                 strcat(depends, ")");
808                         }
809                 }
810         }
811         return(depends);
812 }
813 #endif
814
815 static void write_buffer_no_status(FILE *new_status_file, const char *control_buffer)
816 {
817         char *name;
818         char *value;
819         int start = 0;
820         while (1) {
821                 start += read_package_field(&control_buffer[start], &name, &value);
822                 if (name == NULL) {
823                         break;
824                 }
825                 if (strcmp(name, "Status") != 0) {
826                         fprintf(new_status_file, "%s: %s\n", name, value);
827                 }
828         }
829         return;
830 }
831
832 /* This could do with a cleanup */
833 static void write_status_file(deb_file_t **deb_file)
834 {
835         FILE *old_status_file = bb_xfopen("/var/lib/dpkg/status", "r");
836         FILE *new_status_file = bb_xfopen("/var/lib/dpkg/status.udeb", "w");
837         char *package_name;
838         char *status_from_file;
839         char *control_buffer = NULL;
840         char *tmp_string;
841         int status_num;
842         int field_start = 0;
843         int write_flag;
844         int i = 0;
845
846         /* Update previously known packages */
847         while ((control_buffer = fgets_str(old_status_file, "\n\n")) != NULL) {
848                 if ((tmp_string = strstr(control_buffer, "Package:")) == NULL) {
849                         continue;
850                 }
851
852                 tmp_string += 8;
853                 tmp_string += strspn(tmp_string, " \n\t");
854                 package_name = bb_xstrndup(tmp_string, strcspn(tmp_string, "\n\0"));
855                 write_flag = FALSE;
856                 tmp_string = strstr(control_buffer, "Status:");
857                 if (tmp_string != NULL) {
858                         /* Seperate the status value from the control buffer */
859                         tmp_string += 7;
860                         tmp_string += strspn(tmp_string, " \n\t");
861                         status_from_file = bb_xstrndup(tmp_string, strcspn(tmp_string, "\n"));
862                 } else {
863                         status_from_file = NULL;
864                 }
865
866                 /* Find this package in the status hashtable */
867                 status_num = search_status_hashtable(package_name);
868                 if (status_hashtable[status_num] != NULL) {
869                         const char *status_from_hashtable = name_hashtable[status_hashtable[status_num]->status];
870                         if (strcmp(status_from_file, status_from_hashtable) != 0) {
871                                 /* New status isnt exactly the same as old status */
872                                 const int state_status = get_status(status_num, 3);
873                                 if ((strcmp("installed", name_hashtable[state_status]) == 0) ||
874                                         (strcmp("unpacked", name_hashtable[state_status]) == 0)) {
875                                         /* We need to add the control file from the package */
876                                         i = 0;
877                                         while(deb_file[i] != NULL) {
878                                                 if (strcmp(package_name, name_hashtable[package_hashtable[deb_file[i]->package]->name]) == 0) {
879                                                         /* Write a status file entry with a modified status */
880                                                         /* remove trailing \n's */
881                                                         write_buffer_no_status(new_status_file, deb_file[i]->control_file);
882                                                         set_status(status_num, "ok", 2);
883                                                         fprintf(new_status_file, "Status: %s\n\n", name_hashtable[status_hashtable[status_num]->status]);
884                                                         write_flag = TRUE;
885                                                         break;
886                                                 }
887                                                 i++;
888                                         }
889                                         /* This is temperary, debugging only */
890                                         if (deb_file[i] == NULL) {
891                                                 bb_error_msg_and_die("ALERT: Couldnt find a control file, your status file may be broken, status may be incorrect for %s", package_name);
892                                         }
893                                 }
894                                 else if (strcmp("not-installed", name_hashtable[state_status]) == 0) {
895                                         /* Only write the Package, Status, Priority and Section lines */
896                                         fprintf(new_status_file, "Package: %s\n", package_name);
897                                         fprintf(new_status_file, "Status: %s\n", status_from_hashtable);
898
899                                         while (1) {
900                                                 char *field_name;
901                                                 char *field_value;
902                                                 field_start += read_package_field(&control_buffer[field_start], &field_name, &field_value);
903                                                 if (field_name == NULL) {
904                                                         break;
905                                                 }
906                                                 if ((strcmp(field_name, "Priority") == 0) ||
907                                                         (strcmp(field_name, "Section") == 0)) {
908                                                         fprintf(new_status_file, "%s: %s\n", field_name, field_value);
909                                                 }
910                                         }
911                                         write_flag = TRUE;
912                                         fputs("\n", new_status_file);
913                                 }
914                                 else if (strcmp("config-files", name_hashtable[state_status]) == 0) {
915                                         /* only change the status line */
916                                         while (1) {
917                                                 char *field_name;
918                                                 char *field_value;
919                                                 field_start += read_package_field(&control_buffer[field_start], &field_name, &field_value);
920                                                 if (field_name == NULL) {
921                                                         break;
922                                                 }
923                                                 /* Setup start point for next field */
924                                                 if (strcmp(field_name, "Status") == 0) {
925                                                         fprintf(new_status_file, "Status: %s\n", status_from_hashtable);
926                                                 } else {
927                                                         fprintf(new_status_file, "%s: %s\n", field_name, field_value);
928                                                 }
929                                         }
930                                         write_flag = TRUE;
931                                         fputs("\n", new_status_file);
932                                 }
933                         }
934                 }
935                 /* If the package from the status file wasnt handle above, do it now*/
936                 if (! write_flag) {
937                         fprintf(new_status_file, "%s\n\n", control_buffer);
938                 }
939
940                 free(status_from_file);
941                 free(package_name);
942                 free(control_buffer);
943         }
944
945         /* Write any new packages */
946         for(i = 0; deb_file[i] != NULL; i++) {
947                 status_num = search_status_hashtable(name_hashtable[package_hashtable[deb_file[i]->package]->name]);
948                 if (strcmp("reinstreq", name_hashtable[get_status(status_num, 2)]) == 0) {
949                         write_buffer_no_status(new_status_file, deb_file[i]->control_file);
950                         set_status(status_num, "ok", 2);
951                         fprintf(new_status_file, "Status: %s\n\n", name_hashtable[status_hashtable[status_num]->status]);
952                 }
953         }
954         fclose(old_status_file);
955         fclose(new_status_file);
956
957
958         /* Create a separate backfile to dpkg */
959         if (rename("/var/lib/dpkg/status", "/var/lib/dpkg/status.udeb.bak") == -1) {
960                 struct stat stat_buf;
961                 if (stat("/var/lib/dpkg/status", &stat_buf) == 0) {
962                         bb_error_msg_and_die("Couldnt create backup status file");
963                 }
964                 /* Its ok if renaming the status file fails because status
965                  * file doesnt exist, maybe we are starting from scratch */
966                 bb_error_msg("No status file found, creating new one");
967         }
968
969         if (rename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status") == -1) {
970                 bb_error_msg_and_die("DANGER: Couldnt create status file, you need to manually repair your status file");
971         }
972 }
973
974 /* This function returns TRUE if the given package can satisfy a
975  * dependency of type depend_type.
976  *
977  * A pre-depends is satisfied only if a package is already installed,
978  * which a regular depends can be satisfied by a package which we want
979  * to install.
980  */
981 static int package_satisfies_dependency(int package, int depend_type)
982 {
983         int status_num = search_status_hashtable(name_hashtable[package_hashtable[package]->name]);
984
985         /* status could be unknown if package is a pure virtual
986          * provides which cannot satisfy any dependency by itself.
987          */
988         if ( status_hashtable[status_num] == NULL )
989                 return 0;
990
991         switch (depend_type) {
992         case EDGE_PRE_DEPENDS:  return get_status(status_num, 3) == search_name_hashtable("installed");
993         case EDGE_DEPENDS:      return get_status(status_num, 1) == search_name_hashtable("install");
994         }
995         return 0;
996 }
997
998 static int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
999 {
1000         int *conflicts = NULL;
1001         int conflicts_num = 0;
1002         int i = deb_start;
1003         int j;
1004
1005         /* Check for conflicts
1006          * TODO: TEST if conflicts with other packages to be installed
1007          *
1008          * Add install packages and the packages they provide
1009          * to the list of files to check conflicts for
1010          */
1011
1012         /* Create array of package numbers to check against
1013          * installed package for conflicts*/
1014         while (deb_file[i] != NULL) {
1015                 const unsigned int package_num = deb_file[i]->package;
1016                 conflicts = xrealloc(conflicts, sizeof(int) * (conflicts_num + 1));
1017                 conflicts[conflicts_num] = package_num;
1018                 conflicts_num++;
1019                 /* add provides to conflicts list */
1020                 for (j = 0; j < package_hashtable[package_num]->num_of_edges; j++) {
1021                         if (package_hashtable[package_num]->edge[j]->type == EDGE_PROVIDES) {
1022                                 const int conflicts_package_num = search_package_hashtable(
1023                                         package_hashtable[package_num]->edge[j]->name,
1024                                         package_hashtable[package_num]->edge[j]->version,
1025                                         package_hashtable[package_num]->edge[j]->operator);
1026                                 if (package_hashtable[conflicts_package_num] == NULL) {
1027                                         /* create a new package */
1028                                         common_node_t *new_node = (common_node_t *) xmalloc(sizeof(common_node_t));
1029                                         new_node->name = package_hashtable[package_num]->edge[j]->name;
1030                                         new_node->version = package_hashtable[package_num]->edge[j]->version;
1031                                         new_node->num_of_edges = 0;
1032                                         new_node->edge = NULL;
1033                                         package_hashtable[conflicts_package_num] = new_node;
1034                                 }
1035                                 conflicts = xrealloc(conflicts, sizeof(int) * (conflicts_num + 1));
1036                                 conflicts[conflicts_num] = conflicts_package_num;
1037                                 conflicts_num++;
1038                         }
1039                 }
1040                 i++;
1041         }
1042
1043         /* Check conflicts */
1044         i = 0;
1045         while (deb_file[i] != NULL) {
1046                 const common_node_t *package_node = package_hashtable[deb_file[i]->package];
1047                 int status_num = 0;
1048                 status_num = search_status_hashtable(name_hashtable[package_node->name]);
1049
1050                 if (get_status(status_num, 3) == search_name_hashtable("installed")) {
1051                         i++;
1052                         continue;
1053                 }
1054
1055                 for (j = 0; j < package_node->num_of_edges; j++) {
1056                         const edge_t *package_edge = package_node->edge[j];
1057
1058                         if (package_edge->type == EDGE_CONFLICTS) {
1059                                 const unsigned int package_num =
1060                                         search_package_hashtable(package_edge->name,
1061                                                                  package_edge->version,
1062                                                                  package_edge->operator);
1063                                 int result = 0;
1064                                 if (package_hashtable[package_num] != NULL) {
1065                                         status_num = search_status_hashtable(name_hashtable[package_hashtable[package_num]->name]);
1066
1067                                         if (get_status(status_num, 1) == search_name_hashtable("install")) {
1068                                                 result = test_version(package_hashtable[deb_file[i]->package]->version,
1069                                                         package_edge->version, package_edge->operator);
1070                                         }
1071                                 }
1072
1073                                 if (result) {
1074                                         bb_error_msg_and_die("Package %s conflicts with %s",
1075                                                 name_hashtable[package_node->name],
1076                                                 name_hashtable[package_edge->name]);
1077                                 }
1078                         }
1079                 }
1080                 i++;
1081         }
1082
1083
1084         /* Check dependendcies */
1085         for (i = 0; i < PACKAGE_HASH_PRIME; i++) {
1086                 int status_num = 0;
1087                 int number_of_alternatives = 0;
1088                 const edge_t * root_of_alternatives = NULL;
1089                 const common_node_t *package_node = package_hashtable[i];
1090
1091                 /* If the package node does not exist then this
1092                  * package is a virtual one. In which case there are
1093                  * no dependencies to check.
1094                  */
1095                 if ( package_node == NULL ) continue;
1096
1097                 status_num = search_status_hashtable(name_hashtable[package_node->name]);
1098
1099                 /* If there is no status then this package is a
1100                  * virtual one provided by something else. In which
1101                  * case there are no dependencies to check.
1102                  */
1103                 if ( status_hashtable[status_num] == NULL ) continue;
1104
1105                 /* If we don't want this package installed then we may
1106                  * as well ignore it's dependencies.
1107                  */
1108                 if (get_status(status_num, 1) != search_name_hashtable("install")) {
1109                         continue;
1110                 }
1111
1112 #if 0
1113                 /* This might be needed so we don't complain about
1114                  * things which are broken but unrelated to the
1115                  * packages that are currently being installed
1116                  */
1117                 if (state_status == search_name_hashtable("installed"))
1118                         continue;
1119 #endif
1120
1121                 /* This code is tested only for EDGE_DEPENDS, since I
1122                  * have no suitable pre-depends available. There is no
1123                  * reason that it shouldn't work though :-)
1124                  */
1125                 for (j = 0; j < package_node->num_of_edges; j++) {
1126                         const edge_t *package_edge = package_node->edge[j];
1127                         unsigned int package_num;
1128
1129                         if ( package_edge->type == EDGE_OR_PRE_DEPENDS ||
1130                              package_edge->type == EDGE_OR_DEPENDS ) {  /* start an EDGE_OR_ list */
1131                                 number_of_alternatives = package_edge->version;
1132                                 root_of_alternatives = package_edge;
1133                                 continue;
1134                         } else if ( number_of_alternatives == 0 ) {     /* not in the middle of an EDGE_OR_ list */
1135                                 number_of_alternatives = 1;
1136                                 root_of_alternatives = NULL;
1137                         }
1138
1139                         package_num = search_package_hashtable(package_edge->name, package_edge->version, package_edge->operator);
1140
1141                         if (package_edge->type == EDGE_PRE_DEPENDS ||
1142                             package_edge->type == EDGE_DEPENDS ) {
1143                                 int result=1;
1144                                 status_num = 0;
1145
1146                                 /* If we are inside an alternative then check
1147                                  * this edge is the right type.
1148                                  *
1149                                  * EDGE_DEPENDS == OR_DEPENDS -1
1150                                  * EDGE_PRE_DEPENDS == OR_PRE_DEPENDS -1
1151                                  */
1152                                 if ( root_of_alternatives && package_edge->type != root_of_alternatives->type - 1)
1153                                         bb_error_msg_and_die("Fatal error. Package dependencies corrupt: %d != %d - 1 \n",
1154                                                              package_edge->type, root_of_alternatives->type);
1155
1156                                 if (package_hashtable[package_num] != NULL)
1157                                         result = !package_satisfies_dependency(package_num, package_edge->type);
1158
1159                                 if (result) { /* check for other package which provide what we are looking for */
1160                                         int provider = -1;
1161
1162                                         while ( (provider = search_for_provides(package_edge->name, provider) ) > -1 ) {
1163                                                 if ( package_hashtable[provider] == NULL ) {
1164                                                         printf("Have a provider but no package information for it\n");
1165                                                         continue;
1166                                                 }
1167                                                 result = !package_satisfies_dependency(provider, package_edge->type);
1168
1169                                                 if ( result == 0 )
1170                                                         break;
1171                                         }
1172                                 }
1173
1174                                 /* It must be already installed, or to be installed */
1175                                 number_of_alternatives--;
1176                                 if (result && number_of_alternatives == 0) {
1177                                         if ( root_of_alternatives )
1178                                                 bb_error_msg_and_die(
1179                                                         "Package %s %sdepends on %s, "
1180                                                         "which cannot be satisfied",
1181                                                         name_hashtable[package_node->name],
1182                                                         package_edge->type == EDGE_PRE_DEPENDS ? "pre-" : "",
1183                                                         name_hashtable[root_of_alternatives->name]);
1184                                         else
1185                                                 bb_error_msg_and_die(
1186                                                         "Package %s %sdepends on %s, which %s\n",
1187                                                         name_hashtable[package_node->name],
1188                                                         package_edge->type == EDGE_PRE_DEPENDS ? "pre-" : "",
1189                                                         name_hashtable[package_edge->name],
1190                                                         describe_status(status_num));
1191                                 } else if ( result == 0 && number_of_alternatives ) {
1192                                         /* we've found a package which
1193                                          * satisfies the dependency,
1194                                          * so skip over the rest of
1195                                          * the alternatives.
1196                                          */
1197                                         j += number_of_alternatives;
1198                                         number_of_alternatives = 0;
1199                                 }
1200                         }
1201                 }
1202         }
1203         free(conflicts);
1204         return(TRUE);
1205 }
1206
1207 static char **create_list(const char *filename)
1208 {
1209         FILE *list_stream;
1210         char **file_list = NULL;
1211         char *line = NULL;
1212         int count = 0;
1213
1214         /* don't use [xw]fopen here, handle error ourself */
1215         list_stream = fopen(filename, "r");
1216         if (list_stream == NULL) {
1217                 return(NULL);
1218         }
1219
1220         while ((line = bb_get_chomped_line_from_file(list_stream)) != NULL) {
1221                 file_list = xrealloc(file_list, sizeof(char *) * (count + 2));
1222                 file_list[count] = line;
1223                 count++;
1224         }
1225         fclose(list_stream);
1226
1227         if (count == 0) {
1228                 return(NULL);
1229         } else {
1230                 file_list[count] = NULL;
1231                 return(file_list);
1232         }
1233 }
1234
1235 /* maybe i should try and hook this into remove_file.c somehow */
1236 static int remove_file_array(char **remove_names, char **exclude_names)
1237 {
1238         struct stat path_stat;
1239         int match_flag;
1240         int remove_flag = FALSE;
1241         int i,j;
1242
1243         if (remove_names == NULL) {
1244                 return(FALSE);
1245         }
1246         for (i = 0; remove_names[i] != NULL; i++) {
1247                 match_flag = FALSE;
1248                 if (exclude_names != NULL) {
1249                         for (j = 0; exclude_names[j] != 0; j++) {
1250                                 if (strcmp(remove_names[i], exclude_names[j]) == 0) {
1251                                         match_flag = TRUE;
1252                                         break;
1253                                 }
1254                         }
1255                 }
1256                 if (!match_flag) {
1257                         if (lstat(remove_names[i], &path_stat) < 0) {
1258                                 continue;
1259                         }
1260                         if (S_ISDIR(path_stat.st_mode)) {
1261                                 if (rmdir(remove_names[i]) != -1) {
1262                                         remove_flag = TRUE;
1263                                 }
1264                         } else {
1265                                 if (unlink(remove_names[i]) != -1) {
1266                                         remove_flag = TRUE;
1267                                 }
1268                         }
1269                 }
1270         }
1271         return(remove_flag);
1272 }
1273
1274 static int run_package_script(const char *package_name, const char *script_type)
1275 {
1276         struct stat path_stat;
1277         char *script_path;
1278         int result;
1279
1280         script_path = xmalloc(strlen(package_name) + strlen(script_type) + 21);
1281         sprintf(script_path, "/var/lib/dpkg/info/%s.%s", package_name, script_type);
1282
1283         /* If the file doesnt exist is isnt a fatal */
1284         if (lstat(script_path, &path_stat) < 0) {
1285                 result = EXIT_SUCCESS;
1286         } else {
1287                 result = system(script_path);
1288         }
1289         free(script_path);
1290         return(result);
1291 }
1292
1293 static const char *all_control_files[] = {"preinst", "postinst", "prerm", "postrm",
1294         "list", "md5sums", "shlibs", "conffiles", "config", "templates", NULL };
1295
1296 static char **all_control_list(const char *package_name)
1297 {
1298         unsigned short i = 0;
1299         char **remove_files;
1300
1301         /* Create a list of all /var/lib/dpkg/info/<package> files */
1302         remove_files = xmalloc(sizeof(all_control_files));
1303         while (all_control_files[i]) {
1304                 remove_files[i] = xmalloc(strlen(package_name) + strlen(all_control_files[i]) + 21);
1305                 sprintf(remove_files[i], "/var/lib/dpkg/info/%s.%s", package_name, all_control_files[i]);
1306                 i++;
1307         }
1308         remove_files[sizeof(all_control_files)/sizeof(char*) - 1] = NULL;
1309
1310         return(remove_files);
1311 }
1312
1313 static void free_array(char **array)
1314 {
1315
1316         if (array) {
1317                 unsigned short i = 0;
1318                 while (array[i]) {
1319                         free(array[i]);
1320                         i++;
1321                 }
1322                 free(array);
1323         }
1324 }
1325
1326 /* This function lists information on the installed packages. It loops through
1327  * the status_hashtable to retrieve the info. This results in smaller code than
1328  * scanning the status file. The resulting list, however, is unsorted.
1329  */
1330 static void list_packages(void)
1331 {
1332         int i;
1333
1334         printf("    Name           Version\n");
1335         printf("+++-==============-==============\n");
1336
1337         /* go through status hash, dereference package hash and finally strings */
1338         for (i=0; i<STATUS_HASH_PRIME+1; i++) {
1339
1340                 if (status_hashtable[i]) {
1341                         const char *stat_str;  /* status string */
1342                         const char *name_str;  /* package name */
1343                         const char *vers_str;  /* version */
1344                         char  s1, s2;          /* status abbreviations */
1345                         int   spccnt;          /* space count */
1346                         int   j;
1347
1348                         stat_str = name_hashtable[status_hashtable[i]->status];
1349                         name_str = name_hashtable[package_hashtable[status_hashtable[i]->package]->name];
1350                         vers_str = name_hashtable[package_hashtable[status_hashtable[i]->package]->version];
1351
1352                         /* get abbreviation for status field 1 */
1353                         s1 = stat_str[0] == 'i' ? 'i' : 'r';
1354
1355                         /* get abbreviation for status field 2 */
1356                         for (j=0, spccnt=0; stat_str[j] && spccnt<2; j++) {
1357                                 if (stat_str[j] == ' ') spccnt++;
1358                         }
1359                         s2 = stat_str[j];
1360
1361                         /* print out the line formatted like Debian dpkg */
1362                         printf("%c%c  %-14s %s\n", s1, s2, name_str, vers_str);
1363                 }
1364     }
1365 }
1366
1367 static void remove_package(const unsigned int package_num, int noisy)
1368 {
1369         const char *package_name = name_hashtable[package_hashtable[package_num]->name];
1370         const char *package_version = name_hashtable[package_hashtable[package_num]->version];
1371         const unsigned int status_num = search_status_hashtable(package_name);
1372         const int package_name_length = strlen(package_name);
1373         char **remove_files;
1374         char **exclude_files;
1375         char list_name[package_name_length + 25];
1376         char conffile_name[package_name_length + 30];
1377         int return_value;
1378
1379         if ( noisy )
1380                 printf("Removing %s (%s) ...\n", package_name, package_version);
1381
1382         /* run prerm script */
1383         return_value = run_package_script(package_name, "prerm");
1384         if (return_value == -1) {
1385                 bb_error_msg_and_die("script failed, prerm failure");
1386         }
1387
1388         /* Create a list of files to remove, and a separate list of those to keep */
1389         sprintf(list_name, "/var/lib/dpkg/info/%s.list", package_name);
1390         remove_files = create_list(list_name);
1391
1392         sprintf(conffile_name, "/var/lib/dpkg/info/%s.conffiles", package_name);
1393         exclude_files = create_list(conffile_name);
1394
1395         /* Some directories cant be removed straight away, so do multiple passes */
1396         while (remove_file_array(remove_files, exclude_files));
1397         free_array(exclude_files);
1398         free_array(remove_files);
1399
1400         /* Create a list of files in /var/lib/dpkg/info/<package>.* to keep  */
1401         exclude_files = xmalloc(sizeof(char*) * 3);
1402         exclude_files[0] = bb_xstrdup(conffile_name);
1403         exclude_files[1] = xmalloc(package_name_length + 27);
1404         sprintf(exclude_files[1], "/var/lib/dpkg/info/%s.postrm", package_name);
1405         exclude_files[2] = NULL;
1406
1407         /* Create a list of all /var/lib/dpkg/info/<package> files */
1408         remove_files = all_control_list(package_name);
1409
1410         remove_file_array(remove_files, exclude_files);
1411         free_array(remove_files);
1412         free_array(exclude_files);
1413
1414         /* rename <package>.conffile to <package>.list */
1415         rename(conffile_name, list_name);
1416
1417         /* Change package status */
1418         set_status(status_num, "config-files", 3);
1419 }
1420
1421 static void purge_package(const unsigned int package_num)
1422 {
1423         const char *package_name = name_hashtable[package_hashtable[package_num]->name];
1424         const char *package_version = name_hashtable[package_hashtable[package_num]->version];
1425         const unsigned int status_num = search_status_hashtable(package_name);
1426         char **remove_files;
1427         char **exclude_files;
1428         char list_name[strlen(package_name) + 25];
1429
1430         printf("Purging %s (%s) ...\n", package_name, package_version);
1431
1432         /* run prerm script */
1433         if (run_package_script(package_name, "prerm") != 0) {
1434                 bb_error_msg_and_die("script failed, prerm failure");
1435         }
1436
1437         /* Create a list of files to remove */
1438         sprintf(list_name, "/var/lib/dpkg/info/%s.list", package_name);
1439         remove_files = create_list(list_name);
1440
1441         exclude_files = xmalloc(sizeof(char*));
1442         exclude_files[0] = NULL;
1443
1444         /* Some directories cant be removed straight away, so do multiple passes */
1445         while (remove_file_array(remove_files, exclude_files));
1446         free_array(remove_files);
1447
1448         /* Create a list of all /var/lib/dpkg/info/<package> files */
1449         remove_files = all_control_list(package_name);
1450         remove_file_array(remove_files, exclude_files);
1451         free_array(remove_files);
1452         free(exclude_files);
1453
1454         /* run postrm script */
1455         if (run_package_script(package_name, "postrm") == -1) {
1456                 bb_error_msg_and_die("postrm fialure.. set status to what?");
1457         }
1458
1459         /* Change package status */
1460         set_status(status_num, "not-installed", 3);
1461 }
1462
1463 static archive_handle_t *init_archive_deb_ar(const char *filename)
1464 {
1465         archive_handle_t *ar_handle;
1466
1467         /* Setup an ar archive handle that refers to the gzip sub archive */
1468         ar_handle = init_handle();
1469         ar_handle->filter = filter_accept_list_reassign;
1470         ar_handle->src_fd = bb_xopen(filename, O_RDONLY);
1471
1472         return(ar_handle);
1473 }
1474
1475 static void init_archive_deb_control(archive_handle_t *ar_handle)
1476 {
1477         archive_handle_t *tar_handle;
1478
1479         /* Setup the tar archive handle */
1480         tar_handle = init_handle();
1481         tar_handle->src_fd = ar_handle->src_fd;
1482
1483         /* We don't care about data.tar.* or debian-binary, just control.tar.* */
1484 #ifdef CONFIG_FEATURE_DEB_TAR_GZ
1485         ar_handle->accept = llist_add_to(NULL, "control.tar.gz");
1486 #endif
1487 #ifdef CONFIG_FEATURE_DEB_TAR_BZ2
1488         ar_handle->accept = llist_add_to(ar_handle->accept, "control.tar.bz2");
1489 #endif
1490
1491         /* Assign the tar handle as a subarchive of the ar handle */
1492         ar_handle->sub_archive = tar_handle;
1493
1494         return;
1495 }
1496
1497 static void init_archive_deb_data(archive_handle_t *ar_handle)
1498 {
1499         archive_handle_t *tar_handle;
1500
1501         /* Setup the tar archive handle */
1502         tar_handle = init_handle();
1503         tar_handle->src_fd = ar_handle->src_fd;
1504
1505         /* We don't care about control.tar.* or debian-binary, just data.tar.* */
1506 #ifdef CONFIG_FEATURE_DEB_TAR_GZ
1507         ar_handle->accept = llist_add_to(NULL, "data.tar.gz");
1508 #endif
1509 #ifdef CONFIG_FEATURE_DEB_TAR_BZ2
1510         ar_handle->accept = llist_add_to(ar_handle->accept, "data.tar.bz2");
1511 #endif
1512
1513         /* Assign the tar handle as a subarchive of the ar handle */
1514         ar_handle->sub_archive = tar_handle;
1515
1516         return;
1517 }
1518
1519 static char *deb_extract_control_file_to_buffer(archive_handle_t *ar_handle, llist_t *myaccept)
1520 {
1521         ar_handle->sub_archive->action_data = data_extract_to_buffer;
1522         ar_handle->sub_archive->accept = myaccept;
1523         ar_handle->sub_archive->filter = filter_accept_list;
1524
1525         unpack_ar_archive(ar_handle);
1526         close(ar_handle->src_fd);
1527
1528         return(ar_handle->sub_archive->buffer);
1529 }
1530
1531 static void data_extract_all_prefix(archive_handle_t *archive_handle)
1532 {
1533         char *name_ptr = archive_handle->file_header->name;
1534
1535         name_ptr += strspn(name_ptr, "./");
1536         if (name_ptr[0] != '\0') {
1537                 archive_handle->file_header->name = xmalloc(strlen(archive_handle->buffer) + 2 + strlen(name_ptr));
1538                 strcpy(archive_handle->file_header->name, archive_handle->buffer);
1539                 strcat(archive_handle->file_header->name, name_ptr);
1540                 data_extract_all(archive_handle);
1541         }
1542         return;
1543 }
1544
1545 static void unpack_package(deb_file_t *deb_file)
1546 {
1547         const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
1548         const unsigned int status_num = search_status_hashtable(package_name);
1549         const unsigned int status_package_num = status_hashtable[status_num]->package;
1550         char *info_prefix;
1551         archive_handle_t *archive_handle;
1552         FILE *out_stream;
1553         llist_t *accept_list = NULL;
1554         int i = 0;
1555
1556         /* If existing version, remove it first */
1557         if (strcmp(name_hashtable[get_status(status_num, 3)], "installed") == 0) {
1558                 /* Package is already installed, remove old version first */
1559                 printf("Preparing to replace %s %s (using %s) ...\n", package_name,
1560                         name_hashtable[package_hashtable[status_package_num]->version],
1561                         deb_file->filename);
1562                 remove_package(status_package_num, 0);
1563         } else {
1564                 printf("Unpacking %s (from %s) ...\n", package_name, deb_file->filename);
1565         }
1566
1567         /* Extract control.tar.gz to /var/lib/dpkg/info/<package>.filename */
1568         info_prefix = (char *) xmalloc(strlen(package_name) + 20 + 4 + 2);
1569         sprintf(info_prefix, "/var/lib/dpkg/info/%s.", package_name);
1570         archive_handle = init_archive_deb_ar(deb_file->filename);
1571         init_archive_deb_control(archive_handle);
1572
1573         while(all_control_files[i]) {
1574                 char *c = (char *) xmalloc(3 + bb_strlen(all_control_files[i]));
1575                 sprintf(c, "./%s", all_control_files[i]);
1576                 accept_list= llist_add_to(accept_list, c);
1577                 i++;
1578         }
1579         archive_handle->sub_archive->accept = accept_list;
1580         archive_handle->sub_archive->filter = filter_accept_list;
1581         archive_handle->sub_archive->action_data = data_extract_all_prefix;
1582         archive_handle->sub_archive->buffer = info_prefix;
1583         archive_handle->sub_archive->flags |= ARCHIVE_EXTRACT_UNCONDITIONAL;
1584         unpack_ar_archive(archive_handle);
1585
1586         /* Run the preinst prior to extracting */
1587         if (run_package_script(package_name, "preinst") != 0) {
1588                 /* when preinst returns exit code != 0 then quit installation process */
1589                 bb_error_msg_and_die("subprocess pre-installation script returned error.");
1590         }
1591
1592         /* Extract data.tar.gz to the root directory */
1593         archive_handle = init_archive_deb_ar(deb_file->filename);
1594         init_archive_deb_data(archive_handle);
1595         archive_handle->sub_archive->action_data = data_extract_all_prefix;
1596         archive_handle->sub_archive->buffer = "/";
1597         archive_handle->sub_archive->flags |= ARCHIVE_EXTRACT_UNCONDITIONAL;
1598         unpack_ar_archive(archive_handle);
1599
1600         /* Create the list file */
1601         strcat(info_prefix, "list");
1602         out_stream = bb_xfopen(info_prefix, "w");
1603         while (archive_handle->sub_archive->passed) {
1604                 /* the leading . has been stripped by data_extract_all_prefix already */
1605                 fputs(archive_handle->sub_archive->passed->data, out_stream);
1606                 fputc('\n', out_stream);
1607                 archive_handle->sub_archive->passed = archive_handle->sub_archive->passed->link;
1608         }
1609         fclose(out_stream);
1610
1611         /* change status */
1612         set_status(status_num, "install", 1);
1613         set_status(status_num, "unpacked", 3);
1614
1615         free(info_prefix);
1616 }
1617
1618 static void configure_package(deb_file_t *deb_file)
1619 {
1620         const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
1621         const char *package_version = name_hashtable[package_hashtable[deb_file->package]->version];
1622         const int status_num = search_status_hashtable(package_name);
1623
1624         printf("Setting up %s (%s) ...\n", package_name, package_version);
1625
1626         /* Run the postinst script */
1627         if (run_package_script(package_name, "postinst") != 0) {
1628                 /* TODO: handle failure gracefully */
1629                 bb_error_msg_and_die("postrm failure.. set status to what?");
1630         }
1631         /* Change status to reflect success */
1632         set_status(status_num, "install", 1);
1633         set_status(status_num, "installed", 3);
1634 }
1635
1636 int dpkg_main(int argc, char **argv)
1637 {
1638         deb_file_t **deb_file = NULL;
1639         status_node_t *status_node;
1640         int opt;
1641         int package_num;
1642         int dpkg_opt = 0;
1643         int deb_count = 0;
1644         int state_status;
1645         int status_num;
1646         int i;
1647
1648         while ((opt = getopt(argc, argv, "CF:ilPru")) != -1) {
1649                 switch (opt) {
1650                         case 'C': // equivalent to --configure in official dpkg
1651                                 dpkg_opt |= dpkg_opt_configure;
1652                                 dpkg_opt |= dpkg_opt_package_name;
1653                                 break;
1654                         case 'F': // equivalent to --force in official dpkg
1655                                 if (strcmp(optarg, "depends") == 0) {
1656                                         dpkg_opt |= dpkg_opt_force_ignore_depends;
1657                                 }
1658                                 break;
1659                         case 'i':
1660                                 dpkg_opt |= dpkg_opt_install;
1661                                 dpkg_opt |= dpkg_opt_filename;
1662                                 break;
1663                         case 'l':
1664                                 dpkg_opt |= dpkg_opt_list_installed;
1665                                 break;
1666                         case 'P':
1667                                 dpkg_opt |= dpkg_opt_purge;
1668                                 dpkg_opt |= dpkg_opt_package_name;
1669                                 break;
1670                         case 'r':
1671                                 dpkg_opt |= dpkg_opt_remove;
1672                                 dpkg_opt |= dpkg_opt_package_name;
1673                                 break;
1674                         case 'u':       /* Equivalent to --unpack in official dpkg */
1675                                 dpkg_opt |= dpkg_opt_unpack;
1676                                 dpkg_opt |= dpkg_opt_filename;
1677                                 break;
1678                         default:
1679                                 bb_show_usage();
1680                 }
1681         }
1682         /* check for non-otion argument if expected  */
1683         if ((dpkg_opt == 0) || ((argc == optind) && !(dpkg_opt && dpkg_opt_list_installed))) {
1684                 bb_show_usage();
1685         }
1686
1687 /*      puts("(Reading database ... xxxxx files and directories installed.)"); */
1688         index_status_file("/var/lib/dpkg/status");
1689
1690         /* if the list action was given print the installed packages and exit */
1691         if (dpkg_opt & dpkg_opt_list_installed) {
1692                 list_packages();
1693                 return(EXIT_SUCCESS);
1694         }
1695
1696         /* Read arguments and store relevant info in structs */
1697         while (optind < argc) {
1698                 /* deb_count = nb_elem - 1 and we need nb_elem + 1 to allocate terminal node [NULL pointer] */
1699                 deb_file = xrealloc(deb_file, sizeof(deb_file_t *) * (deb_count + 2));
1700                 deb_file[deb_count] = (deb_file_t *) xmalloc(sizeof(deb_file_t));
1701                 if (dpkg_opt & dpkg_opt_filename) {
1702                         archive_handle_t *archive_handle;
1703                         llist_t *control_list = NULL;
1704
1705                         /* Extract the control file */
1706                         control_list = llist_add_to(NULL, "./control");
1707                         archive_handle = init_archive_deb_ar(argv[optind]);
1708                         init_archive_deb_control(archive_handle);
1709                         deb_file[deb_count]->control_file = deb_extract_control_file_to_buffer(archive_handle, control_list);
1710                         if (deb_file[deb_count]->control_file == NULL) {
1711                                 bb_error_msg_and_die("Couldnt extract control file");
1712                         }
1713                         deb_file[deb_count]->filename = bb_xstrdup(argv[optind]);
1714                         package_num = fill_package_struct(deb_file[deb_count]->control_file);
1715
1716                         if (package_num == -1) {
1717                                 bb_error_msg("Invalid control file in %s", argv[optind]);
1718                                 optind++;
1719                                 continue;
1720                         }
1721                         deb_file[deb_count]->package = (unsigned int) package_num;
1722
1723                         /* Add the package to the status hashtable */
1724                         if ((dpkg_opt & dpkg_opt_unpack) || (dpkg_opt & dpkg_opt_install)) {
1725                                 /* Try and find a currently installed version of this package */
1726                                 status_num = search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
1727                                 /* If no previous entry was found initialise a new entry */
1728                                 if ((status_hashtable[status_num] == NULL) ||
1729                                         (status_hashtable[status_num]->status == 0)) {
1730                                         status_node = (status_node_t *) xmalloc(sizeof(status_node_t));
1731                                         status_node->package = deb_file[deb_count]->package;
1732                                         /* reinstreq isnt changed to "ok" until the package control info
1733                                          * is written to the status file*/
1734                                         status_node->status = search_name_hashtable("install reinstreq not-installed");
1735                                         status_hashtable[status_num] = status_node;
1736                                 } else {
1737                                         set_status(status_num, "install", 1);
1738                                         set_status(status_num, "reinstreq", 2);
1739                                 }
1740                         }
1741                 }
1742                 else if (dpkg_opt & dpkg_opt_package_name) {
1743                         deb_file[deb_count]->filename = NULL;
1744                         deb_file[deb_count]->control_file = NULL;
1745                         deb_file[deb_count]->package = search_package_hashtable(
1746                                 search_name_hashtable(argv[optind]),
1747                                 search_name_hashtable("ANY"), VER_ANY);
1748                         if (package_hashtable[deb_file[deb_count]->package] == NULL) {
1749                                 bb_error_msg_and_die("Package %s is uninstalled or unknown\n", argv[optind]);
1750                         }
1751                         package_num = deb_file[deb_count]->package;
1752                         status_num = search_status_hashtable(name_hashtable[package_hashtable[package_num]->name]);
1753                         state_status = get_status(status_num, 3);
1754
1755                         /* check package status is "installed" */
1756                         if (dpkg_opt & dpkg_opt_remove) {
1757                                 if ((strcmp(name_hashtable[state_status], "not-installed") == 0) ||
1758                                         (strcmp(name_hashtable[state_status], "config-files") == 0)) {
1759                                         bb_error_msg_and_die("%s is already removed.", name_hashtable[package_hashtable[package_num]->name]);
1760                                 }
1761                                 set_status(status_num, "deinstall", 1);
1762                         }
1763                         else if (dpkg_opt & dpkg_opt_purge) {
1764                                 /* if package status is "conf-files" then its ok */
1765                                 if (strcmp(name_hashtable[state_status], "not-installed") == 0) {
1766                                         bb_error_msg_and_die("%s is already purged.", name_hashtable[package_hashtable[package_num]->name]);
1767                                 }
1768                                 set_status(status_num, "purge", 1);
1769                         }
1770                 }
1771                 deb_count++;
1772                 optind++;
1773         }
1774         deb_file[deb_count] = NULL;
1775
1776         /* Check that the deb file arguments are installable */
1777         if ((dpkg_opt & dpkg_opt_force_ignore_depends) != dpkg_opt_force_ignore_depends) {
1778                 if (!check_deps(deb_file, 0, deb_count)) {
1779                         bb_error_msg_and_die("Dependency check failed");
1780                 }
1781         }
1782
1783         /* TODO: install or remove packages in the correct dependency order */
1784         for (i = 0; i < deb_count; i++) {
1785                 /* Remove or purge packages */
1786                 if (dpkg_opt & dpkg_opt_remove) {
1787                         remove_package(deb_file[i]->package, 1);
1788                 }
1789                 else if (dpkg_opt & dpkg_opt_purge) {
1790                         purge_package(deb_file[i]->package);
1791                 }
1792                 else if (dpkg_opt & dpkg_opt_unpack) {
1793                         unpack_package(deb_file[i]);
1794                 }
1795                 else if (dpkg_opt & dpkg_opt_install) {
1796                         unpack_package(deb_file[i]);
1797                         /* package is configured in second pass below */
1798                 }
1799                 else if (dpkg_opt & dpkg_opt_configure) {
1800                         configure_package(deb_file[i]);
1801                 }
1802         }
1803         /* configure installed packages */
1804         if (dpkg_opt & dpkg_opt_install) {
1805                 for (i = 0; i < deb_count; i++)
1806                         configure_package(deb_file[i]);
1807         }
1808
1809         write_status_file(deb_file);
1810
1811         for (i = 0; i < deb_count; i++) {
1812                 free(deb_file[i]->control_file);
1813                 free(deb_file[i]->filename);
1814                 free(deb_file[i]);
1815         }
1816
1817         free(deb_file);
1818
1819         for (i = 0; i < NAME_HASH_PRIME; i++) {
1820                 free(name_hashtable[i]);
1821         }
1822
1823         for (i = 0; i < PACKAGE_HASH_PRIME; i++) {
1824                 if (package_hashtable[i] != NULL) {
1825                         free_package(package_hashtable[i]);
1826                 }
1827         }
1828
1829         for (i = 0; i < STATUS_HASH_PRIME; i++) {
1830                 free(status_hashtable[i]);
1831         }
1832
1833         return(EXIT_SUCCESS);
1834 }
1835