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