Coverage Report

Created: 2026-10-31 06:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pigeonhole/src/lib-sieve/sieve-binary-file.c
Line
Count
Source
1
/* Copyright (c) Pigeonhole authors, see top-level COPYING file */
2
3
#include "lib.h"
4
#include "str.h"
5
#include "str-sanitize.h"
6
#include "mempool.h"
7
#include "buffer.h"
8
#include "hash.h"
9
#include "array.h"
10
#include "ostream.h"
11
#include "eacces-error.h"
12
#include "safe-mkstemp.h"
13
#include "file-lock.h"
14
15
#include "sieve-common.h"
16
#include "sieve-error.h"
17
#include "sieve-extensions.h"
18
#include "sieve-code.h"
19
#include "sieve-script.h"
20
#include "sieve-script-private.h"
21
#include "sieve-storage-private.h"
22
#include "sieve-rusage.h"
23
24
#include "sieve-binary-private.h"
25
26
#include <sys/types.h>
27
#include <sys/stat.h>
28
#include <unistd.h>
29
#include <fcntl.h>
30
31
/*
32
 * Macros
33
 */
34
35
0
#define SIEVE_BINARY_MAGIC                      0xcafebabe
36
0
#define SIEVE_BINARY_MAGIC_OTHER_ENDIAN         0xbebafeca
37
38
#define SIEVE_BINARY_ALIGN(offset) \
39
0
  (((offset) + 3) & ~3U)
40
#define SIEVE_BINARY_ALIGN_PTR(ptr) \
41
  ((void *)SIEVE_BINARY_ALIGN(((size_t) ptr)))
42
43
0
#define SIEVE_BINARY_PRE_HDR_SIZE_MAJOR         1
44
0
#define SIEVE_BINARY_PRE_HDR_SIZE_MINOR         4
45
0
#define SIEVE_BINARY_PRE_HDR_SIZE_HDR_SIZE      12
46
47
/*
48
 * Header and record structures of the binary on disk
49
 */
50
51
struct sieve_binary_block_index {
52
  uint32_t id;
53
  uint32_t size;
54
  uint32_t offset;
55
  uint32_t ext_id;
56
};
57
58
struct sieve_binary_block_header {
59
  uint32_t id;
60
  uint32_t size;
61
};
62
63
/*
64
 * Utility
65
 */
66
67
static bool sieve_binary_can_update(struct sieve_binary *sbin)
68
0
{
69
0
  const char *dirpath, *p;
70
71
0
  p = strrchr(sbin->path, '/');
72
0
  if (p == NULL)
73
0
    dirpath = ".";
74
0
  else
75
0
    dirpath = t_strdup_until(sbin->path, p);
76
77
0
  return (access(dirpath, W_OK | X_OK) == 0);
78
0
}
79
80
/*
81
 * Header manipulation
82
 */
83
84
static int
85
sieve_binary_file_read_header(struct sieve_binary *sbin, int fd,
86
            struct sieve_binary_header *header_r,
87
            enum sieve_error *error_code_r)
