14 use Time
::HiRes qw
(gettimeofday
);
29 my $msg = shift || '';
37 return $dbh->last_insert_id(
38 undef, undef, undef, undef, { sequence
=> $seq});
42 my ($filename, $lasttime) = @_;
44 my $st = stat($filename);
46 return 0 if !defined($st);
48 return ($lasttime >= $st->ctime);
51 sub extract_filename
{
54 if (my $value = $head->recommended_filename()) {
56 if (my $decvalue = MIME
::Words
::decode_mimewords
($value)) {
57 $decvalue =~ s/\0/ /g;
58 $decvalue = PVE
::Tools
::trim
($decvalue);
67 my ($entity, $add_id, $id) = @_;
71 foreach my $tag (grep {/^x-proxmox-tmp/i} $entity->head->tags) {
72 $entity->head->delete ($tag);
75 $entity->head->replace('X-Proxmox-tmp-AID', $id) if $add_id;
77 foreach my $part ($entity->parts) {
78 $id = remove_marks
($part, $add_id, $id + 1);
89 foreach my $k (keys %$dh) {
92 $body =~ s/__\Q${k}\E__/$v/gs;
100 my ($entity, $sender, $targets, $xforward, $me, $nodsn) = @_;
108 my $smtp = Net
::SMTP-
>new('127.0.0.1', Port
=> 10025, Hello
=> $me) ||
109 die "unable to connect to localhost at port 10025";
111 if (defined($xforward)) {
114 foreach my $attr (keys %{$xforward}) {
115 $xfwd .= " $attr=$xforward->{$attr}";
118 if ($xfwd && $smtp->command("XFORWARD", $xfwd)->response() != CMD_OK
) {
119 syslog
('err', "xforward error - got: %s %s", $smtp->code, scalar($smtp->message));
123 if (!$smtp->mail($sender)) {
124 syslog
('err', "smtp error - got: %s %s", $smtp->code, scalar ($smtp->message));
125 die "smtp from: ERROR";
128 my $dsnopts = $nodsn ?
{Notify
=> ['NEVER']} : {};
130 if (!$smtp->to (@$targets, $dsnopts)) {
131 syslog
('err', "smtp error - got: %s %s", $smtp->code, scalar($smtp->message));
132 die "smtp to: ERROR";
136 #$entity->sync_headers ();
139 my $out = PMG
::SMTPPrinter-
>new($smtp);
140 $entity->print($out);
142 # make sure we always have a newline at the end of the mail
143 # else dataend() fails
144 $smtp->datasend("\n");
146 if ($smtp->dataend()) {
147 my @msgs = $smtp->message;
148 $resmess = $msgs[$#msgs];
149 ($resid) = $resmess =~ m/Ok: queued as ([0-9A-Z]+)/;
150 $rescode = $smtp->code;
152 die sprintf("unexpected SMTP result - got: %s %s : WARNING", $smtp->code, $resmess);
155 my @msgs = $smtp->message;
156 $resmess = $msgs[$#msgs];
157 $rescode = $smtp->code;
158 die sprintf("sending data failed - got: %s %s : ERROR", $smtp->code, $resmess);
163 $smtp->quit if $smtp;
166 syslog
('err', $err);
169 return wantarray ?
($resid, $rescode, $resmess) : $resid;
172 sub analyze_virus_clam
{
173 my ($queue, $dname, $pmg_cfg) = @_;
178 my $clamdscan_opts = "--stdout";
180 my ($csec, $usec) = gettimeofday
();
186 $previous_alarm = alarm($timeout);
189 die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " .
190 "virus analyze (clamav) failed: ERROR";
193 open(CMD
, "/usr/bin/clamdscan $clamdscan_opts '$dname'|") ||
194 die "$queue->{logid}: can't exec clamdscan: $! : ERROR";
199 while (defined(my $line = <CMD
>)) {
200 if ($line =~ m/^$dname.*:\s+([^ :]*)\s+FOUND$/) {
201 # we just use the first detected virus name
202 $vinfo = $1 if !$vinfo;
203 } elsif ($line =~ m/^Infected files:\s(\d*)$/i) {
212 alarm(0); # avoid race conditions
214 if (!defined($ifiles)) {
215 die "$queue->{logid}: got undefined output from " .
216 "virus detector: $response : ERROR";
220 syslog
('info', "$queue->{logid}: virus detected: $vinfo (clamav)");
225 alarm($previous_alarm);
227 my ($csec_end, $usec_end) = gettimeofday
();
228 $queue->{ptime_clam
} =
229 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
232 syslog
('err', $err);
234 $queue->{errors
} = 1;
237 $queue->{vinfo_clam
} = $vinfo;
239 return $vinfo ?
"$vinfo (clamav)" : undef;
243 my ($queue, $filename, $pmg_cfg, $testmode) = @_;
245 # TODO: support other virus scanners?
247 # always scan with clamav
248 return analyze_virus_clam
($queue, $filename, $pmg_cfg);
251 sub magic_mime_type_for_file
{
254 # we do not use get_mime_type_for_file, because that considers
255 # filename extensions - we only want magic type detection
257 my $bufsize = Xdgmime
::xdg_mime_get_max_buffer_extents
();
258 die "got strange value for max_buffer_extents" if $bufsize > 4096*10;
260 my $ct = "application/octet-stream";
262 my $fh = IO
::File-
>new("<$filename") ||
263 die "unable to open file '$filename' - $!";
266 if (($len = $fh->read($buf, $bufsize)) > 0) {
267 $ct = xdg_mime_get_mime_type_for_data
($buf, $len);
271 die "unable to read file '$filename' - $!" if ($len < 0);
279 if (my $path = $entity->{PMX_decoded_path
}) {
281 # set a reasonable default if magic does not give a result
282 $entity->{PMX_magic_ct
} = $entity->head->mime_attr('content-type');
284 if (my $ct = magic_mime_type_for_file
($path)) {
285 if ($ct ne 'application/octet-stream' || !$entity->{PMX_magic_ct
}) {
286 $entity->{PMX_magic_ct
} = $ct;
290 my $filename = $entity->head->recommended_filename;
291 $filename = basename
($path) if !defined($filename) || $filename eq '';
293 if (my $ct = xdg_mime_get_mime_type_from_file_name
($filename)) {
294 $entity->{PMX_glob_ct
} = $ct;
298 foreach my $part ($entity->parts) {
299 add_ct_marks
($part);
303 # x509 certificate utils
305 my $proxmox_tls_cert_fn = "/etc/proxmox/proxmox-tls.pem";
307 sub gen_proxmox_tls_cert
{
308 my ($force, $company, $cn) = @_;
310 return if !$force && -f
$proxmox_tls_cert_fn;
312 my $sslconf = <<__EOD__;
313 RANDFILE = /root/.rnd
318 distinguished_name = req_distinguished_name
319 req_extensions = v3_req
321 string_mask = nombstr
323 [ req_distinguished_name ]
324 organizationalUnitName = Proxmox Mail Gateway
325 organizationName = $company
329 basicConstraints = CA:FALSE
331 keyUsage = nonRepudiation, digitalSignature, keyEncipherment
334 my $cfgfn = "/tmp/proxmoxtlsconf-$$.tmp";
335 my $fh = IO
::File-
>new ($cfgfn, "w");
340 PVE
::Tools
::run_command
(['openssl', 'req', '-batch', '-x509', '-new', '-sha256',
341 '-config', $cfgfn, '-days', 3650, '-nodes',
342 '-out', $proxmox_tls_cert_fn,
343 '-keyout', $proxmox_tls_cert_fn]);
347 unlink $proxmox_tls_cert_fn;
349 die "unable to generate proxmox certificate request:\n$err";
355 sub find_local_network_for_ip
{
358 my $testip = Net
::IP-
>new($ip);
360 my $isv6 = $testip->version == 6;
362 PVE
::ProcFSTools
::read_proc_net_ipv6_route
() :
363 PVE
::ProcFSTools
::read_proc_net_route
();
365 foreach my $entry (@$routes) {
368 $mask = $entry->{prefix
};
369 next if !$mask; # skip the default route...
371 $mask = $PVE::Network
::ipv4_mask_hash_localnet-
>{$entry->{mask
}};
372 next if !defined($mask);
374 my $cidr = "$entry->{dest}/$mask";
375 my $testnet = Net
::IP-
>new($cidr);
376 my $overlap = $testnet->overlaps($testip);
377 if ($overlap == $Net::IP
::IP_B_IN_A_OVERLAP
||
378 $overlap == $Net::IP
::IP_IDENTICAL
)
384 die "unable to detect local network for ip '$ip'\n";
388 my ($service, $cmd) = @_;
390 die "unknown service command '$cmd'\n"
391 if $cmd !~ m/^(start|stop|restart|reload)$/;
393 if ($service eq 'pmgdaemon' || $service eq 'pmgproxy') {
394 if ($cmd eq 'restart') {
397 die "invalid service cmd '$service $cmd': ERROR";
401 $service = 'postfix@-' if $service eq 'postfix';
402 PVE
::Tools
::run_command
(['systemctl', $cmd, $service]);
405 # this is also used to get the IP of the local node
407 my ($nodename, $noerr) = @_;
409 my ($family, $packed_ip);
412 my @res = PVE
::Tools
::getaddrinfo_all
($nodename);
413 $family = $res[0]->{family
};
414 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
418 die "hostname lookup failed:\n$@" if !$noerr;
422 my $ip = Socket
::inet_ntop
($family, $packed_ip);
423 if ($ip =~ m/^127\.|^::1$/) {
424 die "hostname lookup failed - got local IP address ($nodename = $ip)\n" if !$noerr;
428 return wantarray ?
($ip, $family) : $ip;