# Copyright (c) 2025, Daily Data, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list
#    of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this
#    list of conditions and the following disclaimer in the documentation and/or other
#    materials provided with the distribution.
# 3. Neither the name of Daily Data, Inc. nor the names of its contributors may be
#    used to endorse or promote products derived from this software without specific
#    prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# Library to interface with the OPNsense API
# Provides methods to interact with OPNsense routers via their API.
#
# Change History:
#  v1.0.0 2025-10-01 - RWR
#    Initial version
#  v1.0.1 2025-10-07 - RWR
#    Fixed bug where script was looking for localport, but was localPort
#    Fixed bug where not all users were returned because opnSense (v24.7)
#       does not send the username, it sends the description. Possible
#       programming error, but quick fix is to use username, then description


package opnsense;
use strict;
use warnings;

use LWP::UserAgent;
use JSON;
use Data::Dumper;
use XML::Simple;

our $VERSION = "1.0.0";

our $useCurl = 1; # set to 1 to use curl for API requests, 0 to use LWP
our $debug = 0;    # set to 1 for debug output

#-----------------------------
# new: Constructor
#-----------------------------
sub new {
   my ($class, %args) = @_;
   my $self = {
      baseUrl   => $args{url},
      apiKey    => $args{apiKey},
      apiSecret => $args{apiSecret},
      ovpnIndex => $args{ovpnIndex},
      template  => $args{template},
      hostname  => $args{hostname},
      localPort => $args{localPort},
      ua        => $useCurl ?
         'curl -s --insecure' :
         LWP::UserAgent->new(
            ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0 }
         ),
   };
   bless $self, $class;
   return $self;
}

#-----------------------------
# apiRequest: API request dispatcher
#-----------------------------
sub apiRequest {

   if ($useCurl) {
       return apiRequestCurl(@_);
   } else {
       return apiRequestLwp(@_);
   }
}

#-----------------------------
# apiRequestCurl: API request using curl
#-----------------------------
sub apiRequestCurl {
   my ($self, $endpoint, $method, $data) = @_;
   $method ||= 'GET';
   my $url = $self->{baseUrl} . $endpoint;

   my @data = ();
   push @data, '--request', $method;
   push @data, "--header 'Content-Type: application/json'" if ( $method eq 'POST' || $method eq 'PUT' );
   push @data, "--user '$self->{apiKey}:$self->{apiSecret}'";
   push @data, "--data '" . encode_json($data) . "'" if $data;
   my $cmd = join(' ', $self->{ua}, @data, $url);
   die "In apiRequestCurl, command is:\n $cmd" if $debug;
   my $json_text = `$cmd`;
   if ( $json_text =~ /<\?xml/) {
      # returned an XML string, just send it
      return $json_text;
   }
   return decode_json($json_text);
}


#-----------------------------
# apiRequestLwp: API request using LWP
#-----------------------------
sub apiRequestLwp {
    my ($self, $endpoint, $method, $data) = @_;
    $method ||= 'GET';
    my $url = $self->{baseUrl} . $endpoint;
    my $req = HTTP::Request->new($method => $url);
    $req->header('Content-Type' => 'application/json');
    $req->header('Authorization' => 'key ' . $self->{apiKey} . ':' . $self->{apiSecret});
    die "In apiRequestLwp, request object:\n" . Dumper($req);
    $req->content(encode_json($data)) if $data;
    my $res = $self->{ua}->request($req);
    return decode_json($res->decoded_content) if $res->is_success;
    die "API request failed: " . $res->status_line;

}

#-----------------------------
# getVpnUsers: get VPN users
#-----------------------------
sub getVpnUsers {
    my ($self) = @_;
    my $return = {};
    my $endpoint = "/api/openvpn/export/accounts/$self->{ovpnIndex}";
    my $users = $self->apiRequest($endpoint);
    #print "In get_vpn_users, users object:\n" . Dumper($users); die;
    foreach my $user ( keys %$users ) {
      next unless $user;
      # the username can be in the array users (preferable) or in the description
      my $username = ($users->{$user}->{'users'}->[0] ? $users->{$user}->{'users'}->[0] : $users->{$user}->{'description'} );
      # we do not allow usernames with spaces in our setup
      next if $username =~ m/ /;
#         $user && 
#         $users->{$user}->{'users'} &&
#         ref($users->{$user}->{'users'}) eq 'ARRAY'
#         && @{$users->{$user}->{'users'}} > 0;
         # only return the first user in the array
      $return->{$user} = $username;
    }
#    print "In get_vpn_users, return object:\n" . Dumper($return); die;
    return $return;
}

#-----------------------------
# getAllUsers: get all users on the system
#-----------------------------
# returns a hashref keyed by username, value is the user object
# The api is seriously broken. It is supposed to be /api/system/user, but that returns an error
# so, we download the entire config and extract the users from there
sub getAllUsers {
    my ($self) = @_;
    my $endpoint = "/api/core/backup/download/this";
    my $xml = XML::Simple->new();
    my $data = $self->apiRequest($endpoint);
    my $config = $xml->XMLin($data);
    my $return = {};
    if (ref($config->{system}->{user}) eq 'ARRAY') {
        foreach my $user (@{$config->{system}->{user}}) {
            $return->{$user->{name}} = $user;
        }
    } elsif (ref($config->{system}->{user}) eq 'HASH') {
        $return = $config->{system}->{user};
    }
    return $return;
}

#-----------------------------
# getVpnProviders: get VPN providers
#-----------------------------
sub getVpnProviders {
   my ($self) = @_;
   my $endpoint = "/api/openvpn/export/providers";
   my $return = {};
   my $providers = $self->apiRequest($endpoint);
   #die "In getVPNProviders, providers object:\n" . Dumper($providers);
   return $return unless
      ref($providers) eq 'HASH' && keys %$providers;
    # key by vpnid, value is name
   foreach my $provider ( keys %$providers ) {
       $return->{$providers->{$provider}->{'vpnid'}} = $providers->{$provider}->{'name'};
    }
   return $return; 
}

#-----------------------------
# getVpnConfig: get VPN configuration file
#-----------------------------
sub getVpnConfig {
   my ( $self, $cert ) = @_;
   my $endpoint = "/api/openvpn/export/download/$self->{ovpnIndex}/$cert";
   my $payload = ();
   $payload->{'openvpn_export'} = {
       validate_server_cn => 1,
       hostname => $self->{hostname},
       template => $self->{template},
       auth_nocache => 0,
       p12_password_confirm => "",
       random_local_port => 1,
       servers => "\"1\"",
       plain_config => "",
       p12_password => "",
       local_port => $self->{localPort},
       cryptoapi => 0
   };
   $debug = 0;
   my $return = $self->apiRequest($endpoint, 'POST', $payload);
   return $return;
}


1;
