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