1 package FS::part_export::sqlradius;
3 use vars qw(@ISA $DEBUG %info %options $notes1 $notes2);
5 use FS::Record qw( dbh qsearch qsearchs );
10 @ISA = qw(FS::part_export);
14 tie %options, 'Tie::IxHash',
15 'datasrc' => { label=>'DBI data source ' },
16 'username' => { label=>'Database username' },
17 'password' => { label=>'Database password' },
18 'ignore_accounting' => {
20 label => 'Ignore accounting records from this database'
24 label => 'Hide IP address information on session reports',
28 label => 'Hide download/upload information on session reports',
30 'show_called_station' => {
32 label => 'Show the Called-Station-ID on session reports',
34 'groups_susp_reason' => { label =>
35 'Radius group mapping to reason (via template user)',
42 Real-time export of <b>radcheck</b>, <b>radreply</b> and <b>usergroup</b>
43 tables to any SQL database for
44 <a href="http://www.freeradius.org/">FreeRADIUS</a>
45 or <a href="http://radius.innercite.com/">ICRADIUS</a>.
49 An existing RADIUS database will be updated in realtime, but you can use
50 <a href="../docs/man/bin/freeside-sqlradius-reset">freeside-sqlradius-reset</a>
51 to delete the entire RADIUS database and repopulate the tables from the
52 Freeside database. See the
53 <a href="http://search.cpan.org/dist/DBI/DBI.pm#connect">DBI documentation</a>
55 <a href="http://search.cpan.org/search?mode=module&query=DBD%3A%3A">documentation for your DBD</a>
56 for the exact syntax of a DBI data source.
58 <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.
59 <li>Using ICRADIUS, add a dummy "op" column to your database:
61 ALTER TABLE radcheck ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
62 ALTER TABLE radreply ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
63 ALTER TABLE radgroupcheck ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
64 ALTER TABLE radgroupreply ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='
66 <li>Using Radiator, see the
67 <a href="http://www.open.com.au/radiator/faq.html#38">Radiator FAQ</a>
68 for configuration information.
74 'desc' => 'Real-time export to SQL-backed RADIUS (FreeRADIUS, ICRADIUS)',
75 'options' => \%options,
78 'This export does not export RADIUS realms (see also '.
79 'sqlradius_withdomain). '.
83 sub _groups_susp_reason_map { map { reverse( /^\s*(\S+)\s*(.*)$/ ) }
84 split( "\n", shift->option('groups_susp_reason'));
87 sub rebless { shift; }
90 my($self, $svc_acct) = (shift, shift);
91 warn "export_username called on $self with arg $svc_acct" if $DEBUG;
96 my($self, $svc_acct) = (shift, shift);
98 foreach my $table (qw(reply check)) {
99 my $method = "radius_$table";
100 my %attrib = $svc_acct->$method();
101 next unless keys %attrib;
102 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'insert',
103 $table, $self->export_username($svc_acct), %attrib );
104 return $err_or_queue unless ref($err_or_queue);
106 my @groups = $svc_acct->radius_groups;
108 my $err_or_queue = $self->sqlradius_queue(
109 $svc_acct->svcnum, 'usergroup_insert',
110 $self->export_username($svc_acct), @groups );
111 return $err_or_queue unless ref($err_or_queue);
116 sub _export_replace {
117 my( $self, $new, $old ) = (shift, shift, shift);
119 local $SIG{HUP} = 'IGNORE';
120 local $SIG{INT} = 'IGNORE';
121 local $SIG{QUIT} = 'IGNORE';
122 local $SIG{TERM} = 'IGNORE';
123 local $SIG{TSTP} = 'IGNORE';
124 local $SIG{PIPE} = 'IGNORE';
126 my $oldAutoCommit = $FS::UID::AutoCommit;
127 local $FS::UID::AutoCommit = 0;
131 if ( $self->export_username($old) ne $self->export_username($new) ) {
132 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'rename',
133 $self->export_username($new), $self->export_username($old) );
134 unless ( ref($err_or_queue) ) {
135 $dbh->rollback if $oldAutoCommit;
136 return $err_or_queue;
138 $jobnum = $err_or_queue->jobnum;
141 foreach my $table (qw(reply check)) {
142 my $method = "radius_$table";
143 my %new = $new->$method();
144 my %old = $old->$method();
145 if ( grep { !exists $old{$_} #new attributes
146 || $new{$_} ne $old{$_} #changed
149 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'insert',
150 $table, $self->export_username($new), %new );
151 unless ( ref($err_or_queue) ) {
152 $dbh->rollback if $oldAutoCommit;
153 return $err_or_queue;
156 my $error = $err_or_queue->depend_insert( $jobnum );
158 $dbh->rollback if $oldAutoCommit;
164 my @del = grep { !exists $new{$_} } keys %old;
166 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'attrib_delete',
167 $table, $self->export_username($new), @del );
168 unless ( ref($err_or_queue) ) {
169 $dbh->rollback if $oldAutoCommit;
170 return $err_or_queue;
173 my $error = $err_or_queue->depend_insert( $jobnum );
175 $dbh->rollback if $oldAutoCommit;
183 my (@oldgroups) = $old->radius_groups;
184 my (@newgroups) = $new->radius_groups;
185 $error = $self->sqlreplace_usergroups( $new->svcnum,
186 $self->export_username($new),
187 $jobnum ? $jobnum : '',
192 $dbh->rollback if $oldAutoCommit;
196 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
201 sub _export_suspend {
202 my( $self, $svc_acct ) = (shift, shift);
204 my $new = $svc_acct->clone_suspended;
206 local $SIG{HUP} = 'IGNORE';
207 local $SIG{INT} = 'IGNORE';
208 local $SIG{QUIT} = 'IGNORE';
209 local $SIG{TERM} = 'IGNORE';
210 local $SIG{TSTP} = 'IGNORE';
211 local $SIG{PIPE} = 'IGNORE';
213 my $oldAutoCommit = $FS::UID::AutoCommit;
214 local $FS::UID::AutoCommit = 0;
217 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'insert',
218 'check', $self->export_username($new), $new->radius_check );
219 unless ( ref($err_or_queue) ) {
220 $dbh->rollback if $oldAutoCommit;
221 return $err_or_queue;
225 my (@newgroups) = $self->suspended_usergroups($svc_acct);
227 $self->sqlreplace_usergroups( $new->svcnum,
228 $self->export_username($new),
230 $svc_acct->usergroup,
234 $dbh->rollback if $oldAutoCommit;
237 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
242 sub _export_unsuspend {
243 my( $self, $svc_acct ) = (shift, shift);
245 local $SIG{HUP} = 'IGNORE';
246 local $SIG{INT} = 'IGNORE';
247 local $SIG{QUIT} = 'IGNORE';
248 local $SIG{TERM} = 'IGNORE';
249 local $SIG{TSTP} = 'IGNORE';
250 local $SIG{PIPE} = 'IGNORE';
252 my $oldAutoCommit = $FS::UID::AutoCommit;
253 local $FS::UID::AutoCommit = 0;
256 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'insert',
257 'check', $self->export_username($svc_acct), $svc_acct->radius_check );
258 unless ( ref($err_or_queue) ) {
259 $dbh->rollback if $oldAutoCommit;
260 return $err_or_queue;
264 my (@oldgroups) = $self->suspended_usergroups($svc_acct);
265 $error = $self->sqlreplace_usergroups( $svc_acct->svcnum,
266 $self->export_username($svc_acct),
269 $svc_acct->usergroup,
272 $dbh->rollback if $oldAutoCommit;
275 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
281 my( $self, $svc_acct ) = (shift, shift);
282 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'delete',
283 $self->export_username($svc_acct) );
284 ref($err_or_queue) ? '' : $err_or_queue;
287 sub sqlradius_queue {
288 my( $self, $svcnum, $method ) = (shift, shift, shift);
289 my $queue = new FS::queue {
291 'job' => "FS::part_export::sqlradius::sqlradius_$method",
294 $self->option('datasrc'),
295 $self->option('username'),
296 $self->option('password'),
301 sub suspended_usergroups {
302 my ($self, $svc_acct) = (shift, shift);
304 return () unless $svc_acct;
306 #false laziness with FS::part_export::shellcommands
307 #subclass part_export?
309 my $r = $svc_acct->cust_svc->cust_pkg->last_reason;
310 my %reasonmap = $self->_groups_susp_reason_map;
313 $userspec = $reasonmap{$r->reasonnum}
314 if exists($reasonmap{$r->reasonnum});
315 $userspec = $reasonmap{$r->reason}
316 if (!$userspec && exists($reasonmap{$r->reason}));
319 if ($userspec =~ /^d+$/ ){
320 $suspend_user = qsearchs( 'svc_acct', { 'svcnum' => $userspec } );
321 }elsif ($userspec =~ /^\S+\@\S+$/){
322 my ($username,$domain) = split(/\@/, $userspec);
323 for my $user (qsearch( 'svc_acct', { 'username' => $username } )){
324 $suspend_user = $user if $userspec eq $user->email;
327 $suspend_user = qsearchs( 'svc_acct', { 'username' => $userspec } );
330 return $suspend_user->radius_groups if $suspend_user;
334 sub sqlradius_insert { #subroutine, not method
335 my $dbh = sqlradius_connect(shift, shift, shift);
336 my( $table, $username, %attributes ) = @_;
338 foreach my $attribute ( keys %attributes ) {
340 my $s_sth = $dbh->prepare(
341 "SELECT COUNT(*) FROM rad$table WHERE UserName = ? AND Attribute = ?"
342 ) or die $dbh->errstr;
343 $s_sth->execute( $username, $attribute ) or die $s_sth->errstr;
345 if ( $s_sth->fetchrow_arrayref->[0] ) {
347 my $u_sth = $dbh->prepare(
348 "UPDATE rad$table SET Value = ? WHERE UserName = ? AND Attribute = ?"
349 ) or die $dbh->errstr;
350 $u_sth->execute($attributes{$attribute}, $username, $attribute)
351 or die $u_sth->errstr;
355 my $i_sth = $dbh->prepare(
356 "INSERT INTO rad$table ( UserName, Attribute, op, Value ) ".
357 "VALUES ( ?, ?, ?, ? )"
358 ) or die $dbh->errstr;
362 ( $attribute =~ /Password/i ? '==' : ':=' ),
363 $attributes{$attribute},
364 ) or die $i_sth->errstr;
372 sub sqlradius_usergroup_insert { #subroutine, not method
373 my $dbh = sqlradius_connect(shift, shift, shift);
374 my( $username, @groups ) = @_;
376 my $sth = $dbh->prepare(
377 "INSERT INTO usergroup ( UserName, GroupName ) VALUES ( ?, ? )"
378 ) or die $dbh->errstr;
379 foreach my $group ( @groups ) {
380 $sth->execute( $username, $group )
381 or die "can't insert into groupname table: ". $sth->errstr;
386 sub sqlradius_usergroup_delete { #subroutine, not method
387 my $dbh = sqlradius_connect(shift, shift, shift);
388 my( $username, @groups ) = @_;
390 my $sth = $dbh->prepare(
391 "DELETE FROM usergroup WHERE UserName = ? AND GroupName = ?"
392 ) or die $dbh->errstr;
393 foreach my $group ( @groups ) {
394 $sth->execute( $username, $group )
395 or die "can't delete from groupname table: ". $sth->errstr;
400 sub sqlradius_rename { #subroutine, not method
401 my $dbh = sqlradius_connect(shift, shift, shift);
402 my($new_username, $old_username) = @_;
403 foreach my $table (qw(radreply radcheck usergroup )) {
404 my $sth = $dbh->prepare("UPDATE $table SET Username = ? WHERE UserName = ?")
406 $sth->execute($new_username, $old_username)
407 or die "can't update $table: ". $sth->errstr;
412 sub sqlradius_attrib_delete { #subroutine, not method
413 my $dbh = sqlradius_connect(shift, shift, shift);
414 my( $table, $username, @attrib ) = @_;
416 foreach my $attribute ( @attrib ) {
417 my $sth = $dbh->prepare(
418 "DELETE FROM rad$table WHERE UserName = ? AND Attribute = ?" )
420 $sth->execute($username,$attribute)
421 or die "can't delete from rad$table table: ". $sth->errstr;
426 sub sqlradius_delete { #subroutine, not method
427 my $dbh = sqlradius_connect(shift, shift, shift);
428 my $username = shift;
430 foreach my $table (qw( radcheck radreply usergroup )) {
431 my $sth = $dbh->prepare( "DELETE FROM $table WHERE UserName = ?" );
432 $sth->execute($username)
433 or die "can't delete from $table table: ". $sth->errstr;
438 sub sqlradius_connect {
439 #my($datasrc, $username, $password) = @_;
440 #DBI->connect($datasrc, $username, $password) or die $DBI::errstr;
441 DBI->connect(@_) or die $DBI::errstr;
444 sub sqlreplace_usergroups {
445 my ($self, $svcnum, $username, $jobnum, $old, $new) = @_;
447 # (sorta) false laziness with FS::svc_acct::replace
448 my @oldgroups = @$old;
449 my @newgroups = @$new;
451 foreach my $oldgroup ( @oldgroups ) {
452 if ( grep { $oldgroup eq $_ } @newgroups ) {
453 @newgroups = grep { $oldgroup ne $_ } @newgroups;
456 push @delgroups, $oldgroup;
460 my $err_or_queue = $self->sqlradius_queue( $svcnum, 'usergroup_delete',
461 $username, @delgroups );
463 unless ref($err_or_queue);
465 my $error = $err_or_queue->depend_insert( $jobnum );
466 return $error if $error;
471 my $err_or_queue = $self->sqlradius_queue( $svcnum, 'usergroup_insert',
472 $username, @newgroups );
474 unless ref($err_or_queue);
476 my $error = $err_or_queue->depend_insert( $jobnum );
477 return $error if $error;
486 =item usage_sessions TIMESTAMP_START TIMESTAMP_END [ SVC_ACCT [ IP [ PREFIX [ SQL_SELECT ] ] ] ]
488 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
489 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
492 SVC_ACCT, if specified, limits the results to the specified account.
494 IP, if specified, limits the results to the specified IP address.
496 PREFIX, if specified, limits the results to records with a matching
499 #SQL_SELECT defaults to * if unspecified. It can be useful to set it to
500 #SUM(acctsessiontime) or SUM(AcctInputOctets), etc.
502 Returns an arrayref of hashrefs with the following fields:
508 =item framedipaddress
514 =item acctsessiontime
516 =item acctinputoctets
518 =item acctoutputoctets
520 =item calledstationid
526 #some false laziness w/cust_svc::seconds_since_sqlradacct
529 my( $self, $start, $end ) = splice(@_, 0, 3);
530 my $svc_acct = @_ ? shift : '';
531 my $ip = @_ ? shift : '';
532 my $prefix = @_ ? shift : '';
533 #my $select = @_ ? shift : '*';
537 return [] if $self->option('ignore_accounting');
539 my $dbh = sqlradius_connect( map $self->option($_),
540 qw( datasrc username password ) );
542 #select a unix time conversion function based on database type
544 if ( $dbh->{Driver}->{Name} =~ /^mysql(PP)?$/ ) {
545 $str2time = 'UNIX_TIMESTAMP(';
546 } elsif ( $dbh->{Driver}->{Name} eq 'Pg' ) {
547 $str2time = 'EXTRACT( EPOCH FROM ';
549 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
550 "; guessing how to convert to UNIX timestamps";
551 $str2time = 'extract(epoch from ';
555 qw( username realm framedipaddress
556 acctsessiontime acctinputoctets acctoutputoctets
559 "$str2time acctstarttime ) as acctstarttime",
560 "$str2time acctstoptime ) as acctstoptime",
567 my $username = $self->export_username($svc_acct);
568 if ( $svc_acct =~ /^([^@]+)\@([^@]+)$/ ) {
569 $where = '( UserName = ? OR ( UserName = ? AND Realm = ? ) ) AND';
570 push @param, $username, $1, $2;
572 $where = 'UserName = ? AND';
573 push @param, $username;
578 $where .= ' FramedIPAddress = ? AND';
582 if ( length($prefix) ) {
583 #assume sip: for now, else things get ugly trying to match /^\w+:$prefix/
584 $where .= " CalledStationID LIKE 'sip:$prefix\%' AND";
587 push @param, $start, $end;
589 my $sth = $dbh->prepare('SELECT '. join(', ', @fields).
592 $str2time AcctStopTime ) >= ?
593 AND $str2time AcctStopTime ) <= ?
594 ORDER BY AcctStartTime DESC
595 ") or die $dbh->errstr;
596 $sth->execute(@param) or die $sth->errstr;
598 [ map { { %$_ } } @{ $sth->fetchall_arrayref({}) } ];
602 =item update_svc_acct
606 sub update_svc_acct {
609 my $dbh = sqlradius_connect( map $self->option($_),
610 qw( datasrc username password ) );
612 my @fields = qw( radacctid username realm acctsessiontime );
617 my $sth = $dbh->prepare("
618 SELECT RadAcctId, UserName, Realm, AcctSessionTime,
619 AcctInputOctets, AcctOutputOctets
621 WHERE FreesideStatus IS NULL
622 AND AcctStopTime != 0
623 ") or die $dbh->errstr;
624 $sth->execute() or die $sth->errstr;
626 while ( my $row = $sth->fetchrow_arrayref ) {
627 my($RadAcctId, $UserName, $Realm, $AcctSessionTime,
628 $AcctInputOctets, $AcctOutputOctets) = @$row;
629 warn "processing record: ".
630 "$RadAcctId ($UserName\@$Realm for ${AcctSessionTime}s"
633 my %search = ( 'username' => $UserName );
635 if ( ref($self) =~ /withdomain/ ) { #well...
636 $extra_sql = " AND '$Realm' = ( SELECT domain FROM svc_domain
637 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
641 grep { qsearch( 'export_svc', { 'exportnum' => $self->exportnum,
642 'svcpart' => $_->cust_svc->svcpart, } )
645 { 'username' => $UserName },
650 my $errinfo = "for RADIUS detail RadAcctID $RadAcctId ".
651 "(UserName $UserName, Realm $Realm)";
652 my $status = 'skipped';
654 warn "WARNING: no svc_acct record found $errinfo - skipping\n";
655 } elsif ( scalar(@svc_acct) > 1 ) {
656 warn "WARNING: multiple svc_acct records found $errinfo - skipping\n";
658 warn "found svc_acct ". $svc_acct[0]->svcnum. " $errinfo\n" if $DEBUG;
659 _try_decrement($svc_acct[0], 'seconds', $AcctSessionTime)
661 _try_decrement($svc_acct[0], 'upbytes', $AcctInputOctets)
663 _try_decrement($svc_acct[0], 'downbytes', $AcctOutputOctets)
665 _try_decrement($svc_acct[0], 'totalbytes', $AcctInputOctets +
670 warn "setting FreesideStatus to $status $errinfo\n" if $DEBUG;
671 my $psth = $dbh->prepare("UPDATE radacct
672 SET FreesideStatus = ?
674 ) or die $dbh->errstr;
675 $psth->execute($status, $RadAcctId) or die $psth->errstr;
682 my ($svc_acct, $column, $amount) = @_;
683 if ( $svc_acct->$column !~ /^$/ ) {
684 warn " svc_acct.$column found (". $svc_acct->$column.
687 my $method = 'decrement_' . $column;
688 my $error = $svc_acct->$method($amount);
689 die $error if $error;
692 warn " no existing $column value for svc_acct - skipping\n" if $DEBUG;