File: Lock.pm

package info (click to toggle)
mailscanner 4.79.11-2.2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 5,820 kB
  • ctags: 1,309
  • sloc: perl: 25,655; sh: 2,666; xml: 624; makefile: 242
file content (419 lines) | stat: -rw-r--r-- 12,824 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#
#   MailScanner - SMTP E-Mail Virus Scanner
#   Copyright (C) 2002  Julian Field
#
#   $Id: Lock.pm 4351 2008-03-17 21:06:55Z sysjkf $
#
#   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
#
#   The author, Julian Field, can be contacted by email at
#      Jules@JulianField.net
#   or by paper mail at
#      Julian Field
#      Dept of Electronics & Computer Science
#      University of Southampton
#      Southampton
#      SO17 1BJ
#      United Kingdom
#

# Provide functions to deal with opening + locking spool files

package MailScanner::Lock;

use strict;
use Fcntl qw(:DEFAULT :flock);
use POSIX qw(:unistd_h :errno_h);
#use MailScanner::Log;

use vars qw($FLOCK_STRUCT);

my $have_module;
my $LockType;

sub ReportLockType {
  return $LockType;
}

# Run-time initialisation

sub initialise {

  eval {
      require MailScanner::Fcntl;
      import MailScanner::Fcntl (@MailScanner::Fcntl::EXPORT,
                                 @MailScanner::Fcntl::EXPORT_OK);
      1;
  };

  $have_module = ($@ eq ""?1:0);

  # Determine locktype to use
  $LockType = (MailScanner::Config::Value('locktype'))?
    MailScanner::Config::Value('locktype') : $global::MS->{mta}->{LockType};

  #print STDERR "Debug = " . MailScanner::Config::Value('debug') . "\n";
  #print STDERR "Config Value = " . MailScanner::Config::Value('locktype') . "\n";
  #print STDERR "Global = " . $global::MS->{mta}->{LockType} . "\n";
  #print STDERR "Lock Type = $LockType\n";

  MailScanner::Log::DebugLog("lock.pl sees Config  LockType =  " .
                             $LockType);
  #MailScanner::Log::DebugLog("lock.pl sees MTA::LockType =  ".$MTA::LockType);
  MailScanner::Log::DebugLog("lock.pl sees have_module =  ".$have_module);

  # module has bugs
  $LockType =~ /posix/ and $have_module and $LockType = "module";

  MailScanner::Log::InfoLog("Using locktype = " . $LockType);


  # Note that in IEEE Std 1003.1-2001,
  # "The interaction between fcntl() and lockf() locks is unspecified."
  #
  # (bother)
  #
  # And we shouldn't really call these "posix" locks, as although they are
  # specified in POSIX, there are two possible types, which may or may not
  # be the same. DOH!

  # Determine correct struct_flock to use at include time

  # HORRIBLY HARDWIRED
  # would like to "use File::lockf" but that would make
  # installation harder. And lockf isn't guaranteed to
  # do the same thing as fcntl :(
  #
  # CPAN File::Lock also appears to be broken (doesn't build, then when
  # built, doesn't pass it's own tests - including segfaulting)
  #
  # So I'll do it myself.

  if ($LockType =~ /posix/i) {
    
    for ($^O) {
	
	# $^O returns:
	#  Linux: "linux"
	#  OpenBSD: "openbsd"
	#  Solaris: "solaris"
	#  SunOS4: "sunos"
	#  AIX: "aix"
	#  IRIX: "irix"
	#

	if (/bsd/) {

	    #MailScanner::Log::InfoLog("Creating hardcoded struct_flock subroutine for $^O (BSD-type)");

	    # from "man fcntl" and /usr/include/sys/fcntl.h on OBSD 2.7:
	    #     struct flock {
	    #             off_t   l_start;        /* starting offset */
	    #             off_t   l_len;          /* len = 0 means until end of file */
	    #             pid_t   l_pid;          /* lock owner */
	    #             short   l_type;         /* lock type: read/write, etc. */
	    #             short   l_whence;       /* type of l_start */
	    #     };
	    #
	    # FreeBSD exim.tulsaconnect.com 4.5-RELEASE FreeBSD 4.5-RELEASE #0: Sun May
	    # 19 23:53:40 CDT 2002
	    #
	    # from /usr/include/sys/fcntl.h:
	    #
	    # /*
	    #  * Advisory file segment locking data type -
	    #  * information passed to system by user
	    #  */
	    # struct flock {
	    #         off_t   l_start;        /* starting offset */
	    #         off_t   l_len;          /* len = 0 means until end of file */
	    #         pid_t   l_pid;          /* lock owner */
	    #         short   l_type;         /* lock type: read/write, etc. */
	    #         short   l_whence;       /* type of l_start */
	    # };
	    #
	    # FreeBSD off_t is typedef'd to _BSD_OFF_T_ which is in turn __int64_t
	    #

	    eval <<'__EOD';
	    
	    # XXX: should be Q not LL but
	    # "Quads are available only if your system supports 64-bit
	    # integer values _and_ if Perl has been compiled to support those.
	    # Causes a fatal error otherwise."
	    #
	    $FLOCK_STRUCT = 'LL LL L l s';
	    
	    sub struct_flock {
		my ($xxstart, $start, $xxlen, $len, $pid, $type, $whence);
		if (wantarray) {
		    ($xxstart, $start, $xxlen, $len, $pid, $type, $whence) =
		      unpack($FLOCK_STRUCT, $_[0]);
		    return ($type, $whence, $start, $len, $pid);
		} else {
		    ($type, $whence, $start, $len, $pid) = @_;
		    ($xxstart, $xxlen) = (0,0);
		    return pack($FLOCK_STRUCT, $xxstart, $start, $xxlen, $len, $pid, $type, $whence);
		}
	    }
	    
__EOD
	    if ($@ ne "") {
		MailScanner::Log::DieLog("Unable to create struct_flock subroutine: $@");
	    }
	    next;
	}
	
        if ($_ eq 'linux') {

	    #MailScanner::Log::InfoLog("Creating hardcoded struct_flock subroutine for $^O (Linux-type)");

	    # from linux 2.2 /usr/include/asm/fcntl.h:
	    #	struct flock {
	    #        short l_type;
	    #        short l_whence;
	    #        off_t l_start;
	    #        off_t l_len;
	    #        pid_t l_pid;
	    #	};
	    #
	    # size of off_t appears to depend on whether we've got large file support etc. ugh.
	    #
	    # was previously using ssx32 to pack and sslls to unpack
	    #
	    
	    eval <<'__EOD';

	    $FLOCK_STRUCT = 's s LL LL I';

	    sub struct_flock {
		my ($start, $len, $pid, $type, $whence);
		if (wantarray) {
                    # Interpreting a returned struct
		    ($type, $whence, $start, $len, $pid) =
		      unpack($FLOCK_STRUCT, $_[0]);
		    return ($type, $whence, $start, $len, $pid);
		} else {
                    # Building a struct
		    ($type, $whence, $start, $len, $pid) = @_;
		    return pack($FLOCK_STRUCT, $type, $whence, $start, $len, $pid);
		}
	    }

__EOD
	    if ($@ ne "") {
		MailScanner::Log::DieLog("Unable to create struct_flock subroutine: $@");
	    }
	    next;
	}

        if (/solaris|irix|aix/) {

	    #MailScanner::Log::InfoLog("Creating hardcoded struct_flock subroutine for $^O (misc-type)");

	    # from solaris 2.7 /usr/include/sys/fcntl.h:
	    #	/* regular version, for both small and large file compilation environment */
	    #	typedef struct flock {
	    #		short   l_type;
	    #		short   l_whence;
	    #		off_t   l_start;
	    #		off_t   l_len;          /* len == 0 means until end of file */
	    #		int     l_sysid;
	    #		pid_t   l_pid;
	    #		long    l_pad[4];               /* reserve area */
	    #	} flock_t;
	    #
	    # and:
	    #	/* transitional large file interface version */
	    #
	    #	#if     defined(_LARGEFILE64_SOURCE)
	    #
	    #	typedef struct flock64 {
	    #		short   l_type;
	    #		short   l_whence;
	    #		off64_t l_start;
	    #		off64_t l_len;          /* len == 0 means until end of file */
	    #		int     l_sysid;
	    #		pid_t   l_pid;
	    #		long    l_pad[4];               /* reserve area */
	    #	} flock64_t;
	    #
	    # and:
	    #	/* SVr3 flock type; needed for rfs across the wire compatibility */
	    #	typedef struct o_flock {
	    #		int16_t l_type;
	    #		int16_t l_whence;
	    #		int32_t l_start;
	    #		int32_t l_len;          /* len == 0 means until end of file */
	    #		int16_t l_sysid;
	    #		int16_t l_pid;
	    #	} o_flock_t;
	    #
	    # so even thought that one's not used in solaris any more, I guess there'll
	    # be systems "out there" that use it.
	    #
	    #
	    # From IRIX 5.3 man pages:
	    # The structure flock describes a file lock.  It includes the following
	    # members:
	    #
	    #  short   l_type;     /* Type of lock */
	    #  short   l_whence;   /* Flag for starting offset */
	    #  off_t   l_start;    /* Relative offset in bytes */
	    #  off_t   l_len;      /* Size; if 0 then until EOF */
	    #  long    l_sysid;    /* Returned with F_GETLK */
	    #  pid_t   l_pid;      /* Returned with F_GETLK */
	    #
	    #
	    # The structure flock64 describes a file lock for use on large files.  It
	    # includes the following members:
	    #
	    #  short   l_type;     /* Type of lock */
	    #  short   l_whence;   /* Flag for starting offset */
	    #  off64_t l_start;    /* Relative offset in bytes */
	    #  off64_t l_len;      /* Size; if 0 then until EOF */
	    #  long    l_sysid;    /* Returned with F_GETLK */
	    #  pid_t   l_pid;      /* Returned with F_GETLK */
	    #
	    # Apparently the 64-bit version is used with a different fcntl command
	    # (F_SETLK64 as opposed to F_SETLK).
	    #
	    #
	    # It seems that under AIX, a struct flock is:
	    # l_type, l_whence, l_start, l_len, l_sysid, l_pid, l_vfs
	    # Again, things vary depending on whether large file support is being
	    # used.
	    #

	    eval <<'__EOD';

	    # TEST THIS!
	    $FLOCK_STRUCT = 's s L L I I'; # ignore solaris' pad on the end

	    sub struct_flock {
		my ($type, $whence, $start, $len, $sysid, $pid);
		if (wantarray) {
		    ($type, $whence, $start, $len, $sysid, $pid) =
		      unpack($FLOCK_STRUCT, $_[0]);
		    return ($type, $whence, $start, $len, $pid);
		} else {
		    ($type, $whence, $start, $len, $pid) = @_;
		    $sysid = 0;
		    return pack($FLOCK_STRUCT, $type, $whence, $start, $len, $sysid, $pid);
		}
	    }

__EOD
	    if ($@ ne "") {
		MailScanner::Log::DieLog("Unable to create struct_flock subroutine: $@");
	    }
	    next;
	}
	
        MailScanner::Log::DieLog("1\n2\n3\n4\n5\nDon't know how to do fcntl locking on '$^O'\nPlease contact mailscanner authors.5\n4\n3\n2\n1");

    }
  }
}


