]> git.sesse.net Git - cubemap/blob - util.cpp
Set Connection: close in outgoing HTTP headers.
[cubemap] / util.cpp
1 #include <errno.h>
2 #include <stddef.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6
7 #include "log.h"
8 #include "util.h"
9
10 using namespace std;
11
12 int make_tempfile(const std::string &contents)
13 {
14         char filename[] = "/tmp/cubemap.XXXXXX";
15         int fd = mkstemp(filename);
16         if (fd == -1) {
17                 log_perror("mkstemp");
18                 return -1;
19         }
20
21         if (unlink(filename) == -1) {
22                 log_perror("unlink");
23                 // Can still continue;
24         }
25
26         const char *ptr = contents.data();
27         size_t to_write = contents.size();
28         while (to_write > 0) {
29                 ssize_t ret = write(fd, ptr, to_write);
30                 if (ret == -1) {
31                         log_perror("write");
32                         close(fd);
33                         return -1;
34                 }
35
36                 ptr += ret;
37                 to_write -= ret;
38         }
39
40         return fd;
41 }
42
43 bool read_tempfile_and_close(int fd, std::string *contents)
44 {
45         bool ok = read_tempfile(fd, contents);
46
47         int ret;
48         do {
49                 ret = close(fd);  // Implicitly deletes the file.
50         } while (ret == -1 && errno == EINTR);
51         
52         if (ret == -1) {
53                 log_perror("close");
54                 // Can still continue.
55         }
56
57         return ok;
58 }
59
60 bool read_tempfile(int fd, std::string *contents)
61 {
62         ssize_t ret, has_read;
63
64         off_t len = lseek(fd, 0, SEEK_END);
65         if (len == -1) {
66                 log_perror("lseek");
67                 return false;
68         }
69
70         contents->resize(len);
71
72         if (lseek(fd, 0, SEEK_SET) == -1) {
73                 log_perror("lseek");
74                 return false;
75         }
76
77         has_read = 0;
78         while (has_read < len) {
79                 ret = read(fd, &((*contents)[has_read]), len - has_read);
80                 if (ret == -1) {
81                         log_perror("read");
82                         return false;
83                 }
84                 if (ret == 0) {
85                         log(ERROR, "Unexpected EOF!");
86                         return false;
87                 }
88                 has_read += ret;
89         }
90
91         return true;
92 }