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.

RefreshWebcalJob.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2018 Georg Ehrke <oc.list@georgehrke.com>
  5. *
  6. * @author Georg Ehrke <oc.list@georgehrke.com>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  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\BackgroundJob;
  26. use GuzzleHttp\HandlerStack;
  27. use GuzzleHttp\Middleware;
  28. use OC\BackgroundJob\Job;
  29. use OCA\DAV\CalDAV\CalDavBackend;
  30. use OCP\AppFramework\Utility\ITimeFactory;
  31. use OCP\Http\Client\IClientService;
  32. use OCP\IConfig;
  33. use OCP\ILogger;
  34. use Psr\Http\Message\RequestInterface;
  35. use Psr\Http\Message\ResponseInterface;
  36. use Sabre\DAV\Exception\BadRequest;
  37. use Sabre\DAV\PropPatch;
  38. use Sabre\DAV\Xml\Property\Href;
  39. use Sabre\VObject\Component;
  40. use Sabre\VObject\DateTimeParser;
  41. use Sabre\VObject\InvalidDataException;
  42. use Sabre\VObject\ParseException;
  43. use Sabre\VObject\Reader;
  44. use Sabre\VObject\Splitter\ICalendar;
  45. class RefreshWebcalJob extends Job {
  46. /** @var CalDavBackend */
  47. private $calDavBackend;
  48. /** @var IClientService */
  49. private $clientService;
  50. /** @var IConfig */
  51. private $config;
  52. /** @var ILogger */
  53. private $logger;
  54. /** @var ITimeFactory */
  55. private $timeFactory;
  56. /** @var array */
  57. private $subscription;
  58. /**
  59. * RefreshWebcalJob constructor.
  60. *
  61. * @param CalDavBackend $calDavBackend
  62. * @param IClientService $clientService
  63. * @param IConfig $config
  64. * @param ILogger $logger
  65. * @param ITimeFactory $timeFactory
  66. */
  67. public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger, ITimeFactory $timeFactory) {
  68. $this->calDavBackend = $calDavBackend;
  69. $this->clientService = $clientService;
  70. $this->config = $config;
  71. $this->logger = $logger;
  72. $this->timeFactory = $timeFactory;
  73. }
  74. /**
  75. * this function is called at most every hour
  76. *
  77. * @inheritdoc
  78. */
  79. public function execute($jobList, ILogger $logger = null) {
  80. $subscription = $this->getSubscription($this->argument['principaluri'], $this->argument['uri']);
  81. if (!$subscription) {
  82. return;
  83. }
  84. // if no refresh rate was configured, just refresh once a week
  85. $subscriptionId = $subscription['id'];
  86. $refreshrate = $subscription['refreshrate'] ?? 'P1W';
  87. try {
  88. /** @var \DateInterval $dateInterval */
  89. $dateInterval = DateTimeParser::parseDuration($refreshrate);
  90. } catch(InvalidDataException $ex) {
  91. $this->logger->logException($ex);
  92. $this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid");
  93. return;
  94. }
  95. $interval = $this->getIntervalFromDateInterval($dateInterval);
  96. if (($this->timeFactory->getTime() - $this->lastRun) <= $interval) {
  97. return;
  98. }
  99. parent::execute($jobList, $logger);
  100. }
  101. /**
  102. * @param array $argument
  103. */
  104. protected function run($argument) {
  105. $subscription = $this->getSubscription($argument['principaluri'], $argument['uri']);
  106. $mutations = [];
  107. if (!$subscription) {
  108. return;
  109. }
  110. $webcalData = $this->queryWebcalFeed($subscription, $mutations);
  111. if (!$webcalData) {
  112. return;
  113. }
  114. $stripTodos = $subscription['striptodos'] ?? 1;
  115. $stripAlarms = $subscription['stripalarms'] ?? 1;
  116. $stripAttachments = $subscription['stripattachments'] ?? 1;
  117. try {
  118. $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
  119. // we wait with deleting all outdated events till we parsed the new ones
  120. // in case the new calendar is broken and `new ICalendar` throws a ParseException
  121. // the user will still see the old data
  122. $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
  123. while ($vObject = $splitter->getNext()) {
  124. /** @var Component $vObject */
  125. $uid = null;
  126. $compName = null;
  127. foreach ($vObject->getComponents() as $component) {
  128. if ($component->name === 'VTIMEZONE') {
  129. continue;
  130. }
  131. $uid = $component->{'UID'}->getValue();
  132. $compName = $component->name;
  133. if ($stripAlarms) {
  134. unset($component->{'VALARM'});
  135. }
  136. if ($stripAttachments) {
  137. unset($component->{'ATTACH'});
  138. }
  139. }
  140. if ($stripTodos && $compName === 'VTODO') {
  141. continue;
  142. }
  143. $uri = $uid . '.ics';
  144. $calendarData = $vObject->serialize();
  145. try {
  146. $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  147. } catch(BadRequest $ex) {
  148. $this->logger->logException($ex);
  149. }
  150. }
  151. $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
  152. if ($newRefreshRate) {
  153. $mutations['{http://apple.com/ns/ical/}refreshrate'] = $newRefreshRate;
  154. }
  155. $this->updateSubscription($subscription, $mutations);
  156. } catch(ParseException $ex) {
  157. $subscriptionId = $subscription['id'];
  158. $this->logger->logException($ex);
  159. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
  160. }
  161. }
  162. /**
  163. * gets webcal feed from remote server
  164. *
  165. * @param array $subscription
  166. * @param array &$mutations
  167. * @return null|string
  168. */
  169. private function queryWebcalFeed(array $subscription, array &$mutations) {
  170. $client = $this->clientService->newClient();
  171. $didBreak301Chain = false;
  172. $latestLocation = null;
  173. $handlerStack = HandlerStack::create();
  174. $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
  175. return $request
  176. ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
  177. ->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
  178. }));
  179. $handlerStack->push(Middleware::mapResponse(function(ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
  180. if (!$didBreak301Chain) {
  181. if ($response->getStatusCode() !== 301) {
  182. $didBreak301Chain = true;
  183. } else {
  184. $latestLocation = $response->getHeader('Location');
  185. }
  186. }
  187. return $response;
  188. }));
  189. $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
  190. $subscriptionId = $subscription['id'];
  191. $url = $this->cleanURL($subscription['source']);
  192. if ($url === null) {
  193. return null;
  194. }
  195. if ($allowLocalAccess !== 'yes') {
  196. $host = strtolower(parse_url($url, PHP_URL_HOST));
  197. // remove brackets from IPv6 addresses
  198. if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
  199. $host = substr($host, 1, -1);
  200. }
  201. // Disallow localhost and local network
  202. if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
  203. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  204. return null;
  205. }
  206. // Disallow hostname only
  207. if (substr_count($host, '.') === 0) {
  208. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  209. return null;
  210. }
  211. if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  212. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  213. return null;
  214. }
  215. }
  216. try {
  217. $params = [
  218. 'allow_redirects' => [
  219. 'redirects' => 10
  220. ],
  221. 'handler' => $handlerStack,
  222. ];
  223. $user = parse_url($subscription['source'], PHP_URL_USER);
  224. $pass = parse_url($subscription['source'], PHP_URL_PASS);
  225. if ($user !== null && $pass !== null) {
  226. $params['auth'] = [$user, $pass];
  227. }
  228. $response = $client->get($url, $params);
  229. $body = $response->getBody();
  230. if ($latestLocation) {
  231. $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
  232. }
  233. $contentType = $response->getHeader('Content-Type');
  234. $contentType = explode(';', $contentType, 2)[0];
  235. switch($contentType) {
  236. case 'application/calendar+json':
  237. try {
  238. $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
  239. } catch(\Exception $ex) {
  240. // In case of a parsing error return null
  241. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  242. return null;
  243. }
  244. return $jCalendar->serialize();
  245. case 'application/calendar+xml':
  246. try {
  247. $xCalendar = Reader::readXML($body);
  248. } catch(\Exception $ex) {
  249. // In case of a parsing error return null
  250. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  251. return null;
  252. }
  253. return $xCalendar->serialize();
  254. case 'text/calendar':
  255. default:
  256. try {
  257. $vCalendar = Reader::read($body);
  258. } catch(\Exception $ex) {
  259. // In case of a parsing error return null
  260. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  261. return null;
  262. }
  263. return $vCalendar->serialize();
  264. }
  265. } catch(\Exception $ex) {
  266. $this->logger->logException($ex);
  267. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
  268. return null;
  269. }
  270. }
  271. /**
  272. * loads subscription from backend
  273. *
  274. * @param string $principalUri
  275. * @param string $uri
  276. * @return array|null
  277. */
  278. private function getSubscription(string $principalUri, string $uri) {
  279. $subscriptions = array_values(array_filter(
  280. $this->calDavBackend->getSubscriptionsForUser($principalUri),
  281. function($sub) use ($uri) {
  282. return $sub['uri'] === $uri;
  283. }
  284. ));
  285. if (\count($subscriptions) === 0) {
  286. return null;
  287. }
  288. $this->subscription = $subscriptions[0];
  289. return $this->subscription;
  290. }
  291. /**
  292. * get total number of seconds from DateInterval object
  293. *
  294. * @param \DateInterval $interval
  295. * @return int
  296. */
  297. private function getIntervalFromDateInterval(\DateInterval $interval):int {
  298. return $interval->s
  299. + ($interval->i * 60)
  300. + ($interval->h * 60 * 60)
  301. + ($interval->d * 60 * 60 * 24)
  302. + ($interval->m * 60 * 60 * 24 * 30)
  303. + ($interval->y * 60 * 60 * 24 * 365);
  304. }
  305. /**
  306. * check if:
  307. * - current subscription stores a refreshrate
  308. * - the webcal feed suggests a refreshrate
  309. * - return suggested refreshrate if user didn't set a custom one
  310. *
  311. * @param array $subscription
  312. * @param string $webcalData
  313. * @return string|null
  314. */
  315. private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
  316. // if there is no refreshrate stored in the database, check the webcal feed
  317. // whether it suggests any refresh rate and store that in the database
  318. if (isset($subscription['refreshrate']) && $subscription['refreshrate'] !== null) {
  319. return null;
  320. }
  321. /** @var Component\VCalendar $vCalendar */
  322. $vCalendar = Reader::read($webcalData);
  323. $newRefreshrate = null;
  324. if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
  325. $newRefreshrate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
  326. }
  327. if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
  328. $newRefreshrate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
  329. }
  330. if (!$newRefreshrate) {
  331. return null;
  332. }
  333. // check if new refresh rate is even valid
  334. try {
  335. DateTimeParser::parseDuration($newRefreshrate);
  336. } catch(InvalidDataException $ex) {
  337. return null;
  338. }
  339. return $newRefreshrate;
  340. }
  341. /**
  342. * update subscription stored in database
  343. * used to set:
  344. * - refreshrate
  345. * - source
  346. *
  347. * @param array $subscription
  348. * @param array $mutations
  349. */
  350. private function updateSubscription(array $subscription, array $mutations) {
  351. if (empty($mutations)) {
  352. return;
  353. }
  354. $propPatch = new PropPatch($mutations);
  355. $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
  356. $propPatch->commit();
  357. }
  358. /**
  359. * This method will strip authentication information and replace the
  360. * 'webcal' or 'webcals' protocol scheme
  361. *
  362. * @param string $url
  363. * @return string|null
  364. */
  365. private function cleanURL(string $url) {
  366. $parsed = parse_url($url);
  367. if ($parsed === false) {
  368. return null;
  369. }
  370. if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
  371. $scheme = 'http';
  372. } else {
  373. $scheme = 'https';
  374. }
  375. $host = $parsed['host'] ?? '';
  376. $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
  377. $path = $parsed['path'] ?? '';
  378. $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
  379. $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
  380. $cleanURL = "$scheme://$host$port$path$query$fragment";
  381. // parse_url is giving some weird results if no url and no :// is given,
  382. // so let's test the url again
  383. $parsedClean = parse_url($cleanURL);
  384. if ($parsedClean === false || !isset($parsedClean['host'])) {
  385. return null;
  386. }
  387. return $cleanURL;
  388. }
  389. }