88
0
{
89
0
  struct sieve_binary_header header;
90
0
  ssize_t rret;
91
92
0
  sieve_error_args_init(&error_code_r, NULL);
93
94
0
  rret = pread(fd, &header, sizeof(header), 0);
95
0
  if (rret == 0) {
96
0
    e_error(sbin->event, "read: "
97
0
      "file is not large enough to contain the header");
98
0
    *error_code_r = SIEVE_ERROR_NOT_VALID;
99
0
    return -1;
100
0
  } else if (rret < 0) {
101
0
    e_error(sbin->event, "read: "
102
0
      "failed to read from binary: %m");
103
0
    *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
104
0
    return -1;
105
0
  } else if (rret != sizeof(header)) {
106
0
    e_error(sbin->event, "read: "
107
0
      "header read only partially %zd/%zu",
108
0
      rret, sizeof(header));
109
0
    *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
110
0
    return -1;
111
0
  }
112
113
  /* Check header validity */
114
0
  if (header.magic != SIEVE_BINARY_MAGIC) {
115
0
    if (header.magic != SIEVE_BINARY_MAGIC_OTHER_ENDIAN) {
116
0
      e_error(sbin->event, "read: "
117
0
        "binary has corrupted header "
118
0
        "(0x%08x) or it is not a Sieve binary",
119
0
        header.magic);
120
0
    } else {
121
0
      e_error(sbin->event, "read: "
122
0
        "binary stored with in different endian format "
123
0
        "(automatically fixed when re-compiled)");
124
0
    }
125
0
    *error_code_r = SIEVE_ERROR_NOT_VALID;
126
0
    return -1;
127
0
  }
128
  /* Check binary version */
129
0
  if (header.version_major == SIEVE_BINARY_PRE_HDR_SIZE_MAJOR &&
130
0
      header.version_minor == SIEVE_BINARY_PRE_HDR_SIZE_MINOR) {
131
    /* Old header without hdr_size; clear new fields */
132
0
    static const size_t old_header_size =
133
0
      SIEVE_BINARY_PRE_HDR_SIZE_HDR_SIZE;
134
0
    memset(PTR_OFFSET(&header, old_header_size), 0,
135
0
           (sizeof(header) - old_header_size));
136
0
    header.hdr_size = old_header_size;
137
0
  } else if (header.version_major != SIEVE_BINARY_VERSION_MAJOR) {
138
    /* Binary is of different major version. Caller will have to
139
       recompile */
140
0
    bool important = (sbin->script == NULL ||
141
0
          !sieve_binary_can_update(sbin));
142
0
    enum log_type log_type = (important ?
143
0
            LOG_TYPE_ERROR : LOG_TYPE_DEBUG);
144
0
    e_log(sbin->event, log_type, "read: "
145
0
          "binary stored with different major version %d.%d "
146
0
          "(!= %d.%d; automatically fixed when re-compiled)",
147
0
          (int)header.version_major, (int)header.version_minor,
148
0
          SIEVE_BINARY_VERSION_MAJOR, SIEVE_BINARY_VERSION_MINOR);
149
0
    *error_code_r = SIEVE_ERROR_NOT_VALID;
150
0
    return -1;
151
0
  } else if (header.hdr_size < SIEVE_BINARY_BASE_HEADER_SIZE) {
152
    /* Header size is smaller than base size */
153
0
    e_error(sbin->event, "read: "
154
0
      "binary is corrupt: header size is too small");
155
0
    *error_code_r = SIEVE_ERROR_NOT_VALID;
156
0
    return -1;
157
0
  }
158
  /* Check block content */
159
0
  if (header.blocks == 0) {
160
0
    e_error(sbin->event, "read: "
161
0
      "binary is corrupt: it contains no blocks");
162
0
    *error_code_r = SIEVE_ERROR_NOT_VALID;
163
0
    return -1;
164
0
  }
165
  /* Valid */
166
0
  *header_r = header;
167
0
  return 0;
168
0
}
169
170
/* The on-disk binary header carries unused resource_usage fields for
171
   backward compatibility. Tracking lives in the per-user sieve-rusage file. */
172
static void sieve_binary_file_zero_header_rusage(struct sieve_binary *sbin)
173
0
{
174
0
  struct sieve_binary_header *header = &sbin->header;
175
176
0
  header->unused_update_time = 0;
177
0
  header->unused_cpu_time_msecs = 0;
178
0
  sieve_resource_usage_init(&sbin->rusage);
179
0
  sbin->rusage_updated = FALSE;
180
0
}
181
182
/*
183
 * Saving the binary to a file.
184
 */
185
186
static inline bool
187
_save_skip(struct sieve_binary *sbin, struct ostream *stream, size_t size)
188
0
{
189
0
  if ((o_stream_seek(stream, stream->offset + size)) <= 0) {
190
0
    e_error(sbin->event, "save: "
191
0
      "failed to skip output stream to position "
192
0
      "%"PRIuUOFF_T": %s", stream->offset + size,
193
0
      strerror(stream->stream_errno));
194
0
    return FALSE;
195
0
  }
196
197
0
  return TRUE;
198
0
}
199
200
static inline bool
201
_save_skip_aligned(struct sieve_binary *sbin, struct ostream *stream,
202
       size_t size, uoff_t *offset)
203
0
{
204
0
  uoff_t aligned_offset = SIEVE_BINARY_ALIGN(stream->offset);
205
206
0
  if ((o_stream_seek(stream, aligned_offset + size)) <= 0) {
207
0
    e_error(sbin->event, "save: "
208
0
      "failed to skip output stream to position "
209
0
      "%"PRIuUOFF_T": %s", aligned_offset + size,
210
0
      strerror(stream->stream_errno));
211
0
    return FALSE;
212
0
  }
213
214
0
  if (offset != NULL)
215
0
    *offset = aligned_offset;
216
0
  return TRUE;
217
0
}
218
219
/* FIXME: Is this even necessary for a file? */
220
static bool
221
_save_full(struct sieve_binary *sbin, struct ostream *stream,
222
     const void *data, size_t size)
223
0
{
224
0
  size_t bytes_left = size;
225
0
  const void *pdata = data;
226
227
0
  while (bytes_left > 0) {
228
0
    ssize_t ret;
229
230
0
    ret = o_stream_send(stream, pdata, bytes_left);
231
0
    if (ret <= 0) {
232
0
      e_error(sbin->event, "save: "
233
0
        "failed to write %zu bytes "
234
0
        "to output stream: %s", bytes_left,
235
0
        strerror(stream->stream_errno));
236
0
      return FALSE;
237
0
    }
238
239
0
    pdata = PTR_OFFSET(pdata, ret);
240
0
    bytes_left -= ret;
241
0
  }
242
243
0
  return TRUE;
244
0
}
245
246
static bool
247
_save_aligned(struct sieve_binary *sbin, struct ostream *stream,
248
        const void *data, size_t size, uoff_t *offset)
