summaryrefslogtreecommitdiff
path: root/src/multipart-replace.c
blob: 658d634b15201a91482fbe621cd8154c0c299185 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/* multipart-replace.c - handle mixed/x-multipart-replace streams
 *
 * Copyright (C) 2016  Luke Shumaker
 *
 * 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 3 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 <http://www.gnu.org/licenses/>.
 */

#include <errno.h>
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "multipart-replace.h"
#include "util.h"

#define threaderror(stat, errnum, ...) do { \
		error(0, errnum, __VA_ARGS__); \
		ret = stat; \
		goto end; \
	} while(0)
#define stdioerror(stream, name) do {	  \
		if (feof(stream)) { \
			error(0, 0, "%s: EOF", name); \
		} else { \
			if (ferror(stream)) { \
				fflush(stream); \
				error(0, errno, "%s", name); \
			} else { \
				error(0, 0, "%s: panic: neither feof nor ferror", name); \
			} \
			ret = EXIT_FAILURE; \
		} \
		goto end; \
	} while(0)

static
char *boundary_line(const char *old) {
	size_t len = strlen(old);
	char *new = xrealloc(NULL, len+5);
	new[0] = '-';
	new[1] = '-';
	strcpy(&new[2], old);
	new[2+len+0] = '\r';
	new[2+len+1] = '\n';
	new[2+len+2] = '\0';
	return new;
}

static
ssize_t safe_atoi(char *str) {
	while (*str == ' ')
		str++;
	size_t len = 0;
	while ('0' <= str[len] && str[len] <= '9')
		len++;
	size_t i = len;
	while (str[i] == ' ')
		i++;
	if (len < 1 || strcmp(&str[i], "\r\n") != 0)
		return -1;
	return atoi(str);
}

int multipart_replace_reader(struct multipart_replace_stream *s, int fd, const char *_boundary) {
	int ret = 0;
	FILE *stream = fdopen(fd, "r");
	char *boundary = boundary_line(_boundary);

	char *line_buf = NULL;
	size_t line_cap = 0;
	ssize_t line_len = 0;
	ssize_t content_length = -1;

	while (running) {
		content_length = -1;
		/* scan for the first non-empty line */
		do {
			line_len = getline(&line_buf, &line_cap, stream);
			if (line_len < 0)
				stdioerror(stream, "src");
		} while (strcmp(line_buf, "\r\n") == 0);
		/* make sure it matches the boundary separator */
		if (strcmp(line_buf, boundary) != 0)
			threaderror(EXIT_FAILURE, 0, "line does not match boundary: \"%s\"", line_buf);
		/* read the frame header (MIME headers) */
		s->back->len = 0;
		do {
			line_len = getline(&line_buf, &line_cap, stream);
			if (line_len < 0)
				stdioerror(stream, "src");
			/* append the line to the frame contents */
			if ((ssize_t)s->back->cap < s->back->len + line_len)
				s->back->buf = xrealloc(s->back->buf, s->back->cap = s->back->len + line_len);
			memcpy(&s->back->buf[s->back->len], line_buf, line_len);
			s->back->len += line_len;
			/* parse the Content-length (if applicable) */
			if (strncasecmp(line_buf, "Content-length:", strlen("Content-length:")) == 0) {
				content_length = safe_atoi(&line_buf[strlen("Content-length:")]);
			}
		} while (strcmp(line_buf, "\r\n") != 0);
		/* make sure that it included a Content-length header */
		if (content_length < 0)
			threaderror(EXIT_FAILURE, 0, "did not get frame length");
		/* read the frame contents */
		if ((ssize_t)s->back->cap < s->back->len + content_length)
			s->back->buf = xrealloc(s->back->buf, s->back->cap = s->back->len + content_length);
		if (fread(&s->back->buf[s->back->len], content_length, 1, stream) != 1)
			stdioerror(stream, "src");
		s->back->len += content_length;

		/* swap the frames */
		pthread_rwlock_wrlock(&s->frontlock);
		struct frame *tmp = s->front;
		s->front = s->back;
		s->back = tmp;
		pthread_cond_broadcast(&s->newframe);
		pthread_rwlock_unlock(&s->frontlock);
	}
 end:
	free(boundary);
	free(line_buf);
	fclose(stream);
	return ret;
}

int multipart_replace_writer(struct multipart_replace_stream *s, int fd, const char *_boundary) {
	int ret = 0;
	FILE *stream = fdopen(fd, "w");
	struct frame myframe = { 0 };
	char *boundary = boundary_line(_boundary);
	size_t boundary_len = strlen(boundary);

	while (running) {
		pthread_cond_wait(&s->newframe, &s->newframe_lock);

		/* get the most recent frame (copy `s->front` to `myframe`) */
		pthread_rwlock_rdlock(&s->frontlock);
		if (myframe.cap < (size_t)s->front->len)
			myframe.buf = xrealloc(myframe.buf, myframe.cap = s->front->len);
		memcpy(myframe.buf, s->front->buf, myframe.len = s->front->len);
		pthread_rwlock_unlock(&s->frontlock);

		if (myframe.len == 0)
			threaderror(EXIT_FAILURE, 0, "got empty frame");

		/* send the frame to the client */
		if (fwrite(boundary, boundary_len, 1, stream) < 1)
			stdioerror(stream, "dst <- boundary");
		if (fwrite(myframe.buf, myframe.len, 1, stream) < 1)
			stdioerror(stream, "dst <- frame");
		/* send a blank line for pleasantness */
		if (fwrite("\r\n", 2, 1, stream) < 1)
			stdioerror(stream, "dst <- nl");
		if (fflush(stream) != 0)
			threaderror(EXIT_FAILURE, errno, "dst");
	}
 end:
	free(boundary);
	free(myframe.buf);
	fclose(stream);
	return ret;
}

void init_multipart_replace_stream(struct multipart_replace_stream *s) {
	ZERO(s->a);
	ZERO(s->b);
	s->front = &s->a;
	s->back = &s->b;
	pthread_rwlock_init(&s->frontlock, NULL);
	pthread_cond_init(&s->newframe, NULL);
	pthread_mutex_init(&s->newframe_lock, NULL);
}

void destroy_multipart_replace_stream(struct multipart_replace_stream *s) {
	free(s->a.buf);
	free(s->b.buf);
	pthread_rwlock_destroy(&s->frontlock);
	pthread_cond_destroy(&s->newframe);
	pthread_mutex_destroy(&s->newframe_lock);
}