summaryrefslogtreecommitdiff
path: root/lib/Kolab/Utils/DAVLogger.php
blob: c1c3067c245beed6fef3e6872a969a1e4ed04085 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<?php

/**
 * Utility class logging DAV requests
 *
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 *
 * Copyright (C) 2013, Kolab Systems AG <contact@kolabsys.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

namespace Kolab\Utils;

use \rcube;
use Sabre\DAV;
use Kolab\DAV\Auth\HTTPBasic;


/**
 * Utility class to log debug information about processed DAV requests
 */
class DAVLogger extends DAV\ServerPlugin
{
    const CONSOLE = 1;
    const HTTP_REQUEST = 2;
    const HTTP_RESPONSE = 4;

    private $rcube;
    private $server;
    private $method;
    private $loglevel;


    /**
     * Default constructor
     */
    public function __construct($level = 1)
    {
        $this->rcube = rcube::get_instance();
        $this->loglevel = $level;
    }

    /**
     * This initializes the plugin.
     * This method should set up the required event subscriptions.
     *
     * @param Server $server
     */
    public function initialize(DAV\Server $server)
    {
        $this->server = $server;

        $server->subscribeEvent('beforeMethod', array($this, '_beforeMethod'), 15);
        $server->subscribeEvent('exception', array($this, '_exception'));
        $server->subscribeEvent('exit', array($this, '_exit'));

        // replace $server->httpResponse with a derived class that can do logging
        $server->httpResponse = new HTTPResponse();
   }

    /**
     * Handler for 'beforeMethod' events
     */
    public function _beforeMethod($method, $uri)
    {
        $this->method = $method;

        // turn on per-user http logging if the destination file exists
        if ($this->loglevel < 2 && $this->rcube->config->get('kolabdav_user_debug', false)
            && ($log_dir = $this->user_log_dir()) && file_exists($log_dir . '/httpraw')) {
            $this->loglevel |= (self::HTTP_REQUEST | self::HTTP_RESPONSE);
        }

        // log full HTTP request data
        if ($this->loglevel & self::HTTP_REQUEST) {
            $request = $this->server->httpRequest;
            $content_type = $request->getHeader('CONTENT_TYPE');
            if (strpos($content_type, 'text/') === 0 || strpos($content_type, 'application/xml') === 0) {
                $http_body = $request->getBody(true);

                // Hack for reading php:://input because that stream can only be read once.
                // This is why we re-populate the request body with the existing data.
                $request->setBody($http_body);
            }
            else if (!empty($content_type)) {
                $http_body = '[binary data]';
            }

            // catch all headers
            $http_headers = array();
            foreach (apache_request_headers() as $hdr => $value) {
                if (strtolower($hdr) == 'authorization') {
                    $method = preg_match('/^((basic|digest)\s+)/i', $value, $m) ? $m[1] : '';
                    $value = $method . str_repeat('*', strlen($value) - strlen($method));
                }
                $http_headers[$hdr] = "$hdr: $value";
            }

            $this->write_log('httpraw', $request->getMethod() . ' ' . $request->getUri() . ' ' . $_SERVER['SERVER_PROTOCOL'] . "\n" .
               join("\n", $http_headers) . "\n\n" . $http_body);
        }

        // log to console
        if ($this->loglevel & self::CONSOLE) {
           $this->write_log('console', $method . ' ' . $uri);
        }
    }

    /**
     * Handler for 'exception' events
     */
    public function _exception($e)
    {
        // log to console
        $this->console(get_class($e) . ' (EXCEPTION)', $e->getMessage() /*, $e->getTraceAsString()*/);
    }

    /**
     * Handler for 'exit' events
     */
    public function _exit()
    {
        if ($this->loglevel & self::CONSOLE) {
            $time = microtime(true) - KOLAB_DAV_START;

            if (function_exists('memory_get_usage'))
               $mem = round(memory_get_usage() / 1024 / 1024, 1) . 'MB';
            if (function_exists('memory_get_peak_usage'))
               $mem .= '/' . round(memory_get_peak_usage() / 1024 / 1024, 1) . 'MB';

            $this->write_log('console', sprintf("/%s: %0.4f sec; %s", $this->method, $time, $mem));
        }

        // log full HTTP reponse
        if ($this->loglevel & self::HTTP_RESPONSE) {
            $this->write_log('httpraw', "RESPONSE: " . $this->server->httpResponse->dump());
        }
    }

    /**
     * Wrapper for rcube::cosole() to write per-user logs
     */
    public function console(/* ... */)
    {
        if ($this->loglevel & self::CONSOLE) {
            $msg = array();
            foreach (func_get_args() as $arg) {
                $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
            }

            $this->write_log('console', join(";\n", $msg));
        }
    }

    /**
     * Wrapper for rcube::write_log() that can write per-user logs
     */
    public function write_log($filename, $msg)
    {
        // dump data per user
        if ($this->rcube->config->get('kolabdav_user_debug', false)) {
            if ($this->user_log_dir()) {
               $filename = HTTPBasic::$current_user . '/' . $filename;
            }
            else {
               return;  // don't log
            }
        }

        rcube::write_log($filename, $msg);
    }

    /**
     * Get the per-user log directory
     */
    private function user_log_dir()
    {
        $log_dir = $this->rcube->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs');
        $user_log_dir = $log_dir . '/' . HTTPBasic::$current_user;

        return HTTPBasic::$current_user && is_writable($user_log_dir) ? $user_log_dir : false;
    }
}