summaryrefslogtreecommitdiff
path: root/lib/ext/Syncroton/Server.php
blob: e89b0fe1a034e0889ebdffeb1da4f991ee4a82fb (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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
<?php
/**
 * Syncroton
 *
 * @package     Syncroton
 * @license     http://www.tine20.org/licenses/lgpl.html LGPL Version 3
 * @copyright   Copyright (c) 2009-2012 Metaways Infosystems GmbH (http://www.metaways.de)
 * @author      Lars Kneschke <l.kneschke@metaways.de>
 */

/**
 * class to handle incoming http ActiveSync requests
 * 
 * @package     Syncroton
 */
class Syncroton_Server
{
    const PARAMETER_ATTACHMENTNAME = 0;
    const PARAMETER_COLLECTIONID   = 1;
    const PARAMETER_ITEMID         = 3;
    const PARAMETER_OPTIONS        = 7;
    
    protected $_body;
    
    /**
     * informations about the currently device
     *
     * @var Syncroton_Backend_IDevice
     */
    protected $_deviceBackend;
    
    /**
     * @var Zend_Log
     */
    protected $_logger;
    
    /**
     * @var Zend_Controller_Request_Http
     */
    protected $_request;
    
    protected $_userId;
    
    public function __construct($userId, Zend_Controller_Request_Http $request = null, $body = null)
    {
        if (Syncroton_Registry::isRegistered('loggerBackend')) {
            $this->_logger = Syncroton_Registry::get('loggerBackend');
        }
        
        $this->_userId  = $userId;
        $this->_request = $request instanceof Zend_Controller_Request_Http ? $request : new Zend_Controller_Request_Http();
        $this->_body    = $body !== null ? $body : fopen('php://input', 'r');
        
        $this->_deviceBackend = Syncroton_Registry::getDeviceBackend();
        
    }
        
    public function handle()
    {
        if ($this->_logger instanceof Zend_Log)
            $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' REQUEST METHOD: ' . $this->_request->getMethod());
        
        switch($this->_request->getMethod()) {
            case 'OPTIONS':
                $this->_handleOptions();
                break;
        
            case 'POST':
                $this->_handlePost();
                break;
        
            case 'GET':
                echo "It works!<br>Your userid is: {$this->_userId} and your IP address is: {$_SERVER['REMOTE_ADDR']}.";
                break;
        }
    }
    
    /**
     * handle options request
     */
    protected function _handleOptions()
    {
        $command = new Syncroton_Command_Options();
    
        $this->_sendHeaders($command->getHeaders());
    }
    
    protected function _sendHeaders(array $headers)
    {
        foreach ($headers as $name => $value) {
            header($name . ': ' . $value);
        }
    } 
    
    /**
     * handle post request
     */
    protected function _handlePost()
    {
        $requestParameters = $this->_getRequestParameters($this->_request);
        
        if ($this->_logger instanceof Zend_Log) 
            $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' REQUEST ' . print_r($requestParameters, true));
        
        $className = 'Syncroton_Command_' . $requestParameters['command'];
        
        if(!class_exists($className)) {
            if ($this->_logger instanceof Zend_Log)
                $this->_logger->crit(__METHOD__ . '::' . __LINE__ . " command not supported: " . $requestParameters['command']);
            
            header("HTTP/1.1 501 not implemented");
            
            return;
        }
        
        // get user device
        $device = $this->_getUserDevice($this->_userId, $requestParameters);
        
        if ($requestParameters['contentType'] == 'application/vnd.ms-sync.wbxml' || $requestParameters['contentType'] == 'application/vnd.ms-sync') {
            // decode wbxml request
            try {
                $decoder = new Syncroton_Wbxml_Decoder($this->_body);
                $requestBody = $decoder->decode();
                if ($this->_logger instanceof Zend_Log) {
                    $requestBody->formatOutput = true;
                    $this->_logger->debug(__METHOD__ . '::' . __LINE__ . " xml request:\n" . $requestBody->saveXML());
                }
            } catch(Syncroton_Wbxml_Exception_UnexpectedEndOfFile $e) {
                $requestBody = NULL;
            }
        } else {
            $requestBody = $this->_body;
        }
        
        header("MS-Server-ActiveSync: 14.00.0536.000");

        // avoid sending HTTP header "Content-Type: text/html" for empty sync responses
        ini_set('default_mimetype', 'application/vnd.ms-sync.wbxml');
        
        try {
            $command = new $className($requestBody, $device, $requestParameters);
        
            $command->handle();
        
            $response = $command->getResponse();
            
        } catch (Syncroton_Exception_ProvisioningNeeded $sepn) {
            if ($this->_logger instanceof Zend_Log) 
                $this->_logger->info(__METHOD__ . '::' . __LINE__ . " provisioning needed");
            
            header("HTTP/1.1 449 Retry after sending a PROVISION command");
            
            if (version_compare($device->acsversion, '14.0', '>=')) {
                $response = $sepn->domDocument;
            } else {
                // pre 14.0 method
                return;
            }
            
        } catch (Exception $e) {
            if ($this->_logger instanceof Zend_Log)
                $this->_logger->crit(__METHOD__ . '::' . __LINE__ . " unexpected exception occured: " . get_class($e));
            if ($this->_logger instanceof Zend_Log)
                $this->_logger->crit(__METHOD__ . '::' . __LINE__ . " exception message: " . $e->getMessage());
            if ($this->_logger instanceof Zend_Log)
                $this->_logger->crit(__METHOD__ . '::' . __LINE__ . " " . $e->getTraceAsString());
            
            header("HTTP/1.1 500 Internal server error");
            
            return;
        }
        
        if ($response instanceof DOMDocument) {
            if ($this->_logger instanceof Zend_Log) {
                $this->_logDomDocument(Zend_Log::DEBUG, $response, __METHOD__, __LINE__);
            }
            
            if (isset($command) && $command instanceof Syncroton_Command_ICommand) {
                $this->_sendHeaders($command->getHeaders());
            }
            
            $outputStream = fopen("php://temp", 'r+');
            
            $encoder = new Syncroton_Wbxml_Encoder($outputStream, 'UTF-8', 3);
            
            try {
                 $encoder->encode($response);
            } catch (Syncroton_Wbxml_Exception $swe) {
                if ($this->_logger instanceof Zend_Log) {
                    $this->_logger->err(__METHOD__ . '::' . __LINE__ . " Could not encode output: " . $swe);
                    $this->_logDomDocument(Zend_Log::ERR, $response, __METHOD__, __LINE__);
                }
                
                header("HTTP/1.1 500 Internal server error");
                
                return;
            }
            
            if ($requestParameters['acceptMultipart'] == true) {
                $parts = $command->getParts();
                
                // output multipartheader
                $bodyPartCount = 1 + count($parts);
                
                // number of parts (4 bytes)
                $header  = pack('i', $bodyPartCount);
                
                $partOffset = 4 + (($bodyPartCount * 2) * 4);
                
                // wbxml body start and length
                $streamStat = fstat($outputStream);
                $header .= pack('ii', $partOffset, $streamStat['size']);
                
                $partOffset += $streamStat['size'];
                
                // calculate start and length of parts
                foreach ($parts as $partId => $partStream) {
                    rewind($partStream);
                    $streamStat = fstat($partStream);
                    
                    // part start and length
                    $header .= pack('ii', $partOffset, $streamStat['size']);
                    $partOffset += $streamStat['size'];
                }
                
                echo $header;
            }
            
            // output body
            rewind($outputStream);
            fpassthru($outputStream);
            
            // output multiparts
            if (isset($parts)) {
                foreach ($parts as $partStream) {
                    rewind($partStream);
                    fpassthru($partStream);
                }
            }
        }
    }
    
    /**
     * write (possible big) DOMDocument in smaller chunks to log file
     * 
     * @param unknown     $priority
     * @param DOMDocument $dom
     * @param string      $method
     * @param int         $line
     */
    protected function _logDomDocument($priority, DOMDocument $dom, $method, $line)
    {
        $loops = 0;
        
        $tempStream = fopen('php://temp/maxmemory:5242880', 'r+');
                
        $dom->formatOutput = true;
        fwrite($tempStream, $dom->saveXML());
        $dom->formatOutput = false;
        
        rewind($tempStream);
        
        // log data in 1MByte chunks
        while (!feof($tempStream)) {
            $this->_logger->log($method . '::' . $line . " xml response($loops):\n" . fread($tempStream, 1048576), $priority);
            
            $loops++;
        }
        
        fclose($tempStream);
    }
    
    /**
     * return request params
     * 
     * @return array
     */
    protected function _getRequestParameters(Zend_Controller_Request_Http $request)
    {
        if (strpos($request->getRequestUri(), '&') === false) {
            $commands = array(
                0  => 'Sync',
                1  => 'SendMail',
                2  => 'SmartForward',
                3  => 'SmartReply',
                4  => 'GetAttachment',
                9  => 'FolderSync',
                10 => 'FolderCreate',
                11 => 'FolderDelete',
                12 => 'FolderUpdate',
                13 => 'MoveItems',
                14 => 'GetItemEstimate',
                15 => 'MeetingResponse',
                16 => 'Search',
                17 => 'Settings',
                18 => 'Ping',
                19 => 'ItemOperations',
                20 => 'Provision',
                21 => 'ResolveRecipients',
                22 => 'ValidateCert'
            );
            
            $requestParameters = substr($request->getRequestUri(), strpos($request->getRequestUri(), '?'));

            $stream = fopen("php://temp", 'r+');
            fwrite($stream, base64_decode($requestParameters));
            rewind($stream);

            // unpack the first 4 bytes
            $unpacked = unpack('CprotocolVersion/Ccommand/vlocale', fread($stream, 4));
            
            // 140 => 14.0
            $protocolVersion = substr($unpacked['protocolVersion'], 0, -1) . '.' . substr($unpacked['protocolVersion'], -1);
            $command = $commands[$unpacked['command']];
            $locale = $unpacked['locale'];
            
            // unpack deviceId
            $length = ord(fread($stream, 1));
            if ($length > 0) {
                $toUnpack = fread($stream, $length);
                
                $unpacked = unpack("H" . ($length * 2) . "string", $toUnpack);
                $deviceId = $unpacked['string'];
            }
            
            // unpack policyKey
            $length = ord(fread($stream, 1));
            if ($length > 0) {
                $unpacked  = unpack('Vstring', fread($stream, $length));
                $policyKey = $unpacked['string'];
            }
            
            // unpack device type
            $length = ord(fread($stream, 1));
            if ($length > 0) {
                $unpacked   = unpack('A' . $length . 'string', fread($stream, $length));
                $deviceType = $unpacked['string'];
            }
            
            while (! feof($stream)) {
                $tag    = ord(fread($stream, 1));
                $length = ord(fread($stream, 1));

                switch ($tag) {
                    case self::PARAMETER_ATTACHMENTNAME:
                        $unpacked = unpack('A' . $length . 'string', fread($stream, $length));
                        
                        $attachmentName = $unpacked['string'];
                        break;
                        
                    case self::PARAMETER_COLLECTIONID:
                        $unpacked = unpack('A' . $length . 'string', fread($stream, $length));
                        
                        $collectionId = $unpacked['string'];
                        break;
                        
                    case self::PARAMETER_ITEMID:
                        $unpacked = unpack('A' . $length . 'string', fread($stream, $length));
                        
                        $itemId = $unpacked['string'];
                        break;
                        
                    case self::PARAMETER_OPTIONS:
                        $options = ord(fread($stream, 1));
                        
                        $saveInSent      = !!($options & 0x01); 
                        $acceptMultiPart = !!($options & 0x02);
                        break;
                        
                    default:
                        if ($this->_logger instanceof Zend_Log)
                            $this->_logger->crit(__METHOD__ . '::' . __LINE__ . " found unhandled command parameters");
                        
                }
            }
             
            $result = array(
                'protocolVersion' => $protocolVersion,
                'command'         => $command,
                'deviceId'        => $deviceId,
                'deviceType'      => isset($deviceType)      ? $deviceType      : null,
                'policyKey'       => isset($policyKey)       ? $policyKey       : null,
                'saveInSent'      => isset($saveInSent)      ? $saveInSent      : false,
                'collectionId'    => isset($collectionId)    ? $collectionId    : null,
                'itemId'          => isset($itemId)          ? $itemId          : null,
                'attachmentName'  => isset($attachmentName)  ? $attachmentName  : null,
                'acceptMultipart' => isset($acceptMultiPart) ? $acceptMultiPart : false
            );
        } else {
            $result = array(
                'protocolVersion' => $request->getServer('HTTP_MS_ASPROTOCOLVERSION'),
                'command'         => $request->getQuery('Cmd'),
                'deviceId'        => $request->getQuery('DeviceId'),
                'deviceType'      => $request->getQuery('DeviceType'),
                'policyKey'       => $request->getServer('HTTP_X_MS_POLICYKEY'),
                'saveInSent'      => $request->getQuery('SaveInSent') == 'T',
                'collectionId'    => $request->getQuery('CollectionId'),
                'itemId'          => $request->getQuery('ItemId'),
                'attachmentName'  => $request->getQuery('AttachmentName'),
                'acceptMultipart' => $request->getServer('HTTP_MS_ASACCEPTMULTIPART') == 'T'
            );
        }
        
        $result['userAgent']   = $request->getServer('HTTP_USER_AGENT', $result['deviceType']);
        $result['contentType'] = $request->getServer('CONTENT_TYPE');
        
        return $result;
    }
    
    /**
     * get existing device of owner or create new device for owner
     *
     * @param unknown_type $ownerId
     * @param unknown_type $deviceId
     * @param unknown_type $deviceType
     * @param unknown_type $userAgent
     * @param unknown_type $protocolVersion
     * @return Syncroton_Model_Device
     */
    protected function _getUserDevice($ownerId, $requestParameters)
    {
        try {
            $device = $this->_deviceBackend->getUserDevice($ownerId, $requestParameters['deviceId']);
        
            $device->useragent  = $requestParameters['userAgent'];
            $device->acsversion = $requestParameters['protocolVersion'];
            
            if ($device->isDirty()) {
                $device = $this->_deviceBackend->update($device);
            }
        
        } catch (Syncroton_Exception_NotFound $senf) {
            $device = $this->_deviceBackend->create(new Syncroton_Model_Device(array(
                'owner_id'   => $ownerId,
                'deviceid'   => $requestParameters['deviceId'],
                'devicetype' => $requestParameters['deviceType'],
                'useragent'  => $requestParameters['userAgent'],
                'acsversion' => $requestParameters['protocolVersion'],
                'policyId'   => Syncroton_Registry::isRegistered(Syncroton_Registry::DEFAULT_POLICY) ? Syncroton_Registry::get(Syncroton_Registry::DEFAULT_POLICY) : null
            )));
        }

        return $device;
    }
}