Version 5.2.6.1, tag libreoffice-5.2.6.1
[LibreOffice.git] / onlineupdate / source / update / src / mar_extract.c
blob75cbd645f29647523a0b0bfc30e946ee87baf1f6
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include "mar_private.h"
13 #include "mar.h"
15 #ifdef _WIN32
16 #include <io.h>
17 #include <direct.h>
18 #endif
20 /* Ensure that the directory containing this file exists */
21 static int mar_ensure_parent_dir(const char *path)
23 char *slash = strrchr(path, '/');
24 if (slash)
26 *slash = '\0';
27 mar_ensure_parent_dir(path);
28 #ifdef _WIN32
29 _mkdir(path);
30 #else
31 mkdir(path, 0755);
32 #endif
33 *slash = '/';
35 return 0;
38 static int mar_test_callback(MarFile *mar, const MarItem *item, void *unused) {
39 FILE *fp;
40 char buf[BLOCKSIZE];
41 int fd, len, offset = 0;
43 (void) unused; // avoid warnings
45 if (mar_ensure_parent_dir(item->name))
46 return -1;
48 #ifdef _WIN32
49 fd = _open(item->name, _O_BINARY|_O_CREAT|_O_TRUNC|_O_WRONLY, item->flags);
50 #else
51 fd = creat(item->name, item->flags);
52 #endif
53 if (fd == -1) {
54 fprintf(stderr, "ERROR: could not create file in mar_test_callback()\n");
55 perror(item->name);
56 return -1;
59 fp = fdopen(fd, "wb");
60 if (!fp)
61 return -1;
63 while ((len = mar_read(mar, item, offset, buf, sizeof(buf))) > 0) {
64 if (fwrite(buf, len, 1, fp) != 1)
65 break;
66 offset += len;
69 fclose(fp);
70 return len == 0 ? 0 : -1;
73 int mar_extract(const char *path) {
74 MarFile *mar;
75 int rv;
77 mar = mar_open(path);
78 if (!mar)
79 return -1;
81 rv = mar_enum_items(mar, mar_test_callback, NULL);
83 mar_close(mar);
84 return rv;