File: archive.c

package info (click to toggle)
inn2 2.4.5-5
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 8,912 kB
  • ctags: 7,860
  • sloc: ansic: 85,104; perl: 11,427; sh: 9,863; makefile: 2,498; yacc: 1,563; python: 298; lex: 252; tcl: 7
file content (653 lines) | stat: -rw-r--r-- 14,642 bytes parent folder | download
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
/*  $Id: archive.c 6138 2003-01-19 04:13:51Z rra $
**
**  Read batchfiles on standard input and archive them.
*/

#include "config.h"
#include "clibrary.h"
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <time.h>

#ifdef TM_IN_SYS_TIME
# include <sys/time.h>
#endif

#include "inn/innconf.h"
#include "inn/messages.h"
#include "inn/wire.h"
#include "libinn.h"
#include "paths.h"
#include "storage.h"


static char	*Archive = NULL;
static char	*ERRLOG = NULL;

/*
**  Return a YYYYMM string that represents the current year/month
*/
static char *
DateString(void)
{
    static char		ds[10];
    time_t		now;
    struct tm		*x;

    time(&now);
    x = localtime(&now);
    snprintf(ds, sizeof(ds), "%d%d", x->tm_year + 1900, x->tm_mon + 1);

    return ds;
}


/*
**  Try to make one directory.  Return false on error.
*/
static bool
MakeDir(char *Name)
{
    struct stat		Sb;

    if (mkdir(Name, GROUPDIR_MODE) >= 0)
	return true;

    /* See if it failed because it already exists. */
    return stat(Name, &Sb) >= 0 && S_ISDIR(Sb.st_mode);
}


/*
**  Given an entry, comp/foo/bar/1123, create the directory and all
**  parent directories needed.  Return false on error.
*/
static bool
MakeArchiveDirectory(char *Name)
{
    char	*p;
    char	*save;
    bool		made;

    if ((save = strrchr(Name, '/')) != NULL)
	*save = '\0';

    /* Optimize common case -- parent almost always exists. */
    if (MakeDir(Name)) {
	if (save)
	    *save = '/';
	return true;
    }

    /* Try to make each of comp and comp/foo in turn. */
    for (p = Name; *p; p++)
	if (*p == '/' && p != Name) {
	    *p = '\0';
	    made = MakeDir(Name);
	    *p = '/';
	    if (!made) {
		if (save)
		    *save = '/';
		return false;
	    }
	}

    made = MakeDir(Name);
    if (save)
	*save = '/';
    return made;
}


/*
**  Copy a file.  Return false if error.
*/
static bool
Copy(char *src, char *dest)
{
    FILE	*in;
    FILE	*out;
    size_t	i;
    char	*p;
    char	buff[BUFSIZ];

    /* Open the output file. */
    if ((out = fopen(dest, "w")) == NULL) {
	/* Failed; make any missing directories and try again. */
	if ((p = strrchr(dest, '/')) != NULL) {
	    if (!MakeArchiveDirectory(dest)) {
                syswarn("cannot mkdir for %s", dest);
		return false;
	    }
	    out = fopen(dest, "w");
	}
	if (p == NULL || out == NULL) {
            syswarn("cannot open %s for writing", dest);
	    return false;
	}
    }

    /* Opening the input file is easier. */
    if ((in = fopen(src, "r")) == NULL) {
        syswarn("cannot open %s for reading", src);
	fclose(out);
	unlink(dest);
	return false;
    }

    /* Write the data. */
    while ((i = fread(buff, 1, sizeof buff, in)) != 0)
	if (fwrite(buff, 1, i, out) != i) {
            syswarn("cannot write to %s", dest);
	    fclose(in);
	    fclose(out);
	    unlink(dest);
	    return false;
	}
    fclose(in);

    /* Flush and close the output. */
    if (ferror(out) || fflush(out) == EOF) {
        syswarn("cannot flush %s", dest);
	unlink(dest);
	fclose(out);
	return false;
    }
    if (fclose(out) == EOF) {
        syswarn("cannot close %s", dest);
	unlink(dest);
	return false;
    }

    return true;
}


