Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

backup nextcloud v2 #2289

Merged
merged 2 commits into from
Apr 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
270 changes: 270 additions & 0 deletions src/opnsense/mvc/app/library/OPNsense/Backup/Nextcloud.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
<?php
/**
* Copyright (C) 2018 Deciso B.V.
* Copyright (C) 2018 Fabian Franz
*
* 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.
*
* THIS SOFTWARE IS PROVIDED ``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
* AUTHOR 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.
*
*/

namespace OPNsense\Backup;

use OPNsense\Core\Config;
use OPNsense\Backup\NextcloudSettings;

/**
* Class Nextcloud backup
* @package OPNsense\Backup
*/
class Nextcloud extends Base implements IBackupProvider
{

/**
* get required (user interface) fields for backup connector
* @return array configuration fields, types and description
*/
public function getConfigurationFields()
{
$fields = array(
array(
"name" => "nextcloud_enabled",
"type" => "checkbox",
"label" => gettext("Enable"),
"value" => null
),
array(
"name" => "nextcloud_url",
"type" => "text",
"label" => gettext("URL"),
"help" => gettext("The Base URL to Nextcloud. For example: https://cloud.example.com"),
"value" => null
),
array(
"name" => "nextcloud_user",
"type" => "text",
"label" => gettext("User Name"),
"help" => gettext("The name you use for logging into your Nextcloud account"),
"value" => null
),
array(
"name" => "nextcloud_password",
"type" => "password",
"label" => gettext("Password"),
"help" => gettext("The app password which has been generated for you"),
"value" => null
),
array(
"name" => "nextcloud_backupdir",
"type" => "text",
"label" => gettext("Directory Name"),
"value" => 'OPNsense-Backup'
)
);
$cnf = Config::getInstance();
if ($cnf->isValid()) {
$config = $cnf->object();
foreach ($fields as &$field) {
$fieldname = $field['name'];
if (isset($config->OPNsense->system->backup->nextcloud->$fieldname)) {
$field['value'] = (string)$config->OPNsense->system->backup->nextcloud->$fieldname;
}
}
}

return $fields;
}

/**
* backup provider name
* @return string user friendly name
*/
public function getName()
{
return gettext("Nextcloud");
}

/**
* validate and set configuration
* @param array $conf configuration array
* @return array of validation errors when not saved
*/
public function setConfiguration($conf)
{
$nextcloud = new NextcloudSettings();
$unprefixed = array();
foreach ($_POST as $postkey => $postvalue) {
if(stripos($postkey, 'Nextcloud_') === 0) {
$unprefixed[str_replace( 'Nextcloud_' , '' , $postkey)] = $postvalue;
}
}
if (!isset($unprefixed['nextcloud_enabled'])) {
$unprefixed['nextcloud_enabled'] = '0';
} else {
$unprefixed['nextcloud_enabled'] = $unprefixed['nextcloud_enabled'] == 'on' ? '1' : '0';
}
$nextcloud->setNodes($unprefixed);
$validation_messages = $nextcloud->performValidation();

if ($validation_messages->count() == 0) {
$nextcloud->serializeToConfig();
Config::getInstance()->save();
}
// convert validation data to array
$validation_messages2 = array();
foreach ($validation_messages as $validation_message) {
$validation_messages2[] = $validation_message;
}
return $validation_messages2;
}

/**
* @return array filelist
*/
function backup() {
$cnf = Config::getInstance();
$nextcloud = new NextcloudSettings();
if ($cnf->isValid()) {
$config = $cnf->object();
if ($nextcloud->nextcloud_enabled == true) {
$url = (string)$nextcloud->nextcloud_url;
$username = (string)$nextcloud->nextcloud_user;
$password = (string)$nextcloud->nextcloud_password;
$backupdir = (string)$nextcloud->nextcloud_backupdir;
$hostname = $config->system->hostname . '.' .$config->system->domain;
$configname = 'config-' . $hostname . '-' . date("Y-m-d_h:m:s") . '.xml';
// backup source data to local strings (plain/encrypted)
$confdata = file_get_contents('/conf/config.xml');
$confdata_enc = chunk_split(
$this->encrypt($confdata, (string)$nextcloud->nextcloud_password)
);
try {
$directories = $this->listFiles($url, $username, $password, '/');
if (!in_array("/$backupdir/", $directories)) {
$this->create_directory($url, $username, $password, $backupdir);
}
$this->upload_file_content(
$url,
$username,
$password,
$backupdir,
$configname,
$confdata_enc);
// do not list directories
return array_filter(
$this->listFiles($url, $username, $password, "/$backupdir/", false),
function ($filename){
return (substr($filename, -1) !== '/');
}
);
} catch (\Exception $e) {
return array();
}
}
}
}
public function listFiles($url, $username, $password, $directory = '/', $only_dirs=true) {
$result = $this->curl_request(
"$url/remote.php/dav/files/$username$directory",
$username,
$password,
'PROPFIND',
"Error while fetching filelist from Nextcloud");
// workaround - simplexml seems to be broken when using namespaces - remove them.
$xml = simplexml_load_string(str_replace( ['<d:', '</d:'], ['<', '</'] , $result['response']));
$ret = array();
foreach ($xml->children() as $response)
{
// d:response
if ($response->getName() == 'response') {
$fileurl = (string)$response->href;
$dirname = explode( "/remote.php/dav/files/$username", $fileurl,2)[1];
if ($response->propstat->prop->resourcetype->children()->count() > 0 &&
$response->propstat->prop->resourcetype->children()[0]->getName() == 'collection' &&
$only_dirs)
{
$ret[] = $dirname;
} elseif(!$only_dirs) {
$ret[] = $dirname;
}
}
}
return $ret;
}
public function upload_file_content($url, $username, $password, $backupdir, $filename, $local_file_content) {
$this->curl_request(
$url . "/remote.php/dav/files/$username/$backupdir/$filename",
$username,
$password,
'PUT',
'cannot execute PUT',
$local_file_content
);
}
public function create_directory($url, $username, $password, $backupdir) {
$this->curl_request($url . "/remote.php/dav/files/$username/$backupdir",
$username,
$password,
'MKCOL',
'cannot execute MKCOL');
}
public function curl_request($url, $username, $password, $method, $error_message, $postdata = null) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => $method, // Create a file in WebDAV is PUT
CURLOPT_RETURNTRANSFER => true, // Do not output the data to STDOUT
CURLOPT_VERBOSE => 0, // same here
CURLOPT_MAXREDIRS => 0, // no redirects
CURLOPT_TIMEOUT => 60, // maximum time: 1 min
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_USERPWD => $username . ":" . $password,
CURLOPT_HTTPHEADER => array(
"User-Agent: OPNsense Firewall"
)
));
if ($postdata != null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
}
$response = curl_exec($curl);
$err = curl_error($curl);
$info = curl_getinfo($curl);
if (!($info['http_code'] == 200 || $info['http_code'] == 207 || $info['http_code'] == 201) || $err) {
syslog(LOG_ERR, $error_message);
syslog(LOG_ERR,json_encode($info));
throw new \Exception();
}
curl_close($curl);
return array('response' => $response, 'info' => $info);
}