# Open and lock a file.
#
# Pass in a filehandle, a filespec (including ">", "<", or
# whatever on the front), and (optionally) the type of lock
# you want - "r" or "s" for shared/read lock, or pretty much
# anything else (but "w" or "x" really) for exclusive/write
# lock.
#
# Lock type used (flock or fcntl/lockf/posix) depends on
# config. If you're using posix locks, then don't try asking
# for a write-lock on a file opened for reading - it'll fail
# with EBADF (Bad file descriptor).
#
# If $quiet is true, then don't print any warning.
#
sub openlock {
    my ($fh, $fn, $rw, $quiet) = @_;
    
    my ($struct_flock);

    defined $rw or $rw = ((substr($fn,0,1) eq '>')?"w":"r");
    $rw =~ /^[rs]/i or $rw = 'w';

    # Set umask every time as SpamAssassin might have reset it
    #umask 0077; # Now cleared up after SpamAssassin runs

    unless (open($fh, $fn)) {
	MailScanner::Log::NoticeLog("Could not open file $fn: %s", $!)
          unless $quiet;
	return 0;
    }

    if ($LockType =~ /module/i) {
	#MailScanner::Log::DebugLog("Using module to lock $fn");
	MailScanner::Fcntl::setlk($fh, ($rw eq 'w' ? F_WRLCK : F_RDLCK)) == 0 and return 1;
    }
    elsif ($LockType =~ /posix/i) {
        # Added 3 zeroes for 'start, length, + pid',
        # otherwise pack was being called with undefined values -- nwp
	#MailScanner::Log::DebugLog("Using fcntl() to lock $fn");
	$struct_flock =  struct_flock(($rw eq 'w' ? F_WRLCK : F_RDLCK),0,0,0,0);
	fcntl($fh, F_SETLK, $struct_flock) and return 1;
    }
    elsif ($LockType =~ /flock/i) {
	#MailScanner::Log::DebugLog("Using flock() to lock $fn");
	flock($fh, ($rw eq 'w' ? LOCK_EX : LOCK_SH) + LOCK_NB) and return 1;
    }
    else {
	MailScanner::Log::DebugLog("Not locking spool file $fn");
	return 1;
    }

    close ($fh);

    if (($! == POSIX::EAGAIN) || ($! == POSIX::EACCES)) {
	MailScanner::Log::DebugLog("Failed to lock $fn: %s", $!)
          unless $quiet;
    }
    else {
	MailScanner::Log::NoticeLog("Failed to lock $fn with unexpected error: %s", $!);
    }

    return 0;
}


sub unlockclose {
    my ($fh) = @_;

    if ($LockType =~ /module/i) {
	MailScanner::Fcntl::setlk($fh, F_UNLCK);
    }
    elsif ($LockType =~ /posix/i) {
	fcntl($fh, F_SETLK, struct_flock(F_UNLCK,0,0,0,0));
    }
    elsif ($LockType =~ /flock/i) {
	flock($fh, LOCK_UN);
    }
# else {
#   default - do nothing, as we didn't lock it in the first place
# }

    close ($fh);
    return 1;
}


1;