Debian Codegraph @

cassandane/Cassandane/Cyrus/TestCase.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2017 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Cyrus::TestCase;
41 use strict;
42 use warnings;
43 use attributes;
44 use version 0.77;
45 use Cwd qw(abs_path);
46 use Data::Dumper;
47 use Digest::file qw(digest_file_hex);
48 use File::Path qw(rmtree);
49 use File::Temp qw(tempfile);
50 use List::Util qw(uniq);
51 use Scalar::Util qw(refaddr);
52
53 use lib '.';
54 use base qw(Cassandane::Unit::TestCase);
55 use Cassandane::Util::Log;
56 use Cassandane::Util::Slurp;
57 use Cassandane::Util::Words;
58 use Cassandane::Generator;
59 use Cassandane::GenericListener;
60 use Cassandane::MessageStoreFactory;
61 use Cassandane::Instance;
62 use Cassandane::PortManager;
63 use Cyrus::CheckReplication;
64
65 my @stores = qw(store adminstore
66 replica_store replica_adminstore
67 frontend_store frontend_adminstore
68 backend2_store backend2_adminstore);
69 my %magic_handlers;
70
71 # This code for storing function attributes is from
72 # http://stackoverflow.com/questions/987059/how-do-perl-method-attributes-work
73
74 my %attrs; # package variable to store attribute lists by coderef address
75
76 sub MODIFY_CODE_ATTRIBUTES
77 {
78 my ($package, $subref, @attrs) = @_;
79 $attrs{refaddr $subref} = \@attrs;
80 return;
81 }
82
83 sub FETCH_CODE_ATTRIBUTES
84 {
85 my ($package, $subref) = @_;
86 my $attrs = $attrs{refaddr $subref} || [];
87 return @$attrs;
88 }
89
90 sub new
91 {
92 my ($class, $params, @args) = @_;
93
94 my $want = {
95 instance => 1,
96 replica => 0,
97 imapmurder => 0,
98 httpmurder => 0,
99 start_instances => 1,
100 services => [ 'imap' ],
101 store => 1,
102 adminstore => 0,
103 gen => 1,
104 deliver => 0,
105 jmap => 0,
106 install_certificates => 0,
107 squatter => 0,
108 smtpdaemon => 0,
109 };
110 map {
111 $want->{$_} = delete $params->{$_}
112 if defined $params->{$_};
113
114 } keys %$want;
115 $want->{folder} = delete $params->{folder}
116 if defined $params->{folder};
117
118 my $instance_params = {};
119 foreach my $p (qw(config))
120 {
121 $instance_params->{$p} = delete $params->{$p}
122 if defined $params->{$p};
123 }
124
125 # should have consumed all of the $params hash; if
126 # not something is awry.
127 my $leftovers = join(' ', keys %$params);
128 die "Unexpected configuration parameters: $leftovers"
129 if length($leftovers);
130
131 my $self = $class->SUPER::new(@args);
132 $self->{_name} = $args[0] || 'unknown';
133 $self->{_want} = $want;
134 $self->{_instance_params} = $instance_params;
135
136 return $self;
137 }
138
139 # return an id for use by xlog
140 sub id
141 {
142 my ($self) = @_;
143 return $self->{_name}; # XXX something cleverer?
144 }
145
146 sub filter
147 {
148 my ($self) = @_;
149
150 my $filter = $self->SUPER::filter(@_);
151
152 $filter->{enable_wanted_properties} = sub {
153 return if not exists $self->{_name};
154 my $sub = $self->can($self->{_name});
155 return if not defined $sub;
156
157 # n.b. cannot be used to unwant, sorry
158 foreach my $attr (attributes::get($sub)) {
159 next if $attr !~ m/^want(_service)?_(\w+)$/;
160
161 # XXX Since this is a 'filter', it could also check
162 # XXX whether the required components are configured
163 # XXX ala :needs_foo, and skip the test if they're
164 # XXX missing, rather than failing to start them.
165 # XXX That is, :want_service_http could be taken to
166 # XXX imply :needs_component_httpd, and the test
167 # XXX skipped if it's unavailable. But note that
168 # XXX there isn't a clean mapping between the names!
169 # XXX For now, tests will need to be annotated with
170 # XXX both attributes in these cases.
171
172 $self->{_current_magic} = "Test function attribute ':$attr'";
173 if (defined $1 && $1 eq '_service') {
174 $self->want_services($2);
175 }
176 else {
177 $self->want($2);
178 }
179 $self->{_current_magic} = undef;
180 }
181 return;
182 };
183
184 return $filter;
185 }
186
187 # will magically cause some special actions to be taken during test
188 # setup. This used to be a horrible hack to enable a replica instance
189 # if the test name contained the word "replication", but now it's more
190 # general. The handler function is called near the start of set_up(),
191 # before Cyrus instances are created, and can call want() to add to the
192 # set of features wanted by this test, or config_set() to set additional
193 # imapd.conf variables for all instances.
194 sub magic
195 {
196 my ($name, $handler) = @_;
197 $name = lc($name);
198 die "Magic \"$name\" registered twice"
199 if defined $magic_handlers{$name};
200 $magic_handlers{$name} = $handler;
201 }
202
203 sub _who_wants_it
204 {
205 my ($self) = @_;
206 return $self->{_current_magic}
207 if defined $self->{_current_magic} ;
208 return "Test " . $self->{_name};
209 }
210
211 sub want
212 {
213 my ($self, $name, $value) = @_;
214 $value = 1 if !defined $value;
215 $self->{_want}->{$name} = $value;
216 xlog $self->_who_wants_it() . " wants $name = $value";
217 }
218
219 sub want_services
220 {
221 my ($self, @services) = @_;
222
223 @{$self->{_want}->{services}} = uniq(@{$self->{_want}->{services}},
224 @services);
225 xlog $self->_who_wants_it() . " wants services " . join(', ', @services);
226
227 }
228
229 sub needs
230 {
231 my ($self, $category, $key, $want_value) = @_;
232
233 # $category and $key are as per cyr_buildinfo output. $want_value is
234 # optional and defaults to '1', but can be a particular value for
235 # category=>key pairs that aren't boolean.
236 # See Cassandane::Unit:TestCase::is_feature_missing to see how
237 # needs are used.
238 $self->{needs}->{$category}->{$key} = $want_value // 1;
239 }
240
241 sub config_set
242 {
243 my ($self, %pairs) = @_;
244 $self->{_config}->set(%pairs);
245 while (my ($n, $v) = each %pairs)
246 {
247 xlog $self->_who_wants_it() . " sets config $n = $v";
248 }
249 }
250
251 # XXX put these in alphabetical order someday
252 magic(ReverseACLs => sub {
253 shift->config_set(reverseacls => 1);
254 });
255 magic(RightNow => sub {
256 shift->config_set(sync_rightnow_channel => '""');
257 });
258 magic(SyncLog => sub {
259 shift->config_set(sync_log => 1);
260 });
261 magic(Replication => sub { shift->want('replica'); });
262 magic(CSyncReplication => sub {
263 my ($self) = @_;
264 $self->want('csyncreplica');
265 $self->config_set('sync_try_imap' => 0);
266 });
267 magic(IMAPMurder => sub { shift->want('imapmurder'); });
268 magic(HTTPMurder => sub { shift->want('httpmurder'); });
269 magic(AnnotationAllowUndefined => sub {
270 shift->config_set(annotation_allow_undefined => 1);
271 });
272 magic(AllowDeleted => sub {
273 shift->config_set(allowdeleted => 1);
274 });
275 magic(ImmediateDelete => sub {
276 shift->config_set(delete_mode => 'immediate');
277 });
278 magic(DelayedDelete => sub {
279 shift->config_set(delete_mode => 'delayed');
280 });
281 magic(UnixHierarchySep => sub {
282 shift->config_set(unixhierarchysep => 'yes');
283 });
284 magic(ImmediateExpunge => sub {
285 shift->config_set(expunge_mode => 'immediate');
286 });
287 magic(SemidelayedExpunge => sub {
288 my $semidelayed = 'semidelayed';
289 my ($maj, $min) = Cassandane::Instance->get_version();
290 if ($maj < 3 || ($maj == 3 && $min < 1)) {
291 # this value used to be called 'default' in 3.0 and earlier
292 $semidelayed = 'default';
293 }
294 shift->config_set(expunge_mode => $semidelayed);
295 });
296 magic(DelayedExpunge => sub {
297 shift->config_set(expunge_mode => 'delayed');
298 });
299 magic(VirtDomains => sub {
300 shift->config_set(virtdomains => 'userid');
301 });
302 magic(NoVirtDomains => sub {
303 shift->config_set(virtdomains => 'off');
304 });
305 magic(AltNamespace => sub {
306 shift->config_set(altnamespace => 'yes');
307 });
308 magic(NoAltNamespace => sub {
309 shift->config_set(altnamespace => 'no');
310 });
311 magic(NoMailboxLegacyDirs => sub {
312 shift->config_set(mailbox_legacy_dirs => 'no');
313 });
314 magic(MailboxLegacyDirs => sub {
315 shift->config_set(mailbox_legacy_dirs => 'yes');
316 });
317 magic(CrossDomains => sub {
318 shift->config_set(crossdomains => 'yes');
319 });
320 magic(Conversations => sub {
321 shift->config_set(conversations => 'yes');
322 });
323 magic(ConversationsQuota => sub {
324 # this setting is new in 3.3.0 -- any test using this magic
325 # also needs :min_version_3_3
326 shift->config_set(quota_use_conversations => 'yes');
327 });
328 magic(Admin => sub {
329 shift->want('adminstore');
330 });
331 magic(AllowMoves => sub {
332 shift->config_set('allowusermoves' => 'yes');
333 });
334 magic(DisconnectOnVanished => sub {
335 shift->config_set('disconnect_on_vanished_mailbox' => 'yes');
336 });
337 magic(NoStartInstances => sub {
338 # If you use this magic, you must call $self->_start_instances()
339 # and optionally $self->_setup_http_service_objects()
340 # yourself from your test function once you're ready for Cyrus
341 # to be started!
342 # If any test function in your suite uses this magic, then
343 # your suite's set_up function cannot assume Cyrus is running!
344 shift->want('start_instances' => 0);
345 });
346 magic(MagicPlus => sub {
347 shift->config_set('imapmagicplus' => 'yes');
348 });
349 magic(FastMailSharing => sub {
350 shift->config_set('fastmailsharing' => 'true');
351 });
352 magic(Partition2 => sub {
353 shift->config_set('partition-p2' => '@basedir@/data-p2');
354 });
355 magic(FastMailEvent => sub {
356 shift->config_set(
357 event_content_inclusion_mode => 'standard',
358 event_content_size => 1, # just the first byte
359 event_exclude_specialuse => '\\Junk',
360 event_extra_params => 'modseq vnd.fastmail.clientId service uidnext vnd.fastmail.sessionId vnd.cmu.envelope vnd.fastmail.convUnseen vnd.fastmail.convExists vnd.fastmail.cid vnd.cmu.mbtype vnd.cmu.davFilename vnd.cmu.davUid vnd.cmu.mailboxACL vnd.fastmail.counters messages vnd.cmu.unseenMessages flagNames vnd.cmu.visibleUsers',
361 event_groups => 'mailbox message flags calendar applepushservice',
362 );
363 });
364 magic(NoMunge8Bit => sub {
365 shift->config_set(munge8bit => 'no');
366 });
367 magic(RFC2047_UTF8 => sub {
368 shift->config_set(rfc2047_utf8 => 'yes');
369 });
370 magic(JMAPSearchDBLegacy => sub {
371 # XXX Needed for JMAPEmail.email_query_..._legacy (3.1-3.4).
372 # XXX Don't use in newer tests, and remove this someday when 3.4 is
373 # XXX obsolete.
374 shift->config_set('jmap_emailsearch_db_path' =>
375 '@basedir@/search/jmap_emailsearch.db');
376 });
377 magic(JMAPQueryCacheMaxAge1s => sub {
378 shift->config_set('jmap_querycache_max_age' => '1s');
379 });
380 magic(JMAPNoHasAttachment => sub {
381 shift->config_set('jmap_set_has_attachment' => 'no');
382 });
383 magic(JMAPExtensions => sub {
384 shift->config_set('jmap_nonstandard_extensions' => 'yes');
385 });
386 magic(SearchAttachmentExtractor => sub {
387 my $port = Cassandane::PortManager::alloc("localhost");
388 my $self = shift;
389 $self->config_set('search_attachment_extractor_url' =>
390 "http://localhost:$port/extractor");
391 $self->config_set('search_attachment_extractor_request_timeout' => '3s');
392 $self->config_set('search_attachment_extractor_idle_timeout' => '3s');
393 });
394 magic(SearchLanguage => sub {
395 shift->config_set('search_index_language' => 'yes');
396 });
397 magic(SieveUTF8Fileinto => sub {
398 shift->config_set('sieve_utf8fileinto' => 'yes');
399 });
400 magic(SearchSetForceScanMode => sub {
401 shift->config_set(search_queryscan => '1');
402 });
403 magic(SearchFuzzyAlways => sub {
404 shift->config_set(search_fuzzy_always => '1');
405 });
406 magic(SearchEngineSquat => sub {
407 shift->config_set(search_engine => 'squat');
408 });
409 magic(SearchNormalizationMax20000 => sub {
410 shift->config_set(search_normalisation_max => 20000);
411 });
412 magic(SearchMaxtime1Sec => sub {
413 shift->config_set(search_maxtime => 1);
414 });
415 magic(SearchMaxSize4k => sub {
416 shift->config_set(search_maxsize => 4);
417 });
418 magic(TLS => sub {
419 # XXX Here be dragons. Check existing tests that use this magic
420 # XXX for some of the hoops you may still need to jump through!
421 my $self = shift;
422 $self->config_set(tls_server_cert => '@basedir@/conf/certs/cert.pem');
423 $self->config_set(tls_server_key => '@basedir@/conf/certs/key.pem');
424 $self->want('install_certificates');
425 $self->want_services('imaps');
426 });
427 magic(LowEmailLimits => sub {
428 # these settings are new in 3.3.0 -- any test using this magic
429 # also needs :min_version_3_3
430 shift->config_set(
431 conversations_max_guidrecords => 10,
432 conversations_max_guidexists => 5,
433 conversations_max_guidinfolder => 2,
434 );
435 });
436 magic(HttpJWTAuthRSA => sub {
437 my $self = shift;
438 $self->config_set(http_jwt_key_dir => '@basedir@/conf/certs/http_jwt');
439 $self->want('install_certificates');
440 });
441 magic(iCalendarMaxSize10k => sub {
442 shift->config_set(icalendar_max_size => 100000);
443 });
444 magic(CalDAVNoDefaultCalendar => sub {
445 shift->config_set(
446 caldav_create_default => 'no',
447 );
448 });
449 magic(AltPTSDBPath => sub {
450 shift->config_set(
451 'ptscache_db_path' => '@basedir@/conf/non-default-ptscache.db'
452 );
453 });
454 magic(ArchivePartition => sub {
455 my $conf = shift;
456 $conf->config_set('archivepartition-default' => '@basedir@/archive');
457 $conf->config_set('archive_enabled' => 'yes');
458 $conf->config_set('archive_after' => '7d');
459 });
460 magic(ArchiveNow => sub {
461 my $conf = shift;
462 $conf->config_set('archivepartition-default' => '@basedir@/archive');
463 $conf->config_set('archive_enabled' => 'yes');
464 $conf->config_set('archive_after' => '0d');
465 });
466 magic(AllowCalendarAdmin => sub {
467 my $conf = shift;
468 $conf->config_set('caldav_allowcalendaradmin' => 'yes');
469 });
470 magic(NoCheckSyslog => sub {
471 my $self = shift;
472 $self->{no_check_syslog} = 1;
473 });
474 magic(JmapMaxCalendarEventNotifs => sub {
475 my $conf = shift;
476 # set to some small number
477 $conf->config_set('jmap_max_calendareventnotifs' => 10);
478 });
479 magic(NoReplicaonly => sub {
480 my $self = shift;
481 $self->{no_replicaonly} = 1;
482 });
483 magic(ConversationMaxThread10 => sub {
484 my $self = shift;
485 $self->config_set('conversation_max_thread' => 10);
486 });
487 magic(SlowIO => sub {
488 my $self = shift;
489 $self->config_set('debug_slowio' => 'yes');
490 });
491 magic(Mboxgroups => sub {
492 my $self = shift;
493 $self->config_set('auth_mech' => 'mboxgroups');
494 });
495 magic(CaldavAlarmOnlyVevent => sub {
496 my $self = shift;
497 $self->config_set('caldav_alarm_support_components' => 'VEVENT');
498 });
499
500
501 # Run any magic handlers indicated by the test name or attributes
502 sub _run_magic
503 {
504 my ($self) = @_;
505
506 my %seen;
507
508 foreach my $m (split(/_/, $self->{_name}))
509 {
510 next if $seen{$m};
511 next unless defined $magic_handlers{$m};
512 $self->{_current_magic} = "Magic word $m in name";
513 $magic_handlers{$m}->($self);
514 $self->{_current_magic} = undef;
515 $seen{$m} = 1;
516 }
517
518 my $sub = $self->can($self->{_name});
519 if (defined $sub) {
520 foreach my $a (attributes::get($sub))
521 {
522 my $m = lc($a);
523 # ignore min/max version attribution here
524 next if $a =~ m/^(?:min|max)_(?:other_)?version_/;
525 # ignore feature test attribution here
526 next if $a =~ m/^needs_/;
527 # ignore want attribution here
528 next if $a =~ m/^want_/;
529 die "Unknown attribute $a"
530 unless defined $magic_handlers{$m};
531 next if $seen{$m};
532 $self->{_current_magic} = "Magic attribute $a";
533 $magic_handlers{$m}->($self);
534 $self->{_current_magic} = undef;
535 $seen{$m} = 1;
536 }
537 }
538 }
539
540 sub _create_instances
541 {
542 my ($self) = @_;
543 my $sync_port;
544 my $mupdate_port;
545 my $frontend_service_port;
546 my $backend1_service_port;
547 my $backend2_service_port;
548
549 $self->{_config} = $self->{_instance_params}->{config} || Cassandane::Config->default();
550 $self->{_config} = $self->{_config}->clone();
551
552 $self->_run_magic();
553
554 my $want = $self->{_want};
555 my %instance_params = %{$self->{_instance_params}};
556
557 my $cassini = Cassandane::Cassini->instance();
558
559 if ($want->{imapmurder} && $want->{httpmurder}) {
560 # XXX Murder is implemented assuming that everything is on standard
561 # XXX ports, but Cassandane needs to use high port numbers.
562 # XXX We fudge a workaround here by embedding the service port
563 # XXX number in the server name, which tricks Murder into using
564 # XXX that port number instead of the standard one, but that means
565 # XXX we can only have one proxied service per instance.
566 die "Cannot enable murder for both IMAP and JMAP at the same time";
567 }
568
569 if ($want->{instance})
570 {
571 my $conf = $self->{_config}->clone();
572
573 if ($want->{replica} || $want->{csyncreplica})
574 {
575 $sync_port = Cassandane::PortManager::alloc("localhost");
576 $conf->set(
577 # sync_client will find the port in the config
578 sync_host => 'localhost',
579 sync_port => $sync_port,
580 # tell sync_client how to login
581 sync_authname => 'repluser',
582 sync_password => 'replpass',
583 );
584 }
585
586 if ($want->{imapmurder} || $want->{httpmurder})
587 {
588 $mupdate_port = Cassandane::PortManager::alloc("localhost");
589 $backend1_service_port = Cassandane::PortManager::alloc("localhost");
590
591 $conf->set(
592 servername => "localhost:$backend1_service_port",
593 mupdate_server => "localhost:$mupdate_port",
594 # XXX documentation says to use mupdate_port, but
595 # XXX this doesn't work -- need to embed port number in
596 # XXX mupdate_server setting instead.
597 #mupdate_port => $mupdate_port,
598 mupdate_username => 'mupduser',
599 mupdate_authname => 'mupduser',
600 mupdate_password => 'mupdpass',
601 proxyservers => 'mailproxy',
602 lmtp_admins => 'mailproxy',
603 proxy_authname => 'mailproxy',
604 proxy_password => 'mailproxy',
605 );
606 }
607
608 my $sub = $self->{_name};
609 if ($sub =~ s/^test_/config_/ && $self->can($sub))
610 {
611 die 'Use of config_<testname> subs is not supported anymore';
612 }
613
614 $instance_params{config} = $conf;
615 $instance_params{install_certificates} = $want->{install_certificates};
616 $instance_params{smtpdaemon} = $want->{smtpdaemon};
617
618 $instance_params{description} = "main instance for test $self->{_name}";
619 $self->{instance} = Cassandane::Instance->new(%instance_params);
620 $self->{instance}->add_services(@{$want->{services}});
621 $self->{instance}->_setup_for_deliver()
622 if ($want->{deliver});
623
624 if ($want->{squatter}) {
625 $self->{instance}->add_daemon(
626 name => 'squatter',
627 argv => [
628 'squatter',
629 '-R',
630 ],
631 wait => 'y',
632 );
633 }
634
635 if ($want->{replica} || $want->{csyncreplica})
636 {
637 my %replica_params = %instance_params;
638 $replica_params{config} = $self->{_config}->clone();
639 $replica_params{config}->set(sync_rightnow_channel => undef);
640 unless ($self->{no_replicaonly}) {
641 $replica_params{config}->set(replicaonly => 'yes');
642 }
643 my $cyrus_other_prefix = $cassini->val('cyrus other', 'prefix');
644 if (defined $cyrus_other_prefix and -d $cyrus_other_prefix) {
645 xlog $self, "replica instance: using [cyrus other] configuration";
646 $replica_params{installation} = 'other';
647 }
648
649 $replica_params{description} = "replica instance for test $self->{_name}";
650 $self->{replica} = Cassandane::Instance->new(%replica_params,
651 setup_mailbox => 0);
652 my ($v) = Cassandane::Instance->get_version($replica_params{installation});
653 if ($v < 3 || $want->{csyncreplica}) {
654 $self->{replica}->add_service(name => 'sync',
655 port => $sync_port,
656 argv => ['sync_server']);
657 }
658 else {
659 $self->{replica}->add_service(name => 'sync', port => $sync_port);
660 }
661 $self->{replica}->add_services(@{$want->{services}});
662 $self->{replica}->_setup_for_deliver()
663 if ($want->{deliver});
664 }
665
666 if ($want->{imapmurder} || $want->{httpmurder})
667 {
668 $frontend_service_port = Cassandane::PortManager::alloc("localhost");
669 $backend2_service_port = Cassandane::PortManager::alloc("localhost");
670
671 my %frontend_params = %instance_params;
672 my %backend2_params = %instance_params;
673
674 # set up a front end on which we also run the mupdate master
675 my $frontend_conf = $self->{_config}->clone();
676 $frontend_conf->set(
677 servername => "localhost:$frontend_service_port",
678 mupdate_server => "localhost:$mupdate_port",
679 # XXX documentation says to use mupdate_port, but
680 # XXX this doesn't work -- need to embed port number in
681 # XXX mupdate_server setting instead.
682 #mupdate_port => $mupdate_port,
683 mupdate_username => 'mupduser',
684 mupdate_authname => 'mupduser',
685 mupdate_password => 'mupdpass',
686 serverlist =>
687 "localhost:$backend1_service_port localhost:$backend2_service_port",
688 proxy_authname => 'mailproxy',
689 proxy_password => 'mailproxy',
690 );
691
692 my $cyrus_other_prefix = $cassini->val('cyrus other', 'prefix');
693 if (defined $cyrus_other_prefix and -d $cyrus_other_prefix) {
694 xlog $self, "frontend instance: using [cyrus other] configuration";
695 xlog $self, "backend2 instance: using [cyrus other] configuration";
696 $frontend_params{installation} = 'other';
697 $backend2_params{installation} = 'other';
698 }
699
700 $frontend_params{description} = "murder frontend for test $self->{_name}";
701 $frontend_params{config} = $frontend_conf;
702 $self->{frontend} = Cassandane::Instance->new(%frontend_params,
703 setup_mailbox => 0);
704 $self->{frontend}->add_service(name => 'mupdate',
705 port => $mupdate_port,
706 argv => ['mupdate', '-m'],
707 prefork => 1);
708 $self->{frontend}->add_services(@{$want->{services}});
709 $self->{frontend}->_setup_for_deliver()
710 if ($want->{deliver});
711
712 # arrange for frontend service to run on a known port
713 if ($want->{imapmurder}) {
714 $self->{frontend}->remove_service('imap');
715 $self->{frontend}->add_service(name => 'imap',
716 port => $frontend_service_port);
717 }
718 elsif ($want->{httpmurder}) {
719 $self->{frontend}->remove_service('http');
720 $self->{frontend}->add_service(name => 'http',
721 port => $frontend_service_port);
722 }
723 else {
724 die "shouldn't get here!";
725 }
726
727 # arrange for backend1 to push to mupdate on startup
728 $self->{instance}->add_start(name => 'mupdatepush',
729 argv => ['ctl_mboxlist', '-m']);
730
731 # arrange for backend1 service to run on a known port
732 if ($want->{imapmurder}) {
733 $self->{instance}->remove_service('imap');
734 $self->{instance}->add_service(name => 'imap',
735 port => $backend1_service_port);
736 }
737 elsif ($want->{httpmurder}) {
738 $self->{instance}->remove_service('http');
739 $self->{instance}->add_service(name => 'http',
740 port => $backend1_service_port);
741 }
742 else {
743 die "shouldn't get here!";
744 }
745
746 # set up a second backend
747 my $backend2_conf = $self->{_config}->clone();
748 $backend2_conf->set(
749 servername => "localhost:$backend2_service_port",
750 mupdate_server => "localhost:$mupdate_port",
751 # XXX documentation says to use mupdate_port, but
752 # XXX this doesn't work -- need to embed port number in
753 # XXX mupdate_server setting instead.
754 #mupdate_port => $mupdate_port,
755 mupdate_username => 'mupduser',
756 mupdate_authname => 'mupduser',
757 mupdate_password => 'mupdpass',
758 proxyservers => 'mailproxy',
759 lmtp_admins => 'mailproxy',
760 sasl_mech_list => 'PLAIN',
761 proxy_authname => 'mailproxy',
762 proxy_password => 'mailproxy',
763 );
764
765 $backend2_params{description} = "murder backend2 for test $self->{_name}";
766 $backend2_params{config} = $backend2_conf;
767 $self->{backend2} = Cassandane::Instance->new(%backend2_params,
768 setup_mailbox => 0); # XXX ?
769 $self->{backend2}->add_services(@{$want->{services}});
770
771 # arrange for backend2 to push to mupdate on startup
772 $self->{backend2}->add_start(name => 'mupdatepush',
773 argv => ['ctl_mboxlist', '-m']);
774
775 # arrange for backend2 service to run on a known port
776 if ($want->{imapmurder}) {
777 $self->{backend2}->remove_service('imap');
778 $self->{backend2}->add_service(name => 'imap',
779 port => $backend2_service_port);
780 }
781 elsif ($want->{httpmurder}) {
782 $self->{backend2}->remove_service('http');
783 $self->{backend2}->add_service(name => 'http',
784 port => $backend2_service_port);
785 }
786 else {
787 die "shouldn't get here!";
788 }
789
790 $self->{backend2}->_setup_for_deliver()
791 if ($want->{deliver});
792 }
793 }
794
795 if ($want->{gen})
796 {
797 $self->{gen} = Cassandane::Generator->new();
798 }
799 }
800
801 sub _need_http_tiny_env
802 {
803 # Net::DAVTalk < 0.23 and Mail::JMAPTalk < 0.17 don't pass through
804 # SSL_options, but HTTP::Tiny >= 0.083 enables SSL certificate
805 # verification, which will fail without our SSL_options.
806 #
807 # For HTTP::Tiny >= 0.086, we can set an environment variable
808 # to turn off SSL certificate verifications.
809 #
810 # For HTTP::Tiny in 0.083 .. 0.085, ¯\_(ツ)_/¯
811 eval {
812 require Net::DAVTalk;
813 require HTTP::Tiny;
814 };
815 return undef if $@;
816
817 my $ndv = version->parse($Net::DAVTalk::VERSION);
818 my $mjv = version->parse($Mail::JMAPTalk::VERSION);
819 my $htv = version->parse($HTTP::Tiny::VERSION);
820
821 # not needed: old HTTP::Tiny doesn't check certificates
822 return undef if $htv < version->parse('0.083');
823
824 # not needed: new Net::DAVTalk and Mail::JMAPTalk pass through SSL_options
825 return undef if $ndv >= version->parse('0.23')
826 && $mjv >= version->parse('0.17');
827
828 # awkward: HTTP::Tiny 0.083-0.085 are new enough to check certificates
829 # by default, but not new enough for us to override that by the
830 # environment variable. if you get errors here, you need to either
831 # upgrade HTTP::Tiny to 0.086 (or later), or upgrade Net::DAVTalk to 0.23
832 # and Mail::JMAPTalk to 0.17 (or later).
833 HTTP::Tiny->VERSION('0.086');
834
835 xlog "Have Net::DAVTalk version " . Net::DAVTalk->VERSION();
836 xlog "Have Mail::JMAPTalk version " . Mail::JMAPTalk->VERSION();
837 xlog "Have HTTP::Tiny version " . HTTP::Tiny->VERSION();
838 xlog "Will set PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT=1";
839 return 1;
840 }
841
842 sub _setup_http_service_objects
843 {
844 my ($self) = @_;
845
846 # nothing to do if no http or https service
847 my $service = $self->{instance}->get_service("https");
848 $service ||= $self->{instance}->get_service("http");
849 return if !$service;
850
851 my $ca_file = abs_path("data/certs/cacert.pem");
852
853 my %common_args = (
854 user => 'cassandane',
855 password => 'pass',
856 host => $service->host(),
857 port => $service->port(),
858 scheme => ($service->is_ssl() ? 'https' : 'http'),
859 SSL_options => {
860 SSL_ca_file => $ca_file,
861 SSL_verifycn_scheme => 'none',
862 },
863 );
864
865 local $ENV{PERL_HTTP_TINY_SSL_INSECURE_BY_DEFAULT} = _need_http_tiny_env();
866
867 if ($self->{instance}->{config}->get_bit('httpmodules', 'carddav')) {
868 require Net::CardDAVTalk;
869 $self->{carddav} = Net::CardDAVTalk->new(
870 %common_args,
871 url => '/',
872 expandurl => 1,
873 );
874 }
875 if ($self->{instance}->{config}->get_bit('httpmodules', 'caldav')) {
876 require Net::CalDAVTalk;
877 $self->{caldav} = Net::CalDAVTalk->new(
878 %common_args,
879 url => '/',
880 expandurl => 1,
881 );
882 $self->{caldav}->UpdateAddressSet("Test User",
883 "cassandane\@example.com");
884 }
885 if ($self->{instance}->{config}->get_bit('httpmodules', 'jmap')) {
886 require Mail::JMAPTalk;
887 $ENV{DEBUGJMAP} = 1;
888 $self->{jmap} = Mail::JMAPTalk->new(
889 %common_args,
890 url => '/jmap/',
891 );
892
893 # preload default UA while the HTTP::Tiny env var is still set
894 $self->{jmap}->ua();
895 }
896
897 xlog $self, "http service objects setup complete!";
898 }
899
900 sub set_up
901 {
902 my ($self) = @_;
903
904 xlog "---------- BEGIN $self->{_name} ----------";
905
906 $self->_create_instances();
907 if ($self->{_want}->{start_instances}) {
908 eval {
909 $self->_start_instances();
910 $self->_setup_http_service_objects() if defined $self->{instance};
911 };
912 if ($@) {
913 my $e = $@;
914 $self->tear_down();
915 die $e;
916 }
917 }
918 else {
919 xlog $self, "Instances not started due to :NoStartInstances magic!";
920 xlog $self, "HTTP service objects not setup due to :NoStartInstances"
921 . " magic!";
922 }
923
924 if ($self->{no_check_syslog}) {
925 xlog $self, "Disabling syslog checks for test instance";
926 }
927
928 xlog $self, "Calling test function";
929 }
930
931 sub _start_instances
932 {
933 my ($self) = @_;
934
935 $self->{frontend}->start()
936 if (defined $self->{frontend});
937 $self->{instance}->start()
938 if (defined $self->{instance});
939 $self->{backend2}->start()
940 if (defined $self->{backend2});
941 $self->{replica}->start()
942 if (defined $self->{replica});
943
944 $self->{store} = undef;
945 $self->{adminstore} = undef;
946 $self->{master_store} = undef;
947 $self->{master_adminstore} = undef;
948 $self->{replica_store} = undef;
949 $self->{replica_adminstore} = undef;
950 $self->{frontend_store} = undef;
951 $self->{frontend_adminstore} = undef;
952 $self->{backend1_store} = undef;
953 $self->{backend1_adminstore} = undef;
954 $self->{backend2_store} = undef;
955 $self->{backend2_adminstore} = undef;
956
957 # Run the replication engine to create the user mailbox
958 # in the replica. Doing it this way avoids issues with
959 # mismatched mailbox uniqueids.
960 $self->run_replication()
961 if (defined $self->{replica});
962
963 my %store_params;
964 $store_params{folder} = $self->{_want}->{folder}
965 if defined $self->{_want}->{folder};
966
967 my %adminstore_params = ( %store_params, username => 'admin' );
968 # The admin stores need an extra parameter to force their
969 # default folder because otherwise they will default to 'INBOX'
970 # which refers to user.admin not user.cassandane
971 $adminstore_params{folder} ||= 'INBOX';
972 $adminstore_params{folder} = 'user.cassandane'
973 if ($adminstore_params{folder} =~ m/^inbox$/i);
974
975 if (defined $self->{instance})
976 {
977 my $svc = $self->{instance}->get_service('imap');
978 if (defined $svc)
979 {
980 $self->{store} = $svc->create_store(%store_params)
981 if ($self->{_want}->{store});
982 $self->{adminstore} = $svc->create_store(%adminstore_params)
983 if ($self->{_want}->{adminstore});
984 }
985 }
986 if (defined $self->{replica})
987 {
988 # aliases for the master's store(s)
989 $self->{master_store} = $self->{store};
990 $self->{master_adminstore} = $self->{adminstore};
991
992 my $svc = $self->{replica}->get_service('imap');
993 if (defined $svc)
994 {
995 $self->{replica_store} = $svc->create_store(%store_params)
996 if ($self->{_want}->{store});
997 $self->{replica_adminstore} = $svc->create_store(%adminstore_params)
998 if ($self->{_want}->{adminstore});
999 }
1000 }
1001 if (defined $self->{frontend})
1002 {
1003 # aliases for first backend store
1004 $self->{backend1_store} = $self->{store};
1005 $self->{backend1_adminstore} = $self->{adminstore};
1006
1007 my $svc = $self->{frontend}->get_service('imap');
1008 if (defined $svc)
1009 {
1010 $self->{frontend_store} = $svc->create_store(%store_params)
1011 if ($self->{_want}->{store});
1012 $self->{frontend_adminstore} = $svc->create_store(%adminstore_params)
1013 if ($self->{_want}->{adminstore});
1014 }
1015 }
1016 if (defined $self->{backend2})
1017 {
1018 my $svc = $self->{backend2}->get_service('imap');
1019 if (defined $svc)
1020 {
1021 $self->{backend2_store} = $svc->create_store(%store_params)
1022 if ($self->{_want}->{store});
1023 $self->{backend2_adminstore} = $svc->create_store(%adminstore_params)
1024 if ($self->{_want}->{adminstore});
1025 }
1026 }
1027 }
1028
1029 sub tear_down
1030 {
1031 my ($self) = @_;
1032
1033 xlog $self, "Beginning tear_down";
1034
1035 foreach my $s (@stores)
1036 {
1037 if (defined $self->{$s})
1038 {
1039 $self->{$s}->disconnect();
1040 $self->{$s} = undef;
1041 }
1042 }
1043 $self->{master_store} = undef;
1044 $self->{master_adminstore} = undef;
1045 $self->{backend1_store} = undef;
1046 $self->{backend1_adminstore} = undef;
1047
1048 my @stop_errors;
1049 my @basedirs;
1050
1051 if (defined $self->{instance})
1052 {
1053 eval {
1054 push @stop_errors, $self->{instance}->stop(
1055 no_check_syslog => defined $self->{no_check_syslog}
1056 );
1057 };
1058 push @basedirs, $self->{instance}->get_basedir();
1059 $self->{instance} = undef;
1060 }
1061 if (defined $self->{backend2})
1062 {
1063 eval {
1064 push @stop_errors, $self->{backend2}->stop(
1065 no_check_syslog => defined $self->{no_check_syslog}
1066 );
1067 };
1068 push @basedirs, $self->{backend2}->get_basedir();
1069 $self->{backend2} = undef;
1070 }
1071 if (defined $self->{replica})
1072 {
1073 eval {
1074 push @stop_errors, $self->{replica}->stop(
1075 no_check_syslog => defined $self->{no_check_syslog}
1076 );
1077 };
1078 push @basedirs, $self->{replica}->get_basedir();
1079 $self->{replica} = undef;
1080 }
1081 if (defined $self->{frontend})
1082 {
1083 eval {
1084 push @stop_errors, $self->{frontend}->stop(
1085 no_check_syslog => defined $self->{no_check_syslog}
1086 );
1087 };
1088 push @basedirs, $self->{frontend}->get_basedir();
1089 $self->{frontend} = undef;
1090 }
1091
1092 $self->{cleanup_basedirs} = [@basedirs];
1093
1094 if (@stop_errors) {
1095 if (exists $self->{'__Error__'}) {
1096 # XXX this feels fragile, but there isn't a correct way for
1097 # XXX tear_down to see the test's result.
1098
1099 # looks like we already failed, and dying again here would conceal
1100 # the test failure details, which are probably more interesting
1101 xlog "errors found during instance shutdown";
1102 }
1103 else {
1104 # maybe there's multiple errors, but we can only die once...
1105 die $stop_errors[0];
1106 }
1107 }
1108
1109 xlog "---------- END $self->{_name} ----------";
1110 }
1111
1112 sub post_tear_down
1113 {
1114 my ($self, $result) = @_;
1115
1116 if ($result eq 'pass'
1117 && ref $self->{cleanup_basedirs}
1118 && Cassandane::Cassini->instance()->bool_val('cassandane', 'cleanup')
1119 ) {
1120 foreach my $basedir (@{$self->{cleanup_basedirs}}) {
1121 xlog $self, "Cleaning up basedir " . $basedir;
1122 rmtree $basedir;
1123 }
1124 }
1125
1126 die "Found some stray processes"
1127 if (Cassandane::GenericListener::kill_processes_on_ports(
1128 Cassandane::PortManager::free_all()));
1129 }
1130
1131 sub _save_message
1132 {
1133 my ($self, $msg, $store) = @_;
1134
1135 $store ||= $self->{store};
1136
1137 $store->write_begin();
1138 $store->write_message($msg);
1139 $store->write_end();
1140 }
1141
1142 sub make_message
1143 {
1144 my ($self, $subject, %attrs) = @_;
1145
1146 my $store = $attrs{store}; # may be undef
1147 delete $attrs{store};
1148
1149 my $msg = $self->{gen}->generate(subject => $subject, %attrs);
1150 $msg->remove_headers('subject') if !defined $subject;
1151 $msg->remove_headers('to') if exists $attrs{to} and not $attrs{to};
1152 $msg->remove_headers('from') if exists $attrs{from} and not $attrs{from};
1153 $self->_save_message($msg, $store);
1154
1155 return $msg;
1156 }
1157
1158 sub make_random_data
1159 {
1160 my ($self, $kb, %params) = @_;
1161 my $data = '';
1162 $params{minreps} = 10
1163 unless defined $params{minreps};
1164 $params{maxreps} = 100
1165 unless defined $params{maxreps};
1166 $params{separators} = ' '
1167 unless defined $params{separators};
1168 my $sepidx = 0;
1169 while (!defined $kb || length($data) < 1024*$kb)
1170 {
1171 my $word = random_word();
1172 my $count = $params{minreps} +
1173 rand($params{maxreps} - $params{minreps});
1174 while ($count > 0)
1175 {
1176 my $sep = substr($params{separators},
1177 $sepidx % length($params{separators}), 1);
1178 $sepidx++;
1179 $data .= $sep . $word;
1180 $count--;
1181 }
1182 last unless defined $kb;
1183 }
1184 return $data;
1185 }
1186
1187 sub check_messages
1188 {
1189 my ($self, $expected, %params) = @_;
1190 my $actual = $params{actual};
1191 my $check_guid = $params{check_guid};
1192 $check_guid = 1 unless defined $check_guid;
1193 my $keyed_on = $params{keyed_on} || 'subject';
1194
1195 xlog $self, "check_messages: " . join(' ', %params);
1196
1197 if (!defined $actual)
1198 {
1199 my $store = $params{store} || $self->{store};
1200 $actual = {};
1201 $store->read_begin();
1202 while (my $msg = $store->read_message())
1203 {
1204 my $key = $msg->$keyed_on();
1205 $self->assert(!defined $actual->{$key});
1206 $actual->{$key} = $msg;
1207 }
1208 $store->read_end();
1209 }
1210
1211 $self->assert_num_equals(scalar keys %$expected, scalar keys %$actual);
1212
1213 foreach my $expmsg (values %$expected)
1214 {
1215 my $key = $expmsg->$keyed_on();
1216 xlog $self, "message \"$key\"";
1217 my $actmsg = $actual->{$key};
1218
1219 $self->assert_not_null($actmsg);
1220
1221 if ($check_guid)
1222 {
1223 xlog $self, "checking guid";
1224 $self->assert_str_equals($expmsg->get_guid(),
1225 $actmsg->get_guid());
1226 }
1227
1228 # Check required headers
1229 foreach my $h (qw(x-cassandane-unique))
1230 {
1231 xlog $self, "checking header $h";
1232 $self->assert_not_null($actmsg->get_header($h));
1233 $self->assert_str_equals($expmsg->get_header($h),
1234 $actmsg->get_header($h));
1235 }
1236
1237 # if there were optional headers we wished to check, do it here
1238
1239 # check optional string attributes
1240 foreach my $a (qw(id uid cid))
1241 {
1242 next unless defined $expmsg->get_attribute($a);
1243 xlog $self, "checking attribute $a";
1244 $self->assert_str_equals($expmsg->get_attribute($a),
1245 $actmsg->get_attribute($a));
1246 }
1247
1248 # check optional structured attributes
1249 foreach my $a (qw(modseq))
1250 {
1251 next unless defined $expmsg->get_attribute($a);
1252 xlog $self, "checking attribute $a";
1253 $self->assert_deep_equals($expmsg->get_attribute($a),
1254 $actmsg->get_attribute($a));
1255 }
1256
1257 # check optional order-agnostic attributes
1258 foreach my $a (qw(flags))
1259 {
1260 next unless defined $expmsg->get_attribute($a);
1261 xlog $self, "checking attribute $a";
1262
1263 my $exp = $expmsg->get_attribute($a);
1264 my $act = $actmsg->get_attribute($a);
1265
1266 if (ref $exp eq 'ARRAY') {
1267 $exp = [ sort @{$exp} ];
1268 }
1269 if (ref $act eq 'ARRAY') {
1270 $act = [ sort @{$act} ];
1271 }
1272
1273 $self->assert_deep_equals($exp, $act);
1274 }
1275
1276 # check annotations
1277 foreach my $ea ($expmsg->list_annotations())
1278 {
1279 xlog $self, "checking annotation ($ea->{entry} $ea->{attrib})";
1280 $self->assert($actmsg->has_annotation($ea));
1281 my $expval = $expmsg->get_annotation($ea);
1282 my $actval = $actmsg->get_annotation($ea);
1283 if (defined $expval)
1284 {
1285 $self->assert_not_null($actval);
1286 $self->assert_str_equals($expval, $actval);
1287 }
1288 else
1289 {
1290 $self->assert_null($actval);
1291 }
1292 }
1293 }
1294
1295 return $actual;
1296 }
1297
1298 sub _disconnect_all
1299 {
1300 my ($self) = @_;
1301
1302 foreach my $s (@stores)
1303 {
1304 $self->{$s}->disconnect()
1305 if defined $self->{$s};
1306 }
1307 }
1308
1309 sub _reconnect_all
1310 {
1311 my ($self) = @_;
1312
1313 foreach my $s (@stores)
1314 {
1315 if (defined $self->{$s})
1316 {
1317 $self->{$s}->connect();
1318 $self->{$s}->_select();
1319 }
1320 }
1321 }
1322
1323 sub run_replication
1324 {
1325 my ($self, %opts) = @_;
1326
1327 # Parse options from caller
1328 my $server = $self->{replica}->get_service('sync')->store_params()->{host};
1329 $server = delete $opts{server} if exists $opts{server};
1330 # $server might be undef at this point
1331 my $channel = delete $opts{channel};
1332 my $inputfile = delete $opts{inputfile};
1333
1334 # mode options
1335 my $nmodes = 0;
1336 my $user = delete $opts{user};
1337 my $rolling = delete $opts{rolling};
1338 my $mailbox = delete $opts{mailbox};
1339 my $meta = delete $opts{meta};
1340 my $nosyncback = delete $opts{nosyncback};
1341 my $allusers = delete $opts{allusers};
1342 my $stagetoarchive = delete $opts{stagetoarchive};
1343 $nmodes++ if $user;
1344 $nmodes++ if $rolling;
1345 $nmodes++ if $mailbox;
1346 $nmodes++ if $meta;
1347 $nmodes++ if $allusers;
1348
1349 # pass through run_command options
1350 my $handlers = delete $opts{handlers};
1351 my $redirects = delete $opts{redirects};
1352
1353 # historical default for Cassandane tests is user mode
1354 $user = 'cassandane' if ($nmodes == 0);
1355 die "Too many mode options" if ($nmodes > 1);
1356
1357 die "Unrecognised options: " . join(' ', keys %opts) if (scalar %opts);
1358
1359 xlog $self, "running replication";
1360
1361 # Disconnect during replication to ensure no imapd
1362 # is locking the mailbox, which gives us a spurious
1363 # error which is ignored in real world scenarios.
1364 $self->_disconnect_all();
1365
1366 # build sync_client command line
1367 my @cmd = ('sync_client', '-v', '-v', '-o');
1368 push(@cmd, '-S', $server) if defined $server;
1369 push(@cmd, '-n', $channel) if defined $channel;
1370 push(@cmd, '-f', $inputfile) if defined $inputfile;
1371 push(@cmd, '-R') if defined $rolling;
1372 push(@cmd, '-s') if defined $meta;
1373 push(@cmd, '-O') if defined $nosyncback;
1374 push(@cmd, '-u', $user) if defined $user;
1375 push(@cmd, '-m', $mailbox) if defined $mailbox;
1376 push(@cmd, '-A') if $allusers; # n.b. boolean
1377 push(@cmd, '-a') if $stagetoarchive; # n.b. boolean
1378
1379 my %run_options;
1380 $run_options{cyrus} = 1;
1381 $run_options{handlers} = $handlers if defined $handlers;
1382 $run_options{redirects} = $redirects if defined $redirects;
1383 $self->{instance}->run_command(\%run_options, @cmd);
1384
1385 $self->_reconnect_all();
1386 }
1387
1388 sub check_replication {
1389 my ($self, $user) = @_;
1390
1391 # get store connections as the user
1392
1393 my $mastersvc = $self->{instance}->get_service('imap');
1394 my $masterstore = $mastersvc->create_store(username => $user);
1395
1396 my $replicasvc = $self->{replica}->get_service('imap');
1397 my $replicastore = $replicasvc->create_store(username => $user);
1398
1399 my $CR = Cyrus::CheckReplication->new(
1400 IMAPs1 => $masterstore->get_client(),
1401 IMAPs2 => $replicastore->get_client(),
1402 CyrusName => $user,
1403 SleepTime => 0,
1404 Repeats => 1,
1405 CheckConversations => 1,
1406 CheckAnnotations => 1,
1407 CheckMetadata => 1,
1408 );
1409 $CR->CheckUserReplication(2);
1410 if ($CR->HasError()) {
1411 my @Messages = $CR->GetMessages();
1412 $self->assert(0, "GOT ERRORS " . join(', ', @Messages));
1413 }
1414 }
1415
1416 sub run_delayed_expunge
1417 {
1418 my ($self) = @_;
1419
1420 xlog $self, "Performing delayed expunge";
1421
1422 $self->_disconnect_all();
1423
1424 my @cmd = ( 'cyr_expire', '-E', '1', '-X', '0', '-D', '0' );
1425 push(@cmd, '-v')
1426 if get_verbose;
1427 $self->{instance}->run_command({ cyrus => 1 }, @cmd);
1428
1429 $self->_reconnect_all();
1430 }
1431
1432 sub check_conversations
1433 {
1434 my ($self) = @_;
1435 my $filename = $self->{instance}{basedir} . "/ctl_conversationsdb.out";
1436 $self->{instance}->run_command({
1437 cyrus => 1,
1438 redirects => {stdout => $filename},
1439 }, 'ctl_conversationsdb', '-A', '-r', '-v');
1440
1441 my $str = slurp_file($filename);
1442
1443 xlog $self, "RESULT: $str";
1444 $self->assert_matches(qr/is OK/, $str);
1445 $self->assert_does_not_match(qr/is BROKEN/, $str);
1446 }
1447
1448 # Set up a mailbox structure from data
1449 # See List.pm tests for examples of how to drive this
1450 sub setup_mailbox_structure
1451 {
1452 my ($self, $client, $test_data) = @_;
1453
1454 foreach my $row (@{$test_data}) {
1455 my ($cmd, $arg) = @{$row};
1456 if (ref $arg) {
1457 foreach (@{$arg}) {
1458 $client->$cmd($_) || die "$cmd '$_': $@";
1459 }
1460 }
1461 else {
1462 $client->$cmd($arg) || die "$cmd '$_': $@";
1463 }
1464 }
1465 }
1466
1467 # Assert that the provided LIST response match the expected data
1468 # See List.pm tests for examples of how to drive this
1469 sub assert_mailbox_structure
1470 {
1471 my ($self, $actual, $expected_hiersep, $expected_mailbox_flags,
1472 $strict, $msg) = @_;
1473
1474 # rearrange list output into order-agnostic format
1475 my %actual_hash;
1476 foreach my $row (@{$actual}) {
1477 my ($flags, $hiersep, $mailbox) = @{$row};
1478
1479 $actual_hash{$mailbox} = {
1480 flags => { map { (lc($_) => 1) } @{$flags} },
1481 hiersep => $hiersep,
1482 mailbox => $mailbox,
1483 }
1484 }
1485
1486 # check that expected data exists
1487 foreach my $mailbox (sort keys %{$expected_mailbox_flags}) {
1488 xlog $self, "expect mailbox: $mailbox";
1489 $self->assert(
1490 exists $actual_hash{$mailbox},
1491 "'$mailbox': mailbox not found"
1492 );
1493
1494 $self->assert_str_equals(
1495 $actual_hash{$mailbox}->{hiersep},
1496 $expected_hiersep,
1497 "'$mailbox': got hierarchy separator '"
1498 . $actual_hash{$mailbox}->{hiersep}
1499 . "', expected '$expected_hiersep'"
1500 );
1501
1502 my %expected_flags;
1503 if (ref $expected_mailbox_flags->{$mailbox}) {
1504 %expected_flags = map { (lc($_) => 1) }
1505 @{$expected_mailbox_flags->{$mailbox}};
1506 }
1507 else {
1508 %expected_flags = map { (lc($_) => 1) }
1509 split / /, $expected_mailbox_flags->{$mailbox};
1510 }
1511
1512 # look for expected flags
1513 foreach my $flag (sort keys %expected_flags) {
1514 # https://tools.ietf.org/html/rfc5258#section-3.4:
1515 # \NoInferiors implies \HasNoChildren
1516 # \NonExistent implies \NoSelect
1517 if ($flag eq "\\hasnochildren") {
1518 $self->assert(
1519 (exists $actual_hash{$mailbox}->{flags}->{$flag}
1520 || exists $actual_hash{$mailbox}->{flags}->{"\\noinferiors"}),
1521 "'$mailbox': missing flag '$flag'"
1522 );
1523 }
1524 elsif ($flag eq "\\noselect") {
1525 $self->assert(
1526 (exists $actual_hash{$mailbox}->{flags}->{$flag}
1527 || exists $actual_hash{$mailbox}->{flags}->{"\\nonexistent"}),
1528 "'$mailbox': missing flag '$flag'"
1529 );
1530 }
1531 else {
1532 $self->assert(
1533 exists $actual_hash{$mailbox}->{flags}->{$flag},
1534 "'$mailbox': missing flag '$flag'"
1535 );
1536 }
1537 }
1538
1539 next if not $strict;
1540
1541 # look for unexpected flags
1542 foreach my $flag (sort keys %{$actual_hash{$mailbox}->{flags}}) {
1543 if ($flag eq "\\noinferiors") {
1544 $self->assert(
1545 (exists $actual_hash{$mailbox}->{flags}->{$flag}
1546 || exists $actual_hash{$mailbox}->{flags}->{"\\hasnochildren"}),
1547 "'$mailbox': found unexpected flag '$flag'"
1548 );
1549 }
1550 elsif ($flag eq "\\nonexistent") {
1551 $self->assert(
1552 (exists $actual_hash{$mailbox}->{flags}->{$flag}
1553 || exists $actual_hash{$mailbox}->{flags}->{"\\noselect"}),
1554 "'$mailbox': found unexpected flag '$flag'"
1555 );
1556 }
1557 else {
1558 $self->assert(
1559 exists $expected_flags{$flag},
1560 "'$mailbox': found unexected flag '$flag'"
1561 );
1562 }
1563 }
1564 }
1565
1566 # check that unexpected data does not exist
1567 foreach my $mailbox (sort keys %actual_hash) {
1568 $self->assert(
1569 exists $expected_mailbox_flags->{$mailbox},
1570 "'$mailbox': found unexpected extra mailbox"
1571 );
1572 }
1573 }
1574
1575 sub assert_sieve_exists
1576 {
1577 my ($self, $instance, $user, $scriptname, $bc_only) = @_;
1578
1579 my $sieve_dir = $instance->get_sieve_script_dir($user);
1580
1581 $self->assert(( -f "$sieve_dir/$scriptname.bc" ),
1582 "$sieve_dir/$scriptname.bc: file not found");
1583
1584 if ($bc_only == 0) {
1585 $self->assert(( -f "$sieve_dir/$scriptname.script" ),
1586 "$sieve_dir/$scriptname.script: file not found");
1587 }
1588 }
1589
1590 sub assert_sieve_not_exists
1591 {
1592 my ($self, $instance, $user, $scriptname, $bc_only) = @_;
1593
1594 my $sieve_dir = $instance->get_sieve_script_dir($user);
1595
1596 $self->assert(( ! -f "$sieve_dir/$scriptname.bc" ),
1597 "$sieve_dir/$scriptname.bc: file exists");
1598
1599 if ($bc_only == 0) {
1600 $self->assert(( ! -f "$sieve_dir/$scriptname.script" ),
1601 "$sieve_dir/$scriptname.script: file exists");
1602 }
1603 }
1604
1605 sub assert_sieve_active
1606 {
1607 my ($self, $instance, $user, $scriptname) = @_;
1608
1609 my $sieve_dir = $instance->get_sieve_script_dir($user);
1610
1611 $self->assert(( -l "$sieve_dir/defaultbc" ),
1612 "$sieve_dir/defaultbc: missing or not a symlink");
1613 $self->assert_str_equals("$scriptname.bc", readlink "$sieve_dir/defaultbc");
1614 }
1615
1616 sub assert_sieve_noactive
1617 {
1618 my ($self, $instance, $user) = @_;
1619
1620 my $sieve_dir = $instance->get_sieve_script_dir($user);
1621
1622 $self->assert(( ! -e "$sieve_dir/defaultbc" ),
1623 "$sieve_dir/defaultbc exists");
1624 $self->assert(( ! -l "$sieve_dir/defaultbc" ),
1625 "dangling $sieve_dir/defaultbc symlink exists");
1626 }
1627
1628 sub assert_sieve_matches
1629 {
1630 my ($self, $instance, $user, $scriptname, $scriptcontent) = @_;
1631
1632 my $sieve_dir = $instance->get_sieve_script_dir($user);
1633
1634 my $bcname = "$sieve_dir/$scriptname.bc";
1635
1636 $self->assert(( -f $bcname ),
1637 "$sieve_dir/$scriptname.bc: file not found");
1638
1639 # compile $scriptcontent and compare digests of bytecode
1640 my (undef, $tmp) = tempfile('scriptXXXXX', OPEN => 0,
1641 DIR => $instance->{basedir} . "/tmp");
1642 open my $f, '>', $tmp or die "open: $!";
1643 print $f $scriptcontent;
1644 close $f;
1645
1646 my (undef, $filename) = tempfile('tmpXXXXXX', OPEN => 0,
1647 DIR => $instance->{basedir} . "/tmp");
1648
1649 $instance->run_command({ redirects => {stdin => \$scriptcontent},
1650 cyrus => 1,
1651 },
1652 'sievec', $tmp, "$filename");
1653 $self->assert_str_equals(digest_file_hex($bcname, "MD5"),
1654 digest_file_hex($filename, "MD5"));
1655 }
1656
1657 sub assert_syslog_matches
1658 {
1659 my ($self, $instance, $pattern) = @_;
1660
1661 if ($instance->{have_syslog_replacement}) {
1662 $self->assert((scalar $instance->getsyslog($pattern) >= 1),
1663 "syslog does not match pattern $pattern");
1664 }
1665 }
1666
1667 sub assert_syslog_does_not_match
1668 {
1669 my ($self, $instance, $pattern) = @_;
1670
1671 if ($instance->{have_syslog_replacement}) {
1672 $self->assert((scalar $instance->getsyslog($pattern) == 0),
1673 "syslog matches pattern $pattern");
1674 }
1675 }
1676
1677 # create a bunch of mailboxes and messages with various flags and annots,
1678 # returning a hash of what to expect to find there later
1679 sub populate_user
1680 {
1681 my ($self, $instance, $store, $folders) = @_;
1682
1683 my $created = {};
1684
1685 my @specialuse = qw(Drafts Junk Sent Trash);
1686
1687 foreach my $folder (@{$folders}) {
1688 $store->set_folder($folder);
1689
1690 # create some messages
1691 foreach my $n (1 .. 20) {
1692 my $msg = $self->make_message("Message $n", store => $store);
1693 $created->{mailboxes}->{$folder}->{messages}->{$msg->uid()} = $msg;
1694 }
1695
1696 # fizzbuzz some flags
1697 my $talk = $store->get_client();
1698 $talk->select($folder);
1699 my $n = 1;
1700 while (my ($uid, $msg)
1701 = each %{$created->{mailboxes}->{$folder}->{messages}})
1702 {
1703 my @flags;
1704
1705 if ($n % 3 == 0) {
1706 # fizz
1707 $talk->store("$uid", '+flags', '(\\Flagged)');
1708 $self->assert_str_equals(
1709 'ok', $talk->get_last_completion_response()
1710 );
1711 push @flags, '\\Flagged';
1712 }
1713 if ($n % 5 == 0) {
1714 # buzz
1715 $talk->store("$uid", '+flags', '(\\Deleted)');
1716 $self->assert_str_equals(
1717 'ok', $talk->get_last_completion_response()
1718 );
1719 push @flags, '\\Deleted';
1720 }
1721
1722 $msg->set_attribute('flags', \@flags) if scalar @flags;
1723 $n++;
1724 }
1725
1726 # make sure the messages are as expected
1727 $store->set_fetch_attributes('uid', 'flags');
1728 $self->check_messages($created->{mailboxes}->{$folder}->{messages},
1729 store => $store,
1730 check_guid => 0,
1731 keyed_on => 'uid');
1732
1733 # maybe set a special use annotation if the folder name is such
1734 my ($suflag, @extra) = grep {
1735 lc $folder =~ m{^(?:INBOX[./])?$_$}
1736 } @specialuse;
1737 if ($suflag and not scalar @extra) {
1738 $talk->setmetadata($folder, '/private/specialuse', "\\$suflag");
1739 $self->assert_str_equals('ok',
1740 $talk->get_last_completion_response());
1741 $created->{mailboxes}->{$folder}->{specialuse} = "\\$suflag";
1742 }
1743 }
1744
1745 # XXX ought to be conditional on whether $instance was built with sieve
1746 # XXX support, but Cassandane::BuildInfo doesn't currently support
1747 # XXX choosing an instance to ask about...
1748 my $scriptname = random_word();
1749 my $scriptcontent = 'keep;';
1750
1751 $instance->install_sieve_script($scriptcontent,
1752 name => $scriptname,
1753 username => $store->{username});
1754 $self->assert_sieve_exists($instance, $store->{username}, $scriptname);
1755 $self->assert_sieve_active($instance, $store->{username}, $scriptname);
1756
1757 $created->{sieve}->{scripts}->{$scriptname} = $scriptcontent;
1758 $created->{sieve}->{active} = $scriptname;
1759
1760 return $created;
1761 }
1762
1763 # check that the contents of the store match the data returned by
1764 # populate_user()
1765 sub check_user
1766 {
1767 my ($self, $instance, $store, $expected) = @_;
1768
1769 die "bad expected hash" if ref $expected ne 'HASH';
1770
1771 foreach my $folder (keys %{$expected->{mailboxes}}) {
1772 $store->set_folder($folder);
1773 $store->set_fetch_attributes('uid', 'flags');
1774 $self->check_messages($expected->{mailboxes}->{$folder}->{messages},
1775 store => $store,
1776 check_guid => 0,
1777 keyed_on => 'uid');
1778
1779 my $specialuse = $expected->{mailboxes}->{$folder}->{specialuse};
1780 if ($specialuse) {
1781 my $talk = $store->get_client();
1782 my $res = $talk->getmetadata($folder, '/private/specialuse');
1783 $self->assert_str_equals('ok',
1784 $talk->get_last_completion_response());
1785 $self->assert_not_null($res);
1786
1787 $self->assert_str_equals($specialuse,
1788 $res->{$folder}->{'/private/specialuse'});
1789 }
1790 }
1791
1792 if (exists $expected->{sieve}) {
1793 while (my ($scriptname, $scriptcontent)
1794 = each %{$expected->{sieve}->{scripts}})
1795 {
1796 $self->assert_sieve_exists($instance, $store->{username},
1797 $scriptname, 1);
1798 $self->assert_sieve_matches($instance, $store->{username},
1799 $scriptname, $scriptcontent);
1800 }
1801 if ($expected->{sieve}->{active}) {
1802 $self->assert_sieve_active($instance, $store->{username},
1803 $expected->{sieve}->{active});
1804 }
1805 }
1806 }
1807
1808 1;