249
0
{
250
0
  uoff_t aligned_offset = SIEVE_BINARY_ALIGN(stream->offset);
251
252
0
  o_stream_cork(stream);
253
254
  /* Align the data by adding zeroes to the output stream */
255
0
  if (stream->offset < aligned_offset) {
256
0
    if (!_save_skip(sbin, stream,
257
0
        (aligned_offset - stream->offset)))
258
0
      return FALSE;
259
0
  }
260
261
0
  if (!_save_full(sbin, stream, data, size))
262
0
    return FALSE;
263
264
0
  o_stream_uncork(stream);
265
266
0
  if (offset != NULL)
267
0
    *offset = aligned_offset;
268
0
  return TRUE;
269
0
}
270
271
static bool
272
_save_block(struct sieve_binary *sbin, struct ostream *stream, unsigned int id)
273
0
{
274
0
  struct sieve_binary_block_header block_header;
275
0
  struct sieve_binary_block *block;
276
0
  const void *data;
277
0
  size_t size;
278
279
0
  block = sieve_binary_block_get(sbin, id);
280
0
  if (block == NULL)
281
0
    return FALSE;
282
283
0
  data = buffer_get_data(block->data, &size);
284
285
0
  block_header.id = id;
286
0
  block_header.size = size;
287
288
0
  if (!_save_aligned(sbin, stream, &block_header, sizeof(block_header),
289
0
         &block->offset))
290
0
    return FALSE;
291
292
0
  return _save_aligned(sbin, stream, data, size, NULL);
293
0
}
294
295
static bool
296
_save_block_index_record(struct sieve_binary *sbin, struct ostream *stream,
297
       unsigned int id)
298
0
{
299
0
  struct sieve_binary_block *block;
300
0
  struct sieve_binary_block_index header;
301
302
0
  block = sieve_binary_block_get(sbin, id);
303
0
  if (block == NULL)
304
0
    return FALSE;
305
306
0
  header.id = id;
307
0
  header.size = buffer_get_used_size(block->data);
308
0
  header.ext_id = block->ext_index;
309
0
  header.offset = block->offset;
310
311
0
  if (!_save_full(sbin, stream, &header, sizeof(header))) {
312
0
    e_error(sbin->event, "save: "
313
0
      "failed to save block index header %d", id);
314
0
    return FALSE;
315
0
  }
316
317
0
  return TRUE;
318
0
}
319
320
static bool
321
sieve_binary_save_to_stream(struct sieve_binary *sbin, struct ostream *stream)
322
0
{
323
0
  struct sieve_binary_header *header = &sbin->header;
324
0
  struct sieve_binary_block *ext_block;
325
0
  unsigned int ext_count, blk_count, i;
326
0
  uoff_t block_index;
327
328
0
  blk_count = sieve_binary_block_count(sbin);
329
330
  /* Create header */
331
332
0
  header->magic = SIEVE_BINARY_MAGIC;
333
0
  header->version_major = SIEVE_BINARY_VERSION_MAJOR;
334
0
  header->version_minor = SIEVE_BINARY_VERSION_MINOR;
335
0
  header->blocks = blk_count;
336
0
  header->hdr_size = sizeof(*header);
337
338
0
  header->flags = 0;
339
0
  sieve_binary_file_zero_header_rusage(sbin);
340
341
0
  if (!_save_aligned(sbin, stream, header, sizeof(*header), NULL)) {
342
0
    e_error(sbin->event, "save: failed to save header");
343
0
    return FALSE;
344
0
  }
345
346
  /* Skip block index for now */
347
348
0
  if (!_save_skip_aligned(
349
0
    sbin, stream,
350
0
    (sizeof(struct sieve_binary_block_index) * blk_count),
351
0
    &block_index))
352
0
    return FALSE;
353
354
  /* Create block containing all used extensions */
355
356
0
  ext_block = sieve_binary_block_get(sbin, SBIN_SYSBLOCK_EXTENSIONS);
357
0
  i_assert(ext_block != NULL);
358
0
  sieve_binary_block_clear(ext_block);
359
360
0
  ext_count = array_count(&sbin->linked_extensions);
361
0
  sieve_binary_emit_unsigned(ext_block, ext_count);
362
363
0
  for (i = 0; i < ext_count; i++) {
364
0
    struct sieve_binary_extension_reg *const *ext =
365
0
      array_idx(&sbin->linked_extensions, i);
366
367
0
    sieve_binary_emit_cstring(
368
0
      ext_block, sieve_extension_name((*ext)->extension));
369
0
    sieve_binary_emit_unsigned(
370
0
      ext_block, sieve_extension_version((*ext)->extension));
371
0
    sieve_binary_emit_unsigned(ext_block, (*ext)->block_id);
372
0
  }
373
374
  /* Save all blocks into the binary */
375
376
0
  for (i = 0; i < blk_count; i++) {
377
0
    if (!_save_block(sbin, stream, i))
378
0
      return FALSE;
379
0
  }
380
381
  /* Create the block index */
382
0
  o_stream_seek(stream, block_index);
383
0
  for (i = 0; i < blk_count; i++) {
384
0
    if (!_save_block_index_record(sbin, stream, i))
385
0
      return FALSE;
386
0
  }
387
388
0
  if (o_stream_finish(stream) <= 0) {
389
0
    e_error(sbin->event, "save: "
390
0
      "failed to finish output stream: %s",
391
0
      o_stream_get_error(stream));
392
0
    return FALSE;
393
0
  }
394
0
  return TRUE;
395
0
}
396
397
static int
398
sieve_binary_do_save(struct sieve_binary *sbin, const char *path, bool update,
399
         mode_t save_mode, enum sieve_error *error_code_r)
