SyncService.php 9.2 KB

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