SyncService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Thomas Citharel <nextcloud@tcit.fr>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Anna Larch <anna.larch@gmx.net>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\DAV\CardDAV;
  31. use OCP\AppFramework\Db\TTransactional;
  32. use OCP\AppFramework\Http;
  33. use OCP\Http\Client\IClientService;
  34. use OCP\IDBConnection;
  35. use OCP\IUser;
  36. use OCP\IUserManager;
  37. use Psr\Http\Client\ClientExceptionInterface;
  38. use Psr\Log\LoggerInterface;
  39. use Sabre\DAV\Xml\Response\MultiStatus;
  40. use Sabre\DAV\Xml\Service;
  41. use Sabre\VObject\Reader;
  42. use function is_null;
  43. class SyncService {
  44. use TTransactional;
  45. private CardDavBackend $backend;
  46. private IUserManager $userManager;
  47. private IDBConnection $dbConnection;
  48. private LoggerInterface $logger;
  49. private ?array $localSystemAddressBook = null;
  50. private Converter $converter;
  51. protected string $certPath;
  52. private IClientService $clientService;
  53. public function __construct(CardDavBackend $backend,
  54. IUserManager $userManager,
  55. IDBConnection $dbConnection,
  56. LoggerInterface $logger,
  57. Converter $converter,
  58. IClientService $clientService) {
  59. $this->backend = $backend;
  60. $this->userManager = $userManager;
  61. $this->logger = $logger;
  62. $this->converter = $converter;
  63. $this->certPath = '';
  64. $this->dbConnection = $dbConnection;
  65. $this->clientService = $clientService;
  66. }
  67. /**
  68. * @throws \Exception
  69. */
  70. public function syncRemoteAddressBook(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken, string $targetBookHash, string $targetPrincipal, array $targetProperties): string {
  71. // 1. create addressbook
  72. $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookHash, $targetProperties);
  73. $addressBookId = $book['id'];
  74. // 2. query changes
  75. try {
  76. $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
  77. } catch (ClientExceptionInterface $ex) {
  78. if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
  79. // remote server revoked access to the address book, remove it
  80. $this->backend->deleteAddressBook($addressBookId);
  81. $this->logger->error('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
  82. throw $ex;
  83. }
  84. $this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);
  85. throw $ex;
  86. }
  87. // 3. apply changes
  88. // TODO: use multi-get for download
  89. foreach ($response['response'] as $resource => $status) {
  90. $cardUri = basename($resource);
  91. if (isset($status[200])) {
  92. $vCard = $this->download($url, $userName, $sharedSecret, $resource);
  93. $this->atomic(function () use ($addressBookId, $cardUri, $vCard) {
  94. $existingCard = $this->backend->getCard($addressBookId, $cardUri);
  95. if ($existingCard === false) {
  96. $this->backend->createCard($addressBookId, $cardUri, $vCard);
  97. } else {
  98. $this->backend->updateCard($addressBookId, $cardUri, $vCard);
  99. }
  100. }, $this->dbConnection);
  101. } else {
  102. $this->backend->deleteCard($addressBookId, $cardUri);
  103. }
  104. }
  105. return $response['token'];
  106. }
  107. /**
  108. * @throws \Sabre\DAV\Exception\BadRequest
  109. */
  110. public function ensureSystemAddressBookExists(string $principal, string $uri, array $properties): ?array {
  111. return $this->atomic(function () use ($principal, $uri, $properties) {
  112. $book = $this->backend->getAddressBooksByUri($principal, $uri);
  113. if (!is_null($book)) {
  114. return $book;
  115. }
  116. $this->backend->createAddressBook($principal, $uri, $properties);
  117. return $this->backend->getAddressBooksByUri($principal, $uri);
  118. }, $this->dbConnection);
  119. }
  120. private function prepareUri(string $host, string $path): string {
  121. /*
  122. * The trailing slash is important for merging the uris together.
  123. *
  124. * $host is stored in oc_trusted_servers.url and usually without a trailing slash.
  125. *
  126. * Example for a report request
  127. *
  128. * $host = 'https://server.internal/cloud'
  129. * $path = 'remote.php/dav/addressbooks/system/system/system'
  130. *
  131. * Without the trailing slash, the webroot is missing:
  132. * https://server.internal/remote.php/dav/addressbooks/system/system/system
  133. *
  134. * Example for a download request
  135. *
  136. * $host = 'https://server.internal/cloud'
  137. * $path = '/cloud/remote.php/dav/addressbooks/system/system/system/Database:alice.vcf'
  138. *
  139. * The response from the remote usually contains the webroot already and must be normalized to:
  140. * https://server.internal/cloud/remote.php/dav/addressbooks/system/system/system/Database:alice.vcf
  141. */
  142. $host = rtrim($host, '/') . '/';
  143. $uri = \GuzzleHttp\Psr7\UriResolver::resolve(
  144. \GuzzleHttp\Psr7\Utils::uriFor($host),
  145. \GuzzleHttp\Psr7\Utils::uriFor($path)
  146. );
  147. return (string)$uri;
  148. }
  149. /**
  150. * @throws ClientExceptionInterface
  151. */
  152. protected function requestSyncReport(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken): array {
  153. $client = $this->clientService->newClient();
  154. $uri = $this->prepareUri($url, $addressBookUrl);
  155. $options = [
  156. 'auth' => [$userName, $sharedSecret],
  157. 'body' => $this->buildSyncCollectionRequestBody($syncToken),
  158. 'headers' => ['Content-Type' => 'application/xml']
  159. ];
  160. $response = $client->request(
  161. 'REPORT',
  162. $uri,
  163. $options
  164. );
  165. $body = $response->getBody();
  166. assert(is_string($body));
  167. return $this->parseMultiStatus($body);
  168. }
  169. protected function download(string $url, string $userName, string $sharedSecret, string $resourcePath): string {
  170. $client = $this->clientService->newClient();
  171. $uri = $this->prepareUri($url, $resourcePath);
  172. $options = [
  173. 'auth' => [$userName, $sharedSecret],
  174. ];
  175. $response = $client->get(
  176. $uri,
  177. $options
  178. );
  179. return (string)$response->getBody();
  180. }
  181. private function buildSyncCollectionRequestBody(?string $syncToken): string {
  182. $dom = new \DOMDocument('1.0', 'UTF-8');
  183. $dom->formatOutput = true;
  184. $root = $dom->createElementNS('DAV:', 'd:sync-collection');
  185. $sync = $dom->createElement('d:sync-token', $syncToken ?? '');
  186. $prop = $dom->createElement('d:prop');
  187. $cont = $dom->createElement('d:getcontenttype');
  188. $etag = $dom->createElement('d:getetag');
  189. $prop->appendChild($cont);
  190. $prop->appendChild($etag);
  191. $root->appendChild($sync);
  192. $root->appendChild($prop);
  193. $dom->appendChild($root);
  194. return $dom->saveXML();
  195. }
  196. /**
  197. * @param string $body
  198. * @return array
  199. * @throws \Sabre\Xml\ParseException
  200. */
  201. private function parseMultiStatus($body) {
  202. $xml = new Service();
  203. /** @var MultiStatus $multiStatus */
  204. $multiStatus = $xml->expect('{DAV:}multistatus', $body);
  205. $result = [];
  206. foreach ($multiStatus->getResponses() as $response) {
  207. $result[$response->getHref()] = $response->getResponseProperties();
  208. }
  209. return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
  210. }
  211. /**
  212. * @param IUser $user
  213. */
  214. public function updateUser(IUser $user): void {
  215. $systemAddressBook = $this->getLocalSystemAddressBook();
  216. $addressBookId = $systemAddressBook['id'];
  217. $cardId = self::getCardUri($user);
  218. if ($user->isEnabled()) {
  219. $this->atomic(function () use ($addressBookId, $cardId, $user) {
  220. $card = $this->backend->getCard($addressBookId, $cardId);
  221. if ($card === false) {
  222. $vCard = $this->converter->createCardFromUser($user);
  223. if ($vCard !== null) {
  224. $this->backend->createCard($addressBookId, $cardId, $vCard->serialize(), false);
  225. }
  226. } else {
  227. $vCard = $this->converter->createCardFromUser($user);
  228. if (is_null($vCard)) {
  229. $this->backend->deleteCard($addressBookId, $cardId);
  230. } else {
  231. $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
  232. }
  233. }
  234. }, $this->dbConnection);
  235. } else {
  236. $this->backend->deleteCard($addressBookId, $cardId);
  237. }
  238. }
  239. /**
  240. * @param IUser|string $userOrCardId
  241. */
  242. public function deleteUser($userOrCardId) {
  243. $systemAddressBook = $this->getLocalSystemAddressBook();
  244. if ($userOrCardId instanceof IUser) {
  245. $userOrCardId = self::getCardUri($userOrCardId);
  246. }
  247. $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
  248. }
  249. /**
  250. * @return array|null
  251. */
  252. public function getLocalSystemAddressBook() {
  253. if (is_null($this->localSystemAddressBook)) {
  254. $systemPrincipal = "principals/system/system";
  255. $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
  256. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
  257. ]);
  258. }
  259. return $this->localSystemAddressBook;
  260. }
  261. /**
  262. * @return void
  263. */
  264. public function syncInstance(?\Closure $progressCallback = null) {
  265. $systemAddressBook = $this->getLocalSystemAddressBook();
  266. $this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback) {
  267. $this->updateUser($user);
  268. if (!is_null($progressCallback)) {
  269. $progressCallback();
  270. }
  271. });
  272. // remove no longer existing
  273. $allCards = $this->backend->getCards($systemAddressBook['id']);
  274. foreach ($allCards as $card) {
  275. $vCard = Reader::read($card['carddata']);
  276. $uid = $vCard->UID->getValue();
  277. // load backend and see if user exists
  278. if (!$this->userManager->userExists($uid)) {
  279. $this->deleteUser($card['uri']);
  280. }
  281. }
  282. }
  283. /**
  284. * @param IUser $user
  285. * @return string
  286. */
  287. public static function getCardUri(IUser $user): string {
  288. return $user->getBackendClassName() . ':' . $user->getUID() . '.vcf';
  289. }
  290. }