/*
**  Copy an article from memory into a file.
*/
static bool
CopyArt(ARTHANDLE *art, char *dest, bool Concat)
{
    FILE	*out;
    const char		*p;
    char		*q, *article;
    size_t		i;
    const char		*mode = "w";

    if (Concat) mode = "a";

    /* Open the output file. */
    if ((out = fopen(dest, mode)) == NULL) {
	/* Failed; make any missing directories and try again. */
	if ((p = strrchr(dest, '/')) != NULL) {
	    if (!MakeArchiveDirectory(dest)) {
                syswarn("cannot mkdir for %s", dest);
		return false;
	    }
	    out = fopen(dest, mode);
	}
	if (p == NULL || out == NULL) {
            syswarn("cannot open %s for writing", dest);
	    return false;
	}
    }

    /* Copy the data. */
    article = xmalloc(art->len);
    for (i=0, q=article, p=art->data; p<art->data+art->len;) {
	if (&p[1] < art->data + art->len && p[0] == '\r' && p[1] == '\n') {
	    p += 2;
	    *q++ = '\n';
	    i++;
	    if (&p[1] < art->data + art->len && p[0] == '.' && p[1] == '.') {
		p += 2;
		*q++ = '.';
		i++;
	    }
	    if (&p[2] < art->data + art->len && p[0] == '.' && p[1] == '\r' && p[2] == '\n') {
		break;
	    }
	} else {
	    *q++ = *p++;
	    i++;
	}
    }
    *q++ = '\0';

    /* Write the data. */
    if (Concat) {
	/* Write a separator... */
	fprintf(out, "-----------\n");
    }
    if (fwrite(article, i, 1, out) != 1) {
        syswarn("cannot write to %s", dest);
	fclose(out);
	if (!Concat) unlink(dest);
	free(article);
	return false;
    }
    free(article);

    /* Flush and close the output. */
    if (ferror(out) || fflush(out) == EOF) {
        syswarn("cannot flush %s", dest);
	if (!Concat) unlink(dest);
	fclose(out);
	return false;
    }
    if (fclose(out) == EOF) {
        syswarn("cannot close %s", dest);
	if (!Concat) unlink(dest);
	return false;
    }

    return true;
}


/*
**  Write an index entry.  Ignore I/O errors; our caller checks for them.
*/
static void
WriteArtIndex(ARTHANDLE *art, char *ShortName)
{
    const char	*p;
    int	i;
    char		Subject[BUFSIZ];
    char		MessageID[BUFSIZ];

    Subject[0] = '\0';		/* default to null string */
    p = wire_findheader(art->data, art->len, "Subject");
    if (p != NULL) {
	for (i=0; *p != '\r' && *p != '\n' && *p != '\0'; i++) {
	    Subject[i] = *p++;
	}
	Subject[i] = '\0';
    }

    MessageID[0] = '\0';	/* default to null string */
    p = wire_findheader(art->data, art->len, "Message-ID");
    if (p != NULL) {
	for (i=0; *p != '\r' && *p != '\n' && *p != '\0'; i++) {
	    MessageID[i] = *p++;
	}
	MessageID[i] = '\0';
    }

    printf("%s %s %s\n",
	    ShortName,
	    MessageID[0] ? MessageID : "<none>",
	    Subject[0] ? Subject : "<none>");
}


/*
** Crack an Xref line apart into separate strings, each of the form "ng:artnum".
** Return in "lenp" the number of newsgroups found.
** 
** This routine blatantly stolen from tradspool.c
*/
static char **
CrackXref(const char *xref, unsigned int *lenp) {
    char *p;
    char **xrefs;
    char *q;
    unsigned int len, xrefsize;

    len = 0;
    xrefsize = 5;
    xrefs = xmalloc(xrefsize * sizeof(char *));

    /* skip pathhost */
    if ((p = strchr(xref, ' ')) == NULL) {
        warn("cannot find pathhost in Xref header");
	return NULL;
    }
    /* skip next spaces */
    for (p++; *p == ' ' ; p++) ;
    while (true) {
	/* check for EOL */
	/* shouldn't ever hit null w/o hitting a \r\n first, but best to be paranoid */
	if (*p == '\n' || *p == '\r' || *p == 0) {
	    /* hit EOL, return. */
	    *lenp = len;
	    return xrefs;
	}
	/* skip to next space or EOL */
	for (q=p; *q && *q != ' ' && *q != '\n' && *q != '\r' ; ++q) ;

        xrefs[len] = xstrndup(p, q - p);

	if (++len == xrefsize) {
	    /* grow xrefs if needed. */
	    xrefsize *= 2;
            xrefs = xrealloc(xrefs, xrefsize * sizeof(char *));
	}

 	p = q;
	/* skip spaces */
	for ( ; *p == ' ' ; p++) ;
    }
}


