#!/usr/bin/php
<?php
/*
* Daily cron script to backup the monowall hardware router
* The program requests the monowall webgui for the configuration
* XML file, used for settings and backup/restore.
*
* Written by Kaspar Lyngsie <backupmonowall(a)pacroon.dk>
* Non-standard port variable by Stefan Onderka <stefan(a)onderka.com> 
*/

/* Change these settings to reflect your setup! */
$username "admin";
$password "mono";
$m0n0wall_url "https://192.168.1.1";
$m0n0wall_port "8080";
$targetpath "/data/backup/router/";

function 
post($data$url$username$password$timeout=30$m0n0wall_port) {

        
$url_array parse_url($url);
        
$query "";

        foreach (
$data as $key => $value) {
                if (
$query$query .= "&";
                
$query .= $key "=" urlencode($value);
        }

        
$len strlen($query);

        
$headers =
        
"POST " $url_array['path'] . "?" $url_array['query'] . " HTTP/1.1\r\n".
        
"Host: {$url_array['host']}\r\n".
        
"User-Agent: PHP/" phpversion() . "\r\n" .
        
"Authorization: Basic " base64_encode("{$username}:{$password}") . "\r\n" .
        
"Content-Type: application/x-www-form-urlencoded\r\n".
        
"Content-Length: $len\r\n\r\n" $query;

        if (
$url_array['scheme'] == "https")
                
$socket fsockopen("ssl://" $url_array['host'], $m0n0wall_port$errno$errstr$timeout);
        else
                
$socket fsockopen($url_array['host'], $m0n0wall_port$errno$errstr$timeout);

        if (!
$socket) {
                return 
false;
        } else {
                
fputs($socket$headers);

                
$header $body "";
                
$isbody false;

                while (!
feof($socket)) {
                        
$line fgets($socket);

                        if (
$line == "\r\n") {
                                if (!
$isbody) {
                                        
$isbody true;
                                        continue;
                                }
                        }

                        if (
$isbody)
                                
$body .= $line;
                        else
                                
$header .= $line;
                }

                return array(
$header,$body);
        }
}

$data = array("Submit" => "Download configuration");

list(
$header,$body) = post($data"{$m0n0wall_url}/diag_backup.php"$username$password60$m0n0wall_port);

preg_match("/filename=(.+?)\r\n/i"$header$filename);

$fd fopen($targetpath "/" $filename[1], "w");
fwrite($fd$body);
fclose($fd);
?>