SyncService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\DAV\CardDAV;
  8. use OCP\AppFramework\Db\TTransactional;
  9. use OCP\AppFramework\Http;
  10. use OCP\DB\Exception;
  11. use OCP\Http\Client\IClient;
  12. use OCP\Http\Client\IClientService;
  13. use OCP\IConfig;
  14. use OCP\IDBConnection;
  15. use OCP\IUser;
  16. use OCP\IUserManager;
  17. use Psr\Http\Client\ClientExceptionInterface;
  18. use Psr\Log\LoggerInterface;
  19. use Sabre\DAV\Xml\Response\MultiStatus;
  20. use Sabre\DAV\Xml\Service;
  21. use Sabre\VObject\Reader;
  22. use function is_null;
  23. class SyncService {
  24. use TTransactional;
  25. private ?array $localSystemAddressBook = null;
  26. protected string $certPath;
  27. public function __construct(
  28. private CardDavBackend $backend,
  29. private IUserManager $userManager,
  30. private IDBConnection $dbConnection,
  31. private LoggerInterface $logger,
  32. private Converter $converter,
  33. private IClientService $clientService,
  34. private IConfig $config,
  35. ) {
  36. $this->certPath = '';
  37. }
  38. /**
  39. * @throws \Exception
  40. */
  41. public function syncRemoteAddressBook(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken, string $targetBookHash, string $targetPrincipal, array $targetProperties): string {
  42. // 1. create addressbook
  43. $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookHash, $targetProperties);
  44. $addressBookId = $book['id'];
  45. // 2. query changes
  46. try {
  47. $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
  48. } catch (ClientExceptionInterface $ex) {
  49. if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
  50. // remote server revoked access to the address book, remove it
  51. $this->backend->deleteAddressBook($addressBookId);
  52. $this->logger->error('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
  53. throw $ex;
  54. }
  55. $this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);
  56. throw $ex;
  57. }
  58. // 3. apply changes
  59. // TODO: use multi-get for download
  60. foreach ($response['response'] as $resource => $status) {
  61. $cardUri = basename($resource);
  62. if (isset($status[200])) {
  63. $vCard = $this->download($url, $userName, $sharedSecret, $resource);
  64. $this->atomic(function () use ($addressBookId, $cardUri, $vCard): void {
  65. $existingCard = $this->backend->getCard($addressBookId, $cardUri);
  66. if ($existingCard === false) {
  67. $this->backend->createCard($addressBookId, $cardUri, $vCard);
  68. } else {
  69. $this->backend->updateCard($addressBookId, $cardUri, $vCard);
  70. }
  71. }, $this->dbConnection);
  72. } else {
  73. $this->backend->deleteCard($addressBookId, $cardUri);
  74. }
  75. }
  76. return $response['token'];
  77. }
  78. /**
  79. * @throws \Sabre\DAV\Exception\BadRequest
  80. */
  81. public function ensureSystemAddressBookExists(string $principal, string $uri, array $properties): ?array {
  82. try {
  83. return $this->atomic(function () use ($principal, $uri, $properties) {
  84. $book = $this->backend->getAddressBooksByUri($principal, $uri);
  85. if (!is_null($book)) {
  86. return $book;
  87. }
  88. $this->backend->createAddressBook($principal, $uri, $properties);
  89. return $this->backend->getAddressBooksByUri($principal, $uri);
  90. }, $this->dbConnection);
  91. } catch (Exception $e) {
  92. // READ COMMITTED doesn't prevent a nonrepeatable read above, so
  93. // two processes might create an address book here. Ignore our
  94. // failure and continue loading the entry written by the other process
  95. if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  96. throw $e;
  97. }
  98. // If this fails we might have hit a replication node that does not
  99. // have the row written in the other process.
  100. // TODO: find an elegant way to handle this
  101. $ab = $this->backend->getAddressBooksByUri($principal, $uri);
  102. if ($ab === null) {
  103. throw new Exception('Could not create system address book', $e->getCode(), $e);
  104. }
  105. return $ab;
  106. }
  107. }
  108. private function prepareUri(string $host, string $path): string {
  109. /*
  110. * The trailing slash is important for merging the uris together.
  111. *
  112. * $host is stored in oc_trusted_servers.url and usually without a trailing slash.
  113. *
  114. * Example for a report request
  115. *
  116. * $host = 'https://server.internal/cloud'
  117. * $path = 'remote.php/dav/addressbooks/system/system/system'
  118. *
  119. * Without the trailing slash, the webroot is missing:
  120. * https://server.internal/remote.php/dav/addressbooks/system/system/system
  121. *
  122. * Example for a download request
  123. *
  124. * $host = 'https://server.internal/cloud'
  125. * $path = '/cloud/remote.php/dav/addressbooks/system/system/system/Database:alice.vcf'
  126. *
  127. * The response from the remote usually contains the webroot already and must be normalized to:
  128. * https://server.internal/cloud/remote.php/dav/addressbooks/system/system/system/Database:alice.vcf
  129. */
  130. $host = rtrim($host, '/') . '/';
  131. $uri = \GuzzleHttp\Psr7\UriResolver::resolve(
  132. \GuzzleHttp\Psr7\Utils::uriFor($host),
  133. \GuzzleHttp\Psr7\Utils::uriFor($path)
  134. );
  135. return (string)$uri;
  136. }
  137. /**
  138. * @throws ClientExceptionInterface
  139. */
  140. protected function requestSyncReport(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken): array {
  141. $client = $this->clientService->newClient();
  142. $uri = $this->prepareUri($url, $addressBookUrl);
  143. $options = [
  144. 'auth' => [$userName, $sharedSecret],
  145. 'body' => $this->buildSyncCollectionRequestBody($syncToken),
  146. 'headers' => ['Content-Type' => 'application/xml'],
  147. 'timeout' => $this->config->getSystemValueInt('carddav_sync_request_timeout', IClient::DEFAULT_REQUEST_TIMEOUT)
  148. ];
  149. $response = $client->request(
  150. 'REPORT',
  151. $uri,
  152. $options
  153. );
  154. $body = $response->getBody();
  155. assert(is_string($body));
  156. return $this->parseMultiStatus($body);
  157. }
  158. protected function download(string $url, string $userName, string $sharedSecret, string $resourcePath): string {
  159. $client = $this->clientService->newClient();
  160. $uri = $this->prepareUri($url, $resourcePath);
  161. $options = [
  162. 'auth' => [$userName, $sharedSecret],
  163. ];
  164. $response = $client->get(
  165. $uri,
  166. $options
  167. );
  168. return (string)$response->getBody();
  169. }
  170. private function buildSyncCollectionRequestBody(?string $syncToken): string {
  171. $dom = new \DOMDocument('1.0', 'UTF-8');
  172. $dom->formatOutput = true;
  173. $root = $dom->createElementNS('DAV:', 'd:sync-collection');
  174. $sync = $dom->createElement('d:sync-token', $syncToken ?? '');
  175. $prop = $dom->createElement('d:prop');
  176. $cont = $dom->createElement('d:getcontenttype');
  177. $etag = $dom->createElement('d:getetag');
  178. $prop->appendChild($cont);
  179. $prop->appendChild($etag);
  180. $root->appendChild($sync);
  181. $root->appendChild($prop);
  182. $dom->appendChild($root);
  183. return $dom->saveXML();
  184. }
  185. /**
  186. * @param string $body
  187. * @return array
  188. * @throws \Sabre\Xml\ParseException
  189. */
  190. private function parseMultiStatus($body) {
  191. $xml = new Service();
  192. /** @var MultiStatus $multiStatus */
  193. $multiStatus = $xml->expect('{DAV:}multistatus', $body);
  194. $result = [];
  195. foreach ($multiStatus->getResponses() as $response) {
  196. $result[$response->getHref()] = $response->getResponseProperties();
  197. }
  198. return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
  199. }
  200. /**
  201. * @param IUser $user
  202. */
  203. public function updateUser(IUser $user): void {
  204. $systemAddressBook = $this->getLocalSystemAddressBook();
  205. $addressBookId = $systemAddressBook['id'];
  206. $cardId = self::getCardUri($user);
  207. if ($user->isEnabled()) {
  208. $this->atomic(function () use ($addressBookId, $cardId, $user): void {
  209. $card = $this->backend->getCard($addressBookId, $cardId);
  210. if ($card === false) {
  211. $vCard = $this->converter->createCardFromUser($user);
  212. if ($vCard !== null) {
  213. $this->backend->createCard($addressBookId, $cardId, $vCard->serialize(), false);
  214. }
  215. } else {
  216. $vCard = $this->converter->createCardFromUser($user);
  217. if (is_null($vCard)) {
  218. $this->backend->deleteCard($addressBookId, $cardId);
  219. } else {
  220. $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
  221. }
  222. }
  223. }, $this->dbConnection);
  224. } else {
  225. $this->backend->deleteCard($addressBookId, $cardId);
  226. }
  227. }
  228. /**
  229. * @param IUser|string $userOrCardId
  230. */
  231. public function deleteUser($userOrCardId) {
  232. $systemAddressBook = $this->getLocalSystemAddressBook();
  233. if ($userOrCardId instanceof IUser) {
  234. $userOrCardId = self::getCardUri($userOrCardId);
  235. }
  236. $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
  237. }
  238. /**
  239. * @return array|null
  240. */
  241. public function getLocalSystemAddressBook() {
  242. if (is_null($this->localSystemAddressBook)) {
  243. $systemPrincipal = 'principals/system/system';
  244. $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
  245. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
  246. ]);
  247. }
  248. return $this->localSystemAddressBook;
  249. }
  250. /**
  251. * @return void
  252. */
  253. public function syncInstance(?\Closure $progressCallback = null) {
  254. $systemAddressBook = $this->getLocalSystemAddressBook();
  255. $this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback): void {
  256. $this->updateUser($user);
  257. if (!is_null($progressCallback)) {
  258. $progressCallback();
  259. }
  260. });
  261. // remove no longer existing
  262. $allCards = $this->backend->getCards($systemAddressBook['id']);
  263. foreach ($allCards as $card) {
  264. $vCard = Reader::read($card['carddata']);
  265. $uid = $vCard->UID->getValue();
  266. // load backend and see if user exists
  267. if (!$this->userManager->userExists($uid)) {
  268. $this->deleteUser($card['uri']);
  269. }
  270. }
  271. }
  272. /**
  273. * @param IUser $user
  274. * @return string
  275. */
  276. public static function getCardUri(IUser $user): string {
  277. return $user->getBackendClassName() . ':' . $user->getUID() . '.vcf';
  278. }
  279. }