summaryrefslogtreecommitdiffstats
path: root/lib/private/legacy/api.php
blob: 30083294861c7224b17106696a8fdac26fb3c8c0 (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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
<?php
/**
 * @copyright Copyright (c) 2016, ownCloud, Inc.
 *
 * @author Bart Visscher <bartv@thisnet.nl>
 * @author Bernhard Posselt <dev@bernhard-posselt.com>
 * @author Björn Schießle <bjoern@schiessle.org>
 * @author Christoph Wurst <christoph@owncloud.com>
 * @author Joas Schilling <coding@schilljs.com>
 * @author Jörn Friedrich Dreyer <jfd@butonic.de>
 * @author Lukas Reschke <lukas@statuscode.ch>
 * @author Michael Gapczynski <GapczynskiM@gmail.com>
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Robin Appelman <robin@icewind.nl>
 * @author Roeland Jago Douma <roeland@famdouma.nl>
 * @author Thomas Müller <thomas.mueller@tmit.eu>
 * @author Tom Needham <tom@owncloud.com>
 * @author Vincent Petry <pvince81@owncloud.com>
 *
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
use OCP\API;
use OCP\AppFramework\Http;

class OC_API {

	/**
	 * API authentication levels
	 */

	/** @deprecated Use \OCP\API::GUEST_AUTH instead */
	const GUEST_AUTH = 0;

	/** @deprecated Use \OCP\API::USER_AUTH instead */
	const USER_AUTH = 1;

	/** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
	const SUBADMIN_AUTH = 2;

	/** @deprecated Use \OCP\API::ADMIN_AUTH instead */
	const ADMIN_AUTH = 3;

	/**
	 * API Response Codes
	 */

	/** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
	const RESPOND_UNAUTHORISED = 997;

	/** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
	const RESPOND_SERVER_ERROR = 996;

	/** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
	const RESPOND_NOT_FOUND = 998;

	/** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
	const RESPOND_UNKNOWN_ERROR = 999;

	/**
	 * api actions
	 */
	protected static $actions = array();
	private static $logoutRequired = false;
	private static $isLoggedIn = false;

	/**
	 * registers an api call
	 * @param string $method the http method
	 * @param string $url the url to match
	 * @param callable $action the function to run
	 * @param string $app the id of the app registering the call
	 * @param int $authLevel the level of authentication required for the call
	 * @param array $defaults
	 * @param array $requirements
	 */
	public static function register($method, $url, $action, $app,
				$authLevel = API::USER_AUTH,
				$defaults = array(),
				$requirements = array()) {
		$name = strtolower($method).$url;
		$name = str_replace(array('/', '{', '}'), '_', $name);
		if(!isset(self::$actions[$name])) {
			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
			OC::$server->getRouter()->useCollection('ocs');
			OC::$server->getRouter()->create($name, $url)
				->method($method)
				->defaults($defaults)
				->requirements($requirements)
				->action('OC_API', 'call');
			self::$actions[$name] = array();
			OC::$server->getRouter()->useCollection($oldCollection);
		}
		self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
	}

	/**
	 * handles an api call
	 * @param array $parameters
	 */
	public static function call($parameters) {
		$request = \OC::$server->getRequest();
		$method = $request->getMethod();

		// Prepare the request variables
		if($method === 'PUT') {
			$parameters['_put'] = $request->getParams();
		} else if($method === 'DELETE') {
			$parameters['_delete'] = $request->getParams();
		}
		$name = $parameters['_route'];
		// Foreach registered action
		$responses = array();
		foreach(self::$actions[$name] as $action) {
			// Check authentication and availability
			if(!self::isAuthorised($action)) {
				$responses[] = array(
					'app' => $action['app'],
					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
					'shipped' => OC_App::isShipped($action['app']),
					);
				continue;
			}
			if(!is_callable($action['action'])) {
				$responses[] = array(
					'app' => $action['app'],
					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
					'shipped' => OC_App::isShipped($action['app']),
					);
				continue;
			}
			// Run the action
			$responses[] = array(
				'app' => $action['app'],
				'response' => call_user_func($action['action'], $parameters),
				'shipped' => OC_App::isShipped($action['app']),
				);
		}
		$response = self::mergeResponses($responses);
		$format = self::requestedFormat();
		if (self::$logoutRequired) {
			\OC::$server->getUserSession()->logout();
		}

		self::respond($response, $format);
	}

	/**
	 * merge the returned result objects into one response
	 * @param array $responses
	 * @return OC_OCS_Result
	 */
	public static function mergeResponses($responses) {
		// Sort into shipped and third-party
		$shipped = array(
			'succeeded' => array(),
			'failed' => array(),
			);
		$thirdparty = array(
			'succeeded' => array(),
			'failed' => array(),
			);

		foreach($responses as $response) {
			if($response['shipped'] || ($response['app'] === 'core')) {
				if($response['response']->succeeded()) {
					$shipped['succeeded'][$response['app']] = $response;
				} else {
					$shipped['failed'][$response['app']] = $response;
				}
			} else {
				if($response['response']->succeeded()) {
					$thirdparty['succeeded'][$response['app']] = $response;
				} else {
					$thirdparty['failed'][$response['app']] = $response;
				}
			}
		}

		// Remove any error responses if there is one shipped response that succeeded
		if(!empty($shipped['failed'])) {
			// Which shipped response do we use if they all failed?
			// They may have failed for different reasons (different status codes)
			// Which response code should we return?
			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
			// Merge failed responses if more than one
			$data = array();
			foreach($shipped['failed'] as $failure) {
				$data = array_merge_recursive($data, $failure['response']->getData());
			}
			$picked = reset($shipped['failed']);
			$code = $picked['response']->getStatusCode();
			$meta = $picked['response']->getMeta();
			$headers = $picked['response']->getHeaders();
			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
			return $response;
		} elseif(!empty($shipped['succeeded'])) {
			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
		} elseif(!empty($thirdparty['failed'])) {
			// Merge failed responses if more than one
			$data = array();
			foreach($thirdparty['failed'] as $failure) {
				$data = array_merge_recursive($data, $failure['response']->getData());
			}
			$picked = reset($thirdparty['failed']);
			$code = $picked['response']->getStatusCode();
			$meta = $picked['response']->getMeta();
			$headers = $picked['response']->getHeaders();
			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
			return $response;
		} else {
			$responses = $thirdparty['succeeded'];
		}
		// Merge the successful responses
		$data = [];
		$codes = [];
		$header = [];

		foreach($responses as $response) {
			if($response['shipped']) {
				$data = array_merge_recursive($response['response']->getData(), $data);
			} else {
				$data = array_merge_recursive($data, $response['response']->getData());
			}
			$header = array_merge_recursive($header, $response['response']->getHeaders());
			$codes[] = ['code' => $response['response']->getStatusCode(),
				'meta' => $response['response']->getMeta()];
		}

		// Use any non 100 status codes
		$statusCode = 100;
		$statusMessage = null;
		foreach($codes as $code) {
			if($code['code'] != 100) {
				$statusCode = $code['code'];
				$statusMessage = $code['meta']['message'];
				break;
			}
		}

		return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
	}

	/**
	 * authenticate the api call
	 * @param array $action the action details as supplied to OC_API::register()
	 * @return bool
	 */
	private static function isAuthorised($action) {
		$level = $action['authlevel'];
		switch($level) {
			case API::GUEST_AUTH:
				// Anyone can access
				return true;
			case API::USER_AUTH:
				// User required
				return self::loginUser();
			case API::SUBADMIN_AUTH:
				// Check for subadmin
				$user = self::loginUser();
				if(!$user) {
					return false;
				} else {
					$userObject = \OC::$server->getUserSession()->getUser();
					if($userObject === null) {
						return false;
					}
					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
					$admin = OC_User::isAdminUser($user);
					if($isSubAdmin || $admin) {
						return true;
					} else {
						return false;
					}
				}
			case API::ADMIN_AUTH:
				// Check for admin
				$user = self::loginUser();
				if(!$user) {
					return false;
				} else {
					return OC_User::isAdminUser($user);
				}
			default:
				// oops looks like invalid level supplied
				return false;
		}
	}

	/**
	 * http basic auth
	 * @return string|false (username, or false on failure)
	 */
	private static function loginUser() {
		if(self::$isLoggedIn === true) {
			return \OC_User::getUser();
		}

		// reuse existing login
		$loggedIn = \OC::$server->getUserSession()->isLoggedIn();
		if ($loggedIn === true) {
			if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor()) {
				// Do not allow access to OCS until the 2FA challenge was solved successfully
				return false;
			}
			$ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
			if ($ocsApiRequest) {

				// initialize the user's filesystem
				\OC_Util::setupFS(\OC_User::getUser());
				self::$isLoggedIn = true;

				return OC_User::getUser();
			}
			return false;
		}

		// basic auth - because OC_User::login will create a new session we shall only try to login
		// if user and pass are set
		$userSession = \OC::$server->getUserSession();
		$request = \OC::$server->getRequest();
		try {
			$loginSuccess = $userSession->tryTokenLogin($request);
			if (!$loginSuccess) {
				$loginSuccess = $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler());
			}
		} catch (\OC\User\LoginException $e) {
			return false;
		}
	
		if ($loginSuccess === true) {
			self::$logoutRequired = true;

			// initialize the user's filesystem
			\OC_Util::setupFS(\OC_User::getUser());
			self::$isLoggedIn = true;

			return \OC_User::getUser();
		}

		return false;
	}

	/**
	 * respond to a call
	 * @param OC_OCS_Result $result
	 * @param string $format the format xml|json
	 */
	public static function respond($result, $format='xml') {
		$request = \OC::$server->getRequest();

		// Send 401 headers if unauthorised
		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
			// If request comes from JS return dummy auth request
			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
			} else {
				header('WWW-Authenticate: Basic realm="Authorisation Required"');
			}
			header('HTTP/1.0 401 Unauthorized');
		}

		foreach($result->getHeaders() as $name => $value) {
			header($name . ': ' . $value);
		}

		$meta = $result->getMeta();
		$data = $result->getData();
		if (self::isV2($request)) {
			$statusCode = self::mapStatusCodes($result->getStatusCode());
			if (!is_null($statusCode)) {
				$meta['statuscode'] = $statusCode;
				OC_Response::setStatus($statusCode);
			}
		}

		self::setContentType($format);
		$body = self::renderResult($format, $meta, $data);
		echo $body;
	}

	/**
	 * @param XMLWriter $writer
	 */
	private static function toXML($array, $writer) {
		foreach($array as $k => $v) {
			if ($k[0] === '@') {
				$writer->writeAttribute(substr($k, 1), $v);
				continue;
			} else if (is_numeric($k)) {
				$k = 'element';
			}
			if(is_array($v)) {
				$writer->startElement($k);
				self::toXML($v, $writer);
				$writer->endElement();
			} else {
				$writer->writeElement($k, $v);
			}
		}
	}

	/**
	 * @return string
	 */
	public static function requestedFormat() {
		$formats = array('json', 'xml');

		$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
		return $format;
	}

	/**
	 * Based on the requested format the response content type is set
	 * @param string $format
	 */
	public static function setContentType($format = null) {
		$format = is_null($format) ? self::requestedFormat() : $format;
		if ($format === 'xml') {
			header('Content-type: text/xml; charset=UTF-8');
			return;
		}

		if ($format === 'json') {
			header('Content-Type: application/json; charset=utf-8');
			return;
		}

		header('Content-Type: application/octet-stream; charset=utf-8');
	}

	/**
	 * @param \OCP\IRequest $request
	 * @return bool
	 */
	protected static function isV2(\OCP\IRequest $request) {
		$script = $request->getScriptName();

		return substr($script, -11) === '/ocs/v2.php';
	}

	/**
	 * @param integer $sc
	 * @return int
	 */
	public static function mapStatusCodes($sc) {
		switch ($sc) {
			case API::RESPOND_NOT_FOUND:
				return Http::STATUS_NOT_FOUND;
			case API::RESPOND_SERVER_ERROR:
				return Http::STATUS_INTERNAL_SERVER_ERROR;
			case API::RESPOND_UNKNOWN_ERROR:
				return Http::STATUS_INTERNAL_SERVER_ERROR;
			case API::RESPOND_UNAUTHORISED:
				// already handled for v1
				return null;
			case 100:
				return Http::STATUS_OK;
		}
		// any 2xx, 4xx and 5xx will be used as is
		if ($sc >= 200 && $sc < 600) {
			return $sc;
		}

		return Http::STATUS_BAD_REQUEST;
	}

	/**
	 * @param string $format
	 * @return string
	 */
	public static function renderResult($format, $meta, $data) {
		$response = array(
			'ocs' => array(
				'meta' => $meta,
				'data' => $data,
			),
		);
		if ($format == 'json') {
			return OC_JSON::encode($response);
		}

		$writer = new XMLWriter();
		$writer->openMemory();
		$writer->setIndent(true);
		$writer->startDocument();
		self::toXML($response, $writer);
		$writer->endDocument();
		return $writer->outputMemory(true);
	}
}