// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "golang.org/x/net/bpf" ) // MulticastTTL returns the time-to-live field value for outgoing // multicast packets. func (c *dgramOpt) MulticastTTL() (int, error) { if !c.ok() { return 0, errInvalidConn } so, ok := sockOpts[ssoMulticastTTL] if !ok { return 0, errNotImplemented } return so.GetInt(c.Conn) } // SetMulticastTTL sets the time-to-live field value for future // outgoing multicast packets. func (c *dgramOpt) SetMulticastTTL(ttl int) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoMulticastTTL] if !ok { return errNotImplemented } return so.SetInt(c.Conn, ttl) } // MulticastInterface returns the default interface for multicast // packet transmissions. func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { if !c.ok() { return nil, errInvalidConn } so, ok := sockOpts[ssoMulticastInterface] if !ok { return nil, errNotImplemented } return so.getMulticastInterface(c.Conn) } // SetMulticastInterface sets the default interface for future // multicast packet transmissions. func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoMulticastInterface] if !ok { return errNotImplemented } return so.setMulticastInterface(c.Conn, ifi) } // MulticastLoopback reports whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) MulticastLoopback() (bool, error) { if !c.ok() { return false, errInvalidConn } so, ok := sockOpts[ssoMulticastLoopback] if !ok { return false, errNotImplemented } on, err := so.GetInt(c.Conn) if err != nil { return false, err } return on == 1, nil } // SetMulticastLoopback sets whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) SetMulticastLoopback(on bool) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoMulticastLoopback] if !ok { return errNotImplemented } return so.SetInt(c.Conn, boolint(on)) } // JoinGroup joins the group address group on the interface ifi. // By default all sources that can cast data to group are accepted. // It's possible to mute and unmute data transmission from a specific // source by using ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup. // JoinGroup uses the system assigned multicast interface when ifi is // nil, although this is not recommended because the assignment // depends on platforms and sometimes it might require routing // configuration. func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoJoinGroup] if !ok { return errNotImplemented } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } return so.setGroup(c.Conn, ifi, grp) } // LeaveGroup leaves the group address group on the interface ifi // regardless of whether the group is any-source group or // source-specific group. func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoLeaveGroup] if !ok { return errNotImplemented } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } return so.setGroup(c.Conn, ifi, grp) } // JoinSourceSpecificGroup joins the source-specific group comprising // group and source on the interface ifi. // JoinSourceSpecificGroup uses the system assigned multicast // interface when ifi is nil, although this is not recommended because // the assignment depends on platforms and sometimes it might require // routing configuration. func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoJoinSourceGroup] if !ok { return errNotImplemented } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // LeaveSourceSpecificGroup leaves the source-specific group on the // interface ifi. func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoLeaveSourceGroup] if !ok { return errNotImplemented } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // ExcludeSourceSpecificGroup excludes the source-specific group from // the already joined any-source groups by JoinGroup on the interface // ifi. func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoBlockSourceGroup] if !ok { return errNotImplemented } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // IncludeSourceSpecificGroup includes the excluded source-specific // group by ExcludeSourceSpecificGroup again on the interface ifi. func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoUnblockSourceGroup] if !ok { return errNotImplemented } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // ICMPFilter returns an ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { if !c.ok() { return nil, errInvalidConn } so, ok := sockOpts[ssoICMPFilter] if !ok { return nil, errNotImplemented } return so.getICMPFilter(c.Conn) } // SetICMPFilter deploys the ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoICMPFilter] if !ok { return errNotImplemented } return so.setICMPFilter(c.Conn, f) } // SetBPF attaches a BPF program to the connection. // // Only supported on Linux. func (c *dgramOpt) SetBPF(filter []bpf.RawInstruction) error { if !c.ok() { return errInvalidConn } so, ok := sockOpts[ssoAttachFilter] if !ok { return errNotImplemented } return so.setBPF(c.Conn, filter) } ion> Nextcloud server, a safe home for all your data: https://github.com/nextcloud/serverwww-data
aboutsummaryrefslogtreecommitdiffstats
path: root/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php
blob: a0981e6dec16f609b2b4ce85ce1349dce0a8961d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OCA\DAV\CalDAV\WebcalCaching;

use OCA\DAV\CalDAV\CalDavBackend;
use OCP\AppFramework\Utility\ITimeFactory;
use Psr\Log\LoggerInterface;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\PropPatch;
use Sabre\VObject\Component;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\InvalidDataException;
use Sabre\VObject\ParseException;
use Sabre\VObject\Reader;
use Sabre\VObject\Recur\NoInstancesException;
use Sabre\VObject\Splitter\ICalendar;
use Sabre\VObject\UUIDUtil;
use function count;

class RefreshWebcalService {

	public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
	public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
	public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
	public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';

	public function __construct(
		private CalDavBackend $calDavBackend,
		private LoggerInterface $logger,
		private Connection $connection,
		private ITimeFactory $time,
	) {
	}

