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