You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RefreshWebcalService.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2020, Thomas Citharel <nextcloud@tcit.fr>
  5. *
  6. * @author Georg Ehrke <oc.list@georgehrke.com>
  7. * @author Thomas Citharel <nextcloud@tcit.fr>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OCA\DAV\CalDAV\WebcalCaching;
  26. use Exception;
  27. use GuzzleHttp\HandlerStack;
  28. use GuzzleHttp\Middleware;
  29. use OCA\DAV\CalDAV\CalDavBackend;
  30. use OCP\Http\Client\IClientService;
  31. use OCP\IConfig;
  32. use OCP\ILogger;
  33. use Psr\Http\Message\RequestInterface;
  34. use Psr\Http\Message\ResponseInterface;
  35. use Sabre\DAV\Exception\BadRequest;
  36. use Sabre\DAV\PropPatch;
  37. use Sabre\DAV\Xml\Property\Href;
  38. use Sabre\VObject\Component;
  39. use Sabre\VObject\DateTimeParser;
  40. use Sabre\VObject\InvalidDataException;
  41. use Sabre\VObject\ParseException;
  42. use Sabre\VObject\Reader;
  43. use Sabre\VObject\Splitter\ICalendar;
  44. use Sabre\VObject\UUIDUtil;
  45. use function count;
  46. class RefreshWebcalService {
  47. /** @var CalDavBackend */
  48. private $calDavBackend;
  49. /** @var IClientService */
  50. private $clientService;
  51. /** @var IConfig */
  52. private $config;
  53. /** @var ILogger */
  54. private $logger;
  55. public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
  56. public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
  57. public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
  58. public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
  59. /**
  60. * RefreshWebcalJob constructor.
  61. *
  62. * @param CalDavBackend $calDavBackend
  63. * @param IClientService $clientService
  64. * @param IConfig $config
  65. * @param ILogger $logger
  66. */
  67. public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger) {
  68. $this->calDavBackend = $calDavBackend;
  69. $this->clientService = $clientService;
  70. $this->config = $config;
  71. $this->logger = $logger;
  72. }
  73. /**
  74. * @param string $principalUri
  75. * @param string $uri
  76. */
  77. public function refreshSubscription(string $principalUri, string $uri) {
  78. $subscription = $this->getSubscription($principalUri, $uri);
  79. $mutations = [];
  80. if (!$subscription) {
  81. return;
  82. }
  83. $webcalData = $this->queryWebcalFeed($subscription, $mutations);
  84. if (!$webcalData) {
  85. return;
  86. }
  87. $stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
  88. $stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
  89. $stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
  90. try {
  91. $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
  92. // we wait with deleting all outdated events till we parsed the new ones
  93. // in case the new calendar is broken and `new ICalendar` throws a ParseException
  94. // the user will still see the old data
  95. $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
  96. while ($vObject = $splitter->getNext()) {
  97. /** @var Component $vObject */
  98. $compName = null;
  99. foreach ($vObject->getComponents() as $component) {
  100. if ($component->name === 'VTIMEZONE') {
  101. continue;
  102. }
  103. $compName = $component->name;
  104. if ($stripAlarms) {
  105. unset($component->{'VALARM'});
  106. }
  107. if ($stripAttachments) {
  108. unset($component->{'ATTACH'});
  109. }
  110. }
  111. if ($stripTodos && $compName === 'VTODO') {
  112. continue;
  113. }
  114. $uri = $this->getRandomCalendarObjectUri();
  115. $calendarData = $vObject->serialize();
  116. try {
  117. $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  118. } catch (BadRequest $ex) {
  119. $this->logger->logException($ex);
  120. }
  121. }
  122. $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
  123. if ($newRefreshRate) {
  124. $mutations[self::REFRESH_RATE] = $newRefreshRate;
  125. }
  126. $this->updateSubscription($subscription, $mutations);
  127. } catch (ParseException $ex) {
  128. $subscriptionId = $subscription['id'];
  129. $this->logger->logException($ex);
  130. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
  131. }
  132. }
  133. /**
  134. * loads subscription from backend
  135. *
  136. * @param string $principalUri
  137. * @param string $uri
  138. * @return array|null
  139. */
  140. public function getSubscription(string $principalUri, string $uri) {
  141. $subscriptions = array_values(array_filter(
  142. $this->calDavBackend->getSubscriptionsForUser($principalUri),
  143. function ($sub) use ($uri) {
  144. return $sub['uri'] === $uri;
  145. }
  146. ));
  147. if (count($subscriptions) === 0) {
  148. return null;
  149. }
  150. return $subscriptions[0];
  151. }
  152. /**
  153. * gets webcal feed from remote server
  154. *
  155. * @param array $subscription
  156. * @param array &$mutations
  157. * @return null|string
  158. */
  159. private function queryWebcalFeed(array $subscription, array &$mutations) {
  160. $client = $this->clientService->newClient();
  161. $didBreak301Chain = false;
  162. $latestLocation = null;
  163. $handlerStack = HandlerStack::create();
  164. $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
  165. return $request
  166. ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
  167. ->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
  168. }));
  169. $handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
  170. if (!$didBreak301Chain) {
  171. if ($response->getStatusCode() !== 301) {
  172. $didBreak301Chain = true;
  173. } else {
  174. $latestLocation = $response->getHeader('Location');
  175. }
  176. }
  177. return $response;
  178. }));
  179. $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
  180. $subscriptionId = $subscription['id'];
  181. $url = $this->cleanURL($subscription['source']);
  182. if ($url === null) {
  183. return null;
  184. }
  185. if ($allowLocalAccess !== 'yes') {
  186. $host = strtolower(parse_url($url, PHP_URL_HOST));
  187. // remove brackets from IPv6 addresses
  188. if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
  189. $host = substr($host, 1, -1);
  190. }
  191. // Disallow localhost and local network
  192. if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
  193. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  194. return null;
  195. }
  196. // Disallow hostname only
  197. if (substr_count($host, '.') === 0) {
  198. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  199. return null;
  200. }
  201. if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  202. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  203. return null;
  204. }
  205. // Also check for IPv6 IPv4 nesting, because that's not covered by filter_var
  206. if ((bool)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
  207. $delimiter = strrpos($host, ':'); // Get last colon
  208. $ipv4Address = substr($host, $delimiter + 1);
  209. if (!filter_var($ipv4Address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  210. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  211. return null;
  212. }
  213. }
  214. }
  215. try {
  216. $params = [
  217. 'allow_redirects' => [
  218. 'redirects' => 10
  219. ],
  220. 'handler' => $handlerStack,
  221. ];
  222. $user = parse_url($subscription['source'], PHP_URL_USER);
  223. $pass = parse_url($subscription['source'], PHP_URL_PASS);
  224. if ($user !== null && $pass !== null) {
  225. $params['auth'] = [$user, $pass];
  226. }
  227. $response = $client->get($url, $params);
  228. $body = $response->getBody();
  229. if ($latestLocation) {
  230. $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
  231. }
  232. $contentType = $response->getHeader('Content-Type');
  233. $contentType = explode(';', $contentType, 2)[0];
  234. switch ($contentType) {
  235. case 'application/calendar+json':
  236. try {
  237. $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
  238. } catch (Exception $ex) {
  239. // In case of a parsing error return null
  240. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  241. return null;
  242. }
  243. return $jCalendar->serialize();
  244. case 'application/calendar+xml':
  245. try {
  246. $xCalendar = Reader::readXML($body);
  247. } catch (Exception $ex) {
  248. // In case of a parsing error return null
  249. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  250. return null;
  251. }
  252. return $xCalendar->serialize();
  253. case 'text/calendar':
  254. default:
  255. try {
  256. $vCalendar = Reader::read($body);
  257. } catch (Exception $ex) {
  258. // In case of a parsing error return null
  259. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  260. return null;
  261. }
  262. return $vCalendar->serialize();
  263. }
  264. } catch (Exception $ex) {
  265. $this->logger->logException($ex);
  266. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
  267. return null;
  268. }
  269. }
  270. /**
  271. * check if:
  272. * - current subscription stores a refreshrate
  273. * - the webcal feed suggests a refreshrate
  274. * - return suggested refreshrate if user didn't set a custom one
  275. *
  276. * @param array $subscription
  277. * @param string $webcalData
  278. * @return string|null
  279. */
  280. private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
  281. // if there is no refreshrate stored in the database, check the webcal feed
  282. // whether it suggests any refresh rate and store that in the database
  283. if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
  284. return null;
  285. }
  286. /** @var Component\VCalendar $vCalendar */
  287. $vCalendar = Reader::read($webcalData);
  288. $newRefreshRate = null;
  289. if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
  290. $newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
  291. }
  292. if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
  293. $newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
  294. }
  295. if (!$newRefreshRate) {
  296. return null;
  297. }
  298. // check if new refresh rate is even valid
  299. try {
  300. DateTimeParser::parseDuration($newRefreshRate);
  301. } catch (InvalidDataException $ex) {
  302. return null;
  303. }
  304. return $newRefreshRate;
  305. }
  306. /**
  307. * update subscription stored in database
  308. * used to set:
  309. * - refreshrate
  310. * - source
  311. *
  312. * @param array $subscription
  313. * @param array $mutations
  314. */
  315. private function updateSubscription(array $subscription, array $mutations) {
  316. if (empty($mutations)) {
  317. return;
  318. }
  319. $propPatch = new PropPatch($mutations);
  320. $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
  321. $propPatch->commit();
  322. }
  323. /**
  324. * This method will strip authentication information and replace the
  325. * 'webcal' or 'webcals' protocol scheme
  326. *
  327. * @param string $url
  328. * @return string|null
  329. */
  330. private function cleanURL(string $url) {
  331. $parsed = parse_url($url);
  332. if ($parsed === false) {
  333. return null;
  334. }
  335. if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
  336. $scheme = 'http';
  337. } else {
  338. $scheme = 'https';
  339. }
  340. $host = $parsed['host'] ?? '';
  341. $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
  342. $path = $parsed['path'] ?? '';
  343. $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
  344. $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
  345. $cleanURL = "$scheme://$host$port$path$query$fragment";
  346. // parse_url is giving some weird results if no url and no :// is given,
  347. // so let's test the url again
  348. $parsedClean = parse_url($cleanURL);
  349. if ($parsedClean === false || !isset($parsedClean['host'])) {
  350. return null;
  351. }
  352. return $cleanURL;
  353. }
  354. /**
  355. * Returns a random uri for a calendar-object
  356. *
  357. * @return string
  358. */
  359. public function getRandomCalendarObjectUri():string {
  360. return UUIDUtil::getUUID() . '.ics';
  361. }
  362. }