1 package FS::part_export::sqlradius;
3 use vars qw(@ISA %info %options $notes1 $notes2);
5 use FS::Record qw( dbh );
8 @ISA = qw(FS::part_export);
10 tie %options, 'Tie::IxHash',
11 'datasrc' => { label=>'DBI data source ' },
12 'username' => { label=>'Database username' },
13 'password' => { label=>'Database password' },
14 'ignore_accounting' => {
16 label => 'Ignore accounting records from this database'
20 label => 'Hide IP address information on session reports',
24 label => 'Hide download/upload information on session reports',
26 'show_called_station' => {
28 label => 'Show the Called-Station-ID on session reports',
33 Real-time export of radcheck, radreply and usergroup tables to any SQL database
34 for <a href="http://www.freeradius.org/">FreeRADIUS</a>,
35 <a href="http://radius.innercite.com/">ICRADIUS</a>
36 or <a href="http://www.open.com.au/radiator/">Radiator</a>.
40 An existing RADIUS database will be updated in realtime, but you can use
41 <a href="../docs/man/bin/freeside-sqlradius-reset">freeside-sqlradius-reset</a>
42 to delete the entire RADIUS database and repopulate the tables from the
43 Freeside database. See the
44 <a href="http://search.cpan.org/dist/DBI/DBI.pm#connect">DBI documentation</a>
46 <a href="http://search.cpan.org/search?mode=module&query=DBD%3A%3A">documentation for your DBD</a>
47 for the exact syntax of a DBI data source.
49 <li>Using FreeRADIUS 0.9.0 with the PostgreSQL backend, the db_postgresql.sql schema and postgresql.conf queries contain incompatible changes. This is fixed in 0.9.1. Only new installs with 0.9.0 and PostgreSQL are affected - upgrades and other database backends and versions are unaffected.
50 <li>Using ICRADIUS, add a dummy "op" column to your database:
52 ALTER TABLE radcheck ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
53 ALTER TABLE radreply ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
54 ALTER TABLE radgroupcheck ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
55 ALTER TABLE radgroupreply ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='
57 <li>Using Radiator, see the
58 <a href="http://www.open.com.au/radiator/faq.html#38">Radiator FAQ</a>
59 for configuration information.
65 'desc' => 'Real-time export to SQL-backed RADIUS (FreeRADIUS, ICRADIUS, Radiator)',
66 'options' => \%options,
69 'This export does not export RADIUS realms (see also '.
70 'sqlradius_withdomain). '.
74 sub rebless { shift; }
77 my($self, $svc_acct) = (shift, shift);
82 my($self, $svc_acct) = (shift, shift);
84 foreach my $table (qw(reply check)) {
85 my $method = "radius_$table";
86 my %attrib = $svc_acct->$method();
87 next unless keys %attrib;
88 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'insert',
89 $table, $self->export_username($svc_acct), %attrib );
90 return $err_or_queue unless ref($err_or_queue);
92 my @groups = $svc_acct->radius_groups;
94 my $err_or_queue = $self->sqlradius_queue(
95 $svc_acct->svcnum, 'usergroup_insert',
96 $self->export_username($svc_acct), @groups );
97 return $err_or_queue unless ref($err_or_queue);
102 sub _export_replace {
103 my( $self, $new, $old ) = (shift, shift, shift);
105 local $SIG{HUP} = 'IGNORE';
106 local $SIG{INT} = 'IGNORE';
107 local $SIG{QUIT} = 'IGNORE';
108 local $SIG{TERM} = 'IGNORE';
109 local $SIG{TSTP} = 'IGNORE';
110 local $SIG{PIPE} = 'IGNORE';
112 my $oldAutoCommit = $FS::UID::AutoCommit;
113 local $FS::UID::AutoCommit = 0;
117 if ( $self->export_username($old) ne $self->export_username($new) ) {
118 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'rename',
119 $self->export_username($new), $self->export_username($old) );
120 unless ( ref($err_or_queue) ) {
121 $dbh->rollback if $oldAutoCommit;
122 return $err_or_queue;
124 $jobnum = $err_or_queue->jobnum;
127 foreach my $table (qw(reply check)) {
128 my $method = "radius_$table";
129 my %new = $new->$method();
130 my %old = $old->$method();
131 if ( grep { !exists $old{$_} #new attributes
132 || $new{$_} ne $old{$_} #changed
135 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'insert',
136 $table, $self->export_username($new), %new );
137 unless ( ref($err_or_queue) ) {
138 $dbh->rollback if $oldAutoCommit;
139 return $err_or_queue;
142 my $error = $err_or_queue->depend_insert( $jobnum );
144 $dbh->rollback if $oldAutoCommit;
150 my @del = grep { !exists $new{$_} } keys %old;
152 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'attrib_delete',
153 $table, $self->export_username($new), @del );
154 unless ( ref($err_or_queue) ) {
155 $dbh->rollback if $oldAutoCommit;
156 return $err_or_queue;
159 my $error = $err_or_queue->depend_insert( $jobnum );
161 $dbh->rollback if $oldAutoCommit;
168 # (sorta) false laziness with FS::svc_acct::replace
169 my @oldgroups = @{$old->usergroup}; #uuuh
170 my @newgroups = $new->radius_groups;
172 foreach my $oldgroup ( @oldgroups ) {
173 if ( grep { $oldgroup eq $_ } @newgroups ) {
174 @newgroups = grep { $oldgroup ne $_ } @newgroups;
177 push @delgroups, $oldgroup;
181 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'usergroup_delete',
182 $self->export_username($new), @delgroups );
183 unless ( ref($err_or_queue) ) {
184 $dbh->rollback if $oldAutoCommit;
185 return $err_or_queue;
188 my $error = $err_or_queue->depend_insert( $jobnum );
190 $dbh->rollback if $oldAutoCommit;
197 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'usergroup_insert',
198 $self->export_username($new), @newgroups );
199 unless ( ref($err_or_queue) ) {
200 $dbh->rollback if $oldAutoCommit;
201 return $err_or_queue;
204 my $error = $err_or_queue->depend_insert( $jobnum );
206 $dbh->rollback if $oldAutoCommit;
212 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
218 my( $self, $svc_acct ) = (shift, shift);
219 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'delete',
220 $self->export_username($svc_acct) );
221 ref($err_or_queue) ? '' : $err_or_queue;
224 sub sqlradius_queue {
225 my( $self, $svcnum, $method ) = (shift, shift, shift);
226 my $queue = new FS::queue {
228 'job' => "FS::part_export::sqlradius::sqlradius_$method",
231 $self->option('datasrc'),
232 $self->option('username'),
233 $self->option('password'),
238 sub sqlradius_insert { #subroutine, not method
239 my $dbh = sqlradius_connect(shift, shift, shift);
240 my( $table, $username, %attributes ) = @_;
242 foreach my $attribute ( keys %attributes ) {
244 my $s_sth = $dbh->prepare(
245 "SELECT COUNT(*) FROM rad$table WHERE UserName = ? AND Attribute = ?"
246 ) or die $dbh->errstr;
247 $s_sth->execute( $username, $attribute ) or die $s_sth->errstr;
249 if ( $s_sth->fetchrow_arrayref->[0] ) {
251 my $u_sth = $dbh->prepare(
252 "UPDATE rad$table SET Value = ? WHERE UserName = ? AND Attribute = ?"
253 ) or die $dbh->errstr;
254 $u_sth->execute($attributes{$attribute}, $username, $attribute)
255 or die $u_sth->errstr;
259 my $i_sth = $dbh->prepare(
260 "INSERT INTO rad$table ( UserName, Attribute, op, Value ) ".
261 "VALUES ( ?, ?, ?, ? )"
262 ) or die $dbh->errstr;
266 ( $attribute =~ /Password/i ? '==' : ':=' ),
267 $attributes{$attribute},
268 ) or die $i_sth->errstr;
276 sub sqlradius_usergroup_insert { #subroutine, not method
277 my $dbh = sqlradius_connect(shift, shift, shift);
278 my( $username, @groups ) = @_;
280 my $sth = $dbh->prepare(
281 "INSERT INTO usergroup ( UserName, GroupName ) VALUES ( ?, ? )"
282 ) or die $dbh->errstr;
283 foreach my $group ( @groups ) {
284 $sth->execute( $username, $group )
285 or die "can't insert into groupname table: ". $sth->errstr;
290 sub sqlradius_usergroup_delete { #subroutine, not method
291 my $dbh = sqlradius_connect(shift, shift, shift);
292 my( $username, @groups ) = @_;
294 my $sth = $dbh->prepare(
295 "DELETE FROM usergroup WHERE UserName = ? AND GroupName = ?"
296 ) or die $dbh->errstr;
297 foreach my $group ( @groups ) {
298 $sth->execute( $username, $group )
299 or die "can't delete from groupname table: ". $sth->errstr;
304 sub sqlradius_rename { #subroutine, not method
305 my $dbh = sqlradius_connect(shift, shift, shift);
306 my($new_username, $old_username) = @_;
307 foreach my $table (qw(radreply radcheck usergroup )) {
308 my $sth = $dbh->prepare("UPDATE $table SET Username = ? WHERE UserName = ?")
310 $sth->execute($new_username, $old_username)
311 or die "can't update $table: ". $sth->errstr;
316 sub sqlradius_attrib_delete { #subroutine, not method
317 my $dbh = sqlradius_connect(shift, shift, shift);
318 my( $table, $username, @attrib ) = @_;
320 foreach my $attribute ( @attrib ) {
321 my $sth = $dbh->prepare(
322 "DELETE FROM rad$table WHERE UserName = ? AND Attribute = ?" )
324 $sth->execute($username,$attribute)
325 or die "can't delete from rad$table table: ". $sth->errstr;
330 sub sqlradius_delete { #subroutine, not method
331 my $dbh = sqlradius_connect(shift, shift, shift);
332 my $username = shift;
334 foreach my $table (qw( radcheck radreply usergroup )) {
335 my $sth = $dbh->prepare( "DELETE FROM $table WHERE UserName = ?" );
336 $sth->execute($username)
337 or die "can't delete from $table table: ". $sth->errstr;
342 sub sqlradius_connect {
343 #my($datasrc, $username, $password) = @_;
344 #DBI->connect($datasrc, $username, $password) or die $DBI::errstr;
345 DBI->connect(@_) or die $DBI::errstr;
350 =item usage_sessions TIMESTAMP_START TIMESTAMP_END [ SVC_ACCT [ IP [ PREFIX [ SQL_SELECT ] ] ] ]
352 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
353 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
356 SVC_ACCT, if specified, limits the results to the specified account.
358 IP, if specified, limits the results to the specified IP address.
360 PREFIX, if specified, limits the results to records with a matching
363 #SQL_SELECT defaults to * if unspecified. It can be useful to set it to
364 #SUM(acctsessiontime) or SUM(AcctInputOctets), etc.
366 Returns an array of hash references
367 Returns an arrayref of hashrefs with the following fields:
373 =item framedipaddress
379 =item acctsessiontime
381 =item acctinputoctets
383 =item acctoutputoctets
385 =item calledstationid
391 #some false laziness w/cust_svc::seconds_since_sqlradacct
394 my( $self, $start, $end ) = splice(@_, 0, 3);
395 my $svc_acct = @_ ? shift : '';
396 my $ip = @_ ? shift : '';
397 my $prefix = @_ ? shift : '';
398 #my $select = @_ ? shift : '*';
402 return [] if $self->option('ignore_accounting');
404 my $dbh = sqlradius_connect( map $self->option($_),
405 qw( datasrc username password ) );
407 #select a unix time conversion function based on database type
409 if ( $dbh->{Driver}->{Name} =~ /^mysql(PP)?$/ ) {
410 $str2time = 'UNIX_TIMESTAMP(';
411 } elsif ( $dbh->{Driver}->{Name} eq 'Pg' ) {
412 $str2time = 'EXTRACT( EPOCH FROM ';
414 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
415 "; guessing how to convert to UNIX timestamps";
416 $str2time = 'extract(epoch from ';
420 qw( username realm framedipaddress
421 acctsessiontime acctinputoctets acctoutputoctets
424 "$str2time acctstarttime ) as acctstarttime",
425 "$str2time acctstoptime ) as acctstoptime",
432 my $username = $self->export_username($svc_acct);
433 if ( $svc_acct =~ /^([^@]+)\@([^@]+)$/ ) {
434 $where = '( UserName = ? OR ( UserName = ? AND Realm = ? ) ) AND';
435 push @param, $username, $1, $2;
437 $where = 'UserName = ? AND';
438 push @param, $username;
443 $where .= ' FramedIPAddress = ? AND';
447 if ( length($prefix) ) {
448 #assume sip: for now, else things get ugly trying to match /^\w+:$prefix/
449 $where .= " CalledStationID LIKE 'sip:$prefix\%' AND";
452 push @param, $start, $end;
454 my $sth = $dbh->prepare('SELECT '. join(', ', @fields).
457 $str2time AcctStopTime ) >= ?
458 AND $str2time AcctStopTime ) <= ?
459 ORDER BY AcctStartTime DESC
460 ") or die $dbh->errstr;
461 $sth->execute(@param) or die $sth->errstr;
463 [ map { { %$_ } } @{ $sth->fetchall_arrayref({}) } ];