sympa.pl 83.8 KB
Newer Older
root's avatar
root committed
1
#! --PERL--
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# sympa.pl - This script is the main one ; it runs as a daemon and does
# the messages/commands processing
# RCS Identication ; $Revision$ ; $Date$ 
#
# Sympa - SYsteme de Multi-Postage Automatique
# Copyright (c) 1997, 1998, 1999, 2000, 2001 Comite Reseau des Universites
# Copyright (c) 1997,1998, 1999 Institut Pasteur & Christophe Wolfhugel
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

root's avatar
root committed
24
25
use strict;

26
use lib '--LIBDIR--';
27
#use Getopt::Std;
28
use Getopt::Long;
root's avatar
root committed
29
30
31
32
33
34

use Mail::Address;
use File::Path;

use Commands;
use Conf;
35
use Auth;
36
use SympaSession;
root's avatar
root committed
37
38
39
use Language;
use Log;
use Version;
40
use mail;
root's avatar
root committed
41
42
use MIME::QuotedPrint;
use List;
43
use Message;
44
45
46
use admin;
use Config_XML;
use Family;
47
use report;
48
use File::Copy;
49

root's avatar
root committed
50
require 'tools.pl';
51
require 'tt2.pl';
52
require 'parser.pl';
53

root's avatar
root committed
54
55
56
# durty global variables
my $is_signed = {}; 
my $is_crypted ;
57

root's avatar
root committed
58
59
60
61
62

## Internal tuning
# delay between each read of the digestqueue
my $digestsleep = 5; 

63
64
65
## Init random engine
srand (time());

66
my $version_string = "Sympa version is $Version\n";
67

68
69
70
71
72
my $daemon_name = &Log::set_daemon($0);
my $ip;
$ip = $ENV{'REMOTE_HOST'};
$ip = $ENV{'REMOTE_ADDR'} unless ($ip);

73
74
75
76
my $usage_string = "Usage:
   $0 [OPTIONS]

Options:
77
78
   -d, --debug                           : sets Sympa in debug mode 
   -f, --config=FILE                     : uses an alternative configuration file
79
   --import=list\@dom                    : import subscribers (read from STDIN)
80
81
82
   -k, --keepcopy=dir                    : keep a copy of incoming message
   -l, --lang=LANG                       : use a language catalog for Sympa
   -m, --mail                            : log calls to sendmail
83
   --service=process_command|process_message|process_creation  : process dedicated to messages distribution, commands or to automatic lists creation (default three of them)
84
   --dump=list\@dom|ALL                  : dumps subscribers 
85
   --make_alias_file                     : create file in /tmp with all aliases (usefull when aliases.tpl is changed)
86
   --lowercase                           : lowercase email addresses in database
87
   --md5_encode_password                 : rewrite password in database using md5 fingerprint. YOU CAN'T UNDO unless you save this table first
88
   --create_list --robot=robot_name --input_file=/path/to/file.xml 
89
                                         : create a list with the xml file under robot_name
90
   --instantiate_family=family_name  --robot=robot_name --input_file=/path/to/file.xml [--close_unknown] [--quiet]
91
                                         : instantiate family_name lists described in the file.xml under robot_name,
92
93
94
                                           the family directory must exist ;
                                           automatically close undefined lists in a new instantation if --close_unknown specified,
                                           do not print report if --quiet specified.
95
  --add_list=family_name --robot=robot_name --input_file=/path/to/file.xml
96
97
                                         : add the list described by the file.xml under robot_name, to the family
                                           family_name.
98
   --modify_list=family_name --robot=robot_name --input_file=/path/to/file.xml
99
100
101
102
                                         : modify the existing list installed under the robot_name robot and that 
                                           belongs to family_name family. The new description is in the file.xml
   --close_family=family_name --robot=robot_name 
                                         : close lists of family_name family under robot_name.      
103

104
   --close_list=listname\@robot          : close a list
serge.aumont's avatar
   
serge.aumont committed
105
   --purge_list=listname\@robot          : remove a list no backup is possible
106
   --sync_include=listname\@robot        : trigger the list members update
107
108
   --reload_list_config --list=mylist\@mydom  : recreates all config.bin files. You should run this command if you edit 
                                                authorization scenarios. The list parameter is optional.
109
   --upgrade [--from=X] [--to=Y]             : runs Sympa maintenance script to upgrade from version X to version Y
110
   --log_level=LEVEL                     : sets Sympa log level
111
   --md5_digest=password                 : output a MD5 digest of a password (usefull for SOAP client trusted application)
112
113
   -h, --help                            : print this help
   -v, --version                         : print version number
114
115
116
117
118
119

Sympa is a mailinglists manager and comes with a complete (user and admin)
web interface. Sympa  can be linked to an LDAP directory or an RDBMS to 
create dynamic mailing lists. Sympa provides S/MIME and HTTPS based authentication and
encryption.
";
root's avatar
root committed
120

121
122
## Check --dump option
my %options;
serge.aumont's avatar
   
serge.aumont committed
123
unless (&GetOptions(\%main::options, 'dump=s', 'debug|d', ,'log_level=s','foreground', 'service=s','config|f=s', 
124
		    'lang|l=s', 'mail|m', 'keepcopy|k=s', 'help', 'version', 'import=s','make_alias_file','lowercase','md5_encode_password',
serge.aumont's avatar
   
serge.aumont committed
125
		    'close_list=s','purge_list=s','create_list','instantiate_family=s','robot=s','add_list=s','modify_list=s','close_family=s','md5_digest=s',
126
		    'input_file=s','sync_include=s','upgrade','from=s','to=s','reload_list_config','list=s','quiet','close_unknown')) {
127
128
    &fatal_err("Unknown options.");
}
129

