5eddd3a090758e19d21cd2d68c3faa9f359da4dd
[freeside.git] / FS / FS / part_export / sqlradius.pm
1 package FS::part_export::sqlradius;
2
3 use vars qw(@ISA %info %options $notes1 $notes2);
4 use Tie::IxHash;
5 use FS::Record qw( dbh );
6 use FS::part_export;
7
8 @ISA = qw(FS::part_export);
9
10 tie %options, 'Tie::IxHash',
11   'datasrc'  => { label=>'DBI data source ' },
12   'username' => { label=>'Database username' },
13   'password' => { label=>'Database password' },
14   'ignore_accounting' => {
15      type => 'checkbox',
16      label=>'Ignore accounting records from this database'
17   },
18 ;
19
20 $notes1 = <<'END';
21 Real-time export of radcheck, radreply and usergroup tables to any SQL database
22 for <a href="http://www.freeradius.org/">FreeRADIUS</a>,
23 <a href="http://radius.innercite.com/">ICRADIUS</a>
24 or <a href="http://www.open.com.au/radiator/">Radiator</a>.  
25 END
26
27 $notes2 = <<'END';
28 An existing RADIUS database will be updated in realtime, but you can use
29 <a href="../docs/man/bin/freeside-sqlradius-reset">freeside-sqlradius-reset</a>
30 to delete the entire RADIUS database and repopulate the tables from the
31 Freeside database.  See the
32 <a href="http://search.cpan.org/dist/DBI/DBI.pm#connect">DBI documentation</a>
33 and the
34 <a href="http://search.cpan.org/search?mode=module&query=DBD%3A%3A">documentation for your DBD</a>
35 for the exact syntax of a DBI data source.
36 <ul>
37   <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.
38   <li>Using ICRADIUS, add a dummy "op" column to your database:
39     <blockquote><code>
40       ALTER&nbsp;TABLE&nbsp;radcheck&nbsp;ADD&nbsp;COLUMN&nbsp;op&nbsp;VARCHAR(2)&nbsp;NOT&nbsp;NULL&nbsp;DEFAULT&nbsp;'=='<br>
41       ALTER&nbsp;TABLE&nbsp;radreply&nbsp;ADD&nbsp;COLUMN&nbsp;op&nbsp;VARCHAR(2)&nbsp;NOT&nbsp;NULL&nbsp;DEFAULT&nbsp;'=='<br>
42       ALTER&nbsp;TABLE&nbsp;radgroupcheck&nbsp;ADD&nbsp;COLUMN&nbsp;op&nbsp;VARCHAR(2)&nbsp;NOT&nbsp;NULL&nbsp;DEFAULT&nbsp;'=='<br>
43       ALTER&nbsp;TABLE&nbsp;radgroupreply&nbsp;ADD&nbsp;COLUMN&nbsp;op&nbsp;VARCHAR(2)&nbsp;NOT&nbsp;NULL&nbsp;DEFAULT&nbsp;'=='
44     </code></blockquote>
45   <li>Using Radiator, see the
46     <a href="http://www.open.com.au/radiator/faq.html#38">Radiator FAQ</a>
47     for configuration information.
48 </ul>
49 END
50
51 %info = (
52   'svc'      => 'svc_acct',
53   'desc'     => 'Real-time export to SQL-backed RADIUS (FreeRADIUS, ICRADIUS, Radiator)',
54   'options'  => \%options,
55   'nodomain' => 'Y',
56   'notes'    => $notes1.
57                 'This export does not export RADIUS realms (see also '.
58                 'sqlradius_withdomain).  '.
59                 $notes2
60 );
61
62 sub rebless { shift; }
63
64 sub export_username {
65   my($self, $svc_acct) = (shift, shift);
66   $svc_acct->username;
67 }
68
69 sub _export_insert {
70   my($self, $svc_acct) = (shift, shift);
71
72   foreach my $table (qw(reply check)) {
73     my $method = "radius_$table";
74     my %attrib = $svc_acct->$method();
75     next unless keys %attrib;
76     my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'insert',
77       $table, $self->export_username($svc_acct), %attrib );
78     return $err_or_queue unless ref($err_or_queue);
79   }
80   my @groups = $svc_acct->radius_groups;
81   if ( @groups ) {
82     my $err_or_queue = $self->sqlradius_queue(
83       $svc_acct->svcnum, 'usergroup_insert',
84       $self->export_username($svc_acct), @groups );
85     return $err_or_queue unless ref($err_or_queue);
86   }
87   '';
88 }
89
90 sub _export_replace {
91   my( $self, $new, $old ) = (shift, shift, shift);
92
93   local $SIG{HUP} = 'IGNORE';
94   local $SIG{INT} = 'IGNORE';
95   local $SIG{QUIT} = 'IGNORE';
96   local $SIG{TERM} = 'IGNORE';
97   local $SIG{TSTP} = 'IGNORE';
98   local $SIG{PIPE} = 'IGNORE';
99
100   my $oldAutoCommit = $FS::UID::AutoCommit;
101   local $FS::UID::AutoCommit = 0;
102   my $dbh = dbh;
103
104   my $jobnum = '';
105   if ( $self->export_username($old) ne $self->export_username($new) ) {
106     my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'rename',
107       $self->export_username($new), $self->export_username($old) );
108     unless ( ref($err_or_queue) ) {
109       $dbh->rollback if $oldAutoCommit;
110       return $err_or_queue;
111     }
112     $jobnum = $err_or_queue->jobnum;
113   }
114
115   foreach my $table (qw(reply check)) {
116     my $method = "radius_$table";
117     my %new = $new->$method();
118     my %old = $old->$method();
119     if ( grep { !exists $old{$_} #new attributes
120                 || $new{$_} ne $old{$_} #changed
121               } keys %new
122     ) {
123       my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'insert',
124         $table, $self->export_username($new), %new );
125       unless ( ref($err_or_queue) ) {
126         $dbh->rollback if $oldAutoCommit;
127         return $err_or_queue;
128       }
129       if ( $jobnum ) {
130         my $error = $err_or_queue->depend_insert( $jobnum );
131         if ( $error ) {
132           $dbh->rollback if $oldAutoCommit;
133           return $error;
134         }
135       }
136     }
137
138     my @del = grep { !exists $new{$_} } keys %old;
139     if ( @del ) {
140       my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'attrib_delete',
141         $table, $self->export_username($new), @del );
142       unless ( ref($err_or_queue) ) {
143         $dbh->rollback if $oldAutoCommit;
144         return $err_or_queue;
145       }
146       if ( $jobnum ) {
147         my $error = $err_or_queue->depend_insert( $jobnum );
148         if ( $error ) {
149           $dbh->rollback if $oldAutoCommit;
150           return $error;
151         }
152       }
153     }
154   }
155
156   # (sorta) false laziness with FS::svc_acct::replace
157   my @oldgroups = @{$old->usergroup}; #uuuh
158   my @newgroups = $new->radius_groups;
159   my @delgroups = ();
160   foreach my $oldgroup ( @oldgroups ) {
161     if ( grep { $oldgroup eq $_ } @newgroups ) {
162       @newgroups = grep { $oldgroup ne $_ } @newgroups;
163       next;
164     }
165     push @delgroups, $oldgroup;
166   }
167
168   if ( @delgroups ) {
169     my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'usergroup_delete',
170       $self->export_username($new), @delgroups );
171     unless ( ref($err_or_queue) ) {
172       $dbh->rollback if $oldAutoCommit;
173       return $err_or_queue;
174     }
175     if ( $jobnum ) {
176       my $error = $err_or_queue->depend_insert( $jobnum );
177       if ( $error ) {
178         $dbh->rollback if $oldAutoCommit;
179         return $error;
180       }
181     }
182   }
183
184   if ( @newgroups ) {
185     my $err_or_queue = $self->sqlradius_queue( $new->svcnum, 'usergroup_insert',
186       $self->export_username($new), @newgroups );
187     unless ( ref($err_or_queue) ) {
188       $dbh->rollback if $oldAutoCommit;
189       return $err_or_queue;
190     }
191     if ( $jobnum ) {
192       my $error = $err_or_queue->depend_insert( $jobnum );
193       if ( $error ) {
194         $dbh->rollback if $oldAutoCommit;
195         return $error;
196       }
197     }
198   }
199
200   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
201
202   '';
203 }
204
205 sub _export_delete {
206   my( $self, $svc_acct ) = (shift, shift);
207   my $err_or_queue = $self->sqlradius_queue( $svc_acct->svcnum, 'delete',
208     $self->export_username($svc_acct) );
209   ref($err_or_queue) ? '' : $err_or_queue;
210 }
211
212 sub sqlradius_queue {
213   my( $self, $svcnum, $method ) = (shift, shift, shift);
214   my $queue = new FS::queue {
215     'svcnum' => $svcnum,
216     'job'    => "FS::part_export::sqlradius::sqlradius_$method",
217   };
218   $queue->insert(
219     $self->option('datasrc'),
220     $self->option('username'),
221     $self->option('password'),
222     @_,
223   ) or $queue;
224 }
225
226 sub sqlradius_insert { #subroutine, not method
227   my $dbh = sqlradius_connect(shift, shift, shift);
228   my( $table, $username, %attributes ) = @_;
229
230   foreach my $attribute ( keys %attributes ) {
231   
232     my $s_sth = $dbh->prepare(
233       "SELECT COUNT(*) FROM rad$table WHERE UserName = ? AND Attribute = ?"
234     ) or die $dbh->errstr;
235     $s_sth->execute( $username, $attribute ) or die $s_sth->errstr;
236
237     if ( $s_sth->fetchrow_arrayref->[0] ) {
238
239       my $u_sth = $dbh->prepare(
240         "UPDATE rad$table SET Value = ? WHERE UserName = ? AND Attribute = ?"
241       ) or die $dbh->errstr;
242       $u_sth->execute($attributes{$attribute}, $username, $attribute)
243         or die $u_sth->errstr;
244
245     } else {
246
247       my $i_sth = $dbh->prepare(
248         "INSERT INTO rad$table ( UserName, Attribute, op, Value ) ".
249           "VALUES ( ?, ?, ?, ? )"
250       ) or die $dbh->errstr;
251       $i_sth->execute(
252         $username,
253         $attribute,
254         ( $attribute =~ /Password/i ? '==' : ':=' ),
255         $attributes{$attribute},
256       ) or die $i_sth->errstr;
257
258     }
259
260   }
261   $dbh->disconnect;
262 }
263
264 sub sqlradius_usergroup_insert { #subroutine, not method
265   my $dbh = sqlradius_connect(shift, shift, shift);
266   my( $username, @groups ) = @_;
267
268   my $sth = $dbh->prepare( 
269     "INSERT INTO usergroup ( UserName, GroupName ) VALUES ( ?, ? )"
270   ) or die $dbh->errstr;
271   foreach my $group ( @groups ) {
272     $sth->execute( $username, $group )
273       or die "can't insert into groupname table: ". $sth->errstr;
274   }
275   $dbh->disconnect;
276 }
277
278 sub sqlradius_usergroup_delete { #subroutine, not method
279   my $dbh = sqlradius_connect(shift, shift, shift);
280   my( $username, @groups ) = @_;
281
282   my $sth = $dbh->prepare( 
283     "DELETE FROM usergroup WHERE UserName = ? AND GroupName = ?"
284   ) or die $dbh->errstr;
285   foreach my $group ( @groups ) {
286     $sth->execute( $username, $group )
287       or die "can't delete from groupname table: ". $sth->errstr;
288   }
289   $dbh->disconnect;
290 }
291
292 sub sqlradius_rename { #subroutine, not method
293   my $dbh = sqlradius_connect(shift, shift, shift);
294   my($new_username, $old_username) = @_;
295   foreach my $table (qw(radreply radcheck usergroup )) {
296     my $sth = $dbh->prepare("UPDATE $table SET Username = ? WHERE UserName = ?")
297       or die $dbh->errstr;
298     $sth->execute($new_username, $old_username)
299       or die "can't update $table: ". $sth->errstr;
300   }
301   $dbh->disconnect;
302 }
303
304 sub sqlradius_attrib_delete { #subroutine, not method
305   my $dbh = sqlradius_connect(shift, shift, shift);
306   my( $table, $username, @attrib ) = @_;
307
308   foreach my $attribute ( @attrib ) {
309     my $sth = $dbh->prepare(
310         "DELETE FROM rad$table WHERE UserName = ? AND Attribute = ?" )
311       or die $dbh->errstr;
312     $sth->execute($username,$attribute)
313       or die "can't delete from rad$table table: ". $sth->errstr;
314   }
315   $dbh->disconnect;
316 }
317
318 sub sqlradius_delete { #subroutine, not method
319   my $dbh = sqlradius_connect(shift, shift, shift);
320   my $username = shift;
321
322   foreach my $table (qw( radcheck radreply usergroup )) {
323     my $sth = $dbh->prepare( "DELETE FROM $table WHERE UserName = ?" );
324     $sth->execute($username)
325       or die "can't delete from $table table: ". $sth->errstr;
326   }
327   $dbh->disconnect;
328 }
329
330 sub sqlradius_connect {
331   #my($datasrc, $username, $password) = @_;
332   #DBI->connect($datasrc, $username, $password) or die $DBI::errstr;
333   DBI->connect(@_) or die $DBI::errstr;
334 }
335
336 #--
337
338 =item usage_sessions TIMESTAMP_START TIMESTAMP_END [ SVC_ACCT [ IP [ SQL_SELECT ] ] ]
339
340 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
341 L<perlfunc/"time">.  Also see L<Time::Local> and L<Date::Parse> for conversion
342 functions.
343
344 SVC_ACCT, if specified, limits the results to the specified account.
345
346 IP, if specified, limits the results to the specified IP address.
347
348 #SQL_SELECT defaults to * if unspecified.  It can be useful to set it to 
349 #SUM(acctsessiontime) or SUM(AcctInputOctets), etc.
350
351 Returns an array of hash references
352 Returns an arrayref of hashrefs with the following fields:
353
354 =over 4
355
356 =item username
357
358 =item framedipaddress
359
360 =item acctstarttime
361
362 =item acctstoptime
363
364 =item acctsessiontime
365
366 =item acctinputoctets
367
368 =item acctoutputoctets
369
370 =back
371
372 =cut
373
374 #some false laziness w/cust_svc::seconds_since_sqlradacct
375
376 sub usage_sessions {
377   my( $self, $start, $end ) = splice(@_, 0, 3);
378   my $svc_acct = @_ ? shift : '';
379   my $ip = @_ ? shift : '';
380   #my $select = @_ ? shift : '*';
381
382   $end ||= 2147483647;
383
384   return [] if $self->option('ignore_accounting');
385
386   my $dbh = sqlradius_connect( map $self->option($_),
387                                    qw( datasrc username password ) );
388
389   #select a unix time conversion function based on database type
390   my $str2time;
391   if ( $dbh->{Driver}->{Name} =~ /^mysql(PP)?$/ ) {
392     $str2time = 'UNIX_TIMESTAMP(';
393   } elsif ( $dbh->{Driver}->{Name} eq 'Pg' ) {
394     $str2time = 'EXTRACT( EPOCH FROM ';
395   } else {
396     warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
397          "; guessing how to convert to UNIX timestamps";
398     $str2time = 'extract(epoch from ';
399   }
400
401   my @fields = (
402                  qw( username realm framedipaddress
403                      acctsessiontime acctinputoctets acctoutputoctets
404                    ),
405                  "$str2time acctstarttime ) as acctstarttime",
406                  "$str2time acctstoptime ) as acctstoptime",
407                );
408
409   my @param = ();
410   my $where = '';
411
412   if ( $svc_acct ) {
413     my $username = $self->export_username($svc_acct);
414     if ( $svc_acct =~ /^([^@]+)\@([^@]+)$/ ) {
415       $where = '( UserName = ? OR ( UserName = ? AND Realm = ? ) ) AND';
416       push @param, $username, $1, $2;
417     } else {
418       $where = 'UserName = ? AND';
419       push @param, $username;
420     }
421   }
422
423   if ( length($ip) ) {
424     $where .= ' FramedIPAddress = ? AND';
425     push @param, $ip;
426   }
427
428   push @param, $start, $end;
429
430   my $sth = $dbh->prepare('SELECT '. join(', ', @fields).
431                           "  FROM radacct
432                              WHERE $where
433                                    $str2time AcctStopTime ) >= ?
434                                AND $str2time AcctStopTime ) <=  ?
435                                ORDER BY AcctStartTime DESC
436   ") or die $dbh->errstr;                                 
437   $sth->execute(@param) or die $sth->errstr;
438
439   [ map { { %$_ } } @{ $sth->fetchall_arrayref({}) } ];
440
441 }
442
443 1;
444