- make unknown elements less fatal
[platform/upstream/libsolv.git] / tools / repo_products.c
1 /*
2  * repo_products.c
3  *
4  * Parses all files below 'proddir'
5  * See http://en.opensuse.org/Product_Management/Code11
6  *
7  *
8  * Copyright (c) 2008, Novell Inc.
9  *
10  * This program is licensed under the BSD license, read LICENSE.BSD
11  * for further information
12  */
13
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <unistd.h>
17 #include <limits.h>
18 #include <fcntl.h>
19 #include <ctype.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <assert.h>
24 #include <dirent.h>
25 #include <expat.h>
26
27 #include "pool.h"
28 #include "repo.h"
29 #include "util.h"
30 #define DISABLE_SPLIT
31 #include "tools_util.h"
32 #include "repo_content.h"
33 #include "repo_zyppdb.h"
34
35
36 //#define DUMPOUT 0
37
38 enum state {
39   STATE_START,           // 0
40   STATE_PRODUCT,         // 1
41   STATE_VENDOR,          // 2
42   STATE_NAME,            // 3
43   STATE_VERSION,         // 4
44   STATE_RELEASE,         // 5
45   STATE_ARCH,            // 6
46   STATE_SUMMARY,         // 7
47   STATE_DESCRIPTION,     // 8
48   STATE_UPDATEREPOKEY,   // 9 should go away
49   STATE_CPEID,         // 9
50   STATE_URLS,            // 10
51   STATE_URL,             // 11
52   STATE_RUNTIMECONFIG,   // 12
53   STATE_LINGUAS,         // 13
54   STATE_LANG,            // 14
55   STATE_REGISTER,        // 15
56   STATE_TARGET,          // 16
57   STATE_REGRELEASE,      // 18
58   STATE_PRODUCTLINE,     // 19
59   NUMSTATES              // 0
60 };
61
62 struct stateswitch {
63   enum state from;
64   char *ename;
65   enum state to;
66   int docontent;
67 };
68
69 /* !! must be sorted by first column !! */
70 static struct stateswitch stateswitches[] = {
71   { STATE_START,     "product",       STATE_PRODUCT,       0 },
72   { STATE_PRODUCT,   "vendor",        STATE_VENDOR,        1 },
73   { STATE_PRODUCT,   "name",          STATE_NAME,          1 },
74   { STATE_PRODUCT,   "version",       STATE_VERSION,       1 },
75   { STATE_PRODUCT,   "release",       STATE_RELEASE,       1 },
76   { STATE_PRODUCT,   "arch",          STATE_ARCH,          1 },
77   { STATE_PRODUCT,   "productline",   STATE_PRODUCTLINE,   1 },
78   { STATE_PRODUCT,   "summary",       STATE_SUMMARY,       1 },
79   { STATE_PRODUCT,   "description",   STATE_DESCRIPTION,   1 },
80   { STATE_PRODUCT,   "register",      STATE_REGISTER,      0 },
81   { STATE_PRODUCT,   "urls",          STATE_URLS,          0 },
82   { STATE_PRODUCT,   "runtimeconfig", STATE_RUNTIMECONFIG, 0 },
83   { STATE_PRODUCT,   "linguas",       STATE_LINGUAS,       0 },
84   { STATE_PRODUCT,   "updaterepokey", STATE_UPDATEREPOKEY, 1 },
85   { STATE_PRODUCT,   "cpename",       STATE_CPEID,         1 },
86   { STATE_URLS,      "url",           STATE_URL,           1 },
87   { STATE_LINGUAS,   "lang",          STATE_LANG,          0 },
88   { STATE_REGISTER,  "target",        STATE_TARGET,        1 },
89   { STATE_REGISTER,  "release",       STATE_REGRELEASE,    1 },
90   { NUMSTATES }
91 };
92
93 struct parsedata {
94   const char *filename;
95   const char *basename;
96   int depth;
97   enum state state;
98   int statedepth;
99   char *content;
100   int lcontent;
101   int acontent;
102   int docontent;
103   Pool *pool;
104   Repo *repo;
105   Repodata *data;
106
107   struct stateswitch *swtab[NUMSTATES];
108   enum state sbtab[NUMSTATES];
109
110   const char *tmplang;
111
112   const char *tmpvers;
113   const char *tmprel;
114   const char *tmpurltype;
115
116   unsigned int ctime;
117
118   Solvable *solvable;
119   Id handle;
120
121   ino_t baseproduct;
122   ino_t currentproduct;
123   int productscheme;
124
125   Id langcache[ID_NUM_INTERNAL];
126 };
127
128
129 /*
130  * find_attr
131  * find value for xml attribute
132  * I: txt, name of attribute
133  * I: atts, list of key/value attributes
134  * I: dup, strdup it
135  * O: pointer to value of matching key, or NULL
136  *
137  */
138
139 static inline const char *
140 find_attr(const char *txt, const char **atts, int dup)
141 {
142   for (; *atts; atts += 2)
143     {
144       if (!strcmp(*atts, txt))
145         return dup ? strdup(atts[1]) : atts[1];
146     }
147   return 0;
148 }
149
150
151 /*
152  * create localized tag
153  */
154
155 static Id
156 langtag(struct parsedata *pd, Id tag, const char *language)
157 {
158   if (language && !language[0])
159     language = 0;
160   if (!language || tag >= ID_NUM_INTERNAL)
161     return pool_id2langid(pd->repo->pool, tag, language, 1);
162   if (!pd->langcache[tag])
163     pd->langcache[tag] = pool_id2langid(pd->repo->pool, tag, language, 1);
164   return pd->langcache[tag];
165 }
166
167
168 /*
169  * XML callback: startElement
170  */
171
172 static void XMLCALL
173 startElement(void *userData, const char *name, const char **atts)
174 {
175   struct parsedata *pd = userData;
176   Pool *pool = pd->pool;
177   Solvable *s = pd->solvable;
178   struct stateswitch *sw;
179
180 #if 0
181       fprintf(stderr, "start: [%d]%s\n", pd->state, name);
182 #endif
183   if (pd->depth != pd->statedepth)
184     {
185       pd->depth++;
186       return;
187     }
188
189   pd->depth++;
190   if (!pd->swtab[pd->state])    /* no statetable -> no substates */
191     {
192 #if 0
193       fprintf(stderr, "into unknown: %s (from: %d)\n", name, pd->state);
194 #endif
195       return;
196     }
197   for (sw = pd->swtab[pd->state]; sw->from == pd->state; sw++)  /* find name in statetable */
198     if (!strcmp(sw->ename, name))
199       break;
200
201   if (sw->from != pd->state)
202     {
203 #if 0
204       fprintf(stderr, "into unknown: %s (from: %d)\n", name, pd->state);
205 #endif
206       return;
207     }
208   pd->state = sw->to;
209   pd->docontent = sw->docontent;
210   pd->statedepth = pd->depth;
211   pd->lcontent = 0;
212   *pd->content = 0;
213
214   switch(pd->state)
215     {
216     case STATE_PRODUCT:
217       /* parse 'schemeversion' and store in global variable */
218       {
219         const char * scheme = find_attr("schemeversion", atts, 0);
220         pd->productscheme = (scheme && *scheme) ? atoi(scheme) : -1;
221       }
222       if (!s)
223         {
224           s = pd->solvable = pool_id2solvable(pool, repo_add_solvable(pd->repo));
225           pd->handle = s - pool->solvables;
226         }
227       break;
228
229       /* <summary lang="xy">... */
230     case STATE_SUMMARY:
231       pd->tmplang = find_attr("lang", atts, 1);
232       break;
233     case STATE_DESCRIPTION:
234       pd->tmplang = find_attr("lang", atts, 1);
235       break;
236     case STATE_URL:
237       pd->tmpurltype = find_attr("name", atts, 1);
238       break;
239     default:
240       break;
241     }
242 }
243
244
245 static void XMLCALL
246 endElement(void *userData, const char *name)
247 {
248   struct parsedata *pd = userData;
249   Solvable *s = pd->solvable;
250
251 #if 0
252       fprintf(stderr, "end: [%d]%s\n", pd->state, name);
253 #endif
254   if (pd->depth != pd->statedepth)
255     {
256       pd->depth--;
257 #if 0
258       fprintf(stderr, "back from unknown %d %d %d\n", pd->state, pd->depth, pd->statedepth);
259 #endif
260       return;
261     }
262
263   pd->depth--;
264   pd->statedepth--;
265
266   switch (pd->state)
267     {
268     case STATE_PRODUCT:
269       /* product done, finish solvable */
270       if (pd->ctime)
271         repodata_set_num(pd->data, pd->handle, SOLVABLE_INSTALLTIME, pd->ctime);
272
273       if (pd->basename)
274         repodata_set_str(pd->data, pd->handle, PRODUCT_REFERENCEFILE, pd->basename);
275
276       /* this is where <productsdir>/baseproduct points to */
277       if (pd->currentproduct == pd->baseproduct)
278         repodata_set_str(pd->data, pd->handle, PRODUCT_TYPE, "base");
279
280       if (pd->tmprel)
281         {
282           if (pd->tmpvers)
283             s->evr = makeevr(pd->pool, join2(pd->tmpvers, "-", pd->tmprel));
284           else
285             {
286               fprintf(stderr, "Seen <release> but no <version>\n");
287             }
288         }
289       else if (pd->tmpvers)
290         s->evr = makeevr(pd->pool, pd->tmpvers); /* just version, no release */
291       pd->tmpvers = sat_free((void *)pd->tmpvers);
292       pd->tmprel = sat_free((void *)pd->tmprel);
293       if (!s->arch)
294         s->arch = ARCH_NOARCH;
295       if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
296         s->provides = repo_addid_dep(pd->repo, s->provides, rel2id(pd->pool, s->name, s->evr, REL_EQ, 1), 0);
297       pd->solvable = 0;
298       break;
299     case STATE_VENDOR:
300       s->vendor = str2id(pd->pool, pd->content, 1);
301       break;
302     case STATE_NAME:
303       s->name = str2id(pd->pool, join2("product", ":", pd->content), 1);
304       break;
305     case STATE_VERSION:
306       pd->tmpvers = strdup(pd->content);
307       break;
308     case STATE_RELEASE:
309       pd->tmprel = strdup(pd->content);
310       break;
311     case STATE_ARCH:
312       s->arch = str2id(pd->pool, pd->content, 1);
313       break;
314     case STATE_PRODUCTLINE:
315       repodata_set_str(pd->data, pd->handle, PRODUCT_PRODUCTLINE, pd->content);
316     break;
317     case STATE_UPDATEREPOKEY:
318       repodata_set_str(pd->data, pd->handle, langtag(pd, PRODUCT_UPDATEREPOKEY, pd->tmplang), pd->content);
319       break;
320     case STATE_SUMMARY:
321       repodata_set_str(pd->data, pd->handle, langtag(pd, SOLVABLE_SUMMARY, pd->tmplang), pd->content);
322       pd->tmplang = sat_free((void *)pd->tmplang);
323       break;
324     case STATE_DESCRIPTION:
325       repodata_set_str(pd->data, pd->handle, langtag(pd, SOLVABLE_DESCRIPTION, pd->tmplang), pd->content );
326       pd->tmplang = sat_free((void *)pd->tmplang);
327       break;
328     case STATE_URL:
329       if (pd->tmpurltype)
330         {
331           repodata_add_poolstr_array(pd->data, pd->handle, PRODUCT_URL, pd->content);
332           repodata_add_idarray(pd->data, pd->handle, PRODUCT_URL_TYPE, str2id(pd->pool, pd->tmpurltype, 1));
333         }
334       pd->tmpurltype = sat_free((void *)pd->tmpurltype);
335       break;
336     case STATE_TARGET:
337       repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_TARGET, pd->content);
338       break;
339     case STATE_REGRELEASE:
340       repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_RELEASE, pd->content);
341       break;
342     case STATE_CPEID:
343       if (pd->content)
344         repodata_set_str(pd->data, pd->handle, SOLVABLE_CPE_ID, pd->content);
345     default:
346       break;
347     }
348
349   pd->state = pd->sbtab[pd->state];
350   pd->docontent = 0;
351
352 #if 0
353       fprintf(stderr, "end: [%s] -> %d\n", name, pd->state);
354 #endif
355 }
356
357
358 static void XMLCALL
359 characterData(void *userData, const XML_Char *s, int len)
360 {
361   struct parsedata *pd = userData;
362   int l;
363   char *c;
364   if (!pd->docontent)
365     return;
366   l = pd->lcontent + len + 1;
367   if (l > pd->acontent)
368     {
369       pd->content = sat_realloc(pd->content, l + 256);
370       pd->acontent = l + 256;
371     }
372   c = pd->content + pd->lcontent;
373   pd->lcontent += len;
374   while (len-- > 0)
375     *c++ = *s++;
376   *c = 0;
377 }
378
379 #define BUFF_SIZE 8192
380
381
382 /*
383  * add single product to repo
384  *
385  */
386
387 static void
388 repo_add_product(struct parsedata *pd, FILE *fp, int code11)
389 {
390   char buf[BUFF_SIZE];
391   int l;
392   struct stat st;
393
394   if (!fstat(fileno(fp), &st))
395     {
396       pd->currentproduct = st.st_ino;
397       pd->ctime = (unsigned int)st.st_ctime;
398     }
399   else
400     {
401       pd->currentproduct = pd->baseproduct + 1; /* make it != baseproduct if stat fails */
402       perror("fstat");
403       pd->ctime = 0;
404     }
405
406   if (code11)
407     {
408       XML_Parser parser = XML_ParserCreate(NULL);
409       XML_SetUserData(parser, pd);
410       XML_SetElementHandler(parser, startElement, endElement);
411       XML_SetCharacterDataHandler(parser, characterData);
412
413       for (;;)
414         {
415           l = fread(buf, 1, sizeof(buf), fp);
416           if (XML_Parse(parser, buf, l, l == 0) == XML_STATUS_ERROR)
417             {
418               pool_debug(pd->pool, SAT_ERROR, "%s: %s at line %u:%u\n", pd->filename, XML_ErrorString(XML_GetErrorCode(parser)), (unsigned int)XML_GetCurrentLineNumber(parser), (unsigned int)XML_GetCurrentColumnNumber(parser));
419               pool_debug(pd->pool, SAT_ERROR, "Skipping this product\n");
420               XML_ParserFree(parser);
421               return;
422             }
423           if (l == 0)
424             break;
425         }
426       XML_ParserFree(parser);
427     }
428   else
429     {
430       Id name = 0;
431       Id arch = 0;
432       Id version = 0;
433       int lnum = 0; /* line number */
434       char *ptr, *ptr1;
435       /* parse /etc/<xyz>-release file */
436       while (fgets(buf, sizeof(buf), fp))
437         {
438           /* remove trailing \n */
439           int l = strlen(buf);
440           if (*(buf + l - 1) == '\n')
441             {
442               --l;
443               *(buf + l) = 0;
444             }
445           ++lnum;
446
447           if (lnum == 1)
448             {
449               /* 1st line, <name> [(<arch>)] */
450               ptr = strchr(buf, '(');
451               if (ptr)
452                 {
453                   ptr1 = ptr - 1;
454                   *ptr++ = 0;
455                 }
456               else
457                 ptr1 = buf + l - 1;
458
459               /* track back until non-blank, non-digit */
460               while (ptr1 > buf
461                      && (*ptr1 == ' ' || isdigit(*ptr1) || *ptr1 == '.'))
462                 --ptr1;
463               *(++ptr1) = 0;
464               name = str2id(pd->pool, join2("product", ":", buf), 1);
465
466               if (ptr)
467                 {
468                   /* have arch */
469                   char *ptr1 = strchr(ptr, ')');
470                   if (ptr1)
471                     {
472                       *ptr1 = 0;
473                       /* downcase arch */
474                       ptr1 = ptr;
475                       while (*ptr1)
476                         {
477                           if (isupper(*ptr1)) *ptr1 = tolower(*ptr1);
478                           ++ptr1;
479                         }
480                       arch = str2id(pd->pool, ptr, 1);
481                     }
482                 }
483             }
484           else if (strncmp(buf, "VERSION", 7) == 0)
485             {
486               ptr = strchr(buf+7, '=');
487               if (ptr)
488                 {
489                   while (*++ptr == ' ');
490                   version = makeevr(pd->pool, ptr);
491                 }
492             }
493         }
494       if (name)
495         {
496           Solvable *s = pd->solvable = pool_id2solvable(pd->pool, repo_add_solvable(pd->repo));
497           s->name = name;
498           if (version)
499             s->evr = version;
500           if (arch)
501             s->arch = arch;
502           if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
503             s->provides = repo_addid_dep(pd->repo, s->provides, rel2id(pd->pool, s->name, s->evr, REL_EQ, 1), 0);
504         }
505     }
506 }
507
508
509
510 /*
511  * parse dir looking for files ending in suffix
512  */
513
514 static void
515 parse_dir(DIR *dir, const char *path, struct parsedata *pd, int code11)
516 {
517   struct dirent *entry;
518   char *suffix = code11 ? ".prod" : "-release";
519   int slen = code11 ? 5 : 8;  /* strlen(".prod") : strlen("-release") */
520   struct stat st;
521
522   /* check for <productsdir>/baseproduct on code11 and remember its target inode */
523   if (code11
524       && stat(join2(path, "/", "baseproduct"), &st) == 0) /* follow symlink */
525     {
526       pd->baseproduct = st.st_ino;
527     }
528   else
529     pd->baseproduct = 0;
530
531   while ((entry = readdir(dir)))
532     {
533       int len;
534       len = strlen(entry->d_name);
535
536       /* skip /etc/lsb-release, thats not a product per-se */
537       if (!code11
538           && strcmp(entry->d_name, "lsb-release") == 0)
539         {
540           continue;
541         }
542
543       if (len > slen
544           && strcmp(entry->d_name + len - slen, suffix) == 0)
545         {
546           char *fullpath = join2(path, "/", entry->d_name);
547           FILE *fp = fopen(fullpath, "r");
548           if (!fp)
549             {
550               perror(fullpath);
551               break;
552             }
553           pd->filename = fullpath;
554           pd->basename = entry->d_name;
555           repo_add_product(pd, fp, code11);
556           fclose(fp);
557         }
558     }
559 }
560
561
562 /*
563  * read all installed products
564  *
565  * try proddir (reading all .xml files from this directory) first
566  * if not available, assume non-code11 layout and parse /etc/xyz-release
567  *
568  * parse each one as a product
569  */
570
571 /* Oh joy! Three parsers for the price of one! */
572
573 void
574 repo_add_products(Repo *repo, const char *proddir, const char *root, int flags)
575 {
576   const char *fullpath = proddir;
577   DIR *dir;
578   int i;
579   struct parsedata pd;
580   struct stateswitch *sw;
581   Repodata *data;
582
583   if (!(flags & REPO_REUSE_REPODATA))
584     data = repo_add_repodata(repo, 0);
585   else
586     data = repo_last_repodata(repo);
587
588   memset(&pd, 0, sizeof(pd));
589   pd.repo = repo;
590   pd.pool = repo->pool;
591   pd.data = data;
592
593   pd.content = sat_malloc(256);
594   pd.acontent = 256;
595
596   for (i = 0, sw = stateswitches; sw->from != NUMSTATES; i++, sw++)
597     {
598       if (!pd.swtab[sw->from])
599         pd.swtab[sw->from] = sw;
600       pd.sbtab[sw->to] = sw->from;
601     }
602
603   dir = opendir(fullpath);
604   if (dir)
605     {
606       parse_dir(dir, fullpath, &pd, 1); /* assume 'code11' products */
607       closedir(dir);
608     }
609   else
610     {
611       fullpath = root ? join2(root, "", "/var/lib/zypp/db/products") : "/var/lib/zypp/db/products";
612       dir = opendir(fullpath);
613       if (dir)
614         {
615           repo_add_zyppdb_products(repo, data, fullpath, dir);      /* assume 'code10' zypp-style products */
616           closedir(dir);
617         }
618       else
619         {
620           fullpath = root ? join2(root, "", "/etc") : "/etc";
621           dir = opendir(fullpath);
622           if (dir)
623             {
624               parse_dir(dir, fullpath, &pd, 0); /* fall back to /etc/<xyz>-release parsing */
625               closedir(dir);
626             }
627           else
628             {
629               perror(fullpath);
630             }
631         }
632     }
633
634   sat_free((void *)pd.tmplang);
635   sat_free(pd.content);
636   join_freemem();
637
638   if (!(flags & REPO_NO_INTERNALIZE))
639     repodata_internalize(data);
640 }
641
642 /* EOF */