130
if ($main::options{'debug'}) {
salaun's avatar
salaun committed
131
    $main::options{'log_level'} = 2 unless ($main::options{'log_level'});
132
}
133
## Batch mode, ie NOT daemon
134
$main::options{'batch'} = 1 if ($main::options{'dump'} || 
135
136
137
138
139
				$main::options{'help'} ||
				$main::options{'version'} || 
				$main::options{'import'} || 
				$main::options{'make_alias_file'} ||
				$main::options{'lowercase'} ||
140
				$main::options{'md5_encode_password'} ||
141
				$main::options{'close_list'} ||
serge.aumont's avatar
   
serge.aumont committed
142
				$main::options{'purge_list'} ||
143
144
145
146
147
148
149
150
151
				$main::options{'create_list'} ||
				$main::options{'instantiate_family'} ||
				$main::options{'add_list'} ||
				$main::options{'modify_list'} ||
				$main::options{'close_family'} ||
				$main::options{'md5_digest'} || 
				$main::options{'sync_include'} ||
				$main::options{'upgrade'} ||
				$main::options{'reload_list_config'}
152
153
154
155
156
157
				 );

# Some option force foreground mode
$main::options{'foreground'} = 1 if ($main::options{'debug'} || $main::options{'batch'});

$main::options{'log_to_stderr'} = 1 unless ($main::options{'batch'});
158
$main::options{'log_to_stderr'} = 1 if ($main::options{'upgrade'} || $main::options{'reload_list_config'});
159

root's avatar
root committed
160
161
162
163
my @parser_param = ($*, $/);
my %loop_info;
my %msgid_table;

salaun's avatar
salaun committed
164
165
166
# this loop is run foreach HUP signal received
my $signal = 0;

167
local $main::daemon_usage; 
serge.aumont's avatar
   
serge.aumont committed
168

