Imported Upstream version 0.6.13
[platform/upstream/libsolv.git] / examples / solv / mirror.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <string.h>
5
6 #include "pool.h"
7 #include "util.h"
8 #include "fastestmirror.h"
9
10 #include "mirror.h"
11
12 char *
13 findmetalinkurl(FILE *fp, unsigned char *chksump, Id *chksumtypep)
14 {
15   char buf[4096], *bp, *ep;
16   char **urls = 0;
17   int nurls = 0;
18   int i;
19
20   if (chksumtypep)
21     *chksumtypep = 0;
22   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
23     {
24       while (*bp == ' ' || *bp == '\t')
25         bp++;
26       if (chksumtypep && !*chksumtypep && !strncmp(bp, "<hash type=\"sha256\">", 20))
27         {
28           bp += 20;
29           if (solv_hex2bin((const char **)&bp, chksump, 32) == 32)
30             *chksumtypep = REPOKEY_TYPE_SHA256;
31           continue;
32         }
33       if (strncmp(bp, "<url", 4))
34         continue;
35       bp = strchr(bp, '>');
36       if (!bp)
37         continue;
38       bp++;
39       ep = strstr(bp, "repodata/repomd.xml</url>");
40       if (!ep)
41         continue;
42       *ep = 0;
43       if (strncmp(bp, "http", 4))
44         continue;
45       urls = solv_extend(urls, nurls, 1, sizeof(*urls), 15);
46       urls[nurls++] = strdup(bp);
47     }
48   if (nurls)
49     {
50       if (nurls > 1)
51         findfastest(urls, nurls > 5 ? 5 : nurls);
52       bp = urls[0];
53       urls[0] = 0;
54       for (i = 0; i < nurls; i++)
55         solv_free(urls[i]);
56       solv_free(urls);
57       ep = strchr(bp, '/');
58       if ((ep = strchr(ep + 2, '/')) != 0)
59         {
60           *ep = 0;
61           printf("[using mirror %s]\n", bp);
62           *ep = '/';
63         }
64       return bp;
65     }
66   return 0;
67 }
68
69 char *
70 findmirrorlisturl(FILE *fp)
71 {
72   char buf[4096], *bp, *ep;
73   int i, l;
74   char **urls = 0;
75   int nurls = 0;
76
77   while((bp = fgets(buf, sizeof(buf), fp)) != 0)
78     {
79       while (*bp == ' ' || *bp == '\t')
80         bp++;
81       if (!*bp || *bp == '#')
82         continue;
83       l = strlen(bp);
84       while (l > 0 && (bp[l - 1] == ' ' || bp[l - 1] == '\t' || bp[l - 1] == '\n'))
85         bp[--l] = 0;
86       if ((ep = strstr(bp, "url=")) != 0)
87         bp = ep + 4;
88       urls = solv_extend(urls, nurls, 1, sizeof(*urls), 15);
89       urls[nurls++] = strdup(bp);
90     }
91   if (nurls)
92     {
93       if (nurls > 1)
94         findfastest(urls, nurls > 5 ? 5 : nurls);
95       bp = urls[0];
96       urls[0] = 0;
97       for (i = 0; i < nurls; i++)
98         solv_free(urls[i]);
99       solv_free(urls);
100       ep = strchr(bp, '/');
101       if ((ep = strchr(ep + 2, '/')) != 0)
102         {
103           *ep = 0;
104           printf("[using mirror %s]\n", bp);
105           *ep = '/';
106         }
107       return bp;
108     }
109   return 0;
110 }