Codebase list cyrus-imapd / debian/2.4.9_beta1-1 imap / squatter.c
debian/2.4.9_beta1-1

Tree @debian/2.4.9_beta1-1 (Download .tar.gz)

squatter.c @debian/2.4.9_beta1-1raw · history · blame

  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
/* squatter.c -- SQUAT-based message indexing tool
 *
 * Copyright (c) 1994-2008 Carnegie Mellon University.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The name "Carnegie Mellon University" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For permission or any legal
 *    details, please contact
 *      Carnegie Mellon University
 *      Center for Technology Transfer and Enterprise Creation
 *      4615 Forbes Avenue
 *      Suite 302
 *      Pittsburgh, PA  15213
 *      (412) 268-7393, fax: (412) 268-7395
 *      innovation@andrew.cmu.edu
 *
 * 4. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by Computing Services
 *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
 *
 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
 * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * $Id: squatter.c,v 1.26 2010/06/28 12:04:20 brong Exp $
 */

/*
  This is the tool that creates SQUAT indexes for Cyrus mailboxes.

  SQUAT index files are organised as follows:

  There is (at most) one index file for each Cyrus mailbox, named
  "cyrus.squat", stored in the mailbox directory.

  Source documents are named 'xUID' where UID is the numeric UID of a
  message and x is a character denoting a part of the message: 'f' ==
  FROM, 't' == TO, 'b' == BCC, 'c' == CC, 's' == SUBJECT, 'h' == other
  headers, 'm' == the body. So, a messge with UID 331 could give rise
  to several source documents named "f331", "t331", "b331", "c331",
  "s331", "h331"  and "m331".

  There is also a special source document named "validity.N" where N
  is the validitity nonce for the mailbox. We use this to detect when
  the UIDs have been renumbered since we created the index (in which
  case the index is useless and is ignored).

  This tool creates new indexes for one or more mailboxes. (We do not
  support incremental updates to an index yet.) The index is created
  in "cyrus.squat.tmp" and then, if creation was successful, it is
  atomically renamed to "cyrus.squat". This guarantees that we don't
  interfere with anyone who has the old index open.
*/

#include <config.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <syslog.h>
#include <string.h>

#include "annotate.h"
#include "assert.h"
#include "mboxlist.h"
#include "global.h"
#include "exitcodes.h"
#include "imap_err.h"
#include "mailbox.h"
#include "xmalloc.h"
#include "xstrlcpy.h"
#include "xstrlcat.h"
#include "acl.h"
#include "seen.h"
#include "mboxname.h"
#include "map.h"
#include "squat.h"
#include "index.h"
#include "util.h"

/* global state */
const int config_need_data = CONFIG_NEED_PARTITION_DATA;

extern char *optarg;
extern int optind;

/* current namespace */
static struct namespace squat_namespace;

/* These stats are gathered 1) per mailbox and 2) for the whole operation. */
typedef struct {
  unsigned long indexed_bytes;    /* How many bytes of processed message text
			   have we indexed? */
  unsigned long indexed_messages; /* How many messages have we indexed? */
  unsigned long index_size;       /* How many bytes is the index using? */
  time_t start_time;    /* When did this operation start? */
  time_t end_time;      /* When did it end? */
} SquatStats;

const int SKIP_FUZZ = 60;

static int verbose = 0;
static int mailbox_count = 0;
static int skip_unmodified = 0;
static int incremental_mode = 0;
static SquatStats total_stats;

static void start_stats(SquatStats* stats) {
  stats->index_size = 0;
  stats->indexed_bytes = 0;
  stats->indexed_messages = 0;
  stats->start_time = time(NULL);
}

static void stop_stats(SquatStats* stats) {
  stats->end_time = time(NULL);
}

static void print_stats(FILE* out, SquatStats* stats) {
  fprintf(out, "Indexed %lu messages (%lu bytes) "
          "into %lu index bytes in %d seconds\n",
          stats->indexed_messages, stats->indexed_bytes,
          stats->index_size, (int) (stats->end_time - stats->start_time));
}