salaun's avatar
salaun committed
169
while ($signal ne 'term') { #as long as a SIGTERM is not received }
salaun's avatar
salaun committed
170

171
my $config_file = $main::options{'config'} || '--CONFIG--';
root's avatar
root committed
172
173
## Load configuration file
unless (Conf::load($config_file)) {
174
   &fatal_err("Configuration file $config_file has errors.");
175
   
root's avatar
root committed
176
177
178
179
}

## Open the syslog and say we're read out stuff.
do_openlog($Conf{'syslog'}, $Conf{'log_socket_type'}, 'sympa');
180
181
182

# setting log_level using conf unless it is set by calling option
if ($main::options{'log_level'}) {
183
184
    &Log::set_log_level($main::options{'log_level'});
    do_log('info', "Configuration file read, log level set using options : $main::options{'log_level'}"); 
185
}else{
186
187
    &Log::set_log_level($Conf{'log_level'});
    do_log('info', "Configuration file read, default log level $Conf{'log_level'}"); 
188
189
}

root's avatar
root committed
190
191
## Probe Db if defined
if ($Conf{'db_name'} and $Conf{'db_type'}) {
192
    unless (&Upgrade::probe_db()) {
root's avatar
root committed
193
194
195
196
197
198
199
	&fatal_err('Database %s defined in sympa.conf has not the right structure or is unreachable. If you don\'t use any database, comment db_xxx parameters in sympa.conf', $Conf{'db_name'});
    }
}

## Apply defaults to %List::pinfo
&List::_apply_defaults();

200
201
&tools::ciphersaber_installed();

202
if (&tools::cookie_changed($Conf{'cookie'})) {
203
     &fatal_err("sympa.conf/cookie parameter has changed. You may have severe inconsitencies into password storage. Restore previous cookie or write some tool to re-encrypt password in database and check spools contents (look at $Conf{'etc'}/cookies.history file)");
204
205
}

root's avatar
root committed
206
## Set locale configuration
207
208
$main::options{'lang'} =~ s/\.cat$//; ## Compatibility with version < 2.3.3
$Language::default_lang = $main::options{'lang'} || $Conf{'lang'};
root's avatar
root committed
209
210
211
212
213
214

## Main program
if (!chdir($Conf{'home'})) {
   fatal_err("Can't chdir to %s: %m", $Conf{'home'});
   ## Function never returns.
}
215

serge.aumont's avatar
   
serge.aumont committed
216
if ($main::options{'service'} eq 'process_message') {
217
    $main::daemon_usage = DAEMON_MESSAGE;
serge.aumont's avatar
   
serge.aumont committed
218
}elsif ($main::options{'service'} eq 'process_command') {
219
220
221
    $main::daemon_usage = DAEMON_COMMAND;
}elsif ($main::options{'service'} eq 'process_creation') {
    $main::daemon_usage = DAEMON_CREATION;
serge.aumont's avatar
   
serge.aumont committed
222
}else{
223
    $main::daemon_usage = DAEMON_ALL; # default is to run one sympa.pl server for commands, messages and automatic lists creation. 
serge.aumont's avatar
   
serge.aumont committed
224
}
root's avatar
root committed
225

226
227
## Check for several files.
unless (&Conf::checkfiles_as_root()) {
sympa-authors's avatar
   
sympa-authors committed
228
   fatal_err("output checkfiles_as_root : Missing files. Aborting.");
229
230
231
   ## No return.
}

232
## Check that the data structure is uptodate
233
unless ($main::options{'upgrade'} || $main::options{'help'}) {
234
235
236
237
238
    unless (&Upgrade::data_structure_uptodate()) {
	&fatal_err("error : data structure was not updated ; you should run sympa.pl --upgrade to run the upgrade process.");
    }
}

serge.aumont's avatar
   
serge.aumont committed
239
if ($signal ne 'hup') {
240
241
242
243
    ## Put ourselves in background if we're not in debug mode. That method
    ## works on many systems, although, it seems that Unix conceptors have
    ## decided that there won't be a single and easy way to detach a process
    ## from its controlling tty.
244
    unless ($main::options{'foreground'}) {
245
246
247
248
249
	if (open(TTY, "/dev/tty")) {
	    ioctl(TTY, 0x20007471, 0);         # XXX s/b &TIOCNOTTY
	    #       ioctl(TTY, &TIOCNOTTY, 0);
	    close(TTY);
	}
250
	open(STDIN, ">> /dev/null");
251
	open(STDOUT, ">> /dev/null");
252
253
	open(STDERR, ">> /dev/null");

254
	setpgrp(0, 0);
serge.aumont's avatar
   
serge.aumont committed
255
256
	# start the main sympa.pl daemon

257
258
259
	## Fork a new process dedicated to automatic list creation, if required
	if (($Conf{'automatic_list_feature'} eq 'on') || $main::daemon_usage == DAEMON_CREATION) {
	    do_log('debug', "Starting server for automatic lists creation");
serge.aumont's avatar
   
serge.aumont committed
260
	    if ((my $child_pid = fork) != 0) {
261
262
263
264
265
		do_log('notice', "Server for automatic lists creation started, pid $child_pid");
		do_log('debug', "Server for automatic lists creation started, pid $child_pid, exiting from initial process");
	    }else {
		## We're in the specialized child process
		$main::daemon_usage = DAEMON_CREATION; # automatic lists creation	    
serge.aumont's avatar
   
serge.aumont committed
266
	    }
267
268
269
270
271
272
273
274
275
276
277
	}

	unless ($main::daemon_usage == DAEMON_CREATION) {

	    ## A single process that handles both messages and commands
	    ## The distribute/ spool is not used
	    if ($Conf{'distribution_mode'} eq 'single' && 
		
		$main::daemon_usage == DAEMON_ALL ) {
		my $purpose = 'all';
		&do_log('debug', "Starting server for $purpose purpose");
serge.aumont's avatar
   
serge.aumont committed
278
		if ((my $child_pid = fork) != 0) {
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
		    do_log('info', "Server started for $purpose, pid $child_pid");
		    do_log('debug', "$purpose server started, pid $child_pid, exiting from initial process");
		    exit(0);
		}
		
		## Starting a dedicated process if sympa.pl is started with a --service argument
	    }elsif ($main::daemon_usage == DAEMON_COMMAND ||
		    $main::daemon_usage == DAEMON_COMMAND){
		
		my $purpose;
		if ($main::daemon_usage == DAEMON_COMMAND) {$purpose = 'command';}
		elsif ($main::daemon_usage == DAEMON_MESSAGE) {$purpose = 'message';}
		do_log('debug', "Starting server for $purpose purpose");
		if ((my $child_pid = fork) != 0) {
		    do_log('info', "Server started for $purpose, pid $child_pid");
		    do_log('debug', "$purpose server started, pid $child_pid, exiting from initial process");
		    exit(0);
		}
		
		## Sympa forks to have 2 dedicated processes for processing commands and messages
	    }else{
		$main::daemon_usage = DAEMON_COMMAND; # fork sympa.pl dedicated to commands
		do_log('debug', "Starting server for commands");
		if ((my $child_pid = fork) != 0) {
		    do_log('info', "Server for commands started, pid $child_pid");
		    $main::daemon_usage = DAEMON_MESSAGE; # main process continue in order to fork
		    do_log('debug', "Starting server for messages");	    
		    if ((my $child_pid = fork) != 0) {
			do_log('notice', "Server for messages started, pid $child_pid");
			do_log('debug', "Server for messages started, pid $child_pid, exiting from initial process");
			exit(0);  # exit from main process
		    }
		}
serge.aumont's avatar
   
serge.aumont committed
312
	    }
313
314
	}
    }
serge.aumont's avatar
   
serge.aumont committed
315
316

    my $service = 'sympa';
317
    $service .= '(distribute)' if ($main::daemon_usage == DAEMON_MESSAGE);
318
319
    $service .= '(command)' if ($main::daemon_usage == DAEMON_COMMAND);
    $service .= '(creation)' if ($main::daemon_usage == DAEMON_CREATION);
serge.aumont's avatar
   
serge.aumont committed
320
321
    do_openlog($Conf{'syslog'}, $Conf{'log_socket_type'}, $service);

322
    do_log('debug', "Running server $$ for $service purpose ");
323
    unless ($main::options{'batch'} ) {
324

325
	## Create and write the pidfile
serge.aumont's avatar
   
serge.aumont committed
326
	my $file = $Conf{'pidfile'};
327
328
	$file = $Conf{'pidfile_distribute'} if ($main::daemon_usage == DAEMON_MESSAGE) ;
	$file = $Conf{'pidfile_creation'} if ($main::daemon_usage == DAEMON_CREATION) ;
serge.aumont's avatar
   
serge.aumont committed
329
	&tools::write_pid($file, $$);
330
331
    }	

332

333
    # Set the UserID & GroupID for the process
334
    $( = $) = (getgrnam('--GROUP--'))[2];
335
    $< = $> = (getpwnam('--USER--'))[2];
336

337
338
339
340
    ## Required on FreeBSD to change ALL IDs(effective UID + real UID + saved UID)
    &POSIX::setuid((getpwnam('--USER--'))[2]);
    &POSIX::setgid((getgrnam('--GROUP--'))[2]);

341
342
343
344
345
    ## Check if the UID has correctly been set (usefull on OS X)
    unless (($( == (getgrnam('--GROUP--'))[2]) && ($< == (getpwnam('--USER--'))[2])) {
	&fatal_err("Failed to change process userID and groupID. Note that on some OS Perl scripts can't change their real UID. In such circumstances Sympa should be run via SUDO.");
    }

346
    # Sets the UMASK
347
    umask(oct($Conf{'umask'}));
348

349
350
351
352
353
354
 ## Most initializations have now been done.
    do_log('notice', "Sympa $Version started");
}else{
    do_log('notice', "Sympa $Version reload config");
    $signal = '0';
}
root's avatar
root committed
355
356

## Check for several files.
357
## Prevent that 2 processes perform checks at the same time...
358
359
if ($main::daemon_usage == DAEMON_COMMAND ||
    $main::daemon_usage == DAEMON_ALL) {
360
361
362
363
    unless (&Conf::checkfiles()) {
	fatal_err("Missing files. Aborting.");
	## No return.
    }
364
365
}else {
    sleep 1; ## wait until main process has created required directories
root's avatar
root committed
366
367
}

368
## Daemon called for dumping subscribers list
369
if ($main::options{'dump'}) {
370
    
371
    my ($all_lists, $list);
372
    if ($main::options{'dump'} eq 'ALL') {
373
	$all_lists = &List::get_lists('*');
374
    }else {	
375
	
376
377
378
	## The parameter can be a list address
	unless ($main::options{'dump'} =~ /\@/) {
	    &do_log('err','Incorrect list address %s', $main::options{'dump'});
379
	    
380
381
382
	    exit;
	} 

383
	my $list = new List ($main::options{'dump'});
384
	unless (defined $list) {
385
	    &do_log('err','Unknown list %s', $main::options{'dump'});
386
	    
387
	    exit;
388
	}
389
	push @$all_lists, $list;
390
    }
391

392
    foreach my $list (@$all_lists) {
393
	unless ($list->dump()) {
394
	    printf STDERR "Could not dump list(s)\n";
395
	}
396
    }
397

398
399
400
    exit 0;
}elsif ($main::options{'help'}) {
    print $usage_string;
salaun's avatar
salaun committed
401
402
    exit 0;
}elsif ($main::options{'make_alias_file'}) {
403
    my $all_lists = &List::get_lists('*');
salaun's avatar
salaun committed
404
405
406
407
    unless (open TMP, ">/tmp/sympa_aliases.$$") {
	printf STDERR "Unable to create tmp/sympa_aliases.$$, exiting\n";
	exit;
    }
408
    printf TMP "#\n#\tAliases for all Sympa lists open (but not for robots)\n#\n";
salaun's avatar
salaun committed
409
    close TMP;
410
    foreach my $list (@$all_lists) {
411
	system ("$Conf{'alias_manager'} add $list->{'name'} $list->{'domain'} /tmp/sympa_aliases.$$") if ($list->{'admin'}{'status'} eq 'open');
salaun's avatar
salaun committed
412
413
    }
    printf ("Sympa aliases file is /tmp/sympa_aliases.$$ file made, you probably need to installed it in your SMTP engine\n");
414
415
416
417
418
    
    exit 0;
}elsif ($main::options{'version'}) {
    print $version_string;
    
419
420
    exit 0;
}elsif ($main::options{'md5_digest'}) {
421
    my $md5 = &tools::md5_fingerprint($main::options{'md5_digest'});
422
423
    printf "md5 digest : $md5 \n";
    
salaun's avatar
salaun committed
424
425
426
    exit 0;
}elsif ($main::options{'import'}) {
    my ($list, $total);
427
428
429
430
431
432
433
434

    ## The parameter should be a list address
    unless ($main::options{'import'} =~ /\@/) {
	&do_log('err','Incorrect list address %s', $main::options{'import'});
	exit;
    } 


salaun's avatar
salaun committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    unless ($list = new List ($main::options{'import'})) {
	fatal_err('Unknown list name %s', $main::options{'import'});
    }

    ## Read imported data from STDIN
    while (<STDIN>) {
	next if /^\s*$/;
	next if /^\s*\#/;

	unless (/^\s*((\S+|\".*\")@\S+)(\s*(\S.*))?\s*$/) {
	    printf STDERR "Not an email address: %s\n", $_;
	}

	my $email = lc($1);
	my $gecos = $4;
450
451
452
	my $u;
	my $defaults = $list->get_default_user_options();
	%{$u} = %{$defaults};
453
454
	$u->{'email'} = $email;
	$u->{'gecos'} = $gecos;
salaun's avatar
salaun committed
455

456
	unless ($list->add_user($u)) {
salaun's avatar
salaun committed
457
458
459
460
461
462
463
464
465
466
	    printf STDERR "\nCould not add %s\n", $email;
	    next;
	}
	print STDERR '+';
	
	$total++;	
    }
    
    printf STDERR "Total imported subscribers: %d\n", $total;

salaun's avatar
salaun committed
467
    exit 0;
468
469
470
471
472
473
474
475
476
477
478
}elsif ($main::options{'md5_encode_password'}) {

    unless ($List::use_db) {
	&fatal_err("You don't have a database setup, can't lowercase email addresses");
    }
    
    my $total=&Upgrade::md5_encode_password();
    printf STDERR "Total password re-encoded using md5: %d\n", $total;
    
    exit 0;
    
salaun's avatar
salaun committed
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
}elsif ($main::options{'lowercase'}) {
    
    unless ($List::use_db) {
	&fatal_err("You don't have a database setup, can't lowercase email addresses");
    }

    print STDERR "Working on user_table...\n";
    my $total = &List::lowercase_field('user_table', 'email_user');

    print STDERR "Working on subscriber_table...\n";
    $total += &List::lowercase_field('subscriber_table', 'user_subscriber');

    unless (defined $total) {
	&fatal_err("Could not work on dabatase");
    }

    printf STDERR "Total lowercased rows: %d\n", $total;

497
498
499
500
501
502
503
504
505
506
507
    exit 0;
}elsif ($main::options{'close_list'}) {

    my ($listname, $robotname) = split /\@/, $main::options{'close_list'};
    my $list = new List ($listname, $robotname);

    unless (defined $list) {
	print STDERR "Incorrect list name $main::options{'close_list'}\n";
	exit 1;
    }

508
509
510
511
512
513
514
515
    if ($list->{'admin'}{'family_name'}) {
 	unless($list->set_status_family_closed('close_list',$list->{'name'})) {
 	    print STDERR "Could not close list $main::options{'close_list'}\n";
 	    exit 1;	
 	}
    } else {
	unless ($list->close()) {
	    print STDERR "Could not close list $main::options{'close_list'}\n";
serge.aumont's avatar
   
serge.aumont committed
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
	    exit 1;	
	}
    }

    printf STDOUT "List %s has been closed, aliases have been removed\n", $list->{'name'};
    
    exit 0;
}elsif ($main::options{'purge_list'}) {

    my ($listname, $robotname) = split /\@/, $main::options{'purge_list'};
    my $list = new List ($listname, $robotname);

    unless (defined $list) {
	print STDERR "Incorrect list name $main::options{'purge_list'}\n";
	exit 1;
    }

    if ($list->{'admin'}{'family_name'}) {
 	unless($list->set_status_family_closed('purge_list',$list->{'name'})) {
 	    print STDERR "Could not purge list $main::options{'purge_list'}\n";
 	    exit 1;	
 	}
    } else {
	unless ($list->purge()) {
	    print STDERR "Could not purge list $main::options{'close_list'}\n";
541
542
	    exit 1;	
	}
543
544
545
546
    }

    printf STDOUT "List %s has been closed, aliases have been removed\n", $list->{'name'};
    
547
548
549
    exit 0;
}elsif ($main::options{'create_list'}) {
    
550
    my $robot = $main::options{'robot'} || $Conf{'host'};
551
    
sympa-authors's avatar
sympa-authors committed
552
    unless ($main::options{'input_file'}) {
553
 	print STDERR "Error : missing 'input_file' parameter\n";
sympa-authors's avatar
sympa-authors committed
554
555
556
557
 	exit 1;
    }

    unless (open INFILE, $main::options{'input_file'}) {
558
	print STDERR "Unable to open $main::options{'input_file'}) file";
sympa-authors's avatar
sympa-authors committed
559
560
561
562
 	exit 1;	
    }
    
    my $config = new Config_XML(\*INFILE);
563
564
565
566
567
568
569
    unless (defined $config->createHash()) {
 	print STDERR "Error in representation data with these xml data\n";
 	exit 1;
    } 
    
    my $hash = $config->getHash();
    
sympa-authors's avatar
sympa-authors committed
570
571
    close INFILE;

572
    my $resul = &admin::create_list_old($hash->{'config'},$hash->{'type'},$robot,"command_line");
573
574
575
576
577
    unless (defined $resul) {
 	print STDERR "Could not create list with these xml data\n";
 	exit 1;
    }
    
578
    if (! defined($resul->{'aliases'}) || $resul->{'aliases'} == 1) {
579
580
581
582
583
584
585
586
 	printf STDOUT "List has been created \n";
 	exit 0;
    }else {
 	printf STDOUT "List has been created, required aliases :\n $resul->{'aliases'} \n";
 	exit 0;
    }
}elsif ($main::options{'instantiate_family'}) {
    
587
588
    my $robot = $main::options{'robot'} || $Conf{'host'};

589
590
    my $family_name;
    unless ($family_name = $main::options{'instantiate_family'}) {
591
 	print STDERR "Error : missing family parameter\n";
592
593
594
595
596
597
598
 	exit 1;
    }
    my $family;
    unless ($family = new Family($family_name,$robot)) {
 	print STDERR "The family $family_name does not exist, impossible instantiation\n";
 	exit 1;
    }
sympa-authors's avatar
sympa-authors committed
599
600

    unless ($main::options{'input_file'}) {
601
 	print STDERR "Error : missing input_file parameter\n";
sympa-authors's avatar
sympa-authors committed
602
603
604
 	exit 1;
    }

605
    unless (-r $main::options{'input_file'}) {
sympa-authors's avatar
typo    
sympa-authors committed
606
	print STDERR "Unable to read $main::options{'input_file'} file";
sympa-authors's avatar
sympa-authors committed
607
608
609
 	exit 1;	
    }

610
    unless ($family->instantiate($main::options{'input_file'}, $main::options{'close_unknown'})) {
611
612
613
 	print STDERR "\nImpossible family instantiation : action stopped \n";
 	exit 1;
    } 
sympa-authors's avatar
sympa-authors committed
614
        
615
616
    my %result;
    my $err = $family->get_instantiation_results(\%result);
sympa-authors's avatar
sympa-authors committed
617
    close INFILE;
618
619
620
621
622
623
624
625

    unless ($main::options{'quiet'}) {
        print STDOUT "@{$result{'info'}}";
        print STDOUT "@{$result{'warn'}}";
    }
    if ($err) {
        print STDERR "@{$result{'errors'}}";
    }
626
    
627
628
629
    exit 0;
}elsif ($main::options{'add_list'}) {
     
sympa-authors's avatar
sympa-authors committed
630
    my $robot = $main::options{'robot'} || $Conf{'host'};
631

632
633
    my $family_name;
    unless ($family_name = $main::options{'add_list'}) {
634
	print STDERR "Error : missing family parameter\n";
635
636
637
638
639
640
641
642
643
644
645
 	exit 1;
    }
    
    print STDOUT "\n************************************************************\n";
    
    my $family;
    unless ($family = new Family($family_name,$robot)) {
 	print STDERR "The family $family_name does not exist, impossible to add a list\n";
 	exit 1;
    }
    
sympa-authors's avatar
sympa-authors committed
646
    unless ($main::options{'input_file'}) {
647
 	print STDERR "Error : missing 'input_file' parameter\n";
sympa-authors's avatar
sympa-authors committed
648
649
650
651
 	exit 1;
    }

    unless (open INFILE, $main::options{'input_file'}) {
652
	print STDERR "\n Impossible to open input file  : $! \n";
sympa-authors's avatar
sympa-authors committed
653
654
655
 	exit 1;	
    }

656
    my $result;
sympa-authors's avatar
sympa-authors committed
657
    unless ($result = $family->add_list(\*INFILE)) {
658
659
660
661
662
663
664
 	print STDERR "\nImpossible to add a list to the family : action stopped \n";
 	exit 1;
    } 
    
    print STDOUT "\n************************************************************\n";
    
    unless (defined $result->{'ok'}) {
665
 	printf STDERR "\n%s\n", join ("\n", @{$result->{'string_info'}});
666
 	print STDERR "\n The action has been stopped because of error :\n";
667
 	printf STDERR "\n%s\n", join ("\n", @{$result->{'string_error'}});
668
669
670
 	exit 1;
    }
    
sympa-authors's avatar
sympa-authors committed
671
672
    close INFILE;

673
    print STDOUT "\n%s\n", join ("\n", @{$result->{'string_info'}});
674
    exit 0;
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
}elsif ($main::options{'sync_include'}) {

    my $list = new List ($main::options{'sync_include'});

    unless (defined $list) {
	print STDERR "Incorrect list name $main::options{'sync_include'}\n";
	exit 1;
    }

    unless (defined $list->sync_include()) {
	print STDERR "Failed to synchronize list members\n";
	exit 1;
    }

    printf "Members of list %s have been successfully update.\n", $list->get_list_address();
690
691
    exit 0;
## Migration from one version to another
692
}elsif ($main::options{'upgrade'}) {
693
694
    
    &do_log('notice', "Upgrade process...");
695

696
697
    $main::options{'from'} ||= &Upgrade::get_previous_version();
    $main::options{'to'} ||= $Version::Version;
698

699
700
701
702
703
    if ($main::options{'from'} eq $main::options{'to'}) {
	&do_log('err', "Current version : %s ; no upgrade is required.", $main::options{'to'});
	exit 0;
    }else {
	&do_log('notice', "Upgrading from %s to %s...", $main::options{'from'}, $main::options{'to'});
704
705
    }

706
707
    unless (&Upgrade::upgrade($main::options{'from'}, $main::options{'to'})) {
	&do_log('err',  "Migration from %s to %s failed", $main::options{'from'}, $main::options{'to'});
708
709
710
 	exit 1;
    }

711
712
713
    &do_log('notice', "Upgrade process finished.");    
    &Upgrade::update_version();

714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
    exit 0;

## Reload binary list config files
}elsif ($main::options{'reload_list_config'}) {

    if ($main::options{'list'}) {

	&do_log('notice', "Loading list $main::options{'list'}...");
	my $list = new List ($main::options{'list'}, '', {'reload_config' => 1});
	unless (defined $list) {
	    print STDERR "Error : incorrect list name '$main::options{'list'}'\n";
	    exit 1;
	}
    }else {
	&do_log('notice', "Loading ALL lists...");
	my $all_lists = &List::get_lists('*',{'reload_config' => 1});
    }

732
    exit 0;
733
734
735
736
737
}

##########################################
elsif ($main::options{'modify_list'}) {
    
738
739
    my $robot = $main::options{'robot'} || $Conf{'host'};

740
741
    my $family_name;
    unless ($family_name = $main::options{'modify_list'}) {
742
 	print STDERR "Error : missing family parameter\n";
743
744
745
746
747
748
749
750
751
752
753
 	exit 1;
    }
    
    print STDOUT "\n************************************************************\n";
    
    my $family;
    unless ($family = new Family($family_name,$robot)) {
 	print STDERR "The family $family_name does not exist, impossible to modify the list.\n";
 	exit 1;
    }
    
sympa-authors's avatar
sympa-authors committed
754
    unless ($main::options{'input_file'}) {
755
 	print STDERR "Error : missing input_file parameter\n";
sympa-authors's avatar
sympa-authors committed
756
757
758
759
 	exit 1;
    }

    unless (open INFILE, $main::options{'input_file'}) {
760
	print STDERR "Unable to open $main::options{'input_file'}) file";
sympa-authors's avatar
sympa-authors committed
761
762
763
 	exit 1;	
    }

764
    my $result;
sympa-authors's avatar
sympa-authors committed
765
    unless ($result = $family->modify_list(\*INFILE)) {
766
767
768
769
770
771
772
 	print STDERR "\nImpossible to modify the family list : action stopped. \n";
 	exit 1;
    } 
    
    print STDOUT "\n************************************************************\n";
    
    unless (defined $result->{'ok'}) {
773
 	printf STDERR "\n%s\n", join ("\n", @{$result->{'string_info'}});
774
 	print STDERR "\nThe action has been stopped because of error :\n";
775
 	printf STDERR "\n%s\n", join ("\n", @{$result->{'string_error'}});
776
777
 	exit 1;
    }
sympa-authors's avatar
sympa-authors committed
778
779

    close INFILE;
780
    
781
    printf STDOUT "\n%s\n", join ("\n", @{$result->{'string_info'}});
782
783
784
785
786
787
    exit 0;
}

##########################################
elsif ($main::options{'close_family'}) {
    
788
789
    my $robot = $main::options{'robot'} || $Conf{'host'};

790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
    my $family_name;
    unless ($family_name = $main::options{'close_family'}) {
 	print STDERR $usage_string;
 	exit 1;
    }
    my $family;
    unless ($family = new Family($family_name,$robot)) {
 	print STDERR "The family $family_name does not exist, impossible family closure\n";
 	exit 1;
    }
    
    my $string;
    unless ($string = $family->close()) {
 	print STDERR "\nImpossible family closure : action stopped \n";
 	exit 1;
    } 
    
    print STDOUT $string;
808
809
    exit 0;
}
810
 
811

812
813
814
815
816
817
## Do we have right access in the directory
if ($main::options{'keepcopy'}) {
    if (! -d $main::options{'keepcopy'}) {
	&do_log('notice', 'Cannot keep a copy of incoming messages : %s is not a directory', $main::options{'keepcopy'});
	delete $main::options{'keepcopy'};
    }elsif (! -w $main::options{'keepcopy'}) {
818
	&do_log('notice','Cannot keep a copy of incoming messages : no write access to %s', $main::options{'keepcopy'});
819
820
821
822
	delete $main::options{'keepcopy'};
    }
}

root's avatar
root committed
823
824
## Catch SIGTERM, in order to exit cleanly, whenever possible.
$SIG{'TERM'} = 'sigterm';
salaun's avatar
salaun committed
825
$SIG{'HUP'} = 'sighup';
826
$SIG{'PIPE'} = 'IGNORE'; ## Ignore SIGPIPE ; prevents sympa.pl from dying
root's avatar
root committed
827
828

my $index_queuedigest = 0; # verify the digest queue
829
my $index_cleanqueue = 0; 
root's avatar
root committed
830
831
my @qfile;

serge.aumont's avatar
   
serge.aumont committed
832
my $spool = $Conf{'queue'};
833
834
835
836
837
838
# if daemon is dedicated to message or automatic lists creation, change the current spool
if ($main::daemon_usage == DAEMON_MESSAGE) {
    $spool = $Conf{'queuedistribute'};
}elsif ($main::daemon_usage == DAEMON_CREATION) {
    $spool = $Conf{'queueautomatic'};
}
serge.aumont's avatar
   
serge.aumont committed
839

840
## This is the main loop : look for files in the directory, handles
root's avatar
root committed
841
## them, sleeps a while and continues the good job.
salaun's avatar
salaun committed
842
while (!$signal) {
root's avatar
root committed
843
844
845

    &Language::SetLang($Language::default_lang);

846
847
    &List::init_list_cache();

serge.aumont's avatar
   
serge.aumont committed
848
849
    if (!opendir(DIR, $spool)) {
	fatal_err("Can't open dir %s: %m", $spool); ## No return.
root's avatar
root committed
850
    }
851
    @qfile = sort tools::by_date grep (!/^\./,readdir(DIR));
root's avatar
root committed
852
853
    closedir(DIR);

854
    unless ($main::daemon_usage == DAEMON_COMMAND)  { # process digest only in distribution mode
serge.aumont's avatar
   
serge.aumont committed
855
856
857
858
859
860
	## Scan queuedigest
	if ($index_queuedigest++ >=$digestsleep){
	    $index_queuedigest=0;
	    &SendDigest();
	}
    }
861
    unless ($main::daemon_usage == DAEMON_MESSAGE) { # process expire and bads only in command mode 
serge.aumont's avatar
   
serge.aumont committed
862
863
864
865
    
	## Clean queue (bad)
	if ($index_cleanqueue++ >= 100){
	    $index_cleanqueue=0;
866
867
868
	    if (-e "$spool/bad") {
		&tools::CleanSpool("$spool/bad", $Conf{'clean_delay_queue'});
	    }
869
	    &tools::CleanSpool($Conf{'queuemod'}, $Conf{'clean_delay_queuemod'});
870
871
872
873
874
875
	    if (-e $Conf{'queueoutgoing'}.'/bad') {
		&tools::CleanSpool($Conf{'queueoutgoing'}.'/bad', $Conf{'clean_delay_queueoutgoing'});
	    }
	    if (-e $Conf{'queuebounce'}.'/bad') {
		&tools::CleanSpool($Conf{'queuebounce'}.'/bad', $Conf{'clean_delay_queuebounce'});
	    }
876
877
878
879
880
	    &tools::CleanSpool($Conf{'queueauth'}, $Conf{'clean_delay_queueauth'});
	    &tools::CleanSpool($Conf{'queuetopic'}, $Conf{'clean_delay_queuetopic'});
	    &tools::CleanSpool($Conf{'tmpdir'}, $Conf{'clean_delay_tmpdir'});
	    &tools::CleanSpool($Conf{'queuesubscribe'}, $Conf{'clean_delay_queuesubscribe'});
	    &tools::CleanSpool($Conf{'queueautomatic'}, $Conf{'clean_delay_queueautomatic'});
serge.aumont's avatar
   
serge.aumont committed
881
	}
882
    }
root's avatar
root committed
883
884
    my $filename;
    my $listname;
salaun's avatar
salaun committed
885
886
    my $robot;

root's avatar
root committed
887
    my $highest_priority = 'z'; ## lowest priority
888
    my $t_spool = $spool; ## in single mode we may have to supervise automatic spool
root's avatar
root committed
889
890
891
892
893
894
895
    
    ## Scans files in queue
    ## Search file with highest priority
    foreach my $t_filename (sort @qfile) {
	my $priority;
	my $type;
	my $list;
896
	my ($t_listname, $t_robot);
897
	
root's avatar
root committed
898
899
900
901
902
	# trying to fix a bug (perl bug ??) of solaris version
	($*, $/) = @parser_param;

	## test ever if it is an old bad file
	if ($t_filename =~ /^BAD\-/i){
903
904
 	    if ((stat "$t_spool/$t_filename")[9] < (time - &Conf::get_robot_conf($robot, 'clean_delay_queue')*86400) ){
 		unlink ("$t_spool/$t_filename") ;
905
		&do_log('notice',"Deleting bad message %s because too old", $t_filename);
root's avatar
root committed
906
907
908
909
910
911
	    };
	    next;
	}

	## z and Z are a null priority, so file stay in queue and are processed
	## only if renamed by administrator
912
	next unless ($t_filename =~ /^(\S+)\.\d+\.\w+$/);
root's avatar
root committed
913
914
915
916

	## Don't process temporary files created by queue (T.xxx)
	next if ($t_filename =~ /^T\./);

917
	($t_listname, $t_robot) = split(/\@/,$1);
salaun's avatar
salaun committed
918
	
919
920
921
	$t_listname = lc($t_listname);
	if ($t_robot) {
	    $t_robot=lc($t_robot);
salaun's avatar
salaun committed
922
	}else{
923
	    $t_robot = lc(&Conf::get_robot_conf($robot, 'host'));
salaun's avatar
salaun committed
924
925
	}

926
927
928
	my $list_check_regexp = &Conf::get_robot_conf($robot,'list_check_regexp');

	if ($t_listname =~ /^(\S+)-($list_check_regexp)$/) {
929
	    ($t_listname, $type) = ($1, $2);
root's avatar
root committed
930
931
	}

salaun's avatar
salaun committed
932
	# (sa) le terme "(\@$Conf{'host'})?" est inutile
933
	#unless ($t_listname =~ /^(sympa|$Conf{'listmaster_email'}|$Conf{'email'})(\@$Conf{'host'})?$/i) {
934
935
	#    $list = new List ($t_listname);
	#}
936
937
938

	my $email = &Conf::get_robot_conf($robot, 'email');	

939
	if ($t_listname eq $Conf{'listmaster_email'}) {
root's avatar
root committed
940
941
942
	    ## highest priority
	    $priority = 0;
	}elsif ($type eq 'request') {
943
	    $priority = &Conf::get_robot_conf($robot, 'request_priority');
root's avatar
root committed
944
	}elsif ($type eq 'owner') {
945
946
947
	    $priority = &Conf::get_robot_conf($robot, 'owner_priority');
	}elsif ($t_listname =~ /^(sympa|$email)(\@$Conf{'host'})?$/i) {	
	    $priority = &Conf::get_robot_conf($robot,'sympa_priority');
root's avatar
root committed
948
	}else {
949
	    my $list =  new List ($t_listname, $t_robot, {'just_try' => 1});
950
951
952
	    if ($list) {
		$priority = $list->{'admin'}{'priority'};
	    }else {
953
		$priority = &Conf::get_robot_conf($robot, 'default_list_priority');
954
	    }
root's avatar
root committed
955
956
957
958
959
960
961
962
	}
	
	if (ord($priority) < ord($highest_priority)) {
	    $highest_priority = $priority;
	    $filename = $t_filename;
	}
    } ## END of spool lookup

963
    &mail::reaper;
root's avatar
root committed
964
965

    unless ($filename) {
966
	sleep(&Conf::get_robot_conf($robot, 'sleep'));
root's avatar
root committed
967
968
969
	next;
    }

970
    &do_log('debug', "Processing %s/%s with priority %s", $t_spool,$filename, $highest_priority) ;
aumont's avatar
aumont committed
971
972
    
    if ($main::options{'mail'} != 1) {
973
	$main::options{'mail'} = $robot if (&Conf::get_robot_conf($robot, 'log_smtp'));
aumont's avatar
aumont committed
974
    }
975
976
977
978

    ## Set NLS default lang for current message
    $Language::default_lang = $main::options{'lang'} || &Conf::get_robot_conf($robot, 'lang');

979
    my $status = &DoFile("$t_spool/$filename");
root's avatar
root committed
980
981
    
    if (defined($status)) {
982
	&do_log('debug', "Finished %s", "$t_spool/$filename") ;
983
984

	if ($main::options{'keepcopy'}) {
985
986
	    unless (&File::Copy::copy($t_spool.'/'.$filename, $main::options{'keepcopy'}.'/'.$filename) ) {
 		&do_log('notice', 'Could not rename %s to %s: %s', "$t_spool/$filename", $main::options{'keepcopy'}."/$filename", $!);
987
988
	    }
	}
989
	unlink("$t_spool/$filename");
root's avatar
root committed
990
    }else {
991
	my $bad_dir = "$t_spool/bad";
sympa-authors's avatar
sympa-authors committed
992
	
993
	if (-d $bad_dir) {
994
	    unless (rename("$t_spool/$filename", "$bad_dir/$filename")){
995
		&fatal_err("Exiting, unable to rename bad file $filename to $bad_dir/$filename (check directory permission)");
996
997
998
999
	    }
	    do_log('notice', "Moving bad file %s to bad/", $filename);
	}else{
	    do_log('notice', "Missing directory '%s'", $bad_dir);
1000
	    unless (rename("$t_spool/$filename", "$t_spool/BAD-$filename")) {
1001
		&fatal_err("Exiting, unable to rename bad file $filename to BAD-$filename");
1002
	    }
1003
	    do_log('notice', "Renaming bad file %s to BAD-%s", $filename, $filename);
1004
	}	
root's avatar
root committed
1005
1006
1007
1008
1009
    }

} ## END of infinite loop

## Dump of User files in DB