api.cgi 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/local/cpanel/3rdparty/bin/perl
  2. #ACLS:all
  3. package Troglodyne::CGI::API;
  4. use strict;
  5. use warnings;
  6. use Cpanel::LoadModule::Custom ();
  7. use JSON::XS ();
  8. exit run() unless caller();
  9. sub run {
  10. # Load up CGI processing modules
  11. Cpanel::LoadModule::Custom::load_perl_module("Troglodyne::CGI");
  12. my $ret = { 'metadata' => {} };
  13. # Process the args
  14. my $args;
  15. my $err;
  16. {
  17. local $@;
  18. eval { $args = Troglodyne::CGI::get_args() };
  19. $err = $@;
  20. }
  21. if(!$args || !scalar(keys(%$args))) {
  22. $ret->{'result'} = 0;
  23. $ret->{'error'} = "No args detected! $err";
  24. return emit($ret);
  25. }
  26. $err = '';
  27. $ret->{'metadata'}{'input_args'} = $args;
  28. # XXX Validation plz
  29. # Load route code
  30. my $namespace = "Troglodyne::API::$args->{'module'}";
  31. my ( $loaded, $coderef );
  32. {
  33. local $@;
  34. $loaded = eval {
  35. Cpanel::LoadModule::Custom::load_perl_module($namespace);
  36. };
  37. $err = $@;
  38. $coderef = $namespace->can($args->{'function'});
  39. }
  40. # Get back the datastruct from the called module.
  41. # Yeah, yeah, I know. String eval. XXX
  42. if( $loaded && $coderef ) {
  43. local $@;
  44. my $data = eval { $coderef->($args) };
  45. my $error = $@;
  46. if($data) {
  47. $ret->{'data'} = $data;
  48. $ret->{'result'} = 1;
  49. } else {
  50. $ret->{'result'} = 0;
  51. $ret->{'error'} = $error;
  52. }
  53. } elsif( !$coderef ) {
  54. $ret->{'error'} = "No such function '$args->{'function'}' in $namespace";
  55. $ret->{'result'} = 0;
  56. } else {
  57. $ret->{'error'} = $err;
  58. $ret->{'result'} = 0;
  59. }
  60. return emit($ret);
  61. }
  62. sub emit {
  63. print "Content-type: application/json\r\n\r\n";
  64. print JSON::XS::encode_json($_[0]);
  65. return 0;
  66. }
  67. 1;