bnc#429177
[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_CPENAME,         // 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_FLAVOR,          // 17
58   STATE_REGRELEASE,      // 18
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,   "summary",       STATE_SUMMARY,       1 },
78   { STATE_PRODUCT,   "description",   STATE_DESCRIPTION,   1 },
79   { STATE_PRODUCT,   "register",      STATE_REGISTER,      0 },
80   { STATE_PRODUCT,   "urls",          STATE_URLS,          0 },
81   { STATE_PRODUCT,   "runtimeconfig", STATE_RUNTIMECONFIG, 0 },
82   { STATE_PRODUCT,   "linguas",       STATE_LINGUAS,       0 },
83   { STATE_PRODUCT,   "updaterepokey", STATE_UPDATEREPOKEY, 1 },
84   { STATE_PRODUCT,   "cpename",       STATE_CPENAME,       1 },
85   { STATE_URLS,      "url",           STATE_URL,           1 },
86   { STATE_LINGUAS,   "lang",          STATE_LANG,          0 },
87   { STATE_REGISTER,  "flavor",        STATE_FLAVOR,        1 },
88   { STATE_REGISTER,  "target",        STATE_TARGET,        1 },
89   { STATE_REGISTER,  "release",       STATE_REGRELEASE,    1 },
90   { NUMSTATES }
91 };
92
93 struct parsedata {
94   int depth;
95   enum state state;
96   int statedepth;
97   char *content;
98   int lcontent;
99   int acontent;
100   int docontent;
101   Pool *pool;
102   Repo *repo;
103   Repodata *data;
104
105   struct stateswitch *swtab[NUMSTATES];
106   enum state sbtab[NUMSTATES];
107   const char *attribute; /* only print this attribute, if currentproduct == baseproduct */
108
109   const char *tmplang;
110
111   const char *tmpvers;
112   const char *tmprel;
113   const char *tmpurltype;
114
115   unsigned int ctime;
116
117   Solvable *solvable;
118   Id handle;
119
120   ino_t baseproduct;
121   ino_t currentproduct;
122   int productscheme;
123
124   Id langcache[ID_NUM_INTERNAL];
125 };
126
127
128 /*
129  * find_attr
130  * find value for xml attribute
131  * I: txt, name of attribute
132  * I: atts, list of key/value attributes
133  * I: dup, strdup it
134  * O: pointer to value of matching key, or NULL
135  *
136  */
137
138 static inline const char *
139 find_attr(const char *txt, const char **atts, int dup)
140 {
141   for (; *atts; atts += 2)
142     {
143       if (!strcmp(*atts, txt))
144         return dup ? strdup(atts[1]) : atts[1];
145     }
146   return 0;
147 }
148
149
150 /*
151  * create localized tag
152  */
153
154 static Id
155 langtag(struct parsedata *pd, Id tag, const char *language)
156 {
157   if (language && !language[0])
158     language = 0;
159   if (!language || tag >= ID_NUM_INTERNAL)
160     return pool_id2langid(pd->repo->pool, tag, language, 1);
161   if (!pd->langcache[tag])
162     pd->langcache[tag] = pool_id2langid(pd->repo->pool, tag, language, 1);
163   return pd->langcache[tag];
164 }
165
166
167 /*
168  * XML callback: startElement
169  */
170
171 static void XMLCALL
172 startElement(void *userData, const char *name, const char **atts)
173 {
174   struct parsedata *pd = userData;
175   Pool *pool = pd->pool;
176   Solvable *s = pd->solvable;
177   struct stateswitch *sw;
178
179 #if 0
180       fprintf(stderr, "start: [%d]%s\n", pd->state, name);
181 #endif
182   if (pd->depth != pd->statedepth)
183     {
184       pd->depth++;
185       return;
186     }
187
188   pd->depth++;
189   if (!pd->swtab[pd->state])    /* no statetable -> no substates */
190     {
191 #if 0
192       fprintf(stderr, "into unknown: %s (from: %d)\n", name, pd->state);
193 #endif
194       return;
195     }
196   for (sw = pd->swtab[pd->state]; sw->from == pd->state; sw++)  /* find name in statetable */
197     if (!strcmp(sw->ename, name))
198       break;
199
200   if (sw->from != pd->state)
201     {
202 #if 0
203       fprintf(stderr, "into unknown: %s (from: %d)\n", name, pd->state);
204 #endif
205       return;
206     }
207   pd->state = sw->to;
208   pd->docontent = sw->docontent;
209   pd->statedepth = pd->depth;
210   pd->lcontent = 0;
211   *pd->content = 0;
212
213   switch(pd->state)
214     {
215     case STATE_PRODUCT:
216       /* parse 'schemeversion' and store in global variable */
217       {
218         const char * scheme = find_attr("schemeversion", atts, 0);
219         pd->productscheme = (scheme && *scheme) ? atoi(scheme) : -1;
220       }
221       if (!s)
222         {
223           s = pd->solvable = pool_id2solvable(pool, repo_add_solvable(pd->repo));
224           repodata_extend(pd->data, s - pool->solvables);
225           pd->handle = repodata_get_handle(pd->data, (s - pool->solvables) - pd->repo->start);
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       if (pd->tmprel)
278         {
279           if (pd->tmpvers)
280             s->evr = makeevr(pd->pool, join2(pd->tmpvers, "-", pd->tmprel));
281           else
282             {
283               fprintf(stderr, "Seen <release> but no <version>\n");
284             }
285         }
286       else if (pd->tmpvers)
287         s->evr = makeevr(pd->pool, pd->tmpvers); /* just version, no release */
288       pd->tmpvers = sat_free((void *)pd->tmpvers);
289       pd->tmprel = sat_free((void *)pd->tmprel);
290       if (!s->arch)
291         s->arch = ARCH_NOARCH;
292       if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
293         s->provides = repo_addid_dep(pd->repo, s->provides, rel2id(pd->pool, s->name, s->evr, REL_EQ, 1), 0);
294       pd->solvable = 0;
295       break;
296     case STATE_VENDOR:
297       s->vendor = str2id(pd->pool, pd->content, 1);
298       break;
299     case STATE_NAME:
300       s->name = str2id(pd->pool, join2("product", ":", pd->content), 1);
301       break;
302     case STATE_VERSION:
303       pd->tmpvers = strdup(pd->content);
304       break;
305     case STATE_RELEASE:
306       pd->tmprel = strdup(pd->content);
307       break;
308     case STATE_ARCH:
309       s->arch = str2id(pd->pool, pd->content, 1);
310       break;
311     case STATE_UPDATEREPOKEY:
312       repodata_set_str(pd->data, pd->handle, langtag(pd, PRODUCT_UPDATEREPOKEY, pd->tmplang), pd->content);
313       break;
314     case STATE_SUMMARY:
315       repodata_set_str(pd->data, pd->handle, langtag(pd, SOLVABLE_SUMMARY, pd->tmplang), pd->content);
316       pd->tmplang = sat_free((void *)pd->tmplang);
317       break;
318     case STATE_DESCRIPTION:
319       repodata_set_str(pd->data, pd->handle, langtag(pd, SOLVABLE_DESCRIPTION, pd->tmplang), pd->content );
320       pd->tmplang = sat_free((void *)pd->tmplang);
321       break;
322     case STATE_URL:
323       if (pd->tmpurltype)
324         {
325           repodata_add_poolstr_array(pd->data, pd->handle, PRODUCT_URL, pd->content);
326           repodata_add_idarray(pd->data, pd->handle, PRODUCT_URL_TYPE, str2id(pd->pool, pd->tmpurltype, 1));
327         }
328       pd->tmpurltype = sat_free((void *)pd->tmpurltype);
329       break;
330     case STATE_TARGET:
331       repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_TARGET, pd->content);
332       if (pd->currentproduct == pd->baseproduct
333           && pd->attribute
334           && !strcmp(pd->attribute, "register.target"))
335         {
336           printf("%s\n", pd->content);
337         }
338     break;
339     case STATE_FLAVOR:
340       repodata_set_str(pd->data, pd->handle, PRODUCT_FLAVOR, pd->content);
341       if (pd->currentproduct == pd->baseproduct
342           && pd->attribute
343           && !strcmp(pd->attribute, "register.flavor"))
344         {
345           printf("%s\n", pd->content);
346         }
347     break;
348     case STATE_REGRELEASE:
349       repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_RELEASE, pd->content);
350       if (pd->currentproduct == pd->baseproduct
351           && pd->attribute
352           && !strcmp(pd->attribute, "register.release"))
353         {
354           printf("%s\n", pd->content);
355         }
356     break;
357     case STATE_CPENAME:
358       if (pd->content)
359         repodata_set_str(pd->data, pd->handle, SOLVABLE_CPE_NAME, pd->content);
360     default:
361       break;
362     }
363
364   pd->state = pd->sbtab[pd->state];
365   pd->docontent = 0;
366
367 #if 0
368       fprintf(stderr, "end: [%s] -> %d\n", name, pd->state);
369 #endif
370 }
371
372
373 static void XMLCALL
374 characterData(void *userData, const XML_Char *s, int len)
375 {
376   struct parsedata *pd = userData;
377   int l;
378   char *c;
379   if (!pd->docontent) {
380 #if 0
381     char *dup = strndup( s, len );
382   fprintf(stderr, "Content: [%d]'%s'\n", pd->state, dup );
383   free( dup );
384 #endif
385     return;
386   }
387   l = pd->lcontent + len + 1;
388   if (l > pd->acontent)
389     {
390       pd->content = realloc(pd->content, l + 256);
391       pd->acontent = l + 256;
392     }
393   c = pd->content + pd->lcontent;
394   pd->lcontent += len;
395   while (len-- > 0)
396     *c++ = *s++;
397   *c = 0;
398 }
399
400 #define BUFF_SIZE 8192
401
402
403 /*
404  * add single product to repo
405  *
406  */
407
408 static void
409 repo_add_product(struct parsedata *pd, Repodata *data, FILE *fp, int code11)
410 {
411   char buf[BUFF_SIZE];
412   int l;
413   struct stat st;
414
415   if (!fstat(fileno(fp), &st))
416     {
417       pd->currentproduct = st.st_ino;
418       pd->ctime = (unsigned int)st.st_ctime;
419     }
420   else
421     {
422       pd->currentproduct = pd->baseproduct + 1; /* make it != baseproduct if stat fails */
423       perror("fstat");
424       pd->ctime = 0;
425     }
426
427   if (code11)
428     {
429       XML_Parser parser = XML_ParserCreate(NULL);
430       XML_SetUserData(parser, pd);
431       XML_SetElementHandler(parser, startElement, endElement);
432       XML_SetCharacterDataHandler(parser, characterData);
433       
434       for (;;)
435         {
436           l = fread(buf, 1, sizeof(buf), fp);
437           if (XML_Parse(parser, buf, l, l == 0) == XML_STATUS_ERROR)
438             {
439               fprintf(stderr, "repo_products: %s at line %u:%u\n", XML_ErrorString(XML_GetErrorCode(parser)), (unsigned int)XML_GetCurrentLineNumber(parser), (unsigned int)XML_GetCurrentColumnNumber(parser));
440               exit(1);
441             }
442           if (l == 0)
443             break;
444         }
445       XML_ParserFree(parser);
446     }
447   else
448     {
449       Id name = 0;
450       Id arch = 0;
451       Id version = 0;
452       int lnum = 0; /* line number */
453       char *ptr, *ptr1;
454       /* parse /etc/<xyz>-release file */
455       while (fgets(buf, sizeof(buf), fp))
456         {
457           /* remove trailing \n */
458           int l = strlen(buf);
459           if (*(buf + l - 1) == '\n')
460             {
461               --l;
462               *(buf + l) = 0;
463             }
464           ++lnum;
465           
466           if (lnum == 1)
467             {
468               /* 1st line, <name> [(<arch>)] */
469               ptr = strchr(buf, '(');
470               if (ptr)
471                 {
472                   ptr1 = ptr - 1;
473                   *ptr++ = 0;
474                 }
475               else
476                 ptr1 = buf + l - 1;
477               
478               /* track back until non-blank, non-digit */
479               while (ptr1 > buf
480                      && (*ptr1 == ' ' || isdigit(*ptr1) || *ptr1 == '.'))
481                 --ptr1;
482               *(++ptr1) = 0;
483               name = str2id(pd->pool, join2("product", ":", buf), 1);
484
485               if (ptr)
486                 {
487                   /* have arch */
488                   char *ptr1 = strchr(ptr, ')');
489                   if (ptr1)
490                     {
491                       *ptr1 = 0;
492                       /* downcase arch */
493                       ptr1 = ptr;
494                       while (*ptr1)
495                         {
496                           if (isupper(*ptr1)) *ptr1 = tolower(*ptr1);
497                           ++ptr1;
498                         }
499                       arch = str2id(pd->pool, ptr, 1);
500                     }
501                 }
502             }
503           else if (strncmp(buf, "VERSION", 7) == 0) 
504             {
505               ptr = strchr(buf+7, '=');
506               if (ptr)
507                 {
508                   while (*++ptr == ' ');
509                   version = makeevr(pd->pool, ptr);
510                 }
511             }
512         }
513       if (name)
514         {
515           Solvable *s = pd->solvable = pool_id2solvable(pd->pool, repo_add_solvable(pd->repo));
516           s->name = name;
517           if (version)
518             s->evr = version;
519           if (arch)
520             s->arch = arch;
521           if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
522             s->provides = repo_addid_dep(pd->repo, s->provides, rel2id(pd->pool, s->name, s->evr, REL_EQ, 1), 0);
523         }
524     }
525   return;
526 }
527
528
529
530 /*
531  * parse dir looking for files ending in suffix
532  */
533
534 static void
535 parse_dir(DIR *dir, const char *path, struct parsedata *pd, Repodata *repodata, int code11)
536 {
537   struct dirent *entry;
538   char *suffix = code11 ? ".prod" : "-release";
539   int slen = code11 ? 5 : 8;  /* strlen(".prod") : strlen("-release") */
540   struct stat st;
541
542   /* check for <productsdir>/baseproduct on code11 and remember its target inode */
543   if (code11
544       && stat(join2(path, "/", "baseproduct"), &st) == 0) /* follow symlink */
545     {
546       pd->baseproduct = st.st_ino;
547     }
548   else
549     pd->baseproduct = 0;
550
551   while ((entry = readdir(dir)))
552     {
553       int len;
554       len = strlen(entry->d_name);
555
556       /* skip /etc/lsb-release, thats not a product per-se */
557       if (!code11
558           && strcmp(entry->d_name, "lsb-release") == 0)
559         {
560           continue;
561         }
562
563       if (len > slen
564           && strcmp(entry->d_name + len - slen, suffix) == 0)
565         {
566           char *fullpath = join2(path, "/", entry->d_name);
567           FILE *fp = fopen(fullpath, "r");
568           if (!fp)
569             {
570               perror(fullpath);
571               break;
572             }
573           repo_add_product(pd, repodata, 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 void
590 repo_add_products(Repo *repo, Repodata *repodata, const char *proddir, const char *root, const char *attribute)
591 {
592   const char *fullpath = proddir;
593   DIR *dir;
594   int i;
595   struct parsedata pd;
596   struct stateswitch *sw;
597
598   memset(&pd, 0, sizeof(pd));
599   pd.repo = repo;
600   pd.pool = repo->pool;
601   pd.data = repodata;
602
603   pd.content = malloc(256);
604   pd.acontent = 256;
605
606   pd.attribute = attribute;
607
608   for (i = 0, sw = stateswitches; sw->from != NUMSTATES; i++, sw++)
609     {
610       if (!pd.swtab[sw->from])
611         pd.swtab[sw->from] = sw;
612       pd.sbtab[sw->to] = sw->from;
613     }
614
615   dir = opendir(fullpath);
616   if (dir)
617     {
618       parse_dir(dir, fullpath, &pd, repodata, 1); /* assume 'code11' products */
619       closedir(dir);
620     }
621   else
622     {
623       fullpath = root ? join2(root, "", "/var/lib/zypp/db/products") : "/var/lib/zypp/db/products";
624       dir = opendir(fullpath);
625       if (dir)
626         {
627           repo_add_zyppdb_products(repo, repodata, fullpath, dir); /* assume 'code10' zypp-style products */
628           closedir(dir);
629         }
630       else
631         {
632           fullpath = root ? join2(root, "", "/etc") : "/etc";
633           dir = opendir(fullpath);
634           if (dir)
635             {
636               parse_dir(dir, fullpath, &pd, repodata, 0); /* fall back to /etc/<xyz>-release parsing */
637               closedir(dir);
638             }
639           else
640             {
641               perror(fullpath);
642             }
643         }
644     }
645               
646   sat_free((void *)pd.tmplang);
647   free(pd.content);
648   join_freemem();
649   
650 }
651
652 /* EOF */