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