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',
36 label => 'Do not change the password on suspend and unsuspend events',
38 'groups_susp_reason' => { label =>
39 'Radius group mapping to reason (via template user)',
46 Real-time export of <b>radcheck</b>, <b>radreply</b> and <b>usergroup</b>
47 tables to any SQL database for
48 <a href="http://www.freeradius.org/">FreeRADIUS</a>
49 or <a href="http://radius.innercite.com/">ICRADIUS</a>.
53 An existing RADIUS database will be updated in realtime, but you can use
54 <a href="../docs/man/bin/freeside-sqlradius-reset">freeside-sqlradius-reset</a>
55 to delete the entire RADIUS database and repopulate the tables from the
56 Freeside database. See the
57 <a href="http://search.cpan.org/dist/DBI/DBI.pm#connect">DBI documentation</a>
59 <a href="http://search.cpan.org/search?mode=module&query=DBD%3A%3A">documentation for your DBD</a>
60 for the exact syntax of a DBI data source.
62 <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.
63 <li>Using ICRADIUS, add a dummy "op" column to your database:
65 ALTER TABLE radcheck ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
66 ALTER TABLE radreply ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
67 ALTER TABLE radgroupcheck ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='<br>
68 ALTER TABLE radgroupreply ADD COLUMN op VARCHAR(2) NOT NULL DEFAULT '=='
70 <li>Using Radiator, see the
71 <a href="http://www.open.com.au/radiator/faq.html#38">Radiator FAQ</a>
72 for configuration information.
78 'desc' => 'Real-time export to SQL-backed RADIUS (FreeRADIUS, ICRADIUS)',
79 'options' => \%options,
82 'This export does not export RADIUS realms (see also '.
83 'sqlradius_withdomain). '.
87 sub _groups_susp_reason_map { map { reverse( /^\s*(\S+)\s*(.*)$/ ) }
88 split( "\n", shift->option('groups_susp_reason'));
91 sub rebless { shift; }
94 my($self, $svc_acct) = (shift, shift);
95 warn "export_username called on $self with arg $svc_acct" if $DEBUG;
100 my($self, $svc_acct) = (shift, shift);
102 foreach my $table (qw(reply check)) {
103 my $method = "radius_$table";
104 my %attrib = $svc_acct->$method();
105 next unless keys %attrib;
106 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'insert',
107 $table, $self->export_username($svc_acct), %attrib );
108 return $err_or_queue unless ref($err_or_queue);
110 my @groups = $svc_acct->radius_groups;
112 my $err_or_queue = $self->sqlradius_queue(
113 $svc_acct->svcnum, 'usergroup_insert',
114 $self->export_username($svc_acct), @groups );
115 return $err_or_queue unless ref($err_or_queue);
120 sub _export_replace {
121 my( $self, $new, $old ) = (shift, shift, shift);
123 local $SIG{HUP} = 'IGNORE';
124 local $SIG{INT} = 'IGNORE';
125 local $SIG{QUIT} = 'IGNORE';
126 local $SIG{TERM} = 'IGNORE';
127 local $SIG{TSTP} = 'IGNORE';
128 local $SIG{PIPE} = 'IGNORE';
130 my $oldAutoCommit = $FS::UID::AutoCommit;
131 local $FS::UID::AutoCommit = 0;
135 if ( $self->export_username($old) ne $self->export_username($new) ) {
136 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'rename',
137 $self->export_username($new), $self->export_username($old) );
138 unless ( ref($err_or_queue) ) {
139 $dbh->rollback if $oldAutoCommit;
140 return $err_or_queue;
142 $jobnum = $err_or_queue->jobnum;
145 foreach my $table (qw(reply check)) {
146 my $method = "radius_$table";
147 my %new = $new->$method();
148 my %old = $old->$method();
149 if ( grep { !exists $old{$_} #new attributes
150 || $new{$_} ne $old{$_} #changed
153 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'insert',
154 $table, $self->export_username($new), %new );
155 unless ( ref($err_or_queue) ) {
156 $dbh->rollback if $oldAutoCommit;
157 return $err_or_queue;
160 my $error = $err_or_queue->depend_insert( $jobnum );
162 $dbh->rollback if $oldAutoCommit;
168 my @del = grep { !exists $new{$_} } keys %old;
170 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'attrib_delete',
171 $table, $self->export_username($new), @del );
172 unless ( ref($err_or_queue) ) {
173 $dbh->rollback if $oldAutoCommit;
174 return $err_or_queue;
177 my $error = $err_or_queue->depend_insert( $jobnum );
179 $dbh->rollback if $oldAutoCommit;
187 my (@oldgroups) = $old->radius_groups;
188 my (@newgroups) = $new->radius_groups;
189 $error = $self->sqlreplace_usergroups( $new->svcnum,
190 $self->export_username($new),
191 $jobnum ? $jobnum : '',
196 $dbh->rollback if $oldAutoCommit;
200 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
205 sub _export_suspend {
206 my( $self, $svc_acct ) = (shift, shift);
208 my $new = $self->option('keep_password') ? $svc_acct
209 : $svc_acct->clone_suspended;
211 local $SIG{HUP} = 'IGNORE';
212 local $SIG{INT} = 'IGNORE';
213 local $SIG{QUIT} = 'IGNORE';
214 local $SIG{TERM} = 'IGNORE';
215 local $SIG{TSTP} = 'IGNORE';
216 local $SIG{PIPE} = 'IGNORE';
218 my $oldAutoCommit = $FS::UID::AutoCommit;
219 local $FS::UID::AutoCommit = 0;
222 my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'insert',
223 'check', $self->export_username($new), $new->radius_check );
224 unless ( ref($err_or_queue) ) {
225 $dbh->rollback if $oldAutoCommit;
226 return $err_or_queue;
230 my (@newgroups) = $self->suspended_usergroups($svc_acct);
232 $self->sqlreplace_usergroups( $new->svcnum,
233 $self->export_username($new),
235 $svc_acct->usergroup,
239 $dbh->rollback if $oldAutoCommit;
242 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
247 sub _export_unsuspend {
248 my( $self, $svc_acct ) = (shift, shift);
250 local $SIG{HUP} = 'IGNORE';
251 local $SIG{INT} = 'IGNORE';
252 local $SIG{QUIT} = 'IGNORE';
253 local $SIG{TERM} = 'IGNORE';
254 local $SIG{TSTP} = 'IGNORE';
255 local $SIG{PIPE} = 'IGNORE';
257 my $oldAutoCommit = $FS::UID::AutoCommit;
258 local $FS::UID::AutoCommit = 0;
261 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'insert',
262 'check', $self->export_username($svc_acct), $svc_acct->radius_check );
263 unless ( ref($err_or_queue) ) {
264 $dbh->rollback if $oldAutoCommit;
265 return $err_or_queue;
269 my (@oldgroups) = $self->suspended_usergroups($svc_acct);
270 $error = $self->sqlreplace_usergroups( $svc_acct->svcnum,
271 $self->export_username($svc_acct),
274 $svc_acct->usergroup,
277 $dbh->rollback if $oldAutoCommit;
280 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
286 my( $self, $svc_acct ) = (shift, shift);
287 my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'delete',
288 $self->export_username($svc_acct) );
289 ref($err_or_queue) ? '' : $err_or_queue;
292 sub sqlradius_queue {
293 my( $self, $svcnum, $method ) = (shift, shift, shift);
294 my $queue = new FS::queue {
296 'job' => "FS::part_export::sqlradius::sqlradius_$method",
299 $self->option('datasrc'),
300 $self->option('username'),
301 $self->option('password'),
306 sub suspended_usergroups {
307 my ($self, $svc_acct) = (shift, shift);
309 return () unless $svc_acct;
311 #false laziness with FS::part_export::shellcommands
312 #subclass part_export?
314 my $r = $svc_acct->cust_svc->cust_pkg->last_reason;
315 my %reasonmap = $self->_groups_susp_reason_map;
318 $userspec = $reasonmap{$r->reasonnum}
319 if exists($reasonmap{$r->reasonnum});
320 $userspec = $reasonmap{$r->reason}
321 if (!$userspec && exists($reasonmap{$r->reason}));
324 if ($userspec =~ /^d+$/ ){
325 $suspend_user = qsearchs( 'svc_acct', { 'svcnum' => $userspec } );
326 }elsif ($userspec =~ /^\S+\@\S+$/){
327 my ($username,$domain) = split(/\@/, $userspec);
328 for my $user (qsearch( 'svc_acct', { 'username' => $username } )){
329 $suspend_user = $user if $userspec eq $user->email;
332 $suspend_user = qsearchs( 'svc_acct', { 'username' => $userspec } );
335 return $suspend_user->radius_groups if $suspend_user;
339 sub sqlradius_insert { #subroutine, not method
340 my $dbh = sqlradius_connect(shift, shift, shift);
341 my( $table, $username, %attributes ) = @_;
343 foreach my $attribute ( keys %attributes ) {
345 my $s_sth = $dbh->prepare(
346 "SELECT COUNT(*) FROM rad$table WHERE UserName = ? AND Attribute = ?"
347 ) or die $dbh->errstr;
348 $s_sth->execute( $username, $attribute ) or die $s_sth->errstr;
350 if ( $s_sth->fetchrow_arrayref->[0] ) {
352 my $u_sth = $dbh->prepare(
353 "UPDATE rad$table SET Value = ? WHERE UserName = ? AND Attribute = ?"
354 ) or die $dbh->errstr;
355 $u_sth->execute($attributes{$attribute}, $username, $attribute)
356 or die $u_sth->errstr;
360 my $i_sth = $dbh->prepare(
361 "INSERT INTO rad$table ( UserName, Attribute, op, Value ) ".
362 "VALUES ( ?, ?, ?, ? )"
363 ) or die $dbh->errstr;
367 ( $attribute =~ /Password/i ? '==' : ':=' ),
368 $attributes{$attribute},
369 ) or die $i_sth->errstr;
377 sub sqlradius_usergroup_insert { #subroutine, not method
378 my $dbh = sqlradius_connect(shift, shift, shift);
379 my( $username, @groups ) = @_;
381 my $sth = $dbh->prepare(
382 "INSERT INTO usergroup ( UserName, GroupName ) VALUES ( ?, ? )"
383 ) or die $dbh->errstr;
384 foreach my $group ( @groups ) {
385 $sth->execute( $username, $group )
386 or die "can't insert into groupname table: ". $sth->errstr;
391 sub sqlradius_usergroup_delete { #subroutine, not method
392 my $dbh = sqlradius_connect(shift, shift, shift);
393 my( $username, @groups ) = @_;
395 my $sth = $dbh->prepare(
396 "DELETE FROM usergroup WHERE UserName = ? AND GroupName = ?"
397 ) or die $dbh->errstr;
398 foreach my $group ( @groups ) {
399 $sth->execute( $username, $group )
400 or die "can't delete from groupname table: ". $sth->errstr;
405 sub sqlradius_rename { #subroutine, not method
406 my $dbh = sqlradius_connect(shift, shift, shift);
407 my($new_username, $old_username) = @_;
408 foreach my $table (qw(radreply radcheck usergroup )) {
409 my $sth = $dbh->prepare("UPDATE $table SET Username = ? WHERE UserName = ?")
411 $sth->execute($new_username, $old_username)
412 or die "can't update $table: ". $sth->errstr;
417 sub sqlradius_attrib_delete { #subroutine, not method
418 my $dbh = sqlradius_connect(shift, shift, shift);
419 my( $table, $username, @attrib ) = @_;
421 foreach my $attribute ( @attrib ) {
422 my $sth = $dbh->prepare(
423 "DELETE FROM rad$table WHERE UserName = ? AND Attribute = ?" )
425 $sth->execute($username,$attribute)
426 or die "can't delete from rad$table table: ". $sth->errstr;
431 sub sqlradius_delete { #subroutine, not method
432 my $dbh = sqlradius_connect(shift, shift, shift);
433 my $username = shift;
435 foreach my $table (qw( radcheck radreply usergroup )) {
436 my $sth = $dbh->prepare( "DELETE FROM $table WHERE UserName = ?" );
437 $sth->execute($username)
438 or die "can't delete from $table table: ". $sth->errstr;
443 sub sqlradius_connect {
444 #my($datasrc, $username, $password) = @_;
445 #DBI->connect($datasrc, $username, $password) or die $DBI::errstr;
446 DBI->connect(@_) or die $DBI::errstr;
449 sub sqlreplace_usergroups {
450 my ($self, $svcnum, $username, $jobnum, $old, $new) = @_;
452 # (sorta) false laziness with FS::svc_acct::replace
453 my @oldgroups = @$old;
454 my @newgroups = @$new;
456 foreach my $oldgroup ( @oldgroups ) {
457 if ( grep { $oldgroup eq $_ } @newgroups ) {
458 @newgroups = grep { $oldgroup ne $_ } @newgroups;
461 push @delgroups, $oldgroup;
465 my $err_or_queue = $self->sqlradius_queue( $svcnum, 'usergroup_delete',
466 $username, @delgroups );
468 unless ref($err_or_queue);
470 my $error = $err_or_queue->depend_insert( $jobnum );
471 return $error if $error;
476 my $err_or_queue = $self->sqlradius_queue( $svcnum, 'usergroup_insert',
477 $username, @newgroups );
479 unless ref($err_or_queue);
481 my $error = $err_or_queue->depend_insert( $jobnum );
482 return $error if $error;
491 =item usage_sessions TIMESTAMP_START TIMESTAMP_END [ SVC_ACCT [ IP [ PREFIX [ SQL_SELECT ] ] ] ]
493 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
494 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
497 SVC_ACCT, if specified, limits the results to the specified account.
499 IP, if specified, limits the results to the specified IP address.
501 PREFIX, if specified, limits the results to records with a matching
504 #SQL_SELECT defaults to * if unspecified. It can be useful to set it to
505 #SUM(acctsessiontime) or SUM(AcctInputOctets), etc.
507 Returns an arrayref of hashrefs with the following fields:
513 =item framedipaddress
519 =item acctsessiontime
521 =item acctinputoctets
523 =item acctoutputoctets
525 =item calledstationid
531 #some false laziness w/cust_svc::seconds_since_sqlradacct
534 my( $self, $start, $end ) = splice(@_, 0, 3);
535 my $svc_acct = @_ ? shift : '';
536 my $ip = @_ ? shift : '';
537 my $prefix = @_ ? shift : '';
538 #my $select = @_ ? shift : '*';
542 return [] if $self->option('ignore_accounting');
544 my $dbh = sqlradius_connect( map $self->option($_),
545 qw( datasrc username password ) );
547 #select a unix time conversion function based on database type
549 if ( $dbh->{Driver}->{Name} =~ /^mysql(PP)?$/ ) {
550 $str2time = 'UNIX_TIMESTAMP(';
551 } elsif ( $dbh->{Driver}->{Name} eq 'Pg' ) {
552 $str2time = 'EXTRACT( EPOCH FROM ';
554 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
555 "; guessing how to convert to UNIX timestamps";
556 $str2time = 'extract(epoch from ';
560 qw( username realm framedipaddress
561 acctsessiontime acctinputoctets acctoutputoctets
564 "$str2time acctstarttime ) as acctstarttime",
565 "$str2time acctstoptime ) as acctstoptime",
572 my $username = $self->export_username($svc_acct);
573 if ( $svc_acct =~ /^([^@]+)\@([^@]+)$/ ) {
574 $where = '( UserName = ? OR ( UserName = ? AND Realm = ? ) ) AND';
575 push @param, $username, $1, $2;
577 $where = 'UserName = ? AND';
578 push @param, $username;
583 $where .= ' FramedIPAddress = ? AND';
587 if ( length($prefix) ) {
588 #assume sip: for now, else things get ugly trying to match /^\w+:$prefix/
589 $where .= " CalledStationID LIKE 'sip:$prefix\%' AND";
592 push @param, $start, $end;
594 my $sth = $dbh->prepare('SELECT '. join(', ', @fields).
597 $str2time AcctStopTime ) >= ?
598 AND $str2time AcctStopTime ) <= ?
599 ORDER BY AcctStartTime DESC
600 ") or die $dbh->errstr;
601 $sth->execute(@param) or die $sth->errstr;
603 [ map { { %$_ } } @{ $sth->fetchall_arrayref({}) } ];
607 =item update_svc_acct
611 sub update_svc_acct {
614 my $dbh = sqlradius_connect( map $self->option($_),
615 qw( datasrc username password ) );
617 my @fields = qw( radacctid username realm acctsessiontime );
622 my $sth = $dbh->prepare("
623 SELECT RadAcctId, UserName, Realm, AcctSessionTime,
624 AcctInputOctets, AcctOutputOctets
626 WHERE FreesideStatus IS NULL
627 AND AcctStopTime != 0
628 ") or die $dbh->errstr;
629 $sth->execute() or die $sth->errstr;
631 while ( my $row = $sth->fetchrow_arrayref ) {
632 my($RadAcctId, $UserName, $Realm, $AcctSessionTime,
633 $AcctInputOctets, $AcctOutputOctets) = @$row;
634 warn "processing record: ".
635 "$RadAcctId ($UserName\@$Realm for ${AcctSessionTime}s"
638 my %search = ( 'username' => $UserName );
640 if ( ref($self) =~ /withdomain/ ) { #well...
641 $extra_sql = " AND '$Realm' = ( SELECT domain FROM svc_domain
642 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
646 grep { qsearch( 'export_svc', { 'exportnum' => $self->exportnum,
647 'svcpart' => $_->cust_svc->svcpart, } )
650 { 'username' => $UserName },
655 my $errinfo = "for RADIUS detail RadAcctID $RadAcctId ".
656 "(UserName $UserName, Realm $Realm)";
657 my $status = 'skipped';
659 warn "WARNING: no svc_acct record found $errinfo - skipping\n";
660 } elsif ( scalar(@svc_acct) > 1 ) {
661 warn "WARNING: multiple svc_acct records found $errinfo - skipping\n";
663 warn "found svc_acct ". $svc_acct[0]->svcnum. " $errinfo\n" if $DEBUG;
664 _try_decrement($svc_acct[0], 'seconds', $AcctSessionTime)
666 _try_decrement($svc_acct[0], 'upbytes', $AcctInputOctets)
668 _try_decrement($svc_acct[0], 'downbytes', $AcctOutputOctets)
670 _try_decrement($svc_acct[0], 'totalbytes', $AcctInputOctets +
675 warn "setting FreesideStatus to $status $errinfo\n" if $DEBUG;
676 my $psth = $dbh->prepare("UPDATE radacct
677 SET FreesideStatus = ?
679 ) or die $dbh->errstr;
680 $psth->execute($status, $RadAcctId) or die $psth->errstr;
687 my ($svc_acct, $column, $amount) = @_;
688 if ( $svc_acct->$column !~ /^$/ ) {
689 warn " svc_acct.$column found (". $svc_acct->$column.
692 my $method = 'decrement_' . $column;
693 my $error = $svc_acct->$method($amount);
694 die $error if $error;
697 warn " no existing $column value for svc_acct - skipping\n" if $DEBUG;