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