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