summaryrefslogtreecommitdiff
path: root/platform/x11/curl_stream.c
blob: 3a0de68c82e0a0ee1c21dd824f91eb178207f557 (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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/* Simple example fz_stream implementation using curl */

#include "mupdf/fitz.h"
#include "curl_stream.h"

#define CURL_STATICLIB
#include <curl/curl.h>

#undef DEBUG_BLOCK_FETCHING

#ifdef DEBUG_BLOCK_FETCHING
#define DEBUG_MESSAGE(A) do { fz_warn A; } while(0)
#else
#define DEBUG_MESSAGE(A) do { } while(0)
#endif

#define BLOCK_SHIFT 12
#define BLOCK_SIZE (1<<BLOCK_SHIFT)

#ifdef _WIN32
#include <windows.h>
#else
#include "pthread.h"
#include <ctype.h>
#endif

typedef struct curl_stream_state_s curl_stream_state;

struct curl_stream_state_s
{
	fz_context *ctx;
	CURL *handle;
	char *filename;
	int data_arrived;
	int content_length; /* As returned by curl. -1 for unknown. */
	int total_length; /* As obtained from the Content-Range header. */
	int buffer_max;
	int buffer_fill;
	unsigned char *buffer;
	int map_length;
	unsigned char *map;
	int fill_point; /* The next file offset we will fetch to */
	int current_fill_point; /* The current file offset we are fetching to */
	int complete;
	int kill_thread;
	void (*more_data)(void *, int);
	void *more_data_arg;

#ifdef _WIN32
	void *thread;
	DWORD thread_id;
	HANDLE mutex;
#else
	pthread_t thread;
	pthread_mutex_t mutex;
#endif
};

static void fetcher_thread(curl_stream_state *state);

#ifdef _WIN32
static void
lock(curl_stream_state *state)
{
	WaitForSingleObject(state->mutex, INFINITE);
}

static void
unlock(curl_stream_state *state)
{
	ReleaseMutex(state->mutex);
}

static DWORD WINAPI
win_thread(void *lparam)
{
	fetcher_thread((curl_stream_state *)lparam);

	return 0;
}

#else /* Anything else assumed to be pthreads */

static void
lock(curl_stream_state *state)
{
	pthread_mutex_lock(&state->mutex);
}

static void
unlock(curl_stream_state *state)
{
	pthread_mutex_unlock(&state->mutex);
}


static void *
pthread_thread(void *arg)
{
	fetcher_thread((curl_stream_state *)arg);

	return NULL;
}
#endif

static size_t header_arrived(void *ptr, size_t size, size_t nmemb, void *state_)
{
	curl_stream_state *state = (curl_stream_state *)state_;

	if (strncmp(ptr, "Content-Range:", 14) == 0)
	{
		char *p = (char *)ptr;
		int len = nmemb * size;
		int start, end, total;
		while (len && !isdigit(*p))
			p++, len--;
		start = 0;
		while (len && isdigit(*p))
		{
			start = start*10 + *p-'0';
			p++, len--;
		}
		while (len && !isdigit(*p))
			p++, len--;
		end = 0;
		while (len && isdigit(*p))
		{
			end = end*10 + *p-'0';
			p++, len--;
		}
		while (len && !isdigit(*p))
			p++, len--;
		total = 0;
		while (len && isdigit(*p))
		{
			total = total*10 + *p-'0';
			p++, len--;
		}
		state->total_length = total;
	}

	return nmemb * size;
}

static size_t data_arrived(void *ptr, size_t size, size_t nmemb, void *state_)
{
	curl_stream_state *state = (curl_stream_state *)state_;
	int old_start;

	size *= nmemb;

	if (state->data_arrived == 0)
	{
		double d;
		long response;
		int len;
		/* This is the first time data has arrived. If the response
		 * code is 206, then we can do byte requests, and we will
		 * known the total_length from having processed the header
		 * already. */
		curl_easy_getinfo(state->handle, CURLINFO_RESPONSE_CODE, &response);
		if (state->total_length && response == 206)
		{
			/* We got a range header, and the correct http response
			 * code. We can assume that byte fetches are accepted
			 * and we'll run without progressive mode. */
			state->content_length = len = state->total_length;
			state->map_length = (len+BLOCK_SIZE-1)>>BLOCK_SHIFT;
			state->map = fz_malloc_no_throw(state->ctx, (state->map_length+7)>>3);
			state->buffer = fz_malloc_no_throw(state->ctx, len);
			state->buffer_max = len;
			if (state->map == NULL || state->buffer == NULL)
			{
				/* FIXME: Crap error handling! */
				exit(1);
			}
			memset(state->map, 0, (state->map_length+7)>>3);
		}
		else
		{
			/* So we can't use ByteRanges. Do we at least know the
			 * complete length of the file? */
			curl_easy_getinfo(state->handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);
			state->content_length = len = (int)d;
			if (len > 0 && response == 200)
			{
				/* Yes. We can run as a progressive file */
				state->buffer = fz_malloc_no_throw(state->ctx, len);
				state->buffer_max = len;
				if (state->buffer == NULL)
				{
					/* FIXME: Crap error handling! */
					exit(1);
				}
			}
			else
			{
				/* What a crap server. Won't tell us how big
				 * the file is. We'll have to expand as data
				 * as arrives. */
				state->content_length = -1;
			}
		}
		state->data_arrived = 1;
	}
	if (state->content_length < 0)
	{
		int newsize = state->current_fill_point + size;
		if (newsize > state->buffer_max)
		{
			/* Expand the buffer */
			int new_max = state->buffer_max * 2;
			if (new_max == 0)
				new_max = 4096;
			state->buffer = fz_resize_array_no_throw(state->ctx, state->buffer, new_max, 1);
			if (state->buffer == NULL)
			{
				/* FIXME: Crap error handling! */
				exit(1);
			}
			state->buffer_max = new_max;
		}
	}

	DEBUG_MESSAGE((state->ctx, "data arrived: offset=%d len=%d", state->current_fill_point, size));
	old_start = state->current_fill_point;
	memcpy(state->buffer + state->current_fill_point, ptr, size);
	state->current_fill_point += size;
	if (state->current_fill_point == state->content_length ||
		(((state->current_fill_point ^ old_start) & ~(BLOCK_SIZE-1)) != 0))
	{
		if (state->map)
		{
			old_start >>= BLOCK_SHIFT;
			state->map[old_start>>3] |= 1<<(old_start & 7);
		}
	}

	if (state->more_data)
		state->more_data(state->more_data_arg, 0);

	return size;
}

#define HAVE_BLOCK(map, num) \
	(((map)[(num)>>3] & (1<<((num) & 7))) != 0)

static void
fetch_chunk(curl_stream_state *state)
{
	char text[32];
	int fill, start, end;

	lock(state);

	if (state->kill_thread)
	{
		state->complete = 1;
		unlock(state);
		return;
	}

	fill = state->fill_point;
	if (state->content_length > 0)
	{
		/* Find the next block that we haven't got */
		int map_length = state->map_length;
		unsigned char *map = state->map;
		for ( ; (fill < map_length && HAVE_BLOCK(map, fill)); fill++);
		if (fill == map_length)
		{
			for (fill = 0;
				(fill < map_length && HAVE_BLOCK(map, fill));
				fill++);
			if (fill == map_length)
			{
				/* We've got it all! */
				state->complete = 1;
				state->kill_thread = 1;
				unlock(state);
				if (state->more_data)
					state->more_data(state->more_data_arg, 1);
				fz_warn(state->ctx, "Background fetch complete!");
				return;
			}
		}
		DEBUG_MESSAGE((state->ctx, "block requested was %d, fetching %d", state->fill_point, fill));
		state->fill_point = fill;
	}

	unlock(state);

	/* Fetch that block */
	start = fill * BLOCK_SIZE;
	end = start + BLOCK_SIZE-1;
	state->current_fill_point = start;
	if (state->content_length > 0 && start >= state->content_length)
		state->complete = 1;
	if (state->content_length > 0 && end >= state->content_length)
		end = state->content_length-1;
	snprintf(text, 32, "%d-%d", start, end);
	curl_easy_setopt(state->handle, CURLOPT_RANGE, text);
	curl_easy_perform(state->handle);
}

static void
fetcher_thread(curl_stream_state *state)
{
	while (!state->complete)
		fetch_chunk(state);
}

static int
stream_read(fz_stream *stream, unsigned char *buf, int len)
{
	curl_stream_state *state = (curl_stream_state *)stream->state;
	int len_read = 0;
	int read_point = stream->pos;
	int block = read_point>>BLOCK_SHIFT;
	int left_over = (-read_point) & (BLOCK_SIZE-1);

	if (state->content_length == 0)
		fz_throw(stream->ctx, FZ_ERROR_TRYLATER, "read of a block we don't have (A) (offset=%d)", read_point);

	if (state->map == NULL)
	{
		/* We are doing a simple linear fetch as we don't know the
		 * content length. */
		if (read_point + len > state->current_fill_point)
		{
			stream->rp = stream->wp = stream->bp;
			fz_throw(stream->ctx, FZ_ERROR_TRYLATER, "read of a block we don't have (B) (offset=%d)", read_point);
		}
		memcpy(buf, state->buffer + read_point, len);
		return len;
	}

	if (read_point + len > state->content_length)
		len = state->content_length - read_point;
	if (left_over > len)
		left_over = len;

	if (left_over)
	{
		/* We are starting midway through a block */
		if (!HAVE_BLOCK(state->map, block))
		{
			lock(state);
			state->fill_point = block;
			unlock(state);
			stream->rp = stream->wp = stream->bp;
			fz_throw(stream->ctx, FZ_ERROR_TRYLATER, "read of a block we don't have (C) (offset=%d)", read_point);
		}
		block++;
		if (left_over > len)
			left_over = len;
		memcpy(buf, state->buffer + read_point, left_over);
		buf += left_over;
		read_point += left_over;
		len -= left_over;
		len_read += left_over;
	}

	/* Copy any complete blocks */
	while (len > BLOCK_SIZE)
	{
		if (!HAVE_BLOCK(state->map, block))
		{
			lock(state);
			state->fill_point = block;
			unlock(state);
			stream->rp = stream->wp = stream->bp;
			fz_throw(stream->ctx, FZ_ERROR_TRYLATER, "read of a block we don't have (D) (offset=%d)", read_point);
		}
		block++;
		memcpy(buf, state->buffer + read_point, BLOCK_SIZE);
		buf += BLOCK_SIZE;
		read_point += BLOCK_SIZE;
		len -= BLOCK_SIZE;
		len_read += BLOCK_SIZE;
	}

	/* Copy any trailing bytes */
	if (len > 0)
	{
		if (!HAVE_BLOCK(state->map, block))
		{
			lock(state);
			state->fill_point = block;
			unlock(state);
			stream->rp = stream->wp = stream->bp;
			fz_throw(stream->ctx, FZ_ERROR_TRYLATER, "read of a block we don't have (E) (offset=%d)", read_point);
		}
		memcpy(buf, state->buffer + read_point, len);
		len_read += len;
	}

	return len_read;
}

static void
stream_close(fz_context *ctx, void *state_)
{
	curl_stream_state *state = (curl_stream_state *)state_;

	if (!state || state->kill_thread)
		return;

	lock(state);
	state->kill_thread = 1;
	unlock(state);

#ifdef _WIN32
	WaitForSingleObject(state->thread, INFINITE);
	CloseHandle(state->thread);
	CloseHandle(state->mutex);
#else
	pthread_join(state->thread, NULL);
	pthread_mutex_destroy(&state->mutex);
#endif

	fz_free(state->ctx, state->buffer);
	fz_free(state->ctx, state->map);
	fz_free(state->ctx, state);
}

static fz_stream hack_stream;
static curl_stream_state hack;
static int hack_pos;

static void
stream_seek(fz_stream *stream, int offset, int whence)
{
	curl_stream_state *state = (curl_stream_state *)stream->state;

	switch(whence)
	{
	case SEEK_CUR:
		offset += stream->pos;
		break;
	case SEEK_END:
		offset += state->content_length;
		break;
	default:
	case SEEK_SET:
		break;
	}
	if (offset < 0)
		offset = 0;
	else if (state->content_length > 0 && offset > state->content_length)
		offset = state->content_length;
	stream->wp = stream->rp = stream->bp;
	stream->pos = offset;
	hack = *state;
	hack_pos = offset;
	hack_stream = *stream;
}

static int
stream_meta(fz_stream *stream, int key, int size, void *ptr)
{
	curl_stream_state *state = (curl_stream_state *)stream->state;

	switch(key)
	{
	case FZ_STREAM_META_LENGTH:
		if (!state->data_arrived)
			fz_throw(stream->ctx, FZ_ERROR_TRYLATER, "still awaiting file length");
		return state->content_length;
	case FZ_STREAM_META_PROGRESSIVE:
		return 1;
	}
	return -1;
}

fz_stream *fz_stream_from_curl(fz_context *ctx, char *filename, void (*more_data)(void *,int), void *more_data_arg)
{
	CURLcode ret;
	CURL *handle;
	curl_stream_state *state = fz_malloc_struct(ctx, curl_stream_state);
	fz_stream *stream;

	ret = curl_global_init(CURL_GLOBAL_ALL);
	if (ret != 0)
		fz_throw(ctx, FZ_ERROR_GENERIC, "curl init failed (code %d)", ret);

	state->ctx = ctx;
	state->handle = handle = curl_easy_init();
	state->more_data = more_data;
	state->more_data_arg = more_data_arg;

	curl_easy_setopt(handle, CURLOPT_URL, filename);

	curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 1);

	curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, data_arrived);

	curl_easy_setopt(handle, CURLOPT_WRITEDATA, state);

	curl_easy_setopt(handle, CURLOPT_WRITEHEADER, state);

	curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, header_arrived);

#ifdef _WIN32
	state->mutex = CreateMutex(NULL, FALSE, NULL);
	if (state->mutex == NULL)
		fz_throw(ctx, FZ_ERROR_GENERIC, "mutex creation failed");

	state->thread = CreateThread(NULL, 0, win_thread, state, 0, &state->thread_id);
	if (state->thread == NULL)
		fz_throw(ctx, FZ_ERROR_GENERIC, "thread creation failed");
#else
	if (pthread_mutex_init(&state->mutex, NULL))
		fz_throw(ctx, FZ_ERROR_GENERIC, "mutex creation failed");

	if (pthread_create(&state->thread, NULL, pthread_thread, state))
		fz_throw(ctx, FZ_ERROR_GENERIC, "thread creation failed");

#endif

	stream = fz_new_stream(ctx, state, stream_read, stream_close);
	stream->seek = stream_seek;
	stream->meta = stream_meta;
	return stream;
}