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