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.

449 lines
13 KiB

  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. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\DAV\BackgroundJob;
  25. use GuzzleHttp\HandlerStack;
  26. use GuzzleHttp\Middleware;
  27. use OC\BackgroundJob\Job;
  28. use OCA\DAV\CalDAV\CalDavBackend;
  29. use OCP\AppFramework\Utility\ITimeFactory;
  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. class RefreshWebcalJob extends Job {
  45. /** @var CalDavBackend */
  46. private $calDavBackend;
  47. /** @var IClientService */
  48. private $clientService;
  49. /** @var IConfig */
  50. private $config;
  51. /** @var ILogger */
  52. private $logger;
  53. /** @var ITimeFactory */
  54. private $timeFactory;
  55. /** @var array */
  56. private $subscription;
  57. /**
  58. * RefreshWebcalJob constructor.
  59. *
  60. * @param CalDavBackend $calDavBackend
  61. * @param IClientService $clientService
  62. * @param IConfig $config
  63. * @param ILogger $logger
  64. * @param ITimeFactory $timeFactory
  65. */
  66. public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger, ITimeFactory $timeFactory) {
  67. $this->calDavBackend = $calDavBackend;
  68. $this->clientService = $clientService;
  69. $this->config = $config;
  70. $this->logger = $logger;
  71. $this->timeFactory = $timeFactory;
  72. }
  73. /**
  74. * this function is called at most every hour
  75. *
  76. * @inheritdoc
  77. */
  78. public function execute($jobList, ILogger $logger = null) {
  79. $subscription = $this->getSubscription($this->argument['principaluri'], $this->argument['uri']);
  80. if (!$subscription) {
  81. return;
  82. }
  83. // if no refresh rate was configured, just refresh once a week
  84. $subscriptionId = $subscription['id'];
  85. $refreshrate = $subscription['refreshrate'] ?? 'P1W';
  86. try {
  87. /** @var \DateInterval $dateInterval */
  88. $dateInterval = DateTimeParser::parseDuration($refreshrate);
  89. } catch(InvalidDataException $ex) {
  90. $this->logger->logException($ex);
  91. $this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid");
  92. return;
  93. }
  94. $interval = $this->getIntervalFromDateInterval($dateInterval);
  95. if (($this->timeFactory->getTime() - $this->lastRun) <= $interval) {
  96. return;
  97. }
  98. parent::execute($jobList, $logger);
  99. }
  100. /**
  101. * @param array $argument
  102. */
  103. protected function run($argument) {
  104. $subscription = $this->getSubscription($argument['principaluri'], $argument['uri']);
  105. $mutations = [];
  106. if (!$subscription) {
  107. return;
  108. }
  109. $webcalData = $this->queryWebcalFeed($subscription, $mutations);
  110. if (!$webcalData) {
  111. return;
  112. }
  113. $stripTodos = $subscription['striptodos'] ?? 1;
  114. $stripAlarms = $subscription['stripalarms'] ?? 1;
  115. $stripAttachments = $subscription['stripattachments'] ?? 1;
  116. try {
  117. $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
  118. // we wait with deleting all outdated events till we parsed the new ones
  119. // in case the new calendar is broken and `new ICalendar` throws a ParseException
  120. // the user will still see the old data
  121. $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
  122. while ($vObject = $splitter->getNext()) {
  123. /** @var Component $vObject */
  124. $uid = null;
  125. $compName = null;
  126. foreach ($vObject->getComponents() as $component) {
  127. if ($component->name === 'VTIMEZONE') {
  128. continue;
  129. }
  130. $uid = $component->{'UID'}->getValue();
  131. $compName = $component->name;
  132. if ($stripAlarms) {
  133. unset($component->{'VALARM'});
  134. }
  135. if ($stripAttachments) {
  136. unset($component->{'ATTACH'});
  137. }
  138. }
  139. if ($stripTodos && $compName === 'VTODO') {
  140. continue;
  141. }
  142. $uri = $uid . '.ics';
  143. $calendarData = $vObject->serialize();
  144. try {
  145. $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  146. } catch(BadRequest $ex) {
  147. $this->logger->logException($ex);
  148. }
  149. }
  150. $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
  151. if ($newRefreshRate) {
  152. $mutations['{http://apple.com/ns/ical/}refreshrate'] = $newRefreshRate;
  153. }
  154. $this->updateSubscription($subscription, $mutations);
  155. } catch(ParseException $ex) {
  156. $subscriptionId = $subscription['id'];
  157. $this->logger->logException($ex);
  158. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
  159. }
  160. }
  161. /**
  162. * gets webcal feed from remote server
  163. *
  164. * @param array $subscription
  165. * @param array &$mutations
  166. * @return null|string
  167. */
  168. private function queryWebcalFeed(array $subscription, array &$mutations) {
  169. $client = $this->clientService->newClient();
  170. $didBreak301Chain = false;
  171. $latestLocation = null;
  172. $handlerStack = HandlerStack::create();
  173. $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
  174. return $request
  175. ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
  176. ->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
  177. }));
  178. $handlerStack->push(Middleware::mapResponse(function(ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
  179. if (!$didBreak301Chain) {
  180. if ($response->getStatusCode() !== 301) {
  181. $didBreak301Chain = true;
  182. } else {
  183. $latestLocation = $response->getHeader('Location');
  184. }
  185. }
  186. return $response;
  187. }));
  188. $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
  189. $subscriptionId = $subscription['id'];
  190. $url = $this->cleanURL($subscription['source']);
  191. if ($url === null) {
  192. return null;
  193. }
  194. if ($allowLocalAccess !== 'yes') {
  195. $host = strtolower(parse_url($url, PHP_URL_HOST));
  196. // remove brackets from IPv6 addresses
  197. if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
  198. $host = substr($host, 1, -1);
  199. }
  200. // Disallow localhost and local network
  201. if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
  202. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  203. return null;
  204. }
  205. // Disallow hostname only
  206. if (substr_count($host, '.') === 0) {
  207. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  208. return null;
  209. }
  210. if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  211. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  212. return null;
  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. * loads subscription from backend
  272. *
  273. * @param string $principalUri
  274. * @param string $uri
  275. * @return array|null
  276. */
  277. private function getSubscription(string $principalUri, string $uri) {
  278. $subscriptions = array_values(array_filter(
  279. $this->calDavBackend->getSubscriptionsForUser($principalUri),
  280. function($sub) use ($uri) {
  281. return $sub['uri'] === $uri;
  282. }
  283. ));
  284. if (\count($subscriptions) === 0) {
  285. return null;
  286. }
  287. $this->subscription = $subscriptions[0];
  288. return $this->subscription;
  289. }
  290. /**
  291. * get total number of seconds from DateInterval object
  292. *
  293. * @param \DateInterval $interval
  294. * @return int
  295. */
  296. private function getIntervalFromDateInterval(\DateInterval $interval):int {
  297. return $interval->s
  298. + ($interval->i * 60)
  299. + ($interval->h * 60 * 60)
  300. + ($interval->d * 60 * 60 * 24)
  301. + ($interval->m * 60 * 60 * 24 * 30)
  302. + ($interval->y * 60 * 60 * 24 * 365);
  303. }
  304. /**
  305. * check if:
  306. * - current subscription stores a refreshrate
  307. * - the webcal feed suggests a refreshrate
  308. * - return suggested refreshrate if user didn't set a custom one
  309. *
  310. * @param array $subscription
  311. * @param string $webcalData
  312. * @return string|null
  313. */
  314. private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
  315. // if there is no refreshrate stored in the database, check the webcal feed
  316. // whether it suggests any refresh rate and store that in the database
  317. if (isset($subscription['refreshrate']) && $subscription['refreshrate'] !== null) {
  318. return null;
  319. }
  320. /** @var Component\VCalendar $vCalendar */
  321. $vCalendar = Reader::read($webcalData);
  322. $newRefreshrate = null;
  323. if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
  324. $newRefreshrate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
  325. }
  326. if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
  327. $newRefreshrate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
  328. }
  329. if (!$newRefreshrate) {
  330. return null;
  331. }
  332. // check if new refresh rate is even valid
  333. try {
  334. DateTimeParser::parseDuration($newRefreshrate);
  335. } catch(InvalidDataException $ex) {
  336. return null;
  337. }
  338. return $newRefreshrate;
  339. }
  340. /**
  341. * update subscription stored in database
  342. * used to set:
  343. * - refreshrate
  344. * - source
  345. *
  346. * @param array $subscription
  347. * @param array $mutations
  348. */
  349. private function updateSubscription(array $subscription, array $mutations) {
  350. if (empty($mutations)) {
  351. return;
  352. }
  353. $propPatch = new PropPatch($mutations);
  354. $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
  355. $propPatch->commit();
  356. }
  357. /**
  358. * This method will strip authentication information and replace the
  359. * 'webcal' or 'webcals' protocol scheme
  360. *
  361. * @param string $url
  362. * @return string|null
  363. */
  364. private function cleanURL(string $url) {
  365. $parsed = parse_url($url);
  366. if ($parsed === false) {
  367. return null;
  368. }
  369. if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
  370. $scheme = 'http';
  371. } else {
  372. $scheme = 'https';
  373. }
  374. $host = $parsed['host'] ?? '';
  375. $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
  376. $path = $parsed['path'] ?? '';
  377. $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
  378. $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
  379. $cleanURL = "$scheme://$host$port$path$query$fragment";
  380. // parse_url is giving some weird results if no url and no :// is given,
  381. // so let's test the url again
  382. $parsedClean = parse_url($cleanURL);
  383. if ($parsedClean === false || !isset($parsedClean['host'])) {
  384. return null;
  385. }
  386. return $cleanURL;
  387. }
  388. }