400
0
{
401
0
  int result, fd;
402
0
  string_t *temp_path;
403
0
  struct ostream *stream;
404
0
  struct sieve_binary_extension_reg *const *regs;
405
0
  unsigned int ext_count, i;
406
407
0
  sieve_error_args_init(&error_code_r, NULL);
408
409
  /* Check whether saving is necessary */
410
0
  if (!update && sbin->path != NULL && strcmp(sbin->path, path) == 0) {
411
0
    e_debug(sbin->event, "save: "
412
0
      "not saving binary, because it is already stored");
413
0
    return 0;
414
0
  }
415
416
  /* Open it as temp file first, as not to overwrite an existing just yet */
417
0
  temp_path = t_str_new(256);
418
0
  str_append(temp_path, path);
419
0
  str_append_c(temp_path, '.');
420
0
  fd = safe_mkstemp_hostpid(temp_path, save_mode, (uid_t)-1, (gid_t)-1);
421
0
  if (fd < 0) {
422
0
    if (errno == EACCES) {
423
0
      e_error(sbin->event, "save: "
424
0
        "failed to create temporary file: %s",
425
0
        eacces_error_get_creating("open",
426
0
                str_c(temp_path)));
427
0
      *error_code_r = SIEVE_ERROR_NO_PERMISSION;
428
0
    } else {
429
0
      e_error(sbin->event, "save: "
430
0
        "failed to create temporary file: "
431
0
        "open(%s) failed: %m", str_c(temp_path));
432
0
      *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
433
0
    }
434
0
    return -1;
435
0
  }
436
437
  /* Signal all extensions that we're about to save the binary */
438
0
  regs = array_get(&sbin->extensions, &ext_count);
439
0
  for (i = 0; i < ext_count; i++) {
440
0
    const struct sieve_binary_extension *binext = regs[i]->binext;
441
442
0
    if (binext != NULL && binext->binary_pre_save != NULL &&
443
0
        !binext->binary_pre_save(regs[i]->extension, sbin,
444
0
               regs[i]->context, error_code_r)) {
445
0
      i_assert(*error_code_r != SIEVE_ERROR_NONE);
446
0
      return -1;
447
0
    }
448
0
  }
449
450
  /* Save binary */
451
0
  result = 1;
452
0
  stream = o_stream_create_fd(fd, 0);
453
0
  if (!sieve_binary_save_to_stream(sbin, stream)) {
454
0
    result = -1;
455
0
    *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
456
0
    o_stream_ignore_last_errors(stream);
457
0
  }
458
0
  o_stream_destroy(&stream);
459
460
  /* Close saved binary */
461
0
  if (close(fd) < 0) {
462
0
    e_error(sbin->event, "save: "
463
0
      "failed to close temporary file: "
464
0
      "close(fd=%s) failed: %m", str_c(temp_path));
465
0
  }
466
467
  /* Replace any original binary atomically */
468
0
  if (result > 0 && (rename(str_c(temp_path), path) < 0)) {
469
0
    if (errno == EACCES) {
470
0
      e_error(sbin->event, "save: "
471
0
        "failed to save binary: %s",
472
0
        eacces_error_get_creating("rename", path));
473
0
      *error_code_r = SIEVE_ERROR_NO_PERMISSION;
474
0
    } else {
475
0
      e_error(sbin->event, "save: "
476
0
        "failed to save binary: "
477
0
        "rename(%s, %s) failed: %m",
478
0
        str_c(temp_path), path);
479
0
      *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
480
0
    }
481
0
    result = -1;
482
0
  }
483
484
0
  if (result < 0) {
485
    /* Get rid of temp output (if any) */
486
0
    if (unlink(str_c(temp_path)) < 0 && errno != ENOENT) {
487
0
      e_error(sbin->event, "save: "
488
0
        "failed to clean up after error: "
489
0
        "unlink(%s) failed: %m", str_c(temp_path));
490
0
    }
491
0
  } else {
492
0
    if (sbin->path == NULL)
493
0
      sbin->path = p_strdup(sbin->pool, path);
494
495
    /* Signal all extensions that we successfully saved the binary.
496
     */
497
0
    regs = array_get(&sbin->extensions, &ext_count);
498
0
    for (i = 0; i < ext_count; i++) {
499
0
      const struct sieve_binary_extension *binext =
500
0
        regs[i]->binext;
501
502
0
      if (binext != NULL &&
503
0
          binext->binary_post_save != NULL &&
504
0
          !binext->binary_post_save(regs[i]->extension, sbin,
505
0
                  regs[i]->context,
506
0
                  error_code_r)) {
507
0
        i_assert(*error_code_r != SIEVE_ERROR_NONE);
508
0
        result = -1;
509
0
        break;
510
0
      }
511
0
    }
512
513
0
    if (result < 0 && unlink(path) < 0 && errno != ENOENT) {
514
0
      e_error(sbin->event, "failed to clean up after error: "
515
0
        "unlink(%s) failed: %m", path);
516
0
    }
517
0
  }
518
519
0
  return result;
520
0
}
521
522
int sieve_binary_save(struct sieve_binary *sbin, const char *path, bool update,
523
          mode_t save_mode, enum sieve_error *error_code_r)
