ipguard-api 0.1.0b6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ """Async DEALER/CURVE transport with correlated requests and bounded cleanup."""
2
+
3
+ import asyncio
4
+ import json
5
+ from collections.abc import Awaitable, Callable, Coroutine
6
+ from dataclasses import dataclass
7
+
8
+ import zmq
9
+ import zmq.asyncio
10
+ from zmq.utils.monitor import parse_monitor_message
11
+
12
+ from .errors import (
13
+ ConnectionFailureError,
14
+ InvalidInputError,
15
+ IpguardError,
16
+ RelayUnavailableError,
17
+ )
18
+ from .protocol import (
19
+ MAX_MESSAGE_BYTES,
20
+ Packet,
21
+ assert_android_metadata,
22
+ decode_frames,
23
+ validate_endpoint,
24
+ )
25
+ from .validation import validate_duration, validate_routing_identity
26
+
27
+ type PacketHandler = Callable[[Packet], Awaitable[None]]
28
+ type FailureHandler = Callable[[IpguardError], None]
29
+ type Predicate = Callable[[Packet], bool]
30
+ type SendGuard = Callable[[], None]
31
+
32
+
33
+ def _reader_task(
34
+ reader: Coroutine[object, object, None], name: str
35
+ ) -> asyncio.Task[None]:
36
+ try:
37
+ return asyncio.create_task(reader, name=name)
38
+ except BaseException:
39
+ reader.close()
40
+ raise
41
+
42
+
43
+ @dataclass(eq=False, slots=True)
44
+ class _Waiter:
45
+ predicate: Predicate
46
+ future: asyncio.Future[Packet]
47
+
48
+
49
+ class ZmqTransport:
50
+ """A single connection. It never replays requests or release writes."""
51
+
52
+ def __init__(
53
+ self,
54
+ identity: str,
55
+ endpoint: str,
56
+ timeout: float,
57
+ on_packet: PacketHandler,
58
+ on_failure: FailureHandler,
59
+ server_key: str | None = None,
60
+ ) -> None:
61
+ validate_endpoint(endpoint)
62
+ validate_routing_identity(identity)
63
+ timeout = validate_duration(timeout, 300)
64
+ self.identity, self.endpoint, self.timeout = identity, endpoint, timeout
65
+ self.on_packet, self.on_failure, self.server_key = (
66
+ on_packet,
67
+ on_failure,
68
+ server_key,
69
+ )
70
+ self._context: zmq.asyncio.Context | None = None
71
+ self._socket: zmq.asyncio.Socket | None = None
72
+ self._monitor: zmq.asyncio.Socket | None = None
73
+ self._reader: asyncio.Task[None] | None = None
74
+ self._monitor_reader: asyncio.Task[None] | None = None
75
+ self._pending: set[_Waiter] = set()
76
+ self._send_lock = asyncio.Lock()
77
+ self._closed = False
78
+
79
+ async def async_start(self) -> None:
80
+ if self.server_key is not None and not zmq.has("curve"):
81
+ raise ConnectionFailureError(
82
+ "CURVE support is unavailable in this runtime."
83
+ )
84
+ try:
85
+ context = self._context = zmq.asyncio.Context()
86
+ socket = self._socket = context.socket(zmq.DEALER)
87
+ socket.setsockopt(zmq.IDENTITY, self.identity.encode())
88
+ socket.setsockopt(zmq.LINGER, 0)
89
+ socket.setsockopt(zmq.IMMEDIATE, 1)
90
+ socket.setsockopt(zmq.MAXMSGSIZE, MAX_MESSAGE_BYTES)
91
+ socket.setsockopt(zmq.HANDSHAKE_IVL, int(self.timeout * 1000))
92
+ socket.setsockopt(zmq.TCP_KEEPALIVE, 1)
93
+ socket.setsockopt(zmq.TCP_KEEPALIVE_IDLE, 60)
94
+ socket.setsockopt(zmq.TCP_KEEPALIVE_INTVL, 60)
95
+ socket.setsockopt(zmq.TCP_KEEPALIVE_CNT, 3)
96
+ if self.server_key is not None:
97
+ public, secret = zmq.curve_keypair()
98
+ socket.curve_publickey, socket.curve_secretkey = public, secret
99
+ socket.curve_serverkey = self.server_key.encode("ascii")
100
+ self._monitor = socket.get_monitor_socket(
101
+ events=zmq.EVENT_DISCONNECTED
102
+ | zmq.EVENT_HANDSHAKE_FAILED_AUTH
103
+ | zmq.EVENT_HANDSHAKE_FAILED_PROTOCOL
104
+ )
105
+ socket.connect(self.endpoint)
106
+ self._reader = _reader_task(self._read(), "ipguard-reader")
107
+ self._monitor_reader = _reader_task(self._read_monitor(), "ipguard-monitor")
108
+ except BaseException as error:
109
+ await self.async_close()
110
+ if isinstance(
111
+ error, asyncio.CancelledError | KeyboardInterrupt | SystemExit
112
+ ):
113
+ raise
114
+ raise ConnectionFailureError(
115
+ "Could not initialize the IPGUARD connection."
116
+ ) from None
117
+
118
+ async def async_send(
119
+ self, packet: Packet, callee: str = "", *, before_send: SendGuard | None = None
120
+ ) -> None:
121
+ assert_android_metadata(packet)
122
+ header = packet["header"]
123
+ if not isinstance(header, dict) or header["sender"] != self.identity:
124
+ raise InvalidInputError("Message sender does not match this installation.")
125
+ routing = validate_routing_identity(callee) if callee else b""
126
+ payload = json.dumps(packet, separators=(",", ":")).encode()
127
+ if len(routing) + len(payload) > MAX_MESSAGE_BYTES:
128
+ raise InvalidInputError("Outgoing message exceeds supported bounds.")
129
+ frames = [routing, payload] if callee else [payload]
130
+ if callee and self._send_lock.locked():
131
+ raise RelayUnavailableError(
132
+ "The connection is busy; no release was queued."
133
+ )
134
+ try:
135
+ async with asyncio.timeout(self.timeout), self._send_lock:
136
+ if self._closed or self._socket is None:
137
+ raise ConnectionFailureError("IPGUARD connection is closed.")
138
+ if before_send is not None:
139
+ before_send()
140
+ try:
141
+ await self._socket.send_multipart(
142
+ frames, flags=zmq.DONTWAIT if callee else 0
143
+ )
144
+ except zmq.ZMQError:
145
+ raise ConnectionFailureError(
146
+ "Could not send to the IPGUARD service."
147
+ ) from None
148
+ except TimeoutError:
149
+ raise ConnectionFailureError(
150
+ "Timed out sending to the IPGUARD service."
151
+ ) from None
152
+
153
+ async def async_request(
154
+ self,
155
+ packet: Packet,
156
+ predicate: Predicate,
157
+ callee: str = "",
158
+ *,
159
+ before_send: SendGuard | None = None,
160
+ ) -> Packet:
161
+ waiter = _Waiter(predicate, asyncio.get_running_loop().create_future())
162
+ self._pending.add(waiter)
163
+ try:
164
+ await self.async_send(packet, callee, before_send=before_send)
165
+ async with asyncio.timeout(self.timeout):
166
+ return await waiter.future
167
+ except TimeoutError:
168
+ raise ConnectionFailureError(
169
+ "Timed out waiting for an IPGUARD response."
170
+ ) from None
171
+ finally:
172
+ self._pending.discard(waiter)
173
+ if not waiter.future.done():
174
+ waiter.future.cancel()
175
+ elif not waiter.future.cancelled():
176
+ waiter.future.exception()
177
+
178
+ async def _read(self) -> None:
179
+ assert self._socket is not None
180
+ try:
181
+ while not self._closed:
182
+ frames = await self._socket.recv_multipart()
183
+ packet = decode_frames(frames)
184
+ if packet is None:
185
+ continue
186
+ await self.on_packet(packet)
187
+ for waiter in tuple(self._pending):
188
+ if not waiter.future.done() and waiter.predicate(packet):
189
+ waiter.future.set_result(packet)
190
+ except asyncio.CancelledError:
191
+ raise
192
+ except IpguardError as error:
193
+ self._fail(error)
194
+ except Exception:
195
+ if not self._closed:
196
+ self._fail(
197
+ ConnectionFailureError(
198
+ "IPGUARD connection could not read service messages."
199
+ )
200
+ )
201
+
202
+ @property
203
+ def closed(self) -> bool:
204
+ return self._closed
205
+
206
+ async def _read_monitor(self) -> None:
207
+ assert self._monitor is not None
208
+ try:
209
+ while not self._closed:
210
+ message = parse_monitor_message(await self._monitor.recv_multipart())
211
+ if int(message["event"]) in (
212
+ zmq.EVENT_HANDSHAKE_FAILED_AUTH,
213
+ zmq.EVENT_HANDSHAKE_FAILED_PROTOCOL,
214
+ ):
215
+ self._fail(
216
+ ConnectionFailureError("IPGUARD secure handshake failed.")
217
+ )
218
+ return
219
+ if int(message["event"]) == zmq.EVENT_DISCONNECTED:
220
+ self._fail(
221
+ ConnectionFailureError("IPGUARD connection was interrupted.")
222
+ )
223
+ return
224
+ except asyncio.CancelledError:
225
+ raise
226
+ except Exception:
227
+ if not self._closed:
228
+ self._fail(ConnectionFailureError("IPGUARD connection monitor failed."))
229
+
230
+ def _fail(self, error: IpguardError) -> None:
231
+ if self._closed:
232
+ return
233
+ self._shutdown(error)
234
+ self.on_failure(error)
235
+
236
+ def _shutdown(self, error: IpguardError) -> None:
237
+ self._closed = True
238
+ for waiter in tuple(self._pending):
239
+ if not waiter.future.done():
240
+ waiter.future.set_exception(error)
241
+ self._pending.clear()
242
+ socket, self._socket = self._socket, None
243
+ monitor, self._monitor = self._monitor, None
244
+ for connection in (socket, monitor):
245
+ if connection is not None:
246
+ connection.close(linger=0)
247
+ current = asyncio.current_task()
248
+ for task in (self._reader, self._monitor_reader):
249
+ if task is not None and task is not current:
250
+ task.cancel()
251
+ context, self._context = self._context, None
252
+ if context is not None:
253
+ context.term()
254
+
255
+ async def async_close(self) -> None:
256
+ self._shutdown(ConnectionFailureError("IPGUARD connection is closed."))
257
+ current = asyncio.current_task()
258
+ tasks = [
259
+ task
260
+ for task in (self._reader, self._monitor_reader)
261
+ if task is not None and task is not current
262
+ ]
263
+ for task in tasks:
264
+ task.cancel()
265
+ await asyncio.gather(*tasks, return_exceptions=True)
@@ -0,0 +1,93 @@
1
+ """Local enrollment input validation; these functions perform no network IO."""
2
+
3
+ import re
4
+ from math import isfinite
5
+
6
+ from .errors import InvalidInputError
7
+ from .models import AuthIdentifier, IdentifierKind
8
+
9
+ _EMAIL = re.compile(r"[^\s@]+@[^\s@]+\.[^\s@]+", re.ASCII)
10
+ _PHONE = re.compile(r"00[1-9][0-9]{6,14}", re.ASCII)
11
+ _CODE = re.compile(r"[0-9]{6}", re.ASCII)
12
+ _CLIENT_MARKER = re.compile(
13
+ r"(?:^|[^a-z0-9])(?:cli|node[\s._-]*js|home[\s_-]*assistant|custom[\s_-]*client|codex|poc|proof[\s_-]*of[\s_-]*concept|automation|integration|script|python|curl|bot|macbook|macos|windows|linux|docker|terminal|laptop|desktop|raspberry[\s_-]*pi)(?:$|[^a-z0-9])",
14
+ re.IGNORECASE | re.ASCII,
15
+ )
16
+
17
+
18
+ def validate_utf8(value: str, maximum: int, message: str) -> bytes:
19
+ """Bound encoded text without including its contents in an error."""
20
+ if not isinstance(value, str) or len(value) > maximum:
21
+ raise InvalidInputError(message)
22
+ try:
23
+ encoded = value.encode("utf-8")
24
+ except UnicodeError:
25
+ raise InvalidInputError(message) from None
26
+ if len(encoded) > maximum:
27
+ raise InvalidInputError(message)
28
+ return encoded
29
+
30
+
31
+ def validate_routing_identity(identity: str) -> bytes:
32
+ """Validate a ZeroMQ routing identity before allocating or sending."""
33
+ encoded = validate_utf8(identity, 255, "Invalid board or installation identity.")
34
+ if not encoded or b"\0" in encoded:
35
+ raise InvalidInputError("Invalid board or installation identity.")
36
+ return encoded
37
+
38
+
39
+ def validate_duration(value: float, maximum: float) -> float:
40
+ """Reject non-numeric, unbounded and sub-millisecond durations."""
41
+ if (
42
+ isinstance(value, bool)
43
+ or not isinstance(value, (int, float))
44
+ or not 0.001 <= value <= maximum
45
+ or not isfinite(value)
46
+ ):
47
+ raise InvalidInputError(
48
+ "Timeouts and reconnect delays are outside supported bounds."
49
+ )
50
+ return float(value)
51
+
52
+
53
+ def validate_identifier(identifier: str) -> AuthIdentifier:
54
+ """Preserve email spelling or normalize an international phone to ``00``."""
55
+ validate_utf8(identifier, 1024, "Invalid account identifier.")
56
+ if not identifier.strip():
57
+ raise InvalidInputError(
58
+ "A registered email or international phone is required."
59
+ )
60
+ value = identifier.strip()
61
+ if _EMAIL.fullmatch(value):
62
+ validate_utf8(value, 320, "Invalid account identifier.")
63
+ return AuthIdentifier(IdentifierKind.EMAIL, value)
64
+ phone = re.sub(r"[\s().-]", "", value)
65
+ if phone.startswith("+"):
66
+ phone = f"00{phone[1:]}"
67
+ if not _PHONE.fullmatch(phone):
68
+ raise InvalidInputError(
69
+ "Use a registered email or an international phone number."
70
+ )
71
+ return AuthIdentifier(IdentifierKind.PHONE, phone)
72
+
73
+
74
+ def validate_verification_code(code: str) -> str:
75
+ """Require six ASCII digits as text, preserving any leading zero."""
76
+ if not isinstance(code, str) or not _CODE.fullmatch(code):
77
+ raise InvalidInputError("The verification code must contain six ASCII digits.")
78
+ return code
79
+
80
+
81
+ def validate_installation_label(label: str) -> str:
82
+ """Require a personal label without implementation identifiers."""
83
+ if not isinstance(label, str) or not label.strip() or len(label.strip()) > 80:
84
+ raise InvalidInputError(
85
+ "Choose a personal installation name of 1 to 80 characters."
86
+ )
87
+ value = label.strip()
88
+ validate_utf8(value, 320, "Invalid installation label.")
89
+ if _CLIENT_MARKER.search(value):
90
+ raise InvalidInputError(
91
+ "Choose a personal installation name without client markers."
92
+ )
93
+ return value
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.5
2
+ Name: ipguard-api
3
+ Version: 0.1.0b6
4
+ Summary: Typed asynchronous client for the IPGUARD cloud service
5
+ Project-URL: Repository, https://github.com/KennyTangHK/ipguard-api
6
+ Project-URL: Issues, https://github.com/KennyTangHK/ipguard-api/issues
7
+ Project-URL: Documentation, https://github.com/KennyTangHK/ipguard-api/blob/master/docs/USAGE.md
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3.14
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: <3.15,>=3.14.2
14
+ Requires-Dist: pyzmq<28,>=27.2.0
15
+ Description-Content-Type: text/markdown
16
+
17
+ # ipguard-api
18
+
19
+ Source repository: [KennyTangHK/ipguard-api](https://github.com/KennyTangHK/ipguard-api). The default branch is `master`.
20
+
21
+ **Beta software.** This software is not a stable release.
22
+
23
+ This is an independent community project. It is not affiliated with, sponsored by, or endorsed by IPGUARD, NACD, or Noralsy.
24
+
25
+ Use this software lawfully. Use it only with your own authorized account and with buildings or doors that you have permission to access and control. Do not use it for unauthorized access or abuse.
26
+
27
+ **Use at your own risk.** To the extent permitted by applicable law, the software is provided without warranty. Its authors and contributors accept no responsibility or liability for its use. The warranty and liability limits in the [Apache-2.0 license](LICENSE) apply.
28
+
29
+ `ipguard-api` is a typed asynchronous Python library for an authorized IPGUARD cloud account. It supports phone and email enrollment, ZeroMQ CURVE connections, relay discovery, incoming-call callbacks, and explicit remote release commands. It does not depend on Home Assistant.
30
+
31
+ **Video calling and camera streaming are not supported.** By default, incoming calls give passive notifications. The library does not retain media offers or answer calls. To attempt one immediate hangup after the notification, set `auto_hangup=True` for the client. This attempt is intended to trigger carrier-call fallback sooner. The provider and account configuration determine the actual routing and timing.
32
+
33
+ For enrollment, saved sessions, event subscriptions, and command errors, see [API usage](docs/USAGE.md). For tests and release builds, see [Development](DEVELOPMENT.md).
34
+
35
+ The [package metadata](pyproject.toml) defines the Python and dependency requirements. The [lockfile](uv.lock) records the resolved dependencies. The PyPI package is `ipguard-api`; the import package is `ipguard_api`. The separate Home Assistant integration is at [hass-ipguard](https://github.com/KennyTangHK/hass-ipguard).
36
+
37
+ The [protocol implementation](src/ipguard_api/protocol.py) defines the protocol behavior. The [handset profile](src/ipguard_api/models.py) defines the client metadata values. Direct enrollment uses unencrypted TCP to retrieve the server public key. The authenticated channel then uses CURVE. A board acknowledgement does not show the physical state of a door. Bluetooth, SIP, pickup, and media transport and decoding are outside the scope of this library. Local fixtures test client behavior with synthetic accounts. They do not show current provider acceptance or physical door outcomes.
38
+
39
+ ## Installation
40
+
41
+ After a release is published to PyPI, install the package:
42
+
43
+ ```sh
44
+ python -m pip install --pre ipguard-api
45
+ ```
46
+
47
+ The `--pre` option permits beta releases. To install this checkout, use `python -m pip install .`. For a locked test environment, see the [development guide](DEVELOPMENT.md). Installation and import do not enroll an account or open a connection.
@@ -0,0 +1,12 @@
1
+ ipguard_api/__init__.py,sha256=P0SJ5cBQMfUqVT4ATjzEqFNa0ydPX6UlnjD9VV59ENc,1393
2
+ ipguard_api/client.py,sha256=tcVBFUjsEzBbRKooSrlFRvbzbnzt3ZSQmuU3G03aLPw,32198
3
+ ipguard_api/errors.py,sha256=1InUEY9IHcA3ZBuy_W7v0PT05Botj3cYyU_17hcuLJs,1573
4
+ ipguard_api/models.py,sha256=Z1-zKgD_I_LcrHesEkEAV5Ny4eAgHYpZGt0y85gSGZ4,7586
5
+ ipguard_api/protocol.py,sha256=vngiLnqS6B2qSKb0DX0YRrE2HemanSvj9If9yHsmSY0,17293
6
+ ipguard_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ ipguard_api/transport.py,sha256=ocV-ZnnTsv7cLVc7M_wAcAB1pMFhsur3rXi8dq_Btts,10035
8
+ ipguard_api/validation.py,sha256=IwpeBc7dSny-AyNnFAMAULHoKp9bqmzZW8Sq8DYRwGw,3667
9
+ ipguard_api-0.1.0b6.dist-info/METADATA,sha256=TP8DsSUzI_c0yJCEp_K3zGUOtnnrxjQZ8ihVUw0Sf8c,3584
10
+ ipguard_api-0.1.0b6.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
11
+ ipguard_api-0.1.0b6.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
12
+ ipguard_api-0.1.0b6.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.