static int usage(const char *name)
{
    fprintf(stderr,
	    "usage: %s [-C <alt_config>] [-r] [-s] [-a] [-v] [mailbox...]\n",
	    name);
 
    exit(EC_USAGE);
}

static void fatal_syserror(const char* s)
{
  perror(s);
  exit(99);
}

static void fatal_squat_error(const char* s)
{
  int err = squat_get_last_error();

  switch (err) {
  case SQUAT_ERR_OUT_OF_MEMORY:
    fprintf(stderr, "SQUAT: Out of memory (%s)\n", s);
    break;
  case SQUAT_ERR_SYSERR:
    perror(s);
    break;
  default:
    /* There are other error codes, but they only apply for searching,
       not index construction */
    fprintf(stderr, "SQUAT: Unknown error %d (%s)\n", err, s);
  }

  exit(98);
}

/* ====================================================================== */

/* uid_info is used to track which messages exist in old squat index, by
 * parsing document names (e.g: m456. is part of message UID 456).
 */

struct uid_item {
  unsigned long uid;
  int flagged;
};

struct uid_info {
  struct uid_item *list;
  unsigned long len;
  unsigned long uidvalidity;
  int valid;
};

static void uid_info_init(struct uid_info *uid_info, unsigned long exists)
{
  uid_info->list = xmalloc((exists+1)*sizeof(struct uid_item));
  uid_info->len  = exists;
  uid_info->uidvalidity = 0L;
  uid_info->valid = 1;
}

static void uid_info_free(struct uid_info *uid_info)
{
  if (uid_info->list != NULL)
    free(uid_info->list);

  uid_info->list = NULL;
}

static void uid_item_init(struct uid_item *uid_item, unsigned long uid)
{
  uid_item->uid = uid;
  uid_item->flagged = 0;
}

static struct uid_item *find_uid_item(struct uid_info *uid_info,
                                      unsigned long uid)
{
  struct uid_item *list = uid_info->list;
  unsigned long first = 0;
  unsigned long last  = uid_info->len;

  /* Binary chop on sorted array */
  while (first < last) {
    unsigned long middle = (first + last) / 2;

    if (list[middle].uid == uid)
      return(&list[middle]);
    if (list[middle].uid < uid)
      first = middle + 1;
    else
      last = middle;
  }
  return(NULL);
}

/* Populate uid_info map using document names from SquatSearchIndex backend */
static int doc_check(void *closure, SquatListDoc const* doc)
{
  struct uid_info *uid_info = (struct uid_info *)closure;
  struct uid_item *uid_item;
  unsigned long uid;

  /* validity will be replaced with new value in same slot */
  if  (!strncmp(doc->doc_name, "validity.", 9)) {
    uid_info->uidvalidity = strtoul(doc->doc_name+9, NULL, 10);
    return(1);
  }

  if (!strchr("tfcbsmh", doc->doc_name[0])) {
    syslog(LOG_ERR, "Invalid document name: %s", doc->doc_name);
    uid_info->valid = 0;
    return(1);
  }

  uid = strtoul(doc->doc_name+1, NULL, 10);
  if ((uid > 0) && (uid_item=find_uid_item(uid_info, uid))) {
    uid_item->flagged = 1;
    return(1);
  }

  /* Remove this UID from the index */
  return(0);
}

/* ====================================================================== */


typedef struct {
  SquatStats* mailbox_stats;
  SquatIndex* index;
  struct mailbox* mailbox;
} SquatReceiverData;

/* Cyrus passes the text to index in here, after it has canonicalized
   the text. We figure out what source document the text belongs to,
   and update the index. */