/**
* Is this provider enabled
* @return boolean enabled status
*/
public function isEnabled()
{
$nextcloud = new NextcloudSettings();
return $nextcloud->nextcloud_enabled == true;
}
}
39 changes: 39 additions & 0 deletions src/opnsense/mvc/app/models/OPNsense/Backup/NextcloudSettings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
/**
* Copyright (C) 2018 Fabian Franz
*
* 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.
*
* THIS SOFTWARE IS PROVIDED ``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
* AUTHOR 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.
*
*/
namespace OPNsense\Backup;

use OPNsense\Base\BaseModel;

/**
* Class Nextcloud
* @package Backup
*/
class NextcloudSettings extends BaseModel
{
}
35 changes: 35 additions & 0 deletions src/opnsense/mvc/app/models/OPNsense/Backup/NextcloudSettings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<model>
<mount>//system/backup/nextcloud</mount>
<version>1.0.0</version>
<description>
OPNsense Nextcloud Backup Settings
</description>
<items>
<nextcloud_enabled type="BooleanField">
<default>N</default>
<Required>Y</Required>
</nextcloud_enabled>
<nextcloud_url type="TextField">
<Required>Y</Required>
<multiple>N</multiple>
<ValidationMessage>An URL for the Nextcloud server must be set.</ValidationMessage>
</nextcloud_url>
<nextcloud_user type="TextField">
<Required>Y</Required>
<multiple>N</multiple>
<ValidationMessage>An user for the Nextcloud server must be set.</ValidationMessage>
</nextcloud_user>
<nextcloud_password type="TextField">
<Required>Y</Required>
<multiple>N</multiple>
<ValidationMessage>A password for a Nextcloud server must be set.</ValidationMessage>
</nextcloud_password>
<nextcloud_backupdir type="TextField">
<Required>Y</Required>
<multiple>N</multiple>
<mask>/[a-z0-9\-]+/i</mask>
<default>OPNsense-Backup</default>
<ValidationMessage>The Backup Directory can only consist of alphanumeric characters.</ValidationMessage>
</nextcloud_backupdir>
</items>
</model>