Merge branch 'patch-18' of https://github.com/gjones2/Freeside
[freeside.git] / FS / FS / part_export / shellcommands.pm
1 package FS::part_export::shellcommands;
2
3 use vars qw(@ISA %info);
4 use Tie::IxHash;
5 use String::ShellQuote;
6 use FS::part_export;
7 use FS::Record qw( qsearch qsearchs );
8
9 @ISA = qw(FS::part_export);
10
11 tie my %options, 'Tie::IxHash',
12   'user' => { label=>'Remote username', default=>'root' },
13   'useradd' => { label=>'Insert command',
14                  default=>'useradd -c $finger -d $dir -m -s $shell -u $uid -p $crypt_password $username'
15                 #default=>'cp -pr /etc/skel $dir; chown -R $uid.$gid $dir'
16                },
17   'useradd_no_queue' => { label=>'Run immediately',
18                           type => 'checkbox',
19                         },
20   'useradd_stdin' => { label=>'Insert command STDIN',
21                        type =>'textarea',
22                        default=>'',
23                      },
24   'userdel' => { label=>'Delete command',
25                  default=>'userdel -r $username',
26                  #default=>'rm -rf $dir',
27                },
28   'userdel_no_queue' => { label=>'Run immediately',
29                           type =>'checkbox',
30                         },
31   'userdel_stdin' => { label=>'Delete command STDIN',
32                        type =>'textarea',
33                        default=>'',
34                      },
35   'usermod' => { label=>'Modify command',
36                  default=>'usermod -c $new_finger -d $new_dir -m -l $new_username -s $new_shell -u $new_uid -g $new_gid -p $new_crypt_password $old_username',
37                 #default=>'[ -d $old_dir ] && mv $old_dir $new_dir || ( '.
38                  #  'chmod u+t $old_dir; mkdir $new_dir; cd $old_dir; '.
39                  #  'find . -depth -print | cpio -pdm $new_dir; '.
40                  #  'chmod u-t $new_dir; chown -R $uid.$gid $new_dir; '.
41                  #  'rm -rf $old_dir'.
42                  #')'
43                },
44   'usermod_no_queue' => { label=>'Run immediately',
45                           type =>'checkbox',
46                         },
47   'usermod_stdin' => { label=>'Modify command STDIN',
48                        type =>'textarea',
49                        default=>'',
50                      },
51   'usermod_pwonly' => { label=>'Disallow username, domain, uid, gid, and dir changes', #and RADIUS group changes',
52                         type =>'checkbox',
53                       },
54   'usermod_nousername' => { label=>'Disallow just username changes',
55                             type =>'checkbox',
56                           },
57   'suspend' => { label=>'Suspension command',
58                  default=>'usermod -L $username',
59                },
60   'suspend_no_queue' => { label=>'Run immediately',
61                           type =>'checkbox',
62                         },
63   'suspend_stdin' => { label=>'Suspension command STDIN',
64                        default=>'',
65                      },
66   'unsuspend' => { label=>'Unsuspension command',
67                    default=>'usermod -U $username',
68                  },
69   'unsuspend_no_queue' => { label=>'Run immediately',
70                             type =>'checkbox',
71                           },
72   'unsuspend_stdin' => { label=>'Unsuspension command STDIN',
73                          default=>'',
74                        },
75   'crypt' => { label   => 'Default password encryption',
76                type=>'select', options=>[qw(crypt md5)],
77                default => 'crypt',
78              },
79   'groups_susp_reason' => { label =>
80                              'Radius group mapping to reason (via template user)',
81                              type  => 'textarea',
82                           },
83   'fail_on_output' => {
84       label => 'Treat any output from the command as an error',
85       type  => 'checkbox',
86   },
87   'ignore_all_errors' => {
88       label => 'Ignore all errors from the command',
89       type  => 'checkbox',
90   },
91   'ignored_errors' => { label   => 'Regexes of specific errors to ignore, separated by newlines',
92                         type    => 'textarea'
93                       },
94 #  'no_queue' => { label => 'Run command immediately',
95 #                   type  => 'checkbox',
96 #                },
97 ;
98
99 %info = (
100   'svc'         => 'svc_acct',
101   'desc'        => 'Real-time export via remote SSH (i.e. useradd, userdel, etc.)',
102   'options'     => \%options,
103   'nodomain'    => 'Y',
104   'svc_machine' => 1,
105   'notes'       => <<'END'
106 Run remote commands via SSH.  Usernames are considered unique (also see
107 shellcommands_withdomain).  You probably want this if the commands you are
108 running will not accept a domain as a parameter.  You will need to
109 <a href="http://www.freeside.biz/mediawiki/index.php/Freeside:1.9:Documentation:Administration:SSH_Keys">setup SSH for unattended operation</a>.
110
111 <BR><BR>Use these buttons for some useful presets:
112 <UL>
113   <LI>
114     <INPUT TYPE="button" VALUE="Linux" onClick='
115       this.form.useradd.value = "useradd -c $finger -d $dir -m -s $shell -u $uid -p $crypt_password $username";
116       this.form.useradd_stdin.value = "";
117       this.form.userdel.value = "userdel -r $username";
118       this.form.userdel_stdin.value="";
119       this.form.usermod.value = "usermod -c $new_finger -d $new_dir -m -l $new_username -s $new_shell -u $new_uid -g $new_gid -p $new_crypt_password $old_username";
120       this.form.usermod_stdin.value = "";
121       this.form.suspend.value = "usermod -L $username";
122       this.form.suspend_stdin.value="";
123       this.form.unsuspend.value = "usermod -U $username";
124       this.form.unsuspend_stdin.value="";
125     '>
126   <LI>
127     <INPUT TYPE="button" VALUE="FreeBSD" onClick='
128       this.form.useradd.value = "pw useradd $username -d $dir -m -s $shell -u $uid -g $gid -c $finger -h 0";
129       this.form.useradd_stdin.value = "$_password\n";
130       this.form.userdel.value = "pw userdel $username -r";
131       this.form.userdel_stdin.value="";
132       this.form.usermod.value = "pw usermod $old_username -d $new_dir -m -l $new_username -s $new_shell -u $new_uid -g $new_gid -c $new_finger -h 0";
133       this.form.usermod_stdin.value = "$new__password\n";
134       this.form.suspend.value = "pw lock $username";
135       this.form.suspend_stdin.value="";
136       this.form.unsuspend.value = "pw unlock $username";
137       this.form.unsuspend_stdin.value="";
138     '>
139   <LI>
140     <INPUT TYPE="button" VALUE="NetBSD/OpenBSD" onClick='
141       this.form.useradd.value = "useradd -c $finger -d $dir -m -s $shell -u $uid -p $crypt_password $username";
142       this.form.useradd_stdin.value = "";
143       this.form.userdel.value = "userdel -r $username";
144       this.form.userdel_stdin.value="";
145       this.form.usermod.value = "usermod -c $new_finger -d $new_dir -m -l $new_username -s $new_shell -u $new_uid -g $new_gid -p $new_crypt_password $old_username";
146       this.form.usermod_stdin.value = "";
147       this.form.suspend.value = "";
148       this.form.suspend_stdin.value="";
149       this.form.unsuspend.value = "";
150       this.form.unsuspend_stdin.value="";
151     '>
152   <LI>
153     <INPUT TYPE="button" VALUE="Just maintain directories (use with sysvshell or bsdshell)" onClick='
154       this.form.useradd.value = "cp -pr /etc/skel $dir; chown -R $uid.$gid $dir"; this.form.useradd_stdin.value = "";
155       this.form.usermod.value = "[ -d $old_dir ] && mv $old_dir $new_dir || ( chmod u+t $old_dir; mkdir $new_dir; cd $old_dir; find . -depth -print | cpio -pdm $new_dir; chmod u-t $new_dir; chown -R $new_uid.$new_gid $new_dir; rm -rf $old_dir )";
156       this.form.usermod_stdin.value = "";
157       this.form.userdel.value = "rm -rf $dir";
158       this.form.userdel_stdin.value="";
159       this.form.suspend.value = "";
160       this.form.suspend_stdin.value="";
161       this.form.unsuspend.value = "";
162       this.form.unsuspend_stdin.value="";
163     '>
164 </UL>
165
166 The following variables are available for interpolation (prefixed with new_ or
167 old_ for replace operations):
168 <UL>
169   <LI><code>$username</code>
170   <LI><code>$_password</code>
171   <LI><code>$quoted_password</code> - unencrypted password, already quoted for the shell (do not add additional quotes).
172   <LI><code>$crypt_password</code> - encrypted password.  When used on the command line (rather than STDIN), it will be quoted for the shell already (do not add additional quotes).
173   <LI><code>$ldap_password</code> - Password in LDAP/RFC2307 format (for example, "{PLAIN}himom", "{CRYPT}94pAVyK/4oIBk" or "{MD5}5426824942db4253f87a1009fd5d2d4").  When used on the command line (rather than STDIN), it will be quoted for the shell already (do not add additional quotes).
174   <LI><code>$uid</code>
175   <LI><code>$gid</code>
176   <LI><code>$finger</code> - GECOS.  When used on the command line (rather than STDIN), it will be quoted for the shell already (do not add additional quotes).
177   <LI><code>$first</code> - First name of GECOS.  When used on the command line (rather than STDIN), it will be quoted for the shell already (do not add additional quotes).
178   <LI><code>$last</code> - Last name of GECOS.  When used on the command line (rather than STDIN), it will be quoted for the shell already (do not add additional quotes).
179   <LI><code>$dir</code> - home directory
180   <LI><code>$shell</code>
181   <LI><code>$quota</code>
182   <LI><code>@radius_groups</code>
183   <LI><code>$reasonnum (when suspending)</code>
184   <LI><code>$reasontext (when suspending)</code>
185   <LI><code>$reasontypenum (when suspending)</code>
186   <LI><code>$reasontypetext (when suspending)</code>
187   <LI><code>$pkgnum</code>
188   <LI><code>$custnum</code>
189   <LI>All other fields in <b>svc_acct</b> are also available.
190   <LI>The following fields from <b>cust_main</b> are also available (except during replace): company, address1, address2, city, state, zip, county, daytime, night, fax, otaker, agent_custid, locale.  When used on the command line (rather than STDIN), they will be quoted for the shell already (do not add additional quotes).
191 </UL>
192 END
193 );
194
195 sub _groups_susp_reason_map { shift->_map('groups_susp_reason'); }
196
197 sub _map {
198   my $self = shift;
199   map { reverse(/^\s*(\S+)\s*(.*)\s*$/) } split("\n", $self->option(shift) );
200 }
201
202 sub rebless { shift; }
203
204 sub _export_insert {
205   my($self) = shift;
206   $self->_export_command('useradd', @_);
207 }
208
209 sub _export_delete {
210   my($self) = shift;
211   $self->_export_command('userdel', @_);
212 }
213
214 sub _export_suspend {
215   my($self) = shift;
216   $self->_export_command_or_super('suspend', @_);
217 }
218
219 sub _export_unsuspend {
220   my($self) = shift;
221   $self->_export_command_or_super('unsuspend', @_);
222 }
223
224 sub _export_command_or_super {
225   my($self, $action) = (shift, shift);
226   if ( $self->option($action) =~ /^\s*$/ ) {
227     my $method = "SUPER::_export_$action";
228     $self->$method(@_);
229   } else {
230     $self->_export_command($action, @_);
231   }
232 };
233
234 sub _export_command {
235   my ( $self, $action, $svc_acct) = (shift, shift, shift);
236   my $command = $self->option($action);
237   return '' if $command =~ /^\s*$/;
238   my $stdin = $self->option($action."_stdin");
239
240   no strict 'vars';
241   {
242     no strict 'refs';
243     ${$_} = $svc_acct->getfield($_) foreach $svc_acct->fields;
244
245     # snarfs are unused at this point?
246     # my $count = 1;
247     # foreach my $acct_snarf ( $svc_acct->acct_snarf ) {
248     #   ${"snarf_$_$count"} = shell_quote( $acct_snarf->get($_) )
249     #     foreach qw( machine username _password );
250     #   $count++;
251     # }
252   }
253
254   my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
255   if ( $cust_pkg ) {
256     no strict 'vars';
257     {
258       no strict 'refs';
259       foreach my $custf (qw( company address1 address2 city state zip country
260                              daytime night fax otaker agent_custid locale
261                         ))
262       {
263         ${$custf} = $cust_pkg->cust_main->$custf();
264       }
265     }
266     $email = ( grep { $_ !~ /^(POST|FAX)$/ } $cust_pkg->cust_main->invoicing_list )[0];
267   } else {
268     $email = '';
269   }
270
271   $finger =~ /^(.*)\s+(\S+)$/ or $finger =~ /^((.*))$/;
272   ($first, $last ) = ( $1, $2 );
273   $domain = $svc_acct->domain;
274
275   $quoted_password = shell_quote $_password;
276
277   $crypt_password = $svc_acct->crypt_password( $self->option('crypt') );
278   $ldap_password  = $svc_acct->ldap_password(  $self->option('crypt') );
279
280   @radius_groups = $svc_acct->radius_groups;
281
282   my ($reasonnum, $reasontext, $reasontypenum, $reasontypetext);
283   if ( $cust_pkg && $action eq 'suspend' &&
284        (my $r = $cust_pkg->last_reason('susp')) )
285   {
286     $reasonnum = $r->reasonnum;
287     $reasontext = $r->reason;
288     $reasontypenum = $r->reason_type;
289     $reasontypetext = $r->reasontype->type;
290
291     my %reasonmap = $self->_groups_susp_reason_map;
292     my $userspec = '';
293     $userspec = $reasonmap{$reasonnum}
294       if exists($reasonmap{$reasonnum});
295     $userspec = $reasonmap{$reasontext}
296       if (!$userspec && exists($reasonmap{$reasontext}));
297
298     my $suspend_user;
299     if ( $userspec =~ /^\d+$/ ) {
300       $suspend_user = qsearchs( 'svc_acct', { 'svcnum' => $userspec } );
301     } elsif ( $userspec =~ /^\S+\@\S+$/ ) {
302       my ($username,$domain) = split(/\@/, $userspec);
303       for my $user (qsearch( 'svc_acct', { 'username' => $username } )){
304         $suspend_user = $user if $userspec eq $user->email;
305       }
306     } elsif ($userspec) {
307       $suspend_user = qsearchs( 'svc_acct', { 'username' => $userspec } );
308     }
309
310     @radius_groups = $suspend_user->radius_groups
311       if $suspend_user;  
312
313   } else {
314     $reasonnum = $reasontext = $reasontypenum = $reasontypetext = '';
315   }
316
317   $pkgnum = $cust_pkg ? $cust_pkg->pkgnum : '';
318   $custnum = $cust_pkg ? $cust_pkg->custnum : '';
319
320   my $stdin_string = eval(qq("$stdin"));
321
322   $first = shell_quote $first;
323   $last = shell_quote $last;
324   $finger = shell_quote $finger;
325   $crypt_password = shell_quote $crypt_password;
326   $ldap_password  = shell_quote $ldap_password;
327
328   $company = shell_quote $company;
329   $address1 = shell_quote $address1;
330   $address2 = shell_quote $address2;
331   $city = shell_quote $city;
332   $state = shell_quote $state;
333   $zip = shell_quote $zip;
334   $country = shell_quote $country;
335   $daytime = shell_quote $daytime;
336   $night = shell_quote $night;
337   $fax = shell_quote $fax;
338   $otaker = shell_quote $otaker; 
339   $agent_custid = shell_quote $agent_custid;
340   $locale = shell_quote $locale;
341
342   my $command_string = eval(qq("$command"));
343
344   my @ssh_cmd_args = (
345     user          => $self->option('user') || 'root',
346     host          => $self->svc_machine($svc_acct),
347     command       => $command_string,
348     stdin_string  => $stdin_string,
349     ignored_errors    => $self->option('ignored_errors') || '',
350     ignore_all_errors => $self->option('ignore_all_errors'),
351     fail_on_output    => $self->option('fail_on_output'),
352  );
353
354   if($self->option($action . '_no_queue')) {
355     # discard return value just like freeside-queued.
356     eval { ssh_cmd(@ssh_cmd_args) };
357     $error = $@;
358     $error = $error->full_message if ref $error; # Exception::Class::Base
359     return $error. ' ('. $self->exporttype. ' to '. $self->svc_machine($svc_acct). ')'
360       if $error;
361   }
362   else {
363     $self->shellcommands_queue( $svc_acct->svcnum, @ssh_cmd_args );
364   }
365 }
366
367 sub _export_replace {
368   my($self, $new, $old ) = (shift, shift, shift);
369   my $command = $self->option('usermod');
370   return '' if $command =~ /^\s*$/;
371   my $stdin = $self->option('usermod_stdin');
372   no strict 'vars';
373   {
374     no strict 'refs';
375     ${"old_$_"} = $old->getfield($_) foreach $old->fields;
376     ${"new_$_"} = $new->getfield($_) foreach $new->fields;
377   }
378   my $old_cust_pkg = $old->cust_svc->cust_pkg;
379   my $new_cust_pkg = $new->cust_svc->cust_pkg;
380   my $new_cust_main = $new_cust_pkg ? $new_cust_pkg->cust_main : '';
381
382   $new_finger =~ /^(.*)\s+(\S+)$/ or $new_finger =~ /^((.*))$/;
383   ($new_first, $new_last ) = ( $1, $2 );
384   $quoted_new__password = shell_quote $new__password; #old, wrong?
385   $new_quoted_password = shell_quote $new__password; #new, better?
386   $old_domain = $old->domain;
387   $new_domain = $new->domain;
388
389   $new_crypt_password = $new->crypt_password( $self->option('crypt') );
390   $new_ldap_password  = $new->ldap_password(  $self->option('crypt') );
391
392   @old_radius_groups = $old->radius_groups;
393   @new_radius_groups = $new->radius_groups;
394
395   my $error = '';
396   if ( $self->option('usermod_pwonly') || $self->option('usermod_nousername') ){
397     if ( $old_username ne $new_username ) {
398       $error ||= "can't change username";
399     }
400   }
401   if ( $self->option('usermod_pwonly') ) {
402     if ( $old_domain ne $new_domain ) {
403       $error ||= "can't change domain";
404     }
405     if ( $old_uid != $new_uid ) {
406       $error ||= "can't change uid";
407     }
408     if ( $old_gid != $new_gid ) {
409       $error ||= "can't change gid";
410     }
411     if ( $old_dir ne $new_dir ) {
412       $error ||= "can't change dir";
413     }
414     #if ( join("\n", sort @old_radius_groups) ne
415     #     join("\n", sort @new_radius_groups)    ) {
416     #  $error ||= "can't change RADIUS groups";
417     #}
418   }
419   return $error. ' ('. $self->exporttype. ' to '. $self->svc_machine($new). ')'
420     if $error;
421
422   $new_agent_custid = $new_cust_main ? $new_cust_main->agent_custid : '';
423   $new_locale = $new_cust_main ? $new_cust_main->locale : '';
424   $old_pkgnum = $old_cust_pkg ? $old_cust_pkg->pkgnum : '';
425   $old_custnum = $old_cust_pkg ? $old_cust_pkg->custnum : '';
426   $new_pkgnum = $new_cust_pkg ? $new_cust_pkg->pkgnum : '';
427   $new_custnum = $new_cust_pkg ? $new_cust_pkg->custnum : '';
428
429   my $stdin_string = eval(qq("$stdin"));
430
431   $new_first = shell_quote $new_first;
432   $new_last = shell_quote $new_last;
433   $new_finger = shell_quote $new_finger;
434   $new_crypt_password = shell_quote $new_crypt_password;
435   $new_ldap_password  = shell_quote $new_ldap_password;
436   $new_agent_custid = shell_quote $new_agent_custid;
437   $new_locale = shell_quote $new_locale;
438
439   my $command_string = eval(qq("$command"));
440
441   my @ssh_cmd_args = (
442     user          => $self->option('user') || 'root',
443     host          => $self->svc_machine($new),
444     command       => $command_string,
445     stdin_string  => $stdin_string,
446     ignored_errors    => $self->option('ignored_errors') || '',
447     ignore_all_errors => $self->option('ignore_all_errors'),
448     fail_on_output    => $self->option('fail_on_output'),
449   );
450
451   if($self->option('usermod_no_queue')) {
452     # discard return value just like freeside-queued.
453     eval { ssh_cmd(@ssh_cmd_args) };
454     $error = $@;
455     $error = $error->full_message if ref $error; # Exception::Class::Base
456     return $error. ' ('. $self->exporttype. ' to '. $self->svc_machine($new). ')'
457       if $error;
458   }
459   else {
460     $self->shellcommands_queue( $new->svcnum, @ssh_cmd_args );
461   }
462 }
463
464 #a good idea to queue anything that could fail or take any time
465 sub shellcommands_queue {
466   my( $self, $svcnum ) = (shift, shift);
467   my $queue = new FS::queue {
468     'svcnum' => $svcnum,
469     'job'    => "FS::part_export::shellcommands::ssh_cmd",
470   };
471   $queue->insert( @_ );
472 }
473
474 sub ssh_cmd { #subroutine, not method
475   use Net::OpenSSH;
476   my $opt = { @_ };
477   open my $def_in, '<', '/dev/null' or die "unable to open /dev/null\n";
478   my $ssh = Net::OpenSSH->new(
479     $opt->{'user'}.'@'.$opt->{'host'},
480     'default_stdin_fh' => $def_in
481   );
482   # ignore_all_errors doesn't override SSH connection/auth errors--
483   # probably correct
484   die "Couldn't establish SSH connection: ". $ssh->error if $ssh->error;
485
486   my $ssh_opt = {};
487   $ssh_opt->{'stdin_data'} = $opt->{'stdin_string'}
488     if exists($opt->{'stdin_string'}) and length($opt->{'stdin_string'});
489
490   my ($output, $errput) = $ssh->capture2($ssh_opt, $opt->{'command'});
491
492   return if $opt->{'ignore_all_errors'};
493   #die "Error running SSH command: ". $ssh->error if $ssh->error;
494
495   if ( ($output || $errput)
496        && $opt->{'ignored_errors'} && length($opt->{'ignored_errors'})
497   ) {
498     my @ignored_errors = split('\n',$opt->{'ignored_errors'});
499     foreach my $ignored_error ( @ignored_errors ) {
500         $output =~ s/$ignored_error//g;
501         $errput =~ s/$ignored_error//g;
502     }
503     $output =~ s/[\s\n]//g;
504     $errput =~ s/[\s\n]//g;
505   }
506
507   die (($errput || $ssh->error). "\n") if $errput || $ssh->error; 
508   #die "$errput\n" if $errput;
509
510   die "$output\n" if $output and $opt->{'fail_on_output'};
511   '';
512 }
513
514 #sub shellcommands_insert { #subroutine, not method
515 #}
516 #sub shellcommands_replace { #subroutine, not method
517 #}
518 #sub shellcommands_delete { #subroutine, not method
519 #}
520
521 sub _upgrade_exporttype {
522   my $class = shift;
523   $class =~ /^FS::part_export::(\w+)$/;
524   foreach my $self ( qsearch('part_export', { 'exporttype' => $1 }) ) {
525     my %options = $self->options;
526     my $changed = 0;
527     # 2011-12-13 - 2012-02-16: ignore_all_output option
528     if ( $options{'ignore_all_output'} ) {
529       # ignoring STDOUT is now the default
530       $options{'ignore_all_errors'} = 1;
531       delete $options{'ignore_all_output'};
532       $changed++;
533     }
534     my $error = $self->replace(%options) if $changed;
535     die $error if $error;
536   }
537 }
538
539 1;
540