summaryrefslogtreecommitdiff
path: root/Echolot/Commands.pm
blob: 86ea89c8e5ded3fb055896c2c2c27d083f6142b8 (plain)
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
package Echolot::Commands;

# (c) 2002 Peter Palfrader <peter@palfrader.org>
# $Id: Commands.pm,v 1.3 2002/07/02 17:03:13 weasel Exp $
#

=pod

=head1 Name

Echolot::Commands - manage commands like add key, set ttl etc.

=head1 DESCRIPTION

This package provides functions for sending out and receiving pings.

=cut

use strict;
use warnings;
use Carp qw{cluck};
use Fcntl ':flock'; # import LOCK_* constants
use Fcntl ':seek'; # import LOCK_* constants
use English;

sub addCommand($) {
	my ($command) = @_;

	my $filename = Echolot::Config::get()->{'commands_file'};
	open(FH, ">>$filename" ) or
		cluck("Cannot open $filename for appending $!"),
		return 0;
	flock(FH, LOCK_EX) or
		cluck("Cannot get exclusive lock on $filename: $!"),
		return 0;
	
	print FH $command,"\n";
	
	flock(FH, LOCK_UN) or
		cluck("Cannot unlock $filename: $!");
	close(FH) or
		cluck("Cannot close $filename: $!");
};

sub processCommands($) {
	my $filename = Echolot::Config::get()->{'commands_file'};

	(-e $filename) or
		return 1;
	my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks)= stat $filename;
	($size > 0) or
		return 1;
	
	open(FH, "+<$filename" ) or
		cluck("Cannot open $filename for reading: $!"),
		return 0;
	flock(FH, LOCK_EX) or
		cluck("Cannot get exclusive lock on $filename: $!"),
		return 0;
	

	while (<FH>) {
		chomp;
		my ($command, @args) = split;

		if ($command eq 'add') {
			Echolot::Globals::get()->{'storage'}->add_address(@args);
		} elsif ($command eq 'set') {
			Echolot::Globals::get()->{'storage'}->set_stuff(@args);
		} else {
			warn("Unkown command: $_\n");
		};
	};

	seek(FH, 0, SEEK_SET) or
		cluck("Cannot seek to start $filename $!"),
		return 0;
	truncate(FH, 0) or
		cluck("Cannot truncate $filename to zero length: $!"),
		return 0;
	flock(FH, LOCK_UN) or
		cluck("Cannot unlock $filename: $!");
	close(FH) or
		cluck("Cannot close $filename: $!");
};

1;
# vim: set ts=4 shiftwidth=4: