aboutsummaryrefslogtreecommitdiff
path: root/src/download.c
blob: 814fe364874e0f1818e63cd1424427737c39aa9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
 
  pow! - the pow!erful package manager

  Copyright (C) 2026 forever2k38
  
  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program. If not, see <https://www.gnu.org/licenses/>.

*/

#include "hash.h"
#include "log.h"
#include "package.h"

#include "curl/curl.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

static size_t write_cb(char *ptr, size_t size, size_t nmemb, void *stream) {
  size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);

  return written;
}

int pow_download_file(char *path, char *url) {
  FILE *pagefile;
  CURL *curl = curl_easy_init();

  if (!curl) {
    pow_log_error("failed to init curl");

    return 1;
  }

  curl_easy_setopt(curl, CURLOPT_URL, url);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
  curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, "pow! (codeberg.org/einfach/pow)");

  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

  pagefile = fopen(path, "wb");

  if (!pagefile) {
    pow_log_error("failed to open file to download");

    curl_easy_cleanup(curl);

    return 1;
  }

  curl_easy_setopt(curl, CURLOPT_WRITEDATA, pagefile);

  CURLcode result = curl_easy_perform(curl);

  curl_easy_cleanup(curl);

  fclose(pagefile);

  return result;
}

int pow_download_source(pow_package_source *src, const char *prefix) {
  size_t len = strlen(prefix) + strlen(src->out) + 2;
  char *full_path = malloc(len);

  snprintf(full_path, len, "%s/%s", prefix, src->out);

  pow_log_info("downloading source file: %s", src->in);

  if (pow_download_file(full_path, src->in)) {
    pow_log_error("failed to download sources, aborting");

    free(full_path);

    return 1;
  }

  if (pow_check_blake2b_hash(full_path, src->hash)) {
    pow_log_error("hash mismatch. something is going wrong with downloading the file "
           "or it may be tampered with.");

    free(full_path);

    return 1;
  }

  pow_log_info("hashes match, %s", src->hash);

  free(full_path);

  return 0;
}