- don't abort on unknown elements
[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   int depth;
96   enum state state;
97   int statedepth;
98   char *content;
99   int lcontent;
100   int acontent;
101   int docontent;
102   Pool *pool;
103   Repo *repo;
104   Repodata *data;
105
106   struct stateswitch *swtab[NUMSTATES];
107   enum state sbtab[NUMSTATES];
108   const char *attribute; /* only print this attribute, if currentproduct == baseproduct */
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       /* this is where <productsdir>/baseproduct points to */
274       if (pd->currentproduct == pd->baseproduct)
275         repodata_set_str(pd->data, pd->handle, PRODUCT_TYPE, "base");
276
277       // output distver if requested, only if the product is
278       // a base product
279       // this is yum $releasever variable
280       if (pd->currentproduct == pd->baseproduct
281           && pd->attribute
282           && !strcmp(pd->attribute, "releasever"))
283         {
284           printf("%s\n", pd->tmpvers);
285         }
286
287       if (pd->tmprel)
288         {
289           if (pd->tmpvers)
290             s->evr = makeevr(pd->pool, join2(pd->tmpvers, "-", pd->tmprel));
291           else
292             {
293               fprintf(stderr, "Seen <release> but no <version>\n");
294             }
295         }
296       else if (pd->tmpvers)
297         s->evr = makeevr(pd->pool, pd->tmpvers); /* just version, no release */
298       pd->tmpvers = sat_free((void *)pd->tmpvers);
299       pd->tmprel = sat_free((void *)pd->tmprel);
300       if (!s->arch)
301         s->arch = ARCH_NOARCH;
302       if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
303         s->provides = repo_addid_dep(pd->repo, s->provides, rel2id(pd->pool, s->name, s->evr, REL_EQ, 1), 0);
304       pd->solvable = 0;
305       break;
306     case STATE_VENDOR:
307       s->vendor = str2id(pd->pool, pd->content, 1);
308       break;
309     case STATE_NAME:
310       s->name = str2id(pd->pool, join2("product", ":", pd->content), 1);
311       break;
312     case STATE_VERSION:
313       pd->tmpvers = strdup(pd->content);
314       break;
315     case STATE_RELEASE:
316       pd->tmprel = strdup(pd->content);
317       break;
318     case STATE_ARCH:
319       s->arch = str2id(pd->pool, pd->content, 1);
320       break;
321     case STATE_PRODUCTLINE:
322       repodata_set_str(pd->data, pd->handle, PRODUCT_PRODUCTLINE, pd->content);
323     break;
324     case STATE_UPDATEREPOKEY:
325       repodata_set_str(pd->data, pd->handle, langtag(pd, PRODUCT_UPDATEREPOKEY, pd->tmplang), pd->content);
326       break;
327     case STATE_SUMMARY:
328       repodata_set_str(pd->data, pd->handle, langtag(pd, SOLVABLE_SUMMARY, pd->tmplang), pd->content);
329       pd->tmplang = sat_free((void *)pd->tmplang);
330       break;
331     case STATE_DESCRIPTION:
332       repodata_set_str(pd->data, pd->handle, langtag(pd, SOLVABLE_DESCRIPTION, pd->tmplang), pd->content );
333       pd->tmplang = sat_free((void *)pd->tmplang);
334       break;
335     case STATE_URL:
336       if (pd->tmpurltype)
337         {
338           repodata_add_poolstr_array(pd->data, pd->handle, PRODUCT_URL, pd->content);
339           repodata_add_idarray(pd->data, pd->handle, PRODUCT_URL_TYPE, str2id(pd->pool, pd->tmpurltype, 1));
340         }
341       pd->tmpurltype = sat_free((void *)pd->tmpurltype);
342       break;
343     case STATE_TARGET:
344       repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_TARGET, pd->content);
345       if (pd->currentproduct == pd->baseproduct
346           && pd->attribute
347           && !strcmp(pd->attribute, "register.target"))
348         {
349           printf("%s\n", pd->content);
350         }
351     break;
352     case STATE_REGRELEASE:
353       repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_RELEASE, pd->content);
354       if (pd->currentproduct == pd->baseproduct
355           && pd->attribute
356           && !strcmp(pd->attribute, "register.release"))
357         {
358           printf("%s\n", pd->content);
359         }
360     break;
361     case STATE_CPEID:
362       if (pd->content)
363         repodata_set_str(pd->data, pd->handle, SOLVABLE_CPE_ID, pd->content);
364     default:
365       break;
366     }
367
368   pd->state = pd->sbtab[pd->state];
369   pd->docontent = 0;
370
371 #if 0
372       fprintf(stderr, "end: [%s] -> %d\n", name, pd->state);
373 #endif
374 }
375
376
377 static void XMLCALL
378 characterData(void *userData, const XML_Char *s, int len)
379 {
380   struct parsedata *pd = userData;
381   int l;
382   char *c;
383   if (!pd->docontent)
384     return;
385   l = pd->lcontent + len + 1;
386   if (l > pd->acontent)
387     {
388       pd->content = sat_realloc(pd->content, l + 256);
389       pd->acontent = l + 256;
390     }
391   c = pd->content + pd->lcontent;
392   pd->lcontent += len;
393   while (len-- > 0)
394     *c++ = *s++;
395   *c = 0;
396 }
397
398 #define BUFF_SIZE 8192
399
400
401 /*
402  * add single product to repo
403  *
404  */
405
406 static void
407 repo_add_product(struct parsedata *pd, FILE *fp, int code11)
408 {
409   char buf[BUFF_SIZE];
410   int l;
411   struct stat st;
412
413   if (!fstat(fileno(fp), &st))
414     {
415       pd->currentproduct = st.st_ino;
416       pd->ctime = (unsigned int)st.st_ctime;
417     }
418   else
419     {
420       pd->currentproduct = pd->baseproduct + 1; /* make it != baseproduct if stat fails */
421       perror("fstat");
422       pd->ctime = 0;
423     }
424
425   if (code11)
426     {
427       XML_Parser parser = XML_ParserCreate(NULL);
428       XML_SetUserData(parser, pd);
429       XML_SetElementHandler(parser, startElement, endElement);
430       XML_SetCharacterDataHandler(parser, characterData);
431
432       for (;;)
433         {
434           l = fread(buf, 1, sizeof(buf), fp);
435           if (XML_Parse(parser, buf, l, l == 0) == XML_STATUS_ERROR)
436             {
437               fprintf(stderr, "%s: %s at line %u:%u\n", pd->filename, XML_ErrorString(XML_GetErrorCode(parser)), (unsigned int)XML_GetCurrentLineNumber(parser), (unsigned int)XML_GetCurrentColumnNumber(parser));
438               fprintf(stderr, "Skipping this product\n");
439               return;
440             }
441           if (l == 0)
442             break;
443         }
444       XML_ParserFree(parser);
445     }
446   else
447     {
448       Id name = 0;
449       Id arch = 0;
450       Id version = 0;
451       int lnum = 0; /* line number */
452       char *ptr, *ptr1;
453       /* parse /etc/<xyz>-release file */
454       while (fgets(buf, sizeof(buf), fp))
455         {
456           /* remove trailing \n */
457           int l = strlen(buf);
458           if (*(buf + l - 1) == '\n')
459             {
460               --l;
461               *(buf + l) = 0;
462             }
463           ++lnum;
464
465           if (lnum == 1)
466             {
467               /* 1st line, <name> [(<arch>)] */
468               ptr = strchr(buf, '(');
469               if (ptr)
470                 {
471                   ptr1 = ptr - 1;
472                   *ptr++ = 0;
473                 }
474               else
475                 ptr1 = buf + l - 1;
476
477               /* track back until non-blank, non-digit */
478               while (ptr1 > buf
479                      && (*ptr1 == ' ' || isdigit(*ptr1) || *ptr1 == '.'))
480                 --ptr1;
481               *(++ptr1) = 0;
482               name = str2id(pd->pool, join2("product", ":", buf), 1);
483
484               if (ptr)
485                 {
486                   /* have arch */
487                   char *ptr1 = strchr(ptr, ')');
488                   if (ptr1)
489                     {
490                       *ptr1 = 0;
491                       /* downcase arch */
492                       ptr1 = ptr;
493                       while (*ptr1)
494                         {
495                           if (isupper(*ptr1)) *ptr1 = tolower(*ptr1);
496                           ++ptr1;
497                         }
498                       arch = str2id(pd->pool, ptr, 1);
499                     }
500                 }
501             }
502           else if (strncmp(buf, "VERSION", 7) == 0)
503             {
504               ptr = strchr(buf+7, '=');
505               if (ptr)
506                 {
507                   while (*++ptr == ' ');
508                   version = makeevr(pd->pool, ptr);
509                 }
510             }
511         }
512       if (name)
513         {
514           Solvable *s = pd->solvable = pool_id2solvable(pd->pool, repo_add_solvable(pd->repo));
515           s->name = name;
516           if (version)
517             s->evr = version;
518           if (arch)
519             s->arch = arch;
520           if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
521             s->provides = repo_addid_dep(pd->repo, s->provides, rel2id(pd->pool, s->name, s->evr, REL_EQ, 1), 0);
522         }
523     }
524   return;
525 }
526
527
528
529 /*
530  * parse dir looking for files ending in suffix
531  */
532
533 static void
534 parse_dir(DIR *dir, const char *path, struct parsedata *pd, int code11)
535 {
536   struct dirent *entry;
537   char *suffix = code11 ? ".prod" : "-release";
538   int slen = code11 ? 5 : 8;  /* strlen(".prod") : strlen("-release") */
539   struct stat st;
540
541   /* check for <productsdir>/baseproduct on code11 and remember its target inode */
542   if (code11
543       && stat(join2(path, "/", "baseproduct"), &st) == 0) /* follow symlink */
544     {
545       pd->baseproduct = st.st_ino;
546     }
547   else
548     pd->baseproduct = 0;
549
550   while ((entry = readdir(dir)))
551     {
552       int len;
553       len = strlen(entry->d_name);
554
555       /* skip /etc/lsb-release, thats not a product per-se */
556       if (!code11
557           && strcmp(entry->d_name, "lsb-release") == 0)
558         {
559           continue;
560         }
561
562       if (len > slen
563           && strcmp(entry->d_name + len - slen, suffix) == 0)
564         {
565           char *fullpath = join2(path, "/", entry->d_name);
566           FILE *fp = fopen(fullpath, "r");
567           if (!fp)
568             {
569               perror(fullpath);
570               break;
571             }
572           pd->filename = fullpath;
573           repo_add_product(pd, fp, code11);
574           fclose(fp);
575         }
576     }
577 }
578
579
580 /*
581  * read all installed products
582  *
583  * try proddir (reading all .xml files from this directory) first
584  * if not available, assume non-code11 layout and parse /etc/xyz-release
585  *
586  * parse each one as a product
587  */
588
589 /* Oh joy! Three parsers for the price of one! */
590
591 void
592 repo_add_products(Repo *repo, const char *proddir, const char *root, const char *attribute, int flags)
593 {
594   const char *fullpath = proddir;
595   DIR *dir;
596   int i;
597   struct parsedata pd;
598   struct stateswitch *sw;
599   Repodata *data;
600
601   if (!(flags & REPO_REUSE_REPODATA))
602     data = repo_add_repodata(repo, 0);
603   else 
604     data = repo_last_repodata(repo);
605
606   memset(&pd, 0, sizeof(pd));
607   pd.repo = repo;
608   pd.pool = repo->pool;
609   pd.data = data;
610
611   pd.content = sat_malloc(256);
612   pd.acontent = 256;
613
614   pd.attribute = attribute;
615
616   for (i = 0, sw = stateswitches; sw->from != NUMSTATES; i++, sw++)
617     {
618       if (!pd.swtab[sw->from])
619         pd.swtab[sw->from] = sw;
620       pd.sbtab[sw->to] = sw->from;
621     }
622
623   dir = opendir(fullpath);
624   if (dir)
625     {
626       parse_dir(dir, fullpath, &pd, 1); /* assume 'code11' products */
627       closedir(dir);
628     }
629   else
630     {
631       fullpath = root ? join2(root, "", "/var/lib/zypp/db/products") : "/var/lib/zypp/db/products";
632       dir = opendir(fullpath);
633       if (dir)
634         {
635           repo_add_zyppdb_products(repo, data, fullpath, dir);      /* assume 'code10' zypp-style products */
636           closedir(dir);
637         }
638       else
639         {
640           fullpath = root ? join2(root, "", "/etc") : "/etc";
641           dir = opendir(fullpath);
642           if (dir)
643             {
644               parse_dir(dir, fullpath, &pd, 0); /* fall back to /etc/<xyz>-release parsing */
645               closedir(dir);
646             }
647           else
648             {
649               perror(fullpath);
650             }
651         }
652     }
653
654   sat_free((void *)pd.tmplang);
655   sat_free(pd.content);
656   join_freemem();
657
658
659   if (!(flags & REPO_NO_INTERNALIZE))
660     repodata_internalize(data);
661 }
662
663 /* EOF */