static void search_text_receiver(int uid, int part, int cmd,
                                 char const* text, int text_len, void* rock) {
  SquatReceiverData* d = (SquatReceiverData*)rock;

  if ((cmd & SEARCHINDEX_CMD_BEGINPART) != 0) {
    char buf[100];
    char part_char = 0;
    
    /* Figure out what the name of the source document is going to be. */
    switch (part) {
    case SEARCHINDEX_PART_FROM: part_char = 'f'; break;
    case SEARCHINDEX_PART_TO:   part_char = 't'; break;
    case SEARCHINDEX_PART_CC:   part_char = 'c'; break;
    case SEARCHINDEX_PART_BCC:  part_char = 'b'; break;
    case SEARCHINDEX_PART_SUBJECT: part_char = 's'; break;
    case SEARCHINDEX_PART_HEADERS: part_char = 'h'; break;
    case SEARCHINDEX_PART_BODY:
      part_char = 'm';
      d->mailbox_stats->indexed_messages++;
      total_stats.indexed_messages++;
      break;
    default:
      fatal("Unknown search_text part", EC_SOFTWARE);
    }

    snprintf(buf, sizeof(buf), "%c%d", part_char, uid);

    /* don't index document parts that are going to be empty (or too
       short to search) */
    if ((cmd & SEARCHINDEX_CMD_ENDPART) != 0
        && ((cmd & SEARCHINDEX_CMD_APPENDPART) == 0
            || text_len < SQUAT_WORD_SIZE)) {
      if (verbose > 2) {
        printf("Skipping tiny document part '%s' (size %d)\n", buf,
               (cmd & SEARCHINDEX_CMD_APPENDPART) == 0 ? 0 : text_len);
      }
      return;
    }

    if (verbose > 2) {
      printf("Opening document part '%s'\n", buf);
    }

    if (squat_index_open_document(d->index, buf) != SQUAT_OK) {
      fatal_squat_error("Writing index");
    }
  }

  if ((cmd & SEARCHINDEX_CMD_APPENDPART) != 0) {
    if (verbose > 3) {
      printf("Writing %d bytes into message %d\n", text_len, uid);
    }

    if (squat_index_append_document(d->index, text, text_len) != SQUAT_OK) {
      fatal_squat_error("Writing index data");
    }
    d->mailbox_stats->indexed_bytes += text_len;
    total_stats.indexed_bytes += text_len;
  }

  if ((cmd & SEARCHINDEX_CMD_ENDPART) != 0) {
    if (squat_index_close_document(d->index) != SQUAT_OK) {
      fatal_squat_error("Writing index update");
    }
  }
}

/* Let SQUAT tell us what's going on in the expensive
   squat_index_finish function. */
static void stats_callback(void* closure __attribute__((unused)),
			   SquatStatsEvent* params) {
  switch (params->generic.type) {
  case SQUAT_STATS_COMPLETED_INITIAL_CHAR:
    if (verbose > 1) {
      if (params->completed_initial_char.num_words > 0) {
        printf("Processing index character %d, %d total words, "
               "temp file size is %d\n",
               params->completed_initial_char.completed_char,
               params->completed_initial_char.num_words,
               params->completed_initial_char.temp_file_size);
      }
    }
    break;

  default:
    ; /* do nothing */
  }
}

