More feedback to user
[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  *  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
165         make_hash(key, &probe_address, &probe_decrement, NAME_HASH_PRIME);
166         while(name_hashtable[probe_address] != NULL) {
167                 if (strcmp(name_hashtable[probe_address], key) == 0) {
168                         return(probe_address);
169                 } else {
170                         probe_address -= probe_decrement;
171                         if ((int)probe_address < 0) {
172                                 probe_address += NAME_HASH_PRIME;
173                         }
174                 }
175         }
176         name_hashtable[probe_address] = xstrdup(key);
177
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
216         if (version1 == NULL) {
217                 version1 = xstrdup("");
218         }
219         if (version2 != NULL) {
220                 version2 = xstrdup("");
221         }
222         upstream_len1 = strlen(version1);
223         upstream_len2 = strlen(version2);
224
225         while ((len1 < upstream_len1) || (len2 < upstream_len2)) {
226                 /* Compare non-digit section */
227                 tmp_int = strcspn(&version1[len1], "0123456789");
228                 name1_char = xstrndup(&version1[len1], tmp_int);
229                 len1 += tmp_int;
230                 tmp_int = strcspn(&version2[len2], "0123456789");
231                 name2_char = xstrndup(&version2[len2], tmp_int);
232                 len2 += tmp_int;
233                 tmp_int = strcmp(name1_char, name2_char);
234                 free(name1_char);
235                 free(name2_char);
236                 if (tmp_int != 0) {
237                         return(tmp_int);
238                 }
239
240                 /* Compare digits */
241                 tmp_int = strspn(&version1[len1], "0123456789");
242                 name1_char = xstrndup(&version1[len1], tmp_int);
243                 len1 += tmp_int;
244                 tmp_int = strspn(&version2[len2], "0123456789");
245                 name2_char = xstrndup(&version2[len2], tmp_int);
246                 len2 += tmp_int;
247                 ver_num1 = atoi(name1_char);
248                 ver_num2 = atoi(name2_char);
249                 free(name1_char);
250                 free(name2_char);
251                 if (ver_num1 < ver_num2) {
252                         return(-1);
253                 }
254                 else if (ver_num1 > ver_num2) {
255                         return(1);
256                 }
257         }
258         return(0);
259 }
260
261 /* if ver1 < ver2 return -1,
262  * if ver1 = ver2 return 0,
263  * if ver1 > ver2 return 1,
264  */
265 int version_compare(const unsigned int ver1, const unsigned int ver2)
266 {
267         char *ch_ver1 = name_hashtable[ver1];
268         char *ch_ver2 = name_hashtable[ver2];
269
270         char epoch1, epoch2;
271         char *deb_ver1, *deb_ver2;
272         char *ver1_ptr, *ver2_ptr;
273         char *upstream_ver1;
274         char *upstream_ver2;
275         int result;
276
277         /* Compare epoch */
278         if (ch_ver1[1] == ':') {
279                 epoch1 = ch_ver1[0];
280                 ver1_ptr = strchr(ch_ver1, ':') + 1;
281         } else {
282                 epoch1 = '0';
283                 ver1_ptr = ch_ver1;
284         }
285         if (ch_ver2[1] == ':') {
286                 epoch2 = ch_ver2[0];
287                 ver2_ptr = strchr(ch_ver2, ':') + 1;
288         } else {
289                 epoch2 = '0';
290                 ver2_ptr = ch_ver2;
291         }
292         if (epoch1 < epoch2) {
293                 return(-1);
294         }
295         else if (epoch1 > epoch2) {
296                 return(1);
297         }
298
299         /* Compare upstream version */
300         upstream_ver1 = xstrdup(ver1_ptr);
301         upstream_ver2 = xstrdup(ver2_ptr);
302
303         /* Chop off debian version, and store for later use */
304         deb_ver1 = strrchr(upstream_ver1, '-');
305         deb_ver2 = strrchr(upstream_ver2, '-');
306         if (deb_ver1) {
307                 deb_ver1[0] = '\0';
308                 deb_ver1++;
309         }
310         if (deb_ver2) {
311                 deb_ver2[0] = '\0';
312                 deb_ver2++;
313         }
314         result = version_compare_part(upstream_ver1, upstream_ver2);
315
316         free(upstream_ver1);
317         free(upstream_ver2);
318
319         if (result != 0) {
320                 return(result);
321         }
322
323         /* Compare debian versions */
324         return(version_compare_part(deb_ver1, deb_ver2));
325 }
326
327 int test_version(const unsigned int version1, const unsigned int version2, const unsigned int operator)
328 {
329         const int version_result = version_compare(version1, version2);
330         switch(operator) {
331                 case (VER_ANY):
332                         return(TRUE);
333                 case (VER_EQUAL):
334                         if (version_result == 0) {
335                                 return(TRUE);
336                         }
337                         break;
338                 case (VER_LESS):
339                         if (version_result < 0) {
340                                 return(TRUE);
341                         }
342                         break;
343                 case (VER_LESS_EQUAL):
344                         if (version_result <= 0) {
345                                 return(TRUE);
346                         }
347                         break;
348                 case (VER_MORE):
349                         if (version_result > 0) {
350                                 return(TRUE);
351                         }
352                         break;
353                 case (VER_MORE_EQUAL):
354                         if (version_result >= 0) {
355                                 return(TRUE);
356                         }
357                         break;
358         }
359         return(FALSE);
360 }
361
362
363 int search_package_hashtable(const unsigned int name, const unsigned int version, const unsigned int operator)
364 {
365         unsigned int probe_address = 0;
366         unsigned int probe_decrement = 0;
367
368         make_hash(name_hashtable[name], &probe_address, &probe_decrement, PACKAGE_HASH_PRIME);
369         while(package_hashtable[probe_address] != NULL) {
370                 if (package_hashtable[probe_address]->name == name) {
371                         if (operator == VER_ANY) {
372                                 return(probe_address);
373                         }
374                         if (test_version(package_hashtable[probe_address]->version, version, operator)) {
375                                 return(probe_address);
376                         }
377                 }
378                 probe_address -= probe_decrement;
379                 if ((int)probe_address < 0) {
380                         probe_address += PACKAGE_HASH_PRIME;
381                 }
382         }
383         return(probe_address);
384 }
385
386 /*
387  * Create one new node and one new edge for every dependency.
388  */
389 void add_split_dependencies(common_node_t *parent_node, const char *whole_line, unsigned int edge_type)
390 {
391         char *line = xstrdup(whole_line);
392         char *line2;
393         char *line_ptr1 = NULL;
394         char *line_ptr2 = NULL;
395         char *field;
396         char *field2;
397         char *version;
398         edge_t *edge;
399         int offset_ch;
400         int type;
401
402         field = strtok_r(line, ",", &line_ptr1);
403         do {
404                 line2 = xstrdup(field);
405                 field2 = strtok_r(line2, "|", &line_ptr2);
406                 if ((edge_type == EDGE_DEPENDS) && (strcmp(field, field2) != 0)) {
407                         type = EDGE_OR_DEPENDS;
408                 }
409                 else if ((edge_type == EDGE_PRE_DEPENDS) && (strcmp(field, field2) != 0)) {
410                         type = EDGE_OR_PRE_DEPENDS;
411                 } else {
412                         type = edge_type;
413                 }
414
415                 do {
416                         edge = (edge_t *) xmalloc(sizeof(edge_t));
417                         edge->type = type;
418
419                         /* Skip any extra leading spaces */
420                         field2 += strspn(field2, " ");
421
422                         /* Get dependency version info */
423                         version = strchr(field2, '(');
424                         if (version == NULL) {
425                                 edge->operator = VER_ANY;
426                                 /* Get the versions hash number, adding it if the number isnt already in there */
427                                 edge->version = search_name_hashtable("ANY");
428                         } else {
429                                 /* Skip leading ' ' or '(' */
430                                 version += strspn(field2, " ");
431                                 version += strspn(version, "(");
432                                 /* Calculate length of any operator charactors */
433                                 offset_ch = strspn(version, "<=>");
434                                 /* Determine operator */
435                                 if (offset_ch > 0) {
436                                         if (strncmp(version, "=", offset_ch) == 0) {
437                                                 edge->operator = VER_EQUAL;
438                                         }
439                                         else if (strncmp(version, "<<", offset_ch) == 0) {
440                                                 edge->operator = VER_LESS;
441                                         }
442                                         else if (strncmp(version, "<=", offset_ch) == 0) {
443                                                 edge->operator = VER_LESS_EQUAL;
444                                         }
445                                         else if (strncmp(version, ">>", offset_ch) == 0) {
446                                                 edge->operator = VER_MORE;
447                                         }
448                                         else if (strncmp(version, ">=", offset_ch) == 0) {
449                                                 edge->operator = VER_MORE_EQUAL;
450                                         } else {
451                                                 error_msg_and_die("Illegal operator\n");
452                                         }
453                                 }
454                                 /* skip to start of version numbers */
455                                 version += offset_ch;
456                                 version += strspn(version, " ");
457
458                                 /* Truncate version at trailing ' ' or ')' */
459                                 version[strcspn(version, " )")] = '\0';
460                                 /* Get the versions hash number, adding it if the number isnt already in there */
461                                 edge->version = search_name_hashtable(version);
462                         }
463
464                         /* Get the dependency name */
465                         field2[strcspn(field2, " (")] = '\0';
466                         edge->name = search_name_hashtable(field2);
467         
468                         /* link the new edge to the current node */
469                         parent_node->num_of_edges++;
470                         parent_node->edge = xrealloc(parent_node->edge, sizeof(edge_t) * (parent_node->num_of_edges + 1));
471                         parent_node->edge[parent_node->num_of_edges - 1] = edge;
472                 } while ((field2 = strtok_r(NULL, "|", &line_ptr2)) != NULL);
473                 free(line2);
474         } while ((field = strtok_r(NULL, ",", &line_ptr1)) != NULL);
475         free(line);
476
477         return;
478 }
479
480 void free_package(common_node_t *node)
481 {
482         int i;
483         if (node != NULL) {
484                 for (i = 0; i < node->num_of_edges; i++) {
485                         if (node->edge[i] != NULL) {
486                                 free(node->edge[i]);
487                         }
488                 }
489                 if (node->edge != NULL) {
490                         free(node->edge);
491                 }
492                 if (node != NULL) {
493                         free(node);
494                 }
495         }
496 }
497
498 unsigned int fill_package_struct(char *control_buffer)
499 {
500         common_node_t *new_node = (common_node_t *) xcalloc(1, sizeof(common_node_t));
501
502         char *field;
503         char *field_name;
504         char *field_value;
505         int field_start = 0;
506         int field_length;
507         int seperator_offset;
508         int num = -1;
509         int buffer_length = strlen(control_buffer);
510
511         new_node->version = search_name_hashtable("unknown");
512         while (field_start < buffer_length) {
513                 field = read_package_field(&control_buffer[field_start]);
514
515                 /* Setup start point for next field */
516                 field_length = strlen(field);
517                 field_start += (field_length + 1);
518
519                 seperator_offset = strcspn(field, ":");
520                 if (seperator_offset == 0) {
521                         free(field);
522                         continue;
523                 }
524                 field_name = xstrndup(field, seperator_offset);
525                 field_value = field + seperator_offset + 1;
526                 field_value += strspn(field_value, " \n\t");
527
528                 /* Should be able to replace this strlen with pointer arithmatic */
529                 if (strlen(field_value) == 0) {
530                         goto fill_package_struct_cleanup; // Oh no, the dreaded goto statement !!
531                 }
532
533                 if (strcmp(field_name, "Package") == 0) {
534                         new_node->name = search_name_hashtable(field_value);
535                 }
536                 else if (strcmp(field_name, "Version") == 0) {
537                         new_node->version = search_name_hashtable(field_value);
538                 }
539                 else if (strcmp(field_name, "Pre-Depends") == 0) {
540                         add_split_dependencies(new_node, field_value, EDGE_PRE_DEPENDS);
541                 }
542                 else if (strcmp(field_name, "Depends") == 0) {
543                         add_split_dependencies(new_node, field_value, EDGE_DEPENDS);
544                 }
545                 else if (strcmp(field_name, "Replaces") == 0) {
546                         add_split_dependencies(new_node, field_value, EDGE_REPLACES);
547                 }
548                 else if (strcmp(field_name, "Provides") == 0) {
549                         add_split_dependencies(new_node, field_value, EDGE_PROVIDES);
550                 }
551                 else if (strcmp(field_name, "Conflicts") == 0) {
552                         add_split_dependencies(new_node, field_value, EDGE_CONFLICTS);
553                 }
554                 else if (strcmp(field_name, "Suggests") == 0) {
555                         add_split_dependencies(new_node, field_value, EDGE_SUGGESTS);
556                 }
557                 else if (strcmp(field_name, "Recommends") == 0) {
558                         add_split_dependencies(new_node, field_value, EDGE_RECOMMENDS);
559                 }
560                 else if (strcmp(field_name, "Enhances") == 0) {
561                         add_split_dependencies(new_node, field_value, EDGE_ENHANCES);
562                 }
563 fill_package_struct_cleanup:
564                 free(field_name);
565                 free(field);
566         }
567         if (new_node->version == search_name_hashtable("unknown")) {
568                 free_package(new_node);
569                 return(-1);
570         }
571         num = search_package_hashtable(new_node->name, new_node->version, VER_EQUAL);
572         if (package_hashtable[num] == NULL) {
573                 package_hashtable[num] = new_node;
574         } else {
575                 free_package(new_node);
576         }
577         return(num);
578 }
579
580 /* if num = 1, it returns the want status, 2 returns flag, 3 returns status */
581 unsigned int get_status(const unsigned int status_node, const int num)
582 {
583         char *status_string = name_hashtable[status_hashtable[status_node]->status];
584         char *state_sub_string;
585         unsigned int state_sub_num;
586         int len;
587         int i;
588
589         /* set tmp_string to point to the start of the word number */
590         for (i = 1; i < num; i++) {
591                 /* skip past a word */
592                 status_string += strcspn(status_string, " ");
593                 /* skip past the seperating spaces */
594                 status_string += strspn(status_string, " ");
595         }
596         len = strcspn(status_string, " \n\0");
597         state_sub_string = xstrndup(status_string, len);
598         state_sub_num = search_name_hashtable(state_sub_string);
599         free(state_sub_string);
600         return(state_sub_num);
601 }
602
603 void set_status(const unsigned int status_node_num, const char *new_value, const int position)
604 {
605         const unsigned int new_value_len = strlen(new_value);
606         const unsigned int new_value_num = search_name_hashtable(new_value);
607         unsigned int want = get_status(status_node_num, 1);
608         unsigned int flag = get_status(status_node_num, 2);
609         unsigned int status = get_status(status_node_num, 3);
610         int want_len = strlen(name_hashtable[want]);
611         int flag_len = strlen(name_hashtable[flag]);
612         int status_len = strlen(name_hashtable[status]);
613         char *new_status;
614
615         switch (position) {
616                 case (1):
617                         want = new_value_num;
618                         want_len = new_value_len;
619                         break;
620                 case (2):
621                         flag = new_value_num;
622                         flag_len = new_value_len;
623                         break;
624                 case (3):
625                         status = new_value_num;
626                         status_len = new_value_len;
627                         break;
628                 default:
629                         error_msg_and_die("DEBUG ONLY: this shouldnt happen");
630         }
631
632         new_status = (char *) xmalloc(want_len + flag_len + status_len + 3);
633         sprintf(new_status, "%s %s %s", name_hashtable[want], name_hashtable[flag], name_hashtable[status]);
634         status_hashtable[status_node_num]->status = search_name_hashtable(new_status);
635         return;
636 }
637
638 void index_status_file(const char *filename)
639 {
640         FILE *status_file;
641         char *control_buffer;
642         char *status_line;
643         status_node_t *status_node = NULL;
644         unsigned int status_num;
645
646         status_file = xfopen(filename, "r");
647         while ((control_buffer = fgets_str(status_file, "\n\n")) != NULL) {
648                 const unsigned int package_num = fill_package_struct(control_buffer);
649                 if (package_num != -1) {
650                         status_node = xmalloc(sizeof(status_node_t));
651                         /* fill_package_struct doesnt handle the status field */
652                         status_line = strstr(control_buffer, "Status:");
653                         if (status_line != NULL) {
654                                 status_line += 7;
655                                 status_line += strspn(status_line, " \n\t");
656                                 status_line = xstrndup(status_line, strcspn(status_line, "\n\0"));
657                                 status_node->status = search_name_hashtable(status_line);
658                                 free(status_line);
659                         }
660                         status_node->package = package_num;
661                         status_num = search_status_hashtable(name_hashtable[package_hashtable[status_node->package]->name]);
662                         status_hashtable[status_num] = status_node;
663                 }
664                 free(control_buffer);
665         }
666         fclose(status_file);
667         return;
668 }
669
670
671 char *get_depends_field(common_node_t *package, const int depends_type)
672 {
673         char *depends = NULL;
674         char *old_sep = (char *)xcalloc(1, 3);
675         char *new_sep = (char *)xcalloc(1, 3);
676         int line_size = 0;
677         int depends_size;
678
679         int i;
680
681         for (i = 0; i < package->num_of_edges; i++) {
682                 if ((package->edge[i]->type == EDGE_OR_PRE_DEPENDS) ||
683                         (package->edge[i]->type == EDGE_OR_DEPENDS)) {
684                 }
685
686                 if ((package->edge[i]->type == depends_type) ||
687                         (package->edge[i]->type == depends_type + 1)) {
688                         /* Check if its the first time through */
689
690                         depends_size = 8 + strlen(name_hashtable[package->edge[i]->name])
691                                 + strlen(name_hashtable[package->edge[i]->version]);
692                         line_size += depends_size;
693                         depends = (char *) xrealloc(depends, line_size + 1);
694
695                         /* Check to see if this dependency is the type we are looking for
696                          * +1 to check for 'extra' types, e.g. ored dependecies */
697                         strcpy(old_sep, new_sep);
698                         if (package->edge[i]->type == depends_type) {
699                                 strcpy(new_sep, ", ");
700                         }
701                         else if (package->edge[i]->type == depends_type + 1) {
702                                 strcpy(new_sep, "| ");
703                         }
704
705                         if (depends_size == line_size) {
706                                 strcpy(depends, "");
707                         } else {
708                                 if ((strcmp(old_sep, "| ") == 0) && (strcmp(new_sep, "| ") == 0)) {
709                                         strcat(depends, " | ");
710                                 } else {
711                                         strcat(depends, ", ");
712                                 }
713                         }
714
715                         strcat(depends, name_hashtable[package->edge[i]->name]);
716                         if (strcmp(name_hashtable[package->edge[i]->version], "NULL") != 0) {
717                                 if (package->edge[i]->operator == VER_EQUAL) {
718                                         strcat(depends, " (= ");
719                                 }
720                                 else if (package->edge[i]->operator == VER_LESS) {
721                                         strcat(depends, " (<< ");
722                                 }
723                                 else if (package->edge[i]->operator == VER_LESS_EQUAL) {
724                                         strcat(depends, " (<= ");
725                                 }
726                                 else if (package->edge[i]->operator == VER_MORE) {
727                                         strcat(depends, " (>> ");
728                                 }
729                                 else if (package->edge[i]->operator == VER_MORE_EQUAL) {
730                                         strcat(depends, " (>= ");
731                                 } else {
732                                         strcat(depends, " (");
733                                 }
734                                 strcat(depends, name_hashtable[package->edge[i]->version]);
735                                 strcat(depends, ")");
736                         }
737                 }
738         }
739         return(depends);
740 }
741
742 /* This could do with a cleanup */
743 void write_status_file(deb_file_t **deb_file)
744 {
745         FILE *old_status_file = xfopen("/var/lib/dpkg/status", "r");
746         FILE *new_status_file = xfopen("/var/lib/dpkg/status.udeb", "w");
747         char *package_name;
748         char *status_from_file;
749         char *control_buffer = NULL;
750         char *tmp_string;
751         char *field;
752         int status_num;
753         int field_length;
754         int field_start = 0;
755         int buffer_length;
756         int write_flag;
757         int i = 0;
758
759         /* Update previously known packages */
760         while ((control_buffer = fgets_str(old_status_file, "\n\n")) != NULL) {
761                 tmp_string = strstr(control_buffer, "Package:") + 8;
762                 tmp_string += strspn(tmp_string, " \n\t");
763                 package_name = xstrndup(tmp_string, strcspn(tmp_string, "\n\0"));
764                 write_flag = FALSE;
765
766                 tmp_string = strstr(control_buffer, "Status:");
767                 if (tmp_string != NULL) {
768                         /* Seperate the status value from the control buffer */
769                         tmp_string += 7;
770                         tmp_string += strspn(tmp_string, " \n\t");
771                         status_from_file = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
772                 } else {
773                         status_from_file = NULL;
774                 }
775
776                 /* Find this package in the status hashtable */
777                 status_num = search_status_hashtable(package_name);
778                 if (status_hashtable[status_num] != NULL) {
779                         const char *status_from_hashtable = name_hashtable[status_hashtable[status_num]->status];
780                         if (strcmp(status_from_file, status_from_hashtable) != 0) {
781                                 /* New status isnt exactly the same as old status */
782                                 const int state_status = get_status(status_num, 3);
783                                 if ((strcmp("installed", name_hashtable[state_status]) == 0) ||
784                                         (strcmp("unpacked", name_hashtable[state_status]) == 0)) {
785                                         /* We need to add the control file from the package */
786                                         i = 0;
787                                         while(deb_file[i] != NULL) {
788                                                 if (strcmp(package_name, name_hashtable[package_hashtable[deb_file[i]->package]->name]) == 0) {
789                                                         char *last_char;
790                                                         /* Write a status file entry with a modified status */
791                                                         /* remove trailing \n's */
792                                                         while(1) {
793                                                                 last_char = last_char_is(deb_file[i]->control_file, '\n');
794                                                                 if (last_char) {
795                                                                         *last_char = '\0';
796                                                                 } else {
797                                                                         break;
798                                                                 }
799                                                         }
800                                                         fputs(deb_file[i]->control_file, new_status_file);
801                                                         set_status(status_num, "ok", 2);
802                                                         fprintf(new_status_file, "\nStatus: %s\n\n", name_hashtable[status_hashtable[status_num]->status]);
803                                                         write_flag = TRUE;
804                                                         break;
805                                                 }
806                                                 i++;
807                                         }
808                                         /* This is temperary, debugging only */
809                                         if (deb_file[i] == NULL) {
810                                                 error_msg_and_die("ALERT: Couldnt find a control file, your status file may be broken, status may be incorrect for %s", package_name);
811                                         }
812                                 }
813                                 else if (strcmp("not-installed", name_hashtable[state_status]) == 0) {
814                                         /* Only write the Package, Status, Priority and Section lines */
815                                         fprintf(new_status_file, "Package: %s\n", package_name);
816                                         fprintf(new_status_file, "Status: %s\n", status_from_hashtable);
817                                         buffer_length = strlen(control_buffer);
818                                         while (field_start < buffer_length) {
819                                                 field = read_package_field(&control_buffer[field_start]);
820                                                 field_length = strlen(field);
821                                                 field_start += (field_length + 1);
822                                                 if (strncmp(field, "Priority:", 9) == 0) {
823                                                         fprintf(new_status_file, "Priority:%s\n", field + 9);
824                                                 }
825                                                 if (strncmp(field, "Section:", 8) == 0) {
826                                                         fprintf(new_status_file, "Section:%s\n", field + 8);
827                                                 }
828                                         }
829                                         write_flag = TRUE;
830                                         fputs("\n", new_status_file);
831                                 }
832                                 else if (strcmp("config-files", name_hashtable[state_status]) == 0) {
833                                         /* only change the status line */
834                                         buffer_length = strlen(control_buffer);
835                                         while (field_start < buffer_length) {
836                                                 field = read_package_field(&control_buffer[field_start]);
837                                                 /* Setup start point for next field */
838                                                 field_length = strlen(field);
839                                                 field_start += (field_length + 1);
840                                                 if (strncmp(field, "Status:", 7) == 0) {
841                                                         fprintf(new_status_file, "Status: %s\n", status_from_hashtable);
842                                                 } else {
843                                                         fprintf(new_status_file, "%s\n", field);
844                                                 }
845                                                 free(field);
846                                         }
847                                         write_flag = TRUE;
848                                         fputs("\n", new_status_file);
849                                 }
850                         }
851                 }
852
853                 /* If the package from the status file wasnt handle above, do it now*/
854                 if (write_flag == FALSE) {
855                         fprintf(new_status_file, "%s\n\n", control_buffer);
856                 }
857
858                 if (status_from_file != NULL) {
859                         free(status_from_file);
860                 }
861                 free(package_name);
862                 free(control_buffer);
863         }
864
865         /* Write any new packages */
866         for(i = 0; deb_file[i] != NULL; i++) {
867                 status_num = search_status_hashtable(name_hashtable[package_hashtable[deb_file[i]->package]->name]);
868                 if (strcmp("reinstreq", name_hashtable[get_status(status_num, 2)]) == 0) {
869                         char *last_char;
870                         /* remove trailing \n's */
871                         while(1) {
872                                 last_char = last_char_is(deb_file[i]->control_file, '\n');
873                                 if (last_char) {
874                                         *last_char = '\0';
875                                 } else {
876                                         break;
877                                 }
878                         }
879                                 
880                         fputs(deb_file[i]->control_file, new_status_file);
881                         set_status(status_num, "ok", 2);
882                         fprintf(new_status_file, "\nStatus: %s\n\n", name_hashtable[status_hashtable[status_num]->status]);
883                 }
884         }
885         fclose(old_status_file);
886         fclose(new_status_file);
887
888
889         /* Create a seperate backfile to dpkg */
890         if (rename("/var/lib/dpkg/status", "/var/lib/dpkg/status.udeb.bak") == -1) {
891                 struct stat stat_buf;   
892                 if (stat("/var/lib/dpkg/status", &stat_buf) == 0) {
893                         error_msg_and_die("Couldnt create backup status file");
894                 }
895                 /* Its ok if renaming the status file fails becasue status 
896                  * file doesnt exist, maybe we are starting from scratch */
897                 error_msg("No status file found, creating new one");
898         }
899
900         if (rename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status") == -1) {
901                 error_msg_and_die("DANGER: Couldnt create status file, you need to manually repair your status file");
902         }
903 }
904
905 int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
906 {
907         int *conflicts = NULL;
908         int conflicts_num = 0;
909         int state_status;
910         int state_flag;
911         int state_want;
912         unsigned int status_package_num;
913         int i = deb_start;
914         int j, k;
915
916         /* Check for conflicts
917          * TODO: TEST if conflicts with other packages to be installed
918          *
919          * Add install packages and the packages they provide
920          * to the list of files to check conflicts for
921          */
922
923         /* Create array of package numbers to check against
924          * installed package for conflicts*/
925         while (deb_file[i] != NULL) {
926                 const unsigned int package_num = deb_file[i]->package;
927                 conflicts = xrealloc(conflicts, sizeof(int) * (conflicts_num + 1));
928                 conflicts[conflicts_num] = package_num;
929                 conflicts_num++;
930                 /* add provides to conflicts list */
931                 for (j = 0; j < package_hashtable[package_num]->num_of_edges; j++) {
932                         if (package_hashtable[package_num]->edge[j]->type == EDGE_PROVIDES) {
933                                 const int conflicts_package_num = search_package_hashtable(
934                                         package_hashtable[package_num]->edge[j]->name,
935                                         package_hashtable[package_num]->edge[j]->version,
936                                         package_hashtable[package_num]->edge[j]->operator);
937                                 if (package_hashtable[conflicts_package_num] == NULL) {
938                                         /* create a new package */
939                                         common_node_t *new_node = (common_node_t *) xmalloc(sizeof(common_node_t));
940                                         new_node->name = package_hashtable[package_num]->edge[j]->name;
941                                         new_node->version = package_hashtable[package_num]->edge[j]->version;
942                                         new_node->num_of_edges = 0;
943                                         new_node->edge = NULL;
944                                         package_hashtable[conflicts_package_num] = new_node;
945                                 }
946                                 conflicts = xrealloc(conflicts, sizeof(int) * (conflicts_num + 1));
947                                 conflicts[conflicts_num] = conflicts_package_num;
948                                 conflicts_num++;
949                         }
950                 }
951                 i++;
952         }
953
954         /* Check conflicts */
955         for (i = 0; i < conflicts_num; i++) {
956                 /* Check for conflicts */
957                 for (j = 0; j < STATUS_HASH_PRIME; j++) {
958                         if (status_hashtable[j] == NULL) {
959                                 continue;
960                         }
961                         state_flag = get_status(j, 2);
962                         state_status = get_status(j, 3);
963                         if ((state_status != search_name_hashtable("installed"))
964                                 && (state_flag != search_name_hashtable("want-install"))) {
965                                 continue;
966                         }
967                         status_package_num = status_hashtable[j]->package;
968                         for (k = 0; k < package_hashtable[status_package_num]->num_of_edges; k++) {
969                                 const edge_t *package_edge = package_hashtable[status_package_num]->edge[k];
970                                 if (package_edge->type != EDGE_CONFLICTS) {
971                                         continue;
972                                 }
973                                 if (package_edge->name != package_hashtable[conflicts[i]]->name) {
974                                         continue;
975                                 }
976                                 /* There is a conflict against the package name
977                                  * check if version conflict as well */
978                                 if (test_version(package_hashtable[deb_file[i]->package]->version,
979                                                 package_edge->version, package_edge->operator)) {
980                                         error_msg_and_die("Package %s conflict with %s",
981                                                 name_hashtable[package_hashtable[deb_file[i]->package]->name],
982                                                 name_hashtable[package_hashtable[status_package_num]->name]);
983                                 }
984                         }
985                 }
986         }
987
988         /* Check dependendcies */
989         i = 0;
990         while (deb_file[i] != NULL) {
991                 const common_node_t *package_node = package_hashtable[deb_file[i]->package];
992                 int status_num = 0;
993
994                 for (j = 0; j < package_hashtable[deb_file[i]->package]->num_of_edges; j++) {
995                         const edge_t *package_edge = package_node->edge[j];
996                         const unsigned int package_num = search_package_hashtable(package_edge->name,
997                                 package_edge->version, package_edge->operator);
998
999                         status_num = search_status_hashtable(name_hashtable[package_hashtable[package_num]->name]);
1000                         state_status = get_status(status_num, 3);
1001                         state_want = get_status(status_num, 1);
1002                         switch (package_edge->type) {
1003                                 case(EDGE_PRE_DEPENDS):
1004                                 case(EDGE_OR_PRE_DEPENDS):
1005                                         /* It must be already installed */
1006                                         /* NOTE: This is untested, nothing apropriate in my status file */
1007                                         if ((package_hashtable[package_num] == NULL) || (state_status != search_name_hashtable("installed"))) {
1008                                                 error_msg_and_die("Package %s pre-depends on %s, but it is not installed",
1009                                                         name_hashtable[package_node->name],
1010                                                         name_hashtable[package_edge->name]);
1011                                         }
1012                                         break;
1013                                 case(EDGE_DEPENDS):
1014                                 case(EDGE_OR_DEPENDS):
1015                                         /* It must be already installed, or to be installed */
1016                                         if ((package_hashtable[package_num] == NULL) ||
1017                                                 ((state_status != search_name_hashtable("installed")) &&
1018                                                 (state_want != search_name_hashtable("want_install")))) {
1019                                                 error_msg_and_die("Package %s depends on %s, but it is not installed, or flaged to be installed",
1020                                                         name_hashtable[package_node->name],
1021                                                         name_hashtable[package_edge->name]);
1022                                         }
1023                                         break;
1024                         }
1025                 }
1026                 i++;
1027         }
1028         return(TRUE);
1029 }
1030
1031 char **create_list(const char *filename)
1032 {
1033         FILE *list_stream;
1034         char **file_list = xmalloc(sizeof(char *));
1035         char *line = NULL;
1036         char *last_char;
1037         int length = 0;
1038         int count = 0;
1039
1040         list_stream = xfopen(filename, "r");
1041         if (list_stream == NULL) {
1042                 return(NULL);
1043         }
1044         while (getline(&line, &length, list_stream) != -1) {
1045                 file_list = xrealloc(file_list, sizeof(char *) * (length + 1));
1046                 last_char = last_char_is(line, '\n');
1047                 if (last_char) {
1048                         *last_char = '\0';
1049                 }
1050                 file_list[count] = xstrdup(line);
1051                 free(line);
1052                 count++;
1053                 length = 0;
1054         }
1055         fclose(list_stream);
1056         if (count == 0) {
1057                 return(NULL);
1058         } else {
1059                 file_list[count] = NULL;
1060                 return(file_list);
1061         }
1062 }
1063
1064 /* maybe i should try and hook this into remove_file.c somehow */
1065 int remove_file_array(char **remove_names, char **exclude_names)
1066 {
1067         struct stat path_stat;
1068         int match_flag;
1069         int remove_flag = FALSE;
1070         int i,j;
1071
1072         if (remove_names == NULL) {
1073                 return(FALSE);
1074         }
1075         for (i = 0; remove_names[i] != NULL; i++) {
1076                 match_flag = FALSE;
1077                 if (exclude_names != NULL) {
1078                         for (j = 0; exclude_names[j] != 0; j++) {
1079                                 if (strcmp(remove_names[i], exclude_names[j]) == 0) {
1080                                         match_flag = TRUE;
1081                                         break;
1082                                 }
1083                         }
1084                 }
1085                 if (!match_flag) {
1086                         if (lstat(remove_names[i], &path_stat) < 0) {
1087                                 continue;
1088                         }
1089                         if (S_ISDIR(path_stat.st_mode)) {
1090                                 if (rmdir(remove_names[i]) != -1) {
1091                                         remove_flag = TRUE;
1092                                 }
1093                         } else {
1094                                 if (unlink(remove_names[i]) != -1) {
1095                                         remove_flag = TRUE;
1096                                 }
1097                         }
1098                 }
1099         }
1100         return(remove_flag);
1101 }
1102
1103 int run_package_script(const char *package_name, const char *script_type)
1104 {
1105         struct stat path_stat;
1106         char *script_path;
1107
1108         script_path = xmalloc(strlen(package_name) + strlen(script_type) + 21);
1109         sprintf(script_path, "/var/lib/dpkg/info/%s.%s", package_name, script_type);
1110
1111         /* If the file doesnt exist is isnt a fatal */
1112         if (lstat(script_path, &path_stat) < 0) {
1113                 return(EXIT_SUCCESS);
1114         } else {
1115                 return(system(script_path));
1116         }
1117 }
1118
1119 void all_control_list(char **remove_files, const char *package_name)
1120 {
1121         const char *all_extensions[11] = {"preinst", "postinst", "prerm", "postrm",
1122                 "list", "md5sums", "shlibs", "conffiles", "config", "templates", NULL };
1123         int i;
1124
1125         /* Create a list of all /var/lib/dpkg/info/<package> files */
1126         for(i = 0; i < 10; i++) {
1127                 remove_files[i] = xmalloc(strlen(package_name) + strlen(all_extensions[i]) + 21);
1128                 sprintf(remove_files[i], "/var/lib/dpkg/info/%s.%s", package_name, all_extensions[i]);
1129         }
1130         remove_files[10] = NULL;
1131 }
1132
1133 void remove_package(const unsigned int package_num)
1134 {
1135         const char *package_name = name_hashtable[package_hashtable[package_num]->name];
1136         const unsigned int status_num = search_status_hashtable(package_name);
1137         const int package_name_length = strlen(package_name);
1138         char **remove_files;
1139         char **exclude_files;
1140         char list_name[package_name_length + 25];
1141         char conffile_name[package_name_length + 30];
1142         int return_value;
1143
1144         printf("Removing %s ...\n", package_name);
1145
1146         /* run prerm script */
1147         return_value = run_package_script(package_name, "prem");
1148         if (return_value == -1) {
1149                 error_msg_and_die("script failed, prerm failure");
1150         }
1151
1152         /* Create a list of files to remove, and a seperate list of those to keep */
1153         sprintf(list_name, "/var/lib/dpkg/info/%s.list", package_name);
1154         remove_files = create_list(list_name);
1155
1156         sprintf(conffile_name, "/var/lib/dpkg/info/%s.conffiles", package_name);
1157         exclude_files = create_list(conffile_name);
1158
1159         /* Some directories cant be removed straight away, so do multiple passes */
1160         while (remove_file_array(remove_files, exclude_files) == TRUE);
1161
1162         /* Create a list of all /var/lib/dpkg/info/<package> files */
1163         remove_files = xmalloc(11);
1164         all_control_list(remove_files, package_name);
1165
1166         /* Create a list of files in /var/lib/dpkg/info/<package>.* to keep  */
1167         exclude_files = xmalloc(sizeof(char*) * 3);
1168         exclude_files[0] = xstrdup(conffile_name);
1169         exclude_files[1] = xmalloc(package_name_length + 27);
1170         sprintf(exclude_files[1], "/var/lib/dpkg/info/%s.postrm", package_name);
1171         exclude_files[2] = NULL;
1172
1173         remove_file_array(remove_files, exclude_files);
1174
1175         /* rename <package>.conffile to <package>.list */
1176         rename(conffile_name, list_name);
1177
1178         /* Change package status */
1179         set_status(status_num, "deinstall", 1);
1180         set_status(status_num, "config-files", 3);
1181 }
1182
1183 void purge_package(const unsigned int package_num)
1184 {
1185         const char *package_name = name_hashtable[package_hashtable[package_num]->name];
1186         const unsigned int status_num = search_status_hashtable(package_name);
1187         char **remove_files;
1188         char **exclude_files;
1189         char list_name[strlen(package_name) + 25];
1190
1191         /* run prerm script */
1192         if (run_package_script(package_name, "prerm") == -1) {
1193                 error_msg_and_die("script failed, prerm failure");
1194         }
1195
1196         /* Create a list of files to remove */
1197         sprintf(list_name, "/var/lib/dpkg/info/%s.list", package_name);
1198         remove_files = create_list(list_name);
1199
1200         exclude_files = xmalloc(1);
1201         exclude_files[0] = NULL;
1202
1203         /* Some directories cant be removed straight away, so do multiple passes */
1204         while (remove_file_array(remove_files, exclude_files) == TRUE);
1205
1206         /* Create a list of all /var/lib/dpkg/info/<package> files */
1207         remove_files = xmalloc(11);
1208         all_control_list(remove_files, package_name);
1209         remove_file_array(remove_files, exclude_files);
1210
1211         /* run postrm script */
1212         if (run_package_script(package_name, "postrm") == -1) {
1213                 error_msg_and_die("postrm fialure.. set status to what?");
1214         }
1215         /* Change package status */
1216         set_status(status_num, "purge", 1);
1217         set_status(status_num, "not-installed", 3);
1218 }
1219
1220 void unpack_package(deb_file_t *deb_file)
1221 {
1222 //      const unsigned int package_name_num = package_hashtable[deb_file->package]->name;
1223         const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
1224         const unsigned int status_num = search_status_hashtable(package_name);
1225         const unsigned int status_package_num = status_hashtable[status_num]->status;
1226
1227         FILE *out_stream;
1228         char *info_prefix;
1229
1230         /* If existing version, remove it first */
1231         if (strcmp(name_hashtable[get_status(status_num, 3)], "installed") == 0) {
1232                 /* Package is already installed, remove old version first */
1233                 printf("Preparing to replace %s %s (using %s) ...\n", package_name,
1234                         name_hashtable[package_hashtable[status_package_num]->version],
1235                         deb_file->filename);
1236                 remove_package(status_package_num);
1237         } else {
1238                 printf("Unpacking %s (from %s) ...\n", package_name, deb_file->filename);
1239         }
1240
1241         /* Extract control.tar.gz to /var/lib/dpkg/info/<package>.filename */
1242         info_prefix = (char *) xmalloc(sizeof(package_name) + 20 + 4 + 1);
1243         sprintf(info_prefix, "/var/lib/dpkg/info/%s.", package_name);
1244         deb_extract(deb_file->filename, stdout, (extract_quiet | extract_control_tar_gz | extract_all_to_fs), info_prefix, NULL);
1245
1246         /* Extract data.tar.gz to the root directory */
1247         deb_extract(deb_file->filename, stdout, (extract_quiet | extract_data_tar_gz | extract_all_to_fs), "/", NULL);
1248
1249         /* Create the list file */
1250         strcat(info_prefix, "list");
1251
1252         out_stream = xfopen(info_prefix, "w");                  
1253         deb_extract(deb_file->filename, out_stream, (extract_quiet | extract_data_tar_gz | extract_list), NULL, NULL);
1254         fclose(out_stream);
1255
1256         /* change status */
1257         set_status(status_num, "install", 1);
1258         set_status(status_num, "unpacked", 3);
1259 }
1260
1261 void configure_package(deb_file_t *deb_file)
1262 {
1263         const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
1264         const char *package_version = name_hashtable[package_hashtable[deb_file->package]->version];
1265         const int status_num = search_status_hashtable(package_name);
1266         int return_value;
1267
1268         printf("Setting up %s (%s)\n", package_name, package_version);
1269
1270         /* Run the preinst prior to extracting */
1271         return_value = run_package_script(package_name, "postinst");
1272         if (return_value == -1) {
1273                 /* TODO: handle failure gracefully */
1274                 error_msg_and_die("postrm failure.. set status to what?");
1275         }
1276         /* Change status to reflect success */
1277         set_status(status_num, "install", 1);
1278         set_status(status_num, "installed", 3);
1279 }
1280
1281 extern int dpkg_main(int argc, char **argv)
1282 {
1283         deb_file_t **deb_file = NULL;
1284         status_node_t *status_node;
1285         char opt = 0;
1286         int package_num;
1287         int dpkg_opt = 0;
1288         int deb_count = 0;
1289         int state_status;
1290         int status_num;
1291         int i;
1292
1293         while ((opt = getopt(argc, argv, "cF:ilPru")) != -1) {
1294                 switch (opt) {
1295                         case 'c':
1296                                 dpkg_opt |= dpkg_opt_configure;
1297                                 dpkg_opt |= dpkg_opt_package_name;
1298                                 break;
1299                         case 'F': // equivalent to --force in official dpkg
1300                                 if (strcmp(optarg, "depends") == 0) {
1301                                         dpkg_opt |= dpkg_opt_force_ignore_depends;
1302                                 }                               
1303                         case 'i':
1304                                 dpkg_opt |= dpkg_opt_install;
1305                                 dpkg_opt |= dpkg_opt_filename;
1306                                 break;
1307                         case 'l':
1308                                 dpkg_opt |= dpkg_opt_list_installed;
1309                         case 'P':
1310                                 dpkg_opt |= dpkg_opt_purge;
1311                                 dpkg_opt |= dpkg_opt_package_name;
1312                                 break;
1313                         case 'r':
1314                                 dpkg_opt |= dpkg_opt_remove;
1315                                 dpkg_opt |= dpkg_opt_package_name;
1316                                 break;
1317                         case 'u':       /* Equivalent to --unpack in official dpkg */
1318                                 dpkg_opt |= dpkg_opt_unpack;
1319                                 dpkg_opt |= dpkg_opt_filename;
1320                                 break;
1321                         default:
1322                                 show_usage();
1323                 }
1324         }
1325
1326         if ((argc == optind) || (dpkg_opt == 0)) {
1327                 show_usage();
1328         } 
1329
1330         puts("(Reading database ... xxxxx files and directories installed.)");
1331         index_status_file("/var/lib/dpkg/status");
1332
1333         /* Read arguments and store relevant info in structs */
1334         deb_file = xmalloc(sizeof(deb_file_t));
1335         while (optind < argc) {
1336                 deb_file[deb_count] = (deb_file_t *) xmalloc(sizeof(deb_file_t));
1337                 if (dpkg_opt & dpkg_opt_filename) {
1338                         deb_file[deb_count]->filename = xstrdup(argv[optind]);
1339                         deb_file[deb_count]->control_file = deb_extract(argv[optind], stdout, (extract_control_tar_gz | extract_one_to_buffer), NULL, "./control");
1340                         if (deb_file[deb_count]->control_file == NULL) {
1341                                 error_msg_and_die("Couldnt extract control file");
1342                         }
1343                         package_num = fill_package_struct(deb_file[deb_count]->control_file);
1344
1345                         if (package_num == -1) {
1346                                 error_msg("Invalid control file in %s", argv[optind]);
1347                                 continue;
1348                         }
1349                         deb_file[deb_count]->package = (unsigned int) package_num;
1350                         /* Add the package to the status hashtable */
1351                         if ((dpkg_opt & dpkg_opt_unpack) || (dpkg_opt & dpkg_opt_install)) {
1352                                 status_node = (status_node_t *) xmalloc(sizeof(status_node_t));
1353                                 status_node->package = deb_file[deb_count]->package;
1354                                 /* use reinstreq isnt changed to "ok" until the package control info
1355                                  * is written to the status file*/
1356                                 status_node->status = search_name_hashtable("install reinstreq not-installed");
1357
1358                                 status_num = search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
1359                                 status_hashtable[status_num] = status_node;
1360                         }
1361                 }
1362                 else if (dpkg_opt & dpkg_opt_package_name) {
1363                         deb_file[deb_count]->filename = NULL;
1364                         deb_file[deb_count]->control_file = NULL;
1365                         deb_file[deb_count]->package = search_package_hashtable(
1366                                 search_name_hashtable(argv[optind]),
1367                                 search_name_hashtable("ANY"), VER_ANY);
1368                         if (package_hashtable[deb_file[deb_count]->package] == NULL) {
1369                                 error_msg_and_die("Package %s is uninstalled or unknown\n", argv[optind]);
1370                         }
1371                         state_status = get_status(search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]), 3);
1372
1373                         /* check package status is "installed" */
1374                         if (dpkg_opt & dpkg_opt_remove) {
1375                                 if ((strcmp(name_hashtable[state_status], "not-installed") == 0) ||
1376                                         (strcmp(name_hashtable[state_status], "config-files") == 0)) {
1377                                         error_msg_and_die("%s is already removed.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
1378                                 }
1379                         }
1380                         else if (dpkg_opt & dpkg_opt_purge) {
1381                                 /* if package status is "conf-files" then its ok */
1382                                 if (strcmp(name_hashtable[state_status], "not-installed") == 0) {
1383                                         error_msg_and_die("%s is already purged.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
1384                                 }
1385                         }
1386                 }
1387                 deb_count++;
1388                 optind++;
1389         }
1390         deb_file[deb_count] = NULL;
1391
1392         /* Check that the deb file arguments are installable */
1393         /* TODO: check dependencies before removing */
1394         if ((dpkg_opt & dpkg_opt_force_ignore_depends) != dpkg_opt_force_ignore_depends) {
1395                 if (!check_deps(deb_file, 0, deb_count)) {
1396                         error_msg_and_die("Dependency check fialed");
1397                 }
1398         }
1399
1400         for (i = 0; i < deb_count; i++) {
1401                 /* Remove or purge packages */
1402                 if (dpkg_opt & dpkg_opt_remove) {
1403                         remove_package(deb_file[i]->package);
1404                 }
1405                 else if (dpkg_opt & dpkg_opt_purge) {
1406                         purge_package(deb_file[i]->package);
1407                 }
1408                 else if (dpkg_opt & dpkg_opt_unpack) {
1409                         unpack_package(deb_file[i]);
1410                 }
1411                 else if (dpkg_opt & dpkg_opt_install) {
1412                         unpack_package(deb_file[i]);
1413                         configure_package(deb_file[i]);
1414                 }
1415                 else if (dpkg_opt & dpkg_opt_configure) {
1416                         configure_package(deb_file[i]);
1417                 }
1418         }
1419         write_status_file(deb_file);
1420
1421         for (i = 0; i < NAME_HASH_PRIME; i++) {
1422                 if (name_hashtable[i] != NULL) {
1423                         free(name_hashtable[i]);
1424                 }
1425         }
1426
1427         for (i = 0; i < PACKAGE_HASH_PRIME; i++) {
1428                 free_package(package_hashtable[i]);
1429         }
1430
1431         for (i = 0; i < STATUS_HASH_PRIME; i++) {
1432                 if (status_hashtable[i] != NULL) {
1433                         free(status_hashtable[i]);
1434                 }
1435         }
1436
1437         return(EXIT_FAILURE);
1438 }
1439