/*
** Crack an groups pattern parameter apart into separate strings
** Return in "lenp" the number of patterns found.
*/
static char **
CrackGroups(char *group, unsigned int *lenp) {
    char *p;
    char **groups;
    char *q;
    unsigned int len, grpsize;

    len = 0;
    grpsize = 5;
    groups = xmalloc(grpsize * sizeof(char *));

    /* skip leading spaces */
    for (p=group; *p == ' ' ; p++) ;
    while (true) {
	/* check for EOL */
	/* shouldn't ever hit null w/o hitting a \r\n first, but best to be paranoid */
	if (*p == '\n' || *p == '\r' || *p == 0) {
	    /* hit EOL, return. */
	    *lenp = len;
	    return groups;
	}
	/* skip to next comma, space, or EOL */
	for (q=p; *q && *q != ',' && *q != ' ' && *q != '\n' && *q != '\r' ; ++q) ;

        groups[len] = xstrndup(p, q - p);

	if (++len == grpsize) {
	    /* grow groups if needed. */
	    grpsize *= 2;
            groups = xrealloc(groups, grpsize * sizeof(char *));
	}

 	p = q;
	/* skip commas and spaces */
	for ( ; *p == ' ' || *p == ',' ; p++) ;
    }
}


int
main(int ac, char *av[])
{
    char	*Name;
    char	*p;
    FILE	*F;
    int	i;
    bool		Flat;
    bool		Redirect;
    bool		Concat;
    char		*Index;
    char		buff[BUFSIZ];
    char		*spool;
    char		dest[BUFSIZ];
    char		**groups, *q, *ng;
    char		**xrefs;
    const char		*xrefhdr;
    ARTHANDLE		*art;
    TOKEN		token;
    unsigned int	numgroups, numxrefs;
    int			j;
    char		*base = NULL;
    bool		doit;

    /* First thing, set up our identity. */
    message_program_name = "archive";

    /* Set defaults. */
    if (!innconf_read(NULL))
        exit(1);
    Concat = false;
    Flat = false;
    Index = NULL;
    Redirect = true;
    umask(NEWSUMASK);
    ERRLOG = concatpath(innconf->pathlog, _PATH_ERRLOG);
    Archive = innconf->patharchive;
    groups = NULL;
    numgroups = 0;

    /* Parse JCL. */
    while ((i = getopt(ac, av, "a:cfi:p:r")) != EOF)
	switch (i) {
	default:
            die("usage error");
            break;
	case 'a':
	    Archive = optarg;
	    break;
	case 'c':
	    Flat = true;
	    Concat = true;
	    break;
	case 'f':
	    Flat = true;
	    break;
	case 'i':
	    Index = optarg;
	    break;
	case 'p':
	    groups = CrackGroups(optarg, &numgroups);
	    break;
	case 'r':
	    Redirect = false;
	    break;
	}

    /* Parse arguments -- at most one, the batchfile. */
    ac -= optind;
    av += optind;
    if (ac > 2)
        die("usage error");

    /* Do file redirections. */
    if (Redirect)
	freopen(ERRLOG, "a", stderr);
    if (ac == 1 && freopen(av[0], "r", stdin) == NULL)
        sysdie("cannot open %s for input", av[0]);
    if (Index && freopen(Index, "a", stdout) == NULL)
        sysdie("cannot open %s for output", Index);

    /* Go to where the action is. */
    if (chdir(innconf->patharticles) < 0)
        sysdie("cannot chdir to %s", innconf->patharticles);

    /* Set up the destination. */
    strcpy(dest, Archive);
    Name = dest + strlen(dest);
    *Name++ = '/';

    if (!SMinit())
        die("cannot initialize storage manager: %s", SMerrorstr);

    /* Read input. */
    while (fgets(buff, sizeof buff, stdin) != NULL) {
	if ((p = strchr(buff, '\n')) == NULL) {
            warn("skipping %.40s: too long", buff);
	    continue;
	}
	*p = '\0';
	if (buff[0] == '\0' || buff[0] == '#')
	    continue;

	/* Check to see if this is a token... */
	if (IsToken(buff)) {
	    /* Get a copy of the article. */
	    token = TextToToken(buff);
	    if ((art = SMretrieve(token, RETR_ALL)) == NULL) {
                warn("cannot retrieve %s", buff);
		continue;
	    }

	    /* Determine groups from the Xref header */
    	    xrefhdr = wire_findheader(art->data, art->len, "Xref");
	    if (xrefhdr == NULL) {
                warn("cannot find Xref header");
		SMfreearticle(art);
		continue;
	    }

	    if ((xrefs = CrackXref(xrefhdr, &numxrefs)) == NULL || numxrefs == 0) {
                warn("bogus Xref header");
		SMfreearticle(art);
		continue;
	    }

	    /* Process each newsgroup... */
	    if (base) {
		free(base);
		base = NULL;
	    }
	    for (i=0; (unsigned)i<numxrefs; i++) {
		/* Check for group limits... -p flag */
		if ((p=strchr(xrefs[i], ':')) == NULL) {
                    warn("bogus Xref entry %s", xrefs[i]);
		    continue;	/* Skip to next xref */
		}
		if (numgroups > 0) {
		    *p = '\0';
		    ng = xrefs[i];
		    doit = false;
		    for (j=0; (unsigned)j<numgroups && !doit; j++) {
			if (uwildmat(ng, groups[j]) != 0) doit=true;
		    }
		}
		else {
		    doit = true;
		}
		*p = '/';
		if (doit) {
		    p = Name;
		    q = xrefs[i];
		    while(*q) {
		        *p++ = *q++;
		    }
		    *p='\0';

		    if (!Flat) {
		        for (p=Name; *p; p++) {
			    if (*p == '.') {
			        *p = '/';
			    }
		        }
		    }

		    if (Concat) {
			p = strrchr(Name, '/');
			q = DateString();
			p++;
			while (*q) {
			    *p++ = *q++;
			}
			*p = '\0';
		    }
			
		    if (base && !Concat) {
			/* Try to link the file into the archive. */
			if (link(base, dest) < 0) {

			    /* Make the archive directory. */
			    if (!MakeArchiveDirectory(dest)) {
                                syswarn("cannot mkdir for %s", dest);
				continue;
			    }

			    /* Try to link again; if that fails, make a copy. */
			    if (link(base, dest) < 0) {
#if	defined(HAVE_SYMLINK)
				if (symlink(base, dest) < 0)
                                    syswarn("cannot symlink %s to %s",
                                            dest, base);
				else
#endif	/* defined(HAVE_SYMLINK) */
				if (!Copy(base, dest))
				    continue;
				continue;
			    }
			}
		    } else {
			if (!CopyArt(art, dest, Concat))
                            syswarn("copying %s to %s failed", buff, dest);
			base = xstrdup(dest);
		    }

	            /* Write index. */
	            if (Index) {
	                WriteArtIndex(art, Name);
	                if (ferror(stdout) || fflush(stdout) == EOF)
                            syswarn("cannot write index for %s", Name);
	            }
		}
	    }

	    /* Free up the article storage space */
	    SMfreearticle(art);
	    art = NULL;
	    /* Free up the xrefs storage space */
	    for ( i=0; (unsigned)i<numxrefs; i++) free(xrefs[i]);
	    free(xrefs);
	    numxrefs = 0;
	    xrefs = NULL;
	} else {
            warn("%s is not a token", buff);
	    continue;
	}
    }

    /* close down the storage manager api */
    SMshutdown();

    /* If we read all our input, try to remove the file, and we're done. */
    if (feof(stdin)) {
	fclose(stdin);
	if (av[0])
	    unlink(av[0]);
	exit(0);
    }

    /* Make an appropriate spool file. */
    p = av[0];
    if (p == NULL)
        spool = concatpath(innconf->pathoutgoing, "archive");
    else if (*p == '/')
        spool = concat(p, ".bch", (char *) 0);
    else
        spool = concat(innconf->pathoutgoing, "/", p, ".bch", (char *) 0);
    if ((F = xfopena(spool)) == NULL)
        sysdie("cannot spool to %s", spool);

    /* Write the rest of stdin to the spool file. */
    i = 0;
    if (fprintf(F, "%s\n", buff) == EOF) {
        syswarn("cannot start spool");
	i = 1;
    }
    while (fgets(buff, sizeof buff, stdin) != NULL) 
	if (fputs(buff, F) == EOF) {
            syswarn("cannot write to spool");
	    i = 1;
	    break;
	}
    if (fclose(F) == EOF) {
        syswarn("cannot close spool");
	i = 1;
    }

    /* If we had a named input file, try to rename the spool. */
    if (p != NULL && rename(spool, av[0]) < 0) {
        syswarn("cannot rename spool");
	i = 1;
    }

    exit(i);
    /* NOTREACHED */
}