/* Squat a single open mailbox */
static int squat_single(struct index_state *state, int incremental)
{
    struct mailbox *mailbox = state->mailbox;
    char *fname;
    char *newfname;
    SquatStats stats;
    SquatOptions options;
    SquatReceiverData data;
    SquatSearchIndex *old_index = NULL;
    char uid_validity_buf[30];
    struct uid_info  uid_info;
    struct uid_item *uid_item;
    struct stat index_file_info;
    unsigned long lastuid;
    uint32_t msgno;
    int new_index_fd = -1;
    int old_index_fd = -1;
    int r = 0;               /* Using IMAP_* not SQUAT_* return codes here */

    uid_info_init(&uid_info, state->exists);

    newfname = mailbox_meta_newfname(mailbox, META_SQUAT);
    if ((new_index_fd = open(newfname, O_CREAT|O_TRUNC|O_WRONLY, 0666)) < 0)
	fatal_syserror("Unable to create temporary index file");

    options.option_mask = SQUAT_OPTION_TMP_PATH | SQUAT_OPTION_STATISTICS;
    options.tmp_path = mailbox_datapath(mailbox);
    options.stats_callback = stats_callback;
    options.stats_callback_closure = NULL;
    data.index = squat_index_init(new_index_fd, &options);
    if (data.index == NULL)
	fatal_squat_error("Initializing index");

    lastuid = 0;
    uid_item = uid_info.list;
    for (msgno = 1; msgno <= state->exists ; msgno++) {
	lastuid = state->map[msgno-1].record.uid;
	uid_item_init(&uid_item[msgno-1], lastuid);
    }
    /* Add zero UID as an end of list marker: uid_info_init() assigned space */
    uid_item_init(&uid_item[state->exists], 0);

    /* Open existing index if it exists */
    fname = mailbox_meta_fname(mailbox, META_SQUAT);
    old_index_fd   = -1;
    old_index = NULL;
    if (incremental &&
        ((old_index_fd = open(fname, O_RDONLY)) >= 0) &&
        (old_index = squat_search_open(old_index_fd)) == NULL) {
      close(old_index_fd);
      old_index_fd = -1;
    }

    /* Fall back to full update if open() or squat_search_open() failed */
    if (!old_index) incremental = 0;

    if (incremental) {
      /* Copy existing document names verbatim. They end up with the same
       * doc_IDs as in the old index, which makes trie copying much simpler.
       */
      uid_info.valid       = 1;
      uid_info.uidvalidity = 0L;
      squat_index_add_existing(data.index, old_index, doc_check, &uid_info);

      if (!uid_info.valid) {
        syslog(LOG_ERR,
               "Corrupt squat index for %s, retrying without incremental",
               mailbox->name);
        r = IMAP_IOERROR;
        goto bail;
      }

      if (uid_info.uidvalidity != mailbox->i.uidvalidity) {
        /* Squat file refers to old mailbox: force full rebuild */
        r = IMAP_IOERROR;
        goto bail;
      }
    } else {
      /* write an empty document at the beginning to record the validity
         nonce */
      snprintf(uid_validity_buf, sizeof(uid_validity_buf), 
               "validity.%u", mailbox->i.uidvalidity);
      if (squat_index_open_document(data.index, uid_validity_buf) != SQUAT_OK
          || squat_index_close_document(data.index) != SQUAT_OK) {
        fatal_squat_error("Writing index");
      }
    }

    data.mailbox       = mailbox;
    data.mailbox_stats = &stats;
    start_stats(&stats);

    uid_item =  uid_info.list;
    for (msgno = 1; msgno <= state->exists ; msgno++) {
	unsigned uid = state->map[msgno-1].record.uid;
	/* Scan uid_item list for matching UID (ascending order, 0 termination) */
	while (uid_item->uid && (uid_item->uid < uid))
	    uid_item++;

	if ((uid_item->uid == uid) && uid_item->flagged)
	    continue;

	/* This UID didn't appear in the old index file */
	index_getsearchtext_single(state, msgno, search_text_receiver, &data);
	uid_item->flagged = 1;
    }

    if (squat_index_finish(data.index) != SQUAT_OK) {
	if (incremental) {
	    syslog(LOG_ERR,
		   "Corrupt squat index %s, retrying without incremental update",
		   mailbox->name);
	    r = IMAP_IOERROR;
	    goto bail;
	}
	/* Just give up if not incremental */
	fatal_squat_error("Closing index");
    }

    /* Check how big the resulting file is */
    if (fstat(new_index_fd, &index_file_info) < 0) {
      fatal_syserror("Unable to stat temporary index file");
    }
    stats.index_size        = index_file_info.st_size;
    total_stats.index_size += index_file_info.st_size;

    if (close(new_index_fd) < 0) {
      fatal_syserror("Unable to complete writing temporary index file");
    }
    new_index_fd = -1;

    /* OK, we successfully created the index under the temporary file name.
       Let's rename it to make it the real index. */
    if (mailbox_meta_rename(mailbox, META_SQUAT) < 0) {
	fatal_syserror("Unable to rename temporary index file");
    }

    stop_stats(&stats);
    if (verbose > 0) {
	print_stats(stdout, &stats);
    }

 bail:
    if (old_index)             squat_search_close(old_index);
    if (old_index_fd >= 0)     close(old_index_fd);
    if (new_index_fd >= 0)     close(new_index_fd);
    uid_info_free(&uid_info);

    return(r);
}