524
0
{
525
0
  int ret;
526
527
0
  sieve_binary_update_event(sbin, path);
528
0
  ret = sieve_binary_do_save(sbin, path, update, save_mode, error_code_r);
529
0
  sieve_binary_update_event(sbin, NULL);
530
531
0
  return ret;
532
0
}
533
534
535
/*
536
 * Binary file management
537
 */
538
539
static int
540
sieve_binary_fd_open(struct sieve_binary *sbin, const char *path,
541
         int open_flags, enum sieve_error *error_code_r)
542
0
{
543
0
  int fd;
544
545
0
  fd = open(path, open_flags);
546
0
  if (fd < 0) {
547
0
    switch (errno) {
548
0
    case ENOENT:
549
0
      *error_code_r = SIEVE_ERROR_NOT_FOUND;
550
0
      break;
551
0
    case EACCES:
552
0
      e_error(sbin->event, "open: "
553
0
        "failed to open: %s",
554
0
        eacces_error_get("open", path));
555
0
      *error_code_r = SIEVE_ERROR_NO_PERMISSION;
556
0
      break;
557
0
    default:
558
0
      e_error(sbin->event, "open: "
559
0
        "failed to open: open(%s) failed: %m", path);
560
0
      *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
561
0
      break;
562
0
    }
563
0
    return -1;
564
0
  }
565
0
  return fd;
566
0
}
567
568
static int
569
sieve_binary_file_open(struct sieve_binary *sbin, const char *path,
570
           struct sieve_binary_file **file_r,
571
           enum sieve_error *error_code_r)
572
0
{
573
0
  int fd, ret = 0;
574
0
  struct stat st;
575
576
0
  sieve_error_args_init(&error_code_r, NULL);
577
578
0
  fd = sieve_binary_fd_open(sbin, path, O_RDONLY, error_code_r);
579
0
  if (fd < 0)
580
0
    return -1;
581
582
0
  if (fstat(fd, &st) < 0) {
583
0
    if (errno == ENOENT)
584
0
      *error_code_r = SIEVE_ERROR_NOT_FOUND;
585
0
    else {
586
0
      e_error(sbin->event, "open: fstat(%s) failed: %m",
587
0
        path);
588
0
      *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
589
0
    }
590
0
    ret = -1;
591
0
  }
592
593
0
  if (ret == 0 && !S_ISREG(st.st_mode)) {
594
0
    e_error(sbin->event, "open: "
595
0
      "binary is not a regular file");
596
0
    *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
597
0
    ret = -1;
598
0
  }
599
600
0
  if (ret < 0) {
601
0
    if (close(fd) < 0) {
602
0
      e_error(sbin->event, "open: "
603
0
        "close() failed after error: %m");
604
0
    }
605
0
    return -1;
606
0
  }
607
608
0
  pool_t pool;
609
0
  struct sieve_binary_file *file;
610
611
0
  pool = pool_alloconly_create("sieve_binary_file", 4096);
612
0
  file = p_new(pool, struct sieve_binary_file, 1);
613
0
  file->pool = pool;
614
0
  file->path = p_strdup(pool, path);
615
0
  file->fd = fd;
616
0
  file->st = st;
617
0
  file->sbin = sbin;
618
619
0
  *file_r = file;
620
0
  return 0;
621
0
}
622
623
void sieve_binary_file_close(struct sieve_binary_file **_file)
624
0
{
625
0
  struct sieve_binary_file *file = *_file;
626
627
0
  *_file = NULL;
628
0
  if (file == NULL)
629
0
    return;
630
631
0
  if (file->fd != -1) {
632
0
    if (close(file->fd) < 0) {
633
0
      e_error(file->sbin->event, "close: "
634
0
        "failed to close: close() failed: %m");
635
0
    }
636
0
  }
637
638
0
  pool_unref(&file->pool);
639
0
}
640
641
static int
642
sieve_binary_file_read(struct sieve_binary_file *file, off_t *offset,
643
           void *buffer, size_t size)
