Debian Codegraph @

src/common/oscap_acquire.c

raw symbols SCIP
1 /*
2 * Copyright 2012--2014 Red Hat Inc., Durham, North Carolina.
3 * All Rights Reserved.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 *
19 */
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <string.h>
26 #include <errno.h>
27 #ifdef OS_WINDOWS
28 #include <io.h>
29 #include <direct.h>
30 /* The rand_s function requires constant _CRT_RAND_S to be defined before including <stdlib.h>.
31 * See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/rand-s
32 */
33 #define _CRT_RAND_S
34 #else
35 #include <unistd.h>
36 #include <ftw.h>
37 #endif
38 #include <stdlib.h>
39 #include <limits.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42
43 #include <curl/curl.h>
44 #include <curl/easy.h>
45
46 #include "oscap_acquire.h"
47 #include "common/util.h"
48 #include "common/oscap_buffer.h"
49 #include "common/_error.h"
50 #include "oscap_string.h"
51 #include "oscap_helpers.h"
52 #include "debug_priv.h"
53
54 #ifndef OSCAP_TEMP_DIR
55 #define OSCAP_TEMP_DIR "/tmp"
56 #endif
57
58 #define TEMP_DIR_TEMPLATE OSCAP_TEMP_DIR "/oscap.XXXXXX"
59 #define TEMP_URL_TEMPLATE "downloaded.XXXXXX"
60
61 #ifdef OS_WINDOWS
62 char *oscap_acquire_temp_dir()
63 {
64 WCHAR temp_path[PATH_MAX];
65 WCHAR temp_dir[PATH_MAX];
66
67 DWORD ret = GetTempPathW(PATH_MAX, temp_path);
68 if (ret > PATH_MAX || ret == 0) {
69 oscap_seterr(OSCAP_EFAMILY_WINDOWS, "Could not retrieve the path of the directory for temporary files.");
70 return NULL;
71 }
72
73 unsigned int unique;
74 rand_s(&unique);
75 ret = GetTempFileNameW(temp_path, L"oscap", unique, temp_dir);
76 if (ret == 0) {
77 oscap_seterr(OSCAP_EFAMILY_WINDOWS, "Could not get a name for new temporary directory.");
78 return NULL;
79 }
80 char *temp_dir_str = oscap_windows_wstr_to_str(temp_dir);
81
82 WCHAR *path_prefix = temp_dir;
83 do {
84 /* Use wide characters with L modifier because we work with a wide string. */
85 WCHAR *delimiter = wcschr(path_prefix, L'\\');
86 if (delimiter == NULL) {
87 break;
88 }
89 *delimiter = L'\0';
90 if (!CreateDirectoryW(temp_dir, NULL)) {
91 ret = GetLastError();
92 if (ret != ERROR_ALREADY_EXISTS) {
93 char *error_message = oscap_windows_error_message(ret);
94 oscap_seterr(OSCAP_EFAMILY_WINDOWS, "Could not create temp directory '%s': %s.", temp_dir_str, error_message);
95 free(error_message);
96 free(temp_dir_str);
97 return NULL;
98 }
99 }
100 *delimiter = L'\\';
101 path_prefix = ++delimiter;
102 } while (*path_prefix != L'\0');
103
104 if (!CreateDirectoryW(temp_dir, NULL)) {
105 ret = GetLastError();
106 char *error_message = oscap_windows_error_message(ret);
107 oscap_seterr(OSCAP_EFAMILY_WINDOWS, "Could not create temp directory '%s': %s.", temp_dir_str, error_message);
108 free(error_message);
109 free(temp_dir_str);
110 return NULL;
111 }
112
113 return temp_dir_str;
114 }
115 #else
116 char *oscap_acquire_temp_dir()
117 {
118 char *temp_dir = oscap_strdup(TEMP_DIR_TEMPLATE);
119 if (mkdtemp(temp_dir) == NULL) {
120 free(temp_dir);
121 oscap_seterr(OSCAP_EFAMILY_GLIBC, "Could not create temp directory " TEMP_DIR_TEMPLATE ". %s", strerror(errno));
122 return NULL;
123 }
124 return temp_dir;
125 }
126 #endif
127
128 #ifdef OS_WINDOWS
129 static bool _recursive_delete_directory(WCHAR *directory)
130 {
131 if (directory == NULL) {
132 return false;
133 }
134 WCHAR find_pattern[MAX_PATH];
135 wcsncpy(find_pattern, directory, MAX_PATH);
136 wcsncat(find_pattern, L"\\*", MAX_PATH);
137 WCHAR dir_path[MAX_PATH];
138 wcsncpy(dir_path, directory, MAX_PATH);
139 wcsncat(dir_path, L"\\", MAX_PATH);
140 WCHAR file_path[MAX_PATH];
141 wcsncpy(file_path, dir_path, MAX_PATH);
142 DWORD err;
143
144 WIN32_FIND_DATAW find_data;
145 HANDLE find_handle = FindFirstFileW(find_pattern, &find_data);
146 if (find_handle == INVALID_HANDLE_VALUE) {
147 err = GetLastError();
148 char *error_message = oscap_windows_error_message(err);
149 oscap_seterr(OSCAP_EFAMILY_WINDOWS, "FindFirstFileW error: %s", error_message);
150 free(error_message);
151 return false;
152 }
153
154 do {
155 if (wcscmp(find_data.cFileName, L".") != 0 && wcscmp(find_data.cFileName, L"..") != 0) {
156 wcsncat(file_path, find_data.cFileName, MAX_PATH);
157 if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
158 if (!_recursive_delete_directory(file_path)) {
159 FindClose(find_handle);
160 return false;
161 }
162 } else {
163 if (!DeleteFileW(file_path)) {
164 err = GetLastError();
165 char *error_message = oscap_windows_error_message(err);
166 oscap_seterr(OSCAP_EFAMILY_WINDOWS, "DeleteFileW Error: %s", error_message);
167 free(error_message);
168 FindClose(find_handle);
169 return false;
170 }
171 }
172 wcsncpy(file_path, dir_path, MAX_PATH);
173 }
174 } while (FindNextFileW(find_handle, &find_data) != 0);
175 FindClose(find_handle);
176
177 if (!RemoveDirectoryW(dir_path)) {
178 err = GetLastError();
179 char *error_message = oscap_windows_error_message(err);
180 oscap_seterr(OSCAP_EFAMILY_WINDOWS, "RemoveDirectoryW error: %s", error_message);
181 free(error_message);
182 return false;
183 }
184
185 return true;
186 }
187
188 void oscap_acquire_cleanup_dir(char **dir_path)
189 {
190 if (*dir_path != NULL) {
191 WCHAR *dir_path_wstr = oscap_windows_str_to_wstr(*dir_path);
192 _recursive_delete_directory(dir_path_wstr);
193 free(dir_path_wstr);
194 free(*dir_path);
195 *dir_path = NULL;
196 }
197 }
198 #else
199 static int __unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
200 {
201 int rv = remove(fpath);
202
203 if (rv)
204 oscap_seterr(OSCAP_EFAMILY_GLIBC, "Could not remove %s. %s", fpath, strerror(errno));
205
206 return rv;
207 }
208
209 void oscap_acquire_cleanup_dir(char **dir_path)
210 {
211 if (*dir_path != NULL)
212 {
213 nftw(*dir_path, __unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
214 free(*dir_path);
215 *dir_path = NULL;
216 }
217 }
218 #endif
219
220 int
221 oscap_acquire_temp_file(const char *dir, const char *template, char **filename)
222 {
223 #ifdef OS_WINDOWS
224 int old_mode;
225 #else
226 mode_t old_mode;
227 #endif
228 int fd;
229
230 if (dir == NULL || template == NULL || filename == NULL)
231 return -1;
232
233 *filename = malloc(PATH_MAX * sizeof(char));
234 old_mode = umask(077); /* Override unusual umask. Ensure 0700 permissions. */
235 #ifdef OS_WINDOWS
236 char *base_name = oscap_strdup(template);
237 _mktemp_s(base_name, strlen(base_name) + 1); // +1 for terminator
238 snprintf(*filename, PATH_MAX, "%s/%s", dir, base_name);
239 free(base_name);
240 fd = open(*filename, _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE);
241 #else
242 snprintf(*filename, PATH_MAX, "%s/%s", dir, template);
243 fd = mkstemp(*filename);
244 #endif
245 (void) umask(old_mode);
246 if (fd < 1) {
247 oscap_seterr(OSCAP_EFAMILY_GLIBC, "mkstemp for %s failed: %s", *filename, strerror(errno));
248 free(*filename);
249 *filename = NULL;
250 }
251 return fd;
252 }
253
254 bool
255 oscap_acquire_url_is_supported(const char *url)
256 {
257 return oscap_str_startswith(url, "http://") || oscap_str_startswith(url, "https://");
258 }
259
260 char *
261 oscap_acquire_url_to_filename(const char *url)
262 {
263 /* RFC 3986: 2.1. Percent-Encoding */
264 char *curl_filename = NULL;
265 char *filename = NULL;
266 CURL *curl;
267
268 if (curl_global_init(CURL_GLOBAL_ALL) != 0) {
269 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to initialize libcurl.");
270 return NULL;
271 }
272 curl = curl_easy_init();
273 if (curl == NULL) {
274 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to initialize libcurl.");
275 return NULL;
276 }
277
278 curl_filename = curl_easy_escape(curl , url , 0);
279 if (curl_filename == NULL) {
280 curl_easy_cleanup(curl);
281 curl_global_cleanup();
282 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to escape the given url %s", url);
283 return NULL;
284 }
285 filename = oscap_strdup(curl_filename);
286 curl_free(curl_filename);
287 curl_easy_cleanup(curl);
288 curl_global_cleanup();
289 return filename;
290 }
291
292 static int _curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
293 {
294 const char *title;
295
296 switch (type) {
297 case CURLINFO_TEXT:
298 title = "== cURL info";
299 break;
300 case CURLINFO_HEADER_OUT:
301 title = "=> cURL header (out)";
302 break;
303 case CURLINFO_HEADER_IN:
304 title = "<= cURL header (in)";
305 break;
306 case CURLINFO_DATA_OUT:
307 case CURLINFO_SSL_DATA_OUT:
308 case CURLINFO_DATA_IN:
309 case CURLINFO_SSL_DATA_IN:
310 default:
311 return 0;
312 break;
313 }
314
315 dD("%s: %s", title, data);
316
317 return 0;
318 }
319
320 char* oscap_acquire_url_download(const char *url, size_t* memory_size)
321 {
322 CURL *curl;
323 curl = curl_easy_init();
324 if (curl == NULL) {
325 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to initialize libcurl.");
326 return NULL;
327 }
328
329 CURLcode res;
330
331 /* CURLOPT_FAILONERROR - request failure on HTTP response >= 400 */
332 res = curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
333 if (res != 0) {
334 curl_easy_cleanup(curl);
335 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_FAILONERROR: %s", curl_easy_strerror(res));
336 return NULL;
337 }
338
339 res = curl_easy_setopt(curl, CURLOPT_URL, url);
340 if (res != 0) {
341 curl_easy_cleanup(curl);
342 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_URL to '%s': %s", url, curl_easy_strerror(res));
343 return NULL;
344 }
345
346 res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_memory_callback);
347 if (res != 0) {
348 curl_easy_cleanup(curl);
349 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_WRITEFUNCTION to write_to_memory_callback: %s", curl_easy_strerror(res));
350 return NULL;
351 }
352
353 res = curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "");
354 if (res != 0) {
355 curl_easy_cleanup(curl);
356 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_ACCEPT_ENCODING to an empty string: %s", curl_easy_strerror(res));
357 return NULL;
358 }
359
360 res = curl_easy_setopt(curl, CURLOPT_TRANSFER_ENCODING, true);
361 if (res != 0) {
362 curl_easy_cleanup(curl);
363 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_TRANSFER_ENCODING to true: %s", curl_easy_strerror(res));
364 return NULL;
365 }
366
367 res = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
368 if (res != 0) {
369 curl_easy_cleanup(curl);
370 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_FOLLOWLOCATION to true: %s", curl_easy_strerror(res));
371 return NULL;
372 }
373
374 res = curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
375 if (res != 0) {
376 curl_easy_cleanup(curl);
377 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_VERBOSE to true: %s", curl_easy_strerror(res));
378 return NULL;
379 }
380
381 res = curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, _curl_trace);
382 if (res != 0) {
383 curl_easy_cleanup(curl);
384 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_DEBUGFUNCTION to _curl_trace: %s", curl_easy_strerror(res));
385 return NULL;
386 }
387
388 struct oscap_buffer *buffer = oscap_buffer_new();
389 res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);
390 if (res != 0) {
391 curl_easy_cleanup(curl);
392 oscap_seterr(OSCAP_EFAMILY_NET, "Failed to set CURLOPT_WRITEDATA as buffer: %s", curl_easy_strerror(res));
393 oscap_buffer_free(buffer);
394 return NULL;
395 }
396
397 res = curl_easy_perform(curl);
398
399 if (res != 0) {
400 if (res == CURLE_HTTP_RETURNED_ERROR) {
401 long http_code = 0;
402 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
403 oscap_seterr(OSCAP_EFAMILY_NET, "Download failed: %s: %ld", curl_easy_strerror(res), http_code);
404 } else {
405 oscap_seterr(OSCAP_EFAMILY_NET, "Download failed: %s", curl_easy_strerror(res));
406 }
407 curl_easy_cleanup(curl);
408 oscap_buffer_free(buffer);
409 return NULL;
410 }
411
412 curl_easy_cleanup(curl);
413
414 *memory_size = oscap_buffer_get_length(buffer);
415 char* data = oscap_buffer_bequeath(buffer); // get data and free buffer struct
416 return data;
417 }
418
419 size_t write_to_memory_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
420 {
421 size_t new_received_size = size * nmemb; // total size of newly received data
422 oscap_buffer_append_binary_data((struct oscap_buffer*)userdata, ptr, new_received_size);
423 return new_received_size;
424 }
425
426 char *
427 oscap_acquire_pipe_to_string(int fd)
428 {
429 struct oscap_string *pipe_string = oscap_string_new();
430
431 char readbuf;
432 // FIXME: Read by larger chunks in the future
433 while (read(fd, &readbuf, 1) > 0) {
434
435 if (readbuf == '&') {
436 // & is a special case, we have to "escape" it manually
437 // (all else will eventually get handled by libxml)
438 oscap_string_append_string(pipe_string, "&amp;");
439 } else {
440 oscap_string_append_char(pipe_string, readbuf);
441 }
442 }
443
444 close(fd);
445 return oscap_string_bequeath(pipe_string);
446 }
447
448 char *oscap_acquire_guess_realpath(const char *filepath)
449 {
450 char resolved_name[PATH_MAX];
451
452 char *rpath = oscap_realpath(filepath, resolved_name);
453 if (rpath != NULL)
454 rpath = oscap_strdup(rpath);
455 else {
456 // file does not exists, let's try to guess realpath
457 // this is not 100% correct, but it is good enough
458 char *copy = oscap_strdup(filepath);
459 if (copy == NULL) {
460 oscap_seterr(OSCAP_EFAMILY_OSCAP, "Cannot guess realpath for %s, directory: cannot allocate memory!", filepath);
461 return NULL;
462 }
463
464 char *dir_name = oscap_dirname(copy);
465 char *real_dir = oscap_realpath(dir_name, resolved_name);
466 if (real_dir == NULL) {
467 oscap_seterr(OSCAP_EFAMILY_OSCAP, "Cannot guess realpath for %s, directory: %s does not exists!", filepath, dir_name);
468 free(copy);
469 free(dir_name);
470 return NULL;
471 }
472 free(dir_name);
473 char *base_name = oscap_basename((char *)filepath);
474 rpath = oscap_sprintf("%s/%s", real_dir, base_name);
475 free(base_name);
476 free(copy);
477 }
478 return rpath;
479 }
480
481 int oscap_acquire_mkdir_p(const char *path)
482 {
483 // NOTE: This assumes a UNIX VFS path, C:\\folder\\folder would break it!
484
485 if (strlen(path) > PATH_MAX) {
486 return -1;
487 }
488 else {
489 char temp[PATH_MAX + 1]; // +1 for \0
490 unsigned int i;
491
492 for (i = 0; i <= strlen(path); i++) {
493 if (path[i] == '/' || path[i] == '\0') {
494 strncpy(temp, path, i);
495 temp[i] = '\0';
496
497 // skip leading '/', we will never be creating the root anyway
498 if (strlen(temp) == 0)
499 continue;
500
501 #ifndef OS_WINDOWS
502 if (mkdir(temp, S_IRWXU) != 0 && errno != EEXIST) {
503 #else
504 if (mkdir(temp) != 0 && errno != EEXIST) {
505 #endif
506 oscap_seterr(OSCAP_EFAMILY_GLIBC,
507 "Error making directory '%s', while doing recursive mkdir for '%s', error was '%s'.",
508 temp, path, strerror(errno));
509 return -1;
510 }
511 }
512 }
513
514 return 0;
515 }
516 }
517
518 int oscap_acquire_ensure_parent_dir(const char *filepath)
519 {
520 char *filepath_cpy = oscap_strdup(filepath);
521 char *dirpath = oscap_dirname(filepath_cpy);
522 int ret = oscap_acquire_mkdir_p(dirpath);
523 if (ret != 0) {
524 oscap_seterr(OSCAP_EFAMILY_GLIBC, "Error making directory '%s' to ensure correct path of '%s'.", dirpath, filepath);
525 }
526 free(dirpath);
527 free(filepath_cpy);
528 return ret;
529 }