tool_operate: Moved required argument getting into separate function
[platform/upstream/curl.git] / src / tool_metalink.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 #include "tool_setup.h"
23
24 #ifdef USE_METALINK
25
26 #include <sys/stat.h>
27
28 #ifdef HAVE_FCNTL_H
29 #  include <fcntl.h>
30 #endif
31
32 #ifdef USE_SSLEAY
33 #  ifdef USE_OPENSSL
34 #    include <openssl/md5.h>
35 #    include <openssl/sha.h>
36 #  else
37 #    include <md5.h>
38 #    include <sha.h>
39 #  endif
40 #elif defined(USE_GNUTLS_NETTLE)
41 #  include <nettle/md5.h>
42 #  include <nettle/sha.h>
43 #  define MD5_CTX    struct md5_ctx
44 #  define SHA_CTX    struct sha1_ctx
45 #  define SHA256_CTX struct sha256_ctx
46 #elif defined(USE_GNUTLS)
47 #  include <gcrypt.h>
48 #  define MD5_CTX    gcry_md_hd_t
49 #  define SHA_CTX    gcry_md_hd_t
50 #  define SHA256_CTX gcry_md_hd_t
51 #elif defined(USE_NSS)
52 #  include <nss.h>
53 #  include <pk11pub.h>
54 #  define MD5_CTX    void *
55 #  define SHA_CTX    void *
56 #  define SHA256_CTX void *
57    static NSSInitContext *nss_context;
58 #elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \
59               (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040)) || \
60       (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \
61               (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000))
62 /* For Apple operating systems: CommonCrypto has the functions we need.
63    The library's headers are even backward-compatible with OpenSSL's
64    headers as long as we define COMMON_DIGEST_FOR_OPENSSL first.
65
66    These functions are available on Tiger and later, as well as iOS 2.0
67    and later. If you're building for an older cat, well, sorry. */
68 #  define COMMON_DIGEST_FOR_OPENSSL
69 #  include <CommonCrypto/CommonDigest.h>
70 #elif defined(_WIN32)
71 /* For Windows: If no other crypto library is provided, we fallback
72    to the hash functions provided within the Microsoft Windows CryptoAPI */
73 #  include <wincrypt.h>
74 /* Custom structure in order to store the required provider and hash handle */
75 struct win32_crypto_hash {
76   HCRYPTPROV hCryptProv;
77   HCRYPTHASH hHash;
78 };
79 /* Custom Microsoft AES Cryptographic Provider defines required for MinGW */
80 #  ifndef ALG_SID_SHA_256
81 #    define ALG_SID_SHA_256  12
82 #  endif
83 #  ifndef CALG_SHA_256
84 #    define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
85 #  endif
86 #  define MD5_CTX    struct win32_crypto_hash
87 #  define SHA_CTX    struct win32_crypto_hash
88 #  define SHA256_CTX struct win32_crypto_hash
89 #else
90 #  error "Can't compile METALINK support without a crypto library."
91 #endif
92
93 #include "rawstr.h"
94
95 #define ENABLE_CURLX_PRINTF
96 /* use our own printf() functions */
97 #include "curlx.h"
98
99 #include "tool_getparam.h"
100 #include "tool_paramhlp.h"
101 #include "tool_cfgable.h"
102 #include "tool_metalink.h"
103 #include "tool_msgs.h"
104
105 #include "memdebug.h" /* keep this as LAST include */
106
107 /* Copied from tool_getparam.c */
108 #define GetStr(str,val) do { \
109   if(*(str)) { \
110     free(*(str)); \
111     *(str) = NULL; \
112   } \
113   if((val)) \
114     *(str) = strdup((val)); \
115   if(!(val)) \
116     return PARAM_NO_MEM; \
117 } WHILE_FALSE
118
119 #ifdef USE_GNUTLS_NETTLE
120
121 static int MD5_Init(MD5_CTX *ctx)
122 {
123   md5_init(ctx);
124   return 1;
125 }
126
127 static void MD5_Update(MD5_CTX *ctx,
128                        const unsigned char *input,
129                        unsigned int inputLen)
130 {
131   md5_update(ctx, inputLen, input);
132 }
133
134 static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
135 {
136   md5_digest(ctx, 16, digest);
137 }
138
139 static int SHA1_Init(SHA_CTX *ctx)
140 {
141   sha1_init(ctx);
142   return 1;
143 }
144
145 static void SHA1_Update(SHA_CTX *ctx,
146                         const unsigned char *input,
147                         unsigned int inputLen)
148 {
149   sha1_update(ctx, inputLen, input);
150 }
151
152 static void SHA1_Final(unsigned char digest[20], SHA_CTX *ctx)
153 {
154   sha1_digest(ctx, 20, digest);
155 }
156
157 static int SHA256_Init(SHA256_CTX *ctx)
158 {
159   sha256_init(ctx);
160   return 1;
161 }
162
163 static void SHA256_Update(SHA256_CTX *ctx,
164                           const unsigned char *input,
165                           unsigned int inputLen)
166 {
167   sha256_update(ctx, inputLen, input);
168 }
169
170 static void SHA256_Final(unsigned char digest[32], SHA256_CTX *ctx)
171 {
172   sha256_digest(ctx, 32, digest);
173 }
174
175 #elif defined(USE_GNUTLS)
176
177 static int MD5_Init(MD5_CTX *ctx)
178 {
179   gcry_md_open(ctx, GCRY_MD_MD5, 0);
180   return 1;
181 }
182
183 static void MD5_Update(MD5_CTX *ctx,
184                        const unsigned char *input,
185                        unsigned int inputLen)
186 {
187   gcry_md_write(*ctx, input, inputLen);
188 }
189
190 static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
191 {
192   memcpy(digest, gcry_md_read(*ctx, 0), 16);
193   gcry_md_close(*ctx);
194 }
195
196 static int SHA1_Init(SHA_CTX *ctx)
197 {
198   gcry_md_open(ctx, GCRY_MD_SHA1, 0);
199   return 1;
200 }
201
202 static void SHA1_Update(SHA_CTX *ctx,
203                         const unsigned char *input,
204                         unsigned int inputLen)
205 {
206   gcry_md_write(*ctx, input, inputLen);
207 }
208
209 static void SHA1_Final(unsigned char digest[20], SHA_CTX *ctx)
210 {
211   memcpy(digest, gcry_md_read(*ctx, 0), 20);
212   gcry_md_close(*ctx);
213 }
214
215 static int SHA256_Init(SHA256_CTX *ctx)
216 {
217   gcry_md_open(ctx, GCRY_MD_SHA256, 0);
218   return 1;
219 }
220
221 static void SHA256_Update(SHA256_CTX *ctx,
222                           const unsigned char *input,
223                           unsigned int inputLen)
224 {
225   gcry_md_write(*ctx, input, inputLen);
226 }
227
228 static void SHA256_Final(unsigned char digest[32], SHA256_CTX *ctx)
229 {
230   memcpy(digest, gcry_md_read(*ctx, 0), 32);
231   gcry_md_close(*ctx);
232 }
233
234 #elif defined(USE_NSS)
235
236 static int nss_hash_init(void **pctx, SECOidTag hash_alg)
237 {
238   PK11Context *ctx;
239
240   /* we have to initialize NSS if not initialized alraedy */
241   if(!NSS_IsInitialized() && !nss_context) {
242     static NSSInitParameters params;
243     params.length = sizeof params;
244     nss_context = NSS_InitContext("", "", "", "", &params, NSS_INIT_READONLY
245         | NSS_INIT_NOCERTDB   | NSS_INIT_NOMODDB       | NSS_INIT_FORCEOPEN
246         | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
247   }
248
249   ctx = PK11_CreateDigestContext(hash_alg);
250   if(!ctx)
251     return /* failure */ 0;
252
253   if(PK11_DigestBegin(ctx) != SECSuccess) {
254     PK11_DestroyContext(ctx, PR_TRUE);
255     return /* failure */ 0;
256   }
257
258   *pctx = ctx;
259   return /* success */ 1;
260 }
261
262 static void nss_hash_final(void **pctx, unsigned char *out, unsigned int len)
263 {
264   PK11Context *ctx = *pctx;
265   unsigned int outlen;
266   PK11_DigestFinal(ctx, out, &outlen, len);
267   PK11_DestroyContext(ctx, PR_TRUE);
268 }
269
270 static int MD5_Init(MD5_CTX *pctx)
271 {
272   return nss_hash_init(pctx, SEC_OID_MD5);
273 }
274
275 static void MD5_Update(MD5_CTX *pctx,
276                        const unsigned char *input,
277                        unsigned int input_len)
278 {
279   PK11_DigestOp(*pctx, input, input_len);
280 }
281
282 static void MD5_Final(unsigned char digest[16], MD5_CTX *pctx)
283 {
284   nss_hash_final(pctx, digest, 16);
285 }
286
287 static int SHA1_Init(SHA_CTX *pctx)
288 {
289   return nss_hash_init(pctx, SEC_OID_SHA1);
290 }
291
292 static void SHA1_Update(SHA_CTX *pctx,
293                         const unsigned char *input,
294                         unsigned int input_len)
295 {
296   PK11_DigestOp(*pctx, input, input_len);
297 }
298
299 static void SHA1_Final(unsigned char digest[20], SHA_CTX *pctx)
300 {
301   nss_hash_final(pctx, digest, 20);
302 }
303
304 static int SHA256_Init(SHA256_CTX *pctx)
305 {
306   return nss_hash_init(pctx, SEC_OID_SHA256);
307 }
308
309 static void SHA256_Update(SHA256_CTX *pctx,
310                           const unsigned char *input,
311                           unsigned int input_len)
312 {
313   PK11_DigestOp(*pctx, input, input_len);
314 }
315
316 static void SHA256_Final(unsigned char digest[32], SHA256_CTX *pctx)
317 {
318   nss_hash_final(pctx, digest, 32);
319 }
320
321 #elif defined(_WIN32) && !defined(USE_SSLEAY)
322
323 static void win32_crypto_final(struct win32_crypto_hash *ctx,
324                                unsigned char *digest,
325                                unsigned int digestLen)
326 {
327   unsigned long length;
328   CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0);
329   if(length == digestLen)
330     CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0);
331   if(ctx->hHash)
332     CryptDestroyHash(ctx->hHash);
333   if(ctx->hCryptProv)
334     CryptReleaseContext(ctx->hCryptProv, 0);
335 }
336
337 static int MD5_Init(MD5_CTX *ctx)
338 {
339   if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL,
340                          PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
341     CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash);
342   }
343   return 1;
344 }
345
346 static void MD5_Update(MD5_CTX *ctx,
347                        const unsigned char *input,
348                        unsigned int inputLen)
349 {
350   CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
351 }
352
353 static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
354 {
355   win32_crypto_final(ctx, digest, 16);
356 }
357
358 static int SHA1_Init(SHA_CTX *ctx)
359 {
360   if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL,
361                          PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
362     CryptCreateHash(ctx->hCryptProv, CALG_SHA1, 0, 0, &ctx->hHash);
363   }
364   return 1;
365 }
366
367 static void SHA1_Update(SHA_CTX *ctx,
368                         const unsigned char *input,
369                         unsigned int inputLen)
370 {
371   CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
372 }
373
374 static void SHA1_Final(unsigned char digest[20], SHA_CTX *ctx)
375 {
376   win32_crypto_final(ctx, digest, 20);
377 }
378
379 static int SHA256_Init(SHA256_CTX *ctx)
380 {
381   if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL,
382                          PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
383     CryptCreateHash(ctx->hCryptProv, CALG_SHA_256, 0, 0, &ctx->hHash);
384   }
385   return 1;
386 }
387
388 static void SHA256_Update(SHA256_CTX *ctx,
389                           const unsigned char *input,
390                           unsigned int inputLen)
391 {
392   CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
393 }
394
395 static void SHA256_Final(unsigned char digest[32], SHA256_CTX *ctx)
396 {
397   win32_crypto_final(ctx, digest, 32);
398 }
399
400 #endif /* CRYPTO LIBS */
401
402 const digest_params MD5_DIGEST_PARAMS[] = {
403   {
404     (Curl_digest_init_func) MD5_Init,
405     (Curl_digest_update_func) MD5_Update,
406     (Curl_digest_final_func) MD5_Final,
407     sizeof(MD5_CTX),
408     16
409   }
410 };
411
412 const digest_params SHA1_DIGEST_PARAMS[] = {
413   {
414     (Curl_digest_init_func) SHA1_Init,
415     (Curl_digest_update_func) SHA1_Update,
416     (Curl_digest_final_func) SHA1_Final,
417     sizeof(SHA_CTX),
418     20
419   }
420 };
421
422 const digest_params SHA256_DIGEST_PARAMS[] = {
423   {
424     (Curl_digest_init_func) SHA256_Init,
425     (Curl_digest_update_func) SHA256_Update,
426     (Curl_digest_final_func) SHA256_Final,
427     sizeof(SHA256_CTX),
428     32
429   }
430 };
431
432 static const metalink_digest_def SHA256_DIGEST_DEF[] = {
433   {"sha-256", SHA256_DIGEST_PARAMS}
434 };
435
436 static const metalink_digest_def SHA1_DIGEST_DEF[] = {
437   {"sha-1", SHA1_DIGEST_PARAMS}
438 };
439
440 static const metalink_digest_def MD5_DIGEST_DEF[] = {
441   {"md5", MD5_DIGEST_PARAMS}
442 };
443
444 /*
445  * The alias of supported hash functions in the order by preference
446  * (basically stronger hash comes first). We included "sha-256" and
447  * "sha256". The former is the name defined in the IANA registry named
448  * "Hash Function Textual Names". The latter is widely (and
449  * historically) used in Metalink version 3.
450  */
451 static const metalink_digest_alias digest_aliases[] = {
452   {"sha-256", SHA256_DIGEST_DEF},
453   {"sha256", SHA256_DIGEST_DEF},
454   {"sha-1", SHA1_DIGEST_DEF},
455   {"sha1", SHA1_DIGEST_DEF},
456   {"md5", MD5_DIGEST_DEF},
457   {NULL, NULL}
458 };
459
460 digest_context *Curl_digest_init(const digest_params *dparams)
461 {
462   digest_context *ctxt;
463
464   /* Create digest context */
465   ctxt = malloc(sizeof *ctxt);
466
467   if(!ctxt)
468     return ctxt;
469
470   ctxt->digest_hashctx = malloc(dparams->digest_ctxtsize);
471
472   if(!ctxt->digest_hashctx) {
473     free(ctxt);
474     return NULL;
475   }
476
477   ctxt->digest_hash = dparams;
478
479   if(dparams->digest_init(ctxt->digest_hashctx) != 1) {
480     free(ctxt);
481     return NULL;
482   }
483
484   return ctxt;
485 }
486
487 int Curl_digest_update(digest_context *context,
488                        const unsigned char *data,
489                        unsigned int len)
490 {
491   (*context->digest_hash->digest_update)(context->digest_hashctx, data, len);
492
493   return 0;
494 }
495
496 int Curl_digest_final(digest_context *context, unsigned char *result)
497 {
498   (*context->digest_hash->digest_final)(result, context->digest_hashctx);
499
500   free(context->digest_hashctx);
501   free(context);
502
503   return 0;
504 }
505
506 static unsigned char hex_to_uint(const char *s)
507 {
508   int v[2];
509   int i;
510   for(i = 0; i < 2; ++i) {
511     v[i] = Curl_raw_toupper(s[i]);
512     if('0' <= v[i] && v[i] <= '9') {
513       v[i] -= '0';
514     }
515     else if('A' <= v[i] && v[i] <= 'Z') {
516       v[i] -= 'A'-10;
517     }
518   }
519   return (unsigned char)((v[0] << 4) | v[1]);
520 }
521
522 /*
523  * Check checksum of file denoted by filename. The expected hash value
524  * is given in hex_hash which is hex-encoded string.
525  *
526  * This function returns 1 if it succeeds or one of the following
527  * integers:
528  *
529  * 0:
530  *   Checksum didn't match.
531  * -1:
532  *   Could not open file; or could not read data from file.
533  * -2:
534  *   Hash algorithm not available.
535  */
536 static int check_hash(const char *filename,
537                       const metalink_digest_def *digest_def,
538                       const unsigned char *digest, FILE *error)
539 {
540   unsigned char *result;
541   digest_context *dctx;
542   int check_ok, flags, fd;
543
544   flags = O_RDONLY;
545 #ifdef O_BINARY
546   /* O_BINARY is required in order to avoid binary EOF in text mode */
547   flags |= O_BINARY;
548 #endif
549
550   fd = open(filename, flags);
551   if(fd == -1) {
552     fprintf(error, "Metalink: validating (%s) [%s] FAILED (%s)\n", filename,
553             digest_def->hash_name, strerror(errno));
554     return -1;
555   }
556
557   dctx = Curl_digest_init(digest_def->dparams);
558   if(!dctx) {
559     fprintf(error, "Metalink: validating (%s) [%s] FAILED (%s)\n", filename,
560             digest_def->hash_name, "failed to initialize hash algorithm");
561     close(fd);
562     return -2;
563   }
564
565   result = malloc(digest_def->dparams->digest_resultlen);
566   while(1) {
567     unsigned char buf[4096];
568     ssize_t len = read(fd, buf, sizeof(buf));
569     if(len == 0) {
570       break;
571     }
572     else if(len == -1) {
573       fprintf(error, "Metalink: validating (%s) [%s] FAILED (%s)\n", filename,
574               digest_def->hash_name, strerror(errno));
575       Curl_digest_final(dctx, result);
576       close(fd);
577       return -1;
578     }
579     Curl_digest_update(dctx, buf, (unsigned int)len);
580   }
581   Curl_digest_final(dctx, result);
582   check_ok = memcmp(result, digest,
583                     digest_def->dparams->digest_resultlen) == 0;
584   /* sha*sum style verdict output */
585   if(check_ok)
586     fprintf(error, "Metalink: validating (%s) [%s] OK\n", filename,
587             digest_def->hash_name);
588   else
589     fprintf(error, "Metalink: validating (%s) [%s] FAILED (digest mismatch)\n",
590             filename, digest_def->hash_name);
591
592   free(result);
593   close(fd);
594   return check_ok;
595 }
596
597 int metalink_check_hash(struct Configurable *config,
598                         metalinkfile *mlfile,
599                         const char *filename)
600 {
601   int rv;
602   fprintf(config->errors, "Metalink: validating (%s)...\n", filename);
603   if(mlfile->checksum == NULL) {
604     fprintf(config->errors,
605             "Metalink: validating (%s) FAILED (digest missing)\n",
606             filename);
607     return -2;
608   }
609   rv = check_hash(filename, mlfile->checksum->digest_def,
610                   mlfile->checksum->digest, config->errors);
611   return rv;
612 }
613
614 static metalink_checksum *new_metalink_checksum_from_hex_digest
615 (const metalink_digest_def *digest_def, const char *hex_digest)
616 {
617   metalink_checksum *chksum;
618   unsigned char *digest;
619   size_t i;
620   size_t len = strlen(hex_digest);
621   digest = malloc(len/2);
622   for(i = 0; i < len; i += 2) {
623     digest[i/2] = hex_to_uint(hex_digest+i);
624   }
625   chksum = malloc(sizeof(metalink_checksum));
626   chksum->digest_def = digest_def;
627   chksum->digest = digest;
628   return chksum;
629 }
630
631 static metalink_resource *new_metalink_resource(const char *url)
632 {
633   metalink_resource *res;
634   res = malloc(sizeof(metalink_resource));
635   res->next = NULL;
636   res->url = strdup(url);
637   return res;
638 }
639
640 /* Returns nonzero if hex_digest is properly formatted; that is each
641    letter is in [0-9A-Za-z] and the length of the string equals to the
642    result length of digest * 2. */
643 static int check_hex_digest(const char *hex_digest,
644                             const metalink_digest_def *digest_def)
645 {
646   size_t i;
647   for(i = 0; hex_digest[i]; ++i) {
648     char c = hex_digest[i];
649     if(!(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') ||
650          ('A' <= c && c <= 'Z'))) {
651       return 0;
652     }
653   }
654   return digest_def->dparams->digest_resultlen * 2 == i;
655 }
656
657 static metalinkfile *new_metalinkfile(metalink_file_t *fileinfo)
658 {
659   metalinkfile *f;
660   f = (metalinkfile*)malloc(sizeof(metalinkfile));
661   f->next = NULL;
662   f->filename = strdup(fileinfo->name);
663   f->checksum = NULL;
664   f->resource = NULL;
665   if(fileinfo->checksums) {
666     const metalink_digest_alias *digest_alias;
667     for(digest_alias = digest_aliases; digest_alias->alias_name;
668         ++digest_alias) {
669       metalink_checksum_t **p;
670       for(p = fileinfo->checksums; *p; ++p) {
671         if(Curl_raw_equal(digest_alias->alias_name, (*p)->type) &&
672            check_hex_digest((*p)->hash, digest_alias->digest_def)) {
673           f->checksum =
674             new_metalink_checksum_from_hex_digest(digest_alias->digest_def,
675                                                   (*p)->hash);
676           break;
677         }
678       }
679       if(f->checksum) {
680         break;
681       }
682     }
683   }
684   if(fileinfo->resources) {
685     metalink_resource_t **p;
686     metalink_resource root, *tail;
687     root.next = NULL;
688     tail = &root;
689     for(p = fileinfo->resources; *p; ++p) {
690       metalink_resource *res;
691       /* Filter by type if it is non-NULL. In Metalink v3, type
692          includes the type of the resource. In curl, we are only
693          interested in HTTP, HTTPS and FTP. In addition to them,
694          Metalink v3 file may contain bittorrent type URL, which
695          points to the BitTorrent metainfo file. We ignore it here.
696          In Metalink v4, type was deprecated and all
697          fileinfo->resources point to the target file. BitTorrent
698          metainfo file URL may be appeared in fileinfo->metaurls.
699       */
700       if((*p)->type == NULL ||
701          Curl_raw_equal((*p)->type, "http") ||
702          Curl_raw_equal((*p)->type, "https") ||
703          Curl_raw_equal((*p)->type, "ftp") ||
704          Curl_raw_equal((*p)->type, "ftps")) {
705         res = new_metalink_resource((*p)->url);
706         tail->next = res;
707         tail = res;
708       }
709     }
710     f->resource = root.next;
711   }
712   return f;
713 }
714
715 int parse_metalink(struct Configurable *config, struct OutStruct *outs,
716                    const char *metalink_url)
717 {
718   metalink_error_t r;
719   metalink_t* metalink;
720   metalink_file_t **files;
721   bool warnings = FALSE;
722
723   /* metlaink_parse_final deletes outs->metalink_parser */
724   r = metalink_parse_final(outs->metalink_parser, NULL, 0, &metalink);
725   outs->metalink_parser = NULL;
726   if(r != 0) {
727     return -1;
728   }
729   if(metalink->files == NULL) {
730     fprintf(config->errors, "Metalink: parsing (%s) WARNING "
731             "(missing or invalid file name)\n",
732             metalink_url);
733     metalink_delete(metalink);
734     return -1;
735   }
736   for(files = metalink->files; *files; ++files) {
737     struct getout *url;
738     /* Skip an entry which has no resource. */
739     if(!(*files)->resources) {
740       fprintf(config->errors, "Metalink: parsing (%s) WARNING "
741               "(missing or invalid resource)\n",
742               metalink_url, (*files)->name);
743       continue;
744     }
745     if(config->url_get ||
746        ((config->url_get = config->url_list) != NULL)) {
747       /* there's a node here, if it already is filled-in continue to
748          find an "empty" node */
749       while(config->url_get && (config->url_get->flags & GETOUT_URL))
750         config->url_get = config->url_get->next;
751     }
752
753     /* now there might or might not be an available node to fill in! */
754
755     if(config->url_get)
756       /* existing node */
757       url = config->url_get;
758     else
759       /* there was no free node, create one! */
760       url = new_getout(config);
761
762     if(url) {
763       metalinkfile *mlfile;
764       mlfile = new_metalinkfile(*files);
765       if(!mlfile->checksum) {
766         warnings = TRUE;
767         fprintf(config->errors, "Metalink: parsing (%s) WARNING "
768                 "(digest missing)\n",
769                 metalink_url);
770       }
771       /* Set name as url */
772       GetStr(&url->url, mlfile->filename);
773
774       /* set flag metalink here */
775       url->flags |= GETOUT_URL | GETOUT_METALINK;
776
777       if(config->metalinkfile_list) {
778         config->metalinkfile_last->next = mlfile;
779         config->metalinkfile_last = mlfile;
780       }
781       else {
782         config->metalinkfile_list = config->metalinkfile_last = mlfile;
783       }
784     }
785   }
786   metalink_delete(metalink);
787   return (warnings) ? -2 : 0;
788 }
789
790 size_t metalink_write_cb(void *buffer, size_t sz, size_t nmemb,
791                          void *userdata)
792 {
793   struct OutStruct *outs = userdata;
794   struct Configurable *config = outs->config;
795   int rv;
796
797   /*
798    * Once that libcurl has called back tool_write_cb() the returned value
799    * is checked against the amount that was intended to be written, if
800    * it does not match then it fails with CURLE_WRITE_ERROR. So at this
801    * point returning a value different from sz*nmemb indicates failure.
802    */
803   const size_t failure = (sz * nmemb) ? 0 : 1;
804
805   if(!config)
806     return failure;
807
808   rv = metalink_parse_update(outs->metalink_parser, buffer, sz *nmemb);
809   if(rv == 0)
810     return sz * nmemb;
811   else {
812     fprintf(config->errors, "Metalink: parsing FAILED\n");
813     return failure;
814   }
815 }
816
817 /*
818  * Returns nonzero if content_type includes mediatype.
819  */
820 static int check_content_type(const char *content_type, const char *media_type)
821 {
822   const char *ptr = content_type;
823   size_t media_type_len = strlen(media_type);
824   for(; *ptr && (*ptr == ' ' || *ptr == '\t'); ++ptr);
825   if(!*ptr) {
826     return 0;
827   }
828   return Curl_raw_nequal(ptr, media_type, media_type_len) &&
829     (*(ptr+media_type_len) == '\0' || *(ptr+media_type_len) == ' ' ||
830      *(ptr+media_type_len) == '\t' || *(ptr+media_type_len) == ';');
831 }
832
833 int check_metalink_content_type(const char *content_type)
834 {
835   return check_content_type(content_type, "application/metalink+xml");
836 }
837
838 int count_next_metalink_resource(metalinkfile *mlfile)
839 {
840   int count = 0;
841   metalink_resource *res;
842   for(res = mlfile->resource; res; res = res->next, ++count);
843   return count;
844 }
845
846 static void delete_metalink_checksum(metalink_checksum *chksum)
847 {
848   if(chksum == NULL) {
849     return;
850   }
851   Curl_safefree(chksum->digest);
852   Curl_safefree(chksum);
853 }
854
855 static void delete_metalink_resource(metalink_resource *res)
856 {
857   if(res == NULL) {
858     return;
859   }
860   Curl_safefree(res->url);
861   Curl_safefree(res);
862 }
863
864 static void delete_metalinkfile(metalinkfile *mlfile)
865 {
866   metalink_resource *res;
867   if(mlfile == NULL) {
868     return;
869   }
870   Curl_safefree(mlfile->filename);
871   delete_metalink_checksum(mlfile->checksum);
872   for(res = mlfile->resource; res;) {
873     metalink_resource *next;
874     next = res->next;
875     delete_metalink_resource(res);
876     res = next;
877   }
878   Curl_safefree(mlfile);
879 }
880
881 void clean_metalink(struct Configurable *config)
882 {
883   while(config->metalinkfile_list) {
884     metalinkfile *mlfile = config->metalinkfile_list;
885     config->metalinkfile_list = config->metalinkfile_list->next;
886     delete_metalinkfile(mlfile);
887   }
888   config->metalinkfile_last = 0;
889 }
890
891 void metalink_cleanup(void)
892 {
893 #ifdef USE_NSS
894   if(nss_context) {
895     NSS_ShutdownContext(nss_context);
896     nss_context = NULL;
897   }
898 #endif
899 }
900
901 #endif /* USE_METALINK */