/* This is called once for each mailbox we're told to index. */
static int index_me(char *name, int matchlen __attribute__((unused)),
		    int maycreate __attribute__((unused)),
		    void *rock) {
    struct mboxlist_entry mbentry;
    struct index_state *state = NULL;
    int r;
    char *fname;
    struct stat sbuf;
    char extname[MAX_MAILBOX_BUFFER];
    int use_annot = *((int *) rock);

    /* Convert internal name to external */
    (*squat_namespace.mboxname_toexternal)(&squat_namespace, name,
					   NULL, extname);

    /* Skip remote mailboxes */
    r = mboxlist_lookup(name, &mbentry, NULL);
    if (r) {
        if (verbose) {
            printf("error opening looking up %s: %s\n",
		   extname, error_message(r));
        }
        syslog(LOG_INFO, "error opening looking up %s: %s\n",
               extname, error_message(r));

        return 1;
    }
    if (mbentry.mbtype & MBTYPE_REMOTE) return 0;

    /* make sure the mailbox (or an ancestor) has
       /vendor/cmu/cyrus-imapd/squat set to "true" */
    if (use_annot) {
	char buf[MAX_MAILBOX_BUFFER] = "", *p;
	struct annotation_data attrib;
	int domainlen = 0;

	if (config_virtdomains && (p = strchr(name, '!')))
	    domainlen = p - name + 1;

	strlcpy(buf, name, sizeof(buf));

	/* since mailboxes inherit /vendor/cmu/cyrus-imapd/squat,
	   we need to iterate all the way up to "" (server entry) */
	while (1) {
	    r = annotatemore_lookup(buf, "/vendor/cmu/cyrus-imapd/squat", "",
				    &attrib);

	    if (r ||				/* error */
		attrib.value ||			/* found an entry */
		!buf[0]) {			/* done recursing */
		break;
	    }

	    p = strrchr(buf, '.');		/* find parent mailbox */

	    if (p && (p - buf > domainlen))	/* don't split subdomain */
		*p = '\0';
	    else if (!buf[domainlen])		/* server entry */
		buf[0] = '\0';
	    else				/* domain entry */
		buf[domainlen] = '\0';
	}

	if (r || !attrib.value || strcasecmp(attrib.value, "true"))
	    return 0;
    }

    r = index_open(name, NULL, &state);
    if (r) {
        if (verbose) {
            printf("error opening %s: %s\n", extname, error_message(r));
        }
        syslog(LOG_INFO, "error opening %s: %s\n", extname, error_message(r));

        return 1;
    }

    fname = mailbox_meta_fname(state->mailbox, META_SQUAT);

    /* process only changed mailboxes if skip option delected. */
    if (skip_unmodified && !stat(fname, &sbuf)) {
        if (SKIP_FUZZ + state->mailbox->index_mtime < sbuf.st_mtime) {
            syslog(LOG_DEBUG, "skipping mailbox %s", extname);
            if (verbose > 0) {
                printf("Skipping mailbox %s\n", extname);
            }
            index_close(&state);
            return 0;
        }
    }

    syslog(LOG_INFO, "indexing mailbox %s... ", extname);
    if (verbose > 0) {
      printf("Indexing mailbox %s... ", extname);
    }

    if (!incremental_mode || (squat_single(state, 1) != 0)) {
      /* Fall back to complete squat */
      squat_single(state, 0);
    }

    index_close(&state);
    mailbox_count++;

    return 0;
}