644
0
{
645
0
  struct sieve_binary *sbin = file->sbin;
646
0
  int ret;
647
0
  void *indata = buffer;
648
0
  size_t insize = size;
649
650
0
  *offset = SIEVE_BINARY_ALIGN(*offset);
651
652
  /* Seek to the correct position */
653
0
  if (*offset != file->offset &&
654
0
      lseek(file->fd, *offset, SEEK_SET) == (off_t)-1) {
655
0
    e_error(sbin->event, "read: "
656
0
      "failed to seek(fd, %lld, SEEK_SET): %m",
657
0
      (long long) *offset);
658
0
    return -1;
659
0
  }
660
661
  /* Read record into memory */
662
0
  while (insize > 0) {
663
0
    ret = read(file->fd, indata, insize);
664
0
    if (ret <= 0) {
665
0
      if (ret == 0) {
666
0
        e_error(sbin->event, "read: "
667
0
          "binary is truncated "
668
0
          "(more data expected)");
669
0
      } else {
670
0
        e_error(sbin->event, "read: "
671
0
          "failed to read from binary: %m");
672
0
      }
673
0
      break;
674
0
    }
675
676
0
    indata = PTR_OFFSET(indata, ret);
677
0
    insize -= ret;
678
0
  }
679
680
0
  if (insize != 0) {
681
    /* Failed to read the whole requested record */
682
0
    return 0;
683
0
  }
684
685
0
  *offset += size;
686
0
  file->offset = *offset;
687
0
  return 1;
688
0
}
689
690
static const void *
691
sieve_binary_file_load_data(struct sieve_binary_file *file,
692
          off_t *offset, size_t size)
693
0
{
694
0
  void *data = t_malloc_no0(size);
695
696
0
  if (sieve_binary_file_read(file, offset, data, size) > 0)
697
0
    return data;
698
699
0
  return NULL;
700
0
}
701
702
static buffer_t *
703
sieve_binary_file_load_buffer(struct sieve_binary_file *file,
704
            off_t *offset, size_t size)
705
0
{
706
0
  buffer_t *buffer = buffer_create_dynamic(file->pool, size);
707
708
0
  if (sieve_binary_file_read(file, offset,
709
0
           buffer_get_space_unsafe(buffer, 0, size),
710
0
           size) > 0)
711
0
    return buffer;
712
713
0
  return NULL;
714
0
}
715
716
/*
717
 * Load binary from a file
718
 */
719
720
#define LOAD_HEADER(sbin, offset, header) \
721
0
  (header *)sieve_binary_file_load_data(sbin->file, offset, \
722
0
                sizeof(header))
723
724
bool sieve_binary_load_block(struct sieve_binary_block *sblock)
725
0
{
726
0
  struct sieve_binary *sbin = sblock->sbin;
727
0
  unsigned int id = sblock->id;
728
0
  off_t offset = sblock->offset;
729
0
  const struct sieve_binary_block_header *header =
730
0
    LOAD_HEADER(sbin, &offset,
731
0
          const struct sieve_binary_block_header);
732
733
0
  if (header == NULL) {
734
0
    e_error(sbin->event, "load: binary is corrupt: "
735
0
      "failed to read header of block %d", id);
736
0
    return FALSE;
737
0
  }
738
739
0
  if (header->id != id) {
740
0
    e_error(sbin->event, "load: binary is corrupt: "
741
0
      "header of block %d has non-matching id %d",
742
0
      id, header->id);
743
0
    return FALSE;
744
0
  }
745
746
0
  sblock->data = sieve_binary_file_load_buffer(sbin->file, &offset,
747
0
                 header->size);
748
0
  if (sblock->data == NULL) {
749
0
    e_error(sbin->event, "load: "
750
0
      "failed to read block %d of binary (size=%d)",
751
0
      id, header->size);
752
0
    return FALSE;
753
0
  }
754
755
0
  return TRUE;
756
0
}
757
758
static bool
759
_read_block_index_record(struct sieve_binary *sbin, off_t *offset,
760
       unsigned int id)
