[go: up one dir, main page]

File: dwww-cache.c

package info (click to toggle)
dwww 1.12.1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 828 kB
  • sloc: perl: 3,173; ansic: 1,805; sh: 170; makefile: 123
file content (896 lines) | stat: -rw-r--r-- 22,570 bytes parent folder | download | duplicates (3)
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
/* vim:ft=c:cindent:ts=4:sts=4:sw=4:et:fdm=marker
 *
 * File:    dwww-cache.c
 * Purpose: Manage the dwww cache of converted documents.
 * Author:  Lars Wirzenius
 * Description: See the manual page for how to use this program.
 *
 *      Basically, what we do is read in a file from stdin,
 *      store it somewhere, and then retrieve it when asked.
 *      The original name of the file is given on the command
 *      line.  We must be quick, so we keep a mapping between
 *      between the original name and the new name in a file.
 *
 *      The current implementation uses a simple "database"
 *      for the mapping that was written specifically for this
 *      program.  It's relatively fast as long as the database
 *      is not too big -- the whole database is read and written
 *      instead of just a record.  This may have to change
 *      in a future version.  On the other hand, as long as
 *      the database can be kept small, this is quite fast.
 *
 *      One way to make it smaller than it is is to compress
 *      the filenames, since they contain a lot of common
 *      strings ("/usr/share/man/" for example).  We'll see.
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <publib.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <utime.h>
#include <sys/file.h>
#include <libgen.h>
#include <stdbool.h>

#include "utils.h"

#define BUF_SIZE 1024

/*
 * Filename prefixes (for simple compression). At most 256 elements!
 */
static const char *prefs[] = {/* prefs[] {{{*/
    "",     /* MUST BE EMPTY STRING */
    "/usr/lib/",
    "/usr/share/doc/",
    "/usr/share/info/",
    "/usr/share/common-licenses/",
    "/usr/share/man/man1/",
    "/usr/share/man/man2/",
    "/usr/share/man/man3/",
    "/usr/share/man/man4/",
    "/usr/share/man/man5/",
    "/usr/share/man/man6/",
    "/usr/share/man/man7/",
    "/usr/share/man/man8/",
    "/usr/share/",
    "/usr/local/share/doc/",
    "/usr/local/share/info/",
    "/usr/local/share/man/man1/",
    "/usr/local/share/man/man2/",
    "/usr/local/share/man/man3/",
    "/usr/local/share/man/man4/",
    "/usr/local/share/man/man5/",
    "/usr/local/share/man/man6/",
    "/usr/local/share/man/man7/",
    "/usr/local/share/man/man8/",
    "/usr/local/share/"
};/*}}}*/
static int nprefs = sizeof(prefs) / sizeof(*prefs);


/*
 * Information about one file in in-memory format.
 */
struct cache_entry {/*{{{*/
    char type;
    char permanent;
    int pref;       /* full name if prefs[pref]+original */
    char *original;
    char *converted;
};/*}}}*/

/*
 * The whole database.
 */
struct dochash {
    char *db;
    size_t db_size;
    struct dynarr tab;
};

/*
 * Where we store the files and the database.
 */
#define SPOOL_DIR "/var/cache/dwww/db/"

/*
 * The name of the database in SPOOL_DIR.
 */
#define CACHE_DB SPOOL_DIR ".cache_db"


/*
 * What does the user want us to do?
 */
enum {
    action_error,
    action_help,
    action_store,
    action_lookup,
    action_list,
    action_list_all,
    action_clean
};
static int action = action_error;

/*
 * Options; for GNU getopt_long.
 */
static struct option options[] = {/*{{{*/
    { "help", 0, &action, action_help },
    { "store", 0, &action, action_store },
    { "lookup", 0, &action, action_lookup },
    { "list", 0, &action, action_list },
    { "list-all", 0, &action, action_list_all },
    { "clean", 0, &action, action_clean },
    { NULL, 0, NULL, 0 },
};/*}}}*/


static int parse_options(int, char **, struct option *, int *);
static bool store(char *, char *);
static bool lookup(char *, char *);
static bool list(char *, char *);
static bool list_all(char *, char *);
static bool clean(char *, char *);