	public function refreshSubscription(string $principalUri, string $uri) {
		$subscription = $this->getSubscription($principalUri, $uri);
		$mutations = [];
		if (!$subscription) {
			return;
		}

		// Check the refresh rate if there is any
		if (!empty($subscription['{http://apple.com/ns/ical/}refreshrate'])) {
			// add the refresh interval to the lastmodified timestamp
			$refreshInterval = new \DateInterval($subscription['{http://apple.com/ns/ical/}refreshrate']);
			$updateTime = $this->time->getDateTime();
			$updateTime->setTimestamp($subscription['lastmodified'])->add($refreshInterval);
			if ($updateTime->getTimestamp() > $this->time->getTime()) {
				return;
			}
		}


		$webcalData = $this->connection->queryWebcalFeed($subscription);
		if (!$webcalData) {
			return;
		}

		$localData = $this->calDavBackend->getLimitedCalendarObjects((int)$subscription['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);

		$stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
		$stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
		$stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;

		try {
			$splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);

			while ($vObject = $splitter->getNext()) {
				/** @var Component $vObject */
				$compName = null;
				$uid = null;

				foreach ($vObject->getComponents() as $component) {
					if ($component->name === 'VTIMEZONE') {
						continue;
					}

					$compName = $component->name;

					if ($stripAlarms) {
						unset($component->{'VALARM'});
					}
					if ($stripAttachments) {
						unset($component->{'ATTACH'});
					}

					$uid = $component->{ 'UID' }->getValue();
				}

				if ($stripTodos && $compName === 'VTODO') {
					continue;
				}

				if (!isset($uid)) {
					continue;
				}

				try {
					$denormalized = $this->calDavBackend->getDenormalizedData($vObject->serialize());
				} catch (InvalidDataException|Forbidden $ex) {
					$this->logger->warning('Unable to denormalize calendar object from subscription {subscriptionId}', ['exception' => $ex, 'subscriptionId' => $subscription['id'], 'source' => $subscription['source']]);
					continue;
				}

				// Find all identical sets and remove them from the update
				if (isset($localData[$uid]) && $denormalized['etag'] === $localData[$uid]['etag']) {
					unset($localData[$uid]);
					continue;
				}

				$vObjectCopy = clone $vObject;
				$identical = isset($localData[$uid]) && $this->compareWithoutDtstamp($vObjectCopy, $localData[$uid]);
				if ($identical) {
					unset($localData[$uid]);
					continue;
				}

				// Find all modified sets and update them
				if (isset($localData[$uid]) && $denormalized['etag'] !== $localData[$uid]['etag']) {
					$this->calDavBackend->updateCalendarObject($subscription['id'], $localData[$uid]['uri'], $vObject->serialize(), CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
					unset($localData[$uid]);
					continue;
				}

				// Only entirely new events get created here
				try {
					$objectUri = $this->getRandomCalendarObjectUri();
					$this->calDavBackend->createCalendarObject($subscription['id'], $objectUri, $vObject->serialize(), CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
				} catch (NoInstancesException|BadRequest $ex) {
					$this->logger->warning('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $ex, 'subscriptionId' => $subscription['id'], 'source' => $subscription['source']]);
				}
			}

			$ids = array_map(static function ($dataSet): int {
				return (int)$dataSet['id'];
			}, $localData);
			$uris = array_map(static function ($dataSet): string {
				return $dataSet['uri'];
			}, $localData);

			if (!empty($ids) && !empty($uris)) {
				// Clean up on aisle 5
				// The only events left over in the $localData array should be those that don't exist upstream
				// All deleted VObjects from upstream are removed
				$this->calDavBackend->purgeCachedEventsForSubscription($subscription['id'], $ids, $uris);
			}

			$newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
			if ($newRefreshRate) {
				$mutations[self::REFRESH_RATE] = $newRefreshRate;
			}

			$this->updateSubscription($subscription, $mutations);
		} catch (ParseException $ex) {
			$this->logger->error('Subscription {subscriptionId} could not be refreshed due to a parsing error', ['exception' => $ex, 'subscriptionId' => $subscription['id']]);
		}
	}

	/**
	 * loads subscription from backend
	 */
	public function getSubscription(string $principalUri, string $uri): ?array {
		$subscriptions = array_values(array_filter(
			$this->calDavBackend->getSubscriptionsForUser($principalUri),
			function ($sub) use ($uri) {
				return $sub['uri'] === $uri;
			}
		));

		if (count($subscriptions) === 0) {
			return null;
		}

		return $subscriptions[0];
	}


	/**
	 * check if:
	 *  - current subscription stores a refreshrate
	 *  - the webcal feed suggests a refreshrate
	 *  - return suggested refreshrate if user didn't set a custom one
	 *
	 */
	private function checkWebcalDataForRefreshRate(array $subscription, string $webcalData): ?string {
		// if there is no refreshrate stored in the database, check the webcal feed
		// whether it suggests any refresh rate and store that in the database
		if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
			return null;
		}

		/** @var Component\VCalendar $vCalendar */
		$vCalendar = Reader::read($webcalData);

		$newRefreshRate = null;
		if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
			$newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
		}
		if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
			$newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
		}

		if (!$newRefreshRate) {
			return null;
		}

		// check if new refresh rate is even valid
		try {
			DateTimeParser::parseDuration($newRefreshRate);
		} catch (InvalidDataException $ex) {
			return null;
		}

		return $newRefreshRate;
	}

	/**
	 * update subscription stored in database
	 * used to set:
	 *  - refreshrate
	 *  - source
	 *
	 * @param array $subscription
	 * @param array $mutations
	 */
	private function updateSubscription(array $subscription, array $mutations) {
		if (empty($mutations)) {
			return;
		}

		$propPatch = new PropPatch($mutations);
		$this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
		$propPatch->commit();
	}

	/**
	 * Returns a random uri for a calendar-object
	 *
	 * @return string
	 */
	public function getRandomCalendarObjectUri():string {
		return UUIDUtil::getUUID() . '.ics';
	}

	private function compareWithoutDtstamp(Component $vObject, array $calendarObject): bool {
		foreach ($vObject->getComponents() as $component) {
			unset($component->{'DTSTAMP'});
		}

		$localVobject = Reader::read($calendarObject['calendardata']);
		foreach ($localVobject->getComponents() as $component) {
			unset($component->{'DTSTAMP'});
		}

		return strcasecmp($localVobject->serialize(), $vObject->serialize()) === 0;
	}
}