summaryrefslogtreecommitdiff
path: root/navit/file.c
blob: 35bae39a8569edf2a1855b89a007b6f6328f519d (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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/**
 * Navit, a modular navigation system.
 * Copyright (C) 2005-2008 Navit Team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * 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, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

#define _FILE_OFFSET_BITS 64
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <dirent.h>
#include <stdio.h>
#include <wordexp.h>
#include <glib.h>
#include <zlib.h>
#include "debug.h"
#include "cache.h"
#include "file.h"
#include "atom.h"
#include "config.h"
#include "item.h"
#ifdef HAVE_SOCKET
#include <sys/socket.h>
#include <netdb.h>
#endif

extern char *version;

#ifdef HAVE_LIBCRYPTO
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#endif

#ifdef HAVE_API_ANDROID
#define lseek lseek64
#endif

#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifdef CACHE_SIZE
static GHashTable *file_name_hash;
#endif

static struct cache *file_cache;

struct file_cache_id {
	long long offset;
	int size;
	int file_name_id;
	int method;
} __attribute__ ((packed));

#ifdef HAVE_SOCKET
static int
file_socket_connect(char *host, char *service)
{
	struct addrinfo hints;
	struct addrinfo *result, *rp;
	int fd=-1,s;

	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = 0;
	hints.ai_protocol = 0;
	s = getaddrinfo(host, service, &hints, &result);
	if (s != 0) {
		dbg(0,"getaddrinfo error %s\n",gai_strerror(s));
		return -1;
	}
	for (rp = result; rp != NULL; rp = rp->ai_next) {
		fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (fd != -1) {
			if (connect(fd, rp->ai_addr, rp->ai_addrlen) != -1)
				break;
			close(fd);
			fd=-1;
		}
	}
	freeaddrinfo(result);
	return fd;
}
#endif

static void
file_http_request(struct file *file, char *method, char *host, char *path, char *header)
{
	char *request=g_strdup_printf("%s %s HTTP/1.0\r\nUser-Agent: navit %s\r\nHost: %s%s%s%s\r\n\r\n",method,path,version,host,header?"\r\n":"",header?header:"",header?"\r\n":"");
	write(file->fd, request, strlen(request));
	dbg(1,"%s\n",request);
	file->requests++;
}

static char *
file_http_header_end(char *str, int len)
{
	int i;
	for (i=0; i+1<len; i+=2) {
		if (str[i+1]=='\n') {
			if (str[i]=='\n')
				return str+i+2;
			else if (str[i]=='\r' && i+3<len && str[i+2]=='\r' && str[i+3]=='\n')
			        return str+i+4;
			--i;
		} else if (str[i+1]=='\r') {
			if (i+4<len && str[i+2]=='\n' && str[i+3]=='\r' && str[i+4]=='\n')
				return str+i+5;
			--i;
		}
    	}
  	return NULL;
}

struct file *
file_create(char *name, struct attr **options)
{
	struct stat stat;
	struct file *file= g_new0(struct file,1);
	struct attr *attr;
	int open_flags=O_LARGEFILE|O_BINARY;

	if (options && (attr=attr_search(options, NULL, attr_url)) && attr->u.str) {
#ifdef HAVE_SOCKET
		name=attr->u.str;
		file->name = g_strdup(name);
		if (!strncmp(name,"http://",7)) {
			char *host=g_strdup(name+7);
			char *port=strchr(host,':');
			char *path=strchr(name+7,'/');
			char *method="GET";
			char *header=NULL;
			if ((attr=attr_search(options, NULL, attr_http_method)) && attr->u.str)
				method=attr->u.str;
			if ((attr=attr_search(options, NULL, attr_http_header)) && attr->u.str)
				header=attr->u.str;
			if (path) 
				host[path-name-7]='\0';
			if (port)
				*port++='\0';
			dbg(1,"host=%s path=%s\n",host,path);
			file->fd=file_socket_connect(host,port?port:"80");
			file_http_request(file,method,host,path,header);
			file->special=1;
			g_free(host);
		}
#endif
	} else {
		if (options && (attr=attr_search(options, NULL, attr_readwrite)) && attr->u.num) {
			open_flags |= O_RDWR;
			if ((attr=attr_search(options, NULL, attr_create)) && attr->u.num)
				open_flags |= O_CREAT;
		} else
			open_flags |= O_RDONLY;
		file->name = g_strdup(name);
		file->fd=open(name, open_flags, 0666);
		if (file->fd == -1) {
			g_free(file);
			return NULL;
		}
		dbg(1,"fd=%d\n", file->fd);
		fstat(file->fd, &stat);
		file->size=stat.st_size;
		dbg(1,"size=%Ld\n", file->size);
		file->name_id = (int)atom(name);
	}
#ifdef CACHE_SIZE
	if (!options || !(attr=attr_search(options, NULL, attr_cache)) || attr->u.num)
		file->cache=1;
#endif
	dbg_assert(file != NULL);
	return file;
}

#if 0
struct file *
file_create_url(char *url)
{
}
#endif

int file_is_dir(char *name)
{
	struct stat buf;
	if (! stat(name, &buf)) {
		return S_ISDIR(buf.st_mode);
	}
	return 0;

}

long long
file_size(struct file *file)
{
	return file->size;
}

int file_mkdir(char *name, int pflag)
{
	char buffer[strlen(name)+1];
	int ret;
	char *next;
	dbg(1,"enter %s %d\n",name,pflag);
	if (!pflag) {
		if (file_is_dir(name))
			return 0;
#ifdef HAVE_API_WIN32_BASE
		return mkdir(name);
#else
		return mkdir(name, 0777);
#endif
	}
	strcpy(buffer, name);
	next=buffer;
	while ((next=strchr(next, '/'))) {
		*next='\0';
		if (*buffer) {
			ret=file_mkdir(buffer, 0);
			if (ret)
				return ret;
		}
		*next++='/';
	}
	if (pflag == 2)
		return 0;
	return file_mkdir(buffer, 0);
}

int
file_mmap(struct file *file)
{
#if 0
	int mmap_size=file->size+1024*1024;
#else
	int mmap_size=file->size;
#endif
#ifdef HAVE_API_WIN32_BASE
	file->begin = (char*)mmap_readonly_win32( file->name, &file->map_handle, &file->map_file );
#else
	file->begin=mmap(NULL, mmap_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, file->fd, 0);
	dbg_assert(file->begin != NULL);
	if (file->begin == (void *)0xffffffff) {
		perror("mmap");
		return 0;
	}
#endif
	dbg_assert(file->begin != (void *)0xffffffff);
	file->mmap_end=file->begin+mmap_size;
	file->end=file->begin+file->size;

	return 1;
}

unsigned char *
file_data_read(struct file *file, long long offset, int size)
{
	void *ret;
	if (file->special)
		return NULL;
	if (file->begin)
		return file->begin+offset;
	if (file_cache) {
		struct file_cache_id id={offset,size,file->name_id,0};
		ret=cache_lookup(file_cache,&id); 
		if (ret)
			return ret;
		ret=cache_insert_new(file_cache,&id,size);
	} else
		ret=g_malloc(size);
	lseek(file->fd, offset, SEEK_SET);
	if (read(file->fd, ret, size) != size) {
		file_data_free(file, ret);
		ret=NULL;
	}
	return ret;

}

static void
file_process_headers(struct file *file, char *headers)
{
	char *tok;
	char *cl="Content-Length: ";
	while ((tok=strtok(headers, "\r\n"))) {
		if (!strncasecmp(tok,cl,strlen(cl))) {
			file->size=atoll(tok+strlen(cl));
		}
		headers=NULL;
	}
}

static void
file_shift_buffer(struct file *file, int amount)
{
	memmove(file->buffer, file->buffer+amount, file->buffer_len-amount);
	file->buffer_len-=amount;
}

unsigned char *
file_data_read_special(struct file *file, int size, int *size_ret)
{
	unsigned char *ret,*hdr;
	int rets=0,rd;
	int buffer_size=8192;
	int eof=0;
	if (!file->special)
		return NULL;
	if (!file->buffer)
		file->buffer=g_malloc(buffer_size);
	ret=g_malloc(size);
	while (size > 0 && (!eof || file->buffer_len)) {
		int toread=buffer_size-file->buffer_len;
		if (toread >= 4096 && !eof) {
			rd=read(file->fd, file->buffer+file->buffer_len, toread);
			if (rd > 0) {
				file->buffer_len+=rd;
			} else
				eof=1;
		}
		if (file->requests) {
			dbg(1,"checking header\n");
			if ((hdr=file_http_header_end(file->buffer, file->buffer_len))) {
				hdr[-1]='\0';
				dbg(1,"found %s\n",file->buffer);
				file_process_headers(file, file->buffer);
				file_shift_buffer(file, hdr-file->buffer);
				file->requests--;
			}
		} else {
			rd=file->buffer_len;
			if (rd > size)
				rd=size;
			memcpy(ret+rets, file->buffer, rd);
			file_shift_buffer(file, rd);
			rets+=rd;
			size-=rd;
		}
	}
	*size_ret=rets;
	return ret;
}

unsigned char *
file_data_read_all(struct file *file)
{
	return file_data_read(file, 0, file->size);
}

int
file_data_write(struct file *file, long long offset, int size, unsigned char *data)
{
	if (file_cache) {
		struct file_cache_id id={offset,size,file->name_id,0};
		cache_flush(file_cache,&id);
	}
	lseek(file->fd, offset, SEEK_SET);
	if (write(file->fd, data, size) != size)
		return 0;
	if (file->size < offset+size)
		file->size=offset+size;
	return 1;
}

int
file_get_contents(char *name, unsigned char **buffer, int *size)
{
	struct file *file;
	file=file_create(name, 0);
	if (!file)
		return 0;
	*size=file_size(file);
	*buffer=file_data_read_all(file);
	file_destroy(file);
	return 1;	
}


static int
uncompress_int(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
{
	z_stream stream;
	int err;

	stream.next_in = (Bytef*)source;
	stream.avail_in = (uInt)sourceLen;
	stream.next_out = dest;
	stream.avail_out = (uInt)*destLen;

	stream.zalloc = (alloc_func)0;
	stream.zfree = (free_func)0;

	err = inflateInit2(&stream, -MAX_WBITS);
	if (err != Z_OK) return err;

	err = inflate(&stream, Z_FINISH);
	if (err != Z_STREAM_END) {
	inflateEnd(&stream);
	if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
		return Z_DATA_ERROR;
		return err;
	}
	*destLen = stream.total_out;

	err = inflateEnd(&stream);
	return err;
}

unsigned char *
file_data_read_compressed(struct file *file, long long offset, int size, int size_uncomp)
{
	void *ret;
	char *buffer = 0;
	uLongf destLen=size_uncomp;

	if (file_cache) {
		struct file_cache_id id={offset,size,file->name_id,1};
		ret=cache_lookup(file_cache,&id); 
		if (ret)
			return ret;
		ret=cache_insert_new(file_cache,&id,size_uncomp);
	} else 
		ret=g_malloc(size_uncomp);
	lseek(file->fd, offset, SEEK_SET);

	buffer = (char *)g_malloc(size);
	if (read(file->fd, buffer, size) != size) {
		g_free(ret);
		ret=NULL;
	} else {
		if (uncompress_int(ret, &destLen, (Bytef *)buffer, size) != Z_OK) {
			dbg(0,"uncompress failed\n");
			g_free(ret);
			ret=NULL;
		}
	}
	g_free(buffer);

	return ret;
}

unsigned char *
file_data_read_encrypted(struct file *file, long long offset, int size, int size_uncomp, int compressed, char *passwd)
{
#ifdef HAVE_LIBCRYPTO
	void *ret;
	unsigned char *buffer = 0;
	uLongf destLen=size_uncomp;

	if (file_cache) {
		struct file_cache_id id={offset,size,file->name_id,1};
		ret=cache_lookup(file_cache,&id); 
		if (ret)
			return ret;
		ret=cache_insert_new(file_cache,&id,size_uncomp);
	} else 
		ret=g_malloc(size_uncomp);
	lseek(file->fd, offset, SEEK_SET);

	buffer = (unsigned char *)g_malloc(size);
	if (read(file->fd, buffer, size) != size) {
		g_free(ret);
		ret=NULL;
	} else {
		unsigned char key[34], salt[8], verify[2], counter[16], xor[16], mac[10], mactmp[20], *datap;
		int overhead=sizeof(salt)+sizeof(verify)+sizeof(mac);
		int esize=size-overhead;
		PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), (unsigned char *)buffer, 8, 1000, 34, key);
		if (key[32] == buffer[8] && key[33] == buffer[9] && esize >= 0) {
			AES_KEY aeskey;
			AES_set_encrypt_key(key, 128, &aeskey);
			datap=buffer+sizeof(salt)+sizeof(verify);
			memset(counter, 0, sizeof(counter));
			while (esize > 0) {
				int i,curr_size,idx=0;
				do {
					counter[idx]++;
				} while (!counter[idx++]);
				AES_encrypt(counter, xor, &aeskey);
				curr_size=esize;
				if (curr_size > sizeof(xor))
					curr_size=sizeof(xor);
				for (i = 0 ; i < curr_size ; i++) 
					*datap++^=xor[i];
				esize-=curr_size;
			}
			size-=overhead;
			datap=buffer+sizeof(salt)+sizeof(verify);
			if (compressed) {
				if (uncompress_int(ret, &destLen, (Bytef *)datap, size) != Z_OK) {
					dbg(0,"uncompress failed\n");
					g_free(ret);
					ret=NULL;
				}
			} else {
				if (size == destLen) 
					memcpy(ret, buffer, destLen);
				else {
					dbg(0,"memcpy failed\n");
					g_free(ret);
					ret=NULL;
				}
			}
		} else {
			g_free(ret);
			ret=NULL;
		}
	}
	g_free(buffer);

	return ret;
#else
	return NULL;
#endif
}

void
file_data_free(struct file *file, unsigned char *data)
{
	if (file->begin) {
		if (data == file->begin)
			return;
		if (data >= file->begin && data < file->end)
			return;
	}	
	if (file->cache && data) {
		cache_entry_destroy(file_cache, data);
	} else
		g_free(data);
}

int
file_exists(char *name)
{
	struct stat buf;
	if (! stat(name, &buf))
		return 1;
	return 0;
}

void
file_remap_readonly(struct file *f)
{
#if defined(_WIN32) || defined(__CEGCC__)
#else
	void *begin;
	munmap(f->begin, f->size);
	begin=mmap(f->begin, f->size, PROT_READ, MAP_PRIVATE, f->fd, 0);
	if (f->begin != begin)
		printf("remap failed\n");
#endif
}

void
file_unmap(struct file *f)
{
#if defined(_WIN32) || defined(__CEGCC__)
    mmap_unmap_win32( f->begin, f->map_handle , f->map_file );
#else
	munmap(f->begin, f->size);
#endif
}

void *
file_opendir(char *dir)
{
	return opendir(dir);
}

char *
file_readdir(void *hnd)
{
	struct dirent *ent;

	ent=readdir(hnd);
	if (! ent)
		return NULL;
	return ent->d_name;
}

void
file_closedir(void *hnd)
{
	closedir(hnd);
}

struct file *
file_create_caseinsensitive(char *name, struct attr **options)
{
	char dirname[strlen(name)+1];
	char *filename;
	char *p;
	void *d;
	struct file *ret;

	ret=file_create(name, options);
	if (ret)
		return ret;

	strcpy(dirname, name);
	p=dirname+strlen(name);
	while (p > dirname) {
		if (*p == '/')
			break;
		p--;
	}
	*p=0;
	d=file_opendir(dirname);
	if (d) {
		*p++='/';
		while ((filename=file_readdir(d))) {
			if (!strcasecmp(filename, p)) {
				strcpy(p, filename);
				ret=file_create(dirname, options);
				if (ret)
					break;
			}
		}
		file_closedir(d);
	}
	return ret;
}

void
file_destroy(struct file *f)
{
	switch (f->special) {
	case 0:
	case 1:
		close(f->fd);
		break;
	}

    if ( f->begin != NULL )
    {
        file_unmap( f );
    }

	g_free(f->buffer);
	g_free(f->name);
	g_free(f);
}

struct file_wordexp {
	int err;
	wordexp_t we;
};

struct file_wordexp *
file_wordexp_new(const char *pattern)
{
	struct file_wordexp *ret=g_new0(struct file_wordexp, 1);

	ret->err=wordexp(pattern, &ret->we, 0);
	if (ret->err)
		dbg(0,"wordexp('%s') returned %d\n", pattern, ret->err);
	return ret;
}

int
file_wordexp_get_count(struct file_wordexp *wexp)
{
	return wexp->we.we_wordc;
}

char **
file_wordexp_get_array(struct file_wordexp *wexp)
{
	return wexp->we.we_wordv;
}

void
file_wordexp_destroy(struct file_wordexp *wexp)
{
	if (! wexp->err)
		wordfree(&wexp->we);
	g_free(wexp);
}


int
file_get_param(struct file *file, struct param_list *param, int count)
{
	int i=count;
	param_add_string("Filename", file->name, &param, &count);
	param_add_hex("Size", file->size, &param, &count);
	return i-count;
}

int
file_version(struct file *file, int mode)
{
#ifndef HAVE_API_WIN32_BASE
	struct stat st;
	int error;
	if (mode == 3) {
		long long size=lseek(file->fd, 0, SEEK_END);
		if (file->begin && file->begin+size > file->mmap_end) {
			file->version++;
		} else {
			file->size=size;
			if (file->begin)
				file->end=file->begin+file->size;
		}
	} else {
		if (mode == 2)
			error=stat(file->name, &st);
		else
			error=fstat(file->fd, &st);
		if (error || !file->version || file->mtime != st.st_mtime || file->ctime != st.st_ctime) {
			file->mtime=st.st_mtime;
			file->ctime=st.st_ctime;
			file->version++;
			dbg(1,"%s now version %d\n", file->name, file->version);
		}
	}
	return file->version;
#else
	return 0;
#endif
}

void *
file_get_os_handle(struct file *file)
{
	return GINT_TO_POINTER(file->fd);
}

void
file_init(void)
{
#ifdef CACHE_SIZE
	file_name_hash=g_hash_table_new(g_str_hash, g_str_equal);
	file_cache=cache_new(sizeof(struct file_cache_id), CACHE_SIZE);
#endif
}