761
0
{
762
0
  const struct sieve_binary_block_index *record =
763
0
    LOAD_HEADER(sbin, offset,
764
0
          const struct sieve_binary_block_index);
765
0
  struct sieve_binary_block *block;
766
767
0
  if (record == NULL) {
768
0
    e_error(sbin->event, "open: binary is corrupt: "
769
0
      "failed to load block index record %d", id);
770
0
    return FALSE;
771
0
  }
772
773
0
  if (record->id != id) {
774
0
    e_error(sbin->event, "open: binary is corrupt: "
775
0
      "block index record %d has unexpected id %d",
776
0
      id, record->id);
777
0
    return FALSE;
778
0
  }
779
780
0
  block = sieve_binary_block_create_id(sbin, id);
781
0
  block->ext_index = record->ext_id;
782
0
  block->offset = record->offset;
783
784
0
  return TRUE;
785
0
}
786
787
static int _read_extensions(struct sieve_binary_block *sblock)
788
0
{
789
0
  struct sieve_binary *sbin = sblock->sbin;
790
0
  sieve_size_t offset = 0;
791
0
  unsigned int i, count;
792
0
  int result = 1;
793
794
0
  if (!sieve_binary_read_unsigned(sblock, &offset, &count))
795
0
    return -1;
796
797
0
  for (i = 0; result > 0 && i < count; i++) {
798
0
    T_BEGIN {
799
0
      string_t *extension;
800
0
      const struct sieve_extension *ext;
801
0
      unsigned int version;
802
803
0
      if (sieve_binary_read_string(sblock, &offset,
804
0
                 &extension)) {
805
0
        ext = sieve_extension_get_by_name(
806
0
          sbin->svinst, str_c(extension));
807
808
0
        if (ext == NULL) {
809
0
          e_error(sbin->event, "open: "
810
0
            "binary requires unknown extension '%s'",
811
0
            str_sanitize(str_c(extension), 128));
812
0
          result = 0;
813
0
        } else {
814
0
          struct sieve_binary_extension_reg *ereg = NULL;
815
816
0
          (void)sieve_binary_extension_register(sbin, ext, &ereg);
817
0
          if (!sieve_binary_read_unsigned(sblock, &offset, &version) ||
818
0
              !sieve_binary_read_unsigned(sblock, &offset, &ereg->block_id)) {
819
0
            result = -1;
820
0
          } else if (!sieve_extension_version_is(ext, version)) {
821
0
            e_debug(sbin->event, "open: "
822
0
              "binary was compiled with different version "
823
0
              "of the '%s' extension (compiled v%d, expected v%d;"
824
0
              "automatically fixed when re-compiled)",
825
0
              sieve_extension_name(ext), version,
826
0
              sieve_extension_version(ext));
827
0
            result = 0;
828
0
          }
829
0
        }
830
0
      } else {
831
0
        result = -1;
832
0
      }
833
0
    } T_END;
834
0
  }
835
836
0
  return result;
837
0
}
838
839
static bool
840
_sieve_binary_open(struct sieve_binary *sbin, enum sieve_error *error_code_r)
841
0
{
842
0
  bool result = TRUE;
843
0
  off_t offset = 0;
844
0
  struct sieve_binary_block *ext_block;
845
0
  unsigned int i;
846
0
  int ret;
847
848
  /* Read header */
849
850
0
  ret = sieve_binary_file_read_header(sbin, sbin->file->fd,
851
0
              &sbin->header, error_code_r);
852
0
  if (ret < 0)
853
0
    return FALSE;
854
0
  offset = sbin->header.hdr_size;
855
856
  /* Resource usage tracking is no longer kept in the binary file;
857
     discard any data from older versions. */
858
0
  sbin->header.unused_update_time = 0;
859
0
  sbin->header.unused_cpu_time_msecs = 0;
860
0
  sbin->header.flags = 0;
861
862
  /* Load block index */
863
864
0
  for (i = 0; i < sbin->header.blocks && result; i++) {
865
0
    T_BEGIN {
866
0
      if (!_read_block_index_record(sbin, &offset, i))
867
0
        result = FALSE;
868
0
    } T_END;
869
0
  }
870
871
0
  if (!result) {
872
0
    *error_code_r = SIEVE_ERROR_NOT_VALID;
873
0
    return FALSE;
874
0
  }
875
876
  /* Load extensions used by this binary */
877
878
0
  T_BEGIN {
879
0
    ext_block = sieve_binary_block_get(
880
0
      sbin, SBIN_SYSBLOCK_EXTENSIONS);
881
0
    if (ext_block == NULL) {
882
0
      result = FALSE;
883
0
    } else if ((ret = _read_extensions(ext_block)) <= 0) {
884
0
      if (ret < 0) {
885
0
        e_error(sbin->event, "open: binary is corrupt: "
886
0
          "failed to load extension block");
887
0
      }
888
0
      result = FALSE;
889
0
    }
890
0
  } T_END;
891
892
0
  if (!result) {
893
0
    *error_code_r = SIEVE_ERROR_NOT_VALID;
894
0
    return FALSE;
895
0
  }
896
0
  return TRUE;
897
0
}
898
899
int sieve_binary_open(struct sieve_instance *svinst, const char *path,
900
          struct sieve_script *script, struct sieve_binary **sbin_r,
901
          enum sieve_error *error_code_r)
