@cryptotaxi247 / netdata-1 / commits / 6e90e9c7e

Recursively merge mqtt_websockets (#16755)

* initial version * basic GitHub Actions CI * Create README.md * run GitHub Action at least once weekly to check test pass if distro was updated but project doesn't get any change for long time * add test for rbuf_find_bytes * minor - add .vscode to .gitignore * minor - add CFLAGS to makefile * minor - silence unused var warning * minor - update readme * add submodules * initial commit * add README * allow setting MQTT LWT * allow setting LWT QOS * handle MQTT keep-alives properly * allow choosing keep alive time * handle WS_OP_CONNECTION_CLOSE * allow sending other frames than WS_OP_BINARY_FRAME * minor readability improvements * work on graceful disconnect * reset ws_client state on subsequent connections * implement mqtt_wss_destroy * more descriptive RC for mqtt_wss_service * properly free/destroy SSL * work on reconnect * set return code for WS disconnect * Less logging under normal operation * readme point to `test.c` as how-to for now * OpenSSL certificate checking by default * reset poll_fds on reconnect * fix older SSL versions * empty install and dist targets * fix LGTM warning * add rbuf_get_capacity * gh actions test * ws_ping impl * test.c - port as cmd line param * properly handle WebSocket disconnect packet * initial HTTPS proxy support * remove base64 submodule, use OpenSSL * change to urandom * ws_client_process WS_RAW retval fix * coverity fixes * CID 1448838 * CID 1448836 * CID 1448829 * test check for error on init * make it play nicer with automake projects * MQTT-C coverity fixes * Create codeql-analysis.yml * Make typedef introduce a new name for struct. (#2) * add autotools related files to gitignore * minor - silence -Wmaybe-uninitialized warning * reinit on MQTT clean session connect * fix apple endianness functions * add libcrypto for macos * MacOS compatibility * fix FreeBSD build * use TLS SNI * propagate buffer full EC to app layer * store buffer sizes in mqtt_wss_client * allow auto buffer growth on buffer too small * quicker connection drop on BUFFER FULL * always clear last_ec on connect * parse all HTTP headers * minor - rename constant for clarity * rename idx and idx2 for code readability * limit response header field count * flush not needed, replace with descriptive err msg * bump MQTT-C * Blocking publish and inflight MQTT-C buffer growth * update obsolete comment * add missing unlock in error case * fix EINTR * initial MQTT 5 implementation Implements minimal MQTT 5 features. Up to QoS1 * fixes for bugs in initial MQTT5 implementation * initial statistics support * fix vbi parser * initial base http proxy auth support * fix base64 helper for longer credentials * minor - create with single allocation * allow defining custom alloc functions for user * Allow custom memory fncs and macros by user (#5) * update crbuf module * allow custom malloc, free, strdup, calloc ... * use long long for till_next_keep_alive * dont send PUBACK on QOS0 (#6) * fix publish parser (#7) * mark QoS0 as GC on send (#8) * log extra info in case of OpenSSL error (#9) * log extra info in case of SSL error * fix build error with older SSL (#10) * adds possibility to decrypt traffic with wireshark for debugging (#13) * initial commit * add fncs key:uint64 and data:opaque ptr * add uint64_t key iterator * add github test runner * start working on proper tests * Initial support for topic aliases (#12) Add support for topic alias functionality for PUBLISH packets also adds support for parsing all MQTT properties as opposed to just skipping and ignoring them (what we did previously) * implement c_rhash_iter_str_keys + tests * Fixes of Topic Alias implementation (#14) * initial removal of mqtt-c support (#15) * honor max msglen for server (#19) * Update README.md (#20) * memory align fragments (#21) * Remove mqtt_websocket submodule * Remove c-rbuf and c_rhash submodules * Exclude mqtt_websockets from Codacy It seems that it was excluded before merging the mqtt_websockets submodule. --------- Co-authored-by: Timotej Šiškovič <timotejs@gmail.com> Co-authored-by: Timotej S <6674623+underhood@users.noreply.github.com> Co-authored-by: Emmanuel Vasilakis <mrzammler@mm.st>

vkalintiris committed Jan 11, 2024 at 20:03 UTC 6e90e9c7e823356b8ff5dc86f37f60760b945ec0
49 files changed +9290 -4
.codacy.yml
+1
@@ -22,3 +22,4 @@ exclude_paths:
22 - build/**
23 - build_external/**
24 - packaging/**
25 + - mqtt_websockets/**
.gitmodules
-3
@@ -1,6 +1,3 @@
1 -[submodule "mqtt_websockets"]
2 - path = mqtt_websockets
3 - url = https://github.com/underhood/mqtt_websockets.git
1 [submodule "aclk/aclk-schemas"]
2 path = aclk/aclk-schemas
3 url = https://github.com/netdata/aclk-schemas.git
mqtt_websockets deleted
-1
@@ -1 +0,0 @@
1 -Subproject commit 6664789ccf57c95451638364f544d1679efd910e
mqtt_websockets/.github/workflows/run-tests.yaml new
+14
@@ -0,0 +1,14 @@
1 +name: run-tests
2 +on:
3 + push:
4 + schedule:
5 + - cron: '5 3 * * 0'
6 + pull_request:
7 +jobs:
8 + run-tests:
9 + runs-on: ubuntu-latest
10 + steps:
11 + - name: Install ruby and deps
12 + run: sudo apt-get install ruby ruby-dev mosquitto
13 + - name: Checkout
14 + uses: actions/checkout@v2
mqtt_websockets/.gitignore new
+10
@@ -0,0 +1,10 @@
1 +build/*
2 +!build/.keep
3 +test
4 +.vscode
5 +mqtt/mqtt.c
6 +mqtt/include/mqtt.h
7 +libmqttwebsockets.*
8 +*.o
9 +.dirstamp
10 +.deps
mqtt_websockets/LICENSE new
+674
@@ -0,0 +1,674 @@
1 + GNU GENERAL PUBLIC LICENSE
2 + Version 3, 29 June 2007
3 +
4 + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5 + Everyone is permitted to copy and distribute verbatim copies
6 + of this license document, but changing it is not allowed.
7 +
8 + Preamble
9 +
10 + The GNU General Public License is a free, copyleft license for
11 +software and other kinds of works.
12 +
13 + The licenses for most software and other practical works are designed
14 +to take away your freedom to share and change the works. By contrast,
15 +the GNU General Public License is intended to guarantee your freedom to
16 +share and change all versions of a program--to make sure it remains free
17 +software for all its users. We, the Free Software Foundation, use the
18 +GNU General Public License for most of our software; it applies also to
19 +any other work released this way by its authors. You can apply it to
20 +your programs, too.
21 +
22 + When we speak of free software, we are referring to freedom, not
23 +price. Our General Public Licenses are designed to make sure that you
24 +have the freedom to distribute copies of free software (and charge for
25 +them if you wish), that you receive source code or can get it if you
26 +want it, that you can change the software or use pieces of it in new
27 +free programs, and that you know you can do these things.
28 +
29 + To protect your rights, we need to prevent others from denying you
30 +these rights or asking you to surrender the rights. Therefore, you have
31 +certain responsibilities if you distribute copies of the software, or if
32 +you modify it: responsibilities to respect the freedom of others.
33 +
34 + For example, if you distribute copies of such a program, whether
35 +gratis or for a fee, you must pass on to the recipients the same
36 +freedoms that you received. You must make sure that they, too, receive
37 +or can get the source code. And you must show them these terms so they
38 +know their rights.
39 +
40 + Developers that use the GNU GPL protect your rights with two steps:
41 +(1) assert copyright on the software, and (2) offer you this License
42 +giving you legal permission to copy, distribute and/or modify it.
43 +
44 + For the developers' and authors' protection, the GPL clearly explains
45 +that there is no warranty for this free software. For both users' and
46 +authors' sake, the GPL requires that modified versions be marked as
47 +changed, so that their problems will not be attributed erroneously to
48 +authors of previous versions.
49 +
50 + Some devices are designed to deny users access to install or run
51 +modified versions of the software inside them, although the manufacturer
52 +can do so. This is fundamentally incompatible with the aim of
53 +protecting users' freedom to change the software. The systematic
54 +pattern of such abuse occurs in the area of products for individuals to
55 +use, which is precisely where it is most unacceptable. Therefore, we
56 +have designed this version of the GPL to prohibit the practice for those
57 +products. If such problems arise substantially in other domains, we
58 +stand ready to extend this provision to those domains in future versions
59 +of the GPL, as needed to protect the freedom of users.
60 +
61 + Finally, every program is threatened constantly by software patents.
62 +States should not allow patents to restrict development and use of
63 +software on general-purpose computers, but in those that do, we wish to
64 +avoid the special danger that patents applied to a free program could
65 +make it effectively proprietary. To prevent this, the GPL assures that
66 +patents cannot be used to render the program non-free.
67 +
68 + The precise terms and conditions for copying, distribution and
69 +modification follow.
70 +
71 + TERMS AND CONDITIONS
72 +
73 + 0. Definitions.
74 +
75 + "This License" refers to version 3 of the GNU General Public License.
76 +
77 + "Copyright" also means copyright-like laws that apply to other kinds of
78 +works, such as semiconductor masks.
79 +
80 + "The Program" refers to any copyrightable work licensed under this
81 +License. Each licensee is addressed as "you". "Licensees" and
82 +"recipients" may be individuals or organizations.
83 +
84 + To "modify" a work means to copy from or adapt all or part of the work
85 +in a fashion requiring copyright permission, other than the making of an
86 +exact copy. The resulting work is called a "modified version" of the
87 +earlier work or a work "based on" the earlier work.
88 +
89 + A "covered work" means either the unmodified Program or a work based
90 +on the Program.
91 +
92 + To "propagate" a work means to do anything with it that, without
93 +permission, would make you directly or secondarily liable for
94 +infringement under applicable copyright law, except executing it on a
95 +computer or modifying a private copy. Propagation includes copying,
96 +distribution (with or without modification), making available to the
97 +public, and in some countries other activities as well.
98 +
99 + To "convey" a work means any kind of propagation that enables other
100 +parties to make or receive copies. Mere interaction with a user through
101 +a computer network, with no transfer of a copy, is not conveying.
102 +
103 + An interactive user interface displays "Appropriate Legal Notices"
104 +to the extent that it includes a convenient and prominently visible
105 +feature that (1) displays an appropriate copyright notice, and (2)
106 +tells the user that there is no warranty for the work (except to the
107 +extent that warranties are provided), that licensees may convey the
108 +work under this License, and how to view a copy of this License. If
109 +the interface presents a list of user commands or options, such as a
110 +menu, a prominent item in the list meets this criterion.
111 +
112 + 1. Source Code.
113 +
114 + The "source code" for a work means the preferred form of the work
115 +for making modifications to it. "Object code" means any non-source
116 +form of a work.
117 +
118 + A "Standard Interface" means an interface that either is an official
119 +standard defined by a recognized standards body, or, in the case of
120 +interfaces specified for a particular programming language, one that
121 +is widely used among developers working in that language.
122 +
123 + The "System Libraries" of an executable work include anything, other
124 +than the work as a whole, that (a) is included in the normal form of
125 +packaging a Major Component, but which is not part of that Major
126 +Component, and (b) serves only to enable use of the work with that
127 +Major Component, or to implement a Standard Interface for which an
128 +implementation is available to the public in source code form. A
129 +"Major Component", in this context, means a major essential component
130 +(kernel, window system, and so on) of the specific operating system
131 +(if any) on which the executable work runs, or a compiler used to
132 +produce the work, or an object code interpreter used to run it.
133 +
134 + The "Corresponding Source" for a work in object code form means all
135 +the source code needed to generate, install, and (for an executable
136 +work) run the object code and to modify the work, including scripts to
137 +control those activities. However, it does not include the work's
138 +System Libraries, or general-purpose tools or generally available free
139 +programs which are used unmodified in performing those activities but
140 +which are not part of the work. For example, Corresponding Source
141 +includes interface definition files associated with source files for
142 +the work, and the source code for shared libraries and dynamically
143 +linked subprograms that the work is specifically designed to require,
144 +such as by intimate data communication or control flow between those
145 +subprograms and other parts of the work.
146 +
147 + The Corresponding Source need not include anything that users
148 +can regenerate automatically from other parts of the Corresponding
149 +Source.
150 +
151 + The Corresponding Source for a work in source code form is that
152 +same work.
153 +
154 + 2. Basic Permissions.
155 +
156 + All rights granted under this License are granted for the term of
157 +copyright on the Program, and are irrevocable provided the stated
158 +conditions are met. This License explicitly affirms your unlimited
159 +permission to run the unmodified Program. The output from running a
160 +covered work is covered by this License only if the output, given its
161 +content, constitutes a covered work. This License acknowledges your
162 +rights of fair use or other equivalent, as provided by copyright law.
163 +
164 + You may make, run and propagate covered works that you do not
165 +convey, without conditions so long as your license otherwise remains
166 +in force. You may convey covered works to others for the sole purpose
167 +of having them make modifications exclusively for you, or provide you
168 +with facilities for running those works, provided that you comply with
169 +the terms of this License in conveying all material for which you do
170 +not control copyright. Those thus making or running the covered works
171 +for you must do so exclusively on your behalf, under your direction
172 +and control, on terms that prohibit them from making any copies of
173 +your copyrighted material outside their relationship with you.
174 +
175 + Conveying under any other circumstances is permitted solely under
176 +the conditions stated below. Sublicensing is not allowed; section 10
177 +makes it unnecessary.
178 +
179 + 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 +
181 + No covered work shall be deemed part of an effective technological
182 +measure under any applicable law fulfilling obligations under article
183 +11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 +similar laws prohibiting or restricting circumvention of such
185 +measures.
186 +
187 + When you convey a covered work, you waive any legal power to forbid
188 +circumvention of technological measures to the extent such circumvention
189 +is effected by exercising rights under this License with respect to
190 +the covered work, and you disclaim any intention to limit operation or
191 +modification of the work as a means of enforcing, against the work's
192 +users, your or third parties' legal rights to forbid circumvention of
193 +technological measures.
194 +
195 + 4. Conveying Verbatim Copies.
196 +
197 + You may convey verbatim copies of the Program's source code as you
198 +receive it, in any medium, provided that you conspicuously and
199 +appropriately publish on each copy an appropriate copyright notice;
200 +keep intact all notices stating that this License and any
201 +non-permissive terms added in accord with section 7 apply to the code;
202 +keep intact all notices of the absence of any warranty; and give all
203 +recipients a copy of this License along with the Program.
204 +
205 + You may charge any price or no price for each copy that you convey,
206 +and you may offer support or warranty protection for a fee.
207 +
208 + 5. Conveying Modified Source Versions.
209 +
210 + You may convey a work based on the Program, or the modifications to
211 +produce it from the Program, in the form of source code under the
212 +terms of section 4, provided that you also meet all of these conditions:
213 +
214 + a) The work must carry prominent notices stating that you modified
215 + it, and giving a relevant date.
216 +
217 + b) The work must carry prominent notices stating that it is
218 + released under this License and any conditions added under section
219 + 7. This requirement modifies the requirement in section 4 to
220 + "keep intact all notices".
221 +
222 + c) You must license the entire work, as a whole, under this
223 + License to anyone who comes into possession of a copy. This
224 + License will therefore apply, along with any applicable section 7
225 + additional terms, to the whole of the work, and all its parts,
226 + regardless of how they are packaged. This License gives no
227 + permission to license the work in any other way, but it does not
228 + invalidate such permission if you have separately received it.
229 +
230 + d) If the work has interactive user interfaces, each must display
231 + Appropriate Legal Notices; however, if the Program has interactive
232 + interfaces that do not display Appropriate Legal Notices, your
233 + work need not make them do so.
234 +
235 + A compilation of a covered work with other separate and independent
236 +works, which are not by their nature extensions of the covered work,
237 +and which are not combined with it such as to form a larger program,
238 +in or on a volume of a storage or distribution medium, is called an
239 +"aggregate" if the compilation and its resulting copyright are not
240 +used to limit the access or legal rights of the compilation's users
241 +beyond what the individual works permit. Inclusion of a covered work
242 +in an aggregate does not cause this License to apply to the other
243 +parts of the aggregate.
244 +
245 + 6. Conveying Non-Source Forms.
246 +
247 + You may convey a covered work in object code form under the terms
248 +of sections 4 and 5, provided that you also convey the
249 +machine-readable Corresponding Source under the terms of this License,
250 +in one of these ways:
251 +
252 + a) Convey the object code in, or embodied in, a physical product
253 + (including a physical distribution medium), accompanied by the
254 + Corresponding Source fixed on a durable physical medium
255 + customarily used for software interchange.
256 +
257 + b) Convey the object code in, or embodied in, a physical product
258 + (including a physical distribution medium), accompanied by a
259 + written offer, valid for at least three years and valid for as
260 + long as you offer spare parts or customer support for that product
261 + model, to give anyone who possesses the object code either (1) a
262 + copy of the Corresponding Source for all the software in the
263 + product that is covered by this License, on a durable physical
264 + medium customarily used for software interchange, for a price no
265 + more than your reasonable cost of physically performing this
266 + conveying of source, or (2) access to copy the
267 + Corresponding Source from a network server at no charge.
268 +
269 + c) Convey individual copies of the object code with a copy of the
270 + written offer to provide the Corresponding Source. This
271 + alternative is allowed only occasionally and noncommercially, and
272 + only if you received the object code with such an offer, in accord
273 + with subsection 6b.
274 +
275 + d) Convey the object code by offering access from a designated
276 + place (gratis or for a charge), and offer equivalent access to the
277 + Corresponding Source in the same way through the same place at no
278 + further charge. You need not require recipients to copy the
279 + Corresponding Source along with the object code. If the place to
280 + copy the object code is a network server, the Corresponding Source
281 + may be on a different server (operated by you or a third party)
282 + that supports equivalent copying facilities, provided you maintain
283 + clear directions next to the object code saying where to find the
284 + Corresponding Source. Regardless of what server hosts the
285 + Corresponding Source, you remain obligated to ensure that it is
286 + available for as long as needed to satisfy these requirements.
287 +
288 + e) Convey the object code using peer-to-peer transmission, provided
289 + you inform other peers where the object code and Corresponding
290 + Source of the work are being offered to the general public at no
291 + charge under subsection 6d.
292 +
293 + A separable portion of the object code, whose source code is excluded
294 +from the Corresponding Source as a System Library, need not be
295 +included in conveying the object code work.
296 +
297 + A "User Product" is either (1) a "consumer product", which means any
298 +tangible personal property which is normally used for personal, family,
299 +or household purposes, or (2) anything designed or sold for incorporation
300 +into a dwelling. In determining whether a product is a consumer product,
301 +doubtful cases shall be resolved in favor of coverage. For a particular
302 +product received by a particular user, "normally used" refers to a
303 +typical or common use of that class of product, regardless of the status
304 +of the particular user or of the way in which the particular user
305 +actually uses, or expects or is expected to use, the product. A product
306 +is a consumer product regardless of whether the product has substantial
307 +commercial, industrial or non-consumer uses, unless such uses represent
308 +the only significant mode of use of the product.
309 +
310 + "Installation Information" for a User Product means any methods,
311 +procedures, authorization keys, or other information required to install
312 +and execute modified versions of a covered work in that User Product from
313 +a modified version of its Corresponding Source. The information must
314 +suffice to ensure that the continued functioning of the modified object
315 +code is in no case prevented or interfered with solely because
316 +modification has been made.
317 +
318 + If you convey an object code work under this section in, or with, or
319 +specifically for use in, a User Product, and the conveying occurs as
320 +part of a transaction in which the right of possession and use of the
321 +User Product is transferred to the recipient in perpetuity or for a
322 +fixed term (regardless of how the transaction is characterized), the
323 +Corresponding Source conveyed under this section must be accompanied
324 +by the Installation Information. But this requirement does not apply
325 +if neither you nor any third party retains the ability to install
326 +modified object code on the User Product (for example, the work has
327 +been installed in ROM).
328 +
329 + The requirement to provide Installation Information does not include a
330 +requirement to continue to provide support service, warranty, or updates
331 +for a work that has been modified or installed by the recipient, or for
332 +the User Product in which it has been modified or installed. Access to a
333 +network may be denied when the modification itself materially and
334 +adversely affects the operation of the network or violates the rules and
335 +protocols for communication across the network.
336 +
337 + Corresponding Source conveyed, and Installation Information provided,
338 +in accord with this section must be in a format that is publicly
339 +documented (and with an implementation available to the public in
340 +source code form), and must require no special password or key for
341 +unpacking, reading or copying.
342 +
343 + 7. Additional Terms.
344 +
345 + "Additional permissions" are terms that supplement the terms of this
346 +License by making exceptions from one or more of its conditions.
347 +Additional permissions that are applicable to the entire Program shall
348 +be treated as though they were included in this License, to the extent
349 +that they are valid under applicable law. If additional permissions
350 +apply only to part of the Program, that part may be used separately
351 +under those permissions, but the entire Program remains governed by
352 +this License without regard to the additional permissions.
353 +
354 + When you convey a copy of a covered work, you may at your option
355 +remove any additional permissions from that copy, or from any part of
356 +it. (Additional permissions may be written to require their own
357 +removal in certain cases when you modify the work.) You may place
358 +additional permissions on material, added by you to a covered work,
359 +for which you have or can give appropriate copyright permission.
360 +
361 + Notwithstanding any other provision of this License, for material you
362 +add to a covered work, you may (if authorized by the copyright holders of
363 +that material) supplement the terms of this License with terms:
364 +
365 + a) Disclaiming warranty or limiting liability differently from the
366 + terms of sections 15 and 16 of this License; or
367 +
368 + b) Requiring preservation of specified reasonable legal notices or
369 + author attributions in that material or in the Appropriate Legal
370 + Notices displayed by works containing it; or
371 +
372 + c) Prohibiting misrepresentation of the origin of that material, or
373 + requiring that modified versions of such material be marked in
374 + reasonable ways as different from the original version; or
375 +
376 + d) Limiting the use for publicity purposes of names of licensors or
377 + authors of the material; or
378 +
379 + e) Declining to grant rights under trademark law for use of some
380 + trade names, trademarks, or service marks; or
381 +
382 + f) Requiring indemnification of licensors and authors of that
383 + material by anyone who conveys the material (or modified versions of
384 + it) with contractual assumptions of liability to the recipient, for
385 + any liability that these contractual assumptions directly impose on
386 + those licensors and authors.
387 +
388 + All other non-permissive additional terms are considered "further
389 +restrictions" within the meaning of section 10. If the Program as you
390 +received it, or any part of it, contains a notice stating that it is
391 +governed by this License along with a term that is a further
392 +restriction, you may remove that term. If a license document contains
393 +a further restriction but permits relicensing or conveying under this
394 +License, you may add to a covered work material governed by the terms
395 +of that license document, provided that the further restriction does
396 +not survive such relicensing or conveying.
397 +
398 + If you add terms to a covered work in accord with this section, you
399 +must place, in the relevant source files, a statement of the
400 +additional terms that apply to those files, or a notice indicating
401 +where to find the applicable terms.
402 +
403 + Additional terms, permissive or non-permissive, may be stated in the
404 +form of a separately written license, or stated as exceptions;
405 +the above requirements apply either way.
406 +
407 + 8. Termination.
408 +
409 + You may not propagate or modify a covered work except as expressly
410 +provided under this License. Any attempt otherwise to propagate or
411 +modify it is void, and will automatically terminate your rights under
412 +this License (including any patent licenses granted under the third
413 +paragraph of section 11).
414 +
415 + However, if you cease all violation of this License, then your
416 +license from a particular copyright holder is reinstated (a)
417 +provisionally, unless and until the copyright holder explicitly and
418 +finally terminates your license, and (b) permanently, if the copyright
419 +holder fails to notify you of the violation by some reasonable means
420 +prior to 60 days after the cessation.
421 +
422 + Moreover, your license from a particular copyright holder is
423 +reinstated permanently if the copyright holder notifies you of the
424 +violation by some reasonable means, this is the first time you have
425 +received notice of violation of this License (for any work) from that
426 +copyright holder, and you cure the violation prior to 30 days after
427 +your receipt of the notice.
428 +
429 + Termination of your rights under this section does not terminate the
430 +licenses of parties who have received copies or rights from you under
431 +this License. If your rights have been terminated and not permanently
432 +reinstated, you do not qualify to receive new licenses for the same
433 +material under section 10.
434 +
435 + 9. Acceptance Not Required for Having Copies.
436 +
437 + You are not required to accept this License in order to receive or
438 +run a copy of the Program. Ancillary propagation of a covered work
439 +occurring solely as a consequence of using peer-to-peer transmission
440 +to receive a copy likewise does not require acceptance. However,
441 +nothing other than this License grants you permission to propagate or
442 +modify any covered work. These actions infringe copyright if you do
443 +not accept this License. Therefore, by modifying or propagating a
444 +covered work, you indicate your acceptance of this License to do so.
445 +
446 + 10. Automatic Licensing of Downstream Recipients.
447 +
448 + Each time you convey a covered work, the recipient automatically
449 +receives a license from the original licensors, to run, modify and
450 +propagate that work, subject to this License. You are not responsible
451 +for enforcing compliance by third parties with this License.
452 +
453 + An "entity transaction" is a transaction transferring control of an
454 +organization, or substantially all assets of one, or subdividing an
455 +organization, or merging organizations. If propagation of a covered
456 +work results from an entity transaction, each party to that
457 +transaction who receives a copy of the work also receives whatever
458 +licenses to the work the party's predecessor in interest had or could
459 +give under the previous paragraph, plus a right to possession of the
460 +Corresponding Source of the work from the predecessor in interest, if
461 +the predecessor has it or can get it with reasonable efforts.
462 +
463 + You may not impose any further restrictions on the exercise of the
464 +rights granted or affirmed under this License. For example, you may
465 +not impose a license fee, royalty, or other charge for exercise of
466 +rights granted under this License, and you may not initiate litigation
467 +(including a cross-claim or counterclaim in a lawsuit) alleging that
468 +any patent claim is infringed by making, using, selling, offering for
469 +sale, or importing the Program or any portion of it.
470 +
471 + 11. Patents.
472 +
473 + A "contributor" is a copyright holder who authorizes use under this
474 +License of the Program or a work on which the Program is based. The
475 +work thus licensed is called the contributor's "contributor version".
476 +
477 + A contributor's "essential patent claims" are all patent claims
478 +owned or controlled by the contributor, whether already acquired or
479 +hereafter acquired, that would be infringed by some manner, permitted
480 +by this License, of making, using, or selling its contributor version,
481 +but do not include claims that would be infringed only as a
482 +consequence of further modification of the contributor version. For
483 +purposes of this definition, "control" includes the right to grant
484 +patent sublicenses in a manner consistent with the requirements of
485 +this License.
486 +
487 + Each contributor grants you a non-exclusive, worldwide, royalty-free
488 +patent license under the contributor's essential patent claims, to
489 +make, use, sell, offer for sale, import and otherwise run, modify and
490 +propagate the contents of its contributor version.
491 +
492 + In the following three paragraphs, a "patent license" is any express
493 +agreement or commitment, however denominated, not to enforce a patent
494 +(such as an express permission to practice a patent or covenant not to
495 +sue for patent infringement). To "grant" such a patent license to a
496 +party means to make such an agreement or commitment not to enforce a
497 +patent against the party.
498 +
499 + If you convey a covered work, knowingly relying on a patent license,
500 +and the Corresponding Source of the work is not available for anyone
501 +to copy, free of charge and under the terms of this License, through a
502 +publicly available network server or other readily accessible means,
503 +then you must either (1) cause the Corresponding Source to be so
504 +available, or (2) arrange to deprive yourself of the benefit of the
505 +patent license for this particular work, or (3) arrange, in a manner
506 +consistent with the requirements of this License, to extend the patent
507 +license to downstream recipients. "Knowingly relying" means you have
508 +actual knowledge that, but for the patent license, your conveying the
509 +covered work in a country, or your recipient's use of the covered work
510 +in a country, would infringe one or more identifiable patents in that
511 +country that you have reason to believe are valid.
512 +
513 + If, pursuant to or in connection with a single transaction or
514 +arrangement, you convey, or propagate by procuring conveyance of, a
515 +covered work, and grant a patent license to some of the parties
516 +receiving the covered work authorizing them to use, propagate, modify
517 +or convey a specific copy of the covered work, then the patent license
518 +you grant is automatically extended to all recipients of the covered
519 +work and works based on it.
520 +
521 + A patent license is "discriminatory" if it does not include within
522 +the scope of its coverage, prohibits the exercise of, or is
523 +conditioned on the non-exercise of one or more of the rights that are
524 +specifically granted under this License. You may not convey a covered
525 +work if you are a party to an arrangement with a third party that is
526 +in the business of distributing software, under which you make payment
527 +to the third party based on the extent of your activity of conveying
528 +the work, and under which the third party grants, to any of the
529 +parties who would receive the covered work from you, a discriminatory
530 +patent license (a) in connection with copies of the covered work
531 +conveyed by you (or copies made from those copies), or (b) primarily
532 +for and in connection with specific products or compilations that
533 +contain the covered work, unless you entered into that arrangement,
534 +or that patent license was granted, prior to 28 March 2007.
535 +
536 + Nothing in this License shall be construed as excluding or limiting
537 +any implied license or other defenses to infringement that may
538 +otherwise be available to you under applicable patent law.
539 +
540 + 12. No Surrender of Others' Freedom.
541 +
542 + If conditions are imposed on you (whether by court order, agreement or
543 +otherwise) that contradict the conditions of this License, they do not
544 +excuse you from the conditions of this License. If you cannot convey a
545 +covered work so as to satisfy simultaneously your obligations under this
546 +License and any other pertinent obligations, then as a consequence you may
547 +not convey it at all. For example, if you agree to terms that obligate you
548 +to collect a royalty for further conveying from those to whom you convey
549 +the Program, the only way you could satisfy both those terms and this
550 +License would be to refrain entirely from conveying the Program.
551 +
552 + 13. Use with the GNU Affero General Public License.
553 +
554 + Notwithstanding any other provision of this License, you have
555 +permission to link or combine any covered work with a work licensed
556 +under version 3 of the GNU Affero General Public License into a single
557 +combined work, and to convey the resulting work. The terms of this
558 +License will continue to apply to the part which is the covered work,
559 +but the special requirements of the GNU Affero General Public License,
560 +section 13, concerning interaction through a network will apply to the
561 +combination as such.
562 +
563 + 14. Revised Versions of this License.
564 +
565 + The Free Software Foundation may publish revised and/or new versions of
566 +the GNU General Public License from time to time. Such new versions will
567 +be similar in spirit to the present version, but may differ in detail to
568 +address new problems or concerns.
569 +
570 + Each version is given a distinguishing version number. If the
571 +Program specifies that a certain numbered version of the GNU General
572 +Public License "or any later version" applies to it, you have the
573 +option of following the terms and conditions either of that numbered
574 +version or of any later version published by the Free Software
575 +Foundation. If the Program does not specify a version number of the
576 +GNU General Public License, you may choose any version ever published
577 +by the Free Software Foundation.
578 +
579 + If the Program specifies that a proxy can decide which future
580 +versions of the GNU General Public License can be used, that proxy's
581 +public statement of acceptance of a version permanently authorizes you
582 +to choose that version for the Program.
583 +
584 + Later license versions may give you additional or different
585 +permissions. However, no additional obligations are imposed on any
586 +author or copyright holder as a result of your choosing to follow a
587 +later version.
588 +
589 + 15. Disclaimer of Warranty.
590 +
591 + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 +ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 +
600 + 16. Limitation of Liability.
601 +
602 + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 +SUCH DAMAGES.
611 +
612 + 17. Interpretation of Sections 15 and 16.
613 +
614 + If the disclaimer of warranty and limitation of liability provided
615 +above cannot be given local legal effect according to their terms,
616 +reviewing courts shall apply local law that most closely approximates
617 +an absolute waiver of all civil liability in connection with the
618 +Program, unless a warranty or assumption of liability accompanies a
619 +copy of the Program in return for a fee.
620 +
621 + END OF TERMS AND CONDITIONS
622 +
623 + How to Apply These Terms to Your New Programs
624 +
625 + If you develop a new program, and you want it to be of the greatest
626 +possible use to the public, the best way to achieve this is to make it
627 +free software which everyone can redistribute and change under these terms.
628 +
629 + To do so, attach the following notices to the program. It is safest
630 +to attach them to the start of each source file to most effectively
631 +state the exclusion of warranty; and each file should have at least
632 +the "copyright" line and a pointer to where the full notice is found.
633 +
634 + <one line to give the program's name and a brief idea of what it does.>
635 + Copyright (C) <year> <name of author>
636 +
637 + This program is free software: you can redistribute it and/or modify
638 + it under the terms of the GNU General Public License as published by
639 + the Free Software Foundation, either version 3 of the License, or
640 + (at your option) any later version.
641 +
642 + This program is distributed in the hope that it will be useful,
643 + but WITHOUT ANY WARRANTY; without even the implied warranty of
644 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 + GNU General Public License for more details.
646 +
647 + You should have received a copy of the GNU General Public License
648 + along with this program. If not, see <https://www.gnu.org/licenses/>.
649 +
650 +Also add information on how to contact you by electronic and paper mail.
651 +
652 + If the program does terminal interaction, make it output a short
653 +notice like this when it starts in an interactive mode:
654 +
655 + <program> Copyright (C) <year> <name of author>
656 + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 + This is free software, and you are welcome to redistribute it
658 + under certain conditions; type `show c' for details.
659 +
660 +The hypothetical commands `show w' and `show c' should show the appropriate
661 +parts of the General Public License. Of course, your program's commands
662 +might be different; for a GUI interface, you would use an "about box".
663 +
664 + You should also get your employer (if you work as a programmer) or school,
665 +if any, to sign a "copyright disclaimer" for the program, if necessary.
666 +For more information on this, and how to apply and follow the GNU GPL, see
667 +<https://www.gnu.org/licenses/>.
668 +
669 + The GNU General Public License does not permit incorporating your program
670 +into proprietary programs. If your program is a subroutine library, you
671 +may consider it more useful to permit linking proprietary applications with
672 +the library. If this is what you want to do, use the GNU Lesser General
673 +Public License instead of this License. But first, please read
674 +<https://www.gnu.org/licenses/why-not-lgpl.html>.
mqtt_websockets/Makefile new
+61
@@ -0,0 +1,61 @@
1 +# Copyright (C) 2020 Timotej Šiškovič
2 +# SPDX-License-Identifier: GPL-3.0-only
3 +#
4 +# This program is free software: you can redistribute it and/or modify it
5 +# under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
6 +#
7 +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 +# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9 +# See the GNU General Public License for more details.
10 +#
11 +# You should have received a copy of the GNU General Public License along with this program.
12 +# If not, see <https://www.gnu.org/licenses/>.
13 +
14 +CC = gcc -std=gnu99
15 +CFLAGS = -Wextra -Wall `pkg-config --cflags openssl` `pkg-config --cflags libcrypto`
16 +BUILD_DIR = build
17 +
18 +INCLUDES = -Isrc/include -Ic-rbuf/include -Ic_rhash/include -Imqtt/include
19 +
20 +all: test
21 +
22 +$(BUILD_DIR)/c_rhash.o: c_rhash/src/c_rhash.c c_rhash/src/c_rhash_internal.h c_rhash/include/c_rhash.h
23 + $(CC) -o $(BUILD_DIR)/c_rhash.o -c c_rhash/src/c_rhash.c $(CFLAGS) $(INCLUDES)
24 +
25 +c-rbuf/build/ringbuffer.o:
26 + cd c-rbuf && $(MAKE) build/ringbuffer.o
27 +
28 +$(BUILD_DIR)/ws_client.o: src/ws_client.c src/include/ws_client.h src/include/common_internal.h
29 + $(CC) -o $(BUILD_DIR)/ws_client.o -c src/ws_client.c $(CFLAGS) $(INCLUDES)
30 +
31 +$(BUILD_DIR)/test.o: src/test.c src/include/ws_client.h libmqttwebsockets.a
32 + $(CC) -o $(BUILD_DIR)/test.o -c src/test.c $(CFLAGS) $(INCLUDES)
33 +
34 +$(BUILD_DIR)/mqtt_wss_log.o: src/mqtt_wss_log.c src/include/mqtt_wss_log.h
35 + $(CC) -o $(BUILD_DIR)/mqtt_wss_log.o -c src/mqtt_wss_log.c $(CFLAGS) $(INCLUDES)
36 +
37 +$(BUILD_DIR)/mqtt_wss_client.o: src/mqtt_wss_client.c src/include/mqtt_wss_client.h src/include/ws_client.h src/include/common_internal.h $(BUILD_DIR)/common_public.o
38 + $(CC) -o $(BUILD_DIR)/mqtt_wss_client.o -c src/mqtt_wss_client.c $(CFLAGS) $(INCLUDES)
39 +
40 +$(BUILD_DIR)/mqtt_ng.o: src/mqtt_ng.c src/include/mqtt_ng.h src/include/common_internal.h $(BUILD_DIR)/common_public.o
41 + $(CC) -o $(BUILD_DIR)/mqtt_ng.o -c src/mqtt_ng.c $(CFLAGS) $(INCLUDES)
42 +
43 +$(BUILD_DIR)/common_public.o: src/common_public.c src/include/common_public.h
44 + $(CC) -o $(BUILD_DIR)/common_public.o -c src/common_public.c $(CFLAGS) $(INCLUDES)
45 +
46 +libmqttwebsockets.a: $(BUILD_DIR)/mqtt_wss_client.o $(BUILD_DIR)/ws_client.o c-rbuf/build/ringbuffer.o $(BUILD_DIR)/c_rhash.o $(BUILD_DIR)/mqtt_wss_log.o $(BUILD_DIR)/mqtt_ng.o $(BUILD_DIR)/common_public.o
47 + ar rcs libmqttwebsockets.a $(BUILD_DIR)/mqtt_wss_client.o $(BUILD_DIR)/ws_client.o c-rbuf/build/ringbuffer.o $(BUILD_DIR)/c_rhash.o $(BUILD_DIR)/mqtt_wss_log.o $(BUILD_DIR)/mqtt_ng.o $(BUILD_DIR)/common_public.o
48 +
49 +test: $(BUILD_DIR)/test.o libmqttwebsockets.a
50 + $(CC) -o test $(BUILD_DIR)/test.o libmqttwebsockets.a `pkg-config --libs openssl` -lpthread $(CFLAGS)
51 +
52 +clean:
53 + rm -f $(BUILD_DIR)/*
54 + cd c-rbuf && $(MAKE) clean
55 + rm -f test libmqttwebsockets.a
56 +
57 +install:
58 +
59 +dist:
60 +
61 +distdir:
mqtt_websockets/README.md new
+12
@@ -0,0 +1,12 @@
1 +# mqtt_websockets
2 +
3 +Library to connect MQTT client over Websockets Secure (WSS).
4 +Documentation is pending. Best way to figure out how to use the library it to look at `src\test.c`.
5 +
6 +## License
7 +
8 +The Project is released under GPL v3 license. See [License](LICENSE)
9 +
10 +Uses following git submodules:
11 +- **c-rbuf**: under LGPL 3 by underhood
12 +- **c_rhash**: GPL 3 by underhood
mqtt_websockets/build/.keep
mqtt_websockets/c-rbuf/.github/workflows/codeql-analysis.yml new
+67
@@ -0,0 +1,67 @@
1 +# For most projects, this workflow file will not need changing; you simply need
2 +# to commit it to your repository.
3 +#
4 +# You may wish to alter this file to override the set of languages analyzed,
5 +# or to provide custom queries or build logic.
6 +#
7 +# ******** NOTE ********
8 +# We have attempted to detect the languages in your repository. Please check
9 +# the `language` matrix defined below to confirm you have the correct set of
10 +# supported CodeQL languages.
11 +#
12 +name: "CodeQL"
13 +
14 +on:
15 + push:
16 + branches: [ master ]
17 + pull_request:
18 + # The branches below must be a subset of the branches above
19 + branches: [ master ]
20 + schedule:
21 + - cron: '19 3 * * 1'
22 +
23 +jobs:
24 + analyze:
25 + name: Analyze
26 + runs-on: ubuntu-latest
27 +
28 + strategy:
29 + fail-fast: false
30 + matrix:
31 + language: [ 'cpp' ]
32 + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
33 + # Learn more:
34 + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
35 +
36 + steps:
37 + - name: Checkout repository
38 + uses: actions/checkout@v2
39 +
40 + # Initializes the CodeQL tools for scanning.
41 + - name: Initialize CodeQL
42 + uses: github/codeql-action/init@v1
43 + with:
44 + languages: ${{ matrix.language }}
45 + # If you wish to specify custom queries, you can do so here or in a config file.
46 + # By default, queries listed here will override any specified in a config file.
47 + # Prefix the list here with "+" to use these queries and those in the config file.
48 + # queries: ./path/to/local/query, your-org/your-repo/queries@main
49 +
50 + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
51 + # If this step fails, then you should remove it and run the build manually (see below)
52 + - name: Autobuild
53 + uses: github/codeql-action/autobuild@v1
54 +
55 + # ℹ️ Command-line programs to run using the OS shell.
56 + # 📚 https://git.io/JvXDl
57 +
58 + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
59 + # and modify them (or add more) to build your code if your project
60 + # uses a compiled language
61 +
62 + #- run: |
63 + # make bootstrap
64 + # make release
65 +
66 + - name: Perform CodeQL Analysis
67 + uses: github/codeql-action/analyze@v1
mqtt_websockets/c-rbuf/.github/workflows/run-tests.yaml new
+13
@@ -0,0 +1,13 @@
1 +name: run-tests
2 +on:
3 + push:
4 + schedule:
5 + - cron: '5 3 * * 0'
6 + pull_request:
7 +jobs:
8 + run-tests:
9 + runs-on: ubuntu-latest
10 + steps:
11 + - uses: actions/checkout@v2
12 + - run: make
13 + - run: ./test
mqtt_websockets/c-rbuf/.gitignore new
+8
@@ -0,0 +1,8 @@
1 +build/*
2 +!build/.keep
3 +libringbuffer.*
4 +test
5 +.vscode
6 +*.o
7 +.deps
8 +.dirstamp
mqtt_websockets/c-rbuf/LICENSE new
+165
@@ -0,0 +1,165 @@
1 + GNU LESSER GENERAL PUBLIC LICENSE
2 + Version 3, 29 June 2007
3 +
4 + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5 + Everyone is permitted to copy and distribute verbatim copies
6 + of this license document, but changing it is not allowed.
7 +
8 +
9 + This version of the GNU Lesser General Public License incorporates
10 +the terms and conditions of version 3 of the GNU General Public
11 +License, supplemented by the additional permissions listed below.
12 +
13 + 0. Additional Definitions.
14 +
15 + As used herein, "this License" refers to version 3 of the GNU Lesser
16 +General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 +General Public License.
18 +
19 + "The Library" refers to a covered work governed by this License,
20 +other than an Application or a Combined Work as defined below.
21 +
22 + An "Application" is any work that makes use of an interface provided
23 +by the Library, but which is not otherwise based on the Library.
24 +Defining a subclass of a class defined by the Library is deemed a mode
25 +of using an interface provided by the Library.
26 +
27 + A "Combined Work" is a work produced by combining or linking an
28 +Application with the Library. The particular version of the Library
29 +with which the Combined Work was made is also called the "Linked
30 +Version".
31 +
32 + The "Minimal Corresponding Source" for a Combined Work means the
33 +Corresponding Source for the Combined Work, excluding any source code
34 +for portions of the Combined Work that, considered in isolation, are
35 +based on the Application, and not on the Linked Version.
36 +
37 + The "Corresponding Application Code" for a Combined Work means the
38 +object code and/or source code for the Application, including any data
39 +and utility programs needed for reproducing the Combined Work from the
40 +Application, but excluding the System Libraries of the Combined Work.
41 +
42 + 1. Exception to Section 3 of the GNU GPL.
43 +
44 + You may convey a covered work under sections 3 and 4 of this License
45 +without being bound by section 3 of the GNU GPL.
46 +
47 + 2. Conveying Modified Versions.
48 +
49 + If you modify a copy of the Library, and, in your modifications, a
50 +facility refers to a function or data to be supplied by an Application
51 +that uses the facility (other than as an argument passed when the
52 +facility is invoked), then you may convey a copy of the modified
53 +version:
54 +
55 + a) under this License, provided that you make a good faith effort to
56 + ensure that, in the event an Application does not supply the
57 + function or data, the facility still operates, and performs
58 + whatever part of its purpose remains meaningful, or
59 +
60 + b) under the GNU GPL, with none of the additional permissions of
61 + this License applicable to that copy.
62 +
63 + 3. Object Code Incorporating Material from Library Header Files.
64 +
65 + The object code form of an Application may incorporate material from
66 +a header file that is part of the Library. You may convey such object
67 +code under terms of your choice, provided that, if the incorporated
68 +material is not limited to numerical parameters, data structure
69 +layouts and accessors, or small macros, inline functions and templates
70 +(ten or fewer lines in length), you do both of the following:
71 +
72 + a) Give prominent notice with each copy of the object code that the
73 + Library is used in it and that the Library and its use are
74 + covered by this License.
75 +
76 + b) Accompany the object code with a copy of the GNU GPL and this license
77 + document.
78 +
79 + 4. Combined Works.
80 +
81 + You may convey a Combined Work under terms of your choice that,
82 +taken together, effectively do not restrict modification of the
83 +portions of the Library contained in the Combined Work and reverse
84 +engineering for debugging such modifications, if you also do each of
85 +the following:
86 +
87 + a) Give prominent notice with each copy of the Combined Work that
88 + the Library is used in it and that the Library and its use are
89 + covered by this License.
90 +
91 + b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 + document.
93 +
94 + c) For a Combined Work that displays copyright notices during
95 + execution, include the copyright notice for the Library among
96 + these notices, as well as a reference directing the user to the
97 + copies of the GNU GPL and this license document.
98 +
99 + d) Do one of the following:
100 +
101 + 0) Convey the Minimal Corresponding Source under the terms of this
102 + License, and the Corresponding Application Code in a form
103 + suitable for, and under terms that permit, the user to
104 + recombine or relink the Application with a modified version of
105 + the Linked Version to produce a modified Combined Work, in the
106 + manner specified by section 6 of the GNU GPL for conveying
107 + Corresponding Source.
108 +
109 + 1) Use a suitable shared library mechanism for linking with the
110 + Library. A suitable mechanism is one that (a) uses at run time
111 + a copy of the Library already present on the user's computer
112 + system, and (b) will operate properly with a modified version
113 + of the Library that is interface-compatible with the Linked
114 + Version.
115 +
116 + e) Provide Installation Information, but only if you would otherwise
117 + be required to provide such information under section 6 of the
118 + GNU GPL, and only to the extent that such information is
119 + necessary to install and execute a modified version of the
120 + Combined Work produced by recombining or relinking the
121 + Application with a modified version of the Linked Version. (If
122 + you use option 4d0, the Installation Information must accompany
123 + the Minimal Corresponding Source and Corresponding Application
124 + Code. If you use option 4d1, you must provide the Installation
125 + Information in the manner specified by section 6 of the GNU GPL
126 + for conveying Corresponding Source.)
127 +
128 + 5. Combined Libraries.
129 +
130 + You may place library facilities that are a work based on the
131 +Library side by side in a single library together with other library
132 +facilities that are not Applications and are not covered by this
133 +License, and convey such a combined library under terms of your
134 +choice, if you do both of the following:
135 +
136 + a) Accompany the combined library with a copy of the same work based
137 + on the Library, uncombined with any other library facilities,
138 + conveyed under the terms of this License.
139 +
140 + b) Give prominent notice with the combined library that part of it
141 + is a work based on the Library, and explaining where to find the
142 + accompanying uncombined form of the same work.
143 +
144 + 6. Revised Versions of the GNU Lesser General Public License.
145 +
146 + The Free Software Foundation may publish revised and/or new versions
147 +of the GNU Lesser General Public License from time to time. Such new
148 +versions will be similar in spirit to the present version, but may
149 +differ in detail to address new problems or concerns.
150 +
151 + Each version is given a distinguishing version number. If the
152 +Library as you received it specifies that a certain numbered version
153 +of the GNU Lesser General Public License "or any later version"
154 +applies to it, you have the option of following the terms and
155 +conditions either of that published version or of any later version
156 +published by the Free Software Foundation. If the Library as you
157 +received it does not specify a version number of the GNU Lesser
158 +General Public License, you may choose any version of the GNU Lesser
159 +General Public License ever published by the Free Software Foundation.
160 +
161 + If the Library as you received it specifies that a proxy can decide
162 +whether future versions of the GNU Lesser General Public License shall
163 +apply, that proxy's public statement of acceptance of any version is
164 +permanent authorization for you to choose that version for the
165 +Library.
mqtt_websockets/c-rbuf/Makefile new
+24
@@ -0,0 +1,24 @@
1 +CFLAGS = -Wall -Wextra -std=c99
2 +
3 +all: libringbuffer.a libringbuffer.so build/ringbuffer_test.o
4 + gcc -o test build/ringbuffer_test.o libringbuffer.a $(CFLAGS)
5 +
6 +libringbuffer.so: build/ringbuffer.o
7 + gcc -shared -o libringbuffer.so build/ringbuffer.o
8 +
9 +libringbuffer.a: build/ringbuffer.o
10 + ar rcs libringbuffer.a build/ringbuffer.o
11 +
12 +build/ringbuffer.o: src/ringbuffer.c src/ringbuffer_internal.h include/ringbuffer.h
13 + gcc -o build/ringbuffer.o -c src/ringbuffer.c -Iinclude -fPIC $(CFLAGS)
14 +
15 +build/ringbuffer_test.o: libringbuffer.a tests/ringbuffer_test.c
16 + gcc -o build/ringbuffer_test.o -c tests/ringbuffer_test.c -Iinclude $(CFLAGS)
17 +
18 +clean:
19 + rm -f build/*
20 + rm -f libringbuffer.a
21 + rm -f libringbuffer.so
22 + rm -f test
23 +
24 +distclean: clean
mqtt_websockets/c-rbuf/README.md new
+20
@@ -0,0 +1,20 @@
1 +# c-rbuf [![run-tests](https://github.com/underhood/c-rbuf/workflows/run-tests/badge.svg)](https://github.com/underhood/c-rbuf/actions)
2 +
3 +Simple C ringbuffer implementation with API allowing usage without intermediate buffer. Meant to be as simple as possible to use and integrate. You can copy the files into your project, use it as a static lib, or shared lib depending on what is most convenient for you.
4 +
5 +Usage without intermediate buffer means when reading from file descriptor/socket you can insert data directly into the ringbuffer:
6 +```C
7 +char *ptr;
8 +size_t bytes;
9 +rbuf_t buff = rbuf_create(12345);
10 +ptr = rbuf_get_linear_insert_range(buff, &ret);
11 +read(fd, ptr, bytes);
12 +```
13 +
14 +**Multiple tail support:** Only single tail is supported but multiple tail support might be implemented in the future.
15 +
16 +**Thread Safety:** Currently you will have to ensure only a single thread accesses the buffer at a time yourself.
17 +
18 +## License
19 +
20 +The Project is released under LGPL v3 license. See [License](LICENSE)
mqtt_websockets/c-rbuf/build/.keep
mqtt_websockets/c-rbuf/include/ringbuffer.h new
+53
@@ -0,0 +1,53 @@
1 +/*
2 + *
3 + * Copyright: SPDX-License-Identifier: LGPL-3.0-only
4 + *
5 + * Author: Timotej Šiškovič <timotejs@gmail.com>
6 + *
7 + */
8 +
9 +#ifndef RINGBUFFER_H
10 +#define RINGBUFFER_H
11 +
12 +#include <stddef.h>
13 +
14 +typedef struct rbuf_t *rbuf_t;
15 +
16 +rbuf_t rbuf_create(size_t size);
17 +void rbuf_free(rbuf_t buffer);
18 +void rbuf_flush(rbuf_t buffer);
19 +
20 +/* /param bytes how much bytes can be copied into pointer returned
21 + * /return pointer where data can be copied to or NULL if buffer full
22 + */
23 +char *rbuf_get_linear_insert_range(rbuf_t buffer, size_t *bytes);
24 +char *rbuf_get_linear_read_range(rbuf_t buffer, size_t *bytes);
25 +
26 +int rbuf_bump_head(rbuf_t buffer, size_t bytes);
27 +int rbuf_bump_tail(rbuf_t buffer, size_t bytes);
28 +
29 +/* @param buffer related buffer instance
30 + * @returns total capacity of buffer in bytes (not free/used)
31 + */
32 +size_t rbuf_get_capacity(rbuf_t buffer);
33 +
34 +/* @param buffer related buffer instance
35 + * @returns count of bytes stored in the buffer
36 + */
37 +size_t rbuf_bytes_available(rbuf_t buffer);
38 +
39 +/* @param buffer related buffer instance
40 + * @returns count of bytes available/free in the buffer (how many more bytes you can store in this buffer)
41 + */
42 +size_t rbuf_bytes_free(rbuf_t buffer);
43 +
44 +/* writes as many bytes from `data` into the `buffer` as possible
45 + * but maximum `len` bytes
46 + */
47 +size_t rbuf_push(rbuf_t buffer, const char *data, size_t len);
48 +size_t rbuf_pop(rbuf_t buffer, char *data, size_t len);
49 +
50 +char *rbuf_find_bytes(rbuf_t buffer, const char *needle, size_t needle_bytes, int *found_idx);
51 +int rbuf_memcmp_n(rbuf_t buffer, const char *to_cmp, size_t to_cmp_bytes);
52 +
53 +#endif
mqtt_websockets/c-rbuf/src/ringbuffer.c new
+209
@@ -0,0 +1,209 @@
1 +/*
2 + *
3 + * Copyright: SPDX-License-Identifier: LGPL-3.0-only
4 + *
5 + * Author: Timotej Šiškovič <timotejs@gmail.com>
6 + *
7 + */
8 +
9 +#include "ringbuffer.h"
10 +#include "ringbuffer_internal.h"
11 +
12 +#include <stdlib.h>
13 +#include <assert.h>
14 +#include <string.h>
15 +
16 +#define MIN(a,b) (((a)<(b))?(a):(b))
17 +#define MAX(a,b) (((a)>(b))?(a):(b))
18 +
19 +// this allows user to use their own
20 +// custom memory allocation functions
21 +#ifdef RBUF_CUSTOM_MALLOC
22 +#include "ringbuffer_pal.h"
23 +#else
24 +#define crbuf_malloc(...) malloc(__VA_ARGS__)
25 +#define crbuf_free(...) free(__VA_ARGS__)
26 +#endif
27 +
28 +rbuf_t rbuf_create(size_t size)
29 +{
30 + rbuf_t buffer = crbuf_malloc(sizeof(struct rbuf_t) + size);
31 + if (!buffer)
32 + return NULL;
33 +
34 + memset(buffer, 0, sizeof(struct rbuf_t));
35 +
36 + buffer->data = ((char*)buffer) + sizeof(struct rbuf_t);
37 +
38 + buffer->head = buffer->data;
39 + buffer->tail = buffer->data;
40 + buffer->size = size;
41 + buffer->end = buffer->data + size;
42 +
43 + return buffer;
44 +}
45 +
46 +void rbuf_free(rbuf_t buffer)
47 +{
48 + crbuf_free(buffer);
49 +}
50 +
51 +void rbuf_flush(rbuf_t buffer)
52 +{
53 + buffer->head = buffer->data;
54 + buffer->tail = buffer->data;
55 + buffer->size_data = 0;
56 +}
57 +
58 +char *rbuf_get_linear_insert_range(rbuf_t buffer, size_t *bytes)
59 +{
60 + *bytes = 0;
61 + if (buffer->head == buffer->tail && buffer->size_data)
62 + return NULL;
63 +
64 + *bytes = ((buffer->head >= buffer->tail) ? buffer->end : buffer->tail) - buffer->head;
65 + return buffer->head;
66 +}
67 +
68 +char *rbuf_get_linear_read_range(rbuf_t buffer, size_t *bytes)
69 +{
70 + *bytes = 0;
71 + if(buffer->head == buffer->tail && !buffer->size_data)
72 + return NULL;
73 +
74 + *bytes = ((buffer->tail >= buffer->head) ? buffer->end : buffer->head) - buffer->tail;
75 +
76 + return buffer->tail;
77 +}
78 +
79 +int rbuf_bump_head(rbuf_t buffer, size_t bytes)
80 +{
81 + size_t free_bytes = rbuf_bytes_free(buffer);
82 + if (bytes > free_bytes)
83 + return 0;
84 + int i = buffer->head - buffer->data;
85 + buffer->head = &buffer->data[(i + bytes) % buffer->size];
86 + buffer->size_data += bytes;
87 + return 1;
88 +}
89 +
90 +int rbuf_bump_tail(rbuf_t buffer, size_t bytes)
91 +{
92 + if(!rbuf_bump_tail_noopt(buffer, bytes))
93 + return 0;
94 +
95 + // if tail catched up with head
96 + // start writing buffer from beggining
97 + // this is not necessary (rbuf must work well without it)
98 + // but helps to optimize big writes as rbuf_get_linear_insert_range
99 + // will return bigger continuous region
100 + if(buffer->tail == buffer->head) {
101 + assert(buffer->size_data == 0);
102 + rbuf_flush(buffer);
103 + }
104 +
105 + return 1;
106 +}
107 +
108 +size_t rbuf_get_capacity(rbuf_t buffer)
109 +{
110 + return buffer->size;
111 +}
112 +
113 +size_t rbuf_bytes_available(rbuf_t buffer)
114 +{
115 + return buffer->size_data;
116 +}
117 +
118 +size_t rbuf_bytes_free(rbuf_t buffer)
119 +{
120 + return buffer->size - buffer->size_data;
121 +}
122 +
123 +size_t rbuf_push(rbuf_t buffer, const char *data, size_t len)
124 +{
125 + size_t to_cpy;
126 + char *w_ptr = rbuf_get_linear_insert_range(buffer, &to_cpy);
127 + if(!to_cpy)
128 + return to_cpy;
129 +
130 + to_cpy = MIN(to_cpy, len);
131 + memcpy(w_ptr, data, to_cpy);
132 + rbuf_bump_head(buffer, to_cpy);
133 + if(to_cpy < len)
134 + to_cpy += rbuf_push(buffer, &data[to_cpy], len - to_cpy);
135 + return to_cpy;
136 +}
137 +
138 +size_t rbuf_pop(rbuf_t buffer, char *data, size_t len)
139 +{
140 + size_t to_cpy;
141 + const char *r_ptr = rbuf_get_linear_read_range(buffer, &to_cpy);
142 + if(!to_cpy)
143 + return to_cpy;
144 +
145 + to_cpy = MIN(to_cpy, len);
146 + memcpy(data, r_ptr, to_cpy);
147 + rbuf_bump_tail(buffer, to_cpy);
148 + if(to_cpy < len)
149 + to_cpy += rbuf_pop(buffer, &data[to_cpy], len - to_cpy);
150 + return to_cpy;
151 +}
152 +
153 +static inline void rbuf_ptr_inc(rbuf_t buffer, const char **ptr)
154 +{
155 + (*ptr)++;
156 + if(*ptr >= buffer->end)
157 + *ptr = buffer->data;
158 +}
159 +
160 +int rbuf_memcmp(rbuf_t buffer, const char *haystack, const char *needle, size_t needle_bytes)
161 +{
162 + const char *end = needle + needle_bytes;
163 +
164 + // as head==tail can mean 2 things here
165 + if (haystack == buffer->head && buffer->size_data) {
166 + if (*haystack != *needle)
167 + return (*haystack - *needle);
168 + rbuf_ptr_inc(buffer, &haystack);
169 + needle++;
170 + }
171 +
172 + while (haystack != buffer->head && needle != end) {
173 + if (*haystack != *needle)
174 + return (*haystack - *needle);
175 + rbuf_ptr_inc(buffer, &haystack);
176 + needle++;
177 + }
178 + return 0;
179 +}
180 +
181 +int rbuf_memcmp_n(rbuf_t buffer, const char *to_cmp, size_t to_cmp_bytes)
182 +{
183 + return rbuf_memcmp(buffer, buffer->tail, to_cmp, to_cmp_bytes);
184 +}
185 +
186 +char *rbuf_find_bytes(rbuf_t buffer, const char *needle, size_t needle_bytes, int *found_idx)
187 +{
188 + const char *ptr = buffer->tail;
189 + *found_idx = 0;
190 +
191 + if (!rbuf_bytes_available(buffer))
192 + return NULL;
193 +
194 + if (buffer->head == buffer->tail && buffer->size_data) {
195 + if(!rbuf_memcmp(buffer, ptr, needle, needle_bytes))
196 + return (char *)ptr;
197 + rbuf_ptr_inc(buffer, &ptr);
198 + (*found_idx)++;
199 + }
200 +
201 + while (ptr != buffer->head)
202 + {
203 + if(!rbuf_memcmp(buffer, ptr, needle, needle_bytes))
204 + return (char *)ptr;
205 + rbuf_ptr_inc(buffer, &ptr);
206 + (*found_idx)++;
207 + }
208 + return NULL;
209 +}
mqtt_websockets/c-rbuf/src/ringbuffer_internal.h new
+43
@@ -0,0 +1,43 @@
1 +/*
2 + *
3 + * Copyright: SPDX-License-Identifier: LGPL-3.0-only
4 + *
5 + * Author: Timotej Šiškovič <timotejs@gmail.com>
6 + *
7 + */
8 +
9 +#ifndef RINGBUFFER_INTERNAL_H
10 +#define RINGBUFFER_INTERNAL_H
11 +
12 +struct rbuf_t {
13 + char *data;
14 +
15 + // points to next byte where we can write
16 + char *head;
17 + // points to oldest (next to be poped) readable byte
18 + char *tail;
19 +
20 + // to avoid calculating data + size
21 + // all the time
22 + char *end;
23 +
24 + size_t size;
25 + size_t size_data;
26 +};
27 +
28 +/* this exists so that it can be tested by unit tests
29 + * without optimization that resets head and tail to
30 + * beginning if buffer empty
31 + */
32 +inline static int rbuf_bump_tail_noopt(rbuf_t buffer, size_t bytes)
33 +{
34 + if (bytes > buffer->size_data)
35 + return 0;
36 + int i = buffer->tail - buffer->data;
37 + buffer->tail = &buffer->data[(i + bytes) % buffer->size];
38 + buffer->size_data -= bytes;
39 +
40 + return 1;
41 +}
42 +
43 +#endif
mqtt_websockets/c-rbuf/tests/ringbuffer_test.c new
+491
@@ -0,0 +1,491 @@
1 +/*
2 + *
3 + * Copyright: SPDX-License-Identifier: LGPL-3.0-only
4 + *
5 + * Author: Timotej Šiškovič <timotejs@gmail.com>
6 + *
7 + */
8 +
9 +#include "ringbuffer.h"
10 +
11 +// to be able to access internals
12 +// never do this from app
13 +#include "../src/ringbuffer_internal.h"
14 +
15 +#include <stdio.h>
16 +#include <string.h>
17 +
18 +#define KNRM "\x1B[0m"
19 +#define KRED "\x1B[31m"
20 +#define KGRN "\x1B[32m"
21 +#define KYEL "\x1B[33m"
22 +#define KBLU "\x1B[34m"
23 +#define KMAG "\x1B[35m"
24 +#define KCYN "\x1B[36m"
25 +#define KWHT "\x1B[37m"
26 +
27 +#define UNUSED(x) (void)(x)
28 +
29 +int total_fails = 0;
30 +int total_tests = 0;
31 +int total_checks = 0;
32 +
33 +#define CHECK_EQ_RESULT(x, y) \
34 + while (s_len--) \
35 + putchar('.'); \
36 + printf("%s%s " KNRM "\n", (((x) == (y)) ? KGRN : KRED), (((x) == (y)) ? " PASS " : " FAIL ")); \
37 + if ((x) != (y)) \
38 + total_fails++; \
39 + total_checks++;
40 +
41 +#define CHECK_EQ_PREFIX(x, y, prefix, subtest_name, ...) \
42 + { \
43 + int s_len = \
44 + 100 - \
45 + printf(("Checking: " KWHT "%s %s%2d " subtest_name " " KNRM), __func__, prefix, subtest_no, ##__VA_ARGS__); \
46 + CHECK_EQ_RESULT(x, y) \
47 + }
48 +
49 +#define CHECK_EQ(x, y, subtest_name, ...) \
50 + { \
51 + int s_len = \
52 + 100 - printf(("Checking: " KWHT "%s %2d " subtest_name " " KNRM), __func__, subtest_no, ##__VA_ARGS__); \
53 + CHECK_EQ_RESULT(x, y) \
54 + }
55 +
56 +#define TEST_DECL() \
57 + int subtest_no = 0; \
58 + printf(KYEL "TEST SUITE: %s\n" KNRM, __func__); \
59 + total_tests++;
60 +
61 +static void test_rbuf_get_linear_insert_range()
62 +{
63 + TEST_DECL();
64 +
65 + // check empty buffer behaviour
66 + rbuf_t buff = rbuf_create(5);
67 + char *to_write;
68 + size_t ret;
69 + to_write = rbuf_get_linear_insert_range(buff, &ret);
70 + CHECK_EQ(ret, 5, "empty size");
71 + CHECK_EQ(to_write, buff->head, "empty write ptr");
72 + rbuf_free(buff);
73 +
74 + // check full buffer behaviour
75 + subtest_no++;
76 + buff = rbuf_create(5);
77 + ret = rbuf_bump_head(buff, 5);
78 + CHECK_EQ(ret, 1, "ret");
79 + to_write = rbuf_get_linear_insert_range(buff, &ret);
80 + CHECK_EQ(to_write, NULL, "writable NULL");
81 + CHECK_EQ(ret, 0, "writable count = 0");
82 +
83 + // check buffer flush
84 + subtest_no++;
85 + rbuf_flush(buff);
86 + CHECK_EQ(rbuf_bytes_free(buff), 5, "size_free");
87 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
88 + CHECK_EQ(buff->head, buff->data, "head_ptr");
89 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
90 +
91 + // check behaviour head > tail
92 + subtest_no++;
93 + rbuf_flush(buff);
94 + rbuf_bump_head(buff, 3);
95 + to_write = rbuf_get_linear_insert_range(buff, &ret);
96 + CHECK_EQ(to_write, buff->head, "write location");
97 + CHECK_EQ(ret, 2, "availible to linear write");
98 +
99 + // check behaviour tail > head
100 + subtest_no++;
101 + rbuf_flush(buff);
102 + rbuf_bump_head(buff, 5);
103 + rbuf_bump_tail(buff, 3);
104 + CHECK_EQ(buff->head, buff->data, "head_ptr");
105 + CHECK_EQ(buff->tail, buff->data + 3, "tail_ptr");
106 + to_write = rbuf_get_linear_insert_range(buff, &ret);
107 + CHECK_EQ(to_write, buff->head, "write location");
108 + CHECK_EQ(ret, 3, "availible to linear write");
109 +
110 +/* // check behaviour tail and head at last element
111 + subtest_no++;
112 + rbuf_flush(buff);
113 + rbuf_bump_head(buff, 4);
114 + rbuf_bump_tail(buff, 4);
115 + CHECK_EQ(buff->head, buff->end - 1, "head_ptr");
116 + CHECK_EQ(buff->tail, buff->end - 1, "tail_ptr");
117 + to_write = rbuf_get_linear_insert_range(buff, &ret);
118 + CHECK_EQ(to_write, buff->head, "write location");
119 + CHECK_EQ(ret, 1, "availible to linear write");*/
120 +
121 + // check behaviour tail and head at last element
122 + // after rbuf_bump_tail optimisation that restarts buffer
123 + // in case tail catches up with head
124 + subtest_no++;
125 + rbuf_flush(buff);
126 + rbuf_bump_head(buff, 4);
127 + rbuf_bump_tail(buff, 4);
128 + CHECK_EQ(buff->head, buff->data, "head_ptr");
129 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
130 + to_write = rbuf_get_linear_insert_range(buff, &ret);
131 + CHECK_EQ(to_write, buff->head, "write location");
132 + CHECK_EQ(ret, 5, "availible to linear write");
133 +}
134 +
135 +#define _CHECK_EQ(x, y, subtest_name, ...) CHECK_EQ_PREFIX(x, y, prefix, subtest_name, ##__VA_ARGS__)
136 +#define _PREFX "(size = %5zu) "
137 +static void test_rbuf_bump_head_bsize(size_t size)
138 +{
139 + char prefix[16];
140 + snprintf(prefix, 16, _PREFX, size);
141 + int subtest_no = 0;
142 + rbuf_t buff = rbuf_create(size);
143 + _CHECK_EQ(rbuf_bytes_free(buff), size, "size_free");
144 +
145 + subtest_no++;
146 + int ret = rbuf_bump_head(buff, size);
147 + _CHECK_EQ(buff->data, buff->head, "loc");
148 + _CHECK_EQ(ret, 1, "ret");
149 + _CHECK_EQ(buff->size_data, buff->size, "size");
150 + _CHECK_EQ(rbuf_bytes_free(buff), 0, "size_free");
151 +
152 + subtest_no++;
153 + ret = rbuf_bump_head(buff, 1);
154 + _CHECK_EQ(buff->data, buff->head, "loc no move");
155 + _CHECK_EQ(ret, 0, "ret error");
156 + _CHECK_EQ(buff->size_data, buff->size, "size");
157 + _CHECK_EQ(rbuf_bytes_free(buff), 0, "size_free");
158 + rbuf_free(buff);
159 +
160 + subtest_no++;
161 + buff = rbuf_create(size);
162 + ret = rbuf_bump_head(buff, size - 1);
163 + _CHECK_EQ(buff->head, buff->end-1, "loc end");
164 + rbuf_free(buff);
165 +}
166 +#undef _CHECK_EQ
167 +
168 +static void test_rbuf_bump_head()
169 +{
170 + TEST_DECL();
171 + UNUSED(subtest_no);
172 +
173 + size_t test_sizes[] = { 1, 2, 3, 5, 6, 7, 8, 100, 99999, 0 };
174 + for (int i = 0; test_sizes[i]; i++)
175 + test_rbuf_bump_head_bsize(test_sizes[i]);
176 +}
177 +
178 +static void test_rbuf_bump_tail_noopt(int subtest_no)
179 +{
180 + rbuf_t buff = rbuf_create(10);
181 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
182 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
183 +
184 + subtest_no++;
185 + int ret = rbuf_bump_head(buff, 5);
186 + CHECK_EQ(ret, 1, "ret");
187 + CHECK_EQ(rbuf_bytes_free(buff), 5, "size_free");
188 + CHECK_EQ(rbuf_bytes_available(buff), 5, "size_avail");
189 + CHECK_EQ(buff->head, buff->data + 5, "head_ptr");
190 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
191 +
192 + subtest_no++;
193 + ret = rbuf_bump_tail_noopt(buff, 2);
194 + CHECK_EQ(ret, 1, "ret");
195 + CHECK_EQ(rbuf_bytes_available(buff), 3, "size_avail");
196 + CHECK_EQ(rbuf_bytes_free(buff), 7, "size_free");
197 + CHECK_EQ(buff->head, buff->data + 5, "head_ptr");
198 + CHECK_EQ(buff->tail, buff->data + 2, "tail_ptr");
199 +
200 + subtest_no++;
201 + ret = rbuf_bump_tail_noopt(buff, 3);
202 + CHECK_EQ(ret, 1, "ret");
203 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
204 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
205 + CHECK_EQ(buff->head, buff->data + 5, "head_ptr");
206 + CHECK_EQ(buff->tail, buff->data + 5, "tail_ptr");
207 +
208 + subtest_no++;
209 + ret = rbuf_bump_tail_noopt(buff, 1);
210 + CHECK_EQ(ret, 0, "ret");
211 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
212 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
213 + CHECK_EQ(buff->head, buff->data + 5, "head_ptr");
214 + CHECK_EQ(buff->tail, buff->data + 5, "tail_ptr");
215 +
216 + subtest_no++;
217 + ret = rbuf_bump_head(buff, 7);
218 + CHECK_EQ(ret, 1, "ret");
219 + CHECK_EQ(rbuf_bytes_available(buff), 7, "size_avail");
220 + CHECK_EQ(rbuf_bytes_free(buff), 3, "size_free");
221 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
222 + CHECK_EQ(buff->tail, buff->data + 5, "tail_ptr");
223 +
224 + subtest_no++;
225 + ret = rbuf_bump_tail_noopt(buff, 5);
226 + CHECK_EQ(ret, 1, "ret");
227 + CHECK_EQ(rbuf_bytes_available(buff), 2, "size_avail");
228 + CHECK_EQ(rbuf_bytes_free(buff), 8, "size_free");
229 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
230 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
231 +
232 + // check tail can't overrun head
233 + subtest_no++;
234 + ret = rbuf_bump_tail_noopt(buff, 3);
235 + CHECK_EQ(ret, 0, "ret");
236 + CHECK_EQ(rbuf_bytes_available(buff), 2, "size_avail");
237 + CHECK_EQ(rbuf_bytes_free(buff), 8, "size_free");
238 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
239 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
240 +
241 + // check head can't overrun tail
242 + subtest_no++;
243 + ret = rbuf_bump_head(buff, 9);
244 + CHECK_EQ(ret, 0, "ret");
245 + CHECK_EQ(rbuf_bytes_available(buff), 2, "size_avail");
246 + CHECK_EQ(rbuf_bytes_free(buff), 8, "size_free");
247 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
248 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
249 +
250 + // check head can fill the buffer
251 + subtest_no++;
252 + ret = rbuf_bump_head(buff, 8);
253 + CHECK_EQ(ret, 1, "ret");
254 + CHECK_EQ(rbuf_bytes_available(buff), 10, "size_avail");
255 + CHECK_EQ(rbuf_bytes_free(buff), 0, "size_free");
256 + CHECK_EQ(buff->head, buff->data, "head_ptr");
257 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
258 +
259 + // check can empty the buffer
260 + subtest_no++;
261 + ret = rbuf_bump_tail_noopt(buff, 10);
262 + CHECK_EQ(ret, 1, "ret");
263 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
264 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
265 + CHECK_EQ(buff->head, buff->data, "head_ptr");
266 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
267 +}
268 +
269 +static void test_rbuf_bump_tail_opt(int subtest_no)
270 +{
271 + subtest_no++;
272 + rbuf_t buff = rbuf_create(10);
273 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
274 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
275 +
276 + subtest_no++;
277 + int ret = rbuf_bump_head(buff, 5);
278 + CHECK_EQ(ret, 1, "ret");
279 + CHECK_EQ(rbuf_bytes_free(buff), 5, "size_free");
280 + CHECK_EQ(rbuf_bytes_available(buff), 5, "size_avail");
281 + CHECK_EQ(buff->head, buff->data + 5, "head_ptr");
282 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
283 +
284 + subtest_no++;
285 + ret = rbuf_bump_tail(buff, 2);
286 + CHECK_EQ(ret, 1, "ret");
287 + CHECK_EQ(rbuf_bytes_available(buff), 3, "size_avail");
288 + CHECK_EQ(rbuf_bytes_free(buff), 7, "size_free");
289 + CHECK_EQ(buff->head, buff->data + 5, "head_ptr");
290 + CHECK_EQ(buff->tail, buff->data + 2, "tail_ptr");
291 +
292 + subtest_no++;
293 + ret = rbuf_bump_tail(buff, 3);
294 + CHECK_EQ(ret, 1, "ret");
295 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
296 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
297 + CHECK_EQ(buff->head, buff->data, "head_ptr");
298 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
299 +
300 + subtest_no++;
301 + ret = rbuf_bump_tail_noopt(buff, 1);
302 + CHECK_EQ(ret, 0, "ret");
303 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
304 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
305 + CHECK_EQ(buff->head, buff->data, "head_ptr");
306 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
307 +
308 + subtest_no++;
309 + ret = rbuf_bump_head(buff, 6);
310 + ret = rbuf_bump_tail(buff, 5);
311 + ret = rbuf_bump_head(buff, 6);
312 + CHECK_EQ(ret, 1, "ret");
313 + CHECK_EQ(rbuf_bytes_available(buff), 7, "size_avail");
314 + CHECK_EQ(rbuf_bytes_free(buff), 3, "size_free");
315 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
316 + CHECK_EQ(buff->tail, buff->data + 5, "tail_ptr");
317 +
318 + subtest_no++;
319 + ret = rbuf_bump_tail(buff, 5);
320 + CHECK_EQ(ret, 1, "ret");
321 + CHECK_EQ(rbuf_bytes_available(buff), 2, "size_avail");
322 + CHECK_EQ(rbuf_bytes_free(buff), 8, "size_free");
323 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
324 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
325 +
326 + // check tail can't overrun head
327 + subtest_no++;
328 + ret = rbuf_bump_tail(buff, 3);
329 + CHECK_EQ(ret, 0, "ret");
330 + CHECK_EQ(rbuf_bytes_available(buff), 2, "size_avail");
331 + CHECK_EQ(rbuf_bytes_free(buff), 8, "size_free");
332 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
333 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
334 +
335 + // check head can't overrun tail
336 + subtest_no++;
337 + ret = rbuf_bump_head(buff, 9);
338 + CHECK_EQ(ret, 0, "ret");
339 + CHECK_EQ(rbuf_bytes_available(buff), 2, "size_avail");
340 + CHECK_EQ(rbuf_bytes_free(buff), 8, "size_free");
341 + CHECK_EQ(buff->head, buff->data + 2, "head_ptr");
342 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
343 +
344 + // check head can fill the buffer
345 + subtest_no++;
346 + ret = rbuf_bump_head(buff, 8);
347 + CHECK_EQ(ret, 1, "ret");
348 + CHECK_EQ(rbuf_bytes_available(buff), 10, "size_avail");
349 + CHECK_EQ(rbuf_bytes_free(buff), 0, "size_free");
350 + CHECK_EQ(buff->head, buff->data, "head_ptr");
351 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
352 +
353 + // check can empty the buffer
354 + subtest_no++;
355 + ret = rbuf_bump_tail(buff, 10);
356 + CHECK_EQ(ret, 1, "ret");
357 + CHECK_EQ(rbuf_bytes_available(buff), 0, "size_avail");
358 + CHECK_EQ(rbuf_bytes_free(buff), 10, "size_free");
359 + CHECK_EQ(buff->head, buff->data, "head_ptr");
360 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
361 +}
362 +
363 +static void test_rbuf_bump_tail()
364 +{
365 + TEST_DECL();
366 + test_rbuf_bump_tail_noopt(subtest_no);
367 + test_rbuf_bump_tail_opt(subtest_no);
368 +}
369 +
370 +#define ASCII_A 0x61
371 +#define ASCII_Z 0x7A
372 +#define TEST_DATA_SIZE ASCII_Z-ASCII_A+1
373 +static void test_rbuf_push()
374 +{
375 + TEST_DECL();
376 + rbuf_t buff = rbuf_create(10);
377 + int i;
378 + char test_data[TEST_DATA_SIZE];
379 +
380 + for (int i = 0; i <= TEST_DATA_SIZE; i++)
381 + test_data[i] = i + ASCII_A;
382 +
383 + int ret = rbuf_push(buff, test_data, 10);
384 + CHECK_EQ(ret, 10, "written 10 bytes");
385 + CHECK_EQ(rbuf_bytes_free(buff), 0, "empty size == 0");
386 + for (i = 0; i < 10; i++)
387 + CHECK_EQ(buff->data[i], i + ASCII_A, "Check data");
388 +
389 + subtest_no++;
390 + rbuf_flush(buff);
391 + rbuf_bump_head(buff, 5);
392 + rbuf_bump_tail_noopt(buff, 5); //to not reset both pointers to beginning
393 + ret = rbuf_push(buff, test_data, 10);
394 + CHECK_EQ(ret, 10, "written 10 bytes");
395 + for (i = 0; i < 10; i++)
396 + CHECK_EQ(buff->data[i], ((i+5)%10) + ASCII_A, "Check Data");
397 +
398 + subtest_no++;
399 + rbuf_flush(buff);
400 + rbuf_bump_head(buff, 9);
401 + rbuf_bump_tail_noopt(buff, 9);
402 + ret = rbuf_push(buff, test_data, 10);
403 + CHECK_EQ(ret, 10, "written 10 bytes");
404 + for (i = 0; i < 10; i++)
405 + CHECK_EQ(buff->data[i], ((i + 1) % 10) + ASCII_A, "Check data");
406 +
407 + // let tail > head
408 + subtest_no++;
409 + rbuf_flush(buff);
410 + rbuf_bump_head(buff, 9);
411 + rbuf_bump_tail_noopt(buff, 9);
412 + rbuf_bump_head(buff, 1);
413 + ret = rbuf_push(buff, test_data, 9);
414 + CHECK_EQ(ret, 9, "written 9 bytes");
415 + CHECK_EQ(buff->head, buff->end - 1, "head_ptr");
416 + CHECK_EQ(buff->tail, buff->head, "tail_ptr");
417 + rbuf_bump_tail(buff, 1);
418 + //TODO push byte can be usefull optimisation
419 + ret = rbuf_push(buff, &test_data[9], 1);
420 + CHECK_EQ(ret, 1, "written 1 byte");
421 + CHECK_EQ(rbuf_bytes_free(buff), 0, "empty size == 0");
422 + for (i = 0; i < 10; i++)
423 + CHECK_EQ(buff->data[i], i + ASCII_A, "Check data");
424 +
425 + subtest_no++;
426 + rbuf_flush(buff);
427 + rbuf_bump_head(buff, 9);
428 + rbuf_bump_tail_noopt(buff, 7);
429 + rbuf_bump_head(buff, 1);
430 + ret = rbuf_push(buff, test_data, 7);
431 + CHECK_EQ(ret, 7, "written 7 bytes");
432 + CHECK_EQ(buff->head, buff->data + 7, "head_ptr");
433 + CHECK_EQ(buff->tail, buff->head, "tail_ptr");
434 + rbuf_bump_tail(buff, 3);
435 + CHECK_EQ(buff->tail, buff->data, "tail_ptr");
436 + //TODO push byte can be usefull optimisation
437 + ret = rbuf_push(buff, &test_data[7], 3);
438 + CHECK_EQ(ret, 3, "written 3 bytes");
439 + CHECK_EQ(rbuf_bytes_free(buff), 0, "empty size == 0");
440 + for (i = 0; i < 10; i++)
441 + CHECK_EQ(buff->data[i], i + ASCII_A, "Check data");
442 +
443 + // test can't overfill the buffer
444 + subtest_no++;
445 + rbuf_flush(buff);
446 + rbuf_push(buff, test_data, TEST_DATA_SIZE);
447 + CHECK_EQ(ret, 3, "written 10 bytes");
448 + for (i = 0; i < 10; i++)
449 + CHECK_EQ(buff->data[i], i + ASCII_A, "Check data");
450 +}
451 +
452 +#define TEST_RBUF_FIND_BYTES_SIZE 10
453 +void test_rbuf_find_bytes()
454 +{
455 + TEST_DECL();
456 + rbuf_t buff = rbuf_create(TEST_RBUF_FIND_BYTES_SIZE);
457 + char *filler_3 = " ";
458 + char *needle = "needle";
459 + int idx;
460 + char *ptr;
461 +
462 + // make sure needle is wrapped aroung in the buffer
463 + // to test we still can find it
464 + // target "edle ne"
465 + rbuf_bump_head(buff, TEST_RBUF_FIND_BYTES_SIZE / 2);
466 + rbuf_push(buff, filler_3, strlen(filler_3));
467 + rbuf_bump_tail(buff, TEST_RBUF_FIND_BYTES_SIZE / 2);
468 + rbuf_push(buff, needle, strlen(needle));
469 + ptr = rbuf_find_bytes(buff, needle, strlen(needle), &idx);
470 + CHECK_EQ(ptr, buff->data + (TEST_RBUF_FIND_BYTES_SIZE / 2) + strlen(filler_3), "Pointer to needle correct");
471 + CHECK_EQ(idx, ptr - buff->tail, "Check needle index");
472 +}
473 +
474 +int main()
475 +{
476 + test_rbuf_bump_head();
477 + test_rbuf_bump_tail();
478 + test_rbuf_get_linear_insert_range();
479 + test_rbuf_push();
480 + test_rbuf_find_bytes();
481 +
482 + printf(
483 + KNRM "Total Tests %d, Total Checks %d, Successful Checks %d, Failed Checks %d\n",
484 + total_tests, total_checks, total_checks - total_fails, total_fails);
485 + if (total_fails)
486 + printf(KRED "!!!Some test(s) Failed!!!\n");
487 + else
488 + printf(KGRN "ALL TESTS PASSED\n");
489 +
490 + return total_fails;
491 +}
mqtt_websockets/c_rhash/.github/workflows/run-tests.yaml new
+16
@@ -0,0 +1,16 @@
1 +name: run-tests
2 +on:
3 + push:
4 + schedule:
5 + - cron: '5 3 * * 0'
6 + pull_request:
7 +jobs:
8 + run-tests:
9 + runs-on: ubuntu-latest
10 + steps:
11 + - uses: actions/checkout@v2
12 + - run: sudo apt-get install -y valgrind
13 + - run: autoreconf -ivf
14 + - run: ./configure
15 + - run: make
16 + - run: valgrind --leak-check=full --error-exitcode=66 ./test
mqtt_websockets/c_rhash/.gitignore new
+58
@@ -0,0 +1,58 @@
1 +# http://www.gnu.org/software/automake
2 +
3 +Makefile.in
4 +/ar-lib
5 +/mdate-sh
6 +/py-compile
7 +/test-driver
8 +/ylwrap
9 +.deps/
10 +.dirstamp
11 +
12 +# http://www.gnu.org/software/autoconf
13 +
14 +autom4te.cache
15 +/autoscan.log
16 +/autoscan-*.log
17 +/aclocal.m4
18 +/compile
19 +/config.cache
20 +/config.guess
21 +/config.h.in
22 +/config.log
23 +/config.status
24 +/config.sub
25 +/configure
26 +/configure.scan
27 +/depcomp
28 +/install-sh
29 +/missing
30 +/stamp-h1
31 +
32 +# https://www.gnu.org/software/libtool/
33 +
34 +/ltmain.sh
35 +
36 +# http://www.gnu.org/software/texinfo
37 +
38 +/texinfo.tex
39 +
40 +# http://www.gnu.org/software/m4/
41 +
42 +m4/libtool.m4
43 +m4/ltoptions.m4
44 +m4/ltsugar.m4
45 +m4/ltversion.m4
46 +m4/lt~obsolete.m4
47 +
48 +# Generated Makefile
49 +# (meta build system like autotools,
50 +# can automatically generate from config.status script
51 +# (which is called by configure script))
52 +Makefile
53 +
54 +test
55 +*.o
56 +.vscode
57 +libcrhash.a
58 +config.h
mqtt_websockets/c_rhash/AUTHORS
mqtt_websockets/c_rhash/COPYING new
+674
@@ -0,0 +1,674 @@
1 + GNU GENERAL PUBLIC LICENSE
2 + Version 3, 29 June 2007
3 +
4 + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5 + Everyone is permitted to copy and distribute verbatim copies
6 + of this license document, but changing it is not allowed.
7 +
8 + Preamble
9 +
10 + The GNU General Public License is a free, copyleft license for
11 +software and other kinds of works.
12 +
13 + The licenses for most software and other practical works are designed
14 +to take away your freedom to share and change the works. By contrast,
15 +the GNU General Public License is intended to guarantee your freedom to
16 +share and change all versions of a program--to make sure it remains free
17 +software for all its users. We, the Free Software Foundation, use the
18 +GNU General Public License for most of our software; it applies also to
19 +any other work released this way by its authors. You can apply it to
20 +your programs, too.
21 +
22 + When we speak of free software, we are referring to freedom, not
23 +price. Our General Public Licenses are designed to make sure that you
24 +have the freedom to distribute copies of free software (and charge for
25 +them if you wish), that you receive source code or can get it if you
26 +want it, that you can change the software or use pieces of it in new
27 +free programs, and that you know you can do these things.
28 +
29 + To protect your rights, we need to prevent others from denying you
30 +these rights or asking you to surrender the rights. Therefore, you have
31 +certain responsibilities if you distribute copies of the software, or if
32 +you modify it: responsibilities to respect the freedom of others.
33 +
34 + For example, if you distribute copies of such a program, whether
35 +gratis or for a fee, you must pass on to the recipients the same
36 +freedoms that you received. You must make sure that they, too, receive
37 +or can get the source code. And you must show them these terms so they
38 +know their rights.
39 +
40 + Developers that use the GNU GPL protect your rights with two steps:
41 +(1) assert copyright on the software, and (2) offer you this License
42 +giving you legal permission to copy, distribute and/or modify it.
43 +
44 + For the developers' and authors' protection, the GPL clearly explains
45 +that there is no warranty for this free software. For both users' and
46 +authors' sake, the GPL requires that modified versions be marked as
47 +changed, so that their problems will not be attributed erroneously to
48 +authors of previous versions.
49 +
50 + Some devices are designed to deny users access to install or run
51 +modified versions of the software inside them, although the manufacturer
52 +can do so. This is fundamentally incompatible with the aim of
53 +protecting users' freedom to change the software. The systematic
54 +pattern of such abuse occurs in the area of products for individuals to
55 +use, which is precisely where it is most unacceptable. Therefore, we
56 +have designed this version of the GPL to prohibit the practice for those
57 +products. If such problems arise substantially in other domains, we
58 +stand ready to extend this provision to those domains in future versions
59 +of the GPL, as needed to protect the freedom of users.
60 +
61 + Finally, every program is threatened constantly by software patents.
62 +States should not allow patents to restrict development and use of
63 +software on general-purpose computers, but in those that do, we wish to
64 +avoid the special danger that patents applied to a free program could
65 +make it effectively proprietary. To prevent this, the GPL assures that
66 +patents cannot be used to render the program non-free.
67 +
68 + The precise terms and conditions for copying, distribution and
69 +modification follow.
70 +
71 + TERMS AND CONDITIONS
72 +
73 + 0. Definitions.
74 +
75 + "This License" refers to version 3 of the GNU General Public License.
76 +
77 + "Copyright" also means copyright-like laws that apply to other kinds of
78 +works, such as semiconductor masks.
79 +
80 + "The Program" refers to any copyrightable work licensed under this
81 +License. Each licensee is addressed as "you". "Licensees" and
82 +"recipients" may be individuals or organizations.
83 +
84 + To "modify" a work means to copy from or adapt all or part of the work
85 +in a fashion requiring copyright permission, other than the making of an
86 +exact copy. The resulting work is called a "modified version" of the
87 +earlier work or a work "based on" the earlier work.
88 +
89 + A "covered work" means either the unmodified Program or a work based
90 +on the Program.
91 +
92 + To "propagate" a work means to do anything with it that, without
93 +permission, would make you directly or secondarily liable for
94 +infringement under applicable copyright law, except executing it on a
95 +computer or modifying a private copy. Propagation includes copying,
96 +distribution (with or without modification), making available to the
97 +public, and in some countries other activities as well.
98 +
99 + To "convey" a work means any kind of propagation that enables other
100 +parties to make or receive copies. Mere interaction with a user through
101 +a computer network, with no transfer of a copy, is not conveying.
102 +
103 + An interactive user interface displays "Appropriate Legal Notices"
104 +to the extent that it includes a convenient and prominently visible
105 +feature that (1) displays an appropriate copyright notice, and (2)
106 +tells the user that there is no warranty for the work (except to the
107 +extent that warranties are provided), that licensees may convey the
108 +work under this License, and how to view a copy of this License. If
109 +the interface presents a list of user commands or options, such as a
110 +menu, a prominent item in the list meets this criterion.
111 +
112 + 1. Source Code.
113 +
114 + The "source code" for a work means the preferred form of the work
115 +for making modifications to it. "Object code" means any non-source
116 +form of a work.
117 +
118 + A "Standard Interface" means an interface that either is an official
119 +standard defined by a recognized standards body, or, in the case of
120 +interfaces specified for a particular programming language, one that
121 +is widely used among developers working in that language.
122 +
123 + The "System Libraries" of an executable work include anything, other
124 +than the work as a whole, that (a) is included in the normal form of
125 +packaging a Major Component, but which is not part of that Major
126 +Component, and (b) serves only to enable use of the work with that
127 +Major Component, or to implement a Standard Interface for which an
128 +implementation is available to the public in source code form. A
129 +"Major Component", in this context, means a major essential component
130 +(kernel, window system, and so on) of the specific operating system
131 +(if any) on which the executable work runs, or a compiler used to
132 +produce the work, or an object code interpreter used to run it.
133 +
134 + The "Corresponding Source" for a work in object code form means all
135 +the source code needed to generate, install, and (for an executable
136 +work) run the object code and to modify the work, including scripts to
137 +control those activities. However, it does not include the work's
138 +System Libraries, or general-purpose tools or generally available free
139 +programs which are used unmodified in performing those activities but
140 +which are not part of the work. For example, Corresponding Source
141 +includes interface definition files associated with source files for
142 +the work, and the source code for shared libraries and dynamically
143 +linked subprograms that the work is specifically designed to require,
144 +such as by intimate data communication or control flow between those
145 +subprograms and other parts of the work.
146 +
147 + The Corresponding Source need not include anything that users
148 +can regenerate automatically from other parts of the Corresponding
149 +Source.
150 +
151 + The Corresponding Source for a work in source code form is that
152 +same work.
153 +
154 + 2. Basic Permissions.
155 +
156 + All rights granted under this License are granted for the term of
157 +copyright on the Program, and are irrevocable provided the stated
158 +conditions are met. This License explicitly affirms your unlimited
159 +permission to run the unmodified Program. The output from running a
160 +covered work is covered by this License only if the output, given its
161 +content, constitutes a covered work. This License acknowledges your
162 +rights of fair use or other equivalent, as provided by copyright law.
163 +
164 + You may make, run and propagate covered works that you do not
165 +convey, without conditions so long as your license otherwise remains
166 +in force. You may convey covered works to others for the sole purpose
167 +of having them make modifications exclusively for you, or provide you
168 +with facilities for running those works, provided that you comply with
169 +the terms of this License in conveying all material for which you do
170 +not control copyright. Those thus making or running the covered works
171 +for you must do so exclusively on your behalf, under your direction
172 +and control, on terms that prohibit them from making any copies of
173 +your copyrighted material outside their relationship with you.
174 +
175 + Conveying under any other circumstances is permitted solely under
176 +the conditions stated below. Sublicensing is not allowed; section 10
177 +makes it unnecessary.
178 +
179 + 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 +
181 + No covered work shall be deemed part of an effective technological
182 +measure under any applicable law fulfilling obligations under article
183 +11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 +similar laws prohibiting or restricting circumvention of such
185 +measures.
186 +
187 + When you convey a covered work, you waive any legal power to forbid
188 +circumvention of technological measures to the extent such circumvention
189 +is effected by exercising rights under this License with respect to
190 +the covered work, and you disclaim any intention to limit operation or
191 +modification of the work as a means of enforcing, against the work's
192 +users, your or third parties' legal rights to forbid circumvention of
193 +technological measures.
194 +
195 + 4. Conveying Verbatim Copies.
196 +
197 + You may convey verbatim copies of the Program's source code as you
198 +receive it, in any medium, provided that you conspicuously and
199 +appropriately publish on each copy an appropriate copyright notice;
200 +keep intact all notices stating that this License and any
201 +non-permissive terms added in accord with section 7 apply to the code;
202 +keep intact all notices of the absence of any warranty; and give all
203 +recipients a copy of this License along with the Program.
204 +
205 + You may charge any price or no price for each copy that you convey,
206 +and you may offer support or warranty protection for a fee.
207 +
208 + 5. Conveying Modified Source Versions.
209 +
210 + You may convey a work based on the Program, or the modifications to
211 +produce it from the Program, in the form of source code under the
212 +terms of section 4, provided that you also meet all of these conditions:
213 +
214 + a) The work must carry prominent notices stating that you modified
215 + it, and giving a relevant date.
216 +
217 + b) The work must carry prominent notices stating that it is
218 + released under this License and any conditions added under section
219 + 7. This requirement modifies the requirement in section 4 to
220 + "keep intact all notices".
221 +
222 + c) You must license the entire work, as a whole, under this
223 + License to anyone who comes into possession of a copy. This
224 + License will therefore apply, along with any applicable section 7
225 + additional terms, to the whole of the work, and all its parts,
226 + regardless of how they are packaged. This License gives no
227 + permission to license the work in any other way, but it does not
228 + invalidate such permission if you have separately received it.
229 +
230 + d) If the work has interactive user interfaces, each must display
231 + Appropriate Legal Notices; however, if the Program has interactive
232 + interfaces that do not display Appropriate Legal Notices, your
233 + work need not make them do so.
234 +
235 + A compilation of a covered work with other separate and independent
236 +works, which are not by their nature extensions of the covered work,
237 +and which are not combined with it such as to form a larger program,
238 +in or on a volume of a storage or distribution medium, is called an
239 +"aggregate" if the compilation and its resulting copyright are not
240 +used to limit the access or legal rights of the compilation's users
241 +beyond what the individual works permit. Inclusion of a covered work
242 +in an aggregate does not cause this License to apply to the other
243 +parts of the aggregate.
244 +
245 + 6. Conveying Non-Source Forms.
246 +
247 + You may convey a covered work in object code form under the terms
248 +of sections 4 and 5, provided that you also convey the
249 +machine-readable Corresponding Source under the terms of this License,
250 +in one of these ways:
251 +
252 + a) Convey the object code in, or embodied in, a physical product
253 + (including a physical distribution medium), accompanied by the
254 + Corresponding Source fixed on a durable physical medium
255 + customarily used for software interchange.
256 +
257 + b) Convey the object code in, or embodied in, a physical product
258 + (including a physical distribution medium), accompanied by a
259 + written offer, valid for at least three years and valid for as
260 + long as you offer spare parts or customer support for that product
261 + model, to give anyone who possesses the object code either (1) a
262 + copy of the Corresponding Source for all the software in the
263 + product that is covered by this License, on a durable physical
264 + medium customarily used for software interchange, for a price no
265 + more than your reasonable cost of physically performing this
266 + conveying of source, or (2) access to copy the
267 + Corresponding Source from a network server at no charge.
268 +
269 + c) Convey individual copies of the object code with a copy of the
270 + written offer to provide the Corresponding Source. This
271 + alternative is allowed only occasionally and noncommercially, and
272 + only if you received the object code with such an offer, in accord
273 + with subsection 6b.
274 +
275 + d) Convey the object code by offering access from a designated
276 + place (gratis or for a charge), and offer equivalent access to the
277 + Corresponding Source in the same way through the same place at no
278 + further charge. You need not require recipients to copy the
279 + Corresponding Source along with the object code. If the place to
280 + copy the object code is a network server, the Corresponding Source
281 + may be on a different server (operated by you or a third party)
282 + that supports equivalent copying facilities, provided you maintain
283 + clear directions next to the object code saying where to find the
284 + Corresponding Source. Regardless of what server hosts the
285 + Corresponding Source, you remain obligated to ensure that it is
286 + available for as long as needed to satisfy these requirements.
287 +
288 + e) Convey the object code using peer-to-peer transmission, provided
289 + you inform other peers where the object code and Corresponding
290 + Source of the work are being offered to the general public at no
291 + charge under subsection 6d.
292 +
293 + A separable portion of the object code, whose source code is excluded
294 +from the Corresponding Source as a System Library, need not be
295 +included in conveying the object code work.
296 +
297 + A "User Product" is either (1) a "consumer product", which means any
298 +tangible personal property which is normally used for personal, family,
299 +or household purposes, or (2) anything designed or sold for incorporation
300 +into a dwelling. In determining whether a product is a consumer product,
301 +doubtful cases shall be resolved in favor of coverage. For a particular
302 +product received by a particular user, "normally used" refers to a
303 +typical or common use of that class of product, regardless of the status
304 +of the particular user or of the way in which the particular user
305 +actually uses, or expects or is expected to use, the product. A product
306 +is a consumer product regardless of whether the product has substantial
307 +commercial, industrial or non-consumer uses, unless such uses represent
308 +the only significant mode of use of the product.
309 +
310 + "Installation Information" for a User Product means any methods,
311 +procedures, authorization keys, or other information required to install
312 +and execute modified versions of a covered work in that User Product from
313 +a modified version of its Corresponding Source. The information must
314 +suffice to ensure that the continued functioning of the modified object
315 +code is in no case prevented or interfered with solely because
316 +modification has been made.
317 +
318 + If you convey an object code work under this section in, or with, or
319 +specifically for use in, a User Product, and the conveying occurs as
320 +part of a transaction in which the right of possession and use of the
321 +User Product is transferred to the recipient in perpetuity or for a
322 +fixed term (regardless of how the transaction is characterized), the
323 +Corresponding Source conveyed under this section must be accompanied
324 +by the Installation Information. But this requirement does not apply
325 +if neither you nor any third party retains the ability to install
326 +modified object code on the User Product (for example, the work has
327 +been installed in ROM).
328 +
329 + The requirement to provide Installation Information does not include a
330 +requirement to continue to provide support service, warranty, or updates
331 +for a work that has been modified or installed by the recipient, or for
332 +the User Product in which it has been modified or installed. Access to a
333 +network may be denied when the modification itself materially and
334 +adversely affects the operation of the network or violates the rules and
335 +protocols for communication across the network.
336 +
337 + Corresponding Source conveyed, and Installation Information provided,
338 +in accord with this section must be in a format that is publicly
339 +documented (and with an implementation available to the public in
340 +source code form), and must require no special password or key for
341 +unpacking, reading or copying.
342 +
343 + 7. Additional Terms.
344 +
345 + "Additional permissions" are terms that supplement the terms of this
346 +License by making exceptions from one or more of its conditions.
347 +Additional permissions that are applicable to the entire Program shall
348 +be treated as though they were included in this License, to the extent
349 +that they are valid under applicable law. If additional permissions
350 +apply only to part of the Program, that part may be used separately
351 +under those permissions, but the entire Program remains governed by
352 +this License without regard to the additional permissions.
353 +
354 + When you convey a copy of a covered work, you may at your option
355 +remove any additional permissions from that copy, or from any part of
356 +it. (Additional permissions may be written to require their own
357 +removal in certain cases when you modify the work.) You may place
358 +additional permissions on material, added by you to a covered work,
359 +for which you have or can give appropriate copyright permission.
360 +
361 + Notwithstanding any other provision of this License, for material you
362 +add to a covered work, you may (if authorized by the copyright holders of
363 +that material) supplement the terms of this License with terms:
364 +
365 + a) Disclaiming warranty or limiting liability differently from the
366 + terms of sections 15 and 16 of this License; or
367 +
368 + b) Requiring preservation of specified reasonable legal notices or
369 + author attributions in that material or in the Appropriate Legal
370 + Notices displayed by works containing it; or
371 +
372 + c) Prohibiting misrepresentation of the origin of that material, or
373 + requiring that modified versions of such material be marked in
374 + reasonable ways as different from the original version; or
375 +
376 + d) Limiting the use for publicity purposes of names of licensors or
377 + authors of the material; or
378 +
379 + e) Declining to grant rights under trademark law for use of some
380 + trade names, trademarks, or service marks; or
381 +
382 + f) Requiring indemnification of licensors and authors of that
383 + material by anyone who conveys the material (or modified versions of
384 + it) with contractual assumptions of liability to the recipient, for
385 + any liability that these contractual assumptions directly impose on
386 + those licensors and authors.
387 +
388 + All other non-permissive additional terms are considered "further
389 +restrictions" within the meaning of section 10. If the Program as you
390 +received it, or any part of it, contains a notice stating that it is
391 +governed by this License along with a term that is a further
392 +restriction, you may remove that term. If a license document contains
393 +a further restriction but permits relicensing or conveying under this
394 +License, you may add to a covered work material governed by the terms
395 +of that license document, provided that the further restriction does
396 +not survive such relicensing or conveying.
397 +
398 + If you add terms to a covered work in accord with this section, you
399 +must place, in the relevant source files, a statement of the
400 +additional terms that apply to those files, or a notice indicating
401 +where to find the applicable terms.
402 +
403 + Additional terms, permissive or non-permissive, may be stated in the
404 +form of a separately written license, or stated as exceptions;
405 +the above requirements apply either way.
406 +
407 + 8. Termination.
408 +
409 + You may not propagate or modify a covered work except as expressly
410 +provided under this License. Any attempt otherwise to propagate or
411 +modify it is void, and will automatically terminate your rights under
412 +this License (including any patent licenses granted under the third
413 +paragraph of section 11).
414 +
415 + However, if you cease all violation of this License, then your
416 +license from a particular copyright holder is reinstated (a)
417 +provisionally, unless and until the copyright holder explicitly and
418 +finally terminates your license, and (b) permanently, if the copyright
419 +holder fails to notify you of the violation by some reasonable means
420 +prior to 60 days after the cessation.
421 +
422 + Moreover, your license from a particular copyright holder is
423 +reinstated permanently if the copyright holder notifies you of the
424 +violation by some reasonable means, this is the first time you have
425 +received notice of violation of this License (for any work) from that
426 +copyright holder, and you cure the violation prior to 30 days after
427 +your receipt of the notice.
428 +
429 + Termination of your rights under this section does not terminate the
430 +licenses of parties who have received copies or rights from you under
431 +this License. If your rights have been terminated and not permanently
432 +reinstated, you do not qualify to receive new licenses for the same
433 +material under section 10.
434 +
435 + 9. Acceptance Not Required for Having Copies.
436 +
437 + You are not required to accept this License in order to receive or
438 +run a copy of the Program. Ancillary propagation of a covered work
439 +occurring solely as a consequence of using peer-to-peer transmission
440 +to receive a copy likewise does not require acceptance. However,
441 +nothing other than this License grants you permission to propagate or
442 +modify any covered work. These actions infringe copyright if you do
443 +not accept this License. Therefore, by modifying or propagating a
444 +covered work, you indicate your acceptance of this License to do so.
445 +
446 + 10. Automatic Licensing of Downstream Recipients.
447 +
448 + Each time you convey a covered work, the recipient automatically
449 +receives a license from the original licensors, to run, modify and
450 +propagate that work, subject to this License. You are not responsible
451 +for enforcing compliance by third parties with this License.
452 +
453 + An "entity transaction" is a transaction transferring control of an
454 +organization, or substantially all assets of one, or subdividing an
455 +organization, or merging organizations. If propagation of a covered
456 +work results from an entity transaction, each party to that
457 +transaction who receives a copy of the work also receives whatever
458 +licenses to the work the party's predecessor in interest had or could
459 +give under the previous paragraph, plus a right to possession of the
460 +Corresponding Source of the work from the predecessor in interest, if
461 +the predecessor has it or can get it with reasonable efforts.
462 +
463 + You may not impose any further restrictions on the exercise of the
464 +rights granted or affirmed under this License. For example, you may
465 +not impose a license fee, royalty, or other charge for exercise of
466 +rights granted under this License, and you may not initiate litigation
467 +(including a cross-claim or counterclaim in a lawsuit) alleging that
468 +any patent claim is infringed by making, using, selling, offering for
469 +sale, or importing the Program or any portion of it.
470 +
471 + 11. Patents.
472 +
473 + A "contributor" is a copyright holder who authorizes use under this
474 +License of the Program or a work on which the Program is based. The
475 +work thus licensed is called the contributor's "contributor version".
476 +
477 + A contributor's "essential patent claims" are all patent claims
478 +owned or controlled by the contributor, whether already acquired or
479 +hereafter acquired, that would be infringed by some manner, permitted
480 +by this License, of making, using, or selling its contributor version,
481 +but do not include claims that would be infringed only as a
482 +consequence of further modification of the contributor version. For
483 +purposes of this definition, "control" includes the right to grant
484 +patent sublicenses in a manner consistent with the requirements of
485 +this License.
486 +
487 + Each contributor grants you a non-exclusive, worldwide, royalty-free
488 +patent license under the contributor's essential patent claims, to
489 +make, use, sell, offer for sale, import and otherwise run, modify and
490 +propagate the contents of its contributor version.
491 +
492 + In the following three paragraphs, a "patent license" is any express
493 +agreement or commitment, however denominated, not to enforce a patent
494 +(such as an express permission to practice a patent or covenant not to
495 +sue for patent infringement). To "grant" such a patent license to a
496 +party means to make such an agreement or commitment not to enforce a
497 +patent against the party.
498 +
499 + If you convey a covered work, knowingly relying on a patent license,
500 +and the Corresponding Source of the work is not available for anyone
501 +to copy, free of charge and under the terms of this License, through a
502 +publicly available network server or other readily accessible means,
503 +then you must either (1) cause the Corresponding Source to be so
504 +available, or (2) arrange to deprive yourself of the benefit of the
505 +patent license for this particular work, or (3) arrange, in a manner
506 +consistent with the requirements of this License, to extend the patent
507 +license to downstream recipients. "Knowingly relying" means you have
508 +actual knowledge that, but for the patent license, your conveying the
509 +covered work in a country, or your recipient's use of the covered work
510 +in a country, would infringe one or more identifiable patents in that
511 +country that you have reason to believe are valid.
512 +
513 + If, pursuant to or in connection with a single transaction or
514 +arrangement, you convey, or propagate by procuring conveyance of, a
515 +covered work, and grant a patent license to some of the parties
516 +receiving the covered work authorizing them to use, propagate, modify
517 +or convey a specific copy of the covered work, then the patent license
518 +you grant is automatically extended to all recipients of the covered
519 +work and works based on it.
520 +
521 + A patent license is "discriminatory" if it does not include within
522 +the scope of its coverage, prohibits the exercise of, or is
523 +conditioned on the non-exercise of one or more of the rights that are
524 +specifically granted under this License. You may not convey a covered
525 +work if you are a party to an arrangement with a third party that is
526 +in the business of distributing software, under which you make payment
527 +to the third party based on the extent of your activity of conveying
528 +the work, and under which the third party grants, to any of the
529 +parties who would receive the covered work from you, a discriminatory
530 +patent license (a) in connection with copies of the covered work
531 +conveyed by you (or copies made from those copies), or (b) primarily
532 +for and in connection with specific products or compilations that
533 +contain the covered work, unless you entered into that arrangement,
534 +or that patent license was granted, prior to 28 March 2007.
535 +
536 + Nothing in this License shall be construed as excluding or limiting
537 +any implied license or other defenses to infringement that may
538 +otherwise be available to you under applicable patent law.
539 +
540 + 12. No Surrender of Others' Freedom.
541 +
542 + If conditions are imposed on you (whether by court order, agreement or
543 +otherwise) that contradict the conditions of this License, they do not
544 +excuse you from the conditions of this License. If you cannot convey a
545 +covered work so as to satisfy simultaneously your obligations under this
546 +License and any other pertinent obligations, then as a consequence you may
547 +not convey it at all. For example, if you agree to terms that obligate you
548 +to collect a royalty for further conveying from those to whom you convey
549 +the Program, the only way you could satisfy both those terms and this
550 +License would be to refrain entirely from conveying the Program.
551 +
552 + 13. Use with the GNU Affero General Public License.
553 +
554 + Notwithstanding any other provision of this License, you have
555 +permission to link or combine any covered work with a work licensed
556 +under version 3 of the GNU Affero General Public License into a single
557 +combined work, and to convey the resulting work. The terms of this
558 +License will continue to apply to the part which is the covered work,
559 +but the special requirements of the GNU Affero General Public License,
560 +section 13, concerning interaction through a network will apply to the
561 +combination as such.
562 +
563 + 14. Revised Versions of this License.
564 +
565 + The Free Software Foundation may publish revised and/or new versions of
566 +the GNU General Public License from time to time. Such new versions will
567 +be similar in spirit to the present version, but may differ in detail to
568 +address new problems or concerns.
569 +
570 + Each version is given a distinguishing version number. If the
571 +Program specifies that a certain numbered version of the GNU General
572 +Public License "or any later version" applies to it, you have the
573 +option of following the terms and conditions either of that numbered
574 +version or of any later version published by the Free Software
575 +Foundation. If the Program does not specify a version number of the
576 +GNU General Public License, you may choose any version ever published
577 +by the Free Software Foundation.
578 +
579 + If the Program specifies that a proxy can decide which future
580 +versions of the GNU General Public License can be used, that proxy's
581 +public statement of acceptance of a version permanently authorizes you
582 +to choose that version for the Program.
583 +
584 + Later license versions may give you additional or different
585 +permissions. However, no additional obligations are imposed on any
586 +author or copyright holder as a result of your choosing to follow a
587 +later version.
588 +
589 + 15. Disclaimer of Warranty.
590 +
591 + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 +ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 +
600 + 16. Limitation of Liability.
601 +
602 + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 +SUCH DAMAGES.
611 +
612 + 17. Interpretation of Sections 15 and 16.
613 +
614 + If the disclaimer of warranty and limitation of liability provided
615 +above cannot be given local legal effect according to their terms,
616 +reviewing courts shall apply local law that most closely approximates
617 +an absolute waiver of all civil liability in connection with the
618 +Program, unless a warranty or assumption of liability accompanies a
619 +copy of the Program in return for a fee.
620 +
621 + END OF TERMS AND CONDITIONS
622 +
623 + How to Apply These Terms to Your New Programs
624 +
625 + If you develop a new program, and you want it to be of the greatest
626 +possible use to the public, the best way to achieve this is to make it
627 +free software which everyone can redistribute and change under these terms.
628 +
629 + To do so, attach the following notices to the program. It is safest
630 +to attach them to the start of each source file to most effectively
631 +state the exclusion of warranty; and each file should have at least
632 +the "copyright" line and a pointer to where the full notice is found.
633 +
634 + <one line to give the program's name and a brief idea of what it does.>
635 + Copyright (C) <year> <name of author>
636 +
637 + This program is free software: you can redistribute it and/or modify
638 + it under the terms of the GNU General Public License as published by
639 + the Free Software Foundation, either version 3 of the License, or
640 + (at your option) any later version.
641 +
642 + This program is distributed in the hope that it will be useful,
643 + but WITHOUT ANY WARRANTY; without even the implied warranty of
644 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 + GNU General Public License for more details.
646 +
647 + You should have received a copy of the GNU General Public License
648 + along with this program. If not, see <https://www.gnu.org/licenses/>.
649 +
650 +Also add information on how to contact you by electronic and paper mail.
651 +
652 + If the program does terminal interaction, make it output a short
653 +notice like this when it starts in an interactive mode:
654 +
655 + <program> Copyright (C) <year> <name of author>
656 + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 + This is free software, and you are welcome to redistribute it
658 + under certain conditions; type `show c' for details.
659 +
660 +The hypothetical commands `show w' and `show c' should show the appropriate
661 +parts of the General Public License. Of course, your program's commands
662 +might be different; for a GUI interface, you would use an "about box".
663 +
664 + You should also get your employer (if you work as a programmer) or school,
665 +if any, to sign a "copyright disclaimer" for the program, if necessary.
666 +For more information on this, and how to apply and follow the GNU GPL, see
667 +<https://www.gnu.org/licenses/>.
668 +
669 + The GNU General Public License does not permit incorporating your program
670 +into proprietary programs. If your program is a subroutine library, you
671 +may consider it more useful to permit linking proprietary applications with
672 +the library. If this is what you want to do, use the GNU Lesser General
673 +Public License instead of this License. But first, please read
674 +<https://www.gnu.org/licenses/why-not-lgpl.html>.
mqtt_websockets/c_rhash/ChangeLog
mqtt_websockets/c_rhash/INSTALL new
+368
@@ -0,0 +1,368 @@
1 +Installation Instructions
2 +*************************
3 +
4 + Copyright (C) 1994-1996, 1999-2002, 2004-2017, 2020-2021 Free
5 +Software Foundation, Inc.
6 +
7 + Copying and distribution of this file, with or without modification,
8 +are permitted in any medium without royalty provided the copyright
9 +notice and this notice are preserved. This file is offered as-is,
10 +without warranty of any kind.
11 +
12 +Basic Installation
13 +==================
14 +
15 + Briefly, the shell command './configure && make && make install'
16 +should configure, build, and install this package. The following
17 +more-detailed instructions are generic; see the 'README' file for
18 +instructions specific to this package. Some packages provide this
19 +'INSTALL' file but do not implement all of the features documented
20 +below. The lack of an optional feature in a given package is not
21 +necessarily a bug. More recommendations for GNU packages can be found
22 +in *note Makefile Conventions: (standards)Makefile Conventions.
23 +
24 + The 'configure' shell script attempts to guess correct values for
25 +various system-dependent variables used during compilation. It uses
26 +those values to create a 'Makefile' in each directory of the package.
27 +It may also create one or more '.h' files containing system-dependent
28 +definitions. Finally, it creates a shell script 'config.status' that
29 +you can run in the future to recreate the current configuration, and a
30 +file 'config.log' containing compiler output (useful mainly for
31 +debugging 'configure').
32 +
33 + It can also use an optional file (typically called 'config.cache' and
34 +enabled with '--cache-file=config.cache' or simply '-C') that saves the
35 +results of its tests to speed up reconfiguring. Caching is disabled by
36 +default to prevent problems with accidental use of stale cache files.
37 +
38 + If you need to do unusual things to compile the package, please try
39 +to figure out how 'configure' could check whether to do them, and mail
40 +diffs or instructions to the address given in the 'README' so they can
41 +be considered for the next release. If you are using the cache, and at
42 +some point 'config.cache' contains results you don't want to keep, you
43 +may remove or edit it.
44 +
45 + The file 'configure.ac' (or 'configure.in') is used to create
46 +'configure' by a program called 'autoconf'. You need 'configure.ac' if
47 +you want to change it or regenerate 'configure' using a newer version of
48 +'autoconf'.
49 +
50 + The simplest way to compile this package is:
51 +
52 + 1. 'cd' to the directory containing the package's source code and type
53 + './configure' to configure the package for your system.
54 +
55 + Running 'configure' might take a while. While running, it prints
56 + some messages telling which features it is checking for.
57 +
58 + 2. Type 'make' to compile the package.
59 +
60 + 3. Optionally, type 'make check' to run any self-tests that come with
61 + the package, generally using the just-built uninstalled binaries.
62 +
63 + 4. Type 'make install' to install the programs and any data files and
64 + documentation. When installing into a prefix owned by root, it is
65 + recommended that the package be configured and built as a regular
66 + user, and only the 'make install' phase executed with root
67 + privileges.
68 +
69 + 5. Optionally, type 'make installcheck' to repeat any self-tests, but
70 + this time using the binaries in their final installed location.
71 + This target does not install anything. Running this target as a
72 + regular user, particularly if the prior 'make install' required
73 + root privileges, verifies that the installation completed
74 + correctly.
75 +
76 + 6. You can remove the program binaries and object files from the
77 + source code directory by typing 'make clean'. To also remove the
78 + files that 'configure' created (so you can compile the package for
79 + a different kind of computer), type 'make distclean'. There is
80 + also a 'make maintainer-clean' target, but that is intended mainly
81 + for the package's developers. If you use it, you may have to get
82 + all sorts of other programs in order to regenerate files that came
83 + with the distribution.
84 +
85 + 7. Often, you can also type 'make uninstall' to remove the installed
86 + files again. In practice, not all packages have tested that
87 + uninstallation works correctly, even though it is required by the
88 + GNU Coding Standards.
89 +
90 + 8. Some packages, particularly those that use Automake, provide 'make
91 + distcheck', which can by used by developers to test that all other
92 + targets like 'make install' and 'make uninstall' work correctly.
93 + This target is generally not run by end users.
94 +
95 +Compilers and Options
96 +=====================
97 +
98 + Some systems require unusual options for compilation or linking that
99 +the 'configure' script does not know about. Run './configure --help'
100 +for details on some of the pertinent environment variables.
101 +
102 + You can give 'configure' initial values for configuration parameters
103 +by setting variables in the command line or in the environment. Here is
104 +an example:
105 +
106 + ./configure CC=c99 CFLAGS=-g LIBS=-lposix
107 +
108 + *Note Defining Variables::, for more details.
109 +
110 +Compiling For Multiple Architectures
111 +====================================
112 +
113 + You can compile the package for more than one kind of computer at the
114 +same time, by placing the object files for each architecture in their
115 +own directory. To do this, you can use GNU 'make'. 'cd' to the
116 +directory where you want the object files and executables to go and run
117 +the 'configure' script. 'configure' automatically checks for the source
118 +code in the directory that 'configure' is in and in '..'. This is known
119 +as a "VPATH" build.
120 +
121 + With a non-GNU 'make', it is safer to compile the package for one
122 +architecture at a time in the source code directory. After you have
123 +installed the package for one architecture, use 'make distclean' before
124 +reconfiguring for another architecture.
125 +
126 + On MacOS X 10.5 and later systems, you can create libraries and
127 +executables that work on multiple system types--known as "fat" or
128 +"universal" binaries--by specifying multiple '-arch' options to the
129 +compiler but only a single '-arch' option to the preprocessor. Like
130 +this:
131 +
132 + ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
133 + CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
134 + CPP="gcc -E" CXXCPP="g++ -E"
135 +
136 + This is not guaranteed to produce working output in all cases, you
137 +may have to build one architecture at a time and combine the results
138 +using the 'lipo' tool if you have problems.
139 +
140 +Installation Names
141 +==================
142 +
143 + By default, 'make install' installs the package's commands under
144 +'/usr/local/bin', include files under '/usr/local/include', etc. You
145 +can specify an installation prefix other than '/usr/local' by giving
146 +'configure' the option '--prefix=PREFIX', where PREFIX must be an
147 +absolute file name.
148 +
149 + You can specify separate installation prefixes for
150 +architecture-specific files and architecture-independent files. If you
151 +pass the option '--exec-prefix=PREFIX' to 'configure', the package uses
152 +PREFIX as the prefix for installing programs and libraries.
153 +Documentation and other data files still use the regular prefix.
154 +
155 + In addition, if you use an unusual directory layout you can give
156 +options like '--bindir=DIR' to specify different values for particular
157 +kinds of files. Run 'configure --help' for a list of the directories
158 +you can set and what kinds of files go in them. In general, the default
159 +for these options is expressed in terms of '${prefix}', so that
160 +specifying just '--prefix' will affect all of the other directory
161 +specifications that were not explicitly provided.
162 +
163 + The most portable way to affect installation locations is to pass the
164 +correct locations to 'configure'; however, many packages provide one or
165 +both of the following shortcuts of passing variable assignments to the
166 +'make install' command line to change installation locations without
167 +having to reconfigure or recompile.
168 +
169 + The first method involves providing an override variable for each
170 +affected directory. For example, 'make install
171 +prefix=/alternate/directory' will choose an alternate location for all
172 +directory configuration variables that were expressed in terms of
173 +'${prefix}'. Any directories that were specified during 'configure',
174 +but not in terms of '${prefix}', must each be overridden at install time
175 +for the entire installation to be relocated. The approach of makefile
176 +variable overrides for each directory variable is required by the GNU
177 +Coding Standards, and ideally causes no recompilation. However, some
178 +platforms have known limitations with the semantics of shared libraries
179 +that end up requiring recompilation when using this method, particularly
180 +noticeable in packages that use GNU Libtool.
181 +
182 + The second method involves providing the 'DESTDIR' variable. For
183 +example, 'make install DESTDIR=/alternate/directory' will prepend
184 +'/alternate/directory' before all installation names. The approach of
185 +'DESTDIR' overrides is not required by the GNU Coding Standards, and
186 +does not work on platforms that have drive letters. On the other hand,
187 +it does better at avoiding recompilation issues, and works well even
188 +when some directory options were not specified in terms of '${prefix}'
189 +at 'configure' time.
190 +
191 +Optional Features
192 +=================
193 +
194 + If the package supports it, you can cause programs to be installed
195 +with an extra prefix or suffix on their names by giving 'configure' the
196 +option '--program-prefix=PREFIX' or '--program-suffix=SUFFIX'.
197 +
198 + Some packages pay attention to '--enable-FEATURE' options to
199 +'configure', where FEATURE indicates an optional part of the package.
200 +They may also pay attention to '--with-PACKAGE' options, where PACKAGE
201 +is something like 'gnu-as' or 'x' (for the X Window System). The
202 +'README' should mention any '--enable-' and '--with-' options that the
203 +package recognizes.
204 +
205 + For packages that use the X Window System, 'configure' can usually
206 +find the X include and library files automatically, but if it doesn't,
207 +you can use the 'configure' options '--x-includes=DIR' and
208 +'--x-libraries=DIR' to specify their locations.
209 +
210 + Some packages offer the ability to configure how verbose the
211 +execution of 'make' will be. For these packages, running './configure
212 +--enable-silent-rules' sets the default to minimal output, which can be
213 +overridden with 'make V=1'; while running './configure
214 +--disable-silent-rules' sets the default to verbose, which can be
215 +overridden with 'make V=0'.
216 +
217 +Particular systems
218 +==================
219 +
220 + On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC
221 +is not installed, it is recommended to use the following options in
222 +order to use an ANSI C compiler:
223 +
224 + ./configure CC="cc -Ae -D_XOPEN_SOURCE=500"
225 +
226 +and if that doesn't work, install pre-built binaries of GCC for HP-UX.
227 +
228 + HP-UX 'make' updates targets which have the same timestamps as their
229 +prerequisites, which makes it generally unusable when shipped generated
230 +files such as 'configure' are involved. Use GNU 'make' instead.
231 +
232 + On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot
233 +parse its '<wchar.h>' header file. The option '-nodtk' can be used as a
234 +workaround. If GNU CC is not installed, it is therefore recommended to
235 +try
236 +
237 + ./configure CC="cc"
238 +
239 +and if that doesn't work, try
240 +
241 + ./configure CC="cc -nodtk"
242 +
243 + On Solaris, don't put '/usr/ucb' early in your 'PATH'. This
244 +directory contains several dysfunctional programs; working variants of
245 +these programs are available in '/usr/bin'. So, if you need '/usr/ucb'
246 +in your 'PATH', put it _after_ '/usr/bin'.
247 +
248 + On Haiku, software installed for all users goes in '/boot/common',
249 +not '/usr/local'. It is recommended to use the following options:
250 +
251 + ./configure --prefix=/boot/common
252 +
253 +Specifying the System Type
254 +==========================
255 +
256 + There may be some features 'configure' cannot figure out
257 +automatically, but needs to determine by the type of machine the package
258 +will run on. Usually, assuming the package is built to be run on the
259 +_same_ architectures, 'configure' can figure that out, but if it prints
260 +a message saying it cannot guess the machine type, give it the
261 +'--build=TYPE' option. TYPE can either be a short name for the system
262 +type, such as 'sun4', or a canonical name which has the form:
263 +
264 + CPU-COMPANY-SYSTEM
265 +
266 +where SYSTEM can have one of these forms:
267 +
268 + OS
269 + KERNEL-OS
270 +
271 + See the file 'config.sub' for the possible values of each field. If
272 +'config.sub' isn't included in this package, then this package doesn't
273 +need to know the machine type.
274 +
275 + If you are _building_ compiler tools for cross-compiling, you should
276 +use the option '--target=TYPE' to select the type of system they will
277 +produce code for.
278 +
279 + If you want to _use_ a cross compiler, that generates code for a
280 +platform different from the build platform, you should specify the
281 +"host" platform (i.e., that on which the generated programs will
282 +eventually be run) with '--host=TYPE'.
283 +
284 +Sharing Defaults
285 +================
286 +
287 + If you want to set default values for 'configure' scripts to share,
288 +you can create a site shell script called 'config.site' that gives
289 +default values for variables like 'CC', 'cache_file', and 'prefix'.
290 +'configure' looks for 'PREFIX/share/config.site' if it exists, then
291 +'PREFIX/etc/config.site' if it exists. Or, you can set the
292 +'CONFIG_SITE' environment variable to the location of the site script.
293 +A warning: not all 'configure' scripts look for a site script.
294 +
295 +Defining Variables
296 +==================
297 +
298 + Variables not defined in a site shell script can be set in the
299 +environment passed to 'configure'. However, some packages may run
300 +configure again during the build, and the customized values of these
301 +variables may be lost. In order to avoid this problem, you should set
302 +them in the 'configure' command line, using 'VAR=value'. For example:
303 +
304 + ./configure CC=/usr/local2/bin/gcc
305 +
306 +causes the specified 'gcc' to be used as the C compiler (unless it is
307 +overridden in the site shell script).
308 +
309 +Unfortunately, this technique does not work for 'CONFIG_SHELL' due to an
310 +Autoconf limitation. Until the limitation is lifted, you can use this
311 +workaround:
312 +
313 + CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash
314 +
315 +'configure' Invocation
316 +======================
317 +
318 + 'configure' recognizes the following options to control how it
319 +operates.
320 +
321 +'--help'
322 +'-h'
323 + Print a summary of all of the options to 'configure', and exit.
324 +
325 +'--help=short'
326 +'--help=recursive'
327 + Print a summary of the options unique to this package's
328 + 'configure', and exit. The 'short' variant lists options used only
329 + in the top level, while the 'recursive' variant lists options also
330 + present in any nested packages.
331 +
332 +'--version'
333 +'-V'
334 + Print the version of Autoconf used to generate the 'configure'
335 + script, and exit.
336 +
337 +'--cache-file=FILE'
338 + Enable the cache: use and save the results of the tests in FILE,
339 + traditionally 'config.cache'. FILE defaults to '/dev/null' to
340 + disable caching.
341 +
342 +'--config-cache'
343 +'-C'
344 + Alias for '--cache-file=config.cache'.
345 +
346 +'--quiet'
347 +'--silent'
348 +'-q'
349 + Do not print messages saying which checks are being made. To
350 + suppress all normal output, redirect it to '/dev/null' (any error
351 + messages will still be shown).
352 +
353 +'--srcdir=DIR'
354 + Look for the package's source code in directory DIR. Usually
355 + 'configure' can determine that directory automatically.
356 +
357 +'--prefix=DIR'
358 + Use DIR as the installation prefix. *note Installation Names:: for
359 + more details, including other options available for fine-tuning the
360 + installation locations.
361 +
362 +'--no-create'
363 +'-n'
364 + Run the configure checks, but stop before creating any output
365 + files.
366 +
367 +'configure' also accepts some other, not widely useful, options. Run
368 +'configure --help' for more details.
mqtt_websockets/c_rhash/LICENSE new
+674
@@ -0,0 +1,674 @@
1 + GNU GENERAL PUBLIC LICENSE
2 + Version 3, 29 June 2007
3 +
4 + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5 + Everyone is permitted to copy and distribute verbatim copies
6 + of this license document, but changing it is not allowed.
7 +
8 + Preamble
9 +
10 + The GNU General Public License is a free, copyleft license for
11 +software and other kinds of works.
12 +
13 + The licenses for most software and other practical works are designed
14 +to take away your freedom to share and change the works. By contrast,
15 +the GNU General Public License is intended to guarantee your freedom to
16 +share and change all versions of a program--to make sure it remains free
17 +software for all its users. We, the Free Software Foundation, use the
18 +GNU General Public License for most of our software; it applies also to
19 +any other work released this way by its authors. You can apply it to
20 +your programs, too.
21 +
22 + When we speak of free software, we are referring to freedom, not
23 +price. Our General Public Licenses are designed to make sure that you
24 +have the freedom to distribute copies of free software (and charge for
25 +them if you wish), that you receive source code or can get it if you
26 +want it, that you can change the software or use pieces of it in new
27 +free programs, and that you know you can do these things.
28 +
29 + To protect your rights, we need to prevent others from denying you
30 +these rights or asking you to surrender the rights. Therefore, you have
31 +certain responsibilities if you distribute copies of the software, or if
32 +you modify it: responsibilities to respect the freedom of others.
33 +
34 + For example, if you distribute copies of such a program, whether
35 +gratis or for a fee, you must pass on to the recipients the same
36 +freedoms that you received. You must make sure that they, too, receive
37 +or can get the source code. And you must show them these terms so they
38 +know their rights.
39 +
40 + Developers that use the GNU GPL protect your rights with two steps:
41 +(1) assert copyright on the software, and (2) offer you this License
42 +giving you legal permission to copy, distribute and/or modify it.
43 +
44 + For the developers' and authors' protection, the GPL clearly explains
45 +that there is no warranty for this free software. For both users' and
46 +authors' sake, the GPL requires that modified versions be marked as
47 +changed, so that their problems will not be attributed erroneously to
48 +authors of previous versions.
49 +
50 + Some devices are designed to deny users access to install or run
51 +modified versions of the software inside them, although the manufacturer
52 +can do so. This is fundamentally incompatible with the aim of
53 +protecting users' freedom to change the software. The systematic
54 +pattern of such abuse occurs in the area of products for individuals to
55 +use, which is precisely where it is most unacceptable. Therefore, we
56 +have designed this version of the GPL to prohibit the practice for those
57 +products. If such problems arise substantially in other domains, we
58 +stand ready to extend this provision to those domains in future versions
59 +of the GPL, as needed to protect the freedom of users.
60 +
61 + Finally, every program is threatened constantly by software patents.
62 +States should not allow patents to restrict development and use of
63 +software on general-purpose computers, but in those that do, we wish to
64 +avoid the special danger that patents applied to a free program could
65 +make it effectively proprietary. To prevent this, the GPL assures that
66 +patents cannot be used to render the program non-free.
67 +
68 + The precise terms and conditions for copying, distribution and
69 +modification follow.
70 +
71 + TERMS AND CONDITIONS
72 +
73 + 0. Definitions.
74 +
75 + "This License" refers to version 3 of the GNU General Public License.
76 +
77 + "Copyright" also means copyright-like laws that apply to other kinds of
78 +works, such as semiconductor masks.
79 +
80 + "The Program" refers to any copyrightable work licensed under this
81 +License. Each licensee is addressed as "you". "Licensees" and
82 +"recipients" may be individuals or organizations.
83 +
84 + To "modify" a work means to copy from or adapt all or part of the work
85 +in a fashion requiring copyright permission, other than the making of an
86 +exact copy. The resulting work is called a "modified version" of the
87 +earlier work or a work "based on" the earlier work.
88 +
89 + A "covered work" means either the unmodified Program or a work based
90 +on the Program.
91 +
92 + To "propagate" a work means to do anything with it that, without
93 +permission, would make you directly or secondarily liable for
94 +infringement under applicable copyright law, except executing it on a
95 +computer or modifying a private copy. Propagation includes copying,
96 +distribution (with or without modification), making available to the
97 +public, and in some countries other activities as well.
98 +
99 + To "convey" a work means any kind of propagation that enables other
100 +parties to make or receive copies. Mere interaction with a user through
101 +a computer network, with no transfer of a copy, is not conveying.
102 +
103 + An interactive user interface displays "Appropriate Legal Notices"
104 +to the extent that it includes a convenient and prominently visible
105 +feature that (1) displays an appropriate copyright notice, and (2)
106 +tells the user that there is no warranty for the work (except to the
107 +extent that warranties are provided), that licensees may convey the
108 +work under this License, and how to view a copy of this License. If
109 +the interface presents a list of user commands or options, such as a
110 +menu, a prominent item in the list meets this criterion.
111 +
112 + 1. Source Code.
113 +
114 + The "source code" for a work means the preferred form of the work
115 +for making modifications to it. "Object code" means any non-source
116 +form of a work.
117 +
118 + A "Standard Interface" means an interface that either is an official
119 +standard defined by a recognized standards body, or, in the case of
120 +interfaces specified for a particular programming language, one that
121 +is widely used among developers working in that language.
122 +
123 + The "System Libraries" of an executable work include anything, other
124 +than the work as a whole, that (a) is included in the normal form of
125 +packaging a Major Component, but which is not part of that Major
126 +Component, and (b) serves only to enable use of the work with that
127 +Major Component, or to implement a Standard Interface for which an
128 +implementation is available to the public in source code form. A
129 +"Major Component", in this context, means a major essential component
130 +(kernel, window system, and so on) of the specific operating system
131 +(if any) on which the executable work runs, or a compiler used to
132 +produce the work, or an object code interpreter used to run it.
133 +
134 + The "Corresponding Source" for a work in object code form means all
135 +the source code needed to generate, install, and (for an executable
136 +work) run the object code and to modify the work, including scripts to
137 +control those activities. However, it does not include the work's
138 +System Libraries, or general-purpose tools or generally available free
139 +programs which are used unmodified in performing those activities but
140 +which are not part of the work. For example, Corresponding Source
141 +includes interface definition files associated with source files for
142 +the work, and the source code for shared libraries and dynamically
143 +linked subprograms that the work is specifically designed to require,
144 +such as by intimate data communication or control flow between those
145 +subprograms and other parts of the work.
146 +
147 + The Corresponding Source need not include anything that users
148 +can regenerate automatically from other parts of the Corresponding
149 +Source.
150 +
151 + The Corresponding Source for a work in source code form is that
152 +same work.
153 +
154 + 2. Basic Permissions.
155 +
156 + All rights granted under this License are granted for the term of
157 +copyright on the Program, and are irrevocable provided the stated
158 +conditions are met. This License explicitly affirms your unlimited
159 +permission to run the unmodified Program. The output from running a
160 +covered work is covered by this License only if the output, given its
161 +content, constitutes a covered work. This License acknowledges your
162 +rights of fair use or other equivalent, as provided by copyright law.
163 +
164 + You may make, run and propagate covered works that you do not
165 +convey, without conditions so long as your license otherwise remains
166 +in force. You may convey covered works to others for the sole purpose
167 +of having them make modifications exclusively for you, or provide you
168 +with facilities for running those works, provided that you comply with
169 +the terms of this License in conveying all material for which you do
170 +not control copyright. Those thus making or running the covered works
171 +for you must do so exclusively on your behalf, under your direction
172 +and control, on terms that prohibit them from making any copies of
173 +your copyrighted material outside their relationship with you.
174 +
175 + Conveying under any other circumstances is permitted solely under
176 +the conditions stated below. Sublicensing is not allowed; section 10
177 +makes it unnecessary.
178 +
179 + 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 +
181 + No covered work shall be deemed part of an effective technological
182 +measure under any applicable law fulfilling obligations under article
183 +11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 +similar laws prohibiting or restricting circumvention of such
185 +measures.
186 +
187 + When you convey a covered work, you waive any legal power to forbid
188 +circumvention of technological measures to the extent such circumvention
189 +is effected by exercising rights under this License with respect to
190 +the covered work, and you disclaim any intention to limit operation or
191 +modification of the work as a means of enforcing, against the work's
192 +users, your or third parties' legal rights to forbid circumvention of
193 +technological measures.
194 +
195 + 4. Conveying Verbatim Copies.
196 +
197 + You may convey verbatim copies of the Program's source code as you
198 +receive it, in any medium, provided that you conspicuously and
199 +appropriately publish on each copy an appropriate copyright notice;
200 +keep intact all notices stating that this License and any
201 +non-permissive terms added in accord with section 7 apply to the code;
202 +keep intact all notices of the absence of any warranty; and give all
203 +recipients a copy of this License along with the Program.
204 +
205 + You may charge any price or no price for each copy that you convey,
206 +and you may offer support or warranty protection for a fee.
207 +
208 + 5. Conveying Modified Source Versions.
209 +
210 + You may convey a work based on the Program, or the modifications to
211 +produce it from the Program, in the form of source code under the
212 +terms of section 4, provided that you also meet all of these conditions:
213 +
214 + a) The work must carry prominent notices stating that you modified
215 + it, and giving a relevant date.
216 +
217 + b) The work must carry prominent notices stating that it is
218 + released under this License and any conditions added under section
219 + 7. This requirement modifies the requirement in section 4 to
220 + "keep intact all notices".
221 +
222 + c) You must license the entire work, as a whole, under this
223 + License to anyone who comes into possession of a copy. This
224 + License will therefore apply, along with any applicable section 7
225 + additional terms, to the whole of the work, and all its parts,
226 + regardless of how they are packaged. This License gives no
227 + permission to license the work in any other way, but it does not
228 + invalidate such permission if you have separately received it.
229 +
230 + d) If the work has interactive user interfaces, each must display
231 + Appropriate Legal Notices; however, if the Program has interactive
232 + interfaces that do not display Appropriate Legal Notices, your
233 + work need not make them do so.
234 +
235 + A compilation of a covered work with other separate and independent
236 +works, which are not by their nature extensions of the covered work,
237 +and which are not combined with it such as to form a larger program,
238 +in or on a volume of a storage or distribution medium, is called an
239 +"aggregate" if the compilation and its resulting copyright are not
240 +used to limit the access or legal rights of the compilation's users
241 +beyond what the individual works permit. Inclusion of a covered work
242 +in an aggregate does not cause this License to apply to the other
243 +parts of the aggregate.
244 +
245 + 6. Conveying Non-Source Forms.
246 +
247 + You may convey a covered work in object code form under the terms
248 +of sections 4 and 5, provided that you also convey the
249 +machine-readable Corresponding Source under the terms of this License,
250 +in one of these ways:
251 +
252 + a) Convey the object code in, or embodied in, a physical product
253 + (including a physical distribution medium), accompanied by the
254 + Corresponding Source fixed on a durable physical medium
255 + customarily used for software interchange.
256 +
257 + b) Convey the object code in, or embodied in, a physical product
258 + (including a physical distribution medium), accompanied by a
259 + written offer, valid for at least three years and valid for as
260 + long as you offer spare parts or customer support for that product
261 + model, to give anyone who possesses the object code either (1) a
262 + copy of the Corresponding Source for all the software in the
263 + product that is covered by this License, on a durable physical
264 + medium customarily used for software interchange, for a price no
265 + more than your reasonable cost of physically performing this
266 + conveying of source, or (2) access to copy the
267 + Corresponding Source from a network server at no charge.
268 +
269 + c) Convey individual copies of the object code with a copy of the
270 + written offer to provide the Corresponding Source. This
271 + alternative is allowed only occasionally and noncommercially, and
272 + only if you received the object code with such an offer, in accord
273 + with subsection 6b.
274 +
275 + d) Convey the object code by offering access from a designated
276 + place (gratis or for a charge), and offer equivalent access to the
277 + Corresponding Source in the same way through the same place at no
278 + further charge. You need not require recipients to copy the
279 + Corresponding Source along with the object code. If the place to
280 + copy the object code is a network server, the Corresponding Source
281 + may be on a different server (operated by you or a third party)
282 + that supports equivalent copying facilities, provided you maintain
283 + clear directions next to the object code saying where to find the
284 + Corresponding Source. Regardless of what server hosts the
285 + Corresponding Source, you remain obligated to ensure that it is
286 + available for as long as needed to satisfy these requirements.
287 +
288 + e) Convey the object code using peer-to-peer transmission, provided
289 + you inform other peers where the object code and Corresponding
290 + Source of the work are being offered to the general public at no
291 + charge under subsection 6d.
292 +
293 + A separable portion of the object code, whose source code is excluded
294 +from the Corresponding Source as a System Library, need not be
295 +included in conveying the object code work.
296 +
297 + A "User Product" is either (1) a "consumer product", which means any
298 +tangible personal property which is normally used for personal, family,
299 +or household purposes, or (2) anything designed or sold for incorporation
300 +into a dwelling. In determining whether a product is a consumer product,
301 +doubtful cases shall be resolved in favor of coverage. For a particular
302 +product received by a particular user, "normally used" refers to a
303 +typical or common use of that class of product, regardless of the status
304 +of the particular user or of the way in which the particular user
305 +actually uses, or expects or is expected to use, the product. A product
306 +is a consumer product regardless of whether the product has substantial
307 +commercial, industrial or non-consumer uses, unless such uses represent
308 +the only significant mode of use of the product.
309 +
310 + "Installation Information" for a User Product means any methods,
311 +procedures, authorization keys, or other information required to install
312 +and execute modified versions of a covered work in that User Product from
313 +a modified version of its Corresponding Source. The information must
314 +suffice to ensure that the continued functioning of the modified object
315 +code is in no case prevented or interfered with solely because
316 +modification has been made.
317 +
318 + If you convey an object code work under this section in, or with, or
319 +specifically for use in, a User Product, and the conveying occurs as
320 +part of a transaction in which the right of possession and use of the
321 +User Product is transferred to the recipient in perpetuity or for a
322 +fixed term (regardless of how the transaction is characterized), the
323 +Corresponding Source conveyed under this section must be accompanied
324 +by the Installation Information. But this requirement does not apply
325 +if neither you nor any third party retains the ability to install
326 +modified object code on the User Product (for example, the work has
327 +been installed in ROM).
328 +
329 + The requirement to provide Installation Information does not include a
330 +requirement to continue to provide support service, warranty, or updates
331 +for a work that has been modified or installed by the recipient, or for
332 +the User Product in which it has been modified or installed. Access to a
333 +network may be denied when the modification itself materially and
334 +adversely affects the operation of the network or violates the rules and
335 +protocols for communication across the network.
336 +
337 + Corresponding Source conveyed, and Installation Information provided,
338 +in accord with this section must be in a format that is publicly
339 +documented (and with an implementation available to the public in
340 +source code form), and must require no special password or key for
341 +unpacking, reading or copying.
342 +
343 + 7. Additional Terms.
344 +
345 + "Additional permissions" are terms that supplement the terms of this
346 +License by making exceptions from one or more of its conditions.
347 +Additional permissions that are applicable to the entire Program shall
348 +be treated as though they were included in this License, to the extent
349 +that they are valid under applicable law. If additional permissions
350 +apply only to part of the Program, that part may be used separately
351 +under those permissions, but the entire Program remains governed by
352 +this License without regard to the additional permissions.
353 +
354 + When you convey a copy of a covered work, you may at your option
355 +remove any additional permissions from that copy, or from any part of
356 +it. (Additional permissions may be written to require their own
357 +removal in certain cases when you modify the work.) You may place
358 +additional permissions on material, added by you to a covered work,
359 +for which you have or can give appropriate copyright permission.
360 +
361 + Notwithstanding any other provision of this License, for material you
362 +add to a covered work, you may (if authorized by the copyright holders of
363 +that material) supplement the terms of this License with terms:
364 +
365 + a) Disclaiming warranty or limiting liability differently from the
366 + terms of sections 15 and 16 of this License; or
367 +
368 + b) Requiring preservation of specified reasonable legal notices or
369 + author attributions in that material or in the Appropriate Legal
370 + Notices displayed by works containing it; or
371 +
372 + c) Prohibiting misrepresentation of the origin of that material, or
373 + requiring that modified versions of such material be marked in
374 + reasonable ways as different from the original version; or
375 +
376 + d) Limiting the use for publicity purposes of names of licensors or
377 + authors of the material; or
378 +
379 + e) Declining to grant rights under trademark law for use of some
380 + trade names, trademarks, or service marks; or
381 +
382 + f) Requiring indemnification of licensors and authors of that
383 + material by anyone who conveys the material (or modified versions of
384 + it) with contractual assumptions of liability to the recipient, for
385 + any liability that these contractual assumptions directly impose on
386 + those licensors and authors.
387 +
388 + All other non-permissive additional terms are considered "further
389 +restrictions" within the meaning of section 10. If the Program as you
390 +received it, or any part of it, contains a notice stating that it is
391 +governed by this License along with a term that is a further
392 +restriction, you may remove that term. If a license document contains
393 +a further restriction but permits relicensing or conveying under this
394 +License, you may add to a covered work material governed by the terms
395 +of that license document, provided that the further restriction does
396 +not survive such relicensing or conveying.
397 +
398 + If you add terms to a covered work in accord with this section, you
399 +must place, in the relevant source files, a statement of the
400 +additional terms that apply to those files, or a notice indicating
401 +where to find the applicable terms.
402 +
403 + Additional terms, permissive or non-permissive, may be stated in the
404 +form of a separately written license, or stated as exceptions;
405 +the above requirements apply either way.
406 +
407 + 8. Termination.
408 +
409 + You may not propagate or modify a covered work except as expressly
410 +provided under this License. Any attempt otherwise to propagate or
411 +modify it is void, and will automatically terminate your rights under
412 +this License (including any patent licenses granted under the third
413 +paragraph of section 11).
414 +
415 + However, if you cease all violation of this License, then your
416 +license from a particular copyright holder is reinstated (a)
417 +provisionally, unless and until the copyright holder explicitly and
418 +finally terminates your license, and (b) permanently, if the copyright
419 +holder fails to notify you of the violation by some reasonable means
420 +prior to 60 days after the cessation.
421 +
422 + Moreover, your license from a particular copyright holder is
423 +reinstated permanently if the copyright holder notifies you of the
424 +violation by some reasonable means, this is the first time you have
425 +received notice of violation of this License (for any work) from that
426 +copyright holder, and you cure the violation prior to 30 days after
427 +your receipt of the notice.
428 +
429 + Termination of your rights under this section does not terminate the
430 +licenses of parties who have received copies or rights from you under
431 +this License. If your rights have been terminated and not permanently
432 +reinstated, you do not qualify to receive new licenses for the same
433 +material under section 10.
434 +
435 + 9. Acceptance Not Required for Having Copies.
436 +
437 + You are not required to accept this License in order to receive or
438 +run a copy of the Program. Ancillary propagation of a covered work
439 +occurring solely as a consequence of using peer-to-peer transmission
440 +to receive a copy likewise does not require acceptance. However,
441 +nothing other than this License grants you permission to propagate or
442 +modify any covered work. These actions infringe copyright if you do
443 +not accept this License. Therefore, by modifying or propagating a
444 +covered work, you indicate your acceptance of this License to do so.
445 +
446 + 10. Automatic Licensing of Downstream Recipients.
447 +
448 + Each time you convey a covered work, the recipient automatically
449 +receives a license from the original licensors, to run, modify and
450 +propagate that work, subject to this License. You are not responsible
451 +for enforcing compliance by third parties with this License.
452 +
453 + An "entity transaction" is a transaction transferring control of an
454 +organization, or substantially all assets of one, or subdividing an
455 +organization, or merging organizations. If propagation of a covered
456 +work results from an entity transaction, each party to that
457 +transaction who receives a copy of the work also receives whatever
458 +licenses to the work the party's predecessor in interest had or could
459 +give under the previous paragraph, plus a right to possession of the
460 +Corresponding Source of the work from the predecessor in interest, if
461 +the predecessor has it or can get it with reasonable efforts.
462 +
463 + You may not impose any further restrictions on the exercise of the
464 +rights granted or affirmed under this License. For example, you may
465 +not impose a license fee, royalty, or other charge for exercise of
466 +rights granted under this License, and you may not initiate litigation
467 +(including a cross-claim or counterclaim in a lawsuit) alleging that
468 +any patent claim is infringed by making, using, selling, offering for
469 +sale, or importing the Program or any portion of it.
470 +
471 + 11. Patents.
472 +
473 + A "contributor" is a copyright holder who authorizes use under this
474 +License of the Program or a work on which the Program is based. The
475 +work thus licensed is called the contributor's "contributor version".
476 +
477 + A contributor's "essential patent claims" are all patent claims
478 +owned or controlled by the contributor, whether already acquired or
479 +hereafter acquired, that would be infringed by some manner, permitted
480 +by this License, of making, using, or selling its contributor version,
481 +but do not include claims that would be infringed only as a
482 +consequence of further modification of the contributor version. For
483 +purposes of this definition, "control" includes the right to grant
484 +patent sublicenses in a manner consistent with the requirements of
485 +this License.
486 +
487 + Each contributor grants you a non-exclusive, worldwide, royalty-free
488 +patent license under the contributor's essential patent claims, to
489 +make, use, sell, offer for sale, import and otherwise run, modify and
490 +propagate the contents of its contributor version.
491 +
492 + In the following three paragraphs, a "patent license" is any express
493 +agreement or commitment, however denominated, not to enforce a patent
494 +(such as an express permission to practice a patent or covenant not to
495 +sue for patent infringement). To "grant" such a patent license to a
496 +party means to make such an agreement or commitment not to enforce a
497 +patent against the party.
498 +
499 + If you convey a covered work, knowingly relying on a patent license,
500 +and the Corresponding Source of the work is not available for anyone
501 +to copy, free of charge and under the terms of this License, through a
502 +publicly available network server or other readily accessible means,
503 +then you must either (1) cause the Corresponding Source to be so
504 +available, or (2) arrange to deprive yourself of the benefit of the
505 +patent license for this particular work, or (3) arrange, in a manner
506 +consistent with the requirements of this License, to extend the patent
507 +license to downstream recipients. "Knowingly relying" means you have
508 +actual knowledge that, but for the patent license, your conveying the
509 +covered work in a country, or your recipient's use of the covered work
510 +in a country, would infringe one or more identifiable patents in that
511 +country that you have reason to believe are valid.
512 +
513 + If, pursuant to or in connection with a single transaction or
514 +arrangement, you convey, or propagate by procuring conveyance of, a
515 +covered work, and grant a patent license to some of the parties
516 +receiving the covered work authorizing them to use, propagate, modify
517 +or convey a specific copy of the covered work, then the patent license
518 +you grant is automatically extended to all recipients of the covered
519 +work and works based on it.
520 +
521 + A patent license is "discriminatory" if it does not include within
522 +the scope of its coverage, prohibits the exercise of, or is
523 +conditioned on the non-exercise of one or more of the rights that are
524 +specifically granted under this License. You may not convey a covered
525 +work if you are a party to an arrangement with a third party that is
526 +in the business of distributing software, under which you make payment
527 +to the third party based on the extent of your activity of conveying
528 +the work, and under which the third party grants, to any of the
529 +parties who would receive the covered work from you, a discriminatory
530 +patent license (a) in connection with copies of the covered work
531 +conveyed by you (or copies made from those copies), or (b) primarily
532 +for and in connection with specific products or compilations that
533 +contain the covered work, unless you entered into that arrangement,
534 +or that patent license was granted, prior to 28 March 2007.
535 +
536 + Nothing in this License shall be construed as excluding or limiting
537 +any implied license or other defenses to infringement that may
538 +otherwise be available to you under applicable patent law.
539 +
540 + 12. No Surrender of Others' Freedom.
541 +
542 + If conditions are imposed on you (whether by court order, agreement or
543 +otherwise) that contradict the conditions of this License, they do not
544 +excuse you from the conditions of this License. If you cannot convey a
545 +covered work so as to satisfy simultaneously your obligations under this
546 +License and any other pertinent obligations, then as a consequence you may
547 +not convey it at all. For example, if you agree to terms that obligate you
548 +to collect a royalty for further conveying from those to whom you convey
549 +the Program, the only way you could satisfy both those terms and this
550 +License would be to refrain entirely from conveying the Program.
551 +
552 + 13. Use with the GNU Affero General Public License.
553 +
554 + Notwithstanding any other provision of this License, you have
555 +permission to link or combine any covered work with a work licensed
556 +under version 3 of the GNU Affero General Public License into a single
557 +combined work, and to convey the resulting work. The terms of this
558 +License will continue to apply to the part which is the covered work,
559 +but the special requirements of the GNU Affero General Public License,
560 +section 13, concerning interaction through a network will apply to the
561 +combination as such.
562 +
563 + 14. Revised Versions of this License.
564 +
565 + The Free Software Foundation may publish revised and/or new versions of
566 +the GNU General Public License from time to time. Such new versions will
567 +be similar in spirit to the present version, but may differ in detail to
568 +address new problems or concerns.
569 +
570 + Each version is given a distinguishing version number. If the
571 +Program specifies that a certain numbered version of the GNU General
572 +Public License "or any later version" applies to it, you have the
573 +option of following the terms and conditions either of that numbered
574 +version or of any later version published by the Free Software
575 +Foundation. If the Program does not specify a version number of the
576 +GNU General Public License, you may choose any version ever published
577 +by the Free Software Foundation.
578 +
579 + If the Program specifies that a proxy can decide which future
580 +versions of the GNU General Public License can be used, that proxy's
581 +public statement of acceptance of a version permanently authorizes you
582 +to choose that version for the Program.
583 +
584 + Later license versions may give you additional or different
585 +permissions. However, no additional obligations are imposed on any
586 +author or copyright holder as a result of your choosing to follow a
587 +later version.
588 +
589 + 15. Disclaimer of Warranty.
590 +
591 + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 +ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 +
600 + 16. Limitation of Liability.
601 +
602 + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 +SUCH DAMAGES.
611 +
612 + 17. Interpretation of Sections 15 and 16.
613 +
614 + If the disclaimer of warranty and limitation of liability provided
615 +above cannot be given local legal effect according to their terms,
616 +reviewing courts shall apply local law that most closely approximates
617 +an absolute waiver of all civil liability in connection with the
618 +Program, unless a warranty or assumption of liability accompanies a
619 +copy of the Program in return for a fee.
620 +
621 + END OF TERMS AND CONDITIONS
622 +
623 + How to Apply These Terms to Your New Programs
624 +
625 + If you develop a new program, and you want it to be of the greatest
626 +possible use to the public, the best way to achieve this is to make it
627 +free software which everyone can redistribute and change under these terms.
628 +
629 + To do so, attach the following notices to the program. It is safest
630 +to attach them to the start of each source file to most effectively
631 +state the exclusion of warranty; and each file should have at least
632 +the "copyright" line and a pointer to where the full notice is found.
633 +
634 + <one line to give the program's name and a brief idea of what it does.>
635 + Copyright (C) <year> <name of author>
636 +
637 + This program is free software: you can redistribute it and/or modify
638 + it under the terms of the GNU General Public License as published by
639 + the Free Software Foundation, either version 3 of the License, or
640 + (at your option) any later version.
641 +
642 + This program is distributed in the hope that it will be useful,
643 + but WITHOUT ANY WARRANTY; without even the implied warranty of
644 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 + GNU General Public License for more details.
646 +
647 + You should have received a copy of the GNU General Public License
648 + along with this program. If not, see <https://www.gnu.org/licenses/>.
649 +
650 +Also add information on how to contact you by electronic and paper mail.
651 +
652 + If the program does terminal interaction, make it output a short
653 +notice like this when it starts in an interactive mode:
654 +
655 + <program> Copyright (C) <year> <name of author>
656 + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 + This is free software, and you are welcome to redistribute it
658 + under certain conditions; type `show c' for details.
659 +
660 +The hypothetical commands `show w' and `show c' should show the appropriate
661 +parts of the General Public License. Of course, your program's commands
662 +might be different; for a GUI interface, you would use an "about box".
663 +
664 + You should also get your employer (if you work as a programmer) or school,
665 +if any, to sign a "copyright disclaimer" for the program, if necessary.
666 +For more information on this, and how to apply and follow the GNU GPL, see
667 +<https://www.gnu.org/licenses/>.
668 +
669 + The GNU General Public License does not permit incorporating your program
670 +into proprietary programs. If your program is a subroutine library, you
671 +may consider it more useful to permit linking proprietary applications with
672 +the library. If this is what you want to do, use the GNU Lesser General
673 +Public License instead of this License. But first, please read
674 +<https://www.gnu.org/licenses/why-not-lgpl.html>.
mqtt_websockets/c_rhash/Makefile.am new
+21
@@ -0,0 +1,21 @@
1 +crhash_includedir = -I$(abs_top_srcdir)/include
2 +
3 +dist_doc_DATA = LICENSE \
4 + README.md \
5 + $(NULL)
6 +
7 +CRHASH_FILES = src/c_rhash.c \
8 + src/c_rhash.h \
9 + $(NULL)
10 +
11 +lib_LIBRARIES = libcrhash.a
12 +
13 +libcrhash_a_SOURCES = $(CRHASH_FILES)
14 +
15 +libcrhash_a_CFLAGS = $(crhash_includedir)
16 +
17 +bin_PROGRAMS = test
18 +test_LDADD = libcrhash.a
19 +
20 +test_SOURCES = src/tests.c
21 +test_CFLAGS = $(crhash_includedir)
mqtt_websockets/c_rhash/NEWS
mqtt_websockets/c_rhash/README.md
mqtt_websockets/c_rhash/configure.ac new
+8
@@ -0,0 +1,8 @@
1 +AC_INIT([c_rbuf], [0.1])
2 +AM_INIT_AUTOMAKE([subdir-objects])
3 +AC_PROG_CC
4 +AC_PROG_RANLIB
5 +
6 +AC_CONFIG_FILES([Makefile])
7 +
8 +AC_OUTPUT
mqtt_websockets/c_rhash/include/c_rhash.h new
+59
@@ -0,0 +1,59 @@
1 +#include <sys/types.h>
2 +#include <stdint.h>
3 +#include <stddef.h>
4 +
5 +#ifndef DEFAULT_BIN_COUNT
6 + #define DEFAULT_BIN_COUNT 1000
7 +#endif
8 +
9 +#define ITEMTYPE_UNSET (0x0)
10 +#define ITEMTYPE_STRING (0x1)
11 +#define ITEMTYPE_UINT8 (0x2)
12 +#define ITEMTYPE_UINT64 (0x3)
13 +#define ITEMTYPE_OPAQUE_PTR (0x4)
14 +
15 +typedef struct c_rhash_s *c_rhash;
16 +
17 +c_rhash c_rhash_new(size_t bin_count);
18 +
19 +void c_rhash_destroy(c_rhash hash);
20 +
21 +// # Insert
22 +// ## Insert where key is string
23 +int c_rhash_insert_str_ptr(c_rhash hash, const char *key, void *value);
24 +int c_rhash_insert_str_uint8(c_rhash hash, const char *key, uint8_t value);
25 +// ## Insert where key is uint64
26 +int c_rhash_insert_uint64_ptr(c_rhash hash, uint64_t key, void *value);
27 +
28 +// # Get
29 +// ## Get where key is string
30 +int c_rhash_get_ptr_by_str(c_rhash hash, const char *key, void **ret_val);
31 +int c_rhash_get_uint8_by_str(c_rhash hash, const char *key, uint8_t *ret_val);
32 +// ## Get where key is uint64
33 +int c_rhash_get_ptr_by_uint64(c_rhash hash, uint64_t key, void **ret_val);
34 +
35 +typedef struct {
36 + size_t bin;
37 + struct bin_item *item;
38 + int initialized;
39 +} c_rhash_iter_t;
40 +
41 +#define C_RHASH_ITER_T_INITIALIZER { .bin = 0, .item = NULL, .initialized = 0 }
42 +
43 +#define c_rhash_iter_t_initialize(p_iter) memset(p_iter, 0, sizeof(c_rhash_iter_t))
44 +
45 +/*
46 + * goes trough whole hash map and returns every
47 + * type uint64 key present/stored
48 + *
49 + * it is not necessary to finish iterating and iterator can be reinitialized
50 + * there are no guarantees on the order in which the keys will come
51 + * behavior here is implementation dependent and can change any time
52 + *
53 + * returns:
54 + * 0 for every key and stores the key in *key
55 + * 1 on error or when all keys of this type has been already iterated over
56 + */
57 +int c_rhash_iter_uint64_keys(c_rhash hash, c_rhash_iter_t *iter, uint64_t *key);
58 +
59 +int c_rhash_iter_str_keys(c_rhash hash, c_rhash_iter_t *iter, const char **key);
mqtt_websockets/c_rhash/src/c_rhash.c new
+262
@@ -0,0 +1,262 @@
1 +#include "c_rhash_internal.h"
2 +
3 +#include <stdlib.h>
4 +#include <string.h>
5 +
6 +#ifdef DEBUG_VERBOSE
7 +#include <stdio.h>
8 +#endif
9 +
10 +#define c_rmalloc(...) malloc(__VA_ARGS__)
11 +#define c_rcalloc(...) calloc(__VA_ARGS__)
12 +#define c_rfree(...) free(__VA_ARGS__)
13 +
14 +static inline uint32_t simple_hash(const char *name) {
15 + unsigned char *s = (unsigned char *) name;
16 + uint32_t hval = 0x811c9dc5;
17 + while (*s) {
18 + hval *= 16777619;
19 + hval ^= (uint32_t) *s++;
20 + }
21 + return hval;
22 +}
23 +
24 +c_rhash c_rhash_new(size_t bin_count) {
25 + if (!bin_count)
26 + bin_count = 1000;
27 +
28 + c_rhash hash = c_rcalloc(1, sizeof(struct c_rhash_s) + (bin_count * sizeof(struct bin_ll*)) );
29 + if (hash == NULL)
30 + return NULL;
31 +
32 + hash->bin_count = bin_count;
33 + hash->bins = (c_rhash_bin *)((char*)hash + sizeof(struct c_rhash_s));
34 +
35 + return hash;
36 +}
37 +
38 +static size_t get_itemtype_len(uint8_t item_type, const void* item_data) {
39 + switch (item_type) {
40 + case ITEMTYPE_STRING:
41 + return strlen(item_data) + 1;
42 + case ITEMTYPE_UINT64:
43 + return sizeof(uint64_t);
44 + case ITEMTYPE_UINT8:
45 + return 1;
46 + case ITEMTYPE_OPAQUE_PTR:
47 + return sizeof(void*);
48 + default:
49 + return 0;
50 + }
51 +}
52 +
53 +static int compare_bin_item(struct bin_item *item, uint8_t key_type, const void *key) {
54 + if (item->key_type != key_type)
55 + return 1;
56 +
57 + size_t key_value_len = get_itemtype_len(key_type, key);
58 +
59 + if(key_type == ITEMTYPE_STRING) {
60 + size_t new_key_value_len = get_itemtype_len(item->key_type, item->key);
61 + if (new_key_value_len != key_value_len)
62 + return 1;
63 + }
64 +
65 + if(memcmp(item->key, key, key_value_len) == 0) {
66 + return 0;
67 + }
68 +
69 + return 1;
70 +}
71 +
72 +static int insert_into_bin(c_rhash_bin *bin, uint8_t key_type, const void *key, uint8_t value_type, const void *value) {
73 + struct bin_item *prev = NULL;
74 + while (*bin != NULL) {
75 + if (!compare_bin_item(*bin, key_type, key)) {
76 +#ifdef DEBUG_VERBOSE
77 + printf("Key already present! Updating value!\n");
78 +#endif
79 +// TODO: optimize here if the new value is of different kind compared to the old one
80 +// in case it is not crazily bigger we can reuse the memory and avoid malloc and free
81 + c_rfree((*bin)->value);
82 + (*bin)->value_type = value_type;
83 + (*bin)->value = c_rmalloc(get_itemtype_len(value_type, value));
84 + if ((*bin)->value == NULL)
85 + return 1;
86 + memcpy((*bin)->value, value, get_itemtype_len(value_type, value));
87 + return 0;
88 + }
89 + prev = *bin;
90 + bin = &(*bin)->next;
91 + }
92 +
93 + if (*bin == NULL)
94 + *bin = c_rcalloc(1, sizeof(struct bin_item));
95 + if (prev != NULL)
96 + prev->next = *bin;
97 +
98 + (*bin)->key_type = key_type;
99 + size_t len = get_itemtype_len(key_type, key);
100 + (*bin)->key = c_rmalloc(len);
101 + memcpy((*bin)->key, key, len);
102 +
103 + (*bin)->value_type = value_type;
104 + len = get_itemtype_len(value_type, value);
105 + (*bin)->value = c_rmalloc(len);
106 + memcpy((*bin)->value, value, len);
107 + return 0;
108 +}
109 +
110 +static inline uint32_t get_bin_idx_str(c_rhash hash, const char *key) {
111 + uint32_t nhash = simple_hash(key);
112 + return nhash % hash->bin_count;
113 +}
114 +
115 +static inline c_rhash_bin *get_binptr_by_str(c_rhash hash, const char *key) {
116 + return &hash->bins[get_bin_idx_str(hash, key)];
117 +}
118 +
119 +int c_rhash_insert_str_ptr(c_rhash hash, const char *key, void *value) {
120 + c_rhash_bin *bin = get_binptr_by_str(hash, key);
121 +
122 +#ifdef DEBUG_VERBOSE
123 + if (bin != NULL)
124 + printf("COLLISION. There will be more than one item in bin idx=%d\n", nhash);
125 +#endif
126 +
127 + return insert_into_bin(bin, ITEMTYPE_STRING, key, ITEMTYPE_OPAQUE_PTR, &value);
128 +}
129 +
130 +int c_rhash_insert_str_uint8(c_rhash hash, const char *key, uint8_t value) {
131 + c_rhash_bin *bin = get_binptr_by_str(hash, key);
132 +
133 +#ifdef DEBUG_VERBOSE
134 + if (bin != NULL)
135 + printf("COLLISION. There will be more than one item in bin idx=%d\n", nhash);
136 +#endif
137 +
138 + return insert_into_bin(bin, ITEMTYPE_STRING, key, ITEMTYPE_UINT8, &value);
139 +}
140 +
141 +int c_rhash_insert_uint64_ptr(c_rhash hash, uint64_t key, void *value) {
142 + c_rhash_bin *bin = &hash->bins[key % hash->bin_count];
143 +
144 +#ifdef DEBUG_VERBOSE
145 + if (bin != NULL)
146 + printf("COLLISION. There will be more than one item in bin idx=%d\n", nhash);
147 +#endif
148 +
149 + return insert_into_bin(bin, ITEMTYPE_UINT64, &key, ITEMTYPE_OPAQUE_PTR, &value);
150 +}
151 +
152 +int c_rhash_get_uint8_by_str(c_rhash hash, const char *key, uint8_t *ret_val) {
153 + uint32_t nhash = get_bin_idx_str(hash, key);
154 +
155 + struct bin_item *bin = hash->bins[nhash];
156 +
157 + while (bin) {
158 + if (bin->key_type == ITEMTYPE_STRING) {
159 + if (!strcmp(bin->key, key)) {
160 + *ret_val = *(uint8_t*)bin->value;
161 + return 0;
162 + }
163 + }
164 + bin = bin->next;
165 + }
166 + return 1;
167 +}
168 +
169 +int c_rhash_get_ptr_by_str(c_rhash hash, const char *key, void **ret_val) {
170 + uint32_t nhash = get_bin_idx_str(hash, key);
171 +
172 + struct bin_item *bin = hash->bins[nhash];
173 +
174 + while (bin) {
175 + if (bin->key_type == ITEMTYPE_STRING) {
176 + if (!strcmp(bin->key, key)) {
177 + *ret_val = *((void**)bin->value);
178 + return 0;
179 + }
180 + }
181 + bin = bin->next;
182 + }
183 + *ret_val = NULL;
184 + return 1;
185 +}
186 +
187 +int c_rhash_get_ptr_by_uint64(c_rhash hash, uint64_t key, void **ret_val) {
188 + uint32_t nhash = key % hash->bin_count;
189 +
190 + struct bin_item *bin = hash->bins[nhash];
191 +
192 + while (bin) {
193 + if (bin->key_type == ITEMTYPE_UINT64) {
194 + if (*((uint64_t *)bin->key) == key) {
195 + *ret_val = *((void**)bin->value);
196 + return 0;
197 + }
198 + }
199 + bin = bin->next;
200 + }
201 + *ret_val = NULL;
202 + return 1;
203 +}
204 +
205 +static void c_rhash_destroy_bin(c_rhash_bin bin) {
206 + struct bin_item *next;
207 + do {
208 + next = bin->next;
209 + c_rfree(bin->key);
210 + c_rfree(bin->value);
211 + c_rfree(bin);
212 + bin = next;
213 + } while (bin != NULL);
214 +}
215 +
216 +int c_rhash_iter_uint64_keys(c_rhash hash, c_rhash_iter_t *iter, uint64_t *key) {
217 + while (iter->bin < hash->bin_count) {
218 + if (iter->item != NULL)
219 + iter->item = iter->item->next;
220 + if (iter->item == NULL) {
221 + if (iter->initialized)
222 + iter->bin++;
223 + else
224 + iter->initialized = 1;
225 + if (iter->bin < hash->bin_count)
226 + iter->item = hash->bins[iter->bin];
227 + }
228 + if (iter->item != NULL && iter->item->key_type == ITEMTYPE_UINT64) {
229 + *key = *(uint64_t*)iter->item->key;
230 + return 0;
231 + }
232 + }
233 + return 1;
234 +}
235 +
236 +int c_rhash_iter_str_keys(c_rhash hash, c_rhash_iter_t *iter, const char **key) {
237 + while (iter->bin < hash->bin_count) {
238 + if (iter->item != NULL)
239 + iter->item = iter->item->next;
240 + if (iter->item == NULL) {
241 + if (iter->initialized)
242 + iter->bin++;
243 + else
244 + iter->initialized = 1;
245 + if (iter->bin < hash->bin_count)
246 + iter->item = hash->bins[iter->bin];
247 + }
248 + if (iter->item != NULL && iter->item->key_type == ITEMTYPE_STRING) {
249 + *key = (const char*)iter->item->key;
250 + return 0;
251 + }
252 + }
253 + return 1;
254 +}
255 +
256 +void c_rhash_destroy(c_rhash hash) {
257 + for (size_t i = 0; i < hash->bin_count; i++) {
258 + if (hash->bins[i] != NULL)
259 + c_rhash_destroy_bin(hash->bins[i]);
260 + }
261 + c_rfree(hash);
262 +}
\ No newline at end of file
mqtt_websockets/c_rhash/src/c_rhash_internal.h new
+17
@@ -0,0 +1,17 @@
1 +#include "c_rhash.h"
2 +
3 +struct bin_item {
4 + uint8_t key_type:4;
5 + void *key;
6 + uint8_t value_type:4;
7 + void *value;
8 +
9 + struct bin_item *next;
10 +};
11 +
12 +typedef struct bin_item *c_rhash_bin;
13 +
14 +struct c_rhash_s {
15 + size_t bin_count;
16 + c_rhash_bin *bins;
17 +};
mqtt_websockets/c_rhash/src/tests.c new
+271
@@ -0,0 +1,271 @@
1 +#include <stdio.h>
2 +#include <string.h>
3 +
4 +#include "c_rhash.h"
5 +
6 +// terminal color codes
7 +#define KNRM "\x1B[0m"
8 +#define KRED "\x1B[31m"
9 +#define KGRN "\x1B[32m"
10 +#define KYEL "\x1B[33m"
11 +#define KBLU "\x1B[34m"
12 +#define KMAG "\x1B[35m"
13 +#define KCYN "\x1B[36m"
14 +#define KWHT "\x1B[37m"
15 +
16 +#define KEY_1 "key1"
17 +#define KEY_2 "keya"
18 +
19 +#define PRINT_ERR(str, ...) fprintf(stderr, "└─╼ ❌ " KRED str KNRM "\n" __VA_OPT__(,) __VA_ARGS__)
20 +
21 +#define ASSERT_RETVAL(fnc, comparator, expected_retval, ...) \
22 +{ int rval; \
23 +if(!((rval = fnc(__VA_ARGS__)) comparator expected_retval)) { \
24 + PRINT_ERR("Failed test. Value returned by \"%s\" in fnc:\"%s\",line:%d is not equal to expected value. Expected:%d, Got:%d", #fnc, __FUNCTION__, __LINE__, expected_retval, rval); \
25 + rc = 1; \
26 + goto test_cleanup; \
27 +} passed_subtest_count++;};
28 +
29 +#define ASSERT_VAL_UINT8(returned, expected) \
30 +if(returned != expected) { \
31 + PRINT_ERR("Failed test. Value returned (%d) doesn't match expected (%d)! fnc:\"%s\",line:%d", returned, expected, __FUNCTION__, __LINE__); \
32 + rc = 1; \
33 + goto test_cleanup; \
34 +} passed_subtest_count++;
35 +
36 +#define ASSERT_VAL_PTR(returned, expected) \
37 +if((void*)returned != (void*)expected) { \
38 + PRINT_ERR("Failed test. Value returned(%p) doesn't match expected(%p)! fnc:\"%s\",line:%d", (void*)returned, (void*)expected, __FUNCTION__, __LINE__); \
39 + rc = 1; \
40 + goto test_cleanup; \
41 +} passed_subtest_count++;
42 +
43 +#define ALL_SUBTESTS_PASS() printf("└─╼ ✅" KGRN " Test \"%s\" DONE. All of %zu subtests PASS. (line:%d)\n" KNRM, __FUNCTION__, passed_subtest_count, __LINE__);
44 +
45 +#define TEST_START() size_t passed_subtest_count = 0; int rc = 0; printf("╒═ Starting test \"%s\"\n", __FUNCTION__);
46 +
47 +int test_str_uint8() {
48 + c_rhash hash = c_rhash_new(100);
49 + uint8_t val;
50 +
51 + TEST_START();
52 + // function should fail on empty hash
53 + ASSERT_RETVAL(c_rhash_get_uint8_by_str, !=, 0, hash, KEY_1, &val);
54 +
55 + ASSERT_RETVAL(c_rhash_insert_str_uint8, ==, 0, hash, KEY_1, 5);
56 + ASSERT_RETVAL(c_rhash_get_uint8_by_str, ==, 0, hash, KEY_1, &val);
57 + ASSERT_VAL_UINT8(5, val);
58 +
59 + ASSERT_RETVAL(c_rhash_insert_str_uint8, ==, 0, hash, KEY_2, 8);
60 + ASSERT_RETVAL(c_rhash_get_uint8_by_str, ==, 0, hash, KEY_1, &val);
61 + ASSERT_VAL_UINT8(5, val);
62 + ASSERT_RETVAL(c_rhash_get_uint8_by_str, ==, 0, hash, KEY_2, &val);
63 + ASSERT_VAL_UINT8(8, val);
64 + ASSERT_RETVAL(c_rhash_get_uint8_by_str, !=, 0, hash, "sndnskjdf", &val);
65 +
66 + // test update of key
67 + ASSERT_RETVAL(c_rhash_insert_str_uint8, ==, 0, hash, KEY_1, 100);
68 + ASSERT_RETVAL(c_rhash_get_uint8_by_str, ==, 0, hash, KEY_1, &val);
69 + ASSERT_VAL_UINT8(100, val);
70 +
71 + ALL_SUBTESTS_PASS();
72 +test_cleanup:
73 + c_rhash_destroy(hash);
74 + return rc;
75 +}
76 +
77 +int test_uint64_ptr() {
78 + c_rhash hash = c_rhash_new(100);
79 + void *val;
80 +
81 + TEST_START();
82 +
83 + // function should fail on empty hash
84 + ASSERT_RETVAL(c_rhash_get_ptr_by_uint64, !=, 0, hash, 0, &val);
85 +
86 + ASSERT_RETVAL(c_rhash_insert_uint64_ptr, ==, 0, hash, 0, &hash);
87 + ASSERT_RETVAL(c_rhash_get_ptr_by_uint64, ==, 0, hash, 0, &val);
88 + ASSERT_VAL_PTR(&hash, val);
89 +
90 + ASSERT_RETVAL(c_rhash_insert_uint64_ptr, ==, 0, hash, 1, &val);
91 + ASSERT_RETVAL(c_rhash_get_ptr_by_uint64, ==, 0, hash, 0, &val);
92 + ASSERT_VAL_PTR(&hash, val);
93 + ASSERT_RETVAL(c_rhash_get_ptr_by_uint64, ==, 0, hash, 1, &val);
94 + ASSERT_VAL_PTR(&val, val);
95 + ASSERT_RETVAL(c_rhash_get_ptr_by_uint64, !=, 0, hash, 2, &val);
96 +
97 + ALL_SUBTESTS_PASS();
98 +test_cleanup:
99 + c_rhash_destroy(hash);
100 + return rc;
101 +}
102 +
103 +#define UINT64_PTR_INC_ITERATION_COUNT 5000
104 +int test_uint64_ptr_incremental() {
105 + c_rhash hash = c_rhash_new(100);
106 + void *val;
107 +
108 + TEST_START();
109 +
110 + char a = 0x20;
111 + char *ptr = &a;
112 + while(ptr < &a + UINT64_PTR_INC_ITERATION_COUNT) {
113 + ASSERT_RETVAL(c_rhash_insert_uint64_ptr, ==, 0, hash, (ptr-&a), ptr);
114 + ptr++;
115 + }
116 +
117 + ptr = &a;
118 + char *retptr;
119 + for(int i = 0; i < UINT64_PTR_INC_ITERATION_COUNT; i++) {
120 + ASSERT_RETVAL(c_rhash_get_ptr_by_uint64, ==, 0, hash, i, (void**)&retptr);
121 + ASSERT_VAL_PTR(retptr, (&a+i));
122 + }
123 +
124 + ALL_SUBTESTS_PASS();
125 +test_cleanup:
126 + c_rhash_destroy(hash);
127 + return rc;
128 +}
129 +
130 +struct test_string {
131 + const char *str;
132 + int counter;
133 +};
134 +
135 +struct test_string test_strings[] = {
136 + { .str = "Cillum reprehenderit eiusmod elit nisi aliquip esse exercitation commodo Lorem voluptate esse.", .counter = 0 },
137 + { .str = "Ullamco eiusmod tempor occaecat ad.", .counter = 0 },
138 + { .str = "Esse aliquip tempor sint tempor ullamco duis aute incididunt ad.", .counter = 0 },
139 + { .str = "Cillum Lorem labore cupidatat commodo proident adipisicing.", .counter = 0 },
140 + { .str = "Quis ad cillum officia exercitation.", .counter = 0 },
141 + { .str = "Ipsum enim dolor ullamco amet sint nisi ut occaecat sint non.", .counter = 0 },
142 + { .str = "Id duis officia ipsum cupidatat velit fugiat.", .counter = 0 },
143 + { .str = "Aliqua non occaecat voluptate reprehenderit reprehenderit veniam minim exercitation ea aliquip enim aliqua deserunt qui.", .counter = 0 },
144 + { .str = "Ullamco elit tempor laboris reprehenderit quis deserunt duis quis tempor reprehenderit magna dolore reprehenderit exercitation.", .counter = 0 },
145 + { .str = "Culpa do dolor quis incididunt et labore in ex.", .counter = 0 },
146 + { .str = "Aliquip velit cupidatat qui incididunt ipsum nostrud eiusmod ut proident nisi magna fugiat excepteur.", .counter = 0 },
147 + { .str = "Aliqua qui dolore tempor id proident ullamco sunt magna.", .counter = 0 },
148 + { .str = "Labore eiusmod ut fugiat dolore reprehenderit mollit magna.", .counter = 0 },
149 + { .str = "Veniam aliquip dolor excepteur minim nulla esse cupidatat esse.", .counter = 0 },
150 + { .str = "Do quis dolor irure nostrud occaecat aute proident anim.", .counter = 0 },
151 + { .str = "Enim veniam non nulla ad quis sit amet.", .counter = 0 },
152 + { .str = "Cillum reprehenderit do enim esse do ullamco consectetur ea.", .counter = 0 },
153 + { .str = "Sit et duis sint anim qui ad anim labore exercitation sunt cupidatat.", .counter = 0 },
154 + { .str = "Dolor officia adipisicing sint pariatur in dolor occaecat officia reprehenderit magna.", .counter = 0 },
155 + { .str = "Aliquip dolore qui occaecat eiusmod sunt incididunt reprehenderit minim et.", .counter = 0 },
156 + { .str = "Aute fugiat laboris cillum tempor consequat tempor do non laboris culpa officia nisi.", .counter = 0 },
157 + { .str = "Et excepteur do aliquip fugiat nisi velit tempor officia enim quis elit incididunt.", .counter = 0 },
158 + { .str = "Eu officia adipisicing incididunt occaecat officia cupidatat enim sit sit officia.", .counter = 0 },
159 + { .str = "Do amet cillum duis pariatur commodo nulla cillum magna nulla Lorem veniam cupidatat.", .counter = 0 },
160 + { .str = "Dolor adipisicing voluptate laboris occaecat culpa aliquip ipsum ut consequat aliqua aliquip commodo sunt velit.", .counter = 0 },
161 + { .str = "Nulla proident ipsum quis nulla.", .counter = 0 },
162 + { .str = "Laborum adipisicing nulla do aute aliqua est quis sint culpa pariatur laborum voluptate qui.", .counter = 0 },
163 + { .str = "Proident eiusmod sunt et nulla elit pariatur dolore irure ex voluptate excepteur adipisicing consectetur.", .counter = 0 },
164 + { .str = "Consequat ex voluptate officia excepteur aute deserunt proident commodo et.", .counter = 0 },
165 + { .str = "Velit sit cupidatat dolor dolore.", .counter = 0 },
166 + { .str = "Sunt enim do non anim nostrud exercitation ullamco ex proident commodo.", .counter = 0 },
167 + { .str = "Id ex officia cillum ad.", .counter = 0 },
168 + { .str = "Laboris in sunt eiusmod veniam laboris nostrud.", .counter = 0 },
169 + { .str = "Ex magna occaecat ea ea incididunt aliquip.", .counter = 0 },
170 + { .str = "Sunt eiusmod ex nostrud eu pariatur sit cupidatat ea adipisicing cillum culpa esse consequat aliquip.", .counter = 0 },
171 + { .str = "Excepteur commodo qui incididunt enim culpa sunt non excepteur Lorem adipisicing.", .counter = 0 },
172 + { .str = "Quis officia est ullamco reprehenderit incididunt occaecat pariatur ex reprehenderit nisi.", .counter = 0 },
173 + { .str = "Culpa irure proident proident et eiusmod irure aliqua ipsum cupidatat minim sit.", .counter = 0 },
174 + { .str = "Qui cupidatat aliquip est velit magna veniam.", .counter = 0 },
175 + { .str = "Pariatur ad ad mollit nostrud non irure minim veniam anim aliquip quis eu.", .counter = 0 },
176 + { .str = "Nisi ex minim eu adipisicing tempor Lorem nisi do ad exercitation est non eu.", .counter = 0 },
177 + { .str = "Cupidatat do mollit ad commodo cupidatat ut.", .counter = 0 },
178 + { .str = "Est non excepteur eiusmod nostrud et eu.", .counter = 0 },
179 + { .str = "Cupidatat mollit nisi magna officia ut elit eiusmod.", .counter = 0 },
180 + { .str = "Est aliqua consectetur laboris ex consequat est ut dolor.", .counter = 0 },
181 + { .str = "Duis eu laboris laborum ut id Lorem nostrud qui ad velit proident fugiat minim ullamco.", .counter = 0 },
182 + { .str = "Pariatur esse excepteur anim amet excepteur irure sint quis esse ex cupidatat ut.", .counter = 0 },
183 + { .str = "Esse reprehenderit amet qui excepteur aliquip amet.", .counter = 0 },
184 + { .str = "Ullamco laboris elit labore adipisicing aute nulla qui laborum tempor officia ut dolor aute.", .counter = 0 },
185 + { .str = "Commodo sunt cillum velit minim laborum Lorem aliqua tempor ad id eu.", .counter = 0 },
186 + { .str = NULL, .counter = 0 }
187 +};
188 +
189 +uint32_t test_strings_contain_element(const char *str) {
190 + struct test_string *str_desc = test_strings;
191 + while(str_desc->str) {
192 + if (!strcmp(str, str_desc->str))
193 + return str_desc - test_strings;
194 + str_desc++;
195 + }
196 + return -1;
197 +}
198 +
199 +#define TEST_INCREMENT_STR_KEYS_HASH_SIZE 20
200 +int test_increment_str_keys() {
201 + c_rhash hash;
202 + const char *key;
203 +
204 + TEST_START();
205 +
206 + hash = c_rhash_new(TEST_INCREMENT_STR_KEYS_HASH_SIZE); // less than element count of test_strings
207 +
208 + c_rhash_iter_t iter = C_RHASH_ITER_T_INITIALIZER;
209 +
210 + // check iter on empty hash
211 + ASSERT_RETVAL(c_rhash_iter_str_keys, !=, 0, hash, &iter, &key);
212 +
213 + int32_t element_count = 0;
214 + while (test_strings[element_count].str) {
215 + ASSERT_RETVAL(c_rhash_insert_str_ptr, ==, 0, hash, test_strings[element_count].str, NULL);
216 + test_strings[element_count].counter++; // we want to test we got each key exactly once
217 + element_count++;
218 + }
219 +
220 + if (element_count <= TEST_INCREMENT_STR_KEYS_HASH_SIZE * 2) {
221 + // verify we are actually test also iteration trough single bin (when 2 keys have same hash pointing them to same bin)
222 + PRINT_ERR("For this test to properly test all the hash size needs to be much smaller than all test key count.");
223 + rc = 1;
224 + goto test_cleanup;
225 + }
226 +
227 + // we insert another type of key as iterator should skip it
228 + // in case is another type
229 + ASSERT_RETVAL(c_rhash_insert_uint64_ptr, ==, 0, hash, 5, NULL);
230 +
231 + c_rhash_iter_t_initialize(&iter);
232 + while(!c_rhash_iter_str_keys(hash, &iter, &key)) {
233 + element_count--;
234 + int i;
235 + if ( (i = test_strings_contain_element(key)) < 0) {
236 + PRINT_ERR("Key \"%s\" is not present in test_strings array! (Fnc: %s, Line: %d)", key, __FUNCTION__, __LINE__);
237 + rc = 1;
238 + goto test_cleanup;
239 + }
240 + passed_subtest_count++;
241 +
242 + test_strings[i].counter--;
243 + }
244 + ASSERT_VAL_UINT8(element_count, 0); // we added also same non string keys
245 +
246 + // check each key was present exactly once
247 + struct test_string *str_desc = test_strings;
248 + while (str_desc->str) {
249 + ASSERT_VAL_UINT8(str_desc->counter, 0);
250 + str_desc++;
251 + }
252 +
253 + ALL_SUBTESTS_PASS();
254 +test_cleanup:
255 + c_rhash_destroy(hash);
256 + return rc;
257 +}
258 +
259 +#define RUN_TEST(fnc) \
260 +if(fnc()) \
261 + return 1;
262 +
263 +int main(int argc, char *argv[]) {
264 + RUN_TEST(test_str_uint8);
265 + RUN_TEST(test_uint64_ptr);
266 + RUN_TEST(test_uint64_ptr_incremental);
267 + RUN_TEST(test_increment_str_keys);
268 + // TODO hash with mixed key tests
269 + // TODO iterator test
270 + return 0;
271 +}
mqtt_websockets/src/common_public.c new
+7
@@ -0,0 +1,7 @@
1 +#include "common_public.h"
2 +
3 +// this dummy exists to have a special pointer with special meaning
4 +// other than NULL
5 +void _caller_responsibility(void *ptr) {
6 + (void)(ptr);
7 +}
mqtt_websockets/src/include/common_internal.h new
+37
@@ -0,0 +1,37 @@
1 +// SPDX-License-Identifier: GPL-3.0-only
2 +//
3 +// This program is free software: you can redistribute it and/or modify it
4 +// under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
5 +//
6 +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8 +// See the GNU General Public License for more details.
9 +//
10 +// You should have received a copy of the GNU General Public License along with this program.
11 +// If not, see <https://www.gnu.org/licenses/>.
12 +
13 +#ifndef COMMON_INTERNAL_H
14 +#define COMMON_INTERNAL_H
15 +
16 +#include "endian_compat.h"
17 +
18 +#ifdef MQTT_WSS_CUSTOM_ALLOC
19 +#include "mqtt_wss_pal.h"
20 +#else
21 +#define mw_malloc(...) malloc(__VA_ARGS__)
22 +#define mw_calloc(...) calloc(__VA_ARGS__)
23 +#define mw_free(...) free(__VA_ARGS__)
24 +#define mw_strdup(...) strdup(__VA_ARGS__)
25 +#define mw_realloc(...) realloc(__VA_ARGS__)
26 +#endif
27 +
28 +#ifndef MQTT_WSS_FRAG_MEMALIGN
29 +#define MQTT_WSS_FRAG_MEMALIGN (8)
30 +#endif
31 +
32 +#define OPENSSL_VERSION_095 0x00905100L
33 +#define OPENSSL_VERSION_097 0x00907000L
34 +#define OPENSSL_VERSION_110 0x10100000L
35 +#define OPENSSL_VERSION_111 0x10101000L
36 +
37 +#endif /* COMMON_INTERNAL_H */
mqtt_websockets/src/include/common_public.h new
+33
@@ -0,0 +1,33 @@
1 +#ifndef MQTT_WEBSOCKETS_COMMON_PUBLIC_H
2 +#define MQTT_WEBSOCKETS_COMMON_PUBLIC_H
3 +
4 +#include <stddef.h>
5 +
6 +/* free_fnc_t in general (in whatever function or struct it is used)
7 + * decides how the related data will be handled.
8 + * - If NULL the data are copied internally (causing malloc and later free)
9 + * - If pointer provided the free function pointed will be called when data are no longer needed
10 + * to free associated memory. This is effectively transfering ownership of that pointer to the library.
11 + * This also allows caller to provide custom free function other than system one.
12 + * - If == CALLER_RESPONSIBILITY the library will not copy the data pointed to and will not call free
13 + * at the end. This is usefull to avoid copying memory (and associated malloc/free) when data are for
14 + * example static. In this case caller has to guarantee the memory pointed to will be valid for entire duration
15 + * it is needed. For example by freeing the data after PUBACK is received or by data being static.
16 + */
17 +typedef void (*free_fnc_t)(void *ptr);
18 +void _caller_responsibility(void *ptr);
19 +#define CALLER_RESPONSIBILITY ((free_fnc_t)&_caller_responsibility)
20 +
21 +struct mqtt_ng_stats {
22 + size_t tx_bytes_queued;
23 + int tx_messages_queued;
24 + int tx_messages_sent;
25 + int rx_messages_rcvd;
26 + size_t tx_buffer_used;
27 + size_t tx_buffer_free;
28 + size_t tx_buffer_size;
29 + // part of transaction buffer that containes mesages we can free alredy during the garbage colleciton step
30 + size_t tx_buffer_reclaimable;
31 +};
32 +
33 +#endif /* MQTT_WEBSOCKETS_COMMON_PUBLIC_H */
mqtt_websockets/src/include/endian_compat.h new
+41
@@ -0,0 +1,41 @@
1 +// SPDX-License-Identifier: GPL-3.0-only
2 +//
3 +// This program is free software: you can redistribute it and/or modify it
4 +// under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
5 +//
6 +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8 +// See the GNU General Public License for more details.
9 +//
10 +// You should have received a copy of the GNU General Public License along with this program.
11 +// If not, see <https://www.gnu.org/licenses/>.
12 +
13 +#ifndef MQTT_WSS_ENDIAN_COMPAT_H
14 +#define MQTT_WSS_ENDIAN_COMPAT_H
15 +
16 +#ifdef __APPLE__
17 + #include <libkern/OSByteOrder.h>
18 +
19 + #define htobe16(x) OSSwapHostToBigInt16(x)
20 + #define htole16(x) OSSwapHostToLittleInt16(x)
21 + #define be16toh(x) OSSwapBigToHostInt16(x)
22 + #define le16toh(x) OSSwapLittleToHostInt16(x)
23 +
24 + #define htobe32(x) OSSwapHostToBigInt32(x)
25 + #define htole32(x) OSSwapHostToLittleInt32(x)
26 + #define be32toh(x) OSSwapBigToHostInt32(x)
27 + #define le32toh(x) OSSwapLittleToHostInt32(x)
28 +
29 + #define htobe64(x) OSSwapHostToBigInt64(x)
30 + #define htole64(x) OSSwapHostToLittleInt64(x)
31 + #define be64toh(x) OSSwapBigToHostInt64(x)
32 + #define le64toh(x) OSSwapLittleToHostInt64(x)
33 +#else
34 +#ifdef __FreeBSD__
35 + #include <sys/endian.h>
36 +#else
37 + #include <endian.h>
38 +#endif
39 +#endif
40 +
41 +#endif /* MQTT_WSS_ENDIAN_COMPAT_H */
mqtt_websockets/src/include/mqtt_constants.h new
+101
@@ -0,0 +1,101 @@
1 +#ifndef MQTT_CONSTANTS_H
2 +#define MQTT_CONSTANTS_H
3 +
4 +#define MQTT_MAX_QOS 0x02
5 +
6 +#define MQTT_VERSION_5_0 0x5
7 +
8 +/* [MQTT-1.5.5] most significant bit
9 + of MQTT Variable Byte Integer signifies
10 + there are more bytes following */
11 +#define MQTT_VBI_CONTINUATION_FLAG 0x80
12 +#define MQTT_VBI_DATA_MASK 0x7F
13 +#define MQTT_VBI_MAXBYTES 4
14 +
15 +/* MQTT control packet types as defined in
16 + 2.1.2 MQTT Control Packet type */
17 +#define MQTT_CPT_CONNECT 0x1
18 +#define MQTT_CPT_CONNACK 0x2
19 +#define MQTT_CPT_PUBLISH 0x3
20 +#define MQTT_CPT_PUBACK 0x4
21 +#define MQTT_CPT_PUBREC 0x5
22 +#define MQTT_CPT_PUBREL 0x6
23 +#define MQTT_CPT_PUBCOMP 0x7
24 +#define MQTT_CPT_SUBSCRIBE 0x8
25 +#define MQTT_CPT_SUBACK 0x9
26 +#define MQTT_CPT_UNSUBSCRIBE 0xA
27 +#define MQTT_CPT_UNSUBACK 0xB
28 +#define MQTT_CPT_PINGREQ 0xC
29 +#define MQTT_CPT_PINGRESP 0xD
30 +#define MQTT_CPT_DISCONNECT 0xE
31 +#define MQTT_CPT_AUTH 0xF
32 +
33 +// MQTT CONNECT FLAGS (spec:3.1.2.3)
34 +#define MQTT_CONNECT_FLAG_USERNAME 0x80
35 +#define MQTT_CONNECT_FLAG_PASSWORD 0x40
36 +#define MQTT_CONNECT_FLAG_LWT_RETAIN 0x20
37 +#define MQTT_CONNECT_FLAG_LWT 0x04
38 +#define MQTT_CONNECT_FLAG_CLEAN_START 0x02
39 +
40 +#define MQTT_CONNECT_FLAG_QOS_MASK 0x18
41 +#define MQTT_CONNECT_FLAG_QOS_BITSHIFT 3
42 +
43 +#define MQTT_MAX_CLIENT_ID 23 /* [MQTT-3.1.3-5] */
44 +
45 +// MQTT Property identifiers [MQTT-2.2.2.2]
46 +#define MQTT_PROP_PAYLOAD_FMT_INDICATOR 0x01
47 +#define MQTT_PROP_PAYLOAD_FMT_INDICATOR_NAME "Payload Format Indicator"
48 +#define MQTT_PROP_MSG_EXPIRY_INTERVAL 0x02
49 +#define MQTT_PROP_MSG_EXPIRY_INTERVAL_NAME "Message Expiry Interval"
50 +#define MQTT_PROP_CONTENT_TYPE 0x03
51 +#define MQTT_PROP_CONTENT_TYPE_NAME "Content Type"
52 +#define MQTT_PROP_RESPONSE_TOPIC 0x08
53 +#define MQTT_PROP_RESPONSE_TOPIC_NAME "Response Topic"
54 +#define MQTT_PROP_CORRELATION_DATA 0x09
55 +#define MQTT_PROP_CORRELATION_DATA_NAME "Correlation Data"
56 +#define MQTT_PROP_SUB_IDENTIFIER 0x0B
57 +#define MQTT_PROP_SUB_IDENTIFIER_NAME "Subscription Identifier"
58 +#define MQTT_PROP_SESSION_EXPIRY_INTERVAL 0x11
59 +#define MQTT_PROP_SESSION_EXPIRY_INTERVAL_NAME "Session Expiry Interval"
60 +#define MQTT_PROP_ASSIGNED_CLIENT_ID 0x12
61 +#define MQTT_PROP_ASSIGNED_CLIENT_ID_NAME "Assigned Client Identifier"
62 +#define MQTT_PROP_SERVER_KEEP_ALIVE 0x13
63 +#define MQTT_PROP_SERVER_KEEP_ALIVE_NAME "Server Keep Alive"
64 +#define MQTT_PROP_AUTH_METHOD 0x15
65 +#define MQTT_PROP_AUTH_METHOD_NAME "Authentication Method"
66 +#define MQTT_PROP_AUTH_DATA 0x16
67 +#define MQTT_PROP_AUTH_DATA_NAME "Authentication Data"
68 +#define MQTT_PROP_REQ_PROBLEM_INFO 0x17
69 +#define MQTT_PROP_REQ_PROBLEM_INFO_NAME "Request Problem Information"
70 +#define MQTT_PROP_WILL_DELAY_INTERVAL 0x18
71 +#define MQTT_PROP_WIIL_DELAY_INTERVAL_NAME "Will Delay Interval"
72 +#define MQTT_PROP_REQ_RESP_INFORMATION 0x19
73 +#define MQTT_PROP_REQ_RESP_INFORMATION_NAME "Request Response Information"
74 +#define MQTT_PROP_RESP_INFORMATION 0x1A
75 +#define MQTT_PROP_RESP_INFORMATION_NAME "Response Information"
76 +#define MQTT_PROP_SERVER_REF 0x1C
77 +#define MQTT_PROP_SERVER_REF_NAME "Server Reference"
78 +#define MQTT_PROP_REASON_STR 0x1F
79 +#define MQTT_PROP_REASON_STR_NAME "Reason String"
80 +#define MQTT_PROP_RECEIVE_MAX 0x21
81 +#define MQTT_PROP_RECEIVE_MAX_NAME "Receive Maximum"
82 +#define MQTT_PROP_TOPIC_ALIAS_MAX 0x22
83 +#define MQTT_PROP_TOPIC_ALIAS_MAX_NAME "Topic Alias Maximum"
84 +#define MQTT_PROP_TOPIC_ALIAS 0x23
85 +#define MQTT_PROP_TOPIC_ALIAS_NAME "Topic Alias"
86 +#define MQTT_PROP_MAX_QOS 0x24
87 +#define MQTT_PROP_MAX_QOS_NAME "Maximum QoS"
88 +#define MQTT_PROP_RETAIN_AVAIL 0x25
89 +#define MQTT_PROP_RETAIN_AVAIL_NAME "Retain Available"
90 +#define MQTT_PROP_USR 0x26
91 +#define MQTT_PROP_USR_NAME "User Property"
92 +#define MQTT_PROP_MAX_PKT_SIZE 0x27
93 +#define MQTT_PROP_MAX_PKT_SIZE_NAME "Maximum Packet Size"
94 +#define MQTT_PROP_WILDCARD_SUB_AVAIL 0x28
95 +#define MQTT_PROP_WILDCARD_SUB_AVAIL_NAME "Wildcard Subscription Available"
96 +#define MQTT_PROP_SUB_ID_AVAIL 0x29
97 +#define MQTT_PROP_SUB_ID_AVAIL_NAME "Subscription Identifier Available"
98 +#define MQTT_PROP_SHARED_SUB_AVAIL 0x2A
99 +#define MQTT_PROP_SHARED_SUB_AVAIL_NAME "Shared Subscription Available"
100 +
101 +#endif /* MQTT_CONSTANTS_H */
mqtt_websockets/src/include/mqtt_ng.h new
+97
@@ -0,0 +1,97 @@
1 +#include <stdint.h>
2 +#include <sys/types.h>
3 +#include <time.h>
4 +
5 +#include "ringbuffer.h"
6 +#include "common_public.h"
7 +
8 +#define MQTT_NG_MSGGEN_OK 0
9 +// MQTT_NG_MSGGEN_USER_ERROR means parameters given to this function
10 +// do not make sense or are out of MQTT specs
11 +#define MQTT_NG_MSGGEN_USER_ERROR 1
12 +#define MQTT_NG_MSGGEN_BUFFER_OOM 2
13 +#define MQTT_NG_MSGGEN_MSG_TOO_BIG 3
14 +
15 +struct mqtt_ng_client;
16 +
17 +/* Converts integer to MQTT Variable Byte Integer as per 1.5.5 of MQTT 5 specs
18 + * @param input value to be converted
19 + * @param output pointer to memory where output will be written to. Must allow up to 4 bytes to be written.
20 + * @return number of bytes written to output or <= 0 if error in which case contents of output are undefined
21 + */
22 +int uint32_to_mqtt_vbi(uint32_t input, char *output);
23 +
24 +struct mqtt_lwt_properties {
25 + char *will_topic;
26 + free_fnc_t will_topic_free;
27 +
28 + void *will_message;
29 + free_fnc_t will_message_free;
30 + size_t will_message_size;
31 +
32 + int will_qos;
33 + int will_retain;
34 +};
35 +
36 +struct mqtt_auth_properties {
37 + char *client_id;
38 + free_fnc_t client_id_free;
39 + char *username;
40 + free_fnc_t username_free;
41 + char *password;
42 + free_fnc_t password_free;
43 +};
44 +
45 +int mqtt_ng_connect(struct mqtt_ng_client *client,
46 + struct mqtt_auth_properties *auth,
47 + struct mqtt_lwt_properties *lwt,
48 + uint8_t clean_start,
49 + uint16_t keep_alive);
50 +
51 +int mqtt_ng_publish(struct mqtt_ng_client *client,
52 + char *topic,
53 + free_fnc_t topic_free,
54 + void *msg,
55 + free_fnc_t msg_free,
56 + size_t msg_len,
57 + uint8_t publish_flags,
58 + uint16_t *packet_id);
59 +
60 +struct mqtt_sub {
61 + char *topic;
62 + free_fnc_t topic_free;
63 + uint8_t options;
64 +};
65 +
66 +int mqtt_ng_subscribe(struct mqtt_ng_client *client, struct mqtt_sub *subscriptions, size_t subscription_count);
67 +
68 +int mqtt_ng_ping(struct mqtt_ng_client *client);
69 +
70 +typedef ssize_t (*mqtt_ng_send_fnc_t)(void *user_ctx, const void* buf, size_t len);
71 +
72 +struct mqtt_ng_init {
73 + mqtt_wss_log_ctx_t log;
74 + rbuf_t data_in;
75 + mqtt_ng_send_fnc_t data_out_fnc;
76 + void *user_ctx;
77 +
78 + void (*puback_callback)(uint16_t packet_id);
79 + void (*connack_callback)(void* user_ctx, int connack_reply);
80 + void (*msg_callback)(const char *topic, const void *msg, size_t msglen, int qos);
81 +};
82 +
83 +struct mqtt_ng_client *mqtt_ng_init(struct mqtt_ng_init *settings);
84 +
85 +void mqtt_ng_destroy(struct mqtt_ng_client *client);
86 +
87 +int mqtt_ng_disconnect(struct mqtt_ng_client *client, uint8_t reason_code);
88 +
89 +int mqtt_ng_sync(struct mqtt_ng_client *client);
90 +
91 +time_t mqtt_ng_last_send_time(struct mqtt_ng_client *client);
92 +
93 +void mqtt_ng_set_max_mem(struct mqtt_ng_client *client, size_t bytes);
94 +
95 +void mqtt_ng_get_stats(struct mqtt_ng_client *client, struct mqtt_ng_stats *stats);
96 +
97 +int mqtt_ng_set_topic_alias(struct mqtt_ng_client *client, const char *topic);
mqtt_websockets/src/include/mqtt_wss_client.h new
+172
@@ -0,0 +1,172 @@
1 +// Copyright (C) 2020 Timotej Šiškovič
2 +// SPDX-License-Identifier: GPL-3.0-only
3 +//
4 +// This program is free software: you can redistribute it and/or modify it
5 +// under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
6 +//
7 +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9 +// See the GNU General Public License for more details.
10 +//
11 +// You should have received a copy of the GNU General Public License along with this program.
12 +// If not, see <https://www.gnu.org/licenses/>.
13 +
14 +#ifndef MQTT_WSS_CLIENT_H
15 +#define MQTT_WSS_CLIENT_H
16 +
17 +#include <stdint.h>
18 +#include <stddef.h> //size_t
19 +
20 +#include "mqtt_wss_log.h"
21 +#include "common_public.h"
22 +
23 +// All OK call me at your earliest convinience
24 +#define MQTT_WSS_OK 0
25 +/* All OK, poll timeout you requested when calling mqtt_wss_service expired - you might want to know if timeout
26 + * happened or we got some data or handle same as MQTT_WSS_OK
27 + */
28 +#define MQTT_WSS_OK_TO 1
29 +// Connection was closed by remote
30 +#define MQTT_WSS_ERR_CONN_DROP -1
31 +// Error in MQTT protocol (e.g. malformed packet)
32 +#define MQTT_WSS_ERR_PROTO_MQTT -2
33 +// Error in WebSocket protocol (e.g. malformed packet)
34 +#define MQTT_WSS_ERR_PROTO_WS -3
35 +
36 +#define MQTT_WSS_ERR_TX_BUF_TOO_SMALL -4
37 +#define MQTT_WSS_ERR_RX_BUF_TOO_SMALL -5
38 +
39 +#define MQTT_WSS_ERR_TOO_BIG_FOR_SERVER -6
40 +// if client was initialized with MQTT 3 but MQTT 5 feature
41 +// was requested by user of library
42 +#define MQTT_WSS_ERR_CANT_DO -8
43 +
44 +typedef struct mqtt_wss_client_struct *mqtt_wss_client;
45 +
46 +typedef void (*msg_callback_fnc_t)(const char *topic, const void *msg, size_t msglen, int qos);
47 +/* Creates new instance of MQTT over WSS. Doesn't start connection.
48 + * @param log_prefix this is prefix to be used when logging to discern between multiple
49 + * mqtt_wss instances. Can be NULL.
50 + * @param log_callback is function pointer to fnc to be called when mqtt_wss wants
51 + * to log. This allows plugging this library into your own logging system/solution.
52 + * If NULL STDOUT/STDERR will be used.
53 + * @param msg_callback is function pointer to function which will be called
54 + * when application level message arrives from broker (for subscribed topics).
55 + * Can be NULL if you are not interested about incoming messages.
56 + * @param puback_callback is function pointer to function to be called when QOS1 Publish
57 + * is acknowledged by server
58 + */
59 +mqtt_wss_client mqtt_wss_new(const char *log_prefix,
60 + mqtt_wss_log_callback_t log_callback,
61 + msg_callback_fnc_t msg_callback,
62 + void (*puback_callback)(uint16_t packet_id));
63 +
64 +void mqtt_wss_set_max_buf_size(mqtt_wss_client client, size_t size);
65 +
66 +void mqtt_wss_destroy(mqtt_wss_client client);
67 +
68 +struct mqtt_connect_params;
69 +struct mqtt_wss_proxy;
70 +
71 +#define MQTT_WSS_SSL_CERT_CHECK_FULL 0x00
72 +#define MQTT_WSS_SSL_ALLOW_SELF_SIGNED 0x01
73 +#define MQTT_WSS_SSL_DONT_CHECK_CERTS 0x08
74 +
75 +/* Will block until the MQTT over WSS connection is established or return error
76 + * @param client mqtt_wss_client which should connect
77 + * @param host to connect to (where MQTT over WSS server is listening)
78 + * @param port to connect to (where MQTT over WSS server is listening)
79 + * @param mqtt_params pointer to mqtt_connect_params structure which contains MQTT credentials and settings
80 + * @param ssl_flags parameters for OpenSSL, 0=MQTT_WSS_SSL_CERT_CHECK_FULL
81 + */
82 +int mqtt_wss_connect(mqtt_wss_client client, char *host, int port, struct mqtt_connect_params *mqtt_params, int ssl_flags, struct mqtt_wss_proxy *proxy);
83 +int mqtt_wss_service(mqtt_wss_client client, int timeout_ms);
84 +void mqtt_wss_disconnect(mqtt_wss_client client, int timeout_ms);
85 +
86 +// we redefine this instead of using MQTT-C flags as in future
87 +// we want to support different MQTT implementations if needed
88 +enum mqtt_wss_publish_flags {
89 + MQTT_WSS_PUB_QOS0 = 0x0,
90 + MQTT_WSS_PUB_QOS1 = 0x1,
91 + MQTT_WSS_PUB_QOS2 = 0x2,
92 + MQTT_WSS_PUB_QOSMASK = 0x3,
93 + MQTT_WSS_PUB_RETAIN = 0x4
94 +};
95 +
96 +struct mqtt_connect_params {
97 + const char *clientid;
98 + const char *username;
99 + const char *password;
100 + const char *will_topic;
101 + const void *will_msg;
102 + enum mqtt_wss_publish_flags will_flags;
103 + size_t will_msg_len;
104 + int keep_alive;
105 + int drop_on_publish_fail;
106 +};
107 +
108 +enum mqtt_wss_proxy_type {
109 + MQTT_WSS_DIRECT = 0,
110 + MQTT_WSS_PROXY_HTTP
111 +};
112 +
113 +struct mqtt_wss_proxy {
114 + enum mqtt_wss_proxy_type type;
115 + const char *host;
116 + int port;
117 + const char *username;
118 + const char *password;
119 +};
120 +
121 +/* TODO!!! update the description
122 + * Publishes MQTT message and gets message id
123 + * @param client mqtt_wss_client which should transfer the message
124 + * @param topic MQTT topic to publish message to (0 terminated C string)
125 + * @param msg Message to be published (no need for 0 termination)
126 + * @param msg_len Length of the message to be published
127 + * @param publish_flags see enum mqtt_wss_publish_flags e.g. (MQTT_WSS_PUB_QOS1 | MQTT_WSS_PUB_RETAIN)
128 + * @param packet_id is 16 bit unsigned int representing ID that can be used to pair with PUBACK callback
129 + * for usages where application layer wants to know which messages are delivered when
130 + * @return Returns 0 on success
131 + */
132 +int mqtt_wss_publish5(mqtt_wss_client client,
133 + char *topic,
134 + free_fnc_t topic_free,
135 + void *msg,
136 + free_fnc_t msg_free,
137 + size_t msg_len,
138 + uint8_t publish_flags,
139 + uint16_t *packet_id);
140 +
141 +int mqtt_wss_set_topic_alias(mqtt_wss_client client, const char *topic);
142 +
143 +/* Subscribes to MQTT topic
144 + * @param client mqtt_wss_client which should do the subscription
145 + * @param topic MQTT topic to subscribe to
146 + * @param max_qos_level maximum QOS level that broker can send to us on this subscription
147 + * @return Returns 0 on success
148 + */
149 +int mqtt_wss_subscribe(mqtt_wss_client client, char *topic, int max_qos_level);
150 +
151 +
152 +struct mqtt_wss_stats {
153 + uint64_t bytes_tx;
154 + uint64_t bytes_rx;
155 +#ifdef MQTT_WSS_CPUSTATS
156 + uint64_t time_keepalive;
157 + uint64_t time_read_socket;
158 + uint64_t time_write_socket;
159 + uint64_t time_process_websocket;
160 + uint64_t time_process_mqtt;
161 +#endif
162 + struct mqtt_ng_stats mqtt;
163 +};
164 +
165 +struct mqtt_wss_stats mqtt_wss_get_stats(mqtt_wss_client client);
166 +
167 +#ifdef MQTT_WSS_DEBUG
168 +#include <openssl/ssl.h>
169 +void mqtt_wss_set_SSL_CTX_keylog_cb(mqtt_wss_client client, void (*ssl_ctx_keylog_cb)(const SSL *ssl, const char *line));
170 +#endif
171 +
172 +#endif /* MQTT_WSS_CLIENT_H */
mqtt_websockets/src/include/mqtt_wss_log.h new
+37
@@ -0,0 +1,37 @@
1 +#ifndef MQTT_WSS_LOG_H
2 +#define MQTT_WSS_LOG_H
3 +
4 +typedef enum mqtt_wss_log_type {
5 + MQTT_WSS_LOG_DEBUG = 0x01,
6 + MQTT_WSS_LOG_INFO = 0x02,
7 + MQTT_WSS_LOG_WARN = 0x03,
8 + MQTT_WSS_LOG_ERROR = 0x81,
9 + MQTT_WSS_LOG_FATAL = 0x88
10 +} mqtt_wss_log_type_t;
11 +
12 +typedef void (*mqtt_wss_log_callback_t)(mqtt_wss_log_type_t, const char*);
13 +
14 +typedef struct mqtt_wss_log_ctx *mqtt_wss_log_ctx_t;
15 +
16 +/** Creates logging context with optional prefix and optional callback
17 + * @param ctx_prefix String to be prefixed to every log message.
18 + * This is useful if multiple clients are instantiated to be able to
19 + * know which one this message belongs to. Can be `NULL` for no prefix.
20 + * @param log_callback Callback to be called instead of logging to
21 + * `STDOUT` or `STDERR` (if debug enabled otherwise silent). Callback has to be
22 + * pointer to function of `void function(mqtt_wss_log_type_t, const char*)` type.
23 + * If `NULL` default will be used (silent or STDERR/STDOUT).
24 + * @return mqtt_wss_log_ctx_t or `NULL` on error */
25 +mqtt_wss_log_ctx_t mqtt_wss_log_ctx_create(const char *ctx_prefix, mqtt_wss_log_callback_t log_callback);
26 +
27 +/** Destroys logging context and cleans up the memory
28 + * @param ctx Context to destroy */
29 +void mqtt_wss_log_ctx_destroy(mqtt_wss_log_ctx_t ctx);
30 +
31 +void mws_fatal(mqtt_wss_log_ctx_t ctx, const char *fmt, ...);
32 +void mws_error(mqtt_wss_log_ctx_t ctx, const char *fmt, ...);
33 +void mws_warn (mqtt_wss_log_ctx_t ctx, const char *fmt, ...);
34 +void mws_info (mqtt_wss_log_ctx_t ctx, const char *fmt, ...);
35 +void mws_debug(mqtt_wss_log_ctx_t ctx, const char *fmt, ...);
36 +
37 +#endif /* MQTT_WSS_LOG_H */
mqtt_websockets/src/include/ws_client.h new
+130
@@ -0,0 +1,130 @@
1 +// Copyright (C) 2020 Timotej Šiškovič
2 +// SPDX-License-Identifier: GPL-3.0-only
3 +//
4 +// This program is free software: you can redistribute it and/or modify it
5 +// under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
6 +//
7 +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9 +// See the GNU General Public License for more details.
10 +//
11 +// You should have received a copy of the GNU General Public License along with this program.
12 +// If not, see <https://www.gnu.org/licenses/>.
13 +
14 +#ifndef WS_CLIENT_H
15 +#define WS_CLIENT_H
16 +
17 +#include "ringbuffer.h"
18 +#include "mqtt_wss_log.h"
19 +
20 +#include <stdint.h>
21 +
22 +#define WS_CLIENT_NEED_MORE_BYTES 0x10
23 +#define WS_CLIENT_PARSING_DONE 0x11
24 +#define WS_CLIENT_CONNECTION_CLOSED 0x12
25 +#define WS_CLIENT_PROTOCOL_ERROR -0x10
26 +#define WS_CLIENT_BUFFER_FULL -0x11
27 +#define WS_CLIENT_INTERNAL_ERROR -0x12
28 +
29 +enum websocket_client_conn_state {
30 + WS_RAW = 0,
31 + WS_HANDSHAKE,
32 + WS_ESTABLISHED,
33 + WS_ERROR, // connection has to be restarted if this is reached
34 + WS_CONN_CLOSED_GRACEFUL
35 +};
36 +
37 +enum websocket_client_hdr_parse_state {
38 + WS_HDR_HTTP = 0, // need to check HTTP/1.1
39 + WS_HDR_RC, // need to read HTTP code
40 + WS_HDR_ENDLINE, // need to read rest of the first line
41 + WS_HDR_PARSE_HEADERS, // rest of the header until CRLF CRLF
42 + WS_HDR_PARSE_DONE,
43 + WS_HDR_ALL_DONE
44 +};
45 +
46 +enum websocket_client_rx_ws_parse_state {
47 + WS_FIRST_2BYTES = 0,
48 + WS_PAYLOAD_EXTENDED_16,
49 + WS_PAYLOAD_EXTENDED_64,
50 + WS_PAYLOAD_DATA, // BINARY payload to be passed to MQTT
51 + WS_PAYLOAD_CONNECTION_CLOSE,
52 + WS_PAYLOAD_CONNECTION_CLOSE_EC,
53 + WS_PAYLOAD_CONNECTION_CLOSE_MSG,
54 + WS_PAYLOAD_SKIP_UNKNOWN_PAYLOAD,
55 + WS_PAYLOAD_PING_REQ_PAYLOAD, // PING payload to be sent back as PONG
56 + WS_PACKET_DONE
57 +};
58 +
59 +enum websocket_opcode {
60 + WS_OP_CONTINUATION_FRAME = 0x0,
61 + WS_OP_TEXT_FRAME = 0x1,
62 + WS_OP_BINARY_FRAME = 0x2,
63 + WS_OP_CONNECTION_CLOSE = 0x8,
64 + WS_OP_PING = 0x9,
65 + WS_OP_PONG = 0xA
66 +};
67 +
68 +struct ws_op_close_payload {
69 + uint16_t ec;
70 + char *reason;
71 +};
72 +
73 +struct http_header {
74 + char *key;
75 + char *value;
76 + struct http_header *next;
77 +};
78 +
79 +typedef struct websocket_client {
80 + enum websocket_client_conn_state state;
81 +
82 + struct ws_handshake {
83 + enum websocket_client_hdr_parse_state hdr_state;
84 + char *nonce_reply;
85 + int nonce_matched;
86 + int http_code;
87 + char *http_reply_msg;
88 + struct http_header *headers;
89 + struct http_header *headers_tail;
90 + int hdr_count;
91 + } hs;
92 +
93 + struct ws_rx {
94 + enum websocket_client_rx_ws_parse_state parse_state;
95 + enum websocket_opcode opcode;
96 + uint64_t payload_length;
97 + uint64_t payload_processed;
98 + union {
99 + struct ws_op_close_payload op_close;
100 + char *ping_msg;
101 + } specific_data;
102 + } rx;
103 +
104 + rbuf_t buf_read; // from SSL
105 + rbuf_t buf_write; // to SSL and then to socket
106 + // TODO if ringbuffer gets multiple tail support
107 + // we can work without buf_to_mqtt and thus reduce
108 + // memory usage and remove one more memcpy buf_read->buf_to_mqtt
109 + rbuf_t buf_to_mqtt; // RAW data for MQTT lib
110 +
111 + int entropy_fd;
112 +
113 + // careful host is borrowed, don't free
114 + char **host;
115 + mqtt_wss_log_ctx_t log;
116 +} ws_client;
117 +
118 +ws_client *ws_client_new(size_t buf_size, char **host, mqtt_wss_log_ctx_t log);
119 +void ws_client_destroy(ws_client *client);
120 +void ws_client_reset(ws_client *client);
121 +
122 +int ws_client_start_handshake(ws_client *client);
123 +
124 +int ws_client_want_write(ws_client *client);
125 +
126 +int ws_client_process(ws_client *client);
127 +
128 +int ws_client_send(ws_client *client, enum websocket_opcode frame_type, const char *data, size_t size);
129 +
130 +#endif /* WS_CLIENT_H */
mqtt_websockets/src/mqtt_ng.c new
+2233
@@ -0,0 +1,2233 @@
1 +#define _GNU_SOURCE
2 +
3 +#include <stdint.h>
4 +#include <stdlib.h>
5 +#include <string.h>
6 +#include <pthread.h>
7 +#include <inttypes.h>
8 +
9 +#include "c_rhash.h"
10 +
11 +#include "common_internal.h"
12 +#include "mqtt_constants.h"
13 +#include "mqtt_wss_log.h"
14 +#include "mqtt_ng.h"
15 +
16 +#define UNIT_LOG_PREFIX "mqtt_client: "
17 +#define FATAL(fmt, ...) mws_fatal(client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
18 +#define ERROR(fmt, ...) mws_error(client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
19 +#define WARN(fmt, ...) mws_warn (client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
20 +#define INFO(fmt, ...) mws_info (client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
21 +#define DEBUG(fmt, ...) mws_debug(client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
22 +
23 +#define SMALL_STRING_DONT_FRAGMENT_LIMIT 128
24 +
25 +#define MIN(a,b) (((a)<(b))?(a):(b))
26 +
27 +#define LOCK_HDR_BUFFER(buffer) pthread_mutex_lock(&((buffer)->mutex))
28 +#define UNLOCK_HDR_BUFFER(buffer) pthread_mutex_unlock(&((buffer)->mutex))
29 +
30 +#define BUFFER_FRAG_GARBAGE_COLLECT 0x01
31 +// some packets can be marked for garbage collection
32 +// immediately when they are sent (e.g. sent PUBACK on QoS1)
33 +#define BUFFER_FRAG_GARBAGE_COLLECT_ON_SEND 0x02
34 +// as buffer fragment can point to both
35 +// external data and data in the same buffer
36 +// we mark the former case with BUFFER_FRAG_DATA_EXTERNAL
37 +#define BUFFER_FRAG_DATA_EXTERNAL 0x04
38 +// as single MQTT Packet can be stored into multiple
39 +// buffer fragments (depending on copy requirements)
40 +// this marks this fragment to be the first/last
41 +#define BUFFER_FRAG_MQTT_PACKET_HEAD 0x10
42 +#define BUFFER_FRAG_MQTT_PACKET_TAIL 0x20
43 +
44 +typedef uint16_t buffer_frag_flag_t;
45 +struct buffer_fragment {
46 + size_t len;
47 + size_t sent;
48 + buffer_frag_flag_t flags;
49 + void (*free_fnc)(void *ptr);
50 + char *data;
51 +
52 + uint16_t packet_id;
53 +
54 + struct buffer_fragment *next;
55 +};
56 +
57 +typedef struct buffer_fragment *mqtt_msg_data;
58 +
59 +// buffer used for MQTT headers only
60 +// not for actual data sent
61 +struct header_buffer {
62 + size_t size;
63 + char *data;
64 + char *tail;
65 + struct buffer_fragment *tail_frag;
66 +};
67 +
68 +struct transaction_buffer {
69 + struct header_buffer hdr_buffer;
70 + // used while building new message
71 + // to be able to revert state easily
72 + // in case of error mid processing
73 + struct header_buffer state_backup;
74 + pthread_mutex_t mutex;
75 + struct buffer_fragment *sending_frag;
76 +};
77 +
78 +enum mqtt_client_state {
79 + RAW = 0,
80 + CONNECT_PENDING,
81 + CONNECTING,
82 + CONNECTED,
83 + ERROR,
84 + DISCONNECTED
85 +};
86 +
87 +enum parser_state {
88 + MQTT_PARSE_FIXED_HEADER_PACKET_TYPE = 0,
89 + MQTT_PARSE_FIXED_HEADER_LEN,
90 + MQTT_PARSE_VARIABLE_HEADER,
91 + MQTT_PARSE_MQTT_PACKET_DONE
92 +};
93 +
94 +enum varhdr_parser_state {
95 + MQTT_PARSE_VARHDR_INITIAL = 0,
96 + MQTT_PARSE_VARHDR_OPTIONAL_REASON_CODE,
97 + MQTT_PARSE_VARHDR_PROPS,
98 + MQTT_PARSE_VARHDR_TOPICNAME,
99 + MQTT_PARSE_VARHDR_POST_TOPICNAME,
100 + MQTT_PARSE_VARHDR_PACKET_ID,
101 + MQTT_PARSE_REASONCODES,
102 + MQTT_PARSE_PAYLOAD
103 +};
104 +
105 +struct mqtt_vbi_parser_ctx {
106 + char data[MQTT_VBI_MAXBYTES];
107 + uint8_t bytes;
108 + uint32_t result;
109 +};
110 +
111 +enum mqtt_datatype {
112 + MQTT_TYPE_UNKNOWN = 0,
113 + MQTT_TYPE_UINT_8,
114 + MQTT_TYPE_UINT_16,
115 + MQTT_TYPE_UINT_32,
116 + MQTT_TYPE_VBI,
117 + MQTT_TYPE_STR,
118 + MQTT_TYPE_STR_PAIR,
119 + MQTT_TYPE_BIN
120 +};
121 +
122 +struct mqtt_property {
123 + uint8_t id;
124 + enum mqtt_datatype type;
125 + union {
126 + char *strings[2];
127 + void *bindata;
128 + uint8_t uint8;
129 + uint16_t uint16;
130 + uint32_t uint32;
131 + } data;
132 + size_t bindata_len;
133 + struct mqtt_property *next;
134 +};
135 +
136 +enum mqtt_properties_parser_state {
137 + PROPERTIES_LENGTH = 0,
138 + PROPERTY_CREATE,
139 + PROPERTY_ID,
140 + PROPERTY_TYPE_UINT8,
141 + PROPERTY_TYPE_UINT16,
142 + PROPERTY_TYPE_UINT32,
143 + PROPERTY_TYPE_STR_BIN_LEN,
144 + PROPERTY_TYPE_STR,
145 + PROPERTY_TYPE_BIN,
146 + PROPERTY_TYPE_VBI,
147 + PROPERTY_NEXT
148 +};
149 +
150 +struct mqtt_properties_parser_ctx {
151 + enum mqtt_properties_parser_state state;
152 + struct mqtt_property *head;
153 + struct mqtt_property *tail;
154 + uint32_t properties_length;
155 + uint32_t vbi_length;
156 + struct mqtt_vbi_parser_ctx vbi_parser_ctx;
157 + size_t bytes_consumed;
158 + int str_idx;
159 +};
160 +
161 +struct mqtt_connack {
162 + uint8_t flags;
163 + uint8_t reason_code;
164 +};
165 +struct mqtt_puback {
166 + uint16_t packet_id;
167 + uint8_t reason_code;
168 +};
169 +
170 +struct mqtt_suback {
171 + uint16_t packet_id;
172 + uint8_t *reason_codes;
173 + uint8_t reason_code_count;
174 + uint8_t reason_codes_pending;
175 +};
176 +
177 +struct mqtt_publish {
178 + uint16_t topic_len;
179 + char *topic;
180 + uint16_t packet_id;
181 + size_t data_len;
182 + char *data;
183 + uint8_t qos;
184 +};
185 +
186 +struct mqtt_disconnect {
187 + uint8_t reason_code;
188 +};
189 +
190 +struct mqtt_ng_parser {
191 + rbuf_t received_data;
192 +
193 + uint8_t mqtt_control_packet_type;
194 + uint32_t mqtt_fixed_hdr_remaining_length;
195 + size_t mqtt_parsed_len;
196 +
197 + struct mqtt_vbi_parser_ctx vbi_parser;
198 + struct mqtt_properties_parser_ctx properties_parser;
199 +
200 + enum parser_state state;
201 + enum varhdr_parser_state varhdr_state;
202 +
203 + struct mqtt_property *varhdr_properties;
204 +
205 + union {
206 + struct mqtt_connack connack;
207 + struct mqtt_puback puback;
208 + struct mqtt_suback suback;
209 + struct mqtt_publish publish;
210 + struct mqtt_disconnect disconnect;
211 + } mqtt_packet;
212 +};
213 +
214 +struct topic_alias_data {
215 + uint16_t idx;
216 + uint32_t usage_count;
217 +};
218 +
219 +struct topic_aliases_data {
220 + c_rhash stoi_dict;
221 + uint32_t idx_max;
222 + uint32_t idx_assigned;
223 + pthread_rwlock_t rwlock;
224 +};
225 +
226 +struct mqtt_ng_client {
227 + struct transaction_buffer main_buffer;
228 +
229 + enum mqtt_client_state client_state;
230 +
231 + mqtt_msg_data connect_msg;
232 +
233 + mqtt_wss_log_ctx_t log;
234 +
235 + mqtt_ng_send_fnc_t send_fnc_ptr;
236 + void *user_ctx;
237 +
238 + // time when last fragment of MQTT message was sent
239 + time_t time_of_last_send;
240 +
241 + struct mqtt_ng_parser parser;
242 +
243 + size_t max_mem_bytes;
244 +
245 + void (*puback_callback)(uint16_t packet_id);
246 + void (*connack_callback)(void* user_ctx, int connack_reply);
247 + void (*msg_callback)(const char *topic, const void *msg, size_t msglen, int qos);
248 +
249 + unsigned int ping_pending:1;
250 +
251 + struct mqtt_ng_stats stats;
252 + pthread_mutex_t stats_mutex;
253 +
254 + struct topic_aliases_data tx_topic_aliases;
255 + c_rhash rx_aliases;
256 +
257 + size_t max_msg_size;
258 +};
259 +
260 +char pingreq[] = { MQTT_CPT_PINGREQ << 4, 0x00 };
261 +
262 +struct buffer_fragment ping_frag = {
263 + .data = pingreq,
264 + .flags = BUFFER_FRAG_MQTT_PACKET_HEAD | BUFFER_FRAG_MQTT_PACKET_TAIL,
265 + .free_fnc = NULL,
266 + .len = sizeof(pingreq),
267 + .next = NULL,
268 + .sent = 0,
269 + .packet_id = 0
270 +};
271 +
272 +int uint32_to_mqtt_vbi(uint32_t input, char *output) {
273 + int i = 1;
274 + *output = 0;
275 +
276 + /* MQTT 5 specs allows max 4 bytes of output
277 + making it 0xFF, 0xFF, 0xFF, 0x7F
278 + representing number 268435455 decimal
279 + see 1.5.5. Variable Byte Integer */
280 + if(input >= 256 * 1024 * 1024)
281 + return 0;
282 +
283 + if(!input) {
284 + *output = 0;
285 + return 1;
286 + }
287 +
288 + while(input) {
289 + output[i-1] = input & MQTT_VBI_DATA_MASK;
290 + input >>= 7;
291 + if (input)
292 + output[i-1] |= MQTT_VBI_CONTINUATION_FLAG;
293 + i++;
294 + }
295 + return i - 1;
296 +}
297 +
298 +int mqtt_vbi_to_uint32(char *input, uint32_t *output) {
299 + // dont want to operate directly on output
300 + // as I want it to be possible for input and output
301 + // pointer to be the same
302 + uint32_t result = 0;
303 + uint32_t multiplier = 1;
304 +
305 + do {
306 + result += (uint32_t)(*input & MQTT_VBI_DATA_MASK) * multiplier;
307 + if (multiplier > 128*128*128)
308 + return 1;
309 + multiplier <<= 7;
310 + } while (*input++ & MQTT_VBI_CONTINUATION_FLAG);
311 + *output = result;
312 + return 0;
313 +}
314 +
315 +#ifdef TESTS
316 +#include <stdio.h>
317 +#define MQTT_VBI_MAXLEN 4
318 +// we add extra byte to check we dont write out of bounds
319 +// in case where 4 bytes are supposed to be written
320 +static const char _mqtt_vbi_0[MQTT_VBI_MAXLEN + 1] = { 0x00, 0x00, 0x00, 0x00, 0x00 };
321 +static const char _mqtt_vbi_127[MQTT_VBI_MAXLEN + 1] = { 0x7F, 0x00, 0x00, 0x00, 0x00 };
322 +static const char _mqtt_vbi_128[MQTT_VBI_MAXLEN + 1] = { 0x80, 0x01, 0x00, 0x00, 0x00 };
323 +static const char _mqtt_vbi_16383[MQTT_VBI_MAXLEN + 1] = { 0xFF, 0x7F, 0x00, 0x00, 0x00 };
324 +static const char _mqtt_vbi_16384[MQTT_VBI_MAXLEN + 1] = { 0x80, 0x80, 0x01, 0x00, 0x00 };
325 +static const char _mqtt_vbi_2097151[MQTT_VBI_MAXLEN + 1] = { 0xFF, 0xFF, 0x7F, 0x00, 0x00 };
326 +static const char _mqtt_vbi_2097152[MQTT_VBI_MAXLEN + 1] = { 0x80, 0x80, 0x80, 0x01, 0x00 };
327 +static const char _mqtt_vbi_268435455[MQTT_VBI_MAXLEN + 1] = { 0xFF, 0xFF, 0xFF, 0x7F, 0x00 };
328 +static const char _mqtt_vbi_999999999[MQTT_VBI_MAXLEN + 1] = { 0x80, 0x80, 0x80, 0x80, 0x01 };
329 +
330 +#define MQTT_VBI_TESTCASE(case, expected_len) \
331 + { \
332 + memset(buf, 0, MQTT_VBI_MAXLEN + 1); \
333 + int len; \
334 + if ((len=uint32_to_mqtt_vbi(case, buf)) != expected_len) { \
335 + fprintf(stderr, "uint32_to_mqtt_vbi(case:%d, line:%d): Incorrect length returned. Expected %d, Got %d\n", case, __LINE__, expected_len, len); \
336 + return 1; \
337 + } \
338 + if (memcmp(buf, _mqtt_vbi_ ## case, MQTT_VBI_MAXLEN + 1 )) { \
339 + fprintf(stderr, "uint32_to_mqtt_vbi(case:%d, line:%d): Wrong output\n", case, __LINE__); \
340 + return 1; \
341 + } }
342 +
343 +
344 +int test_uint32_mqtt_vbi() {
345 + char buf[MQTT_VBI_MAXLEN + 1];
346 +
347 + MQTT_VBI_TESTCASE(0, 1)
348 + MQTT_VBI_TESTCASE(127, 1)
349 + MQTT_VBI_TESTCASE(128, 2)
350 + MQTT_VBI_TESTCASE(16383, 2)
351 + MQTT_VBI_TESTCASE(16384, 3)
352 + MQTT_VBI_TESTCASE(2097151, 3)
353 + MQTT_VBI_TESTCASE(2097152, 4)
354 + MQTT_VBI_TESTCASE(268435455, 4)
355 +
356 + memset(buf, 0, MQTT_VBI_MAXLEN + 1);
357 + int len;
358 + if ((len=uint32_to_mqtt_vbi(268435456, buf)) != 0) {
359 + fprintf(stderr, "uint32_to_mqtt_vbi(case:268435456, line:%d): Incorrect length returned. Expected 0, Got %d\n", __LINE__, len);
360 + return 1;
361 + }
362 +
363 + return 0;
364 +}
365 +
366 +#define MQTT_VBI2UINT_TESTCASE(case, expected_error) \
367 + { \
368 + uint32_t result; \
369 + int ret = mqtt_vbi_to_uint32(_mqtt_vbi_ ## case, &result); \
370 + if (ret && !(expected_error)) { \
371 + fprintf(stderr, "mqtt_vbi_to_uint(case:%d, line:%d): Unexpectedly Errored\n", (case), __LINE__); \
372 + return 1; \
373 + } \
374 + if (!ret && (expected_error)) { \
375 + fprintf(stderr, "mqtt_vbi_to_uint(case:%d, line:%d): Should return error but didnt\n", (case), __LINE__); \
376 + return 1; \
377 + } \
378 + if (!ret && result != (case)) { \
379 + fprintf(stderr, "mqtt_vbi_to_uint(case:%d, line:%d): Returned wrong result %d\n", (case), __LINE__, result); \
380 + return 1; \
381 + }}
382 +
383 +
384 +int test_mqtt_vbi_to_uint32() {
385 + MQTT_VBI2UINT_TESTCASE(0, 0)
386 + MQTT_VBI2UINT_TESTCASE(127, 0)
387 + MQTT_VBI2UINT_TESTCASE(128, 0)
388 + MQTT_VBI2UINT_TESTCASE(16383, 0)
389 + MQTT_VBI2UINT_TESTCASE(16384, 0)
390 + MQTT_VBI2UINT_TESTCASE(2097151, 0)
391 + MQTT_VBI2UINT_TESTCASE(2097152, 0)
392 + MQTT_VBI2UINT_TESTCASE(268435455, 0)
393 + MQTT_VBI2UINT_TESTCASE(999999999, 1)
394 + return 0;
395 +}
396 +#endif /* TESTS */
397 +
398 +// this helps with switch statements
399 +// as they have to use integer type (not pointer)
400 +enum memory_mode {
401 + MEMCPY,
402 + EXTERNAL_FREE_AFTER_USE,
403 + CALLER_RESPONSIBLE
404 +};
405 +
406 +static inline enum memory_mode ptr2memory_mode(void * ptr) {
407 + if (ptr == NULL)
408 + return MEMCPY;
409 + if (ptr == CALLER_RESPONSIBILITY)
410 + return CALLER_RESPONSIBLE;
411 + return EXTERNAL_FREE_AFTER_USE;
412 +}
413 +
414 +#define frag_is_marked_for_gc(frag) ((frag->flags & BUFFER_FRAG_GARBAGE_COLLECT) || ((frag->flags & BUFFER_FRAG_GARBAGE_COLLECT_ON_SEND) && frag->sent == frag->len))
415 +#define FRAG_SIZE_IN_BUFFER(frag) (sizeof(struct buffer_fragment) + ((frag->flags & BUFFER_FRAG_DATA_EXTERNAL) ? 0 : frag->len))
416 +
417 +static void buffer_frag_free_data(struct buffer_fragment *frag)
418 +{
419 + if ( frag->flags & BUFFER_FRAG_DATA_EXTERNAL && frag->data != NULL) {
420 + switch (ptr2memory_mode(frag->free_fnc)) {
421 + case MEMCPY:
422 + mw_free(frag->data);
423 + break;
424 + case EXTERNAL_FREE_AFTER_USE:
425 + frag->free_fnc(frag->data);
426 + break;
427 + case CALLER_RESPONSIBLE:
428 + break;
429 + }
430 + frag->data = NULL;
431 + }
432 +}
433 +
434 +#define HEADER_BUFFER_SIZE 1024*1024
435 +#define GROWTH_FACTOR 1.25
436 +
437 +#define BUFFER_BYTES_USED(buf) ((size_t)((buf)->tail - (buf)->data))
438 +#define BUFFER_BYTES_AVAILABLE(buf) ((buf)->size - BUFFER_BYTES_USED(buf))
439 +#define BUFFER_FIRST_FRAG(buf) ((struct buffer_fragment *)((buf)->tail_frag ? (buf)->data : NULL))
440 +static void buffer_purge(struct header_buffer *buf) {
441 + struct buffer_fragment *frag = BUFFER_FIRST_FRAG(buf);
442 + while (frag) {
443 + buffer_frag_free_data(frag);
444 + frag = frag->next;
445 + }
446 + buf->tail = buf->data;
447 + buf->tail_frag = NULL;
448 +}
449 +
450 +#define FRAG_PADDING(addr) ((MQTT_WSS_FRAG_MEMALIGN - ((uintptr_t)addr % MQTT_WSS_FRAG_MEMALIGN)) % MQTT_WSS_FRAG_MEMALIGN)
451 +static struct buffer_fragment *buffer_new_frag(struct header_buffer *buf, buffer_frag_flag_t flags)
452 +{
453 + uint8_t padding = FRAG_PADDING(buf->tail);
454 +
455 + if (BUFFER_BYTES_AVAILABLE(buf) < sizeof(struct buffer_fragment) + padding)
456 + return NULL;
457 +
458 + struct buffer_fragment *frag = (struct buffer_fragment *)(buf->tail + padding);
459 +
460 + memset(frag, 0, sizeof(*frag));
461 + buf->tail += sizeof(*frag) + padding;
462 +
463 + if (/*!((frag)->flags & BUFFER_FRAG_MQTT_PACKET_HEAD) &&*/ buf->tail_frag)
464 + buf->tail_frag->next = frag;
465 +
466 + buf->tail_frag = frag;
467 +
468 + frag->data = buf->tail;
469 +
470 + frag->flags = flags;
471 +
472 + return frag;
473 +}
474 +
475 +static void buffer_rebuild(struct header_buffer *buf)
476 +{
477 + struct buffer_fragment *frag = (struct buffer_fragment*)buf->data;
478 + do {
479 + buf->tail = (char*)frag + sizeof(struct buffer_fragment);
480 + buf->tail_frag = frag;
481 + if (!(frag->flags & BUFFER_FRAG_DATA_EXTERNAL)) {
482 + buf->tail_frag->data = buf->tail;
483 + buf->tail += frag->len;
484 + }
485 + if (frag->next != NULL)
486 + frag->next = (struct buffer_fragment*)(buf->tail + FRAG_PADDING(buf->tail));
487 + frag = frag->next;
488 + } while(frag);
489 +}
490 +
491 +static void buffer_garbage_collect(struct header_buffer *buf, mqtt_wss_log_ctx_t log_ctx)
492 +{
493 +#if !defined(MQTT_DEBUG_VERBOSE) && !defined(ADDITIONAL_CHECKS)
494 + (void) log_ctx;
495 +#endif
496 +#ifdef MQTT_DEBUG_VERBOSE
497 + mws_debug(log_ctx, "Buffer Garbage Collection!");
498 +#endif
499 +
500 + struct buffer_fragment *frag = BUFFER_FIRST_FRAG(buf);
501 + while (frag) {
502 + if (!frag_is_marked_for_gc(frag))
503 + break;
504 +
505 + buffer_frag_free_data(frag);
506 +
507 + frag = frag->next;
508 + }
509 +
510 + if (frag == BUFFER_FIRST_FRAG(buf)) {
511 +#ifdef MQTT_DEBUG_VERBOSE
512 + mws_debug(log_ctx, "Buffer Garbage Collection! No Space Reclaimed!");
513 +#endif
514 + return;
515 + }
516 +
517 + if (!frag) {
518 + buf->tail_frag = NULL;
519 + buf->tail = buf->data;
520 + return;
521 + }
522 +
523 +#ifdef ADDITIONAL_CHECKS
524 + if (!(frag->flags & BUFFER_FRAG_MQTT_PACKET_HEAD)) {
525 + mws_error(log_ctx, "Expected to find end of buffer (NULL) or next packet head!");
526 + return;
527 + }
528 +#endif
529 +
530 + memmove(buf->data, frag, buf->tail - (char*)frag);
531 + buffer_rebuild(buf);
532 +}
533 +
534 +static void transaction_buffer_garbage_collect(struct transaction_buffer *buf, mqtt_wss_log_ctx_t log_ctx)
535 +{
536 +#ifdef MQTT_DEBUG_VERBOSE
537 + mws_debug(log_ctx, "Transaction Buffer Garbage Collection! %s", buf->sending_frag == NULL ? "NULL" : "in flight message");
538 +#endif
539 +
540 + // Invalidate the cached sending fragment
541 + // as we will move data around
542 + if (buf->sending_frag != &ping_frag)
543 + buf->sending_frag = NULL;
544 +
545 + buffer_garbage_collect(&buf->hdr_buffer, log_ctx);
546 +}
547 +
548 +static int transaction_buffer_grow(struct transaction_buffer *buf, mqtt_wss_log_ctx_t log_ctx, float rate, size_t max)
549 +{
550 + if (buf->hdr_buffer.size >= max)
551 + return 0;
552 +
553 + // Invalidate the cached sending fragment
554 + // as we will move data around
555 + if (buf->sending_frag != &ping_frag)
556 + buf->sending_frag = NULL;
557 +
558 + buf->hdr_buffer.size *= rate;
559 + if (buf->hdr_buffer.size > max)
560 + buf->hdr_buffer.size = max;
561 +
562 + void *ret = mw_realloc(buf->hdr_buffer.data, buf->hdr_buffer.size);
563 + if (ret == NULL) {
564 + mws_warn(log_ctx, "Buffer growth failed (realloc)");
565 + return 1;
566 + }
567 +
568 + mws_debug(log_ctx, "Message metadata buffer was grown");
569 +
570 + buf->hdr_buffer.data = ret;
571 + buffer_rebuild(&buf->hdr_buffer);
572 + return 0;
573 +}
574 +
575 +inline static int transaction_buffer_init(struct transaction_buffer *to_init, size_t size)
576 +{
577 + pthread_mutex_init(&to_init->mutex, NULL);
578 +
579 + to_init->hdr_buffer.size = size;
580 + to_init->hdr_buffer.data = mw_malloc(size);
581 + if (to_init->hdr_buffer.data == NULL)
582 + return 1;
583 +
584 + to_init->hdr_buffer.tail = to_init->hdr_buffer.data;
585 + to_init->hdr_buffer.tail_frag = NULL;
586 + return 0;
587 +}
588 +
589 +static void transaction_buffer_destroy(struct transaction_buffer *to_init)
590 +{
591 + buffer_purge(&to_init->hdr_buffer);
592 + pthread_mutex_destroy(&to_init->mutex);
593 + mw_free(to_init->hdr_buffer.data);
594 +}
595 +
596 +// Creates transaction
597 +// saves state of buffer before any operation was done
598 +// allowing for rollback if things go wrong
599 +#define transaction_buffer_transaction_start(buf) \
600 + { LOCK_HDR_BUFFER(buf); \
601 + memcpy(&(buf)->state_backup, &(buf)->hdr_buffer, sizeof((buf)->hdr_buffer)); }
602 +
603 +#define transaction_buffer_transaction_commit(buf) UNLOCK_HDR_BUFFER(buf);
604 +
605 +void transaction_buffer_transaction_rollback(struct transaction_buffer *buf, struct buffer_fragment *frag)
606 +{
607 + memcpy(&buf->hdr_buffer, &buf->state_backup, sizeof(buf->hdr_buffer));
608 + if (buf->hdr_buffer.tail_frag != NULL)
609 + buf->hdr_buffer.tail_frag->next = NULL;
610 +
611 + while(frag) {
612 + buffer_frag_free_data(frag);
613 + // we are not actually freeing the structure itself
614 + // just the data it manages
615 + // structure itself is in permanent buffer
616 + // which is locked by HDR_BUFFER lock
617 + frag = frag->next;
618 + }
619 +
620 + UNLOCK_HDR_BUFFER(buf);
621 +}
622 +
623 +#define TX_ALIASES_INITIALIZE() c_rhash_new(0)
624 +#define RX_ALIASES_INITIALIZE() c_rhash_new(UINT16_MAX >> 8)
625 +struct mqtt_ng_client *mqtt_ng_init(struct mqtt_ng_init *settings)
626 +{
627 + struct mqtt_ng_client *client = mw_calloc(1, sizeof(struct mqtt_ng_client));
628 + if (client == NULL)
629 + return NULL;
630 +
631 + if (transaction_buffer_init(&client->main_buffer, HEADER_BUFFER_SIZE))
632 + goto err_free_client;
633 +
634 + client->rx_aliases = RX_ALIASES_INITIALIZE();
635 + if (client->rx_aliases == NULL)
636 + goto err_free_trx_buf;
637 +
638 + if (pthread_mutex_init(&client->stats_mutex, NULL))
639 + goto err_free_rx_alias;
640 +
641 + client->tx_topic_aliases.stoi_dict = TX_ALIASES_INITIALIZE();
642 + if (client->tx_topic_aliases.stoi_dict == NULL)
643 + goto err_free_stats_mutex;
644 + client->tx_topic_aliases.idx_max = UINT16_MAX;
645 +
646 + if (pthread_rwlock_init(&client->tx_topic_aliases.rwlock, NULL))
647 + goto err_free_tx_alias;
648 +
649 + // TODO just embed the struct into mqtt_ng_client
650 + client->parser.received_data = settings->data_in;
651 + client->send_fnc_ptr = settings->data_out_fnc;
652 + client->user_ctx = settings->user_ctx;
653 +
654 + client->log = settings->log;
655 +
656 + client->puback_callback = settings->puback_callback;
657 + client->connack_callback = settings->connack_callback;
658 + client->msg_callback = settings->msg_callback;
659 +
660 + return client;
661 +
662 +err_free_tx_alias:
663 + c_rhash_destroy(client->tx_topic_aliases.stoi_dict);
664 +err_free_stats_mutex:
665 + pthread_mutex_destroy(&client->stats_mutex);
666 +err_free_rx_alias:
667 + c_rhash_destroy(client->rx_aliases);
668 +err_free_trx_buf:
669 + transaction_buffer_destroy(&client->main_buffer);
670 +err_free_client:
671 + mw_free(client);
672 + return NULL;
673 +}
674 +
675 +static inline uint8_t get_control_packet_type(uint8_t first_hdr_byte)
676 +{
677 + return first_hdr_byte >> 4;
678 +}
679 +
680 +static void mqtt_ng_destroy_rx_alias_hash(c_rhash hash)
681 +{
682 + c_rhash_iter_t i = C_RHASH_ITER_T_INITIALIZER;
683 + uint64_t stored_key;
684 + void *to_free;
685 + while(!c_rhash_iter_uint64_keys(hash, &i, &stored_key)) {
686 + c_rhash_get_ptr_by_uint64(hash, stored_key, &to_free);
687 + mw_free(to_free);
688 + }
689 + c_rhash_destroy(hash);
690 +}
691 +
692 +static void mqtt_ng_destroy_tx_alias_hash(c_rhash hash)
693 +{
694 + c_rhash_iter_t i = C_RHASH_ITER_T_INITIALIZER;
695 + const char *stored_key;
696 + void *to_free;
697 + while(!c_rhash_iter_str_keys(hash, &i, &stored_key)) {
698 + c_rhash_get_ptr_by_str(hash, stored_key, &to_free);
699 + mw_free(to_free);
700 + }
701 + c_rhash_destroy(hash);
702 +}
703 +
704 +void mqtt_ng_destroy(struct mqtt_ng_client *client)
705 +{
706 + transaction_buffer_destroy(&client->main_buffer);
707 + pthread_mutex_destroy(&client->stats_mutex);
708 +
709 + mqtt_ng_destroy_tx_alias_hash(client->tx_topic_aliases.stoi_dict);
710 + pthread_rwlock_destroy(&client->tx_topic_aliases.rwlock);
711 + mqtt_ng_destroy_rx_alias_hash(client->rx_aliases);
712 +
713 + mw_free(client);
714 +}
715 +
716 +int frag_set_external_data(mqtt_wss_log_ctx_t log, struct buffer_fragment *frag, void *data, size_t data_len, free_fnc_t data_free_fnc)
717 +{
718 + if (frag->len) {
719 + // TODO?: This could potentially be done in future if we set rule
720 + // external data always follows in buffer data
721 + // could help reduce fragmentation in some messages but
722 + // currently not worth it considering time is tight
723 + mws_fatal(log, UNIT_LOG_PREFIX "INTERNAL ERROR: Cannot set external data to fragment already containing in buffer data!");
724 + return 1;
725 + }
726 +
727 + switch (ptr2memory_mode(data_free_fnc)) {
728 + case MEMCPY:
729 + frag->data = mw_malloc(data_len);
730 + if (frag->data == NULL) {
731 + mws_error(log, UNIT_LOG_PREFIX "OOM while malloc @_optimized_add");
732 + return 1;
733 + }
734 + memcpy(frag->data, data, data_len);
735 + break;
736 + case EXTERNAL_FREE_AFTER_USE:
737 + case CALLER_RESPONSIBLE:
738 + frag->data = data;
739 + break;
740 + }
741 + frag->free_fnc = data_free_fnc;
742 + frag->len = data_len;
743 +
744 + frag->flags |= BUFFER_FRAG_DATA_EXTERNAL;
745 + return 0;
746 + }
747 +
748 +// this is fixed part of variable header for connect packet
749 +// mqtt-v5.0-cs1, 3.1.2.1, 2.1.2.2
750 +static const char mqtt_protocol_name_frag[] =
751 + { 0x00, 0x04, 'M', 'Q', 'T', 'T', MQTT_VERSION_5_0 };
752 +
753 +#define MQTT_UTF8_STRING_SIZE(string) (2 + strlen(string))
754 +
755 +// see 1.5.5
756 +#define MQTT_VARSIZE_INT_BYTES(value) ( value > 2097152 ? 4 : ( value > 16384 ? 3 : ( value > 128 ? 2 : 1 ) ) )
757 +
758 +static size_t mqtt_ng_connect_size(struct mqtt_auth_properties *auth,
759 + struct mqtt_lwt_properties *lwt)
760 +{
761 + // First get the size of payload + variable header
762 + size_t size =
763 + + sizeof(mqtt_protocol_name_frag) /* Proto Name and Version */
764 + + 1 /* Connect Flags */
765 + + 2 /* Keep Alive */
766 + + 4 /* 3.1.2.11.1 Property Length - for now fixed to only Topic Alias Maximum, TODO TODO*/;
767 +
768 + // CONNECT payload. 3.1.3
769 + if (auth->client_id)
770 + size += MQTT_UTF8_STRING_SIZE(auth->client_id);
771 +
772 + if (lwt) {
773 + // 3.1.3.2 will properties TODO TODO
774 + size += 1;
775 +
776 + // 3.1.3.3
777 + if (lwt->will_topic)
778 + size += MQTT_UTF8_STRING_SIZE(lwt->will_topic);
779 +
780 + // 3.1.3.4 will payload
781 + if (lwt->will_message) {
782 + size += 2 + lwt->will_message_size;
783 + }
784 + }
785 +
786 + // 3.1.3.5
787 + if (auth->username)
788 + size += MQTT_UTF8_STRING_SIZE(auth->username);
789 +
790 + // 3.1.3.6
791 + if (auth->password)
792 + size += MQTT_UTF8_STRING_SIZE(auth->password);
793 +
794 + return size;
795 +}
796 +
797 +#define BUFFER_TRANSACTION_NEW_FRAG(buf, flags, frag, on_fail) \
798 + { if(frag==NULL) { \
799 + frag = buffer_new_frag(buf, (flags)); } \
800 + if(frag==NULL) { on_fail; }}
801 +
802 +#define CHECK_BYTES_AVAILABLE(buf, needed, fail) \
803 + { if (BUFFER_BYTES_AVAILABLE(buf) < (size_t)needed) { \
804 + fail; } }
805 +
806 +#define DATA_ADVANCE(buf, bytes, frag) { size_t b = (bytes); (buf)->tail += b; (frag)->len += b; }
807 +
808 +// TODO maybe just user client->buf.tail?
809 +#define WRITE_POS(frag) (&(frag->data[frag->len]))
810 +
811 +// [MQTT-1.5.2] Two Byte Integer
812 +#define PACK_2B_INT(buffer, integer, frag) { *(uint16_t *)WRITE_POS(frag) = htobe16((integer)); \
813 + DATA_ADVANCE(buffer, sizeof(uint16_t), frag); }
814 +
815 +static int _optimized_add(struct header_buffer *buf, mqtt_wss_log_ctx_t log_ctx, void *data, size_t data_len, free_fnc_t data_free_fnc, struct buffer_fragment **frag)
816 +{
817 + if (data_len > SMALL_STRING_DONT_FRAGMENT_LIMIT) {
818 + buffer_frag_flag_t flags = BUFFER_FRAG_DATA_EXTERNAL;
819 + if ((*frag)->flags & BUFFER_FRAG_GARBAGE_COLLECT_ON_SEND)
820 + flags |= BUFFER_FRAG_GARBAGE_COLLECT_ON_SEND;
821 + if( (*frag = buffer_new_frag(buf, flags)) == NULL ) {
822 + mws_error(log_ctx, "Out of buffer space while generating the message");
823 + return 1;
824 + }
825 + if (frag_set_external_data(log_ctx, *frag, data, data_len, data_free_fnc)) {
826 + mws_error(log_ctx, "Error adding external data to newly created fragment");
827 + return 1;
828 + }
829 + // we dont want to write to this fragment anymore
830 + *frag = NULL;
831 + } else if (data_len) {
832 + // if the data are small dont bother creating new fragments
833 + // store in buffer directly
834 + CHECK_BYTES_AVAILABLE(buf, data_len, return 1);
835 + memcpy(buf->tail, data, data_len);
836 + DATA_ADVANCE(buf, data_len, *frag);
837 + }
838 + return 0;
839 +}
840 +
841 +#define TRY_GENERATE_MESSAGE(generator_function, client, ...) \
842 + int rc = generator_function(&client->main_buffer, client->log, ##__VA_ARGS__); \
843 + if (rc == MQTT_NG_MSGGEN_BUFFER_OOM) { \
844 + LOCK_HDR_BUFFER(&client->main_buffer); \
845 + transaction_buffer_garbage_collect((&client->main_buffer), client->log); \
846 + UNLOCK_HDR_BUFFER(&client->main_buffer); \
847 + rc = generator_function(&client->main_buffer, client->log, ##__VA_ARGS__); \
848 + if (rc == MQTT_NG_MSGGEN_BUFFER_OOM && client->max_mem_bytes) { \
849 + LOCK_HDR_BUFFER(&client->main_buffer); \
850 + transaction_buffer_grow((&client->main_buffer), client->log, GROWTH_FACTOR, client->max_mem_bytes); \
851 + UNLOCK_HDR_BUFFER(&client->main_buffer); \
852 + rc = generator_function(&client->main_buffer, client->log, ##__VA_ARGS__); \
853 + } \
854 + if (rc == MQTT_NG_MSGGEN_BUFFER_OOM) \
855 + mws_error(client->log, "%s failed to generate message due to insufficient buffer space (line %d)", __FUNCTION__, __LINE__); \
856 + } \
857 + if (rc == MQTT_NG_MSGGEN_OK) { \
858 + pthread_mutex_lock(&client->stats_mutex); \
859 + client->stats.tx_messages_queued++; \
860 + pthread_mutex_unlock(&client->stats_mutex); \
861 + } \
862 + return rc;
863 +
864 +mqtt_msg_data mqtt_ng_generate_connect(struct transaction_buffer *trx_buf,
865 + mqtt_wss_log_ctx_t log_ctx,
866 + struct mqtt_auth_properties *auth,
867 + struct mqtt_lwt_properties *lwt,
868 + uint8_t clean_start,
869 + uint16_t keep_alive)
870 +{
871 + // Sanity Checks First (are given parameters correct and up to MQTT spec)
872 + if (!auth->client_id) {
873 + mws_error(log_ctx, "ClientID must be set. [MQTT-3.1.3-3]");
874 + return NULL;
875 + }
876 +
877 + size_t len = strlen(auth->client_id);
878 + if (!len) {
879 + // [MQTT-3.1.3-6] server MAY allow empty client_id and treat it
880 + // as specific client_id (not same as client_id not given)
881 + // however server MUST allow ClientIDs between 1-23 bytes [MQTT-3.1.3-5]
882 + // so we will warn client server might not like this and he is using it
883 + // at his own risk!
884 + mws_warn(log_ctx, "client_id provided is empty string. This might not be allowed by server [MQTT-3.1.3-6]");
885 + }
886 + if(len > MQTT_MAX_CLIENT_ID) {
887 + // [MQTT-3.1.3-5] server MUST allow client_id length 1-32
888 + // server MAY allow longer client_id, if user provides longer client_id
889 + // warn them he is doing so at his own risk!
890 + mws_warn(log_ctx, "client_id provided is longer than 23 bytes, server might not allow that [MQTT-3.1.3-5]");
891 + }
892 +
893 + if (lwt) {
894 + if (lwt->will_message && lwt->will_message_size > 65535) {
895 + mws_error(log_ctx, "Will message cannot be longer than 65535 bytes due to MQTT protocol limitations [MQTT-3.1.3-4] and [MQTT-1.5.6]");
896 + return NULL;
897 + }
898 +
899 + if (!lwt->will_topic) { //TODO topic given with strlen==0 ? check specs
900 + mws_error(log_ctx, "If will message is given will topic must also be given [MQTT-3.1.3.3]");
901 + return NULL;
902 + }
903 +
904 + if (lwt->will_qos > MQTT_MAX_QOS) {
905 + // refer to [MQTT-3-1.2-12]
906 + mws_error(log_ctx, "QOS for LWT message is bigger than max");
907 + return NULL;
908 + }
909 + }
910 +
911 + // >> START THE RODEO <<
912 + transaction_buffer_transaction_start(trx_buf);
913 +
914 + // Calculate the resulting message size sans fixed MQTT header
915 + size_t size = mqtt_ng_connect_size(auth, lwt);
916 +
917 + // Start generating the message
918 + struct buffer_fragment *frag = NULL;
919 + mqtt_msg_data ret = NULL;
920 +
921 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, BUFFER_FRAG_MQTT_PACKET_HEAD, frag, goto fail_rollback );
922 + ret = frag;
923 +
924 + // MQTT Fixed Header
925 + size_t needed_bytes = 1 /* Packet type */ + MQTT_VARSIZE_INT_BYTES(size) + sizeof(mqtt_protocol_name_frag) + 1 /* CONNECT FLAGS */ + 2 /* keepalive */ + 1 /* Properties TODO now fixed 0*/;
926 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, needed_bytes, goto fail_rollback);
927 +
928 + *WRITE_POS(frag) = MQTT_CPT_CONNECT << 4;
929 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
930 + DATA_ADVANCE(&trx_buf->hdr_buffer, uint32_to_mqtt_vbi(size, WRITE_POS(frag)), frag);
931 +
932 + memcpy(WRITE_POS(frag), mqtt_protocol_name_frag, sizeof(mqtt_protocol_name_frag));
933 + DATA_ADVANCE(&trx_buf->hdr_buffer, sizeof(mqtt_protocol_name_frag), frag);
934 +
935 + // [MQTT-3.1.2.3] Connect flags
936 + char *connect_flags = WRITE_POS(frag);
937 + *connect_flags = 0;
938 + if (auth->username)
939 + *connect_flags |= MQTT_CONNECT_FLAG_USERNAME;
940 + if (auth->password)
941 + *connect_flags |= MQTT_CONNECT_FLAG_PASSWORD;
942 + if (lwt) {
943 + *connect_flags |= MQTT_CONNECT_FLAG_LWT;
944 + *connect_flags |= lwt->will_qos << MQTT_CONNECT_FLAG_QOS_BITSHIFT;
945 + if (lwt->will_retain)
946 + *connect_flags |= MQTT_CONNECT_FLAG_LWT_RETAIN;
947 + }
948 + if (clean_start)
949 + *connect_flags |= MQTT_CONNECT_FLAG_CLEAN_START;
950 +
951 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
952 +
953 + PACK_2B_INT(&trx_buf->hdr_buffer, keep_alive, frag);
954 +
955 + // TODO Property Length [MQTT-3.1.3.2.1] temporary fixed to 3 (one property topic alias max)
956 + DATA_ADVANCE(&trx_buf->hdr_buffer, uint32_to_mqtt_vbi(3, WRITE_POS(frag)), frag);
957 + *WRITE_POS(frag) = MQTT_PROP_TOPIC_ALIAS_MAX;
958 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
959 +
960 + PACK_2B_INT(&trx_buf->hdr_buffer, 65535, frag);
961 +
962 + // [MQTT-3.1.3.1] Client identifier
963 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, 2, goto fail_rollback);
964 + PACK_2B_INT(&trx_buf->hdr_buffer, strlen(auth->client_id), frag);
965 + if (_optimized_add(&trx_buf->hdr_buffer, log_ctx, auth->client_id, strlen(auth->client_id), auth->client_id_free, &frag))
966 + goto fail_rollback;
967 +
968 + if (lwt != NULL) {
969 + // Will Properties [MQTT-3.1.3.2]
970 + // TODO for now fixed 0
971 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, 0, frag, goto fail_rollback);
972 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, 1, goto fail_rollback);
973 + *WRITE_POS(frag) = 0;
974 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
975 +
976 + // Will Topic [MQTT-3.1.3.3]
977 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, 2, goto fail_rollback);
978 + PACK_2B_INT(&trx_buf->hdr_buffer, strlen(lwt->will_topic), frag);
979 + if (_optimized_add(&trx_buf->hdr_buffer, log_ctx, lwt->will_topic, strlen(lwt->will_topic), lwt->will_topic_free, &frag))
980 + goto fail_rollback;
981 +
982 + // Will Payload [MQTT-3.1.3.4]
983 + if (lwt->will_message_size) {
984 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, 0, frag, goto fail_rollback);
985 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, 2, goto fail_rollback);
986 + PACK_2B_INT(&trx_buf->hdr_buffer, lwt->will_message_size, frag);
987 + if (_optimized_add(&trx_buf->hdr_buffer, log_ctx, lwt->will_message, lwt->will_message_size, lwt->will_topic_free, &frag))
988 + goto fail_rollback;
989 + }
990 + }
991 +
992 + // [MQTT-3.1.3.5]
993 + if (auth->username) {
994 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, 0, frag, goto fail_rollback);
995 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, 2, goto fail_rollback);
996 + PACK_2B_INT(&trx_buf->hdr_buffer, strlen(auth->username), frag);
997 + if (_optimized_add(&trx_buf->hdr_buffer, log_ctx, auth->username, strlen(auth->username), auth->username_free, &frag))
998 + goto fail_rollback;
999 + }
1000 +
1001 + // [MQTT-3.1.3.6]
1002 + if (auth->password) {
1003 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, 0, frag, goto fail_rollback);
1004 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, 2, goto fail_rollback);
1005 + PACK_2B_INT(&trx_buf->hdr_buffer, strlen(auth->password), frag);
1006 + if (_optimized_add(&trx_buf->hdr_buffer, log_ctx, auth->password, strlen(auth->password), auth->password_free, &frag))
1007 + goto fail_rollback;
1008 + }
1009 + trx_buf->hdr_buffer.tail_frag->flags |= BUFFER_FRAG_MQTT_PACKET_TAIL;
1010 + transaction_buffer_transaction_commit(trx_buf);
1011 + return ret;
1012 +fail_rollback:
1013 + transaction_buffer_transaction_rollback(trx_buf, ret);
1014 + return NULL;
1015 +}
1016 +
1017 +int mqtt_ng_connect(struct mqtt_ng_client *client,
1018 + struct mqtt_auth_properties *auth,
1019 + struct mqtt_lwt_properties *lwt,
1020 + uint8_t clean_start,
1021 + uint16_t keep_alive)
1022 +{
1023 + client->client_state = RAW;
1024 + client->parser.state = MQTT_PARSE_FIXED_HEADER_PACKET_TYPE;
1025 +
1026 + LOCK_HDR_BUFFER(&client->main_buffer);
1027 + client->main_buffer.sending_frag = NULL;
1028 + if (clean_start)
1029 + buffer_purge(&client->main_buffer.hdr_buffer);
1030 + UNLOCK_HDR_BUFFER(&client->main_buffer);
1031 +
1032 + pthread_rwlock_wrlock(&client->tx_topic_aliases.rwlock);
1033 + // according to MQTT spec topic aliases should not be persisted
1034 + // even if clean session is true
1035 + mqtt_ng_destroy_tx_alias_hash(client->tx_topic_aliases.stoi_dict);
1036 + client->tx_topic_aliases.stoi_dict = TX_ALIASES_INITIALIZE();
1037 + if (client->tx_topic_aliases.stoi_dict == NULL) {
1038 + pthread_rwlock_unlock(&client->tx_topic_aliases.rwlock);
1039 + return 1;
1040 + }
1041 + client->tx_topic_aliases.idx_assigned = 0;
1042 + pthread_rwlock_unlock(&client->tx_topic_aliases.rwlock);
1043 +
1044 + mqtt_ng_destroy_rx_alias_hash(client->rx_aliases);
1045 + client->rx_aliases = RX_ALIASES_INITIALIZE();
1046 + if (client->rx_aliases == NULL)
1047 + return 1;
1048 +
1049 + client->connect_msg = mqtt_ng_generate_connect(&client->main_buffer, client->log, auth, lwt, clean_start, keep_alive);
1050 + if (client->connect_msg == NULL)
1051 + return 1;
1052 +
1053 + pthread_mutex_lock(&client->stats_mutex);
1054 + if (clean_start)
1055 + client->stats.tx_messages_queued = 1;
1056 + else
1057 + client->stats.tx_messages_queued++;
1058 +
1059 + client->stats.tx_messages_sent = 0;
1060 + client->stats.rx_messages_rcvd = 0;
1061 + pthread_mutex_unlock(&client->stats_mutex);
1062 +
1063 + client->client_state = CONNECT_PENDING;
1064 + return 0;
1065 +}
1066 +
1067 +uint16_t get_unused_packet_id() {
1068 + static uint16_t packet_id = 0;
1069 + packet_id++;
1070 + return packet_id ? packet_id : ++packet_id;
1071 +}
1072 +
1073 +static inline size_t mqtt_ng_publish_size(const char *topic,
1074 + size_t msg_len,
1075 + uint16_t topic_id)
1076 +{
1077 + size_t retval = 2 /* Topic Name Length */
1078 + + (topic == NULL ? 0 : strlen(topic))
1079 + + 2 /* Packet identifier */
1080 + + 1 /* Properties Length TODO for now fixed to 1 property */
1081 + + msg_len;
1082 +
1083 + if (topic_id)
1084 + retval += 3;
1085 +
1086 + return retval;
1087 +}
1088 +
1089 +int mqtt_ng_generate_publish(struct transaction_buffer *trx_buf,
1090 + mqtt_wss_log_ctx_t log_ctx,
1091 + char *topic,
1092 + free_fnc_t topic_free,
1093 + void *msg,
1094 + free_fnc_t msg_free,
1095 + size_t msg_len,
1096 + uint8_t publish_flags,
1097 + uint16_t *packet_id,
1098 + uint16_t topic_alias)
1099 +{
1100 + // >> START THE RODEO <<
1101 + transaction_buffer_transaction_start(trx_buf);
1102 +
1103 + // Calculate the resulting message size sans fixed MQTT header
1104 + size_t size = mqtt_ng_publish_size(topic, msg_len, topic_alias);
1105 +
1106 + // Start generating the message
1107 + struct buffer_fragment *frag = NULL;
1108 + mqtt_msg_data mqtt_msg = NULL;
1109 +
1110 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, BUFFER_FRAG_MQTT_PACKET_HEAD, frag, goto fail_rollback );
1111 + // in case of QOS 0 we can garbage collect immediatelly after sending
1112 + uint8_t qos = (publish_flags >> 1) & 0x03;
1113 + if (!qos)
1114 + frag->flags |= BUFFER_FRAG_GARBAGE_COLLECT_ON_SEND;
1115 + mqtt_msg = frag;
1116 +
1117 + // MQTT Fixed Header
1118 + size_t needed_bytes = 1 /* Packet type */ + MQTT_VARSIZE_INT_BYTES(size) + size - msg_len;
1119 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, needed_bytes, goto fail_rollback);
1120 +
1121 + *WRITE_POS(frag) = (MQTT_CPT_PUBLISH << 4) | (publish_flags & 0xF);
1122 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1123 + DATA_ADVANCE(&trx_buf->hdr_buffer, uint32_to_mqtt_vbi(size, WRITE_POS(frag)), frag);
1124 +
1125 + // MQTT Variable Header
1126 + // [MQTT-3.3.2.1]
1127 + PACK_2B_INT(&trx_buf->hdr_buffer, topic == NULL ? 0 : strlen(topic), frag);
1128 + if (topic != NULL) {
1129 + if (_optimized_add(&trx_buf->hdr_buffer, log_ctx, topic, strlen(topic), topic_free, &frag))
1130 + goto fail_rollback;
1131 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, 0, frag, goto fail_rollback);
1132 + }
1133 +
1134 + // [MQTT-3.3.2.2]
1135 + mqtt_msg->packet_id = get_unused_packet_id();
1136 + *packet_id = mqtt_msg->packet_id;
1137 + PACK_2B_INT(&trx_buf->hdr_buffer, mqtt_msg->packet_id, frag);
1138 +
1139 + // [MQTT-3.3.2.3.1] TODO Property Length for now fixed 0
1140 + *WRITE_POS(frag) = topic_alias ? 3 : 0;
1141 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1142 +
1143 + if(topic_alias) {
1144 + *WRITE_POS(frag) = MQTT_PROP_TOPIC_ALIAS;
1145 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1146 +
1147 + PACK_2B_INT(&trx_buf->hdr_buffer, topic_alias, frag);
1148 + }
1149 +
1150 + if( (frag = buffer_new_frag(&trx_buf->hdr_buffer, BUFFER_FRAG_DATA_EXTERNAL)) == NULL )
1151 + goto fail_rollback;
1152 +
1153 + if (frag_set_external_data(log_ctx, frag, msg, msg_len, msg_free))
1154 + goto fail_rollback;
1155 +
1156 + trx_buf->hdr_buffer.tail_frag->flags |= BUFFER_FRAG_MQTT_PACKET_TAIL;
1157 + if (!qos)
1158 + trx_buf->hdr_buffer.tail_frag->flags |= BUFFER_FRAG_GARBAGE_COLLECT_ON_SEND;
1159 + transaction_buffer_transaction_commit(trx_buf);
1160 + return MQTT_NG_MSGGEN_OK;
1161 +fail_rollback:
1162 + transaction_buffer_transaction_rollback(trx_buf, mqtt_msg);
1163 + return MQTT_NG_MSGGEN_BUFFER_OOM;
1164 +}
1165 +
1166 +#define PUBLISH_SP_SIZE 64
1167 +int mqtt_ng_publish(struct mqtt_ng_client *client,
1168 + char *topic,
1169 + free_fnc_t topic_free,
1170 + void *msg,
1171 + free_fnc_t msg_free,
1172 + size_t msg_len,
1173 + uint8_t publish_flags,
1174 + uint16_t *packet_id)
1175 +{
1176 + struct topic_alias_data *alias = NULL;
1177 + pthread_rwlock_rdlock(&client->tx_topic_aliases.rwlock);
1178 + c_rhash_get_ptr_by_str(client->tx_topic_aliases.stoi_dict, topic, (void**)&alias);
1179 + pthread_rwlock_unlock(&client->tx_topic_aliases.rwlock);
1180 +
1181 + uint16_t topic_id = 0;
1182 +
1183 + if (alias != NULL) {
1184 + topic_id = alias->idx;
1185 + uint32_t cnt = __atomic_fetch_add(&alias->usage_count, 1, __ATOMIC_SEQ_CST);
1186 + if (cnt) {
1187 + topic = NULL;
1188 + topic_free = NULL;
1189 + }
1190 + }
1191 +
1192 + if (client->max_msg_size && PUBLISH_SP_SIZE + mqtt_ng_publish_size(topic, msg_len, topic_id) > client->max_msg_size) {
1193 + mws_error(client->log, "Message too big for server: %zu", msg_len);
1194 + return MQTT_NG_MSGGEN_MSG_TOO_BIG;
1195 + }
1196 +
1197 + TRY_GENERATE_MESSAGE(mqtt_ng_generate_publish, client, topic, topic_free, msg, msg_free, msg_len, publish_flags, packet_id, topic_id);
1198 +}
1199 +
1200 +static inline size_t mqtt_ng_subscribe_size(struct mqtt_sub *subs, size_t sub_count)
1201 +{
1202 + size_t len = 2 /* Packet Identifier */ + 1 /* Properties Length TODO for now fixed 0 */;
1203 + len += sub_count * (2 /* topic filter string length */ + 1 /* [MQTT-3.8.3.1] Subscription Options Byte */);
1204 +
1205 + for (size_t i = 0; i < sub_count; i++) {
1206 + len += strlen(subs[i].topic);
1207 + }
1208 + return len;
1209 +}
1210 +
1211 +int mqtt_ng_generate_subscribe(struct transaction_buffer *trx_buf, mqtt_wss_log_ctx_t log_ctx, struct mqtt_sub *subs, size_t sub_count)
1212 +{
1213 + // >> START THE RODEO <<
1214 + transaction_buffer_transaction_start(trx_buf);
1215 +
1216 + // Calculate the resulting message size sans fixed MQTT header
1217 + size_t size = mqtt_ng_subscribe_size(subs, sub_count);
1218 +
1219 + // Start generating the message
1220 + struct buffer_fragment *frag = NULL;
1221 + mqtt_msg_data ret = NULL;
1222 +
1223 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, BUFFER_FRAG_MQTT_PACKET_HEAD, frag, goto fail_rollback);
1224 + ret = frag;
1225 +
1226 + // MQTT Fixed Header
1227 + size_t needed_bytes = 1 /* Packet type */ + MQTT_VARSIZE_INT_BYTES(size) + 3 /*Packet ID + Property Length*/;
1228 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, needed_bytes, goto fail_rollback);
1229 +
1230 + *WRITE_POS(frag) = (MQTT_CPT_SUBSCRIBE << 4) | 0x2 /* [MQTT-3.8.1-1] */;
1231 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1232 + DATA_ADVANCE(&trx_buf->hdr_buffer, uint32_to_mqtt_vbi(size, WRITE_POS(frag)), frag);
1233 +
1234 + // MQTT Variable Header
1235 + // [MQTT-3.8.2] PacketID
1236 + ret->packet_id = get_unused_packet_id();
1237 + PACK_2B_INT(&trx_buf->hdr_buffer, ret->packet_id, frag);
1238 +
1239 + // [MQTT-3.8.2.1.1] Property Length // TODO for now fixed 0
1240 + *WRITE_POS(frag) = 0;
1241 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1242 +
1243 + for (size_t i = 0; i < sub_count; i++) {
1244 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, 0, frag, goto fail_rollback);
1245 + PACK_2B_INT(&trx_buf->hdr_buffer, strlen(subs[i].topic), frag);
1246 + if (_optimized_add(&trx_buf->hdr_buffer, log_ctx, subs[i].topic, strlen(subs[i].topic), subs[i].topic_free, &frag))
1247 + goto fail_rollback;
1248 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, 0, frag, goto fail_rollback);
1249 + *WRITE_POS(frag) = subs[i].options;
1250 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1251 + }
1252 +
1253 + trx_buf->hdr_buffer.tail_frag->flags |= BUFFER_FRAG_MQTT_PACKET_TAIL;
1254 + transaction_buffer_transaction_commit(trx_buf);
1255 + return MQTT_NG_MSGGEN_OK;
1256 +fail_rollback:
1257 + transaction_buffer_transaction_rollback(trx_buf, ret);
1258 + return MQTT_NG_MSGGEN_BUFFER_OOM;
1259 +}
1260 +
1261 +int mqtt_ng_subscribe(struct mqtt_ng_client *client, struct mqtt_sub *subs, size_t sub_count)
1262 +{
1263 + TRY_GENERATE_MESSAGE(mqtt_ng_generate_subscribe, client, subs, sub_count);
1264 +}
1265 +
1266 +int mqtt_ng_generate_disconnect(struct transaction_buffer *trx_buf, mqtt_wss_log_ctx_t log_ctx, uint8_t reason_code)
1267 +{
1268 + (void) log_ctx;
1269 + // >> START THE RODEO <<
1270 + transaction_buffer_transaction_start(trx_buf);
1271 +
1272 + // Calculate the resulting message size sans fixed MQTT header
1273 + size_t size = reason_code ? 1 : 0;
1274 +
1275 + // Start generating the message
1276 + struct buffer_fragment *frag = NULL;
1277 + mqtt_msg_data ret = NULL;
1278 +
1279 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, BUFFER_FRAG_MQTT_PACKET_HEAD, frag, goto fail_rollback);
1280 + ret = frag;
1281 +
1282 + // MQTT Fixed Header
1283 + size_t needed_bytes = 1 /* Packet type */ + MQTT_VARSIZE_INT_BYTES(size) + (reason_code ? 1 : 0);
1284 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, needed_bytes, goto fail_rollback);
1285 +
1286 + *WRITE_POS(frag) = MQTT_CPT_DISCONNECT << 4;
1287 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1288 + DATA_ADVANCE(&trx_buf->hdr_buffer, uint32_to_mqtt_vbi(size, WRITE_POS(frag)), frag);
1289 +
1290 + if (reason_code) {
1291 + // MQTT Variable Header
1292 + // [MQTT-3.14.2.1] PacketID
1293 + *WRITE_POS(frag) = reason_code;
1294 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1295 + }
1296 +
1297 + trx_buf->hdr_buffer.tail_frag->flags |= BUFFER_FRAG_MQTT_PACKET_TAIL;
1298 + transaction_buffer_transaction_commit(trx_buf);
1299 + return MQTT_NG_MSGGEN_OK;
1300 +fail_rollback:
1301 + transaction_buffer_transaction_rollback(trx_buf, ret);
1302 + return MQTT_NG_MSGGEN_BUFFER_OOM;
1303 +}
1304 +
1305 +int mqtt_ng_disconnect(struct mqtt_ng_client *client, uint8_t reason_code)
1306 +{
1307 + TRY_GENERATE_MESSAGE(mqtt_ng_generate_disconnect, client, reason_code);
1308 +}
1309 +
1310 +static int mqtt_generate_puback(struct transaction_buffer *trx_buf, mqtt_wss_log_ctx_t log_ctx, uint16_t packet_id, uint8_t reason_code)
1311 +{
1312 + (void) log_ctx;
1313 + // >> START THE RODEO <<
1314 + transaction_buffer_transaction_start(trx_buf);
1315 +
1316 + // Calculate the resulting message size sans fixed MQTT header
1317 + size_t size = 2 /* Packet ID */ + (reason_code ? 1 : 0) /* reason code */;
1318 +
1319 + // Start generating the message
1320 + struct buffer_fragment *frag = NULL;
1321 +
1322 + BUFFER_TRANSACTION_NEW_FRAG(&trx_buf->hdr_buffer, BUFFER_FRAG_MQTT_PACKET_HEAD | BUFFER_FRAG_GARBAGE_COLLECT_ON_SEND, frag, goto fail_rollback);
1323 +
1324 + // MQTT Fixed Header
1325 + size_t needed_bytes = 1 /* Packet type */ + MQTT_VARSIZE_INT_BYTES(size) + size;
1326 + CHECK_BYTES_AVAILABLE(&trx_buf->hdr_buffer, needed_bytes, goto fail_rollback);
1327 +
1328 + *WRITE_POS(frag) = MQTT_CPT_PUBACK << 4;
1329 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1330 + DATA_ADVANCE(&trx_buf->hdr_buffer, uint32_to_mqtt_vbi(size, WRITE_POS(frag)), frag);
1331 +
1332 + // MQTT Variable Header
1333 + PACK_2B_INT(&trx_buf->hdr_buffer, packet_id, frag);
1334 +
1335 + if (reason_code) {
1336 + // MQTT Variable Header
1337 + // [MQTT-3.14.2.1] PacketID
1338 + *WRITE_POS(frag) = reason_code;
1339 + DATA_ADVANCE(&trx_buf->hdr_buffer, 1, frag);
1340 + }
1341 +
1342 + trx_buf->hdr_buffer.tail_frag->flags |= BUFFER_FRAG_MQTT_PACKET_TAIL;
1343 + transaction_buffer_transaction_commit(trx_buf);
1344 + return MQTT_NG_MSGGEN_OK;
1345 +fail_rollback:
1346 + transaction_buffer_transaction_rollback(trx_buf, frag);
1347 + return MQTT_NG_MSGGEN_BUFFER_OOM;
1348 +}
1349 +
1350 +static int mqtt_ng_puback(struct mqtt_ng_client *client, uint16_t packet_id, uint8_t reason_code)
1351 +{
1352 + TRY_GENERATE_MESSAGE(mqtt_generate_puback, client, packet_id, reason_code);
1353 +}
1354 +
1355 +int mqtt_ng_ping(struct mqtt_ng_client *client)
1356 +{
1357 + client->ping_pending = 1;
1358 + return MQTT_NG_MSGGEN_OK;
1359 +}
1360 +
1361 +#define MQTT_NG_CLIENT_NEED_MORE_BYTES 0x10
1362 +#define MQTT_NG_CLIENT_MQTT_PACKET_DONE 0x11
1363 +#define MQTT_NG_CLIENT_PARSE_DONE 0x12
1364 +#define MQTT_NG_CLIENT_WANT_WRITE 0x13
1365 +#define MQTT_NG_CLIENT_OK_CALL_AGAIN 0
1366 +#define MQTT_NG_CLIENT_PROTOCOL_ERROR -1
1367 +#define MQTT_NG_CLIENT_SERVER_RETURNED_ERROR -2
1368 +#define MQTT_NG_CLIENT_NOT_IMPL_YET -3
1369 +#define MQTT_NG_CLIENT_OOM -4
1370 +#define MQTT_NG_CLIENT_INTERNAL_ERROR -5
1371 +
1372 +#define BUF_READ_CHECK_AT_LEAST(buf, x) \
1373 + if (rbuf_bytes_available(buf) < (x)) \
1374 + return MQTT_NG_CLIENT_NEED_MORE_BYTES;
1375 +
1376 +#define vbi_parser_reset_ctx(ctx) memset(ctx, 0, sizeof(struct mqtt_vbi_parser_ctx))
1377 +
1378 +static int vbi_parser_parse(struct mqtt_vbi_parser_ctx *ctx, rbuf_t data, mqtt_wss_log_ctx_t log)
1379 +{
1380 + if (ctx->bytes > MQTT_VBI_MAXBYTES - 1) {
1381 + mws_error(log, "MQTT Variable Byte Integer can't be longer than %d bytes", MQTT_VBI_MAXBYTES);
1382 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
1383 + }
1384 + if (!ctx->bytes || ctx->data[ctx->bytes-1] & MQTT_VBI_CONTINUATION_FLAG) {
1385 + BUF_READ_CHECK_AT_LEAST(data, 1);
1386 + ctx->bytes++;
1387 + rbuf_pop(data, &ctx->data[ctx->bytes-1], 1);
1388 + if ( ctx->data[ctx->bytes-1] & MQTT_VBI_CONTINUATION_FLAG )
1389 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1390 + }
1391 +
1392 + if (mqtt_vbi_to_uint32(ctx->data, &ctx->result)) {
1393 + mws_error(log, "MQTT Variable Byte Integer failed to be parsed.");
1394 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
1395 + }
1396 +
1397 + return MQTT_NG_CLIENT_PARSE_DONE;
1398 +}
1399 +
1400 +static void mqtt_properties_parser_ctx_reset(struct mqtt_properties_parser_ctx *ctx)
1401 +{
1402 + ctx->state = PROPERTIES_LENGTH;
1403 + while (ctx->head) {
1404 + struct mqtt_property *f = ctx->head;
1405 + ctx->head = ctx->head->next;
1406 + if (f->type == MQTT_TYPE_STR || f->type == MQTT_TYPE_STR_PAIR)
1407 + mw_free(f->data.strings[0]);
1408 + if (f->type == MQTT_TYPE_STR_PAIR)
1409 + mw_free(f->data.strings[1]);
1410 + if (f->type == MQTT_TYPE_BIN)
1411 + mw_free(f->data.bindata);
1412 + mw_free(f);
1413 + }
1414 + ctx->tail = NULL;
1415 + ctx->properties_length = 0;
1416 + ctx->bytes_consumed = 0;
1417 + vbi_parser_reset_ctx(&ctx->vbi_parser_ctx);
1418 +}
1419 +
1420 +struct mqtt_property_type {
1421 + uint8_t id;
1422 + enum mqtt_datatype datatype;
1423 + const char* name;
1424 +};
1425 +
1426 +const struct mqtt_property_type mqtt_property_types[] = {
1427 + { .id = MQTT_PROP_TOPIC_ALIAS, .name = MQTT_PROP_TOPIC_ALIAS_NAME, .datatype = MQTT_TYPE_UINT_16 },
1428 +
1429 + { .id = MQTT_PROP_PAYLOAD_FMT_INDICATOR, .name = MQTT_PROP_PAYLOAD_FMT_INDICATOR_NAME, .datatype = MQTT_TYPE_UINT_8 },
1430 + { .id = MQTT_PROP_MSG_EXPIRY_INTERVAL, .name = MQTT_PROP_MSG_EXPIRY_INTERVAL_NAME, .datatype = MQTT_TYPE_UINT_32 },
1431 + { .id = MQTT_PROP_CONTENT_TYPE, .name = MQTT_PROP_CONTENT_TYPE_NAME, .datatype = MQTT_TYPE_STR },
1432 + { .id = MQTT_PROP_RESPONSE_TOPIC, .name = MQTT_PROP_RESPONSE_TOPIC_NAME, .datatype = MQTT_TYPE_STR },
1433 + { .id = MQTT_PROP_CORRELATION_DATA, .name = MQTT_PROP_CORRELATION_DATA_NAME, .datatype = MQTT_TYPE_BIN },
1434 + { .id = MQTT_PROP_SUB_IDENTIFIER, .name = MQTT_PROP_SUB_IDENTIFIER_NAME, .datatype = MQTT_TYPE_VBI },
1435 + { .id = MQTT_PROP_SESSION_EXPIRY_INTERVAL, .name = MQTT_PROP_SESSION_EXPIRY_INTERVAL_NAME, .datatype = MQTT_TYPE_UINT_32 },
1436 + { .id = MQTT_PROP_ASSIGNED_CLIENT_ID, .name = MQTT_PROP_ASSIGNED_CLIENT_ID_NAME, .datatype = MQTT_TYPE_STR },
1437 + { .id = MQTT_PROP_SERVER_KEEP_ALIVE, .name = MQTT_PROP_SERVER_KEEP_ALIVE_NAME, .datatype = MQTT_TYPE_UINT_16 },
1438 + { .id = MQTT_PROP_AUTH_METHOD, .name = MQTT_PROP_AUTH_METHOD_NAME, .datatype = MQTT_TYPE_STR },
1439 + { .id = MQTT_PROP_AUTH_DATA, .name = MQTT_PROP_AUTH_DATA_NAME, .datatype = MQTT_TYPE_BIN },
1440 + { .id = MQTT_PROP_REQ_PROBLEM_INFO, .name = MQTT_PROP_REQ_PROBLEM_INFO_NAME, .datatype = MQTT_TYPE_UINT_8 },
1441 + { .id = MQTT_PROP_WILL_DELAY_INTERVAL, .name = MQTT_PROP_WIIL_DELAY_INTERVAL_NAME, .datatype = MQTT_TYPE_UINT_32 },
1442 + { .id = MQTT_PROP_REQ_RESP_INFORMATION, .name = MQTT_PROP_REQ_RESP_INFORMATION_NAME, .datatype = MQTT_TYPE_UINT_8 },
1443 + { .id = MQTT_PROP_RESP_INFORMATION, .name = MQTT_PROP_RESP_INFORMATION_NAME, .datatype = MQTT_TYPE_STR },
1444 + { .id = MQTT_PROP_SERVER_REF, .name = MQTT_PROP_SERVER_REF_NAME, .datatype = MQTT_TYPE_STR },
1445 + { .id = MQTT_PROP_REASON_STR, .name = MQTT_PROP_REASON_STR_NAME, .datatype = MQTT_TYPE_STR },
1446 + { .id = MQTT_PROP_RECEIVE_MAX, .name = MQTT_PROP_RECEIVE_MAX_NAME, .datatype = MQTT_TYPE_UINT_16 },
1447 + { .id = MQTT_PROP_TOPIC_ALIAS_MAX, .name = MQTT_PROP_TOPIC_ALIAS_MAX_NAME, .datatype = MQTT_TYPE_UINT_16 },
1448 + // MQTT_PROP_TOPIC_ALIAS is first as it is most often used
1449 + { .id = MQTT_PROP_MAX_QOS, .name = MQTT_PROP_MAX_QOS_NAME, .datatype = MQTT_TYPE_UINT_8 },
1450 + { .id = MQTT_PROP_RETAIN_AVAIL, .name = MQTT_PROP_RETAIN_AVAIL_NAME, .datatype = MQTT_TYPE_UINT_8 },
1451 + { .id = MQTT_PROP_USR, .name = MQTT_PROP_USR_NAME, .datatype = MQTT_TYPE_STR_PAIR },
1452 + { .id = MQTT_PROP_MAX_PKT_SIZE, .name = MQTT_PROP_MAX_PKT_SIZE_NAME, .datatype = MQTT_TYPE_UINT_32 },
1453 + { .id = MQTT_PROP_WILDCARD_SUB_AVAIL, .name = MQTT_PROP_WILDCARD_SUB_AVAIL_NAME, .datatype = MQTT_TYPE_UINT_8 },
1454 + { .id = MQTT_PROP_SUB_ID_AVAIL, .name = MQTT_PROP_SUB_ID_AVAIL_NAME, .datatype = MQTT_TYPE_UINT_8 },
1455 + { .id = MQTT_PROP_SHARED_SUB_AVAIL, .name = MQTT_PROP_SHARED_SUB_AVAIL_NAME, .datatype = MQTT_TYPE_UINT_8 },
1456 + { .id = 0, .name = NULL, .datatype = MQTT_TYPE_UNKNOWN }
1457 +};
1458 +
1459 +static int get_property_type_by_id(uint8_t property_id) {
1460 + for (int i = 0; mqtt_property_types[i].datatype != MQTT_TYPE_UNKNOWN; i++) {
1461 + if (mqtt_property_types[i].id == property_id)
1462 + return mqtt_property_types[i].datatype;
1463 + }
1464 + return MQTT_TYPE_UNKNOWN;
1465 +}
1466 +
1467 +struct mqtt_property *get_property_by_id(struct mqtt_property *props, uint8_t property_id)
1468 +{
1469 + while (props) {
1470 + if (props->id == property_id) {
1471 + return props;
1472 + }
1473 + props = props->next;
1474 + }
1475 + return NULL;
1476 +}
1477 +
1478 +// Parses [MQTT-2.2.2]
1479 +static int parse_properties_array(struct mqtt_properties_parser_ctx *ctx, rbuf_t data, mqtt_wss_log_ctx_t log)
1480 +{
1481 + int rc;
1482 + switch (ctx->state) {
1483 + case PROPERTIES_LENGTH:
1484 + rc = vbi_parser_parse(&ctx->vbi_parser_ctx, data, log);
1485 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1486 + ctx->properties_length = ctx->vbi_parser_ctx.result;
1487 + ctx->bytes_consumed += ctx->vbi_parser_ctx.bytes;
1488 + ctx->vbi_length = ctx->vbi_parser_ctx.bytes;
1489 + if (!ctx->properties_length)
1490 + return MQTT_NG_CLIENT_PARSE_DONE;
1491 + ctx->state = PROPERTY_CREATE;
1492 + break;
1493 + }
1494 + return rc;
1495 + case PROPERTY_CREATE:
1496 + BUF_READ_CHECK_AT_LEAST(data, 1);
1497 + struct mqtt_property *prop = mw_calloc(1, sizeof(struct mqtt_property));
1498 + if (ctx->head == NULL) {
1499 + ctx->head = prop;
1500 + ctx->tail = prop;
1501 + } else {
1502 + ctx->tail->next = prop;
1503 + ctx->tail = ctx->tail->next;
1504 + }
1505 + ctx->state = PROPERTY_ID;
1506 + /* FALLTHROUGH */
1507 + case PROPERTY_ID:
1508 + rbuf_pop(data, (char*)&ctx->tail->id, 1);
1509 + ctx->bytes_consumed += 1;
1510 + ctx->tail->type = get_property_type_by_id(ctx->tail->id);
1511 + switch (ctx->tail->type) {
1512 + case MQTT_TYPE_UINT_16:
1513 + ctx->state = PROPERTY_TYPE_UINT16;
1514 + break;
1515 + case MQTT_TYPE_UINT_32:
1516 + ctx->state = PROPERTY_TYPE_UINT32;
1517 + break;
1518 + case MQTT_TYPE_UINT_8:
1519 + ctx->state = PROPERTY_TYPE_UINT8;
1520 + break;
1521 + case MQTT_TYPE_VBI:
1522 + ctx->state = PROPERTY_TYPE_VBI;
1523 + vbi_parser_reset_ctx(&ctx->vbi_parser_ctx);
1524 + break;
1525 + case MQTT_TYPE_STR:
1526 + case MQTT_TYPE_STR_PAIR:
1527 + ctx->str_idx = 0;
1528 + /* FALLTHROUGH */
1529 + case MQTT_TYPE_BIN:
1530 + ctx->state = PROPERTY_TYPE_STR_BIN_LEN;
1531 + break;
1532 + default:
1533 + mws_error(log, "Unsupported property type %d for property id %d.", (int)ctx->tail->type, (int)ctx->tail->id);
1534 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
1535 + }
1536 + break;
1537 + case PROPERTY_TYPE_STR_BIN_LEN:
1538 + BUF_READ_CHECK_AT_LEAST(data, sizeof(uint16_t));
1539 + rbuf_pop(data, (char*)&ctx->tail->bindata_len, sizeof(uint16_t));
1540 + ctx->tail->bindata_len = be16toh(ctx->tail->bindata_len);
1541 + ctx->bytes_consumed += 2;
1542 + switch (ctx->tail->type) {
1543 + case MQTT_TYPE_BIN:
1544 + ctx->state = PROPERTY_TYPE_BIN;
1545 + break;
1546 + case MQTT_TYPE_STR:
1547 + case MQTT_TYPE_STR_PAIR:
1548 + ctx->state = PROPERTY_TYPE_STR;
1549 + break;
1550 + default:
1551 + mws_error(log, "Unexpected datatype in PROPERTY_TYPE_STR_BIN_LEN %d", (int)ctx->tail->type);
1552 + return MQTT_NG_CLIENT_INTERNAL_ERROR;
1553 + }
1554 + break;
1555 + case PROPERTY_TYPE_STR:
1556 + BUF_READ_CHECK_AT_LEAST(data, ctx->tail->bindata_len);
1557 + ctx->tail->data.strings[ctx->str_idx] = mw_malloc(ctx->tail->bindata_len + 1);
1558 + rbuf_pop(data, ctx->tail->data.strings[ctx->str_idx], ctx->tail->bindata_len);
1559 + ctx->tail->data.strings[ctx->str_idx][ctx->tail->bindata_len] = 0;
1560 + ctx->str_idx++;
1561 + ctx->bytes_consumed += ctx->tail->bindata_len;
1562 + if (ctx->tail->type == MQTT_TYPE_STR_PAIR && ctx->str_idx < 2) {
1563 + ctx->state = PROPERTY_TYPE_STR_BIN_LEN;
1564 + break;
1565 + }
1566 + ctx->state = PROPERTY_NEXT;
1567 + break;
1568 + case PROPERTY_TYPE_BIN:
1569 + BUF_READ_CHECK_AT_LEAST(data, ctx->tail->bindata_len);
1570 + ctx->tail->data.bindata = mw_malloc(ctx->tail->bindata_len);
1571 + rbuf_pop(data, ctx->tail->data.bindata, ctx->tail->bindata_len);
1572 + ctx->bytes_consumed += ctx->tail->bindata_len;
1573 + ctx->state = PROPERTY_NEXT;
1574 + break;
1575 + case PROPERTY_TYPE_VBI:
1576 + rc = vbi_parser_parse(&ctx->vbi_parser_ctx, data, log);
1577 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1578 + ctx->tail->data.uint32 = ctx->vbi_parser_ctx.result;
1579 + ctx->bytes_consumed += ctx->vbi_parser_ctx.bytes;
1580 + ctx->state = PROPERTY_NEXT;
1581 + break;
1582 + }
1583 + return rc;
1584 + case PROPERTY_TYPE_UINT8:
1585 + BUF_READ_CHECK_AT_LEAST(data, sizeof(uint8_t));
1586 + rbuf_pop(data, (char*)&ctx->tail->data.uint8, sizeof(uint8_t));
1587 + ctx->bytes_consumed += sizeof(uint8_t);
1588 + ctx->state = PROPERTY_NEXT;
1589 + break;
1590 + case PROPERTY_TYPE_UINT32:
1591 + BUF_READ_CHECK_AT_LEAST(data, sizeof(uint32_t));
1592 + rbuf_pop(data, (char*)&ctx->tail->data.uint32, sizeof(uint32_t));
1593 + ctx->tail->data.uint32 = be32toh(ctx->tail->data.uint32);
1594 + ctx->bytes_consumed += sizeof(uint32_t);
1595 + ctx->state = PROPERTY_NEXT;
1596 + break;
1597 + case PROPERTY_TYPE_UINT16:
1598 + BUF_READ_CHECK_AT_LEAST(data, sizeof(uint16_t));
1599 + rbuf_pop(data, (char*)&ctx->tail->data.uint16, sizeof(uint16_t));
1600 + ctx->tail->data.uint16 = be16toh(ctx->tail->data.uint16);
1601 + ctx->bytes_consumed += sizeof(uint16_t);
1602 + ctx->state = PROPERTY_NEXT;
1603 + /* FALLTHROUGH */
1604 + case PROPERTY_NEXT:
1605 + if (ctx->properties_length > ctx->bytes_consumed - ctx->vbi_length) {
1606 + ctx->state = PROPERTY_CREATE;
1607 + break;
1608 + } else
1609 + return MQTT_NG_CLIENT_PARSE_DONE;
1610 + }
1611 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1612 +}
1613 +
1614 +static int parse_connack_varhdr(struct mqtt_ng_client *client)
1615 +{
1616 + struct mqtt_ng_parser *parser = &client->parser;
1617 + switch (parser->varhdr_state) {
1618 + case MQTT_PARSE_VARHDR_INITIAL:
1619 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 2);
1620 + rbuf_pop(parser->received_data, (char*)&parser->mqtt_packet.connack.flags, 1);
1621 + rbuf_pop(parser->received_data, (char*)&parser->mqtt_packet.connack.reason_code, 1);
1622 + parser->varhdr_state = MQTT_PARSE_VARHDR_PROPS;
1623 + mqtt_properties_parser_ctx_reset(&parser->properties_parser);
1624 + break;
1625 + case MQTT_PARSE_VARHDR_PROPS:
1626 + return parse_properties_array(&parser->properties_parser, parser->received_data, client->log);
1627 + default:
1628 + ERROR("invalid state for connack varhdr parser");
1629 + return MQTT_NG_CLIENT_INTERNAL_ERROR;
1630 + }
1631 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1632 +}
1633 +
1634 +static int parse_disconnect_varhdr(struct mqtt_ng_client *client)
1635 +{
1636 + struct mqtt_ng_parser *parser = &client->parser;
1637 + switch (parser->varhdr_state) {
1638 + case MQTT_PARSE_VARHDR_INITIAL:
1639 + if (!parser->mqtt_fixed_hdr_remaining_length) {
1640 + // [MQTT-3.14.2.1] if reason code omitted act same as == 0
1641 + parser->mqtt_packet.disconnect.reason_code = 0;
1642 + return MQTT_NG_CLIENT_PARSE_DONE;
1643 + }
1644 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 1);
1645 + rbuf_pop(parser->received_data, (char*)&parser->mqtt_packet.connack.reason_code, 1);
1646 + if (parser->mqtt_fixed_hdr_remaining_length == 1)
1647 + return MQTT_NG_CLIENT_PARSE_DONE;
1648 + parser->varhdr_state = MQTT_PARSE_VARHDR_PROPS;
1649 + mqtt_properties_parser_ctx_reset(&parser->properties_parser);
1650 + break;
1651 + case MQTT_PARSE_VARHDR_PROPS:
1652 + return parse_properties_array(&parser->properties_parser, parser->received_data, client->log);
1653 + default:
1654 + ERROR("invalid state for connack varhdr parser");
1655 + return MQTT_NG_CLIENT_INTERNAL_ERROR;
1656 + }
1657 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1658 +}
1659 +
1660 +static int parse_puback_varhdr(struct mqtt_ng_client *client)
1661 +{
1662 + struct mqtt_ng_parser *parser = &client->parser;
1663 + switch (parser->varhdr_state) {
1664 + case MQTT_PARSE_VARHDR_INITIAL:
1665 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 2);
1666 + rbuf_pop(parser->received_data, (char*)&parser->mqtt_packet.puback.packet_id, 2);
1667 + parser->mqtt_packet.puback.packet_id = be16toh(parser->mqtt_packet.puback.packet_id);
1668 + if (parser->mqtt_fixed_hdr_remaining_length < 3) {
1669 + // [MQTT-3.4.2.1] if length is not big enough for reason code
1670 + // it is omitted and handled same as if it was present and == 0
1671 + // initially missed this detail and was wondering WTF is going on (sigh)
1672 + parser->mqtt_packet.puback.reason_code = 0;
1673 + return MQTT_NG_CLIENT_PARSE_DONE;
1674 + }
1675 + parser->varhdr_state = MQTT_PARSE_VARHDR_OPTIONAL_REASON_CODE;
1676 + /* FALLTHROUGH */
1677 + case MQTT_PARSE_VARHDR_OPTIONAL_REASON_CODE:
1678 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 1);
1679 + rbuf_pop(parser->received_data, (char*)&parser->mqtt_packet.puback.reason_code, 1);
1680 + // LOL so in CONNACK you have to have 0 byte to
1681 + // signify empty properties list
1682 + // but in PUBACK it can be omitted if remaining length doesn't allow it (sigh)
1683 + if (parser->mqtt_fixed_hdr_remaining_length < 4)
1684 + return MQTT_NG_CLIENT_PARSE_DONE;
1685 +
1686 + parser->varhdr_state = MQTT_PARSE_VARHDR_PROPS;
1687 + mqtt_properties_parser_ctx_reset(&parser->properties_parser);
1688 + /* FALLTHROUGH */
1689 + case MQTT_PARSE_VARHDR_PROPS:
1690 + return parse_properties_array(&parser->properties_parser, parser->received_data, client->log);
1691 + default:
1692 + ERROR("invalid state for puback varhdr parser");
1693 + return MQTT_NG_CLIENT_INTERNAL_ERROR;
1694 + }
1695 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1696 +}
1697 +
1698 +static int parse_suback_varhdr(struct mqtt_ng_client *client)
1699 +{
1700 + int rc;
1701 + size_t avail;
1702 + struct mqtt_ng_parser *parser = &client->parser;
1703 + struct mqtt_suback *suback = &client->parser.mqtt_packet.suback;
1704 + switch (parser->varhdr_state) {
1705 + case MQTT_PARSE_VARHDR_INITIAL:
1706 + suback->reason_codes = NULL;
1707 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 2);
1708 + rbuf_pop(parser->received_data, (char*)&suback->packet_id, 2);
1709 + suback->packet_id = be16toh(suback->packet_id);
1710 + parser->varhdr_state = MQTT_PARSE_VARHDR_PROPS;
1711 + parser->mqtt_parsed_len = 2;
1712 + mqtt_properties_parser_ctx_reset(&parser->properties_parser);
1713 + /* FALLTHROUGH */
1714 + case MQTT_PARSE_VARHDR_PROPS:
1715 + rc = parse_properties_array(&parser->properties_parser, parser->received_data, client->log);
1716 + if (rc != MQTT_NG_CLIENT_PARSE_DONE)
1717 + return rc;
1718 + parser->mqtt_parsed_len += parser->properties_parser.bytes_consumed;
1719 + suback->reason_code_count = parser->mqtt_fixed_hdr_remaining_length - parser->mqtt_parsed_len;
1720 + suback->reason_codes = mw_calloc(suback->reason_code_count, sizeof(*suback->reason_codes));
1721 + suback->reason_codes_pending = suback->reason_code_count;
1722 + parser->varhdr_state = MQTT_PARSE_REASONCODES;
1723 + /* FALLTHROUGH */
1724 + case MQTT_PARSE_REASONCODES:
1725 + avail = rbuf_bytes_available(parser->received_data);
1726 + if (avail < 1)
1727 + return MQTT_NG_CLIENT_NEED_MORE_BYTES;
1728 +
1729 + suback->reason_codes_pending -= rbuf_pop(parser->received_data, (char*)suback->reason_codes, MIN(suback->reason_codes_pending, avail));
1730 +
1731 + if (!suback->reason_codes_pending)
1732 + return MQTT_NG_CLIENT_PARSE_DONE;
1733 +
1734 + return MQTT_NG_CLIENT_NEED_MORE_BYTES;
1735 + default:
1736 + ERROR("invalid state for suback varhdr parser");
1737 + return MQTT_NG_CLIENT_INTERNAL_ERROR;
1738 + }
1739 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1740 +}
1741 +
1742 +static int parse_publish_varhdr(struct mqtt_ng_client *client)
1743 +{
1744 + int rc;
1745 + struct mqtt_ng_parser *parser = &client->parser;
1746 + struct mqtt_publish *publish = &client->parser.mqtt_packet.publish;
1747 + switch (parser->varhdr_state) {
1748 + case MQTT_PARSE_VARHDR_INITIAL:
1749 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 2);
1750 + publish->topic = NULL;
1751 + publish->qos = ((parser->mqtt_control_packet_type >> 1) & 0x03);
1752 + rbuf_pop(parser->received_data, (char*)&publish->topic_len, 2);
1753 + publish->topic_len = be16toh(publish->topic_len);
1754 + parser->mqtt_parsed_len = 2;
1755 + if (!publish->topic_len) {
1756 + parser->varhdr_state = MQTT_PARSE_VARHDR_POST_TOPICNAME;
1757 + break;
1758 + }
1759 + publish->topic = mw_calloc(1, publish->topic_len + 1 /* add 0x00 */);
1760 + if (publish->topic == NULL)
1761 + return MQTT_NG_CLIENT_OOM;
1762 + parser->varhdr_state = MQTT_PARSE_VARHDR_TOPICNAME;
1763 + /* FALLTHROUGH */
1764 + case MQTT_PARSE_VARHDR_TOPICNAME:
1765 + // TODO check empty topic can be valid? In which case we have to skip this step
1766 + BUF_READ_CHECK_AT_LEAST(parser->received_data, publish->topic_len);
1767 + rbuf_pop(parser->received_data, publish->topic, publish->topic_len);
1768 + parser->mqtt_parsed_len += publish->topic_len;
1769 + parser->varhdr_state = MQTT_PARSE_VARHDR_POST_TOPICNAME;
1770 + /* FALLTHROUGH */
1771 + case MQTT_PARSE_VARHDR_POST_TOPICNAME:
1772 + mqtt_properties_parser_ctx_reset(&parser->properties_parser);
1773 + if (!publish->qos) { // PacketID present only for QOS > 0 [MQTT-3.3.2.2]
1774 + parser->varhdr_state = MQTT_PARSE_VARHDR_PROPS;
1775 + break;
1776 + }
1777 + parser->varhdr_state = MQTT_PARSE_VARHDR_PACKET_ID;
1778 + /* FALLTHROUGH */
1779 + case MQTT_PARSE_VARHDR_PACKET_ID:
1780 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 2);
1781 + rbuf_pop(parser->received_data, (char*)&publish->packet_id, 2);
1782 + publish->packet_id = be16toh(publish->packet_id);
1783 + parser->varhdr_state = MQTT_PARSE_VARHDR_PROPS;
1784 + parser->mqtt_parsed_len += 2;
1785 + /* FALLTHROUGH */
1786 + case MQTT_PARSE_VARHDR_PROPS:
1787 + rc = parse_properties_array(&parser->properties_parser, parser->received_data, client->log);
1788 + if (rc != MQTT_NG_CLIENT_PARSE_DONE)
1789 + return rc;
1790 + parser->mqtt_parsed_len += parser->properties_parser.bytes_consumed;
1791 + parser->varhdr_state = MQTT_PARSE_PAYLOAD;
1792 + /* FALLTHROUGH */
1793 + case MQTT_PARSE_PAYLOAD:
1794 + if (parser->mqtt_fixed_hdr_remaining_length < parser->mqtt_parsed_len) {
1795 + mw_free(publish->topic);
1796 + publish->topic = NULL;
1797 + ERROR("Error parsing PUBLISH message");
1798 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
1799 + }
1800 + publish->data_len = parser->mqtt_fixed_hdr_remaining_length - parser->mqtt_parsed_len;
1801 + if (!publish->data_len) {
1802 + publish->data = NULL;
1803 + return MQTT_NG_CLIENT_PARSE_DONE; // 0 length payload is OK [MQTT-3.3.3]
1804 + }
1805 + BUF_READ_CHECK_AT_LEAST(parser->received_data, publish->data_len);
1806 +
1807 + publish->data = mw_malloc(publish->data_len);
1808 + if (publish->data == NULL) {
1809 + mw_free(publish->topic);
1810 + publish->topic = NULL;
1811 + return MQTT_NG_CLIENT_OOM;
1812 + }
1813 +
1814 + rbuf_pop(parser->received_data, publish->data, publish->data_len);
1815 + parser->mqtt_parsed_len += publish->data_len;
1816 +
1817 + return MQTT_NG_CLIENT_PARSE_DONE;
1818 + default:
1819 + ERROR("invalid state for publish varhdr parser");
1820 + return MQTT_NG_CLIENT_INTERNAL_ERROR;
1821 + }
1822 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1823 +}
1824 +
1825 +// TODO move to separate file, dont send whole client pointer just to be able
1826 +// to access LOG context send parser only which should include log
1827 +static int parse_data(struct mqtt_ng_client *client)
1828 +{
1829 + int rc;
1830 + struct mqtt_ng_parser *parser = &client->parser;
1831 + switch(parser->state) {
1832 + case MQTT_PARSE_FIXED_HEADER_PACKET_TYPE:
1833 + BUF_READ_CHECK_AT_LEAST(parser->received_data, 1);
1834 + rbuf_pop(parser->received_data, (char*)&parser->mqtt_control_packet_type, 1);
1835 + vbi_parser_reset_ctx(&parser->vbi_parser);
1836 + parser->state = MQTT_PARSE_FIXED_HEADER_LEN;
1837 + break;
1838 + case MQTT_PARSE_FIXED_HEADER_LEN:
1839 + rc = vbi_parser_parse(&parser->vbi_parser, parser->received_data, client->log);
1840 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1841 + parser->mqtt_fixed_hdr_remaining_length = parser->vbi_parser.result;
1842 + parser->state = MQTT_PARSE_VARIABLE_HEADER;
1843 + parser->varhdr_state = MQTT_PARSE_VARHDR_INITIAL;
1844 + break;
1845 + }
1846 + return rc;
1847 + case MQTT_PARSE_VARIABLE_HEADER:
1848 + switch (get_control_packet_type(parser->mqtt_control_packet_type)) {
1849 + case MQTT_CPT_CONNACK:
1850 + rc = parse_connack_varhdr(client);
1851 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1852 + parser->state = MQTT_PARSE_MQTT_PACKET_DONE;
1853 + break;
1854 + }
1855 + return rc;
1856 + case MQTT_CPT_PUBACK:
1857 + rc = parse_puback_varhdr(client);
1858 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1859 + parser->state = MQTT_PARSE_MQTT_PACKET_DONE;
1860 + break;
1861 + }
1862 + return rc;
1863 + case MQTT_CPT_SUBACK:
1864 + rc = parse_suback_varhdr(client);
1865 + if (rc != MQTT_NG_CLIENT_NEED_MORE_BYTES && rc != MQTT_NG_CLIENT_OK_CALL_AGAIN) {
1866 + mw_free(parser->mqtt_packet.suback.reason_codes);
1867 + }
1868 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1869 + parser->state = MQTT_PARSE_MQTT_PACKET_DONE;
1870 + break;
1871 + }
1872 + return rc;
1873 + case MQTT_CPT_PUBLISH:
1874 + rc = parse_publish_varhdr(client);
1875 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1876 + parser->state = MQTT_PARSE_MQTT_PACKET_DONE;
1877 + break;
1878 + }
1879 + return rc;
1880 + case MQTT_CPT_PINGRESP:
1881 + if (parser->mqtt_fixed_hdr_remaining_length) {
1882 + ERROR ("PINGRESP has to be 0 Remaining Length."); // [MQTT-3.13.1]
1883 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
1884 + }
1885 + parser->state = MQTT_PARSE_MQTT_PACKET_DONE;
1886 + break;
1887 + case MQTT_CPT_DISCONNECT:
1888 + rc = parse_disconnect_varhdr(client);
1889 + if (rc == MQTT_NG_CLIENT_PARSE_DONE) {
1890 + parser->state = MQTT_PARSE_MQTT_PACKET_DONE;
1891 + break;
1892 + }
1893 + return rc;
1894 + default:
1895 + ERROR("Parsing Control Packet Type %" PRIu8 " not implemented yet.", get_control_packet_type(parser->mqtt_control_packet_type));
1896 + rbuf_bump_tail(parser->received_data, parser->mqtt_fixed_hdr_remaining_length);
1897 + parser->state = MQTT_PARSE_MQTT_PACKET_DONE;
1898 + return MQTT_NG_CLIENT_NOT_IMPL_YET;
1899 + }
1900 + // we could also return MQTT_NG_CLIENT_OK_CALL_AGAIN
1901 + // and be called again later
1902 + /* FALLTHROUGH */
1903 + case MQTT_PARSE_MQTT_PACKET_DONE:
1904 + parser->state = MQTT_PARSE_FIXED_HEADER_PACKET_TYPE;
1905 + return MQTT_NG_CLIENT_MQTT_PACKET_DONE;
1906 + }
1907 + return MQTT_NG_CLIENT_OK_CALL_AGAIN;
1908 +}
1909 +
1910 +// set next MQTT fragment to send
1911 +// return 1 if nothing to send
1912 +// return -1 on error
1913 +// return 0 if there is fragment set
1914 +static int mqtt_ng_next_to_send(struct mqtt_ng_client *client) {
1915 + if (client->client_state == CONNECT_PENDING) {
1916 + client->main_buffer.sending_frag = client->connect_msg;
1917 + client->client_state = CONNECTING;
1918 + return 0;
1919 + }
1920 + if (client->client_state != CONNECTED)
1921 + return -1;
1922 +
1923 + struct buffer_fragment *frag = BUFFER_FIRST_FRAG(&client->main_buffer.hdr_buffer);
1924 + while (frag) {
1925 + if ( frag->sent != frag->len )
1926 + break;
1927 + frag = frag->next;
1928 + }
1929 +
1930 + if ( client->ping_pending && (!frag || (frag->flags & BUFFER_FRAG_MQTT_PACKET_HEAD && frag->sent == 0)) ) {
1931 + client->ping_pending = 0;
1932 + ping_frag.sent = 0;
1933 + client->main_buffer.sending_frag = &ping_frag;
1934 + return 0;
1935 + }
1936 +
1937 + client->main_buffer.sending_frag = frag;
1938 + return frag == NULL ? 1 : 0;
1939 +}
1940 +
1941 +// send current fragment
1942 +// return 0 if whole remaining length could be sent as a whole
1943 +// return -1 if send buffer was filled and
1944 +// nothing could be written anymore
1945 +// return 1 if last fragment of a message was fully sent
1946 +static int send_fragment(struct mqtt_ng_client *client) {
1947 + struct buffer_fragment *frag = client->main_buffer.sending_frag;
1948 +
1949 + // for readability
1950 + char *ptr = frag->data + frag->sent;
1951 + size_t bytes = frag->len - frag->sent;
1952 +
1953 + size_t processed = 0;
1954 +
1955 + if (bytes)
1956 + processed = client->send_fnc_ptr(client->user_ctx, ptr, bytes);
1957 + else
1958 + WARN("This fragment was fully sent already. This should not happen!");
1959 +
1960 + frag->sent += processed;
1961 + if (frag->sent != frag->len)
1962 + return -1;
1963 +
1964 + if (frag->flags & BUFFER_FRAG_MQTT_PACKET_TAIL) {
1965 + client->time_of_last_send = time(NULL);
1966 + pthread_mutex_lock(&client->stats_mutex);
1967 + if (client->main_buffer.sending_frag != &ping_frag)
1968 + client->stats.tx_messages_queued--;
1969 + client->stats.tx_messages_sent++;
1970 + pthread_mutex_unlock(&client->stats_mutex);
1971 + client->main_buffer.sending_frag = NULL;
1972 + return 1;
1973 + }
1974 +
1975 + client->main_buffer.sending_frag = frag->next;
1976 +
1977 + return 0;
1978 +}
1979 +
1980 +// attempt sending all fragments of current single MQTT packet
1981 +static int send_all_message_fragments(struct mqtt_ng_client *client) {
1982 + int rc;
1983 + while ( !(rc = send_fragment(client)) );
1984 + return rc;
1985 +}
1986 +
1987 +static void try_send_all(struct mqtt_ng_client *client) {
1988 + do {
1989 + if (client->main_buffer.sending_frag == NULL && mqtt_ng_next_to_send(client))
1990 + return;
1991 + } while(send_all_message_fragments(client) >= 0);
1992 +}
1993 +
1994 +static inline void mark_message_for_gc(struct buffer_fragment *frag)
1995 +{
1996 + while (frag) {
1997 + frag->flags |= BUFFER_FRAG_GARBAGE_COLLECT;
1998 + buffer_frag_free_data(frag);
1999 + if (frag->flags & BUFFER_FRAG_MQTT_PACKET_TAIL)
2000 + return;
2001 + frag = frag->next;
2002 + }
2003 +}
2004 +
2005 +static int mark_packet_acked(struct mqtt_ng_client *client, uint16_t packet_id)
2006 +{
2007 + LOCK_HDR_BUFFER(&client->main_buffer);
2008 + struct buffer_fragment *frag = BUFFER_FIRST_FRAG(&client->main_buffer.hdr_buffer);
2009 + while (frag) {
2010 + if ( (frag->flags & BUFFER_FRAG_MQTT_PACKET_HEAD) && frag->packet_id == packet_id) {
2011 + if (!frag->sent) {
2012 + ERROR("Received packet_id (%" PRIu16 ") belongs to MQTT packet which was not yet sent!", packet_id);
2013 + UNLOCK_HDR_BUFFER(&client->main_buffer);
2014 + return 1;
2015 + }
2016 + mark_message_for_gc(frag);
2017 + UNLOCK_HDR_BUFFER(&client->main_buffer);
2018 + return 0;
2019 + }
2020 + frag = frag->next;
2021 + }
2022 + ERROR("Received packet_id (%" PRIu16 ") is unknown!", packet_id);
2023 + UNLOCK_HDR_BUFFER(&client->main_buffer);
2024 + return 1;
2025 +}
2026 +
2027 +int handle_incoming_traffic(struct mqtt_ng_client *client)
2028 +{
2029 + int rc;
2030 + struct mqtt_publish *pub;
2031 + while( (rc = parse_data(client)) == MQTT_NG_CLIENT_OK_CALL_AGAIN );
2032 + if ( rc == MQTT_NG_CLIENT_MQTT_PACKET_DONE ) {
2033 + struct mqtt_property *prop;
2034 +#ifdef MQTT_DEBUG_VERBOSE
2035 + DEBUG("MQTT Packet Parsed Successfully!");
2036 +#endif
2037 + pthread_mutex_lock(&client->stats_mutex);
2038 + client->stats.rx_messages_rcvd++;
2039 + pthread_mutex_unlock(&client->stats_mutex);
2040 +
2041 + switch (get_control_packet_type(client->parser.mqtt_control_packet_type)) {
2042 + case MQTT_CPT_CONNACK:
2043 +#ifdef MQTT_DEBUG_VERBOSE
2044 + DEBUG("Received CONNACK");
2045 +#endif
2046 + LOCK_HDR_BUFFER(&client->main_buffer);
2047 + mark_message_for_gc(client->connect_msg);
2048 + UNLOCK_HDR_BUFFER(&client->main_buffer);
2049 + client->connect_msg = NULL;
2050 + if (client->client_state != CONNECTING) {
2051 + ERROR("Received unexpected CONNACK");
2052 + client->client_state = ERROR;
2053 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
2054 + }
2055 + if ((prop = get_property_by_id(client->parser.properties_parser.head, MQTT_PROP_MAX_PKT_SIZE)) != NULL) {
2056 + INFO("MQTT server limits message size to %" PRIu32, prop->data.uint32);
2057 + client->max_msg_size = prop->data.uint32;
2058 + }
2059 + if (client->connack_callback)
2060 + client->connack_callback(client->user_ctx, client->parser.mqtt_packet.connack.reason_code);
2061 + if (!client->parser.mqtt_packet.connack.reason_code) {
2062 + INFO("MQTT Connection Accepted By Server");
2063 + client->client_state = CONNECTED;
2064 + break;
2065 + }
2066 + client->client_state = ERROR;
2067 + return MQTT_NG_CLIENT_SERVER_RETURNED_ERROR;
2068 + case MQTT_CPT_PUBACK:
2069 +#ifdef MQTT_DEBUG_VERBOSE
2070 + DEBUG("Received PUBACK %" PRIu16, client->parser.mqtt_packet.puback.packet_id);
2071 +#endif
2072 + if (mark_packet_acked(client, client->parser.mqtt_packet.puback.packet_id))
2073 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
2074 + if (client->puback_callback)
2075 + client->puback_callback(client->parser.mqtt_packet.puback.packet_id);
2076 + break;
2077 + case MQTT_CPT_PINGRESP:
2078 +#ifdef MQTT_DEBUG_VERBOSE
2079 + DEBUG("Received PINGRESP");
2080 +#endif
2081 + break;
2082 + case MQTT_CPT_SUBACK:
2083 +#ifdef MQTT_DEBUG_VERBOSE
2084 + DEBUG("Received SUBACK %" PRIu16, client->parser.mqtt_packet.suback.packet_id);
2085 +#endif
2086 + if (mark_packet_acked(client, client->parser.mqtt_packet.suback.packet_id))
2087 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
2088 + break;
2089 + case MQTT_CPT_PUBLISH:
2090 +#ifdef MQTT_DEBUG_VERBOSE
2091 + DEBUG("Recevied PUBLISH");
2092 +#endif
2093 + pub = &client->parser.mqtt_packet.publish;
2094 + if (pub->qos > 1) {
2095 + mw_free(pub->topic);
2096 + mw_free(pub->data);
2097 + return MQTT_NG_CLIENT_NOT_IMPL_YET;
2098 + }
2099 + if ( pub->qos == 1 && (rc = mqtt_ng_puback(client, pub->packet_id, 0)) ) {
2100 + client->client_state = ERROR;
2101 + ERROR("Error generating PUBACK reply for PUBLISH");
2102 + return rc;
2103 + }
2104 + if ( (prop = get_property_by_id(client->parser.properties_parser.head, MQTT_PROP_TOPIC_ALIAS)) != NULL ) {
2105 + // Topic Alias property was sent from server
2106 + void *topic_ptr;
2107 + if (!c_rhash_get_ptr_by_uint64(client->rx_aliases, prop->data.uint8, &topic_ptr)) {
2108 + if (pub->topic != NULL) {
2109 + ERROR("We do not yet support topic alias reassignment");
2110 + return MQTT_NG_CLIENT_NOT_IMPL_YET;
2111 + }
2112 + pub->topic = topic_ptr;
2113 + } else {
2114 + if (pub->topic == NULL) {
2115 + ERROR("Topic alias with id %d unknown and topic not set by server!", prop->data.uint8);
2116 + return MQTT_NG_CLIENT_PROTOCOL_ERROR;
2117 + }
2118 + c_rhash_insert_uint64_ptr(client->rx_aliases, prop->data.uint8, pub->topic);
2119 + }
2120 + }
2121 + if (client->msg_callback)
2122 + client->msg_callback(pub->topic, pub->data, pub->data_len, pub->qos);
2123 + // in case we have property topic alias and we have topic we take over the string
2124 + // and add pointer to it into topic alias list
2125 + if (prop == NULL)
2126 + mw_free(pub->topic);
2127 + mw_free(pub->data);
2128 + return MQTT_NG_CLIENT_WANT_WRITE;
2129 + case MQTT_CPT_DISCONNECT:
2130 + INFO ("Got MQTT DISCONNECT control packet from server. Reason code: %d", (int)client->parser.mqtt_packet.disconnect.reason_code);
2131 + client->client_state = DISCONNECTED;
2132 + break;
2133 + }
2134 + }
2135 +
2136 + return rc;
2137 +}
2138 +
2139 +int mqtt_ng_sync(struct mqtt_ng_client *client)
2140 +{
2141 + if (client->client_state == RAW || client->client_state == DISCONNECTED)
2142 + return 0;
2143 +
2144 + if (client->client_state == ERROR)
2145 + return 1;
2146 +
2147 + LOCK_HDR_BUFFER(&client->main_buffer);
2148 + try_send_all(client);
2149 + UNLOCK_HDR_BUFFER(&client->main_buffer);
2150 +
2151 + int rc;
2152 +
2153 + while ((rc = handle_incoming_traffic(client)) != MQTT_NG_CLIENT_NEED_MORE_BYTES) {
2154 + if (rc < 0)
2155 + break;
2156 + if (rc == MQTT_NG_CLIENT_WANT_WRITE) {
2157 + LOCK_HDR_BUFFER(&client->main_buffer);
2158 + try_send_all(client);
2159 + UNLOCK_HDR_BUFFER(&client->main_buffer);
2160 + }
2161 + }
2162 +
2163 + if (rc < 0)
2164 + return rc;
2165 +
2166 + return 0;
2167 +}
2168 +
2169 +time_t mqtt_ng_last_send_time(struct mqtt_ng_client *client)
2170 +{
2171 + return client->time_of_last_send;
2172 +}
2173 +
2174 +void mqtt_ng_set_max_mem(struct mqtt_ng_client *client, size_t bytes)
2175 +{
2176 + client->max_mem_bytes = bytes;
2177 +}
2178 +
2179 +void mqtt_ng_get_stats(struct mqtt_ng_client *client, struct mqtt_ng_stats *stats)
2180 +{
2181 + pthread_mutex_lock(&client->stats_mutex);
2182 + memcpy(stats, &client->stats, sizeof(struct mqtt_ng_stats));
2183 + pthread_mutex_unlock(&client->stats_mutex);
2184 +
2185 + stats->tx_bytes_queued = 0;
2186 + stats->tx_buffer_reclaimable = 0;
2187 +
2188 + LOCK_HDR_BUFFER(&client->main_buffer);
2189 + stats->tx_buffer_used = BUFFER_BYTES_USED(&client->main_buffer.hdr_buffer);
2190 + stats->tx_buffer_free = BUFFER_BYTES_AVAILABLE(&client->main_buffer.hdr_buffer);
2191 + stats->tx_buffer_size = client->main_buffer.hdr_buffer.size;
2192 + struct buffer_fragment *frag = BUFFER_FIRST_FRAG(&client->main_buffer.hdr_buffer);
2193 + while (frag) {
2194 + stats->tx_bytes_queued += frag->len - frag->sent;
2195 + if (frag_is_marked_for_gc(frag))
2196 + stats->tx_buffer_reclaimable += FRAG_SIZE_IN_BUFFER(frag);
2197 +
2198 + frag = frag->next;
2199 + }
2200 + UNLOCK_HDR_BUFFER(&client->main_buffer);
2201 +}
2202 +
2203 +int mqtt_ng_set_topic_alias(struct mqtt_ng_client *client, const char *topic)
2204 +{
2205 + uint16_t idx;
2206 + pthread_rwlock_wrlock(&client->tx_topic_aliases.rwlock);
2207 +
2208 + if (client->tx_topic_aliases.idx_assigned >= client->tx_topic_aliases.idx_max) {
2209 + pthread_rwlock_unlock(&client->tx_topic_aliases.rwlock);
2210 + mws_error(client->log, "Tx topic alias indexes were exhausted (current version of the library doesn't support reassigning yet. Feel free to contribute.");
2211 + return 0; //0 is not a valid topic alias
2212 + }
2213 +
2214 + struct topic_alias_data *alias;
2215 + if (!c_rhash_get_ptr_by_str(client->tx_topic_aliases.stoi_dict, topic, (void**)&alias)) {
2216 + // this is not a problem for library but might be helpful to warn user
2217 + // as it might indicate bug in their program (but also might be expected)
2218 + idx = alias->idx;
2219 + pthread_rwlock_unlock(&client->tx_topic_aliases.rwlock);
2220 + mws_debug(client->log, "%s topic \"%s\" already has alias set. Ignoring.", __FUNCTION__, topic);
2221 + return idx;
2222 + }
2223 +
2224 + alias = mw_malloc(sizeof(struct topic_alias_data));
2225 + idx = ++client->tx_topic_aliases.idx_assigned;
2226 + alias->idx = idx;
2227 + __atomic_store_n(&alias->usage_count, 0, __ATOMIC_SEQ_CST);
2228 +
2229 + c_rhash_insert_str_ptr(client->tx_topic_aliases.stoi_dict, topic, (void*)alias);
2230 +
2231 + pthread_rwlock_unlock(&client->tx_topic_aliases.rwlock);
2232 + return idx;
2233 +}
mqtt_websockets/src/mqtt_wss_client.c new
+1138
@@ -0,0 +1,1138 @@
1 +// Copyright (C) 2020 Timotej Šiškovič
2 +// SPDX-License-Identifier: GPL-3.0-only
3 +//
4 +// This program is free software: you can redistribute it and/or modify it
5 +// under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
6 +//
7 +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9 +// See the GNU General Public License for more details.
10 +//
11 +// You should have received a copy of the GNU General Public License along with this program.
12 +// If not, see <https://www.gnu.org/licenses/>.
13 +#define _GNU_SOURCE
14 +
15 +#include "mqtt_wss_client.h"
16 +#include "mqtt_ng.h"
17 +#include "ws_client.h"
18 +#include "common_internal.h"
19 +
20 +#include <stdlib.h>
21 +#include <fcntl.h>
22 +#include <unistd.h>
23 +#include <poll.h>
24 +#include <string.h>
25 +#include <time.h>
26 +
27 +#include <sys/socket.h>
28 +#include <netinet/in.h>
29 +#include <arpa/inet.h>
30 +#include <netinet/tcp.h> //TCP_NODELAY
31 +#include <netdb.h>
32 +
33 +#include <openssl/err.h>
34 +#include <openssl/ssl.h>
35 +
36 +#define PIPE_READ_END 0
37 +#define PIPE_WRITE_END 1
38 +#define POLLFD_SOCKET 0
39 +#define POLLFD_PIPE 1
40 +
41 +#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110) && (SSLEAY_VERSION_NUMBER >= OPENSSL_VERSION_097)
42 +#include <openssl/conf.h>
43 +#endif
44 +
45 +//TODO MQTT_PUBLISH_RETAIN should not be needed anymore
46 +#define MQTT_PUBLISH_RETAIN 0x01
47 +#define MQTT_CONNECT_CLEAN_SESSION 0x02
48 +#define MQTT_CONNECT_WILL_RETAIN 0x20
49 +
50 +char *util_openssl_ret_err(int err)
51 +{
52 + switch(err){
53 + case SSL_ERROR_WANT_READ:
54 + return "SSL_ERROR_WANT_READ";
55 + case SSL_ERROR_WANT_WRITE:
56 + return "SSL_ERROR_WANT_WRITE";
57 + case SSL_ERROR_NONE:
58 + return "SSL_ERROR_NONE";
59 + case SSL_ERROR_ZERO_RETURN:
60 + return "SSL_ERROR_ZERO_RETURN";
61 + case SSL_ERROR_WANT_CONNECT:
62 + return "SSL_ERROR_WANT_CONNECT";
63 + case SSL_ERROR_WANT_ACCEPT:
64 + return "SSL_ERROR_WANT_ACCEPT";
65 + case SSL_ERROR_WANT_X509_LOOKUP:
66 + return "SSL_ERROR_WANT_X509_LOOKUP";
67 +#ifdef SSL_ERROR_WANT_ASYNC
68 + case SSL_ERROR_WANT_ASYNC:
69 + return "SSL_ERROR_WANT_ASYNC";
70 +#endif
71 +#ifdef SSL_ERROR_WANT_ASYNC_JOB
72 + case SSL_ERROR_WANT_ASYNC_JOB:
73 + return "SSL_ERROR_WANT_ASYNC_JOB";
74 +#endif
75 +#ifdef SSL_ERROR_WANT_CLIENT_HELLO_CB
76 + case SSL_ERROR_WANT_CLIENT_HELLO_CB:
77 + return "SSL_ERROR_WANT_CLIENT_HELLO_CB";
78 +#endif
79 + case SSL_ERROR_SYSCALL:
80 + return "SSL_ERROR_SYSCALL";
81 + case SSL_ERROR_SSL:
82 + return "SSL_ERROR_SSL";
83 + }
84 + return "UNKNOWN";
85 +}
86 +
87 +struct mqtt_wss_client_struct {
88 + ws_client *ws_client;
89 +
90 + mqtt_wss_log_ctx_t log;
91 +
92 +// immediate connection (e.g. proxy server)
93 + char *host;
94 + int port;
95 +
96 +// target of connection (e.g. where we want to connect to)
97 + char *target_host;
98 + int target_port;
99 +
100 + enum mqtt_wss_proxy_type proxy_type;
101 + char *proxy_uname;
102 + char *proxy_passwd;
103 +
104 +// nonblock IO related
105 + int sockfd;
106 + int write_notif_pipe[2];
107 + struct pollfd poll_fds[2];
108 +
109 + SSL_CTX *ssl_ctx;
110 + SSL *ssl;
111 + int ssl_flags;
112 +
113 + struct mqtt_ng_client *mqtt;
114 +
115 + int mqtt_keepalive;
116 +
117 + pthread_mutex_t pub_lock;
118 +
119 +// signifies that we didn't write all MQTT wanted
120 +// us to write during last cycle (e.g. due to buffer
121 +// size) and thus we should arm POLLOUT
122 + unsigned int mqtt_didnt_finish_write:1;
123 +
124 + unsigned int mqtt_connected:1;
125 + unsigned int mqtt_disconnecting:1;
126 +
127 +// Application layer callback pointers
128 + void (*msg_callback)(const char *, const void *, size_t, int);
129 + void (*puback_callback)(uint16_t packet_id);
130 +
131 + pthread_mutex_t stat_lock;
132 + struct mqtt_wss_stats stats;
133 +
134 +#ifdef MQTT_WSS_DEBUG
135 + void (*ssl_ctx_keylog_cb)(const SSL *ssl, const char *line);
136 +#endif
137 +};
138 +
139 +static void mws_connack_callback_ng(void *user_ctx, int code)
140 +{
141 + mqtt_wss_client client = user_ctx;
142 + switch(code) {
143 + case 0:
144 + client->mqtt_connected = 1;
145 + return;
146 +//TODO manual labor: all the CONNACK error codes with some nice error message
147 + default:
148 + mws_error(client->log, "MQTT CONNACK returned error %d", code);
149 + return;
150 + }
151 +}
152 +
153 +static ssize_t mqtt_send_cb(void *user_ctx, const void* buf, size_t len)
154 +{
155 + mqtt_wss_client mqtt_wss_client = user_ctx;
156 +#ifdef DEBUG_ULTRA_VERBOSE
157 + mws_debug(mqtt_wss_client->log, "mqtt_pal_sendall(len=%d)", len);
158 +#endif
159 + int ret = ws_client_send(mqtt_wss_client->ws_client, WS_OP_BINARY_FRAME, buf, len);
160 + if (ret >= 0 && (size_t)ret != len) {
161 +#ifdef DEBUG_ULTRA_VERBOSE
162 + mws_debug(mqtt_wss_client->log, "Not complete message sent (Msg=%d,Sent=%d). Need to arm POLLOUT!", len, ret);
163 +#endif
164 + mqtt_wss_client->mqtt_didnt_finish_write = 1;
165 + }
166 + return ret;
167 +}
168 +
169 +mqtt_wss_client mqtt_wss_new(const char *log_prefix,
170 + mqtt_wss_log_callback_t log_callback,
171 + msg_callback_fnc_t msg_callback,
172 + void (*puback_callback)(uint16_t packet_id))
173 +{
174 + mqtt_wss_log_ctx_t log;
175 +
176 + log = mqtt_wss_log_ctx_create(log_prefix, log_callback);
177 + if(!log)
178 + return NULL;
179 +
180 + SSL_library_init();
181 + SSL_load_error_strings();
182 +
183 + mqtt_wss_client client = mw_calloc(1, sizeof(struct mqtt_wss_client_struct));
184 + if (!client) {
185 + mws_error(log, "OOM alocating mqtt_wss_client");
186 + goto fail;
187 + }
188 +
189 + pthread_mutex_init(&client->pub_lock, NULL);
190 + pthread_mutex_init(&client->stat_lock, NULL);
191 +
192 + client->msg_callback = msg_callback;
193 + client->puback_callback = puback_callback;
194 +
195 + client->ws_client = ws_client_new(0, &client->target_host, log);
196 + if (!client->ws_client) {
197 + mws_error(log, "Error creating ws_client");
198 + goto fail_1;
199 + }
200 +
201 + client->log = log;
202 +
203 +#ifdef __APPLE__
204 + if (pipe(client->write_notif_pipe)) {
205 +#else
206 + if (pipe2(client->write_notif_pipe, O_CLOEXEC /*| O_DIRECT*/)) {
207 +#endif
208 + mws_error(log, "Couldn't create pipe");
209 + goto fail_2;
210 + }
211 +
212 + client->poll_fds[POLLFD_PIPE].fd = client->write_notif_pipe[PIPE_READ_END];
213 + client->poll_fds[POLLFD_PIPE].events = POLLIN;
214 +
215 + client->poll_fds[POLLFD_SOCKET].events = POLLIN;
216 +
217 + struct mqtt_ng_init settings = {
218 + .log = log,
219 + .data_in = client->ws_client->buf_to_mqtt,
220 + .data_out_fnc = &mqtt_send_cb,
221 + .user_ctx = client,
222 + .connack_callback = &mws_connack_callback_ng,
223 + .puback_callback = puback_callback,
224 + .msg_callback = msg_callback
225 + };
226 + if ( (client->mqtt = mqtt_ng_init(&settings)) == NULL ) {
227 + mws_error(log, "Error initializing internal MQTT client");
228 + goto fail_3;
229 + }
230 +
231 + return client;
232 +
233 +fail_3:
234 + close(client->write_notif_pipe[PIPE_WRITE_END]);
235 + close(client->write_notif_pipe[PIPE_READ_END]);
236 +fail_2:
237 + ws_client_destroy(client->ws_client);
238 +fail_1:
239 + mw_free(client);
240 +fail:
241 + mqtt_wss_log_ctx_destroy(log);
242 + return NULL;
243 +}
244 +
245 +void mqtt_wss_set_max_buf_size(mqtt_wss_client client, size_t size)
246 +{
247 + mqtt_ng_set_max_mem(client->mqtt, size);
248 +}
249 +
250 +void mqtt_wss_destroy(mqtt_wss_client client)
251 +{
252 + mqtt_ng_destroy(client->mqtt);
253 +
254 + close(client->write_notif_pipe[PIPE_WRITE_END]);
255 + close(client->write_notif_pipe[PIPE_READ_END]);
256 +
257 + ws_client_destroy(client->ws_client);
258 +
259 + // deleted after client->ws_client
260 + // as it "borrows" this pointer and might use it
261 + if (client->target_host == client->host)
262 + client->target_host = NULL;
263 + if (client->target_host)
264 + mw_free(client->target_host);
265 + if (client->host)
266 + mw_free(client->host);
267 + mw_free(client->proxy_passwd);
268 + mw_free(client->proxy_uname);
269 +
270 + if (client->ssl)
271 + SSL_free(client->ssl);
272 +
273 + if (client->ssl_ctx)
274 + SSL_CTX_free(client->ssl_ctx);
275 +
276 + if (client->sockfd > 0)
277 + close(client->sockfd);
278 +
279 + pthread_mutex_destroy(&client->pub_lock);
280 + pthread_mutex_destroy(&client->stat_lock);
281 +
282 + mqtt_wss_log_ctx_destroy(client->log);
283 + mw_free(client);
284 +}
285 +
286 +static int cert_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
287 +{
288 + SSL *ssl;
289 + X509 *err_cert;
290 + mqtt_wss_client client;
291 + int err = 0, depth;
292 + char *err_str;
293 +
294 + ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
295 + client = SSL_get_ex_data(ssl, 0);
296 +
297 + // TODO handle depth as per https://www.openssl.org/docs/man1.0.2/man3/SSL_CTX_set_verify.html
298 +
299 + if (!preverify_ok) {
300 + err = X509_STORE_CTX_get_error(ctx);
301 + depth = X509_STORE_CTX_get_error_depth(ctx);
302 + err_cert = X509_STORE_CTX_get_current_cert(ctx);
303 + err_str = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
304 +
305 + mws_error(client->log, "verify error:num=%d:%s:depth=%d:%s", err,
306 + X509_verify_cert_error_string(err), depth, err_str);
307 +
308 + mw_free(err_str);
309 + }
310 +
311 + if (!preverify_ok && err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
312 + client->ssl_flags & MQTT_WSS_SSL_ALLOW_SELF_SIGNED)
313 + {
314 + preverify_ok = 1;
315 + mws_error(client->log, "Self Signed Certificate Accepted as the connection was "
316 + "requested with MQTT_WSS_SSL_ALLOW_SELF_SIGNED");
317 + }
318 +
319 + return preverify_ok;
320 +}
321 +
322 +#define PROXY_CONNECT "CONNECT"
323 +#define PROXY_HTTP "HTTP/1.1"
324 +#define HTTP_ENDLINE "\x0D\x0A"
325 +#define HTTP_HDR_TERMINATOR "\x0D\x0A\x0D\x0A"
326 +#define HTTP_CODE_LEN 4
327 +#define HTTP_REASON_MAX_LEN 512
328 +static int http_parse_reply(mqtt_wss_client client, rbuf_t buf)
329 +{
330 + char *ptr;
331 + char http_code_s[4];
332 + int http_code;
333 + int idx;
334 +
335 + if (rbuf_memcmp_n(buf, PROXY_HTTP, strlen(PROXY_HTTP))) {
336 + mws_error(client->log, "http_proxy expected reply with \"" PROXY_HTTP "\"");
337 + return 1;
338 + }
339 +
340 + rbuf_bump_tail(buf, strlen(PROXY_HTTP));
341 +
342 + if (!rbuf_pop(buf, http_code_s, 1) || http_code_s[0] != 0x20) {
343 + mws_error(client->log, "http_proxy missing space after \"" PROXY_HTTP "\"");
344 + return 2;
345 + }
346 +
347 + if (!rbuf_pop(buf, http_code_s, HTTP_CODE_LEN)) {
348 + mws_error(client->log, "http_proxy missing HTTP code");
349 + return 3;
350 + }
351 +
352 + for (int i = 0; i < HTTP_CODE_LEN - 1; i++)
353 + if (http_code_s[i] > 0x39 || http_code_s[i] < 0x30) {
354 + mws_error(client->log, "http_proxy HTTP code non numeric");
355 + return 4;
356 + }
357 +
358 + http_code_s[HTTP_CODE_LEN - 1] = 0;
359 + http_code = atoi(http_code_s);
360 +
361 + // TODO check if we ever have more headers here
362 + rbuf_find_bytes(buf, HTTP_ENDLINE, strlen(HTTP_ENDLINE), &idx);
363 + if (idx >= HTTP_REASON_MAX_LEN) {
364 + mws_error(client->log, "http_proxy returned reason that is too long");
365 + return 5;
366 + }
367 +
368 + if (http_code != 200) {
369 + ptr = mw_malloc(idx + 1);
370 + if (!ptr)
371 + return 6;
372 + rbuf_pop(buf, ptr, idx);
373 + ptr[idx] = 0;
374 +
375 + mws_error(client->log, "http_proxy returned error code %d \"%s\"", http_code, ptr);
376 + mw_free(ptr);
377 + return 7;
378 + }/* else
379 + rbuf_bump_tail(buf, idx);*/
380 +
381 + rbuf_find_bytes(buf, HTTP_HDR_TERMINATOR, strlen(HTTP_HDR_TERMINATOR), &idx);
382 + if (idx)
383 + rbuf_bump_tail(buf, idx);
384 +
385 + rbuf_bump_tail(buf, strlen(HTTP_HDR_TERMINATOR));
386 +
387 + if (rbuf_bytes_available(buf)) {
388 + mws_error(client->log, "http_proxy unexpected trailing bytes after end of HTTP hdr");
389 + return 8;
390 + }
391 +
392 + mws_debug(client->log, "http_proxy CONNECT succeeded");
393 + return 0;
394 +}
395 +
396 +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
397 +static EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void)
398 +{
399 + EVP_ENCODE_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
400 +
401 + if (ctx != NULL) {
402 + memset(ctx, 0, sizeof(*ctx));
403 + }
404 + return ctx;
405 +}
406 +static void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx)
407 +{
408 + OPENSSL_free(ctx);
409 + return;
410 +}
411 +#endif
412 +
413 +inline static int base64_encode_helper(unsigned char *out, int *outl, const unsigned char *in, int in_len)
414 +{
415 + int len;
416 + unsigned char *str = out;
417 + EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
418 + EVP_EncodeInit(ctx);
419 + EVP_EncodeUpdate(ctx, str, outl, in, in_len);
420 + str += *outl;
421 + EVP_EncodeFinal(ctx, str, &len);
422 + *outl += len;
423 +
424 + str = out;
425 + while(*str) {
426 + if (*str != 0x0D && *str != 0x0A)
427 + *out++ = *str++;
428 + else
429 + str++;
430 + }
431 + *out = 0;
432 +
433 + EVP_ENCODE_CTX_free(ctx);
434 + return 0;
435 +}
436 +
437 +static int http_proxy_connect(mqtt_wss_client client)
438 +{
439 + int rc;
440 + struct pollfd poll_fd;
441 + rbuf_t r_buf = rbuf_create(4096);
442 + if (!r_buf)
443 + return 1;
444 + char *r_buf_ptr;
445 + size_t r_buf_linear_insert_capacity;
446 +
447 + poll_fd.fd = client->sockfd;
448 + poll_fd.events = POLLIN;
449 +
450 + r_buf_ptr = rbuf_get_linear_insert_range(r_buf, &r_buf_linear_insert_capacity);
451 + snprintf(r_buf_ptr, r_buf_linear_insert_capacity,"%s %s:%d %s" HTTP_ENDLINE, PROXY_CONNECT, client->target_host, client->target_port, PROXY_HTTP);
452 + write(client->sockfd, r_buf_ptr, strlen(r_buf_ptr));
453 +
454 + if (client->proxy_uname) {
455 + size_t creds_plain_len = strlen(client->proxy_uname) + strlen(client->proxy_passwd) + 2;
456 + char *creds_plain = mw_malloc(creds_plain_len);
457 + if (!creds_plain) {
458 + mws_error(client->log, "OOM creds_plain");
459 + rc = 6;
460 + goto cleanup;
461 + }
462 + int creds_base64_len = (((4 * creds_plain_len / 3) + 3) & ~3);
463 + // OpenSSL encoder puts newline every 64 output bytes
464 + // we remove those but during encoding we need that space in the buffer
465 + creds_base64_len += (1+(creds_base64_len/64)) * strlen("\n");
466 + char *creds_base64 = mw_malloc(creds_base64_len + 1);
467 + if (!creds_base64) {
468 + mw_free(creds_plain);
469 + mws_error(client->log, "OOM creds_base64");
470 + rc = 6;
471 + goto cleanup;
472 + }
473 + char *ptr = creds_plain;
474 + strcpy(ptr, client->proxy_uname);
475 + ptr += strlen(client->proxy_uname);
476 + *ptr++ = ':';
477 + strcpy(ptr, client->proxy_passwd);
478 +
479 + int b64_len;
480 + base64_encode_helper((unsigned char*)creds_base64, &b64_len, (unsigned char*)creds_plain, strlen(creds_plain));
481 + mw_free(creds_plain);
482 +
483 + r_buf_ptr = rbuf_get_linear_insert_range(r_buf, &r_buf_linear_insert_capacity);
484 + snprintf(r_buf_ptr, r_buf_linear_insert_capacity,"Proxy-Authorization: Basic %s" HTTP_ENDLINE, creds_base64);
485 + write(client->sockfd, r_buf_ptr, strlen(r_buf_ptr));
486 + mw_free(creds_base64);
487 + }
488 + write(client->sockfd, HTTP_ENDLINE, strlen(HTTP_ENDLINE));
489 +
490 + // read until you find CRLF, CRLF (HTTP HDR end)
491 + // or ring buffer is full
492 + // or timeout
493 + while ((rc = poll(&poll_fd, 1, 1000)) >= 0) {
494 + if (!rc) {
495 + mws_error(client->log, "http_proxy timeout waiting reply from proxy server");
496 + rc = 2;
497 + goto cleanup;
498 + }
499 + r_buf_ptr = rbuf_get_linear_insert_range(r_buf, &r_buf_linear_insert_capacity);
500 + if (!r_buf_ptr) {
501 + mws_error(client->log, "http_proxy read ring buffer full");
502 + rc = 3;
503 + goto cleanup;
504 + }
505 + if ((rc = read(client->sockfd, r_buf_ptr, r_buf_linear_insert_capacity)) < 0) {
506 + if (errno == EWOULDBLOCK || errno == EAGAIN) {
507 + continue;
508 + }
509 + mws_error(client->log, "http_proxy error reading from socket \"%s\"", strerror(errno));
510 + rc = 4;
511 + goto cleanup;
512 + }
513 + rbuf_bump_head(r_buf, rc);
514 + if (rbuf_find_bytes(r_buf, HTTP_HDR_TERMINATOR, strlen(HTTP_HDR_TERMINATOR), &rc)) {
515 + rc = 0;
516 + if (http_parse_reply(client, r_buf))
517 + rc = 5;
518 +
519 + goto cleanup;
520 + }
521 + }
522 + mws_error(client->log, "proxy negotiation poll error \"%s\"", strerror(errno));
523 + rc = 5;
524 +cleanup:
525 + rbuf_free(r_buf);
526 + return rc;
527 +}
528 +
529 +int mqtt_wss_connect(mqtt_wss_client client, char *host, int port, struct mqtt_connect_params *mqtt_params, int ssl_flags, struct mqtt_wss_proxy *proxy)
530 +{
531 + struct sockaddr_in addr;
532 + memset(&addr, 0, sizeof(addr));
533 + addr.sin_family = AF_INET;
534 +
535 + struct hostent *he;
536 + struct in_addr **addr_list;
537 +
538 + if (!mqtt_params) {
539 + mws_error(client->log, "mqtt_params can't be null!");
540 + return -1;
541 + }
542 +
543 + // reset state in case this is reconnect
544 + client->mqtt_didnt_finish_write = 0;
545 + client->mqtt_connected = 0;
546 + client->mqtt_disconnecting = 0;
547 + ws_client_reset(client->ws_client);
548 +
549 + if (client->target_host == client->host)
550 + client->target_host = NULL;
551 + if (client->target_host)
552 + mw_free(client->target_host);
553 + if (client->host)
554 + mw_free(client->host);
555 +
556 + if (proxy && proxy->type != MQTT_WSS_DIRECT) {
557 + client->host = mw_strdup(proxy->host);
558 + client->port = proxy->port;
559 + client->target_host = mw_strdup(host);
560 + client->target_port = port;
561 + client->proxy_type = proxy->type;
562 + if (proxy->username)
563 + client->proxy_uname = mw_strdup(proxy->username);
564 + if (proxy->password)
565 + client->proxy_passwd = mw_strdup(proxy->password);
566 + } else {
567 + client->host = mw_strdup(host);
568 + client->port = port;
569 + client->target_host = client->host;
570 + client->target_port = port;
571 + }
572 +
573 + client->ssl_flags = ssl_flags;
574 +
575 + //TODO gethostbyname -> getaddinfo
576 + // hstrerror -> gai_strerror
577 + if ((he = gethostbyname(client->host)) == NULL) {
578 + mws_error(client->log, "gethostbyname() error \"%s\"", hstrerror(h_errno));
579 + return -1;
580 + }
581 +
582 + addr_list = (struct in_addr **)he->h_addr_list;
583 + if(!addr_list[0]) {
584 + mws_error(client->log, "No IP addr resolved");
585 + return -1;
586 + }
587 + mws_debug(client->log, "Resolved IP: %s", inet_ntoa(*addr_list[0]));
588 + addr.sin_addr = *addr_list[0];
589 + addr.sin_port = htons(client->port);
590 +
591 + if (client->sockfd > 0)
592 + close(client->sockfd);
593 + client->sockfd = socket(AF_INET, SOCK_STREAM, 0);
594 + if (client->sockfd < 0) {
595 + mws_error(client->log, "Couldn't create socket()");
596 + return -1;
597 + }
598 +
599 + int flag = 1;
600 + int result = setsockopt(client->sockfd,
601 + IPPROTO_TCP,
602 + TCP_NODELAY,
603 + &flag,
604 + sizeof(int));
605 + if (result < 0)
606 + mws_error(client->log, "Could not dissable NAGLE");
607 +
608 + if (connect(client->sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
609 + mws_error(client->log, "Could not connect to remote endpoint \"%s\", port %d.\n", client->host, client->port);
610 + return -3;
611 + }
612 +
613 + client->poll_fds[POLLFD_SOCKET].fd = client->sockfd;
614 +
615 + if (fcntl(client->sockfd, F_SETFL, fcntl(client->sockfd, F_GETFL, 0) | O_NONBLOCK) == -1) {
616 + mws_error(client->log, "Error setting O_NONBLOCK to TCP socket. \"%s\"", strerror(errno));
617 + return -8;
618 + }
619 +
620 + if (client->proxy_type != MQTT_WSS_DIRECT)
621 + if (http_proxy_connect(client))
622 + return -4;
623 +
624 +#if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
625 +#if (SSLEAY_VERSION_NUMBER >= OPENSSL_VERSION_097)
626 + OPENSSL_config(NULL);
627 +#endif
628 + SSL_load_error_strings();
629 + SSL_library_init();
630 +#else
631 + if (OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL) != 1) {
632 + mws_error(client->log, "Failed to initialize SSL");
633 + return -1;
634 + };
635 +#endif
636 +
637 + // free SSL structs from possible previous connections
638 + if (client->ssl)
639 + SSL_free(client->ssl);
640 + if (client->ssl_ctx)
641 + SSL_CTX_free(client->ssl_ctx);
642 +
643 + client->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
644 + if (!(client->ssl_flags & MQTT_WSS_SSL_DONT_CHECK_CERTS)) {
645 + SSL_CTX_set_default_verify_paths(client->ssl_ctx);
646 + SSL_CTX_set_verify(client->ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, cert_verify_callback);
647 + } else
648 + mws_error(client->log, "SSL Certificate checking completely disabled!!!");
649 +
650 +#ifdef MQTT_WSS_DEBUG
651 + if(client->ssl_ctx_keylog_cb)
652 + SSL_CTX_set_keylog_callback(client->ssl_ctx, client->ssl_ctx_keylog_cb);
653 +#endif
654 +
655 + client->ssl = SSL_new(client->ssl_ctx);
656 + if (!(client->ssl_flags & MQTT_WSS_SSL_DONT_CHECK_CERTS)) {
657 + if (!SSL_set_ex_data(client->ssl, 0, client)) {
658 + mws_error(client->log, "Could not SSL_set_ex_data");
659 + return -4;
660 + }
661 + }
662 + SSL_set_fd(client->ssl, client->sockfd);
663 + SSL_set_connect_state(client->ssl);
664 +
665 + if (!SSL_set_tlsext_host_name(client->ssl, client->target_host)) {
666 + mws_error(client->log, "Error setting TLS SNI host");
667 + return -7;
668 + }
669 +
670 + result = SSL_connect(client->ssl);
671 + if (result != -1 && result != 1) {
672 + mws_error(client->log, "SSL could not connect");
673 + return -5;
674 + }
675 + if (result == -1) {
676 + int ec = SSL_get_error(client->ssl, result);
677 + if (ec != SSL_ERROR_WANT_READ && ec != SSL_ERROR_WANT_WRITE) {
678 + mws_error(client->log, "Failed to start SSL connection");
679 + return -6;
680 + }
681 + }
682 +
683 + uint8_t mqtt_flags = (mqtt_params->will_flags & MQTT_WSS_PUB_QOSMASK) << 3;
684 + if (mqtt_params->will_flags & MQTT_WSS_PUB_RETAIN)
685 + mqtt_flags |= MQTT_CONNECT_WILL_RETAIN;
686 + mqtt_flags |= MQTT_CONNECT_CLEAN_SESSION;
687 +
688 + client->mqtt_keepalive = (mqtt_params->keep_alive ? mqtt_params->keep_alive : 400);
689 +
690 + mws_info(client->log, "Going to connect using internal MQTT 5 implementation");
691 + struct mqtt_auth_properties auth;
692 + auth.client_id = (char*)mqtt_params->clientid;
693 + auth.client_id_free = NULL;
694 + auth.username = (char*)mqtt_params->username;
695 + auth.username_free = NULL;
696 + auth.password = (char*)mqtt_params->password;
697 + auth.password_free = NULL;
698 + struct mqtt_lwt_properties lwt;
699 + lwt.will_topic = (char*)mqtt_params->will_topic;
700 + lwt.will_topic_free = NULL;
701 + lwt.will_message = (void*)mqtt_params->will_msg;
702 + lwt.will_message_free = NULL; // TODO expose no copy version to API
703 + lwt.will_message_size = mqtt_params->will_msg_len;
704 + lwt.will_qos = (mqtt_params->will_flags & MQTT_WSS_PUB_QOSMASK);
705 + lwt.will_retain = mqtt_params->will_flags & MQTT_WSS_PUB_RETAIN;
706 + int ret = mqtt_ng_connect(client->mqtt, &auth, mqtt_params->will_msg ? &lwt : NULL, 1, client->mqtt_keepalive);
707 + if (ret) {
708 + mws_error(client->log, "Error generating MQTT connect");
709 + return 1;
710 + }
711 +
712 + client->poll_fds[POLLFD_PIPE].events = POLLIN;
713 + client->poll_fds[POLLFD_SOCKET].events = POLLIN;
714 + // wait till MQTT connection is established
715 + while (!client->mqtt_connected) {
716 + if(mqtt_wss_service(client, -1)) {
717 + mws_error(client->log, "Error connecting to MQTT WSS server \"%s\", port %d.", host, port);
718 + return 2;
719 + }
720 + }
721 +
722 + return 0;
723 +}
724 +
725 +#define NSEC_PER_USEC 1000ULL
726 +#define USEC_PER_SEC 1000000ULL
727 +#define NSEC_PER_MSEC 1000000ULL
728 +#define NSEC_PER_SEC 1000000000ULL
729 +
730 +static inline uint64_t boottime_usec(mqtt_wss_client client) {
731 + struct timespec ts;
732 +#if defined(__APPLE__) || defined(__FreeBSD__)
733 + if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) {
734 +#else
735 + if (clock_gettime(CLOCK_BOOTTIME, &ts) == -1) {
736 +#endif
737 + mws_error(client->log, "clock_gettimte failed");
738 + return 0;
739 + }
740 + return (uint64_t)ts.tv_sec * USEC_PER_SEC + (ts.tv_nsec % NSEC_PER_SEC) / NSEC_PER_USEC;
741 +}
742 +
743 +#define MWS_TIMED_OUT 1
744 +#define MWS_ERROR 2
745 +#define MWS_OK 0
746 +static inline const char *mqtt_wss_error_tos(int ec)
747 +{
748 + switch(ec) {
749 + case MWS_TIMED_OUT:
750 + return "Error: Operation was not able to finish in time";
751 + case MWS_ERROR:
752 + return "Unspecified Error";
753 + default:
754 + return "Unknown Error Code!";
755 + }
756 +
757 +}
758 +
759 +static inline int mqtt_wss_service_all(mqtt_wss_client client, int timeout_ms)
760 +{
761 + uint64_t exit_by = boottime_usec(client) + (timeout_ms * NSEC_PER_MSEC);
762 + uint64_t now;
763 + client->poll_fds[POLLFD_SOCKET].events |= POLLOUT; // TODO when entering mwtt_wss_service use out buffer size to arm POLLOUT
764 + while (rbuf_bytes_available(client->ws_client->buf_write)) {
765 + now = boottime_usec(client);
766 + if (now >= exit_by)
767 + return MWS_TIMED_OUT;
768 + if (mqtt_wss_service(client, exit_by - now))
769 + return MWS_ERROR;
770 + }
771 + return MWS_OK;
772 +}
773 +
774 +void mqtt_wss_disconnect(mqtt_wss_client client, int timeout_ms)
775 +{
776 + int ret;
777 +
778 + // block application from sending more MQTT messages
779 + client->mqtt_disconnecting = 1;
780 +
781 + // send whatever was left at the time of calling this function
782 + ret = mqtt_wss_service_all(client, timeout_ms / 4);
783 + if(ret)
784 + mws_error(client->log,
785 + "Error while trying to send all remaining data in an attempt "
786 + "to gracefully disconnect! EC=%d Desc:\"%s\"",
787 + ret,
788 + mqtt_wss_error_tos(ret));
789 +
790 + // schedule and send MQTT disconnect
791 + mqtt_ng_disconnect(client->mqtt, 0);
792 + mqtt_ng_sync(client->mqtt);
793 +
794 + ret = mqtt_wss_service_all(client, timeout_ms / 4);
795 + if(ret)
796 + mws_error(client->log,
797 + "Error while trying to send MQTT disconnect message in an attempt "
798 + "to gracefully disconnect! EC=%d Desc:\"%s\"",
799 + ret,
800 + mqtt_wss_error_tos(ret));
801 +
802 + // send WebSockets close message
803 + uint16_t ws_rc = htobe16(1000);
804 + ws_client_send(client->ws_client, WS_OP_CONNECTION_CLOSE, (const char*)&ws_rc, sizeof(ws_rc));
805 + ret = mqtt_wss_service_all(client, timeout_ms / 4);
806 + if(ret) {
807 + // Some MQTT/WSS servers will close socket on receipt of MQTT disconnect and
808 + // do not wait for WebSocket to be closed properly
809 + mws_warn(client->log,
810 + "Error while trying to send WebSocket disconnect message in an attempt "
811 + "to gracefully disconnect! EC=%d Desc:\"%s\".",
812 + ret,
813 + mqtt_wss_error_tos(ret));
814 + }
815 +
816 + // Service WSS connection until remote closes connection (usual)
817 + // or timeout happens (unusual) in which case we close
818 + mqtt_wss_service_all(client, timeout_ms / 4);
819 +
820 + close(client->sockfd);
821 + client->sockfd = -1;
822 +}
823 +
824 +static inline void mqtt_wss_wakeup(mqtt_wss_client client)
825 +{
826 +#ifdef DEBUG_ULTRA_VERBOSE
827 + mws_debug(client->log, "mqtt_wss_wakup - forcing wake up of main loop");
828 +#endif
829 + write(client->write_notif_pipe[PIPE_WRITE_END], " ", 1);
830 +}
831 +
832 +#define THROWAWAY_BUF_SIZE 32
833 +char throwaway[THROWAWAY_BUF_SIZE];
834 +static inline void util_clear_pipe(int fd)
835 +{
836 + (void)read(fd, throwaway, THROWAWAY_BUF_SIZE);
837 +}
838 +
839 +static inline void set_socket_pollfds(mqtt_wss_client client, int ssl_ret) {
840 + if (ssl_ret == SSL_ERROR_WANT_WRITE)
841 + client->poll_fds[POLLFD_SOCKET].events |= POLLOUT;
842 + if (ssl_ret == SSL_ERROR_WANT_READ)
843 + client->poll_fds[POLLFD_SOCKET].events |= POLLIN;
844 +}
845 +
846 +static int handle_mqtt_internal(mqtt_wss_client client)
847 +{
848 + int rc = mqtt_ng_sync(client->mqtt);
849 + if (rc) {
850 + mws_error(client->log, "mqtt_ng_sync returned %d != 0", rc);
851 + client->mqtt_connected = 0;
852 + return 1;
853 + }
854 + return 0;
855 +}
856 +
857 +#define SEC_TO_MSEC 1000
858 +static inline long long int t_till_next_keepalive_ms(mqtt_wss_client client)
859 +{
860 + time_t last_send = mqtt_ng_last_send_time(client->mqtt);
861 + long long int next_mqtt_keep_alive = (last_send * SEC_TO_MSEC)
862 + + (client->mqtt_keepalive * (SEC_TO_MSEC * 0.75 /* SEND IN ADVANCE */));
863 + return(next_mqtt_keep_alive - (time(NULL) * SEC_TO_MSEC));
864 +}
865 +
866 +#ifdef MQTT_WSS_CPUSTATS
867 +static inline uint64_t mqtt_wss_now_usec(mqtt_wss_client client) {
868 + struct timespec ts;
869 + if(clock_gettime(CLOCK_MONOTONIC, &ts) == -1) {
870 + mws_error(client->log, "clock_gettime(CLOCK_MONOTONIC, &timespec) failed.");
871 + return 0;
872 + }
873 + return (uint64_t)ts.tv_sec * USEC_PER_SEC + (ts.tv_nsec % NSEC_PER_SEC) / NSEC_PER_USEC;
874 +}
875 +#endif
876 +
877 +int mqtt_wss_service(mqtt_wss_client client, int timeout_ms)
878 +{
879 + char *ptr;
880 + size_t size;
881 + int ret;
882 + int send_keepalive = 0;
883 +
884 +#ifdef MQTT_WSS_CPUSTATS
885 + uint64_t t1,t2;
886 + t1 = mqtt_wss_now_usec(client);
887 +#endif
888 +
889 +#ifdef DEBUG_ULTRA_VERBOSE
890 + mws_debug(client->log, ">>>>> mqtt_wss_service <<<<<");
891 + mws_debug(client->log, "Waiting for events: %s%s%s",
892 + (client->poll_fds[POLLFD_SOCKET].events & POLLIN) ? "SOCKET_POLLIN " : "",
893 + (client->poll_fds[POLLFD_SOCKET].events & POLLOUT) ? "SOCKET_POLLOUT " : "",
894 + (client->poll_fds[POLLFD_PIPE].events & POLLIN) ? "PIPE_POLLIN" : "" );
895 +#endif
896 +
897 + // Check user requested TO doesn't interfere with MQTT keep alives
898 + long long int till_next_keep_alive = t_till_next_keepalive_ms(client);
899 + if (client->mqtt_connected && (timeout_ms < 0 || timeout_ms >= till_next_keep_alive)) {
900 + #ifdef DEBUG_ULTRA_VERBOSE
901 + mws_debug(client->log, "Shortening Timeout requested %d to %lld to ensure keep-alive can be sent", timeout_ms, till_next_keep_alive);
902 + #endif
903 + timeout_ms = till_next_keep_alive;
904 + send_keepalive = 1;
905 + }
906 +
907 +#ifdef MQTT_WSS_CPUSTATS
908 + t2 = mqtt_wss_now_usec(client);
909 + client->stats.time_keepalive += t2 - t1;
910 +#endif
911 +
912 + if ((ret = poll(client->poll_fds, 2, timeout_ms >= 0 ? timeout_ms : -1)) < 0) {
913 + if (errno == EINTR) {
914 + mws_warn(client->log, "poll interrupted by EINTR");
915 + return 0;
916 + }
917 + mws_error(client->log, "poll error \"%s\"", strerror(errno));
918 + return -2;
919 + }
920 +
921 +#ifdef DEBUG_ULTRA_VERBOSE
922 + mws_debug(client->log, "Poll events happened: %s%s%s%s",
923 + (client->poll_fds[POLLFD_SOCKET].revents & POLLIN) ? "SOCKET_POLLIN " : "",
924 + (client->poll_fds[POLLFD_SOCKET].revents & POLLOUT) ? "SOCKET_POLLOUT " : "",
925 + (client->poll_fds[POLLFD_PIPE].revents & POLLIN) ? "PIPE_POLLIN " : "",
926 + (!ret) ? "POLL_TIMEOUT" : "");
927 +#endif
928 +
929 +#ifdef MQTT_WSS_CPUSTATS
930 + t1 = mqtt_wss_now_usec(client);
931 +#endif
932 +
933 + if (ret == 0) {
934 + if (send_keepalive) {
935 + // otherwise we shortened the timeout ourselves to take care of
936 + // MQTT keep alives
937 +#ifdef DEBUG_ULTRA_VERBOSE
938 + mws_debug(client->log, "Forcing MQTT Ping/keep-alive");
939 +#endif
940 + mqtt_ng_ping(client->mqtt);
941 + } else {
942 + // if poll timed out and user requested timeout was being used
943 + // return here let user do his work and he will call us back soon
944 + return 0;
945 + }
946 + }
947 +
948 +#ifdef MQTT_WSS_CPUSTATS
949 + t2 = mqtt_wss_now_usec(client);
950 + client->stats.time_keepalive += t2 - t1;
951 +#endif
952 +
953 + client->poll_fds[POLLFD_SOCKET].events = 0;
954 +
955 + if ((ptr = rbuf_get_linear_insert_range(client->ws_client->buf_read, &size))) {
956 + if((ret = SSL_read(client->ssl, ptr, size)) > 0) {
957 +#ifdef DEBUG_ULTRA_VERBOSE
958 + mws_debug(client->log, "SSL_Read: Read %d.", ret);
959 +#endif
960 + pthread_mutex_lock(&client->stat_lock);
961 + client->stats.bytes_rx += ret;
962 + pthread_mutex_unlock(&client->stat_lock);
963 + rbuf_bump_head(client->ws_client->buf_read, ret);
964 + } else {
965 + int errnobkp = errno;
966 + ret = SSL_get_error(client->ssl, ret);
967 +#ifdef DEBUG_ULTRA_VERBOSE
968 + mws_debug(client->log, "Read Err: %s", util_openssl_ret_err(ret));
969 +#endif
970 + set_socket_pollfds(client, ret);
971 + if (ret != SSL_ERROR_WANT_READ &&
972 + ret != SSL_ERROR_WANT_WRITE) {
973 + mws_error(client->log, "SSL_read error: %d %s", ret, util_openssl_ret_err(ret));
974 + if (ret == SSL_ERROR_SYSCALL)
975 + mws_error(client->log, "SSL_read SYSCALL errno: %d %s", errnobkp, strerror(errnobkp));
976 + return MQTT_WSS_ERR_CONN_DROP;
977 + }
978 + }
979 + }
980 +
981 +#ifdef MQTT_WSS_CPUSTATS
982 + t1 = mqtt_wss_now_usec(client);
983 + client->stats.time_read_socket += t1 - t2;
984 +#endif
985 +
986 + ret = ws_client_process(client->ws_client);
987 + switch(ret) {
988 + case WS_CLIENT_PROTOCOL_ERROR:
989 + return MQTT_WSS_ERR_PROTO_WS;
990 + case WS_CLIENT_NEED_MORE_BYTES:
991 +#ifdef DEBUG_ULTRA_VERBOSE
992 + mws_debug(client->log, "WSCLIENT WANT READ");
993 +#endif
994 + client->poll_fds[POLLFD_SOCKET].events |= POLLIN;
995 + break;
996 + case WS_CLIENT_CONNECTION_CLOSED:
997 + return MQTT_WSS_ERR_CONN_DROP;
998 + }
999 +
1000 +#ifdef MQTT_WSS_CPUSTATS
1001 + t2 = mqtt_wss_now_usec(client);
1002 + client->stats.time_process_websocket += t2 - t1;
1003 +#endif
1004 +
1005 + // process MQTT stuff
1006 + if(client->ws_client->state == WS_ESTABLISHED)
1007 + if (handle_mqtt_internal(client))
1008 + return MQTT_WSS_ERR_PROTO_MQTT;
1009 +
1010 + if (client->mqtt_didnt_finish_write) {
1011 + client->mqtt_didnt_finish_write = 0;
1012 + client->poll_fds[POLLFD_SOCKET].events |= POLLOUT;
1013 + }
1014 +
1015 +#ifdef MQTT_WSS_CPUSTATS
1016 + t1 = mqtt_wss_now_usec(client);
1017 + client->stats.time_process_mqtt += t1 - t2;
1018 +#endif
1019 +
1020 + if ((ptr = rbuf_get_linear_read_range(client->ws_client->buf_write, &size))) {
1021 +#ifdef DEBUG_ULTRA_VERBOSE
1022 + mws_debug(client->log, "Have data to write to SSL");
1023 +#endif
1024 + if ((ret = SSL_write(client->ssl, ptr, size)) > 0) {
1025 +#ifdef DEBUG_ULTRA_VERBOSE
1026 + mws_debug(client->log, "SSL_Write: Written %d of avail %d.", ret, size);
1027 +#endif
1028 + pthread_mutex_lock(&client->stat_lock);
1029 + client->stats.bytes_tx += ret;
1030 + pthread_mutex_unlock(&client->stat_lock);
1031 + rbuf_bump_tail(client->ws_client->buf_write, ret);
1032 + } else {
1033 + int errnobkp = errno;
1034 + ret = SSL_get_error(client->ssl, ret);
1035 +#ifdef DEBUG_ULTRA_VERBOSE
1036 + mws_debug(client->log, "Write Err: %s", util_openssl_ret_err(ret));
1037 +#endif
1038 + set_socket_pollfds(client, ret);
1039 + if (ret != SSL_ERROR_WANT_READ &&
1040 + ret != SSL_ERROR_WANT_WRITE) {
1041 + mws_error(client->log, "SSL_write error: %d %s", ret, util_openssl_ret_err(ret));
1042 + if (ret == SSL_ERROR_SYSCALL)
1043 + mws_error(client->log, "SSL_write SYSCALL errno: %d %s", errnobkp, strerror(errnobkp));
1044 + return MQTT_WSS_ERR_CONN_DROP;
1045 + }
1046 + }
1047 + }
1048 +
1049 + if(client->poll_fds[POLLFD_PIPE].revents & POLLIN)
1050 + util_clear_pipe(client->write_notif_pipe[PIPE_READ_END]);
1051 +
1052 +#ifdef MQTT_WSS_CPUSTATS
1053 + t2 = mqtt_wss_now_usec(client);
1054 + client->stats.time_write_socket += t2 - t1;
1055 +#endif
1056 +
1057 + return MQTT_WSS_OK;
1058 +}
1059 +
1060 +int mqtt_wss_publish5(mqtt_wss_client client,
1061 + char *topic,
1062 + free_fnc_t topic_free,
1063 + void *msg,
1064 + free_fnc_t msg_free,
1065 + size_t msg_len,
1066 + uint8_t publish_flags,
1067 + uint16_t *packet_id)
1068 +{
1069 + if (client->mqtt_disconnecting) {
1070 + mws_error(client->log, "mqtt_wss is disconnecting can't publish");
1071 + return 1;
1072 + }
1073 +
1074 + if (!client->mqtt_connected) {
1075 + mws_error(client->log, "MQTT is offline. Can't send message.");
1076 + return 1;
1077 + }
1078 + uint8_t mqtt_flags = 0;
1079 +
1080 + mqtt_flags = (publish_flags & MQTT_WSS_PUB_QOSMASK) << 1;
1081 + if (publish_flags & MQTT_WSS_PUB_RETAIN)
1082 + mqtt_flags |= MQTT_PUBLISH_RETAIN;
1083 +
1084 + int rc = mqtt_ng_publish(client->mqtt, topic, topic_free, msg, msg_free, msg_len, mqtt_flags, packet_id);
1085 + if (rc == MQTT_NG_MSGGEN_MSG_TOO_BIG)
1086 + return MQTT_WSS_ERR_TOO_BIG_FOR_SERVER;
1087 +
1088 + mqtt_wss_wakeup(client);
1089 +
1090 + return rc;
1091 +}
1092 +
1093 +int mqtt_wss_subscribe(mqtt_wss_client client, char *topic, int max_qos_level)
1094 +{
1095 + (void)max_qos_level; //TODO now hardcoded
1096 + if (!client->mqtt_connected) {
1097 + mws_error(client->log, "MQTT is offline. Can't subscribe.");
1098 + return 1;
1099 + }
1100 +
1101 + if (client->mqtt_disconnecting) {
1102 + mws_error(client->log, "mqtt_wss is disconnecting can't subscribe");
1103 + return 1;
1104 + }
1105 +
1106 + struct mqtt_sub sub = {
1107 + .topic = topic,
1108 + .topic_free = NULL,
1109 + .options = /* max_qos_level & 0x3 TODO when QOS > 1 implemented */ 0x01 | (0x01 << 3)
1110 + };
1111 + mqtt_ng_subscribe(client->mqtt, &sub, 1);
1112 +
1113 + mqtt_wss_wakeup(client);
1114 + return 0;
1115 +}
1116 +
1117 +struct mqtt_wss_stats mqtt_wss_get_stats(mqtt_wss_client client)
1118 +{
1119 + struct mqtt_wss_stats current;
1120 + pthread_mutex_lock(&client->stat_lock);
1121 + current = client->stats;
1122 + memset(&client->stats, 0, sizeof(client->stats));
1123 + pthread_mutex_unlock(&client->stat_lock);
1124 + mqtt_ng_get_stats(client->mqtt, &current.mqtt);
1125 + return current;
1126 +}
1127 +
1128 +int mqtt_wss_set_topic_alias(mqtt_wss_client client, const char *topic)
1129 +{
1130 + return mqtt_ng_set_topic_alias(client->mqtt, topic);
1131 +}
1132 +
1133 +#ifdef MQTT_WSS_DEBUG
1134 +void mqtt_wss_set_SSL_CTX_keylog_cb(mqtt_wss_client client, void (*ssl_ctx_keylog_cb)(const SSL *ssl, const char *line))
1135 +{
1136 + client->ssl_ctx_keylog_cb = ssl_ctx_keylog_cb;
1137 +}
1138 +#endif
mqtt_websockets/src/mqtt_wss_log.c new
+127
@@ -0,0 +1,127 @@
1 +#include "mqtt_wss_log.h"
2 +#include <stdlib.h>
3 +#include <stdarg.h>
4 +#include <string.h>
5 +#include <stdio.h>
6 +#include "common_internal.h"
7 +
8 +struct mqtt_wss_log_ctx {
9 + mqtt_wss_log_callback_t extern_log_fnc;
10 + char *ctx_prefix;
11 + char *buffer;
12 + char *buffer_w_ptr;
13 + size_t buffer_bytes_avail;
14 +};
15 +
16 +#define LOG_BUFFER_SIZE 1024 * 4
17 +#define LOG_CTX_PREFIX_SEV_STR " : "
18 +#define LOG_CTX_PREFIX_LIMIT 15
19 +#define LOG_CTX_PREFIX_LIMIT_STR (LOG_CTX_PREFIX_LIMIT - (2 + strlen(LOG_CTX_PREFIX_SEV_STR))) // with [] characters and affixed ' ' it is total 15 chars
20 +#if (LOG_CTX_PREFIX_LIMIT * 10) > LOG_BUFFER_SIZE
21 +#error "LOG_BUFFER_SIZE too small"
22 +#endif
23 +mqtt_wss_log_ctx_t mqtt_wss_log_ctx_create(const char *ctx_prefix, mqtt_wss_log_callback_t log_callback)
24 +{
25 + mqtt_wss_log_ctx_t ctx = mw_calloc(1, sizeof(struct mqtt_wss_log_ctx));
26 + if(!ctx)
27 + return NULL;
28 +
29 + if(log_callback) {
30 + ctx->extern_log_fnc = log_callback;
31 + ctx->buffer = mw_calloc(1, LOG_BUFFER_SIZE);
32 + if(!ctx->buffer)
33 + goto cleanup;
34 +
35 + ctx->buffer_w_ptr = ctx->buffer;
36 + if(ctx_prefix) {
37 + *(ctx->buffer_w_ptr++) = '[';
38 + strncpy(ctx->buffer_w_ptr, ctx_prefix, LOG_CTX_PREFIX_LIMIT_STR);
39 + ctx->buffer_w_ptr += strnlen(ctx_prefix, LOG_CTX_PREFIX_LIMIT_STR);
40 + *(ctx->buffer_w_ptr++) = ']';
41 + }
42 + strcpy(ctx->buffer_w_ptr, LOG_CTX_PREFIX_SEV_STR);
43 + ctx->buffer_w_ptr += strlen(LOG_CTX_PREFIX_SEV_STR);
44 + // no term '\0' -> calloc is used
45 +
46 + ctx->buffer_bytes_avail = LOG_BUFFER_SIZE - strlen(ctx->buffer);
47 +
48 + return ctx;
49 + }
50 +
51 + if(ctx_prefix) {
52 + ctx->ctx_prefix = strndup(ctx_prefix, LOG_CTX_PREFIX_LIMIT_STR);
53 + if(!ctx->ctx_prefix)
54 + goto cleanup;
55 + }
56 +
57 + return ctx;
58 +
59 +cleanup:
60 + mw_free(ctx);
61 + return NULL;
62 +}
63 +
64 +void mqtt_wss_log_ctx_destroy(mqtt_wss_log_ctx_t ctx)
65 +{
66 + mw_free(ctx->ctx_prefix);
67 + mw_free(ctx->buffer);
68 + mw_free(ctx);
69 +}
70 +
71 +static inline char severity_to_c(int severity)
72 +{
73 + switch (severity) {
74 + case MQTT_WSS_LOG_FATAL:
75 + return 'F';
76 + case MQTT_WSS_LOG_ERROR:
77 + return 'E';
78 + case MQTT_WSS_LOG_WARN:
79 + return 'W';
80 + case MQTT_WSS_LOG_INFO:
81 + return 'I';
82 + case MQTT_WSS_LOG_DEBUG:
83 + return 'D';
84 + default:
85 + return '?';
86 + }
87 +}
88 +
89 +void mws_log(int severity, mqtt_wss_log_ctx_t ctx, const char *fmt, va_list args)
90 +{
91 + size_t size;
92 +
93 + if(ctx->extern_log_fnc) {
94 + size = vsnprintf(ctx->buffer_w_ptr, ctx->buffer_bytes_avail, fmt, args);
95 + *(ctx->buffer_w_ptr - 3) = severity_to_c(severity);
96 +
97 + ctx->extern_log_fnc(severity, ctx->buffer);
98 +
99 + if(size >= ctx->buffer_bytes_avail)
100 + mws_error(ctx, "Last message of this type was truncated! Consider what you log or increase LOG_BUFFER_SIZE if really needed.");
101 +
102 + return;
103 + }
104 +
105 + if(ctx->ctx_prefix)
106 + printf("[%s] ", ctx->ctx_prefix);
107 +
108 + printf("%c: ", severity_to_c(severity));
109 +
110 + vprintf(fmt, args);
111 + putchar('\n');
112 +}
113 +
114 +#define DEFINE_MWS_SEV_FNC(severity_fncname, severity) \
115 +void mws_ ## severity_fncname(mqtt_wss_log_ctx_t ctx, const char *fmt, ...) \
116 +{ \
117 + va_list args; \
118 + va_start(args, fmt); \
119 + mws_log(severity, ctx, fmt, args); \
120 + va_end(args); \
121 +}
122 +
123 +DEFINE_MWS_SEV_FNC(fatal, MQTT_WSS_LOG_FATAL)
124 +DEFINE_MWS_SEV_FNC(error, MQTT_WSS_LOG_ERROR)
125 +DEFINE_MWS_SEV_FNC(warn, MQTT_WSS_LOG_WARN )
126 +DEFINE_MWS_SEV_FNC(info, MQTT_WSS_LOG_INFO )
127 +DEFINE_MWS_SEV_FNC(debug, MQTT_WSS_LOG_DEBUG)
mqtt_websockets/src/test.c new
+100
@@ -0,0 +1,100 @@
1 +// Copyright (C) 2020 Timotej Šiškovič
2 +// SPDX-License-Identifier: GPL-3.0-only
3 +//
4 +// This program is free software: you can redistribute it and/or modify it
5 +// under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
6 +//
7 +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9 +// See the GNU General Public License for more details.
10 +//
11 +// You should have received a copy of the GNU General Public License along with this program.
12 +// If not, see <https://www.gnu.org/licenses/>.
13 +
14 +#include <unistd.h>
15 +#include <stdio.h>
16 +#include <string.h>
17 +#include <stdlib.h>
18 +
19 +#include "mqtt_wss_client.h"
20 +
21 +int test_exit = 0;
22 +int port = 0;
23 +
24 +void mqtt_wss_log_cb(mqtt_wss_log_type_t log_type, const char* str)
25 +{
26 + (void)log_type;
27 + puts(str);
28 +}
29 +
30 +#define TEST_MSGLEN_MAX 512
31 +void msg_callback(const char *topic, const void *msg, size_t msglen, int qos)
32 +{
33 + char cmsg[TEST_MSGLEN_MAX];
34 + size_t len = (msglen < TEST_MSGLEN_MAX - 1) ? msglen : (TEST_MSGLEN_MAX - 1);
35 + memcpy(cmsg,
36 + msg,
37 + len);
38 + cmsg[len] = 0;
39 +
40 + if (!strcmp(cmsg, "shutdown"))
41 + test_exit = 1;
42 +
43 + printf("Got Message From Broker Topic \"%s\" QOS %d MSG: \"%s\"\n", topic, qos, cmsg);
44 +}
45 +
46 +#define TESTMSG "Hello World!"
47 +int client_handle(mqtt_wss_client client)
48 +{
49 + struct mqtt_connect_params params = {
50 + .clientid = "test",
51 + .username = "anon",
52 + .password = "anon",
53 + .keep_alive = 10
54 + };
55 +
56 +/* struct mqtt_wss_proxy proxy = {
57 + .host = "127.0.0.1",
58 + .port = 3128,
59 + .type = MQTT_WSS_PROXY_HTTP
60 + };*/
61 +
62 + while (mqtt_wss_connect(client, "127.0.0.1", port, &params, MQTT_WSS_SSL_ALLOW_SELF_SIGNED, NULL /*&proxy*/)) {
63 + printf("Connect failed\n");
64 + sleep(1);
65 + printf("Attempting Reconnect\n");
66 + }
67 + printf("Connection succeeded\n");
68 +
69 + mqtt_wss_subscribe(client, "test", 1);
70 +
71 + while (!test_exit) {
72 + if(mqtt_wss_service(client, -1) < 0)
73 + return 1;
74 + }
75 + return 0;
76 +}
77 +
78 +int main(int argc, char **argv)
79 +{
80 + if (argc >= 2)
81 + port = atoi(argv[1]);
82 + if (!port)
83 + port = 9002;
84 + printf("Using port %d\n", port);
85 +
86 + mqtt_wss_client client = mqtt_wss_new("main", mqtt_wss_log_cb, msg_callback, NULL);
87 + if (!client) {
88 + printf("Couldn't initialize mqtt_wss\n");
89 + return 1;
90 + }
91 + while (!test_exit) {
92 + printf("client_handle = %d\n", client_handle(client));
93 + }
94 + if (test_exit) {
95 + mqtt_wss_disconnect(client, 2000);
96 + }
97 +
98 + mqtt_wss_destroy(client);
99 + return 0;
100 +}
mqtt_websockets/src/ws_client.c new
+744
@@ -0,0 +1,744 @@
1 +// Copyright (C) 2020 Timotej Šiškovič
2 +// SPDX-License-Identifier: GPL-3.0-only
3 +//
4 +// This program is free software: you can redistribute it and/or modify it
5 +// under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
6 +//
7 +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9 +// See the GNU General Public License for more details.
10 +//
11 +// You should have received a copy of the GNU General Public License along with this program.
12 +// If not, see <https://www.gnu.org/licenses/>.
13 +
14 +#include <fcntl.h>
15 +#include <unistd.h>
16 +#include <string.h>
17 +#include <errno.h>
18 +#include <ctype.h>
19 +
20 +#include <openssl/evp.h>
21 +
22 +#include "ws_client.h"
23 +#include "common_internal.h"
24 +
25 +#ifdef MQTT_WEBSOCKETS_DEBUG
26 +#include "../c-rbuf/src/ringbuffer_internal.h"
27 +#endif
28 +
29 +#define UNIT_LOG_PREFIX "ws_client: "
30 +#define FATAL(fmt, ...) mws_fatal(client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
31 +#define ERROR(fmt, ...) mws_error(client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
32 +#define WARN(fmt, ...) mws_warn (client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
33 +#define INFO(fmt, ...) mws_info (client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
34 +#define DEBUG(fmt, ...) mws_debug(client->log, UNIT_LOG_PREFIX fmt, ##__VA_ARGS__)
35 +
36 +const char *websocket_upgrage_hdr = "GET /mqtt HTTP/1.1\x0D\x0A"
37 + "Host: %s\x0D\x0A"
38 + "Upgrade: websocket\x0D\x0A"
39 + "Connection: Upgrade\x0D\x0A"
40 + "Sec-WebSocket-Key: %s\x0D\x0A"
41 + "Origin: http://example.com\x0D\x0A"
42 + "Sec-WebSocket-Protocol: mqtt\x0D\x0A"
43 + "Sec-WebSocket-Version: 13\x0D\x0A\x0D\x0A";
44 +
45 +const char *mqtt_protoid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
46 +
47 +#define DEFAULT_RINGBUFFER_SIZE (1024*128)
48 +#define ENTROPY_SOURCE "/dev/urandom"
49 +ws_client *ws_client_new(size_t buf_size, char **host, mqtt_wss_log_ctx_t log)
50 +{
51 + ws_client *client;
52 +
53 + if(!host)
54 + return NULL;
55 +
56 + client = mw_calloc(1, sizeof(ws_client));
57 + if (!client)
58 + return NULL;
59 +
60 + client->host = host;
61 + client->log = log;
62 +
63 + client->buf_read = rbuf_create(buf_size ? buf_size : DEFAULT_RINGBUFFER_SIZE);
64 + if (!client->buf_read)
65 + goto cleanup;
66 +
67 + client->buf_write = rbuf_create(buf_size ? buf_size : DEFAULT_RINGBUFFER_SIZE);
68 + if (!client->buf_write)
69 + goto cleanup_1;
70 +
71 + client->buf_to_mqtt = rbuf_create(buf_size ? buf_size : DEFAULT_RINGBUFFER_SIZE);
72 + if (!client->buf_to_mqtt)
73 + goto cleanup_2;
74 +
75 + client->entropy_fd = open(ENTROPY_SOURCE, O_RDONLY);
76 + if (client->entropy_fd < 1) {
77 + ERROR("Error opening entropy source \"" ENTROPY_SOURCE "\". Reason: \"%s\"", strerror(errno));
78 + goto cleanup_3;
79 + }
80 +
81 + return client;
82 +
83 +cleanup_3:
84 + rbuf_free(client->buf_to_mqtt);
85 +cleanup_2:
86 + rbuf_free(client->buf_write);
87 +cleanup_1:
88 + rbuf_free(client->buf_read);
89 +cleanup:
90 + mw_free(client);
91 + return NULL;
92 +}
93 +
94 +void ws_client_free_headers(ws_client *client)
95 +{
96 + struct http_header *ptr = client->hs.headers;
97 + struct http_header *tmp;
98 +
99 + while (ptr) {
100 + tmp = ptr;
101 + ptr = ptr->next;
102 + mw_free(tmp);
103 + }
104 +
105 + client->hs.headers = NULL;
106 + client->hs.headers_tail = NULL;
107 + client->hs.hdr_count = 0;
108 +}
109 +
110 +void ws_client_destroy(ws_client *client)
111 +{
112 + ws_client_free_headers(client);
113 + mw_free(client->hs.nonce_reply);
114 + mw_free(client->hs.http_reply_msg);
115 + close(client->entropy_fd);
116 + rbuf_free(client->buf_read);
117 + rbuf_free(client->buf_write);
118 + rbuf_free(client->buf_to_mqtt);
119 + mw_free(client);
120 +}
121 +
122 +void ws_client_reset(ws_client *client)
123 +{
124 + ws_client_free_headers(client);
125 + mw_free(client->hs.nonce_reply);
126 + client->hs.nonce_reply = NULL;
127 + mw_free(client->hs.http_reply_msg);
128 + client->hs.http_reply_msg = NULL;
129 + rbuf_flush(client->buf_read);
130 + rbuf_flush(client->buf_write);
131 + rbuf_flush(client->buf_to_mqtt);
132 + client->state = WS_RAW;
133 + client->hs.hdr_state = WS_HDR_HTTP;
134 + client->rx.parse_state = WS_FIRST_2BYTES;
135 +}
136 +
137 +#define MAX_HTTP_HDR_COUNT 128
138 +int ws_client_add_http_header(ws_client *client, struct http_header *hdr)
139 +{
140 + if (client->hs.hdr_count > MAX_HTTP_HDR_COUNT) {
141 + ERROR("Too many HTTP response header fields");
142 + return -1;
143 + }
144 +
145 + if (client->hs.headers)
146 + client->hs.headers_tail->next = hdr;
147 + else
148 + client->hs.headers = hdr;
149 +
150 + client->hs.headers_tail = hdr;
151 + client->hs.hdr_count++;
152 +
153 + return 0;
154 +}
155 +
156 +int ws_client_want_write(ws_client *client)
157 +{
158 + return rbuf_bytes_available(client->buf_write);
159 +}
160 +
161 +#define RAND_SRC "/dev/urandom"
162 +static int ws_client_get_nonce(ws_client *client, char *dest, unsigned int size)
163 +{
164 + // we do not need crypto secure random here
165 + // it's just used for protocol negotiation
166 + int rd;
167 + int f = open(RAND_SRC, O_RDONLY);
168 + if (f < 0) {
169 + ERROR("Error opening \"%s\". Err: \"%s\"", RAND_SRC, strerror(errno));
170 + return -2;
171 + }
172 +
173 + if ((rd = read(f, dest, size)) > 0) {
174 + close(f);
175 + return rd;
176 + }
177 + close(f);
178 + return -1;
179 +}
180 +
181 +#define WEBSOCKET_NONCE_SIZE 16
182 +#define TEMP_BUF_SIZE 4096
183 +int ws_client_start_handshake(ws_client *client)
184 +{
185 + char nonce[WEBSOCKET_NONCE_SIZE];
186 + char nonce_b64[256];
187 + char second[TEMP_BUF_SIZE];
188 + unsigned int md_len;
189 + unsigned char *digest;
190 + EVP_MD_CTX *md_ctx;
191 + const EVP_MD *md;
192 +
193 + if(!*client->host) {
194 + ERROR("Hostname has not been set. We should not be able to come here!");
195 + return 1;
196 + }
197 +
198 + ws_client_get_nonce(client, nonce, WEBSOCKET_NONCE_SIZE);
199 + EVP_EncodeBlock((unsigned char *)nonce_b64, (const unsigned char *)nonce, WEBSOCKET_NONCE_SIZE);
200 + snprintf(second, TEMP_BUF_SIZE, websocket_upgrage_hdr,
201 + *client->host,
202 + nonce_b64);
203 + if(rbuf_bytes_free(client->buf_write) < strlen(second)) {
204 + ERROR("Write buffer capacity too low.");
205 + return 1;
206 + }
207 +
208 + rbuf_push(client->buf_write, second, strlen(second));
209 + client->state = WS_HANDSHAKE;
210 +
211 + //Calculating expected Sec-WebSocket-Accept reply
212 + snprintf(second, TEMP_BUF_SIZE, "%s%s", nonce_b64, mqtt_protoid);
213 +
214 +#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110)
215 + md_ctx = EVP_MD_CTX_create();
216 +#else
217 + md_ctx = EVP_MD_CTX_new();
218 +#endif
219 + if (md_ctx == NULL) {
220 + ERROR("Cant create EVP_MD Context");
221 + return 1;
222 + }
223 +
224 + md = EVP_get_digestbyname("sha1");
225 + if (!md) {
226 + ERROR("Unknown message digest");
227 + return 1;
228 + }
229 +
230 + if ((digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_sha256()))) == NULL) {
231 + ERROR("Cant alloc digest");
232 + return 1;
233 + }
234 +
235 + EVP_DigestInit_ex(md_ctx, md, NULL);
236 + EVP_DigestUpdate(md_ctx, second, strlen(second));
237 + EVP_DigestFinal_ex(md_ctx, digest, &md_len);
238 +
239 + EVP_EncodeBlock((unsigned char *)nonce_b64, digest, md_len);
240 +
241 + mw_free(client->hs.nonce_reply);
242 + client->hs.nonce_reply = mw_strdup(nonce_b64);
243 +
244 + OPENSSL_free(digest);
245 +
246 +#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110)
247 + EVP_MD_CTX_destroy(md_ctx);
248 +#else
249 + EVP_MD_CTX_free(md_ctx);
250 +#endif
251 +
252 + return 0;
253 +}
254 +
255 +#define BUF_READ_MEMCMP_CONST(const, err) \
256 + if (rbuf_memcmp_n(client->buf_read, const, strlen(const))) { \
257 + ERROR(err); \
258 + rbuf_flush(client->buf_read); \
259 + return WS_CLIENT_PROTOCOL_ERROR; \
260 + }
261 +
262 +#define BUF_READ_CHECK_AT_LEAST(x) \
263 + if (rbuf_bytes_available(client->buf_read) < x) \
264 + return WS_CLIENT_NEED_MORE_BYTES;
265 +
266 +#define MAX_HTTP_LINE_LENGTH 1024*4
267 +#define HTTP_SC_LENGTH 4 // "XXX " http status code as C string
268 +#define WS_CLIENT_HTTP_HDR "HTTP/1.1 "
269 +#define WS_CONN_ACCEPT "sec-websocket-accept"
270 +#define HTTP_HDR_SEPARATOR ": "
271 +#define WS_NONCE_STRLEN_B64 28
272 +#define WS_HTTP_NEWLINE "\r\n"
273 +#define HTTP_HEADER_NAME_MAX_LEN 256
274 +#if HTTP_HEADER_NAME_MAX_LEN > MAX_HTTP_LINE_LENGTH
275 +#error "Buffer too small"
276 +#endif
277 +#if WS_NONCE_STRLEN_B64 > MAX_HTTP_LINE_LENGTH
278 +#error "Buffer too small"
279 +#endif
280 +
281 +#define HTTP_HDR_LINE_CHECK_LIMIT(x) if ((x) >= MAX_HTTP_LINE_LENGTH) \
282 +{ \
283 + ERROR("HTTP line received is too long. Maximum is %d", MAX_HTTP_LINE_LENGTH); \
284 + return WS_CLIENT_PROTOCOL_ERROR; \
285 +}
286 +
287 +int ws_client_parse_handshake_resp(ws_client *client)
288 +{
289 + char buf[HTTP_SC_LENGTH];
290 + int idx_crlf, idx_sep;
291 + char *ptr;
292 + size_t bytes;
293 + switch (client->hs.hdr_state) {
294 + case WS_HDR_HTTP:
295 + BUF_READ_CHECK_AT_LEAST(strlen(WS_CLIENT_HTTP_HDR))
296 + BUF_READ_MEMCMP_CONST(WS_CLIENT_HTTP_HDR, "Expected \"HTTP1.1\" header");
297 + rbuf_bump_tail(client->buf_read, strlen(WS_CLIENT_HTTP_HDR));
298 + client->hs.hdr_state = WS_HDR_RC;
299 + break;
300 + case WS_HDR_RC:
301 + BUF_READ_CHECK_AT_LEAST(HTTP_SC_LENGTH); // "XXX " http return code
302 + rbuf_pop(client->buf_read, buf, HTTP_SC_LENGTH);
303 + if (buf[HTTP_SC_LENGTH - 1] != 0x20) {
304 + ERROR("HTTP status code received is not terminated by space (0x20)");
305 + return WS_CLIENT_PROTOCOL_ERROR;
306 + }
307 + buf[HTTP_SC_LENGTH - 1] = 0;
308 + client->hs.http_code = atoi(buf);
309 + if (client->hs.http_code < 100 || client->hs.http_code >= 600) {
310 + ERROR("HTTP status code received not in valid range 100-600");
311 + return WS_CLIENT_PROTOCOL_ERROR;
312 + }
313 + client->hs.hdr_state = WS_HDR_ENDLINE;
314 + break;
315 + case WS_HDR_ENDLINE:
316 + ptr = rbuf_find_bytes(client->buf_read, WS_HTTP_NEWLINE, strlen(WS_HTTP_NEWLINE), &idx_crlf);
317 + if (!ptr) {
318 + bytes = rbuf_bytes_available(client->buf_read);
319 + HTTP_HDR_LINE_CHECK_LIMIT(bytes);
320 + return WS_CLIENT_NEED_MORE_BYTES;
321 + }
322 + HTTP_HDR_LINE_CHECK_LIMIT(idx_crlf);
323 +
324 + client->hs.http_reply_msg = mw_malloc(idx_crlf+1);
325 + rbuf_pop(client->buf_read, client->hs.http_reply_msg, idx_crlf);
326 + client->hs.http_reply_msg[idx_crlf] = 0;
327 + rbuf_bump_tail(client->buf_read, strlen(WS_HTTP_NEWLINE));
328 + client->hs.hdr_state = WS_HDR_PARSE_HEADERS;
329 + break;
330 + case WS_HDR_PARSE_HEADERS:
331 + ptr = rbuf_find_bytes(client->buf_read, WS_HTTP_NEWLINE, strlen(WS_HTTP_NEWLINE), &idx_crlf);
332 + if (!ptr) {
333 + bytes = rbuf_bytes_available(client->buf_read);
334 + HTTP_HDR_LINE_CHECK_LIMIT(bytes);
335 + return WS_CLIENT_NEED_MORE_BYTES;
336 + }
337 + HTTP_HDR_LINE_CHECK_LIMIT(idx_crlf);
338 +
339 + if (!idx_crlf) { // empty line, header end
340 + rbuf_bump_tail(client->buf_read, strlen(WS_HTTP_NEWLINE));
341 + client->hs.hdr_state = WS_HDR_PARSE_DONE;
342 + return 0;
343 + }
344 +
345 + ptr = rbuf_find_bytes(client->buf_read, HTTP_HDR_SEPARATOR, strlen(HTTP_HDR_SEPARATOR), &idx_sep);
346 + if (!ptr || idx_sep > idx_crlf) {
347 + ERROR("Expected HTTP hdr field key/value separator \": \" before endline in non empty HTTP header line");
348 + return WS_CLIENT_PROTOCOL_ERROR;
349 + }
350 + if (idx_crlf == idx_sep + (int)strlen(HTTP_HDR_SEPARATOR)) {
351 + ERROR("HTTP Header value cannot be empty");
352 + return WS_CLIENT_PROTOCOL_ERROR;
353 + }
354 +
355 + if (idx_sep > HTTP_HEADER_NAME_MAX_LEN) {
356 + ERROR("HTTP header too long (%d)", idx_sep);
357 + return WS_CLIENT_PROTOCOL_ERROR;
358 + }
359 +
360 + struct http_header *hdr = mw_calloc(1, sizeof(struct http_header) + idx_crlf); //idx_crlf includes ": " that will be used as 2 \0 bytes
361 + hdr->key = ((char*)hdr) + sizeof(struct http_header);
362 + hdr->value = hdr->key + idx_sep + 1;
363 +
364 + bytes = rbuf_pop(client->buf_read, hdr->key, idx_sep);
365 + rbuf_bump_tail(client->buf_read, strlen(HTTP_HDR_SEPARATOR));
366 +
367 + bytes = rbuf_pop(client->buf_read, hdr->value, idx_crlf - idx_sep - strlen(HTTP_HDR_SEPARATOR));
368 + rbuf_bump_tail(client->buf_read, strlen(WS_HTTP_NEWLINE));
369 +
370 + for (int i = 0; hdr->key[i]; i++)
371 + hdr->key[i] = tolower(hdr->key[i]);
372 +
373 +// DEBUG("HTTP header \"%s\" received. Value \"%s\"", hdr->key, hdr->value);
374 +
375 + if (ws_client_add_http_header(client, hdr))
376 + return WS_CLIENT_PROTOCOL_ERROR;
377 +
378 + if (!strcmp(hdr->key, WS_CONN_ACCEPT)) {
379 + if (strcmp(client->hs.nonce_reply, hdr->value)) {
380 + ERROR("Received NONCE \"%s\" does not match expected nonce of \"%s\"", hdr->value, client->hs.nonce_reply);
381 + return WS_CLIENT_PROTOCOL_ERROR;
382 + }
383 + client->hs.nonce_matched = 1;
384 + }
385 +
386 + break;
387 + case WS_HDR_PARSE_DONE:
388 + if (!client->hs.nonce_matched) {
389 + ERROR("Missing " WS_CONN_ACCEPT " header");
390 + return WS_CLIENT_PROTOCOL_ERROR;
391 + }
392 + if (client->hs.http_code != 101) {
393 + ERROR("HTTP return code not 101. Received %d with msg \"%s\".", client->hs.http_code, client->hs.http_reply_msg);
394 + return WS_CLIENT_PROTOCOL_ERROR;
395 + }
396 +
397 + client->state = WS_ESTABLISHED;
398 + client->hs.hdr_state = WS_HDR_ALL_DONE;
399 + INFO("Websocket Connection Accepted By Server");
400 + return WS_CLIENT_PARSING_DONE;
401 + case WS_HDR_ALL_DONE:
402 + FATAL("This is error we should never come here!");
403 + return WS_CLIENT_PROTOCOL_ERROR;
404 + }
405 + return 0;
406 +}
407 +
408 +#define BYTE_MSB 0x80
409 +#define WS_FINAL_FRAG BYTE_MSB
410 +#define WS_PAYLOAD_MASKED BYTE_MSB
411 +
412 +static inline size_t get_ws_hdr_size(size_t payload_size)
413 +{
414 + size_t hdr_len = 2 + 4 /*mask*/;
415 + if(payload_size > 125)
416 + hdr_len += 2;
417 + if(payload_size > 65535)
418 + hdr_len += 6;
419 + return hdr_len;
420 +}
421 +
422 +#define MAX_POSSIBLE_HDR_LEN 14
423 +int ws_client_send(ws_client *client, enum websocket_opcode frame_type, const char *data, size_t size)
424 +{
425 + // TODO maybe? implement fragmenting, it is not necessary though
426 + // as both tested MQTT brokers have no reuirement of one MQTT envelope
427 + // be equal to one WebSockets envelope. Therefore there is no need to send
428 + // one big MQTT message as single fragmented WebSocket envelope
429 + char hdr[MAX_POSSIBLE_HDR_LEN];
430 + char *ptr = hdr;
431 + char *mask;
432 + int size_written = 0;
433 + size_t j = 0;
434 +
435 + size_t w_buff_free = rbuf_bytes_free(client->buf_write);
436 + size_t hdr_len = get_ws_hdr_size(size);
437 +
438 + if (w_buff_free < hdr_len * 2) {
439 +#ifdef DEBUG_ULTRA_VERBOSE
440 + DEBUG("Write buffer full. Can't write requested %d size.", size);
441 +#endif
442 + return 0;
443 + }
444 +
445 + if (w_buff_free < (hdr_len + size)) {
446 +#ifdef DEBUG_ULTRA_VERBOSE
447 + DEBUG("Can't write whole MQTT packet of %d bytes into the buffer. Will do partial send of %d.", size, w_buff_free - hdr_len);
448 +#endif
449 + size = w_buff_free - hdr_len;
450 + hdr_len = get_ws_hdr_size(size);
451 + // the actual needed header size might decrease if we cut number of bytes
452 + // if decrease of size crosses 65535 or 125 boundary
453 + // but I can live with that at least for now
454 + // worst case is we have 6 more bytes we could have written
455 + // no bigus dealus
456 + }
457 +
458 + *ptr++ = frame_type | WS_FINAL_FRAG;
459 +
460 + //generate length
461 + *ptr = WS_PAYLOAD_MASKED;
462 + if (size > 65535) {
463 + *ptr++ |= 0x7f;
464 + uint64_t be = htobe64(size);
465 + memcpy(ptr, (void *)&be, sizeof(be));
466 + ptr += sizeof(be);
467 + } else if (size > 125) {
468 + *ptr++ |= 0x7e;
469 + uint16_t be = htobe16(size);
470 + memcpy(ptr, (void *)&be, sizeof(be));
471 + ptr += sizeof(be);
472 + } else
473 + *ptr++ |= size;
474 +
475 + mask = ptr;
476 + if (read(client->entropy_fd, mask, sizeof(uint32_t)) < (ssize_t)sizeof(uint32_t)) {
477 + ERROR("Unable to get mask from \"" ENTROPY_SOURCE "\"");
478 + return -2;
479 + }
480 +
481 + rbuf_push(client->buf_write, hdr, hdr_len);
482 +
483 + if (!size)
484 + return 0;
485 +
486 + // copy and mask data in the write ringbuffer
487 + while (size - size_written) {
488 + size_t writable_bytes;
489 + char *w_ptr = rbuf_get_linear_insert_range(client->buf_write, &writable_bytes);
490 + if(!writable_bytes)
491 + break;
492 +
493 + writable_bytes = (writable_bytes > size) ? (size - size_written) : writable_bytes;
494 +
495 + memcpy(w_ptr, &data[size_written], writable_bytes);
496 + rbuf_bump_head(client->buf_write, writable_bytes);
497 +
498 + for (size_t i = 0; i < writable_bytes; i++, j++)
499 + w_ptr[i] ^= mask[j % 4];
500 + size_written += writable_bytes;
501 + }
502 + return size_written;
503 +}
504 +
505 +static int check_opcode(ws_client *client,enum websocket_opcode oc)
506 +{
507 + switch(oc) {
508 + case WS_OP_BINARY_FRAME:
509 + case WS_OP_CONNECTION_CLOSE:
510 + case WS_OP_PING:
511 + return 0;
512 + case WS_OP_CONTINUATION_FRAME:
513 + FATAL("WS_OP_CONTINUATION_FRAME NOT IMPLEMENTED YET!!!!");
514 + return 0;
515 + case WS_OP_TEXT_FRAME:
516 + FATAL("WS_OP_TEXT_FRAME NOT IMPLEMENTED YET!!!!");
517 + return 0;
518 + case WS_OP_PONG:
519 + FATAL("WS_OP_PONG NOT IMPLEMENTED YET!!!!");
520 + return 0;
521 + default:
522 + return WS_CLIENT_PROTOCOL_ERROR;
523 + }
524 +}
525 +
526 +static inline void ws_client_rx_post_hdr_state(ws_client *client)
527 +{
528 + switch(client->rx.opcode) {
529 + case WS_OP_BINARY_FRAME:
530 + client->rx.parse_state = WS_PAYLOAD_DATA;
531 + return;
532 + case WS_OP_CONNECTION_CLOSE:
533 + client->rx.parse_state = WS_PAYLOAD_CONNECTION_CLOSE;
534 + return;
535 + case WS_OP_PING:
536 + client->rx.parse_state = WS_PAYLOAD_PING_REQ_PAYLOAD;
537 + return;
538 + default:
539 + client->rx.parse_state = WS_PAYLOAD_SKIP_UNKNOWN_PAYLOAD;
540 + return;
541 + }
542 +}
543 +
544 +#define LONGEST_POSSIBLE_HDR_PART 8
545 +int ws_client_process_rx_ws(ws_client *client)
546 +{
547 + char buf[LONGEST_POSSIBLE_HDR_PART];
548 + size_t size;
549 + switch (client->rx.parse_state) {
550 + case WS_FIRST_2BYTES:
551 + BUF_READ_CHECK_AT_LEAST(2);
552 + rbuf_pop(client->buf_read, buf, 2);
553 + client->rx.opcode = buf[0] & (char)~BYTE_MSB;
554 +
555 + if (!(buf[0] & (char)~WS_FINAL_FRAG)) {
556 + ERROR("Not supporting fragmented messages yet!");
557 + return WS_CLIENT_PROTOCOL_ERROR;
558 + }
559 +
560 + if (check_opcode(client, client->rx.opcode) == WS_CLIENT_PROTOCOL_ERROR)
561 + return WS_CLIENT_PROTOCOL_ERROR;
562 +
563 + if (buf[1] & (char)WS_PAYLOAD_MASKED) {
564 + ERROR("Mask is not allowed in Server->Client Websocket direction.");
565 + return WS_CLIENT_PROTOCOL_ERROR;
566 + }
567 +
568 + switch (buf[1]) {
569 + case 127:
570 + client->rx.parse_state = WS_PAYLOAD_EXTENDED_64;
571 + break;
572 + case 126:
573 + client->rx.parse_state = WS_PAYLOAD_EXTENDED_16;
574 + break;
575 + default:
576 + client->rx.payload_length = buf[1];
577 + ws_client_rx_post_hdr_state(client);
578 + }
579 + break;
580 + case WS_PAYLOAD_EXTENDED_16:
581 + BUF_READ_CHECK_AT_LEAST(2);
582 + rbuf_pop(client->buf_read, buf, 2);
583 + client->rx.payload_length = be16toh(*((uint16_t *)buf));
584 + ws_client_rx_post_hdr_state(client);
585 + break;
586 + case WS_PAYLOAD_EXTENDED_64:
587 + BUF_READ_CHECK_AT_LEAST(LONGEST_POSSIBLE_HDR_PART);
588 + rbuf_pop(client->buf_read, buf, LONGEST_POSSIBLE_HDR_PART);
589 + client->rx.payload_length = be64toh(*((uint64_t *)buf));
590 + ws_client_rx_post_hdr_state(client);
591 + break;
592 + case WS_PAYLOAD_DATA:
593 + // TODO not pretty?
594 + while (client->rx.payload_processed < client->rx.payload_length) {
595 + size_t remaining = client->rx.payload_length - client->rx.payload_processed;
596 + if (!rbuf_bytes_available(client->buf_read))
597 + return WS_CLIENT_NEED_MORE_BYTES;
598 + char *insert = rbuf_get_linear_insert_range(client->buf_to_mqtt, &size);
599 + if (!insert) {
600 +#ifdef DEBUG_ULTRA_VERBOSE
601 + DEBUG("BUFFER TOO FULL. Avail %d req %d", (int)size, (int)remaining);
602 +#endif
603 + return WS_CLIENT_BUFFER_FULL;
604 + }
605 + size = (size > remaining) ? remaining : size;
606 + size = rbuf_pop(client->buf_read, insert, size);
607 + rbuf_bump_head(client->buf_to_mqtt, size);
608 + client->rx.payload_processed += size;
609 + }
610 + client->rx.parse_state = WS_PACKET_DONE;
611 + break;
612 + case WS_PAYLOAD_CONNECTION_CLOSE:
613 + // for WS_OP_CONNECTION_CLOSE allowed is
614 + // a) empty payload
615 + // b) 2byte reason code
616 + // c) 2byte reason code followed by message
617 + if (client->rx.payload_length == 1) {
618 + ERROR("WebScoket CONNECTION_CLOSE can't have payload of size 1");
619 + return WS_CLIENT_PROTOCOL_ERROR;
620 + }
621 + if (!client->rx.payload_length) {
622 + INFO("WebSocket server closed the connection without giving reason.");
623 + client->rx.parse_state = WS_PACKET_DONE;
624 + break;
625 + }
626 + client->rx.parse_state = WS_PAYLOAD_CONNECTION_CLOSE_EC;
627 + break;
628 + case WS_PAYLOAD_CONNECTION_CLOSE_EC:
629 + BUF_READ_CHECK_AT_LEAST(sizeof(uint16_t));
630 +
631 + rbuf_pop(client->buf_read, buf, sizeof(uint16_t));
632 + client->rx.specific_data.op_close.ec = be16toh(*((uint16_t *)buf));
633 + client->rx.payload_processed += sizeof(uint16_t);
634 +
635 + if(client->rx.payload_processed == client->rx.payload_length) {
636 + INFO("WebSocket server closed the connection with EC=%d. Without message.",
637 + client->rx.specific_data.op_close.ec);
638 + client->rx.parse_state = WS_PACKET_DONE;
639 + break;
640 + }
641 + client->rx.parse_state = WS_PAYLOAD_CONNECTION_CLOSE_MSG;
642 + break;
643 + case WS_PAYLOAD_CONNECTION_CLOSE_MSG:
644 + if (!client->rx.specific_data.op_close.reason)
645 + client->rx.specific_data.op_close.reason = mw_malloc(client->rx.payload_length + 1);
646 +
647 + while (client->rx.payload_processed < client->rx.payload_length) {
648 + if (!rbuf_bytes_available(client->buf_read))
649 + return WS_CLIENT_NEED_MORE_BYTES;
650 + client->rx.payload_processed += rbuf_pop(client->buf_read,
651 + &client->rx.specific_data.op_close.reason[client->rx.payload_processed - sizeof(uint16_t)],
652 + client->rx.payload_length - client->rx.payload_processed);
653 + }
654 + client->rx.specific_data.op_close.reason[client->rx.payload_length] = 0;
655 + INFO("WebSocket server closed the connection with EC=%d and reason \"%s\"",
656 + client->rx.specific_data.op_close.ec,
657 + client->rx.specific_data.op_close.reason);
658 + mw_free(client->rx.specific_data.op_close.reason);
659 + client->rx.specific_data.op_close.reason = NULL;
660 + client->rx.parse_state = WS_PACKET_DONE;
661 + break;
662 + case WS_PAYLOAD_SKIP_UNKNOWN_PAYLOAD:
663 + BUF_READ_CHECK_AT_LEAST(client->rx.payload_length);
664 + WARN("Skipping Websocket Packet of unsupported/unknown type");
665 + if (client->rx.payload_length)
666 + rbuf_bump_tail(client->buf_read, client->rx.payload_length);
667 + client->rx.parse_state = WS_PACKET_DONE;
668 + return WS_CLIENT_PARSING_DONE;
669 + case WS_PAYLOAD_PING_REQ_PAYLOAD:
670 + if (client->rx.payload_length > rbuf_get_capacity(client->buf_read) / 2) {
671 + ERROR("Ping arrived with payload which is too big!");
672 + return WS_CLIENT_INTERNAL_ERROR;
673 + }
674 + BUF_READ_CHECK_AT_LEAST(client->rx.payload_length);
675 + client->rx.specific_data.ping_msg = mw_malloc(client->rx.payload_length);
676 + rbuf_pop(client->buf_read, client->rx.specific_data.ping_msg, client->rx.payload_length);
677 + // TODO schedule this instead of sending right away
678 + // then attempt to send as soon as buffer space clears up
679 + size = ws_client_send(client, WS_OP_PONG, client->rx.specific_data.ping_msg, client->rx.payload_length);
680 + if (size != client->rx.payload_length) {
681 + ERROR("Unable to send the PONG as one packet back. Closing connection.");
682 + return WS_CLIENT_PROTOCOL_ERROR;
683 + }
684 + client->rx.parse_state = WS_PACKET_DONE;
685 + return WS_CLIENT_PARSING_DONE;
686 + case WS_PACKET_DONE:
687 + client->rx.parse_state = WS_FIRST_2BYTES;
688 + client->rx.payload_processed = 0;
689 + if (client->rx.opcode == WS_OP_CONNECTION_CLOSE)
690 + return WS_CLIENT_CONNECTION_CLOSED;
691 + return WS_CLIENT_PARSING_DONE;
692 + default:
693 + FATAL("Unknown parse state");
694 + return WS_CLIENT_INTERNAL_ERROR;
695 + }
696 + return 0;
697 +}
698 +
699 +int ws_client_process(ws_client *client)
700 +{
701 + int ret;
702 + switch(client->state) {
703 + case WS_RAW:
704 + if (ws_client_start_handshake(client))
705 + return WS_CLIENT_INTERNAL_ERROR;
706 + return WS_CLIENT_NEED_MORE_BYTES;
707 + case WS_HANDSHAKE:
708 + do {
709 + ret = ws_client_parse_handshake_resp(client);
710 + if (ret == WS_CLIENT_PROTOCOL_ERROR)
711 + client->state = WS_ERROR;
712 + if (ret == WS_CLIENT_PARSING_DONE && client->state == WS_ESTABLISHED)
713 + ret = WS_CLIENT_NEED_MORE_BYTES;
714 + } while (!ret);
715 + break;
716 + case WS_ESTABLISHED:
717 + do {
718 + ret = ws_client_process_rx_ws(client);
719 + switch(ret) {
720 + case WS_CLIENT_PROTOCOL_ERROR:
721 + client->state = WS_ERROR;
722 + break;
723 + case WS_CLIENT_CONNECTION_CLOSED:
724 + client->state = WS_CONN_CLOSED_GRACEFUL;
725 + break;
726 + }
727 + // if ret == 0 we can continue parsing
728 + // if ret == WS_CLIENT_PARSING_DONE we processed
729 + // one websocket packet and attempt processing
730 + // next one if data available in the buffer
731 + } while (!ret || ret == WS_CLIENT_PARSING_DONE);
732 + break;
733 + case WS_ERROR:
734 + ERROR("ws_client is in error state. Restart the connection!");
735 + return WS_CLIENT_PROTOCOL_ERROR;
736 + case WS_CONN_CLOSED_GRACEFUL:
737 + ERROR("Connection has been gracefully closed. Calling this is useless (and probably bug) until you reconnect again.");
738 + return WS_CLIENT_CONNECTION_CLOSED;
739 + default:
740 + FATAL("Unknown connection state! Probably memory corruption.");
741 + return WS_CLIENT_INTERNAL_ERROR;
742 + }
743 + return ret;
744 +}