struct tmpnode {
    struct tmpnode *next;
    char *name;
};
struct tmplist {
    struct tmpnode *head;
    struct tmpnode *tail;
};

static int addmbox(char *name,
		   int matchlen __attribute__((unused)),
		   int maycreate __attribute__((unused)),
		   void *rock)
{
    struct tmplist **lptr = (struct tmplist **) rock;
    struct tmplist *l = *lptr;
    struct tmpnode *n = xmalloc(sizeof (struct tmpnode));

    n->next = NULL;
    n->name = xstrdup(name);

    if (l->head) {
        l->tail->next = n;
        l->tail = l->tail->next;
    } else {
        l->head = l->tail = n;
    }

    return 0;
}

int main(int argc, char **argv)
{
    int opt;
    char *alt_config = NULL;
    int rflag = 0, use_annot = 0;
    int i;
    char buf[MAX_MAILBOX_PATH+1];
    int r;

    if ((geteuid()) == 0 && (become_cyrus() != 0)) {
	fatal("must run as the Cyrus user", EC_USAGE);
    }

    setbuf(stdout, NULL);

    while ((opt = getopt(argc, argv, "C:rsiav")) != EOF) {
	switch (opt) {
	case 'C': /* alt config file */
          alt_config = optarg;
          break;

        case 'v': /* verbose */
          verbose++;
          break;

	case 'r': /* recurse */
	  rflag = 1;
	  break;

	case 's': /* skip unmodifed */
	  skip_unmodified = 1;
          break;

	case 'i': /* incremental mode */
	  incremental_mode = 1;
          break;

	case 'a': /* use /squat annotation */
	  use_annot = 1;
	  break;

	default:
	    usage("squatter");
	}
    }

    cyrus_init(alt_config, "squatter", 0);

    syslog(LOG_NOTICE, "indexing mailboxes");

    /* Set namespace -- force standard (internal) */
    if ((r = mboxname_init_namespace(&squat_namespace, 1)) != 0) {
	fatal(error_message(r), EC_CONFIG);
    }

    annotatemore_init(0, NULL, NULL);
    annotatemore_open(NULL);

    mboxlist_init(0);
    mboxlist_open(NULL);

    start_stats(&total_stats);

    if (optind == argc) {
        struct tmplist *l;
        struct tmpnode *current;

        l = xmalloc(sizeof(struct tmplist));
        l->head = l->tail = NULL;

	if (rflag) {
	    fprintf(stderr, "please specify a mailbox to recurse from\n");
	    exit(EC_USAGE);
	}
	assert(!rflag);
	strlcpy(buf, "*", sizeof(buf));
	(*squat_namespace.mboxlist_findall)(&squat_namespace, buf, 1,
					    0, 0, addmbox, &l);

        for (current = l->head; current; current = current->next) {
            index_me(current->name, strlen(current->name), 0, &use_annot);
            /* Ignore errors: most will be mailboxes moving around */
        }
    }

    for (i = optind; i < argc; i++) {
	/* Translate any separators in mailboxname */
	(*squat_namespace.mboxname_tointernal)(&squat_namespace, argv[i],
					       NULL, buf);
	index_me(buf, 0, 0, &use_annot);
	if (rflag) {
	    strlcat(buf, ".*", sizeof(buf));
	    (*squat_namespace.mboxlist_findall)(&squat_namespace, buf, 1,
						0, 0, index_me, &use_annot);
	}
    }

    if (verbose > 0 && mailbox_count > 1) {
      stop_stats(&total_stats);
      printf("Total over all mailboxes: ");
      print_stats(stdout, &total_stats);
    }

    syslog(LOG_NOTICE, "done indexing mailboxes");

    seen_done();
    mboxlist_close();
    mboxlist_done();
    annotatemore_close();
    annotatemore_done();

    cyrus_done();
    
    return 0;
}