902
0
{
903
0
  struct sieve_binary_extension_reg *const *regs;
904
0
  unsigned int ext_count, i;
905
0
  struct sieve_binary *sbin;
906
0
  struct sieve_binary_file *file;
907
908
0
  i_assert(script == NULL || sieve_script_svinst(script) == svinst);
909
0
  *sbin_r = NULL;
910
0
  sieve_error_args_init(&error_code_r, NULL);
911
912
  /* Create binary object */
913
0
  sbin = sieve_binary_create(svinst, script);
914
0
  sbin->path = p_strdup(sbin->pool, path);
915
916
0
  if (sieve_binary_file_open(sbin, path, &file, error_code_r) < 0) {
917
0
    sieve_binary_unref(&sbin);
918
0
    return -1;
919
0
  }
920
921
0
  sbin->file = file;
922
923
0
  event_set_append_log_prefix(
924
0
    sbin->event,
925
0
    t_strdup_printf("binary %s: ", path));
926
927
0
  if (!_sieve_binary_open(sbin, error_code_r)) {
928
0
    sieve_binary_unref(&sbin);
929
0
    return -1;
930
0
  }
931
932
0
  sieve_binary_activate(sbin);
933
934
  /* Signal open event to extensions */
935
0
  regs = array_get(&sbin->extensions, &ext_count);
936
0
  for (i = 0; i < ext_count; i++) {
937
0
    const struct sieve_binary_extension *binext = regs[i]->binext;
938
939
0
    if (binext != NULL && binext->binary_open != NULL &&
940
0
        !binext->binary_open(regs[i]->extension, sbin,
941
0
           regs[i]->context)) {
942
      /* Extension thinks its corrupt */
943
0
      *error_code_r = SIEVE_ERROR_NOT_VALID;
944
0
      sieve_binary_unref(&sbin);
945
0
      return -1;
946
0
    }
947
0
  }
948
949
0
  *sbin_r = sbin;
950
0
  return 0;
951
0
}
952
953
int sieve_binary_check_executable(struct sieve_binary *sbin,
954
          enum sieve_error *error_code_r,
955
          const char **client_error_r)
956
0
{
957
0
  struct sieve_resource_usage rusage;
958
0
  struct sieve_script *script = sbin->script;
959
960
0
  *client_error_r = NULL;
961
0
  sieve_error_args_init(&error_code_r, NULL);
962
963
0
  sieve_binary_get_resource_usage(sbin, &rusage);
964
0
  if (sieve_resource_usage_is_excessive(sbin->svinst, &rusage)) {
965
    /* Cumulative resource usage is only tracked for personal
966
       scripts. */
967
0
    i_assert(script != NULL);
968
0
    i_assert(sieve_storage_is_personal(script->storage));
969
970
0
    e_info(sbin->event,
971
0
           "Personal sieve processing disabled for script '%s': "
972
0
           "cumulative resource usage limit exceeded (%s)",
973
0
           sieve_script_label(script),
974
0
           sieve_resource_usage_get_summary(&rusage));
975
0
    *error_code_r = SIEVE_ERROR_RESOURCE_LIMIT;
976
0
    *client_error_r = "cumulative resource usage limit exceeded";
977
0
    return 0;
978
0
  }
979
0
  return 1;
980
0
}
981
982
/*
983
 * Resource usage
984
 */
985
986
int sieve_binary_file_update_resource_usage(struct sieve_binary *sbin,
987
              enum sieve_error *error_code_r)
988
0
{
989
0
  struct sieve_storage *storage;
990
0
  struct sieve_resource_usage delta;
991
992
0
  sieve_error_args_init(&error_code_r, NULL);
993
994
0
  sieve_binary_file_close(&sbin->file);
995
996
0
  if (sbin->script == NULL || sbin->script->storage == NULL ||
997
0
      sbin->script->storage->rusage_path == NULL) {
998
    /* No per-user file: tracking discarded. */
999
0
    sieve_resource_usage_init(&sbin->rusage);
1000
0
    sbin->rusage_updated = FALSE;
1001
0
    return 0;
1002
0
  }
1003
0
  storage = sbin->script->storage;
1004
1005
0
  delta = sbin->rusage;
1006
1007
  /* Persist only when this run consumed a meaningful amount of CPU.
1008
     Critically, refused-without-running attempts (delta == 0) must not
1009
     touch the file - otherwise the file's update_time would be refreshed
1010
     on every blocked attempt, preventing the resource_usage_timeout from
1011
     ever decaying the persisted CPU time and re-enabling the user. */
1012
0
  if (!sieve_resource_usage_is_high(sbin->svinst, &delta)) {
1013
0
    sieve_resource_usage_init(&sbin->rusage);
1014
0
    sbin->rusage_updated = FALSE;
1015
0
    return 0;
1016
0
  }
1017
1018
0
  if (sieve_rusage_storage_add(storage, &delta) < 0) {
1019
0
    *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
1020
0
    return -1;
1021
0
  }
1022
1023
0
  sieve_resource_usage_init(&sbin->rusage);
1024
0
  sbin->rusage_updated = FALSE;
1025
0
  return 0;
1026
0
}