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