rpm: make -ql display more compatible; improve help text
[oweals/busybox.git] / archival / rpm.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini rpm applet for busybox
4  *
5  * Copyright (C) 2001,2002 by Laurence Anderson
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9
10 //usage:#define rpm_trivial_usage
11 //usage:       "-i PACKAGE.rpm; rpm -qp[ildc] PACKAGE.rpm"
12 //usage:#define rpm_full_usage "\n\n"
13 //usage:       "Manipulate RPM packages\n"
14 //usage:     "\nCommands:"
15 //usage:     "\n        -i      Install package"
16 //usage:     "\n        -qp     Query package"
17 //usage:     "\n        -qpi    Show information"
18 //usage:     "\n        -qpl    List contents"
19 //usage:     "\n        -qpd    List documents"
20 //usage:     "\n        -qpc    List config files"
21
22 #include "libbb.h"
23 #include "bb_archive.h"
24 #include "rpm.h"
25
26 #define RPM_CHAR_TYPE           1
27 #define RPM_INT8_TYPE           2
28 #define RPM_INT16_TYPE          3
29 #define RPM_INT32_TYPE          4
30 /* #define RPM_INT64_TYPE       5   ---- These aren't supported (yet) */
31 #define RPM_STRING_TYPE         6
32 #define RPM_BIN_TYPE            7
33 #define RPM_STRING_ARRAY_TYPE   8
34 #define RPM_I18NSTRING_TYPE     9
35
36 #define TAG_NAME                1000
37 #define TAG_VERSION             1001
38 #define TAG_RELEASE             1002
39 #define TAG_SUMMARY             1004
40 #define TAG_DESCRIPTION         1005
41 #define TAG_BUILDTIME           1006
42 #define TAG_BUILDHOST           1007
43 #define TAG_SIZE                1009
44 #define TAG_VENDOR              1011
45 #define TAG_LICENSE             1014
46 #define TAG_PACKAGER            1015
47 #define TAG_GROUP               1016
48 #define TAG_URL                 1020
49 #define TAG_PREIN               1023
50 #define TAG_POSTIN              1024
51 #define TAG_FILEFLAGS           1037
52 #define TAG_FILEUSERNAME        1039
53 #define TAG_FILEGROUPNAME       1040
54 #define TAG_SOURCERPM           1044
55 #define TAG_PREINPROG           1085
56 #define TAG_POSTINPROG          1086
57 #define TAG_PREFIXS             1098
58 #define TAG_DIRINDEXES          1116
59 #define TAG_BASENAMES           1117
60 #define TAG_DIRNAMES            1118
61
62 #define RPMFILE_CONFIG          (1 << 0)
63 #define RPMFILE_DOC             (1 << 1)
64
65 enum rpm_functions_e {
66         rpm_query = 1,
67         rpm_install = 2,
68         rpm_query_info = 4,
69         rpm_query_package = 8,
70         rpm_query_list = 16,
71         rpm_query_list_doc = 32,
72         rpm_query_list_config = 64
73 };
74
75 typedef struct {
76         uint32_t tag; /* 4 byte tag */
77         uint32_t type; /* 4 byte type */
78         uint32_t offset; /* 4 byte offset */
79         uint32_t count; /* 4 byte count */
80 } rpm_index;
81
82 static void *map;
83 static rpm_index **mytags;
84 static int tagcount;
85
86 static void extract_cpio(int fd, const char *source_rpm);
87 static rpm_index **rpm_gettags(int fd, int *num_tags);
88 static int bsearch_rpmtag(const void *key, const void *item);
89 static char *rpm_getstr(int tag, int itemindex);
90 static int rpm_getint(int tag, int itemindex);
91 static int rpm_getcount(int tag);
92 static void fileaction_dobackup(char *filename, int fileref);
93 static void fileaction_setowngrp(char *filename, int fileref);
94 static void loop_through_files(int filetag, void (*fileaction)(char *filename, int fileref));
95
96 int rpm_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
97 int rpm_main(int argc, char **argv)
98 {
99         int opt, func = 0;
100         const unsigned pagesize = getpagesize();
101
102         while ((opt = getopt(argc, argv, "iqpldc")) != -1) {
103                 switch (opt) {
104                 case 'i': /* First arg: Install mode, with q: Information */
105                         if (!func) func = rpm_install;
106                         else func |= rpm_query_info;
107                         break;
108                 case 'q': /* First arg: Query mode */
109                         if (func) bb_show_usage();
110                         func = rpm_query;
111                         break;
112                 case 'p': /* Query a package */
113                         func |= rpm_query_package;
114                         break;
115                 case 'l': /* List files in a package */
116                         func |= rpm_query_list;
117                         break;
118                 case 'd': /* List doc files in a package (implies list) */
119                         func |= rpm_query_list;
120                         func |= rpm_query_list_doc;
121                         break;
122                 case 'c': /* List config files in a package (implies list) */
123                         func |= rpm_query_list;
124                         func |= rpm_query_list_config;
125                         break;
126                 default:
127                         bb_show_usage();
128                 }
129         }
130         argv += optind;
131         //argc -= optind;
132         if (!argv[0]) {
133                 bb_show_usage();
134         }
135
136         while (*argv) {
137                 int rpm_fd;
138                 unsigned offset;
139                 const char *source_rpm;
140
141                 rpm_fd = xopen(*argv++, O_RDONLY);
142                 mytags = rpm_gettags(rpm_fd, &tagcount);
143                 if (!mytags)
144                         bb_error_msg_and_die("error reading rpm header");
145                 offset = xlseek(rpm_fd, 0, SEEK_CUR);
146                 /* Some NOMMU systems prefer MAP_PRIVATE over MAP_SHARED */
147                 map = mmap(0, (offset + pagesize) & (-(int)pagesize), PROT_READ, MAP_PRIVATE, rpm_fd, 0);
148
149                 source_rpm = rpm_getstr(TAG_SOURCERPM, 0);
150
151                 if (func & rpm_install) {
152                         /* Backup any config files */
153                         loop_through_files(TAG_BASENAMES, fileaction_dobackup);
154                         /* Extact the archive */
155                         extract_cpio(rpm_fd, source_rpm);
156                         /* Set the correct file uid/gid's */
157                         loop_through_files(TAG_BASENAMES, fileaction_setowngrp);
158                 }
159                 else if ((func & (rpm_query|rpm_query_package)) == (rpm_query|rpm_query_package)) {
160                         if (!(func & (rpm_query_info|rpm_query_list))) {
161                                 /* If just a straight query, just give package name */
162                                 printf("%s-%s-%s\n", rpm_getstr(TAG_NAME, 0), rpm_getstr(TAG_VERSION, 0), rpm_getstr(TAG_RELEASE, 0));
163                         }
164                         if (func & rpm_query_info) {
165                                 /* Do the nice printout */
166                                 time_t bdate_time;
167                                 struct tm *bdate_ptm;
168                                 char bdatestring[50];
169                                 const char *p;
170
171                                 printf("%-12s: %s\n", "Name"        , rpm_getstr(TAG_NAME, 0));
172                                 /* TODO compat: add "Epoch" here */
173                                 printf("%-12s: %s\n", "Version"     , rpm_getstr(TAG_VERSION, 0));
174                                 printf("%-12s: %s\n", "Release"     , rpm_getstr(TAG_RELEASE, 0));
175                                 /* add "Architecture" */
176                                 printf("%-12s: %s\n", "Install Date", "(not installed)");
177                                 printf("%-12s: %s\n", "Group"       , rpm_getstr(TAG_GROUP, 0));
178                                 printf("%-12s: %d\n", "Size"        , rpm_getint(TAG_SIZE, 0));
179                                 printf("%-12s: %s\n", "License"     , rpm_getstr(TAG_LICENSE, 0));
180                                 /* add "Signature" */
181                                 printf("%-12s: %s\n", "Source RPM"  , source_rpm ? source_rpm : "(none)");
182                                 bdate_time = rpm_getint(TAG_BUILDTIME, 0);
183                                 bdate_ptm = localtime(&bdate_time);
184                                 strftime(bdatestring, 50, "%a %d %b %Y %T %Z", bdate_ptm);
185                                 printf("%-12s: %s\n", "Build Date"  , bdatestring);
186                                 printf("%-12s: %s\n", "Build Host"  , rpm_getstr(TAG_BUILDHOST, 0));
187                                 p = rpm_getstr(TAG_PREFIXS, 0);
188                                 printf("%-12s: %s\n", "Relocations" , p ? p : "(not relocatable)");
189                                 /* add "Packager" */
190                                 p = rpm_getstr(TAG_VENDOR, 0);
191                                 printf("%-12s: %s\n", "Vendor"      , p ? p : "(none)");
192                                 printf("%-12s: %s\n", "URL"         , rpm_getstr(TAG_URL, 0));
193                                 printf("%-12s: %s\n", "Summary"     , rpm_getstr(TAG_SUMMARY, 0));
194                                 printf("Description :\n%s\n", rpm_getstr(TAG_DESCRIPTION, 0));
195                         }
196                         if (func & rpm_query_list) {
197                                 int count, it, flags;
198                                 count = rpm_getcount(TAG_BASENAMES);
199                                 for (it = 0; it < count; it++) {
200                                         flags = rpm_getint(TAG_FILEFLAGS, it);
201                                         switch (func & (rpm_query_list_doc|rpm_query_list_config)) {
202                                         case rpm_query_list_doc:
203                                                 if (!(flags & RPMFILE_DOC)) continue;
204                                                 break;
205                                         case rpm_query_list_config:
206                                                 if (!(flags & RPMFILE_CONFIG)) continue;
207                                                 break;
208                                         case rpm_query_list_doc|rpm_query_list_config:
209                                                 if (!(flags & (RPMFILE_CONFIG|RPMFILE_DOC))) continue;
210                                                 break;
211                                         }
212                                         printf("%s%s\n",
213                                                 rpm_getstr(TAG_DIRNAMES, rpm_getint(TAG_DIRINDEXES, it)),
214                                                 rpm_getstr(TAG_BASENAMES, it));
215                                 }
216                         }
217                 }
218                 free(mytags);
219                 close(rpm_fd);
220         }
221         return 0;
222 }
223
224 static void extract_cpio(int fd, const char *source_rpm)
225 {
226         archive_handle_t *archive_handle;
227
228         if (source_rpm != NULL) {
229                 /* Binary rpm (it was built from some SRPM), install to root */
230                 xchdir("/");
231         } /* else: SRPM, install to current dir */
232
233         /* Initialize */
234         archive_handle = init_handle();
235         archive_handle->seek = seek_by_read;
236         archive_handle->action_data = data_extract_all;
237 #if 0 /* For testing (rpm -i only lists the files in internal cpio): */
238         archive_handle->action_header = header_list;
239         archive_handle->action_data = data_skip;
240 #endif
241         archive_handle->ah_flags = ARCHIVE_RESTORE_DATE | ARCHIVE_CREATE_LEADING_DIRS
242                 /* compat: overwrite existing files.
243                  * try "rpm -i foo.src.rpm" few times in a row -
244                  * standard rpm will not complain.
245                  * (TODO? real rpm creates "file;1234" and then renames it) */
246                 | ARCHIVE_UNLINK_OLD;
247         archive_handle->src_fd = fd;
248         /*archive_handle->offset = 0; - init_handle() did it */
249
250         setup_unzip_on_fd(archive_handle->src_fd, /*fail_if_not_detected:*/ 1);
251         while (get_header_cpio(archive_handle) == EXIT_SUCCESS)
252                 continue;
253 }
254
255 static rpm_index **rpm_gettags(int fd, int *num_tags)
256 {
257         /* We should never need more than 200 (shrink via realloc later) */
258         rpm_index **tags = xzalloc(200 * sizeof(tags[0]));
259         int pass, tagindex = 0;
260
261         xlseek(fd, 96, SEEK_CUR); /* Seek past the unused lead */
262
263         /* 1st pass is the signature headers, 2nd is the main stuff */
264         for (pass = 0; pass < 2; pass++) {
265                 struct rpm_header header;
266                 rpm_index *tmpindex;
267                 int storepos;
268
269                 xread(fd, &header, sizeof(header));
270                 if (header.magic_and_ver != htonl(RPM_HEADER_MAGICnVER))
271                         return NULL; /* Invalid magic, or not version 1 */
272                 header.size = ntohl(header.size);
273                 header.entries = ntohl(header.entries);
274                 storepos = xlseek(fd, 0, SEEK_CUR) + header.entries * 16;
275
276                 while (header.entries--) {
277                         tmpindex = tags[tagindex++] = xmalloc(sizeof(*tmpindex));
278                         xread(fd, tmpindex, sizeof(*tmpindex));
279                         tmpindex->tag = ntohl(tmpindex->tag);
280                         tmpindex->type = ntohl(tmpindex->type);
281                         tmpindex->count = ntohl(tmpindex->count);
282                         tmpindex->offset = storepos + ntohl(tmpindex->offset);
283                         if (pass == 0)
284                                 tmpindex->tag -= 743;
285                 }
286                 storepos = xlseek(fd, header.size, SEEK_CUR); /* Seek past store */
287                 /* Skip padding to 8 byte boundary after reading signature headers */
288                 if (pass == 0)
289                         xlseek(fd, (-storepos) & 0x7, SEEK_CUR);
290         }
291         /* realloc tags to save space */
292         tags = xrealloc(tags, tagindex * sizeof(tags[0]));
293         *num_tags = tagindex;
294         /* All done, leave the file at the start of the gzipped cpio archive */
295         return tags;
296 }
297
298 static int bsearch_rpmtag(const void *key, const void *item)
299 {
300         int *tag = (int *)key;
301         rpm_index **tmp = (rpm_index **) item;
302         return (*tag - tmp[0]->tag);
303 }
304
305 static int rpm_getcount(int tag)
306 {
307         rpm_index **found;
308         found = bsearch(&tag, mytags, tagcount, sizeof(struct rpmtag *), bsearch_rpmtag);
309         if (!found)
310                 return 0;
311         return found[0]->count;
312 }
313
314 static char *rpm_getstr(int tag, int itemindex)
315 {
316         rpm_index **found;
317         found = bsearch(&tag, mytags, tagcount, sizeof(struct rpmtag *), bsearch_rpmtag);
318         if (!found || itemindex >= found[0]->count)
319                 return NULL;
320         if (found[0]->type == RPM_STRING_TYPE
321          || found[0]->type == RPM_I18NSTRING_TYPE
322          || found[0]->type == RPM_STRING_ARRAY_TYPE
323         ) {
324                 int n;
325                 char *tmpstr = (char *) map + found[0]->offset;
326                 for (n = 0; n < itemindex; n++)
327                         tmpstr = tmpstr + strlen(tmpstr) + 1;
328                 return tmpstr;
329         }
330         return NULL;
331 }
332
333 static int rpm_getint(int tag, int itemindex)
334 {
335         rpm_index **found;
336         char *tmpint;
337
338         /* gcc throws warnings here when sizeof(void*)!=sizeof(int) ...
339          * it's ok to ignore it because tag won't be used as a pointer */
340         found = bsearch(&tag, mytags, tagcount, sizeof(struct rpmtag *), bsearch_rpmtag);
341         if (!found || itemindex >= found[0]->count)
342                 return -1;
343
344         tmpint = (char *) map + found[0]->offset;
345         if (found[0]->type == RPM_INT32_TYPE) {
346                 tmpint += itemindex*4;
347                 return ntohl(*(int32_t*)tmpint);
348         }
349         if (found[0]->type == RPM_INT16_TYPE) {
350                 tmpint += itemindex*2;
351                 return ntohs(*(int16_t*)tmpint);
352         }
353         if (found[0]->type == RPM_INT8_TYPE) {
354                 tmpint += itemindex;
355                 return *(int8_t*)tmpint;
356         }
357         return -1;
358 }
359
360 static void fileaction_dobackup(char *filename, int fileref)
361 {
362         struct stat oldfile;
363         int stat_res;
364         char *newname;
365         if (rpm_getint(TAG_FILEFLAGS, fileref) & RPMFILE_CONFIG) {
366                 /* Only need to backup config files */
367                 stat_res = lstat(filename, &oldfile);
368                 if (stat_res == 0 && S_ISREG(oldfile.st_mode)) {
369                         /* File already exists  - really should check MD5's etc to see if different */
370                         newname = xasprintf("%s.rpmorig", filename);
371                         copy_file(filename, newname, FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS);
372                         remove_file(filename, FILEUTILS_RECUR | FILEUTILS_FORCE);
373                         free(newname);
374                 }
375         }
376 }
377
378 static void fileaction_setowngrp(char *filename, int fileref)
379 {
380         /* real rpm warns: "user foo does not exist - using <you>" */
381         struct passwd *pw = getpwnam(rpm_getstr(TAG_FILEUSERNAME, fileref));
382         int uid = pw ? pw->pw_uid : getuid(); /* or euid? */
383         struct group *gr = getgrnam(rpm_getstr(TAG_FILEGROUPNAME, fileref));
384         int gid = gr ? gr->gr_gid : getgid();
385         chown(filename, uid, gid);
386 }
387
388 static void loop_through_files(int filetag, void (*fileaction)(char *filename, int fileref))
389 {
390         int count = 0;
391         while (rpm_getstr(filetag, count)) {
392                 char* filename = xasprintf("%s%s",
393                         rpm_getstr(TAG_DIRNAMES, rpm_getint(TAG_DIRINDEXES, count)),
394                         rpm_getstr(TAG_BASENAMES, count));
395                 fileaction(filename, count++);
396                 free(filename);
397         }
398 }