static bool help(char *type UNUSED, char *location UNUSED) { /*{{{*/
    fprintf(stdout, "Usage: %s [--lookup|--store|--list] type location\n"
                    "       %s --list-all|--clean|--help\n",
                    get_progname(), get_progname() );
    exit(0);
}   /*}}}*/

static int open_db_reading(void);
static int open_db_writing(void);
static bool read_db(int, struct dochash *);
static int compare_entry(const void *, const void *);
static void sort_db(struct dochash *);
static int lookup_db(struct dochash *, char *);
static int insert_db(struct dochash *, struct cache_entry *);
static int write_db(int, struct dochash *);
static bool close_db(const int, const bool);
static size_t storage_size(struct cache_entry *);
static int output_file(char *);
static void init_entry(struct cache_entry *, char *, char *, char *, char);
static int create_tmp_file(char *, char *, size_t);
static int get_new_filename(char *, char *, char *, size_t);
static int copy_fd_to_fd(int, int, int);
static char *int_to_type(int);
static char type_to_int(char *);
static int rebuild_db(struct dochash *);
static bool check_mtimes(const char * const origname,
                        const char * const cachedname);
static int find_pref(const char *);
static int set_modtime_from_orig(const char * const , const char * const);

int main(int argc, char **argv) {/*{{{*/
    static struct {
        int action;
        int need_args;
        bool (*func)(char *, char *);
    } actions[] = {
        { action_help, 0, help },
        { action_lookup, 2, lookup },
        { action_store, 2, store },
        { action_list, 2, list },
        { action_list_all, 0, list_all },
        { action_clean, 0, clean },
        { action_error, 0, NULL },
    };
    int i, first_nonopt;

    dwww_initialize( "dwww-cache");


    if (parse_options(argc, argv, options, &first_nonopt) == -1)
        return EXIT_FAILURE;

    for (i = 0; actions[i].action != action_error; ++i)
        if (actions[i].action == action)
            break;

    if (actions[i].action == action_error)
        errormsg(1, 0, "error: no action specified");

    if (actions[i].need_args != argc - first_nonopt)
        errormsg(1, 0, "error: wrong number of args");

    if (!actions[i].func(argv[first_nonopt], argv[first_nonopt+1]))
        return EXIT_FAILURE;

    if (fflush(stdout) == EOF || ferror(stdout)) {
        errormsg(0, -1, "error writing to stdout");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}/*}}}*/


static int parse_options(int argc, char **argv, struct option *opt, int *ind) {/*{{{*/
    int o;

    while ((o = getopt_long(argc, argv, "", opt, ind)) != EOF)
        if (o == '?' || o == ':')
            return -1;
    *ind = optind;
    return 0;
}/*}}}*/



static bool list(char *type UNUSED, char *location) {/*{{{*/
    struct dochash hash;
    struct cache_entry *data;
    int i, db;
    char buf[BUF_SIZE];
    char orig[BUF_SIZE];

    db = open_db_reading();
    if (db == -1)
        return false;
    if (!read_db(db, &hash))
        return close_db(db, false);
    i = lookup_db(&hash, location);
    if (i == -1)
        return close_db(db, false);

    data = hash.tab.data;
    snprintf(orig, sizeof(orig), "%s%s", prefs[data[i].pref], data[i].original);
    snprintf(buf,  sizeof(buf),  "%s%.20s", SPOOL_DIR, data[i].converted);
    if (!check_mtimes(orig, buf)) {
        return close_db(db, false);
    }
    printf("%s %s %s %s\n", int_to_type(data[i].type),
        orig, data[i].converted,
        data[i].permanent ? "y" : "n");

    return close_db(db, true);
}/*}}}*/



static bool list_all(char *type UNUSED, char *location UNUSED) {/*{{{*/
    struct dochash hash;
    struct cache_entry *data;
    size_t i;
    int    db;
    char buf[BUF_SIZE];
    char orig[BUF_SIZE];

    db = open_db_reading();
    if (db == -1)
        return false;
    if (!read_db(db, &hash))
        return close_db(db, false);
    data = hash.tab.data;

    for (i = 0; i < hash.tab.used; ++i) {
        snprintf(orig, sizeof(orig), "%s%s", prefs[data[i].pref], data[i].original);
        snprintf(buf,  sizeof(buf),  "%s%.20s", SPOOL_DIR, data[i].converted);
        if (check_mtimes(orig, buf))
            printf("%s %s %s %s\n", int_to_type(data[i].type),
                orig, data[i].converted,
                data[i].permanent ? "y" : "n");
    }

    return close_db(db, true);
}/*}}}*/



static bool lookup(char *type UNUSED, char *location) {/*{{{*/
    struct dochash hash;
    struct cache_entry *data;
    int i, db;
    char buf[BUF_SIZE];
    char orig[BUF_SIZE];

    db = open_db_reading();
    if (db == -1)
        return false;
    if (!read_db(db, &hash))
        return close_db(db, false);
    i = lookup_db(&hash, location);
    if (i == -1)
        return close_db(db, false);

    data = hash.tab.data;
    snprintf(orig, sizeof(orig), "%s%s", prefs[data[i].pref], data[i].original);
    snprintf(buf,  sizeof(buf),  "%s%.20s", SPOOL_DIR, data[i].converted);
    if (!check_mtimes(orig, buf)) {
        return close_db(db, false);
    }
    if (output_file(buf) == -1) {
        return close_db(db, false);
    }
    return close_db(db, true);
}/*}}}*/


static bool internal_store(char * type,
                           char * location,
                           char * tmp_file,
                           const int fd,
                           const int db) {/*{{{*/
    int i;
    struct dochash hash;
    struct cache_entry new, *data;
    char filename[BUF_SIZE];
    char buf[BUF_SIZE];


    if (copy_fd_to_fd(STDIN_FILENO, fd, STDOUT_FILENO) == -1) {
        errormsg(0, -1, "can't copy stdin to %s", *tmp_file ? tmp_file : "stdout");
        return false;
    }

    if (!*tmp_file)
        return false;


    if (!read_db(db, &hash)) {
        return false;
    }

    i = lookup_db(&hash, location);
    if (i != -1) {
        data =  hash.tab.data;
        snprintf(filename, sizeof(filename), "%s%s", SPOOL_DIR, data[i].converted);
    } else {
        if (get_new_filename(location, SPOOL_DIR, buf, sizeof(buf)) == -1) {
            errormsg(0, -1, "can't get new cache filename");
            return false;
        }
        snprintf(filename, sizeof(filename), "%s%s", SPOOL_DIR, buf);

        init_entry(&new, type, location, buf, 0);

        if (insert_db(&hash, &new) == -1)
        {
            return false;
        }
    }

    if (rename(tmp_file, filename) == -1)
    {
        errormsg(0, -1, "can't rename temporary file to %s", filename);
        return false;
    }
    *tmp_file = 0; // tmp_file no longer exists...

    if (set_modtime_from_orig(filename, location) < 0
        || write_db(db, &hash) == -1)
    {
        (void) unlink(filename);
        return false;
    }

    return true;
}/*}}}*/


static bool store(char *type, char *location) {/*{{{*/
    int  db, fd;
    bool retval;
    char tmp_file[BUF_SIZE];

    fd = -1;

    db = open_db_writing();
    if (db >= 0)
    {
        fd = create_tmp_file(SPOOL_DIR, tmp_file, sizeof(tmp_file));
        if (fd == -1) {
            errormsg(0, -1, "can't create temporary cache file");
        }
    }

    if (fd < 0)
    {
        /* failed to open database or create temporary file, thus
           output to stdout only & don't cache */
        *tmp_file = 0;
        fd = STDOUT_FILENO;
    }

    retval = internal_store(type,
                            location,
                            tmp_file,
                            fd,
                            db);

    if (*tmp_file && unlink(tmp_file) < 0)
    {
        errormsg(0, -1, "can't remove temporary file %s", tmp_file);
        retval = false;
    }

    if (fd != STDOUT_FILENO && close(fd) < 0)
    {
        errormsg(0, -1, "can't close file");
        retval = false;
    }

    if (db >= 0)
        return close_db(db, retval);

    return retval;
}/*}}}*/



static bool clean(char *type UNUSED, char *location UNUSED) {/*{{{*/
    struct  dochash hash;
    struct  cache_entry *data;
    char    buf[BUF_SIZE];
    char    orig[BUF_SIZE];
    size_t  i, j;
    int     db;

    db = open_db_writing();
    if (db == -1 || !read_db(db, &hash))
        return false;

    data = hash.tab.data;
    j = 0;
    for (i = 0; i < hash.tab.used; ++i) {
        snprintf(orig, sizeof(orig), "%s%s", prefs[data[i].pref], data[i].original);
        snprintf(buf,  sizeof(buf),  "%s%.20s", SPOOL_DIR, data[i].converted);
        if (check_mtimes(orig, buf))
            data[j++] = data[i];
        else
            (void) unlink(buf);
    }
    hash.tab.used = j;

    if (!rebuild_db(&hash)   ||
        !write_db(db, &hash))
        return close_db(db, false);

    return close_db(db, true);
}/*}}}*/



static int open_db_reading(void) {/*{{{*/
    int db;
    int tries = 5;

    db = open(CACHE_DB, O_RDONLY, 0644);
    if (db == -1) {
            if (errno != ENOENT)
                errormsg(0, -1, "can't check cache database");
        return -1;
    }

    while (--tries && flock(db, LOCK_SH | LOCK_NB) < 0)
            sleep(1);

    if (!tries)
    {
        (void) close(db);
        errormsg(0, -1, "can't create shared lock on cache database");
        return -1;
    }

    return db;
}/*}}}*/


static int open_db_writing(void) {/*{{{*/
    int db;
    int tries = 5;

    db = open(CACHE_DB, O_RDWR | O_CREAT, 0664);
    if (db == -1)
    {
        errormsg(0, -1, "can't update cache database");
        return -1;
    }

    while (--tries && flock(db, LOCK_EX | LOCK_NB) < 0)
            sleep(1);

    if (!tries)
    {
        (void) close(db);
        errormsg(0, -1, "can't create exlusive lock on cache database");
        return -1;
    }

    return db;
}/*}}}*/


static bool read_db(int db, struct dochash *hash) {/*{{{*/
    struct stat st;
    char *p, *end;
    struct cache_entry *data;

    if (fstat(db, &st) == -1) {
        errormsg(0, -1, "can't find database size");
        return false;
    }

    p = malloc((size_t)st.st_size);
    if (p == NULL) {
        errormsg(0, -1, "out of memory");
        return false;
    }

    if (read(db, p, (size_t)st.st_size) != st.st_size) {
        free(p);
        errormsg(0, -1, "couldn't read database");
        return false;
    }

    hash->db = p;
    hash->db_size = (size_t) st.st_size;
    dynarr_init(&hash->tab, sizeof(struct cache_entry));

    end = p + st.st_size;
    while (p < end) {
        if (dynarr_resize(&hash->tab, hash->tab.used + 1) == -1) {
            errormsg(0, -1, "out of memory");
            return false;
        }
        data = hash->tab.data;
        data += hash->tab.used;
        data->type = *p++;
        data->permanent = *p++;
        data->pref = *p++;
        data->original = p;
        p += strlen(p) + 1;
        data->converted = p;
        p += strlen(p) + 1;
        ++hash->tab.used;
    }

    sort_db(hash);

    return true;
}/*}}}*/


static int compare_entry(const void *a, const void *b) {/*{{{*/
    const struct cache_entry *aa = a;
    const struct cache_entry *bb = b;
    int i;

    i = aa->pref - bb->pref;
    if (i == 0)
        i = strcmp(aa->original, bb->original);
    return i;
}/*}}}*/


static void sort_db(struct dochash *hash) {/*{{{*/
    qsort(hash->tab.data, hash->tab.used, sizeof(struct cache_entry),
        compare_entry);
}/*}}}*/


static int lookup_db(struct dochash *hash, char *original) {/*{{{*/
    struct cache_entry dummy, *p, *data;

    init_entry(&dummy, "", original, 0, 0);
    data = hash->tab.data;
    p = bsearch(&dummy, data, hash->tab.used,
        sizeof(struct cache_entry), compare_entry);
    if (p == NULL)
        return -1;
    return p - data;
}/*}}}*/


static int insert_db(struct dochash *hash, struct cache_entry *new) {/*{{{*/
    struct cache_entry *data;
    int i;

    i = lookup_db(hash, new->original);
    if (i == -1) {
        if (dynarr_resize(&hash->tab, hash->tab.used + 1) == -1) {
            errormsg(0, -1, "out of memory");
            return -1;
        }
        i = (int) hash->tab.used;
        ++hash->tab.used;
    }

    data = hash->tab.data;
    data[i] = *new;
    return rebuild_db(hash);
}/*}}}*/


static int rebuild_db(struct dochash *hash) {/*{{{*/
    struct  cache_entry *data;
    size_t  i, n;
    size_t   qsize;
    char    *q, *qq;

    data = hash->tab.data;
    qsize = 0;
    for (i = 0; i < hash->tab.used; ++i)
        qsize += storage_size(data + i);

    q = malloc(qsize + 1);
    if (q == NULL) {
        errormsg(0, -1, "out of memory");
        return -1;
    }

    qq = q;
    for (i = 0; i < hash->tab.used; ++i) {
        *qq++ = data[i].type;
        *qq++ = data[i].permanent;
        *qq++ = (char)data[i].pref;
        n = strlen(data[i].original) + 1;
        memcpy(qq, data[i].original, n);
        qq += n;
        n = strlen(data[i].converted) + 1;
        memcpy(qq, data[i].converted, n);
        qq += n;
    }

    free(hash->db);
    hash->db = q;
    hash->db_size = qsize;

    return 0;
}/*}}}*/


static int write_db(int db, struct dochash *hash) {/*{{{*/
    if (lseek(db, 0, SEEK_SET) == -1) {
        errormsg(0, -1, "can't update cache database");
        return -1;
    }

    if (ftruncate(db, 0) == -1) {
        errormsg(0, -1, "can't truncate cache database");
        return -1;
    }

    if (write(db, hash->db, hash->db_size) == -1) {
        errormsg(0, -1, "can't update cache database");
        return -1;
    }

    return 0;
}/*}}}*/


static bool close_db(int db, const bool retVal) {/*{{{*/
    if (flock(db, LOCK_UN) == -1) {
        close(db);
        errormsg(0, -1, "can't unlock cache database");
        return false;
    }
    if (close(db) == -1) {
        errormsg(0, -1, "error closing database");
        return false;
    }
    return retVal;
}/*}}}*/


static size_t storage_size(struct cache_entry *p) {/*{{{*/
    return 2 + 1 + strlen(p->original) + 1 + strlen(p->converted) + 1;
}/*}}}*/


static void init_entry(struct cache_entry *p, char *type, char *orig,/*{{{*/
char *conv, char perm)
{
    p->type = type_to_int(type);
    p->pref = find_pref(orig);
    p->original = orig + strlen(prefs[p->pref]);
    p->converted = conv;
    p->permanent = perm;
}/*}}}*/



static int output_file(char *name) {/*{{{*/
    int fd;

    fd = open(name, O_RDONLY);
    if (fd == -1) {
        errormsg(0, -1, "can't read file %s", name);
        return -1;
    }

    if (copy_fd_to_fd(fd, 1, 1) == -1) {
        (void) close(fd);
        return -1;
    }

    close(fd);
    return 0;
}/*}}}*/


static int copy_fd_to_fd(int from, int to_prim, int to_sec) {/*{{{*/
    char    buf[BUF_SIZE];
    ssize_t n;
    ssize_t n_prim = 0;
    ssize_t n_sec  = 0;


    if (to_prim == to_sec)
        n_sec = -100; /* *must* be less then 0 */

    while ((n = read(from, buf, sizeof(buf))) > 0) {
        if (n_prim >= 0)
            n_prim = write(to_prim, buf, (size_t)n) - n;
        if (n_sec >= 0)
            n_sec = write(to_sec, buf, (size_t)n) - n;
        if (n_prim < 0 && n_sec < 0)
        {
            errormsg(0, -1, "error writing");
            return -1;
        }
    }

    if (n_prim < 0)
    {
        errormsg(0, -1, "error writing");
        return -1;
    }

    if (n < 0) {
        errormsg(0, -1, "error reading");
        return -1;
    }

    return 0;
}/*}}}*/


static int create_tmp_file(char * dir, char * full, size_t size) {/*{{{*/
    int fd;

    snprintf(full, size,  "%s/tmp%d.%ld", dir, (int) getpid(), (long int)time(NULL));
    fd = open(full, O_CREAT | O_EXCL | O_RDWR, 0664);

    return fd;
}/*}}}*/

static int get_new_filename(char * location, char * dir, char * buf, size_t buf_size)/*{{{*/
{
        char * tmp;
        char full[BUF_SIZE];
        int  i = 0;
        char c = '_';

        tmp = basename(location);
        if (tmp != NULL)
                c = *tmp;

        snprintf(full, sizeof(full), "%s/%c", dir, c);
        if (mkdir(full, 0775) == -1 && errno != EEXIST)
        {
                errormsg(0, -1, "can't create directory %d", full);
                return -1;
        }
        for (i = 0; i < INT_MAX; i++)
        {
                snprintf(full, sizeof(full), "%s/%c/%d", dir, c, i);
                errno = 0;
                if (access(full, F_OK) == -1 && errno == ENOENT)
                {
                        snprintf(buf, buf_size, "%c/%d", c, i);
                        return 0;
                }
                else if (errno)
                        return -1;
        }
        return -1;
}/*}}}*/


static const struct {/*typetab[] {{{*/
    char *str;
    char ch;
} typetab[] = {
    { "man", 'm' },
    { "runman", 'r' },
    { "info", 'i' },
    { "text", 't' },
    { "dir", 'd' },
    { "html", 'h' },
    { "text/html", 'h' },
    { "file", 'f' },
    { NULL, '?' },
};/*}}}*/


static char type_to_int(char *str) {/*{{{*/
    int i;

    for (i = 0; typetab[i].str != NULL; ++i)
        if (strcmp(typetab[i].str, str) == 0)
            break;
    return typetab[i].ch;
}/*}}}*/


static char *int_to_type(int ch) {/*{{{*/
    int i;

    for (i = 0; typetab[i].str != NULL; ++i)
        if (typetab[i].ch == ch)
            return typetab[i].str;
    return "unknown";
}/*}}}*/


static time_t mtime(const char * const name) {/*{{{*/
    struct stat st;
    if (stat(name, &st) == -1)
        return 0;
    if (!st.st_size) /* file is empty, possibly truncated before */
        return 0;
    return st.st_mtime;
}/*}}}*/

static bool check_mtimes(const char * const origname,
                        const char * const cachedname) { /*{{{*/

    const time_t cachedmtime = mtime(cachedname);
    if (!cachedmtime)
    {
      /* cached file does not exist or is empty  (or some bad gay intentionally set its mtime to 0...) */
        return false;
    }

    if (mtime(origname) == cachedmtime)
        return true;

    /* Don't care if truncate fails or not... It could fail mostly because of EPERM, but it's OK
       Normally I would write
          (void) truncate(cachedname, 0);
       but compilers tries to be too smart, see
       http://launchpadlibrarian.net/28344578/buildlog_ubuntu-karmic-amd64.dwww_1.11.1ubuntu1_FULLYBUILT.txt.gz
   */
    if (truncate(cachedname, 0))
        return false;
    return false;
}/*}}}*/



static int find_pref(const char *s) {/*{{{*/
    int i;
    for (i = 1; i < nprefs; ++i)
        if (strncmp(s, prefs[i], strlen(prefs[i])) == 0)
            return i;
    return 0;
}/*}}}*/


static int set_modtime_from_orig(const char * const cachedname,
                                 const char * const origname) {/*{{{*/
    struct utimbuf ut;

    ut.modtime = mtime(origname);
    if (!ut.modtime)
        return -1;
    ut.actime  = time(NULL);

    return utime(cachedname, &ut);
}/*}}}*/